<?php
/**
 * @package linea21.externals
 * @subpackage Class Installer
 * @author Simon Georget
 * @license GNU Lesser General Public License
 */
session_start();
$noplugin = true; // flag for ../config/define.php file

include_once("../config/define.php");
include_once('../lib/input_helpers.php');


$verbose = true;
$debug = false;

ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(E_ALL & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED);


// we update the main config.ini file
if(!is_writable ('../config/config.ini')) die("'config/config.ini' file is not writable. Please change permissions and refresh the page.");
if(!is_writable ('../config/')) die("'config/' folder is not writable. Please change permissions and refresh the page.");

$newver = format_version_number(LINEA_VERSION);
$curverfile='';

if(file_exists('../config/.curver')) {
	$curver = format_version_number(get_curver());
} else {
	$curver = $newver-10;
	$nocurverfile = "No <em>.curver</em> file found.";
}


// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Generic actions
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

if($verbose) echo '<h1>Updating Linea21 to version '. LINEA_VERSION . '</h1>';
if($nocurverfile) echo '<h2>'.$nocurverfile.' Supposed version : '.$curver.'</h2>';

// Run SQL updates
if($verbose) echo '<h3>Running SQL updates</h3>';
$sql_files = glob("../install/scripts_sql/patches/*.sql");


if($curver == $newver) exit("Seems to be up to date [Test : current version : " . $curver . " - new version : " . $newver . "].");
	


sort($sql_files, SORT_REGULAR ); // sort on name
foreach ($sql_files as $filename)	{
	$v = format_version_number(basename($filename, '.sql'));
	
	// we get only SQL files > to previous version. if curver = 160, previous 120, 130, 140, 150 will be omitted
	if($v > $curver) {
		if($verbose) echo '<span style="color:##43628E">Applying SQL patches : '. $filename. '</span><br />' ;
		// echo $v."<br >";
		sql_update($filename, $sql_object);
	}
}


		
// we run update PHP scripts
if($verbose) echo '<h3>Running PHP scripts</h3>';
$scripts = glob("../install/installer/data/update/*.php");
// sort to get the oldest first
sort($scripts, SORT_REGULAR ); // sort on name
foreach ($scripts as $filename)	{
	$v = substr(basename($filename), 0, 3); // we take the 3 first characters only to get version number
	// we get only php files > to previous version. if curver = 160, previous 120, 130, 140, 150 will be omitted
	if($v > $curver) {
		if($verbose) echo '<span style="color:#43628E">Applying update routine : '.$filename. '</span><br />' ;
		include_once($filename);
	}
}


write_curver(); // we write current version in hidden file (config/.curver)
// Final message
echo '<h2><strong>Update is done!</strong> Please go to the <a href="../admin/logout.php">admin page to log-in</a>.</h2>';
