src/Controller/MainController.php line 551

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\Article;
  4. use App\Entity\Card;
  5. use App\Entity\CardItem;
  6. use App\Entity\Category;
  7. use App\Entity\Channel;
  8. use App\Entity\Comment;
  9. use App\Entity\Media;
  10. use App\Entity\StaticPage;
  11. use App\Entity\StripeProduct;
  12. use App\Entity\User;
  13. use App\Form\RegisterType;
  14. use App\Service\ArticleEntityService;
  15. use App\Service\CaptchaService;
  16. use App\Service\CartService;
  17. use App\Service\FavoriteService;
  18. use App\Service\LikesService;
  19. use App\Service\MediaEntityService;
  20. use App\Service\PlatformService;
  21. use App\Service\StaticPageBlockEntityService;
  22. use App\Service\StorageService;
  23. use App\Service\StripeService;
  24. use App\Service\UserService;
  25. use Bluesquare\ValidatorBundle\Validator;
  26. use Doctrine\ORM\EntityManagerInterface;
  27. use Psr\Container\ContainerInterface;
  28. use Psr\Log\LoggerInterface;
  29. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Cache;
  30. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  31. use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
  32. use Symfony\Component\Form\Extension\Core\Type\EmailType;
  33. use Symfony\Component\Form\Extension\Core\Type\PasswordType;
  34. use Symfony\Component\HttpFoundation\Request;
  35. use Symfony\Component\HttpFoundation\Response;
  36. use Symfony\Component\HttpKernel\KernelInterface;
  37. use Symfony\Component\Mailer\MailerInterface;
  38. use Symfony\Component\Routing\Annotation\Route;
  39. use Symfony\Component\Validator\Constraints as Assert;
  40. use Symfony\Component\Validator\Constraints\Email;
  41. use Symfony\Component\Validator\Constraints\NotBlank;
  42. use Symfony\Component\Validator\Validator\ValidatorInterface;
  43. class MainController extends AbstractController
  44. {
  45.     private KernelInterface $appKernel;
  46.     protected MediaEntityService $mediaEntityService;
  47.     private ParameterBagInterface $parameterBag;
  48.     // constructor injection
  49.     public function __construct(
  50.         KernelInterface $appKernel,
  51.         MediaEntityService $mediaEntityService,
  52.         ParameterBagInterface $parameterBag
  53.     ){
  54.         $this->appKernel $appKernel;
  55.         $this->mediaEntityService $mediaEntityService;
  56.         $this->parameterBag $parameterBag;
  57.     }
  58.     /**
  59.      * @Route("/", name="home")
  60.      */
  61.     public function index(EntityManagerInterface $managerStaticPageBlockEntityService $staticPageBlockEntityService)
  62.     {
  63.         $channel $manager->getRepository(Channel::class)->findOneBy(['active' => true]);
  64.         if ($channel instanceof Channel) {
  65.             $homepage $channel->getHomepage();
  66.             if ($homepage instanceof StaticPage) {
  67.                 $structure $this->getStaticPageStructure($homepage$staticPageBlockEntityService);
  68.                 return $this->render('static_page/static_page.html.twig', [
  69.                     'page' => $homepage,
  70.                     'blocks' => $structure['blocks'],
  71.                     'block_header' => $structure['block_header'],
  72.                     'homepage_static_page' => true,
  73.                 ]);
  74.             }
  75.             return $this->redirectToRoute('homepage');
  76.         }
  77.         throw $this->createNotFoundException();
  78.     }
  79.     /**
  80.      * @Route("/home/{page}", name="homepage",defaults={"page"=1})
  81.      * @throws \Exception
  82.      */
  83.     public function home(
  84.         Request $request,
  85.         Validator $validator,
  86.         ArticleEntityService $articleService,
  87.         EntityManagerInterface $manager,
  88.         StripeService $stripeService,
  89.         $page
  90.     ): ?Response
  91.     {
  92.         $channel $manager->getRepository(Channel::class)->findOneBy(['active' => true]);
  93.         if (!$channel) {
  94.             throw $this->createNotFoundException();
  95.         }
  96.         if ($request->isXmlHttpRequest()) {
  97.             $articlesHomepage=$manager->getRepository(Article::class)->getLiveArticlesRefonte($channel,8,$page*3);
  98.             $articlesHomepage $articleService->formatAll($articlesHomepage);
  99.             return $this->render('home/recent-articles-more.html.twig', [
  100.                 'page' => $page,
  101.                 'articles' => $articlesHomepage,
  102.             ]);
  103.         }
  104.         /* @var User $user */
  105.         $user $this->getUser();
  106.         $user_subscriptions $user $stripeService->getUserSubscriptions($user) : [];
  107.         $subscription_status false;
  108.         if (!empty($user_subscriptions)) {
  109.             // Check if user has an active subscription
  110.             foreach ($user_subscriptions as $user_subscription) {
  111.                 if ('active' === $user_subscription->getStatus()) {
  112.                     $subscription_status true;
  113.                     break;
  114.                 }
  115.             }
  116.         }
  117.         return $this->render('home/home.html.twig', [
  118.             'validator' => $validator,
  119.             'user' => $user,
  120.             'userSubscriptionsStatus' => $subscription_status,
  121.             'page' => $page,
  122.         ]);
  123.     }
  124.     /**
  125.      * @Route("/static/banner.jpg", name="static.platform.banner")
  126.      */
  127.     public function banner(PlatformService $platformService)
  128.     {
  129.         $banner $platformService->getImagePath('banner.jpg'$platformService->getRoot().'/public/assets/images/default/banner.jpg');
  130.         header('content-type: image/jpeg');
  131.         header('Pragma: public');
  132.         header('Cache-Control: must-revalidate');
  133.         header('Last-Modified: '.gmdate('D, d M Y H:i:s'$platformService->getConfig(true)['images.last_update']).' GMT');
  134.         echo file_get_contents($banner);
  135.         exit;
  136.     }
  137.     /**
  138.      * @Route("/static/logo.png", name="static.platform.logo")
  139.      */
  140.     public function logo(PlatformService $platformService)
  141.     {
  142.         $logo $platformService->getImagePath('logo.png'$platformService->getRoot().'/public/assets/images/default/logo_transparent.jpg');
  143.         header('content-type: image/png');
  144.         header('Pragma: public');
  145.         header('Cache-Control: must-revalidate');
  146.         header('Last-Modified: '.gmdate('D, d M Y H:i:s'$platformService->getConfig(true)['images.last_update']).' GMT');
  147.         echo file_get_contents($logo);
  148.         exit;
  149.     }
  150.     /**
  151.      * @Route("/static/favicon.png", name="static.platform.favicon")
  152.      */
  153.     public function favicon(PlatformService $platformService)
  154.     {
  155.         $favicon $platformService->getImagePath('favicon.png'$platformService->getRoot().'/public/assets/images/default/favicon.png');
  156.         header('content-type: image/png');
  157.         header('Pragma: public');
  158.         header('Cache-Control: must-revalidate');
  159.         header('Last-Modified: '.gmdate('D, d M Y H:i:s'$platformService->getConfig(true)['images.last_update']).' GMT');
  160.         echo file_get_contents($favicon);
  161.         exit;
  162.     }
  163.     /**
  164.      * @Route("/rss", name="rss", defaults={"_format"="xml"})
  165.      */
  166.     public function rss(ArticleEntityService $articleServiceEntityManagerInterface $emMediaEntityService $entityService): Response
  167.     {
  168.         $articles_array = [];
  169.         $articleRepository $this->getDoctrine()->getRepository(Article::class);
  170.         $articles $articleRepository->getLiveArticles(null50);
  171.         $projectDir $this->appKernel->getProjectDir();
  172.         $tempDir $projectDir '/var/temp';
  173.         if (!is_dir($tempDir)) {
  174.             @mkdir($tempDir0755true);
  175.         }
  176.         foreach ($articles as $article) {
  177.             $cover $article->getCover();
  178.             // If cover exists but no thumbnail, try to download and generate one
  179.             if ($cover && !$cover->getThumbnail()) {
  180.                 $entity $em->getRepository(Media::class)->find($cover->getId());
  181.                 if (!$entity) {
  182.                     $entity = new Media();
  183.                     $entity->setType($cover->getType());
  184.                     $entity->setLabel($cover->getLabel());
  185.                     $em->persist($entity);
  186.                     $em->flush();
  187.                 }
  188.                 $type $cover->getType() ?? 'image/jpeg';
  189.                 $parts explode('/'$type);
  190.                 $extension $parts[1] ?? 'jpg';
  191.                 $file $tempDir '/' uniqid('article_' $article->getId() . '_') . '.' $extension;
  192.                 // build remote path
  193.                 $storageUrlFront $this->getParameter('storage_url_front');
  194.                 $storagePathFront $this->parameterBag->has('storage_path') ? $this->getParameter('storage_path_front') : null;
  195.                 if ($storagePathFront) {
  196.                     $path rtrim($storageUrlFront'/') . '/' trim($storagePathFront'/') . '/media/' $cover->getFile();
  197.                 } else {
  198.                     $path rtrim($storageUrlFront'/') . '/media/' $cover->getFile();
  199.                 }
  200.                 try {
  201.                     $content = @file_get_contents($path);
  202.                     if ($content === false) {
  203.                         // cannot fetch remote file
  204.                         @unlink($file);
  205.                         continue;
  206.                     }
  207.                     file_put_contents($file$content);
  208.                 } catch (\Throwable $e) {
  209.                     @unlink($file);
  210.                     continue;
  211.                 }
  212.                 try {
  213.                     $uploadedFile = new \Symfony\Component\HttpFoundation\File\UploadedFile(
  214.                         $file,
  215.                         basename($file),
  216.                         mime_content_type($file) ?: $type,
  217.                         null,
  218.                         true
  219.                     );
  220.                     $entityService->postValidateThumbnail($entity$uploadedFile);
  221.                     $em->persist($entity);
  222.                     $article->setCover($entity);
  223.                     $em->persist($article);
  224.                     $em->flush();
  225.                 } catch (\Throwable $e) {
  226.                     // ignore errors for a single article and continue
  227.                 } finally {
  228.                     @unlink($file);
  229.                 }
  230.             }
  231.             // If article has a usable thumbnail, verify it and add to the list
  232.             if ($article->getCover() !== null && $article->getCover()->getThumbnail() !== null) {
  233.                 $thumbnail $article->getCover()->getThumbnail();
  234.                 $folder '/media_thumbnail/';
  235.                 if ($article->getCover()->getWpThumbnail()) {
  236.                     $thumbnail $article->getCover()->getWpThumbnail();
  237.                     $folder '/media_thumbnail_wp/';
  238.                 }
  239.                 if ($this->parameterBag->has('storage_path')) {
  240.                     $path rtrim($this->getParameter('storage_url'), '/') . '/' trim($this->getParameter('storage_path'), '/') . $folder $thumbnail;
  241.                 } else {
  242.                     $path rtrim($this->getParameter('storage_url'), '/') . $folder $thumbnail;
  243.                 }
  244.                 if ($this->mediaEntityService->isMediaWorking($path)) {
  245.                     $articles_array[] = $article;
  246.                 }
  247.                 // else skip article
  248.             } elseif ($article->getCover() === null) {
  249.                 // no cover - include article
  250.                 $articles_array[] = $article;
  251.             }
  252.         }
  253.         $articles $articleService->formatAll($articles_array);
  254.         return $this->render('rss.xml.twig', [
  255.             'articles' => $articles,
  256.         ]);
  257.     }
  258.     /**
  259.      * @Route("/rss/{slug}.xml", name="rss.slug", defaults={"_format"="xml"})
  260.      */
  261.     public function rssBySlug(ArticleEntityService $articleServiceEntityManagerInterface $emMediaEntityService $entityService$slug): Response
  262.     {
  263.         // slug currently unused; reuse main rss logic
  264.         return $this->rss($articleService$em$entityService);
  265.     }
  266.     /**
  267.      * @Route("/moneyTizerDirectCode", name="moneyTizerDirectCode")
  268.      */
  269.     public function moneyTizerDirectCode(): Response
  270.     {
  271.         return $this->render('article/moneyTizerDirectCode.html.twig');
  272.     }
  273.     /**
  274.      * @Route("/sitemap.xml", name="sitemap", defaults={"_format"="xml"})
  275.      */
  276.     public function sitemap(ArticleEntityService $articleEntityService)
  277.     {
  278.         $urlCategories = [];
  279.         $articleRepository $this->getDoctrine()->getRepository(Article::class);
  280.         $categoryRepository $this->getDoctrine()->getRepository(Category::class);
  281.         $articles $articleEntityService->formatAll($articleRepository->getLiveArticles(null50));
  282.         $appurl $this->parameterBag->get('app_url');
  283.         $categories $categoryRepository->getCategories_all();
  284.         foreach ($categories as $category) {
  285.             $urlCategories[] = $appurl.$this->generateUrl('category.view', ['slug' => $category->getSlug()]);
  286.         }
  287.         $dailyChanges=[
  288.             $appurl.$this->generateUrl('homepage'),
  289.             $appurl.$this->generateUrl('articleLive'),
  290.         ];
  291.         $urls=[
  292.             $appurl.$this->generateUrl('homepage'),
  293.             $appurl.$this->generateUrl('articleLive'),
  294.             $appurl$this->generateUrl('video-podcast'),
  295.             $appurl$this->generateUrl('offer.index'),
  296.             $appurl$this->generateUrl('contact.form'),
  297.             $appurl$this->generateUrl('auth.login'),
  298.             $appurl$this->generateUrl('articles.recherche.view'),
  299.             $appurl."/page/abonnements",
  300.             $appurl."/page/mentions-legales",
  301.         ];
  302.         $urls array_merge($urls$urlCategories);
  303.         return $this->render('sitemaps/sitemap.xml.twig', [
  304.             'articles' => $articles,
  305.             'urls' => $urls,
  306.             'dailyChanges' => $dailyChanges,
  307.             'urlCategories' => $urlCategories,
  308.         ]);
  309.     }
  310.     /**
  311.      * @Route("/sitemap-images.xml", name="sitemap_images", defaults={"_format"="xml"})
  312.      */
  313.     public function sitemapImages(ArticleEntityService $articleEntityService)
  314.     {
  315.         $articleRepository $this->getDoctrine()->getRepository(Article::class);
  316.         $articles $articleEntityService->formatAll($articleRepository->getLiveArticles(null50));
  317.         return $this->render('sitemaps/sitemap-images.xml.twig', [
  318.             'articles' => $articles,
  319.         ]);
  320.     }
  321.     /**
  322.      * @Route("/sitemap-news.xml", name="sitemap_news", defaults={"_format"="xml"})
  323.      */
  324.     public function sitemapNews(ArticleEntityService $articleEntityService)
  325.     {
  326.         $articleRepository $this->getDoctrine()->getRepository(Article::class);
  327.         $articles $articleEntityService->formatAll($articleRepository->getLiveArticles(null50));
  328.         return $this->render('sitemaps/sitemap-news.xml.twig', [
  329.             'articles' => $articles,
  330.         ]);
  331.     }
  332.     /**
  333.      * @Route("/robots.txt", name="robots", defaults={"_format"="txt"})
  334.      */
  335.     public function robots()
  336.     {
  337.         return $this->render('robots.txt.twig');
  338.     }
  339.     /**
  340.      * @Route("/_captcha", name="captcha")
  341.      */
  342.     public function captcha(CaptchaService $captchaService)
  343.     {
  344.         return $this->json($captchaService->generate());
  345.     }
  346.     protected function getStaticPageStructure(StaticPage $pageStaticPageBlockEntityService $blockEntityService)
  347.     {
  348.         $blocks $blockEntityService->index($page);
  349.         usort($blocks, function ($a$b) {
  350.             return $a['position'] - $b['position'];
  351.         });
  352.         // BLOCK_HEADER sorting
  353.         $header null;
  354.         $types array_column($blocks'type');
  355.         if (\in_array('STATIC_PAGE_BLOCK_HEADER'$typestrue)) {
  356.             $header_key array_search('STATIC_PAGE_BLOCK_HEADER'$typestrue);
  357.             $header $blocks[$header_key]; // Retrieve BLOCK_HEADER
  358.             unset($blocks[$header_key]); // Remove it from the $blocks array
  359.             $blocks array_values($blocks); // Redindexing array
  360.             // Get children
  361.             $parent_id $header['id'];
  362.             $ids array_column($blocks'id');
  363.             $header_children_media = [];
  364.             foreach ($blocks as $block) {
  365.                 if ($block['parent'] === $parent_id && 'STATIC_PAGE_BLOCK_MEDIA' === $block['type']) {
  366.                     $child_id $block['id'];
  367.                     $child_key array_search($child_id$idstrue);
  368.                     unset($blocks[$child_key]); // Remove child from $blocks array
  369.                     $header_children_media[] = $block['media']['file']; // Retrieve BLOCK_HEADER's media children
  370.                 }
  371.             }
  372.             $header['media'] = $header_children_media;
  373.         }
  374.         $blocks array_map(function ($block) {
  375.             $block['data'] = @json_decode($block['data'], true);
  376.             if (!\is_array($block['data'])) {
  377.                 $block['data'] = [];
  378.             }
  379.             return $block;
  380.         }, $blocks);
  381.         return [
  382.             'blocks' => $blocks,
  383.             'block_header' => $header,
  384.         ];
  385.     }
  386.     /**
  387.      * @Route("/ads-txt-smilewanted-2021.txt", name="ads-txt-smilewanted-2021.txt", methods={"GET"})
  388.      * @Cache(expires="+1 day", public=true)
  389.      */
  390.     public function adText(PlatformService $platformService)
  391.     {
  392.         if ('aircosmos' !== $this->getParameter('app_slug')) {
  393.             return new Response("Vous n'êtes pas sur Air&Cosmos");
  394.         }
  395.         $txt file_get_contents($platformService->getRoot().'/public/assets/smileWanted/ads-txt-smilewanted-2021.txt');
  396.         $response = new Response(json_encode($txt));
  397.         $response->headers->set('Content-Type''text/plain');
  398.         $response->sendHeaders();
  399.         return $response;
  400.     }
  401.     /**
  402.      * @Route("/ads.txt", name="ads.txt", methods={"GET"})
  403.      */
  404.     public function adsText(PlatformService $platformServiceStorageService $storageService)
  405.     {
  406.         if ('aircosmos' !== $this->getParameter('app_slug')) {
  407.             return new Response("Vous n'êtes pas sur Air&Cosmos"404);
  408.         }
  409.         $localFilePath $this->appKernel->getProjectDir().'/var/data/ads.txt';
  410.         if (file_exists($localFilePath)) {
  411.             @unlink($localFilePath);
  412.         }
  413.         $storageService->retrieve('platform/ads.txt'$localFilePath);
  414.         $txt file_get_contents($this->appKernel->getProjectDir().'/var/data/ads.txt');
  415.         $ads_txt_themoneytizer file_get_contents('https://www.themoneytizer.com/ads.txt?id=85376');
  416.         if (empty($ads_txt_themoneytizer)) {
  417.             $ch curl_init();
  418.             curl_setopt($ch, \CURLOPT_RETURNTRANSFER1);
  419.             curl_setopt($ch, \CURLOPT_URL'https://www.themoneytizer.com/ads.txt?id=85376');
  420.             $ads_txt_themoneytizer curl_exec($ch);
  421.             curl_close($ch);
  422.         }
  423.         $txt $txt."\n".$ads_txt_themoneytizer;
  424.         $response = new Response($txt);
  425.         $response->headers->set('Content-Type''text/plain');
  426.         $response->sendHeaders();
  427.         return $response;
  428.     }
  429.     /**
  430.      * @Route("/forgot-pwd-modal", name="forgot-pwd-modal")
  431.      */
  432.     public function forgot_pwd_modal(): Response
  433.     {
  434.         $builder $this->createFormBuilder()
  435.             ->add('email'EmailType::class, [
  436.                 'constraints' => [
  437.                     new NotBlank(),
  438.                     new Email(),
  439.                 ],
  440.             ]);
  441.         $form $builder->getForm();
  442.         return $this->render('_partials/login/forgot_password_modal.html.twig', ['form' => $form->createView()]);
  443.     }
  444.     /**
  445.      * @Route("/login-modal", name="login-modal")
  446.      */
  447.     public function login_modal(Request $request): Response
  448.     {
  449.         $builder $this->createFormBuilder()
  450.             ->add('email'EmailType::class, [
  451.                 'constraints' => [
  452.                     new NotBlank(),
  453.                     new Email(),
  454.                 ],
  455.                 'attr' => [
  456.                     'class' => 'auth-form-input',
  457.                 ],
  458.             ])
  459.             ->add('password'PasswordType::class, [
  460.                 'constraints' => [
  461.                     new NotBlank(),
  462.                 ],
  463.                 'attr' => [
  464.                     'class' => 'auth-form-input',
  465.                 ],
  466.             ])
  467. //            ->add('recaptcha', EWZRecaptchaV3Type::class, [
  468. //                'action_name' => 'auth_register',
  469. //                'mapped' => false,
  470. //                'constraints' => [
  471. //                    new IsTrueV3(),
  472. //                ],
  473. //            ])
  474.         ;
  475.         $form $builder->getForm();
  476.         return $this->render('_partials/login/login-modal.html.twig', ['form' => $form->createView()]);
  477.     }
  478.     /**
  479.      * @Route("/auth/creation-compte", name="creation-compte")
  480.      */
  481.     public function register_modal(Request $requestUserService $userServiceEntityManagerInterface $entityManagerMailerInterface $symfonyMailer,ValidatorInterface $validator)
  482.     {
  483.         $user = new User();
  484.         $form $this->createForm(RegisterType::class, $user);
  485.         $form->handleRequest($request);
  486.         if ($request->isXmlHttpRequest()) {
  487.             $data json_decode($request->getContent());
  488.             $email $data->email;
  489.             $violations $validator->validate($email, [
  490.                 new Assert\NotBlank(),
  491.                 new Assert\Email(),
  492.             ]);
  493.             $user_exist $entityManager->getRepository(User::class)->findOneBy(['email' => $email]);
  494.             if ($user_exist ) {
  495.                 return $this->json(['errors' => 'error','motif'=>'exist'], 500);
  496.             } if ( !== \count($violations)) {
  497.                 return $this->json(['errors' => 'error','motif'=>'invalid'], 500);
  498.             }
  499.             return $this->json(['success' => 'ok'], 200);
  500.         }
  501.         $sender $this->getParameter('mailer_from_address');
  502.         if ($form->isSubmitted() && $form->isValid()) {
  503.             $email $form->get('email')->getData();
  504.             $user_exist $entityManager->getRepository(User::class)->findOneBy(['email' => $email]);
  505.             if ($this->hasNumbers($form->getData()->getFirstname()) && $this->hasNumbers($form->getData()->getLastname())) {
  506.                 $this->addFlash('error''les données ne sont pas valides');
  507.                 return $this->render('_partials/register/register-confirm.html.twig', [
  508.                     'form' => $form->createView(), 'email' => $email,
  509.                 ]);
  510.             } else {
  511.                 if (!$user_exist) {
  512.                     $user $userService->createUser_new($form->getData());
  513.                     $userService->sendActivationEmail($user$sender$symfonyMailer);
  514.                     $session $request->getSession();
  515.                     $price_id $session->get('price_id');
  516.                     if ($price_id && $user->getActivatedAt()) {
  517.                         return $this->redirectToRoute('products.details', ['price_id' => $price_id]);
  518.                     }
  519.                     $article_id $session->get('article_id');
  520.                     $article_slug $session->get('article_slug');
  521.                     if ($article_id && $article_slug && $user->getActivatedAt()) {
  522.                         return $this->redirectToRoute('article.view', ['id' => $article_id'slug' => $article_slug]);
  523.                     }
  524.                     return $this->render('_partials/register/register-confirm.html.twig', [
  525.                         'form' => $form->createView(), 'email' => $email,
  526.                     ]);
  527.                 }
  528.         }
  529.             return $this->redirectToRoute('homepage');
  530.         }
  531.         return $this->render('_partials/register/register-modal.html.twig', [
  532.             'form' => $form->createView(),
  533.         ]);
  534.     }
  535.     /**
  536.      * @Route("/resend-email/{email}", name="resend-email")
  537.      */
  538.     public function resend_email($emailUserService $userServiceEntityManagerInterface $manager MailerInterface $symfonyMailer)
  539.     {
  540.         $sender $this->getParameter('mailer_from_address');
  541.         $user $manager->getRepository(User::class)->findOneBy(['email' => $email]);
  542.         $userService->sendActivationEmail($user$sender$symfonyMailer);
  543.         return $this->render('_partials/register/register-confirm.html.twig', [
  544.             'email' => $email,
  545.         ]);
  546.     }
  547.     /**
  548.      * @Route("/like-comment", name="like-comment")
  549.      */
  550.     public function like_comment(Request $requestLikesService $likesServiceEntityManagerInterface $manager)
  551.     {
  552.         $user $this->getUser();
  553.         if ($request->isXmlHttpRequest()) {
  554.             $data json_decode($request->getContent());
  555.             $comment $manager->getRepository(Comment::class)->findOneBy(['id' => $data->data]);
  556.             if ($comment->isLikedByUser($user)) {
  557.                 $likesService->dislike($user$comment);
  558.                 return $this->json(['count' => \count($comment->getCommentLikes())], 200);
  559.             }
  560.             $likesService->like($user$comment);
  561.             return $this->json(['count' => \count($comment->getCommentLikes())], 200);
  562.         }
  563.         return $this->redirectToRoute('homepage');
  564.     }
  565.     /**
  566.      * @Route("/add-cart", name="add-cart")
  567.      */
  568.     public function add_to_cart(Request $requestCartService $cartServiceEntityManagerInterface $manager)
  569.     {
  570.         $user $this->getUser();
  571.         if ($request->isXmlHttpRequest()) {
  572.             if ($user) {
  573.                 $data json_decode($request->getContent());
  574.                 $product $manager->getRepository(StripeProduct::class)->findOneBy(['stripe_id' => $data->data]);
  575.                 if ($product) {
  576.                     $cartService->addProductToCart($user$product);
  577.                     return $this->json(['success' => 'ok'], 200);
  578.                 }
  579.             }
  580.         }
  581.         return $this->redirectToRoute('homepage');
  582.     }
  583.     /**
  584.      * @Route("/add-cart/{stripe_id}", name="add-to-cart")
  585.      */
  586.     public function addProductToCart(Request $requestCartService $cartServiceEntityManagerInterface $manager$stripe_id)
  587.     {
  588.         /** @var User $user */
  589.         $user $this->getUser();
  590.         if ($request->isXmlHttpRequest()) {
  591.             $product $manager->getRepository(StripeProduct::class)->findOneBy(['stripe_id' => $stripe_id]);
  592.             if ($user && $product) {
  593.                 $cartService->addProductToCart($user$product);
  594.                 return $this->json(['success' => 'ok'], 200);
  595.             }
  596.         }
  597.         return $this->redirectToRoute('homepage');
  598.     }
  599.     /**
  600.      * @Route("/add-favorites", name="add-favorites")
  601.      */
  602.     public function add_to_favorites(Request $requestFavoriteService $favoriteServiceEntityManagerInterface $manager)
  603.     {
  604.         /** @var User $user */
  605.         $user $this->getUser();
  606.         $productiD $request->get('product');
  607.         $product $manager->getRepository(StripeProduct::class)->findOneBy(['stripe_id' => $productiD]);
  608.         if ($request->isXmlHttpRequest()) {
  609.             if ($product && $user) {
  610.                 $favoriteService->addProductToFavorite($user$product);
  611.                 return $this->json(['success' => 'ok''action' => 'add'], 200);
  612.             }
  613.         }
  614.         return $this->redirectToRoute('homepage');
  615.     }
  616.     /**
  617.      * @Route("/remove-from-favorites", name="remove-from-favorites")
  618.      */
  619.     public function remove_from_favorites(Request $requestFavoriteService $favoriteServiceEntityManagerInterface $manager)
  620.     {
  621.         /** @var User $user */
  622.         $user $this->getUser();
  623.         $productiD $request->get('product');
  624.         $product $manager->getRepository(StripeProduct::class)->findOneBy(['stripe_id' => $productiD]);
  625.         if ($request->isXmlHttpRequest()) {
  626.             if ($product && $user) {
  627.                 $favoriteService->removeProductFromFavorite($user$product);
  628.                 return $this->json(['success' => 'ok''action' => 'remove'], 200);
  629.             }
  630.         }
  631.         return $this->redirectToRoute('homepage');
  632.     }
  633.     /**
  634.      * @Route("/remove-from-cart", name="remove-from-cart")
  635.      */
  636.     public function remove_from_cart(Request $requestEntityManagerInterface $manager):Response
  637.     {
  638.         /** @var User $user */
  639.         $user $this->getUser();
  640.         $productiD $request->get('product');
  641.         $product $manager->getRepository(StripeProduct::class)->findOneBy(['stripe_id' => $productiD]);
  642.         $id $product->getId();
  643.         if ($request->isXmlHttpRequest()) {
  644.             if ($product && $user) {
  645.                 $itemID $manager->getRepository(Card::class)->findCardItem($user $id);
  646.                 $item $manager->getRepository(CardItem::class)->findOneBy(['id' => $itemID[0]['id']]);
  647.                 $quantity $item->getQuantity();
  648.                 $manager->remove($item);
  649.                 $manager->flush();
  650.                 return $this->json([
  651.                     'success' => 'ok',
  652.                     'action' => 'remove',
  653.                     'quantity' => $quantity
  654.                 ], 200);
  655.             }
  656.         }
  657.         return new Response("ok");
  658.     }
  659.     /**
  660.      * @Route("/add-article-favorites", name="add-article-favorites")
  661.      */
  662.     public function add_article_to_favorites(Request $requestFavoriteService $favoriteServiceEntityManagerInterface $manager)
  663.     {
  664.         if ($request->isXmlHttpRequest()) {
  665.             $articleId $request->get('article');
  666.             $article $articleId $manager->getRepository(Article::class)->find($articleId): null;
  667.             if ($article) {
  668.                 /** @var User $user */
  669.                 $user $this->getUser();
  670.                 $favoriteService->addArticleToFavorite($user$article);
  671.                 return $this->json(['success' => 'ok''action' => 'add'], 200);
  672.             }
  673.         }
  674.         return $this->redirectToRoute('homepage');
  675.     }
  676.     /**
  677.      * @Route("/remove-article-from-favorites", name="remove-article-from-favorites")
  678.      */
  679.     public function remove_article_from_favorites(Request $requestFavoriteService $favoriteServiceEntityManagerInterface $manager)
  680.     {
  681.         if ($request->isXmlHttpRequest()) {
  682.             $articleId $request->get('article');
  683.             $article $articleId $manager->getRepository(Article::class)->find($articleId): null;
  684.             if ($article) {
  685.                 /** @var User $user */
  686.                 $user $this->getUser();
  687.                 $favoriteService->removeArticleFromFavorite($user$article);
  688.                 return $this->json(['success' => 'ok''action' => 'remove'], 200);
  689.             }
  690.         }
  691.         return $this->redirectToRoute('homepage');
  692.     }
  693. //    public function defaultThumbnail($articles, $container, $em, $entityService, $temp_dir)
  694. //    {
  695. //        foreach ($articles as $article) {
  696. //            if(!$article->getCover()->getThumbnail()){
  697. //                $a=$container->get('kernel')->getProjectDir()."/public/assets/images/theme-5/air_cosmos.jpg";
  698. //                $entityD=$em->getRepository(Media::class)->find($article->getCover()->getId());
  699. //                $fileD=$temp_dir."/".rand(0,999)."--defaultThumbail.jpg";
  700. //
  701. //                $content = file_get_contents($a);
  702. //                file_put_contents($fileD, $content);
  703. //                $uploadedFileD = new \Symfony\Component\HttpFoundation\File\UploadedFile(
  704. //                    $fileD,
  705. //                    basename($fileD),
  706. //                    mime_content_type($fileD),
  707. //                    filesize($fileD),
  708. //                    false,
  709. //                    true
  710. //                );
  711. //
  712. //                $entityService->postValidateThumbnailDefault($entityD, $uploadedFileD);
  713. //                $em->persist($entityD);
  714. //                $article->setCover($entityD);
  715. //                $em->persist($article);
  716. //                $em->flush();
  717. //                @unlink($fileD);
  718. //            }
  719. //        }
  720. //    }
  721.     private function hasNumbers($str) {
  722.         return preg_match('/\d/'$str) === 1;
  723.     }
  724. }