<?php

if(php_sapi_name() == 'cli' || empty($_SERVER['REMOTE_ADDR'])) {	
	$cron_name = __FILE__;	
	$dir_name = $_SERVER['DOCUMENT_ROOT']."/admin/modules/backup/images_backup_temp/";	
}else{
	$cron_name = "backup/db_backup";
	//include("../../include/startup.php");
	$dir_name = $_SERVER['DOCUMENT_ROOT']."/{$other_fields["project_folder_name"]}admin/modules/backup/images_backup_temp/";	
    if($_SERVER['HTTP_HOST'] =="localhost" ){
		$dir_name = $_SERVER['DOCUMENT_ROOT']."{$other_fields["project_folder_name"]}admin/modules/backup/images_backup_temp/";	   
    }
}

global $db,$conn;
$db->query("CREATE TABLE IF NOT EXISTS `cron_tracker` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `cron_name` varchar(255) NOT NULL,
  `cron_alias` varchar(255) NOT NULL,
  `start_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `end_time` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
  `details` varchar(1000) NOT NULL,
  PRIMARY KEY (`id`)
);");


$file_to_write = "";
$file_name_new = "";

$sql = "INSERT INTO cron_tracker (cron_name,cron_alias) VALUES('".$cron_name."','db_backup')";	
$db->query($sql);
$cron_start_id = $db->insert_id();

ini_set('memory_limit', '150M');
set_time_limit(0);
error_reporting(0);


$projects = "";

if($_GET['db'] =="etuk_blog"){
	
	$Database_hostname = "localhost";
	$Database_username = "etuk_cuser";
	$Database_password = "puixu&?Uie7#";
	$Database_name     = "etuk_blog";

	//$projects .= $Database_name." , ";
	
	$configBackupDB[] = array('server'=>$Database_hostname,
							  'username'=>$Database_username,
							  'password'=>$Database_password,
							  'database'=>$Database_name,
							  'tables'=> '*',
							  'bkp_name'=>$Database_name,
							  'only_structure'=>array(),
							  );
}else if($_GET['db'] =="etuk_livehelp"){
	
	$Database_hostname = "localhost";
	$Database_username = "etuk_cuser";
	$Database_password = "puixu&?Uie7#";
	$Database_name     = "etuk_livehelp";

	//$projects .= $Database_name." , ";
	$configBackupDB[] = array('server'=>$Database_hostname,
							  'username'=>$Database_username,
							  'password'=>$Database_password,
							  'database'=>$Database_name,
							  'tables'=> '*',
							  'bkp_name'=>$Database_name,
							  'only_structure'=>array(),
							  );
}else{
//$projects .= $Database_name." , ";

$configBackupDB[] = array('server'=>$Database_hostname,
						  'username'=>$Database_username,
						  'password'=>$Database_password,
						  'database'=>$Database_name,
						  'tables'=> '*',
						  'bkp_name'=>$Database_name,
						  'only_structure'=>array(),
						  );

}
						  
//'bkp_name'=>'all-wthout-user-and-google'
$projects .=$configBackupDB[0]['tables']."<br><br>";

$i_bkp = 0;

foreach($configBackupDB as $dbs){		
	backup_tables($dbs['server'],$dbs['username'],$dbs['password'],$dbs['database'],$dbs['tables'],$dbs['bkp_name'],true,$dbs['only_structure']);	
}
/* backup the db OR just a table */
function backup_tables($host,$user,$pass,$name,$tables = '*',$bkp_name = "",$with_records = true,$only_structure)
{
	global $file_to_write,$dir_name;
	$link = mysqli_connect($host,$user,$pass);
	mysqli_select_db($name,$link);

	//get all of the tables
	if($tables == '*')
	{
		$tables = array();
		$result = mysqli_query($conn,'SHOW TABLES');
		while($row = mysqli_fetch_row($result))
		{
			$tables[] = $row[0];
		}
	}
	else
	{
		$tables = is_array($tables) ? $tables : explode(',',$tables);
	}
	$return = '';
	//cycle through
	foreach($tables as $table)
	{
		$result = mysqli_query($conn,'SELECT * FROM '.$table);
		$num_fields = @mysqli_num_fields($result);
		
		$return.= 'DROP TABLE IF EXISTS `'.$table.'`;';
		$row2 = @mysqli_fetch_row(mysqli_query($conn,'SHOW CREATE TABLE '.$table));
		$return.= "\n\n".$row2[1].";\n\n";
		if($with_records && !in_array($table,$only_structure)){
			for ($i = 0; $i < $num_fields; $i++) 
			{
				while($row = mysqli_fetch_row($result))
				{
					$return.= 'INSERT INTO `'.$table.'` VALUES(';
					for($j=0; $j < $num_fields; $j++) 
					{
						$row[$j] = addslashes($row[$j]);
						//$row[$j] = preg_replace("\n","\\n",$row[$j]);
						if (isset($row[$j])) { $return.= '"'.$row[$j].'"' ; } else { $return.= '""'; }
						if ($j < ($num_fields-1)) { $return.= ','; }
					}
					$return.= ");\n";
				}
			}
		}	
		$return.="\n\n\n";
		
	}	
	
	//echo $dir_name;
	
	mkdir($dir_name);	
	deleteDir($dir_name);
	mkdir($dir_name);
	
	global $file_name_new,$dir_name;
	$file_name_new 	 = $name."-bkp-".date("d_m_Y_h_i_s")."-".$bkp_name.".sql";
	
	$file_to_write =  $dir_name.$file_name_new;
	
	if($fh = fopen($file_to_write, 'w')){
			fwrite($fh, $return);
			fclose($fh);
	}else{ 
		$msg = "can't open file ";
		mail("kumarshailesh007@gmail.com","test 134  ",$msg);
		die("can't open file");
	}	
	
	$return = null;
	unset($return);
	//global $db,$conn;		
	//$db->free();
	//mysqli_close();
	$file_to_write = $file_name_new; 	
}


/////////////////////////////////////////////////////// ZIP started ///////////////////////////////////////////
// Get real path for our folder

$rootPath = realpath($dir_name);

// Initialize archive object
$zip = new ZipArchive();
$zip_name = str_replace(".sql","",$file_name_new);
$zip_file_name = $zip_name.'.zip';

$zip->open($dir_name.$zip_file_name, ZipArchive::CREATE | ZipArchive::OVERWRITE);

// Create recursive directory iterator
/** @var SplFileInfo[] $files */
$files = new RecursiveIteratorIterator(
    new RecursiveDirectoryIterator($rootPath),
    RecursiveIteratorIterator::LEAVES_ONLY
);


foreach ($files as $name => $file)
{
    // Skip directories (they would be added automatically)
    if (!$file->isDir())
    {
        // Get real and relative path for current file
        $filePath = $file->getRealPath();
        $relativePath = substr($filePath, strlen($rootPath) + 1);

        // Add current file to archive
        $zip->addFile($filePath, $relativePath);
    }
}

// Zip archive will be created only after closing object
$zip->close();

// the message
$msg = "Backup cron executed for the following table(s)  <br><br><br>".$projects;
// use wordwrap() if lines are longer than 70 characters
$msg = wordwrap($msg,70);
// send email
$to = "harendar.kyadav87@gmail.com,kumarshailesh007@gmail.com";
//$to = "kumarshailesh007@gmail.com";
$subject = "Ablex DB backup taken from adminn ";
//utility::send_multiple_attachment_mail($to, $subject, $functions->HTMLemail($msg), array(), "newhelpalliance@gmail.com");	

if($_GET['db'] != "etuk_blog" && $_GET['db'] != "etuk_livehelp"){
$cron_end_time = date('Y-m-d h:i:s');
$sql = "UPDATE cron_tracker SET end_time ='".$cron_end_time."' WHERE id='$cron_start_id' ";	
$db->query($sql);
}
$archive_file_name = $dir_name.$zip_file_name;
ob_clean();
header("Content-type: application/zip"); 
header("Content-Disposition: attachment; filename=$zip_file_name");
header("Content-length: " . filesize($archive_file_name));
header("Pragma: no-cache"); 
header("Expires: 0"); 
readfile("$archive_file_name");
//ini_set('memory_limit', '2M');
?>