other_ticket_id". Unlink also finds a link * recorded from the other ticket's side. * * Responses: 200 {success, ticket_id, relation, other_ticket_id[, removed]}; * 400 bad input; 404 a ticket missing or not visible to this key, or no such * link to remove; 409 already linked or a circular blocking chain. */ header('Content-Type: application/json'); require_once dirname(__DIR__) . '/helpers/ErrorHandler.php'; ErrorHandler::init(); require_once dirname(__DIR__) . '/middleware/RateLimitMiddleware.php'; RateLimitMiddleware::apply('api'); require_once dirname(__DIR__) . '/config/config.php'; require_once dirname(__DIR__) . '/helpers/Database.php'; require_once dirname(__DIR__) . '/middleware/ApiKeyAuth.php'; require_once dirname(__DIR__) . '/models/TicketModel.php'; require_once dirname(__DIR__) . '/services/DependencyService.php'; try { $conn = Database::getConnection(); } catch (Throwable $e) { error_log('ticket_link_api: DB connection failed: ' . $e->getMessage()); http_response_code(500); echo json_encode(['success' => false, 'error' => 'Internal server error']); exit; } $apiKeyAuth = new ApiKeyAuth($conn); try { $systemUser = $apiKeyAuth->authenticate(); } catch (Exception $e) { // ApiKeyAuth already sent the 401 response. exit; } // Linking is a write: reject 'read' keys with 403 before any mutation. $apiKeyAuth->requireScope('read_write'); if ($_SERVER['REQUEST_METHOD'] !== 'POST') { http_response_code(405); echo json_encode(['success' => false, 'error' => 'Method not allowed. Use POST.']); exit; } $data = json_decode(file_get_contents('php://input'), true); if (!is_array($data)) { http_response_code(400); echo json_encode(['success' => false, 'error' => 'Invalid JSON body']); exit; } $ticketId = trim((string)($data['ticket_id'] ?? '')); $otherId = trim((string)($data['other_ticket_id'] ?? '')); $relation = (string)($data['relation'] ?? ''); $action = strtolower(trim((string)($data['action'] ?? 'link'))); if ($ticketId === '' || $otherId === '' || $relation === '') { http_response_code(400); echo json_encode(['success' => false, 'error' => 'ticket_id, other_ticket_id and relation are required']); exit; } if (!in_array($action, ['link', 'unlink'], true)) { http_response_code(400); echo json_encode(['success' => false, 'error' => 'action must be "link" or "unlink"']); exit; } $context = $apiKeyAuth->getKeyContext(); $keyName = (string)($context['key_name'] ?? 'API'); // Keys see public tickets only unless marked see_all_visibility (#70), the // same rule as tickets_api.php. Check that first with the same synthetic // no-access user (user_id -1, so it can never match a creator or assignee), // answering a hidden ticket exactly like a missing one. if (empty($context['see_all_visibility'])) { $ticketModel = new TicketModel($conn); $visibilityUser = ['user_id' => -1, 'is_admin' => false, 'groups' => '']; foreach ([$ticketId, $otherId] as $id) { $ticket = ctype_digit($id) ? $ticketModel->getTicketById($id) : null; if (!$ticket || !$ticketModel->canUserAccessTicket($ticket, $visibilityUser)) { http_response_code(404); echo json_encode(['success' => false, 'error' => "Ticket {$id} not found"]); exit; } } } // The link is created and audited as the system user, like other API writes; // past the check above the key may act on both tickets. $actor = array_merge($systemUser, ['is_admin' => true]); $auditExtra = ['api_key' => $keyName]; $result = $action === 'unlink' ? DependencyService::unlink($conn, $actor, $ticketId, $relation, $otherId, $auditExtra) : DependencyService::link($conn, $actor, $ticketId, $relation, $otherId, $auditExtra); if (empty($result['success'])) { http_response_code((int)($result['http_status'] ?? 400)); echo json_encode(['success' => false, 'error' => $result['error'] ?? 'Request failed']); exit; } echo json_encode($result); exit;