Files
VITEC-website/packages/vitec/Classes/UserFunc/DatasheetsJsonRenderer.php
o-rasche 3aaf8fdad5 VITEC headless v14: 5-bug fix unifies plugin renderers + cleanup
Resolves a cascade of TYPO3 v14 breaking changes that left every VITEC
plugin's JSON output silently empty:

1. `list_type` column dropped — all renderer page-discovery queries now
   filter by `CType = 'vitec_X'`.
2. `#[AsAllowedCallable]` attribute added to every public render() —
   without it v14 throws AllowedCallableException, which headless
   silently filters via its "Oops, an error occurred!" guard.
3. `$GLOBALS['TSFE']->id` is null inside JSON cObj context — page id
   now read from the `frontend.page.information` request attribute
   (TSFE fallback kept for legacy entry points).
4. page.tsconfig wizard items migrated to `CType = vitec_X` directly
   (legacy `CType=list, list_type=...` no longer exists in v14).
5. ContainerChildrenProcessor + ContentElementResolver dispatch the
   PLUGIN_RENDERERS map by CType (primary) with list_type fallback.

Beyond the bug fix this commit also contains:
- Datasheets renderer rewritten to "products with newest datasheet"
  semantics (filtered via Download.hideondatasheets).
- New vitec/card content block — multi-purpose card with backend
  preview and layout/background/aspect/alignment/border/shadow options.
- New vitec_container CType (b13 single-column container, FlexForm
  cssClass propagated into the JSON envelope).
- ContentElementResolver service for contentelement/contentelementcta
  link resolution; ContainerChildrenProcessor for nested plugin
  resolution inside b13 containers.
- Vitecset setup.typoscript: ContentElement import moved to top so
  lib.contentElement is defined before VITEC's tt_content blocks.
- Cleanup: 98 .bak.<timestamp> debugging backups removed; *.bak.* and
  /public/_assets_install/ added to .gitignore.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-06-15 14:29:17 +02:00

396 lines
15 KiB
PHP

<?php
declare(strict_types=1);
namespace Evomedien\Vitec\UserFunc;
use TYPO3\CMS\Core\Attribute\AsAllowedCallable;
use Doctrine\DBAL\ParameterType;
use TYPO3\CMS\Core\Database\ConnectionPool;
use TYPO3\CMS\Core\Resource\ResourceFactory;
use TYPO3\CMS\Core\Service\FlexFormService;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Extbase\Service\ImageService;
/**
* UserFunc to render the Datasheets plugin as JSON.
*
* Lists every product that has at least one datasheet, with the LATEST
* datasheet attached. "Datasheet" = a Download linked to the product via
* tx_vitec_product_download_mm with hideondatasheets = 0. "Latest" is
* the download with the highest tstamp.
*
* The plugin is global — the page on which it is placed is not used as
* a filter. FlexForm settings (showFilter, showSearch, itemsPerPage)
* are passed through for the frontend UI to honour.
*
* Exception-safe. Returns '' on failure / nothing to render.
*/
class DatasheetsJsonRenderer
{
#[AsAllowedCallable]
public function render(string $content, array $conf): string
{
$pageId = 0;
$req = $GLOBALS["TYPO3_REQUEST"] ?? null;
if ($req !== null) {
$pi = $req->getAttribute("frontend.page.information");
if ($pi !== null) { $pageId = (int)$pi->getId(); }
}
if ($pageId <= 0) { $pageId = (int)($GLOBALS["TSFE"]->id ?? 0); }
$qb = GeneralUtility::makeInstance(ConnectionPool::class)
->getQueryBuilderForTable('tt_content');
$rows = $qb
->select('*')
->from('tt_content')
->where(
$qb->expr()->eq('pid', $qb->createNamedParameter($pageId, ParameterType::INTEGER)),
$qb->expr()->or(
$qb->expr()->eq('CType', $qb->createNamedParameter('vitec_datasheets', ParameterType::STRING)),
$qb->expr()->and(
$qb->expr()->eq('CType', $qb->createNamedParameter('list', ParameterType::STRING)),
$qb->expr()->eq('CType', $qb->createNamedParameter('vitec_datasheets', ParameterType::STRING))
)
),
$qb->expr()->eq('deleted', 0),
$qb->expr()->eq('hidden', 0)
)
->executeQuery()
->fetchAllAssociative();
if (empty($rows)) {
return '';
}
return $this->renderForRecord($rows[0]);
}
/**
* @param array<string,mixed> $contentElement
*/
public function renderForRecord(array $contentElement): string
{
try {
$flexFormService = GeneralUtility::makeInstance(FlexFormService::class);
$flexFormData = $flexFormService->convertFlexFormContentToArray($contentElement['pi_flexform'] ?? '');
$settings = $flexFormData['settings'] ?? [];
$debugMode = (bool)($settings['debug'] ?? false);
$settingsOut = [
'showFilter' => (bool)($settings['showFilter'] ?? true),
'showSearch' => (bool)($settings['showSearch'] ?? true),
'itemsPerPage' => (int)($settings['itemsPerPage'] ?? 20),
];
// 1) Pull all (product_uid, latest_datasheet_uid) pairs in one query.
// GROUP BY product, take MAX(tstamp) → join back to get that exact download.
$items = $this->fetchProductLatestDatasheetPairs();
// 2) Hydrate each pair: full product + full datasheet objects.
$itemsOut = [];
foreach ($items as $pair) {
$productUid = (int)$pair['product_uid'];
$datasheetUid = (int)$pair['datasheet_uid'];
$product = $this->fetchProduct($productUid);
$datasheet = $this->fetchDownload($datasheetUid);
if (!$product || !$datasheet) {
continue;
}
$itemsOut[] = [
'product' => $this->serializeProduct($product),
'datasheet' => $this->serializeDatasheet($datasheet),
];
}
$response = [
'items' => $itemsOut,
'settings' => $settingsOut,
];
if ($debugMode) {
$response['debug'] = [
'productCount' => count($itemsOut),
'settings' => $settings,
];
}
return json_encode($response);
} catch (\Throwable $e) {
return '';
}
}
/**
* For each visible product that has at least one visible datasheet,
* return [product_uid => latest_datasheet_uid]. Sorted by product title.
*
* @return array<int,array{product_uid:int,datasheet_uid:int}>
*/
private function fetchProductLatestDatasheetPairs(): array
{
$qb = GeneralUtility::makeInstance(ConnectionPool::class)
->getQueryBuilderForTable('tx_vitec_product_download_mm');
$expr = $qb->expr();
// Inner aggregation: for each product, the latest download tstamp.
// We use a single query with JOIN on the same (mm + download) to resolve
// the actual download_uid matching MAX(tstamp). Approach: do it in two
// simple steps to stay SQL-portable.
// Step A: gather all candidate (product_uid, download_uid, tstamp) tuples.
$rows = $qb
->select(
'mm.uid_local AS product_uid',
'mm.uid_foreign AS datasheet_uid',
'd.tstamp AS d_tstamp',
'p.title AS p_title'
)
->from('tx_vitec_product_download_mm', 'mm')
->join('mm', 'tx_vitec_domain_model_download', 'd', 'd.uid = mm.uid_foreign')
->join('mm', 'tx_vitec_domain_model_product', 'p', 'p.uid = mm.uid_local')
->where(
$expr->eq('d.deleted', 0),
$expr->eq('d.hidden', 0),
$expr->eq('d.hideonwebsite', 0),
$expr->eq('d.hideondatasheets', 0),
$expr->eq('p.deleted', 0),
$expr->eq('p.hidden', 0),
$expr->eq('p.hideonwebsite', 0)
)
->executeQuery()
->fetchAllAssociative();
// Step B: reduce to {product_uid => latest datasheet} in PHP.
$latestPerProduct = []; // product_uid => [datasheet_uid, tstamp, title]
foreach ($rows as $r) {
$pUid = (int)$r['product_uid'];
$dUid = (int)$r['datasheet_uid'];
$ts = (int)$r['d_tstamp'];
$title = (string)$r['p_title'];
if (!isset($latestPerProduct[$pUid]) || $ts > $latestPerProduct[$pUid]['tstamp']) {
$latestPerProduct[$pUid] = [
'product_uid' => $pUid,
'datasheet_uid' => $dUid,
'tstamp' => $ts,
'title' => $title,
];
}
}
// Sort by product title ASC.
usort($latestPerProduct, static fn($a, $b) => strcasecmp($a['title'], $b['title']));
// Strip helper fields.
return array_map(
static fn($r) => ['product_uid' => $r['product_uid'], 'datasheet_uid' => $r['datasheet_uid']],
$latestPerProduct
);
}
/**
* @return array<string,mixed>|false
*/
private function fetchProduct(int $uid)
{
$qb = GeneralUtility::makeInstance(ConnectionPool::class)
->getQueryBuilderForTable('tx_vitec_domain_model_product');
return $qb
->select('uid', 'title', 'slug', 'subtitle', 'teaser')
->from('tx_vitec_domain_model_product')
->where(
$qb->expr()->eq('uid', $qb->createNamedParameter($uid, ParameterType::INTEGER)),
$qb->expr()->eq('deleted', 0),
$qb->expr()->eq('hidden', 0)
)
->executeQuery()
->fetchAssociative();
}
/**
* @return array<string,mixed>|false
*/
private function fetchDownload(int $uid)
{
$qb = GeneralUtility::makeInstance(ConnectionPool::class)
->getQueryBuilderForTable('tx_vitec_domain_model_download');
return $qb
->select('*')
->from('tx_vitec_domain_model_download')
->where(
$qb->expr()->eq('uid', $qb->createNamedParameter($uid, ParameterType::INTEGER)),
$qb->expr()->eq('deleted', 0),
$qb->expr()->eq('hidden', 0)
)
->executeQuery()
->fetchAssociative();
}
/**
* @param array<string,mixed> $product
* @return array<string,mixed>
*/
private function serializeProduct(array $product): array
{
$uid = (int)$product['uid'];
return [
'uid' => $uid,
'title' => (string)($product['title'] ?? ''),
'slug' => (string)($product['slug'] ?? ''),
'subtitle' => (string)($product['subtitle'] ?? ''),
'teaser' => (string)($product['teaser'] ?? ''),
'link' => '/product/' . (string)($product['slug'] ?? ''),
'image' => $this->getProductFirstImage($uid),
'categories' => $this->getProductCategories($uid),
];
}
/**
* @param array<string,mixed> $download
* @return array<string,mixed>
*/
private function serializeDatasheet(array $download): array
{
$uid = (int)$download['uid'];
return [
'uid' => $uid,
'title' => (string)($download['title'] ?? ''),
'slug' => (string)($download['slug'] ?? ''),
'teaser' => (string)($download['teaser'] ?? ''),
'description' => (string)($download['description'] ?? ''),
'tstamp' => (int)($download['tstamp'] ?? 0),
'file' => $this->getDownloadFile($uid),
];
}
/**
* @return array<string,mixed>|null
*/
private function getProductFirstImage(int $productUid): ?array
{
$qb = GeneralUtility::makeInstance(ConnectionPool::class)
->getQueryBuilderForTable('sys_file_reference');
$fileRefData = $qb
->select('sfr.uid', 'sfr.title', 'sfr.description', 'sfr.alternative', 'sfr.crop')
->from('sys_file_reference', 'sfr')
->where(
$qb->expr()->eq('sfr.tablenames', $qb->createNamedParameter('tx_vitec_domain_model_product', ParameterType::STRING)),
$qb->expr()->eq('sfr.fieldname', $qb->createNamedParameter('productimage', ParameterType::STRING)),
$qb->expr()->eq('sfr.uid_foreign', $qb->createNamedParameter($productUid, ParameterType::INTEGER)),
$qb->expr()->eq('sfr.deleted', 0),
$qb->expr()->eq('sfr.hidden', 0)
)
->orderBy('sfr.sorting_foreign')
->setMaxResults(1)
->executeQuery()
->fetchAssociative();
if (!$fileRefData) {
return null;
}
try {
$resourceFactory = GeneralUtility::makeInstance(ResourceFactory::class);
$imageService = GeneralUtility::makeInstance(ImageService::class);
$fileReference = $resourceFactory->getFileReferenceObject((int)$fileRefData['uid']);
$default = $imageService->applyProcessingInstructions(
$fileReference,
['width' => 400, 'crop' => $fileRefData['crop'] ?? null]
);
return [
'uid' => (int)$fileRefData['uid'],
'url' => $imageService->getImageUri($default),
'title' => $fileRefData['title'] ?? '',
'alternative' => $fileRefData['alternative'] ?? '',
'description' => $fileRefData['description'] ?? '',
];
} catch (\Exception $e) {
return null;
}
}
private function getProductCategories(int $productUid): array
{
$qb = GeneralUtility::makeInstance(ConnectionPool::class)
->getQueryBuilderForTable('sys_category');
$categories = $qb
->select('c.uid', 'c.title', 'c.description')
->from('sys_category', 'c')
->join(
'c',
'sys_category_record_mm',
'mm',
'mm.uid_local = c.uid AND mm.tablenames = ' .
$qb->createNamedParameter('tx_vitec_domain_model_product', ParameterType::STRING) .
' AND mm.fieldname = ' .
$qb->createNamedParameter('categories', ParameterType::STRING)
)
->where(
$qb->expr()->eq('mm.uid_foreign', $qb->createNamedParameter($productUid, ParameterType::INTEGER)),
$qb->expr()->eq('c.deleted', 0),
$qb->expr()->eq('c.hidden', 0)
)
->orderBy('mm.sorting', 'ASC')
->executeQuery()
->fetchAllAssociative();
return array_map(static function ($cat) {
return [
'uid' => (int)$cat['uid'],
'title' => (string)($cat['title'] ?? ''),
'description' => (string)($cat['description'] ?? ''),
];
}, $categories);
}
/**
* @return array<string,mixed>|null
*/
private function getDownloadFile(int $downloadUid): ?array
{
$qb = GeneralUtility::makeInstance(ConnectionPool::class)
->getQueryBuilderForTable('sys_file_reference');
$row = $qb
->select('fr.uid', 'fr.title', 'fr.description', 'f.uid AS file_uid', 'f.identifier', 'f.name', 'f.size', 'f.extension', 'f.mime_type')
->from('sys_file_reference', 'fr')
->join('fr', 'sys_file', 'f', 'fr.uid_local = f.uid')
->where(
$qb->expr()->eq('fr.tablenames', $qb->createNamedParameter('tx_vitec_domain_model_download', ParameterType::STRING)),
$qb->expr()->eq('fr.fieldname', $qb->createNamedParameter('file', ParameterType::STRING)),
$qb->expr()->eq('fr.uid_foreign', $qb->createNamedParameter($downloadUid, ParameterType::INTEGER)),
$qb->expr()->eq('fr.deleted', 0),
$qb->expr()->eq('f.missing', 0)
)
->orderBy('fr.sorting_foreign', 'ASC')
->setMaxResults(1)
->executeQuery()
->fetchAssociative();
if (!$row) {
return null;
}
return [
'uid' => (int)$row['file_uid'],
'name' => (string)($row['name'] ?? ''),
'url' => '/fileadmin' . ($row['identifier'] ?? ''),
'size' => (int)($row['size'] ?? 0),
'extension' => (string)($row['extension'] ?? ''),
'mimeType' => (string)($row['mime_type'] ?? ''),
'title' => (string)($row['title'] ?? ''),
'description' => (string)($row['description'] ?? ''),
];
}
}