Initial commit

This commit is contained in:
Porawit Dongwang
2026-09-16 23:20:08 +07:00
commit 0041668dbb
32577 changed files with 3687927 additions and 0 deletions
@@ -0,0 +1,141 @@
<?php
// api/admin_settings.php - Super Admin Management API for Agencies, Passwords, and System Settings
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/logger.php';
try {
$dbInfo = getDbConnection();
$pdo = $dbInfo['pdo'];
$method = $_SERVER['REQUEST_METHOD'];
if ($method === 'GET') {
// Fetch all agencies including password
$agenciesStmt = $pdo->query("SELECT id, name, code, COALESCE(admin_password, '1234') AS admin_password FROM agencies ORDER BY id ASC");
$agencies = $agenciesStmt->fetchAll();
// Fetch all system settings
$settingsStmt = $pdo->query("SELECT setting_key, setting_value FROM system_settings");
$rawSettings = $settingsStmt->fetchAll();
$settings = [];
foreach ($rawSettings as $row) {
$settings[$row['setting_key']] = $row['setting_value'];
}
echo json_encode([
'status' => 'success',
'agencies' => $agencies,
'settings' => $settings
], JSON_UNESCAPED_UNICODE);
exit;
}
if ($method === 'POST') {
$input = json_decode(file_get_contents('php://input'), true);
if (!$input) {
$input = $_POST;
}
$action = $input['action'] ?? '';
if ($action === 'save_agency') {
$id = strtoupper(trim($input['id'] ?? ''));
$name = trim($input['name'] ?? '');
$code = strtoupper(trim($input['code'] ?? ''));
$password = trim($input['password'] ?? '1234');
$isEdit = !empty($input['is_edit']);
if (empty($id) || empty($name) || empty($code)) {
echo json_encode(['status' => 'error', 'message' => 'กรุณากรอกรหัสหน่วยงาน ชื่อกลุ่มงาน และอักษรย่อให้ครบถ้วน']);
exit;
}
if ($isEdit) {
$stmt = $pdo->prepare("UPDATE agencies SET name = ?, code = ?, admin_password = ? WHERE id = ?");
$stmt->execute([$name, $code, $password, $id]);
$msg = 'บันทึกการแก้ไขหน่วยงานเรียบร้อยแล้ว';
} else {
// Check if duplicate ID
$chk = $pdo->prepare("SELECT COUNT(*) AS cnt FROM agencies WHERE id = ?");
$chk->execute([$id]);
if ($chk->fetch()['cnt'] > 0) {
echo json_encode(['status' => 'error', 'message' => "รหัสหน่วยงาน '{$id}' มีอยู่ในระบบแล้ว"]);
exit;
}
$stmt = $pdo->prepare("INSERT INTO agencies (id, name, code, admin_password) VALUES (?, ?, ?, ?)");
$stmt->execute([$id, $name, $code, $password]);
$msg = 'สร้างหน่วยงานใหม่เรียบร้อยแล้ว';
}
$actionUserId = $input['action_user_id'] ?? 'SUPER_ADMIN';
$actionUserName = $input['action_user_name'] ?? 'ผู้ดูแลระบบ';
logActivity($pdo, $actionUserId, $actionUserName, 'SAVE_AGENCY', ['agency_id' => $id, 'name' => $name, 'code' => $code, 'is_edit' => $isEdit]);
echo json_encode(['status' => 'success', 'message' => $msg], JSON_UNESCAPED_UNICODE);
exit;
}
if ($action === 'delete_agency') {
$id = trim($input['id'] ?? '');
if (empty($id)) {
echo json_encode(['status' => 'error', 'message' => 'ไม่พบรหัสหน่วยงาน']);
exit;
}
// Check if news exist for this agency
$chk = $pdo->prepare("SELECT COUNT(*) AS cnt FROM news WHERE agency_id = ?");
$chk->execute([$id]);
if ($chk->fetch()['cnt'] > 0) {
echo json_encode(['status' => 'error', 'message' => 'ไม่สามารถลบหน่วยงานนี้ได้เนื่องจากมีหนังสือเวียนของหน่วยงานนี้อยู่ในระบบ']);
exit;
}
$stmt = $pdo->prepare("DELETE FROM agencies WHERE id = ?");
$stmt->execute([$id]);
$actionUserId = $input['action_user_id'] ?? 'SUPER_ADMIN';
$actionUserName = $input['action_user_name'] ?? 'ผู้ดูแลระบบ';
logActivity($pdo, $actionUserId, $actionUserName, 'DELETE_AGENCY', ['agency_id' => $id]);
echo json_encode(['status' => 'success', 'message' => 'ลบหน่วยงานออกจากระบบเรียบร้อยแล้ว'], JSON_UNESCAPED_UNICODE);
exit;
}
if ($action === 'save_settings') {
$validKeys = [
'hospital_name',
'system_title',
'hospital_logo_url',
'ticker_text',
'super_admin_password',
'gdrive_gas_url',
'footer_text'
];
$sql = "REPLACE INTO system_settings (setting_key, setting_value) VALUES (?, ?)";
$stmt = $pdo->prepare($sql);
foreach ($validKeys as $key) {
if (isset($input[$key])) {
$stmt->execute([$key, trim($input[$key])]);
}
}
$actionUserId = $input['action_user_id'] ?? 'SUPER_ADMIN';
$actionUserName = $input['action_user_name'] ?? 'ผู้ดูแลระบบ';
logActivity($pdo, $actionUserId, $actionUserName, 'SAVE_SETTINGS', ['updated_keys' => array_keys($input)]);
echo json_encode(['status' => 'success', 'message' => 'บันทึกการตั้งค่าระบบเรียบร้อยแล้ว'], JSON_UNESCAPED_UNICODE);
exit;
}
}
echo json_encode(['status' => 'error', 'message' => 'Invalid action']);
} catch (\Exception $e) {
echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
}
?>
@@ -0,0 +1,117 @@
<?php
// api/agency_actions.php - Handle CRUD for agencies
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/logger.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;
}
$action = $input['action'] ?? '';
if (empty($action)) {
echo json_encode(['status' => 'error', 'message' => 'Missing action']);
exit;
}
try {
$dbInfo = getDbConnection();
$pdo = $dbInfo['pdo'];
if ($action === 'add_agency') {
$id = strtoupper(trim($input['id'] ?? ''));
$name = trim($input['name'] ?? '');
$code = strtoupper(trim($input['code'] ?? ''));
$password = trim($input['password'] ?? '1234');
$gdriveFolderId = trim($input['gdriveFolderId'] ?? '');
if(empty($id) || empty($name) || empty($code)) {
echo json_encode(['status' => 'error', 'message' => 'Missing required fields']);
exit;
}
// Check if ID exists
$checkStmt = $pdo->prepare("SELECT id FROM agencies WHERE id = ?");
$checkStmt->execute([$id]);
if ($checkStmt->fetch()) {
echo json_encode(['status' => 'error', 'message' => 'รหัสหน่วยงานนี้มีอยู่ในระบบแล้ว']);
exit;
}
$stmt = $pdo->prepare("INSERT INTO agencies (id, name, code, admin_password, gdrive_folder_id) VALUES (?, ?, ?, ?, ?)");
$stmt->execute([$id, $name, $code, $password, $gdriveFolderId ?: null]);
$actionUserId = $input['action_user_id'] ?? 'SUPER_ADMIN';
$actionUserName = $input['action_user_name'] ?? 'ผู้ดูแลระบบ';
logActivity($pdo, $actionUserId, $actionUserName, 'ADD_AGENCY', ['agency_id' => $id, 'name' => $name, 'code' => $code]);
echo json_encode(['status' => 'success', 'message' => 'เพิ่มหน่วยงานเรียบร้อยแล้ว']);
}
elseif ($action === 'edit_agency') {
$id = strtoupper(trim($input['id'] ?? ''));
$name = trim($input['name'] ?? '');
$code = strtoupper(trim($input['code'] ?? ''));
$password = trim($input['password'] ?? '');
$gdriveFolderId = trim($input['gdriveFolderId'] ?? '');
if(empty($id) || empty($name) || empty($code)) {
echo json_encode(['status' => 'error', 'message' => 'Missing required fields']);
exit;
}
if (empty($password)) {
$stmt = $pdo->prepare("UPDATE agencies SET name = ?, code = ?, gdrive_folder_id = ? WHERE id = ?");
$stmt->execute([$name, $code, $gdriveFolderId ?: null, $id]);
} else {
$stmt = $pdo->prepare("UPDATE agencies SET name = ?, code = ?, admin_password = ?, gdrive_folder_id = ? WHERE id = ?");
$stmt->execute([$name, $code, $password, $gdriveFolderId ?: null, $id]);
}
$actionUserId = $input['action_user_id'] ?? 'SUPER_ADMIN';
$actionUserName = $input['action_user_name'] ?? 'ผู้ดูแลระบบ';
logActivity($pdo, $actionUserId, $actionUserName, 'EDIT_AGENCY', ['agency_id' => $id, 'name' => $name, 'code' => $code]);
echo json_encode(['status' => 'success', 'message' => 'แก้ไขข้อมูลหน่วยงานเรียบร้อยแล้ว']);
}
elseif ($action === 'delete_agency') {
$id = strtoupper(trim($input['id'] ?? ''));
if(empty($id)) {
echo json_encode(['status' => 'error', 'message' => 'Missing agency ID']);
exit;
}
$stmt = $pdo->prepare("DELETE FROM agencies WHERE id = ?");
$stmt->execute([$id]);
$actionUserId = $input['action_user_id'] ?? 'SUPER_ADMIN';
$actionUserName = $input['action_user_name'] ?? 'ผู้ดูแลระบบ';
logActivity($pdo, $actionUserId, $actionUserName, 'DELETE_AGENCY', ['agency_id' => $id]);
echo json_encode(['status' => 'success', 'message' => 'ลบหน่วยงานเรียบร้อยแล้ว']);
}
elseif ($action === 'reset_password') {
$id = strtoupper(trim($input['id'] ?? ''));
if(empty($id)) {
echo json_encode(['status' => 'error', 'message' => 'Missing agency ID']);
exit;
}
$stmt = $pdo->prepare("UPDATE agencies SET admin_password = '1234' WHERE id = ?");
$stmt->execute([$id]);
echo json_encode(['status' => 'success', 'message' => 'รีเซ็ตรหัสผ่านเป็น 1234 เรียบร้อยแล้ว']);
}
else {
echo json_encode(['status' => 'error', 'message' => 'Invalid action']);
}
} catch (\Exception $e) {
echo json_encode(['status' => 'error', 'message' => 'Database Error: ' . $e->getMessage()]);
}
?>
@@ -0,0 +1,87 @@
<?php
// api/category_actions.php - Handle CRUD for categories
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/logger.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;
}
$action = $input['action'] ?? '';
if (empty($action)) {
echo json_encode(['status' => 'error', 'message' => 'Missing action']);
exit;
}
try {
$dbInfo = getDbConnection();
$pdo = $dbInfo['pdo'];
if ($action === 'add_category') {
$id = $input['id'] ?? '';
$name = $input['name'] ?? '';
$agencyId = $input['agencyId'] ?? 'SUPER_ADMIN';
if(empty($id) || empty($name)) {
echo json_encode(['status' => 'error', 'message' => 'Missing category ID or name']);
exit;
}
$stmt = $pdo->prepare("INSERT INTO categories (id, name, agency_id) VALUES (?, ?, ?)");
$stmt->execute([$id, $name, $agencyId]);
$actionUserId = $input['action_user_id'] ?? 'SYSTEM';
$actionUserName = $input['action_user_name'] ?? 'SYSTEM';
logActivity($pdo, $actionUserId, $actionUserName, 'ADD_CATEGORY', ['category_id' => $id, 'name' => $name]);
echo json_encode(['status' => 'success', 'message' => 'เพิ่มหมวดหมู่เรียบร้อยแล้ว']);
}
elseif ($action === 'edit_category') {
$id = $input['id'] ?? '';
$name = $input['name'] ?? '';
if(empty($id) || empty($name)) {
echo json_encode(['status' => 'error', 'message' => 'Missing category ID or name']);
exit;
}
$stmt = $pdo->prepare("UPDATE categories SET name = ? WHERE id = ?");
$stmt->execute([$name, $id]);
$actionUserId = $input['action_user_id'] ?? 'SYSTEM';
$actionUserName = $input['action_user_name'] ?? 'SYSTEM';
logActivity($pdo, $actionUserId, $actionUserName, 'EDIT_CATEGORY', ['category_id' => $id, 'name' => $name]);
echo json_encode(['status' => 'success', 'message' => 'แก้ไขหมวดหมู่เรียบร้อยแล้ว']);
}
elseif ($action === 'delete_category') {
$id = $input['id'] ?? '';
if(empty($id)) {
echo json_encode(['status' => 'error', 'message' => 'Missing category ID']);
exit;
}
$stmt = $pdo->prepare("DELETE FROM categories WHERE id = ?");
$stmt->execute([$id]);
$actionUserId = $input['action_user_id'] ?? 'SYSTEM';
$actionUserName = $input['action_user_name'] ?? 'SYSTEM';
logActivity($pdo, $actionUserId, $actionUserName, 'DELETE_CATEGORY', ['category_id' => $id]);
echo json_encode(['status' => 'success', 'message' => 'ลบหมวดหมู่เรียบร้อยแล้ว']);
}
else {
echo json_encode(['status' => 'error', 'message' => 'Invalid action']);
}
} catch (\Exception $e) {
echo json_encode(['status' => 'error', 'message' => 'Database Error: ' . $e->getMessage()]);
}
?>
@@ -0,0 +1,83 @@
<?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;
}
@@ -0,0 +1,50 @@
<?php
// api/get_logs.php - Fetch Activity Logs for Super Admin
header("Content-Type: application/json; charset=UTF-8");
require_once '../config/db.php';
try {
$agencyId = $_GET['agency_id'] ?? '';
if ($agencyId !== 'SUPER_ADMIN') {
echo json_encode(['status' => 'error', 'message' => 'Unauthorized']);
exit;
}
$startDate = $_GET['start_date'] ?? '';
$endDate = $_GET['end_date'] ?? '';
$search = $_GET['search'] ?? '';
$db = getDbConnection();
$pdo = $db['pdo'];
$query = "SELECT * FROM activity_logs WHERE 1=1";
$params = [];
if ($startDate) {
$query .= " AND created_at >= ?";
$params[] = $startDate . ' 00:00:00';
}
if ($endDate) {
$query .= " AND created_at <= ?";
$params[] = $endDate . ' 23:59:59';
}
if ($search) {
$query .= " AND (user_name LIKE ? OR action LIKE ? OR details LIKE ?)";
$searchParam = "%$search%";
$params[] = $searchParam;
$params[] = $searchParam;
$params[] = $searchParam;
}
$query .= " ORDER BY created_at DESC LIMIT 500"; // Limit to prevent massive payload
$stmt = $pdo->prepare($query);
$stmt->execute($params);
$logs = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo json_encode(['status' => 'success', 'data' => $logs]);
} catch (\Exception $e) {
echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
}
@@ -0,0 +1,76 @@
<?php
// api/get_news.php - PHP REST Endpoint to fetch news, agencies, and system settings from database
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
require_once __DIR__ . '/../config/db.php';
try {
$dbInfo = getDbConnection();
$pdo = $dbInfo['pdo'];
// Increment view count if ID specified
if (isset($_GET['view_id']) && !empty($_GET['view_id'])) {
$viewStmt = $pdo->prepare("UPDATE news SET views = views + 1 WHERE id = ?");
$viewStmt->execute([$_GET['view_id']]);
}
// Query news list with agency and category names
$stmt = $pdo->query("
SELECT n.*, a.name AS agency_name, a.code AS agency_code, c.name AS category_name
FROM news n
JOIN agencies a ON n.agency_id = a.id
JOIN categories c ON n.category_id = c.id
ORDER BY n.publish_date DESC, n.created_at DESC
");
$newsList = $stmt->fetchAll();
// Query attachments for each news document
foreach ($newsList as &$news) {
$attachStmt = $pdo->prepare("SELECT file_name AS name, file_type AS type, file_size AS size, file_url AS url FROM attachments WHERE news_id = ?");
$attachStmt->execute([$news['id']]);
$news['attachments'] = $attachStmt->fetchAll();
$news['isPinned'] = (bool)$news['is_pinned'];
$news['isUrgent'] = (bool)$news['is_urgent'];
$news['isHidden'] = (bool)($news['is_hidden'] ?? 0);
$news['docNum'] = $news['doc_num'];
$news['agencyId'] = $news['agency_id'];
$news['categoryId'] = $news['category_id'];
$news['date'] = $news['publish_date'];
$news['views'] = (int)$news['views'];
}
// Query active agencies list
$agenciesStmt = $pdo->query("SELECT id, name, code, COALESCE(admin_password, '1234') AS admin_password, gdrive_folder_id FROM agencies ORDER BY id ASC");
$agenciesList = $agenciesStmt->fetchAll();
// Query categories list
$categoriesStmt = $pdo->query("SELECT id, name, agency_id FROM categories ORDER BY id ASC");
$categoriesList = $categoriesStmt->fetchAll();
// Query system settings
$settingsStmt = $pdo->query("SELECT setting_key, setting_value FROM system_settings");
$rawSettings = $settingsStmt->fetchAll();
$settings = [];
foreach ($rawSettings as $row) {
$settings[$row['setting_key']] = $row['setting_value'];
}
// Query templates list
$templatesStmt = $pdo->query("SELECT id, agency_id, name, category_id, doc_num_format, title, content FROM templates ORDER BY created_at ASC");
$templatesList = $templatesStmt->fetchAll();
echo json_encode([
'status' => 'success',
'driver' => $dbInfo['driver'],
'data' => $newsList,
'agencies' => $agenciesList,
'categories' => $categoriesList,
'templates' => $templatesList,
'settings' => $settings
], JSON_UNESCAPED_UNICODE);
} catch (\Exception $e) {
echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
}
?>
@@ -0,0 +1,25 @@
<?php
// api/log_auth.php - Logs Authentication Events (Login)
header("Content-Type: application/json; charset=UTF-8");
require_once '../config/db.php';
require_once 'logger.php';
try {
$input = file_get_contents('php://input');
$data = json_decode($input, true);
if (!$data || !isset($data['user_id']) || !isset($data['user_name']) || !isset($data['action'])) {
echo json_encode(['status' => 'error', 'message' => 'Invalid data']);
exit;
}
$db = getDbConnection();
$pdo = $db['pdo'];
logActivity($pdo, $data['user_id'], $data['user_name'], $data['action'], $data['details'] ?? '');
echo json_encode(['status' => 'success']);
} catch (\Exception $e) {
echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
}
@@ -0,0 +1,12 @@
<?php
// api/logger.php - Activity Logger Helper
function logActivity($pdo, $userId, $userName, $action, $details) {
try {
$stmt = $pdo->prepare("INSERT INTO activity_logs (user_id, user_name, action, details) VALUES (?, ?, ?, ?)");
$detailsStr = is_array($details) || is_object($details) ? json_encode($details, JSON_UNESCAPED_UNICODE) : $details;
$stmt->execute([$userId, $userName, $action, $detailsStr]);
} catch (\Exception $e) {
error_log("Failed to log activity: " . $e->getMessage());
}
}
@@ -0,0 +1,105 @@
<?php
// api/news_actions.php - Handle hide and delete news actions
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/logger.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;
}
$action = $input['action'] ?? '';
$id = $input['id'] ?? '';
if (empty($action) || empty($id)) {
echo json_encode(['status' => 'error', 'message' => 'Missing action or id']);
exit;
}
try {
$dbInfo = getDbConnection();
$pdo = $dbInfo['pdo'];
if ($action === 'delete_news') {
// Fetch attachments first to delete them from Google Drive
$stmt = $pdo->prepare("SELECT file_url FROM attachments WHERE news_id = ?");
$stmt->execute([$id]);
$attachments = $stmt->fetchAll(PDO::FETCH_ASSOC);
if (!empty($attachments)) {
// Get GAS URL
$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)) {
foreach ($attachments as $att) {
if (!empty($att['file_url'])) {
preg_match('/\/d\/([a-zA-Z0-9_-]+)/', $att['file_url'], $matches);
if (!empty($matches[1])) {
$fileId = $matches[1];
$payload = json_encode(['action' => 'delete', 'fileId' => $fileId]);
$ch = curl_init($gasUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
curl_exec($ch);
curl_close($ch);
}
}
}
}
}
// Delete from attachments table (cascading might handle this, but to be safe)
$stmt = $pdo->prepare("DELETE FROM attachments WHERE news_id = ?");
$stmt->execute([$id]);
$stmt = $pdo->prepare("DELETE FROM news WHERE id = ?");
$stmt->execute([$id]);
$actionUserId = $input['action_user_id'] ?? 'SYSTEM';
$actionUserName = $input['action_user_name'] ?? 'SYSTEM';
logActivity($pdo, $actionUserId, $actionUserName, 'DELETE_NEWS', ['news_id' => $id]);
echo json_encode(['status' => 'success', 'message' => 'ลบข้อมูลและไฟล์แนบที่เกี่ยวข้องเรียบร้อยแล้ว']);
}
elseif ($action === 'toggle_hide_news') {
// First get current status
$stmt = $pdo->prepare("SELECT is_hidden FROM news WHERE id = ?");
$stmt->execute([$id]);
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if ($row) {
$newStatus = $row['is_hidden'] ? 0 : 1;
$update = $pdo->prepare("UPDATE news SET is_hidden = ? WHERE id = ?");
$update->execute([$newStatus, $id]);
$actionUserId = $input['action_user_id'] ?? 'SYSTEM';
$actionUserName = $input['action_user_name'] ?? 'SYSTEM';
logActivity($pdo, $actionUserId, $actionUserName, 'TOGGLE_HIDE_NEWS', ['news_id' => $id, 'is_hidden' => $newStatus]);
echo json_encode(['status' => 'success', 'message' => 'อัปเดตสถานะเรียบร้อยแล้ว', 'is_hidden' => $newStatus]);
} else {
echo json_encode(['status' => 'error', 'message' => 'ไม่พบข้อมูล']);
}
}
else {
echo json_encode(['status' => 'error', 'message' => 'Invalid action']);
}
} catch (\Exception $e) {
echo json_encode(['status' => 'error', 'message' => 'Database Error: ' . $e->getMessage()]);
}
?>
@@ -0,0 +1,104 @@
<?php
// api/save_news.php - PHP REST Endpoint to insert or update news in database
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/logger.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;
}
$id = $input['id'] ?? '';
$docNum = trim($input['docNum'] ?? $input['doc_num'] ?? '');
if ($docNum === '') $docNum = '-';
$title = trim($input['title'] ?? '');
$agencyId = $input['agencyId'] ?? $input['agency_id'] ?? '';
$categoryId = $input['categoryId'] ?? $input['category_id'] ?? '';
$date = $input['date'] ?? $input['publish_date'] ?? date('Y-m-d');
$content = trim($input['content'] ?? '');
$isPinned = !empty($input['isPinned']) || !empty($input['is_pinned']) ? 1 : 0;
$isUrgent = !empty($input['isUrgent']) || !empty($input['is_urgent']) ? 1 : 0;
$attachments = $input['attachments'] ?? [];
if (empty($title) || empty($agencyId) || empty($categoryId)) {
echo json_encode(['status' => 'error', 'message' => 'กรุณากรอกข้อมูลที่จำเป็นให้ครบถ้วน']);
exit;
}
try {
$dbInfo = getDbConnection();
$pdo = $dbInfo['pdo'];
$pdo->beginTransaction();
if (!empty($id)) {
// Update existing document
$stmt = $pdo->prepare("
UPDATE news
SET doc_num = ?, title = ?, agency_id = ?, category_id = ?, publish_date = ?, content = ?, is_pinned = ?, is_urgent = ?
WHERE id = ?
");
$stmt->execute([$docNum, $title, $agencyId, $categoryId, $date, $content, $isPinned, $isUrgent, $id]);
// Delete existing attachments to recreate
$delAttach = $pdo->prepare("DELETE FROM attachments WHERE news_id = ?");
$delAttach->execute([$id]);
$newsId = $id;
$message = 'บันทึกการแก้ไขข้อมูลลงในฐานข้อมูลเรียบร้อยแล้ว';
} else {
// Generate new ID
$countStmt = $pdo->query("SELECT COUNT(*) AS total FROM news");
$total = $countStmt->fetch()['total'] + 1;
$newsId = 'DOC-2026-' . str_pad($total, 3, '0', STR_PAD_LEFT);
$stmt = $pdo->prepare("
INSERT INTO news (id, doc_num, title, agency_id, category_id, publish_date, content, is_pinned, is_urgent, views)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 1)
");
$stmt->execute([$newsId, $docNum, $title, $agencyId, $categoryId, $date, $content, $isPinned, $isUrgent]);
$message = 'เผยแพร่บันทึกข้อความลงในฐานข้อมูลเรียบร้อยแล้ว';
}
// Insert attachments
if (is_array($attachments) && count($attachments) > 0) {
$attachStmt = $pdo->prepare("
INSERT INTO attachments (news_id, file_name, file_type, file_size, file_url)
VALUES (?, ?, ?, ?, ?)
");
foreach ($attachments as $att) {
$fileName = trim($att['name'] ?? $att['file_name'] ?? '');
$fileType = $att['type'] ?? $att['file_type'] ?? 'pdf';
$fileSize = $att['size'] ?? $att['file_size'] ?? '1.0 MB';
$fileUrl = $att['url'] ?? $att['file_url'] ?? null;
if (!empty($fileName)) {
$attachStmt->execute([$newsId, $fileName, $fileType, $fileSize, $fileUrl]);
}
}
}
$actionUserId = $input['action_user_id'] ?? 'SYSTEM';
$actionUserName = $input['action_user_name'] ?? 'SYSTEM';
$actionType = $id ? 'UPDATE_NEWS' : 'CREATE_NEWS';
logActivity($pdo, $actionUserId, $actionUserName, $actionType, ['news_id' => $newsId, 'title' => $title]);
$pdo->commit();
echo json_encode(['status' => 'success', 'message' => $message, 'id' => $newsId], JSON_UNESCAPED_UNICODE);
} catch (\Exception $e) {
if (isset($pdo) && $pdo->inTransaction()) {
$pdo->rollBack();
}
echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
}
?>
@@ -0,0 +1,85 @@
<?php
// api/template_actions.php - Handle CRUD for templates
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;
}
$action = $input['action'] ?? '';
if (empty($action)) {
echo json_encode(['status' => 'error', 'message' => 'Missing action']);
exit;
}
try {
$dbInfo = getDbConnection();
$pdo = $dbInfo['pdo'];
if ($action === 'add_template') {
$agencyId = $input['agencyId'] ?? '';
$name = $input['name'] ?? '';
$categoryId = $input['categoryId'] ?? '';
$docNumFormat = $input['docNumFormat'] ?? '';
$title = $input['title'] ?? '';
$content = $input['content'] ?? '';
if(empty($agencyId) || empty($name)) {
echo json_encode(['status' => 'error', 'message' => 'Missing required fields']);
exit;
}
// Generate unique ID
$id = 'TPL-' . time() . rand(100, 999);
$stmt = $pdo->prepare("INSERT INTO templates (id, agency_id, name, category_id, doc_num_format, title, content) VALUES (?, ?, ?, ?, ?, ?, ?)");
$stmt->execute([$id, $agencyId, $name, $categoryId, $docNumFormat, $title, $content]);
echo json_encode(['status' => 'success', 'message' => 'เพิ่มแม่แบบด่วนเรียบร้อยแล้ว', 'id' => $id]);
}
elseif ($action === 'edit_template') {
$id = $input['id'] ?? '';
$agencyId = $input['agencyId'] ?? '';
$name = $input['name'] ?? '';
$categoryId = $input['categoryId'] ?? '';
$docNumFormat = $input['docNumFormat'] ?? '';
$title = $input['title'] ?? '';
$content = $input['content'] ?? '';
if(empty($id) || empty($name)) {
echo json_encode(['status' => 'error', 'message' => 'Missing required fields']);
exit;
}
$stmt = $pdo->prepare("UPDATE templates SET name = ?, category_id = ?, doc_num_format = ?, title = ?, content = ? WHERE id = ? AND (agency_id = ? OR ? = 'SUPER_ADMIN')");
$stmt->execute([$name, $categoryId, $docNumFormat, $title, $content, $id, $agencyId, $agencyId]);
echo json_encode(['status' => 'success', 'message' => 'แก้ไขแม่แบบด่วนเรียบร้อยแล้ว']);
}
elseif ($action === 'delete_template') {
$id = $input['id'] ?? '';
$agencyId = $input['agencyId'] ?? '';
if(empty($id)) {
echo json_encode(['status' => 'error', 'message' => 'Missing template ID']);
exit;
}
$stmt = $pdo->prepare("DELETE FROM templates WHERE id = ? AND (agency_id = ? OR ? = 'SUPER_ADMIN')");
$stmt->execute([$id, $agencyId, $agencyId]);
echo json_encode(['status' => 'success', 'message' => 'ลบแม่แบบด่วนเรียบร้อยแล้ว']);
}
else {
echo json_encode(['status' => 'error', 'message' => 'Invalid action']);
}
} catch (\Exception $e) {
echo json_encode(['status' => 'error', 'message' => 'Database Error: ' . $e->getMessage()]);
}
?>
@@ -0,0 +1,129 @@
<?php
// api/upload_file.php - Upload file to 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';
// Set higher limits for large file uploads to GAS (70MB+ requires a lot of memory for base64 & JSON)
set_time_limit(600);
ini_set('memory_limit', '1024M');
ini_set('post_max_size', '128M');
ini_set('upload_max_filesize', '128M');
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
echo json_encode(['status' => 'error', 'message' => 'Invalid request method']);
exit;
}
if (!isset($_FILES['file']) || $_FILES['file']['error'] !== UPLOAD_ERR_OK) {
echo json_encode(['status' => 'error', 'message' => 'No file uploaded or upload error']);
exit;
}
$folderId = $_POST['folderId'] ?? '';
if (empty($folderId)) {
echo json_encode(['status' => 'error', 'message' => 'Missing Google Drive Folder ID. ผู้ดูแลระบบยังไม่ได้ตั้งค่า Folder ID ให้กับหน่วยงานนี้']);
exit;
}
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;
}
$fileTmpPath = $_FILES['file']['tmp_name'];
$fileName = $_FILES['file']['name'];
$fileMimeType = mime_content_type($fileTmpPath);
if (!$fileMimeType) {
$fileMimeType = $_FILES['file']['type'];
}
$fileData = file_get_contents($fileTmpPath);
$base64 = base64_encode($fileData);
$payload = json_encode([
'filename' => $fileName,
'mimeType' => $fileMimeType,
'base64' => $base64,
'folderId' => $folderId
]);
// Send to GAS via cURL
$ch = curl_init($gasUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false); // Handle redirect manually to prevent POST/GET confusion
curl_setopt($ch, CURLOPT_HEADER, true); // Include headers to parse Location
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
curl_setopt($ch, CURLOPT_TIMEOUT, 120);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json'
]);
$response = curl_exec($ch);
if(curl_errno($ch)) {
throw new \Exception(curl_error($ch));
}
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$headerStr = substr($response, 0, $headerSize);
$bodyStr = substr($response, $headerSize);
curl_close($ch);
// If GAS rejects because payload is too large
if ($httpCode === 413) {
echo json_encode(['status' => 'error', 'message' => 'ขนาดไฟล์ใหญ่เกินกว่าที่ Google Drive จะรับได้ (จำกัดการส่งข้อมูลที่ 50MB)']);
exit;
}
// If GAS returns a redirect (e.g. 302, 307)
if ($httpCode >= 300 && $httpCode < 400) {
if (preg_match('/^Location:\s*([^\r\n]+)/im', $headerStr, $matches)) {
$redirectUrl = trim($matches[1]);
// Force a GET request to the redirect URL
$ch2 = curl_init($redirectUrl);
curl_setopt($ch2, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch2, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch2, CURLOPT_HTTPGET, true); // Force GET
curl_setopt($ch2, CURLOPT_TIMEOUT, 60);
$bodyStr = curl_exec($ch2);
if(curl_errno($ch2)) {
throw new \Exception(curl_error($ch2));
}
curl_close($ch2);
} else {
throw new \Exception("GAS returned redirect but no Location header found.");
}
}
$resData = json_decode($bodyStr, true);
if ($resData && isset($resData['status']) && $resData['status'] === 'success') {
echo json_encode([
'status' => 'success',
'message' => 'File uploaded to Google Drive',
'fileId' => $resData['fileId'] ?? null,
'url' => $resData['url'] ?? null,
'fileName' => $fileName,
'fileSize' => $_FILES['file']['size']
]);
} else {
echo json_encode(['status' => 'error', 'message' => 'Google Apps Script Error: ' . ($resData['message'] ?? $response)]);
}
} catch (\Exception $e) {
echo json_encode(['status' => 'error', 'message' => 'Upload Error: ' . $e->getMessage()]);
}
?>