<?php

// +-------------------------------------------------+
// © 2002-2004 PMB Services / www.sigb.net pmb@sigb.net et contributeurs (voir www.sigb.net)
// +-------------------------------------------------+
// $Id: restaure_act.php,v 1.13 2026/03/17 13:47:11 qvarin Exp $

//Restauration d'un jeu

require "lib/api.inc.php";

global $msg;

$critical = false;
$current_module = 'restaure';
$backups_path = '../backup/backups/';
$logid = intval($_POST["logid"] ?? 0);
$displayed_filename = '';
$filename = '';
$database = '';
$tables = [];

if ($logid) {
    $base_path = "../..";
    $base_auth = "SAUV_AUTH|ADMINISTRATION_AUTH";
    $base_title = '$msg[sauv_misc_ract_title]';

    require_once $base_path."/includes/init.inc.php";

    $requete = "SELECT sauv_log_file FROM sauv_log WHERE sauv_log_id = " . $logid;
    $resultat = pmb_mysql_query($requete) or die(pmb_mysql_error());
    $displayed_filename = pmb_mysql_result($resultat, 0, 0);
    $filename = $backups_path . basename($displayed_filename);
} else {
    $charset = 'iso-8859-1';
    require_once "emergency/messages_env_ract.inc.php";

    $base_path = "../..";
    $class_path = $base_path . "/classes";
    $includes_path = $base_path . "/includes";

    require_once $includes_path . '/mysql_functions.inc.php';

    session_start();
    if (!empty($_SESSION['emergency']) && $_SESSION['emergency']['critical']) {
        $critical = true;
        $database = $_SESSION['emergency']['database'];
        $displayed_filename = $_SESSION['emergency']['original_name'];
        $filename = $backups_path . basename($_SESSION['emergency']['filename']);
        $tables = isset($_POST["tables"]) ? $_POST["tables"] : [];
    }
}

if (
    !is_string($displayed_filename) ||
    empty(trim($displayed_filename)) ||
    !is_file($filename)
) {
    http_response_code(400);
    if ('uft-8' !== $charset) {
        $msg['sauv_misc_ract_no_sauv'] = mb_convert_encoding($msg['sauv_misc_ract_no_sauv'], 'UTF-8', $charset);
    }
    abort_critical($msg['sauv_misc_ract_no_sauv']);
    exit();
}

if ($critical) {
    require_once 'lib/database_parser.class.php';

    $databaseParser = new DatabaseParser();
    $databases = $databaseParser->parse(file_get_contents('../../includes/db_param.inc.php'));

    $database_information = $databases[$database] ?? [];
    $host = $database_information[DatabaseParser::DATABASE_HOST] ?? '';
    $db_user = $database_information[DatabaseParser::DATABASE_USER] ?? '';
    $db_password = $database_information[DatabaseParser::DATABASE_PASS] ?? '';
    $db_name = $database_information[DatabaseParser::DATABASE_NAME] ?? '';

    $dbh = pmb_mysql_connect($host, $db_user, $db_password) or abort_critical($msg["sauv_misc_ract_cant_connect"]);
    pmb_mysql_select_db($db_name, $dbh) or abort_critical(sprintf($msg["sauv_misc_ract_db_dont_exists"], $db));

    unset($database_information, $databases);
    unset($host, $db_user, $db_password, $db_name);
}

// Verification du fichier
$infos = read_infos($filename);
if (!empty($infos['error'])) {
    @unlink($filename);
    abort_critical($msg['sauv_misc_ract_no_sauv']);
    exit();
}

// Info compression/decompression
$compress = $infos['Compress'];
$compress_type = $infos['compress_type'];
if ($compress == 1 && $compress_type !== 'internal') {
    abort_critical($msg['sauv_misc_ract_invalid_compress']);
    exit();
}

// Nom du fichier temporaire
$tempfile = $backups_path . "temp_restaure";
if ($compress == 1) {
    $tempfile .= '.bz2';
} else {
    $tempfile .= ".sql";
}

// Ouverture fichier temporaire
$ftemp = fopen($tempfile, "w+") or abort_critical($msg["sauv_misc_ract_create"]);

//Ouverture fichier sauvegarde
$f = fopen($filename, "r") or abort_critical($msg["sauv_misc_ract_cant_open_file"]);

//Recuperation partie data et copie dans le fichier temporaire
$line = rtrim(fgets($f, 8192));
while ((!feof($f)) && ($line != "#data-section")) {
    $line = rtrim(fgets($f, 8192));
}

while (!feof($f)) {
    fwrite($ftemp, fread($f, 8192));
}
fclose($ftemp);
fclose($f);

//Decompression fichier temporaire vers fichier sql
$tempfiledest = $backups_path . "temp_restaure.sql";
if ($compress == 1) {
    echo "<b>".htmlentities($msg["sauv_misc_ract_decompress"], ENT_QUOTES, $charset)."</b><br />";
    flush();

    $ftempin = bzopen($tempfile, "r") or abort_critical($msg["sauv_misc_ract_not_bz2"]);
    $ftempout = fopen($tempfiledest, "w+") or abort_critical($msg["sauv_misc_ract_create"]);
    while (!feof($ftempin)) {
        $datas = bzread($ftempin, 2048);
        fwrite($ftempout, $datas);
    }

    bzclose($ftempin);
    fclose($ftempout);
    @unlink($tempfile);
}

//Application des requetes
echo "<b>".htmlentities($msg["sauv_misc_ract_restaure_tables"], ENT_QUOTES, $charset)."</b><br /><br />";

//Ouverture fichier SQL
$fsql = fopen($tempfiledest, "r") or abort_critical($msg["sauv_misc_ract_open_failed"]);

$mod_query = 0;
$currentTable = "";

while (!feof($fsql)) {
    $line = "";
    while ((substr($line, strlen($line) - 1, 1) != "\n") && (!feof($fsql))) {
        $line .= fgets($fsql, 4096);
    }
    $line = rtrim($line);
    if ($line != "") {
        if (substr($line, 0, 1) == "#") {
            if (($currentTable != "") && ($mod_query == 1)) {
                echo htmlentities(sprintf($msg["sauv_misc_ract_restaured_t"], $currentTable), ENT_QUOTES, $charset)."<br />";
                flush();
            }
            $currentTable = substr($line, 1);
            $as = array_search($currentTable, $tables);
            if ($as !== false) {
                $mod_query = 1;
                echo htmlentities(sprintf($msg["sauv_misc_ract_start_restaure"], $currentTable), ENT_QUOTES, $charset)."<br />";
            } else {
                $mod_query = 0;
                echo sprintf($msg["sauv_misc_ract_ignore"], $currentTable)."<br />";
            }
            flush();
        } elseif ($mod_query == 1) {
            pmb_mysql_query($line) or abort_critical(sprintf($msg["sauv_misc_ract_invalid_request"], $line));
        }
    }
}
fclose($fsql);
@unlink($tempfiledest);



echo "<h2>".htmlentities($msg["sauv_misc_ract_correct"], ENT_QUOTES, $charset)."</h2>";
echo "</div>";

if ($critical) {
    echo '</body></html>';
    unset($_SESSION['emergency']);
    unlink($filename);
} else {
    /**
     * Succeed - Gestion du cas particulier :
     * Dernière sauvegarde effectuée <=> sauv_log_succeed valorisé à 1 après sauvegarde
     * Lors de la restauration, on récupère la valeur 0, enregistrée avant la fin de la sauvegarde.
     */
    $requete = "update sauv_log set sauv_log_succeed=1 where sauv_log_id=".$logid;
    @pmb_mysql_query($requete);
}
