<?php

/// additional security condition starts/////
$redirectURL = "https://demo.web-alliance.uk/demo_crm_lte_3/files_folder_xyz/index.php";
$url = "https://demo.web-alliance.uk/demo_crm_lte_3/files_folder_xyz/api/matchSecretCode";

//include_once("../../include/startup.php");
$project_folder = "/thermotec/";	
//$project_folder = "";	
    
//include_once($_SERVER['DOCUMENT_ROOT']."/include/startup.php");	
$dir_name = $_SERVER['DOCUMENT_ROOT'].$project_folder."/admin/modules/376/297/aPx-1947/ab_thik_hai/";	
include_once($_SERVER['DOCUMENT_ROOT'].$project_folder."/include/startup.php");
//include_once("/home/richdiamonds/public_html/include/startup.php");


if (!isset($_REQUEST['secret_code'])) {
	$protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https://' : 'http://';
    $currentURL = $protocol . $_SERVER['HTTP_HOST'] . ucwords($_SERVER['REQUEST_URI']);
	
    header("Location: $redirectURL?originalURL=$currentURL");
    exit();
}else{
	$scode=$_REQUEST['secret_code'];
	$secret_key = 'BaCkUPEncodedDataforGDPRNewRule-tre-rekl@awR!d@ugi6*w95!';
	$secret_iv =  'BaCkUP-NewDATAEncodeSchemeCode-seFl7#zo+lJA0Lsw*jL@hEQ$';
	$output = false;
	$encrypt_method = "AES-256-CBC";
	$key = hash( 'sha256', $secret_key );
	$iv = substr( hash( 'sha256', $secret_iv ), 0, 16 );
	$output = openssl_decrypt( base64_decode($scode), $encrypt_method, $key, 0, $iv );
	
	////  curl code start/////
	

	$curl = curl_init($url);
	curl_setopt($curl, CURLOPT_URL, $url);
	curl_setopt($curl, CURLOPT_POST, true);
	curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

	$headers = array(
	   "Accept: application/json",
	   "Authorization: Bearer {token}",
	   "Content-Type: application/json",
	);
	curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
	
	$dataArray = array(
		"secret_code" => $output,
		"encrypted_secret_code" => $scode,
		"ic" => $_REQUEST['ic']
	);
	
	$data = json_encode($dataArray);
	curl_setopt($curl, CURLOPT_POSTFIELDS, $data);

	curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
	curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);

	$resp = curl_exec($curl);
	curl_close($curl);
	
	if (substr($resp, 0, 3) === "\xEF\xBB\xBF") {
		$resp = substr($resp, 3);
	}
	
	$data = json_decode($resp, true);
	$secret_code = $data['data'][0]['secret_code'];
	$encrypted_secret_code = $data['data'][0]['encrypted_secret_code'];
	$is_valid = $data['data'][0]['is_valid'];
	
	////  curl code start/////
}

if($is_valid==0){
	die("Code not matched");
}else if($is_valid==2){
	die("Link is expired");
}

/// additional security condition ends/////


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;
	//echo "<font color='white'>$today</font>";
	if($today == $ic){
		return "1";
	}else{
		return "2";
	}
	
}


$ic_not_valid = check_query_string($_GET['ic']);

if(isset($_GET['ic'])){
	if($ic_not_valid == "2"){
		die("Invalid URL Found");			
	} 
}else if(isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] != "79.79.5.125"){
	die("Invalid URL Found");
}


include_once("functions.php");	

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

ini_set('memory_limit', '2550M');
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;
//print_r($configBackupDB);

foreach($configBackupDB as $dbs){	

	if(date("d") == 29 and $i_bkp ==0){
		//$projects .="only-structure-of-all-tables<br><br>";
		//backup_tables($dbs['server'],$dbs['username'],$dbs['password'],$dbs['database'],'*',"_only_structure"."",false);
	}	
	
	//$i_bkp++;
	
	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;
	
	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{ 
		die("can't open file");
	}	
	
	$return = null;
	unset($return);	
	$file_to_write = $file_name_new; 	
}

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

$rootPath = realpath($dir_name);
$dir = $dir_name.$file_name_new;

//echo "<h3>Backing up database to `<code>{$dir}</code>`</h3>";
/* echo "mysqldump --no-tablespaces --user={$Database_username} --password='{$Database_password}' --host={$Database_hostname} {$Database_name} --result-file={$dir}";
die; */

$command_var = "mysqldump --no-tablespaces --user={$Database_username} --password='{$Database_password}' --host={$Database_hostname} {$Database_name} --result-file={$dir}";

exec($command_var, $output);

//var_dump($output);


// 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();
$archive_file_name = $dir_name.$zip_file_name;
sleep(2);
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;
?>