Compare commits

...
Author SHA1 Message Date
jaredandClaude Opus 4.8 e0e92e326a Quick-win fixes from second review
Security / PHP Security (semgrep) (push) Successful in 1m27s
Lint / Deploy (push) Successful in 4s
Lint / Notify on failure (push) Has been skipped
Lint / PHP (phpcs PSR-12) (push) Successful in 20s
Lint / JS (eslint) (push) Successful in 9s
Lint / PHP requirements (version + extensions) (push) Successful in 38s
- create_ticket_api.php: validate status (against TICKET_STATUSES) and
  priority (numeric 1-5). A non-numeric priority previously cast to 0 and
  escalated the ticket below P1 on the dedup/update path.
- manage_workflows.php: reject empty/invalid from_status/to_status on POST
  and PUT (must be valid ticket statuses) so the workflow table can't be
  populated with bogus transitions.
- TicketModel::getAllTickets: COUNT(*) OVER() rides on returned rows, so a
  page past the last row returned total/pages = 0. Fall back to a direct
  COUNT when an over-range page yields no rows, keeping pager math correct.
- DashboardView: stop double-escaping category/type/assigned active-filter
  labels (they were htmlspecialchars'd into the label and again at output,
  rendering R&D as R&D); output escaping is retained.
- check_duplicates.php / NotificationHelper::notifyWatchers: wrap the DB
  lookups in try/catch so a failed prepare/query degrades gracefully
  (advisory dup-check returns none; best-effort watcher notify is skipped)
  instead of fataling the request. Works whether mysqli throws or returns
  false. (manage_* endpoints already have a top-level try/catch.)

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-30 12:26:28 -04:00
jaredandClaude Opus 4.8 4164f85051 Fix bugs found in second multi-agent review
Security / PHP Security (semgrep) (push) Successful in 1m14s
Lint / Deploy (push) Successful in 3s
Lint / PHP (phpcs PSR-12) (push) Successful in 19s
Lint / JS (eslint) (push) Successful in 8s
Lint / PHP requirements (version + extensions) (push) Successful in 24s
Lint / Notify on failure (push) Has been skipped
XSS / security:
- markdown.js: sanitize footnote labels to a safe slug before using them in
  id/href attributes. Labels are captured before the HTML-escape pass, so a
  label like x"><img onerror=...> broke out → stored XSS (the earlier quote-
  escape fix didn't cover this path). Verified neutralized.
- RateLimitMiddleware: only trust X-Forwarded-For / X-Real-IP when REMOTE_ADDR
  is a configured trusted proxy, and use the rightmost (proxy-appended) entry.
  Previously any client could rotate XFF to escape the per-IP rate limit.
- .env.example: document TRUSTED_PROXIES so fresh deploys aren't fail-open on
  the Authelia forward-auth spoofing protection.

Correctness:
- notifications.php: my previous assigned-to LIKE fix anchored only on '}', so
  BULK assignments (logged {"assigned_to":N,"bulk_operation_id":..}) produced
  no "assigned to you" notification — now matches both '}' and ',' delimiters.
- notifications.php: implement the documented @mention notifications (query
  action_type='mention' rows for the current user); they were never delivered.
- NotificationHelper::notifyWatchers: guard unchecked prepare() so a missing
  ticket_watchers table can't fatal the request after its DB write committed.
- AuditLogModel::getTicketTimeline: JSON_UNQUOTE the extracted ticket_id so
  comment events actually match (string vs JSON-number comparison never did).
- AuditLogModel/audit_log.php: CSV export no longer silently truncates to the
  1000-row UI cap; uses a dedicated higher export limit.
- DashboardView: quick-preview drawer read .ticket-link from the title cell
  (which has none), so the title was always blank — use the cell text.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-30 12:00:36 -04:00
12 changed files with 196 additions and 53 deletions
+8
View File
@@ -24,6 +24,14 @@ APP_DOMAIN=
# Include all domains that can access this application # Include all domains that can access this application
ALLOWED_HOSTS=localhost,127.0.0.1 ALLOWED_HOSTS=localhost,127.0.0.1
# Trusted reverse proxy IP(s), comma-separated (e.g. the Authelia/nginx proxy).
# STRONGLY RECOMMENDED in production: Authelia forward-auth (Remote-User /
# Remote-Groups) and forwarded client IPs are only trusted when REMOTE_ADDR is
# in this list. Leaving it empty disables that protection (relies solely on
# network topology) and lets anything reaching PHP directly spoof admin login.
# Exact IP match only (no CIDR). Example: TRUSTED_PROXIES=10.10.10.27
TRUSTED_PROXIES=
# Timezone (default: America/New_York) # Timezone (default: America/New_York)
TIMEZONE=America/New_York TIMEZONE=America/New_York
+4 -2
View File
@@ -46,8 +46,10 @@ if ($_SERVER['REQUEST_METHOD'] === 'GET') {
$filters['ip_address'] = $_GET['ip_address']; $filters['ip_address'] = $_GET['ip_address'];
} }
// Get all matching logs (no limit for CSV export) // Get all matching logs for export. The forExport flag raises the cap
$result = $auditLogModel->getFilteredLogs($filters, 10000, 0); // (model clamps to its export limit) so the CSV isn't silently truncated
// to the 1000-row UI page limit.
$result = $auditLogModel->getFilteredLogs($filters, PHP_INT_MAX, 0, true);
$logs = $result['logs']; $logs = $result['logs'];
// Set CSV headers // Set CSV headers
+17 -5
View File
@@ -50,12 +50,24 @@ $sql = "SELECT ticket_id, title, status, priority, created_at
$types = "ss" . $visFilter['types']; $types = "ss" . $visFilter['types'];
$params = array_merge([$searchTerm, $soundexTitle], $visFilter['params']); $params = array_merge([$searchTerm, $soundexTitle], $visFilter['params']);
$stmt = $conn->prepare($sql);
if (!empty($params)) { // Duplicate detection is advisory (it must not block ticket creation), so on any
$stmt->bind_param($types, ...$params); // DB error degrade gracefully to "no duplicates" rather than fataling the request.
// mysqli may throw (default exception mode) or return false depending on config.
try {
$stmt = $conn->prepare($sql);
if (!$stmt) {
throw new RuntimeException('prepare failed: ' . $conn->error);
}
if (!empty($params)) {
$stmt->bind_param($types, ...$params);
}
$stmt->execute();
$result = $stmt->get_result();
} catch (Throwable $e) {
error_log('check_duplicates: ' . $e->getMessage());
ResponseHelper::success(['duplicates' => []]);
} }
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) { while ($row = $result->fetch_assoc()) {
// Calculate similarity score // Calculate similarity score
+18
View File
@@ -82,6 +82,15 @@ try {
case 'POST': case 'POST':
$data = json_decode(file_get_contents('php://input'), true); $data = json_decode(file_get_contents('php://input'), true);
$wfValid = $GLOBALS['config']['TICKET_STATUSES'] ?? ['Open', 'Pending', 'In Progress', 'Closed'];
if (
!in_array($data['from_status'] ?? '', $wfValid, true)
|| !in_array($data['to_status'] ?? '', $wfValid, true)
) {
http_response_code(400);
echo json_encode(['success' => false, 'error' => 'from_status and to_status must be valid ticket statuses']);
exit;
}
if (($data['from_status'] ?? '') === ($data['to_status'] ?? '')) { if (($data['from_status'] ?? '') === ($data['to_status'] ?? '')) {
http_response_code(400); http_response_code(400);
echo json_encode(['success' => false, 'error' => 'From Status and To Status cannot be the same']); echo json_encode(['success' => false, 'error' => 'From Status and To Status cannot be the same']);
@@ -125,6 +134,15 @@ try {
$data = json_decode(file_get_contents('php://input'), true); $data = json_decode(file_get_contents('php://input'), true);
$wfValid = $GLOBALS['config']['TICKET_STATUSES'] ?? ['Open', 'Pending', 'In Progress', 'Closed'];
if (
!in_array($data['from_status'] ?? '', $wfValid, true)
|| !in_array($data['to_status'] ?? '', $wfValid, true)
) {
http_response_code(400);
echo json_encode(['success' => false, 'error' => 'from_status and to_status must be valid ticket statuses']);
exit;
}
if (($data['from_status'] ?? '') === ($data['to_status'] ?? '')) { if (($data['from_status'] ?? '') === ($data['to_status'] ?? '')) {
http_response_code(400); http_response_code(400);
echo json_encode(['success' => false, 'error' => 'From Status and To Status cannot be the same']); echo json_encode(['success' => false, 'error' => 'From Status and To Status cannot be the same']);
+32 -6
View File
@@ -55,15 +55,18 @@ $assignSql = "SELECT
AND al.entity_type = 'ticket' AND al.entity_type = 'ticket'
AND al.user_id != ? AND al.user_id != ?
AND al.created_at >= DATE_SUB(NOW(), INTERVAL 7 DAY) AND al.created_at >= DATE_SUB(NOW(), INTERVAL 7 DAY)
AND al.details LIKE ? AND (al.details LIKE ? OR al.details LIKE ?)
ORDER BY al.created_at DESC ORDER BY al.created_at DESC
LIMIT 15"; LIMIT 15";
// Match the exact JSON value with a trailing delimiter so user 12 doesn't also // Match the exact JSON value with a trailing delimiter so user 12 doesn't also
// match 120/123/etc. The assign detail is logged as {"assigned_to":<int>}. // match 120/123/etc. Single assigns log {"assigned_to":5} (closing brace) while
$assignLike = '%"assigned_to":' . (int)$userId . '}%'; // bulk assigns log {"assigned_to":5,"bulk_operation_id":N} (comma) — match both.
$assignId = (int)$userId;
$assignEnd = '%"assigned_to":' . $assignId . '}%';
$assignMid = '%"assigned_to":' . $assignId . ',%';
$stmt = $conn->prepare($assignSql); $stmt = $conn->prepare($assignSql);
$stmt->bind_param('is', $userId, $assignLike); $stmt->bind_param('iss', $userId, $assignEnd, $assignMid);
$stmt->execute(); $stmt->execute();
$assignRows = $stmt->get_result()->fetch_all(MYSQLI_ASSOC); $assignRows = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$stmt->close(); $stmt->close();
@@ -150,10 +153,32 @@ $stmt->execute();
$statusRows = $stmt->get_result()->fetch_all(MYSQLI_ASSOC); $statusRows = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$stmt->close(); $stmt->close();
// Query 4: @mentions of me (logged by add_comment.php as
// action_type='mention', entity_type='user', entity_id=<mentioned user_id>).
$mentionSql = "SELECT
al.audit_id AS log_id, al.action_type, al.entity_type, al.entity_id, al.details, al.created_at,
COALESCE(u.display_name, u.username, 'System') AS actor_name
FROM audit_log al
LEFT JOIN users u ON al.user_id = u.user_id
WHERE al.action_type = 'mention'
AND al.entity_type = 'user'
AND al.entity_id = ?
AND al.user_id != ?
AND al.created_at >= DATE_SUB(NOW(), INTERVAL 7 DAY)
ORDER BY al.created_at DESC
LIMIT 15";
$mentionEntityId = (string)$userId;
$stmt = $conn->prepare($mentionSql);
$stmt->bind_param('si', $mentionEntityId, $userId);
$stmt->execute();
$mentionRows = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$stmt->close();
// Merge, deduplicate by log_id, sort by created_at desc // Merge, deduplicate by log_id, sort by created_at desc
$all = []; $all = [];
$seen = []; $seen = [];
foreach (array_merge($assignRows, $commentRows, $statusRows) as $row) { foreach (array_merge($assignRows, $commentRows, $statusRows, $mentionRows) as $row) {
$id = (int)$row['log_id']; $id = (int)$row['log_id'];
if (isset($seen[$id])) { if (isset($seen[$id])) {
continue; continue;
@@ -172,7 +197,7 @@ foreach ($all as $row) {
$actionType = ($row['action_type'] === 'create' && $row['entity_type'] === 'comment') $actionType = ($row['action_type'] === 'create' && $row['entity_type'] === 'comment')
? 'comment' ? 'comment'
: $row['action_type']; : $row['action_type'];
$ticketId = ($actionType === 'comment') $ticketId = ($actionType === 'comment' || $actionType === 'mention')
? ($details['ticket_id'] ?? 0) ? ($details['ticket_id'] ?? 0)
: $row['entity_id']; : $row['entity_id'];
$isRead = $lastSeen && $row['created_at'] <= $lastSeen; $isRead = $lastSeen && $row['created_at'] <= $lastSeen;
@@ -181,6 +206,7 @@ foreach ($all as $row) {
$title = match ($actionType) { $title = match ($actionType) {
'assign' => "{$row['actor_name']} assigned ticket #{$ticketId} to you", 'assign' => "{$row['actor_name']} assigned ticket #{$ticketId} to you",
'comment' => "{$row['actor_name']} commented on ticket #{$ticketId}", 'comment' => "{$row['actor_name']} commented on ticket #{$ticketId}",
'mention' => "{$row['actor_name']} mentioned you on ticket #{$ticketId}",
'update' => (function () use ($row, $details, $ticketId) { 'update' => (function () use ($row, $details, $ticketId) {
// logTicketUpdate stores delta as {"status": {"from": "Open", "to": "In Progress"}} // logTicketUpdate stores delta as {"status": {"from": "Open", "to": "In Progress"}}
$from = $details['status']['from'] ?? ($details['old_value'] ?? '?'); $from = $details['status']['from'] ?? ($details['old_value'] ?? '?');
+10 -3
View File
@@ -6,6 +6,13 @@
function parseMarkdown(markdown) { function parseMarkdown(markdown) {
if (!markdown) return ''; if (!markdown) return '';
// Footnote labels are captured before the HTML-escape pass, so they must be
// sanitized to a safe slug before being interpolated into id/href attributes
// (otherwise a label like `x"><img onerror=...>` breaks out → stored XSS).
var fnSlug = function (label) {
return String(label).replace(/[^a-zA-Z0-9_-]/g, '-');
};
// Footnotes — collect definitions and mark references with placeholders // Footnotes — collect definitions and mark references with placeholders
// (must happen before HTML escaping so <sup> tags don't get escaped) // (must happen before HTML escaping so <sup> tags don't get escaped)
const footnotes = {}; const footnotes = {};
@@ -146,7 +153,7 @@ function parseMarkdown(markdown) {
// Restore footnote reference placeholders // Restore footnote reference placeholders
fnRefs.forEach(function(ref, i) { fnRefs.forEach(function(ref, i) {
html = html.replace('%%FNREF' + i + '%%', html = html.replace('%%FNREF' + i + '%%',
'<sup class="fn-ref"><a href="#fn-' + ref.label + '" id="fnref-' + ref.label + '">[' + ref.n + ']</a></sup>'); '<sup class="fn-ref"><a href="#fn-' + fnSlug(ref.label) + '" id="fnref-' + fnSlug(ref.label) + '">[' + ref.n + ']</a></sup>');
}); });
// Wrap in paragraph if not already wrapped // Wrap in paragraph if not already wrapped
@@ -158,9 +165,9 @@ function parseMarkdown(markdown) {
if (footnoteOrder.length) { if (footnoteOrder.length) {
html += '<hr class="fn-hr"><ol class="fn-list">'; html += '<hr class="fn-hr"><ol class="fn-list">';
footnoteOrder.forEach(function(label, i) { footnoteOrder.forEach(function(label, i) {
html += '<li id="fn-' + label + '" class="fn-item">' + html += '<li id="fn-' + fnSlug(label) + '" class="fn-item">' +
parseMarkdown(footnotes[label]).replace(/<\/?p>/g, '') + parseMarkdown(footnotes[label]).replace(/<\/?p>/g, '') +
' <a href="#fnref-' + label + '" class="fn-back">&#x21A9;</a></li>'; ' <a href="#fnref-' + fnSlug(label) + '" class="fn-back">&#x21A9;</a></li>';
}); });
html += '</ol>'; html += '</ol>';
} }
+16
View File
@@ -231,6 +231,22 @@ $priority = $data['priority'] ?? '4';
$category = (string)($data['category'] ?? 'General'); $category = (string)($data['category'] ?? 'General');
$type = (string)($data['type'] ?? 'Issue'); $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;
$ticketHash = generateTicketHash($data); $ticketHash = generateTicketHash($data);
$auditLog = new AuditLogModel($conn); $auditLog = new AuditLogModel($conn);
+31 -16
View File
@@ -164,23 +164,38 @@ class NotificationHelper
return; return;
} }
// Fetch watcher usernames, excluding the actor so they don't notify themselves // Fetch watcher usernames, excluding the actor so they don't notify
if ($excludeUserId !== null) { // themselves. Notifications are best-effort: if the watchers table is
$sql = "SELECT u.username FROM ticket_watchers tw JOIN users u ON tw.user_id = u.user_id WHERE tw.ticket_id = ? AND tw.user_id != ?"; // absent or the query fails, skip silently rather than fataling the
$stmt = $conn->prepare($sql); // request that already committed its DB change. mysqli may either throw
$stmt->bind_param("ii", $ticketId, $excludeUserId); // (default exception mode) or return false, so handle both.
} else {
$sql = "SELECT u.username FROM ticket_watchers tw JOIN users u ON tw.user_id = u.user_id WHERE tw.ticket_id = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $ticketId);
}
$stmt->execute();
$result = $stmt->get_result();
$stmt->close();
$usernames = []; $usernames = [];
while ($row = $result->fetch_assoc()) { try {
$usernames[] = $row['username']; if ($excludeUserId !== null) {
$sql = "SELECT u.username FROM ticket_watchers tw JOIN users u ON tw.user_id = u.user_id WHERE tw.ticket_id = ? AND tw.user_id != ?";
$stmt = $conn->prepare($sql);
} else {
$sql = "SELECT u.username FROM ticket_watchers tw JOIN users u ON tw.user_id = u.user_id WHERE tw.ticket_id = ?";
$stmt = $conn->prepare($sql);
}
if (!$stmt) {
return;
}
if ($excludeUserId !== null) {
$stmt->bind_param("ii", $ticketId, $excludeUserId);
} else {
$stmt->bind_param("i", $ticketId);
}
$stmt->execute();
$result = $stmt->get_result();
$stmt->close();
while ($row = $result->fetch_assoc()) {
$usernames[] = $row['username'];
}
} catch (\Throwable $e) {
error_log('NotificationHelper::notifyWatchers watcher lookup failed: ' . $e->getMessage());
return;
} }
if (empty($usernames)) { if (empty($usernames)) {
+23 -11
View File
@@ -41,19 +41,31 @@ class RateLimitMiddleware
*/ */
private static function getClientIp(): string private static function getClientIp(): string
{ {
// Check for forwarded IP (behind proxy/load balancer) $remoteAddr = $_SERVER['REMOTE_ADDR'] ?? '127.0.0.1';
$headers = ['HTTP_X_FORWARDED_FOR', 'HTTP_X_REAL_IP', 'HTTP_CLIENT_IP'];
foreach ($headers as $header) { // Forwarded headers are client-controlled, so only believe them when the
if (!empty($_SERVER[$header])) { // request actually came from a trusted reverse proxy. Otherwise a client
// Take the first IP in a comma-separated list // could rotate X-Forwarded-For each request to escape the per-IP limit.
$ips = explode(',', $_SERVER[$header]); $trusted = $GLOBALS['config']['TRUSTED_PROXIES'] ?? [];
$ip = trim($ips[0]); if (empty($trusted) || !in_array($remoteAddr, $trusted, true)) {
if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) { return $remoteAddr;
return $ip; }
}
// The trusted proxy appends the connecting client to X-Forwarded-For, so
// the RIGHTMOST entry is the IP it observed (a client-supplied prefix is
// not trustworthy). X-Real-IP is set by the proxy itself.
if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$ips = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
$ip = trim(end($ips));
if (filter_var($ip, FILTER_VALIDATE_IP)) {
return $ip;
} }
} }
return $_SERVER['REMOTE_ADDR'] ?? '127.0.0.1'; if (!empty($_SERVER['HTTP_X_REAL_IP']) && filter_var($_SERVER['HTTP_X_REAL_IP'], FILTER_VALIDATE_IP)) {
return trim($_SERVER['HTTP_X_REAL_IP']);
}
return $remoteAddr;
} }
/** /**
+10 -6
View File
@@ -10,6 +10,9 @@ class AuditLogModel
/** @var int Maximum allowed limit for pagination */ /** @var int Maximum allowed limit for pagination */
private const MAX_LIMIT = 1000; private const MAX_LIMIT = 1000;
/** @var int Maximum rows for a CSV/forensic export (higher than the UI cap) */
private const EXPORT_LIMIT = 100000;
/** @var int Default limit for pagination */ /** @var int Default limit for pagination */
private const DEFAULT_LIMIT = 100; private const DEFAULT_LIMIT = 100;
@@ -36,12 +39,12 @@ class AuditLogModel
* @param int $limit Requested limit * @param int $limit Requested limit
* @return int Validated limit * @return int Validated limit
*/ */
private function validateLimit(int $limit): int private function validateLimit(int $limit, int $max = self::MAX_LIMIT): int
{ {
if ($limit < 1) { if ($limit < 1) {
return self::DEFAULT_LIMIT; return self::DEFAULT_LIMIT;
} }
return min($limit, self::MAX_LIMIT); return min($limit, $max);
} }
/** /**
@@ -534,7 +537,7 @@ class AuditLogModel
FROM audit_log al FROM audit_log al
LEFT JOIN users u ON al.user_id = u.user_id LEFT JOIN users u ON al.user_id = u.user_id
WHERE (al.entity_type = 'ticket' AND al.entity_id = ?) WHERE (al.entity_type = 'ticket' AND al.entity_id = ?)
OR (al.entity_type = 'comment' AND JSON_EXTRACT(al.details, '$.ticket_id') = ?) OR (al.entity_type = 'comment' AND JSON_UNQUOTE(JSON_EXTRACT(al.details, '$.ticket_id')) = ?)
ORDER BY al.created_at DESC" ORDER BY al.created_at DESC"
); );
$stmt->bind_param("ss", $ticketId, $ticketId); $stmt->bind_param("ss", $ticketId, $ticketId);
@@ -561,10 +564,11 @@ class AuditLogModel
* @param int $offset Offset for pagination * @param int $offset Offset for pagination
* @return array Array containing logs and total count * @return array Array containing logs and total count
*/ */
public function getFilteredLogs($filters = [], $limit = 50, $offset = 0) public function getFilteredLogs($filters = [], $limit = 50, $offset = 0, $forExport = false)
{ {
// Validate pagination parameters // Validate pagination parameters. Exports allow a much higher cap so a
$limit = $this->validateLimit((int)$limit); // forensic/compliance CSV isn't silently truncated to the UI page limit.
$limit = $this->validateLimit((int)$limit, $forExport ? self::EXPORT_LIMIT : self::MAX_LIMIT);
$offset = $this->validateOffset((int)$offset); $offset = $this->validateOffset((int)$offset);
$whereConditions = []; $whereConditions = [];
+23
View File
@@ -208,6 +208,11 @@ class TicketModel
ORDER BY $sortExpression $sortDirection ORDER BY $sortExpression $sortDirection
LIMIT ? OFFSET ?"; LIMIT ? OFFSET ?";
// Keep a copy of the filter params (without LIMIT/OFFSET) for the
// fallback COUNT below.
$countParams = $params;
$countParamTypes = $paramTypes;
$params[] = $limit; $params[] = $limit;
$params[] = $offset; $params[] = $offset;
$paramTypes .= 'ii'; $paramTypes .= 'ii';
@@ -228,6 +233,24 @@ class TicketModel
} }
$stmt->close(); $stmt->close();
// COUNT(*) OVER() rides on returned rows, so a page past the last row
// yields zero rows and a bogus total of 0. Fall back to a direct COUNT
// so the total/pages stay correct for stale or over-range page links.
if ($totalTickets === 0 && $offset > 0) {
$countSql = "SELECT COUNT(*) AS c
FROM tickets t
LEFT JOIN users u_created ON t.created_by = u_created.user_id
LEFT JOIN users u_assigned ON t.assigned_to = u_assigned.user_id
$whereClause";
$countStmt = $this->conn->prepare($countSql);
if (!empty($countParams)) {
$countStmt->bind_param($countParamTypes, ...$countParams);
}
$countStmt->execute();
$totalTickets = (int)($countStmt->get_result()->fetch_assoc()['c'] ?? 0);
$countStmt->close();
}
return [ return [
'tickets' => $tickets, 'tickets' => $tickets,
'total' => $totalTickets, 'total' => $totalTickets,
+4 -4
View File
@@ -48,14 +48,14 @@ if (!empty($_GET['priority'])) {
} }
} }
if (!empty($_GET['category'])) { if (!empty($_GET['category'])) {
$activeFilters[] = ['type' => 'category', 'value' => $_GET['category'], 'label' => 'Category: ' . htmlspecialchars($_GET['category'])]; $activeFilters[] = ['type' => 'category', 'value' => $_GET['category'], 'label' => 'Category: ' . $_GET['category']];
} }
if (!empty($_GET['type'])) { if (!empty($_GET['type'])) {
$activeFilters[] = ['type' => 'type', 'value' => $_GET['type'], 'label' => 'Type: ' . htmlspecialchars($_GET['type'])]; $activeFilters[] = ['type' => 'type', 'value' => $_GET['type'], 'label' => 'Type: ' . $_GET['type']];
} }
if (!empty($_GET['assigned_to'])) { if (!empty($_GET['assigned_to'])) {
$label = match ($_GET['assigned_to']) { $label = match ($_GET['assigned_to']) {
'unassigned' => 'Unassigned', 'me' => 'Me', default => 'User #' . htmlspecialchars($_GET['assigned_to']) 'unassigned' => 'Unassigned', 'me' => 'Me', default => 'User #' . $_GET['assigned_to']
}; };
$activeFilters[] = ['type' => 'assigned_to', 'value' => $_GET['assigned_to'], 'label' => 'Assigned: ' . $label]; $activeFilters[] = ['type' => 'assigned_to', 'value' => $_GET['assigned_to'], 'label' => 'Assigned: ' . $label];
} }
@@ -1342,7 +1342,7 @@ if (advForm) advForm.addEventListener('submit', function(e) {
var o = hasCheckbox ? 1 : 0; // column offset for checkbox col var o = hasCheckbox ? 1 : 0; // column offset for checkbox col
var priority = cells[1 + o] ? cells[1 + o].textContent.trim() : ''; var priority = cells[1 + o] ? cells[1 + o].textContent.trim() : '';
var title = cells[2 + o] ? cells[2 + o].querySelector('.ticket-link')?.textContent.trim() || '' : ''; var title = cells[2 + o] ? cells[2 + o].textContent.trim() : '';
var category = cells[3 + o] ? cells[3 + o].textContent.trim() : ''; var category = cells[3 + o] ? cells[3 + o].textContent.trim() : '';
var typeVal = cells[4 + o] ? cells[4 + o].textContent.trim() : ''; var typeVal = cells[4 + o] ? cells[4 + o].textContent.trim() : '';
var status = cells[5 + o] ? cells[5 + o].textContent.trim().replace(/^\s*●\s*/, '') : ''; var status = cells[5 + o] ? cells[5 + o].textContent.trim().replace(/^\s*●\s*/, '') : '';