Repository navigation
Expand file tree
/
Copy pathLibriController.php
More file actions
4199 lines (3787 loc) · 187 KB
/
Copy pathLibriController.php
File metadata and controls
4199 lines (3787 loc) · 187 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
declare(strict_types=1);
namespace App\Controllers;
use mysqli;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use App\Support\SecureLogger;
use App\Support\Csv;
use App\Support\LibraryThingInstaller;
use App\Models\SeriesRepository;
use Slim\Exception\HttpNotFoundException;
class LibriController
{
/**
* Centralized whitelist of allowed domains for external cover image downloads
* Used by both downloadExternalCover() and isUrlAllowed()
*/
private const COVER_ALLOWED_DOMAINS = [
// Google Books
'books.google.com',
'books.google.it',
'images.google.com',
// Open Library
'covers.openlibrary.org',
// Italian bookstores
'www.libreriauniversitaria.it',
'img.libreriauniversitaria.it',
'img2.libreriauniversitaria.it',
'img3.libreriauniversitaria.it',
'cdn.mondadoristore.it',
'www.lafeltrinelli.it',
// Amazon
'images.amazon.com',
'images-na.ssl-images-amazon.com',
'images-eu.ssl-images-amazon.com',
// Ubik Libri
'www.ubiklibri.it',
'ubiklibri.it',
// Internet Archive — covers.openlibrary.org 302-redirects here (issue #173)
'archive.org',
];
/**
* Wide suffix allow-list for cover hosts (issue #173). Exact-host matching kept
* blocking legitimate sources whose CDN host is dynamic — most notably
* covers.openlibrary.org, which 302s to archive.org / iaNNNNNN.us.archive.org.
* These suffixes cover the major book-cover CDNs. SSRF is still bounded by the
* private/reserved-IP check, the image-content validation and the size cap below.
*/
private const COVER_ALLOWED_SUFFIXES = [
'.archive.org',
'.openlibrary.org',
'.googleusercontent.com', '.ggpht.com', '.gstatic.com', '.googleapis.com', '.google.com',
'.ssl-images-amazon.com', '.media-amazon.com', '.images-amazon.com', '.amazonaws.com',
'.cloudfront.net', '.akamaized.net', '.akamaihd.net', '.fastly.net', '.cloudflare.com',
'.cloudinary.com', '.imgix.net', '.wikimedia.org',
'.gr-assets.com', '.images-bn.com', '.bookshop.org',
'.libreriauniversitaria.it', '.mondadoristore.it', '.lafeltrinelli.it', '.ibs.it', '.ubiklibri.it',
];
/**
* Whether a host may be fetched as a cover source: exact match in
* COVER_ALLOWED_DOMAINS, or ends with one of the wide COVER_ALLOWED_SUFFIXES.
*/
private static function coverHostAllowed(string $host): bool
{
if ($host === '') {
return false;
}
$host = strtolower($host);
if (\in_array($host, self::COVER_ALLOWED_DOMAINS, true)) {
return true;
}
foreach (self::COVER_ALLOWED_SUFFIXES as $suffix) {
if (str_ends_with($host, $suffix)) {
return true;
}
}
return false;
}
/**
* Maximum file size for cover downloads (5MB)
*/
private const MAX_COVER_SIZE = 5 * 1024 * 1024;
/**
* Default values for LibraryThing fields (27 unique fields)
* Used by both store() and update() to avoid duplication
*/
private const LIBRARYTHING_FIELDS_DEFAULTS = [
'review' => null,
'rating' => null,
'comment' => null,
'private_comment' => null,
'physical_description' => null,
'dewey_wording' => null,
'lccn' => null,
'lc_classification' => null,
'other_call_number' => null,
'entry_date' => null,
'date_started' => null,
'date_read' => null,
'bcid' => null,
'barcode' => null,
'oclc' => null,
'work_id' => null,
'original_languages' => null,
'source' => null,
'from_where' => null,
'lending_patron' => null,
'lending_status' => null,
'lending_start' => null,
'lending_end' => null,
'value' => null,
'condition_lt' => null,
];
/**
* Get the storage directory path
* Centralized configuration for storage location
*/
private function getStoragePath(): string
{
return __DIR__ . '/../../storage';
}
/**
* Get the uploads directory path for covers
* Centralized configuration for upload location
*/
private function getCoversUploadPath(): string
{
return __DIR__ . '/../../public/uploads/copertine';
}
/**
* Get the relative URL path for covers (from web root)
*/
private function getCoversUrlPath(): string
{
return '/uploads/copertine';
}
private function syncSeriesMetadataFromBookForm(mysqli $db, int $bookId, array $fields, array $data): void
{
try {
(new SeriesRepository($db))->syncBookFromForm($bookId, $fields, $data);
} catch (\Throwable $e) {
SecureLogger::warning('LibriController::syncSeriesMetadataFromBookForm failed', [
'error' => $e->getMessage(),
'libro_id' => $bookId,
'collana' => $fields['collana'] ?? '',
]);
}
}
/**
* Download external cover image and save locally
*
* @param string|null $url External URL or local path
* @return string|null Local URL path on success, original URL on failure, null/empty passed through
*/
private function downloadExternalCover(?string $url): ?string
{
if ($url === null || $url === '' || !preg_match('#^https?://#i', $url)) {
return $url; // Not an external URL, return as-is
}
// Fix HTML-encoded ampersands from Google Books API URLs
$url = html_entity_decode($url, ENT_QUOTES | ENT_HTML5, 'UTF-8');
$parsedUrl = parse_url($url);
$host = strtolower($parsedUrl['host'] ?? '');
// Initial host: wide cover allow-list (exact + suffix). The real SSRF
// boundary is the public-IP check after each request, not this list.
if (!self::coverHostAllowed($host)) {
\App\Support\SecureLogger::warning('Cover download from non-whitelisted domain', ['url' => $url, 'host' => $host]);
return $url; // Return original URL if domain not allowed
}
try {
// SSRF-safe fetch: redirects are followed MANUALLY, each hop's host is
// resolved to a validated PUBLIC IP and pinned via CURLOPT_RESOLVE, with a
// size cap and image validation (App\Support\SsrfGuard). This is what lets
// the cover allow-list stay wide (issue #173) without an SSRF: a wide host
// can still never make the server reach an internal/reserved IP, on any hop.
$fetched = \App\Support\SsrfGuard::fetchImage($url, self::MAX_COVER_SIZE);
if ($fetched === null) {
\App\Support\SecureLogger::warning('Cover not saved locally: SSRF-safe fetch blocked or failed', ['url' => $url]);
return $url; // keep the original URL when we cannot safely localise it
}
[$imageData, $mimeType] = $fetched;
$extension = match ($mimeType) {
'image/jpeg', 'image/jpg' => 'jpg',
'image/png' => 'png',
default => null,
};
if ($extension === null) {
return $url; // Unsupported format
}
// Ensure upload directory exists
$uploadDir = $this->getCoversUploadPath();
if (!is_dir($uploadDir)) {
mkdir($uploadDir, 0755, true);
}
// Generate unique filename and save
$filename = 'copertina_' . uniqid('', true) . '.' . $extension;
$filepath = $uploadDir . '/' . $filename;
// Create image resource and save
$image = imagecreatefromstring($imageData);
if ($image === false) {
SecureLogger::warning('Cover image processing failed: imagecreatefromstring returned false', [
'url' => $url,
'data_length' => strlen($imageData),
]);
return $url;
}
$saveResult = match ($extension) {
'png' => imagepng($image, $filepath, 9),
default => imagejpeg($image, $filepath, 85),
};
imagedestroy($image);
if (!$saveResult) {
SecureLogger::warning('Cover image save failed', [
'url' => $url,
'filepath' => $filepath,
'extension' => $extension,
]);
return $url;
}
chmod($filepath, 0644);
\App\Support\SecureLogger::info('Cover downloaded successfully', ['url' => $url, 'local' => $filename]);
return $this->getCoversUrlPath() . '/' . $filename;
} catch (\Throwable $e) {
\App\Support\SecureLogger::error('Cover download exception', ['url' => $url, 'error' => $e->getMessage()]);
return $url; // Return original URL on any error
}
}
/**
* Normalize text fields by removing MARC-8 control characters and collapsing whitespace
* MARC-8 uses characters like NSB (0x88, 0x98) and NSE (0x89, 0x9C) for non-sorting blocks
* These appear as invisible characters or ? when stored in MySQL with UTF-8
*/
private function normalizeText(?string $text): string
{
if ($text === null || $text === '') {
return '';
}
// Remove C1 control characters (U+0080–U+009F) including MARC-8 NSB/NSE markers.
// MUST use /u flag to match Unicode code points, not raw bytes — without it,
// continuation bytes in multi-byte UTF-8 chars like Ø (0xC3 0x98) get stripped.
$text = preg_replace('/[\x{0080}-\x{009F}]/u', '', $text) ?? $text;
// Collapse multiple whitespace into single space and trim
$text = trim(preg_replace('/\s+/u', ' ', $text) ?? $text);
return $text;
}
/**
* Normalize and validate ISSN. Returns canonical XXXX-XXXX format, null for empty, or throws on invalid.
* @throws \InvalidArgumentException if ISSN format is invalid
*/
private function normalizeIssn(?string $raw): ?string
{
$issnRaw = trim((string) $raw);
if ($issnRaw === '') {
return null;
}
$issnCompact = strtoupper(str_replace('-', '', preg_replace('/\s+/', '', $issnRaw)));
if (!preg_match('/^\d{7}[\dX]$/', $issnCompact)) {
throw new \InvalidArgumentException('invalid_issn');
}
return substr($issnCompact, 0, 4) . '-' . substr($issnCompact, 4, 4);
}
/**
* Rotate log files to prevent unlimited growth
* Keeps only last 7 days of logs, max 10MB per file
*/
private function rotateLogFile(string $logFile): void
{
if (!file_exists($logFile)) {
return;
}
$maxSize = 10 * 1024 * 1024; // 10MB
$maxAge = 7 * 24 * 60 * 60; // 7 days
// Check size
if (filesize($logFile) > $maxSize) {
// Rotate by renaming
$rotated = $logFile . '.' . date('Y-m-d_His');
rename($logFile, $rotated);
}
// Clean old rotated logs
$dir = dirname($logFile);
$basename = basename($logFile);
$pattern = $dir . '/' . $basename . '.*';
foreach (glob($pattern) as $oldLog) {
if (filemtime($oldLog) < time() - $maxAge) {
// nosemgrep: php.lang.security.unlink-use.unlink-use -- glob() restricted to the app log directory; rotated-log names are app-generated, not user input
unlink($oldLog);
}
}
}
private function logCoverDebug(string $label, array $data): void
{
if (getenv('APP_ENV') === 'development') {
$logDir = $this->getStoragePath();
// Create directory if not exists
if (!is_dir($logDir)) {
mkdir($logDir, 0755, true);
}
$file = $logDir . '/cover_debug.log';
// Rotate log before writing
$this->rotateLogFile($file);
// Enhanced sanitization - remove any sensitive data
$sanitized = $data;
$sensitiveKeys = ['password', 'token', 'csrf_token', 'api_key', 'secret', 'auth'];
foreach ($sensitiveKeys as $key) {
unset($sanitized[$key]);
}
$line = date('Y-m-d H:i:s') . " [$label] " . json_encode($sanitized, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . "\n";
// Use LOCK_EX to prevent race conditions
file_put_contents($file, $line, FILE_APPEND | LOCK_EX);
}
}
/**
* Strip HTML tags and limit publisher name length.
*/
private function sanitizePublisherName(string $name): string
{
$name = trim(strip_tags($name));
if (mb_strlen($name) > 255) {
$name = mb_substr($name, 0, 255);
}
return $name;
}
public function index(Request $request, Response $response, mysqli $db): Response
{
$repo = new \App\Models\BookRepository($db);
$libri = $repo->listWithAuthors(100);
// Resolve genre names for URL filter display
$params = $request->getQueryParams();
$genreFilterName = '';
$subgenreFilterName = '';
$genreId = (int) ($params['genere'] ?? $params['genere_filter'] ?? 0);
$subgenreId = (int) ($params['sottogenere'] ?? $params['sottogenere_filter'] ?? 0);
if ($genreId > 0 || $subgenreId > 0) {
$lookupId = $subgenreId > 0 ? $subgenreId : $genreId;
$stmt = $db->prepare('SELECT nome FROM generi WHERE id = ?');
if ($stmt) {
$stmt->bind_param('i', $lookupId);
$stmt->execute();
$row = $stmt->get_result()->fetch_assoc();
if ($subgenreId > 0) {
$subgenreFilterName = $row['nome'] ?? '';
} else {
$genreFilterName = $row['nome'] ?? '';
}
$stmt->close();
}
if ($genreId > 0 && $subgenreId > 0) {
$stmt2 = $db->prepare('SELECT nome FROM generi WHERE id = ?');
if ($stmt2) {
$stmt2->bind_param('i', $genreId);
$stmt2->execute();
$row2 = $stmt2->get_result()->fetch_assoc();
$genreFilterName = $row2['nome'] ?? '';
$stmt2->close();
}
}
}
ob_start();
$articleHintState = \App\Support\PeriodicalArticlesHint::state($db);
$data = ['libri' => $libri, 'genreFilterName' => $genreFilterName, 'subgenreFilterName' => $subgenreFilterName];
// extract($data);
require __DIR__ . '/../Views/libri/index.php';
$content = ob_get_clean();
ob_start();
require __DIR__ . '/../Views/layout.php';
$html = ob_get_clean();
$response->getBody()->write($html);
return $response;
}
public function show(Request $request, Response $response, mysqli $db, int $id): Response
{
$repo = new \App\Models\BookRepository($db);
$libro = $repo->getById($id);
if (!$libro) {
throw new HttpNotFoundException($request);
}
$loanRepo = new \App\Models\LoanRepository($db);
$activeLoan = $loanRepo->getActiveLoanByBook($id);
// Recupera tutte le copie del libro con informazioni sui prestiti
$copyRepo = new \App\Models\CopyRepository($db);
$copie = $copyRepo->getByBookId($id);
$copySchedule = $copyRepo->getScheduleByBookId($id);
// Borrower identity (name/email/reading history) is GDPR-sensitive and must
// only be exposed to admin/staff. Standard/premium patrons can reach this
// page (route allows them) but must see availability WITHOUT any borrower PII.
$currentUserRole = $_SESSION['user']['tipo_utente'] ?? '';
$isAdminOrStaff = \App\Support\Permissions::can('loans.manage');
// Redact borrower PII from the active loan for non-admin/staff viewers,
// preserving the loan-existence/date fields needed for availability display.
if (!$isAdminOrStaff && !empty($activeLoan)) {
foreach (['utente_nome', 'utente_cognome', 'utente_email', 'utente_id'] as $piiField) {
unset($activeLoan[$piiField]);
}
}
// Redact per-copy current-borrower PII for non-admin/staff viewers.
if (!$isAdminOrStaff) {
foreach ($copie as $ci => $copia) {
foreach (['utente_nome', 'utente_cognome', 'utente_email', 'utente_id'] as $piiField) {
unset($copie[$ci][$piiField]);
}
}
}
// Get loan history for this book — contains borrower PII, so only fetch it
// for admin/staff. Non-admin viewers get an empty history (block hidden).
$loanHistory = [];
if ($isAdminOrStaff) {
$loanHistoryQuery = "
SELECT
p.id,
p.data_prestito,
p.data_scadenza,
p.data_restituzione,
p.stato,
p.renewals,
p.note,
u.nome as utente_nome,
u.cognome as utente_cognome,
u.email as utente_email,
u.id as utente_id,
staff.nome as staff_nome,
staff.cognome as staff_cognome
FROM prestiti p
LEFT JOIN utenti u ON p.utente_id = u.id
LEFT JOIN utenti staff ON p.processed_by = staff.id
WHERE p.libro_id = ?
ORDER BY p.data_prestito DESC
";
$stmt = $db->prepare($loanHistoryQuery);
$stmt->bind_param('i', $id);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
$loanHistory[] = $row;
}
$stmt->close();
}
// Active reservations for this book (admin/staff only - contains PII)
$activeReservations = [];
if ($isAdminOrStaff) {
$resStmt = $db->prepare("
SELECT r.id, r.data_inizio_richiesta, r.data_fine_richiesta, r.data_scadenza_prenotazione,
r.stato, r.queue_position,
u.nome, u.cognome, u.email
FROM prenotazioni r
JOIN utenti u ON u.id = r.utente_id
WHERE r.libro_id = ? AND r.stato = 'attiva'
ORDER BY r.data_inizio_richiesta IS NULL, r.data_inizio_richiesta ASC, r.id ASC
");
$resStmt->bind_param('i', $id);
$resStmt->execute();
$resResult = $resStmt->get_result();
while ($row = $resResult->fetch_assoc()) {
$activeReservations[] = $row;
}
$resStmt->close();
}
// Multi-volume: check if this book is a parent work or a volume
// No INFORMATION_SCHEMA check needed — volumi table is in schema.sql and migrate_0.5.1.sql.
// If prepare() fails (table missing on unmigrated DB), the if($stmt) guard handles it.
$volumes = [];
$parentWork = null;
// Volumes of this work (this book is the parent)
$volStmt = $db->prepare("
SELECT v.numero_volume, v.titolo_volume, l.id, l.titolo, l.isbn13, l.isbn10,
(SELECT " . \App\Support\AuthorName::displaySql('a') . " FROM libri_autori la JOIN autori a ON la.autore_id = a.id
WHERE la.libro_id = l.id AND la.ruolo = 'principale' LIMIT 1) AS autore
FROM volumi v
JOIN libri l ON v.volume_id = l.id AND l.deleted_at IS NULL
WHERE v.opera_id = ?
ORDER BY v.numero_volume
");
if ($volStmt) {
$volStmt->bind_param('i', $id);
$volStmt->execute();
$volRes = $volStmt->get_result();
while ($row = $volRes->fetch_assoc()) {
$volumes[] = $row;
}
$volStmt->close();
}
// Check if this book is a volume of another work
$parentStmt = $db->prepare("
SELECT v.numero_volume, v.titolo_volume, l.id, l.titolo
FROM volumi v
JOIN libri l ON v.opera_id = l.id AND l.deleted_at IS NULL
WHERE v.volume_id = ?
LIMIT 1
");
if ($parentStmt) {
$parentStmt->bind_param('i', $id);
$parentStmt->execute();
$parentRes = $parentStmt->get_result();
$parentWork = $parentRes->fetch_assoc() ?: null;
$parentStmt->close();
}
$libraryThingInstalled = LibraryThingInstaller::isInstalled($db);
// Renewal cap is admin-configurable (loans.max_renewals); pass it to the
// view so the displayed limit and the "Renew" button gate match the
// server-side check in PrestitiController::renew (#157).
$loanSettingsRepo = new \App\Models\SettingsRepository($db);
// Validate numeric BEFORE casting: a non-numeric stored value (e.g. "abc")
// would cast to 0, silently flipping the cap to "no renewals" instead of
// falling back to the safe default. Only a genuine number is honoured.
$rawMaxRenewals = $loanSettingsRepo->get('loans', 'max_renewals', '3');
$maxRenewals = is_numeric($rawMaxRenewals) ? (int) $rawMaxRenewals : 3;
if ($maxRenewals < 0) {
$maxRenewals = 3;
}
// Issue #374: the audit timeline is staff-only. This route is also
// reachable by patrons, so do not even query audit/operator data unless
// the same role gate used for borrower PII has passed.
$activityFeed = ['items' => [], 'page' => 1, 'pages' => 1, 'total' => 0];
if ($isAdminOrStaff) {
$query = $request->getQueryParams();
$rawActivityPage = $query['book_activity_page'] ?? 1;
$activityPage = is_scalar($rawActivityPage)
&& preg_match('/^[1-9]\d*$/D', (string) $rawActivityPage) === 1
? (int) $rawActivityPage
: 1;
$rawActivityQ = $query['activity_q'] ?? '';
$activityQ = is_string($rawActivityQ) ? mb_substr(trim($rawActivityQ), 0, 100) : '';
$rawActivityType = $query['activity_type'] ?? '';
$activityType = is_string($rawActivityType)
&& in_array($rawActivityType, \App\Support\ActivityLog::TYPES, true)
? $rawActivityType
: '';
$activityFeed = \App\Support\ActivityLog::forBook(
$db,
$id,
$activityPage,
20,
$activityQ !== '' ? $activityQ : null,
$activityType !== '' ? $activityType : null
);
}
ob_start();
// extract([
// 'libro' => $libro,
// 'activeLoan' => $activeLoan,
// 'bookPath' => $bookPath,
// 'loanHistory' => $loanHistory,
// 'libraryThingInstalled' => $libraryThingInstalled,
// ]);
require __DIR__ . '/../Views/libri/scheda_libro.php';
$content = ob_get_clean();
ob_start();
require __DIR__ . '/../Views/layout.php';
$html = ob_get_clean();
$response->getBody()->write($html);
return $response;
}
public function createForm(Request $request, Response $response, mysqli $db): Response
{
// For select boxes, load minimal lists
$editRepo = new \App\Models\PublisherRepository($db);
$autRepo = new \App\Models\AuthorRepository($db);
$editori = $editRepo->listBasic();
$autori = $autRepo->listBasic(500);
$colRepo = new \App\Models\CollocationRepository($db);
$taxRepo = new \App\Models\TaxonomyRepository($db);
$scaffali = $colRepo->getScaffali();
$mensole = $colRepo->getMensole();
$generi = $taxRepo->genres();
$sottogeneri = $taxRepo->subgenres();
$libraryThingInstalled = \App\Support\LibraryThingInstaller::isInstalled($db);
$articleHintState = \App\Support\PeriodicalArticlesHint::state($db);
ob_start();
// Variables are available in the template scope via require
require __DIR__ . '/../Views/libri/crea_libro.php';
$content = ob_get_clean();
ob_start();
require __DIR__ . '/../Views/layout.php';
$html = ob_get_clean();
$response->getBody()->write($html);
return $response;
}
/**
* Normalize picker payloads at the HTTP boundary. Empty/zero/garbage values
* emitted by an unenhanced multi-select are ignored here; BookRepository
* remains fail-fast when an invalid id reaches its internal API directly.
*
* @return list<int>
*/
private function positiveIntegerIds(mixed $values): array
{
$ids = [];
foreach ((array) $values as $value) {
if (is_int($value)) {
$id = $value;
} elseif (is_string($value) && preg_match('/^\s*[0-9]+\s*$/D', $value) === 1) {
$id = (int) trim($value);
} else {
continue;
}
if ($id > 0) {
$ids[$id] = $id;
}
}
return array_values($ids);
}
/**
* Resolve a contributor role's picker submission into a flat list of author
* ids (issue #237). Existing selections arrive as `<role>_ids[]`; brand-new
* names as `<role>_new[]`, which are find-or-created just like authors.
* Shared by store() and update() for illustratori/traduttori/curatori/coloristi.
*
* @param array<string,mixed> $data
* @return list<int>
*/
private function resolveContributorIds(mysqli $db, array $data, string $roleKey): array
{
$ids = $this->positiveIntegerIds($data[$roleKey . '_ids'] ?? []);
$newNames = (array)($data[$roleKey . '_new'] ?? []);
if ($newNames !== []) {
$authRepo = new \App\Models\AuthorRepository($db);
foreach ($newNames as $name) {
$name = trim((string)$name);
if ($name === '') {
continue;
}
$existing = $authRepo->findByCanonicalName($name);
$ids[] = $existing ?? $authRepo->create([
'nome' => $name, 'pseudonimo' => '', 'data_nascita' => null,
'data_morte' => null, 'nazionalita' => '', 'biografia' => '', 'sito_web' => '',
]);
}
}
// Backward-compatible ingestion path: callers predating the entity
// pickers still submit singular free-text fields (and the ISBN scraper
// submits scraped_translator/scraped_illustrator). Convert those names
// to entities as well. The marker makes the current admin form
// authoritative: if a librarian removes a scraped chip, its stale
// hidden scraped_* value must not silently add it back on submit.
$pickerIsAuthoritative = (string)($data['contributors_entity_picker'] ?? '') === '1';
if (!$pickerIsAuthoritative) {
$legacySources = [
'illustratori' => ['illustratore', 'scraped_illustrator'],
'traduttori' => ['traduttore', 'scraped_translator'],
'curatori' => ['curatore'],
'coloristi' => ['colorista'],
];
foreach ($legacySources[$roleKey] ?? [] as $sourceKey) {
$raw = $data[$sourceKey] ?? '';
if (!is_scalar($raw) || trim((string)$raw) === '') {
continue;
}
$resolved = \App\Support\ContributorSync::resolveNameIds($db, (string)$raw);
$ids = array_merge($ids, $resolved['ids']);
}
}
return array_values(array_unique(array_filter($ids, static fn($i) => $i > 0)));
}
/**
* Build one bounded advisory-lock name per identifier value. Field names are
* intentionally irrelevant: ISBN-13 and EAN are cross-compared by the
* duplicate query, so the same value must map to the same lock whichever
* field carried it. Sorting makes multi-lock acquisition deadlock-safe.
*
* @param array<string,string> $codes
* @return list<string>
*/
private static function bookIdentifierLockNames(string $databaseName, array $codes): array
{
if ($databaseName === '') {
throw new \RuntimeException('Unable to resolve the current database for identifier locking.');
}
$values = [];
foreach ($codes as $value) {
// Identifier input is ASCII by definition. Normalise the ISBN-10
// check digit as well: the database collation compares x/X as the
// same value, so their advisory-lock identity must do the same.
$normalized = strtoupper(trim((string) $value));
if ($normalized !== '') {
$values[$normalized] = true;
}
}
$values = array_keys($values);
sort($values, SORT_STRING);
return array_map(
static fn(string $value): string => 'pinakes-book-id:' . md5($databaseName . "\0" . $value),
$values
);
}
/** @param array<string,string> $codes @return list<string> */
private function acquireBookIdentifierLocks(mysqli $db, array $codes): array
{
$databaseName = '';
$databaseResult = $db->query('SELECT DATABASE()');
if ($databaseResult instanceof \mysqli_result) {
$databaseName = (string) ($databaseResult->fetch_row()[0] ?? '');
$databaseResult->free();
}
$lockNames = self::bookIdentifierLockNames($databaseName, $codes);
$acquired = [];
try {
foreach ($lockNames as $lockName) {
$stmt = $db->prepare('SELECT GET_LOCK(?, 10)');
if ($stmt === false) {
throw new \RuntimeException('Unable to prepare book-identifier lock.');
}
$stmt->bind_param('s', $lockName);
try {
if (!$stmt->execute()) {
throw new \RuntimeException('Unable to acquire book-identifier lock: ' . $stmt->error);
}
$result = $stmt->get_result();
$locked = $result instanceof \mysqli_result
&& (int) ($result->fetch_row()[0] ?? 0) === 1;
} finally {
$stmt->close();
}
if (!$locked) {
throw new \RuntimeException('Timed out while waiting for a book-identifier lock.');
}
$acquired[] = $lockName;
}
return $acquired;
} catch (\Throwable $e) {
$this->releaseBookIdentifierLocks($db, $acquired);
throw $e;
}
}
/** @param list<string> $lockNames */
private function releaseBookIdentifierLocks(mysqli $db, array $lockNames): void
{
foreach (array_reverse($lockNames) as $lockName) {
try {
$stmt = $db->prepare('SELECT RELEASE_LOCK(?)');
if ($stmt === false) {
continue;
}
$stmt->bind_param('s', $lockName);
try {
$stmt->execute();
} finally {
$stmt->close();
}
} catch (\Throwable $e) {
// Advisory locks are connection-scoped and a broken connection
// releases them server-side. Never mask the original save error.
}
}
}
/**
* Create a book from the admin form: validates input, resolves authors and
* publishers (multi-publisher, issue #143), handles cover + scraping data,
* then persists via BookRepository.
*/
public function store(Request $request, Response $response, mysqli $db): Response
{
$data = $this->parseRequestBody($request);
if ($data === null) {
$_SESSION['error_message'] = __('Impossibile leggere i dati del modulo. Riprova.');
return $response->withHeader('Location', url('/admin/books/create'))->withStatus(302);
}
if (!\App\Support\DigitalAttachments::mayEditSubmission($data)) { return $response->withStatus(403); }
// CSRF validated by CsrfMiddleware
// SECURITY: Debug logging rimosso per prevenire information disclosure
// Il logging dettagliato è disponibile solo in ambiente development tramite AppLog
// Merge all supported fields with defaults
$fields = [
'titolo' => '',
'sottotitolo' => '',
'isbn10' => '',
'isbn13' => '',
'ean' => '',
'issn' => '',
'genere_id' => 0,
'sottogenere_id' => 0,
'editore_id' => 0,
'data_acquisizione' => null,
'tipo_acquisizione' => '',
'descrizione' => '',
'parole_chiave' => '',
'formato' => '',
'peso' => null,
'dimensioni' => '',
'prezzo' => null,
'copie_totali' => 1,
'copie_disponibili' => 1,
'numero_inventario' => '',
'classificazione_dewey' => '',
'collana' => '',
'numero_serie' => '',
'note_varie' => '',
'file_url' => '',
'audio_url' => '',
'copertina_url' => '',
'scaffale_id' => 0,
'mensola_id' => 0,
'posizione_progressiva' => 0,
'posizione_id' => 0,
'collocazione' => '',
'stato' => '',
'lingua' => '',
'anno_pubblicazione' => null,
'edizione' => '',
'luogo_pubblicazione' => '',
'data_pubblicazione' => '',
'numero_pagine' => null,
];
// Merge LibraryThing fields defaults only if plugin installed
if (LibraryThingInstaller::isInstalled($db)) {
$fields = array_merge($fields, self::LIBRARYTHING_FIELDS_DEFAULTS);
}
foreach ($fields as $k => $v) {
if (array_key_exists($k, $data))
$fields[$k] = $data[$k];
}
try {
$fields = \App\Support\DigitalAttachments::applySubmission($fields, $data);
} catch (\InvalidArgumentException $e) {
$response->getBody()->write(json_encode(['error' => 'validation', 'message' => $e->getMessage()], JSON_UNESCAPED_UNICODE));
return $response->withStatus(400)->withHeader('Content-Type', 'application/json');
}
// Normalize text fields to remove MARC-8 control characters and collapse whitespace
$fields['titolo'] = $this->normalizeText($fields['titolo']);
$fields['sottotitolo'] = $this->normalizeText($fields['sottotitolo']);
// Validate title is not empty after normalization
if (trim($fields['titolo']) === '') {
$response->getBody()->write(json_encode([
'error' => true,
'message' => __('Il titolo del libro è obbligatorio.'),
], JSON_UNESCAPED_UNICODE));
return $response->withStatus(422)->withHeader('Content-Type', 'application/json');
}
// Merge scraped subtitle and notes if present
$subtitleFromScrape = trim((string) ($data['subtitle'] ?? ''));
if ($subtitleFromScrape !== '') {
$fields['sottotitolo'] = $this->normalizeText($subtitleFromScrape);
}
$notesParts = [];
$currentNotes = trim((string) ($fields['note_varie'] ?? ''));
if ($currentNotes !== '') {
$notesParts[] = $currentNotes;
}
$notesFromScrape = trim((string) ($data['notes'] ?? ''));
if ($notesFromScrape !== '') {
$notesParts[] = $notesFromScrape;
}
$tipologiaScrape = trim((string) ($data['scraped_tipologia'] ?? ''));
if ($tipologiaScrape !== '') {
$notesParts[] = 'Tipologia: ' . $tipologiaScrape;
}
if ($notesParts) {
$uniqueNotes = [];
foreach ($notesParts as $part) {
$clean = trim($part);
if ($clean === '')
continue;
$exists = false;
foreach ($uniqueNotes as $existing) {
if (strcasecmp($existing, $clean) === 0) {
$exists = true;
break;
}
}
if (!$exists) {
$uniqueNotes[] = $clean;
}
}
$fields['note_varie'] = implode("\n", $uniqueNotes);
}
// Sanitize ISBN/EAN: strip spaces and dashes (server-side safety)
foreach (['isbn10', 'isbn13', 'ean'] as $codeKey) {
if (isset($fields[$codeKey])) {
$rawValue = (string) $fields[$codeKey];
// Input validation: prevent ReDoS by checking length before regex
// ISBN-10: max 13 chars (10 digits + 3 separators), ISBN-13: max 17 chars (13 digits + 4 separators), EAN: max 13
$maxLength = ($codeKey === 'isbn10') ? 13 : (($codeKey === 'isbn13') ? 17 : 13);
if (strlen($rawValue) > $maxLength) {
$rawValue = substr($rawValue, 0, $maxLength);
}
$fields[$codeKey] = preg_replace('/[\s-]+/', '', $rawValue);
}
}
// Normalize + validate ISSN (canonical format: XXXX-XXXX)
if (isset($fields['issn'])) {
try {
$fields['issn'] = $this->normalizeIssn($fields['issn']);
} catch (\InvalidArgumentException $e) {
$_SESSION['error_message'] = __('ISSN non valido. Il formato corretto è XXXX-XXXX (8 cifre, l\'ultima può essere X).');
return $response->withHeader('Location', url('/admin/books/create'))->withStatus(302);
}
}
// Convert empty ISBN/EAN to NULL for UNIQUE constraint compatibility
foreach (['isbn10', 'isbn13', 'ean'] as $codeKey) {
if (isset($fields[$codeKey]) && $fields[$codeKey] === '') {
$fields[$codeKey] = null;
}
}
// Convert 0 to NULL for optional foreign keys to avoid constraint failures
$fields['editore_id'] = empty($fields['editore_id']) || $fields['editore_id'] == 0 ? null : (int) $fields['editore_id'];
$fields['genere_id'] = empty($fields['genere_id']) || $fields['genere_id'] == 0 ? null : (int) $fields['genere_id'];
$fields['sottogenere_id'] = empty($fields['sottogenere_id']) || $fields['sottogenere_id'] == 0 ? null : (int) $fields['sottogenere_id'];
// Reject non-scalar or non-integer input BEFORE casting: (int) "abc" is 0
// and (int) (non-empty array) is 1, both of which would slip past the
// 0..9999 bounds as a silent, wrong copy count. Only a genuine integer
// string is honoured; anything else falls back to zero copies.
$rawCopie = $fields['copie_totali'] ?? 0;
$fields['copie_totali'] = (is_scalar($rawCopie) && preg_match('/^\d+$/', trim((string) $rawCopie)) === 1)
? (int) trim((string) $rawCopie)
: 0;
if ($fields['copie_totali'] > 9999) {
$fields['copie_totali'] = 9999;
}
// In creazione, copie_disponibili = copie_totali (le copie sono tutte nuove e disponibili)
$fields['copie_disponibili'] = $fields['copie_totali'];
$fields['scaffale_id'] = empty($fields['scaffale_id']) ? null : (int) $fields['scaffale_id'];
$fields['mensola_id'] = empty($fields['mensola_id']) ? null : (int) $fields['mensola_id'];
$fields['posizione_progressiva'] = isset($fields['posizione_progressiva']) && $fields['posizione_progressiva'] !== '' ? (int) $fields['posizione_progressiva'] : null;
$fields['posizione_id'] = null;
$fields['peso'] = $fields['peso'] !== null && $fields['peso'] !== '' ? (float) $fields['peso'] : null;
$fields['prezzo'] = $fields['prezzo'] !== null && $fields['prezzo'] !== '' ? (float) $fields['prezzo'] : null;
$numPagineRaw = $fields['numero_pagine'] ?? null;