<?php
/**
 * /uploads/file.php
 * @version 1.0
 * @desc Output files based on tokens
 * @author Fándly Gergő Zoltán (gergo@systemtest.tk, systemtest.tk)
 * @copy 2018 Fándly Gergő Zoltán
 * License:
    Systemtest.tk website's.
    Copyright (C) 2018  Fándly Gergő Zoltán

    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 <https://www.gnu.org/licenses/>.
 **/

require_once("../config/config.php");

if(isset($_GET['token'])){
    $sql=$db->prepare("SELECT COUNT(id) AS count, id, name, extension FROM files WHERE token=:token");
    $sql->execute(array(":token"=>$_GET['token']));
    $res=$sql->fetch(PDO::FETCH_ASSOC);
    
    if($res['count']<1){
        echo "Not found";
        die();
    }
    else{
        if($res['extension']=="txt"){
            header("Content-type: text/plain");
        }
        else if($res['extension']=="js"){
            header("Content-type: text/javascript");
        }
        else if($res['extension']=="css"){
            header("Content-type: text/css");
        }
        else if($res['extension']=="html"){
            header("Content-type: text/html");
        }
        else if($res['extension']=="gif"){
            header("Content-type: image/gif");
        }
        else if($res['extension']=="png"){
            header("Content-type: image/png");
        }
        else if($res['extension']=="jpg" || $res['extension']=="jpeg"){
            header("Content-type: image/jpeg");
        }
        else if($res['extension']=="bmp"){
            header("Content-type: image/bmp");
        }
        else if($res['extension']=="pdf"){
            header("Content-type: application/pdf");
        }
        else{
            header("Content-type: application/octet-stream");
            header("Content-disposition: attachment; filename='".$res['name'].".".$res['extension']."'");
        }
        
        $path="./files/".$res['id'];
        readfile($path);
        die();
    }
}
