<?php
namespace App\Twig;
use App\Model\DataObject\WeatherStation;
use App\Service\CanonicalRedirectHelper;
use App\Service\NewsletterService;
use Carbon\Carbon;
use Pimcore\Cache;
use Pimcore\Config;
use Pimcore\Google\Cse\Item;
use Pimcore\Image;
use Pimcore\Model\Asset;
use Pimcore\Model\DataObject;
use Pimcore\Model\DataObject\AlpsteinRegion;
use Pimcore\Model\DataObject\AlpsteinTour;
use Pimcore\Model\DataObject\BlogTheme;
use Pimcore\Model\DataObject\Community;
use Pimcore\Model\DataObject\DemiInfrastructure;
use Pimcore\Model\DataObject\Fieldcollection\Data\WeatherTextStationDataSet;
use Pimcore\Model\DataObject\MediaUser;
use Pimcore\Model\DataObject\Region;
use Pimcore\Model\DataObject\WeatherAvalancheStation;
use Pimcore\Model\DataObject\WeatherLiveStation;
use Pimcore\Model\DataObject\WeatherTextStation;
use Pimcore\Model\Document;
use Pimcore\Model\Site;
use Pimcore\Tool;
use Pimcore\Translation\Translator;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Intl\Countries;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;
class LayoutExtension extends AbstractExtension
{
/**
* @var Config
*/
private $systemConfig;
/**
* @var Translator
*/
private $translator;
/**
* @var LinkGenerator
*/
private $linkGenerator;
/**
* @var RequestStack
*/
private $requestStack;
/**
* @var ObjectExtension
*/
private $objectExtension;
private UrlGeneratorInterface $router;
public const ROOT_DOCUMENT_ID = 1;
/**
* LayoutExtension constructor.
* @param Config $systemConfig
* @param Translator $translator
* @param LinkGenerator $linkGenerator
*/
public function __construct(Config $systemConfig, Translator $translator, LinkGenerator $linkGenerator, RequestStack $requestStack, ObjectExtension $objectExtension, UrlGeneratorInterface $router)
{
$this->systemConfig = $systemConfig;
$this->translator = $translator;
$this->linkGenerator = $linkGenerator;
$this->requestStack = $requestStack;
$this->objectExtension = $objectExtension;
$this->router = $router;
}
/**
* @return string
*/
public function getName()
{
return "Layout Extension";
}
/**
* @return array|TwigFunction[]
*/
public function getFunctions()
{
return [
new TwigFunction('getEnv', [$this, 'getEnv']),
new TwigFunction('googleApiKey', [$this, 'googleApiKey']),
new TwigFunction('selectableIcons', [$this, 'getSelectableIcons']),
new TwigFunction('isValidAsset', [$this, 'isValidAsset']),
new TwigFunction('getImageDescription', [$this, 'getImageDescription']),
new TwigFunction('getImageTexts', [$this, 'getImageTexts']),
new TwigFunction('getTourLocation', [$this, 'getTourLocation']),
new TwigFunction('getWeatherIcon', [$this, 'getWeatherIcon']),
new TwigFunction('getSocialIcons', [$this, 'getSocialIcons']),
new TwigFunction('getRegionsArray', [$this, 'getRegionsArray']),
new TwigFunction('getIndexFromRegion', [$this, 'getIndexFromRegion']),
new TwigFunction('getWeatherPrognosis', [$this, 'getWeatherPrognosis']),
new TwigFunction('getThemeByCategoryId', [$this, 'getThemeByCategoryId']),
new TwigFunction('getUseRelativeLink', [$this, 'getUseRelativeLink']),
new TwigFunction('hostUrl', [$this, 'getHostUrl']),
new TwigFunction('getHotspotData', [$this, 'getHotspotData']),
new TwigFunction('getCountrySelectData', [$this, 'getCountrySelectData']),
new TwigFunction('getPathInfo', [$this, 'getPathInfo']),
new TwigFunction('getVideoEditable', [$this, 'getVideoEditable']),
new TwigFunction('getNewsletterPools', [$this, 'getNewsletterPools']),
new TwigFunction('getMediaUser', [$this, 'getMediaUser']),
new TwigFunction('getPressWishlistCount', [$this, 'getPressWishlistCount']),
new TwigFunction('getMasterRequest', [$this, 'getMasterRequest']),
new TwigFunction('getMainRequest', [$this, 'getMainRequest']),
new TwigFunction('randomizeRelationEvery24h', [$this, 'randomizeRelationEvery24h']),
new TwigFunction('randomizeBlock', [$this, 'randomizeBlock']),
new TwigFunction('getImageType', [$this, 'getImageType']),
new TwigFunction('getBadgesForAsset', [$this, 'getBadgesForAsset']),
new TwigFunction('getFormattedVideoDuration', [$this, 'getFormattedVideoDuration']),
new TwigFunction('getYoutubeIdFromHref', [$this, 'getYoutubeIdFromHref']),
new TwigFunction('getAccessiblityObjects', [$this, 'getAccessiblityObjects']),
new TwigFunction('getSubttitleOfAudio', [$this, 'getSubttitleOfAudio']),
new TwigFunction('checkIfNoRenderletIsValid', [$this, 'checkIfNoRenderletIsValid']),
new TwigFunction('getAuthorForQuote', [$this, 'getAuthorForQuote']),
new TwigFunction('getCurrentWeatherImage', [$this, 'getCurrentWeatherImage']),
new TwigFunction('getWeatherStationByAlpsteinTour', [$this, 'getWeatherStationByAlpsteinTour']),
new TwigFunction('getDownloadItemDataByAsset', [$this, 'getDownloadItemDataByAsset']),
new TwigFunction('getPackagesByPackageCategories', [$this, 'getPackagesByPackageCategories']),
new TwigFunction('hasGetParams', [$this, 'hasGetParams']),
new TwigFunction('removeUnpublishedElements', [$this, 'removeUnpublishedElements']),
new TwigFunction('chooseDescription', [$this, 'chooseDescription']),
new TwigFunction('getMainLogo', [$this, 'getMainLogo']),
new TwigFunction('getMainConfig', [$this, 'getMainConfig']),
new TwigFunction('getFileContent', [$this, 'getFileContent']),
new TwigFunction('getSVGPathForExperienceTeaserBackgroundText', [$this, 'getSVGPathForExperienceTeaserBackgroundText']),
new TwigFunction('getObjectImageFromCSEResult', [$this, 'getObjectImageFromCSEResult']),
new TwigFunction('getTimeOfDay', [$this, 'getTimeOfDay']),
new TwigFunction('getCache', [$this, 'getCache']),
new TwigFunction('saveInCache', [$this, 'saveInCache']),
new TwigFunction('cachingAllowed', [$this, 'cachingAllowed']),
new TwigFunction('getAssetOrientation', [$this, 'getAssetOrientation']),
];
}
/**
* @param array $params
* @return bool
*/
public function hasGetParams($params = []) {
if (empty($params)) {
return !empty($_GET);
}
foreach ($params as $param) {
if (array_key_exists($param, $_GET)) {
return true;
}
}
return false;
}
public function getEnv(string $envName) {
return $_ENV[$envName];
}
/**
* @return bool
*/
public function getUseRelativeLink() {
return CanonicalRedirectHelper::USE_RELATIVE_LINK;
}
/**
* @param DataObject\DemiAccommodationServiceProvider|DemiInfrastructure $object
*/
public function getAccessiblityObjects(DataObject $object) {
$accessibilityCategories = [];
if ($object->getDemiExtension() && $object->getDemiExtension()->getDemiAccessibilityCategories()) {
foreach($object->getDemiExtension()->getDemiAccessibilityCategories()->getAccessibilityCategories() ?: [] as $entry) {
$category = $entry->getObject();
$percent = $entry->getPercent();
if($percent >= 80) {
$accessibilityCategories[$category->getId()] = ['category' => $category, 'percent' => $percent, 'isTop' => $percent >= 85];
}
}
}
return $accessibilityCategories;
}
/**
* @return Request|null
*/
public function getMasterRequest() {
return $this->requestStack->getMainRequest();
}
/**
* @return Request|null
*/
public function getMainRequest() {
return $this->requestStack->getMainRequest();
}
/**
* @return string[]
*/
public function getNewsletterPools() {
return NewsletterService::ALLOWED_NEWSLETTER_LISTS;
}
/**
* @return mixed
*/
public function googleApiKey() {
return $this->systemConfig['services']['google']['browser_api_key'];
}
/**
* @return string[][]
*/
public function getSelectableIcons() {
return [
['', 'No Icon'],
['hiking', '<span class="icon icon-hiking" style="font-size: 20px"></span> Hiking'],
['baggage', '<span class="icon icon-baggage" style="font-size: 20px"></span> Baggage'],
['calendar', '<span class="icon icon-calendar" style="font-size: 20px"></span> Calendar'],
['eye', '<span class="icon icon-eye" style="font-size: 20px"></span> Eye'],
['heart-outline', '<span class="icon icon-heart-outline" style="font-size: 20px"></span> Heart outline'],
['heart', '<span class="icon icon-heart" style="font-size: 20px"></span> Heart'],
['infrastructure', '<span class="icon icon-infrastructure" style="font-size: 20px"></span> Infrastructure'],
['mountain', '<span class="icon icon-mountain" style="font-size: 20px"></span> Mountain'],
['regions', '<span class="icon icon-regions" style="font-size: 20px"></span> Regions'],
['pin', '<span class="icon icon-pin" style="font-size: 20px"></span> Pin'],
['search', '<span class="icon icon-search" style="font-size: 20px"></span> Search'],
['sightseeing', '<span class="icon icon-sightseeing" style="font-size: 20px"></span> Sightseeing'],
['tag', '<span class="icon icon-tag" style="font-size: 20px"></span> Tag'],
['traffic', '<span class="icon icon-traffic" style="font-size: 20px"></span> Traffic'],
['corona', '<span class="icon icon-corona" style="font-size: 20px"></span> Corona'],
];
}
/**
* @param Asset $asset
* @return bool
*/
public function isValidAsset(Asset $asset) {
// check if contains neccessary data based on CC License
return true;
}
/**
* @param Asset\Image|null $image
* @return array|false
* @throws \Exception
*/
public function getImageTexts(Asset $image = null, $noCopyrightIfInMetadata = false, bool $onlyCopyright = false) {
if (!$image instanceof Asset\Image) {
return false;
}
$arrayKey = $image->getId() . ($noCopyrightIfInMetadata ? '_noCopyright' : '');
$cacheKey = $arrayKey . '_' . $this->requestStack->getCurrentRequest()?->getLocale();
if (!array_key_exists($arrayKey, $this->imageMetadata)) {
$texts = Cache::load($cacheKey);
if(!$texts) {
$metadataCopyright = $image->getMetadata('copyright');
$copyright = null;
$metaData = $image->getEmbeddedMetaData(true);
if (!$noCopyrightIfInMetadata || $metadataCopyright == '') {
$copyrightObject = $image->getMetadata('General.copyright');
if ($copyrightObject instanceof DataObject\MediaCopyright && !($noCopyrightIfInMetadata && $metadataCopyright != '')) {
$copyright = $copyrightObject->getText();
}
if ($copyright == '') {
$copyright = $metadataCopyright;
if ($copyright == '') {
if (isset($metaData['Copyright']) && $metaData['Copyright']) {
$copyright = $metaData['Copyright'];
} elseif (isset($metaData['CopyrightNotice']) && $metaData['CopyrightNotice']) {
$copyright = $metaData['CopyrightNotice'];
} elseif (isset($metaData['Rights'])) {
$copyright = $metaData['Rights'];
}
// $copyright = $metaData['Copyright'] ?: ($metaData['CopyrightNotice'] ?: $metaData['Rights']);
}
}
if ($copyright != '' && strpos($copyright, '©') === false) {
$copyright = '© ' . $copyright;
}
}
$title = $image->getMetadata('General.title');
if ($title == '') {
$title = $image->getMetadata('title');
if ($title == '') {
if (isset($metaData['Title']) && $metaData['Title']) {
$title = $metaData['Title'];
} elseif (isset($metaData['ObjectName'])) {
$title = $metaData['ObjectName'];
}
// $title = $metaData['Title'] ?: $metaData['ObjectName'];
}
}
$author = $image->getMetadata('General.author');
if ($author instanceof DataObject\Contact) {
$author = $author->getName() ?: (trim($author->getFirstname() . ' ' . $author->getLastname()));
}
if ($author == '') {
$author = $image->getMetadata('author');
if ($author == '') {
if (isset($metaData['Artist']) && $metaData['Artist']) {
$author = $metaData['Artist'];
} elseif (isset($metaData['Creator']) && $metaData['Creator']) {
$author = $metaData['Creator'];
} elseif (isset($metaData['By-line'])) {
$author = $metaData['By-line'];
}
// $author = $metaData['Artist'] ?: ($metaData['Creator'] ?: $metaData['By-line']);
}
}
$texts = [];
if ($title != '' && !$onlyCopyright) {
$texts['title'] = $title;
}
if ($copyright != '') {
$texts['copyright'] = $copyright;
}
if ($author != '' && !$onlyCopyright) {
$texts['author'] = $author;
}
$usage = $image->getMetadata('General.usage');
if ($usage && !$onlyCopyright) {
$texts['usage'] = $usage;
}
// save cache for 4 hours
Cache::save($texts, $cacheKey, [$image->getCacheTag()], 14400);
}
$this->imageMetadata[$arrayKey] = $texts;
}
return $this->imageMetadata[$arrayKey];
}
protected $imageMetadata = [];
/**
* @param Asset\Image|DataObject\Data\Hotspotimage|null $image
* @return false|string
* @throws \Exception
*/
public function getImageDescription($image = null, $noCopyrightIfInMetadata = false, bool $onlyCopyright = false) {
if ($image == null) {
return false;
}
if ($image instanceof DataObject\Data\Hotspotimage) {
$image = $image->getImage();
}
if($image instanceof Document\Editable\Image) {
$image = $image->getImage();
}
if ($image instanceof Asset\Image) {
$texts = $this->getImageTexts($image, $noCopyrightIfInMetadata, $onlyCopyright);
}
if (!empty($texts)) {
return implode(' | ', $texts );
}
return false;
}
public function getTourLocation(AlpsteinTour $tour) {
$location = false;
$regions = $tour->getRegions();
if (isset($regions[0]) && $regions[0]->getElement()) {
$location = $regions[0]->getElement();
}
foreach($regions as $regionData){
if ($regionData->getIsStartingRegion()) {
$location = $regionData->getElement();
break;
}
}
if ($location instanceof AlpsteinRegion) {
return $location->getName();
}
return false;
}
public const WEATHER_ICON_MAPPING = [
'01' => '01',
'02' => '02',
'03' => '03', #wetter_wolkig.svg
'04' => '03',
'05' => '07',
'06' => '12',
'07' => '12',
'08' => '08',
'09' => '06',
'10' => '05',
'11' => '11',
'12' => '11',
'13' => '11',
'14' => '09',
'15' => '10',
'16' => '10',
'17' => '04',
'18' => '04',
'19' => '04',
'20' => '08',
'21' => '08',
'22' => '08',
'23' => '08',
'24' => '08',
'25' => '08',
'26' => '13',
'27' => '13',
'28' => '14',
'29' => '08',
'30' => '10',
'31' => '08',
'32' => '10',
'41' => '01',
'42' => '12',
'43' => '15', #wetter_wolkig.svg
'44' => '03',
'45' => '12',
'48' => '12',
'49' => '12',
'61' => '04',
'62' => '04',
'63' => '08', #wetter_leichter_regen.svg
'64' => '04',
'65' => '04',
'66' => '06',
'67' => '04',
'68' => '05',
'69' => '05',
'71' => '08',
'72' => '08',
'73' => '09',
'74' => '08',
'75' => '08',
'76' => '10',
'77' => '08',
'78' => '10',
'79' => '10',
'81' => '08',
'82' => '08',
'83' => '11',
'84' => '08',
'85' => '08',
'86' => '11',
'87' => '08',
'88' => '11',
'89' => '11',
'90' => '02',
'91' => '13',
'92' => '13',
'93' => '14',
'94' => '13',
'95' => '13',
'96' => '14',
'97' => '08',
'98' => '10',
'99' => '08',
];
/**
* @param $symb
* @return string
*/
public function getWeatherIcon($symb) {
return self::WEATHER_ICON_MAPPING[$symb];
}
public const SOCIAL_ICONs = [
"mail",
"linkedin",
"instagram",
"facebook",
"pinterest",
"twitter",
"whatsapp",
"youtube",
"tiktok",
];
/**
* @return array
*/
public function getSocialIcons() {
$icons = [];
foreach (self::SOCIAL_ICONs as $icon) {
$icons[] = [$icon, '<span class=\'icon icon-' . $icon . '\' style=\'display:inline-block;width: 20px;font-size: 16px\'></span> ' . ucfirst($icon)];
}
return $icons;
}
/**
* @param bool $includeMainRegion
* @return array
*/
public function getRegionsArray($includeMainRegion = false) {
$regions = [
'regiongraz' => Region::getById(326447),
'suedweststeiermark' => Region::getById(324085),
'thermenvulkanland' => Region::getById(326440),
'schladmingdachstein' => Region::getById(326444),
'oststeiermark' => Region::getById(326443),
'hochsteiermark' => Region::getById(326445),
'murau' => Region::getById(326446),
'murtal' => Region::getById(1037676),
'gesaeuse' => Region::getById(326441),
'ausseerland' => Region::getById(326442),
'erzbergleoben' => Region::getById(889409),
];
if ($includeMainRegion) {
$regions = array_merge(['steiermark' => Region::getById(324083)], $regions);
}
return $regions;
}
/**
* @param Region|null $currentRegion
* @return int
*/
public function getIndexFromRegion(Region $currentRegion = null, $includeMainRegion = false) {
$index = 0;
if ($currentRegion != '') {
foreach ($this->getRegionsArray($includeMainRegion) as $region) {
if ($region->getId() == $currentRegion->getId()) {
return $index;
}
$index++;
}
}
return 0;
}
/**
* @return array
*/
public function getWeatherPrognosis() {
$weatherTextStation = new WeatherTextStation\Listing();
$weatherTextStation->addConditionParam('IFNULL(isMountain,0) = 0');
$weatherTextStation->setOrderKey('o_modificationdate');
$weatherTextStation->setOrder('DESC');
$weatherTextStation->setLimit(1);
$weatherTextStation = $weatherTextStation->current();
$prognosis = [
'today' => [],
'tomorrow' => [],
'modifiedDate' => null
];
$duplicateTextCheck = [];
if ($weatherTextStation instanceof WeatherTextStation) {
/** @var WeatherTextStationDataSet $item */
foreach ($weatherTextStation->getWeatherData()->getItems() as $item) {
$hash = md5($item->getTitle() . $item->getText());
if (!in_array($hash, $duplicateTextCheck)) {
if ($item->getDate()->isToday()) {
$prognosis['today'][$item->getDaytime()] = [
'title' => $item->getTitle(),
'text' => $item->getText()
];
} else if ($item->getDate()->isTomorrow()) {
$prognosis['tomorrow'][$item->getDaytime()] = [
'title' => $item->getTitle(),
'text' => $item->getText()
];
}
$duplicateTextCheck[] = $hash;
}
}
$prognosis['modifiedDate'] = Carbon::createFromTimestamp($weatherTextStation->getModificationDate());
}
return $prognosis;
}
/**
* @param $categoryId
* @return BlogTheme
*/
public function getThemeByCategoryId($categoryId){
$blogTheme = new BlogTheme\Listing();
$blogTheme->addConditionParam('name != "" AND name IS NOT NULL AND blogCategories LIKE :categoryId', ['categoryId' => "%," . $categoryId . ",%"]);
$blogTheme->setLimit(1);
return $blogTheme->current();
}
public function getHostUrl() {
return \Pimcore\Tool::getHostUrl();
}
public function getHotspotData($left, $top, $item = null, $weatherOnly = false, $title = '') {
if ($item) {
$link = '';
$linkText = '';
if ($item instanceof Region && $weatherOnly) {
if ($item->getIsLive()) {
$link = $item->getSiteConfig()->getWeatherOverview();
$linkText = $item->getNameLocalized() ?: $item->getName();
}
$item = $item->getWeatherLiveStation() ?: $item->getWeatherStation();
}
if ($item instanceof Community && $weatherOnly) {
$link = $this->linkGenerator->generate($item);
$linkText = $item->getNameLocalized() ?: $item->getName();
$item = $item->getLiveWeather() ?: $item->getPrognosis();
}
if ($item instanceof WeatherLiveStation) {
return [
'left' => $left,
'top' => $top,
'value' => $item->getTemperature() . '°',
'img' => "/static/img/weather/" . $this->getWeatherIcon($item->getSymbol()) . '.svg',
'detail' => [
'title' => $item->getName() . ', ' . $item->getAltitude() . 'm',
'subtitle' => '',
'link' => [
'href' => $link,
'text' => $linkText ?: $this->translator->trans('weather.Details')
],
'hasWeatherDetail' => true
]
];
}
if ($item instanceof WeatherStation) {
return [
'left' => $left,
'top' => $top,
'value' => $item->getTempNow() . '°',
'img' => "/static/img/weather/" . $this->getWeatherIcon($item->getSymbNow()) . '.svg',
'detail' => [
'title' => $item->getName() . ', ' . $item->getAltitude() . 'm',
'subtitle' => '',
'link' => [
'href' => $link,
'text' => $linkText ?: $this->translator->trans('weather.Details')
],
'hasWeatherDetail' => true
]
];
}
if ($item instanceof Region) {
return [
'left' => $left,
'top' => $top,
'smallHotspot' => true,
'detail' => [
'title' => $item->getNameLocalized() ?: $item->getName(),
'subtitle' => '',
'link' => [
'href' => $item->getSiteConfig()->getHome(),
'target' => '_blank',
'text' => $this->translator->trans('generic.Details')
]
]
];
}
if ($item instanceof Community) {
return [
'left' => $left,
'top' => $top,
'smallHotspot' => true,
'detail' => [
'title' => $item->getNameLocalized() ?: $item->getName(),
'subtitle' => '',
'link' => [
'href' => $this->linkGenerator->generate($item),
'target' => '_blank',
'text' => $this->translator->trans('generic.Details')
]
]
];
}
if ($item instanceof WeatherAvalancheStation) {
return [
'left' => $left,
'top' => $top,
'isPlain' => true,
'avalanche' => 'avalanche-icon-' . $item->getSymbol()
];
}
if($item instanceof DemiInfrastructure) {
return [
'left' => $left,
'top' => $top,
'smallHotspot' => true,
'value' => null,
'img' => null,
'icon' => true,
'detail' => true,
'title' => $item->getName(),
'subtitle' => '',
'link' => [
'href' => $this->linkGenerator->generate($item),
'text' => $this->translator->trans('arrival.marker.buttontext'),
]
];
}
if($item instanceof Asset\Image) {
return [
'left' => $left,
'top' => $top,
'smallHotspot' => true,
'value' => null,
'img' => null,
'icon' => true,
'detail' => [
'image' => $item,
],
'title' => $title ?: $item->getMetadata('General.title'),
'subtitle' => '',
'isPlain' => false,
];
}
}
return [];
}
public function getCountrySelectData($locale = 'en', $currentSelectedCountryCode = '') {
$retArray = [[
"label" => "",
"value" => "",
"disabled" => true,
"selected" => empty($currentSelectedCountryCode),
"class" => "sr-only"
]];
foreach (Countries::getNames($locale) as $countryCode => $countryName) {
$retArray[] = [
"label" => $countryName,
"value" => $countryCode,
"class" => '',
"selected" => !empty($currentSelectedCountryCode) && $currentSelectedCountryCode == $countryCode
];
}
return $retArray;
}
public function getPathInfo(string $filename) {
return pathinfo($filename)['extension'];
}
public function getVideoEditable(\Pimcore\Model\DataObject\Data\Video $v, $optionalPoster = null) {
$videoData = $v->getData();
if($videoData) {
$video = new \Pimcore\Model\Document\Editable\Video();
$video->setConfig([
"thumbnail" => "video", // specify your thumbnail here - IMPORTANT!
"attributes" => [
"class" => "embed-responsive-item js-play-video__video",
"preload" => "auto",
"lowQualityPlaceholder" => true,
"controls" => "false",
"controlsList" => "nodownload",
]
]);
$video->setDataFromEditmode([
'type' => $v->getType(),
'id' => $videoData instanceof Asset ? $videoData->getId() : $videoData,
'title' => $v->getTitle(),
'description' => $v->getDescription(),
'poster' => $optionalPoster instanceof Asset\Image ? $optionalPoster : ($v->getPoster() ?: null)
]);
return $video;
}
return null;
}
public function getMediaUser(Request $request) {
$pressSession = $request->getSession()->getBag('pressLogin');
if($userId = $pressSession->get('userid')) {
if($user = MediaUser::getById($userId)) {
return $user;
}
}
return null;
}
public function getPressWishlistCount(Request $request) : int {
$dossiers = $request->getSession()?->get('pressDossierWishlistIds', []);
$articles = $request->getSession()?->get('pressArticleWishlistIds', []);
$image = $request->getSession()?->get('pressImageWishlistIds', []);
$album = $request->getSession()?->get('pressAlbumWishlistIds', []);
$albumItems = $request->getSession()?->get('pressAlbumItemsWishlistIds', []);
return count($dossiers) + count($articles) + count($image) + count($album) + count($albumItems);
}
public function randomizeRelationEvery24h(array $elements, Document $document) {
$ids = implode(',',array_map(function($element) {
return $element->getId();
}, $elements));
$cacheKey = md5('radnomizeRelations' . $ids . $document->getId());
if (!($data = \Pimcore\Cache::load($cacheKey))) {
$cacheTime = 86400; //== 1 day in seconds
shuffle($elements);
\Pimcore\Cache::save($elements, $cacheKey, [], $cacheTime, 0, true);
return $elements;
} else {
return $data;
}
}
public function randomizeBlock(array $elements, Document $document) : array {
$ids = implode(',',array_map(function($element) {
return $element->getEditable('headline')->getData();
}, $elements));
$cacheKey = md5('randomizeRelations' . $ids . $document->getId());
if (!($data = \Pimcore\Cache::load($cacheKey))) {
$cacheTime = 86400; //== 1 day in seconds
shuffle($elements);
\Pimcore\Cache::save($elements, $cacheKey, [], $cacheTime, 0, true);
return $elements;
} else {
return $data;
}
}
public function getImageType(Asset $asset) {
$mimetype = $asset->getMimetype();
$posSlash = strpos($mimetype, '/' );
return substr($mimetype, $posSlash+1);
}
public function getBadgesForAsset(Asset $asset, DataObject\MediaAsset $mediaAsset = null) {
$badges = [];
$categories = $asset->getMetadata('General.categories');
$number = $asset->getMetadata('General.number');
if($mediaAsset instanceof DataObject\MediaAsset) {
if(!empty($mediaAsset->getCategories())) {
$categories = $mediaAsset->getCategories();
}
if($mediaAsset->getNumber()) {
$number = $mediaAsset->getNumber();
}
}
if(!empty($categories)) {
if(is_array($categories)) {
$badges[] = $categories[0]->getName();
} else {
$badges[] = $categories->getName();
}
}
if(!empty($number)) {
$badges[] = $this->translator->trans('general.Nr') . ' ' . $number;
}
return $badges;
}
public function getFormattedVideoDuration(Asset\Video $video) {
$duration = $video->getDuration();
$mins = floor($duration / 60);
if($mins < 10) {
$mins = 0 . $mins;
}
$sec = ceil($duration % 60);
if($sec < 10) {
$sec = 0 . $sec;
}
return $mins . ':' . $sec;
}
public function getYoutubeIdFromHref(string $youtubeUrl) {
$pos = strpos($youtubeUrl, 'v=') + 2;
return substr($youtubeUrl, $pos);
}
public function getSubttitleOfAudio(Asset\Audio $audio, string $locale = 'de') : string {
$subtitle = '';
if($copyright = $audio->getMetadata('General.copyright', $locale)) {
$subtitle .= '© ' . $copyright->getText();
}
/** @var DataObject\PressAuthor $author */
if($author = $audio->getMetadata('General.author')) {
if(!empty($subtitle)) $subtitle .= '<br>';
$subtitle .= $author->getName();
}
if($description = $audio->getMetadata('General.usage', $locale)) {
if(!empty($subtitle)) $subtitle .= '<br>';
$subtitle .= $description;
}
if($description = $audio->getMetadata('General.description', $locale)) {
if(!empty($subtitle)) $subtitle .= '<br>';
$subtitle .= $description;
}
return $subtitle;
}
/**
* @param Document\Editable\Renderlet[] $renderlets
* @return bool
*/
public function checkIfNoRenderletIsValid($renderlets) : bool {
/**
* @var Document\Editable\Renderlet $renderlet
*/
foreach ($renderlets as $renderlet) {
if(!$renderlet->isEmpty()) {
if($renderlet->getType() == 'object') {
if(($o = $renderlet->getO()) && $o instanceof DataObject) {
if($o instanceof DataObject\DemiEvent) {
if($this->objectExtension->isEventNotExpired($o)) {
return false;
}
} elseif($o instanceof DataObject\BlogArticle) {
if(!$o->getArticleDate()->isFuture()) {
return false;
}
} elseif($o instanceof DataObject\Package) {
if($this->objectExtension->isPackageNotExpired($o)) {
return false;
}
}
}
} else { // is document or asset => cannot expire
return false;
}
}
}
return true;
}
/**
* @param $object
* @param string $authorText
* @return string
*/
public function getAuthorForQuote($object, string $authorText) : string {
if($object instanceof DataObject\PressAuthor) {
return $object->getName();
} elseif($object instanceof DataObject\BlogAuthor) {
return $object->getName();
} elseif(!empty($authorText)) {
return $authorText;
}
return '';
}
public function getCurrentWeatherImage(WeatherStation $weatherStation, DataObject\SiteConfig $config) : ?Asset\Image {
$icon = $this->getCurrentWeatherIcon($weatherStation);
if( $icon !== null ){
$icon = $this->getWeatherIcon( $icon ); //get mapped icon
}
if($icon && ($image = $config->get('icon' . $icon))) {
return $image;
} elseif($image = $config->getIconDefault()) {
return $image;
}
return null;
}
public function getWeatherStationByAlpsteinTour(AlpsteinTour $tour) : ?WeatherStation {
foreach($tour->getRegions() as $region) {
$region = $region->getElement();
if($region instanceof AlpsteinRegion) {
$community = $this->getFirstCommunityByAlpsteinRegion($region);
if($community && $community->getPrognosis()) {
return $community->getPrognosis();
}
}
}
return null;
}
private function getCurrentWeatherIcon(WeatherStation $weatherStation)
{
$currentHour = Carbon::now()->hour;
$today = $weatherStation->today();
if($today) {
if($currentHour >= 4 && $currentHour < 11) { //morning
return $today->getSymb06();
}elseif($currentHour >= 11 && $currentHour < 16) { //lunch
return $today->getSymb12();
}elseif($currentHour >= 16 && $currentHour < 21) { //evening
return $today->getSymb18();
} else { // night 21-03
return $today->getSymb24();
}
}
return null;
}
private function getFirstCommunityByAlpsteinRegion(AlpsteinRegion $region) : ?Community {
$list = new Community\Listing();
$list->addConditionParam("alpsteinObjects like '%," . $region->getId() .",%'");
return $list->getCount() > 0 ? $list->getObjects()[0]: null;
}
public function getDownloadItemDataByAsset(Asset $asset) {
$image = false;
$viewLink = false;
if ($asset instanceof Asset\Image) {
$image = $asset->getThumbnail('download-list-item');
$viewLink = $asset->getFullPath();
} else if ($asset instanceof Asset\Video) {
$image = $asset->getImageThumbnail('download-list-item');
} else if ($asset instanceof Asset\Document) {
$image = $asset->getImageThumbnail('download-list-item');
if ($asset->getMimetype() == 'application/pdf') {
$viewLink = $asset->getFullPath();
}
}
$filename = $asset->getFilename();
$fileEnding = pathinfo($filename)['extension'];
return [
'file' => strtoupper($fileEnding),
'image' => $image,
'href' => $this->router->generate('app_asset_download', ['id' => $asset->getId()]),
'text' => $asset->getFilename(),
'fileSize' => $asset->getFileSize(true),
'viewLink' => $viewLink
];
}
/**
* @param DataObject\PackageCategory[] $categories
*/
public function getPackagesByPackageCategories(array $categories) : array {
$elements = [];
$allCategories = [];
foreach($categories as $category) {
$this->getChildPackageCategories($category, $allCategories);
}
$packageListing = new DataObject\Package\Listing();
$conditions = [];
foreach ($allCategories as $key => $category) {
$conditions[] = 'categories LIKE "%,' . $key . ',%"';
}
if(!empty($conditions)) {
$packageListing->addConditionParam(implode(' OR ', $conditions));
}
return $packageListing->getObjects();
}
public function removeUnpublishedElements(array $elements) : array {
$publishedElements = [];
foreach ($elements as $element) {
if(method_exists($element, 'getPublished') && $element->getPublished()) {
$publishedElements[] = $element;
}
}
return $publishedElements;
}
public function chooseDescription(?string $shortDescription, ?string $longDescription, int $numSignsShortDescription = 100) {
//returns the sD if it has a min. of letters, otherwise returns the lD except it is empty.
if(strlen($shortDescription) > $numSignsShortDescription) {
return $shortDescription;
} elseif(!empty($longDescription)) {
return $longDescription;
}
return $shortDescription;
}
/**
* @return Asset\Image|null
*/
public function getMainLogo():?Asset\Image{
$rootDocument = Document::getById(self::ROOT_DOCUMENT_ID);
if($rootDocument) {
$mainConfig = $rootDocument->getProperty('siteConfig');
if ($mainConfig) {
$logo = $mainConfig->getLogo();
if ($logo instanceof Asset\Image) {
return $logo;
}
}
}
return null;
}
public function getMainConfig(){
$rootDocument = Document::getById(self::ROOT_DOCUMENT_ID);
if($rootDocument) {
$mainConfig = $rootDocument->getProperty('siteConfig');
if ($mainConfig) {
return $mainConfig->getId();
}
}
return null;
}
private function getChildPackageCategories(DataObject\PackageCategory $category, array & $categories) {
$categories[$category->getId()] = $category;
foreach ($category->getChildren() as $child) {
if($child instanceof DataObject\PackageCategory) {
$this->getChildPackageCategories($child, $categories);
}
}
}
public function getFileContent($file) {
return file_get_contents( $file );
}
public function getSVGPathForExperienceTeaserBackgroundText(string $text, string $lang) {
$mapping = [
"discover-en" => "en/discover.svg",
"enjoy-en" => "en/enjoy.svg",
"experience-en" => "en/experience.svg",
"visit-en" => "en/visit.svg",
"discover-de" => "de/entdecken.svg",
"enjoy-de" => "de/genießen.svg",
"experience-de" => "de/erleben.svg",
"visit-de" => "de/besuchen.svg",
"discover-cz" => "cze/objevte.svg",
"enjoy-cz" => "cze/užívejte si.svg",
"experience-cz" => "cze/zažijte.svg",
"visit-cz" => "cze/navštivte.svg",
"discover-hu" => "hun/kalandok.svg",
"enjoy-hu" => "hun/élvezetek.svg",
"experience-hu" => "hun/élmények.svg",
"visit-hu" => "hun/látnivalók.svg",
"discover-nl" => "nl/ontdekken.svg",
"enjoy-nl" => "nl/genieten.svg",
"experience-nl" => "nl/beleven.svg",
"visit-nl" => "nl/bezoeken.svg",
"discover-pl" => "pl/odkryj.svg",
"enjoy-pl" => "pl/ciesz się.svg",
"experience-pl" => "pl/doświadcz.svg",
"visit-pl" => "pl/odwiedź.svg",
];
return $mapping[$text . '-' . $lang];
}
public function getObjectImageFromCSEResult(Item $cseItem) {
$path = parse_url($cseItem->getLink())['path'];
$id = $this->getIdFromPath($path);
if($id) {
$object = DataObject::getById($id);
if($object instanceof DataObject\DemiAccommodationServiceProvider) {
return $object->getImages() ? current($object->getImages()) : null;
}
}
return null;
}
private function getIdFromPath(string $path) : int {
$matches = array();
if (preg_match('#(\d+)$#', $path, $matches)) {
return $matches[1];
}
return 0;
}
public function getTimeOfDay(int $hour, int $minute, int $second) {
$timeString = '';
if($hour < 10) {
$timeString .= '0';
}
$timeString .= $hour . ':';
if($minute < 10) {
$timeString .= '0';
}
$timeString .= $minute . ':';
if($second < 10) {
$timeString .= '0';
}
$timeString .= $second;
return $timeString;
}
public function getCache($cacheKey) {
return \Pimcore\Cache::load($cacheKey) ?? false;
}
public function saveInCache($cacheKey, $data, $lifetime = 86400) {
\Pimcore\Cache::save($data, $cacheKey, [], $lifetime, 0, true);
}
public function cachingAllowed() : bool {
if($this->getEnv('APP_CACHE') !== 'true') {
return false;
}
$request = $this->getMainRequest(); # no caching if pimcore_preview
if(Tool::isFrontendRequestByAdmin($request)) {
return false;
}
if($request) {
// no caching if path starts with a site root document like /steiermark.com/
$sites = new Site\Listing();
foreach ($sites as $site) {
if ($site && $site->getRootDocument() instanceof Document\Page) {
if(str_starts_with($request->getPathInfo(), $site->getRootDocument()->getRealFullPath() . '/')) {
return false;
}
}
}
}
return true;
// old:
// return $this->getEnv('APP_CACHE') === 'true' && !$request?->get('pimcore_preview') && !str_starts_with($request->getPathInfo(), '/steiermark.com/');
}
public function getAssetOrientation($asset) : string {
$orientation = 'landscape';
if($asset instanceof Asset\Image) {
$orientation = $asset->getWidth() >= $asset->getHeight() ? 'landscape' : 'portrait';
}
return $orientation;
}
}