src/Twig/SlivkiTwigExtension.php line 750

Open in your IDE?
  1. <?php
  2. namespace Slivki\Twig;
  3. use DateTimeInterface;
  4. use Doctrine\ORM\EntityManagerInterface;
  5. use IntlDateFormatter;
  6. use Slivki\Controller\SiteController;
  7. use Slivki\Dao\OfferCode\PurchaseCountDaoInterface;
  8. use Slivki\Entity\BankCurrency;
  9. use Slivki\Entity\BrandingBanner;
  10. use Slivki\Entity\Category;
  11. use Slivki\Entity\CategoryType;
  12. use Slivki\Entity\City;
  13. use Slivki\Entity\Comment;
  14. use Slivki\Entity\Director;
  15. use Slivki\Entity\InfoPage;
  16. use Slivki\Entity\MailingCampaign;
  17. use Slivki\Entity\Media;
  18. use Slivki\Entity\Media\OfferSupplierPhotoMedia;
  19. use Slivki\Entity\MediaType;
  20. use Slivki\Entity\NoticePopup;
  21. use Slivki\Entity\NoticePopupView;
  22. use Slivki\Entity\Offer;
  23. use Slivki\Entity\OfferExtensionVariant;
  24. use Slivki\Entity\PriceDeliveryType;
  25. use Slivki\Entity\ProductCategory;
  26. use Slivki\Entity\ProductFastDelivery;
  27. use Slivki\Entity\PurchaseCount;
  28. use Slivki\Entity\Sale;
  29. use Slivki\Entity\Seo;
  30. use Slivki\Entity\SiteSettings;
  31. use Slivki\Entity\UserGroup;
  32. use Slivki\Entity\Visit;
  33. use Slivki\Entity\VisitCounter;
  34. use Slivki\Enum\SwitcherFeatures;
  35. use Slivki\Repository\OfferRepository;
  36. use Slivki\Repository\ProductFastDeliveryRepository;
  37. use Slivki\Repository\SeoRepository;
  38. use Slivki\Services\BannerService;
  39. use Slivki\Services\CacheService;
  40. use Slivki\Services\ImageService;
  41. use Slivki\Services\RTBHouseService;
  42. use Slivki\Services\Sale\SaleCacheService;
  43. use Slivki\Services\Sidebar\SidebarCacheService;
  44. use Slivki\Services\Switcher\ServerFeatureStateChecker;
  45. use Slivki\Services\TextCacheService;
  46. use Slivki\Services\VideoConfigServiceInterface;
  47. use Slivki\Twig\Filter\PhoneNumberFilterTwigRuntime;
  48. use Slivki\Twig\Filter\ShortPriceFilterTwigRuntime;
  49. use Slivki\Util\OAuth2Client\AbstractOAuth2Client;
  50. use Slivki\Util\SoftCache;
  51. use Slivki\Util\CommonUtil;
  52. use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
  53. use Symfony\Component\HttpFoundation\RequestStack;
  54. use Slivki\Entity\User;
  55. use Slivki\Util\Logger;
  56. use Symfony\Component\DomCrawler\Crawler;
  57. use Symfony\Component\HttpFoundation\Session\Session;
  58. use Slivki\Repository\SiteSettingsRepository;
  59. use Symfony\Component\HttpKernel\KernelInterface;
  60. use Symfony\Component\Security\Acl\Exception\Exception;
  61. use Twig\Environment;
  62. use Twig\Extension\AbstractExtension;
  63. use Twig\TwigFilter;
  64. use Twig\TwigFunction;
  65. use Twig\TwigTest;
  66. class SlivkiTwigExtension extends AbstractExtension {
  67.     private $partnerLogoURL null;
  68.     private $entityManager;
  69.     private $request;
  70.     private $imageService;
  71.     private $bannerService;
  72.     private $textCacheService;
  73.     private $kernel;
  74.     private $cacheService;
  75.     private $saleCacheService;
  76.     private $RTBHouseService;
  77.     private static $photoGuideMenuItem null;
  78.     /**
  79.      * @var VideoConfigServiceInterface
  80.      */
  81.     private $videoConfigService;
  82.     private SidebarCacheService $sidebarCacheService;
  83.     private ServerFeatureStateChecker $serverFeatureStateChecker;
  84.     private ParameterBagInterface $parameterBag;
  85.     private PurchaseCountDaoInterface $purchaseCountDao;
  86.     public function __construct(
  87.         EntityManagerInterface $entityManager,
  88.         RequestStack $requestStack,
  89.         ImageService $imageService,
  90.         BannerService $bannerService,
  91.         TextCacheService $textCacheService,
  92.         KernelInterface $kernel,
  93.         CacheService $cacheService,
  94.         SaleCacheService $saleCacheService,
  95.         RTBHouseService $RTBHouseService,
  96.         VideoConfigServiceInterface $videoConfigService,
  97.         SidebarCacheService $sidebarCacheService,
  98.         ServerFeatureStateChecker $serverFeatureStateChecker,
  99.         ParameterBagInterface $parameterBag,
  100.         PurchaseCountDaoInterface $purchaseCountDao
  101.     ) {
  102.         $this->entityManager $entityManager;
  103.         $this->request $requestStack->getMainRequest();
  104.         $this->imageService $imageService;
  105.         $this->bannerService $bannerService;
  106.         $this->textCacheService $textCacheService;
  107.         $this->kernel $kernel;
  108.         $this->cacheService $cacheService;
  109.         $this->saleCacheService $saleCacheService;
  110.         $this->RTBHouseService $RTBHouseService;
  111.         $this->videoConfigService $videoConfigService;
  112.         $this->sidebarCacheService $sidebarCacheService;
  113.         $this->serverFeatureStateChecker $serverFeatureStateChecker;
  114.         $this->parameterBag $parameterBag;
  115.         $this->purchaseCountDao $purchaseCountDao;
  116.     }
  117.     public function getFilters(): array
  118.     {
  119.         return [
  120.             new TwigFilter('plural', [$this'pluralFilter']),
  121.             new TwigFilter('preg_replace', [$this'pregReplaceFilter']),
  122.             new TwigFilter('localizedate', [$this'localizeDateFilter']),
  123.             new TwigFilter('localize_timestamp_date', [$this'localizeDateTimestampFilter']),
  124.             new TwigFilter('phone', [$this'phoneFilter']),
  125.             new TwigFilter('json_decode', [$this'jsonDecodeFilter']),
  126.             new TwigFilter('short_price', [ShortPriceFilterTwigRuntime::class, 'shortPriceFormat']),
  127.             new TwigFilter('phone_number', [PhoneNumberFilterTwigRuntime::class, 'phoneNumberFormat']),
  128.         ];
  129.     }
  130.     public function getFunctions() {
  131.         return array(
  132.             new TwigFunction("getTopLevelCategories", array($this"getTopLevelCategories")),
  133.             new TwigFunction("getMetaInfo", array($this"getMetaInfo")),
  134.             new TwigFunction("getURL", array($this"getURL")),
  135.             new TwigFunction("getCategoryURL", array($this"getCategoryURL")),
  136.             new TwigFunction("getCategoriesList", array($this"getCategoriesList")),
  137.             new TwigFunction("getCityList", array($this"getCityList")),
  138.             new TwigFunction("getTopCityList", array($this"getTopCityList")),
  139.             new TwigFunction("getCategoryTypeList", array($this"getCategoryTypeList")),
  140.             new TwigFunction("getImageURL", array($this"getImageURL")),
  141.             new TwigFunction("getSidebar", [$this"getSidebar"], ['is_safe' => ['html'], 'needs_environment' => true]),
  142.             new TwigFunction("getProfileImageURL", [$this"getProfileImageURL"]),
  143.             new TwigFunction("getSiteSettings", [$this"getSiteSettings"]),
  144.             new TwigFunction("staticCall", [$this"staticCall"]),
  145.             new TwigFunction("getVisitCount",[$this"getVisitCount"]),
  146.             new TwigFunction("getOfferVisitCount",[$this"getOfferVisitCount"]),
  147.             new TwigFunction("getSaleVisitCount",[$this"getSaleVisitCount"]),
  148.             new TwigFunction("getVideoGuideVisitCount",[$this"getVideoGuideVisitCount"]),
  149.             new TwigFunction("getOfferMonthlyPurchaseCount",[$this"getOfferMonthlyPurchaseCount"]),
  150.             new TwigFunction("getTopSiteBanner",[$this"getTopSiteBanner"], ['is_safe' => ['html'], 'needs_environment' => false]),
  151.             new TwigFunction("getCategoryBanner",[$this"getCategoryBanner"]),
  152.             new TwigFunction('getCommentsBanners',[GetCommentsBanners::class, 'getCommentsBanners']),
  153.             new TwigFunction("getGoogleBanner",[$this"getGoogleBanner"], ['is_safe' => ['html'], 'needs_environment' => true]),
  154.             new TwigFunction("getBankCurrencyList", array($this"getBankCurrencyList")),
  155.             new TwigFunction("getCategoryBreadcrumbs", array($this"getCategoryBreadcrumbs")),
  156.             new TwigFunction("getLastComments", [$this"getLastComments"]),
  157.             new TwigFunction("getCommentEntityByType", [$this"getCommentEntityByType"]),
  158.             new TwigFunction("getCommentsMenuItems", [$this"getCommentsMenuItems"]),
  159.             new TwigFunction("getMainMenu", [$this"getMainMenu"], ['is_safe' => ['html'], 'needs_environment' => true]),
  160.             new TwigFunction("getActiveSubCategories", [$this"getActiveSubCategories"]),
  161.             new TwigFunction("getActiveSalesCount", [$this"getActiveSalesCount"]),
  162.             new TwigFunction("getActiveOffersCount", [$this"getActiveOffersCount"]),
  163.             new TwigFunction("getPartnerLogoURL", [$this"getPartnerLogoURL"]),
  164.             new TwigFunction("getCommentsCountByUserID", [$this"getCommentsCountByUserID"]),
  165.             new TwigFunction("getInfoPages", [$this"getInfoPages"]),
  166.             new TwigFunction("getSaleShortDescription", [$this"getSaleShortDescription"]),
  167.             new TwigFunction("isMobileDevice", [$this"isMobileDevice"]),
  168.             new TwigFunction("getNoticePopup", [$this"getNoticePopup"], ['is_safe' => ['html'], 'needs_environment' => true]),
  169.             new TwigFunction("getBrandingBanner", [$this"getBrandingBanner"], ['is_safe' => ['html'], 'needs_environment' => true]),
  170.             new TwigFunction("addSchemeAndHttpHostToImageSrc", [$this"addSchemeAndHttpHostToImageSrc"]),
  171.             new TwigFunction("getSupplierOfferPhotoBlockByOfferID", [$this"getSupplierOfferPhotoBlockByOfferID"], ['is_safe' => ['html'], 'needs_environment' => true]),
  172.             new TwigFunction("getUserCommentsMediaBlockByEntityID", [$this"getUserCommentsMediaBlockByEntityID"], ['is_safe' => ['html'], 'needs_environment' => true]),
  173.             new TwigFunction("getEntityRatingWithCount", [$this"getEntityRatingWithCount"]),
  174.             new TwigFunction("getInfoLine", [$this"getInfoLine"], ['is_safe' => ['html'], 'needs_environment' => true]),
  175.             new TwigFunction("getTeaserWatermark", [$this"getTeaserWatermark"]),
  176.             new TwigFunction("getCompaniesRatingBlock", [$this"getCompaniesRatingBlock"], ['is_safe' => ['html'], 'needs_environment' => true]),
  177.             new TwigFunction("getTestMenuItem", [$this"getTestMenuItem"]),
  178.             new TwigFunction("getMailingCampaignEntityPositionByEntityID", [$this"getMailingCampaignEntityPositionByEntityID"]),
  179.             new TwigFunction("getUsersOnlineCount", [$this"getUsersOnlineCount"]),
  180.             new TwigFunction("getActiveCityList", [$this"getActiveCityList"]),
  181.             new TwigFunction("getActiveSortedCityList", [$this"getActiveSortedCityList"]),
  182.             new TwigFunction("getCurrentCity", [$this"getCurrentCity"]),
  183.             new TwigFunction("setSeenMicrophoneTooltip", [$this"setSeenMicrophoneTooltip"]),
  184.             new TwigFunction("getFlierProductCategories", [$this"getFlierProductCategories"],  ['is_safe' => ['html'], 'needs_environment' => true]),
  185.             new TwigFunction("getFlierProductSubCategories", [$this"getFlierProductSubCategories"],  ['is_safe' => ['html'], 'needs_environment' => true]),
  186.             new TwigFunction("getIPLocationData", [$this"getIPLocationData"]),
  187.             new TwigFunction("isInDefaultCity", [$this"isInDefaultCity"]),
  188.             new TwigFunction("showMyPromocodesMenuItem", [$this"showMyPromocodesMenuItem"]),
  189.             new TwigFunction("getFooter", [$this"getFooter"],  ['is_safe' => ['html'], 'needs_environment' => true]),
  190.             new TwigFunction("addLazyAndLightboxImagesInDescription", [$this"addLazyAndLightboxImagesInDescription"]),
  191.             new TwigFunction("getStatVisitCount", [$this"getStatVisitCount"]),
  192.             new TwigFunction("getSaleCategoriesSortedBySaleVisits", [$this"getSaleCategoriesSortedBySaleVisits"]),
  193.             new TwigFunction("getMedia", [$this"getMedia"]),
  194.             new TwigFunction("logWrite", [$this"logWrite"]),
  195.             new TwigFunction('getLastVisitedOffersByUserId', [GetLastVisitedOffersTwigRuntime::class, 'getLastVisitedOffersByUserId']),
  196.             new TwigFunction("getManagerPhoneNumber", [$this"getManagerPhoneNumber"]),
  197.             new TwigFunction("getSocialProviderLoginUrl", [$this"getSocialProviderLoginUrl"]),
  198.             new TwigFunction("getBannerCodeFromFile", [$this"getBannerCodeFromFile"]),
  199.             new TwigFunction("getCurrentCityURL", [$this"getCurrentCityURL"]),
  200.             new TwigFunction("getMobileFloatingBanner", [MobileFloatingBannerRuntime::class, "getMobileFloatingBanner"]),
  201.             new TwigFunction("isTireDirector", [$this"isTireDirector"]),
  202.             new TwigFunction('isProductFastDelivery', [$this'isProductFastDelivery']),
  203.             new TwigFunction('calcDeliveryPriceOffer', [$this'calcDeliveryPriceOffer']),
  204.             new TwigFunction('calcDishDiscount', [$this'calcDishDiscount']),
  205.             new TwigFunction('getRTBHouseUID', [$this'getRTBHouseUID']),
  206.             new TwigFunction('getOfferConversion', [$this'getOfferConversion']),
  207.             new TwigFunction('getVimeoEmbedPreview', [$this'getVimeoEmbedPreview']),
  208.             new TwigFunction('qrGeneratorMessage', [QRMessageGeneratorRuntime::class, 'qrGeneratorMessage']),
  209.             new TwigFunction('getFilterOrdersCount', [OnlineOrderHistoryTwigRuntime::class, 'getFilterOrdersCount']),
  210.             new TwigFunction('getUserBalanceCodesCount', [$this'getUserBalanceCodesCount']),
  211.             new TwigFunction('showAppInviteModal', [$this'showAppInviteModal']),
  212.             new TwigFunction('getOfferManagers', [UserGroupTwigRuntime::class, 'getOfferManagers']),
  213.             new TwigFunction('getLinkOnlineOrder', [GetLinkOnlineOrderRuntime::class, 'getLinkOnlineOrder']),
  214.             new TwigFunction('getLinkFoodOnlineOrder', [GetLinkOnlineOrderRuntime::class, 'getLinkFoodOnlineOrder']),
  215.             new TwigFunction('getLinkGiftCertificateOnlineOrder', [GetLinkOnlineOrderRuntime::class, 'getLinkGiftCertificateOnlineOrder']),
  216.             new TwigFunction('getLinkGiftCertificateOnlineOrderByOnlyCode', [GetLinkOnlineOrderRuntime::class, 'getLinkGiftCertificateOnlineOrderByOnlyCode']),
  217.             new TwigFunction('getLinkTireOnlineOrder', [GetLinkOnlineOrderRuntime::class, 'getLinkTireOnlineOrder']),
  218.             new TwigFunction('isSubscriber', [SubscriptionTwigRuntime::class, 'isSubscriber']),
  219.             new TwigFunction('getSubscription', [SubscriptionTwigRuntime::class, 'getSubscription']),
  220.             new TwigFunction('getOfferCommentsCount', [GetCommentsCountTwigRuntime::class, 'getOfferCommentsCount']),
  221.             new TwigFunction('getDeliveryTimeText', [DeliveryTimeTextTwigRuntime::class, 'getDeliveryTimeText']),
  222.             new TwigFunction('getCertificateAddresses', [GiftCertificateTwigRuntime::class, 'getCertificateAddresses']),
  223.             new TwigFunction('isServerFeatureEnabled', [ServerFeatureStateTwigRuntime::class, 'isServerFeatureEnabled']),
  224.             new TwigFunction('getDishNutrients', [GetDishNutrientsTwigRuntime::class, 'getDishNutrients']),
  225.         );
  226.     }
  227.     public function getTests() {
  228.         return [
  229.             new TwigTest('instanceof', [$this'isInstanceof']),
  230.             new TwigTest('object', [$this'isObject'])
  231.         ];
  232.     }
  233.     public function getTeaserWatermark($offerID) {
  234.         return $this->entityManager->getRepository(Offer::class)->getTeaserWatermark($offerID);
  235.     }
  236.     public function addSchemeAndHttpHostToImageSrc($text) {
  237.         $schemeAndHttpHost $this->request->getSchemeAndHttpHost();
  238.         return preg_replace('/(<img.*src=")(?!http)[\/]{0,1}([^"]*)/'"$1".$schemeAndHttpHost."/$2"$text);
  239.     }
  240.     public function getBrandingBanner(Environment $twig$user$categoryIDs = [], $offerID null) {
  241.         // TODO:: REFACTORING AND CACHING
  242.         $brandingBannerList = [];
  243.         if ($user && $user->getEmail() == 'kristina@slivki.by') {
  244.             $dql "select brandingBanner from Slivki:BrandingBanner brandingBanner where brandingBanner.test = :test order by brandingBanner.ID desc";
  245.             $brandingBannerList $this->entityManager->createQuery($dql)->setParameter('test'true)->getResult();
  246.         }
  247.         if (empty($brandingBannerList)) {
  248.             $dql "select brandingBanner from Slivki:BrandingBanner brandingBanner where brandingBanner.activeSince < :timeFrom and brandingBanner.activeTill > :timeTo and brandingBanner.test = :test and brandingBanner.active = :active order by brandingBanner.ID desc";
  249.             $brandingBannerList $this->entityManager->createQuery($dql)
  250.                 ->setParameter('timeFrom', new \DateTime())
  251.                 ->setParameter('timeTo', (new \DateTime())->modify('-1 day'))
  252.                 ->setParameter('test'false)->setParameter('active'true)
  253.                 ->getResult();
  254.             $bannersForCity = [];
  255.             $currentCityID = (int) $this->getCurrentCity()->getID();
  256.             foreach ($brandingBannerList as $key => $item) {
  257.                 if (in_array($currentCityID$item->getCityIds(), true)) {
  258.                     $bannersForCity[] = $item;
  259.                 } else {
  260.                     unset($brandingBannerList[$key]);
  261.                 }
  262.             }
  263.             if (!empty($bannersForCity)) {
  264.                 $brandingBannerList $bannersForCity;
  265.             }
  266.         }
  267.         $currentBrandingBanner = [];
  268.         $refreshCookie $this->request->cookies->get('refresh');
  269.         if (empty($categoryIDs) && strpos($this->request->headers->get('referer'), 'https://www.t.dev.slivki.by') === false && !$refreshCookie) {
  270.             foreach ($brandingBannerList as $branding) {
  271.                 if ($branding->getTitle() == 'yandex') {
  272.                     $currentBrandingBanner = [$branding];
  273.                 }
  274.             }
  275.         }
  276.         if (!$currentBrandingBanner) {
  277.             $breaker false;
  278.             $currentCategory null;
  279.             $categoryBrandingBannerList = [];
  280.             /** @var  BrandingBanner $item */
  281.             foreach ($categoryIDs as $categoryID) {
  282.                 $currentCategory $this->entityManager->getRepository(Category::class)->find($categoryID);
  283.                 if ($currentCategory) {
  284.                     /** @var BrandingBanner $brandingBanner */
  285.                     foreach ($brandingBannerList as $item) {
  286.                         if ($item->isPassThrough()) {
  287.                             $categoryBrandingBannerList[] = $item;
  288.                         } else if ($item->isForCategories()) {
  289.                             foreach ($item->getCategories() as $brandingBannerCategory) {
  290.                                 if ($brandingBannerCategory->getID() == $categoryID || $currentCategory->isChildOfRecursive($brandingBannerCategory->getID())) {
  291.                                     $categoryBrandingBannerList[] = $item;
  292.                                     break;
  293.                                 }
  294.                             }
  295.                         }
  296.                     }
  297.                 }
  298.             }
  299.             if (!empty($categoryBrandingBannerList)) {
  300.                 $brandingBannerList $categoryBrandingBannerList;
  301.             } else {
  302.                 foreach ($categoryIDs as $categoryID) {
  303.                     $currentCategory $this->entityManager->getRepository(Category::class)->find($categoryID);
  304.                     if ($currentCategory) {
  305.                         foreach ($brandingBannerList as $key=>$item) {
  306.                             $removeCategoryFlag true;
  307.                             if ($item->isForCategories() && !$item->isPassThrough()) {
  308.                                 foreach ($item->getCategories() as $brandingBannerCategory) {
  309.                                     if (in_array($brandingBannerCategory->getID(), $categoryIDs) || $currentCategory->isChildOfRecursive($brandingBannerCategory->getID())) {
  310.                                         $removeCategoryFlag false;
  311.                                         break;
  312.                                     }
  313.                                 }
  314.                                 if ($removeCategoryFlag) {
  315.                                     unset($brandingBannerList[$key]);
  316.                                 }
  317.                             }
  318.                         }
  319.                     }
  320.                 }
  321.                 if (empty($categoryIDs)) {
  322.                     foreach ($brandingBannerList as $key=>$item) {
  323.                         if ($item->isForCategories() && !$item->isPassThrough()) {
  324.                             unset($brandingBannerList[$key]);
  325.                         }
  326.                     }
  327.                 }
  328.             }
  329.             $brandingBannerList array_values(array_unique($brandingBannerListSORT_REGULAR));
  330.             if (!$this->isMobileDevice()) {
  331.                 foreach ($brandingBannerList as $brandingBanner) {
  332.                     if (empty($currentBrandingBanner) or $breaker == true) {
  333.                         $currentBrandingBanner $brandingBanner;
  334.                     }
  335.                     if ($breaker) {
  336.                         break;
  337.                     }
  338.                     if ($brandingBanner->getBannerID() == $this->request->cookies->get('fullSiteBanner1')) {
  339.                         $breaker true;
  340.                     }
  341.                 }
  342.             } else {
  343.                 foreach ($brandingBannerList as $brandingBanner) {
  344.                     if (($brandingBanner->getMobileImage() || $brandingBanner->getMobileDivider()) && (empty($currentBrandingBanner) || $breaker == true)) {
  345.                         $currentBrandingBanner $brandingBanner;
  346.                     }
  347.                     if ($breaker) {
  348.                         break;
  349.                     }
  350.                     if ($brandingBanner->getBannerID() == $this->request->cookies->get('fullSiteBanner1')) {
  351.                         $breaker true;
  352.                     }
  353.                 }
  354.             }
  355.         }
  356.         if (self::isMobileDevice()) {
  357.             return empty($currentBrandingBanner) ? null $currentBrandingBanner;
  358.         }
  359.         if (empty($currentBrandingBanner)) {
  360.             return '';
  361.         } else {
  362.             if (is_array($currentBrandingBanner)) {
  363.                 $currentBrandingBanner $currentBrandingBanner[0];
  364.             }
  365.             return $twig->render('Slivki/banners/branding_banner.html.twig', ['brandingBanner' => $currentBrandingBanner]);
  366.         }
  367.     }
  368.     public function getNoticePopup(Environment $twig$user) {
  369.         $noticePopup '';
  370.         $directorPopupID null;
  371.         try {
  372.             /** @var User $user */
  373.             if (($user && $user->hasRole(UserGroup::ROLE_SUPPLIER_ID))) {
  374.                 if (!$user->hasRole(UserGroup::ROLE_DIRECTOR_A) && !$user->hasRole(UserGroup::ROLE_DIRECTOR_B)) {
  375.                     $softCache = new SoftCache('director');
  376.                     $lastDirectorGroup $softCache->get('last_director_group'0);
  377.                     $lastDirectorGroup++;
  378.                     if ($lastDirectorGroup 1) {
  379.                         $lastDirectorGroup 0;
  380.                     }
  381.                     $softCache->set('last_director_group'$lastDirectorGroup0);
  382.                     if ($lastDirectorGroup == 0) {
  383.                         $role $this->entityManager->getRepository(UserGroup::class)->find(UserGroup::ROLE_DIRECTOR_A);
  384.                         $user->addRole($role);
  385.                     } else {
  386.                         $role $this->entityManager->getRepository(UserGroup::class)->find(UserGroup::ROLE_DIRECTOR_B);
  387.                         $user->addRole($role);
  388.                     }
  389.                     $this->entityManager->flush();
  390.                 }
  391.                 if ($user->hasRole(UserGroup::ROLE_DIRECTOR_A)) {
  392.                     $directorPopupID NoticePopup::ID_DIRECTOR_A;
  393.                 } else {
  394.                     $directorPopupID NoticePopup::ID_DIRECTOR_B;
  395.                 }
  396.                 $noticePopup $this->getNoticePopupByID($twig$user$directorPopupID);
  397.             }
  398.             if ($noticePopup == '') {
  399.                 $noticePopup $this->getNoticePopupByID($twig$userNoticePopup::ID_USER);
  400.             }
  401.             if ($user && $user->getEmail() == 'volga@slivki.by') {
  402.                 $testPopups $this->entityManager->getRepository(NoticePopup::class)->findBy(['test' => true'type' => $directorPopupID]);
  403.                 if (isset($testPopups[0])) {
  404.                     $noticePopup $this->getNoticePopupByID($twig$user$testPopups[0]->getType());
  405.                 }
  406.             }
  407.         } catch (\Exception $e) {
  408.             Logger::instance('Notice popup error')->info($e->getMessage());
  409.             return '';
  410.         }
  411.         return $noticePopup;
  412.     }
  413.     private function getNoticePopupByID(Environment $twig$user$type) {
  414.         if ($this->isMobileDevice()) {
  415.             return '';
  416.         }
  417.         $dql 'select noticePopup from Slivki:NoticePopup noticePopup where noticePopup.active = true and noticePopup.type = :type and current_timestamp() between noticePopup.activeFrom and noticePopup.activeTill';
  418.         $noticePopupList $this->entityManager->createQuery($dql)->setParameter('type'$type)->getResult();
  419.         if (!$noticePopupList || count($noticePopupList) == 0) {
  420.             return '';
  421.         }
  422.         $noticePopup $noticePopupList[0];
  423.         if ($noticePopup->isTest() && $user && $user->getEmail() == 'volga@slivki.by') {
  424.             $noticePopupHtml $this->getNoticePopupHtmlView($twig$noticePopup);
  425.             return $noticePopupHtml == SoftCache::EMPTY_VALUE '' $noticePopupHtml;
  426.         }
  427.         if ($noticePopup) {
  428.             if ($this->isNoticePopupShown($noticePopup->getCookieName(), $user$noticePopup->getID())) {
  429.                 return '';
  430.             }
  431.         }
  432.         $noticePopupHtml $this->getNoticePopupHtmlView($twig$noticePopup);
  433.         return $noticePopupHtml == SoftCache::EMPTY_VALUE '' $noticePopupHtml;
  434.     }
  435.     private function getNoticePopupHtmlView(Environment $twig$noticePopup) {
  436.         $noticePopupID $noticePopup->getID();
  437.         $image $this->entityManager->getRepository(Media::class)
  438.             ->findOneBy(['entityID' => $noticePopupID'mediaType' => MediaType::TYPE_NOTICE_POPUP_IMAGE_ID], ['ID' => 'desc']);
  439.         $imageMobile $this->entityManager->getRepository(Media::class)
  440.             ->findOneBy(['entityID' => $noticePopupID'mediaType' => MediaType::TYPE_NOTICE_POPUP_IMAGE_ID_MOBILE], ['ID' => 'desc']);
  441.         return $twig->render('Slivki/popups/notice_popup.html.twig',
  442.             ['id'=> 'notice_popup''noticePopup' => $noticePopup'image' => $image'imageMobile' => $imageMobile]);
  443.     }
  444.     private function isNoticePopupShown($popupID$user$sessionKeySuffix) {
  445.         if (!$user) {
  446.             return false;
  447.         }
  448.         $session = new Session();
  449.         $sessionKey 'noticePopup' $sessionKeySuffix;
  450.         $noticePopupID $session->get($sessionKey);
  451.         if (!$noticePopupID) {
  452.             $popupView $this->entityManager->getRepository(NoticePopupView::class)->findBy(['popupID' => $popupID'userID' => $user->getID()]);
  453.             if (!$popupView) {
  454.                 $popupView = new NoticePopupView();
  455.                 $popupView->setCreatedOn(new \DateTime());
  456.                 $popupView->setPopupID($popupID);
  457.                 $popupView->setUserID($user->getID());
  458.                 $this->entityManager->persist($popupView);
  459.                 $this->entityManager->flush($popupView);
  460.                 return false;
  461.             }
  462.             $session->set($sessionKey$popupID);
  463.             return true;
  464.         }
  465.         if ($noticePopupID != $popupID) {
  466.             $session->set($sessionKey$popupID);
  467.             return false;
  468.         }
  469.         return true;
  470.     }
  471.     public function isMobileDevice() {
  472.         return CommonUtil::isMobileDevice($this->request);
  473.     }
  474.     public function getInfoPages($type) {
  475.         return $this->entityManager->getRepository(InfoPage::class)->getInfoPagesFromCache($type);
  476.     }
  477.     public function getTopSiteBanner($categoryIDs = [], $mobile$mobileCache false) {
  478.         return $this->bannerService->getHeadBannerCached($this->getCurrentCity()->getID(), $categoryIDs$mobile$mobileCache);
  479.     }
  480.     public function getCategoryBanner($categoryID) {
  481.         $categoryRepository $this->entityManager->getRepository(Category::class);
  482.         $category $categoryRepository->findCached($categoryID);
  483.         if (isset($category['category']) && $category['category'] instanceof Category) {
  484.             return $this->bannerService->getCategoryBannerCached($category['category'], self::isMobileDevice());
  485.         }
  486.         return '';
  487.     }
  488.     public function getGoogleBanner(Environment $twig) {
  489.         return $twig->render('Slivki/banners/head_banner_admixer.html.twig');
  490.     }
  491.     public function getCategoryTypeList() {
  492.         return $this->entityManager->getRepository(CategoryType::class)->findAll();
  493.     }
  494.     public function getLastComments() {
  495.         $dql 'select comment from Slivki:Comment comment where comment.hidden = false and comment.confirmedPhone = true order by comment.createdOn desc';
  496.         $commentQuery $this->entityManager->createQuery($dql);
  497.         $commentQuery->setMaxResults(3);
  498.         return $commentQuery->getResult();
  499.     }
  500.     public function getTopCityList() {
  501.         return $this->entityManager->getRepository(City::class)->findBy(['parent' => null], ['ID' => 'ASC']);
  502.     }
  503.     public function getCityList() {
  504.         return $this->entityManager->getRepository(City::class)->getCitiesSorted();
  505.     }
  506.     public function getCategoriesList($domainObjectID$cityID City::DEFAULT_CITY_ID) {
  507.         return $this->entityManager->getRepository(Category::class)->getCategoryTree($domainObjectID0$cityID);
  508.     }
  509.     public function getTopLevelCategories() {
  510.         $categoryRepository $this->entityManager->getRepository(Category::class);
  511.         return $categoryRepository->getTopLevelOfferCategories($this->request->getSession()->get(City::CITY_ID_SESSION_KEYCity::DEFAULT_CITY_ID));
  512.     }
  513.     public function getURL($action$entityID$withDomain false) {
  514.         $url "";
  515.         $seoRepository $this->entityManager->getRepository(Seo::class);
  516.         $seo $seoRepository->getByEntity($action$entityID);
  517.         if ($seo) {
  518.             $url $seo->getMainAlias();
  519.             if ($withDomain) {
  520.                 $url 'https://' $seo->getDomain() . '.slivki.by' $url;
  521.             }
  522.         }
  523.         return $url;
  524.     }
  525.     public function getCategoryURL(Category $category) {
  526.         return $this->entityManager->getRepository(Seo::class)->getCategoryURL($category);
  527.     }
  528.     public function getImageURL($media null$width$height) {
  529.         $imageUrl ImageService::FALLBACK_IMAGE;
  530.         if (!$media) {
  531.             return $imageUrl;
  532.         }
  533.         try {
  534.             $imageUrl $this->imageService->getImageURLCached($media$width$height);
  535.         } catch (Exception $exception) {
  536.             $logger Logger::instance('TwigExtension');
  537.             $logger->info('Media ID = ' $media->getID() . ', file = ' $media->getPath() . $media->getName() . ' not found in getImageURL!');
  538.         }
  539.         return $imageUrl;
  540.     }
  541.     public function getProfileImageURL($media$width$height) {
  542.         if (!$media) {
  543.             return ImageService::DEFAULT_AVATAR;
  544.         }
  545.         return $this->imageService->getImageURL($media$width$height);
  546.     }
  547.     public function getMetaInfo() {
  548.         $metaInfo $this->request->attributes->get(SiteController::PARAMETER_META_INFO);
  549.         if ($metaInfo) {
  550.             $metaInfo = array(
  551.                 "title" => $metaInfo->getTitle(),
  552.                 "metaTitle" => $metaInfo->getMetaTitle(),
  553.                 "metaDescription" => $metaInfo->getMetaDescription(),
  554.                 "metaKeywords" => $metaInfo->getMetaKeywords()
  555.             );
  556.         } else {
  557.             $metaInfo = array(
  558.                 "title" => '',
  559.                 "metaTitle" => "Скидки в Минске! Акции и распродажи на Slivki.by!",
  560.                 "metaDescription" => "Грандиозные скидки и акции в Минске: рестораны, салоны красоты, клубы, спорт, досуг... Лучшие цены в популярных заведениях и магазинах Минска на Slivki.by!",
  561.                 "metaKeywords" => "скидки, распродажи, рекламные акции, Минск, кредит, дисконтная карта, карточка, новогодние скидки, Сезонные Распродажи и скидки, праздничная распродажа, распродажа одежды, приз, подарок, сюрприз, сувенир, РБ, Республика Беларусь, единая дисконтная система Беларуси, выгода, товары и услуги выгодно, экономия, промо, Акция, магазин, успеть купить, Модная одежда, фирмы, компании, рестораны, Минск, сезон потребитель дешево качественно быстро удобно продавец Новый товар"
  562.             );
  563.         }
  564.         return $metaInfo;
  565.     }
  566.     public function getSidebar(Environment $environment$categoryID null): string
  567.     {
  568.         if (!$this->serverFeatureStateChecker->isServerFeatureEnabled(SwitcherFeatures::SALES())) {
  569.             return $environment->render('Slivki/uz/sidebar.html.twig');
  570.         }
  571.         $sidebarCached $this->sidebarCacheService->getSidebarCached();
  572.         if (null === $sidebarCached) {
  573.             return '';
  574.         }
  575.         return $sidebarCached->getFirstPage();
  576.     }
  577.     public function getBannerCodeFromFile($banner) {
  578.         $filePath realpath($this->kernel->getProjectDir() . '/public') . $banner->getCodeFilePath();
  579.         $fileContent = @file_get_contents($filePath);
  580.         return $fileContent;
  581.     }
  582.     /**
  583.      * @return \Slivki\Entity\SiteSettings
  584.      */
  585.     public function getSiteSettings() {
  586.         $softCache = new SoftCache("");
  587.         $cacheKey SiteSettingsRepository::CACHE_NAME;
  588.         $settingsCached $softCache->get($cacheKey);
  589.         if ($settingsCached) {
  590.             return $settingsCached;
  591.         }
  592.         $settingsCached $this->entityManager->getRepository(SiteSettings::class)->findAll();
  593.         $settingsCached $settingsCached[0];
  594.         $softCache->set($cacheKey$settingsCached60 60);
  595.         return $settingsCached;
  596.     }
  597.     public function staticCall($function$arguments = []) {
  598.         return call_user_func($function$arguments);
  599.     }
  600.     public function getStatVisitCount($entityID$entityType$dateFrom$dateTo) {
  601.         $entityManager $this->entityManager;
  602.         switch ($entityType) {
  603.             case Visit::TYPE_MALL_ALL_PAGES:
  604.                 $sql "select sum(visit_count) from stat_visit_count_aggregated where visit_date >= '$dateFrom' and visit_date <= '$dateTo' and entity_type_id in (".Visit::TYPE_MALL_MAIN_PAGE.",".Visit::TYPE_MALL_DETAILS.",".Visit::TYPE_MALL_BRAND.")";
  605.                 break;
  606.             case Visit::TYPE_SLIVKI_TV_ALL:
  607.                 $sql "select sum(visit_count) from stat_visit_count_aggregated where visit_date >= '$dateFrom' and visit_date <= '$dateTo' and entity_type_id in (".Visit::TYPE_SLIVKI_TV_GUIDES.")";
  608.                 break;
  609.             case Visit::TYPE_FLIER_ALL:
  610.                 $sql "select sum(visit_count) from stat_visit_count_aggregated where visit_date >= '$dateFrom' and visit_date <= '$dateTo' and entity_type_id in (".Visit::TYPE_FLIER_DETAILS.")";
  611.                 break;
  612.             case Visit::TYPE_OFFERS_ALL:
  613.                 $sql "select sum(visit_count) from stat_visit_count_aggregated where visit_date >= '$dateFrom' and visit_date <= '$dateTo' and entity_type_id in (".Visit::TYPE_OFFER.")";
  614.                 break;
  615.             case Visit::TYPE_OFFER_CATEGORIES_ALL:
  616.                 $sql "select sum(visit_count) from stat_visit_count_aggregated where visit_date >= '$dateFrom' and visit_date <= '$dateTo' and entity_type_id in (".Visit::TYPE_OFFER_CATEGORY.")";
  617.                 break;
  618.             case Visit::TYPE_SALE_ALL:
  619.                 $sql "select sum(visit_count) from stat_visit_count_aggregated where visit_date >= '$dateFrom' and visit_date <= '$dateTo' and entity_type_id in (".Visit::TYPE_SALE.")";
  620.                 break;
  621.             case Visit::TYPE_SALE_CATEGORIES_ALL: {
  622.                 $sql "select sum(visit_count) from stat_visit_count_aggregated where visit_date >= '$dateFrom' and visit_date <= '$dateTo' and entity_type_id in (".Visit::TYPE_SALE_CATEGORY.")";
  623.                 break;
  624.             }
  625.             case Visit::TYPE_OFFER_BY_CATEGORY:
  626.                 $sql "select sum(visit_count) from stat_visit_count_aggregated where visit_date >= '$dateFrom' and visit_date <= '$dateTo' and entity_type_id in (".Visit::TYPE_OFFER.") and entity_id in (select entity_id from category2entity where category_id = ".$entityID.")";
  627.                 break;
  628.             case Visit::TYPE_OFFER_BY_CATEGORY_REF:
  629.                 $sql "select sum(visit_count_ref) from stat_visit_count_aggregated where visit_date >= '$dateFrom' and visit_date <= '$dateTo' and entity_type_id in (".Visit::TYPE_OFFER.") and entity_id in (select entity_id from category2entity where category_id = ".$entityID.")";
  630.                 break;
  631.             case Visit::TYPE_FLIER_CATEGORIES_ALL: {
  632.                 $sql "select sum(visit_count) from stat_visit_count_aggregated where visit_date >= '$dateFrom' and visit_date <= '$dateTo' and entity_type_id in (".Visit::TYPE_FLIER_CATEGORY.")";
  633.                 break;
  634.             }
  635.             case Visit::TYPE_SLIVKI_TV_CATEGORIES_ALL: {
  636.                 $sql "select sum(visit_count) from stat_visit_count_aggregated where visit_date >= '$dateFrom' and visit_date <= '$dateTo' and entity_type_id in (".Visit::TYPE_SLIVKI_TV_CATEGORIES_ALL.")";
  637.                 break;
  638.             }
  639.             default:
  640.                 $sql "select sum(visit_count) from stat_visit_count_aggregated where visit_date >= '$dateFrom' and visit_date <= '$dateTo' and entity_id = $entityID and entity_type_id = $entityType";
  641.                 break;
  642.         }
  643.         $count $entityManager->getConnection()->executeQuery($sql)->fetchColumn();
  644.         return $count $count 0;
  645.     }
  646.     public function getVisitCount($id$type$increment true) {
  647.         return $this->entityManager->getRepository(Visit::class)->getVisitCount($id$type$increment);
  648.     }
  649.     public function getOfferVisitCount($offer$today false) {
  650.         if ($today) {
  651.             return $this->entityManager->getRepository(Offer::class)->getVisitCount($offertrue);
  652.         }
  653.         return $this->entityManager->getRepository(Visit::class)->getVisitCount($offer->getID(), Visit::TYPE_OFFER30);
  654.     }
  655.     public function getOfferConversion($offerID) {
  656.         $entityManager $this->entityManager;
  657.         $visitRepository $entityManager->getRepository(Visit::class);
  658.         $purchaseCountRepository $entityManager->getRepository(PurchaseCount::class);
  659.         $visitCount $visitRepository->getVisitCount($offerIDVisit::TYPE_OFFER30);
  660.         $purchaseCount $purchaseCountRepository->findOneBy(['entityID' => $offerID]);
  661.         if (!$visitCount || !$purchaseCount || !$purchaseCount->getPurchaseCountLastMonthWithCorrection()) {
  662.             return 0;
  663.         }
  664.         return ceil(100 * ($purchaseCount->getPurchaseCountLastMonthWithCorrection() / $visitCount));
  665.     }
  666.     public function getSaleVisitCount($saleID$daysCount 30$reload false) { //TODO: Use one function for all types
  667.         return $this->entityManager->getRepository(Visit::class)->getVisitCount($saleIDCategory::SALE_CATEGORY_ID$daysCount$reload);
  668.     }
  669.     public function getVideoGuideVisitCount($saleID) {
  670.         return $this->entityManager->getRepository(VisitCounter::class)->getVisitCount($saleIDVisitCounter::TYPE_SALEfalse);
  671.     }
  672.     public function getOfferMonthlyPurchaseCount(int $offerId): int
  673.     {
  674.         return $this->purchaseCountDao->getLastMonthWithCorrectionByOfferId($offerId);
  675.     }
  676.     public function getBankCurrencyList() {
  677.         return $this->entityManager->getRepository(BankCurrency::class)->findBy([], ['ID' => 'ASC']);
  678.     }
  679.     public function getCategoryBreadcrumbs(Category $category) {
  680.         return $this->entityManager->getRepository(Category::class)->getCategoryBreadcrumbs($category);
  681.     }
  682.     public function getCommentEntityByType($entityID$typeID) {
  683.         return $this->entityManager->getRepository(Comment::class)->getCommentEntity($entityID$typeID);
  684.     }
  685.     public function getCommentsCountByUserID($userID$entityID$typeID) {
  686.         return $this->entityManager->getRepository(Comment::class)->getCommentsCountByUserID($userID$entityID$typeID);
  687.     }
  688.     public function getMainMenu(Environment $twig$showStatistics$oldTemplate true) { //TODO: Pass all data to view directly
  689.         $mobileDevice $this->isMobileDevice();
  690.         $cityID $this->request->getSession()->get(City::CITY_ID_SESSION_KEYCity::DEFAULT_CITY_ID);
  691.         $type null;
  692.         if ($showStatistics) {
  693.             $type TextCacheService::MAIN_MENU_STATISTICS_TYPE;
  694.         } else  {
  695.             $type $mobileDevice TextCacheService::MAIN_MENU_MOBILE_TYPE TextCacheService::MAIN_MENU_TYPE;
  696.         }
  697.         if ($mobileDevice && $oldTemplate) {
  698.             $type TextCacheService::MAIN_MENU_OLD_MOBILE_TYPE;
  699.         }
  700.         $textCacheService $this->textCacheService;
  701.         $mainMenu $textCacheService->getText($cityID$typetrue);
  702.         if ($mainMenu) {
  703.             if (!$mobileDevice) {
  704.                 $mainMenuBanner '';
  705.                 $mainMenuBanners $this->bannerService->getMainMenuBannerCached();
  706.                 if ($mainMenuBanners) {
  707.                     $mainMenuBannersCount count($mainMenuBanners);
  708.                     $currentMainMenuBannerIndex $this->request->cookies->get('mainMenuBanner', -1);
  709.                     if ($currentMainMenuBannerIndex == $mainMenuBannersCount 1) {
  710.                         $currentMainMenuBannerIndex 0;
  711.                     } else {
  712.                         $currentMainMenuBannerIndex++;
  713.                     }
  714.                     if (isset($mainMenuBanners[$currentMainMenuBannerIndex])) {
  715.                         $mainMenuBanner $mainMenuBanners[$currentMainMenuBannerIndex];
  716.                     }
  717.                 }
  718.                 $mainMenu[3] = str_replace('||mainMenuBannerPlaceholder||'$mainMenuBanner$mainMenu[3]);
  719.             }
  720.             return $mainMenu[3];
  721.         }
  722.         return '';
  723.     }
  724.     public function getCommentsMenuItems() {
  725.         return $this->entityManager->getRepository(Comment::class)->getTopMenu();
  726.     }
  727.     public function getActiveSubCategories($categoryID) {
  728.         $city $this->getCurrentCity();
  729.         return $this->entityManager->getRepository(Category::class)->getActiveCategories(
  730.             $categoryID, [Category::DEFAULT_CATEGORY_TYPECategory::SERVICE_CATEGORY_TYPE], Category::OFFER_CATEGORY_ID$city->getID());
  731.     }
  732.     public function getTestMenuItem($itemID)
  733.     {
  734.         $keySuffix self::isMobileDevice() ? 'Mobile' '';
  735.         switch ($itemID) {
  736.             case 0:
  737.                 if (!self::$photoGuideMenuItem) {
  738.                     $url $this->getURL(SeoRepository::RESOURCE_URL_SALE_CATEGORYCategory::PHOTOGUIDE_SALE_CATEGORY_ID);
  739.                     self::$photoGuideMenuItem = ['name' => 'Фотогиды''url' => $url];
  740.                 }
  741.                 return self::$photoGuideMenuItem;
  742.             case 1:
  743.                 return ['name' => 'Новости скидок''url' => '/skidki-i-rasprodazhi'];
  744.             case 2:
  745.                 return ['name' => 'e-Товары''abKey' => 'e-tovary' $keySuffix];
  746.         }
  747.         return null;
  748.     }
  749.     public function getActiveSalesCount() {
  750.         return $this->entityManager->getRepository(Sale::class)->getActiveSalesCountCached();
  751.     }
  752.     public function getActiveOffersCount($cityID City::DEFAULT_CITY_ID) {
  753.         return $this->entityManager->getRepository(Offer::class)->getActiveOffersCountCached($cityID);
  754.     }
  755.     public function getPartnerLogoURL($partnerID) {
  756.         if ($this->partnerLogoURL) {
  757.             //return $this->partnerLogoURL;
  758.         }
  759.         $media $this->entityManager->getRepository(Media::class)->getMedia($partnerIDMediaType::TYPE_PARTNER_LOGO_ID);
  760.         if ($media) {
  761.             $this->partnerLogoURL $this->imageService->getImageURLCached($media[0], 860);
  762.         } else {
  763.             $this->partnerLogoURL ImageService::FALLBACK_IMAGE;;
  764.         }
  765.         return $this->partnerLogoURL;
  766.     }
  767.     /**
  768.      * Detect & return the ending for the plural word
  769.      *
  770.      * @param  integer $endings  nouns or endings words for (1, 4, 5)
  771.      * @param  array   $number   number rows to ending determine
  772.      *
  773.      * @return string
  774.      *
  775.      * @example:
  776.      * {{ ['Остался %d час', 'Осталось %d часа', 'Осталось %d часов']|plural(11) }}
  777.      * {{ count }} стат{{ ['ья','ьи','ей']|plural(count)
  778.      */
  779.     function pluralFilter($endings$number) {
  780.         return CommonUtil::plural($endings$number);
  781.     }
  782.     function pregReplaceFilter($str$pattern$replacement) {
  783.         return preg_replace($pattern$replacement$str);
  784.     }
  785.     public function localizeDateFilter(DateTimeInterface $dateTime$format$locale 'ru_Ru'): string
  786.     {
  787.         return (new IntlDateFormatter(
  788.             $locale,
  789.             IntlDateFormatter::NONE,
  790.             IntlDateFormatter::NONE,
  791.             date_default_timezone_get(),
  792.             IntlDateFormatter::GREGORIAN,
  793.             $format
  794.         ))->format($dateTime);
  795.     }
  796.     public function localizeDateTimestampFilter(string $timestampstring $formatstring $locale 'ru_Ru'): string
  797.     {
  798.         return (new \IntlDateFormatter(
  799.             $locale,
  800.             \IntlDateFormatter::NONE,
  801.             \IntlDateFormatter::NONE,
  802.             date_default_timezone_get(),
  803.             \IntlDateFormatter::GREGORIAN,
  804.             $format
  805.         ))->format((new \DateTimeImmutable())->setTimestamp($timestamp));
  806.     }
  807.     function phoneFilter($number) {
  808.         if ($number != (int)$number || strlen((string)$number) != 12) {
  809.             return $number;
  810.         }
  811.         return substr($number,5,3) . ' ' .  substr($number,8,2) . ' '
  812.             substr($number,10,2);
  813.     }
  814.     function jsonDecodeFilter($json) {
  815.         return json_decode($json);
  816.     }
  817.     /**
  818.      * @param $var
  819.      * @param $instance
  820.      * @return bool
  821.      */
  822.     public function isInstanceof($var$instance) {
  823.         return  $var instanceof $instance;
  824.     }
  825.     public function isObject($var) {
  826.         return is_object($var);
  827.     }
  828.     public function getName() {
  829.         return "slivki_extension";
  830.     }
  831.     public function getSaleShortDescription(Sale $sale) {
  832.         $saleDescriptions $sale->getDescriptions();
  833.         if (!$saleDescriptions || $saleDescriptions->count() == 0) {
  834.             return '';
  835.         }
  836.         $description $sale->getDescriptions()->first()->getDescription();
  837.         $crawler = new Crawler();
  838.         $crawler->addHtmlContent($description);
  839.         $pList $crawler->filter('p');
  840.         $i 0;
  841.         $shortDescription '';
  842.         foreach ($pList as $domElement) {
  843.             $p htmlentities($domElement->textContentnull'utf-8');
  844.             $p trim(str_replace("&nbsp;"" "$p));
  845.             $p html_entity_decode($p);
  846.             if (strlen($p) > 0) {
  847.                 $i++;
  848.                 if($i == 2) {
  849.                     $shortDescription $p;
  850.                     break;
  851.                 }
  852.             }
  853.         }
  854.         $shortDescription strip_tags($shortDescription);
  855.         return $shortDescription;
  856.     }
  857.     public function getSupplierOfferPhotoBlockByOfferID(Environment $twig$offerID) {
  858.         $perPage 20;
  859.         $mediaList $this->cacheService->getMediaList($offerID,OfferSupplierPhotoMedia::TYPE00$perPage);
  860.         if (empty($mediaList)) {
  861.             return '';
  862.         }
  863.         $data = [
  864.             'offerID' => $offerID,
  865.             'supplierOfferPhotoList' => $mediaList
  866.         ];
  867.         $data['supplierOfferPhotoList'] = array_slice($data['supplierOfferPhotoList'], 020);
  868.         return $twig->render('Slivki/comments/offer_supplier_photo_block.html.twig'$data);
  869.     }
  870.     public function getUserCommentsMediaBlockByEntityID(Environment $twig$entityID$entityType) {
  871.         $data['commentAndMediaList'] = [];
  872.         switch ($entityType) {
  873.             case 'category':
  874.                 $data['commentAndMediaList'] = $this->entityManager->getRepository(Media::class)->getOfferCommentMediaListByCategoryID($entityID);
  875.                 break;
  876.             case 'offer':
  877.                 $data['commentAndMediaList'] = $this->entityManager->getRepository(Media::class)->getOfferCommentMediaListByOfferID($entityID);
  878.                 break;
  879.             case 'all':
  880.                 $data['commentAndMediaList'] = $this->entityManager->getRepository(Media::class)->getOfferCommentMediaList();
  881.                 break;
  882.         }
  883.         $data['entityID'] = $entityID;
  884.         $data['entityType'] = $entityType;
  885.         if(empty($data['commentAndMediaList'])) {
  886.             return '';
  887.         }
  888.         $html $twig->render('Slivki/comments/media_block.html.twig'$data);
  889.         return $html;
  890.     }
  891.     public function getEntityRatingWithCount($entityType$entityID$dateFrom false$dateTo false) {
  892.         return $this->entityManager->getRepository(Comment::class)->getEntityRatingWithCount($entityType$entityID$dateFrom$dateTo);
  893.     }
  894.     public function getCompaniesRatingBlock(Environment $twig$categoryID$isMobile false) {
  895.         $type $isMobile TextCacheService::COMPANIES_RATING_MOBILE_TYPE TextCacheService::COMPANIES_RATING_TYPE;
  896.         $html $this->textCacheService->getText($categoryID$type);
  897.         if (!$html || $html == '') { //TODO: remove
  898.             $softCache = new SoftCache(OfferRepository::CACHE_NAME);
  899.             $mobileCacheName $isMobile 'mobile-' '';
  900.             $html $softCache->get('company-rating-data-' '-' $mobileCacheName $categoryID);
  901.         }
  902.         return $html $html '';
  903.     }
  904.     public function getMailingCampaignEntityPositionByEntityID($mailingCampaignID$entityID$entityType) {
  905.         $mailingCampaign $this->entityManager->getRepository(MailingCampaign::class)->find($mailingCampaignID);
  906.         return $mailingCampaign->getEntityPositionByEntityID($entityID$entityType);
  907.     }
  908.     public function getActiveCityList() {
  909.         return $this->entityManager->getRepository(City::class)->getActiveCitiesCached();
  910.     }
  911.     public function getActiveSortedCityList() {
  912.         return $this->entityManager->getRepository(City::class)->getActiveSortedCitiesCached();
  913.     }
  914.     public function getCurrentCity() {
  915.         return $this->entityManager->getRepository(City::class)->findCached($this->request->getSession()->get(City::CITY_ID_SESSION_KEYCity::DEFAULT_CITY_ID));
  916.     }
  917.     public function setSeenMicrophoneTooltip(User $user) {
  918.         if (!$user->isSeenMicrophoneTooltip()) {
  919.             $user $this->entityManager->merge($user);
  920.             $user->setSeenMicrophoneTooltip();
  921.             $this->entityManager->flush($user);
  922.         }
  923.     }
  924.     public function getFlierProductCategories(Environment $twig) {
  925.         $dql "select category from Slivki:ProductCategory category where category.parents is empty order by category.name ASC";
  926.         $categories $this->entityManager->createQuery($dql)->getResult();
  927.         return $twig->render('Slivki/admin/sales/products/category_list.html.twig', ['categories' => $categories]);
  928.     }
  929.     public function getFlierProductSubCategories(Environment $twig$categoryID) {
  930.         $categories $this->entityManager->getRepository(ProductCategory::class)->find($categoryID);
  931.         $subCategories $categories->getSubCategories();
  932.         return  $twig->render('Slivki/admin/sales/products/sub_category_list.html.twig', ['categories' => $subCategories]);
  933.     }
  934.     public function getIPLocationData() {
  935.         $defaultLocation = [53.90225027.561889];
  936.         return $defaultLocation;
  937.         $data $this->entityManager->getRepository(City::class)->getIPLocationData($this->request);
  938.         if (!$data) {
  939.             return $defaultLocation;
  940.         }
  941.         return [$data['latitude'], $data['longitude']];
  942.     }
  943.     public function isInDefaultCity() {
  944.         return City::DEFAULT_CITY_ID == $this->entityManager->getRepository(City::class)->getCityIDByGeoIP($this->request);
  945.     }
  946.     public function isTireDirector($userID) {
  947.         return $this->entityManager->getRepository(Director::class)->isTireDirector($userID);
  948.     }
  949.     public function getCurrentCityURL() {
  950.         $cityID $this->request->getSession()->get(City::CITY_ID_SESSION_KEYCity::DEFAULT_CITY_ID);
  951.         if ($cityID == City::DEFAULT_CITY_ID) {
  952.             return '/';
  953.         }
  954.         return $this->entityManager->getRepository(Seo::class)->getCityURL($cityID);
  955.     }
  956.     public function showMyPromocodesMenuItem(User $user) {
  957.         $userRepository $this->entityManager->getRepository(User::class);
  958.         $lastBuyDate $userRepository->getLastBuyDate($user);
  959.         if (!$lastBuyDate) {
  960.             return false;
  961.         }
  962.         return time() - $lastBuyDate->format('U') < 30 24 3600;
  963.     }
  964.     public function getFooter(Environment $twig): string
  965.     {
  966.         $mobile $this->isMobileDevice();
  967.         $footerVersion rand(01);
  968.         $cacheKey 'footer-2-' $this->getCurrentCity()->getID() . '-'  . ($mobile '-mobile' '') . '-' $footerVersion;
  969.         $softCache = new SoftCache('');
  970.         $footer $softCache->getDataWithLock($cacheKey);
  971.         if (!$footer) {
  972.             $view sprintf(
  973.                 'Slivki%s/footer%s.html.twig',
  974.                 $this->parameterBag->get('regional_template_path'),
  975.                 $mobile '_mobile' '',
  976.             );
  977.             $footer $twig->render($view, ['footerVersion' => $footerVersion]);
  978.             $data = ['data' => $footer'expDate' => time() + 60 60];
  979.             $softCache->set($cacheKey$data0);
  980.         }
  981.         return $footer;
  982.     }
  983.     public function getSaleCategoriesSortedBySaleVisits() {
  984.         return $this->entityManager->getRepository(Category::class)->getSaleCategoriesSortedBySaleVisits();
  985.     }
  986.     public function addLazyAndLightboxImagesInDescription($description) {
  987.         if (trim($description) == '') {
  988.             return '';
  989.         }
  990.         $html = new Crawler();
  991.         $html->addHtmlContent($description);
  992.         $nodeList $html->filter('img');
  993.         if (!empty($nodeList)) {
  994.             $nodeList->each(function (Crawler $node) {
  995.                 $nodeElem $node->getNode(0);
  996.                 $source $nodeElem->getAttribute('src');
  997.                 $dataOriginal $nodeElem->getAttribute('data-original');
  998.                 if ($source and !$dataOriginal) {
  999.                     $nodeElem->setAttribute('src''/common-img/d.gif');
  1000.                     $nodeElem->setAttribute('data-original'$source);
  1001.                     $nodeElem->setAttribute('class''sale-lazy-spin');
  1002.                     $parentElem $node->parents()->first()->getNode(0);
  1003.                     $ratio $nodeElem->getAttribute('data-ratio');
  1004.                     if ($ratio != '') {
  1005.                         $newParentNode = new \DOMElement('div');
  1006.                         $parentElem->replaceChild($newParentNode$nodeElem);
  1007.                         $newParentNode->setAttribute('class''sale-lazy-wrap');
  1008.                         $width $nodeElem->getAttribute('width');
  1009.                         $style $nodeElem->getAttribute('style');
  1010.                         $newParentNode->setAttribute('style''max-width:' $width'px;' $style);
  1011.                         $nodeForPadding =  new \DOMElement('div');
  1012.                         $newParentNode->appendChild($nodeForPadding);
  1013.                         $nodeForPadding->setAttribute('style''padding-bottom:' $ratio'%');
  1014.                         $newParentNode->appendChild($nodeElem);
  1015.                     }
  1016.                 }
  1017.             });
  1018.         }
  1019.         if (self::isMobileDevice()) {
  1020.             $nodeList $html->filter('iframe');
  1021.             if (!empty($nodeList)) {
  1022.                 $nodeList->each(function (Crawler $node) {
  1023.                     $nodeElem $node->getNode(0);
  1024.                     $source $nodeElem->getAttribute('src');
  1025.                     if (strpos($source'youtube') !== false) {
  1026.                         $parentElem $node->parents()->first()->getNode(0);
  1027.                         $newParentNode = new \DOMElement('div');
  1028.                         $parentElem->replaceChild($newParentNode$nodeElem);
  1029.                         $newParentNode->setAttribute('class''embed-responsive embed-responsive-16by9');
  1030.                         $nodeElem->setAttribute('class''embed-responsive-item');
  1031.                         $newParentNode->appendChild($nodeElem);
  1032.                     }
  1033.                 });
  1034.             }
  1035.         }
  1036.         $result str_replace('<body>'''$html->html());
  1037.         $result str_replace('</body>'''$result);
  1038.         return $result;
  1039.     }
  1040.     public function getMedia($entityID$type) {
  1041.         $mediaList $this->entityManager->getRepository(Media::class)->getMedia($entityID$type);
  1042.         return $mediaList $mediaList[0] : null;
  1043.     }
  1044.     public function logWrite($data) {
  1045.         Logger::instance('TWIG LOG WRITER')->info(print_r($datatrue));
  1046.     }
  1047.     public function getManagerPhoneNumber($offset 0) {
  1048.         switch ($this->getCurrentCity()->getID()) {
  1049.             case 5:
  1050.                 return '+375 29 380 03 33';
  1051.             case 2:
  1052.                 return '+375 29 678 53 32';
  1053.             default:
  1054.                 return '+375 29 508 44 44';
  1055.         }
  1056.     }
  1057.     public function calcDeliveryPriceOffer(
  1058.         $extension,
  1059.         $pickupDeliveryType,
  1060.         $regularPrice,
  1061.         $priceOffer,
  1062.         ?OfferExtensionVariant $extensionVariant
  1063.     )
  1064.     {
  1065.         return PriceDeliveryType::calcDeliveryPickupPrice(
  1066.             $extension,
  1067.             $pickupDeliveryType,
  1068.             $regularPrice,
  1069.             $priceOffer,
  1070.             $extensionVariant
  1071.         );
  1072.     }
  1073.     public function getSocialProviderLoginUrl($socialNetwork$goto) {
  1074.         $className 'Slivki\Util\OAuth2Client\Provider\\' ucfirst($socialNetwork) . 'Client';
  1075.         /** @var AbstractOAuth2Client $oAuthProvider */
  1076.         $oAuthProvider = new $className();
  1077.         return $oAuthProvider->getLoginUrl($goto);
  1078.     }
  1079.     public function isProductFastDelivery($director): bool
  1080.     {
  1081.         if (null === $director) {
  1082.             return false;
  1083.         }
  1084.         $offers $director->getOffers();
  1085.         /** @var ProductFastDeliveryRepository $deliveryFastRepository */
  1086.         $deliveryFastRepository $this->entityManager->getRepository(ProductFastDelivery::class);
  1087.         /** @var Offer $offerItem */
  1088.         foreach ($offers as $offerItem) {
  1089.             if ($offerItem->isActive()) {
  1090.                 $times $deliveryFastRepository->getFastDeliveryProductsByOffer($offerItem);
  1091.                 if ($times) {
  1092.                     return true;
  1093.                 }
  1094.             }
  1095.         }
  1096.         return false;
  1097.     }
  1098.     public function calcDishDiscount($regularPrice$offerPrice) {
  1099.         $offerPrice = (float)$offerPrice;
  1100.         $regularPrice = (float)$regularPrice;
  1101.         if ($regularPrice == 0) {
  1102.             return 0;
  1103.         }
  1104.         return \round(100 - ($offerPrice $regularPrice 100));
  1105.     }
  1106.     public function getRTBHouseUID(User $user null) {
  1107.         return $this->RTBHouseService->getUID($user);
  1108.     }
  1109.     public function getVimeoEmbedPreview($videoId)
  1110.     {
  1111.         $config $this->videoConfigService->config($videoId);
  1112.         if (isset($config['video']['thumbs'])
  1113.             && \is_array($config['video']['thumbs'])
  1114.             && \count($config['video']['thumbs']) > 0
  1115.         ) {
  1116.             return \reset($config['video']['thumbs']);
  1117.         }
  1118.         return '';
  1119.     }
  1120.     public function getUserBalanceCodesCount(User $user$cityID) {
  1121.         return $this->entityManager->getRepository(User::class)->getUserBalanceCodesCount($user$cityID);
  1122.     }
  1123.     public function showAppInviteModal(User $user null) : bool {
  1124.         if (!$user) {
  1125.             return true;
  1126.         }
  1127.         $sql 'select max(created_on) from offer_order'
  1128.             .' where status > 0 and device_type = ' SiteController::DEVICE_TYPE_MOBILE_APP
  1129.             ' and user_id = ' $user->getID();
  1130.         $userLastAppPurchaseDate $this->entityManager->getConnection()->executeQuery($sql)->fetchColumn();
  1131.         if (!$userLastAppPurchaseDate) {
  1132.             return true;
  1133.         }
  1134.         return (new \DateTime($userLastAppPurchaseDate) < (new \DateTime())->modify('-1 month'));
  1135.     }
  1136. }