false, 'error' => 'Authentication required']); exit; } // CSRF Protection for all state-changing methods (any non-GET/HEAD request) require_once dirname(__DIR__) . '/middleware/CsrfMiddleware.php'; if (!in_array($_SERVER['REQUEST_METHOD'], ['GET', 'HEAD'], true)) { $csrfToken = $_SERVER['HTTP_X_CSRF_TOKEN'] ?? ''; if (!CsrfMiddleware::validateToken($csrfToken)) { http_response_code(403); header('Content-Type: application/json'); echo json_encode([ 'success' => false, 'error' => 'Invalid CSRF token', 'csrf_token' => CsrfMiddleware::getToken() ]); exit; } // Rotate token after successful validation $newCsrfToken = CsrfMiddleware::rotateToken(); } $currentUser = $_SESSION['user']; $userId = $currentUser['user_id']; // Use centralized database connection $conn = Database::getConnection(); // Get POST data $data = json_decode(file_get_contents('php://input'), true); if (!$data) { http_response_code(400); ob_end_clean(); header('Content-Type: application/json'); echo json_encode(['success' => false, 'error' => 'Invalid JSON data received']); exit; } // Validation, access check, mentions, audit log and notifications live in // CommentService so the MCP add_comment tool runs the same code path. require_once dirname(__DIR__) . '/services/CommentService.php'; $result = CommentService::addComment($conn, $currentUser, $data); if (!empty($result['http_status'])) { http_response_code($result['http_status']); unset($result['http_status']); ob_end_clean(); header('Content-Type: application/json'); echo json_encode($result); exit; } if ($result['success'] && isset($newCsrfToken)) { $result['csrf_token'] = $newCsrfToken; } // Discard any unexpected output ob_end_clean(); // Return JSON response if ($result['success']) { http_response_code(201); } header('Content-Type: application/json'); echo json_encode($result); } catch (Exception $e) { // Discard any unexpected output ob_end_clean(); // Log error details but don't expose to client error_log("Add comment API error: " . $e->getMessage()); // Return error response http_response_code(500); header('Content-Type: application/json'); echo json_encode([ 'success' => false, 'error' => 'An internal error occurred' ]); }