Repository navigation
Expand file tree
/
Copy pathFrontendController.php
More file actions
3524 lines (3193 loc) · 160 KB
/
Copy pathFrontendController.php
File metadata and controls
3524 lines (3193 loc) · 160 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 App\Repositories\RecensioniRepository;
use App\Support\Branding;
use App\Support\ConfigStore;
use App\Support\HtmlHelper;
use App\Support\QueryCache;
use App\Support\RouteTranslator;
use mysqli;
use Psr\Container\ContainerInterface;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
class FrontendController
{
private ?ContainerInterface $container = null;
public function __construct(?ContainerInterface $container = null)
{
$this->container = $container;
}
public function home(Request $request, Response $response, mysqli $db, ?ContainerInterface $container = null): Response
{
// Use provided container or fallback to instance container
$container = $container ?? $this->container;
// The whole home dataset (CMS sections, latest books, genre carousels,
// events, hero counters) is identical for every visitor. Build it once
// and cache it across requests; content mutations (books, CMS home,
// events) clear the 'home_' prefix via ContentCache — which also
// covers the home_api_count_* keys below — while the TTL covers
// loan-driven availability drift.
$homeData = \App\Support\QueryCache::remember('home_page_data_v2', function () use ($db) {
return $this->buildHomePageData($db);
}, 300);
$homeContent = $homeData['homeContent'];
$sectionsOrdered = $homeData['sectionsOrdered'];
$latest_books = $homeData['latest_books'];
$latestBooksTotal = $homeData['latestBooksTotal'];
$genres_with_books = $homeData['genres_with_books'];
$genreCarouselEnabled = $homeData['genreCarouselEnabled'];
// Availability was stripped before the shared home cache was written;
// re-read it live per request (a stale count is a double-loan risk),
// exactly as the catalog does. On a read failure the rows are flagged
// _availability_unknown and the grid shows the neutral badge.
$latest_books = $this->mergeLiveAvailability($db, $latest_books);
foreach ($genres_with_books as $gi => $gsection) {
if (isset($gsection['books']) && is_array($gsection['books'])) {
$genres_with_books[$gi]['books'] = $this->mergeLiveAvailability($db, $gsection['books']);
}
}
$homeEvents = $homeData['homeEvents'];
$heroTotalBooks = $homeData['totalBooks'];
$heroCovers = $homeData['heroCovers'] ?? [];
// The centred hero style shows no cover fan: drop the covers so the
// page neither downloads them nor preloads the first one. Read per
// request: the style belongs to the active theme, not to the shared
// home cache.
try {
$heroStyle = (new \App\Support\ThemeManager($db))->getPublicStyle()['hero_style'];
if ($heroStyle === 'centered') {
$heroCovers = [];
}
} catch (\Throwable $e) {
// Keep the covers: the fan is hidden by CSS anyway.
}
$heroAvailableBooks = $homeData['availableBooks'];
$heroTotalGenres = $homeData['totalGenres'] ?? null;
$homeEventsEnabled = $homeData['eventsFeatureEnabled'] && !empty($homeEvents);
// Build dynamic SEO data from settings and CMS
$hero = $homeContent['hero'] ?? [];
// Fetch app settings for SEO fallbacks
$appName = \App\Support\ConfigStore::get('app.name', 'Pinakes');
$footerDescription = \App\Support\ConfigStore::get('app.footer_description', '');
$appLogo = Branding::logo();
// Build base URL (includes base path for subfolder installs)
$baseUrl = rtrim(HtmlHelper::getBaseUrl(), '/');
$seoCanonical = $baseUrl . '/';
$brandLogoUrl = $appLogo !== '' ? HtmlHelper::absoluteUrl($appLogo) : '';
$socialImage = Branding::socialImage();
$defaultSocialImage = $socialImage !== '' ? HtmlHelper::absoluteUrl($socialImage) : '';
// === Basic SEO Meta Tags ===
// SEO Title (priority: custom SEO title > hero title > app name)
$seoTitle = !empty($hero['seo_title']) ? $hero['seo_title'] :
(!empty($hero['title']) ? $hero['title'] . ' - ' . $appName : $appName);
// SEO Description (priority: custom SEO description > hero subtitle > footer description > default)
$seoDescription = !empty($hero['seo_description']) ? $hero['seo_description'] :
(!empty($hero['subtitle']) ? $hero['subtitle'] :
($footerDescription ?: __('Esplora il nostro vasto catalogo di libri, prenota i tuoi titoli preferiti e scopri nuove letture')));
// SEO Keywords (custom or defaults)
$seoKeywords = !empty($hero['seo_keywords']) ? $hero['seo_keywords'] :
__('biblioteca, prestito libri, catalogo online, scopri libri, prenotazioni');
// === Open Graph Meta Tags ===
// OG Title (priority: custom og_title > seo_title > hero title > app name)
$ogTitle = !empty($hero['og_title']) ? $hero['og_title'] :
(!empty($hero['seo_title']) ? $hero['seo_title'] :
(!empty($hero['title']) ? $hero['title'] : $appName));
// OG Description (priority: custom og_description > seo_description > hero subtitle > footer description > default)
$ogDescription = !empty($hero['og_description']) ? $hero['og_description'] :
(!empty($hero['seo_description']) ? $hero['seo_description'] :
(!empty($hero['subtitle']) ? $hero['subtitle'] :
($footerDescription ?: __('Esplora il nostro vasto catalogo di libri, prenota i tuoi titoli preferiti e scopri nuove letture'))));
// OG Type (priority: custom og_type > default 'website')
$ogType = !empty($hero['og_type']) ? $hero['og_type'] : 'website';
// OG URL (priority: custom og_url > canonical URL)
$ogUrl = !empty($hero['og_url']) ? $hero['og_url'] : $seoCanonical;
// OG Image (priority: custom og_image > app logo > default cover).
// The retired hero background photo is no longer a fallback: it is
// not shown on the page and the admin can no longer change it.
$ogImage = $defaultSocialImage;
if (!empty($hero['og_image'])) {
$ogImage = HtmlHelper::absoluteUrl($hero['og_image']);
} elseif ($brandLogoUrl !== '') {
$ogImage = $brandLogoUrl;
}
// Keep $seoImage as alias for backward compatibility
$seoImage = $ogImage;
// === Twitter Card Meta Tags ===
// Twitter Card Type (priority: custom twitter_card > default 'summary_large_image')
$twitterCard = !empty($hero['twitter_card']) ? $hero['twitter_card'] : 'summary_large_image';
// Twitter Title (priority: custom twitter_title > og_title > seo_title > hero title > app name)
$twitterTitle = !empty($hero['twitter_title']) ? $hero['twitter_title'] :
(!empty($hero['og_title']) ? $hero['og_title'] :
(!empty($hero['seo_title']) ? $hero['seo_title'] :
(!empty($hero['title']) ? $hero['title'] : $appName)));
// Twitter Description (priority: custom twitter_description > og_description > seo_description > hero subtitle > footer description > default)
$twitterDescription = !empty($hero['twitter_description']) ? $hero['twitter_description'] :
(!empty($hero['og_description']) ? $hero['og_description'] :
(!empty($hero['seo_description']) ? $hero['seo_description'] :
(!empty($hero['subtitle']) ? $hero['subtitle'] :
($footerDescription ?: __('Esplora il nostro vasto catalogo di libri, prenota i tuoi titoli preferiti e scopri nuove letture')))));
// Twitter Image (priority: custom twitter_image > og_image > app logo > default cover)
$twitterImage = $defaultSocialImage;
if (!empty($hero['twitter_image'])) {
$twitterImage = HtmlHelper::absoluteUrl($hero['twitter_image']);
} elseif (!empty($hero['og_image'])) {
$twitterImage = HtmlHelper::absoluteUrl($hero['og_image']);
} elseif ($brandLogoUrl !== '') {
$twitterImage = $brandLogoUrl;
}
// Social media links
// Sanitize social URLs before they can enter the Organization schema's
// sameAs array — an unsanitized javascript:/data: value would otherwise
// leak into the emitted JSON-LD. sanitizePublicHttpUrl() returns '' for
// anything that isn't a clean http(s) URL, so the guards below skip it.
$socialFacebook = \App\Support\HtmlHelper::sanitizePublicHttpUrl((string) \App\Support\ConfigStore::get('app.social_facebook', ''));
$socialTwitter = \App\Support\HtmlHelper::sanitizePublicHttpUrl((string) \App\Support\ConfigStore::get('app.social_twitter', ''));
$socialInstagram = \App\Support\HtmlHelper::sanitizePublicHttpUrl((string) \App\Support\ConfigStore::get('app.social_instagram', ''));
$socialLinkedin = \App\Support\HtmlHelper::sanitizePublicHttpUrl((string) \App\Support\ConfigStore::get('app.social_linkedin', ''));
$socialBluesky = \App\Support\HtmlHelper::sanitizePublicHttpUrl((string) \App\Support\ConfigStore::get('app.social_bluesky', ''));
$socialTelegram = \App\Support\HtmlHelper::sanitizePublicHttpUrl((string) \App\Support\ConfigStore::get('app.social_telegram', ''));
// Build Schema.org structured data
$schemaOrg = [
'@context' => 'https://schema.org',
'@type' => 'WebSite',
'name' => $appName,
'url' => $baseUrl,
'description' => $seoDescription,
];
// Add search action if applicable
$schemaOrg['potentialAction'] = [
'@type' => 'SearchAction',
'target' => [
'@type' => 'EntryPoint',
'urlTemplate' => $baseUrl . RouteTranslator::route('catalog') . '?q={search_term_string}'
],
'query-input' => 'required name=search_term_string'
];
// Add organization schema if logo exists
if ($brandLogoUrl !== '') {
$logoUrl = $brandLogoUrl;
$orgSchema = [
'@context' => 'https://schema.org',
'@type' => 'Organization',
'name' => $appName,
'url' => $baseUrl,
'logo' => $logoUrl,
];
// Add social media profiles
$sameAs = [];
if ($socialFacebook) $sameAs[] = $socialFacebook;
if ($socialTwitter) $sameAs[] = $socialTwitter;
if ($socialInstagram) $sameAs[] = $socialInstagram;
if ($socialLinkedin) $sameAs[] = $socialLinkedin;
if ($socialBluesky) $sameAs[] = $socialBluesky;
if ($socialTelegram) $sameAs[] = $socialTelegram;
if (!empty($sameAs)) {
$orgSchema['sameAs'] = $sameAs;
}
// Combine schemas. JSON_HEX_TAG neutralises any </script> that could
// reach the value (defence in depth on top of the strip_tags at save).
$seoSchema = json_encode([$schemaOrg, $orgSchema], JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT | JSON_HEX_TAG);
} else {
$seoSchema = json_encode($schemaOrg, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT | JSON_HEX_TAG);
}
// Render template
$container = $container ?? $this->container;
ob_start();
include __DIR__ . '/../Views/frontend/home.php';
$content = ob_get_clean();
$response->getBody()->write($content);
return $response
->withHeader('Content-Type', 'text/html')
->withHeader(\App\Support\LiteSpeedCache::MARKER_HEADER, 'home');
}
/**
* The public catalogue: filtered, paginated results under the header the
* admin set for the visitor's language, or the translated default.
*/
public function catalog(Request $request, Response $response, mysqli $db): Response
{
$params = $request->getQueryParams();
// Parametri di paginazione
$limit = 12;
$page = max(1, (int)($params['page'] ?? 1));
$offset = ($page - 1) * $limit;
// Filtri
$filters = $this->getFilters($params);
$where_conditions = $this->buildWhereConditions($filters, $db);
$query_params = $where_conditions['params'];
$param_types = $where_conditions['types'];
// Extra results from plugins (e.g. archive units) when a search is active.
$searchTerm = trim((string) ($filters['search'] ?? ''));
/** @var array<int, array<string, mixed>> $archiveResults */
// The archive lookup is four leading-wildcard LIKEs over every unit:
// only from the third character, when the term can actually select.
$archiveResults = mb_strlen($searchTerm) >= 3
? $this->collectArchiveResults($searchTerm)
: [];
// Federated-search hint: the catalogue search only reads
// libri.search_index, so a term that lives in a plugin's own corpus
// (periodicals, archives, …) would look like "no results" here. Plugins
// answer the search.external_suggestions filter with a link to their
// own search page; the core knows nothing about their tables.
/** @var array<int, array{label: string, url: string}> $externalSearchSuggestions */
$externalSearchSuggestions = $searchTerm !== ''
? $this->collectExternalSearchSuggestions($searchTerm)
: [];
// Asking for a title by name may reach a book the library WANTS and
// does not own (badged in the grid); browsing may not — padding the
// grid and every counter with wishes is a different feature. Without
// the desiderata plugin the two predicates are the same string.
$visibility = $searchTerm !== ''
? \App\Support\BookVisibility::discoverable($db, 'l')
: \App\Support\BookVisibility::catalogue($db, 'l');
// Query base without the many-to-many authors join, so one book stays
// one row. g + gp are sufficient for filtering every supported genre
// level; sottogenere matches directly on l.sottogenere_id.
$base_query = "
FROM libri l
LEFT JOIN editori e ON l.editore_id = e.id
LEFT JOIN generi g ON l.genere_id = g.id
LEFT JOIN generi gp ON g.parent_id = gp.id
WHERE l.deleted_at IS NULL AND " . $visibility . "
";
if (!empty($where_conditions['conditions'])) {
$base_query .= " AND " . implode(' AND ', $where_conditions['conditions']);
}
// Cached total is identical for every page of the same filter set.
// Every join in base_query is many-to-one and filter-only relations use
// EXISTS, so one libri row can never multiply: COUNT(*) avoids the
// unnecessary DISTINCT aggregation. Short TTL; mutations invalidate it.
$catalogCacheSuffix = md5(serialize($this->normalizeFiltersForCache($filters)));
$count_query = "SELECT COUNT(*) as total " . $base_query;
$countLoader = function () use ($db, $count_query, $param_types, $query_params) {
$stmt_count = $db->prepare($count_query);
if (!empty($query_params)) {
$stmt_count->bind_param($param_types, ...$query_params);
}
$stmt_count->execute();
$total_row = $stmt_count->get_result()->fetch_assoc();
$stmt_count->close();
return (int) ($total_row['total'] ?? 0);
};
$total_books = $this->rememberCatalogValue(
$db,
'catalog_count_' . $catalogCacheSuffix,
$filters,
$countLoader
);
$total_pages = ceil($total_books / $limit);
// Query per i libri. Expose the principal author's surname as an
// explicit column so buildOrderBy can reference an alias instead of
// re-running the correlated subquery twice per row (once for the
// NULLs-last predicate, once for the sort value).
$books_query = "
SELECT l.*,
" . $this->catalogAuthorSelect($db) . ",
e.nome AS editore,
g.nome AS genere
" . $base_query . "
" . $this->buildOrderBy($filters['sort']) . "
LIMIT ? OFFSET ?
";
// Listing rows: cached only for the bounded filter states (availability
// fields stripped from the cached copy and merged back live per request).
try {
$mixed = (new \App\Services\UnifiedCatalogService($db))->page(
$base_query, $this->catalogAuthorSelect($db), $param_types, $query_params,
$filters, (int)$total_books, $limit, $offset
);
} catch (\Throwable $e) {
\App\Support\SecureLogger::error('Unified catalogue unavailable', ['error' => $e->getMessage()]);
$mixed = null;
}
$books = $mixed !== null ? $mixed['rows']
: $this->loadCatalogPageRows($db, $books_query, $param_types, $query_params, $filters, $limit, $offset, $page);
$total_articles = $mixed['articles'] ?? 0;
$total_books = $mixed['total'] ?? $total_books;
$total_pages = ceil($total_books / $limit);
if ($mixed !== null) {
$articlePath = url(\App\Support\RouteTranslator::route('periodicals') . '/articoli');
$externalSearchSuggestions = array_values(array_filter($externalSearchSuggestions,
static fn(array $suggestion): bool => !str_starts_with($suggestion['url'], $articlePath . '?')));
}
// Ottieni le opzioni per i filtri
$filter_options = $this->getFilterOptions($db, $filters);
// "All" removes only the loan-availability facet and includes articles.
// Keep this live, outside the cached book-facet projection.
if (($params['with_stats'] ?? '') !== '1') {
try {
$filter_options['availability_stats']['total'] += (new \App\Services\UnifiedCatalogService($db))
->countArticles(array_replace($filters, ['disponibilita' => '']));
} catch (\Throwable $e) {
\App\Support\SecureLogger::error('Article facet count unavailable', ['error' => $e->getMessage()]);
}
}
// Get hierarchical genre display based on current selection
$genre_display = $this->getDisplayGenres($filter_options['generi'], (int)($filters['genere_id'] ?? 0));
// Render template
$container = $this->container;
// The catalog view reads $current_page for the server-rendered pagination
// nav and the initial JS pagination config; the controller tracks it as
// $page. Without this the no-JS nav always marks page 1 active and never
// links past page 5, so pages 6+ are not crawlable.
$current_page = $page;
// Title and subtitle of the header, editable per language in Settings → CMS.
$catalogHeader = [
'title' => __(\App\Support\CatalogHeader::DEFAULT_TITLE),
'subtitle' => __(\App\Support\CatalogHeader::DEFAULT_SUBTITLE),
];
try {
$catalogHeader = \App\Support\CatalogHeader::forLocale(new \App\Models\SettingsRepository($db), \App\Support\I18n::getLocale());
} catch (\Throwable $e) {
\App\Support\SecureLogger::error('Catalog header texts unavailable', ['error' => $e->getMessage()]);
}
ob_start();
// Rendi disponibili tutte le variabili necessarie nel template
include __DIR__ . '/../Views/frontend/catalog.php';
$content = ob_get_clean();
$response->getBody()->write($content);
if ($mixed !== null) {
// Publication can be revoked independently of book holdings.
return $response->withHeader('Content-Type', 'text/html')
->withHeader('Cache-Control', 'private, no-store');
}
return $response
->withHeader('Content-Type', 'text/html')
->withHeader(\App\Support\LiteSpeedCache::MARKER_HEADER, 'catalog');
}
/** Public archive snippets, bounded and stripped of every non-display field. */
private function collectArchiveResults(string $query): array
{
try { $results = \App\Support\Hooks::apply('frontend.catalog.archive_results', [], [mb_substr($query, 0, 200)]); }
catch (\Throwable $e) { \App\Support\SecureLogger::error('Archive catalogue search failed: ' . $e->getMessage()); return []; }
if (!is_array($results)) { return []; }
return array_map(static fn(array $row): array => array_intersect_key($row, array_flip(['id', 'label', 'reference_code', 'url'])),
array_slice(array_values(array_filter($results, 'is_array')), 0, 6));
}
public function catalogAPI(Request $request, Response $response, mysqli $db): Response
{
$params = $request->getQueryParams();
// Parametri di paginazione
$limit = 12;
$page = max(1, (int)($params['page'] ?? 1));
$offset = ($page - 1) * $limit;
// Filtri
$filters = $this->getFilters($params);
$where_conditions = $this->buildWhereConditions($filters, $db);
$query_params = $where_conditions['params'];
$param_types = $where_conditions['types'];
$searchTerm = trim((string) ($filters['search'] ?? ''));
// Public projection only: the same snippets as the server-rendered catalogue.
$archiveResults = mb_strlen($searchTerm) >= 3 ? $this->collectArchiveResults($searchTerm) : [];
ob_start();
include __DIR__ . '/../Views/frontend/partials/catalog-archive-results.php';
$archiveHtml = (string) ob_get_clean();
$visibility = $searchTerm !== ''
? \App\Support\BookVisibility::discoverable($db, 'l')
: \App\Support\BookVisibility::catalogue($db, 'l');
// Same one-row-per-book join shape as catalog(). g + gp cover the
// hierarchy predicates; no unused grandparent/subgenre joins here.
$base_query = "
FROM libri l
LEFT JOIN editori e ON l.editore_id = e.id
LEFT JOIN generi g ON l.genere_id = g.id
LEFT JOIN generi gp ON g.parent_id = gp.id
WHERE l.deleted_at IS NULL AND " . $visibility . "
";
if (!empty($where_conditions['conditions'])) {
$base_query .= " AND " . implode(' AND ', $where_conditions['conditions']);
}
// The base joins are many-to-one, so COUNT(*) is exact without a
// DISTINCT aggregation (same invariant as catalog()).
$catalogCacheSuffix = md5(serialize($this->normalizeFiltersForCache($filters)));
$count_query = "SELECT COUNT(*) as total " . $base_query;
$countLoader = function () use ($db, $count_query, $param_types, $query_params) {
$stmt_count = $db->prepare($count_query);
if (!empty($query_params)) {
$stmt_count->bind_param($param_types, ...$query_params);
}
$stmt_count->execute();
$total_row = $stmt_count->get_result()->fetch_assoc();
$stmt_count->close();
return (int) ($total_row['total'] ?? 0);
};
$total_books = $this->rememberCatalogValue(
$db,
'catalog_count_' . $catalogCacheSuffix,
$filters,
$countLoader
);
$total_pages = ceil($total_books / $limit);
// Query per i libri. Expose the principal author's surname as an
// explicit column so buildOrderBy can reference an alias instead of
// re-running the correlated subquery twice per row (once for the
// NULLs-last predicate, once for the sort value).
$books_query = "
SELECT l.*,
" . $this->catalogAuthorSelect($db) . ",
e.nome AS editore,
g.nome AS genere
" . $base_query . "
" . $this->buildOrderBy($filters['sort']) . "
LIMIT ? OFFSET ?
";
// Listing rows: cached only for the bounded filter states (availability
// fields stripped from the cached copy and merged back live per request).
try {
$mixed = (new \App\Services\UnifiedCatalogService($db))->page(
$base_query, $this->catalogAuthorSelect($db), $param_types, $query_params,
array_merge($filters, ['_books_only' => ($params['with_stats'] ?? '') === '1']), (int)$total_books, $limit, $offset
);
} catch (\Throwable $e) {
\App\Support\SecureLogger::error('Unified catalogue unavailable', ['error' => $e->getMessage()]);
$mixed = null;
}
$books = $mixed !== null ? $mixed['rows']
: $this->loadCatalogPageRows($db, $books_query, $param_types, $query_params, $filters, $limit, $offset, $page);
$total_articles = $mixed['articles'] ?? 0;
$total_books = $mixed['total'] ?? $total_books;
$total_pages = ceil($total_books / $limit);
// Render only the books grid
ob_start();
include __DIR__ . '/../Views/frontend/catalog-grid.php';
$html = ob_get_clean();
// Get updated filter options based on current filters
$filter_options = $this->getFilterOptions($db, $filters);
// "All" removes only the loan-availability facet and includes articles.
// Keep this live, outside the cached book-facet projection.
if (($params['with_stats'] ?? '') !== '1') {
try {
$filter_options['availability_stats']['total'] += (new \App\Services\UnifiedCatalogService($db))
->countArticles(array_replace($filters, ['disponibilita' => '']));
} catch (\Throwable $e) {
\App\Support\SecureLogger::error('Article facet count unavailable', ['error' => $e->getMessage()]);
}
}
// Get hierarchical genre display for correct sidebar rendering
$genre_display = $this->getDisplayGenres($filter_options['generi'], (int)($filters['genere_id'] ?? 0));
// Available-books count (same filter set, restricted to loanable copies)
// so the home hero "Disponibili" stat can show a real number instead of
// a placeholder emoji. Reuses the same bound params as the total count.
//
// FIX F001: this adds a sixth aggregate scan (5 LEFT JOINs) on top of the
// total-count and books queries, yet ONLY the home hero consumes it (a
// single loadStats() fetch). The live catalog search/filter path — which
// hits this endpoint on every keystroke — used to pay for it and throw
// the value away. Gate it behind an explicit `with_stats=1` flag so the
// aggregate runs only when the caller actually needs the number.
//
// When the flag is absent the field stays null; home.php's JS falls back
// to total_books, but only the search path (which never requests stats)
// ever sees that fallback. When the flag IS passed, database failures are
// logged and cached as 0 so the same failing aggregate is not retried on
// every request until the short cache entry expires.
$available_books = null;
if (($params['with_stats'] ?? '') === '1') {
$availabilityLoader = function () use ($db, $base_query, $param_types, $query_params) {
$available_stmt = $db->prepare("SELECT COUNT(*) as total " . $base_query . " AND l.copie_disponibili > 0");
if ($available_stmt === false) {
\App\Support\SecureLogger::error('Available-books count prepare failed', ['db_error' => $db->error]);
return 0;
}
$available_books = 0;
if (!empty($query_params)) {
$available_stmt->bind_param($param_types, ...$query_params);
}
if (!$available_stmt->execute()) {
\App\Support\SecureLogger::error('Available-books count execute failed', ['db_error' => $available_stmt->error]);
} else {
$available_result = $available_stmt->get_result();
if ($available_result === false) {
\App\Support\SecureLogger::error('Available-books count get_result failed', ['db_error' => $available_stmt->error]);
} else {
$available_row = $available_result->fetch_assoc();
$available_books = (int) ($available_row['total'] ?? 0);
}
}
$available_stmt->close();
return $available_books;
};
$available_books = $this->rememberCatalogValue(
$db,
'catalog_avail_' . $catalogCacheSuffix,
$filters,
$availabilityLoader
);
}
$data = [
'html' => $html,
'archive_html' => $archiveHtml,
'pagination' => [
'current_page' => $page,
'total_pages' => $total_pages,
'total_books' => $total_books,
'total_articles' => $total_articles,
'available_books' => $available_books,
'start' => $offset + 1,
'end' => min($offset + $limit, $total_books)
],
'filter_options' => $filter_options,
'genre_display' => $genre_display
];
$response->getBody()->write(json_encode($data));
return $response->withHeader('Content-Type', 'application/json');
}
/**
* Public, no-store batch endpoint used to hydrate availability fragments in
* LiteSpeed-cached HTML. It exposes only the same counts/status already
* visible on public catalog cards and caps input to prevent query abuse.
*/
public function edgeAvailability(Request $request, Response $response, mysqli $db): Response
{
$raw = (string) ($request->getQueryParams()['ids'] ?? '');
$withStats = (string) ($request->getQueryParams()['stats'] ?? '') === '1';
if (($raw === '' && !$withStats) || ($raw !== '' && preg_match('/^\d+(?:,\d+){0,99}$/D', $raw) !== 1)) {
$response->getBody()->write((string) json_encode(['success' => false, 'message' => 'invalid_ids']));
return $response
->withStatus(400)
->withHeader('Content-Type', 'application/json; charset=UTF-8')
->withHeader('Cache-Control', 'no-store, private')
->withHeader('X-LiteSpeed-Cache-Control', 'no-cache');
}
$ids = $raw === '' ? [] : array_values(array_unique(array_map('intval', explode(',', $raw))));
$live = $this->fetchLiveAvailability($db, $ids);
if ($live === null) {
$response->getBody()->write((string) json_encode(['success' => false, 'message' => 'availability_unavailable']));
return $response
->withStatus(503)
->withHeader('Content-Type', 'application/json; charset=UTF-8')
->withHeader('Cache-Control', 'no-store, private')
->withHeader('Retry-After', '30')
->withHeader('X-LiteSpeed-Cache-Control', 'no-cache');
}
// Owned copies and the reason some are not circulating, so the hydrated
// counter says what the server-rendered one says (#426).
$holdingsById = \App\Support\CopyHoldings::forBooks($db, array_map('intval', array_keys($live)));
$books = [];
foreach ($live as $id => $row) {
$holdings = $holdingsById[(int) $id] ?? null;
$publishedTotal = \App\Support\CopyHoldings::publishedTotal($holdings, (int) $row['copie_totali']);
$available = $row['copie_disponibili'] > 0;
$state = $available ? 'available' : match ((string) $row['stato']) {
'prenotato' => 'reserved',
'prestato' => 'borrowed',
default => 'unavailable',
};
$label = match ($state) {
'available' => __('Disponibile'),
'reserved' => __('Prenotato'),
'borrowed' => __('In prestito'),
default => __('Non disponibile'),
};
$books[(string) $id] = [
'available' => $available,
'copies_available' => $row['copie_disponibili'],
// copies_total keeps its meaning (copies in circulation, the
// lending capacity); copies_owned is what the page publishes.
'copies_total' => $row['copie_totali'],
'copies_owned' => $publishedTotal,
'copies_out_of_circulation' => $holdings['out'] ?? 0,
'count_label' => $row['copie_disponibili'] . ' / ' . $publishedTotal,
'count_note' => \App\Support\CopyHoldings::outOfCirculationNote($holdings) === ''
? ''
: __('Copie non in circolazione') . ' — ' . \App\Support\CopyHoldings::outOfCirculationNote($holdings),
'state' => $state,
'label' => $label,
'detail_label' => $available
? ($publishedTotal > 1
? $row['copie_disponibili'] . '/' . $publishedTotal . ' ' . __('Disponibili')
: __('Disponibile'))
: __('Non disponibile oggi'),
'reservable' => !($publishedTotal > 0 && (int) $row['copie_totali'] === 0),
'action_label' => $available
? __('Richiedi Prestito')
: (($publishedTotal > 0 && (int) $row['copie_totali'] === 0)
? __('Momentaneamente non prenotabile')
: __('Prenota Quando Disponibile')),
];
}
$payload = ['success' => true, 'books' => $books];
if ($withStats) {
try {
// This endpoint is deliberately no-store at HTTP level, but the
// aggregate itself may be shared briefly across workers. The
// home_ namespace is bumped by availability/content write paths,
// so changes invalidate it immediately instead of waiting for TTL.
$stats = QueryCache::remember(
'home_edge_availability_stats',
static function () use ($db): array {
$statsResult = $db->query(
'SELECT COUNT(*) AS total_books, '
. 'COALESCE(SUM(copie_disponibili > 0), 0) AS available_books '
. 'FROM libri WHERE deleted_at IS NULL AND ' . \App\Support\BookVisibility::catalogue($db)
);
if ($statsResult === false) {
throw new \RuntimeException('availability stats query returned false: ' . $db->error);
}
$row = $statsResult->fetch_assoc() ?: [];
return [
'total_books' => (int) ($row['total_books'] ?? 0),
'available_books' => (int) ($row['available_books'] ?? 0),
];
},
30
);
$payload['stats'] = [
'total_books' => (int) ($stats['total_books'] ?? 0),
'available_books' => (int) ($stats['available_books'] ?? 0),
];
} catch (\Throwable $e) {
\App\Support\SecureLogger::error('FrontendController: live availability stats failed', [
'error' => $e->getMessage(),
]);
$response->getBody()->write((string) json_encode(['success' => false, 'message' => 'availability_unavailable']));
return $response
->withStatus(503)
->withHeader('Content-Type', 'application/json; charset=UTF-8')
->withHeader('Cache-Control', 'no-store, private')
->withHeader('Retry-After', '30')
->withHeader('X-LiteSpeed-Cache-Control', 'no-cache');
}
}
$response->getBody()->write((string) json_encode($payload, JSON_UNESCAPED_UNICODE));
return $response
->withHeader('Content-Type', 'application/json; charset=UTF-8')
->withHeader('Cache-Control', 'no-store, private')
->withHeader('Pragma', 'no-cache')
->withHeader('X-LiteSpeed-Cache-Control', 'no-cache');
}
/**
* The book as a RIS file (#412), from the same data as the Cite dialog.
* Visibility is the detail page's: a soft-deleted or unknown book is a 404.
*/
public function bookCitationRis(Request $request, Response $response, mysqli $db, int $bookId): Response
{
$live = $this->fetchLiveAvailability($db, [$bookId]);
if (!is_array($live) || !isset($live[$bookId])) {
return $response->withStatus(404);
}
// The same cached DTO as the book page (same key, same TTL): the link
// sits on every public book page, so crawlers fetch it as often.
$detail = \App\Support\QueryCache::remember(
'book_detail_' . \App\Support\I18n::getLocale() . '_' . $bookId,
fn(): ?array => $this->buildBookDetailStatic($db, $bookId),
300
);
if (!is_array($detail) || !isset($detail['book'])) {
return $response->withStatus(404);
}
$book = $detail['book'];
$book['id'] = $bookId;
$recordUrl = absoluteUrl(book_url([
'id' => $bookId,
'titolo' => $book['titolo'] ?? '',
'autore_principale' => $book['autore_principale'] ?? '',
'autori' => $book['autore_principale'] ?? '',
]));
$body = \App\Support\BookCitation::ris(\App\Support\BookCitation::input($book, $detail['authors']), $book, $recordUrl);
$response->getBody()->write($body);
return $response
->withHeader('Content-Type', 'application/x-research-info-systems; charset=UTF-8')
->withHeader('Content-Disposition', 'attachment; filename="book-' . $bookId . '.ris"')
->withHeader('X-Content-Type-Options', 'nosniff');
}
/**
* Render the public book-detail page, loading the book with its authors,
* publishers (issue #143), series, reviews and related volumes.
*/
public function bookDetail(Request $request, Response $response, mysqli $db): Response
{
$params = $request->getQueryParams();
// Verifica che l'ID sia presente e valido
if (!isset($params['id']) || !is_numeric($params['id'])) {
return $this->render404($response);
}
$book_id = (int)$params['id'];
// Static book-detail DTO (issue #387 step 4): the book row, its
// authors, publishers, series and related volumes are identical for
// every visitor and change only through admin write paths that all
// funnel into ContentCache::booksChanged() → 'book_detail_' generation
// bump. Live availability (copie_disponibili/copie_totali/stato) is
// deliberately EXCLUDED from the cached payload and re-read from the
// database on every request further below: a stale availability number
// is a user-facing correctness bug (double-loan), a stale title is not.
$locale = \App\Support\I18n::getLocale();
// Live availability is read FIRST — it is also the soft-delete-aware proof
// that the book exists. Reading it before remember() means an unknown id
// never creates a cache entry (bounded, mirrors hasBoundedCatalogCacheKey);
// a raw scan of nonexistent ids cannot grow storage/cache. Reused below.
$liveBook = $this->fetchLiveAvailability($db, [$book_id]);
if ($liveBook === null) {
return $this->renderAvailabilityUnavailable($response);
}
if (!isset($liveBook[$book_id])) {
return $this->render404($response);
}
$detail = \App\Support\QueryCache::remember(
'book_detail_' . $locale . '_' . $book_id,
function () use ($db, $book_id): ?array {
return $this->buildBookDetailStatic($db, $book_id);
},
300
);
// Defence in depth: a soft-delete racing between the live read above and
// the DTO build yields null (remember() treats null as a miss — never
// negatively cached).
if (!is_array($detail) || !isset($detail['book'])) {
return $this->render404($response);
}
$book = $detail['book'];
$authors = $detail['authors'];
$seriesBooks = $detail['seriesBooks'];
$related_books = $detail['related_books'];
// Series/collection name shown by the "Nella stessa collana" heading.
// buildBookDetailStatic() computes an identically-named local $collana
// for the sibling query but does not return it, so re-derive it here in
// the render scope from the (cached) book row — the field survives
// stripSharedCacheFields(), which preserves display metadata.
$collana = trim((string) ($book['collana'] ?? ''));
// Ensure canonical URL structure (author slug + book slug + ID)
$canonicalPath = book_url([
'id' => $book_id,
'titolo' => $book['titolo'] ?? '',
'autore_principale' => $book['autore_principale'] ?? '',
'autori' => $book['autore_principale'] ?? '',
]);
$currentPath = '/' . ltrim($request->getUri()->getPath(), '/');
if ($currentPath !== $canonicalPath) {
$queryString = $request->getUri()->getQuery();
if (!empty($queryString)) {
$canonicalPath .= '?' . $queryString;
}
return $response->withHeader('Location', $canonicalPath)->withStatus(301);
}
// LIVE availability merge — NEVER served from cache. The book's own
// availability was already read above ($liveBook); here we only refresh
// the related volumes (one indexed primary-key lookup), reusing $liveBook
// for the book itself rather than querying it twice.
$relatedIds = array_map(static fn(array $row): int => (int) ($row['id'] ?? 0), $related_books);
$liveRelated = $relatedIds !== [] ? $this->fetchLiveAvailability($db, $relatedIds) : [];
$book = array_merge($book, $liveBook[$book_id]);
if ($liveRelated === null) {
// The main book's availability is known, so keep rendering the
// page. Preserve static related-volume metadata, but do not invent
// availability values for it while the second live query is down.
$freshRelated = $related_books;
} else {
$freshRelated = [];
foreach ($related_books as $row) {
$rowId = (int) ($row['id'] ?? 0);
if (!isset($liveRelated[$rowId])) {
continue; // soft-deleted since the DTO was cached
}
$freshRelated[] = array_merge($row, $liveRelated[$rowId]);
}
}
$related_books = $freshRelated;
// Approved reviews + statistics: cached per book ('book_reviews_'
// namespace), invalidated on moderation (approve/reject/delete →
// ContentCache::reviewsChanged()). New reviews are 'pendente' and
// never publicly visible, so submission does not need to invalidate.
$reviewsBlock = \App\Support\QueryCache::remember(
'book_reviews_' . $locale . '_' . $book_id,
static function () use ($db, $book_id): array {
$recensioniRepo = new RecensioniRepository($db);
return [
'reviews' => $recensioniRepo->getApprovedReviewsForBook($book_id),
'stats' => $recensioniRepo->getReviewStats($book_id),
];
},
300
);
$reviews = is_array($reviewsBlock['reviews'] ?? null) ? $reviewsBlock['reviews'] : [];
$reviewStats = is_array($reviewsBlock['stats'] ?? null) ? $reviewsBlock['stats'] : [
'total_reviews' => 0,
'average_rating' => 0,
'one_star' => 0,
'two_star' => 0,
'three_star' => 0,
'four_star' => 0,
'five_star' => 0,
];
// Social sharing
$sharingProviders = array_values(array_filter(array_map('trim', explode(',', (string) ConfigStore::get('sharing.enabled_providers', '')))));
$shareUrl = absoluteUrl($canonicalPath);
$shareTitle = $book['titolo'] ?? '';
// Keep the public request calendar aligned with the server-side default
// used when end_date is omitted. The reservation endpoint caps that
// default to max_loan_duration_days, so expose the same effective value
// to the view instead of hardcoding one calendar month in JavaScript.
$loanSettings = new \App\Models\SettingsRepository($db);
$maxRequestDays = $loanSettings->maxLoanDurationDays();
$defaultRequestLoanDays = $loanSettings->requestLoanDurationDays();
// Check whether the BIBFRAME Linked Data plugin is active.
// Done before template include so the view can use $bibframePluginActive.
// Uses PluginManager::isActive() which caches per-process — the raw
// `SELECT 1 FROM plugins ...` here used to run on every render of the
// book-detail page (hottest catalog URL), including anonymous crawls.
$bibframePluginActive = false;
if ($this->container !== null && $this->container->has('pluginManager')) {
try {
/** @var \App\Support\PluginManager $pluginManager */
$pluginManager = $this->container->get('pluginManager');
$bibframePluginActive = $pluginManager->isActive('bibframe-linked-data');
} catch (\Throwable $e) {
\App\Support\SecureLogger::warning('FrontendController: pluginManager lookup failed', [
'error' => $e->getMessage(),
]);
}
}
// Render template
$container = $this->container;
// What the library owns, separate from what it can lend today (#426).
$bookHoldings = \App\Support\CopyHoldings::forBook($db, (int) ($book['id'] ?? 0));
ob_start();
include __DIR__ . '/../Views/frontend/book-detail.php';
$content = ob_get_clean();
// FAIR Signposting (RFC 9264) — machine-discoverable link relations
$bookArr = $book;
$tipoRes = \App\Support\MediaLabels::resolveTipoMedia(
isset($bookArr['formato']) && is_string($bookArr['formato']) ? $bookArr['formato'] : null,
isset($bookArr['tipo_media']) && is_string($bookArr['tipo_media']) ? $bookArr['tipo_media'] : null
);
$signLinks = [
'<https://schema.org/' . \App\Support\MediaLabels::schemaOrgType($tipoRes) . '>; rel="type"',
];
if ($bibframePluginActive) {
$bibframeBookPath = str_replace('{id}', (string) $book_id, RouteTranslator::route('bibframe.book'));
array_unshift($signLinks, '<' . absoluteUrl($bibframeBookPath) . '>; rel="describedby"; type="application/ld+json"');
}
$primaryAuthor = $authors[0] ?? null;
if (is_array($primaryAuthor)) {
$viafUri = '';
if (!empty($primaryAuthor['viaf_uri']) && is_string($primaryAuthor['viaf_uri'])) {
$viafUri = $primaryAuthor['viaf_uri'];
} elseif (!empty($primaryAuthor['viaf_id']) && is_string($primaryAuthor['viaf_id'])) {
$viafUri = 'https://viaf.org/viaf/' . rawurlencode($primaryAuthor['viaf_id']);
}
if ($viafUri !== '' && filter_var($viafUri, FILTER_VALIDATE_URL) !== false
&& preg_match('/^https?:\/\//', $viafUri)
&& strpbrk($viafUri, "<>,\r\n") === false) {
$signLinks[] = '<' . $viafUri . '>; rel="author"';
}
}
$response->getBody()->write($content);
return $response
->withHeader('Content-Type', 'text/html')
->withHeader('Link', implode(', ', $signLinks))
->withHeader(\App\Support\LiteSpeedCache::MARKER_HEADER, 'book:' . $book_id);
}
/**
* Fields whose value depends on live circulation state. They are stripped
* from every cached payload and re-read from the database at request time
* (fetchLiveAvailability), so a warm cache can never serve a stale
* availability number.
*/
private const LIVE_AVAILABILITY_FIELDS = ['copie_disponibili', 'copie_totali', 'stato'];
/**
* Columns fetched by l.* that must never enter a shared public cache.
* search_index is a potentially large denormalized MEDIUMTEXT used only by
* SQL; the remaining LibraryThing fields are explicitly private in the
* frontend and may contain patron identity or loan dates.
*/
private const SHARED_CACHE_EXCLUDED_FIELDS = [
'search_index',
'private_comment',
'lending_patron',
'lending_status',
'lending_start',
'lending_end',
];