<?php
error_reporting(E_ERROR);
@set_time_limit(0);
class Zip{
 public  $_debug = false;
 public  $datasec, $ctrl_dir = array();
 public  $eof_ctrl_dir = "\x50\x4b\x05\x06\x00\x00\x00\x00";
 public  $old_offset = 0;
 public  $dirs = Array(".");
 public  $write_file = true;//打包时是否写文件
 public  $out = '';
/**
 * 解压缩zip文件
 *
 * @param string $need_extract_file
 * @param string $extract_path
 * @param boolen $dorp
 * @return mix
 */
 function extractZip($need_extract_file,$extract_path,$dorp = false){
 	if(!file_exists($need_extract_file) || !is_file($need_extract_file)){
 		echo 'File '.$need_extract_file .' not exist';
 		return false;
 	}
 	/*if(false!==($this->checkOs())){
 		//linux
 		return $this->unpackZipByCmd($need_extract_file,$extract_path);
 	}else{*/
 		//非linux主机
 		//return $dorp?$this->Extract($need_extract_file,$extract_path,TRUE):$this->Extract($need_extract_file,$extract_path);
               $info=array(
	              "cover"=>array(),
	              "dir"=>0,
				  "folders"=>array(),
				  "file"=>0,
				  "size"=>0,
				  "orig_size"=>0,
				  "error"=>array()
				);
 		return $this->unpackzip($need_extract_file,$extract_path,-1,0,$info);
 	//}
 }
/**
 * 检查服务器环境
 * true ->linux|unix
 * false ->win
 *
 * @return boolen
 */
 function checkOs(){
 	return PATH_SEPARATOR==':'?TRUE:false;
 }
/**
 *  解压缩tar格式文件
*/
  function upack_tar($source,$extractpath){
                  //直接执行LINUX命令行模式 只有在linux下执行 
                  if($this->_debug){
                  	echo '<br />'.$extractpath.'<br />';
                  }
                  if(!is_dir($extractpath))mkdir($extractpath);
                 $ex = exec("tar   -xzvf   $source   -C $extractpath");
               if(!$ex){
               echo "Faid to unpack file $source to $extractpath";exit;
               }
               else echo "EXTRACT FILE TO $extractpath is OK";
               }
 /**
  * linux下解压缩 zip
  *
  * @param unknown_type $source_link
  * @param unknown_type $extractpath
  * @return unknown
  */
 function unpackZipByCmd($source_link,$extractpath){

  	//$cmd = "unzip -oq $source_link -d $extractpath";
  /*	if($this->_debug){*/
  		$cmd = "unzip -o $source_link -d $extractpath";//有输出结果的
  	/*}else{
  		$cmd = "unzip -oq $source_link -d $extractpath";//无输出结果的
  	}*/
  	$ss = system($cmd);
  	if(FALSE!==$ss){
  		echo '<br />extract file is  ok.<br />';
  	}else{
  		echo '<br />Extract file is failed<br />';
  		exit;
  	}
  	return $extractpath.'/';
  }
 function packzip($dir, $zipfilename, $drop=false)//打包
    {
        if (substr($dir, -1) != '/')
        {
            $dir = ($dir == '') ? './' : $dir . '/';
        }

        if (@function_exists('gzcompress'))
        {
            $curdir = getcwd();
            if (is_array($dir))
            {
                $filelist = $dir;
            }
            else
            {
                $filelist = $this -> get_filelist($dir);
            }

            if ((!empty($dir)) && (!is_array($dir))&&(file_exists($dir)))
            {
                chdir($dir);
            }
            else
            {
                chdir($curdir);
            }

            if (count($filelist) > 0)
            {
                foreach ($filelist as $filename)
                {
                    if (is_file($filename))
                    {
                        $fd = fopen ($filename, 'rb');
                        $content = @fread ($fd, filesize ($filename));
                        fclose ($fd);
                        if (is_array($dir))
                        {
                            $filename = basename($filename);
                        }
                        $this -> add_files($content, $filename);
                    }
                }
                $this->out = $this -> file();
                if($this->write_file){
	                chdir($curdir);
	                $fp = fopen($zipfilename, 'wb');
	                fwrite($fp, $this->out, strlen($this->out));
	                fclose($fp);
                }
            }
          if ($drop)//打包完了后直接删除整个打包目录
           {
            $this->RemoveDir($dir,true);
                            //@unlink($filename);
           }
            return 1;
        }
        else
        {
            return 0;
        }
    }
 function RemoveDir($dir, $DeleteMe=false){//删除目录下的是所有文件包括自身
   if(!$dh = @opendir($dir)) return;
   while (false !== ($obj = readdir($dh)))
          {
       if($obj=='.' || $obj=='..') continue;
       if (!@unlink($dir.'/'.$obj))
	            {
		$this->RemoveDir($dir.'/'.$obj, true);
            	}
          }
            if ($DeleteMe)
			{
               closedir($dh);
                @rmdir($dir);
            }
        }
 function get_filelist($dir)//列表指定目录下的所有文件返回array
    {
        $file = array();
        $dir = rtrim($dir,'/');
        if (file_exists($dir))
        {
            $args = func_get_args();
            $pref = isset($args[1]) ? $args[1] : '';
            $dh = opendir($dir);
            while (($files = readdir($dh)) !== false)
            {
                if (($files != '.') && ($files != '..'))
                {
                    if (is_dir($dir .'/'. $files))
                    {
                        $file = array_merge($file, $this -> get_filelist($dir .'/'. $files, "$pref$files/"));
                    }
                    else
                    {
                        $file[] = $pref . $files;
                    }
                }
            }
            closedir($dh);
        }

        return $file;
    }
    /**
     * Converts an Unix timestamp to a four byte DOS date and time format (date
     * in high two bytes, time in low two bytes allowing magnitude comparison).
     *
     * @param  integer  the current Unix timestamp
     *
     * @return integer  the current date in a four byte DOS format
     *
     * @access private

   public function unix2DosTime($unixtime = 0)
    {
        $timearray = ($unixtime == 0) ? getdate() : getdate($unixtime);

        if ($timearray['year'] < 1980) {
            $timearray['year']    = 1980;
            $timearray['mon']     = 1;
            $timearray['mday']    = 1;
            $timearray['hours']   = 0;
            $timearray['minutes'] = 0;
            $timearray['seconds'] = 0;
        } // end if

        return (($timearray['year'] - 1980) << 25) | ($timearray['mon'] << 21) | ($timearray['mday'] << 16) |
                ($timearray['hours'] << 11) | ($timearray['minutes'] << 5) | ($timearray['seconds'] >> 1);
    } // end of the 'unix2DosTime()' method

    /**
     * Adds "file" to archive
     *
     * @param  string   file contents
     * @param  string   name of the file in the archive (may contains the path)
     * @param  integer  the current timestamp
     *
     * @access public
     */
 function add_files($data, $name, $time = 0)
    {
        $name     = str_replace('\\', '/', $name);

        $dtime    = dechex($this->DosTime($time));
        $hexdtime = '\x' . $dtime[6] . $dtime[7]
                  . '\x' . $dtime[4] . $dtime[5]
                  . '\x' . $dtime[2] . $dtime[3]
                  . '\x' . $dtime[0] . $dtime[1];
        eval('$hexdtime = "' . $hexdtime . '";');

        $fr = "\x50\x4b\x03\x04";
        $fr .= "\x14\x00";            // ver needed to extract
        $fr .= "\x00\x00";            // gen purpose bit flag
        $fr .= "\x08\x00";            // compression method
        $fr .= $hexdtime;             // last mod time and date

        // "local file header" segment
        $unc_len = strlen($data);
        $crc     = crc32($data);
        $zdata   = gzcompress($data);
        $c_len   = strlen($zdata);
        $zdata   = substr(substr($zdata, 0, strlen($zdata) - 4), 2); // fix crc bug
        $fr      .= pack('V', $crc);             // crc32
        $fr      .= pack('V', $c_len);           // compressed filesize
        $fr      .= pack('V', $unc_len);         // uncompressed filesize
        $fr      .= pack('v', strlen($name));    // length of filename
        $fr      .= pack('v', 0);                // extra field length
        $fr      .= $name;
        // "file data" segment
        $fr .= $zdata;
        // "data descriptor" segment (optional but necessary if archive is not
        // served as file)
        $fr .= pack('V', $crc);                 // crc32
        $fr .= pack('V', $c_len);               // compressed filesize
        $fr .= pack('V', $unc_len);             // uncompressed filesize
        // add this entry to array
        $this -> datasec[] = $fr;
        $new_offset        = strlen(implode('', $this->datasec));
        // now add to central directory record
        $cdrec = "\x50\x4b\x01\x02";
        $cdrec .= "\x00\x00";                // version made by
        $cdrec .= "\x14\x00";                // version needed to extract
        $cdrec .= "\x00\x00";                // gen purpose bit flag
        $cdrec .= "\x08\x00";                // compression method
        $cdrec .= $hexdtime;                 // last mod time & date
        $cdrec .= pack('V', $crc);           // crc32
        $cdrec .= pack('V', $c_len);         // compressed filesize
        $cdrec .= pack('V', $unc_len);       // uncompressed filesize
        $cdrec .= pack('v', strlen($name) ); // length of filename
        $cdrec .= pack('v', 0 );             // extra field length
        $cdrec .= pack('v', 0 );             // file comment length
        $cdrec .= pack('v', 0 );             // disk number start
        $cdrec .= pack('v', 0 );             // internal file attributes
        $cdrec .= pack('V', 32 );            // external file attributes - 'archive' bit set
        $cdrec .= pack('V', $this -> old_offset ); // relative offset of local header
        $this -> old_offset = $new_offset;
        $cdrec .= $name;
        // optional extra field, file comment goes here
        // save to central directory
        $this -> ctrl_dir[] = $cdrec;
    } // end of the 'add_files()' method
/**
 * Dumps out file
 *
 * @return  string  the zipped file
 *
 * @access public
 */
 function file(){
        $data    = implode('', $this -> datasec);
        $ctrldir = implode('', $this -> ctrl_dir);
        /*$result = $data .$ctrldir.$this -> eof_ctrl_dir.pack('v', sizeof($this -> ctrl_dir)).pack('v', sizeof($this -> ctrl_dir)).pack('V', strlen($ctrldir)).pack('V', strlen($data))."\x00\x00";
		return $result;*/
        return
            $data .
            $ctrldir .
            $this -> eof_ctrl_dir .
            pack('v', sizeof($this -> ctrl_dir)) .  // total # of entries "on this disk"
            pack('v', sizeof($this -> ctrl_dir)) .  // total # of entries overall
            pack('V', strlen($ctrldir)) .           // size of central dir
            pack('V', strlen($data)) .              // offset to start of central dir
            "\x00\x00";                             // .zip file comment length
 } // end of the 'file()' method
/**
*  打包结束
*/
/**
* 解压缩开始
*/
function getext($filename)
{
	$filename = trim(strtolower($filename));
	return trim(array_pop(explode('.',$filename)));
}
function mkdirs($path, $mode = 0777){
		$dirs = explode('/',($path=substr($path,-1,1)!=='/'?$path.'/':$path)); 
		$pos = strrpos($path, "."); 
		$subamount = $pos === false?0:1;
		for ($c=0;$c < count($dirs) - $subamount; $c++) { 
			$thispath=""; 
		for ($cc=0; $cc <= $c; $cc++) { 
			$thispath.=$dirs[$cc].'/'; 
		} 
		if (!file_exists($thispath))@mkdir($thispath,$mode); 
	} 
}
/**
 * 解压zip包
 *
 * @param string $filename
 * @param string $key
 * @param int $indexes
 * @param string $cover 是否覆盖 0->不覆盖 1->覆盖
 * @param  $info
 * @return unknown
 */
function unpackzip( $filename, $key, $indexes = -1,$cover = 0, &$info){
	if (!file_exists($filename)) return false;
	$all=true;
	if ($indexes !=-1) $indexes="|||".$indexes."|||";
	if ($info !=-1) $info=array(
	               "cover"=>array(),
	               "dir"=>0,
				   "folders"=>array(),
				   "file"=>0,
				   "size"=>0,
				   "orig_size"=>0,
				   "error"=>array()
				   );
	$all = ($l = $this->get_list($filename));
	foreach($l as $file)
	{
		if ($indexes !=-1 && !strpos($indexes,"|".$file["index"]."|")) continue;
		//$ftype = $this->getext($file["filename"]);
		//if ($user["limit"]["$ftype"] && !$user["only"]) continue;
		//else if (!$user["limit"]["$ftype"] && $user["only"]) continue;
		$path = $key."/".$file["filename"];
		if ($file["folder"])
		{
			if (!is_dir($path)){
					$this->mkdirs($path);
			}elseif ($info!=-1){
				$info["folders"][] = $path;
			}
			if ($info!=-1) $info["dir"]++;
		}
		else
		{
			if (file_exists($path)) // 处理已经存在的文件
			{
				if ($info!=-1) $info["cover"][] = array("filename"=>$path,"index"=>$file["index"]);
				if (!$cover) continue;
			}
			$pack = $this->Extract($filename,$key,$file["index"]);
			//echo '<pre>';
			//print_r($pack);
			if ($pack)
			{
				if ($info!=-1)
				{
					$info["orig_size"]+=$file["compressed_size"];
					$info["size"]+=$file["size"];
					$info["file"]++;
				}
			}
			else
			{
				if ($info!=-1) $info["error"][]=$path;
				if ($all) $all=false;
			}
		}
	}
	return $all;
}
//读zip
function get_List($zip_name){
   $zip = @fopen($zip_name, 'rb');
   if(!$zip) return(0);
   $centd = $this->ReadCentralDir($zip,$zip_name);

    @rewind($zip);
    @fseek($zip, $centd['offset']);

   for ($i=0; $i<$centd['entries']; $i++)
   {
    $header = $this->ReadCentralFileHeaders($zip);
    $header['index'] = $i;$info['filename'] = $header['filename'];
    $info['stored_filename'] = $header['stored_filename'];
    $info['size'] = $header['size'];$info['compressed_size']=$header['compressed_size'];
    $info['crc'] = strtoupper(dechex( $header['crc'] ));
    $info['mtime'] = $header['mtime']; $info['comment'] = $header['comment'];
    $info['folder'] = ($header['external']==0x41FF0010||$header['external']==16)?1:0;
    $info['index'] = $header['index'];$info['status'] = $header['status'];
    $ret[]=$info; unset($header);
   }
  return $ret;
 }
function Add($files,$compact = 1)
 {
  if(!is_array($files[0])) $files=Array($files);

  for($i=0;$files[$i];$i++){
    $fn = $files[$i];
    if(!in_Array(dirname($fn[0]),$this->dirs))
     $this->add_Dir(dirname($fn[0]));
    if(basename1($fn[0]))
     $ret[basename1($fn[0])]=$this->add_File($fn[1],$fn[0],$compact);
  }
  return $ret;
 }

function get_file()
 {
   $data = implode('', $this -> datasec);
   $ctrldir = implode('', $this -> ctrl_dir);
   return $data . $ctrldir . $this -> eof_ctrl_dir .pack('v', sizeof($this -> ctrl_dir)).pack('v', sizeof($this -> ctrl_dir)).pack('V', strlen($ctrldir)) . pack('V', strlen($data)) . "\x00\x00";
 }

function add_dir($name)
 {
   $name = str_replace("\\", "/", $name);
   $fr = "\x50\x4b\x03\x04\x0a\x00\x00\x00\x00\x00\x00\x00\x00\x00";

   $fr .= pack("V",0).pack("V",0).pack("V",0).pack("v", strlen($name) );
   $fr .= pack("v", 0 ).$name.pack("V", 0).pack("V", 0).pack("V", 0);
   $this -> datasec[] = $fr;

   $new_offset = strlen(implode("", $this->datasec));

   $cdrec = "\x50\x4b\x01\x02\x00\x00\x0a\x00\x00\x00\x00\x00\x00\x00\x00\x00";
   $cdrec .= pack("V",0).pack("V",0).pack("V",0).pack("v", strlen($name) );
   $cdrec .= pack("v", 0 ).pack("v", 0 ).pack("v", 0 ).pack("v", 0 );
   //$ext = "\xff\xff\xff\xff";
   $cdrec .= pack("V", 16 ).pack("V", $this -> old_offset ).$name;

   $this -> ctrl_dir[] = $cdrec;
   $this -> old_offset = $new_offset;
   $this -> dirs[] = $name;
 }
 /**
  * Adds "file" to archive
  *
  * @param  string   file contents
  * @param  string   name of the file in the archive (may contains the path)
  * @param  integer  the current timestamp
  *
  * @access public
  */
function add_File($data, $name, $compact = 1)
 {
   $name     = str_replace('\\', '/', $name);
   $dtime    = dechex($this->DosTime());

   $hexdtime = '\x' . $dtime[6] . $dtime[7].'\x'.$dtime[4] . $dtime[5]
     . '\x' . $dtime[2] . $dtime[3].'\x'.$dtime[0].$dtime[1];
   eval('$hexdtime = "' . $hexdtime . '";');

   if($compact)
   $fr = "\x50\x4b\x03\x04\x14\x00\x00\x00\x08\x00".$hexdtime;
   else $fr = "\x50\x4b\x03\x04\x0a\x00\x00\x00\x00\x00".$hexdtime;
   $unc_len = strlen($data); $crc = crc32($data);

   if($compact){
     $zdata = gzcompress($data); $c_len = strlen($zdata);
     $zdata = substr(substr($zdata, 0, strlen($zdata) - 4), 2);
   }else{
     $zdata = $data;
   }
   $c_len=strlen($zdata);
   $fr .= pack('V', $crc).pack('V', $c_len).pack('V', $unc_len);
   $fr .= pack('v', strlen($name)).pack('v', 0).$name.$zdata;

   $fr .= pack('V', $crc).pack('V', $c_len).pack('V', $unc_len);

   $this -> datasec[] = $fr;
   $new_offset        = strlen(implode('', $this->datasec));
   if($compact)
        $cdrec = "\x50\x4b\x01\x02\x00\x00\x14\x00\x00\x00\x08\x00";
   else $cdrec = "\x50\x4b\x01\x02\x14\x00\x0a\x00\x00\x00\x00\x00";
   $cdrec .= $hexdtime.pack('V', $crc).pack('V', $c_len).pack('V', $unc_len);
   $cdrec .= pack('v', strlen($name) ).pack('v', 0 ).pack('v', 0 );
   $cdrec .= pack('v', 0 ).pack('v', 0 ).pack('V', 32 );
   $cdrec .= pack('V', $this -> old_offset );

   $this -> old_offset = $new_offset;
   $cdrec .= $name;
   $this -> ctrl_dir[] = $cdrec;
   return true;
 }
function DosTime() {
   $timearray = getdate();
   if ($timearray['year'] < 1980) {
     $timearray['year'] = 1980; $timearray['mon'] = 1;
     $timearray['mday'] = 1; $timearray['hours'] = 0;
     $timearray['minutes'] = 0; $timearray['seconds'] = 0;
   }
   return (($timearray['year'] - 1980) << 25) | ($timearray['mon'] << 21) |     ($timearray['mday'] << 16) | ($timearray['hours'] << 11) |
    ($timearray['minutes'] << 5) | ($timearray['seconds'] >> 1);
 }
//解压缩
function Extract ( $zn, $to, $index = Array(-1)){
   //$ok = 0;
   $zip = @fopen($zn,'rb');
   if(!$zip) return(-1);
   $cdir = $this->ReadCentralDir($zip,$zn);
   $pos_entry = $cdir['offset'];
   if(!is_array($index)){ $index = array($index);  }
   for($i=0; $index[$i];$i++){
     if(intval($index[$i])!=$index[$i]||$index[$i]>$cdir['entries'])
      return(-1);
   }
   for ($i=0; $i<$cdir['entries']; $i++){
     @fseek($zip, $pos_entry);
     $header = $this->ReadCentralFileHeaders($zip);
     $header['index'] = $i; $pos_entry = ftell($zip);
     @rewind($zip); fseek($zip, $header['offset']);
     if(in_array("-1",$index)||in_array($i,$index))
      $stat[$header['filename']]=$this->ExtractFile($header, $to, $zip);
      }
   fclose($zip);
   return $stat;
 }

function ReadFileHeader($zip){
    $binary_data = fread($zip, 30);
    $data = unpack('vchk/vid/vversion/vflag/vcompression/vmtime/vmdate/Vcrc/Vcompressed_size/Vsize/vfilename_len/vextra_len', $binary_data);
    $header['filename'] = fread($zip, $data['filename_len']);
    if ($data['extra_len'] != 0) {
      $header['extra'] = fread($zip, $data['extra_len']);
    } else { $header['extra'] = ''; }
    $header['compression'] = $data['compression'];$header['size'] = $data['size'];
    $header['compressed_size'] = $data['compressed_size'];
    $header['crc'] = $data['crc']; $header['flag'] = $data['flag'];
    $header['mdate'] = $data['mdate'];$header['mtime'] = $data['mtime'];
    if ($header['mdate'] && $header['mtime']){
     $hour=($header['mtime']&0xF800)>>11;$minute=($header['mtime']&0x07E0)>>5;
     $seconde=($header['mtime']&0x001F)*2;$year=(($header['mdate']&0xFE00)>>9)+1980;
     $month=($header['mdate']&0x01E0)>>5;$day=$header['mdate']&0x001F;
     $header['mtime'] = mktime($hour, $minute, $seconde, $month, $day, $year);
    }else{$header['mtime'] = time();}

    $header['stored_filename'] = $header['filename'];
    $header['status'] = "ok";
    return $header;
  }
function ReadCentralFileHeaders($zip){
    $binary_data = fread($zip, 46);
    $header = unpack('vchkid/vid/vversion/vversion_extracted/vflag/vcompression/vmtime/vmdate/Vcrc/Vcompressed_size/Vsize/vfilename_len/vextra_len/vcomment_len/vdisk/vinternal/Vexternal/Voffset', $binary_data);
    if ($header['filename_len'] != 0)
      $header['filename'] = fread($zip,$header['filename_len']);
    else $header['filename'] = '';
    if ($header['extra_len'] != 0)
      $header['extra'] = fread($zip, $header['extra_len']);
    else $header['extra'] = '';
    if ($header['comment_len'] != 0)
      $header['comment'] = fread($zip, $header['comment_len']);
    else $header['comment'] = '';
    if ($header['mdate'] && $header['mtime']){
      $hour = ($header['mtime'] & 0xF800) >> 11;
      $minute = ($header['mtime'] & 0x07E0) >> 5;
      $seconde = ($header['mtime'] & 0x001F)*2;
      $year = (($header['mdate'] & 0xFE00) >> 9) + 1980;
      $month = ($header['mdate'] & 0x01E0) >> 5;
      $day = $header['mdate'] & 0x001F;
      $header['mtime'] = mktime($hour, $minute, $seconde, $month, $day, $year);
    } else {
      $header['mtime'] = time();
    }
    $header['stored_filename'] = $header['filename'];
    $header['status'] = 'ok';
    if (substr($header['filename'], -1) == '/')
      $header['external'] = 0x41FF0010;
    return $header;
 }

 function ReadCentralDir($zip,$zip_name)
 {
  $size = filesize($zip_name);
  if ($size < 277) $maximum_size = $size;
  else $maximum_size=277;

  @fseek($zip, $size-$maximum_size);
  $pos = ftell($zip); $bytes = 0x00000000;

  while ($pos < $size)
  {
    $byte = @fread($zip, 1); $bytes=($bytes << 8) | Ord($byte);
    if ($bytes == 0x504b0506){ $pos++; break; } $pos++;
  }

 $data=unpack('vdisk/vdisk_start/vdisk_entries/ventries/Vsize/Voffset/vcomment_size',fread($zip,18));
  if ($data['comment_size'] != 0)
    $centd['comment'] = fread($zip, $data['comment_size']);
    else $centd['comment'] = ''; $centd['entries'] = $data['entries'];
  $centd['disk_entries'] = $data['disk_entries'];
  $centd['offset'] = $data['offset'];$centd['disk_start'] = $data['disk_start'];
  $centd['size'] = $data['size'];  $centd['disk'] = $data['disk'];
  return $centd;
 }
/**
 * 解压
 *
 * @param unknown_type $header
 * @param unknown_type $to
 * @param unknown_type $zip
 * @return unknown
 */
function ExtractFile($header,$to,$zip)
 {
   $header = $this->readfileheader($zip);
   if(substr($to,-1)!="/") $to.="/";
   if(!@is_dir($to)) @mkdir($to,0777);
   $pth = explode("/",dirname($header['filename']));
   for($i=0;isset($pth[$i]);$i++){
     if(!$pth[$i]) continue;$pthss.=$pth[$i]."/";
     if(!is_dir($to.$pthss)) @mkdir($to.$pthss,0777);
   }
  if (!($header['external']==0x41FF0010)&&!($header['external']==16))
  {
   if ($header['compression']==0)
   {
    $fp = @fopen($to.$header['filename'], 'wb');
    if(!$fp) return(-1);
    $size = $header['compressed_size'];

    while ($size != 0)
    {
      $read_size = ($size < 2048 ? $size : 2048);
      $buffer = fread($zip, $read_size);
      $binary_data = pack('a'.$read_size, $buffer);
      @fwrite($fp, $binary_data, $read_size);
      $size -= $read_size;
    }
    fclose($fp);
    touch($to.$header['filename'], $header['mtime']);

  }else{
   $fp = @fopen($to.$header['filename'].'.gz','wb');
   if(!$fp) return(-1);
   $binary_data = pack('va1a1Va1a1', 0x8b1f, Chr($header['compression']),
     Chr(0x00), time(), Chr(0x00), Chr(3));
   fwrite($fp, $binary_data, 10);
   $size = $header['compressed_size'];
   while ($size != 0)
   {
     $read_size = ($size < 1024 ? $size : 1024);
     $buffer = fread($zip, $read_size);
     $binary_data = pack('a'.$read_size, $buffer);
     @fwrite($fp, $binary_data, $read_size);
     $size -= $read_size;
   }
   $binary_data = pack('VV', $header['crc'], $header['size']);
   fwrite($fp, $binary_data,8); fclose($fp);
   $gzp = @gzopen($to.$header['filename'].'.gz','rb');
    if(!$gzp) return(-2);
   $fp = @fopen($to.$header['filename'],'wb');
   if(!$fp) return(-1);
   $size = $header['size'];
   while ($size != 0)
   {
     $read_size = ($size < 2048 ? $size : 2048);
     $buffer = gzread($gzp, $read_size);
     $binary_data = pack('a'.$read_size, $buffer);
     @fwrite($fp, $binary_data, $read_size);
     $size -= $read_size;
   }
   fclose($fp); gzclose($gzp);
   touch($to.$header['filename'], $header['mtime']);
   @unlink($to.$header['filename'].'.gz');
  	}
  }
	if($this->_debug){
		$data = array(
	   			 'extractpath' => $to,
	   			 'filename' => $header[filename],
			);
			echo '<pre>';
			echo "<b><font color ='red'>Unpack file infomation</font></b> <br />";
		    print_r($data);
		    echo '</pre>';
	}
  return true;
 }//end fun
}//end class
?>
