src/Twig/SlivkiTwigExtension.php line 1039

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