<?php

//echo getcwd();
date_default_timezone_set('Europe/London');

//check validity of URL 
function check_query_string($ic = ""){

	$today = date("d")*date("m")*date("Y")*date("h")*date("i");
	$today = floor($today/(376+297)) + 786542953;
	
	if($today == $ic){
		return "1";
	}else{
		return "2";
	}
	
}
if(php_sapi_name() != 'cli' || !empty($_SERVER['REMOTE_ADDR'])) {

	$ic_not_valid = check_query_string($_GET['ic']);
	if(isset($_GET['ic']) && $_GET['ic']=='jsr'){
		$ic_not_valid = "1";	
	}
	if(isset($_GET['ic'])){
		if($ic_not_valid == "2"){
			die("Invalid URL1");			
		} 
	}else if(isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] != "79.79.5.125"){
		die("Invalid URL2");
	}
}
include("functions.php");	
// /home/onairco/public_html/admin/modules/backup
if(php_sapi_name() == 'cli' || empty($_SERVER['REMOTE_ADDR'])) {	
	$project_folder = "/beb";			
	include("../../../../../"."/include/startup.php");	
	$cron_name = "backup/db_backup";
	$dir_name = $_SERVER['DOCUMENT_ROOT']."/admin/modules/376/297/aPx-1947/ab_thik_hai/";
}else{
	
	$cron_name = "backup/db_backup";
	//include("../../include/startup.php");
	
    if($_SERVER['HTTP_HOST'] =="localhost" ){
		$project_folder = "/beb";		
		include($_SERVER['DOCUMENT_ROOT']."$project_folder/include/startup.php");	
		$dir_name = $_SERVER['DOCUMENT_ROOT']."$project_folder/admin/modules/376/297/aPx-1947/ab_thik_hai/";	   		
    }else{
		$project_folder = "/";		
		include($_SERVER['DOCUMENT_ROOT']."$project_folder/include/startup.php");	
		$dir_name = $_SERVER['DOCUMENT_ROOT']."$project_folder/admin/modules/376/297/aPx-1947/ab_thik_hai/";	
	
	}
	
}


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

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

$projects = "";

//$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("search_track","search_phrases"));
//'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,$conn;
	$link = mysqli_connect($host,$user,$pass,$name);
	mysqli_select_db($name,$link);

	//get all of the tables
	if($tables == '*')
	{
		$tables = array();
		$result = mysqli_query($link,'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($link,'SELECT * FROM '.$table);
		$num_fields = @mysqli_num_fields($result);
		
		$return.= 'DROP TABLE IF EXISTS `'.$table.'`;';
		$row2 = @mysqli_fetch_row(mysqli_query($link,'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 in nape backup process";
		//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();
$msg = "Full DB <br><br>";
$msg = wordwrap($msg,70);
$to = "harendar.kyadav87@gmail.com,kumarshailesh007@gmail.com";
$subject = "*** Demo CRM  DB backup ***";
//utility::send_multiple_attachment_mail($to, $subject, $functions->HTMLemail($msg), array(), "newhelpalliance@gmail.com");	


$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);
ini_set('memory_limit', '1000M');

$archive_file_name = $dir_name.$zip_file_name;
global $db,$conn;		
$db->free();
mysqli_close();
$msg = "testing";
mail("kumarshailesh007@gmail.com","1.5 1pcs Auto Backup",$msg);
ob_clean();
header("Content-type: application/zip"); 
header("Content-Disposition: attachment; filename=$zip_file_name");

header("Pragma: no-cache"); 
header("Expires: 0"); 
header("Content-length: " . filesize($archive_file_name));
flush(); // Flush system output buffer
ob_end_clean();
readfile("$archive_file_name");
exit;	
?>