Compare commits
7
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e0e92e326a | ||
|
|
4164f85051 | ||
|
|
b2c19745eb | ||
|
|
b3bc3ab159 | ||
|
|
2b8d593ab0 | ||
|
|
600c46f673 | ||
|
|
5808b93cdb |
@@ -24,6 +24,14 @@ APP_DOMAIN=
|
||||
# Include all domains that can access this application
|
||||
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=America/New_York
|
||||
|
||||
|
||||
@@ -35,10 +35,27 @@ jobs:
|
||||
- name: Run ESLint
|
||||
run: npx eslint assets/js/
|
||||
|
||||
requirements:
|
||||
name: PHP requirements (version + extensions)
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
|
||||
- name: Install PHP with required extensions
|
||||
run: |
|
||||
apt-get update -qq
|
||||
# Install the extensions declared in config/requirements.php so the
|
||||
# check verifies they are actually installable + loadable, and so this
|
||||
# build fails if a required extension can't be provided.
|
||||
apt-get install -y -qq php-cli php-ldap php-mysql php-curl php-mbstring
|
||||
|
||||
- name: Verify runtime requirements
|
||||
run: php scripts/check_requirements.php
|
||||
|
||||
deploy:
|
||||
name: Deploy
|
||||
runs-on: ubuntu-latest
|
||||
needs: [php-lint, js-lint]
|
||||
needs: [php-lint, js-lint, requirements]
|
||||
if: github.event_name == 'push' && (github.ref == 'refs/heads/main' || github.ref == 'refs/heads/development')
|
||||
permissions:
|
||||
contents: write
|
||||
@@ -77,7 +94,7 @@ jobs:
|
||||
notify-failure:
|
||||
name: Notify on failure
|
||||
runs-on: ubuntu-latest
|
||||
needs: [php-lint, js-lint]
|
||||
needs: [php-lint, js-lint, requirements]
|
||||
if: failure() && github.event_name == 'push'
|
||||
steps:
|
||||
- name: Send Matrix alert
|
||||
|
||||
@@ -19,7 +19,9 @@ jobs:
|
||||
run: |
|
||||
apt-get update -qq
|
||||
apt-get install -y -qq python3 python3-pip
|
||||
pip3 install semgrep
|
||||
# Debian's Python is externally managed (PEP 668); the runner is
|
||||
# ephemeral so installing system-wide is fine here.
|
||||
pip3 install --break-system-packages semgrep
|
||||
|
||||
- name: Run semgrep
|
||||
run: |
|
||||
|
||||
+4
-2
@@ -46,8 +46,10 @@ if ($_SERVER['REQUEST_METHOD'] === 'GET') {
|
||||
$filters['ip_address'] = $_GET['ip_address'];
|
||||
}
|
||||
|
||||
// Get all matching logs (no limit for CSV export)
|
||||
$result = $auditLogModel->getFilteredLogs($filters, 10000, 0);
|
||||
// Get all matching logs for export. The forExport flag raises the cap
|
||||
// (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'];
|
||||
|
||||
// Set CSV headers
|
||||
|
||||
@@ -50,12 +50,24 @@ $sql = "SELECT ticket_id, title, status, priority, created_at
|
||||
|
||||
$types = "ss" . $visFilter['types'];
|
||||
$params = array_merge([$searchTerm, $soundexTitle], $visFilter['params']);
|
||||
$stmt = $conn->prepare($sql);
|
||||
if (!empty($params)) {
|
||||
$stmt->bind_param($types, ...$params);
|
||||
|
||||
// Duplicate detection is advisory (it must not block ticket creation), so on any
|
||||
// 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()) {
|
||||
// Calculate similarity score
|
||||
|
||||
@@ -95,6 +95,40 @@ if (is_dir($rateLimitDir) && is_writable($rateLimitDir)) {
|
||||
];
|
||||
}
|
||||
|
||||
// Check 5: Required PHP extensions (catches e.g. a PHP upgrade silently
|
||||
// dropping php-ldap, which breaks avatars with no other visible error).
|
||||
$requirements = require dirname(__DIR__) . '/config/requirements.php';
|
||||
$missingExt = array_values(array_filter(
|
||||
$requirements['required_extensions'],
|
||||
fn($ext) => !extension_loaded($ext)
|
||||
));
|
||||
if (empty($missingExt)) {
|
||||
$checks['php_extensions'] = [
|
||||
'status' => 'ok',
|
||||
'message' => 'All required extensions loaded'
|
||||
];
|
||||
} else {
|
||||
$checks['php_extensions'] = [
|
||||
'status' => 'error',
|
||||
'message' => 'Missing extensions: ' . implode(', ', $missingExt)
|
||||
];
|
||||
$healthy = false;
|
||||
}
|
||||
|
||||
// Check 6: PHP version meets the declared minimum
|
||||
if (version_compare(PHP_VERSION, $requirements['min_php_version'], '>=')) {
|
||||
$checks['php_version'] = [
|
||||
'status' => 'ok',
|
||||
'message' => PHP_VERSION
|
||||
];
|
||||
} else {
|
||||
$checks['php_version'] = [
|
||||
'status' => 'error',
|
||||
'message' => sprintf('PHP %s < required %s', PHP_VERSION, $requirements['min_php_version'])
|
||||
];
|
||||
$healthy = false;
|
||||
}
|
||||
|
||||
// Calculate response time
|
||||
$responseTime = round((microtime(true) - $startTime) * 1000, 2);
|
||||
|
||||
|
||||
@@ -82,6 +82,15 @@ try {
|
||||
case 'POST':
|
||||
$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'] ?? '')) {
|
||||
http_response_code(400);
|
||||
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);
|
||||
|
||||
$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'] ?? '')) {
|
||||
http_response_code(400);
|
||||
echo json_encode(['success' => false, 'error' => 'From Status and To Status cannot be the same']);
|
||||
|
||||
+33
-5
@@ -55,13 +55,18 @@ $assignSql = "SELECT
|
||||
AND al.entity_type = 'ticket'
|
||||
AND al.user_id != ?
|
||||
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
|
||||
LIMIT 15";
|
||||
|
||||
$assignLike = '%"assigned_to":' . $userId . '%';
|
||||
// Match the exact JSON value with a trailing delimiter so user 12 doesn't also
|
||||
// match 120/123/etc. Single assigns log {"assigned_to":5} (closing brace) while
|
||||
// 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->bind_param('is', $userId, $assignLike);
|
||||
$stmt->bind_param('iss', $userId, $assignEnd, $assignMid);
|
||||
$stmt->execute();
|
||||
$assignRows = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
|
||||
$stmt->close();
|
||||
@@ -148,10 +153,32 @@ $stmt->execute();
|
||||
$statusRows = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
|
||||
$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
|
||||
$all = [];
|
||||
$seen = [];
|
||||
foreach (array_merge($assignRows, $commentRows, $statusRows) as $row) {
|
||||
foreach (array_merge($assignRows, $commentRows, $statusRows, $mentionRows) as $row) {
|
||||
$id = (int)$row['log_id'];
|
||||
if (isset($seen[$id])) {
|
||||
continue;
|
||||
@@ -170,7 +197,7 @@ foreach ($all as $row) {
|
||||
$actionType = ($row['action_type'] === 'create' && $row['entity_type'] === 'comment')
|
||||
? 'comment'
|
||||
: $row['action_type'];
|
||||
$ticketId = ($actionType === 'comment')
|
||||
$ticketId = ($actionType === 'comment' || $actionType === 'mention')
|
||||
? ($details['ticket_id'] ?? 0)
|
||||
: $row['entity_id'];
|
||||
$isRead = $lastSeen && $row['created_at'] <= $lastSeen;
|
||||
@@ -179,6 +206,7 @@ foreach ($all as $row) {
|
||||
$title = match ($actionType) {
|
||||
'assign' => "{$row['actor_name']} assigned ticket #{$ticketId} to you",
|
||||
'comment' => "{$row['actor_name']} commented on ticket #{$ticketId}",
|
||||
'mention' => "{$row['actor_name']} mentioned you on ticket #{$ticketId}",
|
||||
'update' => (function () use ($row, $details, $ticketId) {
|
||||
// logTicketUpdate stores delta as {"status": {"from": "Open", "to": "In Progress"}}
|
||||
$from = $details['status']['from'] ?? ($details['old_value'] ?? '?');
|
||||
|
||||
+20
-15
@@ -127,6 +127,25 @@ try {
|
||||
];
|
||||
}
|
||||
|
||||
// Validate visibility BEFORE any DB write so a bad payload can't leave the
|
||||
// ticket half-updated (core fields committed but request reported as failed).
|
||||
$visibilityGroups = null;
|
||||
if (isset($data['visibility'])) {
|
||||
$visibilityGroups = $data['visibility_groups'] ?? null;
|
||||
// Convert array to comma-separated string if needed
|
||||
if (is_array($visibilityGroups)) {
|
||||
$visibilityGroups = implode(',', array_map('trim', $visibilityGroups));
|
||||
}
|
||||
|
||||
// Internal visibility requires at least one group
|
||||
if ($data['visibility'] === 'internal' && (empty($visibilityGroups) || trim($visibilityGroups) === '')) {
|
||||
return [
|
||||
'success' => false,
|
||||
'error' => 'Internal visibility requires at least one group to be specified'
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
// Validate status transition using workflow model
|
||||
if ($currentTicket['status'] !== $updateData['status']) {
|
||||
$allowed = $this->workflowModel->isTransitionAllowed(
|
||||
@@ -160,22 +179,8 @@ try {
|
||||
return $response;
|
||||
}
|
||||
|
||||
// Handle visibility update if provided
|
||||
// Handle visibility update if provided (already validated above)
|
||||
if (isset($data['visibility'])) {
|
||||
$visibilityGroups = $data['visibility_groups'] ?? null;
|
||||
// Convert array to comma-separated string if needed
|
||||
if (is_array($visibilityGroups)) {
|
||||
$visibilityGroups = implode(',', array_map('trim', $visibilityGroups));
|
||||
}
|
||||
|
||||
// Validate internal visibility requires groups
|
||||
if ($data['visibility'] === 'internal' && (empty($visibilityGroups) || trim($visibilityGroups) === '')) {
|
||||
return [
|
||||
'success' => false,
|
||||
'error' => 'Internal visibility requires at least one group to be specified'
|
||||
];
|
||||
}
|
||||
|
||||
$visResult = $this->ticketModel->updateVisibility($id, $data['visibility'], $visibilityGroups, $this->userId);
|
||||
if ($visResult && $this->userId) {
|
||||
$this->auditLog->log(
|
||||
|
||||
+13
-4
@@ -110,6 +110,7 @@ $safeUsername = ldap_escape($username, '', LDAP_ESCAPE_FILTER);
|
||||
$filter = "(uid=$safeUsername)";
|
||||
|
||||
$avatarData = null;
|
||||
$ldapQueryOk = false; // true only if the LDAP lookup completed without error
|
||||
|
||||
try {
|
||||
$ldap = @ldap_connect("ldap://$ldapHost:$ldapPort");
|
||||
@@ -137,20 +138,28 @@ try {
|
||||
$avatarData = $entries[0]['avatar'][0];
|
||||
}
|
||||
|
||||
// The query ran to completion — any "no avatar" result is authoritative.
|
||||
$ldapQueryOk = true;
|
||||
|
||||
ldap_unbind($ldap);
|
||||
} catch (Exception $e) {
|
||||
error_log("user_avatar: LDAP error for username=$username: " . $e->getMessage());
|
||||
// Fall through to 404
|
||||
// Transient LDAP failure: do NOT poison the negative cache. Fall through to
|
||||
// a plain 404 so the avatar is retried on the next request once LDAP recovers.
|
||||
}
|
||||
|
||||
if ($avatarData === null || strlen($avatarData) < 100) {
|
||||
// Write sentinel so we don't hammer LDAP for users without avatars
|
||||
file_put_contents($noAvatarSentinel, '');
|
||||
// Only cache "no avatar" when LDAP actually answered. On an error/timeout we
|
||||
// leave no sentinel, so the lookup is retried instead of being stuck for the TTL.
|
||||
if ($ldapQueryOk) {
|
||||
file_put_contents($noAvatarSentinel, '');
|
||||
}
|
||||
http_response_code(404);
|
||||
exit;
|
||||
}
|
||||
|
||||
// Validate it's actually a JPEG (magic bytes FF D8 FF)
|
||||
// Validate it's actually a JPEG (magic bytes FF D8 FF). A successful LDAP read of
|
||||
// non-JPEG data is a genuine "no usable avatar", so the sentinel is appropriate here.
|
||||
if (substr($avatarData, 0, 3) !== "\xFF\xD8\xFF") {
|
||||
error_log("user_avatar: non-JPEG data for username=$username");
|
||||
file_put_contents($noAvatarSentinel, '');
|
||||
|
||||
@@ -103,7 +103,13 @@ while ($row = $watchersResult->fetch_assoc()) {
|
||||
$watchers[] = ['user_id' => (int)$row['user_id'], 'display_name' => $row['display_name']];
|
||||
}
|
||||
$watchersStmt->close();
|
||||
$count = count($watchers);
|
||||
|
||||
// True watcher count (the list above is capped at 6 for the avatar group)
|
||||
$countStmt = $conn->prepare("SELECT COUNT(*) AS cnt FROM ticket_watchers WHERE ticket_id = ?");
|
||||
$countStmt->bind_param("i", $ticketId);
|
||||
$countStmt->execute();
|
||||
$count = (int)$countStmt->get_result()->fetch_assoc()['cnt'];
|
||||
$countStmt->close();
|
||||
|
||||
echo json_encode([
|
||||
'success' => true,
|
||||
|
||||
+16
-5
@@ -6,6 +6,13 @@
|
||||
function parseMarkdown(markdown) {
|
||||
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
|
||||
// (must happen before HTML escaping so <sup> tags don't get escaped)
|
||||
const footnotes = {};
|
||||
@@ -25,10 +32,14 @@ function parseMarkdown(markdown) {
|
||||
|
||||
let html = markdown;
|
||||
|
||||
// Escape HTML first to prevent XSS
|
||||
// Escape HTML first to prevent XSS. Quotes MUST be escaped too: user-controlled
|
||||
// text (e.g. image/link URLs and alt text) is later interpolated into "..."
|
||||
// attributes, so an unescaped " would break out and inject event handlers.
|
||||
html = html.replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>');
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'/g, ''');
|
||||
|
||||
// Ticket references (#123456789) - convert to clickable links
|
||||
html = html.replace(/#(\d{9})\b/g, '<a href="/ticket/$1" class="ticket-link-ref">#$1</a>');
|
||||
@@ -142,7 +153,7 @@ function parseMarkdown(markdown) {
|
||||
// Restore footnote reference placeholders
|
||||
fnRefs.forEach(function(ref, 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
|
||||
@@ -154,9 +165,9 @@ function parseMarkdown(markdown) {
|
||||
if (footnoteOrder.length) {
|
||||
html += '<hr class="fn-hr"><ol class="fn-list">';
|
||||
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, '') +
|
||||
' <a href="#fnref-' + label + '" class="fn-back">↩</a></li>';
|
||||
' <a href="#fnref-' + fnSlug(label) + '" class="fn-back">↩</a></li>';
|
||||
});
|
||||
html += '</ol>';
|
||||
}
|
||||
|
||||
@@ -60,6 +60,16 @@ $GLOBALS['config'] = [
|
||||
'DB_PASS' => $envVars['DB_PASS'] ?? '',
|
||||
'DB_NAME' => $envVars['DB_NAME'] ?? 'tinkertickets',
|
||||
|
||||
// Trusted reverse proxies. Authelia forward-auth (Remote-* headers) is only
|
||||
// honored when REMOTE_ADDR is in this allowlist, so the spoofable identity
|
||||
// headers can't be set by anything that reaches PHP directly. Comma-separated
|
||||
// IPs in .env (e.g. TRUSTED_PROXIES=10.10.10.27). Empty = enforcement OFF
|
||||
// (backward compatible — relies solely on network topology).
|
||||
'TRUSTED_PROXIES' => array_values(array_filter(array_map(
|
||||
'trim',
|
||||
explode(',', (string)($envVars['TRUSTED_PROXIES'] ?? ''))
|
||||
), fn($ip) => $ip !== '')),
|
||||
|
||||
// URL settings
|
||||
'BASE_URL' => '', // Empty since we're serving from document root
|
||||
'ASSETS_URL' => '/assets', // Assets URL
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* Runtime requirements — single source of truth.
|
||||
*
|
||||
* Consumed by:
|
||||
* - scripts/check_requirements.php (CI: fails the build if unmet)
|
||||
* - api/health.php (production: surfaces drift to monitoring)
|
||||
*
|
||||
* This exists because a PHP upgrade once silently dropped the ldap extension,
|
||||
* which broke avatars with no visible error. Keep this list in sync with the
|
||||
* extensions the code actually relies on.
|
||||
*/
|
||||
|
||||
return [
|
||||
// Minimum supported PHP version (production runs 8.4).
|
||||
'min_php_version' => '8.2',
|
||||
|
||||
// Extensions the application requires to function.
|
||||
'required_extensions' => [
|
||||
'ldap', // api/user_avatar.php — lldap avatar lookups
|
||||
'mysqli', // helpers/Database.php — all data access
|
||||
'curl', // helpers/NotificationHelper.php, SynapseHelper.php — Matrix
|
||||
'mbstring', // multibyte string handling
|
||||
'fileinfo', // api/upload_attachment.php — MIME validation
|
||||
'json', // request/response encoding (bundled, but assert anyway)
|
||||
],
|
||||
];
|
||||
+27
-2
@@ -45,9 +45,11 @@ $conn = new mysqli(
|
||||
);
|
||||
|
||||
if ($conn->connect_error) {
|
||||
error_log('create_ticket_api: DB connection failed: ' . $conn->connect_error);
|
||||
http_response_code(500);
|
||||
echo json_encode([
|
||||
'success' => false,
|
||||
'error' => 'Database connection failed: ' . $conn->connect_error
|
||||
'error' => 'Internal server error'
|
||||
]);
|
||||
exit;
|
||||
}
|
||||
@@ -199,6 +201,11 @@ function generateTicketHash($data)
|
||||
)),
|
||||
];
|
||||
|
||||
// Manual tickets should be unique by title (so different software installs don't collide)
|
||||
if ($sourceType === 'manual') {
|
||||
$stableComponents['title'] = $title;
|
||||
}
|
||||
|
||||
// Include hostname for node-specific issues
|
||||
if (!$isClusterWide) {
|
||||
$stableComponents['hostname'] = $hostname;
|
||||
@@ -224,6 +231,22 @@ $priority = $data['priority'] ?? '4';
|
||||
$category = (string)($data['category'] ?? 'General');
|
||||
$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);
|
||||
$auditLog = new AuditLogModel($conn);
|
||||
|
||||
@@ -397,7 +420,9 @@ try {
|
||||
// Race condition: another node inserted the same hash between our SELECT and INSERT
|
||||
echo json_encode(['success' => false, 'error' => 'Duplicate ticket']);
|
||||
} else {
|
||||
echo json_encode(['success' => false, 'error' => $e->getMessage()]);
|
||||
error_log('create_ticket_api: insert failed: ' . $e->getMessage());
|
||||
http_response_code(500);
|
||||
echo json_encode(['success' => false, 'error' => 'Internal server error']);
|
||||
}
|
||||
exit;
|
||||
}
|
||||
|
||||
@@ -6,12 +6,10 @@
|
||||
*
|
||||
* Cleans up expired rate limit files from the temp directory.
|
||||
* Should be run via cron every 5-10 minutes:
|
||||
* */
|
||||
|
||||
5 * * * * / usr / bin / php / path / to / cron / cleanup_ratelimit . php
|
||||
* 5 * * * * /usr/bin/php /path/to/cron/cleanup_ratelimit.php
|
||||
*
|
||||
* This script can also be run manually for immediate cleanup .
|
||||
* /
|
||||
* This script can also be run manually for immediate cleanup.
|
||||
*/
|
||||
|
||||
// Prevent web access
|
||||
if (php_sapi_name() !== 'cli') {
|
||||
|
||||
@@ -5,19 +5,18 @@
|
||||
* Recurring Tickets Cron Job
|
||||
*
|
||||
* Run this script via cron to automatically create tickets from recurring schedules.
|
||||
* Recommended: Run every 5-15 minutes
|
||||
* Recommended: run every 5-15 minutes.
|
||||
*
|
||||
* Example crontab entry:
|
||||
* */
|
||||
|
||||
10 * * * * / usr / bin / php / path / to / cron / create_recurring_tickets . php >> / var / log / recurring_tickets . log 2 > & 1
|
||||
* /
|
||||
* Example crontab entry (minute 10 of every hour):
|
||||
* 10 * * * * /usr/bin/php /path/to/cron/create_recurring_tickets.php >> /var/log/recurring_tickets.log 2>&1
|
||||
*/
|
||||
|
||||
// Change to project root directory
|
||||
chdir(dirname(__DIR__));
|
||||
|
||||
// Include required files
|
||||
require_once 'config/config.php';
|
||||
require_once 'helpers/Database.php';
|
||||
require_once 'models/RecurringTicketModel.php';
|
||||
require_once 'models/TicketModel.php';
|
||||
require_once 'models/AuditLogModel.php';
|
||||
@@ -31,17 +30,9 @@ function logMessage($message)
|
||||
logMessage("Starting recurring tickets cron job");
|
||||
|
||||
try {
|
||||
// Create database connection
|
||||
$conn = new mysqli(
|
||||
$GLOBALS['config']['DB_HOST'],
|
||||
$GLOBALS['config']['DB_USER'],
|
||||
$GLOBALS['config']['DB_PASS'],
|
||||
$GLOBALS['config']['DB_NAME']
|
||||
);
|
||||
|
||||
if ($conn->connect_error) {
|
||||
throw new Exception("Database connection failed: " . $conn->connect_error);
|
||||
}
|
||||
// Create database connection (Database::getConnection sets utf8mb4 so
|
||||
// non-ASCII titles/descriptions aren't corrupted on insert).
|
||||
$conn = Database::getConnection();
|
||||
|
||||
// Initialize models
|
||||
$recurringModel = new RecurringTicketModel($conn);
|
||||
@@ -59,6 +50,14 @@ try {
|
||||
logMessage("Processing recurring ticket ID: " . $recurring['recurring_id']);
|
||||
|
||||
try {
|
||||
// Claim the schedule FIRST (atomic advance of next_run_at). If another
|
||||
// cron run already claimed it, or it's no longer due, skip it — this
|
||||
// prevents duplicate-ticket floods if a later step throws.
|
||||
if (!$recurringModel->claimForRun($recurring['recurring_id'])) {
|
||||
logMessage("Skipped (already claimed or not due): " . $recurring['recurring_id']);
|
||||
continue;
|
||||
}
|
||||
|
||||
// Prepare ticket data
|
||||
$ticketData = [
|
||||
'title' => processTemplate($recurring['title_template']),
|
||||
@@ -76,9 +75,12 @@ try {
|
||||
$ticketId = $result['ticket_id'];
|
||||
logMessage("Created ticket: " . $ticketId);
|
||||
|
||||
// Assign to user if specified
|
||||
if ($recurring['assigned_to']) {
|
||||
$ticketModel->assignTicket($ticketId, $recurring['assigned_to'], $recurring['created_by']);
|
||||
// Assign to user if specified. assignTicket() requires a non-null
|
||||
// "assigned_by"; fall back to the assignee when created_by is null
|
||||
// (recurring schedules may have no creator).
|
||||
if (!empty($recurring['assigned_to'])) {
|
||||
$assignedBy = (int)($recurring['created_by'] ?? $recurring['assigned_to']);
|
||||
$ticketModel->assignTicket($ticketId, (int)$recurring['assigned_to'], $assignedBy);
|
||||
}
|
||||
|
||||
// Log to audit
|
||||
@@ -90,9 +92,6 @@ try {
|
||||
['source' => 'recurring', 'recurring_id' => $recurring['recurring_id']]
|
||||
);
|
||||
|
||||
// Update the recurring ticket's next run time
|
||||
$recurringModel->updateAfterRun($recurring['recurring_id']);
|
||||
|
||||
$created++;
|
||||
} else {
|
||||
logMessage("ERROR: Failed to create ticket - " . ($result['error'] ?? 'Unknown error'));
|
||||
@@ -106,7 +105,7 @@ try {
|
||||
|
||||
logMessage("Completed: Created $created tickets, $errors errors");
|
||||
|
||||
$conn->close();
|
||||
Database::close();
|
||||
} catch (Exception $e) {
|
||||
logMessage("FATAL ERROR: " . $e->getMessage());
|
||||
exit(1);
|
||||
|
||||
@@ -164,23 +164,38 @@ class NotificationHelper
|
||||
return;
|
||||
}
|
||||
|
||||
// Fetch watcher usernames, excluding the actor so they don't notify themselves
|
||||
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);
|
||||
$stmt->bind_param("ii", $ticketId, $excludeUserId);
|
||||
} 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();
|
||||
|
||||
// Fetch watcher usernames, excluding the actor so they don't notify
|
||||
// themselves. Notifications are best-effort: if the watchers table is
|
||||
// absent or the query fails, skip silently rather than fataling the
|
||||
// request that already committed its DB change. mysqli may either throw
|
||||
// (default exception mode) or return false, so handle both.
|
||||
$usernames = [];
|
||||
while ($row = $result->fetch_assoc()) {
|
||||
$usernames[] = $row['username'];
|
||||
try {
|
||||
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)) {
|
||||
|
||||
@@ -96,6 +96,12 @@ class AuthMiddleware
|
||||
}
|
||||
}
|
||||
|
||||
// Only honor Authelia forward-auth headers from a trusted reverse proxy.
|
||||
// Without this, anything that can reach PHP directly could spoof
|
||||
// Remote-User / Remote-Groups and log in (as admin). No valid session
|
||||
// exists at this point, so we are about to trust request headers.
|
||||
$this->enforceTrustedProxy();
|
||||
|
||||
// Read Authelia forward auth headers
|
||||
$username = $this->getHeader('HTTP_REMOTE_USER');
|
||||
$displayName = $this->getHeader('HTTP_REMOTE_NAME');
|
||||
@@ -136,6 +142,33 @@ class AuthMiddleware
|
||||
return $user;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reject forward-auth headers that did not arrive via a trusted proxy.
|
||||
*
|
||||
* If TRUSTED_PROXIES is configured and the connecting REMOTE_ADDR is not in
|
||||
* the allowlist, the Remote-* headers cannot be trusted, so we refuse rather
|
||||
* than honor a potentially spoofed identity. Empty allowlist = disabled.
|
||||
*/
|
||||
private function enforceTrustedProxy(): void
|
||||
{
|
||||
$trusted = $GLOBALS['config']['TRUSTED_PROXIES'] ?? [];
|
||||
if (empty($trusted)) {
|
||||
return; // Enforcement disabled (no allowlist configured)
|
||||
}
|
||||
|
||||
$remoteAddr = $_SERVER['REMOTE_ADDR'] ?? '';
|
||||
if (!in_array($remoteAddr, $trusted, true)) {
|
||||
$this->logSecurityEvent('untrusted_proxy', [
|
||||
'reason' => 'Remote-* auth headers from non-allowlisted source',
|
||||
'remote_addr' => $remoteAddr ?: 'unknown'
|
||||
]);
|
||||
header('HTTP/1.1 403 Forbidden');
|
||||
header('Content-Type: text/plain; charset=utf-8');
|
||||
echo 'Forbidden: authentication headers must arrive via a trusted proxy.';
|
||||
exit;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get header value from server variables
|
||||
*
|
||||
|
||||
@@ -41,19 +41,31 @@ class RateLimitMiddleware
|
||||
*/
|
||||
private static function getClientIp(): string
|
||||
{
|
||||
// Check for forwarded IP (behind proxy/load balancer)
|
||||
$headers = ['HTTP_X_FORWARDED_FOR', 'HTTP_X_REAL_IP', 'HTTP_CLIENT_IP'];
|
||||
foreach ($headers as $header) {
|
||||
if (!empty($_SERVER[$header])) {
|
||||
// Take the first IP in a comma-separated list
|
||||
$ips = explode(',', $_SERVER[$header]);
|
||||
$ip = trim($ips[0]);
|
||||
if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
|
||||
return $ip;
|
||||
}
|
||||
$remoteAddr = $_SERVER['REMOTE_ADDR'] ?? '127.0.0.1';
|
||||
|
||||
// Forwarded headers are client-controlled, so only believe them when the
|
||||
// request actually came from a trusted reverse proxy. Otherwise a client
|
||||
// could rotate X-Forwarded-For each request to escape the per-IP limit.
|
||||
$trusted = $GLOBALS['config']['TRUSTED_PROXIES'] ?? [];
|
||||
if (empty($trusted) || !in_array($remoteAddr, $trusted, true)) {
|
||||
return $remoteAddr;
|
||||
}
|
||||
|
||||
// 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 +10,9 @@ class AuditLogModel
|
||||
/** @var int Maximum allowed limit for pagination */
|
||||
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 */
|
||||
private const DEFAULT_LIMIT = 100;
|
||||
|
||||
@@ -36,12 +39,12 @@ class AuditLogModel
|
||||
* @param int $limit Requested 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) {
|
||||
return self::DEFAULT_LIMIT;
|
||||
}
|
||||
return min($limit, self::MAX_LIMIT);
|
||||
return min($limit, $max);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -534,7 +537,7 @@ class AuditLogModel
|
||||
FROM audit_log al
|
||||
LEFT JOIN users u ON al.user_id = u.user_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"
|
||||
);
|
||||
$stmt->bind_param("ss", $ticketId, $ticketId);
|
||||
@@ -561,10 +564,11 @@ class AuditLogModel
|
||||
* @param int $offset Offset for pagination
|
||||
* @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
|
||||
$limit = $this->validateLimit((int)$limit);
|
||||
// Validate pagination parameters. Exports allow a much higher cap so a
|
||||
// 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);
|
||||
|
||||
$whereConditions = [];
|
||||
|
||||
@@ -94,6 +94,10 @@ class BulkOperationsModel
|
||||
// Start transaction for data consistency
|
||||
$this->conn->begin_transaction();
|
||||
|
||||
// Attachment files for deleted tickets are removed only AFTER a successful
|
||||
// commit, so a rollback can't leave tickets with their files already gone.
|
||||
$filesToDelete = [];
|
||||
|
||||
try {
|
||||
foreach ($ticketIds as $ticketId) {
|
||||
$ticketId = trim($ticketId);
|
||||
@@ -200,7 +204,7 @@ class BulkOperationsModel
|
||||
break;
|
||||
|
||||
case 'bulk_delete':
|
||||
$success = $ticketModel->deleteTicket($ticketId);
|
||||
$success = $ticketModel->deleteTicket($ticketId, $filesToDelete);
|
||||
if ($success) {
|
||||
$auditLogModel->log(
|
||||
$operation['performed_by'],
|
||||
@@ -249,6 +253,16 @@ class BulkOperationsModel
|
||||
|
||||
// Commit the transaction
|
||||
$this->conn->commit();
|
||||
|
||||
// Now that the DB delete is durable, remove the physical files. Files
|
||||
// are deleted first; directory entries (no trailing filename) last.
|
||||
foreach ($filesToDelete as $path) {
|
||||
if (is_dir($path)) {
|
||||
@rmdir($path); // only succeeds if empty
|
||||
} elseif (file_exists($path)) {
|
||||
@unlink($path);
|
||||
}
|
||||
}
|
||||
} catch (Exception $e) {
|
||||
// Rollback on any unexpected error
|
||||
$this->conn->rollback();
|
||||
|
||||
@@ -151,6 +151,44 @@ class RecurringTicketModel
|
||||
return $items;
|
||||
}
|
||||
|
||||
/**
|
||||
* Atomically claim a due schedule for processing.
|
||||
*
|
||||
* Advances next_run_at (and stamps last_run_at) in a single conditional
|
||||
* UPDATE gated on the row still being active and due. Returns true only if
|
||||
* THIS call won the claim. This must be done BEFORE creating the ticket so
|
||||
* that:
|
||||
* - two overlapping cron runs can't both process the same schedule, and
|
||||
* - a failure in a later step (ticket create, assignment, audit) can't
|
||||
* leave next_run_at in the past, which would re-fire — and re-create a
|
||||
* duplicate ticket — on every subsequent cron run.
|
||||
*
|
||||
* @return bool true if the schedule was claimed by this call
|
||||
*/
|
||||
public function claimForRun($recurringId)
|
||||
{
|
||||
$recurring = $this->getById($recurringId);
|
||||
if (!$recurring) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$nextRun = $this->calculateNextRunTime(
|
||||
$recurring['schedule_type'],
|
||||
$recurring['schedule_day'],
|
||||
$recurring['schedule_time']
|
||||
);
|
||||
|
||||
$sql = "UPDATE recurring_tickets
|
||||
SET last_run_at = NOW(), next_run_at = ?
|
||||
WHERE recurring_id = ? AND is_active = 1 AND next_run_at <= NOW()";
|
||||
$stmt = $this->conn->prepare($sql);
|
||||
$stmt->bind_param('si', $nextRun, $recurringId);
|
||||
$stmt->execute();
|
||||
$claimed = $stmt->affected_rows > 0;
|
||||
$stmt->close();
|
||||
return $claimed;
|
||||
}
|
||||
|
||||
/**
|
||||
* Update last run and calculate next run time
|
||||
*/
|
||||
|
||||
+41
-6
@@ -208,6 +208,11 @@ class TicketModel
|
||||
ORDER BY $sortExpression $sortDirection
|
||||
LIMIT ? OFFSET ?";
|
||||
|
||||
// Keep a copy of the filter params (without LIMIT/OFFSET) for the
|
||||
// fallback COUNT below.
|
||||
$countParams = $params;
|
||||
$countParamTypes = $paramTypes;
|
||||
|
||||
$params[] = $limit;
|
||||
$params[] = $offset;
|
||||
$paramTypes .= 'ii';
|
||||
@@ -228,6 +233,24 @@ class TicketModel
|
||||
}
|
||||
$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 [
|
||||
'tickets' => $tickets,
|
||||
'total' => $totalTickets,
|
||||
@@ -740,9 +763,13 @@ class TicketModel
|
||||
* Admin-only operation. Removes comments, attachments, watchers, dependencies.
|
||||
*
|
||||
* @param string $ticketId Ticket ID
|
||||
* @param array|null &$deferredFiles When provided, attachment file paths to
|
||||
* remove are appended here instead of being unlinked immediately, so a
|
||||
* caller running inside a DB transaction can delete them only AFTER a
|
||||
* successful commit (avoids destroying files for a rolled-back delete).
|
||||
* @return bool Success status
|
||||
*/
|
||||
public function deleteTicket(string $ticketId): bool
|
||||
public function deleteTicket(string $ticketId, ?array &$deferredFiles = null): bool
|
||||
{
|
||||
// Collect attachment filenames before deleting DB rows
|
||||
$attachmentFiles = [];
|
||||
@@ -804,13 +831,21 @@ class TicketModel
|
||||
: (isset($GLOBALS['config']['UPLOAD_DIR']) ? $GLOBALS['config']['UPLOAD_DIR'] : dirname(__DIR__) . '/uploads');
|
||||
$ticketDir = rtrim($uploadDir, '/') . '/' . $ticketId;
|
||||
if (is_dir($ticketDir)) {
|
||||
foreach ($attachmentFiles as $filename) {
|
||||
$file = $ticketDir . '/' . basename($filename);
|
||||
if (file_exists($file)) {
|
||||
@unlink($file);
|
||||
if ($deferredFiles !== null) {
|
||||
// Defer physical deletion to the caller (post-commit).
|
||||
foreach ($attachmentFiles as $filename) {
|
||||
$deferredFiles[] = $ticketDir . '/' . basename($filename);
|
||||
}
|
||||
$deferredFiles[] = $ticketDir; // dir removed last, only if empty
|
||||
} else {
|
||||
foreach ($attachmentFiles as $filename) {
|
||||
$file = $ticketDir . '/' . basename($filename);
|
||||
if (file_exists($file)) {
|
||||
@unlink($file);
|
||||
}
|
||||
}
|
||||
@rmdir($ticketDir); // Remove dir only if empty
|
||||
}
|
||||
@rmdir($ticketDir); // Remove dir only if empty
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -86,7 +86,7 @@ class UserModel
|
||||
$user = $result->fetch_assoc();
|
||||
|
||||
$updateStmt = $this->conn->prepare(
|
||||
"UPDATE users SET display_name = ?, email = ?, groups = ?, is_admin = ?, last_login = NOW() WHERE username = ?"
|
||||
"UPDATE users SET display_name = ?, email = ?, `groups` = ?, is_admin = ?, last_login = NOW() WHERE username = ?"
|
||||
);
|
||||
$updateStmt->bind_param("sssis", $displayName, $email, $groups, $isAdmin, $username);
|
||||
$updateStmt->execute();
|
||||
@@ -100,7 +100,7 @@ class UserModel
|
||||
} else {
|
||||
// Create new user
|
||||
$insertStmt = $this->conn->prepare(
|
||||
"INSERT INTO users (username, display_name, email, groups, is_admin, last_login) VALUES (?, ?, ?, ?, ?, NOW())"
|
||||
"INSERT INTO users (username, display_name, email, `groups`, is_admin, last_login) VALUES (?, ?, ?, ?, ?, NOW())"
|
||||
);
|
||||
$insertStmt->bind_param("ssssi", $username, $displayName, $email, $groups, $isAdmin);
|
||||
$insertStmt->execute();
|
||||
@@ -300,7 +300,7 @@ class UserModel
|
||||
return $cached;
|
||||
}
|
||||
|
||||
$stmt = $this->conn->prepare("SELECT DISTINCT groups FROM users WHERE groups IS NOT NULL AND groups != ''");
|
||||
$stmt = $this->conn->prepare("SELECT DISTINCT `groups` FROM users WHERE `groups` IS NOT NULL AND `groups` != ''");
|
||||
$stmt->execute();
|
||||
$result = $stmt->get_result();
|
||||
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
#!/usr/bin/env php
|
||||
<?php
|
||||
|
||||
/**
|
||||
* Verify the running PHP environment meets the declared runtime requirements.
|
||||
*
|
||||
* Reads config/requirements.php and checks the PHP version and that every
|
||||
* required extension is loaded. Exits non-zero (failing CI) on any miss.
|
||||
*
|
||||
* Usage: php scripts/check_requirements.php
|
||||
*/
|
||||
|
||||
$req = require __DIR__ . '/../config/requirements.php';
|
||||
|
||||
$errors = [];
|
||||
|
||||
// PHP version
|
||||
$minPhp = $req['min_php_version'];
|
||||
if (version_compare(PHP_VERSION, $minPhp, '<')) {
|
||||
$errors[] = sprintf('PHP %s is below the required minimum %s', PHP_VERSION, $minPhp);
|
||||
}
|
||||
|
||||
// Required extensions
|
||||
foreach ($req['required_extensions'] as $ext) {
|
||||
if (!extension_loaded($ext)) {
|
||||
$errors[] = sprintf('Missing required PHP extension: %s', $ext);
|
||||
}
|
||||
}
|
||||
|
||||
if (!empty($errors)) {
|
||||
fwrite(STDERR, "Requirement check FAILED:\n");
|
||||
foreach ($errors as $err) {
|
||||
fwrite(STDERR, ' - ' . $err . "\n");
|
||||
}
|
||||
exit(1);
|
||||
}
|
||||
|
||||
printf(
|
||||
"Requirement check passed: PHP %s (>= %s); extensions: %s\n",
|
||||
PHP_VERSION,
|
||||
$minPhp,
|
||||
implode(', ', $req['required_extensions'])
|
||||
);
|
||||
exit(0);
|
||||
@@ -48,14 +48,14 @@ if (!empty($_GET['priority'])) {
|
||||
}
|
||||
}
|
||||
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'])) {
|
||||
$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'])) {
|
||||
$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];
|
||||
}
|
||||
@@ -1342,7 +1342,7 @@ if (advForm) advForm.addEventListener('submit', function(e) {
|
||||
var o = hasCheckbox ? 1 : 0; // column offset for checkbox col
|
||||
|
||||
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 typeVal = cells[4 + o] ? cells[4 + o].textContent.trim() : '';
|
||||
var status = cells[5 + o] ? cells[5 + o].textContent.trim().replace(/^\s*●\s*/, '') : '';
|
||||
|
||||
@@ -205,7 +205,6 @@ $_lt_assetVer = $GLOBALS['config']['ASSET_VERSION'] ?? '20260329';
|
||||
class="lt-btn lt-btn-ghost lt-btn-sm"
|
||||
title="Command palette (Ctrl+K)"
|
||||
aria-label="Open command palette"
|
||||
onclick="if(window.lt&<.cmdPalette)lt.cmdPalette.open()"
|
||||
style="font-size:0.65rem;opacity:0.65;letter-spacing:0.03em;padding:0.2rem 0.45rem">⌕ K</button>
|
||||
<button type="button" class="lt-theme-btn" id="lt-theme-btn"
|
||||
aria-label="Switch to light mode" title="Switch to light mode">☀</button>
|
||||
@@ -258,6 +257,13 @@ $_lt_assetVer = $GLOBALS['config']['ASSET_VERSION'] ?? '20260329';
|
||||
});
|
||||
} catch(_) {}
|
||||
if (window.lt && lt.cmdPalette) lt.cmdPalette.init(commands);
|
||||
// Bind the header ⌘K trigger here (no inline onclick — CSP blocks inline handlers)
|
||||
var cmdTrigger = document.getElementById('lt-cmd-trigger');
|
||||
if (cmdTrigger) {
|
||||
cmdTrigger.addEventListener('click', function() {
|
||||
if (window.lt && lt.cmdPalette) lt.cmdPalette.open();
|
||||
});
|
||||
}
|
||||
});
|
||||
// Keyboard shortcut: Ctrl+K / Cmd+K
|
||||
document.addEventListener('keydown', function(e) {
|
||||
|
||||
Reference in New Issue
Block a user