Implement comprehensive improvement plan (Phases 1-6)

Security (Phase 1-2):
- Add SecurityHeadersMiddleware with CSP, X-Frame-Options, etc.
- Add RateLimitMiddleware for API rate limiting
- Add security event logging to AuditLogModel
- Add ResponseHelper for standardized API responses
- Update config.php with security constants

Database (Phase 3):
- Add migration 014 for additional indexes
- Add migration 015 for ticket dependencies
- Add migration 016 for ticket attachments
- Add migration 017 for recurring tickets
- Add migration 018 for custom fields

Features (Phase 4-5):
- Add ticket dependencies with DependencyModel and API
- Add duplicate detection with check_duplicates API
- Add file attachments with AttachmentModel and upload/download APIs
- Add @mentions with autocomplete and highlighting
- Add quick actions on dashboard rows

Collaboration (Phase 5):
- Add mention extraction in CommentModel
- Add mention autocomplete dropdown in ticket.js
- Add mention highlighting CSS styles

Admin & Export (Phase 6):
- Add StatsModel for dashboard widgets
- Add dashboard stats cards (open, critical, unassigned, etc.)
- Add CSV/JSON export via export_tickets API
- Add rich text editor toolbar in markdown.js
- Add RecurringTicketModel with cron job
- Add CustomFieldModel for per-category fields
- Add admin views: RecurringTickets, CustomFields, Workflow,
  Templates, AuditLog, UserActivity
- Add admin APIs: manage_workflows, manage_templates,
  manage_recurring, custom_fields, get_users
- Add admin routes in index.php

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
2026-01-20 09:55:01 -05:00
parent 8c7211d311
commit be505b7312
53 changed files with 6640 additions and 169 deletions

View File

@@ -3,23 +3,18 @@
error_reporting(E_ALL);
ini_set('display_errors', 0); // Don't display errors in the response
// Define a debug log function
function debug_log($message) {
file_put_contents('/tmp/api_debug.log', date('Y-m-d H:i:s') . " - $message\n", FILE_APPEND);
}
// Apply rate limiting
require_once dirname(__DIR__) . '/middleware/RateLimitMiddleware.php';
RateLimitMiddleware::apply('api');
// Start output buffering to capture any errors
ob_start();
try {
debug_log("Script started");
// Load config
$configPath = dirname(__DIR__) . '/config/config.php';
debug_log("Loading config from: $configPath");
require_once $configPath;
debug_log("Config loaded successfully");
// Load environment variables (for Discord webhook)
$envPath = dirname(__DIR__) . '/.env';
$envVars = [];
@@ -38,7 +33,6 @@ try {
$envVars[$key] = $value;
}
}
debug_log("Environment variables loaded");
}
// Load models directly with absolute paths
@@ -47,12 +41,10 @@ try {
$auditLogModelPath = dirname(__DIR__) . '/models/AuditLogModel.php';
$workflowModelPath = dirname(__DIR__) . '/models/WorkflowModel.php';
debug_log("Loading models from: $ticketModelPath and $commentModelPath");
require_once $ticketModelPath;
require_once $commentModelPath;
require_once $auditLogModelPath;
require_once $workflowModelPath;
debug_log("Models loaded successfully");
// Check authentication via session
session_start();
@@ -75,7 +67,6 @@ try {
$currentUser = $_SESSION['user'];
$userId = $currentUser['user_id'];
$isAdmin = $currentUser['is_admin'] ?? false;
debug_log("User authenticated: " . $currentUser['username'] . " (admin: " . ($isAdmin ? 'yes' : 'no') . ")");
// Updated controller class that handles partial updates
class ApiTicketController {
@@ -98,8 +89,6 @@ try {
}
public function update($id, $data) {
debug_log("ApiTicketController->update called with ID: $id and data: " . json_encode($data));
// First, get the current ticket data to fill in missing fields
$currentTicket = $this->ticketModel->getTicketById($id);
if (!$currentTicket) {
@@ -108,9 +97,7 @@ try {
'error' => 'Ticket not found'
];
}
debug_log("Current ticket data: " . json_encode($currentTicket));
// Merge current data with updates, keeping existing values for missing fields
$updateData = [
'ticket_id' => $id,
@@ -121,9 +108,7 @@ try {
'status' => $data['status'] ?? $currentTicket['status'],
'priority' => isset($data['priority']) ? (int)$data['priority'] : (int)$currentTicket['priority']
];
debug_log("Merged update data: " . json_encode($updateData));
// Validate required fields
if (empty($updateData['title'])) {
return [
@@ -155,14 +140,10 @@ try {
];
}
}
debug_log("Validation passed, calling ticketModel->updateTicket");
// Update ticket with user tracking
$result = $this->ticketModel->updateTicket($updateData, $this->userId);
debug_log("TicketModel->updateTicket returned: " . ($result ? 'true' : 'false'));
if ($result) {
// Log ticket update to audit log
if ($this->userId) {
@@ -188,12 +169,10 @@ try {
private function sendDiscordWebhook($ticketId, $oldData, $newData, $changedFields) {
if (!isset($this->envVars['DISCORD_WEBHOOK_URL']) || empty($this->envVars['DISCORD_WEBHOOK_URL'])) {
debug_log("Discord webhook URL not configured, skipping webhook");
return;
}
$webhookUrl = $this->envVars['DISCORD_WEBHOOK_URL'];
debug_log("Sending Discord webhook to: $webhookUrl");
// Determine what fields actually changed
$changes = [];
@@ -211,7 +190,6 @@ try {
}
if (empty($changes)) {
debug_log("No actual changes detected, skipping webhook");
return;
}
@@ -248,16 +226,13 @@ try {
$payload = [
'embeds' => [$embed]
];
debug_log("Discord payload: " . json_encode($payload));
// Send webhook
$ch = curl_init($webhookUrl);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
$webhookResult = curl_exec($ch);
@@ -265,18 +240,11 @@ try {
$curlError = curl_error($ch);
curl_close($ch);
if ($curlError) {
debug_log("Discord webhook cURL error: $curlError");
} else {
debug_log("Discord webhook sent. HTTP Code: $httpCode, Response: $webhookResult");
}
// Silently handle errors - webhook is optional
}
}
debug_log("Controller defined successfully");
// Create database connection
debug_log("Creating database connection");
$conn = new mysqli(
$GLOBALS['config']['DB_HOST'],
$GLOBALS['config']['DB_USER'],
@@ -287,8 +255,7 @@ try {
if ($conn->connect_error) {
throw new Exception("Database connection failed: " . $conn->connect_error);
}
debug_log("Database connection successful");
// Check request method
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
throw new Exception("Method not allowed. Expected POST, got " . $_SERVER['REQUEST_METHOD']);
@@ -297,9 +264,7 @@ try {
// Get POST data
$input = file_get_contents('php://input');
$data = json_decode($input, true);
debug_log("Received raw input: " . $input);
debug_log("Decoded data: " . json_encode($data));
if (!$data) {
throw new Exception("Invalid JSON data received: " . $input);
}
@@ -309,17 +274,12 @@ try {
}
$ticketId = (int)$data['ticket_id'];
debug_log("Processing ticket ID: $ticketId");
// Initialize controller
debug_log("Initializing controller");
$controller = new ApiTicketController($conn, $envVars, $userId, $isAdmin);
debug_log("Controller initialized");
// Update ticket
debug_log("Calling controller update method");
$result = $controller->update($ticketId, $data);
debug_log("Update completed with result: " . json_encode($result));
// Close database connection
$conn->close();
@@ -330,12 +290,8 @@ try {
// Return response
header('Content-Type: application/json');
echo json_encode($result);
debug_log("Response sent successfully");
} catch (Exception $e) {
debug_log("Error: " . $e->getMessage());
debug_log("Stack trace: " . $e->getTraceAsString());
// Discard any output that might have been generated
ob_end_clean();
@@ -346,6 +302,5 @@ try {
'success' => false,
'error' => $e->getMessage()
]);
debug_log("Error response sent");
}
?>