Files
4WDCSA.co.za/src/processors/blog/autosave.php

92 lines
2.7 KiB
PHP

<?php
$rootPath = dirname(dirname(dirname(__DIR__)));
require_once($rootPath . "/src/config/env.php");
require_once($rootPath . "/src/config/connection.php");
require_once($rootPath . "/src/config/functions.php");
session_start();
if (!isset($_SESSION['user_id'])) {
http_response_code(401);
echo "Not authorized";
exit;
}
$article_id = (int)($_POST['id'] ?? 0);
$title = $_POST['title'] ?? '';
$content = $_POST['content'] ?? '';
$description = $_POST['subtitle'] ?? '';
$category = $_POST['category'] ?? '';
$user_id = $_SESSION['user_id'];
// Default to current user
$author_id = $_SESSION['user_id'];
// Allow override if admin
$role = getUserRole();
if (($role === 'admin' || $role === 'superadmin') && isset($_POST['author'])) {
$author_id = (int)$_POST['author'];
}
echo $author_id;
$cover_image_path = null;
// Only attempt upload if a file was submitted
if (!empty($_FILES['cover_image']['name'])) {
$uploadDir = $rootPath . "/uploads/blogs/" . $article_id . "/";
if (!is_dir($uploadDir)) {
mkdir($uploadDir, 0755, true);
}
// Validate file using existing function
$file_result = validateFileUpload($_FILES['cover_image'], 'profile_picture');
if ($file_result === false) {
http_response_code(400);
echo "Invalid file upload";
exit;
}
// Use fixed filename "cover" to avoid creating multiple copies on autosave
$extension = $file_result['extension'];
$filename = "cover." . $extension;
// Delete old cover if it exists with different extension
array_map('unlink', glob($uploadDir . "cover.*"));
$targetPath = $uploadDir . $filename;
$cover_image_path = "/uploads/blogs/" . $article_id . "/" . $filename;
// Move the uploaded file
if (move_uploaded_file($_FILES['cover_image']['tmp_name'], $targetPath)) {
// File moved successfully, $cover_image_path is set
} else {
http_response_code(500);
echo "Failed to move uploaded file.";
exit;
}
}
// Prepare SQL with/without image update
if ($cover_image_path) {
$stmt = $conn->prepare("
UPDATE blogs
SET title = ?, content = ?, description = ?, category = ?, image = ?, author = ?
WHERE blog_id = ?
");
$stmt->bind_param("ssssssi", $title, $content, $description, $category, $cover_image_path, $author_id, $article_id);
} else {
$stmt = $conn->prepare("
UPDATE blogs
SET title = ?, content = ?, description = ?, category = ?, author = ?
WHERE blog_id = ?
");
$stmt->bind_param("ssssii", $title, $content, $description, $category, $author_id, $article_id);
}
if ($stmt->execute()) {
echo "Saved";
} else {
http_response_code(500);
echo "Database update failed: " . $stmt->error;
}