Files
termanager2/app/Http/Controllers/AssignmentPdfController.php

80 lines
2.5 KiB
PHP

<?php
namespace App\Http\Controllers;
use App\Models\Assegnazione;
use Illuminate\Contracts\View\View;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Storage;
use Symfony\Component\HttpFoundation\StreamedResponse;
class AssignmentPdfController extends Controller
{
public function viewer(Request $request, Assegnazione $assignment, string $code): View
{
$this->validateAccess($assignment, $code);
if ($expired = $this->linkScaduto($assignment)) {
return $expired;
}
$pdfUrl = route('assignments.pdf.file', [
'assignment' => $assignment->id,
'code' => $code,
]);
return view('assignments.pdf-viewer', [
'assignment' => $assignment,
'pdfUrl' => $pdfUrl,
'showDownload' => (bool) \App\Models\Setting::getValue('pdf_viewer_show_download', true),
]);
}
public function file(Request $request, Assegnazione $assignment, string $code): StreamedResponse|View
{
$this->validateAccess($assignment, $code);
if ($expired = $this->linkScaduto($assignment)) {
return $expired;
}
$pdfPath = $assignment->territorio?->pdf_path;
abort_unless($pdfPath && Storage::disk('public')->exists($pdfPath), 404);
return Storage::disk('public')->response(
$pdfPath,
'territorio-' . $assignment->territorio?->numero . '.pdf',
[
'Content-Type' => 'application/pdf',
'Content-Disposition' => 'inline; filename="territorio-' . $assignment->territorio?->numero . '.pdf"',
]
);
}
protected function validateAccess(Assegnazione $assignment, string $code): void
{
abort_unless($assignment->pdf_access_code && hash_equals($assignment->pdf_access_code, $code), 404);
abort_unless($assignment->is_aperta, 403);
abort_unless($assignment->territorio?->pdf_path, 404);
}
protected function linkScaduto(Assegnazione $assignment): ?View
{
if (auth()->check()) {
return null;
}
$ttlMonths = max(1, (int) \App\Models\Setting::getValue('assignment_link_ttl_hours', 1));
if ($assignment->assigned_at->copy()->addMonths($ttlMonths)->isPast()) {
return view('assignments.link-scaduto', [
'numero' => $assignment->territorio?->numero,
]);
}
return null;
}
}