#!/usr/local/bin/php
<?php

	include('database.php');
	DB_connexion(); 

	date_default_timezone_set('Europe/Paris');
	
	//////////////////////////////
	
	$jour = date('d-m-Y');
	$heure = date("H_i_s");
	$infos = $jour.'-'.$heure;
	$fichier = "lulu____backup_auto_blitz-" .$infos .".txt";     
	$chemin = '/homez.65/analogde/www/WORKAREA/WEBSITE/BLITZ/backup_blitz';
	
	chdir($chemin);
	
	//DB_to_file($fichier , "module_blitz");
	
	//bilou();
	
	tartuffe();


	

	
	//$conn = mysqli_connect($db_host, $db_user, $db_pass, $db_name);
	//$conn->set_charset("utf8");
	
function bilou()
{
	$sqlScript = "";
	
	$tables= "BLITZ_affectation,BLITZ_classement,BLITZ_evolution,BLITZ_parties";

	$tables = is_array($tables) ? $tables : explode(',',$tables);
	
	foreach ($tables as $table) 
	{
       
		$query = "SHOW CREATE TABLE $table";
		$result = mysql_query( $query);
		$row = mysql_fetch_row($result);
		$sqlScript .= "\n\n" . $row[1] . ";\n\n";
    
		$query = "SELECT * FROM $table";
		$result = mysql_query($conn, $query);
		$columnCount = mysql_num_fields($result);
		
		// Prepare SQLscript for dumping data for each table
		for ($i = 0; $i < $columnCount; $i ++) 
		{
			while ($row = mysql_fetch_row($result)) 
			{
				$sqlScript .= "INSERT INTO $table VALUES(";
				
				for ($j = 0; $j < $columnCount; $j ++) 
				{
					$row[$j] = $row[$j];
					if (isset($row[$j])) 
					{
						$sqlScript .= '"' . $row[$j] . '"';
					} 
					else 
					{
						$sqlScript .= '""';
					}
					
					if ($j < ($columnCount - 1)) 
					{
						$sqlScript .= ',';
					}
				}
				
				$sqlScript .= ");\n";
			}
		}
		
		$sqlScript .= "\n"; 
		
	}
	
	$backup_file_name =  'yyyyyy_backup_' . time() . '.sql';
	$fileHandler = fopen($backup_file_name, 'w+');
	$number_of_lines = fwrite($fileHandler, $sqlScript);
	fclose($fileHandler); 

}	
	
function DB_to_file($fichier, $module_selection)
{
				//chdir($chemin);
				
				//$sql = "DELETE FROM " .$_SESSION['classement'] ." where id = '".$id."' ";				
				
				if( $module_selection === "module_chess")
				{
					$sql = "SELECT * FROM parties_new ORDER by date asc"; 
				}
				else
				{
					$sql = "SELECT * FROM BLITZ_parties ORDER by date asc"; 
				}
				
				$results = mysql_query($sql);
				$nb_parties = mysql_num_rows($results);
							
				while($row = mysql_fetch_assoc($results))
				{
					$blanc = $row['w_name'];
					$noir = $row['b_name'];
					$date = $row['date'];
					$resultat = $row['result'];
					$date_partie = date('d/m/Y', $date);
					
					if($resultat == 1)
					{
						$_score_blanc = 1;
						$_score_noir = 0;
					}
					if($resultat == 2)
					{
						$_score_blanc = 0;
						$_score_noir = 1;
					}
					if($resultat == 3)
					{
						$_score_blanc = 0.5;
						$_score_noir = 0.5;
					}
				
					$table_csv[0] = $date_partie;
					$table_csv[1] = $blanc;
					$table_csv[2] = $noir;
					$table_csv[3] = $_score_blanc;
					$table_csv[4] = $_score_noir;

					$table_fichier[] = $table_csv;
				}
				
				//echo getcwd();
				
										
				$fp = fopen($fichier, 'a+'); 
				for ($i=0; $i < $nb_parties; $i++)
				{
					$str_comma_separated = implode(";", $table_fichier[$i]);
					fputs ($fp, $str_comma_separated);
					if($i != $nb_parties - 1)
					fputs($fp, "\n");
				}
						
				fclose($fp);
				
				//echo "Done";
				
			
}

function tartuffe()
{

		$sqlScript = "";
	
		$db_host    = "analogdepat.mysql.db";
		$db_user   = "analogdepat";
		$db_pass   = "Un92pac007";
		$db_name   = "analogdepat";
	
		$tables= "BLITZ_affectation,BLITZ_classement,BLITZ_evolution,BLITZ_parties";

		//$tables = is_array($tables) ? $tables : explode(',',$tables);
		
		$sqlScript = "\n/*---------------------------------------------------------------".
					"\n  SQL DB BACKUP ".date("d.m.Y H:i")." ".
					"\n  HOST: {$db_host}".
					"\n  DATABASE: {$db_name}".
					"\n  TABLES: {$tables}".
					"\n  ---------------------------------------------------------------*/\n";
		
		$tables = is_array($tables) ? $tables : explode(',',$tables);

		foreach ($tables as $table) 
		{
		
			$sqlScript.= "\n/*---------------------------------------------------------------".
						 "\n  TABLE: `{$table}`".
						 "\n  ---------------------------------------------------------------*/\n";  
		
      		//$sqlScript.= "DROP TABLE IF EXISTS `{$table}`;\n";
	  
			$sqlScript.= "TRUNCATE TABLE IF EXISTS `{$table}`;\n";
	  
			// pas utile
			//$query = "SHOW CREATE TABLE $table";
			//$result = mysql_query($query);
			//$row = mysql_fetch_row($result);
			//$sqlScript .= "\n\n" . $row[1] . ";\n\n";
    
			$query = "SELECT * FROM $table";
			$result = mysql_query($query);
			$columnCount = mysql_num_fields($result);
		
			for ($i = 0; $i < $columnCount; $i ++) 
			{
					while ($row = mysql_fetch_row($result)) 
					{
						$sqlScript .= "INSERT INTO $table VALUES(";
						
						for ($j = 0; $j < $columnCount; $j ++) 
						{
							$row[$j] = $row[$j];
							if (isset($row[$j])) 
							{
								$sqlScript .= '"' . $row[$j] . '"';
							} 
							else 
							{
								$sqlScript .= '""';
							}
							
							if ($j < ($columnCount - 1)) 
							{
								$sqlScript .= ',';
							}
						}
						
						$sqlScript .= ");\n";
					}
			}
		
			$sqlScript .= "\n"; 
	
		}
	
		
		//$backup_file_name =  'zzzzz_backup_' . time() . '.sql';
		$backup_file_name = 'blitz_auto_db_tables_backup_'.date("d.m.Y_H:i").'.sql';
		
		
		$fileHandler = fopen($backup_file_name, 'w+');
		$number_of_lines = fwrite($fileHandler, $sqlScript);
		fclose($fileHandler); 
	
		//echo "******** Nom du fichier ********";
		//echo "<br/>";
		//$backup_file = 'blitz_db-backup-'.date("d.m.Y_H:i").'.sql';
		//echo $backup_file;
						
		//echo "<br/>";
		//echo "<br/>";

		//echo "******** Nom du l'archive aprés compression ********";
		//echo "<br/>";
		$backup_file_zipped = 'blitz_auto_db_tables_backup_'.date("d.m.Y_H:i").'.zip';
		//echo $backup_file_zipped;
				
		zip_file($backup_file_name, $backup_file_zipped);
	
}	

function zip_file($backup_file, $backup_file_zipped)
{
	$zip = new ZipArchive;
	if ($zip->open($backup_file_zipped , ZipArchive::CREATE | ZipArchive::OVERWRITE ) === TRUE)
	{
		// Add file to the zip file
		
		
		
		//$chemin_zip = _PATH."/backup_blitz/";
		
		$chemin_zip = "/homez.528/analogde/www/WORKAREA/WEBSITE/BLITZ/backup_blitz/";
		
		//echo ">>>>> " $chemin_zip;
		
		$zip->addFile($backup_file);
		// All files are added, so close the zip file.
		$zip->close();
	}
	
	copy($backup_file_zipped, 'backup_blitz/'.$backup_file_zipped);
	
	// prévoir
	unlink($backup_file);
	//unlink($backup_file_zipped);
	
	
	limiteur_backup("*.zip");
	limiteur_backup("*.csv");
	
}

function limiteur_backup($type_file)
{
	
	$dir = '/homez.65/analogde/www/WORKAREA/WEBSITE/BLITZ/backup_blitz/';
	
	
//	foreach (glob($dir."*.zip") as $file) 
	foreach (glob($dir .$type_file) as $file) 
	{

		// plus de 7 jours 
		if(time() - filectime($file) > 86400 * 7)
		{
			unlink($file);
			//echo $file ."<br/>"; 
		}
		//else
		//{
		//	echo $file ."<br/>"; 
		//}			
	}

}


function xxxxlimiteur_backup()
{

	$dir = _PATH."/backup_blitz/";
	chdir($dir);
	
	$dircontents = scandir($dir); //1
	
	$array_file = array();
	$cpt = 0;
	$associative = array();
	
	foreach ($dircontents as $file) 
	{
		$extension = pathinfo($file, PATHINFO_EXTENSION);
		if ($extension == 'zip') 
		{
			$LastModified = filemtime($file);
			$associative[$file] = $LastModified; 
		}
	}
	
	// tri du plus ancien au plus récent
	uasort($associative, 'cmp');
	
	// renverse le table 
	$reverse = array_reverse($associative);
	
	// debug
	//print_r(array_keys($reverse));
	
	// extraire toutes les clé qui correpondent au nom des fichiers 
	$liste_of_keys = array_keys($reverse);
	
	foreach($liste_of_keys as $element)
	{
		//echo $element;
		//echo "<br/>";
		//echo "<br/>";
		
		$array_file[$cpt][0] = $element;
		$array_file[$cpt][1]= filesize($element);
		$cpt = $cpt + 1;
	}
	
	
	
	// clamp le nombre de sauvegarde 
	$clamp = 40;
	
	// nettoyage
	if( count($array_file) > $clamp)
	{
	
		$lastElement = end($array_file);
	
		$removed = array_pop($array_file);
		unlink($removed);
	
		// il fait effacer les plus anciens
		//$nb_to_remove = count($array_file) - $clamp;
		
		//echo " Sauvegarde à supprimer: " .$nb_to_remove;
		//echo "<br/>";
		
		//for($i = $clamp; $i < count($array_file); $i++)
		//{
			
		
		//	$key = $array_file[$i][0];
			//echo "--> " .$key;
			//echo "<br/>";
			//unset($array_file[$key]); 
		//	unset($array_file[$i]); 
		//	unlink($array_file[$i]);
			
		//}
		
		//echo "<pre>";
		//print_r($array_file);
		//echo "<pre/>";
		
	}

}
	
?>
