<?php
/**
 * x86.world customer portal — file delivery.
 *
 * Every byte a customer downloads passes through here, so the site_id
 * directories can stay where the brief wants them (under the portal) while
 * still being unreachable without a valid session. Apache is told to 404 them
 * directly; this script is the only door.
 *
 * Supports HTTP range requests, so a dropped 200MB flux image can be resumed
 * rather than restarted.
 */

define('X86_PORTAL', 1);
require __DIR__ . '/portal_lib.php';

portal_session_start();

function portal_dl_bail($code, $flash)
{
    header('Location: index.php?e=' . $flash, true, 302);
    exit;
}

$record = portal_current_record();

if ($record === null) {
    header('Location: index.php', true, 302);
    exit;
}
if (portal_is_expired($record['expiry'])) {
    portal_dl_bail(403, 'expired');
}

$siteId = $record['site_id'];

header('X-Content-Type-Options: nosniff');
header('Cache-Control: private, no-store, max-age=0');
header('Referrer-Policy: same-origin');

/* ------------------------------------------------------------------ *
 * Generated manifest
 * ------------------------------------------------------------------ */
if (isset($_GET['sums'])) {
    $files = portal_list_files($siteId);
    $body  = portal_sums_text($files);
    header('Content-Type: text/plain; charset=utf-8');
    header('Content-Disposition: attachment; filename="SHA256SUMS"');
    header('Content-Length: ' . strlen($body));
    echo $body;
    exit;
}

/* ------------------------------------------------------------------ *
 * A single file
 * ------------------------------------------------------------------ */
$name = isset($_GET['f']) ? (string)$_GET['f'] : '';
$path = portal_resolve_file($siteId, $name);

if ($path === null) {
    portal_dl_bail(404, 'notfound');
}

$size = filesize($path);
$fh   = @fopen($path, 'rb');
if ($fh === false) {
    portal_dl_bail(404, 'notfound');
}

/* Range handling: one range only, which is all any browser or wget sends. */
$start  = 0;
$end    = $size - 1;
$status = 200;

if (isset($_SERVER['HTTP_RANGE'])
    && preg_match('/^bytes=(\d*)-(\d*)$/', trim($_SERVER['HTTP_RANGE']), $m)) {

    if ($m[1] === '' && $m[2] === '') {
        /* malformed; ignore and send the whole file */
    } elseif ($m[1] === '') {
        $start = max(0, $size - (int)$m[2]);            /* bytes=-500, the tail */
    } else {
        $start = (int)$m[1];
        if ($m[2] !== '') {
            $end = min((int)$m[2], $size - 1);
        }
    }

    if ($start > $end || $start >= $size) {
        fclose($fh);
        header('HTTP/1.1 416 Range Not Satisfiable');
        header('Content-Range: bytes */' . $size);
        exit;
    }
    $status = 206;
}

$length = $end - $start + 1;

while (ob_get_level() > 0) {
    ob_end_clean();
}
@set_time_limit(0);
@ini_set('zlib.output_compression', '0');

if ($status === 206) {
    header('HTTP/1.1 206 Partial Content');
    header('Content-Range: bytes ' . $start . '-' . $end . '/' . $size);
}
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . str_replace('"', '', $name) . '"; '
     . "filename*=UTF-8''" . rawurlencode($name));
header('Content-Length: ' . $length);
header('Accept-Ranges: bytes');
header('Content-Transfer-Encoding: binary');

/* Let the session go before a long transfer, or the customer's other tabs
   will sit and wait on the session lock. */
session_write_close();

fseek($fh, $start);
$remaining = $length;
$chunk     = 262144;

while ($remaining > 0 && !feof($fh)) {
    if (connection_aborted()) {
        break;
    }
    $read = ($remaining > $chunk) ? $chunk : $remaining;
    $buf  = fread($fh, $read);
    if ($buf === false || $buf === '') {
        break;
    }
    echo $buf;
    flush();
    $remaining -= strlen($buf);
}

fclose($fh);
exit;
