Compare commits
5
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b2c19745eb | ||
|
|
b3bc3ab159 | ||
|
|
2b8d593ab0 | ||
|
|
600c46f673 | ||
|
|
5808b93cdb |
@@ -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: |
|
||||
|
||||
@@ -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);
|
||||
|
||||
|
||||
@@ -59,7 +59,9 @@ $assignSql = "SELECT
|
||||
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. The assign detail is logged as {"assigned_to":<int>}.
|
||||
$assignLike = '%"assigned_to":' . (int)$userId . '}%';
|
||||
$stmt = $conn->prepare($assignSql);
|
||||
$stmt->bind_param('is', $userId, $assignLike);
|
||||
$stmt->execute();
|
||||
|
||||
+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,
|
||||
|
||||
@@ -25,10 +25,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>');
|
||||
|
||||
@@ -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)
|
||||
],
|
||||
];
|
||||
+11
-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;
|
||||
@@ -397,7 +404,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);
|
||||
|
||||
@@ -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
|
||||
*
|
||||
|
||||
@@ -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
|
||||
*/
|
||||
|
||||
+18
-6
@@ -740,9 +740,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 +808,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);
|
||||
@@ -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