<?php
	
	session_start ();
	include('database.php');
	DB_connexion(); 
	
	header( 'content-type: text/html; charset=utf-8' );
	
	error_reporting(0);
	date_default_timezone_set('Europe/Paris');
	
	if(!isset($_SESSION['logged']) )
	{
		header ('Location: interdiction.php');
	}
	
	if($_SESSION['logged']== "no")
	{
		header ('Location: interdiction.php');
	}
	
	/*if (!isset($_SESSION['nom']) && !isset($_SESSION['password']))
	{  
			header("Location: login.php");   
	}*/

	
	if(!empty($_POST) )
	{
		$_SESSION['sauvegarde_formulaire'] = $_POST ;
     
		$page_actuelle = $_SERVER['PHP_SELF'] ;
		if(!empty($_SERVER['QUERY_STRING']))
		{
			$page_actuelle .= '?' . $_SERVER['QUERY_STRING'] ;
		}
     
		header('Location: ' . $page_actuelle);
		exit;
	}
	
	if(isset($_SESSION['sauvegarde_formulaire']))
	{
		$_POST = $_SESSION['sauvegarde_formulaire'] ;
		unset($_SESSION['sauvegarde_formulaire']);		
	}	
	
	
	if( isset($_POST['valide_form']) && $_POST['valide_form'] == "ok" )
	{
		
		$jour = date('d-m-Y');
		$heure = date("H_i_s");
		$infos = $jour.'-'.$heure;
		//$filename = "sauvegarde_edition-" .$infos .".txt"; // "test.csv";
		$fichier = "backup_user-" .$infos .".txt"; 

		DB_to_file($fichier);
	
		echo "Backup fait";
		echo '<br>';
		echo '<br>';

	
	}
?>
	
<script type="text/javascript">
	
function call_update()
{
			scruter();
			setTimeout("call_update()", 1000); 
}

function scruter()
{
			var xhr = getXhr()
			// On défini ce qu'on va faire quand on aura la réponse
			xhr.onreadystatechange = function()
			{
					// On ne fait quelque chose que si on a tout reçu et que le serveur est ok
					if(xhr.readyState == 4 && xhr.status == 200)
					{
						//alert(xhr.responseText);
						retour = xhr.responseText
						
						if(retour == 0)
						{  	
		
							$(function()
							{
									$( "#message_expiration" ).dialog({
									modal: true,
									title: "Infos",
									buttons: {
												Ok: function()
												{
													$( this ).dialog( "close" );
													 document.location.href = "logout_expire.php";
												}
											 }
										});
							});
							
							
						}
	
						
						
					}
			}
					
			xhr.open("GET","session_timeout.php",true);
			xhr.send(null);
}

function getXhr()
{
			var xhr = null; 
			if(window.XMLHttpRequest) // Firefox et autres
			   xhr = new XMLHttpRequest(); 
			else if(window.ActiveXObject)
			{ // Internet Explorer 
			   try {
						xhr = new ActiveXObject("Msxml2.XMLHTTP");
				   } catch (e) 
				   {
						xhr = new ActiveXObject("Microsoft.XMLHTTP");
				   }
			}
			else { // XMLHttpRequest non supporté par le navigateur 
					alert("Votre navigateur ne supporte pas les objets XMLHTTPRequest..."); 
					xhr = false; 
				 } 

			return xhr;
}

</script>

<link href="http://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css" rel="stylesheet">
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>


<?php
	
function DB_to_file($filename)
{
				// sauvegarde du classement dans un fichier
	
				//$sql = "SELECT * FROM parties ORDER by date asc"; 
				$sql = "SELECT * FROM " .$_SESSION['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;
				}
	
				$nom_fichier = $filename;
				chdir("backup");
											
				$fp = fopen($nom_fichier, 'w'); 
				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);
				
				header("location: backup.php");
		
}
?>
	
<style>
	
.couleur_texte
{
color: red;
}

</style>
	
<?php	

function dirsize($repertoire) 
{
  
  $size = 0;
  
  foreach(scandir($repertoire) as $file)
  {
		if(is_file($file) && $file != '.' && $file != '..')
		{
			$size += filesize($file);
		}
  }
  
  if($size > 1024)
  {
	$size = round($size / 1024 , 2);
    $retour = $size ." Koctets";

	if($size > 1024)
	{
		$size = round($size / 1024 , 2);
		$retour = $size ." Moctets";
	}
  }
  else
  { 
	$retour = $size ." octets";
  }
  
  return $retour;
}

function listing_fichier_repertoire($repertoire) 
{
    $results = array();
    $handler = opendir($repertoire);

	$cpt = 0;
		
	$ts_actuel = strtotime(date("d-m-Y H:i:s"));

	//sauvegarde_edition-13-09-2015-10_06_57.txt
	
    while ($file = readdir($handler)) 
	{
		if($file != "." && $file != ".." ) 
		{
			$file_name = explode(".",$file);
			$date_pieces = explode("-",$file_name[0]);
			$jour = $date_pieces[1];
			$mois = $date_pieces[2];
			$annee = $date_pieces[3];
			$heure_tab = explode("_",$date_pieces[4]);
			
			//echo "<pre>";
			//print_r($date_pieces);
			
			$timestamp = mktime ($heure_tab[0], $heure_tab[1], $heure_tab[2], $mois, $jour, $annee);
			
			$ts_difference = $ts_actuel - $timestamp;
			$ts_7jours = 7 * 24 * 3600;
			if($ts_difference >= $ts_7jours)
			{
				//echo $file ." ----  " .$format ."    " .$ts ."   trop ancien" ;
				//chdir("sauvegarde_echec");
				//unlink($file);
				 $coco = 5;
			}
			
			$results[$cpt][0] = $file;
			$results[$cpt][1]= $timestamp;
			$results[$cpt][2]= filesize($file);
			$cpt = $cpt + 1;
		}
    }
	chdir("backup");
	
    closedir($handler);
    return $results;
}


function sauvegarde_DB()
{	
	

	//$fichier = '/homez.65/analogde/www/Massage/Backup/manuel_db-backup-'.$infos.'.sql';
	//system("mysqldump --host=analogdepat.mysql.db --user=analogdepat --password=Un92pac007 --default-character-set=utf8 analogdepat configuration client gestion reservation2015 > $fichier");

	$jour = date('d-m-Y');
	$heure = date("H_i_s");
	$infos = $jour.'-'.$heure;
	$filename = "sauvegarde_manuelle-" .$infos .".txt"; // "test.csv";

	DB_to_file($filename);
	
	echo "Backup Done";
	echo '<br>';
	echo '<br>';

	
}

/////////////////////////////

	$chemin =  getcwd();
	
	echo '<br><br>';
	
	$tab = listing_fichier_repertoire('backup'); 
	//echo '<pre>';
	//print_r($tab);
	
	//chdir($chemin);
	
	for($i=0; $i < count($tab); $i++)
	{
		$tab_fichier = $tab[$i][0];
		$tab_ts[] = $tab[$i][1];
	}
	
	$tab_sort = $tab_ts;
	sort($tab_sort);
	
	$tab_reverse = array_reverse($tab_sort);
	//echo '<pre>';
	//print_r($tab_sort);
	
	for($i=0; $i < count($tab); $i++)
	{
		$element = $tab_reverse[$i];
		$position = array_search($element, $tab_ts);
		//echo '<br><br>';
		$file = $tab[$position][0];
		//echo $position ." " .$tab[$position][0]  ."  " .filesize($file);
		
		$tab_affiche[$i][0] = $tab[$position][0];
		$tab_affiche[$i][1] = filesize($file);
	}
	
	echo '<a href="admin.php">retour ...</a>  
		 <br>
		 <br>';

		 
	echo '<form method="post" action="backup.php">               
		  <input type="submit" name="Envoyer" value="Backup la database" />
		  <input type="hidden" name="valide_form" id="valide_form" value="ok" />
		  </form>';   	
	
	
	
	$taille = dirsize('.'); 
	$nb_fichiers = count($tab_affiche);
	echo "$nb_fichiers fichier(s) pour un espace occupé de : " .$taille ;
	echo '<br>';	
		
	echo "<table border=1 cellpadding=5 cellspacing=0>";
	echo "	<tr>
			<th>Id</th>
			<th>Fichier backup</th>
			<th>Taille en octets</th>
			</tr>";

	for($i=0; $i < count($tab_affiche); $i++)
	{
			$j = $i + 1;
			echo "<tr>
				  <td>" .$j ."</td>";	
			//echo '<td>';
			//echo '<a href="restauration.php?fichier=" .$tab_affiche[$i][0].</a>' .$tab_affiche[$i][0] .'</td>';
			echo '<td> 
				  <a href="restauration.php?fichier='.$tab_affiche[$i][0].'" title = "Restauration">';
			echo  $tab_affiche[$i][0];
			echo '</a>
				  </td>';
			
			
			echo "<td align = 'center'>" .$tab_affiche[$i][1] ."</td>";
			echo '</td>
			      </tr>';
	}
	echo "</table>";
	

?>

	<div id="message_expiration" style="display: none">
	<p>
	<span class="ui-icon ui-icon-circle-check" style="float:left; margin:0 7px 50px 0;"></span>
	La session a expiré. veuillez vous reconnecter.
	</p>
	</div>

	<script type="text/javascript">
		call_update();
	</script>