Files
bookmarkly2/api/upload_tab_background.php
2025-09-28 16:05:53 +02:00

97 lines
3.1 KiB
PHP

<?php
require_once '../include/init.php';
require_once '../include/auth.php';
// --- Security Check: Only Admin can access this page ---
if (!isAdmin()) {
header('Content-Type: application/json');
http_response_code(403); // Forbidden
echo json_encode(['success' => false, 'message' => 'You do not have permission to perform this action.']);
exit;
}
header('Content-Type: application/json');
$response = [
'success' => false,
'message' => 'An unknown error occurred.',
'path' => null
];
$uploadDir = '../data/images/backgrounds/';
// Create directory if it doesn't exist
if (!is_dir($uploadDir)) {
if (!mkdir($uploadDir, 0755, true)) {
http_response_code(500);
$response['message'] = 'Failed to create upload directory.';
echo json_encode($response);
exit;
}
}
if (isset($_FILES['background']) && $_FILES['background']['error'] === UPLOAD_ERR_OK) {
$file = $_FILES['background'];
$tabId = isset($_POST['tab_id']) ? intval($_POST['tab_id']) : 0;
// --- Validation ---
// Size check (e.g., 5MB limit)
if ($file['size'] > 5 * 1024 * 1024) {
http_response_code(400);
$response['message'] = 'File is too large. Maximum size is 5MB.';
echo json_encode($response);
exit;
}
// Type check
$allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
$fileInfo = finfo_open(FILEINFO_MIME_TYPE);
$mimeType = finfo_file($fileInfo, $file['tmp_name']);
finfo_close($fileInfo);
if (!in_array($mimeType, $allowedTypes)) {
http_response_code(400);
$response['message'] = 'Invalid file type. Only JPG, PNG, GIF, and WEBP are allowed.';
echo json_encode($response);
exit;
}
// --- File Processing ---
// Find and delete any existing background for this tab
$existing_files = glob($uploadDir . 'tab_' . $tabId . '.*');
foreach ($existing_files as $file_to_delete) {
unlink($file_to_delete);
}
$extension = pathinfo($file['name'], PATHINFO_EXTENSION);
$fileName = 'tab_' . $tabId . '.' . $extension;
$destination = $uploadDir . $fileName;
if (move_uploaded_file($file['tmp_name'], $destination)) {
$response['success'] = true;
$response['message'] = 'File uploaded successfully.';
// Return the path relative to the project root with a cache-busting query string
$response['path'] = 'data/images/backgrounds/' . $fileName . '?v=' . time();
} else {
http_response_code(500);
$response['message'] = 'Failed to move uploaded file.';
}
} else {
http_response_code(400);
switch ($_FILES['background']['error'] ?? UPLOAD_ERR_NO_FILE) {
case UPLOAD_ERR_INI_SIZE:
case UPLOAD_ERR_FORM_SIZE:
$response['message'] = 'File is too large.';
break;
case UPLOAD_ERR_NO_FILE:
$response['message'] = 'No file was uploaded.';
break;
default:
$response['message'] = 'An error occurred during upload.';
break;
}
}
echo json_encode($response);