<?php
/* Copyright (C) 2016      Garcia MICHEL <garcia@soamichel.fr>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

if(false === (@include '../../main.inc.php')){ // From htdocs directory
  if(false === (@include '../../../main.inc.php')) // From "custom" directory
		die('Failed to include main.inc.php');
}

if(!$conf->autoupgrade->enabled or !$user->admin) accessforbidden();

require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php';
require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php';
dol_include_once('/autoupgrade/class/autoupgrade.class.php');

/*
 * Action
 */
$action = GETPOST('action');
$version = GETPOST('version');
$sortfield = GETPOST('sortfield');
$sortorder = GETPOST('sortorder');
$urlfile = GETPOST('urlfile');

if($action == 'confirm_upgrade' and !empty($version)){
	$obj = new AutoUpgrade($db, $langs);
	try{
		$obj->backUp();

		header('Location: '.$_SERVER["PHP_SELF"].'?action=upgrade_step1&version='.$version);
		exit;
	}catch(Exception $e){
		setEventMessage($e->getMessage(), "errors");

		header('Location: '.$_SERVER["PHP_SELF"]);
		exit;
	}
}elseif($action == 'upgrade_step1' and !empty($version)){
	$obj = new AutoUpgrade($db, $langs);
	try{
		$obj->upgradeTo($version);

		if(file_exists(DOL_DATA_ROOT.'/install.lock')) @unlink(DOL_DATA_ROOT.'/install.lock');
		header('Location: '.DOL_URL_ROOT.'/install');
		exit;
	}catch(Exception $e){
		setEventMessage($e->getMessage(), "errors");

		header('Location: '.$_SERVER["PHP_SELF"]);
		exit;
	}
}elseif($action == 'checkUpgrade'){
	$obj = new AutoUpgrade($db, $langs);
	try{
		$versions = $obj->checkNewVersions(intval($conf->global->AUTOUPGRADE_SHOWUNSTABLE), true);
		if($versions)
			setEventMessage($langs->trans("UpgradeAvailable"));
	}catch(Exception $e){
		setEventMessage($e->getMessage(), "errors");
	}

	header('Location: '.$_SERVER["PHP_SELF"]);
	exit;
}elseif($action == 'addLockfile'){
	file_put_contents(DOL_DATA_ROOT.'/install.lock', '');
	header('Location: '.$_SERVER["PHP_SELF"]);
	exit;
}elseif($action == 'confirm_delete'){
	@unlink(DOL_DATA_ROOT.'/autoupgrade/'.$urlfile);

	header('Location: '.$_SERVER["PHP_SELF"]);
	exit;
}elseif($action == 'showunstable'){
	dolibarr_set_const($db, "AUTOUPGRADE_SHOWUNSTABLE", GETPOST('value', 'alpha'), 'chaine', 0, '', $conf->entity);

	header('Location: '.$_SERVER["PHP_SELF"]);
	exit;
}elseif($action == 'set_scripts_path'){
  dolibarr_set_const($db, "AUTOUPGRADE_SCRIPTS_DIR", GETPOST('path', 'alpha'), 'chaine', 0, '', $conf->entity);

  header('Location: '.$_SERVER["PHP_SELF"]);
	exit;
}

/*
 * View
 */
$langs->load('admin');
$langs->load('autoupgrade@autoupgrade');

$form = new Form($db);
$formfile = new FormFile($db);

llxHeader('',$langs->trans("AutoUpgradeDoli"));

$linkback='<a href="'.DOL_URL_ROOT.'/admin/modules.php">'.$langs->trans("BackToModuleList").'</a>';
print_fiche_titre($langs->trans("AutoUpgradeDoli"),$linkback,'autoupgrade@autoupgrade');

print '<table class="noborder" width="100%">';
print '<tr class="liste_titre">';
print '  <td width="300">'.$langs->trans("Version").'</td>';
print '  <td>'.$langs->trans("Value").'</td>';
print '</tr>';

$var=false;
print '<tr '.$bc[$var].'>';
print '  <td>'.$langs->trans("VersionLastInstall").'</td>';
print '  <td>'.$conf->global->MAIN_VERSION_LAST_INSTALL.'</td>';
print '</tr>';

$var=!$var;
print '<tr '.$bc[$var].'>';
print '  <td>'.$langs->trans("VersionLastUpgrade").'</td>';
print '  <td>'.$conf->global->MAIN_VERSION_LAST_UPGRADE.'</td>';
print '</tr>';

$var=!$var;
print '<tr '.$bc[$var].'>';
print '  <td>'.$langs->trans("VersionProgram").'</td>';
print '  <td>'.DOL_VERSION.'</td>';
print '</tr>';

$var=!$var;
print '<tr '.$bc[$var].'>';
print '	<td>'.$langs->trans("ShowUnStableVersions").'</td>';
if(intval($conf->global->AUTOUPGRADE_SHOWUNSTABLE)){
	print '<td><a href="'.$_SERVER["PHP_SELF"].'?action=showunstable&value=0">'.img_picto($langs->trans("Activated"),'switch_on').'</a></td>';
}else{
	print '<td><a href="'.$_SERVER["PHP_SELF"].'?action=showunstable&value=1">'.img_picto($langs->trans("Disabled"),'switch_off').'</a></td>';
}
print '</tr>';

$var=!$var;
print '<tr '.$bc[$var].'>';
print ' <td>'.$langs->trans("AbsolutePathToScriptsDir").'</td>';
print ' <td>';
print ' <form action="'.$_SERVER['PHP_SELF'].'">';
print '   <input type="text" name="path" value="'.$conf->global->AUTOUPGRADE_SCRIPTS_DIR.'">';
print '   <button name="action" value="set_scripts_path">'.$langs->trans('Modify').'</button>';
print ' </form>';
print ' </td>';
print '</tr>';

print '</table><br>';

$obj = new AutoUpgrade($db, $langs);
try{
	$versions = $obj->checkNewVersions(intval($conf->global->AUTOUPGRADE_SHOWUNSTABLE));
}catch(Exception $e){
	setEventMessage($e->getMessage(), "errors");
}

if(isset($versions) and $versions){
	print info_admin($langs->trans("WarningAutoUpgrade"));

	print '<table class="noborder" width="100%">';
	print '<tr class="liste_titre">';
	print '  <td width="300">'.$langs->trans("UpgradeAvailable").'</td>';
	print '</tr>';

	$var=true;
	foreach($versions as $v){
		$var=!$var;
		print '<tr '.$bc[$var].'>';
		print '  <td style="padding: 10px;"><a href="'.$_SERVER["PHP_SELF"].'?action=upgrade&version='.$v.'" class="butAction">'.$langs->trans("UpgradeTo").' '.$v.'</a></td>';
		print '</tr>';
	}

	print '</table><br>';
}else{
	print info_admin($langs->trans("VersionLastInstalled"));
}
// force check upgrade
print '<div><a href="'.$_SERVER["PHP_SELF"].'?action=checkUpgrade" class="butAction">'.$langs->trans("CheckUpgrade").'</a></div><br>';

if($user->admin and empty($conf->global->MAIN_REMOVE_INSTALL_WARNING)){
	$lockfile = DOL_DATA_ROOT.'/install.lock';
	if(!file_exists($lockfile)){
		$langs->load("errors");
		print info_admin($langs->trans("WarningLockFileDoesNotExists", DOL_DATA_ROOT).' '.$langs->trans("WarningUntilDirRemoved", DOL_DOCUMENT_ROOT."/install"));
		print '<div><a href="'.$_SERVER["PHP_SELF"].'?action=addLockfile" class="butAction">'.$langs->trans("FixWarning").'</a></div><br>';
	}
}

$logFiles = dol_dir_list(DOL_DATA_ROOT.'/autoupgrade/logs', 'files', 0, '', '', $sortfield, (strtolower($sortorder)=='asc'?SORT_ASC:SORT_DESC), 1);
$formfile->list_of_documents($logFiles, null, 'autoupgrade', '', 1, 'logs/', 1, 0, '', 0, $langs->trans("LogFiles"));

print '<br>';

$backupFiles = dol_dir_list(DOL_DATA_ROOT.'/autoupgrade/backups', 'files', 0, '', '', $sortfield, (strtolower($sortorder)=='asc'?SORT_ASC:SORT_DESC), 1);
$formfile->list_of_documents($backupFiles, null, 'autoupgrade', '', 1, 'backups/', 1, 0, '', 0, $langs->trans("BackUpFiles"));

/*
 * Confirm
 */
if($action == 'upgrade'){
	print $form->formconfirm($_SERVER["PHP_SELF"] . '?version='.$version, $langs->trans('UpgradeTo').' '.$version, $langs->trans('ConfirmUpgrade', $version), 'confirm_upgrade', '', 0, 1);
}elseif($action == 'delete'){
	print $form->formconfirm($_SERVER["PHP_SELF"] . '?urlfile='.$urlfile, $langs->trans('DeleteFile'), $langs->trans('ConfirmDeleteFile', basename($urlfile)), 'confirm_delete', '', 0, 1);
}

llxFooter();
?>
