Location: PHPKode > projects > Basic Announce > Basic Announce Version 4.0/inc/classes/backup.class.php
<?php

/**
 *	Class Backup (for Admin Panel)
 *  -------------- 
 *  Description : encapsulates backup operations & properties
 *  Updated	    : 21.12.2009
 *	Written by  : ApPHP
 *	
 **/

class Backup {
	
	public $error;
	
	protected $backupDirectory;
	protected $backupFilePrefix;
	protected $backupFileExt;	
	
	private $db;
	
	//==========================================================================
    // Class Constructor
	//==========================================================================
	function __construct(&$db = null)
	{
		$this->db = $db;
		$this->db->Open();
		$this->backupDirectory = "../tmp/backup/";
		$this->backupFilePrefix = "db-backup-";
		$this->backupFileExt = ".sql"; 
		$this->backupFileZipExt = ".zip";
	}
	
	//==========================================================================
    // Class Destructor
	//==========================================================================
    function __destruct()
	{
		// echo 'this object has been destroyed';
    }

	/***
	 * 	Show list of previouse backups
	 * 		@param $link_type - type of link
	 **/
	function ShowPreviouseBackups($link_type = "delete")
	{
		function DateCompare($a, $b){
			return ($a[1] <= $b[1]) ? 0 : 1;
		}
	
		$files = array();
		if (!file_exists($this->backupDirectory)) { mkdir($this->backupDirectory,0755); }
		if ($handle = opendir($this->backupDirectory)){
			// loop over the directory
			while(false !== ($file = readdir($handle))){				
				if(preg_match("/".$this->backupFilePrefix."/", $file) && preg_match("/.zip/", $file)){
					$files[] = array($file, time() - filemtime($this->backupDirectory.$file), filesize($this->backupDirectory.$file));
				}
			}		
			closedir($handle);
		}		
		
		// sort files by date
		usort($files, 'DateCompare');

		foreach($files as $key => $val){
			$fname = str_replace(array($this->backupFilePrefix, $this->backupFileExt, $this->backupFileZipExt), "", $val[0]);
			if(strtolower(_SITE_MODE) == "demo"){
				echo "<tr><td>&nbsp;</td><td>".$val[0]." <img src='../images/download.jpg' alt='' /></td><td align='center'>".number_format(($val[2]/1024), 0, ".", ",")." KB</td>";								
			}else{
				echo "<tr><td>&nbsp;</td><td>".$val[0]." <a href='mod_download_backup.php?st=download&fname=".$fname."' style='text-decoration:none;' title='Click to download'><img src='../images/download.jpg' title='Click to download' alt='' /></a></td><td align='center'>".number_format(($val[2]/1024), 0, ".", ",")." KB</td>";				
			}
			if($link_type == "delete"){
				echo "<td>&nbsp;</td><td>".((strtolower(_SITE_MODE) != "demo") ? "<a href='mod_backup.php?st=delete&fname=".$fname."' onclick='return confirm(\"Are you sure you want to delete this backup?\")'>[".lang("delete")."]</a>" : "[".lang("delete")."]")."</td><td>&nbsp;</td></tr>";				
			}else if($link_type == "restore"){
				echo "<td>&nbsp;</td><td>".((strtolower(_SITE_MODE) != "demo") ? "<a href='mod_backup.php?st=restore&fname=".$fname."' onclick='return confirm(\"Are you sure you want to restore this backup\")'>[Restore]</a>" : "[Restore]")."</td><td>&nbsp;</td></tr>";				
			}else if($link_type == "delete,restore"){
				echo "<td>&nbsp;</td>
					  <td nowrap>
						  ".((strtolower(_SITE_MODE) != "demo") ? "<a href='mod_backup.php?st=delete&fname=".$fname."' onclick='return confirm(\"Are you sure you want to delete this backup \\n(".$fname.")?\")'>[".lang("delete")."]</a>" : "[".lang("delete")."]")." 
						  ".((strtolower(_SITE_MODE) != "demo") ? "<a href='mod_backup.php?st=restore&fname=".$fname."' onclick='return confirm(\"Are you sure you want to restore this backup \\n(".$fname.")?\")'>[Restore]</a>" : "[Restore]")." 
					  </td>
					  <td>&nbsp;</td>
					  </tr>";				
			}else{
				echo "";				
			}
		}
		
		if(count($files) == 0){
			echo "<tr><td colspan='2'>There are no backups yet.</td></tr>";
		}		
	}

	/***
	 * 	Delete backup file
	 * 		@param $backup_file - backup file name
	 **/
	function DeleteBackup($backup_file = "")
	{
        // block all operations on demo version
		if(strtolower(_SITE_MODE) == "demo"){
			$this->error = "This operation is blocked in Demo Version!";
			return false;				
		}
        
		$backup_file = $this->backupDirectory.$this->backupFilePrefix.$backup_file.$this->backupFileExt.$this->backupFileZipExt;
		
		if($backup_file == ""){
			$this->error = "Backup file name can not be empty! Please re-enter.";
			return false;
		}
		
        if(@unlink($backup_file)){
            return true;		
        }else{
            $this->error = "An error occured while deleting file! Please try again later.";
            return false;
        }
	}

	/***
	 * 	Restore backup the db OR just a table
	 * 		@param $backup_file - backup file name
	 **/
	function RestoreBackup($backup_file = "")
	{
        // block all operations on demo version
		if(strtolower(_SITE_MODE) == "demo"){
			$this->error = "This operation is blocked in Demo Version!";
			return false;				
		}

		$backup_file = $this->backupDirectory.$this->backupFilePrefix.$backup_file.$this->backupFileExt;
		$backup_file_zipped = $backup_file.$this->backupFileZipExt;

		if($backup_file == ""){
			$this->error = "Backup file name can not be empty! Please re-enter.";
			return false;
		}

		$zip = zip_open($backup_file_zipped);
		if ($zip) {
			while ($zip_entry = zip_read($zip)) {
				$fp = fopen($this->backupDirectory.zip_entry_name($zip_entry), "w");
				if (zip_entry_open($zip, $zip_entry, "r")) {
					$buf = zip_entry_read($zip_entry, zip_entry_filesize($zip_entry));
					fwrite($fp,"$buf");
					zip_entry_close($zip_entry);
					fclose($fp);
				}
			}
			zip_close($zip);
		}
		
        $sql_dump = @file_get_contents($backup_file);		
		if($this->ExecuteSqlDump($backup_file)){
			@unlink($backup_file);	
            return true;
        }else{
            $this->error = "An error occured while restoring file! Please try again later.";
            return false;
        }
	}


	/***
	 * 	Execute backup the db OR just a table
	 * 		@param $backup_file - backup file name
	 * 		@param $tables - teables to backup
	 **/
	function ExecuteBackup($backup_file = "", $tables = '*')
	{
        // block all operations on demo version
		if(strtolower(_SITE_MODE) == "demo"){
			$this->error = "This operation is blocked in Demo Version!";
			return false;				
		}

		if($backup_file == ""){
			$this->error = "Backup file name can not be empty! Please re-enter.";
			return false;
		}
		
		$this->db->SetEncoding();
		
        // save all tables
        if($tables == '*'){
            $tables = array();			
            $result = $this->db->Query("SHOW TABLES LIKE '"._DB_PREFIX."%'");
            while($r__ = $this->db->FetchArray()){
				$tables[] = $r__[0];
			}
        }else{
            $tables = is_array($tables) ? $tables : explode(',',$tables);
        }
		
        // run cycle through
		$return = "";
        foreach($tables as $table){

            $this->db->Query("SELECT * FROM ".$table);
			$num_fields = $this->db->ColumnCount();
			
            $return .= "DROP TABLE IF EXISTS ".$table.";";
            $this->db->Query("SHOW CREATE TABLE ".$table);
			$r__ = $this->db->FetchArray();
            $return .= "\n\n".$r__[1].";\n\n";
            
			///echo "<br>SELECT * FROM ".$table;
            $this->db->Query("SELECT * FROM ".$table);
            while($r__ = $this->db->FetchArray()){
                $return .= "INSERT INTO ".$table." VALUES(";
                for($j=0; $j<$num_fields; $j++) 
                {
					//$r__[$j] = utf8_encode($r__[$j]);
					$row_j = $r__[$j];
                    $row_j = preg_replace("/\n/", "\\n", $row_j);
					$row_j = addslashes($row_j);
                    if(isset($r__[$j])) { $return .= "'".$row_j."'" ; } else { $return .= "''"; }
                    if($j<($num_fields-1)) { $return .= ','; }
                }
                $return .= ");\n";
            }
            $return .="\n\n\n";
        }
        
        $backup_file_name = ($backup_file == "") ? date("M-d-Y H:i:s") : $backup_file;
		$backup_file_name = str_replace(array(" "), "_", $backup_file_name);
		$backup_file_name = str_replace(array(":"), "-", $backup_file_name);
        $backup_file_path = $this->backupDirectory.$this->backupFilePrefix.$backup_file_name.$this->backupFileExt;
        $backup_file_path_zip = $backup_file_path.$this->backupFileZipExt;
		
        //save file
		if(!is_writable($this->backupDirectory)){
			$this->error = lang("msg_bk_access_rights")." : ".$this->backupDirectory;
			$result = false;
		}else{
			@chmod($backup_file_path, 0755);
			$handle = @fopen($backup_file_path,'w+');
			if($handle){
				@fwrite($handle,$return);
				@fclose($handle);
				$result = true;

				//----------------------------------------------------------------------
				// Create archive file
				include_once("archive.class.php");
						
				@unlink($backup_file_path_zip);
				//The following example creates a zip file:
				// Create new zip file in the directory below the current one
				$test = new zip_file($backup_file_path_zip);
				// All files added will be relative to the directory in which the script is 
				//    executing since no basedir is set.
				// Create archive in memory
				// Do not recurse through subdirectories
				// Do not store file paths in archive
				$test->set_options(array('inmemory' => 0, 'recurse' => 0, 'storepaths' => 0));
				// Add lib/archive.php to archive
				$test->add_files($backup_file_path);
				// Add all jpegs and gifs in the images directory to archive
				//$test->add_files(array("data/$DB_NAME/days/*.sql"));
				// Store all exe files in bin without compression
				//$test->store_files("bin/*.exe");
				// Create archive in memory
				$test->create_archive();
				// Send archive to user for download
				//$test->download_file();
				//print_r($test->error);
				//header("location: $DB_NAME.zip");
				@unlink($backup_file_path);
				
				return $backup_file_path_zip;
			}else{			
				$this->error = "An error occured while executing backup! Please try again later.";
				$result = false;
			}
			@chmod($backup_file_path, 0644);
		}		
	}

	
	/***
	 * 	Execute SqlDump
	 * 		@param $restore_query - resore query or list of queries
	 **/
	private function ExecuteSqlDump($backup_file)	
	{
		///echo $backup_file;
		
		// get  sql dump content
		$sql_dump = file($backup_file);

		if(get_magic_quotes_gpc()){
			$sql_dump = str_replace("''''", "''", $sql_dump);
		}
	
		// add ";" at the end of file
		if(substr($sql_dump[count($sql_dump)-1], -1) != ";") $sql_dump[count($sql_dump)-1] .= ";";
		
		$this->db->SetEncoding();

		$query = "";
		foreach($sql_dump as $sql_line){
			$tsl = trim(utf8_decode($sql_line));
			if(($sql_line != "") && (substr($tsl, 0, 2) != "--") && (substr($tsl, 0, 1) != "?") && (substr($tsl, 0, 1) != "#")) {
				$query .= $sql_line;
				if(preg_match("/;\s*$/", $sql_line)){
					if(strlen($query) > 5 && !@$this->db->Query($query)){
						$error_mg[] = $this->db->Error();
						return false;
					}					
					$query = "";
				}
			}
		}
		
		return true;	
	}

}
?>
Return current item: Basic Announce