Files
2026-09-16 23:20:08 +07:00

84 lines
2.5 KiB
PHP

<?php
// api/delete_file.php - Delete file from Google Drive via Apps Script Web App
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
require_once __DIR__ . '/../config/db.php';
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
echo json_encode(['status' => 'error', 'message' => 'Invalid request method']);
exit;
}
$input = json_decode(file_get_contents('php://input'), true);
if (!$input) {
$input = $_POST;
}
$url = $input['url'] ?? '';
if (empty($url)) {
echo json_encode(['status' => 'error', 'message' => 'Missing Google Drive File URL']);
exit;
}
// Extract file ID from Google Drive URL
// Typically: https://drive.google.com/file/d/1XyZ.../view?usp=drivesdk
preg_match('/\/d\/([a-zA-Z0-9_-]+)/', $url, $matches);
if (empty($matches[1])) {
echo json_encode(['status' => 'error', 'message' => 'Invalid Google Drive URL format']);
exit;
}
$fileId = $matches[1];
try {
$dbInfo = getDbConnection();
$pdo = $dbInfo['pdo'];
// Get GAS URL from system settings
$settingsStmt = $pdo->query("SELECT setting_value FROM system_settings WHERE setting_key = 'gdrive_gas_url'");
$gasUrlRow = $settingsStmt->fetch();
$gasUrl = $gasUrlRow ? $gasUrlRow['setting_value'] : '';
if (empty($gasUrl)) {
echo json_encode(['status' => 'error', 'message' => 'Super Admin ยังไม่ได้ตั้งค่า Google Apps Script Web App URL']);
exit;
}
$payload = json_encode([
'action' => 'delete',
'fileId' => $fileId
]);
// Send to GAS via cURL
$ch = curl_init($gasUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // GAS requires follow location for redirects
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); // Fix HTTP/2 PROTOCOL_ERROR
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json'
]);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if(curl_errno($ch)) {
throw new \Exception(curl_error($ch));
}
curl_close($ch);
$resData = json_decode($response, true);
if (!$resData) {
throw new \Exception("Invalid JSON response from GAS: " . $response);
}
echo json_encode($resData);
} catch (\Exception $e) {
echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
exit;
}