- <?php
- namespace Slivki\Controller;
- use Psr\Container\ContainerInterface;
- use Slivki\Entity\AuthToken;
- use Slivki\Entity\Banner;
- use Slivki\Entity\Category;
- use Slivki\Entity\City;
- use Slivki\Entity\Comment;
- use Slivki\Entity\FoodOfferOptionExtension;
- use Slivki\Entity\FoodOrder;
- use Slivki\Entity\GeoLocation;
- use Slivki\Entity\GiftCertificate;
- use Slivki\Entity\GiftCertificateOrder;
- use Slivki\Entity\HotFeed;
- use Slivki\Entity\Media;
- use Slivki\Entity\Media\OfferExtensionMedia;
- use Slivki\Entity\Offer;
- use Slivki\Entity\OfferOrder;
- use Slivki\Entity\OfferOrderDetails;
- use Slivki\Entity\Partner;
- use Slivki\Entity\PartnerOffer;
- use Slivki\Entity\Sale;
- use Slivki\Entity\Seo;
- use Slivki\Entity\SiteSettings;
- use Slivki\Entity\User;
- use Slivki\Entity\UserActivity;
- use Slivki\Entity\UserBalanceActivityType;
- use Slivki\Entity\UserConfirmation;
- use Slivki\Entity\UserGroup;
- use Slivki\Entity\Visit;
- use Slivki\Repository\CategoryRepository;
- use Slivki\Repository\OfferRepository;
- use Slivki\Repository\SeoRepository;
- use Slivki\Services\BannerService;
- use Slivki\Services\Comment\CommentCacheService;
- use Slivki\Services\ImageService;
- use Slivki\Services\Mailer;
- use Slivki\Services\Offer\CustomProductOfferSorter;
- use Slivki\Services\Offer\OfferCacheService;
- use Slivki\Services\QRCodeGenerator\Generators\SosediBarcodeGenerator;
- use Slivki\Services\Sale\SaleCacheService;
- use Slivki\Util\Iiko\AbstractDelivery;
- use Slivki\Util\Logger;
- use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
- use Symfony\Bundle\FrameworkBundle\Controller\Controller;
- use Symfony\Component\Filesystem\Filesystem;
- use Symfony\Component\HttpFoundation\Request;
- use Symfony\Component\HttpFoundation\Response;
- use Symfony\Component\HttpFoundation\Cookie;
- use Symfony\Component\HttpFoundation\Session\Session;
- use Symfony\Component\HttpKernel\KernelInterface;
- use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
- use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
- use Slivki\Util\SoftCache;
- use Slivki\Util\CommonUtil;
- use Slivki\Repository\CommentRepository;
- use Mpdf\Config\ConfigVariables;
- use Mpdf\Config\FontVariables;
- use Mpdf\Mpdf;
- class SiteController extends AbstractController {
-     const UTM_SOURCE_COOKIE_NAME = 'utmSource';
-     const PARAMETER_MOBILE_DEVICE = "mobileDevice";
-     const PARAMETER_META_INFO = "slivkiMetaInfo";
-     const USER_TOKEN_COOKIE ='visitedoffers4';
-     const SHOW_INFO_DIALOG_PARAMETER = 'showInfoPopup';
-     const DEVICE_TYPE_DESKTOP = 0;
-     const DEVICE_TYPE_MOBILE = 1;
-     const DEVICE_TYPE_MOBILE_APP = 2;
-     const DEVICE_TYPE_FOOD_COURT = 3;
-     const LAST_OFFER_RATE_ACTIVITY_PARAMETER_NAME = 'lastOfferRateActivity';
-     const TARANTOOL_CATEGORY_BOX = true;
-     public function __construct(KernelInterface $kernel) {
-         $this->setUtmSourceCookie();
-         $this->kernel = $kernel;
-     }
-     public function setContainer(ContainerInterface $container): ?ContainerInterface {
-         $previous = parent::setContainer($container);
-         if ($container) {
-             $user = $this->getUser();
-             if ($user && !$user->isAccountNonLocked()) {
-                 $user->setToken('');
-                 $this->getDoctrine()->getManager()->flush($user);
-                 $this->get('security.token_storage')->setToken(null);
-                 $this->get('request_stack')->getCurrentRequest()->getSession()->invalidate();
-             }
-         }
-         return $previous;
-     }
-     private function setUtmSourceCookie() {
-         $request = Request::createFromGlobals();
-         $utmSource = $request->query->get('utm_source');
-         $referer = $request->headers->get('referer');
-         $response = new Response();
-         if ($utmSource && $referer && parse_url($referer)['host'] != $request->getHost()) {
-             $cookie = [
-                 'utmSource' => $utmSource,
-                 'utm_medium' => $request->query->get('utm_medium'),
-                 'utm_campaign' => $request->query->get('utm_campaign'),
-                 'utm_term' => $request->query->get('utm_term'),
-                 'utm_content' => $request->query->get('utm_content'),
-                 'ref_code' => $request->query->get('ref_code'),
-                 'time' => time(),
-             ];
-             $expire = $utmSource == 'rtbhouse' ? 60*60*24*30 : 604800;
-             $cookie = Cookie::create(self::UTM_SOURCE_COOKIE_NAME, serialize($cookie),  $expire + time());
-             $response->headers->setCookie($cookie);
-             $response->sendHeaders();
-         }
-     }
-     protected function getUtmSourceCookie(Request $request) {
-         $cookie = $request->cookies->get(self::UTM_SOURCE_COOKIE_NAME);
-         if (!$cookie) {
-             return false;
-         }
-         $result = unserialize($cookie);
-         if (count($result) < 2) {
-             return false;
-         }
-         $result['period'] = round((time() - $result['time']) / 86400);
-         return $result;
-     }
-     protected function getUtmSourceArray(Request $request) {
-         return [
-             'utm_source' => $request->query->get('utm_source', ''),
-             'utm_medium' => $request->query->get('utm_medium', ''),
-             'utm_campaign' => $request->query->get('utm_campaign', ''),
-             'utm_term' => $request->query->get('utm_term', ''),
-             'utm_content' => $request->query->get('utm_content', '')
-         ];
-     }
-     protected function getUtmDataFromReferer($referer) {
-         $query = parse_url($referer, PHP_URL_QUERY);
-         if ($query) {
-             $utmArray = [];
-             $parameters = explode('&', $query);
-             foreach ($parameters as $parameter) {
-                 if (CommonUtil::isBeginsWith($parameter, 'utm_')) {
-                     $utmArray[] = $parameter;
-                 }
-             }
-             return implode('&', $utmArray);
-         }
-         return '';
-     }
-     public static function getMobileDevice(Request $request) {
-         return CommonUtil::isMobileDevice($request);
-     }
-     /**
-      * @return \Slivki\Repository\PartnerOfferRepository
-      */
-     protected function getPartnerOfferRepository() {
-         return $this->getDoctrine()->getRepository(PartnerOffer::class);
-     }
-     protected function getGiftSupplierRepository(){
-         return $this->getDoctrine()->getRepository(Partner::class);
-     }
-     /**
-      * @return \Slivki\Repository\OfferRepository
-      */
-     protected function getOfferRepository() {
-         return $this->getDoctrine()->getRepository(Offer::class);
-     }
-     /**
-      * @return \Slivki\Repository\CategoryRepository
-      */
-     protected function getCategoryRepository() {
-         return $this->getDoctrine()->getRepository(Category::class);
-     }
-     /**
-      * @return \Slivki\Repository\SaleRepository
-      */
-     protected function getSaleRepository() {
-         return $this->getDoctrine()->getRepository(Sale::class);
-     }
-     /**
-      * @return \Slivki\Repository\MediaRepository
-      */
-     protected function getMediaRepository() {
-         return $this->getDoctrine()->getRepository(Media::class);
-     }
-     /**
-      * @return \Slivki\Repository\OfferOrderRepository
-      */
-     protected function getOfferOrderRepository() {
-         return $this->getDoctrine()->getRepository(OfferOrder::class);
-     }
-     /**
-      * @return \Slivki\Repository\OfferOrderDetails
-      */
-     protected function getOfferOrderDetailsRepository() {
-         return $this->getDoctrine()->getRepository(OfferOrderDetails::class);
-     }
-     /**
-      * @return \Slivki\Repository\SeoRepository
-      */
-     protected function getSeoRepository() {
-         return $this->getDoctrine()->getRepository(Seo::class);
-     }
-     /**
-      * @return \Slivki\Repository\GeoLocationRepository
-      */
-     protected function getGeoLocationRepository() {
-         return $this->getDoctrine()->getRepository(GeoLocation::class);
-     }
-     /**
-      * @return \Slivki\Repository\CommentRepository
-      */
-     protected function getCommentRepository() {
-         return $this->getDoctrine()->getRepository(Comment::class);
-     }
-     /**
-      * @return \Slivki\Repository\BannerRepository
-      */
-     protected function getBannerRepository() {
-         return $this->getDoctrine()->getRepository(Banner::class);
-     }
-     /**
-      * @return \Slivki\Repository\UserBalanceActivityType
-      */
-     protected function getUserBalanceActivityTypeRepository() {
-         return $this->getDoctrine()->getRepository(UserBalanceActivityType::class);
-     }
-     /**
-      * @return \Slivki\Repository\SiteSettingsRepository
-      */
-     protected  function getSiteSettingsRepository(){
-         return $this->getDoctrine()->getRepository(SiteSettings::class);
-     }
-     
-     /**
-      * @return \Slivki\Repository\UserRepository
-      */
-     protected function getUserRepository() {
-         return $this->getDoctrine()->getRepository(User::class);
-     }
-     /**
-      * @return \Slivki\Repository\UserActivity
-      */
-     protected function getUserActivityRepository() {
-         return $this->getDoctrine()->getRepository(UserActivity::class);
-     }
-     /**
-      * @return \Slivki\Entity\SiteSettings
-      */
-     protected function getSiteSettings() {
-         return $this->getDoctrine()->getRepository(SiteSettings::class)->getSiteSettingsCached();
-     }
-     /**
-      * @return \Slivki\Repository\Visit
-      */
-     protected function getVisitRepository() {
-         return $this->getDoctrine()->getRepository(Visit::class);
-     }
-     public function sendCode(Mailer $mailer, OfferOrder $offerOrder): void
-     {
-         if ($offerOrder instanceof GiftCertificateOrder || $offerOrder instanceof FoodOrder) {
-             return;
-         }
-         $email = trim($offerOrder->getUser()->getEmail());
-         if (!$email || $email == '') {
-             return;
-         }
-         if ($offerOrder instanceof GiftCertificateOrder) {
-             foreach ($offerOrder->getOfferOrderDetails() as $offerOrderDetails) {
-                 if ($offerOrder->getUser()->getEmail()) {
-                     $mpdf = $this->getGiftCertificateMpdf($this->kernel, $offerOrderDetails);
-                     if (!$mpdf) {
-                         continue;
-                     }
-                     $path = '/tmp/certificate'.$offerOrderDetails->getID().'.pdf';
-                     $mpdf->Output($path, 'F');
-                     $message = $mailer->createMessage();
-                     $message->setSubject('Slivki.by - промокод на акцию')
-                         ->setFrom('info@slivki.by', 'Slivki.by')
-                         ->setTo($offerOrder->getUser()->getEmail())
-                         ->setBody($this->get('twig')->render('Slivki/emails/code.html.twig', ['offerOrder' => $offerOrder]), 'text/html')
-                         ->attachFromPath($path);
-                     $mailer->send($message);
-                 }
-             }
-         } else {
-             if ($offerOrder->getUser()->getEmail()) {
-                 $message = $mailer->createMessage();
-                 $message->setSubject('Slivki.by - промокод на акцию')
-                     ->setFrom('info@slivki.by', 'Slivki.by')
-                     ->setTo($offerOrder->getUser()->getEmail())
-                     ->setBody($this->get('twig')->render('Slivki/emails/code.html.twig', ['offerOrder' => $offerOrder]), 'text/html');
-                 $mailer->send($message);
-             }
-         }
-     }
-     private function sendGiftCertificate(KernelInterface $kernel, Mailer $mailer, OfferOrder $order) {
-         foreach ($order->getOfferOrderDetails() as $offerOrderDetails) {
-             $mpdf = $this->getGiftCertificateMpdf($kernel, $offerOrderDetails);
-             if (!$mpdf) {
-                 continue;
-             }
-             $content = $mpdf->Output('', 'S');
-             // save preview
-             $iMagick = new \Imagick();
-             $iMagick->readImageBlob($content);
-             $iMagick->setImageFormat('png');
-             $iMagick->writeImage($kernel->getProjectDir() . GiftCertificate::PREVIEW_PATH . $offerOrderDetails->getID() . '.png');
-             $attachment = new \Swift_Attachment($content, 'certificate.pdf', 'application/pdf');
-             $message = $mailer->createMessage();
-             $user = $offerOrderDetails->getOfferOrder()->getUser();
-             $message->setSubject('Подарочный сертификат Slivki.by')
-                 ->setFrom("info@slivki.by", 'Slivki.by')
-                 ->setTo($user->getEmail())
-                 ->attach($attachment)
-                 ->setBody($this->renderView('Slivki/emails/gift_certificate.html.twig', [
-                     'name' => $user->getFirstName()]), 'text/html');
-             $mailer->send($message);
-         }
-     }
-     /**
-      * @return null|\Mpdf\Mpdf
-      */
-     protected function getGiftCertificateMpdf(KernelInterface $kernel, OfferOrderDetails $offerOrderDetails) {
-         $giftCertificate = $offerOrderDetails->getGiftCertificate();
-         if (!$giftCertificate) {
-             return null;
-         }
-         $customFontDir = $kernel->getProjectDir() . '/public/fonts/crt-fonts/ttf';
-         $defaultConfig = (new ConfigVariables())->getDefaults();
-         $defaultFontDir = $defaultConfig['fontDir'];
-         $defaultFontConfig = (new FontVariables())->getDefaults();
-         $defaultFontData = $defaultFontConfig['fontdata'];
-         $mpdf = new Mpdf([
-             'fontDir' => array_merge($defaultFontDir, [
-                 $customFontDir,
-             ]),
-             'tempDir' => '/tmp',
-             'fontdata' => $defaultFontData + [
-                     'sfrounded' => [
-                         'R' => 'SFRounded-Ultralight.ttf',
-                     ],
-                     'sf' => [
-                         'R' => 'SFProText-Regular.ttf',
-                     ],
-                 ],
-             'mode' => 'utf-8',
-             'format' => 'A4',
-             'orientation' => 'P',
-             'margin_top' => 10,
-             'margin_bottom' => 0,
-             'margin_left' => 0,
-             'margin_right' => 0,
-         ]);
-         $mpdf->curlAllowUnsafeSslRequests = true;
-         $template = 'Slivki/gift_certificates/crt_pdf.html.twig';
-         if (SosediBarcodeGenerator::OFFER_ID === (int) $offerOrderDetails->getOfferOrder()->getOffer()->getID()) {
-             $template = 'Slivki/gift_certificates/sosedi_pdf.html.twig';
-         }
-         $mpdf->WriteHTML($this->renderView($template, [
-             'offerOrderDetails' => $offerOrderDetails,
-             'giftCertificate' => $giftCertificate,
-             'offer' => $giftCertificate->getOffer(),
-         ]));
-         return $mpdf;
-     }
-     protected function sendConfirm(Mailer $mailer, $user) {
-         $userConfirmation = $this->getDoctrine()->getRepository(UserConfirmation::class)->findOneByUserID($user->getID());
-         if(!$userConfirmation){
-             return false;
-         }
-         $confirmURL = "/confirm/" . md5($userConfirmation->getID() . $user->getID());
-         $message = $mailer->createMessage();
-         $message->setSubject("Регистрация на Slivki.by")
-             ->setFrom("info@slivki.by", 'Slivki.by')
-             ->setTo($user->getEmail())
-             ->setBody(
-                 $this->renderView(
-                     'Slivki/emails/confirm_user.html.twig',
-                     array('link' => $confirmURL)
-                 ),
-                 'text/html'
-             );
-         $mailer->send($message);
-         
-         return true;
-     }
-     /**
-      * @deprecated Use OfferOrderRepository::getNewOrderNumber
-      */
-     protected function getNewOrderNumber() {
-         return $this->getDoctrine()->getRepository(OfferOrder::class)->getNewOrderNumber();
-     }
-     protected function getLogger() {
-         return Logger::instance('Controller');
-     }
-     protected function log($text) {
-         $this->getLogger()->info($this->container->get('request_stack')->getMainRequest()->getRequestUri() . ": $text");
-     }
-     protected function getComments(Request $request, BannerService $bannerService, $entityID, $typeID, $lastCommentID = 0, $categoryID = 0, $directorID = 0, $cacheName = CommentCacheService::CACHE_NAME) {
-         $firstPage = $lastCommentID == 0 && $entityID != 0;
-         $softCache = new SoftCache($cacheName);
-         $commentsBlock = '';
-         $cacheKey = $typeID . '-' . $entityID;
-         $mobileDevice = false;
-         $cityID = $request->getSession()->get(City::CITY_ID_SESSION_KEY, City::DEFAULT_CITY_ID);
-         if ($cacheName == CommentRepository::MOBILE_CACHE_NAME) {
-             $mobileDevice = true;
-         }
-         $offerId = 1 === $typeID ? $entityID : null;
-         if ($firstPage) {
-             $commentsBlock = $softCache->getDataForLockedKey($cacheKey, 0);
-             if ($commentsBlock == SoftCache::LOCKED_KEY) {
-                 return '';
-             }
-             if ($commentsBlock) {
-                 return $directorID != 5596 ? $this->insertBannersToComments($bannerService, $commentsBlock, $mobileDevice, $cityID, $offerId) : $commentsBlock;
-             }
-             $softCache->set($cacheKey, SoftCache::LOCKED_KEY, 10);
-         }
-         if ($entityID == 0 ) {
-             $commentRepository = $this->getCommentRepository();
-             if ($categoryID == 0) {
-                 $data['isLiveComments'] = 1;
-                 if ($directorID > 0) {
-                     $data['comments'] = $commentRepository->getCommentsByDirectorID($directorID,CommentRepository::COMMENTS_PER_PAGE, $lastCommentID);
-                 } else {
-                     $data['comments'] = $commentRepository->getLiveComments(CommentRepository::COMMENTS_PER_PAGE, $lastCommentID);
-                 }
-                 $data['commentsAmount'] = CommentRepository::COMMENTS_PER_PAGE;
-                 $data['hasMore'] = true;
-             } else {
-                 $data['isLiveComments'] = 1;
-                 $data['hasMore'] = true;
-                 $data['commentsAmount'] = CommentRepository::COMMENTS_PER_PAGE;
-                 $data['categoryID'] = $categoryID;
-                 $data['comments'] = $commentRepository->getCommentsByCategoryID($categoryID, $data['commentsAmount'], $lastCommentID);
-             }
-         } else {
-             $comments = $this->getCommentRepository()->getCommentsByEntityID($entityID, CommentRepository::COMMENTS_PER_PAGE, $lastCommentID);
-             if (empty($comments)) {
-                 return '';
-             }
-             $lastCommentID = $comments[count($comments) - 1]->getID();
-             $data['comments'] = $comments;
-             if ($firstPage && $typeID == Comment::TYPE_OFFER_COMMENT) {
-                 $offer = $this->getOfferRepository()->getAnyWay($entityID);
-                 if ($offer && !$offer->isHideBannersInComments()) {
-                     $data['showBanners'] = true;
-                 }
-             }
-             $data['commentsAmount'] = CommentRepository::COMMENTS_PER_PAGE;
-             $dql = 'select comment from Slivki:Comment comment
-                 where comment.entityID = :entityID and comment.typeID = :typeID and comment.parentID is null and comment.ID < :lastCommentID and comment.hidden = false and comment.confirmedPhone = true';
-             $query = $this->getDoctrine()->getManager()->createQuery($dql)
-                 ->setParameter('entityID', $entityID)->setParameter('lastCommentID', $lastCommentID)->setParameter('typeID', $typeID);
-             $query->setMaxResults(1);
-             if ($typeID == Comment::TYPE_OFFER_COMMENT) {
-                 $commentsAmount = $this->getCommentRepository()->getCommentsCountByEntityID($entityID, Comment::TYPE_OFFER_COMMENT);
-                 $data['hasMore'] = false;
-                 $data['pagination'] = $this->renderView('Slivki/pagination.html.twig', [
-                     'paginationID' => 'offerCommentPagination',
-                     'current' => 1,
-                     'total' => ceil($commentsAmount/CommentRepository::COMMENTS_PER_PAGE),
-                     'url' => $this->getDoctrine()->getRepository(Seo::class)->getOfferURL($entityID)->getMainAlias() . '?page='
-                 ]);
-             } else {
-                 $data['hasMore'] = count($query->getResult()) > 0;
-             }
-         }
-         $view = 'Slivki/comments/comments.html.twig';
-         if ($mobileDevice) {
-             $view = 'Slivki/mobile/comment/list.html.twig';
-         }
-         $response = $this->get('twig')->render($view, $data);
-         if ($firstPage) {
-             $softCache->set($cacheKey, $response, 48 * 60 * 60);
-         }
-         return $directorID != 5596 ? $this->insertBannersToComments($bannerService, $response, $mobileDevice, $cityID, $offerId) : $response;
-     }
-     // TODO: Refactor and remove to service
-     private function insertBannersToComments(BannerService $bannerService, $commentsHTML, $mobileDevice, $cityID = City::DEFAULT_CITY_ID, $offerId = null) {
-         $bannerList = [];
-         if (!($this->getUser() and $this->getUser()->hasRole(UserGroup::ROLE_ADS_FREE))) {
-             $bannerList = $bannerService->getCommentsBanners($mobileDevice, $cityID, $offerId);
-             if (count($bannerList) == 0 && $cityID != City::DEFAULT_CITY_ID) {
-                 $bannerList = $bannerService->getCommentsBanners($mobileDevice, City::DEFAULT_CITY_ID, $offerId);
-             }
-         }
-         if (count($bannerList) == 0) {
-             return $commentsHTML;
-         }
-         $session = new Session();
-         $sessionKey = 'lastBannerIndex';
-         foreach ($bannerList as $position => $banners) {
-             $bannerHTML = '';
-             if (count($banners) == 1) {
-                 $bannerHTML = $banners[0];
-             } else {
-                 $lastBannerIndex = $session->get($sessionKey . $position, 0);
-                 $nextBannerIndex = $lastBannerIndex + 1 < count($banners) ? $lastBannerIndex + 1 : 0;
-                 $bannerHTML = $banners[$nextBannerIndex];
-                 $session->set($sessionKey . $position, $nextBannerIndex);
-             }
-             $commentsHTML = str_replace('<span id="commentBannerPlaceHolder' . ($position + 1) . '" class="hidden"></span>', $bannerHTML, $commentsHTML);
-         }
-         return $commentsHTML;
-     }
-     /**
-      * @deprecated use CommentCacheService
-      */
-     public function resetCommentsCache($entityID, $typeID) {
-         (new SoftCache(CommentCacheService::CACHE_NAME))->delete($typeID . '-' . $entityID);
-         (new SoftCache(CommentCacheService::MOBILE_CACHE_NAME))->delete($typeID . '-' . $entityID);
-     }
-     public function getParentCategoryList(Request $request, $defaultCategoryID = null) {
-         $data['siteSettings'] = $this->getSiteSettings();
-         $parentCategoryID = $request->cookies->get('referrerCategory');
-         if (!$parentCategoryID) {
-             $parentCategoryID = $defaultCategoryID;
-         }
-         if (!$parentCategoryID) {
-             return false;
-         }
-         $categoryRepository = $this->getCategoryRepository();
-         $category = $categoryRepository->findCached($parentCategoryID);
-         if (!$category) {
-             return false;
-         }
-         $parentCategoryList = $this->getCategoryRepository()->getCategoryParentList($category['category']);
-         $parentCategoryList[] = $category['category'];
-         return $parentCategoryList;
-     }
-     protected function addVisit($entityID, $entityTypeID, $deviceType, $user, $clientIPAddress, $referrer = '') {
-         $visit = new Visit();
-         $visit->setEntityID($entityID);
-         $visit->setEntityTypeID($entityTypeID);
-         if($user) {
-             $visit->setUser($user);
-         }
-         $visit->setDeviceType($deviceType);
-         $visit->setReferrer($referrer);
-         $visit->setIPAddress($clientIPAddress);
-         $entityManager = $this->getDoctrine()->getManager();
-         $entityManager->persist($visit);
-         $entityManager->flush($visit);
-     }
-     protected function sendPassword(Mailer $mailer, string $email, Request $request) {
-         if (!$email) {
-             return false;
-         }
-         Logger::instance('PASSWORD-RECOVERY')->info(print_r([$email, $request->getClientIp(), $request->headers->all()], true));
-         $entityManager = $this->getDoctrine()->getManager();
-         $user = $entityManager->getRepository(User::class)->loadUserByUsername($email, false);
-         if(!$user){
-             return false;
-         }
-         $securityCode = rand(1000, 9999);
-         $user->setSecurityCode($securityCode);
-         $entityManager->flush();
-         $message = $mailer->createMessage();
-         $message->setSubject("Восстановление пароля")
-             ->setFrom("info@slivki.by", 'Slivki.by')
-             ->setTo($email)
-             ->setBody(
-                 $this->renderView(
-                     'Slivki/emails/lost_password.html.twig',
-                     array('securityCode' => $securityCode)
-                 ),
-                 'text/html'
-             );
-         $mailer->send($message);
-         return true;
-     }
-     /** @deprecated  */
-     protected function getOfferTeaserCached(Offer $offer) {
-         $softCache = new SoftCache(OfferRepository::CACHE_NAME_TEASERS);
-         $offerTeaserCached = $softCache->get($offer->getID());
-         if ($offerTeaserCached) {
-             return $offerTeaserCached;
-         }
-         $teaserHTML = $this->get('twig')->render('Slivki/offers/teaser.html.twig', ['offer' => $offer]);
-         $softCache->set($offer->getID(), $teaserHTML, 24 * 60 * 60);
-         return $teaserHTML;
-     }
-     protected function getOfferRateSchedule(Session $session) {
-         $user = $this->getUser();
-         $lastActivity = $session->get(self::LAST_OFFER_RATE_ACTIVITY_PARAMETER_NAME);
-         if (!$user || !$user->isWantRatePopup() || ($lastActivity && time() - $lastActivity < 300) ) {
-             return false;
-         }
-         $dql = 'select schedule from Slivki:OfferRateSchedule schedule where schedule.userID = :userID and schedule.showOn < CURRENT_TIMESTAMP() order by schedule.ID ASC';
-         $rateSchedule = $this->getDoctrine()->getManager()->createQuery($dql)->setParameter('userID', $user->getID())->getResult();
-         return count($rateSchedule) > 0 ? $rateSchedule[0] : false;
-     }
-     protected function handleFileUpload(KernelInterface $kernel, $uploadedFile, $destinationPath) {
-         $fileSystem = new Filesystem();
-         $filePath = $kernel->getProjectDir() . '/public' . $destinationPath;
-         $fileName = $uploadedFile->getClientOriginalName();
-         while ($fileSystem->exists($filePath . $fileName)) {
-             $fileName = time() . '_' . $fileName;
-         }
-         $uploadedFile->move($filePath, $fileName);
-         return $fileName;
-     }
-     public function getShareClicks($entityID) {
-         $sql = "select month_share.network_name as network, coalesce(yesterday_click_count, 0) as yesterday, coalesce(month_click_count, 0) as month from 
-         (select network_name, count(id) as month_click_count from share_click 
-         where entity_id = $entityID and created_on::date between (CURRENT_DATE + INTERVAL '-31 day')::date and CURRENT_DATE group by network_name) as month_share 
-         LEFT JOIN
-         (select network_name, count(id) as yesterday_click_count from share_click 
-         where entity_id = $entityID and created_on::date = (CURRENT_DATE + INTERVAL '-1 day')::date group by network_name) as yestarday_share 
-         on yestarday_share.network_name = month_share.network_name";
-         return $this->getDoctrine()->getManager()->getConnection()->executeQuery($sql)->fetchAll();
-     }
-     public function getMainHotFeed(OfferCacheService $offerCacheService, SaleCacheService $saleCacheService, $limit = null, $offset = 0, $type = HotFeed::TYPE_MAIN_PAGE, $cityID = null) {
-         $entityManager = $this->getDoctrine()->getManager();
-         $cityCondition = '';
-         if ($cityID > 0) {
-             $cityCondition = ' and city_id = ' . $cityID;
-         }
-         $sql = 'select * from hot_feed where type = ' . (int)$type . " $cityCondition order by created_on desc limit " . (int)$limit . ' offset ' . (int)$offset;
-         $entityIDList = $entityManager->getConnection()->executeQuery($sql)->fetchAll();
-         $entityList = [];
-         $saleRepository = $entityManager->getRepository(Sale::class);
-         $categorySoftCache = new SoftCache(CategoryRepository::CACHE_NAME);
-         $categoryRepository = $entityManager->getRepository(Category::class);
-         foreach ($entityIDList as $item) {
-             $entity = null;
-             switch ($item['entity_type_id']) {
-                 case Category::SALE_CATEGORY_ID:
-                     $entity = $saleCacheService->getSale($item['entity_id']);
-                     break;
-                 case Category::OFFER_CATEGORY_ID:
-                     $entity = $offerCacheService->getOffer($item['entity_id'], true);
-                     break;
-                 case Category::CATEGORY_ID:
-                     $entity = $categorySoftCache->get($item['entity_id']);
-                     $entity = $entity["category"];
-                     break;
-             }
-             if ($entity) {
-                 $iconMedia = $entity->getHotFeedIconMedia();
-                 $isVideoGuide = false;
-                 switch ($item['entity_type_id']) {
-                     case Category::OFFER_CATEGORY_ID:
-                         $title = $entity->getTitle();
-                         $entityUrlType = SeoRepository::RESOURCE_URL_OFFER_DETAILS;
-                         if (!$iconMedia && $entity->getCategories()->count() > 0) {
-                             $categoryID = $entity->getCategories()->first()->getID();
-                             $category = $entityManager->getRepository(Category::class)->findCached($categoryID);
-                             if ($category) {
-                                 $iconMedia = $category['category']->getHotFeedIconMedia();
-                             }
-                         }
-                         $imageMedia = $entity->getTeaserMedia();
-                         break;
-                     case Category::SALE_CATEGORY_ID:
-                         $title = $entity->getTitle();
-                         $entityUrlType = SeoRepository::RESOURCE_URL_SALE_DETAILS;
-                         $isVideoGuide = $entity->isInCategory(Category::SALE_VIDEO_GUIDE_CATEGORY_ID);
-                         if (!$iconMedia) {
-                             foreach ($entity->getCategories() as $category) {
-                                 $category = $categoryRepository->findCached($category->getID());
-                                 if ($category) {
-                                     $iconMedia = $category['category']->getHotFeedIconMedia();
-                                     if ($iconMedia) {
-                                         break;
-                                     }
-                                 }
-                             }
-                         }
-                         $imageMedia = $entity->getIcon();
-                         break;
-                     case Category::CATEGORY_ID:
-                         $title = $entity->getHotFeedName() ? $entity->getHotFeedName() : $entity->getName();
-                         switch ($entity->getDomainObjectID()) {
-                             case Category::OFFER_CATEGORY_ID:
-                                 $entityUrlType = SeoRepository::RESOURCE_URL_OFFER_CATEGORY;
-                                 break;
-                             case Category::SALE_CATEGORY_ID:
-                                 $entityUrlType = SeoRepository::RESOURCE_URL_OFFER_CATEGORY;
-                                 break;
-                         }
-                         $imageMedia = $entity->getHotFeedMedia();
-                         break;
-                 }
-                 $createdOn = \DateTime::createFromFormat('Y-m-d H:i:s', $item['created_on']);
-                 $todayStart = \DateTime::createFromFormat('Y-m-d H:i:s', date('Y-m-d H:i:s'))->modify('-23 hour');
-                 $yesterdayStart = \DateTime::createFromFormat('Y-m-d  H:i:s', date('Y-m-d 00:00:00'))->modify('-1 day');
-                 $timeText = $createdOn->format('d.m.y');
-                 if ($createdOn >= $todayStart) {
-                     $timeText = $createdOn->format('H:i');
-                 } elseif ($createdOn >= $yesterdayStart) {
-                     $timeText = "вчера";
-                 }
-                 $entityList[] = [
-                     'createdOn' => $createdOn,
-                     'title' => $title,
-                     'isVideoGuide' => $isVideoGuide,
-                     'entityUrlType' => $entityUrlType,
-                     'iconMedia'=> $iconMedia,
-                     'imageMedia' => $imageMedia,
-                     'timeText' => $timeText,
-                     'entity' => $entity
-                 ];
-             }
-         }
-         return $entityList;
-     }
-     /**
-      * @deprecated use CommentHelper
-      */
-     public function prepareCommentText($commentText) {
-         $commentText = str_replace(['<div>', '</div>', '<br>', '<br/>', '<br />'], "\n", $commentText);
-         $commentText = strip_tags($commentText, '<img><a>');
-         return preg_replace("/[\r\n]+/", "\n", $commentText);
-     }
-     public function sendOfferCommentNotice(Mailer $mailer, Offer $offer, Comment $comment, Comment $parentComment = null) {
-         if (!$comment->isConfirmedPhone()) {
-             return false;
-         }
-         // Send Answer To Customer Comment
-         if ($parentComment) {
-             $email = $parentComment->getUser()->getEmail();
-             if ($email) {
-                 $message = $mailer->createMessage();
-                 $message->setSubject("Отзыв на акцию")
-                     ->setFrom("info@slivki.by", 'Slivki.by')
-                     ->setTo($parentComment->getUser()->getEmail())
-                     ->setBody(
-                         $this->renderView(
-                             'Slivki/emails/answer_to_customer_comment.html.twig',
-                             array('comment' => $comment)
-                         ),
-                         'text/html'
-                     );
-                 $mailer->send($message);
-             }
-         }
-         $directors = $offer->getDirectors();
-         if ($directors && $directors->count() > 0  && $directors->first()->getEmail() != '') {
-             $message = $mailer->createMessage();
-             $message->setSubject("Отзыв на акцию")
-                 ->setFrom("info@slivki.by", 'Slivki.by')
-                 ->setTo($directors->first()->getEmail())
-                 ->setBody($this->renderView('Slivki/emails/comment_to_supplier.html.twig', ['comment' => $comment, 'offer' => $offer]), 'text/html');
-             $mailer->send($message);
-         }
-     }
-     public function getCheckAddressResponse($orderInfo) {
-         $message = '';
-         switch ($orderInfo->resultState) {
-             case 1:
-                 if (isset($orderInfo->problem)) {
-                     $message = $orderInfo->problem;
-                 }
-                 if (isset($orderInfo->minSumForFreeDelivery)) {
-                     $message = \sprintf('Минимальная сумма заказа %s руб.', (string) $orderInfo->minSumForFreeDelivery);
-                 }
-                 break;
-             case 2:
-                 $message = 'Извините, в данное время заказ невозможен. Пожалуйста, выберите другое время';
-                 break;
-             case 3:
-                 $message = 'Извините, на данный адрес доставка не осуществляется';
-                 break;
-             case 4:
-             case 5:
-                 $message = 'На данный момент заказ одного из товаров невозможен';
-                 break;
-             case 9999:
-                 $message = 'Заказы принимаются с 11:00 по 22:22';
-         }
-         return [
-             'status' => $orderInfo->resultState === 0 ? 'success' : 'error',
-             'error' => $orderInfo->resultState != 0,
-             'deliveryPrice' => isset($orderInfo->deliveryServiceProductInfo) ? $orderInfo->deliveryServiceProductInfo->productSum : 0,
-             'message' => $message
-         ];
-     }
-     public function getOptions(
-         ImageService $imageService,
-         Offer &$offer,
-         AbstractDelivery $iikoUtil,
-         $sticksCount,
-         $shippingType = null
-     ) {
-         $entityManager = $this->getDoctrine()->getManager();
-         $optionRepository = $entityManager->getRepository(FoodOfferOptionExtension::class);
-         $options = [];
-         $sticks = $iikoUtil->getProduct($iikoUtil::STICKS_PRODUCT_ID);
-         $sticksID = null;
-         if ($sticks) {
-             $option = $optionRepository->findOneBy(['offer' => $offer, 'partnerItemID' => $sticks->id]);
-             if ($option) {
-                 $sticksID = $sticks->id;
-                 $sticks->partnerID = $sticks->id;
-                 $sticks->id = $option->getID();
-                 $sticks->offerPrice = $sticks->price;
-                 $sticks->regularPrice = $sticks->price;
-                 $sticks->inBasketCount = $sticksCount;
-                 $sticks->isSticks = true;
-                 $sticks->isIncluded = false;
-                 $sticks->position = $option->getPosition() ?: CustomProductOfferSorter::DEFAULT_POSITION;
-                 $sticks->imageURL = '';
-                 if (null !== $sticks->images && count($sticks->images) > 0) {
-                     if ($sticks->images[count($sticks->images) - 1] instanceof OfferExtensionMedia) {
-                         $sticks->imageURL = $imageService->getImageURLCached($sticks->images[count($sticks->images) - 1], 540, 0);
-                     } else if ($sticks->images[count($sticks->images) - 1]) {
-                         $sticks->imageURL = $sticks->images[count($sticks->images) - 1]->imageUrl;
-                     }
-                 }
-                 $sticks->badgeLabel = $option->getBadgeLabel();
-                 $sticks->badgeBgColor = $option->getBadgeBgColor();
-                 $sticks->badgeTextColor = $option->getBadgeTextColor();
-                 if ($option->isActive()) {
-                     $options[] = $sticks;
-                 }
-             }
-         }
-         foreach ($iikoUtil->getOptions() as $item) {
-             if (($sticks && $sticksID == $item->id) || (isset($item->isSticks) && $item->isSticks)) {
-                 continue;
-             }
-             $option = $optionRepository->findOneBy(['offer' => $offer, 'partnerItemID' => $item->id]);
-             if ($option) {
-                 switch ($item->id) {
-                     case $iikoUtil::SOY_SAUCE_PRODUCT_ID:
-                         $item->isSoySauce = true;
-                         $item->isIncluded = false;
-                         break;
-                     case $iikoUtil::WASABI_PRODUCT_ID:
-                         $item->isWasabi = true;
-                         $item->isIncluded = false;
-                         break;
-                     case $iikoUtil::GINGER_PRODUCT_ID:
-                         $item->isGinger = true;
-                         $item->isIncluded = false;
-                 }
-                 $item->partnerID = $item->id;
-                 $item->id = $option->getID();
-                 $item->offerPrice = $item->price;
-                 $item->regularPrice = $item->price;
-                 $item->imageURL = null;
-                 $item->itemCount = (int) $option->getComponentsCount();
-                 $item->weight = (double) $option->getWeight();
-                 $item->position = $option->getPosition() ?: CustomProductOfferSorter::DEFAULT_POSITION;
-                 if (isset($item->images[count($item->images) - 1])) {
-                     if ($item->images[count($item->images) - 1] instanceof OfferExtensionMedia) {
-                         $item->imageURL = $imageService->getImageURLCached($item->images[count($item->images) - 1], 540, 0);
-                     } else if ($item->images[count($item->images) - 1]) {
-                         $item->imageURL = $item->images[count($item->images) - 1]->imageUrl;
-                     }
-                 }
-                 $item->badgeLabel = $option->getBadgeLabel();
-                 $item->badgeBgColor = $option->getBadgeBgColor();
-                 $item->badgeTextColor = $option->getBadgeTextColor();
-                 if ($option->isActive()) {
-                     if (null !== $shippingType) {
-                         $isShippingType = 'getIs' . ucfirst($shippingType);
-                         if ($option->{$isShippingType}()) {
-                             $options[] = $item;
-                         }
-                     } else {
-                         $options[] = $item;
-                     }
-                 }
-             }
-         }
-         return $options;
-     }
- }