<?php
/**
* Created by PhpStorm.
* User: nico.filzmoser
* Date: 26.03.18
* Time: 14:12
*/
namespace App\Twig;
use App\Service\AimsService;
use App\Service\AnnouncementService;
use App\Service\CategoryConfigurationService;
use App\Service\DocumentService;
use App\Service\LinkService;
use App\Service\OverviewService;
use App\Service\MenuService;
use App\Service\PriceRequestProductsService;
use App\Service\ScienceCenterService;
use App\Service\SearchService;
use App\Service\ServiceStationLocatorService;
use App\Service\LocationService;
use App\Service\LabelService;
use App\Service\FaqService;
use App\Service\EventService;
use App\Service\AccessoryService;
use App\Service\TeaserIncludeService;
use App\Service\User\UserService;
use App\Service\VideoTutorialService;
use App\Helper\StoryblokHelper;
use App\Service\NewsroomService;
use App\Service\PromotionService;
use App\Service\WidgetService;
use App\Service\DosingCalculatorService;
use App\Service\SAGEApiService;
use App\Service\RedirectService;
use Exception;
use Psr\Log\LoggerInterface;
use Storyblok;
use Symfony\Component\HttpFoundation\RequestStack;
use Twig\Extension\AbstractExtension;
use Twig\TwigFilter;
use Twig\TwigFunction;
use Parsedown;
class TwigExtension extends AbstractExtension
{
private $storyblok;
private $fontCacheKey;
private $googleAnalyticsKey;
private $googleSiteVerificationContent;
private $cacheVersion;
private $requestStack;
private $logger;
private $projectDir;
private $availableLanguages;
private $domain;
private $micrositeNameMap;
/**
* @var SearchService
*/
private $searchService;
/**
* @var ServiceStationLocatorService
*/
private $serviceStationLocatorService;
/**
* @var LabelService
*/
private $labelService;
/**
* @var FaqService
*/
private $faqService;
/**
* @var EventService
*/
private $eventService;
/**
* @var string
*/
private $datareporterUrl;
/**
* @var OverviewService
*/
private $overviewService;
/**
* @var AccessoryService
*/
private $accessoryService;
/**
* @var TeaserIncludeService
*/
private $teaserIncludeService;
/**
* @var DocumentService
*/
private $documentService;
/**
* @var LocationService
*/
private $locationService;
/**
* @var VideoTutorialService
*/
private $videoTutorialService;
/**
* @var UserService
*/
private $userService;
/**
* @var MenuService
*/
private $menuService;
/**
* @var PriceRequestProductsService
*/
private $priceRequestProductsService;
/**
* @var ScienceCenterService
*/
private $scienceCenterService;
/**
* @var CategoryConfigurationService
*/
private $categoryConfigService;
/**
* @var AnnouncementService
*/
private $announcementService;
/**
* @var StoryblokHelper
*/
private $storyblokHelper;
/**
* @var LinkService
*/
private $linkService;
private $aimsService;
/**
* @var array
*/
private $recaptchaConfig;
/**
* @var NewsroomService;
*/
private $newsroomService;
/**
* @var string
*/
private $newsroomRefreshLanguages;
/**
* @var array
*/
private $shopDomains;
/**
* @var string
*/
private $datareporterUrlActivationCode;
/**
* @var WidgetService;
*/
private $widgetService;
/**
* @var PromotionService;
*/
private $promotionService;
/**
* @var DosingCalculatorService;
*/
private $dosingCalculatorService;
/**
* @var SAGEApiService;
*/
private $sageApiService;
/**
* @var RedirectService;
*/
private $redirectService;
/**
* @var array
*/
private $countryLanguageMapping;
public function __construct(
string $fontCacheKey,
string $googleAnalyticsId,
string $cacheVersion,
array $recaptchaConfig,
string $projectDir,
string $availableLanguages,
string $domain,
string $mapiToken,
string $spaceId,
string $googleSiteVerificationContent,
array $micrositeNameMap,
string $newsroomRefreshLanguages,
string $datareporterUrl,
string $datareporterUrlActivationCode,
array $shopDomains,
array $countryLanguageMapping,
UserService $userService,
SearchService $searchService,
ServiceStationLocatorService $serviceStationLocatorService,
VideoTutorialService $videoTutorialService,
DocumentService $documentService,
LocationService $locationService,
CategoryConfigurationService $categoryConfigurationService,
MenuService $menuService,
PriceRequestProductsService $priceRequestProductsService,
LabelService $labelService,
ScienceCenterService $scienceCenterService,
FaqService $faqService,
EventService $eventService,
AccessoryService $accessoryService,
TeaserIncludeService $teaserIncludeService,
OverviewService $overviewService,
Storyblok\Client $storyblok,
LoggerInterface $logger,
RequestStack $requestStack,
AnnouncementService $announcementService,
StoryblokHelper $storyblokHelper,
LinkService $linkService,
AimsService $aimsService,
NewsroomService $newsroomService,
WidgetService $widgetService,
PromotionService $promotionService,
DosingCalculatorService $dosingCalculatorService,
SAGEApiService $sageApiService,
RedirectService $redirectService
) {
$this->fontCacheKey = $fontCacheKey;
$this->googleAnalyticsId = $googleAnalyticsId;
$this->cacheVersion = $cacheVersion;
$this->projectDir = $projectDir;
$this->availableLanguages = explode('|', $availableLanguages);
$this->domain = $domain;
$this->mapiToken = $mapiToken;
$this->spaceId = $spaceId;
$this->googleSiteVerificationContent = $googleSiteVerificationContent;
$this->countryLanguageMapping = $countryLanguageMapping;
$this->userService = $userService;
$this->accessoryService = $accessoryService;
$this->teaserIncludeService = $teaserIncludeService;
$this->videoTutorialService = $videoTutorialService;
$this->overviewService = $overviewService;
$this->faqService = $faqService;
$this->eventService = $eventService;
$this->labelService = $labelService;
$this->scienceCenterService = $scienceCenterService;
$this->searchService = $searchService;
$this->serviceStationLocatorService = $serviceStationLocatorService;
$this->documentService = $documentService;
$this->locationService = $locationService;
$this->categoryConfigService = $categoryConfigurationService;
$this->menuService = $menuService;
$this->priceRequestProductsService = $priceRequestProductsService;
$this->storyblok = $storyblok;
$this->announcementService = $announcementService;
$this->storyblokHelper = $storyblokHelper;
$this->linkService = $linkService;
$this->datareporterUrl = $datareporterUrl;
$this->datareporterUrlActivationCode = $datareporterUrlActivationCode;
$this->shopDomains = $shopDomains;
$this->logger = $logger;
$this->requestStack = $requestStack;
$this->micrositeNameMap = $micrositeNameMap;
$this->aimsService = $aimsService;
$this->recaptchaConfig = $recaptchaConfig;
$this->newsroomService = $newsroomService;
$this->newsroomRefreshLanguages = $newsroomRefreshLanguages;
$this->widgetService = $widgetService;
$this->promotionService = $promotionService;
$this->dosingCalculatorService = $dosingCalculatorService;
$this->sageApiService = $sageApiService;
$this->redirectService = $redirectService;
}
public function getFilters()
{
return [
new TwigFilter("version", [$this, "version"]),
new TwigFilter("removeNbsp", [$this, "removeNbsp"]),
new TwigFilter("markdown", [$this, "markdown"], ["is_safe" => ["html"]])
];
}
public function getFunctions()
{
return [
new TwigFunction("getCanonical", [$this, "getCanonical"]),
new TwigFunction("getFontCacheKey", [$this, "getFontCacheKey"]),
new TwigFunction("getGoogleAnalyticsId", [$this, "getGoogleAnalyticsId"]),
new TwigFunction("getMetaInfo", [$this, "getMetaInfo"]),
new TwigFunction("getStoryBySlug", [$this, "getStoryBySlug"]),
new TwigFunction("getStories", [$this, "getStories"]),
new TwigFunction("image", [$this, "image"]),
new TwigFunction("url", [$this, "url"]),
new TwigFunction("sbUrl", [$this, "sbUrl"]),
new TwigFunction("sbUrlByUuid", [$this, "sbUrlByUuid"]),
new TwigFunction("sbUrlById", [$this, "sbUrlById"]),
new TwigFunction("include_file", [$this, "includeFile"]),
new TwigFunction("label", [$this, "label"]),
new TwigFunction("getSkus", [$this, "getSkus"]),
new TwigFunction("getFamilyPart", [$this, "getFamilyPart"]),
new TwigFunction("familyUrl", [$this, "familyUrl"]),
new TwigFunction("systemConf", [$this, "systemConf"]),
new TwigFunction("getNewsletterOgInfoById", [$this, "getNewsletterOgInfoById"]),
new TwigFunction("getSearchHeadersForResultsPage", [$this, "getSearchHeadersForResultsPage"]),
new TwigFunction("getClosestRetailer", [$this, "getClosestRetailer"]),
new TwigFunction("getCategory", [$this, "getCategory"]),
new TwigFunction("overviewData", [$this, "overviewData"]),
new TwigFunction("rindex", [$this, "rindex"]),
new TwigFunction("generateBreadcrumb", [$this, "generateBreadcrumb"]),
new TwigFunction("getAccessoriesOptions", [$this, "getAccessoriesOptions"]),
new TwigFunction("getTeasersByUri", [$this, "getTeasersByUri"]),
new TwigFunction("getAccessoriesByProductId", [$this, "getAccessoriesByProductId"]),
new TwigFunction("uuid", [$this, "uuid"]),
new TwigFunction("uniqid", [$this, "uniqid"]),
new TwigFunction("documentInfo", [$this, "documentInfo"]),
new TwigFunction("getVideoTutorialsByProductId", [$this, "getVideoTutorialsByProductId"]),
new TwigFunction("isUserLoggedIn", [$this, "isUserLoggedIn"]),
new TwigFunction("activateUser", [$this, "activateUser"]),
new TwigFunction("isStudentUser", [$this, "isStudentUser"]),
new TwigFunction("userFirstname", [$this, "userFirstname"]),
new TwigFunction("getProductNavigation", [$this, 'getProductNavigation']),
new TwigFunction("getNavigation", [$this, 'getNavigation']),
new TwigFunction("getFAQsByProductId", [$this, 'getFAQsByProductId']),
new TwigFunction("getFAQsByApplicationArea", [$this, 'getFAQsByApplicationArea']),
new TwigFunction("getScienceCenterByProductId", [$this, 'getScienceCenterByProductId']),
new TwigFunction("getNextEvent", [$this, 'getNextEvent']),
new TwigFunction("getLeftNavigation", [$this, 'getLeftNavigation']),
new TwigFunction("getDocumentObject", [$this, 'getDocumentObject']),
new TwigFunction("getCurrentLocation", [$this, 'getCurrentLocation']),
new TwigFunction("getShopUrl", [$this, 'getShopUrl']),
new TwigFunction("getCurrentLatitude", [$this, 'getCurrentLatitude']),
new TwigFunction("getCurrentLongitude", [$this, 'getCurrentLongitude']),
new TwigFunction("setActiveNav", [$this, 'setActiveNav']),
new TwigFunction("getBackendPath", [$this, 'getBackendPath']),
new TwigFunction("getSitemap", [$this, 'getSitemap']),
new TwigFunction("getCountryContactData", [$this, 'getCountryContactData']),
new TwigFunction("getNews", [$this, "getNews"]),
new TwigFunction("resetArrayKeys", [$this, "resetArrayKeys"]),
new TwigFunction("isEditMode", [$this, "isEditMode"]),
new TwigFunction("addTeaserName", [$this, "addTeaserName"]),
new TwigFunction("getAllTeaserNamesFormatted", [$this, "getAllTeaserNamesFormatted"]),
new TwigFunction("addNewsName", [$this, "addNewsName"]),
new TwigFunction("getAllNewsNamesFormatted", [$this, "getAllNewsNamesFormatted"]),
new TwigFunction("getStoryById", [$this, "getStoryById"]),
new TwigFunction("getStoryByUuid", [$this, "getStoryByUuid"]),
new TwigFunction("microtime", [$this, "microtime"]),
new TwigFunction("getRefererLink", [$this, "getRefererLink"]),
new TwigFunction("getLanguageSwitchLinks", [$this, "getLanguageSwitchLinks"]),
new TwigFunction("getStudentNews", [$this, "getStudentNews"]),
new TwigFunction("logErrorReferrer", [$this, "logErrorReferrer"]),
new TwigFunction("getDomain", [$this, "getDomain"]),
new TwigFunction("getVideoChannelUrl", [$this, "getVideoChannelUrl"]),
new TwigFunction("getTeasersByUri", [$this, "getTeasersByUri"]),
new TwigFunction("getTeaserByPath", [$this, "getTeaserByPath"]),
new TwigFunction("getSpaceID", [$this, "getSpaceID"]),
new TwigFunction("isStaticUserLoggedIn", [$this, "isStaticUserLoggedIn"]),
new TwigFunction("getMAPIToken", [$this, "getMAPIToken"]),
new TwigFunction("getBlogNews", [$this, "getBlogNews"]),
new TwigFunction("getMicrositeNavigation", [$this, "getMicrositeNavigation"]),
new TwigFunction("getRandomNumbers", [$this, "getRandomNumbers"]),
new TwigFunction("getRecaptchaSitekey", [$this, "getRecaptchaSitekey"]),
new TwigFunction("getToken", [$this, "getToken"]),
new TwigFunction("getGoogleSiteVerificationContent", [$this, "getGoogleSiteVerificationContent"]),
new TwigFunction("getAimsSteps", [$this, "getAimsSteps"]),
new TwigFunction("getAimsStepIndexes", [$this, "getAimsStepIndexes"]),
new TwigFunction("getAimsStepDisplayNames", [$this, "getAimsStepDisplayNames"]),
new TwigFunction("loadExternalFile", [$this, "loadExternalFile"]),
new TwigFunction("getGoogleRecaptchaSitekey", [$this, "getGoogleRecaptchaSitekey"]),
new TwigFunction("getStudentsSourcefield", [$this, "getStudentsSourcefield"]),
new TwigFunction("getCurrentEnv", [$this, "getCurrentEnv"]),
new TwigFunction("getNewsroomArticles", [$this, "getNewsroomArticles"]),
new TwigFunction("getNewsroomMainCategories", [$this, "getNewsroomMainCategories"]),
new TwigFunction("getNewsroomMainCategoryByType", [$this, "getNewsroomMainCategoryByType"]),
new TwigFunction("getNewsroomArticlesByFamilyId", [$this, "getNewsroomArticlesByFamilyId"]),
new TwigFunction("getNewsroomArticlesByPath", [$this, "getNewsroomArticlesByPath"]),
new TwigFunction("getNewsroomTags", [$this, "getNewsroomTags"]),
new TwigFunction("getNewsroomTagTranslation", [$this, "getNewsroomTagTranslation"]),
new TwigFunction("getNewsroomIntervalDateAgo", [$this, "getNewsroomIntervalDateAgo"]),
new TwigFunction("getNewsroomPathByType", [$this, "getNewsroomPathByType"]),
new TwigFunction("getNewsroomArticlesByType", [$this, "getNewsroomArticlesByType"]),
new TwigFunction("isNewsroomRefreshEnabledForLanguage", [$this, "isNewsroomRefreshEnabledForLanguage"]),
new TwigFunction("getUserProfile", [$this, "getUserProfile"]),
new TwigFunction("formatDateByLocale", [$this, "formatDateByLocale"]),
new TwigFunction("getNewsroomNewsWithFilter", [$this, "getNewsroomNewsWithFilter"]),
new TwigFunction("getAboriginalCountryDatasources", [$this, "getAboriginalCountryDatasources"]),
new TwigFunction("getDatareporterUrl", [$this, "getDatareporterUrl"]),
new TwigFunction("getUserCountryCode", [$this, "getUserCountryCode"]),
new TwigFunction("getDatasourceEntries", [$this, "getDatasourceEntries"]),
new TwigFunction("getDatareporterActivationcodeUrl", [$this, "getDatareporterActivationcodeUrl"]),
new TwigFunction("getAimsContentOverlayTabLinks", [$this, "getAimsContentOverlayTabLinks"]),
new TwigFunction("getAimsColorByStep", [$this, "getAimsColorByStep"]),
new TwigFunction("getProductConfiguratorAnswersHasImage", [$this, "getProductConfiguratorAnswersHasImage"]),
new TwigFunction("getAimsStepsByStep", [$this, "getAimsStepsByStep"]),
new TwigFunction("getAimsStepNumberByAnchorName", [$this, "getAimsStepNumberByAnchorName"]),
new TwigFunction("getAlternatesByLocaleAndFamilyId", [$this, "getAlternatesByLocaleAndFamilyId"]),
new TwigFunction("getWidgetByUid", [$this, "getWidgetByUid"]),
new TwigFunction("getPromotionsCategories", [$this, "getPromotionsCategories"]),
new TwigFunction("getPromotions", [$this, "getPromotions"]),
new TwigFunction("getPromotionCategoryTranslation", [$this, "getPromotionCategoryTranslation"]),
new TwigFunction("getPromotionCategoriesKeys", [$this, "getPromotionCategoriesKeys"]),
new TwigFunction("getPromotionCategoryKey", [$this, "getPromotionCategoryKey"]),
new TwigFunction("hasImageCorrectSize", [$this, "hasImageCorrectSize"]),
new TwigFunction("getDosingCalculatorData", [$this, "getDosingCalculatorData"]),
new TwigFunction("getJobById", [$this, "getJobById"]),
new TwigFunction("isChatbubbleDisabled", [$this, "isChatbubbleDisabled"]),
new TwigFunction("getJobs", [$this, "getJobs"]),
new TwigFunction("getJobContactPersons", [$this, "getJobContactPersons"]),
new TwigFunction("getEventsByType", [$this, "getEventsByType"]),
new TwigFunction("getRedirectsTo", [$this, "getRedirectsTo"])
];
}
public function getRedirectsTo($url)
{
return $this->redirectService->getRedirectsTo($url);
}
public function getEventsByType($type)
{
return $this->newsroomService->getEventsByType($type);
}
public function getJobContactPersons($locale, $contactPersonID)
{
$contactPersons = [];
if (!$contactPersonID) {
return $contactPersons;
}
try {
$categoryConfig = $this->categoryConfigService->getByFamilyId($locale, '/career/contactpersons');
$contactPersons = $this->storyblok->getStories([
'page' => '1',
'per_page' => 1000,
'starts_with' => ltrim($categoryConfig['seo_url'], '/')
])->getBody()['stories'];
foreach ($contactPersons as &$contactPerson) {
$contactPerson['content']['_uid'] = $contactPerson['uuid'];
}
$contactPersons = array_values(array_filter($contactPersons, function ($contactPerson) use ($contactPersonID) {
return $contactPerson['content']['sage_contact_person_id'] === $contactPersonID;
}));
return $contactPersons;
} catch (\Exception $e) {
return $contactPersons;
}
return $contactPersons;
}
public function getJobs()
{
return $this->sageApiService->getJobs();
}
public function getJobById($id)
{
return $this->sageApiService->getJobById($id);
}
public function isChatbubbleDisabled($lang)
{
try {
$categoryConfig = $this->categoryConfigService->getByLocale($lang);
return array_key_exists('disable_chat_bubble_for_language', $categoryConfig) ? $categoryConfig['disable_chat_bubble_for_language'] . '' : 'false';
} catch (\Exception $e) {
return 'false';
}
}
public function getDosingCalculatorData()
{
return $this->dosingCalculatorService->getData();
}
public function getPromotionCategoriesKeys($categories)
{
return $this->promotionService->getCategoriesKeys($categories);
}
public function getPromotionCategoryKey($categories)
{
return $this->promotionService->getCategoryKey($categories);
}
public function getPromotionCategoryTranslation($category)
{
return $this->promotionService->getCategoryTranslation($category);
}
public function getPromotions()
{
return $this->promotionService->getAll();
}
public function getPromotionsCategories()
{
return $this->promotionService->getCategories();
}
public function getWidgetByUid($uid)
{
return $this->widgetService->getByUid($uid);
}
public function getAlternatesByLocaleAndFamilyId($locale, $familyId, $dynamicSlug = null)
{
$langsToIgnore = ['test-aus', 'de_austria', 'de_germany', 'cn_china_consultis', 'cn_china'];
$alternates = [];
try {
foreach ($this->availableLanguages as $lang) {
if ($lang !== $locale) {
$categoryConfig = $this->categoryConfigService->getByFamilyId($lang, $familyId);
if (
isset($categoryConfig) &&
!$categoryConfig['hideEverywhere'] &&
!in_array($lang, $langsToIgnore)
) {
if ($dynamicSlug) {
$fullSlug = $categoryConfig['seo_url'] . '/' . $dynamicSlug;
if ($this->storyblok->getStoryBySlug($fullSlug)) {
array_push($alternates, $fullSlug);
}
} else {
array_push($alternates, $categoryConfig['seo_url']);
}
}
}
}
return $alternates;
} catch (\Exception $e) {
return $alternates;
}
}
public function getAimsStepNumberByAnchorName($sections, $anchorname)
{
$section = array_filter($sections, function ($section) use ($anchorname) {
return $section['anchor_name'] === $anchorname;
});
$index = array_key_first($section);
$section[$index]['index'] = $index;
return array_values($section)[0];
}
public function getAimsColorByStep($step)
{
$colorMapping = array(
'used_item' => 'dark-violet',
'cleaning' => 'congress-blue',
'disinfection' => 'lithe-blue',
'inspection' => 'bondi-blue',
'packaging' => 'jungle-green',
'sterilization' => 'apple-green',
'storage' => 'lime-yellow',
'environment' => 'cement-gray'
);
return array_key_exists($step, $colorMapping) ? $colorMapping[$step] : ''; //color
}
public function getAimsContentOverlayTabLinks($slide)
{
$tabs = [];
try {
$tabs = $this->recursiveFind($slide, 'tabs');
return array_map(function ($tab) {
return [
'name' => $tab['name'],
];
}, $tabs);
} catch (\Exception $e) {
return $tabs;
}
}
private function recursiveFind(array $array, $needle, $searchVal = null)
{
$iterator = new \RecursiveArrayIterator($array);
$recursive = new \RecursiveIteratorIterator($iterator, \RecursiveIteratorIterator::SELF_FIRST);
foreach ($recursive as $key => $value) {
if ($searchVal) {
if ($key === $needle) {
return $value;
}
} else {
if ($key === $needle) {
return $value;
}
}
}
}
public function getProductConfiguratorAnswersHasImage($answers)
{
$hasAnswersWithImage = false;
foreach ($answers as $answer) {
if ($answer['image']['filename']) {
$hasAnswersWithImage = true;
break;
}
}
return $hasAnswersWithImage;
}
public function getDatasourceEntries($slug)
{
$entries = $this->storyblok->getDatasourceEntries($slug, [
'page' => 1,
'per_page' => 1000
])->getBody();
return $entries['datasource_entries'];
}
public function getUserCountryCode()
{
return $this->requestStack->getCurrentRequest()->attributes->get('HTTP_CLOUDFRONT_VIEWER_COUNTRY');
}
public function getDatareporterActivationcodeUrl(): string
{
return $this->datareporterUrlActivationCode;
}
public function getDatareporterUrl(): string
{
return $this->datareporterUrl;
}
public function getNewsroomNewsWithFilter($filter, $count = 200)
{
return $this->newsroomService->getNewsWithFilter($filter, $count);
}
public function getUserProfile()
{
return $this->userService->getProfile();
}
public function isNewsroomRefreshEnabledForLanguage($language)
{
return str_contains($this->newsroomRefreshLanguages, $language);
}
public function getNewsroomArticlesByType($type)
{
return $this->newsroomService->getArticlesByType($type);
}
public function getNewsroomPathByType($type)
{
return $this->newsroomService->getPathByType($type);
}
public function getNewsroomIntervalDateAgo($date, $format = '%a')
{
if ($date) {
$date1 = date_create(date('Y-m-d', time()));
$date2 = date_create(date('Y-m-d', strtotime($date)));
$diff = date_diff($date1, $date2)->format($format);
return $diff;
}
return '';
}
public function getNewsroomTagTranslation($tag)
{
return $this->newsroomService->getTagTranslation($tag);
}
public function getNewsroomTags()
{
return $this->newsroomService->getTags();
}
public function getNewsroomArticlesByPath($path)
{
return $this->newsroomService->getArticlesByPath($path);
}
public function getNewsroomArticlesByFamilyId($familyId)
{
return $this->newsroomService->getArticlesByFamilyId($familyId);
}
public function getNewsroomMainCategoryByType($type)
{
return $this->newsroomService->getMainCategoryByType($type);
}
public function getNewsroomMainCategories()
{
return $this->newsroomService->getMainCategories();
}
public function getNewsroomArticles()
{
return $this->newsroomService->getArticles();
}
public function getStudentsSourcefield($lang)
{
$whitelist = array("cz_czech");
if (in_array($lang, $whitelist)) {
return 'students';
} else {
return 'web';
}
}
public function getGoogleSiteVerificationContent()
{
return $this->googleSiteVerificationContent;
}
public function getCurrentEnv()
{
return $_SERVER['APP_ENV'];
}
public function loadExternalFile($path)
{
try {
$parsed_url = parse_url($path);
$protocol = stripos($_SERVER['SERVER_PROTOCOL'], 'https') === 0 ? 'https:' : 'http:';
return file_get_contents(array_key_exists('scheme', $parsed_url) ? $path : $protocol . $path);
} catch (\Exception $e) {
return 'ICON COULD NOT BE LOADED';
}
}
public function getAimsStepDisplayNames($steps)
{
$array_map = array_map(
function ($item) {
return $item['content']['display_name'] ? $item['content']['display_name'] : str_replace('_', ' ', ucfirst($item['content']['anchor_name']));
},
$steps
);
return $array_map;
}
public function getAimsStepIndexes($steps)
{
$array_map = array_map(
function ($item) {
return $item['content']['anchor_name'];
},
$steps
);
return $array_map;
}
public function getAimsSteps($starts_with, $singleStory = false)
{
return $this->aimsService->getStepsSorted($starts_with, $singleStory);
}
public function markdown($text)
{
if (is_string($text)) {
return \ParsedownExtraPlugin::instance()
->setMarkupEscaped(false)
->setBreaksEnabled(true)
->text($text);
}
return '';
}
public function getRandomNumbers($min, $max, $amount)
{
if ($amount <= 1) {
return random_int($min, $max);
}
$arr = array();
for ($i = 1; $i <= $amount; $i++) {
$number = random_int($min, $max);
if (in_array($number, $arr)) {
$i--;
} else {
array_push($arr, $number);
}
}
return $arr;
}
public function removeNbsp($content)
{
$string = htmlentities($content, null, 'utf-8');
$content = str_replace(" ", " ", $string);
$content = html_entity_decode($content);
return $content;
}
public function isStaticUserLoggedIn($id)
{
return $this->userService->isStaticUserLoggedIn($id);
}
public function getSpaceID()
{
return $this->spaceId;
}
public function getMAPIToken()
{
return $this->mapiToken;
}
public function getVideoChannelUrl($categoryLang)
{
$baseUrl = 'https://video.wh.com/';
$list = ['cz_czech' => 'en_global'];
if (array_key_exists($categoryLang, $list)) {
return $baseUrl . $list[$categoryLang];
} else {
return $baseUrl . $categoryLang;
}
}
public function getTeasersByUri($uri)
{
$articles = $this->teaserIncludeService->getTeasersByUri($uri);
return $articles;
}
public function getDomain()
{
return $this->domain;
}
public function logErrorReferrer()
{
$request = $this->requestStack->getCurrentRequest();
$this->logger->error('Error Page: ' . $request->headers->get('referer'));
}
public function getRefererLink()
{
$request = $this->requestStack->getCurrentRequest();
return $request->headers->get('referer');
}
public function getLanguageSwitchLinks($locale, $alternates, $isMicrosite = false)
{
$links = [];
foreach ($this->availableLanguages as $language) {
if ($language != $locale) {
$alternatesLength = count($alternates);
$i = 0;
while (!isset($links[$language]) && $i < $alternatesLength) {
$alternate = $alternates[$i];
$alternateLang = explode('/', $alternate['full_slug'])[0];
if ($alternateLang == $language) {
$links[$language] = $alternate['full_slug'];
if ($isMicrosite && $_SERVER['APP_ENV'] !== "dev") {
$links[$language] = str_replace('/microsites', '', $links[$language]);
foreach ($this->micrositeNameMap as $key => $micrositeName) {
$links[$language] = str_replace('/' . $micrositeName, '', $links[$language]);
}
}
}
$i += 1;
}
if (!isset($links[$language])) {
$links[$language] = $language;
}
}
}
return $links;
}
public function microtime()
{
return round(microtime(true) * 1000);
}
public function resetArrayKeys($array)
{
return array_values($array);
}
public function getTeaserByPath($count, $path, $criterias)
{
return $this->announcementService->getTeaserByPath($count, $path, $criterias);
}
public function getNews($count, $criterias)
{
return $this->announcementService->getNews($count, $criterias, ['news', 'reports-and-studies', 'kurz-mal-weg']);
}
public function getBlogNews($count, $criterias)
{
return $this->announcementService->getNews($count, $criterias, ['kurz-mal-weg']);
}
public function getStudentNews($count, $criterias)
{
return $this->announcementService->getNews($count, $criterias, ['student-news', 'news', 'reports-and-studies']);
}
public function getNewsletter($count)
{
return $this->announcementService->getNewsletter($count);
}
public function getSearchHeadersForResultsPage()
{
return $this->searchService->getSearchHeadersForResultsPage();
}
public function getClosestRetailer($lat, $lng, $countryCode)
{
return $this->serviceStationLocatorService->getClosestRetailer($lat, $lng, $countryCode);
}
public function getProductNavigation($locale, $familyId)
{
return $this->menuService->getProductNavigationByFamilyId($locale, $familyId);
}
public function getMicrositeNavigation($category)
{
return $this->menuService->getMicrositeNavigation($category);
}
public function getNavigation($locale)
{
return $this->menuService->getNavigation($locale);
}
public function getLeftNavigation($locale, $navigationSlug)
{
return $this->menuService->getLeftNavigation($locale, $navigationSlug);
}
public function getCurrentLocation()
{
return $this->locationService->getCurrentLocation();
}
public function getShopUrl($locale)
{
if (!array_key_exists($locale, $this->shopDomains)) {
return null;
}
$domain = $this->shopDomains[$locale]['domain'];
$location = strtolower($this->getCurrentLocation());
$path = $this->shopDomains[$locale]['path'];
$mappedCountry = array_key_exists($location, $this->countryLanguageMapping) ? $this->countryLanguageMapping[$location] : null;
if ($mappedCountry && $mappedCountry !== $locale) {
$newLocation = array_search($locale, $this->countryLanguageMapping);
$location = $newLocation ? $newLocation : $location;
}
return $domain . $location . $path;
}
public function getCurrentLatitude()
{
return $this->locationService->getCurrentLatitude();
}
public function getCurrentLongitude()
{
return $this->locationService->getCurrentLongitude();
}
/**
* @param $level
* @return array
* @throws \Exception
*/
public function getCategory($level)
{
return $this->categoryConfigService->getByLevel($level);
}
public function getSitemap($locale)
{
return $this->menuService->getSitemap($locale);
}
public function version($url)
{
return $this->addToUrl($url, 'version', $this->cacheVersion);
}
public function isEditMode()
{
return $this->storyblokHelper->isEditmode();
}
public function getCountryContactData($lang)
{
try {
$jsonString = file_get_contents($this->projectDir . '/public/data/contacts/' . $lang . '_contact.json');
$jsonString = preg_replace('/[\x00-\x1F\x7F]/u', '', $jsonString);
return \json_decode($jsonString);
} catch (\Exception $e) {
return \json_decode('');
}
}
public function getStories($starts_with)
{
$now = date('Y-m-d H:i');
try {
$options = [
'starts_with' => $starts_with,
'per_page' => 500,
'filter_query[fromDate][lt-date]' => $now,
'filter_query[toDate][gt-date]' => $now,
'sort_by' => 'content.fromDate:desc'
];
$stories = $this->storyblok->getStories($options)->getBody()['stories'];
return $stories;
} catch (\Exception $e) {
return [];
}
}
public function getStoryBySlug($fullSlug)
{
try {
//check if is UUID format
if (preg_match('/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i', $fullSlug)) {
$this->storyblok->getStoryByUuid($fullSlug);
} else {
$this->storyblok->getStoryBySlug($fullSlug);
}
$data = $this->storyblok->getBody();
return $data['story'];
} catch (\Exception $e) {
return [];
}
}
public function getDocumentObject($documentID, $documentTypeDocfinder, $documentTypeManual)
{
return $this->documentService->createDocObject($documentID, $documentTypeDocfinder, $documentTypeManual);
}
public function documentInfo($documentInfo, $documentTypeId, $countryId, $langId = "")
{
return $this->documentService->get($documentInfo, $documentTypeId, $countryId, $langId);
}
public function getCanonical()
{
$canonical = $this->getDomain() . $this->requestStack->getCurrentRequest()->getPathInfo();
return $canonical;
}
public function getFontCacheKey()
{
return $this->fontCacheKey;
}
public function getGoogleAnalyticsId()
{
return $this->googleAnalyticsKey;
}
public function systemConf($confProperty)
{
return getenv("SYSTEM_CONF_" . $confProperty);
}
public function getBackendPath()
{
return getenv("BACKEND_URL");
}
/**
* @return string
* @throws \Exception
*/
public function uuid()
{
$data = random_bytes(16);
$data[6] = chr(ord($data[6]) & 0x0f | 0x40);
$data[8] = chr(ord($data[8]) & 0x3f | 0x80);
return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4));
}
/**
* @return string
* @throws \Exception
*/
function uniqid()
{
return uniqid();
}
public function hasImageCorrectSize($image, $size, $compareOnlyWidth = false)
{
if (strpos($image, 'a.storyblok') !== false) {
$url_data = array_filter(explode("/", $image), 'strlen');
$dimension = $url_data[5];
if ($compareOnlyWidth) {
$dimensionWidth = explode("x", $dimension)[0];
$sizeWidth = explode("x", $size)[0];
return $dimensionWidth !== $sizeWidth;
}
return $dimension !== $size;
}
return false;
}
public function image($image, $isNoImage = false, $size = '')
{
$optimizedPath = '';
if ($size !== '') {
$optimizedPath = '/m/' . $size;
}
// TODO to be removed in future:
if ($isNoImage) {
return $image;
} else if (strpos($image, 'a.storyblok') === false && strpos($image, '-micropage') === false) {
$image = 'https://www.wh.com' . $image;
} else if (strpos($image, 'a.storyblok') !== false) {
$image = trim($image) . $optimizedPath . '?t=' . time();
} else {
$image = trim($image) . '?t=' . time();
}
return $image;
}
public function url($url)
{
// TODO to be removed in future:
if (strpos($url, 'a.storyblok') === false) {
$url = 'https://www.wh.com' . $url;
}
return $url;
}
public function sbUrl($link)
{
if ($link['linktype'] == "story") {
$uuid = $link['id'];
if (isset($uuid) && $this->linkService->hasLink($uuid)) {
return '/' . $this->linkService->getLinkByUUID($uuid)['slug'];
}
}
return isset($link['url']) ? $link['url'] : $link;
}
public function sbUrlByUuid($uuid)
{
if (isset($uuid) && $this->linkService->hasLink($uuid)) {
return '/' . $this->linkService->getLinkByUUID($uuid)['slug'];
}
}
public function sbUrlById($id)
{
$result = $this->linkService->getLinkById($id);
if ($result) {
return $result['slug'];
} else {
$this->logger->warning("Wasn't able to find link for id: " . $id);
return $id;
}
}
public function getStoryById($id)
{
try {
$fullSlug = $this->sbUrlById($id);
$this->storyblok->getStoryBySlug($fullSlug);
return $this->storyblok->getBody();
} catch (\Exception $e) {
$this->logger->error($e);
return null;
}
}
public function getStoryByUuid($uuid)
{
try {
$fullSlug = $this->sbUrlByUuid($uuid);
$this->storyblok->getStoryBySlug($fullSlug);
return $this->storyblok->getBody();
} catch (\Exception $e) {
$this->logger->error($e);
return null;
}
}
public function getFamilyPart($familyId, $index)
{
$familyParts = explode('/', $familyId);
if ($index == -1) {
# breadcrumb
$result = $familyId;
} else if ($index >= count($familyParts)) {
$result = "";
} else {
$result = $familyParts[$index];
}
return $result;
}
public function getSkus($storyContent)
{
$fieldName = "productBlockPRName";
$result = [];
foreach (array_keys($storyContent) as $key => $value) {
if (strpos($key, $fieldName) > -1) {
array_push($result, $value);
} else if (is_array($value)) {
foreach ($value as $child) {
$result = array_merge($result, $this->getSkus($child));
}
}
}
return $result;
}
public function includeFile($path)
{
try {
$fullPath = $this->projectDir . '/public/' . $path;
return file_get_contents($fullPath);
} catch (\Exception $e) {
$this->logger->error($e);
throw new \Exception("Was not able to include file.");
}
}
public function familyUrl($lang, $familyId)
{
$categoryConfig = $this->categoryConfigService->getByFamilyId($lang, $familyId);
if (isset($categoryConfig)) {
return $categoryConfig['seo_url'];
}
return "#";
}
public function rindex($haystack, $needle, $offset = 0)
{
return strrpos($haystack, $needle, $offset);
}
/**
* @param $key
* @return string
* @throws \Psr\Cache\InvalidArgumentException
*/
public function label($key)
{
return $this->labelService->getLabel($key);
}
public function getNewsletterOgInfoById($nlid)
{
$ogData = new \stdClass();
$ogData->hasData = false;
if ($nlid != null) {
try {
$request_url = $_SERVER['PHP_SELF'];
$fullSlug = $request_url . '/' . $nlid;
$this->storyblok->getStoryBySlug($fullSlug);
$data = $this->storyblok->getBody();
$ogData->title = $data['story']['content']['nl_teaserheadline'];
$ogData->url = $_SERVER['REQUEST_URI'] . '?nlid=' . $nlid;
$ogData->image = $data['story']['content']['nl_teaserimage'];
$ogData->description = $data['story']['content']['nl_teasertext'];
$ogData->hasData = true;
} catch (\Exception $e) {
return $ogData;
}
}
return $ogData;
}
public function generateBreadcrumb()
{
$url = $this->requestStack->getCurrentRequest()->getPathInfo();
$urlwithoutSlash = join('/', array_slice(explode('/', $url), 1));
try {
$slug = $this->categoryConfigService->getSlugByUrl($urlwithoutSlash);
$breadcrumbs = $this->menuService->getBreadcrumbs($slug);
$breadcrumbs = array_filter($breadcrumbs, function ($item) {
return !str_contains($item['url'], 'archive');
});
return $breadcrumbs;
} catch (\Exception $exception) {
$this->logger->warning($exception->getMessage());
return [];
}
}
public function getVideoTutorialsByProductId($productId, $langId)
{
return $this->videoTutorialService->getByProductId($productId, $langId);
}
public function getAccessoriesByProductId($productId, $langId)
{
return $this->accessoryService->getAccessoriesByProductId($productId, $langId);
}
public function getNextEvent($langId, $filterCountry)
{
return $this->eventService->getNextEvent($langId, $filterCountry);
}
public function getFAQsByProductId($productId, $langId, $faqPath)
{
return $this->faqService->getFAQsByProductId($productId, $langId, $faqPath);
}
public function getFAQsByApplicationArea($langId, $applicationAreaId = "")
{
return $this->faqService->getFAQsByApplicationArea($langId, $applicationAreaId);
}
public function overviewData(string $path, string $contentType, int $page = 1, int $limit = 10, string $sortBy = null)
{
return $this->overviewService->getOverviewData($path, $contentType, $page, $limit, $sortBy);
}
public function getScienceCenterByProductId($productId, $langId): array
{
return $this->scienceCenterService->getByProductId($productId, $langId);
}
// TODO: When there is time, move these extensions into the Symfony "user" object
public function isUserLoggedIn()
{
return $this->userService->isLoggedIn();
}
public function activateUser($userId)
{
return $this->userService->activate($userId);
}
public function isStudentUser()
{
return $this->userService->isStudent();
}
// TODO: When there is time, move these extensions into the Symfony "user" object
public function userFirstname()
{
return $this->userService->getFirstname();
}
public function getToken()
{
return $this->userService->getToken();
}
private function addToUrl($url, $key, $value = null)
{
$query = parse_url($url, PHP_URL_QUERY);
if ($query) {
parse_str($query, $queryParams);
$queryParams[$key] = $value;
$url = str_replace("?$query", '?' . http_build_query($queryParams), $url);
} else {
$url .= '?' . urlencode($key) . '=' . urlencode($value);
}
return $url;
}
public function addTeaserName(string $teaserName)
{
$request = $this->requestStack->getCurrentRequest();
$teaserNames = $request->attributes->get('teaserNames');
$teaserNames[] = $teaserName;
$request->attributes->set('teaserNames', $teaserNames);
}
public function getAllTeaserNamesFormatted()
{
$names = $this->requestStack->getCurrentRequest()->attributes->get('teaserNames');
return $this->formatArrayForAnalytics($names ? $names : []);
}
public function addNewsName(string $newsName)
{
$request = $this->requestStack->getCurrentRequest();
$newsNames = $request->attributes->get('newsNames');
$newsNames[] = $newsName;
$request->attributes->set('newsNames', $newsNames);
}
public function getAllNewsNamesFormatted()
{
$names = $this->requestStack->getCurrentRequest()->attributes->get('newsNames');
return $this->formatArrayForAnalytics($names ? $names : []);
}
private function formatArrayForAnalytics(array $array)
{
$arrayLength = count($array);
$arrayString = '';
for ($i = 0; $i < $arrayLength; $i += 1) {
$arrayString .= strtolower($array[$i]);
if ($i < ($arrayLength - 1)) {
$arrayString .= '; ';
}
}
return $arrayString;
}
public function getRecaptchaSitekey(): string
{
return $this->recaptchaConfig['sitekey'];
}
public function formatDateByLocale($locale, $date, $format)
{
switch ($locale) {
case 'de_global':
setlocale(LC_TIME, 'de_DE');
break;
case 'en_global':
setlocale(LC_TIME, 'en_GB');
break;
case 'es_global':
setlocale(LC_TIME, 'es_ES');
break;
case 'es_iberica':
setlocale(LC_TIME, 'es_ES');
break;
case 'en_na':
setlocale(LC_TIME, 'en_CA');
break;
case 'en_uk':
setlocale(LC_TIME, 'en_GB');
break;
case 'en_australia':
setlocale(LC_TIME, 'en_AU');
break;
case 'pl_poland':
setlocale(LC_TIME, 'pl_PL');
break;
case 'bg_bulgaria':
setlocale(LC_TIME, 'bg_BG');
break;
case 'ru_cis':
setlocale(LC_TIME, 'ru_RU');
break;
case 'cn_china':
setlocale(LC_TIME, 'cn_CN');
break;
case 'de_germany':
setlocale(LC_TIME, 'de_DE');
break;
case 'de_austria':
setlocale(LC_TIME, 'de_DE');
break;
case 'it_italy':
setlocale(LC_TIME, 'it_IT');
break;
case 'fr_france':
setlocale(LC_TIME, 'fr_FR');
break;
case 'dk_nordic':
setlocale(LC_TIME, 'dk_DK');
break;
case 'se_nordic':
setlocale(LC_TIME, 'se_SE');
break;
case 'tk_turkey':
setlocale(LC_TIME, 'tr_TR');
break;
case 'ro_romania':
setlocale(LC_TIME, 'ro_RO');
break;
case 'pt_brasil':
setlocale(LC_TIME, 'pt_BR');
break;
default:
setlocale(LC_TIME, 'en_GB');
break;
}
return strftime($format, strtotime($date));
}
public function getAboriginalCountryDatasources()
{
$locale = $this->requestStack->getCurrentRequest()->getLocale();
$aboriginalCountry = $this->storyblok->getDatasourceEntries('aboriginal-country', [
'page' => 1,
'per_page' => 1000,
'dimension' => $locale
])->getBody();
return $aboriginalCountry['datasource_entries'];
}
}