<?php
/**
 * Permet à l'utilisateur de télécharger un fichier importé stocké en BD
 */


require_once("../../base/php/startSession.php");
require_once( "../../base/php/Functions.php" );
require_once("../../base/php//classDatabase.php");


$import_id = @$_POST["mat2a_import_id"];
if ($import_id == "") {
    $import_id = @$_GET["mat2a_import_id"];
}
$import_id = $import_id + 0;

$data_type = @$_POST["data_type"];
if ($data_type == "") {
    $data_type = @$_GET["data_type"];
}

$data_type2 = $data_type;
if ($data_type == "FCPLPP") {
    $data_type2 = "FCP";
}

$dbname = @$_POST["dbname"];
if ($dbname == "") {
    $dbname = @$_GET["dbname"];
}

$dbuser = @$_POST["dbuser"];
if ($dbuser == "") {
    $dbuser = @$_GET["dbuser"];
}

$dbpassword = @$_POST["dbpassword"];
if ($dbpassword == "") {
    $dbpassword = @$_GET["dbpassword"];
}


if ($dbname == "") {
    $database = new Database("iCTI");
}
else {
    $database = new Database("*NODEF_PG", "localhost", 5432, $dbname, $dbuser, $dbpassword);
}


$ok_import = FALSE;
$result  =  $database->exec("SELECT file_path FROM pmsi.p_mat2a_file WHERE mat2a_import_id = $import_id");
if ($result != false) {
    $record = $database->nextRecordInto();
    if ($record != FALSE) {
        $file_name = $record[0];
        $ok_import = TRUE;
    }
}

if ($ok_import == TRUE) {
    header("Pragma: public");
    header("Expires: 0");
    header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
    header("Content-Type: application/".substr($file_name,-3));
    header("Content-Disposition: attachment;filename=\"" . basename($file_name) . "\"");


    $result = $database->exec("SELECT data FROM pmsi.p_mat2a_file WHERE mat2a_import_id =$import_id");
    $ok = TRUE;
    while ($ok == TRUE) {
        $ok = FALSE;
        $record = pg_fetch_array($result);
        if ($record != FALSE) {
            $ok = TRUE;
            $data = $record[0];

            echo  uncompress(pg_unescape_bytea($data));

        }
    }

}
else {
    echo "Pas de fichier $data_type pour le rapport n° $import_id ";
}





?>
