Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
99c840fce0 | ||
|
|
9941fd2dfa |
+1
-1
@@ -70,7 +70,7 @@ if ($_SERVER['REQUEST_METHOD'] === 'GET') {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fputcsv($output, [
|
fputcsv($output, [
|
||||||
$log['log_id'],
|
$log['audit_id'] ?? ($log['log_id'] ?? ''),
|
||||||
$log['created_at'],
|
$log['created_at'],
|
||||||
$log['display_name'] ?? $log['username'] ?? 'N/A',
|
$log['display_name'] ?? $log['username'] ?? 'N/A',
|
||||||
$log['action_type'],
|
$log['action_type'],
|
||||||
|
|||||||
@@ -64,6 +64,11 @@ try {
|
|||||||
}
|
}
|
||||||
$stmt->execute();
|
$stmt->execute();
|
||||||
$result = $stmt->get_result();
|
$result = $stmt->get_result();
|
||||||
|
if ($result === false) {
|
||||||
|
// Non-exception mysqli mode: execute/get_result return false instead of
|
||||||
|
// throwing. Treat as a query failure so we don't fatal on $result below.
|
||||||
|
throw new RuntimeException('query failed: ' . $conn->error);
|
||||||
|
}
|
||||||
} catch (Throwable $e) {
|
} catch (Throwable $e) {
|
||||||
error_log('check_duplicates: ' . $e->getMessage());
|
error_log('check_duplicates: ' . $e->getMessage());
|
||||||
ResponseHelper::success(['duplicates' => []]);
|
ResponseHelper::success(['duplicates' => []]);
|
||||||
|
|||||||
@@ -175,6 +175,23 @@ $stmt->execute();
|
|||||||
$mentionRows = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
|
$mentionRows = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
|
||||||
$stmt->close();
|
$stmt->close();
|
||||||
|
|
||||||
|
// If the user owns/watches a ticket AND was @mentioned in the same comment, the
|
||||||
|
// comment query and the mention query both produce a row for it. Prefer the more
|
||||||
|
// specific mention and drop the duplicate comment notification for that comment.
|
||||||
|
$mentionCommentIds = [];
|
||||||
|
foreach ($mentionRows as $mr) {
|
||||||
|
$md = json_decode($mr['details'] ?? '{}', true) ?? [];
|
||||||
|
if (!empty($md['comment_id'])) {
|
||||||
|
$mentionCommentIds[(int)$md['comment_id']] = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!empty($mentionCommentIds)) {
|
||||||
|
$commentRows = array_filter(
|
||||||
|
$commentRows,
|
||||||
|
fn($cr) => !isset($mentionCommentIds[(int)($cr['entity_id'] ?? 0)])
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
// Merge, deduplicate by log_id, sort by created_at desc
|
// Merge, deduplicate by log_id, sort by created_at desc
|
||||||
$all = [];
|
$all = [];
|
||||||
$seen = [];
|
$seen = [];
|
||||||
|
|||||||
@@ -78,6 +78,17 @@ if ($ticketId <= 0) {
|
|||||||
exit;
|
exit;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Enforce ticket visibility before returning watch state / watcher names, so a
|
||||||
|
// restricted ticket's watcher list and count aren't disclosed (the POST path
|
||||||
|
// already checks this).
|
||||||
|
$ticketModel = new TicketModel($conn);
|
||||||
|
$ticket = $ticketModel->getTicketById($ticketId);
|
||||||
|
if (!$ticket || !$ticketModel->canUserAccessTicket($ticket, $currentUser)) {
|
||||||
|
http_response_code(404);
|
||||||
|
echo json_encode(['success' => false, 'error' => 'Ticket not found']);
|
||||||
|
exit;
|
||||||
|
}
|
||||||
|
|
||||||
$watchingStmt = $conn->prepare(
|
$watchingStmt = $conn->prepare(
|
||||||
"SELECT COUNT(*) as cnt FROM ticket_watchers WHERE ticket_id = ? AND user_id = ?"
|
"SELECT COUNT(*) as cnt FROM ticket_watchers WHERE ticket_id = ? AND user_id = ?"
|
||||||
);
|
);
|
||||||
|
|||||||
+31
-26
@@ -1142,8 +1142,10 @@ function populateKanbanCards() {
|
|||||||
if (cells.length < 6) return;
|
if (cells.length < 6) return;
|
||||||
|
|
||||||
const ticketId = cells[0 + offset]?.querySelector('.ticket-link')?.textContent.trim() || '';
|
const ticketId = cells[0 + offset]?.querySelector('.ticket-link')?.textContent.trim() || '';
|
||||||
const priorityEl = cells[1 + offset]?.querySelector('[class*="lt-p"]');
|
// The priority cell renders a "P1".."P5" badge; extract just the digit.
|
||||||
const priority = priorityEl ? priorityEl.textContent.trim().replace('P','') : cells[1 + offset]?.textContent.trim() || '4';
|
// (The old [class*="lt-p"] selector never matched the lt-badge-p1 class, so
|
||||||
|
// every card fell back to P4 regardless of real priority.)
|
||||||
|
const priority = (cells[1 + offset]?.textContent.trim() || '').replace(/[^0-9]/g, '') || '4';
|
||||||
const title = cells[2 + offset]?.textContent.trim() || '';
|
const title = cells[2 + offset]?.textContent.trim() || '';
|
||||||
const category = cells[3 + offset]?.textContent.trim() || '';
|
const category = cells[3 + offset]?.textContent.trim() || '';
|
||||||
const statusEl = cells[5 + offset]?.querySelector('.lt-status');
|
const statusEl = cells[5 + offset]?.querySelector('.lt-status');
|
||||||
@@ -1219,29 +1221,30 @@ function populateKanbanCards() {
|
|||||||
if (dec) dec.textContent = '(' + Math.max(0, (parseInt(dec.textContent.replace(/\D/g,''),10)||1) - 1) + ')';
|
if (dec) dec.textContent = '(' + Math.max(0, (parseInt(dec.textContent.replace(/\D/g,''),10)||1) - 1) + ')';
|
||||||
if (inc) inc.textContent = '(' + ((parseInt(inc.textContent.replace(/\D/g,''),10)||0) + 1) + ')';
|
if (inc) inc.textContent = '(' + ((parseInt(inc.textContent.replace(/\D/g,''),10)||0) + 1) + ')';
|
||||||
|
|
||||||
// POST status update
|
// Revert the card to its original column and undo the optimistic counts.
|
||||||
fetch('/api/update_ticket.php', {
|
const revert = function () {
|
||||||
method: 'POST',
|
const origCol = document.getElementById(Object.keys(colStatusMap).find(k => colStatusMap[k] === oldStatus));
|
||||||
credentials: 'same-origin',
|
if (origCol) origCol.appendChild(movedCard);
|
||||||
headers: { 'Content-Type': 'application/json', 'X-CSRF-Token': window.CSRF_TOKEN || '' },
|
movedCard.dataset.status = oldStatus;
|
||||||
body: JSON.stringify({ ticket_id: String(ticketId), status: newStatus })
|
if (dec) dec.textContent = '(' + ((parseInt(dec.textContent.replace(/\D/g, ''), 10) || 0) + 1) + ')';
|
||||||
})
|
if (inc) inc.textContent = '(' + Math.max(0, (parseInt(inc.textContent.replace(/\D/g, ''), 10) || 1) - 1) + ')';
|
||||||
.then(r => r.json())
|
};
|
||||||
.then(data => {
|
|
||||||
if (data.success) {
|
// POST status update via the shared wrapper (adds CSRF + JSON, throws on non-2xx)
|
||||||
lt.toast.success('Ticket #' + ticketId + ' → ' + newStatus, 2500);
|
lt.api.post('/api/update_ticket.php', { ticket_id: String(ticketId), status: newStatus })
|
||||||
movedCard.dataset.status = newStatus;
|
.then(function (data) {
|
||||||
} else {
|
if (data && data.success) {
|
||||||
lt.toast.error('Status update failed: ' + (data.error || 'Unknown error'));
|
lt.toast.success('Ticket #' + ticketId + ' → ' + newStatus, 2500);
|
||||||
// Revert: put card back in original column
|
movedCard.dataset.status = newStatus;
|
||||||
const origCol = document.getElementById(Object.keys(colStatusMap).find(k => colStatusMap[k] === oldStatus));
|
} else {
|
||||||
if (origCol) origCol.appendChild(movedCard);
|
lt.toast.error('Status update failed: ' + ((data && data.error) || 'Unknown error'));
|
||||||
movedCard.dataset.status = oldStatus;
|
revert();
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
.catch(() => {
|
.catch(function () {
|
||||||
lt.toast.error('Network error — status not saved');
|
lt.toast.error('Status update failed — reverting');
|
||||||
});
|
revert();
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
Object.keys(columns).forEach(status => {
|
Object.keys(columns).forEach(status => {
|
||||||
@@ -1314,7 +1317,9 @@ function showTicketPreview(event) {
|
|||||||
const offset = isAdmin ? 1 : 0;
|
const offset = isAdmin ? 1 : 0;
|
||||||
|
|
||||||
const ticketId = link.textContent.trim();
|
const ticketId = link.textContent.trim();
|
||||||
const priority = cells[1 + offset]?.textContent.trim() || '';
|
// Cell text is already "P1".."P5"; strip the leading P so the template's
|
||||||
|
// `P${priority}` doesn't render "PP1".
|
||||||
|
const priority = (cells[1 + offset]?.textContent.trim() || '').replace(/^P/i, '');
|
||||||
const title = cells[2 + offset]?.textContent.trim() || '';
|
const title = cells[2 + offset]?.textContent.trim() || '';
|
||||||
const category = cells[3 + offset]?.textContent.trim() || '';
|
const category = cells[3 + offset]?.textContent.trim() || '';
|
||||||
const type = cells[4 + offset]?.textContent.trim() || '';
|
const type = cells[4 + offset]?.textContent.trim() || '';
|
||||||
|
|||||||
@@ -142,12 +142,14 @@ function parseMarkdown(markdown) {
|
|||||||
html = html.replace(/ \n/g, '<br>');
|
html = html.replace(/ \n/g, '<br>');
|
||||||
html = html.replace(/\n\n/g, '</p><p>');
|
html = html.replace(/\n\n/g, '</p><p>');
|
||||||
|
|
||||||
// Restore code blocks and inline code
|
// Restore code blocks and inline code. Use a function replacer so '$'
|
||||||
|
// sequences in user code (e.g. $&, $$, $`, $') are inserted literally rather
|
||||||
|
// than interpreted as String.replace replacement patterns.
|
||||||
codeBlocks.forEach((block, i) => {
|
codeBlocks.forEach((block, i) => {
|
||||||
html = html.replace('%%CODEBLOCK' + i + '%%', block);
|
html = html.replace('%%CODEBLOCK' + i + '%%', () => block);
|
||||||
});
|
});
|
||||||
inlineCodes.forEach((code, i) => {
|
inlineCodes.forEach((code, i) => {
|
||||||
html = html.replace('%%INLINECODE' + i + '%%', code);
|
html = html.replace('%%INLINECODE' + i + '%%', () => code);
|
||||||
});
|
});
|
||||||
|
|
||||||
// Restore footnote reference placeholders
|
// Restore footnote reference placeholders
|
||||||
@@ -164,7 +166,7 @@ function parseMarkdown(markdown) {
|
|||||||
// Append footnote definitions block
|
// Append footnote definitions block
|
||||||
if (footnoteOrder.length) {
|
if (footnoteOrder.length) {
|
||||||
html += '<hr class="fn-hr"><ol class="fn-list">';
|
html += '<hr class="fn-hr"><ol class="fn-list">';
|
||||||
footnoteOrder.forEach(function(label, i) {
|
footnoteOrder.forEach(function(label) {
|
||||||
html += '<li id="fn-' + fnSlug(label) + '" class="fn-item">' +
|
html += '<li id="fn-' + fnSlug(label) + '" class="fn-item">' +
|
||||||
parseMarkdown(footnotes[label]).replace(/<\/?p>/g, '') +
|
parseMarkdown(footnotes[label]).replace(/<\/?p>/g, '') +
|
||||||
' <a href="#fnref-' + fnSlug(label) + '" class="fn-back">↩</a></li>';
|
' <a href="#fnref-' + fnSlug(label) + '" class="fn-back">↩</a></li>';
|
||||||
|
|||||||
+11
-4
@@ -195,10 +195,17 @@ function generateTicketHash($data)
|
|||||||
'source_type' => $sourceType,
|
'source_type' => $sourceType,
|
||||||
'issue_category' => $issueCategory,
|
'issue_category' => $issueCategory,
|
||||||
'issue_subtype' => $issueSubtype,
|
'issue_subtype' => $issueSubtype,
|
||||||
'environment_tags' => array_values(array_filter(
|
'environment_tags' => (function () use ($title) {
|
||||||
explode('][', $title),
|
// Extract each [bracketed] tag, then keep the known environment ones.
|
||||||
fn($tag) => in_array($tag, ['production', 'development', 'staging', 'single-node', 'cluster-wide'])
|
// (explode('][') leaves brackets stuck to the first/last tag, so e.g.
|
||||||
)),
|
// "[production] ..." never matched and the env tag was dropped from the
|
||||||
|
// dedup hash — letting prod and staging issues collide onto one ticket.)
|
||||||
|
preg_match_all('/\[([^\]]+)\]/', $title, $m);
|
||||||
|
return array_values(array_filter(
|
||||||
|
$m[1],
|
||||||
|
fn($tag) => in_array($tag, ['production', 'development', 'staging', 'single-node', 'cluster-wide'], true)
|
||||||
|
));
|
||||||
|
})(),
|
||||||
];
|
];
|
||||||
|
|
||||||
// Manual tickets should be unique by title (so different software installs don't collide)
|
// Manual tickets should be unique by title (so different software installs don't collide)
|
||||||
|
|||||||
+13
-6
@@ -125,16 +125,23 @@ class CacheHelper
|
|||||||
return !file_exists($filePath) || @unlink($filePath);
|
return !file_exists($filePath) || @unlink($filePath);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Delete all files with this prefix
|
// Delete all entries for this prefix. A key is either the bare prefix or
|
||||||
$pattern = self::getCacheDir() . '/' . preg_replace('/[^a-zA-Z0-9_]/', '_', $prefix) . '*.json';
|
// prefix + '_' + md5(identifier) (32 hex chars, see makeKey). Match exactly
|
||||||
$files = glob($pattern);
|
// that so a prefix can't clobber a different prefix that merely shares a
|
||||||
|
// leading substring — e.g. delete('workflow') must not wipe 'workflow_rules'.
|
||||||
|
$safePrefix = preg_replace('/[^a-zA-Z0-9_]/', '_', $prefix);
|
||||||
|
$keyRegex = '/^' . preg_quote($safePrefix, '/') . '(_[0-9a-f]{32})?$/';
|
||||||
|
|
||||||
|
$files = glob(self::getCacheDir() . '/' . $safePrefix . '*.json') ?: [];
|
||||||
foreach ($files as $file) {
|
foreach ($files as $file) {
|
||||||
@unlink($file);
|
if (preg_match($keyRegex, basename($file, '.json'))) {
|
||||||
|
@unlink($file);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Clear memory cache entries with this prefix
|
// Clear matching memory cache entries
|
||||||
foreach (array_keys(self::$memoryCache) as $key) {
|
foreach (array_keys(self::$memoryCache) as $key) {
|
||||||
if (strpos($key, $prefix) === 0) {
|
if (preg_match($keyRegex, $key)) {
|
||||||
unset(self::$memoryCache[$key]);
|
unset(self::$memoryCache[$key]);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+33
-12
@@ -4,8 +4,9 @@
|
|||||||
* SynapseHelper
|
* SynapseHelper
|
||||||
*
|
*
|
||||||
* Resolves local (SSO) usernames → Matrix user IDs by querying the
|
* Resolves local (SSO) usernames → Matrix user IDs by querying the
|
||||||
* Synapse Admin REST API directly. No caching — every call is live
|
* Synapse Admin REST API directly. Results are memoized per-request (not
|
||||||
* so results never go stale.
|
* across requests, so they don't go stale between requests), and a batch
|
||||||
|
* resolve has an overall time budget to bound request latency.
|
||||||
*
|
*
|
||||||
* Required config (.env) keys:
|
* Required config (.env) keys:
|
||||||
* MATRIX_DOMAIN e.g. matrix.lotusguild.org
|
* MATRIX_DOMAIN e.g. matrix.lotusguild.org
|
||||||
@@ -14,6 +15,12 @@
|
|||||||
*/
|
*/
|
||||||
class SynapseHelper
|
class SynapseHelper
|
||||||
{
|
{
|
||||||
|
/** Per-request memo of username => Matrix ID|null, so repeat watchers are free. */
|
||||||
|
private static array $cache = [];
|
||||||
|
|
||||||
|
/** Total wall-clock budget (seconds) for a single resolveUsernames() batch. */
|
||||||
|
private const RESOLVE_BUDGET_SECONDS = 5;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Resolve a local SSO username to its Matrix user ID.
|
* Resolve a local SSO username to its Matrix user ID.
|
||||||
*
|
*
|
||||||
@@ -29,6 +36,11 @@ class SynapseHelper
|
|||||||
*/
|
*/
|
||||||
public static function resolveUsername(string $username): ?string
|
public static function resolveUsername(string $username): ?string
|
||||||
{
|
{
|
||||||
|
// Serve from the per-request cache when we've already looked this up.
|
||||||
|
if (array_key_exists($username, self::$cache)) {
|
||||||
|
return self::$cache[$username];
|
||||||
|
}
|
||||||
|
|
||||||
$baseUrl = $GLOBALS['config']['SYNAPSE_ADMIN_URL'] ?? null;
|
$baseUrl = $GLOBALS['config']['SYNAPSE_ADMIN_URL'] ?? null;
|
||||||
$token = $GLOBALS['config']['SYNAPSE_ADMIN_TOKEN'] ?? null;
|
$token = $GLOBALS['config']['SYNAPSE_ADMIN_TOKEN'] ?? null;
|
||||||
$domain = $GLOBALS['config']['MATRIX_DOMAIN'] ?? null;
|
$domain = $GLOBALS['config']['MATRIX_DOMAIN'] ?? null;
|
||||||
@@ -49,6 +61,7 @@ class SynapseHelper
|
|||||||
'Accept: application/json',
|
'Accept: application/json',
|
||||||
]);
|
]);
|
||||||
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
|
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
|
||||||
|
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 2); // fail fast when Synapse is unreachable
|
||||||
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
|
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
|
||||||
|
|
||||||
$body = curl_exec($ch);
|
$body = curl_exec($ch);
|
||||||
@@ -56,25 +69,24 @@ class SynapseHelper
|
|||||||
$curlError = curl_error($ch);
|
$curlError = curl_error($ch);
|
||||||
curl_close($ch);
|
curl_close($ch);
|
||||||
|
|
||||||
|
$resolved = null;
|
||||||
if ($curlError) {
|
if ($curlError) {
|
||||||
error_log("SynapseHelper: cURL error resolving '{$username}': {$curlError}");
|
error_log("SynapseHelper: cURL error resolving '{$username}': {$curlError}");
|
||||||
return null;
|
} elseif ($httpCode === 200) {
|
||||||
}
|
|
||||||
|
|
||||||
if ($httpCode === 200) {
|
|
||||||
$data = json_decode($body, true);
|
$data = json_decode($body, true);
|
||||||
// Confirm the response contains the name we expect
|
// Confirm the response contains the name we expect
|
||||||
if (!empty($data['name'])) {
|
if (!empty($data['name'])) {
|
||||||
return $data['name']; // e.g. "@jared:matrix.lotusguild.org"
|
$resolved = $data['name']; // e.g. "@jared:matrix.lotusguild.org"
|
||||||
}
|
}
|
||||||
}
|
} elseif ($httpCode !== 404) {
|
||||||
|
// 404 = user not found in Synapse; other codes = error
|
||||||
// 404 = user not found in Synapse; other codes = error
|
|
||||||
if ($httpCode !== 404) {
|
|
||||||
error_log("SynapseHelper: unexpected HTTP {$httpCode} resolving '{$username}'");
|
error_log("SynapseHelper: unexpected HTTP {$httpCode} resolving '{$username}'");
|
||||||
}
|
}
|
||||||
|
|
||||||
return null;
|
// Memoize for the rest of this request (including negative results, so a
|
||||||
|
// missing/unreachable user isn't retried within the same request).
|
||||||
|
self::$cache[$username] = $resolved;
|
||||||
|
return $resolved;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -87,7 +99,16 @@ class SynapseHelper
|
|||||||
public static function resolveUsernames(array $usernames): array
|
public static function resolveUsernames(array $usernames): array
|
||||||
{
|
{
|
||||||
$ids = [];
|
$ids = [];
|
||||||
|
$deadline = microtime(true) + self::RESOLVE_BUDGET_SECONDS;
|
||||||
foreach ($usernames as $username) {
|
foreach ($usernames as $username) {
|
||||||
|
// Cached lookups are free and always allowed; for uncached ones, stop
|
||||||
|
// making live calls once the batch budget is spent so a slow/unreachable
|
||||||
|
// Synapse can't stall the request for N × per-call timeout.
|
||||||
|
$cached = array_key_exists($username, self::$cache);
|
||||||
|
if (!$cached && microtime(true) >= $deadline) {
|
||||||
|
error_log('SynapseHelper: resolve budget exhausted; skipping remaining lookups');
|
||||||
|
break;
|
||||||
|
}
|
||||||
$id = self::resolveUsername($username);
|
$id = self::resolveUsername($username);
|
||||||
if ($id !== null) {
|
if ($id !== null) {
|
||||||
$ids[] = $id;
|
$ids[] = $id;
|
||||||
|
|||||||
@@ -84,28 +84,43 @@ class RateLimitMiddleware
|
|||||||
$ipHash = hash('sha256', $ip . '_' . $type);
|
$ipHash = hash('sha256', $ip . '_' . $type);
|
||||||
$filePath = self::getRateLimitDir() . '/' . $ipHash . '.json';
|
$filePath = self::getRateLimitDir() . '/' . $ipHash . '.json';
|
||||||
|
|
||||||
// Load existing rate data
|
// Hold an exclusive lock across the whole read-modify-write so concurrent
|
||||||
|
// requests from the same IP can't both read the same count and each write
|
||||||
|
// count+1 (which would undercount and let the limit be exceeded).
|
||||||
|
$fh = @fopen($filePath, 'c+');
|
||||||
|
if ($fh === false) {
|
||||||
|
// Can't open the counter file — fail open (don't block legitimate traffic).
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!flock($fh, LOCK_EX)) {
|
||||||
|
fclose($fh);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
$content = stream_get_contents($fh);
|
||||||
$rateData = ['count' => 0, 'window_start' => $now];
|
$rateData = ['count' => 0, 'window_start' => $now];
|
||||||
if (file_exists($filePath)) {
|
if ($content !== false && $content !== '') {
|
||||||
$content = @file_get_contents($filePath);
|
$decoded = json_decode($content, true);
|
||||||
if ($content !== false) {
|
if (is_array($decoded)) {
|
||||||
$decoded = json_decode($content, true);
|
$rateData = $decoded;
|
||||||
if (is_array($decoded)) {
|
|
||||||
$rateData = $decoded;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check if window has expired
|
// Reset when the window has expired
|
||||||
if ($now - $rateData['window_start'] >= self::WINDOW_SECONDS) {
|
if ($now - ($rateData['window_start'] ?? $now) >= self::WINDOW_SECONDS) {
|
||||||
$rateData = ['count' => 0, 'window_start' => $now];
|
$rateData = ['count' => 0, 'window_start' => $now];
|
||||||
}
|
}
|
||||||
|
|
||||||
// Increment count
|
|
||||||
$rateData['count']++;
|
$rateData['count']++;
|
||||||
|
|
||||||
// Save updated data
|
// Rewrite the file in place while still holding the lock
|
||||||
@file_put_contents($filePath, json_encode($rateData), LOCK_EX);
|
rewind($fh);
|
||||||
|
ftruncate($fh, 0);
|
||||||
|
fwrite($fh, json_encode($rateData));
|
||||||
|
fflush($fh);
|
||||||
|
flock($fh, LOCK_UN);
|
||||||
|
fclose($fh);
|
||||||
|
|
||||||
// Check if over limit
|
// Check if over limit
|
||||||
return $rateData['count'] <= $limit;
|
return $rateData['count'] <= $limit;
|
||||||
|
|||||||
@@ -104,6 +104,11 @@ class BulkOperationsModel
|
|||||||
$success = false;
|
$success = false;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
|
// NOTE: bulk_status / bulk_close intentionally do NOT run
|
||||||
|
// WorkflowModel::isTransitionAllowed(). Bulk operations are an
|
||||||
|
// admin-only escape hatch for forcing ticket states (e.g. mass
|
||||||
|
// re-opening), so they bypass the workflow transition rules that
|
||||||
|
// the single-ticket update path enforces. This is by design.
|
||||||
switch ($operation['operation_type']) {
|
switch ($operation['operation_type']) {
|
||||||
case 'bulk_close':
|
case 'bulk_close':
|
||||||
// Get current ticket from pre-loaded batch
|
// Get current ticket from pre-loaded batch
|
||||||
|
|||||||
+34
-20
@@ -176,27 +176,41 @@ class CommentModel
|
|||||||
return [];
|
return [];
|
||||||
}
|
}
|
||||||
|
|
||||||
// All replies for these root comments (up to 3 levels deep)
|
// Load replies level-by-level under this page's roots. A single
|
||||||
$placeholders = implode(',', array_fill(0, count($rootIds), '?'));
|
// "parent_comment_id IN (rootIds)" only fetches DIRECT children, so
|
||||||
$replySql = "SELECT tc.*, u.display_name, u.username
|
// grandchildren/great-grandchildren (addComment allows up to depth 3)
|
||||||
FROM ticket_comments tc
|
// would be missing from the map and dropped by buildCommentThread.
|
||||||
LEFT JOIN users u ON tc.user_id = u.user_id
|
// Expand iteratively until no new replies (bounded by max depth 3).
|
||||||
WHERE tc.ticket_id = ?
|
$parentIds = $rootIds;
|
||||||
AND tc.parent_comment_id IN ($placeholders)
|
$depth = 0;
|
||||||
AND tc.parent_comment_id IS NOT NULL
|
while (!empty($parentIds) && $depth < 3) {
|
||||||
ORDER BY tc.created_at ASC";
|
$placeholders = implode(',', array_fill(0, count($parentIds), '?'));
|
||||||
$replyStmt = $this->conn->prepare($replySql);
|
$replySql = "SELECT tc.*, u.display_name, u.username
|
||||||
$types = 'i' . str_repeat('i', count($rootIds));
|
FROM ticket_comments tc
|
||||||
$replyStmt->bind_param($types, $ticketId, ...$rootIds);
|
LEFT JOIN users u ON tc.user_id = u.user_id
|
||||||
$replyStmt->execute();
|
WHERE tc.ticket_id = ?
|
||||||
$replyResult = $replyStmt->get_result();
|
AND tc.parent_comment_id IN ($placeholders)
|
||||||
$replyStmt->close();
|
ORDER BY tc.created_at ASC";
|
||||||
|
$replyStmt = $this->conn->prepare($replySql);
|
||||||
|
$types = 'i' . str_repeat('i', count($parentIds));
|
||||||
|
$replyStmt->bind_param($types, $ticketId, ...$parentIds);
|
||||||
|
$replyStmt->execute();
|
||||||
|
$replyResult = $replyStmt->get_result();
|
||||||
|
$replyStmt->close();
|
||||||
|
|
||||||
while ($row = $replyResult->fetch_assoc()) {
|
$nextParentIds = [];
|
||||||
$row['display_name_formatted'] = $row['display_name'] ?: ($row['user_name'] ?? 'Unknown User');
|
while ($row = $replyResult->fetch_assoc()) {
|
||||||
$row['replies'] = [];
|
if (isset($commentMap[$row['comment_id']])) {
|
||||||
$row['thread_depth'] = $row['thread_depth'] ?? 1;
|
continue; // guard against cycles / duplicates
|
||||||
$commentMap[$row['comment_id']] = $row;
|
}
|
||||||
|
$row['display_name_formatted'] = $row['display_name'] ?: ($row['user_name'] ?? 'Unknown User');
|
||||||
|
$row['replies'] = [];
|
||||||
|
$row['thread_depth'] = $depth + 1;
|
||||||
|
$commentMap[$row['comment_id']] = $row;
|
||||||
|
$nextParentIds[] = $row['comment_id'];
|
||||||
|
}
|
||||||
|
$parentIds = $nextParentIds;
|
||||||
|
$depth++;
|
||||||
}
|
}
|
||||||
|
|
||||||
$rootComments = [];
|
$rootComments = [];
|
||||||
|
|||||||
@@ -190,14 +190,25 @@ class DependencyModel
|
|||||||
*/
|
*/
|
||||||
private function wouldCreateCycle($ticketId, $dependsOnId, $type): bool
|
private function wouldCreateCycle($ticketId, $dependsOnId, $type): bool
|
||||||
{
|
{
|
||||||
// Only check for cycles in blocking relationships
|
// Only blocking relationships impose an ordering that can form a cycle.
|
||||||
if (!in_array($type, ['blocks', 'blocked_by'])) {
|
if (!in_array($type, ['blocks', 'blocked_by'])) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check if dependsOnId already has ticketId in its dependency chain
|
// Normalize the new row to a precedence edge "from must finish before to":
|
||||||
|
// (t, d, 'blocks') => t blocks d => edge t -> d
|
||||||
|
// (t, d, 'blocked_by') => t blocked_by d => edge d -> t
|
||||||
|
if ($type === 'blocks') {
|
||||||
|
$from = $ticketId;
|
||||||
|
$to = $dependsOnId;
|
||||||
|
} else { // blocked_by
|
||||||
|
$from = $dependsOnId;
|
||||||
|
$to = $ticketId;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Adding edge from->to creates a cycle iff a path to ->* from already exists.
|
||||||
$visited = [];
|
$visited = [];
|
||||||
return $this->hasDependencyPath($dependsOnId, $ticketId, $visited, 0);
|
return $this->hasDependencyPath($to, $from, $visited, 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -236,15 +247,22 @@ class DependencyModel
|
|||||||
|
|
||||||
$visited[] = $source;
|
$visited[] = $source;
|
||||||
|
|
||||||
$sql = "SELECT depends_on_id FROM ticket_dependencies
|
// Walk the unified precedence graph forward from $source. Both directions
|
||||||
WHERE ticket_id = ? AND dependency_type IN ('blocks', 'blocked_by')";
|
// of expression contribute an outgoing edge "$source must finish before X":
|
||||||
|
// blocks rows where ticket_id=$source -> X = depends_on_id
|
||||||
|
// blocked_by rows where depends_on_id=$source -> X = ticket_id
|
||||||
|
$sql = "SELECT depends_on_id AS next_id FROM ticket_dependencies
|
||||||
|
WHERE ticket_id = ? AND dependency_type = 'blocks'
|
||||||
|
UNION
|
||||||
|
SELECT ticket_id AS next_id FROM ticket_dependencies
|
||||||
|
WHERE depends_on_id = ? AND dependency_type = 'blocked_by'";
|
||||||
$stmt = $this->conn->prepare($sql);
|
$stmt = $this->conn->prepare($sql);
|
||||||
$stmt->bind_param("s", $source);
|
$stmt->bind_param("ss", $source, $source);
|
||||||
$stmt->execute();
|
$stmt->execute();
|
||||||
$result = $stmt->get_result();
|
$result = $stmt->get_result();
|
||||||
|
|
||||||
while ($row = $result->fetch_assoc()) {
|
while ($row = $result->fetch_assoc()) {
|
||||||
if ($this->hasDependencyPath($row['depends_on_id'], $target, $visited, $depth + 1)) {
|
if ($this->hasDependencyPath($row['next_id'], $target, $visited, $depth + 1)) {
|
||||||
$stmt->close();
|
$stmt->close();
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|||||||
+23
-8
@@ -28,8 +28,14 @@ class StatsModel
|
|||||||
/**
|
/**
|
||||||
* Get tickets by assignee (top 5)
|
* Get tickets by assignee (top 5)
|
||||||
*/
|
*/
|
||||||
public function getTicketsByAssignee(int $limit = 8): array
|
public function getTicketsByAssignee(int $limit = 8, array $visFilter = []): array
|
||||||
{
|
{
|
||||||
|
// Apply the same visibility filter as the rest of the stats so a non-admin's
|
||||||
|
// assignee widget doesn't count (and thereby leak) confidential tickets.
|
||||||
|
$visSQL = $visFilter['sql'] ?? '';
|
||||||
|
$visParams = $visFilter['params'] ?? [];
|
||||||
|
$visTypes = $visFilter['types'] ?? '';
|
||||||
|
|
||||||
$sql = "SELECT
|
$sql = "SELECT
|
||||||
u.user_id,
|
u.user_id,
|
||||||
u.display_name,
|
u.display_name,
|
||||||
@@ -37,12 +43,20 @@ class StatsModel
|
|||||||
COUNT(t.ticket_id) as open_count
|
COUNT(t.ticket_id) as open_count
|
||||||
FROM tickets t
|
FROM tickets t
|
||||||
LEFT JOIN users u ON t.assigned_to = u.user_id
|
LEFT JOIN users u ON t.assigned_to = u.user_id
|
||||||
WHERE t.status != 'Closed' AND t.assigned_to IS NOT NULL
|
WHERE t.status != 'Closed' AND t.assigned_to IS NOT NULL";
|
||||||
GROUP BY t.assigned_to
|
if ($visSQL !== '') {
|
||||||
ORDER BY open_count DESC
|
$sql .= " AND ($visSQL)";
|
||||||
LIMIT ?";
|
}
|
||||||
|
$sql .= " GROUP BY t.assigned_to
|
||||||
|
ORDER BY open_count DESC
|
||||||
|
LIMIT ?";
|
||||||
|
|
||||||
|
$params = $visParams;
|
||||||
|
$params[] = $limit;
|
||||||
|
$types = $visTypes . 'i';
|
||||||
|
|
||||||
$stmt = $this->conn->prepare($sql);
|
$stmt = $this->conn->prepare($sql);
|
||||||
$stmt->bind_param('i', $limit);
|
$stmt->bind_param($types, ...$params);
|
||||||
$stmt->execute();
|
$stmt->execute();
|
||||||
$result = $stmt->get_result();
|
$result = $stmt->get_result();
|
||||||
$data = [];
|
$data = [];
|
||||||
@@ -173,8 +187,9 @@ class StatsModel
|
|||||||
// Sort priority keys
|
// Sort priority keys
|
||||||
ksort($byPriority);
|
ksort($byPriority);
|
||||||
|
|
||||||
// Query 3: Get assignee stats (requires JOIN, kept separate)
|
// Query 3: Get assignee stats (requires JOIN, kept separate). Pass the same
|
||||||
$byAssignee = $this->getTicketsByAssignee();
|
// visibility filter so confidential tickets aren't counted for non-admins.
|
||||||
|
$byAssignee = $this->getTicketsByAssignee(8, $visFilter);
|
||||||
|
|
||||||
return [
|
return [
|
||||||
'open_tickets' => (int)($counts['open_tickets'] ?? 0),
|
'open_tickets' => (int)($counts['open_tickets'] ?? 0),
|
||||||
|
|||||||
Reference in New Issue
Block a user