<?php
$inifile = __DIR__.'/../../system/data/config.php';
$config = parse_ini_file($inifile, true);

$dbDriver = $config['database']['db_driver'];
$dbHost   = $config['database']['db_host'];
$dbPort   = $config['database']['db_port'];
$dbSource = $config['database']['db_source'];
$dbUser   = $config['database']['db_user'];
$dbPasswd = $config['database']['db_password'];
$dbEnc    = $config['database']['db_encoding'];

$dsn = "mysql:dbname={$dbSource};port={$dbPort};host={$dbHost}";
$db = new PDO($dsn, $dbUser, $dbPasswd);

if (isset($_GET['filepath']) && isset($_GET['email'])) {
    $filepath = $config['global']['chroot_dir'] . '/' . ltrim($_GET['filepath'], '/');
    if (file_exists($filepath)) {
        $id = sha1($filepath . $_GET['email']);
        $md5 = md5_file($filepath);
        $sql = "INSERT INTO tms_downloader (id, path, checksum) VALUES ('$id', '$filepath', '$md5');";
        $db->query($sql);
        header("Content-type:text/plain");
        echo "https://www.plus-5.com/Download/$id";
    } else {
        echo "file not found.";
    }
    exit;
}

if (isset($_GET['rt'])) {
    $sql = "SELECT path, checksum FROM tms_downloader WHERE id='{$_GET['rt']}';";
    $stat = $db->query($sql);
    $result = $stat->fetch(PDO::FETCH_ASSOC);
    $path = $result['path'];

    if (file_exists($path)) {

        if (md5_file($path) != $result['checksum']) {
            header("HTTP/1.0 412 Precondition Failed");
            echo 'File is broken.';
            exit;
        }

        if(preg_match('/MSIE [678]/', $_SERVER['HTTP_USER_AGENT'])) {
            header('Cache-Control: public');
            header('Pragma: public');
        }
        header('Content-Type: octet-stream');
        header('Content-Length: ' . filesize($path));

        $filename = (preg_match("/([^\/\\\]+)$/", $path, $m)) ? $m[1] : $path;
        $output_filename = mb_convert_encoding($filename, 'UTF-8');
        $pattern = '/Chrome|Firefox|(Opera)|(Trident\/7\.0)|(MSIE|IEMobile)|(Safari)/';

        switch (true) {
            case !isset($_SERVER['HTTP_USER_AGENT']) :
            case !preg_match($pattern, $_SERVER['HTTP_USER_AGENT'], $matches) :
            case !isset($matches[1]) :
            case !isset($matches[2]) :
                $enc = '=?utf-8?B?' . base64_encode($output_filename) . '?=';
                header('Content-Disposition: attachment; filename="' . $enc . '"');
                break;
            case !isset($matches[3]):
                $enc = "utf-8'ja'" . urlencode($output_filename);
                header('Content-Disposition: attachment; filename*=' . $enc);
                break;
            case !isset($matches[4]):
                $enc = urlencode($output_filename);
                header('Content-Disposition: attachment; filename="' . $enc . '"');
                break;
            default:
                header('Content-Disposition: attachment; filename="' .$output_filename . '"');
        }

        readfile($path);

        mail (
            $config['global']['mail_address'],
            'Download from ' . $_SERVER['SERVER_NAME'],
            $path . PHP_EOL . PHP_EOL .
            $_SERVER['REMOTE_ADDR'] . PHP_EOL .
            $_SERVER['HTTP_USER_AGENT'] . PHP_EOL .
            date('Y-m-d H:i:s'),
            'From: no-reply@plus-5.com'
        );
    } else {
        header("HTTP/1.0 404 Not Found");
        echo 'file not found.';
    }
}
exit;
