Files
tinker_tickets/api/ticket_comment_api.php
T
jaredandClaude Sonnet 5 71bf64c1e2 Complete ErrorHandler rollout: wire into all endpoints, fix display_errors gaps, add styled 500 page (#38, #39, #105)
README documented ErrorHandler.php as a "global error/exception
handler", but ErrorHandler::init() had exactly one caller app-wide
(api/get_template.php). 13 endpoints never called
ini_set('display_errors', 0) at all, relying on the server's global
php.ini default, and index.php never registered any handler — a
genuine PHP fatal during a page render fell through to PHP's raw
default handling with no app-level 500 response, styled or otherwise.

Investigating the "13 endpoints" claim turned up that 9 of them
(assign_ticket.php, audit_log.php, check_duplicates.php,
get_comments.php, get_users.php, notifications.php, saved_filters.php,
user_preferences.php, watch_ticket.php) already require
api/bootstrap.php as their first statement, which itself calls
ini_set('display_errors', 0) — so they were never actually exposed;
the static grep just couldn't see through the require. The 3 that
were genuinely unprotected (bulk_operation.php, download_attachment.php,
health.php) are fixed here. ticket_dependencies.php already has its
own complete hand-rolled equivalent (shutdown handler, error handler,
exception handler, output-buffer aware) and was deliberately left
alone rather than risk double-registering handlers.

Rather than duplicate the fix 30+ times, wired ErrorHandler::init()
directly into api/bootstrap.php (covering all 9 files above at once)
and into each of the other endpoints' own ini_set/error_reporting
pair, replacing it in place — additive only: existing try/catch blocks
in every endpoint still handle what they already handled identically,
this only adds a safety net for genuinely uncaught fatals that fell
through everything else. Before doing this app-wide, removed
ErrorHandler::init()'s override of PHP's 'error_log' ini setting: it
redirected every error_log() call in the request to a fixed /tmp file,
which would have silently diverted logs away from wherever the server
is actually configured to send them the moment this got wired into
more than one endpoint. That override only existed to support
getRecentErrors(), which has zero callers app-wide.

For index.php (page views, not JSON), added an 'html' response mode to
ErrorHandler that renders a new views/error_500.php instead of a JSON
body. That view is deliberately self-contained (no layout_header.php,
no $GLOBALS/session/DB dependency) since a genuine fatal can happen
before config.php finishes loading or mid-session-start.

Verified: a real uncaught error with no prior output correctly
produces a clean JSON 500 (API mode) or the styled HTML page (page
mode) to the client while the full stack trace goes to error_log, not
the response; normal (non-fatal) requests through both a
bootstrap.php-based endpoint and index.php are byte-for-byte
unaffected. Full project phpcs pass is clean.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Lhz7pGMaoTfL5sdYS5XiKv
2026-09-11 12:17:15 -04:00

126 lines
3.9 KiB
PHP

<?php
/**
* ticket_comment_api.php — Bearer-key endpoint to post a comment on a ticket.
*
* POST only. Requires 'read_write' scope.
*
* Identity = PER-KEY LABEL: the comment author (ticket_comments.user_name) is the
* API key's key_name and the linked user_id is the key's created_by.
*
* Body (JSON): {
* "ticket_id": "NNN" (required),
* "comment_text": "..." (required, non-empty),
* "markdown_enabled": bool (optional)
* }
* Response: {success:true, comment_id:...}
*/
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__) . '/models/CommentModel.php';
require_once dirname(__DIR__) . '/models/AuditLogModel.php';
try {
$conn = Database::getConnection();
} catch (Throwable $e) {
error_log('ticket_comment_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 {
$apiKeyAuth->authenticate();
} catch (Exception $e) {
// ApiKeyAuth already sent the 401 response.
exit;
}
// Posting a comment 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;
}
$context = $apiKeyAuth->getKeyContext();
$keyName = $context['key_name'] ?? 'API';
$createdBy = ($context['created_by'] ?? null) !== null ? (int)$context['created_by'] : null;
$rawInput = file_get_contents('php://input');
$data = json_decode($rawInput, true);
if (!is_array($data)) {
http_response_code(400);
echo json_encode(['success' => false, 'error' => 'Invalid JSON body']);
exit;
}
$ticketId = isset($data['ticket_id']) ? trim((string)$data['ticket_id']) : '';
if ($ticketId === '') {
http_response_code(400);
echo json_encode(['success' => false, 'error' => 'ticket_id is required']);
exit;
}
$commentText = isset($data['comment_text']) ? trim((string)$data['comment_text']) : '';
if ($commentText === '') {
http_response_code(400);
echo json_encode(['success' => false, 'error' => 'comment_text is required']);
exit;
}
$markdownEnabled = !empty($data['markdown_enabled']);
// Validate the ticket exists.
$ticketModel = new TicketModel($conn);
$ticket = $ticketModel->getTicketById($ticketId);
if (!$ticket) {
http_response_code(404);
echo json_encode(['success' => false, 'error' => 'Ticket not found']);
exit;
}
// Post the comment under the key's label / owner.
$commentModel = new CommentModel($conn);
$result = $commentModel->addComment($ticketId, [
'user_name' => $keyName,
'comment_text' => $commentText,
'markdown_enabled' => $markdownEnabled,
], $createdBy);
if (empty($result['success'])) {
error_log('ticket_comment_api: addComment failed for ticket ' . $ticketId
. ': ' . ($result['error'] ?? 'unknown'));
http_response_code(500);
echo json_encode(['success' => false, 'error' => 'Failed to add comment']);
exit;
}
$commentId = $result['comment_id'] ?? null;
// Audit trail (action 'comment' / entity 'comment' are both whitelisted).
$auditLog = new AuditLogModel($conn);
$auditLog->log($createdBy, 'comment', 'comment', (string)$commentId, [
'ticket_id' => $ticketId,
'key_name' => $keyName,
'via_api' => true,
]);
echo json_encode(['success' => true, 'comment_id' => $commentId]);
exit;