Lint / PHP (phpcs PSR-12) (push) Successful in 19s
Lint / JS (eslint) (push) Successful in 7s
Lint / PHP requirements (version + extensions) (push) Successful in 23s
Lint / Notify on failure (push) Skipped
Security / PHP Security (semgrep) (push) Successful in 1m4s
Lint / Deploy (push) Successful in 2s
processBulkOperation()'s docblock claimed the transaction "ensures atomicity - either all tickets are updated or none are," but that's only true when $atomic = true is passed, and the only real caller (api/bulk_operation.php) never passes it — the actual default is best-effort: per-ticket failures are skipped and recorded, and every other ticket in the batch still commits. Reworded the docblock to describe the actual default behavior and when $atomic changes it. The model already collected per-ticket failure reasons into $result['errors'] (dashboard.js's bulkResultMessage() already reads data.errors to render them), but api/bulk_operation.php's success response dropped that field entirely, so admins only ever saw a bare "N succeeded, M failed" count with no way to see which tickets failed or why. Added 'errors' to the response when present. Verified against real MariaDB: a bulk_status operation against a Closed ticket (no transition defined) and an Open ticket (Open->Pending defined) correctly processed 1/1, and the API response now includes errors: ["Ticket ...: transition not allowed (Closed -> Pending)"]. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_0117oBw2jN4kALYeS8HPq4zV
150 lines
5.1 KiB
PHP
150 lines
5.1 KiB
PHP
<?php
|
|
|
|
require_once dirname(__DIR__) . '/helpers/ErrorHandler.php';
|
|
ErrorHandler::init();
|
|
|
|
// Apply rate limiting
|
|
require_once dirname(__DIR__) . '/middleware/RateLimitMiddleware.php';
|
|
RateLimitMiddleware::apply('api');
|
|
|
|
require_once dirname(__DIR__) . '/config/config.php';
|
|
require_once dirname(__DIR__) . '/helpers/Database.php';
|
|
require_once dirname(__DIR__) . '/models/BulkOperationsModel.php';
|
|
require_once dirname(__DIR__) . '/models/TicketModel.php';
|
|
require_once dirname(__DIR__) . '/models/AuditLogModel.php';
|
|
|
|
header('Content-Type: application/json');
|
|
|
|
// Check authentication
|
|
if (!isset($_SESSION['user']) || !isset($_SESSION['user']['user_id'])) {
|
|
http_response_code(401);
|
|
echo json_encode(['success' => false, 'error' => 'Not authenticated']);
|
|
exit;
|
|
}
|
|
|
|
// CSRF Protection for all state-changing methods (any non-GET/HEAD request)
|
|
require_once dirname(__DIR__) . '/middleware/CsrfMiddleware.php';
|
|
if (!in_array($_SERVER['REQUEST_METHOD'], ['GET', 'HEAD'], true)) {
|
|
$csrfToken = $_SERVER['HTTP_X_CSRF_TOKEN'] ?? '';
|
|
if (!CsrfMiddleware::validateToken($csrfToken)) {
|
|
http_response_code(403);
|
|
echo json_encode(['success' => false, 'error' => 'Invalid CSRF token', 'csrf_token' => CsrfMiddleware::getToken()]);
|
|
exit;
|
|
}
|
|
}
|
|
|
|
// Check admin status - bulk operations are admin-only
|
|
$isAdmin = $_SESSION['user']['is_admin'] ?? false;
|
|
if (!$isAdmin) {
|
|
http_response_code(403);
|
|
echo json_encode(['success' => false, 'error' => 'Admin access required']);
|
|
exit;
|
|
}
|
|
|
|
// Get request data
|
|
$data = json_decode(file_get_contents('php://input'), true);
|
|
$operationType = $data['operation_type'] ?? null;
|
|
$ticketIds = $data['ticket_ids'] ?? [];
|
|
$parameters = $data['parameters'] ?? null;
|
|
|
|
// Validate input
|
|
$validOperationTypes = ['bulk_close', 'bulk_assign', 'bulk_priority', 'bulk_status', 'bulk_delete'];
|
|
if (!$operationType || !in_array($operationType, $validOperationTypes, true) || empty($ticketIds)) {
|
|
http_response_code(400);
|
|
echo json_encode(['success' => false, 'error' => 'Operation type and ticket IDs required']);
|
|
exit;
|
|
}
|
|
|
|
// Validate ticket IDs: must be non-empty numeric strings (allows leading zeros)
|
|
$ticketIds = array_values(array_filter(array_map(function ($id) {
|
|
$s = trim((string)$id);
|
|
return (ctype_digit($s) && (int)$s > 0) ? $s : null;
|
|
}, $ticketIds)));
|
|
if (empty($ticketIds)) {
|
|
http_response_code(400);
|
|
echo json_encode(['success' => false, 'error' => 'No valid ticket IDs provided']);
|
|
exit;
|
|
}
|
|
|
|
// Use centralized database connection
|
|
$conn = Database::getConnection();
|
|
|
|
$bulkOpsModel = new BulkOperationsModel($conn);
|
|
$ticketModel = new TicketModel($conn);
|
|
|
|
// Verify user can access all tickets in the bulk operation
|
|
// (Admins can access all, but this is defense-in-depth)
|
|
$accessibleTicketIds = [];
|
|
$inaccessibleCount = 0;
|
|
$tickets = $ticketModel->getTicketsByIds($ticketIds);
|
|
|
|
foreach ($ticketIds as $ticketId) {
|
|
$ticketId = trim($ticketId);
|
|
$ticket = $tickets[$ticketId] ?? null;
|
|
|
|
if ($ticket && $ticketModel->canUserAccessTicket($ticket, $_SESSION['user'])) {
|
|
$accessibleTicketIds[] = $ticketId;
|
|
} else {
|
|
$inaccessibleCount++;
|
|
}
|
|
}
|
|
|
|
if (empty($accessibleTicketIds)) {
|
|
echo json_encode(['success' => false, 'error' => 'No accessible tickets in selection']);
|
|
exit;
|
|
}
|
|
|
|
// Use only accessible ticket IDs
|
|
$ticketIds = $accessibleTicketIds;
|
|
|
|
// Create bulk operation record
|
|
$operationId = $bulkOpsModel->createBulkOperation($operationType, $ticketIds, $_SESSION['user']['user_id'], $parameters);
|
|
|
|
if (!$operationId) {
|
|
echo json_encode(['success' => false, 'error' => 'Failed to create bulk operation']);
|
|
exit;
|
|
}
|
|
|
|
// Process the bulk operation
|
|
$result = $bulkOpsModel->processBulkOperation($operationId);
|
|
|
|
if (isset($result['error'])) {
|
|
$conn->close();
|
|
$response = [
|
|
'success' => false,
|
|
'error' => $result['error']
|
|
];
|
|
// Let the client know it should collect a comment and retry, rather than
|
|
// showing the failure as a dead end.
|
|
if (!empty($result['requires_comment'])) {
|
|
$response['requires_comment'] = true;
|
|
http_response_code(400);
|
|
}
|
|
echo json_encode($response);
|
|
} else {
|
|
// Invalidate stats cache so dashboard tiles reflect changes immediately
|
|
require_once dirname(__DIR__) . '/models/StatsModel.php';
|
|
(new StatsModel($conn))->invalidateCache();
|
|
$conn->close();
|
|
|
|
$message = "Bulk operation completed: {$result['processed']} succeeded, {$result['failed']} failed";
|
|
if ($inaccessibleCount > 0) {
|
|
$message .= " ($inaccessibleCount skipped - no access)";
|
|
}
|
|
$response = [
|
|
'success' => true,
|
|
'operation_id' => $operationId,
|
|
'processed' => $result['processed'],
|
|
'failed' => $result['failed'],
|
|
'skipped' => $inaccessibleCount,
|
|
'message' => $message
|
|
];
|
|
// Best-effort batches (the default; see processBulkOperation()'s docblock)
|
|
// can partially fail — surface the per-ticket reasons so the admin isn't
|
|
// just told a count. The dashboard's bulkResultMessage() already expects this.
|
|
if (!empty($result['errors'])) {
|
|
$response['errors'] = $result['errors'];
|
|
}
|
|
echo json_encode($response);
|
|
}
|