Lint / PHP (phpcs PSR-12) (push) Successful in 17s
Lint / JS (eslint) (push) Successful in 7s
Lint / PHP requirements (version + extensions) (push) Successful in 20s
Lint / Notify on failure (push) Skipped
Security / PHP Security (semgrep) (push) Successful in 1m8s
Lint / Deploy (push) Successful in 2s
The attachment grid's <img> thumbnail pointed at the same download_attachment.php URL as the full-size original, so previewing a multi-MB photo attachment cost a full multi-MB download just to render a small grid preview. loading="lazy" only deferred off-screen images; it never reduced per-image transfer size. Generate a resized JPEG thumbnail (longest side capped at 300px) via GD at upload time, from the same metadata-stripped image stripImageMetadata() already produces, reusing its decompression-bomb guard (~40MP decode cap). Store the thumbnail's filename in a new nullable ticket_attachments. thumbnail_filename column (migration 005); NULL means no thumbnail exists (non-image, GD unavailable, or an attachment predating this change) and callers fall back to the full-size original. download_attachment.php serves the thumbnail when requested via ?thumb=1 and one exists, falling back to the original otherwise. The attachments grid now requests thumb=1 for its <img> preview; the lightbox link is unchanged and still opens the full-size original. delete_attachment.php removes the thumbnail file alongside the original, and cleanup_orphan_uploads.php's orphan lookup now also matches thumbnail_filename so generated thumbnails aren't swept up as orphans. Verified against real MariaDB + GD: a 1600x1200 test JPEG produced a 300x225 thumbnail at ~1.8KB vs. the 52KB original (~29x smaller); confirmed the serving logic picks the thumbnail for image attachments with one, falls back to the original for a non-image attachment even when thumb=1 is requested, and that the updated orphan-cleanup lookup matches both the original and thumbnail filename (and correctly finds neither for an unrelated filename). Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_0117oBw2jN4kALYeS8HPq4zV
203 lines
7.0 KiB
PHP
203 lines
7.0 KiB
PHP
<?php
|
|
|
|
/**
|
|
* Download Attachment API
|
|
*
|
|
* Serves file downloads for ticket attachments
|
|
*/
|
|
|
|
require_once dirname(__DIR__) . '/helpers/ErrorHandler.php';
|
|
ErrorHandler::init();
|
|
|
|
require_once dirname(__DIR__) . '/middleware/RateLimitMiddleware.php';
|
|
RateLimitMiddleware::apply('api');
|
|
|
|
require_once dirname(__DIR__) . '/config/config.php';
|
|
require_once dirname(__DIR__) . '/helpers/Database.php';
|
|
require_once dirname(__DIR__) . '/models/AttachmentModel.php';
|
|
require_once dirname(__DIR__) . '/models/TicketModel.php';
|
|
|
|
// Check authentication
|
|
if (!isset($_SESSION['user']) || !isset($_SESSION['user']['user_id'])) {
|
|
http_response_code(401);
|
|
header('Content-Type: application/json');
|
|
echo json_encode(['success' => false, 'error' => 'Authentication required']);
|
|
exit;
|
|
}
|
|
|
|
// Get attachment ID
|
|
$attachmentId = isset($_GET['id']) ? (int)$_GET['id'] : 0;
|
|
if ($attachmentId <= 0 || (string)$attachmentId !== (string)($_GET['id'] ?? '')) {
|
|
http_response_code(400);
|
|
header('Content-Type: application/json');
|
|
echo json_encode(['success' => false, 'error' => 'Valid attachment ID is required']);
|
|
exit;
|
|
}
|
|
|
|
try {
|
|
$attachmentModel = new AttachmentModel(Database::getConnection());
|
|
|
|
// Get attachment details
|
|
$attachment = $attachmentModel->getAttachment($attachmentId);
|
|
if (!$attachment) {
|
|
http_response_code(404);
|
|
header('Content-Type: application/json');
|
|
echo json_encode(['success' => false, 'error' => 'Attachment not found']);
|
|
exit;
|
|
}
|
|
|
|
// Verify the associated ticket exists and user has access
|
|
$conn = Database::getConnection();
|
|
|
|
$ticketModel = new TicketModel($conn);
|
|
$ticket = $ticketModel->getTicketById($attachment['ticket_id']);
|
|
|
|
if (!$ticket) {
|
|
http_response_code(404);
|
|
header('Content-Type: application/json');
|
|
echo json_encode(['success' => false, 'error' => 'Associated ticket not found']);
|
|
exit;
|
|
}
|
|
|
|
// Check if user has access to this ticket based on visibility settings
|
|
if (!$ticketModel->canUserAccessTicket($ticket, $_SESSION['user'])) {
|
|
http_response_code(403);
|
|
header('Content-Type: application/json');
|
|
echo json_encode(['success' => false, 'error' => 'Access denied to this ticket']);
|
|
exit;
|
|
}
|
|
|
|
$conn->close();
|
|
|
|
// Serve the resized preview thumbnail instead of the full-size original
|
|
// when requested and one was actually generated at upload time; falls
|
|
// through to the full original otherwise (older attachments predating
|
|
// thumbnail generation, non-images, or a GD failure at upload time).
|
|
$wantsThumb = isset($_GET['thumb']) && $_GET['thumb'] === '1';
|
|
$servedFilename = $attachment['filename'];
|
|
$servedMimeType = $attachment['mime_type'];
|
|
if ($wantsThumb && !empty($attachment['thumbnail_filename'])) {
|
|
$servedFilename = $attachment['thumbnail_filename'];
|
|
$servedMimeType = 'image/jpeg';
|
|
}
|
|
|
|
// Build file path
|
|
$uploadDir = $GLOBALS['config']['UPLOAD_DIR'] ?? dirname(__DIR__) . '/uploads';
|
|
$filePath = $uploadDir . '/' . $attachment['ticket_id'] . '/' . $servedFilename;
|
|
|
|
// Security: Verify the resolved path is within the uploads directory (prevent path traversal)
|
|
$realUploadDir = realpath($uploadDir);
|
|
$realFilePath = realpath($filePath);
|
|
|
|
if ($realFilePath === false || $realUploadDir === false || strpos($realFilePath, $realUploadDir . DIRECTORY_SEPARATOR) !== 0) {
|
|
http_response_code(403);
|
|
header('Content-Type: application/json');
|
|
echo json_encode(['success' => false, 'error' => 'Access denied']);
|
|
exit;
|
|
}
|
|
|
|
// Check if file exists
|
|
if (!file_exists($realFilePath)) {
|
|
http_response_code(404);
|
|
header('Content-Type: application/json');
|
|
echo json_encode(['success' => false, 'error' => 'File not found on server']);
|
|
exit;
|
|
}
|
|
|
|
// Use the validated real path
|
|
$filePath = $realFilePath;
|
|
|
|
// Determine if we should display inline or force download
|
|
$inline = isset($_GET['inline']) && $_GET['inline'] === '1';
|
|
$inlineTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp', 'application/pdf', 'text/plain'];
|
|
|
|
// Set headers
|
|
$disposition = ($inline && in_array($servedMimeType, $inlineTypes)) ? 'inline' : 'attachment';
|
|
|
|
// Sanitize filename for Content-Disposition
|
|
$safeFilename = preg_replace('/[^\w\s\-\.]/', '_', $attachment['original_filename']);
|
|
|
|
$fileSize = filesize($filePath);
|
|
|
|
// Parse a single-range "Range: bytes=start-end" request header (RFC 7233).
|
|
// Multi-range requests aren't supported; they fall through to a full 200 response.
|
|
$rangeStart = 0;
|
|
$rangeEnd = $fileSize - 1;
|
|
$isRangeRequest = false;
|
|
|
|
if (isset($_SERVER['HTTP_RANGE']) && preg_match('/^bytes=(\d*)-(\d*)$/', trim($_SERVER['HTTP_RANGE']), $m)) {
|
|
if ($m[1] === '' && $m[2] === '') {
|
|
// Malformed ("bytes=-") — ignore and serve the full file.
|
|
} elseif ($m[1] === '') {
|
|
// Suffix range: last N bytes
|
|
$suffixLength = (int)$m[2];
|
|
$rangeStart = max(0, $fileSize - $suffixLength);
|
|
$rangeEnd = $fileSize - 1;
|
|
$isRangeRequest = true;
|
|
} else {
|
|
$rangeStart = (int)$m[1];
|
|
$rangeEnd = ($m[2] === '') ? $fileSize - 1 : min((int)$m[2], $fileSize - 1);
|
|
$isRangeRequest = true;
|
|
}
|
|
|
|
if ($isRangeRequest && ($rangeStart > $rangeEnd || $rangeStart >= $fileSize)) {
|
|
http_response_code(416);
|
|
header('Content-Range: bytes */' . $fileSize);
|
|
exit;
|
|
}
|
|
}
|
|
|
|
$rangeLength = $rangeEnd - $rangeStart + 1;
|
|
|
|
header('Accept-Ranges: bytes');
|
|
header('Content-Type: ' . $servedMimeType);
|
|
header('Content-Disposition: ' . $disposition . '; filename="' . $safeFilename . '"');
|
|
header('Cache-Control: private, max-age=3600');
|
|
header('X-Content-Type-Options: nosniff');
|
|
|
|
if ($isRangeRequest) {
|
|
http_response_code(206);
|
|
header('Content-Range: bytes ' . $rangeStart . '-' . $rangeEnd . '/' . $fileSize);
|
|
}
|
|
header('Content-Length: ' . $rangeLength);
|
|
|
|
// Prevent PHP from timing out on large files
|
|
set_time_limit(0);
|
|
|
|
// Clear output buffer
|
|
if (ob_get_level()) {
|
|
ob_end_clean();
|
|
}
|
|
|
|
// Stream file
|
|
$handle = fopen($filePath, 'rb');
|
|
if ($handle === false) {
|
|
http_response_code(500);
|
|
header('Content-Type: application/json');
|
|
echo json_encode(['success' => false, 'error' => 'Failed to open file']);
|
|
exit;
|
|
}
|
|
|
|
fseek($handle, $rangeStart);
|
|
$remaining = $rangeLength;
|
|
$chunkSize = 8192;
|
|
while ($remaining > 0 && !feof($handle)) {
|
|
$read = ($remaining < $chunkSize) ? $remaining : $chunkSize;
|
|
$data = fread($handle, $read);
|
|
if ($data === false) {
|
|
break;
|
|
}
|
|
echo $data;
|
|
flush();
|
|
$remaining -= strlen($data);
|
|
}
|
|
|
|
fclose($handle);
|
|
exit;
|
|
} catch (Exception $e) {
|
|
http_response_code(500);
|
|
header('Content-Type: application/json');
|
|
echo json_encode(['success' => false, 'error' => 'Failed to download attachment']);
|
|
exit;
|
|
}
|