Fix API correctness: external API stub/collision, recurring dates, CSV, audit

- create_ticket_api.php: remove the wrong CREATE TABLE stub that broke a
  fresh DB; generate collision-safe ticket_ids so a genuine id collision
  isn't misreported as a duplicate and a hw alert dropped; stop leaking
  raw DB errors; correct a reopen comment that falsely claimed refreshed
  sensor data
- manage_recurring.php: fix next-run so create/edit no longer skips the
  current period (monthly day-of-month this month, daily today if time
  not passed, correct ISO weekday, month-length clamp); only recompute
  on schedule changes to avoid double-fire
- export_tickets.php, audit_log.php: neutralize CSV formula injection
- revoke_api_key.php, generate_api_key.php: correct HTTP status codes and
  stop the catch clobbering specific 4xx codes
- health.php: stop leaking PHP version / extension names / paths to
  unauthenticated callers
- watch_ticket.php: define $data before use
- manage_templates/recurring/custom_fields: add audit logging for CRUD;
  add recurring_ticket + custom_field to the audit entity whitelist

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
2026-07-10 12:26:39 -04:00
co-authored by Claude Opus 4.8
parent 327c225ded
commit d11cb989bf
11 changed files with 322 additions and 68 deletions
+123 -26
View File
@@ -15,6 +15,7 @@ try {
require_once dirname(__DIR__) . '/config/config.php';
require_once dirname(__DIR__) . '/helpers/Database.php';
require_once dirname(__DIR__) . '/models/RecurringTicketModel.php';
require_once dirname(__DIR__) . '/models/AuditLogModel.php';
// Check authentication
if (session_status() === PHP_SESSION_NONE) {
@@ -52,6 +53,7 @@ try {
header('Content-Type: application/json');
$model = new RecurringTicketModel($conn);
$auditLog = new AuditLogModel($conn);
$method = $_SERVER['REQUEST_METHOD'];
$id = isset($_GET['id']) ? (int)$_GET['id'] : null;
$action = isset($_GET['action']) ? $_GET['action'] : null;
@@ -70,6 +72,12 @@ try {
case 'POST':
if ($action === 'toggle' && $id) {
$result = $model->toggleActive($id);
if (!empty($result['success'])) {
$auditLog->log($currentUserId, 'update', 'recurring_ticket', (string)$id, [
'entity' => 'recurring_ticket',
'action' => 'toggle_active'
]);
}
echo json_encode($result);
} else {
$data = json_decode(file_get_contents('php://input'), true);
@@ -90,6 +98,14 @@ try {
$data['created_by'] = $currentUserId;
$result = $model->create($data);
if (!empty($result['success'])) {
$auditLog->log($currentUserId, 'create', 'recurring_ticket', (string)($result['recurring_id'] ?? ''), [
'title_template' => $data['title_template'],
'schedule_type' => $data['schedule_type'],
'schedule_day' => $data['schedule_day'] ?? null,
'schedule_time' => $data['schedule_time'] ?? '09:00'
]);
}
echo json_encode($result);
}
break;
@@ -106,16 +122,49 @@ try {
exit;
}
// Recalculate next run time if schedule changed
$nextRun = calculateNextRun(
$data['schedule_type'],
$data['schedule_day'] ?? null,
$data['schedule_time'] ?? '09:00'
);
$data['next_run_at'] = $nextRun;
$existing = $model->getById($id);
if (!$existing) {
echo json_encode(['success' => false, 'error' => 'Recurring ticket not found']);
exit;
}
$newDay = $data['schedule_day'] ?? null;
$newTime = $data['schedule_time'] ?? '09:00';
// Only the schedule fields affect when the next occurrence fires.
$scheduleChanged =
(string)$existing['schedule_type'] !== (string)$data['schedule_type']
|| (string)($existing['schedule_day'] ?? '') !== (string)($newDay ?? '')
|| substr((string)$existing['schedule_time'], 0, 5) !== substr((string)$newTime, 0, 5);
$existingNextFuture = !empty($existing['next_run_at'])
&& strtotime($existing['next_run_at']) > time();
// Recompute only when the schedule actually changed (or the stored
// next_run is already in the past). Editing an unrelated field (e.g.
// title) must NOT move next_run_at backwards past an occurrence that
// may already have fired, which would double-create a ticket.
if ($scheduleChanged || !$existingNextFuture) {
$data['next_run_at'] = calculateNextRun(
$data['schedule_type'],
$newDay,
$newTime
);
} else {
$data['next_run_at'] = $existing['next_run_at'];
}
$data['is_active'] = isset($data['is_active']) ? (int)$data['is_active'] : 1;
$result = $model->update($id, $data);
if (!empty($result['success'])) {
$auditLog->log($currentUserId, 'update', 'recurring_ticket', (string)$id, [
'entity' => 'recurring_ticket',
'title_template' => $data['title_template'] ?? null,
'schedule_type' => $data['schedule_type'],
'schedule_day' => $newDay,
'schedule_time' => $newTime
]);
}
echo json_encode($result);
break;
@@ -125,7 +174,14 @@ try {
exit;
}
$toDelete = $model->getById($id);
$result = $model->delete($id);
if (!empty($result['success'])) {
$auditLog->log($currentUserId, 'delete', 'recurring_ticket', (string)$id, [
'entity' => 'recurring_ticket',
'title_template' => $toDelete['title_template'] ?? 'unknown'
]);
}
echo json_encode($result);
break;
@@ -139,36 +195,77 @@ try {
echo json_encode(['success' => false, 'error' => 'An internal error occurred']);
}
function calculateNextRun($scheduleType, $scheduleDay, $scheduleTime)
/**
* Compute the SOONEST FUTURE occurrence matching the schedule.
*
* Returns 'Y-m-d H:i:s' in the app-configured timezone. The current period is
* NOT skipped: a schedule whose time today/this-month is still in the future
* fires then, not one period later.
*
* @param string $scheduleType daily|weekly|monthly
* @param int|null $scheduleDay 1-7 (ISO, 1=Mon..7=Sun) weekly; 1-31 monthly
* @param string $scheduleTime HH:MM or HH:MM:SS
* @param DateTime|null $now Injected "now" for testing
*/
function calculateNextRun($scheduleType, $scheduleDay, $scheduleTime, ?DateTime $now = null)
{
$now = new DateTime();
$time = $scheduleTime ?: '09:00';
$tz = new DateTimeZone($GLOBALS['config']['TIMEZONE'] ?? date_default_timezone_get());
$now = $now ? $now : new DateTime('now', $tz);
$parts = explode(':', $scheduleTime ?: '09:00');
$hour = (int)($parts[0] ?? 9);
$minute = (int)($parts[1] ?? 0);
$second = (int)($parts[2] ?? 0);
$next = clone $now;
switch ($scheduleType) {
case 'daily':
$next = new DateTime('tomorrow ' . $time);
break;
case 'weekly':
$days = [1 => 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];
$dayName = $days[(int)$scheduleDay] ?? 'Monday';
$next = new DateTime("next {$dayName} " . $time);
$targetDow = (int)$scheduleDay;
if ($targetDow < 1 || $targetDow > 7) {
$targetDow = 1;
}
$next->setTime($hour, $minute, $second);
$currentDow = (int)$next->format('N'); // 1=Mon .. 7=Sun
$daysAhead = ($targetDow - $currentDow + 7) % 7;
// Same weekday but the time already passed today -> next week.
if ($daysAhead === 0 && $next <= $now) {
$daysAhead = 7;
}
if ($daysAhead > 0) {
$next->modify("+{$daysAhead} day");
$next->setTime($hour, $minute, $second);
}
break;
case 'monthly':
$day = max(1, min(31, (int)$scheduleDay));
$next = new DateTime();
$next->modify('first day of next month');
// Clamp to last day of target month (handles Feb, 30-day months)
$daysInMonth = (int)$next->format('t');
$day = min($day, $daysInMonth);
$next->setDate((int)$next->format('Y'), (int)$next->format('m'), $day);
$parts = explode(':', $time . ':00'); // ensure at least H:M
$next->setTime((int)$parts[0], (int)$parts[1], 0);
// This month first, clamped to the month's length (e.g. day 31 -> Feb 28/29).
$daysInMonth = (int)$now->format('t');
$next->setDate((int)$now->format('Y'), (int)$now->format('n'), min($day, $daysInMonth));
$next->setTime($hour, $minute, $second);
if ($next <= $now) {
// Already passed this month -> first day of next month, then clamp.
$firstNext = clone $now;
$firstNext->modify('first day of next month');
$daysInMonth = (int)$firstNext->format('t');
$next->setDate(
(int)$firstNext->format('Y'),
(int)$firstNext->format('n'),
min($day, $daysInMonth)
);
$next->setTime($hour, $minute, $second);
}
break;
case 'daily':
default:
$next = new DateTime('tomorrow ' . $time);
$next->setTime($hour, $minute, $second);
if ($next <= $now) {
$next->modify('+1 day');
$next->setTime($hour, $minute, $second);
}
break;
}
return $next->format('Y-m-d H:i:s');