false, 'error' => 'Configuration file not found' ]); exit; } // Load application config so UrlHelper can resolve APP_DOMAIN, and so the // DB connection below (via Database::getConnection()) gets the same // charset/timezone sync as every other endpoint instead of a hand-rolled // second connection. require_once __DIR__ . '/config/config.php'; require_once __DIR__ . '/helpers/Database.php'; try { $conn = Database::getConnection(); } catch (\Throwable $e) { error_log('create_ticket_api: DB connection failed: ' . $e->getMessage()); http_response_code(500); echo json_encode([ 'success' => false, 'error' => 'Internal server error' ]); exit; } // Authenticate via API key require_once __DIR__ . '/middleware/ApiKeyAuth.php'; require_once __DIR__ . '/models/AuditLogModel.php'; require_once __DIR__ . '/models/StatsModel.php'; require_once __DIR__ . '/models/TicketModel.php'; require_once __DIR__ . '/models/WorkflowModel.php'; require_once __DIR__ . '/helpers/UrlHelper.php'; require_once __DIR__ . '/helpers/TicketHash.php'; require_once __DIR__ . '/services/AutoTicketService.php'; $apiKeyAuth = new ApiKeyAuth($conn); try { $systemUser = $apiKeyAuth->authenticate(); } catch (Exception $e) { // Authentication failed - ApiKeyAuth already sent the response exit; } // Ticket creation is a write — a read-only key must be rejected with 403. $apiKeyAuth->requireScope('read_write'); $userId = $systemUser['user_id']; // Parse input regardless of content-type header $rawInput = file_get_contents('php://input'); $data = json_decode($rawInput, true); // Validate required fields before any processing if (!is_array($data) || empty($data['title'])) { // Try URL-encoded fallback if (empty($data['title'])) { parse_str($rawInput, $urlData); if (!empty($urlData['title'])) { $data = $urlData; } } if (!is_array($data) || empty($data['title'])) { http_response_code(400); echo json_encode(['success' => false, 'error' => 'title is required']); exit; } } // Shared ticket data $title = (string)($data['title'] ?? ''); $description = (string)($data['description'] ?? ''); $status = (string)($data['status'] ?? 'Open'); $priority = $data['priority'] ?? '4'; $category = (string)($data['category'] ?? 'General'); $type = (string)($data['type'] ?? 'Issue'); // Validate externally-supplied status and priority. (category/type are free-form // in this schema.) A non-numeric priority would otherwise cast to 0 and escalate // the ticket below P1 on the dedup/update path. $validStatuses = $GLOBALS['config']['TICKET_STATUSES'] ?? ['Open', 'Pending', 'In Progress', 'Closed']; if (!in_array($status, $validStatuses, true)) { http_response_code(400); echo json_encode(['success' => false, 'error' => 'Invalid status']); exit; } if (!is_numeric($priority) || (int)$priority < 1 || (int)$priority > 5) { http_response_code(400); echo json_encode(['success' => false, 'error' => 'Invalid priority (must be 1-5)']); exit; } $priority = (int)$priority; // An explicit dedup_key (#123) decides what "the same problem" is. A // malformed one is an error, never a silent fall back to title hashing. if (isset($data['dedup_key']) && $data['dedup_key'] !== '' && !TicketHash::isValidKey($data['dedup_key'])) { http_response_code(400); echo json_encode([ 'success' => false, 'error' => 'Invalid dedup_key: use 1-128 of A-Z a-z 0-9 _ . : - (e.g. host:compute-storage-01:oom)', ]); exit; } $dedupKey = TicketHash::key($data); // Which reporter this is (gandalf, hwmonDaemon, thor): the API key's name. // Recorded as the ticket's source and used as the author of the comments // this endpoint writes. $source = (string)($apiKeyAuth->getKeyContext()['key_name'] ?? 'API'); $commentAuthor = mb_substr($source, 0, 50); $ticketHash = TicketHash::generate($data); $auditLog = new AuditLogModel($conn); // Everything from here through either updating/reopening the matched ticket // or inserting a brand-new one runs inside one transaction with a row lock // on the hash lookup. Without this, two concurrent requests carrying the // same dedup hash (e.g. overlapping monitoring runs) could both read the // same pre-update snapshot and each independently apply an escalation. FOR // UPDATE on this equality lookup against the unique-indexed hash column also // takes a lock on the "gap" where no row currently exists, so two concurrent // requests for a genuinely new hash are still safe from a duplicate row — // but that gap lock is shared, not exclusive, so both can reach the INSERT // below and deadlock with each other rather than one blocking cleanly on the // other's row. See the retry loop and comment near the INSERT's catch block // for how that case is handled. // Retried once if the INSERT below deadlocks with another connection's // concurrent insert into the same not-yet-existing hash (see comment // above the INSERT's catch block) — the retry's own SELECT ... FOR UPDATE // will then find the winner's already-committed row and take the // update/escalate branch instead of erroring out. $maxDedupAttempts = 2; for ($dedupAttempt = 1; $dedupAttempt <= $maxDedupAttempts; $dedupAttempt++) { $conn->begin_transaction(); // Look up the ticket holding this hash (open OR closed) $existing = AutoTicketService::lockByHash($conn, $ticketHash); if ($existing && ($existing['status'] !== 'Closed' || $existing['closed_recently'])) { $existingId = $existing['ticket_id']; $existingStatus = $existing['status']; $existingTitle = $existing['title']; $existingPriority = (int)$existing['priority']; $newPriority = (int)$priority; if ($existingStatus !== 'Closed') { // Ticket is still active — update title, escalate priority, and refresh // description with latest sensor data. $changes = []; $updateSql = "UPDATE tickets SET updated_at = NOW(), updated_by = ?"; $bindTypes = "i"; $bindVals = [$userId]; if ($title !== $existingTitle) { $updateSql .= ", title = ?"; $bindTypes .= "s"; $bindVals[] = $title; $changes['title'] = ['from' => $existingTitle, 'to' => $title]; } if ($newPriority < $existingPriority) { $updateSql .= ", priority = ?"; $bindTypes .= "i"; $bindVals[] = $newPriority; $changes['priority'] = ['from' => $existingPriority, 'to' => $newPriority]; } // Always refresh the description so the ticket body shows current sensor data if (!empty($description)) { $updateSql .= ", description = ?"; $bindTypes .= "s"; $bindVals[] = $description; $changes['description_refreshed'] = true; } if (!empty($changes)) { $updateSql .= " WHERE ticket_id = ?"; $bindTypes .= "s"; $bindVals[] = $existingId; $updStmt = $conn->prepare($updateSql); $updStmt->bind_param($bindTypes, ...$bindVals); $updStmt->execute(); $updStmt->close(); // Only post a comment on priority escalation — title and description updates // are silent (title changes like rising counters would spam a comment every run). // Keep it short: the full sensor data is refreshed in the ticket description, // so the comment just records the bump + a brief reason (no ASCII dump). if (isset($changes['priority'])) { $pLabels = [1 => 'P1 (Critical)', 2 => 'P2 (High)', 3 => 'P3 (Medium)', 4 => 'P4 (Low)', 5 => 'P5 (Minimal)']; $fromP = (int)$changes['priority']['from']; $toP = (int)$changes['priority']['to']; $fromL = $pLabels[$fromP] ?? "P{$fromP}"; $toL = $pLabels[$toP] ?? "P{$toP}"; $commentText = "**{$source} raised priority {$fromL} → {$toL}.**\n\n" . "The latest report described a more severe condition for this issue, " . "so it now needs faster attention. Current details are in the ticket description above."; $commentStmt = $conn->prepare( "INSERT INTO ticket_comments (ticket_id, user_id, user_name, comment_text, markdown_enabled) VALUES (?, ?, ?, ?, 1)" ); $commentStmt->bind_param("siss", $existingId, $userId, $commentAuthor, $commentText); $commentStmt->execute(); $commentStmt->close(); } // Audit only real title/priority changes. The description is // refreshed on every run, and logging that alone wrote a // reason-only row every few minutes per open ticket — 50k+ rows // on one ticket, which broke its page (tinker_tickets#112). $auditedChanges = array_diff_key($changes, ['description_refreshed' => true]); if (!empty($auditedChanges)) { $auditLog->log($userId, 'update', 'ticket', $existingId, array_merge( $auditedChanges, ['reason' => "auto-updated by {$source} (condition worsened)"] )); } // Only notify on priority escalation — title-only updates (e.g. rising // Power_On_Hours counter) should not generate a Matrix ping every hour. if (isset($changes['priority'])) { require_once __DIR__ . '/helpers/NotificationHelper.php'; NotificationHelper::sendTicketNotification($existingId, [ 'title' => $title, 'priority' => $changes['priority']['to'], 'category' => $category, 'type' => $type, 'status' => $existingStatus, ], 'automated'); } // Ticket state (priority/title/description) changed — refresh dashboard stats. (new StatsModel($conn))->invalidateCache(); } $conn->commit(); Database::close(); echo json_encode([ 'success' => true, 'ticket_id' => $existingId, 'message' => empty($changes) ? 'Duplicate — no change' : 'Existing ticket updated', 'action' => empty($changes) ? 'deduplicated' : 'updated', 'changes' => $changes, ]); exit; } // Ticket closed inside the reopen window: reopen it and add a recurrence comment. Route // through the Workflow Designer like every other status-write path in // the app, rather than forcing status='Open' via raw SQL regardless of // configured transition rules. $workflowModel = new WorkflowModel($conn); $reopenStatus = 'Open'; if (!$workflowModel->isTransitionAllowed('Closed', 'Open', false)) { // Direct Closed->Open isn't configured — fall back to any transition // the Workflow Designer does allow from Closed that this unattended, // non-admin automation can actually satisfy (no comment prompt, no // admin elevation). If even that doesn't exist, leave the ticket // Closed rather than force an unconfigured state. $reopenStatus = null; foreach ($workflowModel->getAllowedTransitions('Closed') as $transition) { if (!$transition['requires_comment'] && !$transition['requires_admin']) { $reopenStatus = $transition['to_status']; break; } } } if ($reopenStatus !== null) { $ticketModel = new TicketModel($conn); $ticketModel->updateTicket([ 'ticket_id' => $existingId, 'title' => $title, 'description' => $description, 'category' => $category, 'type' => $type, 'status' => $reopenStatus, 'priority' => $priority, ], $userId); } else { error_log("create_ticket_api: {$source} recurrence for ticket $existingId: " . "no admin-free, comment-free transition from Closed is configured; leaving ticket Closed"); } $commentText = "**Issue recurred, ticket reopened automatically.**\n\n" . "{$source} detected this condition again. The ticket description reflects the " . "latest report; see this comment's timestamp for when the issue recurred."; if ($reopenStatus === null) { $commentText = "**Issue recurred, but the ticket could not be reopened automatically.**\n\n" . "{$source} detected this condition again. No Workflow Designer transition from " . "Closed is configured that this automation can perform unattended (no comment/admin " . "requirement); the ticket remains Closed. Please review and reopen manually if appropriate."; } $commentStmt = $conn->prepare( "INSERT INTO ticket_comments (ticket_id, user_id, user_name, comment_text, markdown_enabled) VALUES (?, ?, ?, ?, 1)" ); $commentStmt->bind_param("siss", $existingId, $userId, $commentAuthor, $commentText); $commentStmt->execute(); $commentStmt->close(); if ($reopenStatus !== null) { $auditLog->log($userId, 'update', 'ticket', $existingId, [ 'status' => ['from' => 'Closed', 'to' => $reopenStatus], 'reason' => "auto-reopened by {$source} (issue recurred)", ]); // Ticket reopened — refresh dashboard stats. (new StatsModel($conn))->invalidateCache(); } else { $auditLog->log($userId, 'update', 'ticket', $existingId, [ 'reason' => "{$source} recurrence detected but no valid reopen transition configured; ticket left Closed", ]); } $conn->commit(); Database::close(); if ($reopenStatus !== null) { require_once __DIR__ . '/helpers/NotificationHelper.php'; NotificationHelper::sendTicketNotification($existingId, [ 'title' => $title, 'priority' => $priority, 'category' => $category, 'type' => $type, 'status' => $reopenStatus, ], 'automated'); } echo json_encode([ 'success' => true, 'ticket_id' => $existingId, 'message' => $reopenStatus !== null ? 'Existing closed ticket reopened' : 'Recurrence noted; ticket left Closed (no valid workflow transition configured)', 'action' => $reopenStatus !== null ? 'reopened' : 'recurrence_noted', ]); exit; } // No ticket holds this hash, or the one that does closed longer ago than // the reopen window (#123): create a new one. In the second case the new // ticket is a recurrence: it takes over the hash (unique, so the old // ticket gives it up), records the old ticket in recurrence_of, and is // linked relates_to it with a history comment. // // Still inside the transaction opened above, so a concurrent request for // the same hash is blocked on its own SELECT ... FOR UPDATE until this one // commits or rolls back rather than racing this INSERT. // // Note on FOR UPDATE over a not-yet-existing key: InnoDB's gap lock in that // case is a shared lock, not exclusive, so two concurrent transactions can // both acquire it and both reach this INSERT. The conflict only surfaces // when they each request the insert-intention lock for the same gap, // which InnoDB resolves as a deadlock (error 1213), not by blocking one // of the SELECTs. The outer loop above retries that case: the loser rolls // back and re-runs its own SELECT ... FOR UPDATE, which by then finds the // winner's committed row and takes the update/escalate branch instead. $previous = $existing; // a Closed ticket outside the window, or null $previousId = $previous['ticket_id'] ?? null; // A ticket_id that is free, so a 1062 on INSERT below can only be the // unique hash, and with the FOR UPDATE lock above only in the unlikely // case of a hash collision between two genuinely different reports. $ticket_id = AutoTicketService::newTicketId($conn); if ($ticket_id === null) { $conn->rollback(); error_log('create_ticket_api: failed to generate a unique ticket_id'); http_response_code(500); echo json_encode(['success' => false, 'error' => 'Internal server error']); exit; } try { if ($previousId !== null) { AutoTicketService::releaseHash($conn, $previousId); } AutoTicketService::insert($conn, [ 'ticket_id' => $ticket_id, 'title' => $title, 'description' => $description, 'status' => $status, 'priority' => $priority, 'category' => $category, 'type' => $type, 'hash' => $ticketHash, 'created_by' => $userId, 'source' => $source, 'dedup_key' => $dedupKey ?? ($previous['dedup_key'] ?? null), 'recurrence_of' => $previousId, ]); } catch (mysqli_sql_exception $e) { $conn->rollback(); if (in_array($e->getCode(), [1213, 1205], true) && $dedupAttempt < $maxDedupAttempts) { // Deadlock (1213) or lock wait timeout (1205) from a concurrent // insert into the same not-yet-existing hash gap: see the note // above. Retry: the next iteration's own SELECT ... FOR UPDATE // will find whichever side won and take the update/escalate path. continue; } if ($e->getCode() === 1062) { // Defensive: only a genuine hash collision between two different // reports can get here now that the SELECT above takes FOR UPDATE. echo json_encode(['success' => false, 'error' => 'Duplicate ticket']); } else { error_log('create_ticket_api: insert failed: ' . $e->getMessage()); http_response_code(500); echo json_encode(['success' => false, 'error' => 'Internal server error']); } exit; } $auditLog->logTicketCreate($userId, $ticket_id, [ 'title' => $title, 'priority' => $priority, 'category' => $category, 'type' => $type, ]); if ($previousId !== null) { AutoTicketService::linkRecurrence($conn, $ticket_id, $previousId, (int)$userId); $historyText = AutoTicketService::historyComment($conn, $ticket_id, $previousId, $previous['closed_at'] ?? null); $commentStmt = $conn->prepare( "INSERT INTO ticket_comments (ticket_id, user_id, user_name, comment_text, markdown_enabled) VALUES (?, ?, ?, ?, 1)" ); $commentStmt->bind_param("siss", $ticket_id, $userId, $commentAuthor, $historyText); $commentStmt->execute(); $commentStmt->close(); $auditLog->log($userId, 'update', 'ticket', $previousId, [ 'reason' => "{$source} reported this problem again after the " . AutoTicketService::reopenWindowDays() . "-day reopen window; continued in {$ticket_id}", ]); } // New ticket created: refresh dashboard stats. (new StatsModel($conn))->invalidateCache(); $conn->commit(); Database::close(); require_once __DIR__ . '/helpers/NotificationHelper.php'; NotificationHelper::sendTicketNotification($ticket_id, [ 'title' => $title, 'priority' => $priority, 'category' => $category, 'type' => $type, 'status' => $status, ], 'automated'); $response = [ 'success' => true, 'ticket_id' => $ticket_id, 'message' => $previousId !== null ? "New ticket for a recurrence of {$previousId}" : 'Ticket created successfully', 'action' => $previousId !== null ? 'new_recurrence' : 'created', ]; if ($previousId !== null) { $response['previous_ticket_id'] = $previousId; } echo json_encode($response); // Done: only the deadlock `continue` above may run the loop again. // Falling through re-entered it on a closed connection, appending a // 500 error body after the success response for every new ticket. exit; }