<?php
function force_download ($data, $name, $mimetype='', $filesize=false) {

    if ($filesize == false OR !is_numeric($filesize)) {
        $filesize = strlen($data);
    }

    if (empty($mimetype)) {
        $mimetype = 'application/octet-stream';
    }

    ob_clean_all();

    header("Pragma: public"); 
    header("Expires: 0");
    header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
    header("Cache-Control: private",false);
    header("Content-Transfer-Encoding: binary");
    header("Content-Type: " . $mimetype);
    header("Content-Length: " . $filesize);
    header("Content-Disposition: attachment; filename=\"" . $name . "\";" );

    echo $data;
    die();
}

function ob_clean_all () {
    $ob_active = ob_get_length () !== false;
    while($ob_active) {
        ob_end_clean();
        $ob_active = ob_get_length () !== false;
    }

    return true;
}

$id = htmlspecialchars($_GET['id']);

include "config.php";

$ip = $_SERVER['REMOTE_ADDR'];
$dnesnidatum = StrFTime("%Y-%m-%d %H:%M:%S", Time());
$banlist = mysql_query("SELECT * FROM jtcms_banlist WHERE ip='".mysql_real_escape_string($ip)."' and druh='2' LIMIT 1");
$banlist_r = mysql_num_rows($banlist);

if ($banlist_r != 0) {
  $banlist = mysql_fetch_array($banlist);
  Header("Location: admin/error.php?error=3&ip=".rawurlencode($banlist['ip']));
  echo '<script type="text/javascript">location.replace("admin/error.php?error=3&ip='.rawurlencode($banlist['ip']).'")</script>';
};

$query = mysql_query("SELECT * FROM jtcms_soubory WHERE id='".intval($id)."' LIMIT 1");
$result = mysql_fetch_array($query);
$radku = mysql_num_rows($query);

$slozka = $result['slozka'];
$soubor = $result['nazev'];
$stazeni = $result['stazeni'];
$stazeni = $stazeni+1;

mysql_query("UPDATE jtcms_soubory SET stazeni='".$stazeni."' WHERE id='".intval($id)."' LIMIT 1");

if (!file_exists("./data/files/".$slozka."/".$soubor) or $radku != 1) {
  Header("Location: error.php?error=9");
  echo '<script type="text/javascript">location.replace("error.php?error=9")</script>';
  exit();
};



$cesta = "./data/files/".$slozka."/".$soubor;

$name = $soubor;
$mimetype = mime_content_type($cesta);
$filesize = filesize($cesta);

$fopen = fopen($cesta, "r");
$data = fread($fopen, $filesize);
fclose($fopen);

mysql_close();

force_download($data, $name, $mimetype, $filesize);
echo '<script type="text/javascript">window.close();</script>';
?>
