<?php
/***********************************************************************************/
/* MassCRM客户关系管理系统							  							   */
/* ========================      						   						   */
/* 欢迎使用 MassCRM ,在您开始使用之前,请务必完整阅读本软件附带的全部说明档	    	   */
/***********************************************************************************/
/* Welcome to http://www.massboxes.com & http://masscrm.massboxes.com		       */
/***********************************************************************************/
	function ZipDir($szDirName, &$szData, &$szInfo)
	{
		// write dir header
		$szInfo .= "$szDirName|[dir]\n" ;
		$file_count = 0 ;
		$hDir = OpenDir($szDirName) ;
		while ( $file = ReadDir($hDir) )
		{
			if ( $file=="." || $file==".." )	continue ;
	
			$szCurFile = "$szDirName/$file" ;
	
			if ( Is_Dir($szCurFile) )
			{
				$file_count += ZipDir($szCurFile, &$szData, &$szInfo) ;
			}
			else if ( Is_File($szCurFile) )
			{
				$hCurFile = fopen($szCurFile, "rb") ;
				$size = filesize($szCurFile) ;
				$szStream = fread( $hCurFile, $size ) ;
				fclose($hCurFile) ;
				$file_count++ ;
	
				// write info
				$szInfo .= "$szCurFile|$size\n" ;
	
				// write data
				$szData .= $szStream ;
			}
		}
	
		// write dir footer
		$szInfo .= "$szDirName|[/dir]\n" ;
		return $file_count ;
	}
	function deldir($dir) {
		$dh=opendir($dir);
		while ($file=readdir($dh)) {
			if($file!="." && $file!=".."){
				$fullpath=$dir."/".$file;
				if(!is_dir($fullpath)){
			      unlink($fullpath);
				}
				else {
			      deldir($fullpath);
				}
			}
		}
			
		closedir($dh);
			
		if(rmdir($dir)) {
			return true;
		}
		else {
			return false;
		}
	}
	
	$time=date("Y-m-d",time());
	$dir="./backupfile/{$_REQUEST[db_dbname]}/{$time}";
	$szData = "" ;
	$szInfo = "" ;
	
	$file_count = @ZipDir($dir, &$szData, &$szInfo) ;
	$info_size_16byte = @sprintf("%016d", @strlen($szInfo)) ;
	$szData = @sprintf("%016d",$file_count) . $info_size_16byte . $szInfo . $szData ;
	$filename = "{$_REQUEST[db_dbname]}_{$time}";
	if ( function_exists("gzencode") )
	{
		$szData = gzencode($szData) ;
		$filename .= ".gz" ;
	}
	
	Header("Content-type: application/octet-stream");
	Header("Accept-Ranges: bytes");
	Header("Accept-Length: " . strlen($szData));
	Header("Content-Disposition: attachment; filename=$filename");
	echo $szData ;
	deldir("./backupfile/{$_REQUEST[db_dbname]}/{$time}/");		
?>