Files
tinker_tickets/models/WorkflowModel.php
T
jaredandClaude Opus 4.8 882ab2662c Fix data-layer bugs: bind_param fatals, ticket_id bindings, cache poisoning
- CustomFieldModel: assign ?? fallbacks to variables before bind_param
  (by-reference args cannot be ?? expressions; fatal on PHP 8.2, custom
  fields were uncreatable/uneditable)
- RecurringTicketModel::create: fix swapped bind type for schedule_type
  (enum bound as int coerced 'daily' to 0, breaking the cron)
- TicketModel/CommentModel: bind varchar ticket_id as string not int so
  the unique index is usable and leading-zero IDs match; ticket_watchers
  (int column) left as integer
- TicketModel::deleteTicket: delete from custom_field_values (real table)
  not the nonexistent ticket_custom_fields
- TicketModel search: honor literal '0'; never emit AGAINST('*') on
  all-special-char input (fall back to LIKE)
- TicketModel::updateTicket: disambiguate not-found vs no-op vs genuine
  optimistic-lock conflict on zero affected rows
- WorkflowModel: do not cache transitions/statuses on DB failure (a
  transient error no longer blocks all status changes for the TTL)
- DependencyModel: filter linked tickets by visibility (new optional user
  context params) to stop confidential metadata leaking via dependencies
- BulkOperationsModel: validate status/priority/assignee before mutating
- AuditLogModel: gate getClientIP forwarded headers on trusted proxies;
  add missing action/entity types so audit-log filters work
- WorkflowModel: add transitionRequiresComment() accessor for enforcement
- CommentModel: stop leaking raw DB errors to clients (log instead)

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-10 10:56:52 -04:00

189 lines
5.8 KiB
PHP

<?php
/**
* WorkflowModel - Handles status transition workflows and validation
*
* Uses caching for frequently accessed transition rules since they rarely change.
*/
require_once dirname(__DIR__) . '/helpers/CacheHelper.php';
class WorkflowModel
{
private mysqli $conn;
private static string $CACHE_PREFIX = 'workflow';
private static int $CACHE_TTL = 600; // 10 minutes
public function __construct(mysqli $conn)
{
$this->conn = $conn;
}
/**
* Get all active transitions (with caching)
*
* @return array All active transitions indexed by from_status
*/
private function getAllTransitions(): array
{
$cached = CacheHelper::get(self::$CACHE_PREFIX, 'all_transitions', self::$CACHE_TTL);
if ($cached !== null) {
return $cached;
}
$sql = "SELECT from_status, to_status, requires_comment, requires_admin
FROM status_transitions
WHERE is_active = TRUE";
$result = $this->conn->query($sql);
if (!$result) {
// A transient DB failure must NOT be cached as "no transitions" — that
// would block every status change for the whole TTL. Fail safe by
// returning empty without storing it, so the next call retries.
return [];
}
$transitions = [];
while ($row = $result->fetch_assoc()) {
$from = $row['from_status'];
if (!isset($transitions[$from])) {
$transitions[$from] = [];
}
$transitions[$from][$row['to_status']] = [
'to_status' => $row['to_status'],
'requires_comment' => (bool)$row['requires_comment'],
'requires_admin' => (bool)$row['requires_admin']
];
}
CacheHelper::set(self::$CACHE_PREFIX, 'all_transitions', $transitions);
return $transitions;
}
/**
* Get allowed status transitions for a given status
*
* @param string $currentStatus Current ticket status
* @return array Array of allowed transitions with requirements
*/
public function getAllowedTransitions(string $currentStatus): array
{
$allTransitions = $this->getAllTransitions();
if (!isset($allTransitions[$currentStatus])) {
return [];
}
return array_values($allTransitions[$currentStatus]);
}
/**
* Check if a status transition is allowed
*
* @param string $fromStatus Current status
* @param string $toStatus Desired status
* @param bool $isAdmin Whether user is admin
* @return bool True if transition is allowed
*/
public function isTransitionAllowed(string $fromStatus, string $toStatus, bool $isAdmin = false): bool
{
// Allow same status (no change)
if ($fromStatus === $toStatus) {
return true;
}
$allTransitions = $this->getAllTransitions();
if (!isset($allTransitions[$fromStatus][$toStatus])) {
return false; // Transition not defined
}
$transition = $allTransitions[$fromStatus][$toStatus];
if ($transition['requires_admin'] && !$isAdmin) {
return false; // Admin required
}
return true;
}
/**
* Get all possible statuses from transitions table
*
* @return array Array of unique status values
*/
public function getAllStatuses(): array
{
$cached = CacheHelper::get(self::$CACHE_PREFIX, 'all_statuses', self::$CACHE_TTL);
if ($cached !== null) {
return $cached;
}
$sql = "SELECT DISTINCT from_status as status FROM status_transitions
UNION
SELECT DISTINCT to_status as status FROM status_transitions
ORDER BY status";
$result = $this->conn->query($sql);
if (!$result) {
// Do not cache an empty list on a transient DB failure.
return [];
}
$statuses = [];
while ($row = $result->fetch_assoc()) {
$statuses[] = $row['status'];
}
CacheHelper::set(self::$CACHE_PREFIX, 'all_statuses', $statuses);
return $statuses;
}
/**
* Get transition requirements
*
* @param string $fromStatus Current status
* @param string $toStatus Desired status
* @return array|null Transition requirements or null if not found
*/
public function getTransitionRequirements(string $fromStatus, string $toStatus): ?array
{
$allTransitions = $this->getAllTransitions();
if (!isset($allTransitions[$fromStatus][$toStatus])) {
return null;
}
$transition = $allTransitions[$fromStatus][$toStatus];
return [
'requires_comment' => $transition['requires_comment'],
'requires_admin' => $transition['requires_admin']
];
}
/**
* Whether a given transition requires a comment.
*
* Convenience accessor so callers (e.g. the update-ticket endpoint) can
* enforce requires_comment server-side without inspecting the full row.
* Returns false for an undefined transition or a no-op (same status).
*
* @param string $fromStatus Current status
* @param string $toStatus Desired status
* @return bool True if the transition requires a comment
*/
public function transitionRequiresComment(string $fromStatus, string $toStatus): bool
{
$requirements = $this->getTransitionRequirements($fromStatus, $toStatus);
return $requirements !== null && !empty($requirements['requires_comment']);
}
/**
* Clear workflow cache (call when transitions are modified)
*/
public static function clearCache(): void
{
CacheHelper::delete(self::$CACHE_PREFIX);
}
}