src/Controller/FileController.php line 354

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\File;
  4. use App\Entity\PSA;
  5. use App\Repository\FileRepository;
  6. use App\Repository\LangRepository;
  7. use App\Repository\PSARepository;
  8. use App\Repository\SiteRepository;
  9. use App\Services\WebserviceUtils;
  10. use CURLFile;
  11. use Doctrine\ORM\EntityManagerInterface;
  12. use Exception;
  13. use PrestaShopWebservice;
  14. use PrestaShopWebserviceException;
  15. use Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted;
  16. use SimpleXMLElement;
  17. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  18. use Symfony\Component\HttpFoundation\BinaryFileResponse;
  19. use Symfony\Component\HttpFoundation\File\Exception\FileException;
  20. use Symfony\Component\HttpFoundation\JsonResponse;
  21. use Symfony\Component\HttpFoundation\Request;
  22. use Symfony\Component\HttpFoundation\Response;
  23. use Symfony\Component\Routing\Annotation\Route;
  24. use Symfony\Component\Security\Core\Security;
  25. use Symfony\Component\String\Slugger\SluggerInterface;
  26. use Symfony\Contracts\Translation\TranslatorInterface;
  27. #[Route('/file'name'app_file')]
  28. #[IsGranted("ROLE_USER")]
  29. class FileController extends AbstractController
  30. {
  31.     public function __construct(Security $securityTranslatorInterface $translator)
  32.     {
  33.         $this->twigData = [];
  34.         $this->translator $translator;
  35.         $this->security $security;
  36.         $this->twigData = [
  37.             'user' => $security->getUser(),
  38.         ];
  39.     }
  40.     #[Route('/'name'_index')]
  41.     public function index(FileRepository $fileRepositoryLangRepository $langRepository): Response
  42.     {
  43.         $this->breadcrumb[0]['name'] = $this->translator->trans('page.catalog.Catalog');
  44.         $this->breadcrumb[0]['link'] = $this->generateUrl('app_catalog_index');
  45.         $this->breadcrumb[0]['last'] = false;
  46.         $this->breadcrumb[1]['name'] = $this->translator->trans('page.files.Files');
  47.         $this->breadcrumb[1]['last'] = true;
  48.         $this->twigData['breadcrumb'] = $this->breadcrumb;
  49.         $langs $langRepository->findAll();
  50.         $this->twigData['langs'] = $langs;
  51.         $this->twigData['files'] = $fileRepository->findAll();
  52.         return $this->render('files/index.html.twig'$this->twigData);
  53.     }
  54.     #[Route('/new'name'_new'methods: ['GET''POST'])]
  55.     public function new(LangRepository $langRepository,SluggerInterface $sluggerFileRepository $fileRepositoryRequest $requestEntityManagerInterface $entityManagerPSARepository $PSARepository): Response
  56.     {
  57.         $this->breadcrumb[0]['name'] = $this->translator->trans('page.catalog.Catalog');
  58.         $this->breadcrumb[0]['link'] = $this->generateUrl('app_catalog_index');
  59.         $this->breadcrumb[0]['last'] = false;
  60.         $this->breadcrumb[1]['name'] = $this->translator->trans('page.files.Files');
  61.         $this->breadcrumb[1]['link'] = $this->generateUrl('app_file_index');
  62.         $this->breadcrumb[1]['last'] = false;
  63.         $this->breadcrumb[2]['name'] = $this->translator->trans('page.files.new');
  64.         $this->breadcrumb[2]['last'] = true;
  65.         $this->twigData['breadcrumb'] = $this->breadcrumb;
  66.         $langs $langRepository->findAll();
  67.         $this->twigData['langs'] = $langs;
  68.         $submit $request->get("submit");
  69.         if ($submit == 1) {
  70.             $file $request->files->get('file');
  71.             $langId $request->request->get('lang');
  72.             $lang $langRepository->find($langId);
  73.             if ($file) {
  74.                 $originalFilename pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME);
  75.                 // this is needed to safely include the file name as part of the URL
  76.                 $safeFilename $slugger->slug($originalFilename);
  77.                 $newFilename $safeFilename.'-'.uniqid().'_'.$lang->getICU().'.'.$file->guessExtension();
  78.                 
  79.                 // Move the file to the directory where product file are stored
  80.                 try {
  81.                     $file->move(
  82.                         $this->getParameter('file_directory'),
  83.                         $newFilename
  84.                     );
  85.                     $fileNameDisplay $request->request->get('name');
  86.                     $fileDescription $request->request->get('description');
  87.                     $file = new File();
  88.                     $file->setName($newFilename);
  89.                     $file->setDescription($fileDescription);
  90.                     $file->setDisplayName($fileNameDisplay);
  91.                     $file->setLang($lang);
  92.                     $fileRepository->add($filetrue);
  93.                 } catch (FileException $e) {
  94.                     return new Response($eResponse::HTTP_INTERNAL_SERVER_ERROR);
  95.                 }
  96.             }
  97.             return $this->redirectToRoute('app_file_index', [], Response::HTTP_SEE_OTHER);
  98.         }
  99.         return $this->render('files/new.html.twig'$this->twigData);
  100.     }
  101.     #[Route('/{id}/edit'name'_edit'methods: ['GET''POST'])]
  102.     public function edit(File $file,LangRepository $langRepository,SluggerInterface $sluggerFileRepository $fileRepositoryRequest $requestEntityManagerInterface $entityManagerPSARepository $PSARepository): Response
  103.     {
  104.         $this->breadcrumb[0]['name'] = $this->translator->trans('page.catalog.Catalog');
  105.         $this->breadcrumb[0]['link'] = $this->generateUrl('app_catalog_index');
  106.         $this->breadcrumb[0]['last'] = false;
  107.         $this->breadcrumb[1]['name'] = $this->translator->trans('page.files.Files');
  108.         $this->breadcrumb[1]['link'] = $this->generateUrl('app_file_index');
  109.         $this->breadcrumb[1]['last'] = false;
  110.         $this->breadcrumb[2]['name'] = $this->translator->trans('page.files.edit');
  111.         $this->breadcrumb[2]['last'] = true;
  112.         $this->twigData['breadcrumb'] = $this->breadcrumb;
  113.         $langs $langRepository->findAll();
  114.         $this->twigData['langs'] = $langs;
  115.         $this->twigData['file'] = $file;
  116.         $submit $request->get("submit");
  117.         if ($submit == 1) {
  118.             $fileFile $request->files->get('file');
  119.             $langId $request->request->get('lang');
  120.             $lang $langRepository->find($langId);
  121.             if ($fileFile) {
  122.                 $originalFilename pathinfo($fileFile->getClientOriginalName(), PATHINFO_FILENAME);
  123.                 // this is needed to safely include the file name as part of the URL
  124.                 $safeFilename $slugger->slug($originalFilename);
  125.                 $newFilename $safeFilename.'-'.uniqid().'_'.$lang->getICU().'.'.$fileFile->guessExtension();
  126.                 
  127.                 // Move the file to the directory where product file are stored
  128.                 try {
  129.                     $fileFile->move(
  130.                         $this->getParameter('file_directory'),
  131.                         $newFilename
  132.                     );
  133.                     $file->setName($newFilename);
  134.                 } catch (FileException $e) {
  135.                     return new Response($eResponse::HTTP_INTERNAL_SERVER_ERROR);
  136.                 }
  137.             }
  138.             $fileNameDisplay $request->request->get('name');
  139.             $fileDescription $request->request->get('description');
  140.             $file->setDescription($fileDescription);
  141.             $file->setDisplayName($fileNameDisplay);
  142.             $file->setLang($lang);
  143.             $fileRepository->add($filetrue);
  144.             return $this->redirectToRoute('app_file_index', [], Response::HTTP_SEE_OTHER);
  145.         }
  146.         return $this->render('files/edit.html.twig'$this->twigData);
  147.     }
  148.     #[Route('/{id}'name'_delete'methods: ['POST'], requirements: ['id' => '\d+'])]
  149.     public function delete(Request $requestFile $fileEntityManagerInterface $entityManager): Response
  150.     {
  151.         if ($this->isCsrfTokenValid('delete'.$file->getId(), $request->request->get('_token'))) {
  152.             $pathToFile $this->getParameter('file_directory').'/'.$file->getName();
  153.             if (file_exists($pathToFile)) {
  154.                 unlink($pathToFile);
  155.             }
  156.             $entityManager->remove($file);
  157.             $entityManager->flush();
  158.         }
  159.         return $this->redirectToRoute('app_file_index', [], Response::HTTP_SEE_OTHER);
  160.     }
  161.     #[Route('/{id}/sync'name'_sync'methods: ['GET''POST'], requirements: ['id' => '\d+'])]
  162.     public function sync(File $fileEntityManagerInterface $entityManagerPSARepository $PSARepositorySiteRepository $siteRepository): Response
  163.     {
  164.         $debug false;
  165.         $sites $siteRepository->findAll();
  166.         foreach ($sites as $key => $site) {
  167.             if ($site->getId() == ) continue;
  168.             $url $site->getUrl();
  169.             $apiKey $site->getApiKey();
  170.             $webService = new PrestaShopWebservice($url$apiKey$debug);
  171.             $webServiceUtils = new WebserviceUtils($webService$url);
  172.             $langs $webServiceUtils->getSiteLangs();
  173.             $psaAttachment $PSARepository->findOneBy(['entityId'=> $file->getId(), "entityName"=>'attachments'"siteId"=>$site->getId()]);
  174.             if($psaAttachment != null){
  175.                 $file_path $this->getParameter('file_directory').'/'.$file->getName();
  176.                 $file_mime mime_content_type($file_path);
  177.                 // dd(filesize($file_path));
  178.                 $args['file'] = new CURLFile($file_path$file_mime$file->getDisplayName().'_'.$file->getLang()->getICU());
  179.                 try {
  180.                     $ch curl_init();
  181.                     curl_setopt($chCURLOPT_HEADERtrue);
  182.                     curl_setopt($chCURLINFO_HEADER_OUTtrue);
  183.                     curl_setopt($chCURLOPT_URL$url."/api/attachments/file/".$psaAttachment->getInSiteId());
  184.                     curl_setopt($chCURLOPT_POSTtrue);
  185.                     curl_setopt($chCURLOPT_USERPWD$apiKey);
  186.                     curl_setopt($chCURLOPT_POSTFIELDS$args);
  187.                     curl_setopt($chCURLOPT_RETURNTRANSFERtrue);
  188.                     
  189.                     $returnFile curl_exec($ch);
  190.                     if ($returnFile === false) {
  191.                         echo "cURL Error: " curl_error($ch);
  192.                     } else {
  193.                         $header_size curl_getinfo($chCURLINFO_HEADER_SIZE);
  194.                         $body substr($returnFile$header_size);
  195.                     
  196.                         // Check HTTP status code
  197.                         $http_code curl_getinfo($chCURLINFO_HTTP_CODE);
  198.                         if ($http_code == 200) {
  199.                             // Handle successful response
  200.                             $response json_decode($bodytrue); // Or use simplexml_load_string() for XML
  201.                     
  202.                             if (isset($response['attachment'])) {
  203.                                 // Process the attachment data
  204.                                 echo "Attachment uploaded successfully.";
  205.                             } else {
  206.                                 echo "Error: 'attachment' property not found in response.";
  207.                             }
  208.                         } else {
  209.                             dd($site$http_code);
  210.                         }
  211.                     }
  212.                     curl_close($ch);
  213.                     $returnFile $body;
  214.                     $returnFile simplexml_load_string($returnFile);
  215.                     // dump($returnFile);
  216.                     $returnFileId intval($returnFile->attachment[0]->id);
  217.                     
  218.                     $xmlAttachmentsResponse $webService->get(['url' => $url '/api/attachments/'.$returnFileId]);
  219.                     $attachmentsXml $xmlAttachmentsResponse->attachment[0];
  220.                     foreach ($langs as $keyLang => $lang) {
  221.                         $attachmentsXml->description->language[$keyLang] = $file->getDescription();
  222.                     }
  223.                     $optAttachment = ['resource' => 'attachments'];
  224.                     $optAttachment['putXml'] = $xmlAttachmentsResponse->asXML();
  225.                     $optAttachment['id'] = $returnFileId;
  226.                 } catch (\Throwable $th) {
  227.                     // dump($site);
  228.                     // dd($th);
  229.                     $errors[] = [
  230.                         'site' => $site->getName(),
  231.                         'error' => $th
  232.                     ]; 
  233.                 }
  234.                 
  235.                 if (isset($optAttachment)) {
  236.                     try {
  237.                         $returnAttachment $webService->edit($optAttachment);
  238.                     } catch (PrestaShopWebserviceException $th) {
  239.                         // dd($th);
  240.                         $errors[] = [
  241.                             'site' => $site->getName(),
  242.                             'error' => $th
  243.                         ]; 
  244.                     }
  245.                 }
  246.                 if (isset($returnFileId)) {
  247.                     $returnAttachmentId $returnFileId;
  248.                     $psaAttachment = new PSA();
  249.                     $psaAttachment->setEntityId($file->getId());
  250.                     $psaAttachment->setEntityName('attachments');
  251.                     $psaAttachment->setInSiteId($returnAttachmentId);
  252.                     $psaAttachment->setSiteId($site->getId());
  253.                     $PSARepository->add($psaAttachmenttrue);
  254.                 }
  255.             }else{
  256.                 $psaAttachment $PSARepository->findOneBy(['entityName' => "attachments"'entityId'=> $file->getId(), 'siteId'=> $site->getId()]);
  257.                 if ($psaAttachment == null) {
  258.                     $file_path $this->getParameter('file_directory').'/'.$file->getName();
  259.                     $file_mime mime_content_type($file_path);
  260.                     $file_name $file->getDisplayName().'_'.$file->getLang()->getICU();
  261.                     $file_name str_replace(' ''_'$file_name);
  262.                     // dd(filesize($file_path));
  263.                     //make file name length less than 32 by removing first characters
  264.                     if(strlen($file_name) > 32){
  265.                         $file_name substr($file_name, -3232);
  266.                     }
  267.                     $args['file'] = new CURLFile($file_path$file_mime$file_name);
  268.                     
  269.                     $ch curl_init();
  270.                     curl_setopt($chCURLOPT_HEADERtrue);
  271.                     curl_setopt($chCURLINFO_HEADER_OUTtrue);
  272.                     curl_setopt($chCURLOPT_URL$url."/api/attachments/file/");
  273.                     curl_setopt($chCURLOPT_POSTtrue);
  274.                     curl_setopt($chCURLOPT_USERPWD$apiKey);
  275.                     curl_setopt($chCURLOPT_POSTFIELDS$args);
  276.                     curl_setopt($chCURLOPT_RETURNTRANSFERtrue);
  277.                     
  278.                     $returnFile curl_exec($ch);
  279.                     if ($returnFile === false) {
  280.                         echo "cURL Error: " curl_error($ch);
  281.                     } else {
  282.                         $header_size curl_getinfo($chCURLINFO_HEADER_SIZE);
  283.                         $body substr($returnFile$header_size);
  284.                     
  285.                         // Check HTTP status code
  286.                         $http_code curl_getinfo($chCURLINFO_HTTP_CODE);
  287.                         if ($http_code == 200) {
  288.                             // Handle successful response
  289.                             $response json_decode($bodytrue); // Or use simplexml_load_string() for XML
  290.                     
  291.                             if (isset($response['attachment'])) {
  292.                                 // Process the attachment data
  293.                                 echo "Attachment uploaded successfully.";
  294.                             } else {
  295.                                 echo "Error: 'attachment' property not found in response.";
  296.                             }
  297.                         } else {
  298.                             dd($site$http_code);
  299.                         }
  300.                     }
  301.                     curl_close($ch);
  302.                     $returnFile $body;
  303.                     
  304.                     $returnFile simplexml_load_string($returnFile);
  305.                     $returnFileId intval($returnFile->attachment[0]->id);
  306.                     
  307.                     $xmlAttachmentsResponse $webService->get(['url' => $url '/api/attachments/'.$returnFileId]);
  308.                     $attachmentsXml $xmlAttachmentsResponse->attachment[0];
  309.                     foreach ($langs as $keyLang => $lang) {
  310.                         $attachmentsXml->description->language[$keyLang] = $file->getDescription();
  311.                     }
  312.                     $optAttachment = ['resource' => 'attachments'];
  313.                     $optAttachment['putXml'] = $xmlAttachmentsResponse->asXML();
  314.                     $optAttachment['id'] = $returnFileId;
  315.                     try {
  316.                         $returnAttachment $webService->edit($optAttachment);
  317.                     } catch (PrestaShopWebserviceException $th) {
  318.                         dd($th);
  319.                     }
  320.                     $returnAttachmentId $returnFileId;
  321.                     $psaAttachment = new PSA();
  322.                     $psaAttachment->setEntityId($file->getId());
  323.                     $psaAttachment->setEntityName('attachments');
  324.                     $psaAttachment->setInSiteId($returnAttachmentId);
  325.                     $psaAttachment->setSiteId($site->getId());
  326.                     $PSARepository->add($psaAttachmenttrue);
  327.                 } else {
  328.                     $xmlAttachmentsResponse $webService->get(['url' => $url '/api/attachments/'.$psaAttachment->getInSiteId()]);
  329.                 }
  330.             }
  331.         }
  332.         return $this->redirectToRoute('app_file_index', [], Response::HTTP_SEE_OTHER);
  333.     }
  334.     #[Route('/{fileName}'name'_display'methods:['GET'])]
  335.     public function display($fileNameRequest $requestSluggerInterface $sluggerFileRepository $fileRepository): Response
  336.     {
  337.         $file $fileRepository->findOneBy(['name'=>$fileName]);
  338.         $filename $this->getParameter('file_directory') . '/' $fileName;
  339.         if (file_exists($filename)) {
  340.             //return a new BinaryFileResponse with the file name
  341.             return new BinaryFileResponse($filename);
  342.         } else {
  343.             return new JsonResponse(null404);
  344.         }
  345.     }
  346. }