vendor/simpledot/edm-bundle/AWEdmBundle/Controller/EdmApiController.php line 32

Open in your IDE?
  1. <?php
  2. namespace AWEdmBundle\Controller;
  3. use AWCmsBundle\Security\CurrentUserProvider;
  4. use AWCmsBundle\Tool\FileSystemTool;
  5. use AWEdmBundle\Entity\Document;
  6. use AWEdmBundle\Entity\File;
  7. use AWEdmBundle\Entity\Folder;
  8. use AWEdmBundle\Manager\DocumentManager;
  9. use Doctrine\DBAL\Exception\ForeignKeyConstraintViolationException;
  10. use Doctrine\ORM\EntityManagerInterface;
  11. use League\Flysystem\FileNotFoundException;
  12. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
  13. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
  14. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
  15. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
  16. use Symfony\Component\HttpFoundation\JsonResponse;
  17. use Symfony\Component\HttpFoundation\Request;
  18. use Symfony\Component\HttpFoundation\Response;
  19. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  20. use Symfony\Component\Security\Core\Exception\AccessDeniedException;
  21. use FOS\RestBundle\Controller\Annotations as Rest;
  22. use Symfony\Contracts\Translation\TranslatorInterface;
  23. /**
  24.  * Class EdmApiController
  25.  * @package AWEdmBundle\Controller
  26.  *
  27.  * @Security("has_role('ROLE_USER')")
  28.  * @Route("/api/ged")
  29.  */
  30. class EdmApiController extends RestController
  31. {
  32.     /**
  33.      * @Rest\Get("documents", name="get_documents_index", options={"expose"=true,"i18n"=false})
  34.      * @Method("GET")
  35.      * @Template
  36.      * @return array
  37.      */
  38.     public function getDocumentsIndexAction()
  39.     {
  40.         return  [];
  41.     }
  42.     /**
  43.      * Returns all the files and folders of a folder
  44.      * @Rest\Get("/get_folder_content", name="get_files", options={"expose"=true,"i18n"=false})
  45.      * @Security("has_role('ROLE_USER')")
  46.      * @Rest\View(serializerGroups={"ged"})
  47.      * @param Request $request
  48.      * @return array
  49.      */
  50.     public function getFolderContentAction(Request $request)
  51.     {
  52.         $subFolder $request->query->get('subFolder''');
  53.         $parentId $request->query->get('parent_id'null);
  54.         $folders $request->query->get('folders'null);
  55.         $foldersId explode(', '$folders);
  56.         $offset $request->query->get('offset'0);
  57.         $limit $request->query->get('limit'100);
  58.         /** @var EntityManagerInterface $entityManager */
  59.         $entityManager $this->get('doctrine.orm.default_entity_manager');
  60.         if ('' != $subFolder) {
  61.             if($parentId === null){
  62.                 $parentId $entityManager->getRepository(Folder::class)->findOneBy(['parent' => null])->getId();
  63.             }
  64.             $folders $entityManager->getRepository(Folder::class)->findBy(['subFolder' => $subFolder'parent' => $parentId], null$limit$offset);
  65.             $folders array_merge($folders$entityManager->getRepository(Folder::class)->findBy(['subFolder' => $subFolder'parent' => $parentId'id' => $foldersId], null$limit$offset));
  66.             $files $entityManager->getRepository(File::class)->findBy(['parent' => $parentId], null$limit$offset);
  67.         }else{
  68.             throw new \InvalidArgumentException('Need a subFolder');
  69.         }
  70.         return [
  71.             'data' => array_merge($folders$files)
  72.         ];
  73.     }
  74.     /**
  75.      * @Rest\GET("/get_document/{document}", name="get_document", options={"expose"=true,"i18n"=false})
  76.      * @Rest\View(serializerGroups={"ged"})
  77.      * @param Document $document
  78.      * @return array
  79.      */
  80.     public function getDocumentAction(Document $document)
  81.     {
  82.         return [
  83.             'data' => $document
  84.         ];
  85.     }
  86.     /**
  87.      * @Rest\Post("/post_documents", name="post_documents", options={"expose"=true,"i18n"=false})
  88.      * @Security("has_role('ROLE_USER')")
  89.      * @Rest\View(serializerGroups={"ged"})
  90.      * @param Request $request
  91.      * @return array
  92.      */
  93.     public function postDocumentsAction(Request $request)
  94.     {
  95.         $documentManager $this->get('awedm.manager.document');
  96.         $entityManager $this->get('doctrine.orm.default_entity_manager');
  97.         $documentsProperties $request->get('document_collection')['documents'];
  98.         $documents = [];
  99.         foreach ($documentsProperties as $documentProperties) {
  100.             $id = (array_key_exists('id'$documentProperties) ? $documentProperties['id'] : null);
  101.             $name $documentProperties['name'];
  102.             $parentId $documentProperties['parent_id'];
  103.             $type $documentProperties['type'];
  104.             $document null;
  105.             if (null !== $id && '' != $id) {
  106.                 if($type === Document::TYPE_FILE){
  107.                     $document $this->get('doctrine.orm.default_entity_manager')->getRepository(File::class)->findOneBy(['id' => $id]);
  108.                 }else{
  109.                     $document $this->get('doctrine.orm.default_entity_manager')->getRepository(Folder::class)->findOneBy(['id' => $id]);
  110.                 }
  111.             }
  112.             $folderParent null;
  113.             /**
  114.              * @TODO to remove...
  115.              */
  116.             if ('' != $parentId and preg_match('|\.|'$parentId)) {
  117.                 $folderParent $entityManager->getRepository(Folder::class)->findOneBy(['uniqueId' => $parentId]);
  118.             }elseif ('' != $parentId){
  119.                 $folderParent $entityManager->getRepository(Folder::class)->find($parentId);
  120.             }
  121.             if (null === $document) {
  122.                 switch ($type) {
  123.                     case 'folder':
  124.                         $document = new Folder();
  125.                         if(array_key_exists('subFolder'$documentProperties)){
  126.                             $document->setSubFolder($documentProperties['subFolder']);
  127.                         }elseif ($folderParent){
  128.                             $document->setSubFolder($folderParent->getSubFolder());
  129.                         }
  130.                         break;
  131.                     case 'file':
  132.                         $document = new File();
  133.                         break;
  134.                 }
  135.             }
  136.             $document->setName($name);
  137.             $document->setParent($folderParent);;
  138.             $documentManager->save($document);
  139.             $documents[] = $document;
  140.         }
  141.         return [
  142.             'data' => $documents
  143.         ];
  144.     }
  145.     /**
  146.      * @Rest\Patch("/patch_documents", name="patch_documents", options={"expose"=true,"i18n"=false})
  147.      * @Rest\View(serializerGroups={"ged"})
  148.      * @Security("has_role('ROLE_USER')")
  149.      *
  150.      * @param Request $request
  151.      * @return array
  152.      */
  153.     public function patchDocumentsAction(Request $request)
  154.     {
  155.         return $this->postDocumentsAction($request);
  156.     }
  157.     
  158.     /**
  159.      * @Rest\Delete("/delete_documents", name="delete_documents", options={"expose"=true,"i18n"=false})
  160.      * @Rest\View(serializerGroups={"ged"})
  161.      * @Security("has_role('ROLE_USER')")
  162.      *
  163.      * @param Request $request
  164.      * @param CurrentUserProvider $userProvider
  165.      * @return JsonResponse
  166.      */
  167.     public function deleteDocumentsAction(Request $requestCurrentUserProvider $userProvider)
  168.     {
  169.         $documentManager $this->get('awedm.manager.document');
  170.         $fileIds = (array) $request->get('files');
  171.         $folderIds = (array) $request->get('folders');
  172.         if(!$fileIds && !$folderIds){
  173.             return new JsonResponse(['success' => false], Response::HTTP_BAD_REQUEST);
  174.         }
  175.         $documents = [];
  176.         foreach ($fileIds as $documentId) {
  177.             /** @var File $document */
  178.             if ($document $this->get('doctrine.orm.default_entity_manager')->getRepository(File::class)->find($documentId)) {
  179.                 $documents[] = $document;
  180.             }
  181.         }
  182.         foreach ($folderIds as $documentId) {
  183.             /** @var File $document */
  184.             if ($document $this->get('doctrine.orm.default_entity_manager')->getRepository(Folder::class)->find($documentId)) {
  185.                 $documents[] = $document;
  186.             }
  187.         }
  188.         /** @var Document $document */
  189.         foreach ($documents as $document) {
  190.             if (
  191.                 !(
  192.                     $this->isGranted('ROLE_ADMIN')
  193.                     || ($this->isGranted('ROLE_USER') && $document->getCreatedBy()->getId() == $userProvider->get()->getId())
  194.                 )
  195.             ) {
  196.                 throw new AccessDeniedException();
  197.             }
  198.             if ($document) {
  199.                 try{
  200.                     $documentManager->delete($document);
  201.                 }
  202.                 catch(\Exception $e){
  203.                     if($e instanceof ForeignKeyConstraintViolationException){
  204.                         return new JsonResponse(['success' => false'error' => $this->get('translator')->trans('error.foreign_key_constraint')], Response::HTTP_BAD_REQUEST);
  205.                     }
  206.                     return new JsonResponse(['success' => false'error' => $e->getMessage()], Response::HTTP_NOT_FOUND);
  207.                 }
  208.             }
  209.         }
  210.         return new JsonResponse(['success' => true]);
  211.     }
  212.     
  213.     /**
  214.      * @Rest\Post("/post_documents_upload/{folder}", name="post_documents_upload", options={"expose"=true,"i18n"=false})
  215.      * @Rest\View(serializerGroups={"ged"})
  216.      * @Security("has_role('ROLE_USER')")
  217.      *
  218.      * @param Request $request
  219.      * @param Folder $folder
  220.      * @return array
  221.      * @throws \Exception
  222.      */
  223.     public function postDocumentsUploadAction(Request $requestFolder $folderDocumentManager $documentManager)
  224.     {
  225.         $subFolder $request->query->get('subFolder''');
  226.         $data = [];
  227.         if (count($_FILES) > 0) {
  228.             $data $documentManager->upload($subFolder$folder'files');
  229.         }
  230.         return ['data' => $data];
  231.     }
  232.     /**
  233.      * @Rest\Get("/get_download_documents", name="get_download_documents", options={"expose"=true,"i18n"=false})
  234.      * @param Request $request
  235.      * @return \Symfony\Component\HttpFoundation\RedirectResponse|Response
  236.      */
  237.     public function getDownloadDocumentsAction(Request $request)
  238.     {
  239.         /** @var DocumentManager $documentManager */
  240.         $documentManager $this->get('awedm.manager.document');
  241.         $archiveName "archive_".uniqid();
  242.         $subFolder $request->query->get('subFolder');
  243.         $tmpDirectory '/tmp/'.$archiveName;
  244.         $fileIds = (array) $request->get('files');
  245.         $folderIds = (array) $request->get('folders');
  246.         $documents = [];
  247.         foreach ($fileIds as $documentId) {
  248.             /** @var File $document */
  249.             if ($document $this->get('doctrine.orm.default_entity_manager')->getRepository(File::class)->find($documentId)) {
  250.                 $documents[] = $document;
  251.             }
  252.         }
  253.         foreach ($folderIds as $documentId) {
  254.             /** @var File $document */
  255.             if ($document $this->get('doctrine.orm.default_entity_manager')->getRepository(Folder::class)->find($documentId)) {
  256.                 $documents[] = $document;
  257.             }
  258.         }
  259.         if(count($documents) == and reset($documents) instanceof File)
  260.             return $documentManager->downloadFile(reset($documents));
  261.         $documentManager->createTree($documents$tmpDirectory$subFolder);
  262.         $zipFile realpath($tmpDirectory.DIRECTORY_SEPARATOR.'..'.DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR.$archiveName.'.zip';
  263.         //dump($zipFile);exit;
  264.         if (file_exists($tmpDirectory)) {
  265.             FileSystemTool::zipFolder(realpath($tmpDirectory), $zipFile);
  266.             FileSystemTool::rmRecursive($tmpDirectory);
  267.             if (file_exists($zipFile)) {
  268.                 FileSystemTool::rangeDownload($zipFilebasename($zipFile), true);
  269.                 exit;
  270.             }
  271.         }
  272.         return new Response('File not found.'Response::HTTP_NOT_FOUND);
  273.     }
  274.     /**
  275.      * @Rest\Get("get_file/{file}", name="get_file", options={"expose"=true,"i18n"=false})
  276.      * @Method("GET")
  277.      * @param File $file
  278.      * @return \Symfony\Component\HttpFoundation\StreamedResponse
  279.      */
  280.     public function getFileAction(File $file)
  281.     {
  282.         /** @var DocumentManager $documentManager */
  283.         $documentManager $this->get('awedm.manager.document');
  284.         try {
  285.             $response $documentManager->downloadFile($file);
  286.         } catch (FileNotFoundException $e) {
  287.             throw new NotFoundHttpException();
  288.         }
  289.         return $response;
  290.     }
  291.     /**
  292.      * @Rest\Get("/check_folder_tree", name="check_folder_tree", options={"expose"=true,"i18n"=false})
  293.      * @Method("GET")
  294.      * @param Request $request
  295.      * @return JsonResponse
  296.      */
  297.     public function getCheckFolderTreeAction(Request $request)
  298.     {
  299.         $path str_replace(' '''$request->get('path'));
  300.         $tree explode(','$path);
  301.         end($tree);         // move the internal pointer to the end of the array
  302.         $lastFolderId key($tree);
  303.         /** @var Folder $lastFolder */
  304.         $lastFolder $this->get('doctrine.orm.default_entity_manager')->getRepository(Folder::class)->findOneBy(['id' => $lastFolderId]);
  305.         $emdPath implode(','$this->container->get('awedm.manager.document')->getFolderIdTree($lastFolder));
  306.         $response = new JsonResponse();
  307.         $response->setData(['success' => $emdPath == $path]);
  308.         return $response;
  309.     }
  310. }