<?php

/* Create a backup file in /backup/ folder and download a copy to the user hard drive. */

if(!function_exists('checkOrigin') || !$bAdmin)
{
	require_once 'config.php';
	relocate(getError('Acc&egrave;s interdit'));
}

//check external link
if(isset($_GET['action']) && $_GET['action']!='')
{
	if(!checkOrigin('backUpCreator'))
	{
		relocate(getError('Aucun lien externe autoris&eacute;'));
	}
	
	//Set designed actions
	switch ($_GET['action'])
	{
		case 'download':
			createBackUp(isset($_POST['dropDb']));
			break;
		case 'restore':
			$sBackFilePath = BACKUP_FOLDER.decodeUrl($_POST['backUpId']);
			restoreBackUp($sBackFilePath, $oConnection);
			break;
		case 'upload' :
			uploadBackUp($_FILES['backUpFile'], isset($_POST['restoreDb']), $oConnection);
			break;
		case 'sync':
			$bInternalLink = ($_POST['version']!='');
			$sUrl = $_POST['backUpUrl'].($bInternalLink?'/index.php?page=remote&action='.$_POST['version']:'');
			$sAuth = isset($_POST['useKeyRing'])?getKeyRing():$_POST['key_ring'];
			syncBackUp($sUrl, $bInternalLink, $sAuth, isset($_POST['restoreDb']), $oConnection);
			break;
		case 'reset' :
			resetDatabase($oConnection);
			break;
		default:
			break;
	}
}

//set Input Box for restoration
$oRestoreInputBox = new InputBox('Restauration d\'une sauvegarde', 'Etes-vous sur de vouloir charger la sauvegarde du #backUpDate# ?', array('Oui'=>'validateBackUp(\'#backUpId#\')', 'Non'=>''));
$oResetInputBox = new InputBox('Reset complet', 'Etes vous s&ucirc;r de vouloir proc&eacute;der &agrave; une r&eacute;intallation compl&egrave;te ? (vous allez perdre toutes vos donn&eacute;es)', array('Oui'=>'document.forms[\'reset\'].submit()', 'Non'=>''));

$sTitle = 'Suppression de la base de donn&eacute;es courante';
$sWarningMessage = 'Etes-vous sur de vouloir remplacer la base de donn&eacute;es par celle-ci ? Il est fortement conseill&eacute; de cr&eacute;er une sauvegarde avant une telle op&eacute;ration.';
$oUploadInputBox = new InputBox($sTitle, $sWarningMessage, array('Oui'=>'', 'Non'=>'document.forms[\'upload\'].restoreDb.checked = false;'));
$oSyncInputBox = new InputBox($sTitle, $sWarningMessage, array('Oui'=>'', 'Non'=>'document.forms[\'sync\'].restoreDb.checked = false;'));

//display available backups
$asFileList = glob(BACKUP_FOLDER.'*.'.DB_EXT_FILE);
$iFileNb = count($asFileList);
$iFilePerPage = 10;

//page switcher load
$oPageSwitcher = new PageSwitch('pageNb', $iFileNb, $iFilePerPage);

foreach($asFileList as $sFileName)
{
	//set input box variables
	$sBackUpId = encodeUrl(basename($sFileName));
	$sTimeStamp = getTimeStampFromFile($sFileName);
	$sBackUpName = date(LAYOUT_DATE_FORMAT, $sTimeStamp);
	$oRestoreInputBox->setTags(array('backUpId'=>$sBackUpId, 'backUpDate'=>$sBackUpName));
	
	$sLinkBackUp[$sTimeStamp] = '	<tr>
										<td>Le '.$sBackUpName.'</td>
										<td><input type="button" value="T&eacute;l&eacute;charger" onClick="goTo(\'?page=download&file='.$sBackUpId.'\');" /></td>
										<td><input type="button" value="Restorer cette sauvegarde" onClick="'.$oRestoreInputBox->getAction().'" /></td>		
									</tr>';
}
if(isset($sLinkBackUp))
{
	krsort($sLinkBackUp);
	$iFirstItem = $oPageSwitcher->getItemStartPointer();
	$aiFileRange = $oPageSwitcher->getItemRange();
	$sLinkBackUp = array_slice($sLinkBackUp, $iFirstItem, $iFilePerPage, true);
	$sPageSwitchInfo = $aiFileRange['start'].' - '.$aiFileRange['end'].' sur ';
}
else
{
	$sLinkBackUp = array('<tr><td colspan="3"><p>Aucune sauvegarde disponible</p><p><input type="button" value="Cr&eacute;er une sauvegarde maintenant" onClick="document.download.submit();" /></p></td></tr>');
	$sPageSwitchInfo = '';
}

//KeyRing
$sKeyRing = getKeyRing();
?>	
<fieldset class="rounded">
	<legend class="rounded">Sauvegardes disponibles</legend>
	<br />
	<form name="restore" action="?page=backUpCreator&action=restore" method="post">
		<table class="maxWidth">
			<tr>
				<th class="top-left-rounded">Date</th>
				<th>T&eacute;l&eacute;chargement</th>
				<th class="top-right-rounded">Restoration</th>
			</tr>
			<?php echo implode("\n", $sLinkBackUp); ?>
			<tr>
				<th colspan="3" class="bottom-left-rounded bottom-right-rounded"><?php echo $oPageSwitcher->getPrevLink().'&nbsp;'.$sPageSwitchInfo.$iFileNb; ?> sauvegardes <?php echo $oPageSwitcher->getNextLink(); ?></th>
			</tr>
		</table>
		<input type="hidden" name="backUpId" value="" />
	</form>
</fieldset>
<fieldset class="rounded">
	<legend class="rounded">Cr&eacute;er une sauvegarde</legend>
	<form name="download" action="?page=backUpCreator&action=download" method="post">
		<p>Sauvegarde de la base de donn&eacute;es <strong><?php echo DB_NAME; ?></strong> incluant les tables <?php echo implode(', ', getTables()); ?>.</p>
		<p>Inclure les requ&ecirc;te de suppression de la base avant r&eacute;&eacute;criture : <input type="checkbox" name="dropDb" checked="checked" /></p>
		<input type="submit" value="Lancer la sauvegarde" />
	</form>
</fieldset>
<fieldset class="rounded">
	<legend class="rounded">Ajouter une de vos sauvegardes</legend>
	<form name="upload" action="?page=backUpCreator&action=upload" method="post" enctype="multipart/form-data">
		<p>Ins&eacute;rer ici le fichier de sauvegarde (.sql) : <input type="file" name="backUpFile" /></p>
		<p>remplacer la base de donn&eacute;es actuelle par celle-ci : 
			<input type="checkbox" name="restoreDb" onchange="if(document.forms['upload'].restoreDb.checked)<?php echo $oUploadInputBox->getAction(); ?>" />
		</p>
		<input type="submit" value="Ajouter la sauvegarde" />
	</form>
</fieldset>
<fieldset class="rounded">
	<legend class="rounded">Synchroniser la base avec un point d'acc&egrave;s</legend>
	<form name="sync" action="?page=backUpCreator&action=sync" method="post">
		<p>
			Ins&eacute;rer ici l'url de sauvegarde : <input type="text" name="backUpUrl" style="width:250px;" value="<?php echo isset($_POST['backUpUrl'])?$_POST['backUpUrl']:''; ?>" />
			<select name="version">
				<option value="<?php echo ACCESS_POINT_LAST_VERSION; ?>">Derni&egrave;re version disponible</option>
				<option value="<?php echo ACCESS_POINT_NEW_VERSION; ?>">Nouvelle version</option>
				<option value="">aucune version (lien directe)</option>
			</select>
		</p>
		<p>remplacer la base de donn&eacute;es actuelle celle du point d'acc&egrave;s : <input type="checkbox" name="restoreDb" onchange="if(document.forms['sync'].restoreDb.checked)<?php echo $oSyncInputBox->getAction(); ?>" /></p>
		<p>
			Utiliser le KeyRing de cette session pour l'authentification : <input type="checkbox" name="useKeyRing" checked="checked" onclick="setKeyRingInput();" />
			<span id="authentification" style="display:none;">
				utiliser celui-ci : <input type="text" name="key_ring" style="width:300px;" />
			</span>
		</p>
		<script type="text/javascript">
			function setKeyRingInput()
			{
				var bUseKeyRing = document.forms['sync'].elements['useKeyRing'].checked;
				setBoxDisplay('authentification', bUseKeyRing?'n':'y');
			}
		</script>
		<input type="submit" value="Synchroniser" />
	</form>
</fieldset>
<fieldset class="rounded">
	<legend class="rounded">KeyRing</legend>
	<form name="keyring">
		<p class="keyring">
			<a href="#" onclick="setSelection('keyring', 'keyring');return false;"><img src="images/keyring.png" title="click pour s&eacute;lectionner la cl&eacute;" /></a>
			<textarea name="keyring" class="disabled" rows="1" onclick="setSelection('keyring', 'keyring');"><?php echo $sKeyRing; ?></textarea>
		</p>
	</form>
</fieldset>
<fieldset class="rounded">
	<legend class="rounded">R&eacute;-initialisation compl&egrave;te</legend>
	<form name="reset" action="?page=backUpCreator&action=reset" method="post">
		<p>Tout supprimer et r&eacute;initialiser l'application (aka la m&eacute;thode du bourinos) : <input type="button" value="Lancer" onclick="<?php echo $oResetInputBox->getAction(); ?>" /></p>
	</form>
</fieldset>
<?php 
echo $oRestoreInputBox->getHtml();
echo $oResetInputBox->getHtml();
echo $oUploadInputBox->getHtml();
echo $oSyncInputBox->getHtml();
?>