src/Ox/HoardBundle/Controller/ImageController.php line 157

Open in your IDE?
  1. <?php
  2. namespace App\Ox\HoardBundle\Controller;
  3. use Symfony\Component\HttpFoundation\Request;
  4. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  5. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
  6. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
  7. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
  8. use Symfony\Component\HttpFoundation\File\File;
  9. use Symfony\Component\HttpFoundation\Response;
  10. use App\Ox\HoardBundle\Entity\Image;
  11. use App\Ox\HoardBundle\Form\ImageType;
  12. use Symfony\Component\Form\Extension\Core\Type\SubmitType;
  13. /**
  14.  * Image controller.
  15.  *
  16.  * @Route("/image")
  17.  */
  18. class ImageController extends AbstractController
  19. {
  20.     
  21.     
  22.         /**
  23.          * @Route("/coin/{coin_id}{coin_image_type}.{ext}", name="coin_image", requirements={
  24.          *      "coin": "\d+",
  25.          *      "type": "\w{1}",
  26.          *      "ext": "\w+"
  27.          * }), methods={"GET"})
  28.          */
  29.         public function coinImage($coin_id$coin_image_type 'c')
  30.         {
  31.             //Symfony complains if we default to the empty string for coin image type.
  32.             // if we supply 'c', then we actually want ''
  33.             if($coin_image_type == 'c')
  34.             {
  35.                 $type '';
  36.             }
  37.             else
  38.             {
  39.                 $type $coin_image_type;
  40.             }
  41.             
  42.             $em $this->getDoctrine()->getManager();
  43.             $coin $em->getRepository('OxHoardBundle:Coin')->find($coin_id);
  44.             if (!$coin) {
  45.                 return $this->coinNotFound($coin_id);
  46.             }
  47.             
  48.             $coinImages $coin->getCoinImages();
  49.             if ($coinImages) {
  50.                 foreach ($coinImages as $coinImage) {
  51.                     if ($coinImage->getType()->getAbbreviation() == $type) {
  52.                         $image = new File($this->getCoinUploadDir() . '/' $coinImage->getImage()->getFileName());
  53.                         
  54.                         $file $image->openFile();
  55.                         
  56.                         $contents file_get_contents($file->getRealPath());
  57.                         $response = new Response($contents);
  58.                         $response->headers->set('Content-Type'$image->getMimeType());
  59.                         $response->headers->set('Content-Length'$file->getSize());
  60.                         $response->headers->set('ETag'md5($contents));
  61.                         $response->headers->set('Last-Modified'$coinImage->getModifiedDate()->format('D, d M Y H:i:s T'));
  62.                         
  63.                         return $response;
  64.                     }
  65.                 }
  66.             }
  67.             return $this->coinImageNotFound($coin_id$coin_image_type);
  68.         }
  69.         
  70.         private function coinNotFound($coin_id)
  71.         {
  72.             return new Response('Coin ' $coin_id ' not found!');
  73.         }
  74.         
  75.         private function coinImageNotFound($coin_id$coin_image_type)
  76.         {
  77.             return new Response($coin_image_type ' image for coin ' $coin_id ' not found!');
  78.         }
  79.         private function getCoinUploadDir()
  80.         {
  81.             // get rid of the __DIR__ so it doesn't screw up
  82.             // when displaying uploaded doc/image in the view.
  83.             return '/srv/hoards_coin_images';
  84.         }
  85.         
  86.         /**
  87.          * @Route("/object/{object_image_id}", name="object_image", requirements={
  88.          *      "object_image_id": "\d+",
  89.          * }), methods={"GET"})
  90.          */
  91.         public function objectImage($object_image_id)
  92.         {
  93.             $em $this->getDoctrine()->getManager();
  94.             
  95.             $objectImage $em->getRepository('OxHoardBundle:ObjectImage')->find($object_image_id);
  96.             if(!$objectImage) {
  97.                 return $this->objectImageNotFound($objectImage);
  98.             }
  99.             
  100.             //TODO check user's permission for the related object
  101.             
  102.             $imageFile = new File($this->getObjectUploadDir() . '/' $objectImage->getImage()->getFileName());
  103.             
  104.             $file $imageFile->openFile();
  105.             
  106.             $contents file_get_contents($file->getRealPath());
  107.             $response = new Response($contents);
  108.             $response->headers->set('Content-Type'$imageFile->getMimeType());
  109.             $response->headers->set('Content-Length'$file->getSize());
  110.             $response->headers->set('ETag'md5($contents));
  111.             $response->headers->set('Last-Modified'$objectImage->getModifiedDate()->format('D, d M Y H:i:s T'));
  112.             
  113.             return $response;
  114.         }
  115.         /**
  116.          * @Route("/container/{container_image_id}", name="container_image", requirements={
  117.          *      "container_image_id": "\d+",
  118.          * }), methods={"GET"})
  119.          */
  120.         public function containerImage($container_image_id)
  121.         {
  122.             $em $this->getDoctrine()->getManager();
  123.             $containerImage $em->getRepository('OxHoardBundle:ContainerImage')->find($container_image_id);
  124.             if(!$containerImage) {
  125.                 return $this->containerImageNotFound($containerImage);
  126.             }
  127.             //TODO check user's permission for the related container
  128.             $imageFile = new File($this->getContainerUploadDir() . '/' $containerImage->getImage()->getFileName());
  129.             $file $imageFile->openFile();
  130.             $contents file_get_contents($file->getRealPath());
  131.             $response = new Response($contents);
  132.             $response->headers->set('Content-Type'$imageFile->getMimeType());
  133.             $response->headers->set('Content-Length'$file->getSize());
  134.             $response->headers->set('ETag'md5($contents));
  135.             $response->headers->set('Last-Modified'$containerImage->getModifiedDate()->format('D, d M Y H:i:s T'));
  136.             return $response;
  137.         }
  138.         
  139.         /**
  140.          * @Route("/hoard/{hoard_image_id}", name="hoard_image", requirements={
  141.          *      "hoard_image_id": "\d+",
  142.          * }), methods={"GET"})
  143.          */
  144.         public function hoardImage($hoard_image_id)
  145.         {
  146.             $em $this->getDoctrine()->getManager();
  147.             
  148.             $hoardImage $em->getRepository('OxHoardBundle:HoardImage')->find($hoard_image_id);
  149.             if(!$hoardImage) {
  150.                 return $this->hoardImageNotFound($hoardImage);
  151.             }
  152.             
  153.             //TODO check user's permission for the related object
  154.             
  155.             $imageFile = new File($this->getHoardUploadDir() . '/' $hoardImage->getImage()->getFileName());
  156.             
  157.             $file $imageFile->openFile();
  158.             
  159.             $contents file_get_contents($file->getRealPath());
  160.             $response = new Response($contents);
  161.             $response->headers->set('Content-Type'$imageFile->getMimeType());
  162.             $response->headers->set('Content-Length'$file->getSize());
  163.             $response->headers->set('ETag'md5($contents));
  164.             // $response->headers->set('Last-Modified', $hoardImage->getModifiedDate()->format('D, d M Y H:i:s T'));
  165.             
  166.             return $response;
  167.         }
  168.         
  169.         /**
  170.          * @Route("/misc/{filename}", name="misc_image", requirements={
  171.          *      "filename": "\S+",
  172.          * }, methods={"GET"})
  173.          */
  174.         public function miscImage($filename) {
  175.             $em $this->getDoctrine()->getManager();
  176.             
  177.             $image $em->getRepository('OxHoardBundle:Image')->findOneBy(array('fileName' => $filename));
  178.             if(!$image) {
  179.                 return new Response('image not found');
  180.             }
  181.             $imageFile = new File($this->getMiscImageUploadDir() . '/' $image->getFileName());
  182.             $file $imageFile->openFile();
  183.             
  184.             $contents file_get_contents($file->getRealPath());
  185.             $response = new Response($contents);
  186.             $response->headers->set('Content-Type'$imageFile->getMimeType());
  187.             $response->headers->set('Content-Length'$file->getSize());
  188.             $response->headers->set('ETag'md5($contents));
  189.             // $response->headers->set('Last-Modified', $hoardImage->getModifiedDate()->format('D, d M Y H:i:s T'));
  190.             
  191.             return $response;
  192.         }
  193.         
  194.         private function objectImageNotFound($object_id)
  195.         {
  196.             return new Response('Object '.$object_id.' not found');
  197.         }
  198.         
  199.         private function containerImageNotFound($container_id)
  200.         {
  201.             return new Response('Container '.$container_id.' not found');
  202.         }
  203.         private function hoardImageNotFound($hoard_id)
  204.         {
  205.             return new Response('Hoard '.$hoard_id.' not found');
  206.         }
  207.         
  208.         private function getObjectUploadDir()
  209.         {
  210.             return '/srv/hoards_object_images';
  211.         }
  212.         
  213.         private function getHoardUploadDir()
  214.         {
  215.             return '/srv/hoards_hoard_images';
  216.         }
  217.         private function getContainerUploadDir()
  218.         {
  219.             return '/srv/hoards_container_images';
  220.         }
  221.         private function getMiscImageUploadDir()
  222.         {
  223.             return '/srv/hoards_misc_images';
  224.         }
  225.     /**
  226.      * Lists all Image entities.
  227.      *
  228.      * @Route("/", name="image", methods={"GET"})
  229.      * @Template()
  230.      */
  231.     public function indexAction()
  232.     {
  233.         $em $this->getDoctrine()->getManager();
  234.         $entities $em->getRepository('OxHoardBundle:Image')->findBy(array('isUserImage' => true));
  235.         return array(
  236.             'entities' => $entities,
  237.         );
  238.     }
  239.     /**
  240.      * Creates a new Image entity.
  241.      *
  242.      * @Route("/", name="image_create", methods={"POST"})
  243.      * @Template("@OxHoardBundle/image/new.html.twig")
  244.      */
  245.     public function createAction(Request $request)
  246.     {
  247.         $entity = new Image();
  248.         $form $this->createCreateForm($entity);
  249.         $form->handleRequest($request);
  250.         if ($form->isValid()) {
  251.             //save image
  252.             $file $request->files->get('ox_hoardbundle_image');
  253.             if(isset($file) && isset($file['file'])) {
  254.                 $fileName $file['file']->getClientOriginalName();
  255.                 $fileName str_replace(' ''_'$fileName);
  256.                 $ext $file['file']->guessExtension();
  257.                 $destPath $this->getMiscImageUploadDir();
  258.                 $savedFile $file['file']->move($destPath$fileName);
  259.                 
  260.                 $entity->setFileName($fileName);
  261.             }
  262.             $entity->setIsUserImage(true);
  263.             $em $this->getDoctrine()->getManager();
  264.             $em->persist($entity);
  265.             $em->flush();
  266.             return $this->redirect($this->generateUrl('image_show', array('id' => $entity->getId())));
  267.             $entity->setIsUserImage(true);
  268.         }
  269.         return array(
  270.             'entity' => $entity,
  271.             'form'   => $form->createView(),
  272.         );
  273.     }
  274.     /**
  275.      * Creates a form to create a Image entity.
  276.      *
  277.      * @param Image $entity The entity
  278.      *
  279.      * @return \Symfony\Component\Form\Form The form
  280.      */
  281.     private function createCreateForm(Image $entity)
  282.     {
  283.         $form $this->createForm(ImageType::class, $entity, array(
  284.             'action' => $this->generateUrl('image_create'),
  285.             'method' => 'POST',
  286.         ));
  287.         $form->add('submit'SubmitType::class, array('label' => 'Create'));
  288.         return $form;
  289.     }
  290.     /**
  291.      * Displays a form to create a new Image entity.
  292.      *
  293.      * @Route("/new", name="image_new", methods={"GET"})
  294.      * @Template()
  295.      */
  296.     public function newAction()
  297.     {
  298.         $entity = new Image();
  299.         $form   $this->createCreateForm($entity);
  300.         return array(
  301.             'entity' => $entity,
  302.             'form'   => $form->createView(),
  303.         );
  304.     }
  305.     /**
  306.      * Finds and displays a Image entity.
  307.      *
  308.      * @Route("/{id}", name="image_show", methods={"GET"})
  309.      * @Template()
  310.      */
  311.     public function showAction($id)
  312.     {
  313.         $em $this->getDoctrine()->getManager();
  314.         $entity $em->getRepository('OxHoardBundle:Image')->find($id);
  315.         if (!$entity) {
  316.             throw $this->createNotFoundException('Unable to find Image entity.');
  317.         }
  318.         if (!$entity->getIsUserImage()) {
  319.             //the image entity technically exists, but we don't want users to access these unless they are flagged as user images.
  320.             throw $this->createNotFoundException('Not a user image');
  321.         }
  322.         $deleteForm $this->createDeleteForm($id);
  323.         return array(
  324.             'entity'      => $entity,
  325.             'delete_form' => $deleteForm->createView(),
  326.         );
  327.     }
  328.     /**
  329.      * Displays a form to edit an existing Image entity.
  330.      *
  331.      * @Route("/{id}/edit", name="image_edit", methods={"GET"})
  332.      * @Template()
  333.      */
  334.     public function editAction($id)
  335.     {
  336.         $em $this->getDoctrine()->getManager();
  337.         $entity $em->getRepository('OxHoardBundle:Image')->find($id);
  338.         if (!$entity) {
  339.             throw $this->createNotFoundException('Unable to find Image entity.');
  340.         }
  341.         if (!$entity->getIsUserImage()) {
  342.             //the image entity technically exists, but we don't want users to access these unless they are flagged as user images.
  343.             throw $this->createNotFoundException('Not a user image');
  344.         }
  345.         $editForm $this->createEditForm($entity);
  346.         $deleteForm $this->createDeleteForm($id);
  347.         return array(
  348.             'entity'      => $entity,
  349.             'edit_form'   => $editForm->createView(),
  350.             'delete_form' => $deleteForm->createView(),
  351.         );
  352.     }
  353.     /**
  354.     * Creates a form to edit a Image entity.
  355.     *
  356.     * @param Image $entity The entity
  357.     *
  358.     * @return \Symfony\Component\Form\Form The form
  359.     */
  360.     private function createEditForm(Image $entity)
  361.     {
  362.         $form $this->createForm(ImageType::class, $entity, array(
  363.             'action' => $this->generateUrl('image_update', array('id' => $entity->getId())),
  364.             'method' => 'PUT',
  365.         ));
  366.         $form->add('submit'SubmitType::class, array('label' => 'Update'));
  367.         return $form;
  368.     }
  369.     /**
  370.      * Edits an existing Image entity.
  371.      *
  372.      * @Route("/{id}", name="image_update", methods={"PUT"})
  373.      * @Template("@OxHoardBundle/image/edit.html.twig")
  374.      */
  375.     public function updateAction(Request $request$id)
  376.     {
  377.         $em $this->getDoctrine()->getManager();
  378.         $entity $em->getRepository('OxHoardBundle:Image')->find($id);
  379.         if (!$entity) {
  380.             throw $this->createNotFoundException('Unable to find Image entity.');
  381.         }
  382.         if (!$entity->getIsUserImage()) {
  383.             //the image entity technically exists, but we don't want users to access these unless they are flagged as user images.
  384.             throw $this->createNotFoundException('Not a user image');
  385.         }
  386.         $deleteForm $this->createDeleteForm($id);
  387.         $editForm $this->createEditForm($entity);
  388.         $editForm->handleRequest($request);
  389.         if ($editForm->isValid()) {
  390.             //save image
  391.             $file $request->files->get('ox_hoardbundle_image');
  392.             if(isset($file) && isset($file['file'])) {
  393.                 $fileName $file['file']->getClientOriginalName();
  394.                 $ext $file['file']->guessExtension();
  395.                 $destPath $this->getMiscImageUploadDir();
  396.                 $savedFile $file['file']->move($destPath$fileName);
  397.                 
  398.                 $entity->setFileName($fileName);
  399.             }
  400.             
  401.             $em->flush();
  402.             return $this->redirect($this->generateUrl('image_edit', array('id' => $id)));
  403.         }
  404.         return array(
  405.             'entity'      => $entity,
  406.             'edit_form'   => $editForm->createView(),
  407.             'delete_form' => $deleteForm->createView(),
  408.         );
  409.     }
  410.     /**
  411.      * Deletes a Image entity.
  412.      *
  413.      * @Route("/{id}", name="image_delete", methods={"DELETE"})
  414.      */
  415.     public function deleteAction(Request $request$id)
  416.     {
  417.         $form $this->createDeleteForm($id);
  418.         $form->handleRequest($request);
  419.         if ($form->isValid()) {
  420.             $em $this->getDoctrine()->getManager();
  421.             $entity $em->getRepository('OxHoardBundle:Image')->find($id);
  422.             if (!$entity) {
  423.                 throw $this->createNotFoundException('Unable to find Image entity.');
  424.             }
  425.             $em->remove($entity);
  426.             $em->flush();
  427.         }
  428.         return $this->redirect($this->generateUrl('image'));
  429.     }
  430.     /**
  431.      * Creates a form to delete a Image entity by id.
  432.      *
  433.      * @param mixed $id The entity id
  434.      *
  435.      * @return \Symfony\Component\Form\Form The form
  436.      */
  437.     private function createDeleteForm($id)
  438.     {
  439.         return $this->createFormBuilder()
  440.             ->setAction($this->generateUrl('image_delete', array('id' => $id)))
  441.             ->setMethod('DELETE')
  442.             ->add('submit'SubmitType::class, array(
  443.                 'label' => 'Delete',
  444.                 'attr' => array( 'class' => 'delete-button btn-danger')
  445.             ))
  446.             ->getForm()
  447.         ;
  448.     }
  449. }