<?php
namespace App\Ox\HoardBundle\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Component\HttpFoundation\File\File;
use Symfony\Component\HttpFoundation\Response;
use App\Ox\HoardBundle\Entity\Image;
use App\Ox\HoardBundle\Form\ImageType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
/**
* Image controller.
*
* @Route("/image")
*/
class ImageController extends AbstractController
{
/**
* @Route("/coin/{coin_id}{coin_image_type}.{ext}", name="coin_image", requirements={
* "coin": "\d+",
* "type": "\w{1}",
* "ext": "\w+"
* }), methods={"GET"})
*/
public function coinImage($coin_id, $coin_image_type = 'c')
{
//Symfony complains if we default to the empty string for coin image type.
// if we supply 'c', then we actually want ''
if($coin_image_type == 'c')
{
$type = '';
}
else
{
$type = $coin_image_type;
}
$em = $this->getDoctrine()->getManager();
$coin = $em->getRepository('OxHoardBundle:Coin')->find($coin_id);
if (!$coin) {
return $this->coinNotFound($coin_id);
}
$coinImages = $coin->getCoinImages();
if ($coinImages) {
foreach ($coinImages as $coinImage) {
if ($coinImage->getType()->getAbbreviation() == $type) {
$image = new File($this->getCoinUploadDir() . '/' . $coinImage->getImage()->getFileName());
$file = $image->openFile();
$contents = file_get_contents($file->getRealPath());
$response = new Response($contents);
$response->headers->set('Content-Type', $image->getMimeType());
$response->headers->set('Content-Length', $file->getSize());
$response->headers->set('ETag', md5($contents));
$response->headers->set('Last-Modified', $coinImage->getModifiedDate()->format('D, d M Y H:i:s T'));
return $response;
}
}
}
return $this->coinImageNotFound($coin_id, $coin_image_type);
}
private function coinNotFound($coin_id)
{
return new Response('Coin ' . $coin_id . ' not found!');
}
private function coinImageNotFound($coin_id, $coin_image_type)
{
return new Response($coin_image_type . ' image for coin ' . $coin_id . ' not found!');
}
private function getCoinUploadDir()
{
// get rid of the __DIR__ so it doesn't screw up
// when displaying uploaded doc/image in the view.
return '/srv/hoards_coin_images';
}
/**
* @Route("/object/{object_image_id}", name="object_image", requirements={
* "object_image_id": "\d+",
* }), methods={"GET"})
*/
public function objectImage($object_image_id)
{
$em = $this->getDoctrine()->getManager();
$objectImage = $em->getRepository('OxHoardBundle:ObjectImage')->find($object_image_id);
if(!$objectImage) {
return $this->objectImageNotFound($objectImage);
}
//TODO check user's permission for the related object
$imageFile = new File($this->getObjectUploadDir() . '/' . $objectImage->getImage()->getFileName());
$file = $imageFile->openFile();
$contents = file_get_contents($file->getRealPath());
$response = new Response($contents);
$response->headers->set('Content-Type', $imageFile->getMimeType());
$response->headers->set('Content-Length', $file->getSize());
$response->headers->set('ETag', md5($contents));
$response->headers->set('Last-Modified', $objectImage->getModifiedDate()->format('D, d M Y H:i:s T'));
return $response;
}
/**
* @Route("/container/{container_image_id}", name="container_image", requirements={
* "container_image_id": "\d+",
* }), methods={"GET"})
*/
public function containerImage($container_image_id)
{
$em = $this->getDoctrine()->getManager();
$containerImage = $em->getRepository('OxHoardBundle:ContainerImage')->find($container_image_id);
if(!$containerImage) {
return $this->containerImageNotFound($containerImage);
}
//TODO check user's permission for the related container
$imageFile = new File($this->getContainerUploadDir() . '/' . $containerImage->getImage()->getFileName());
$file = $imageFile->openFile();
$contents = file_get_contents($file->getRealPath());
$response = new Response($contents);
$response->headers->set('Content-Type', $imageFile->getMimeType());
$response->headers->set('Content-Length', $file->getSize());
$response->headers->set('ETag', md5($contents));
$response->headers->set('Last-Modified', $containerImage->getModifiedDate()->format('D, d M Y H:i:s T'));
return $response;
}
/**
* @Route("/hoard/{hoard_image_id}", name="hoard_image", requirements={
* "hoard_image_id": "\d+",
* }), methods={"GET"})
*/
public function hoardImage($hoard_image_id)
{
$em = $this->getDoctrine()->getManager();
$hoardImage = $em->getRepository('OxHoardBundle:HoardImage')->find($hoard_image_id);
if(!$hoardImage) {
return $this->hoardImageNotFound($hoardImage);
}
//TODO check user's permission for the related object
$imageFile = new File($this->getHoardUploadDir() . '/' . $hoardImage->getImage()->getFileName());
$file = $imageFile->openFile();
$contents = file_get_contents($file->getRealPath());
$response = new Response($contents);
$response->headers->set('Content-Type', $imageFile->getMimeType());
$response->headers->set('Content-Length', $file->getSize());
$response->headers->set('ETag', md5($contents));
// $response->headers->set('Last-Modified', $hoardImage->getModifiedDate()->format('D, d M Y H:i:s T'));
return $response;
}
/**
* @Route("/misc/{filename}", name="misc_image", requirements={
* "filename": "\S+",
* }, methods={"GET"})
*/
public function miscImage($filename) {
$em = $this->getDoctrine()->getManager();
$image = $em->getRepository('OxHoardBundle:Image')->findOneBy(array('fileName' => $filename));
if(!$image) {
return new Response('image not found');
}
$imageFile = new File($this->getMiscImageUploadDir() . '/' . $image->getFileName());
$file = $imageFile->openFile();
$contents = file_get_contents($file->getRealPath());
$response = new Response($contents);
$response->headers->set('Content-Type', $imageFile->getMimeType());
$response->headers->set('Content-Length', $file->getSize());
$response->headers->set('ETag', md5($contents));
// $response->headers->set('Last-Modified', $hoardImage->getModifiedDate()->format('D, d M Y H:i:s T'));
return $response;
}
private function objectImageNotFound($object_id)
{
return new Response('Object '.$object_id.' not found');
}
private function containerImageNotFound($container_id)
{
return new Response('Container '.$container_id.' not found');
}
private function hoardImageNotFound($hoard_id)
{
return new Response('Hoard '.$hoard_id.' not found');
}
private function getObjectUploadDir()
{
return '/srv/hoards_object_images';
}
private function getHoardUploadDir()
{
return '/srv/hoards_hoard_images';
}
private function getContainerUploadDir()
{
return '/srv/hoards_container_images';
}
private function getMiscImageUploadDir()
{
return '/srv/hoards_misc_images';
}
/**
* Lists all Image entities.
*
* @Route("/", name="image", methods={"GET"})
* @Template()
*/
public function indexAction()
{
$em = $this->getDoctrine()->getManager();
$entities = $em->getRepository('OxHoardBundle:Image')->findBy(array('isUserImage' => true));
return array(
'entities' => $entities,
);
}
/**
* Creates a new Image entity.
*
* @Route("/", name="image_create", methods={"POST"})
* @Template("@OxHoardBundle/image/new.html.twig")
*/
public function createAction(Request $request)
{
$entity = new Image();
$form = $this->createCreateForm($entity);
$form->handleRequest($request);
if ($form->isValid()) {
//save image
$file = $request->files->get('ox_hoardbundle_image');
if(isset($file) && isset($file['file'])) {
$fileName = $file['file']->getClientOriginalName();
$fileName = str_replace(' ', '_', $fileName);
$ext = $file['file']->guessExtension();
$destPath = $this->getMiscImageUploadDir();
$savedFile = $file['file']->move($destPath, $fileName);
$entity->setFileName($fileName);
}
$entity->setIsUserImage(true);
$em = $this->getDoctrine()->getManager();
$em->persist($entity);
$em->flush();
return $this->redirect($this->generateUrl('image_show', array('id' => $entity->getId())));
$entity->setIsUserImage(true);
}
return array(
'entity' => $entity,
'form' => $form->createView(),
);
}
/**
* Creates a form to create a Image entity.
*
* @param Image $entity The entity
*
* @return \Symfony\Component\Form\Form The form
*/
private function createCreateForm(Image $entity)
{
$form = $this->createForm(ImageType::class, $entity, array(
'action' => $this->generateUrl('image_create'),
'method' => 'POST',
));
$form->add('submit', SubmitType::class, array('label' => 'Create'));
return $form;
}
/**
* Displays a form to create a new Image entity.
*
* @Route("/new", name="image_new", methods={"GET"})
* @Template()
*/
public function newAction()
{
$entity = new Image();
$form = $this->createCreateForm($entity);
return array(
'entity' => $entity,
'form' => $form->createView(),
);
}
/**
* Finds and displays a Image entity.
*
* @Route("/{id}", name="image_show", methods={"GET"})
* @Template()
*/
public function showAction($id)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('OxHoardBundle:Image')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find Image entity.');
}
if (!$entity->getIsUserImage()) {
//the image entity technically exists, but we don't want users to access these unless they are flagged as user images.
throw $this->createNotFoundException('Not a user image');
}
$deleteForm = $this->createDeleteForm($id);
return array(
'entity' => $entity,
'delete_form' => $deleteForm->createView(),
);
}
/**
* Displays a form to edit an existing Image entity.
*
* @Route("/{id}/edit", name="image_edit", methods={"GET"})
* @Template()
*/
public function editAction($id)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('OxHoardBundle:Image')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find Image entity.');
}
if (!$entity->getIsUserImage()) {
//the image entity technically exists, but we don't want users to access these unless they are flagged as user images.
throw $this->createNotFoundException('Not a user image');
}
$editForm = $this->createEditForm($entity);
$deleteForm = $this->createDeleteForm($id);
return array(
'entity' => $entity,
'edit_form' => $editForm->createView(),
'delete_form' => $deleteForm->createView(),
);
}
/**
* Creates a form to edit a Image entity.
*
* @param Image $entity The entity
*
* @return \Symfony\Component\Form\Form The form
*/
private function createEditForm(Image $entity)
{
$form = $this->createForm(ImageType::class, $entity, array(
'action' => $this->generateUrl('image_update', array('id' => $entity->getId())),
'method' => 'PUT',
));
$form->add('submit', SubmitType::class, array('label' => 'Update'));
return $form;
}
/**
* Edits an existing Image entity.
*
* @Route("/{id}", name="image_update", methods={"PUT"})
* @Template("@OxHoardBundle/image/edit.html.twig")
*/
public function updateAction(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('OxHoardBundle:Image')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find Image entity.');
}
if (!$entity->getIsUserImage()) {
//the image entity technically exists, but we don't want users to access these unless they are flagged as user images.
throw $this->createNotFoundException('Not a user image');
}
$deleteForm = $this->createDeleteForm($id);
$editForm = $this->createEditForm($entity);
$editForm->handleRequest($request);
if ($editForm->isValid()) {
//save image
$file = $request->files->get('ox_hoardbundle_image');
if(isset($file) && isset($file['file'])) {
$fileName = $file['file']->getClientOriginalName();
$ext = $file['file']->guessExtension();
$destPath = $this->getMiscImageUploadDir();
$savedFile = $file['file']->move($destPath, $fileName);
$entity->setFileName($fileName);
}
$em->flush();
return $this->redirect($this->generateUrl('image_edit', array('id' => $id)));
}
return array(
'entity' => $entity,
'edit_form' => $editForm->createView(),
'delete_form' => $deleteForm->createView(),
);
}
/**
* Deletes a Image entity.
*
* @Route("/{id}", name="image_delete", methods={"DELETE"})
*/
public function deleteAction(Request $request, $id)
{
$form = $this->createDeleteForm($id);
$form->handleRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('OxHoardBundle:Image')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find Image entity.');
}
$em->remove($entity);
$em->flush();
}
return $this->redirect($this->generateUrl('image'));
}
/**
* Creates a form to delete a Image entity by id.
*
* @param mixed $id The entity id
*
* @return \Symfony\Component\Form\Form The form
*/
private function createDeleteForm($id)
{
return $this->createFormBuilder()
->setAction($this->generateUrl('image_delete', array('id' => $id)))
->setMethod('DELETE')
->add('submit', SubmitType::class, array(
'label' => 'Delete',
'attr' => array( 'class' => 'delete-button btn-danger')
))
->getForm()
;
}
}