<?

$_SESSION['download_link'] = false;


if(php_sapi_name() == 'cli' || empty($_SERVER['REMOTE_ADDR'])) {
	
	$cron_name = __FILE__;	
	
	$root_path = $_SERVER['DOCUMENT_ROOT'];
	$base_path = $_SERVER['DOCUMENT_ROOT'];
	$copy_destination_path = $_SERVER['DOCUMENT_ROOT']."/admin/modules/backup/images_backup_temp/";
	$delete_zip_files_path = $_SERVER['DOCUMENT_ROOT']."/admin/modules/backup/";	
}else{
	$cron_name = getcwd()."/".basename($_SERVER['PHP_SELF']);
	
	if($_SERVER['HTTP_HOST'] =="localhost" ){
		// start checking the file changes from path
		$root_path = $_SERVER['DOCUMENT_ROOT']."/{$other_fields["project_folder_name"]}";
		//to remove from folder paths
		$base_path = $_SERVER['DOCUMENT_ROOT']."/{$other_fields["project_folder_name"]}";
		$copy_destination_path = $_SERVER['DOCUMENT_ROOT']."/{$other_fields["project_folder_name"]}admin/modules/backup/images_backup_temp/";
		$delete_zip_files_path = $_SERVER['DOCUMENT_ROOT']."/{$other_fields["project_folder_name"]}admin/modules/backup/";
	}else{		
		$root_path = $_SERVER['DOCUMENT_ROOT']."/";
		$base_path = $_SERVER['DOCUMENT_ROOT']."/";
		$copy_destination_path = $_SERVER['DOCUMENT_ROOT']."/admin/modules/backup/images_backup_temp/";
		$delete_zip_files_path = $_SERVER['DOCUMENT_ROOT']."/admin/modules/backup/";	
	}
}


set_time_limit(0);


$day = (isset($_POST['day'])) ? $_POST['day'] : date("d");
$month = (isset($_POST['month'])) ? $_POST['month'] : date("m");
$year = (isset($_POST['year'])) ? $_POST['year'] : date("Y");


$date_array = explode("-",$_POST['backup_from_date']);

$day = $date_array[0];
$month = $date_array[1];
$year = $date_array[2];

$hh = 00;
$mm = 00;
$ss = 01;
$after_date = mktime($hh, $mm, $ss, $month, $day, $year);

if($_POST){
mkdir($copy_destination_path);

deleteDir($copy_destination_path);

mkdir($copy_destination_path);

$typeExtension = array("zip");

deleteFilTypesFromDir($delete_zip_files_path,$typeExtension);

class Directory_tree{
function find_directories($main_folder_path,$directory_array){

    if ($handle = opendir($main_folder_path)){    
        while (false !== ($file = readdir($handle))){
          if ($file != "." && $file != ".." && $file !== "error_log" && $file !== ".hg" && $file !== ".zip" && $file !== "create_cron" && $file !== "images_backup_temp" ){        
            $abc=$main_folder_path.$file."/";                
            if(is_dir($abc)){    
                //echo "<b>Directory</b><br>".$abc;          
                array_push($directory_array,$abc);          
                $directory_array= $this->find_directories($abc,$directory_array);         
            }
          }
        }  
    }
    return $directory_array;
}
function files_in_directory($path,$after_date){
    $files_ind_dir = "";
	
	$upload_types_allowed = array('jpg', 'JPG', 'png', 'PNG');
	if ($handle = opendir($path)){
        while (false !== ($file = readdir($handle))){
          if ($file != "." && $file != ".."){
		  
            $abc=$path.$file;
            if(is_file($abc) && (filemtime($abc) > $after_date ) && $file !== "error_log"){
                //echo $path.$file." -- ".date("d-m-Y H:i:s.", filemtime($abc))."<br>";
                //echo $files_ind_dir .= $path.$file." -- ".gmdate("d-m-Y H:i:s", filemtime($abc))."<br>";
				if (in_array(pathinfo($path.$file, PATHINFO_EXTENSION), $upload_types_allowed)) {
					global $base_path,$copy_destination_path;
					$_SESSION['download_link'] = true;
					$exclude_base = $base_path;
					
					$folder_name_array = explode($exclude_base,$path);
					
					$folder_name_array = explode("/",$folder_name_array[1]);
					$the_dir_to_copy = "";
					for($i_f=0;$i_f<count($folder_name_array);$i_f++){
						$the_dir_to_copy .= $folder_name_array[$i_f].'/';
						//echo $folder_name_array[$i_f]."<br>";
						if($i_f >0){						
							mkdir($copy_destination_path.$the_dir_to_copy);
						}else{
							mkdir($copy_destination_path.$folder_name_array[$i_f]);
						}
					}
					
					
					copy($path.$file, $copy_destination_path.$the_dir_to_copy.$file);
				}
            }
          }
        }
    }
    return $files_ind_dir;
}

} 

// end of class

if(php_sapi_name() == 'cli' || empty($_SERVER['REMOTE_ADDR'])) {	
	$cron_name = "backup/download_latest_images";	
}else{
	//include_once("../../include/startup.php");	
	$cron_name = "backup/download_latest_images";
	
}




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



	
	
	$project_to_list = $_POST['project_to_list']."/";
	$dir_tree = new Directory_tree();
	$main_directory = $root_path;
	$directory_array=array($main_directory);
	$total_directories=$dir_tree->find_directories($main_directory,$directory_array);	
	$list_of_file_changes = "";
	
	for($i=0;$i<count($total_directories);$i++){
		$pos = strpos($total_directories[$i], "/image-nww");
		if($pos === false ){
			
			if($files_ind_dir = $dir_tree->files_in_directory($total_directories[$i],$after_date)){					
					$list_of_file_changes .="<b style='font-size:15px'>".$total_directories[$i]."<br></b>";
					$list_of_file_changes .="<span style='font-size:13px'>".$files_ind_dir."</span>";
					//echo "<b>".$total_directories[$i]."<br></b>";
					//echo $files_ind_dir;
			}
		}
	}


echo $list_of_file_changes;

$to = "kumarshailesh007@gmail.com,shoebahmad999@gmail.com,ashkumar1976@gmail.com,harendar.kyadav87@gmail.com";
$subject = "Image File(s) downloaded from Ablex server ";
$message = "Hello! <br><br>Files have been downloaded from Ablex server.<br><br><br>";
$from = "support@web-alliance.co.uk";
$headers = "From:" . $from;
//utility::send_multiple_attachment_mail($to, $subject, $functions->HTMLemail($message), array(), $from);	

$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);

/////////////////////////////////////////////////////// ZIP started ///////////////////////////////////////////
// Get real path for our folder
$rootPath = realpath($copy_destination_path);

// Initialize archive object
$zip = new ZipArchive();
$zip_file_name = 'ablex_images_changed_from_'.$day.'_'.$month.'_'.$year.'.zip';
$zip->open($delete_zip_files_path.$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();

/////////////////////////////////////////////////////// ZIP ENDED ///////////////////////////////////////////	
}


if($_POST && $_SESSION['download_link']){
$archive_file_name = $delete_zip_files_path.$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");
/*

	//ob_clean();
	$file = $config->siteURL."/modules/backup/".$zip_file_name;	
	if($_SESSION['download_link']){
		echo "<a href='$file'>Click here to download website image changed</a>";
	}else{
		echo "No file to download";
	}
	//header("Location: ".$file);
	exit;*/
}else{
ob_clean();
	echo "No file to download";
}



?>