src/Controller/Forum/ForumController.php line 450

Open in your IDE?
  1. <?php
  2. namespace App\Controller\Forum;
  3. use App\Entity\Commentaires;
  4. use App\Entity\Publications;
  5. use App\Entity\Reactions;
  6. use App\Entity\User;
  7. use App\Form\CommentairesType;
  8. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  9. use Symfony\Component\HttpFoundation\Response;
  10. use Symfony\Component\Routing\Annotation\Route;
  11. use Symfony\Component\HttpFoundation\Request;
  12. use Doctrine\Persistence\ManagerRegistry;
  13. use App\Form\PublicationsType;
  14. use App\Repository\PublicationsRepository;
  15. use App\Repository\ReactionsRepository;
  16. use Symfony\Component\HttpFoundation\Session\SessionInterface
  17. use Symfony\Component\HttpFoundation\RedirectResponse;
  18. use App\Service\UploadImg;
  19. use App\Repository\CommentairesRepository;
  20. use Symfony\Component\Form\FormError;
  21. use Doctrine\ORM\EntityManagerInterface;
  22. use Symfony\Component\HttpFoundation\JsonResponse;
  23. use Symfony\Component\HttpFoundation\File\UploadedFile;
  24. use App\Repository\UserRepository;
  25. use App\Service\OpenAIService;
  26. use App\Service\UserSessionManager;
  27. class ForumController extends AbstractController
  28. {
  29.     private $userSession;
  30.     public function __construct(UserSessionManager $userSession
  31.     {
  32.         $this->userSession $userSession;
  33.        
  34.     }
  35.     public function index(Request $requestReactionsRepository $reactionsRepositoryManagerRegistry $managerUserRepository $userRepositoryPublicationsRepository $rep,OpenAIService $openAIServiceCommentairesRepository $commentairesRepositoryUploadImg $imageUploader): Response
  36.     {
  37.         
  38.         $formResponse $this->addPublication($request$manager,$openAIService$userRepository,$rep,$imageUploader);
  39.         if ($formResponse !== null) {
  40.             return $formResponse
  41.         }
  42.         $form $this->createForm(PublicationsType::class, new Publications());
  43.         $form->handleRequest($request);
  44.         $searchTerm $request->query->get('searchTerm'); 
  45.         if ($searchTerm !== null) {
  46.             $publications $rep->searchPublicationsWithUserDetails($searchTerm);
  47.         } else {
  48.             $publications $this->getAllPublications($rep);
  49.         }
  50.         $user =$this->userSession->getCurrentUser(); 
  51.         $contributors $this->getContributors($rep);
  52.         foreach ($publications as $pub) {
  53.             $commentForm $this->createForm(CommentairesType::class, new Commentaires(), [
  54.                 'action' => $this->generateUrl('home_forum_add_comment', ['idPub' => $pub->getId()]), // Adjust 'your_route_to_handle_comment' and 'idPub' as necessary
  55.             ]);
  56.             $commentForms[$pub->getId()] = $commentForm->createView();
  57.             $commentForm->get('returnPath')->setData('index');
  58.             
  59.         }
  60.         $filter $request->query->get('filter');
  61.         switch ($filter) {
  62.             case 'myPublications':
  63.                 $publications $rep->findPubByUserId($user->getId());
  64.                 break;
  65.             case 'populaire':
  66.                 $publications array_filter($rep->findAllPublicationsOrderedByClicks(), function($pub) {
  67.                     return $pub->getNbClicks() !== null
  68.                 });
  69.                 break;
  70.             case'mostLiked':
  71.                 $publications=$rep->findAllPublicationsOrderedByJaime();
  72.                 break;
  73.             case'mostDisliked':
  74.                 $publications=$rep->findAllPublicationsOrderedByDislike();
  75.                 break;
  76.             default:
  77.                 $publications $this->getAllPublications($rep);
  78.                 break;
  79.         }
  80.         $reactionsSummary $reactionsRepository->findReactionsSummary();
  81.         $reactionsByPubId = [];
  82.         foreach ($reactionsSummary as $reaction) {
  83.             $reactionsByPubId[$reaction['pubId']] = [
  84.                 'jaime' => $reaction['totalJaime'],
  85.                 'dislike' => $reaction['totalDislike']
  86.             ];
  87.         }
  88.         $userReactions $reactionsRepository->findBy(['user' => $user]);
  89.         $userReactionsMap = [];
  90.         foreach ($userReactions as $reaction) {
  91.             if ($reaction->getJaime() === 1) {
  92.                 $userReactionsMap[$reaction->getPub()->getId()] = 'like';
  93.             } elseif ($reaction->getDislike() === 1) {
  94.                 $userReactionsMap[$reaction->getPub()->getId()] = 'dislike';
  95.             }
  96.         }
  97.         foreach ($publications as $pub) {
  98.             $pubId $pub->getId();
  99.             $pub->userReaction $userReactionsMap[$pubId] ?? null;
  100.         }
  101.         if ($form->isSubmitted() && !$form->isValid()) {
  102.         return $this->render('home/forum/index.html.twig', [
  103.             'controller_name' => 'ForumController',
  104.             'forumPub' => $form->createView(),
  105.             'pubs' => $publications,
  106.             'user' => $user,
  107.             'contributors' => $contributors,
  108.             'commentForms' => $commentForms,
  109.             'reactionsByPubId' => $reactionsByPubId,
  110.             'userReactionsMap' => $userReactionsMap
  111.         ]);
  112.     }
  113.         return $this->render('home/forum/index.html.twig', [
  114.             'controller_name' => 'ForumController',
  115.             'forumPub' => $form->createView(),
  116.             'pubs' => $publications,
  117.             'user' => $user,
  118.             'contributors' => $contributors,
  119.             'commentForms' => $commentForms,
  120.             'reactionsByPubId' => $reactionsByPubId,
  121.             'userReactionsMap' => $userReactionsMap
  122.         ]);
  123.     }
  124.    
  125.     //----------------------------------------------------------------------------------//
  126.     public function getAllPublications(PublicationsRepository $rep)
  127.     {
  128.        return $rep->findAllPublicationsWithUserDetails();
  129.        
  130.     }
  131.     //----------------------------------------------------------------------------------//
  132.     public function addPublication(Request $requestManagerRegistry $manager,OpenAIService $openAIServiceUserRepository $userRepository,$publicationsRepositoryUploadImg $imageUploader): ?Response
  133.     {
  134.         $form $this->createForm(PublicationsType::class, new Publications());
  135.         $form->handleRequest($request);
  136.         if ($form->isSubmitted() && $form->isValid()) {
  137.             $em $manager->getManager();
  138.             $publication $form->getData();
  139.             $images $form->get('images')->getData();
  140.             
  141.             if (!empty($images)) {
  142.                 $files array_filter($images, function ($image) {
  143.                     return $image instanceof UploadedFile;
  144.                 });
  145.         
  146.                 $uploadResult $imageUploader->uploadMultiple($files); 
  147.                 $publication->setImages($uploadResult);
  148.             }
  149.             $publication->setDateCreation(new \DateTime());
  150.             
  151.             $user $userRepository->find($this->userSession->getCurrentUser()->getId());
  152.             $user18=$user->getId();
  153.             if (!$user18) {
  154.                 throw $this->createNotFoundException('No user found ');
  155.             }
  156.             $publication->setUser($user);
  157.             $existingPublication $publicationsRepository->findExistingPublication(
  158.                 $user->getId(),
  159.                 $publication->getTitre(),
  160.                 $publication->getContenu()
  161.             );
  162.             
  163.             if ($existingPublication) {
  164.                 $this->addFlash('danger''A publication with the same title and content already exists.');
  165.                 return $this->redirectToRoute('home_forum_index'); // Adjust the route name accordingly
  166.             }
  167.             $publicationText $publication->getTitre() . " - " $publication->getContenu();
  168.             if ($openAIService->checkContent($publicationText)) {
  169.                 $this->addFlash('danger''Your publication contains inappropriate content and cannot be added.');
  170.                 return $this->redirectToRoute('home_forum_index');
  171.             }
  172.            
  173.             $em->persist($publication);
  174.             $em->flush();
  175.             $this->addFlash('success''Publication added successfully.');
  176.             return $this->redirectToRoute('home_forum_index');
  177.         }
  178.         return null
  179.     }
  180. //----------------------------------------------------------------------------------//
  181.  public function getContributors(PublicationsRepository $publicationsRepository)
  182.  {
  183.     return  $publicationsRepository->findDistinctContributors();
  184.  
  185.  }
  186.  
  187.   //----------------------------------------------------------------------------------//
  188.   public function deletePublication(ManagerRegistry $manager,$idPub,PublicationsRepository $rep)
  189.   {
  190.        $PUB=$rep->find($idPub);
  191.        $em=$manager->getManager();
  192.        $em->remove($PUB);
  193.        $em->flush();
  194.       
  195.       return $this->redirectToRoute('home_forum_index');
  196.   }
  197.   //----------------------------------------------------------------------------------//
  198.   public function deleteComment(ManagerRegistry $manager$idCCommentairesRepository $repRequest $request)
  199.     {
  200.         $comment $rep->find($idC);
  201.         $em $manager->getManager();
  202.         $em->remove($comment);
  203.         $em->flush();
  204.         
  205.         $idPub $request->query->get('idPub');
  206.         if ($idPub !== null) {
  207.             return $this->redirectToRoute('home_forum_single_publication', ['idPub' => $idPub]);
  208.         } else {
  209.             return $this->redirectToRoute('home_forum_index');
  210.         }
  211.     }
  212. //----------------------------------------------------------------------------------//
  213. public function updateComment(Request $requestEntityManagerInterface $entityManagerCommentairesRepository $commentairesRepository): Response
  214. {
  215.     $commentId $request->request->get('commentId');
  216.     $newContent $request->request->get('comment');
  217.     $comment $commentairesRepository->find($commentId);
  218.     if (!$comment) {
  219.         return new JsonResponse(['error' => 'Comment not found'], 404);
  220.     }
  221.     $comment->setCommentaire($newContent);
  222.     $entityManager->flush();
  223.     return new JsonResponse(['success' => 'Comment updated']);
  224. }
  225. //----------------------------------------------------------------------------------//
  226. public function addComment(Request $requestManagerRegistry $managerUserRepository $userRepositoryPublicationsRepository $pubRep$idPub,OpenAIService $openAIService): ?Response
  227. {
  228.     $form $this->createForm(CommentairesType::class, new Commentaires());
  229.     $form->handleRequest($request);
  230.     if ($form->isSubmitted() && $form->isValid()) {
  231.         $em $manager->getManager();
  232.         $comment $form->getData();
  233.         $comment->setDate(new \DateTime());
  234.         $publication $pubRep->find($idPub);
  235.         if (!$publication) {
  236.             throw $this->createNotFoundException(sprintf('No publication found for ID %d'$idPub));
  237.         }
  238.         $comment->setIdPub($publication); 
  239.         $user $userRepository->find($this->userSession->getCurrentUser()->getId());
  240.         if (!$user) {
  241.             throw $this->createNotFoundException('No user found for ID 18');
  242.         }
  243.         $comment->setUser($user);
  244.         $commentText $comment->getCommentaire();
  245.         if ($openAIService->checkContent($commentText)) {
  246.             $this->addFlash('danger''Your comment contains inappropriate content and cannot be added.');
  247.             return $this->redirectToRoute('home_forum_index');
  248.         }
  249.         $em->persist($comment);
  250.         $em->flush();
  251.         $this->addFlash('success''Comment added successfully.');
  252.         $returnPath $form->get('returnPath')->getData(); 
  253.         if ($returnPath === 'index') {
  254.             return $this->redirectToRoute('home_forum_index');
  255.         } else {
  256.             return $this->redirectToRoute('home_forum_single_publication', ['idPub' => $idPub]);
  257.         }
  258.     }
  259.    
  260.     return null
  261. }
  262. //----------------------------------------------------------------------------------//
  263. public function single(PublicationsRepository $repReactionsRepository $reactionsRepository,OpenAIService $openAIServiceint $idPubRequest $requestManagerRegistry $managerUserRepository $userRepository): Response
  264. {
  265.     $formResponse $this->addComment($request$manager$userRepository$rep$idPub,$openAIService);
  266.     if ($formResponse !== null) {
  267.         return $formResponse;
  268.     }
  269.     $commentForm $this->createForm(CommentairesType::class, new Commentaires());
  270.     $commentForm->get('returnPath')->setData('single'); 
  271.     $publication $rep->findPublicationWithUserDetails($idPub);
  272.     $contributors $this->getContributors($rep);
  273.     $reactionsSummary $reactionsRepository->findReactionsSummary();
  274.     $reactionsByPubId = [];
  275.     foreach ($reactionsSummary as $reaction) {
  276.         $reactionsByPubId[$reaction['pubId']] = [
  277.             'jaime' => $reaction['totalJaime'],
  278.             'dislike' => $reaction['totalDislike']
  279.         ];
  280.     }    
  281.     $user $this->userSession->getCurrentUser(); 
  282.     $userReactions $reactionsRepository->findBy(['user' => $user]);
  283.     $userReactionsMap = [];
  284.     foreach ($userReactions as $reaction) {
  285.         if ($reaction->getJaime() === 1) {
  286.             $userReactionsMap[$reaction->getPub()->getId()] = 'like';
  287.         } elseif ($reaction->getDislike() === 1) {
  288.             $userReactionsMap[$reaction->getPub()->getId()] = 'dislike';
  289.         }
  290.     }
  291.     foreach ($publication as $pub) {
  292.         $pubId $pub->getId();
  293.         $pub->userReaction $userReactionsMap[$pubId] ?? null;
  294.     }
  295.     return $this->render('home/forum/single.html.twig', [
  296.         'controller_name' => 'ForumController',
  297.         'pub' => $publication,
  298.         'contributors' => $contributors,
  299.         'commentForm' => $commentForm->createView(),
  300.         'reactionsByPubId' => $reactionsByPubId,
  301.         'userReactionsMap' => $userReactionsMap
  302.         'user' => $user,
  303.     ]);
  304. }
  305. //----------------------------------------------------------------------------------//
  306. public function updatePublication(Request $requestEntityManagerInterface $emPublicationsRepository $rep$idPub): Response
  307. {
  308.     if ($request->isXmlHttpRequest()) {
  309.         $data json_decode($request->getContent(), true);
  310.         $publication $rep->find($idPub);
  311.         if ($publication) {
  312.             $publication->setTitre($data['titre']);
  313.             $publication->setContenu($data['contenu']);
  314.             
  315.             $em->persist($publication);
  316.             $em->flush();
  317.             return new RedirectResponse($this->generateUrl('home_forum_index'));
  318.         }
  319.         return new JsonResponse(['status' => 'error''message' => 'Publication not found']);
  320.     }
  321. }
  322. //----------------------------------------------------------------------------------//
  323. public function edit(Request $request,ManagerRegistry $managerPublicationsRepository $repint $idPub): Response
  324. {
  325.     $publication $rep->findPublicationWithUserDetails($idPub);
  326.     $em$manager->getManager();
  327.     $form=$this->createForm(PublicationsType::class,$publication);
  328.     $form->handleRequest($request);
  329.         if ($form->isSubmitted()){
  330.             $em->flush();
  331.             return $this->redirectToRoute('home_forum_index');
  332.         }
  333.         $content $this->renderView('home/components/forum/editForum_popup.html.twig', ['pub' => $publication,'formUp'=>$form]);
  334.         return new Response($content);
  335.     
  336. }
  337. public function reactToPublication($pubId$reactionTypeReactionsRepository $reactionsRepositoryManagerRegistry $managerPublicationsRepository $publicationsRepositoryUserRepository $userRepository): Response
  338. {
  339.     $entityManager $manager->getManager();
  340.     $user $userRepository->find($this->userSession->getCurrentUser()->getId());
  341.     $publication $publicationsRepository->find($pubId);
  342.     if (!$publication || !$user) {
  343.         return $this->redirectToRoute('home_forum_index');
  344.     }
  345.     $reaction $reactionsRepository->findOneBy(['pub' => $publication'user' => $user]);
  346.     if ($reaction) {
  347.         if (($reactionType === 'like' && $reaction->getJaime() === 1) || ($reactionType === 'dislike' && $reaction->getDislike() === 1)) {
  348.             $entityManager->remove($reaction);
  349.         } else {
  350.             if ($reactionType === 'like') {
  351.                 $reaction->setJaime(1);
  352.                 $reaction->setDislike(0);
  353.             } else {
  354.                 $reaction->setJaime(0);
  355.                 $reaction->setDislike(1);
  356.             }
  357.             $entityManager->persist($reaction);
  358.         }
  359.     } else {
  360.         $reaction = new Reactions();
  361.         $reaction->setPub($publication);
  362.         $reaction->setUser($user);
  363.         if ($reactionType === 'like') {
  364.             $reaction->setJaime(1);
  365.             $reaction->setDislike(0);
  366.         } else {
  367.             $reaction->setJaime(0);
  368.             $reaction->setDislike(1);
  369.         }
  370.         $entityManager->persist($reaction);
  371.     }
  372.     $entityManager->flush();
  373.     return $this->redirectToRoute('home_forum_index');
  374. }
  375. //----------------------------------------------------------------------------------//
  376. public function incrementClick(EntityManagerInterface $entityManager$pubId): Response
  377. {
  378.     $publication $entityManager->getRepository(Publications::class)->find($pubId);
  379.     if (!$publication) {
  380.         return $this->json(['error' => 'Publication not found'], 404);
  381.     }
  382.     $currentClicks $publication->getNbclicks();
  383.     $publication->setNbclicks($currentClicks 1);
  384.     $entityManager->flush(); 
  385.     return $this->json(['success' => true]);
  386. }
  387. //---------------------------------------------------------------------------------//
  388.     public function chatBotIndex(Request $requestUserRepository $userRepository): Response
  389.     {
  390.         $user $this->userSession->getCurrentUser(); 
  391.     
  392.         $userImage null;
  393.         if ($user && $user->getImage()) {
  394.             $userImage $user->getImage(); 
  395.         }
  396.     
  397.         return $this->render('home/forum/chatbot.html.twig', [
  398.             'userImage' => $userImage,
  399.         ]);
  400.     }
  401.     
  402.  
  403. //----------------------------------------------------------------------------------//
  404.  
  405.    
  406.   public function chatBotAction(Request $requestOpenAIService $openAIServiceSessionInterface $session): JsonResponse {
  407.     if ($request->isXmlHttpRequest()) {
  408.         $data json_decode($request->getContent(), true);
  409.         $userMessage $data['message'] ?? '';
  410.         $history $session->get('chat_history', []);
  411.         $responseMessage $openAIService->getChatResponse($userMessage$history);
  412.         
  413.         $history[] = ['role' => 'user''content' => $userMessage];
  414.         $history[] = ['role' => 'assistant''content' => $responseMessage]; 
  415.         $session->set('chat_history'$history);
  416.         return new JsonResponse(['message' => $responseMessage]);
  417.     }
  418.     return new JsonResponse(['error' => 'Invalid request type'], Response::HTTP_BAD_REQUEST);
  419. }
  420. public function deleteImageAction(ManagerRegistry $managerRequest $request$publicationIdPublicationsRepository $rep): Response
  421. {
  422.     $data json_decode($request->getContent(), true);
  423.     $imageUrl $data['image']; 
  424.     
  425.     $entityManager $manager->getManager();
  426.     $publication $rep->find($publicationId);
  427.     
  428.     if (!$publication) {
  429.         throw $this->createNotFoundException('Publication not found');
  430.     }
  431.     $currentImages $publication->getImages();
  432.     $updatedImages array_filter($currentImages, function ($image) use ($imageUrl) {
  433.         return $image !== $imageUrl;
  434.     });
  435.     $publication->setImages($updatedImages);
  436.     $entityManager->persist($publication);
  437.     $entityManager->flush();
  438.     return $this->json(['status' => 'success']);
  439. }
  440. }