Files
VITEC-website/packages/vitec/Classes/UserFunc/DownloadcardcollectionJsonRenderer.php

491 lines
18 KiB
PHP
Executable File

<?php
declare(strict_types=1);
namespace Evomedien\Vitec\UserFunc;
use TYPO3\CMS\Core\Attribute\AsAllowedCallable;
use Doctrine\DBAL\ParameterType;
use TYPO3\CMS\Core\Core\Environment;
use TYPO3\CMS\Core\Database\Connection;
use TYPO3\CMS\Core\Database\ConnectionPool;
use TYPO3\CMS\Core\Resource\ResourceFactory;
use TYPO3\CMS\Core\Service\FlexFormService;
use Evomedien\Vitec\Service\RteResolver;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Extbase\Service\ImageService;
/**
* UserFunc to render the Downloadcardcollection plugin as JSON.
*
* FlexForm-driven (no controller action):
* - settings.download : comma-separated tx_vitec_domain_model_download UIDs
* (selectMultipleSideBySide).
* - settings.image : optional header image (inline FAL on the
* tt_content row, fieldname=image).
* - settings.layout / magstyle / magheader / magtext / maglink / adddetaillink
* are passed through under "settings".
*
* Exception-safe. Returns '' when nothing to render.
*/
class DownloadcardcollectionJsonRenderer
{
#[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_downloadcardcollection', ParameterType::STRING)),
$qb->expr()->and(
$qb->expr()->eq('CType', $qb->createNamedParameter('list', ParameterType::STRING)),
$qb->expr()->eq('CType', $qb->createNamedParameter('vitec_downloadcardcollection', 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 {
$ttContentUid = (int)($contentElement['uid'] ?? 0);
$flexFormService = GeneralUtility::makeInstance(FlexFormService::class);
$flexFormData = $flexFormService->convertFlexFormContentToArray($contentElement['pi_flexform'] ?? '');
$settings = $flexFormData['settings'] ?? [];
$debugMode = (bool)($settings['debug'] ?? false);
// Pass-through settings for the frontend
$settingsOut = [
'layout' => (string)($settings['layout'] ?? ''),
'magstyle' => (bool)($settings['magstyle'] ?? false),
'magheader' => (string)($settings['magheader'] ?? ''),
'magtext' => (string)($settings['magtext'] ?? ''),
'maglink' => (string)($settings['maglink'] ?? ''),
'adddetaillink' => (bool)($settings['adddetaillink'] ?? false),
];
// --- Downloads: comma-separated UID list from settings.download ---
$downloadUids = $this->parseUidList($settings['download'] ?? '');
$downloads = $downloadUids === [] ? [] : $this->fetchDownloadsByUids($downloadUids);
$serializedDownloads = array_map(fn($r) => $this->serializeDownload($r), $downloads);
// --- Header image (inline FAL on this tt_content element, fieldname=image) ---
$image = $this->getCollectionImage($ttContentUid);
$response = [
'image' => $image,
'downloads' => $serializedDownloads,
'settings' => $settingsOut,
];
if ($debugMode) {
$response['debug'] = [
'ttContentUid' => $ttContentUid,
'downloadUids' => $downloadUids,
'downloadCount' => count($downloads),
'settings' => $settings,
'fallbackFiles' => $this->collectFallbackFilesFromDownloads($serializedDownloads),
];
}
return json_encode($response);
} catch (\Throwable $e) {
return '';
}
}
/**
* Accepts "5,7,12" or "5,,7" or even an array-like value. Returns int[].
*
* @return int[]
*/
private function parseUidList(mixed $raw): array
{
if (is_array($raw)) {
$raw = implode(',', $raw);
}
$raw = (string)$raw;
if ($raw === '') {
return [];
}
$uids = array_filter(array_map('intval', explode(',', $raw)), static fn(int $u) => $u > 0);
return array_values(array_unique($uids));
}
/**
* @param int[] $uids
* @return array<int,array<string,mixed>>
*/
private function fetchDownloadsByUids(array $uids): array
{
$qb = GeneralUtility::makeInstance(ConnectionPool::class)
->getQueryBuilderForTable('tx_vitec_domain_model_download');
$rows = $qb
->select('*')
->from('tx_vitec_domain_model_download')
->where(
$qb->expr()->in('uid', $qb->createNamedParameter($uids, Connection::PARAM_INT_ARRAY)),
$qb->expr()->eq('deleted', 0),
$qb->expr()->eq('hidden', 0),
$qb->expr()->eq('hideonwebsite', 0)
)
->executeQuery()
->fetchAllAssociative();
// Preserve the editor-defined order from $uids
$orderMap = array_flip($uids);
usort($rows, static function ($a, $b) use ($orderMap) {
return ($orderMap[(int)$a['uid']] ?? PHP_INT_MAX) <=> ($orderMap[(int)$b['uid']] ?? PHP_INT_MAX);
});
return $rows;
}
/**
* Resolve the inline FAL header image stored on this tt_content row
* (tablenames='tt_content', fieldname='image').
*
* @return array<string,mixed>|null
*/
private function getCollectionImage(int $ttContentUid): ?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('tt_content', ParameterType::STRING)),
$qb->expr()->eq('sfr.fieldname', $qb->createNamedParameter('image', ParameterType::STRING)),
$qb->expr()->eq('sfr.uid_foreign', $qb->createNamedParameter($ttContentUid, 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']);
$srcset = [];
foreach ([400, 800, 1200, 1600] as $width) {
$variant = $imageService->applyProcessingInstructions(
$fileReference,
['width' => $width, 'crop' => $fileRefData['crop'] ?? null, 'fileExtension' => 'webp']
);
$srcset[] = [
'url' => $imageService->getImageUri($variant),
'width' => $width,
'descriptor' => $width . 'w',
];
}
$default = $imageService->applyProcessingInstructions(
$fileReference,
['width' => 800, 'crop' => $fileRefData['crop'] ?? null, 'fileExtension' => 'webp']
);
return [
'uid' => (int)$fileRefData['uid'],
'url' => $imageService->getImageUri($default),
'title' => $fileRefData['title'] ?? '',
'alternative' => $fileRefData['alternative'] ?? '',
'description' => $fileRefData['description'] ?? '',
'srcset' => $srcset,
'properties' => [
'width' => $fileReference->getProperty('width'),
'height' => $fileReference->getProperty('height'),
'mimeType' => $fileReference->getProperty('mime_type'),
],
];
} catch (\Exception $e) {
return null;
}
}
/**
* @param array<string,mixed> $download
* @return array<string,mixed>
*/
protected function serializeDownload(array $download): array
{
$uid = (int)$download['uid'];
$fileprefix = (string)($download['fileprefix'] ?? '');
$filetype = $this->getDownloadFileType($uid);
return [
'uid' => $uid,
'title' => (string)($download['title'] ?? ''),
'slug' => (string)($download['slug'] ?? ''),
'teaser' => (string)($download['teaser'] ?? ''),
'description' => RteResolver::html($download['description'] ?? ''),
'keywords' => (string)($download['keywords'] ?? ''),
'icon' => (string)($download['icon'] ?? ''),
'filepath' => (string)($download['filepath'] ?? ''),
'fileprefix' => $fileprefix,
'filetype' => $filetype,
'private_download' => (bool)($download['private_download'] ?? false),
'hideonapp' => (bool)($download['hideonapp'] ?? false),
'hideonwebsite' => (bool)($download['hideonwebsite'] ?? false),
'hideondatasheets' => (bool)($download['hideondatasheets'] ?? false),
'hideonproducts' => (bool)($download['hideonproducts'] ?? false),
'file' => $this->getDownloadFile($uid, $fileprefix, $filetype),
];
}
private function getDownloadFileType(int $downloadUid): string
{
$qb = GeneralUtility::makeInstance(ConnectionPool::class)
->getQueryBuilderForTable('sys_category');
$categories = $qb
->select('c.filetype')
->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_download', ParameterType::STRING) .
' AND mm.fieldname = ' .
$qb->createNamedParameter('categories', ParameterType::STRING)
)
->where(
$qb->expr()->eq('mm.uid_foreign', $qb->createNamedParameter($downloadUid, ParameterType::INTEGER)),
$qb->expr()->eq('c.deleted', 0),
$qb->expr()->eq('c.hidden', 0),
$qb->expr()->eq('c.parent', $qb->createNamedParameter(4, ParameterType::INTEGER))
)
->orderBy('mm.sorting', 'ASC')
->executeQuery()
->fetchAllAssociative();
foreach ($categories as $category) {
$filetype = trim((string)($category['filetype'] ?? ''));
if ($filetype !== '') {
return $filetype;
}
}
return '';
}
/**
* Resolve the FAL file reference (fieldname=file) for a download.
*
* @return array<string,mixed>|null
*/
protected function getDownloadFile(int $downloadUid, string $fileprefix = '', string $filetype = ''): ?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 $this->resolveFileByConvention($fileprefix, $filetype);
}
$thumbnailUrl = null;
try {
$fileObj = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Resource\ResourceFactory::class)
->getFileObject((int)$row['file_uid']);
$processed = $fileObj->process(
\TYPO3\CMS\Core\Resource\ProcessedFile::CONTEXT_IMAGEPREVIEW,
['width' => 400, 'height' => 566]
);
$thumbnailUrl = $processed->getPublicUrl();
} catch (\Throwable $e) {
// ignore — keep null
}
return [
'uid' => (int)$row['file_uid'],
'name' => (string)($row['name'] ?? ''),
'url' => '/fileadmin' . ($row['identifier'] ?? ''),
'thumbnail' => $thumbnailUrl,
'size' => (int)($row['size'] ?? 0),
'extension' => (string)($row['extension'] ?? ''),
'mimeType' => (string)($row['mime_type'] ?? ''),
'title' => (string)($row['title'] ?? ''),
'description' => (string)($row['description'] ?? ''),
];
}
/**
* @return array<string,mixed>|null
*/
private function resolveFileByConvention(string $fileprefix, string $filetype): ?array
{
$fileprefix = trim($fileprefix);
$filetype = trim($filetype);
if ($fileprefix === '' || $filetype === '') {
return null;
}
$baseDir = Environment::getPublicPath() . '/fileadmin/downloads/Collateral';
if (!is_dir($baseDir) || !is_readable($baseDir)) {
return null;
}
$escapedPrefix = preg_quote($fileprefix, '/');
$escapedType = preg_quote($filetype, '/');
$pattern = '/^' . $escapedPrefix . '__' . $escapedType . '__(\\d+)-([A-Za-z]+)\\.([A-Za-z0-9]+)$/';
$bestFile = null;
$bestNumber = -1;
$bestLetterRank = -1;
$entries = scandir($baseDir);
if ($entries === false) {
return null;
}
foreach ($entries as $entry) {
if (!is_string($entry) || $entry === '.' || $entry === '..') {
continue;
}
if (!preg_match($pattern, $entry, $matches)) {
continue;
}
$number = (int)$matches[1];
$letterRank = $this->letterSequenceToRank((string)$matches[2]);
if ($number > $bestNumber || ($number === $bestNumber && $letterRank > $bestLetterRank)) {
$bestNumber = $number;
$bestLetterRank = $letterRank;
$bestFile = $entry;
}
}
if ($bestFile === null) {
return null;
}
$fullPath = $baseDir . '/' . $bestFile;
if (!is_file($fullPath) || !is_readable($fullPath)) {
return null;
}
$extension = strtolower(pathinfo($bestFile, PATHINFO_EXTENSION));
$mimeType = function_exists('mime_content_type') ? (string)(mime_content_type($fullPath) ?: '') : '';
return [
'uid' => 0,
'name' => $bestFile,
'url' => '/fileadmin/downloads/Collateral/' . rawurlencode($bestFile),
'thumbnail' => null,
'size' => (int)(filesize($fullPath) ?: 0),
'extension' => $extension,
'mimeType' => $mimeType,
'title' => '',
'description' => '',
];
}
private function letterSequenceToRank(string $letters): int
{
$rank = 0;
$letters = strtoupper($letters);
$length = strlen($letters);
for ($i = 0; $i < $length; $i++) {
$char = ord($letters[$i]);
if ($char < 65 || $char > 90) {
continue;
}
$rank = ($rank * 26) + ($char - 64);
}
return $rank;
}
/**
* @param array<int,array<string,mixed>> $downloads
* @return array<int,array<string,mixed>>
*/
private function collectFallbackFilesFromDownloads(array $downloads): array
{
$fallbackFiles = [];
foreach ($downloads as $download) {
$file = $download['file'] ?? null;
if (!is_array($file)) {
continue;
}
if ((int)($file['uid'] ?? 1) !== 0) {
continue;
}
$fallbackFiles[] = [
'downloadUid' => (int)($download['uid'] ?? 0),
'name' => (string)($file['name'] ?? ''),
'url' => (string)($file['url'] ?? ''),
'source' => 'naming-convention-fallback',
];
}
return $fallbackFiles;
}
}