Lint / PHP (phpcs PSR-12) (push) Successful in 42s
Lint / JS (eslint) (push) Successful in 13s
Lint / PHP requirements (version + extensions) (push) Successful in 27s
Lint / Notify on failure (push) Skipped
Security / PHP Security (semgrep) (push) Successful in 1m24s
Lint / Deploy (push) Successful in 3s
CustomFieldModel::setValue()/setValues()/getValuesForTicket() were never called anywhere outside api/custom_fields.php's own admin CRUD for field *definitions* — CreateTicketView.php never rendered custom fields, TicketController::create() never collected or saved them, and TicketView.php never displayed them. The whole feature (admin defines fields at /admin/custom-fields, including marking them Required) was config-only with zero consumer; is_required was enforced nowhere. Added: - api/ticket_custom_fields.php: new endpoint (bootstrap.php-based, so any ticket editor can use it, not just admins) that saves values for a ticket. Only considers fields applicable to the ticket's current category (or category-less fields); enforces is_required, validates select values against the field's configured options, and validates number fields are numeric. Values for fields that don't apply are silently ignored rather than persisted, so a value typed before a category change can't linger as orphaned data. - CreateTicketView.php: renders every active field definition (all categories, since the ticket doesn't exist yet), grouped with a data-custom-field-category attribute and toggled client-side as the Category select changes, matching the existing visibility-groups toggle pattern. Submitted as part of the same form. - TicketController::create(): validates is_required server-side against the fields applicable to the *submitted* category (not just whatever was visible client-side) before creating the ticket, then persists via CustomFieldModel::setValues() after a successful create. - TicketView.php: new "Custom Fields" tab (only shown when the ticket's category has applicable fields) rendering current values with a single Save button, calling the new endpoint — a panel-plus-save interaction rather than per-field inline auto-save, to keep scope contained across 6 field types. Verified against real MariaDB and a real running server: a required field left blank is correctly rejected (both at ticket-creation time and when editing an existing ticket) with no partial write; a valid submission persists exactly the fields applicable to that ticket's category; an invalid select value is rejected without touching previously-saved values; and each rejection correctly returns a rotated recovery csrf_token (initially missed on the validation-error paths, since they used a plain echo/exit instead of the bootstrap.php apiRespond() helper every other endpoint's error paths use for this). Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Lhz7pGMaoTfL5sdYS5XiKv
236 lines
10 KiB
PHP
236 lines
10 KiB
PHP
<?php
|
|
|
|
// Use absolute paths for model includes
|
|
require_once dirname(__DIR__) . '/models/TicketModel.php';
|
|
require_once dirname(__DIR__) . '/models/CommentModel.php';
|
|
require_once dirname(__DIR__) . '/models/AuditLogModel.php';
|
|
require_once dirname(__DIR__) . '/models/UserModel.php';
|
|
require_once dirname(__DIR__) . '/models/WorkflowModel.php';
|
|
require_once dirname(__DIR__) . '/models/TemplateModel.php';
|
|
require_once dirname(__DIR__) . '/models/CustomFieldModel.php';
|
|
require_once dirname(__DIR__) . '/helpers/UrlHelper.php';
|
|
require_once dirname(__DIR__) . '/helpers/NotificationHelper.php';
|
|
|
|
class TicketController
|
|
{
|
|
private $ticketModel;
|
|
private $commentModel;
|
|
private $auditLogModel;
|
|
private $userModel;
|
|
private $workflowModel;
|
|
private $templateModel;
|
|
private $customFieldModel;
|
|
private $conn;
|
|
|
|
public function __construct($conn)
|
|
{
|
|
$this->conn = $conn;
|
|
$this->ticketModel = new TicketModel($conn);
|
|
$this->commentModel = new CommentModel($conn);
|
|
$this->auditLogModel = new AuditLogModel($conn);
|
|
$this->userModel = new UserModel($conn);
|
|
$this->workflowModel = new WorkflowModel($conn);
|
|
$this->templateModel = new TemplateModel($conn);
|
|
$this->customFieldModel = new CustomFieldModel($conn);
|
|
}
|
|
|
|
public function view($id)
|
|
{
|
|
// Get current user
|
|
$currentUser = $GLOBALS['currentUser'] ?? null;
|
|
$userId = $currentUser['user_id'] ?? null;
|
|
|
|
// Get ticket data
|
|
$ticket = $this->ticketModel->getTicketById($id);
|
|
|
|
if (!$ticket || !$this->ticketModel->canUserAccessTicket($ticket, $currentUser)) {
|
|
http_response_code(404);
|
|
include dirname(__DIR__) . '/views/error_404.php';
|
|
return;
|
|
}
|
|
|
|
// Load first page of comments; show "load more" if ticket has many
|
|
$commentPageSize = 50;
|
|
$totalComments = $this->commentModel->getCommentCount((int)$id);
|
|
$comments = $this->commentModel->getCommentsByTicketId($id, true, $commentPageSize, 0);
|
|
|
|
// Get timeline for this ticket
|
|
$timeline = $this->auditLogModel->getTicketTimeline($id);
|
|
|
|
// Get all users for assignment dropdown
|
|
$allUsers = $this->userModel->getAllUsers();
|
|
|
|
// Get allowed status transitions for this ticket
|
|
$allowedTransitions = $this->workflowModel->getAllowedTransitions($ticket['status']);
|
|
|
|
// Custom fields applicable to this ticket's category, with any
|
|
// already-saved values for it
|
|
$customFieldDefs = $this->customFieldModel->getAllDefinitions($ticket['category'], true);
|
|
$customFieldValues = $this->customFieldModel->getValuesForTicket($id);
|
|
|
|
// Make $conn available to view for visibility groups
|
|
$conn = $this->conn;
|
|
|
|
// Load the view
|
|
include dirname(__DIR__) . '/views/TicketView.php';
|
|
}
|
|
|
|
public function create()
|
|
{
|
|
// Get current user
|
|
$currentUser = $GLOBALS['currentUser'] ?? null;
|
|
$userId = $currentUser['user_id'] ?? null;
|
|
|
|
// All active custom field definitions (every category, plus
|
|
// category-less ones) — the create form renders them all and toggles
|
|
// visibility client-side as the Category select changes, since the
|
|
// ticket doesn't exist yet to scope the query to one category.
|
|
$allCustomFieldDefs = $this->customFieldModel->getAllDefinitions(null, true);
|
|
|
|
// Check if form was submitted
|
|
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
|
|
// Validate CSRF token
|
|
require_once dirname(__DIR__) . '/middleware/CsrfMiddleware.php';
|
|
$csrfToken = $_POST['csrf_token'] ?? '';
|
|
if (!CsrfMiddleware::validateToken($csrfToken)) {
|
|
$error = "Invalid or expired security token. Please try again.";
|
|
$templates = $this->templateModel->getAllTemplates();
|
|
$allUsers = $this->userModel->getAllUsers();
|
|
$conn = $this->conn;
|
|
include dirname(__DIR__) . '/views/CreateTicketView.php';
|
|
return;
|
|
}
|
|
|
|
// Handle visibility groups (comes as array from checkboxes)
|
|
$visibilityGroups = null;
|
|
if (isset($_POST['visibility_groups']) && is_array($_POST['visibility_groups'])) {
|
|
$visibilityGroups = implode(',', array_map('trim', $_POST['visibility_groups']));
|
|
}
|
|
|
|
// Honor the posted status, validated against the app's canonical list
|
|
$validStatuses = $GLOBALS['config']['TICKET_STATUSES'] ?? ['Open', 'Pending', 'In Progress', 'Closed'];
|
|
$status = $_POST['status'] ?? 'Open';
|
|
if (!in_array($status, $validStatuses, true)) {
|
|
$status = 'Open';
|
|
}
|
|
|
|
$ticketData = [
|
|
'title' => trim($_POST['title'] ?? ''),
|
|
'description' => $_POST['description'] ?? '',
|
|
'priority' => $_POST['priority'] ?? '4',
|
|
'category' => $_POST['category'] ?? 'General',
|
|
'type' => $_POST['type'] ?? 'Issue',
|
|
'status' => $status,
|
|
'visibility' => $_POST['visibility'] ?? 'public',
|
|
'visibility_groups' => $visibilityGroups,
|
|
'assigned_to' => !empty($_POST['assigned_to']) ? $_POST['assigned_to'] : null
|
|
];
|
|
|
|
// Validate input (server-side; form is novalidate)
|
|
if ($ticketData['title'] === '') {
|
|
$error = "Title is required";
|
|
$templates = $this->templateModel->getAllTemplates();
|
|
$allUsers = $this->userModel->getAllUsers();
|
|
$conn = $this->conn; // Make $conn available to view
|
|
include dirname(__DIR__) . '/views/CreateTicketView.php';
|
|
return;
|
|
}
|
|
|
|
if (trim($ticketData['description']) === '') {
|
|
$error = "Description is required";
|
|
$templates = $this->templateModel->getAllTemplates();
|
|
$allUsers = $this->userModel->getAllUsers();
|
|
$conn = $this->conn; // Make $conn available to view
|
|
include dirname(__DIR__) . '/views/CreateTicketView.php';
|
|
return;
|
|
}
|
|
|
|
// Custom fields applicable to the submitted category — validate
|
|
// is_required server-side (the form is novalidate, and a field
|
|
// hidden by the client-side category toggle must not silently
|
|
// bypass a requirement that applies to the category actually
|
|
// submitted).
|
|
$submittedCustomFields = is_array($_POST['custom_fields'] ?? null) ? $_POST['custom_fields'] : [];
|
|
$applicableFieldDefs = array_filter(
|
|
$allCustomFieldDefs,
|
|
fn($def) => $def['category'] === null || $def['category'] === $ticketData['category']
|
|
);
|
|
$customFieldsToSave = [];
|
|
foreach ($applicableFieldDefs as $def) {
|
|
$fieldId = (int)$def['field_id'];
|
|
$raw = $submittedCustomFields[$fieldId] ?? null;
|
|
$normalized = $def['field_type'] === 'checkbox'
|
|
? (!empty($raw) ? '1' : '0')
|
|
: (is_scalar($raw) ? trim((string)$raw) : '');
|
|
|
|
if (!empty($def['is_required']) && $def['field_type'] !== 'checkbox' && $normalized === '') {
|
|
$error = $def['field_label'] . ' is required';
|
|
$templates = $this->templateModel->getAllTemplates();
|
|
$allUsers = $this->userModel->getAllUsers();
|
|
$conn = $this->conn;
|
|
include dirname(__DIR__) . '/views/CreateTicketView.php';
|
|
return;
|
|
}
|
|
|
|
if ($normalized !== '') {
|
|
$customFieldsToSave[$fieldId] = $normalized;
|
|
}
|
|
}
|
|
|
|
// Create ticket with user tracking
|
|
$result = $this->ticketModel->createTicket($ticketData, $userId);
|
|
|
|
if ($result['success']) {
|
|
// Log ticket creation to audit log
|
|
if (isset($GLOBALS['auditLog']) && $userId) {
|
|
$GLOBALS['auditLog']->logTicketCreate($userId, $result['ticket_id'], $ticketData);
|
|
}
|
|
|
|
// Ticket counts changed — invalidate the cached dashboard stats
|
|
require_once dirname(__DIR__) . '/models/StatsModel.php';
|
|
(new StatsModel($this->conn))->invalidateCache();
|
|
|
|
// Persist custom field values for the fields applicable to
|
|
// this ticket's category
|
|
if (!empty($customFieldsToSave)) {
|
|
$this->customFieldModel->setValues($result['ticket_id'], $customFieldsToSave);
|
|
}
|
|
|
|
// Auto-link as duplicate if requested from create form
|
|
$linkDupOfRaw = trim($_POST['link_duplicate_of'] ?? '');
|
|
if ($linkDupOfRaw !== '' && ctype_digit($linkDupOfRaw)) {
|
|
$depSql = "INSERT IGNORE INTO ticket_dependencies (ticket_id, depends_on_id, dependency_type, created_by)
|
|
VALUES (?, ?, 'duplicates', ?)";
|
|
$depStmt = $this->conn->prepare($depSql);
|
|
$depStmt->bind_param("ssi", $result['ticket_id'], $linkDupOfRaw, $userId);
|
|
$depStmt->execute();
|
|
$depStmt->close();
|
|
}
|
|
|
|
// Send Matrix notification for new ticket
|
|
NotificationHelper::sendTicketNotification($result['ticket_id'], $ticketData, 'manual');
|
|
|
|
// Redirect to the new ticket
|
|
header("Location: " . $GLOBALS['config']['BASE_URL'] . "/ticket/" . $result['ticket_id']);
|
|
exit;
|
|
} else {
|
|
$error = $result['error'];
|
|
$templates = $this->templateModel->getAllTemplates();
|
|
$allUsers = $this->userModel->getAllUsers();
|
|
$conn = $this->conn; // Make $conn available to view
|
|
include dirname(__DIR__) . '/views/CreateTicketView.php';
|
|
return;
|
|
}
|
|
} else {
|
|
// Get all templates for the template selector
|
|
$templates = $this->templateModel->getAllTemplates();
|
|
// Get all users for assignment dropdown
|
|
$allUsers = $this->userModel->getAllUsers();
|
|
$conn = $this->conn; // Make $conn available to view
|
|
|
|
// Display the create ticket form
|
|
include dirname(__DIR__) . '/views/CreateTicketView.php';
|
|
}
|
|
}
|
|
}
|