src/Twig/SlivkiTwigExtension.php line 246

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