<?php
namespace App\Controller\Frontend;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\Security;
use App\Entity\Media\DocumentType;
use App\Entity\Media\Category;
use App\Entity\Media\Document;
use App\Form\Media\DocumentFrontFilterType;
use App\Entity\Federation\Classe;
use App\Entity\Federation\Boat;
use App\Entity\Federation\Skipper;
use Symfony\Component\Finder\Exception\AccessDeniedException;
use App\Entity\Media\Conversion;
use App\Entity\Media\Tag;
use App\Entity\History\History;
use App\Form\Media\DownloadMultipleType;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\ResponseHeaderBag;
use Symfony\Component\HttpFoundation\File\File;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Gedmo\Sluggable\Util\Urlizer;
use Symfony\Component\HttpFoundation\JsonResponse;
use App\Entity\Federation\Participation;
use App\Entity\Site\AccessSite;
use App\Entity\Media\Cart;
use App\Service\Site\SiteManager;
use App\Service\Aws\AwsManager;
use App\Service\Media\DownloadManager;
use Symfony\Contracts\Translation\TranslatorInterface;
class DocumentController extends AbstractController
{
public function listAction(Request $request, string $documentTypeSlug, $page, Category $category = null, Security $security, $clear, SiteManager $siteManager)
{
$requestDatas = $request->request->all();
$page = intval($page);
if ($page < 1) $page = 1;
$itemsPerPage = $this->getParameter('application.front_item_per_page');
if($clear == 'clear')
$this->get('session')->remove('document_frontend_filter');
if($request->isMethod('POST') && !empty($requestDatas))
$this->get('session')->set('document_frontend_filter', $requestDatas['document_frontend_filter']);
$em = $this->getDoctrine()->getManager();
$user = $security->getUser();
$documentType = $em->getRepository(DocumentType::class)->findOneByDirectoryName($documentTypeSlug);
$access = $siteManager->userAccessSite($user);
if(empty($category) || (!is_null($category) && !$access->getCategories()->contains($category)))
throw new AccessDeniedException();
$form = $this->createForm(DocumentFrontFilterType::class, null, array(
'race' => $siteManager->getCurrentSite()->getRace()
));
$filter = true;
if(!empty($this->get('session')->get('document_frontend_filter')))
{
$sessionDatas = $this->get('session')->get('document_frontend_filter');
$classes = $boats = $skippers = $tags = array();
if(empty($sessionDatas['classe']) && empty($sessionDatas['boat']) && empty($sessionDatas['skipper']))
$filter = false;
if(!empty($sessionDatas['date']))
{
$date = explode('/', $sessionDatas['date']);
$form->get('date')->setData(new \DateTime($date[2].'-'.$date[1].'-'.$date[0]));
}
if(!empty($sessionDatas['tags']))
{
foreach ($sessionDatas['tags'] as $tag)
array_push($tags, $em->getRepository(Tag::class)->find($tag));
$form->get('tags')->setData($tags);
}
if(!empty($sessionDatas['classe']))
{
$classe = $em->getRepository(Classe::class)->find($sessionDatas['classe']);
array_push($classes, $classe);
$form->get('classe')->setData($classe);
} else {
if($category->isRestrictiveCategory())
$classes = $access->getClasses();
else
$classes = [];
}
if(!empty($sessionDatas['boat']))
{
$boat = $em->getRepository(Boat::class)->find($sessionDatas['boat']);
array_push($boats, $boat);
$form->get('boat')->setData($boat);
} else {
if($category->isRestrictiveCategory())
$boats = $access->getBoats();
else
$boats = [];
}
if(!empty($sessionDatas['skipper']))
{
$skipper = $em->getRepository(Skipper::class)->find($sessionDatas['skipper']);
array_push($skippers, $skipper);
$form->get('skipper')->setData($skipper);
} else {
if($category->isRestrictiveCategory())
$skippers = $access->getSkippers();
else
$skippers = [];
}
//Get All Result
$documents = $this->getDoctrine()
->getManager()
->getRepository(Document::class)
->getFrontAccessDocuments($page, $itemsPerPage, $documentType, $filter, $siteManager->getCurrentSite()->getRace(), $category, $classes, $boats, $skippers, $form['date']->getData(), $tags);
} else {
if($category->isRestrictiveCategory()){
$classes = $access->getClasses();
$boats = $access->getBoats();
$skippers = $access->getSkippers();
} else {
$classes = [];
$boats = [];
$skippers = [];
}
//Get All Result
$documents = $this->getDoctrine()
->getManager()
->getRepository(Document::class)
->getFrontAccessDocuments($page, $itemsPerPage, $documentType, false, $siteManager->getCurrentSite()->getRace(), $category, $classes, $boats, $skippers);
}
$nbPages = ceil(count($documents) / $itemsPerPage);
if ($page > $nbPages && $page > 1)
throw $this->createNotFoundException($this->get('translator')->trans("messages.error.page_no_exist", array('%page%' => $page), 'InodiaBundlesBackendBundle'));
$this->forward('App\Controller\Frontend\CartController::loadCart', ['isRequest' => true]);
return $this->render('Frontend/Views/Document/list.html.twig', array(
'access' => $access,
'documentType' => $documentType,
'category' => $category,
'documents' => $documents,
'form' => $form->createView(),
'nbPages' => $nbPages,
'page' => $page,
'cart' => $em->getRepository(Cart::class)->findOneByAccessSite($access)
));
}
public function proofValidationAction(Request $request, Document $document, Security $security, TranslatorInterface $translator)
{
$user = $security->getUser();
if(sizeof($document->getSkippers()) > 0 || sizeof($document->getBoats()) > 0){
$referents = $this->getDoctrine()->getManager()->getRepository(\App\Entity\Federation\Participation::class)->getReferents($document->getRace(), $document->getBoats(), $document->getSkippers());
foreach ($referents as $key => $referent)
$referents[$key] = $this->getDoctrine()->getManager()->getRepository(\App\Entity\User\User::class)->find($referent['id']);
}
if(!in_array($user, $referents) || $document->getStatus() != 1)
return new AccessDeniedException();
$document->setStatus(0);
$document->setProofValidationUser($user);
$document->setProofValidationDate(new \DateTime());
$this->getDoctrine()->getManager()->flush();
$this->addFlash('success', $translator->trans('document.email.proof-validation-confirmation'));
return $this->redirectToRoute('frontend_homepage');
}
public function viewAction(Document $document, SiteManager $siteManager, Security $security, AwsManager $awsManager)
{
$em = $this->getDoctrine()->getManager();
$proofValidation = false;
$user = $security->getUser();
$access = $siteManager->userAccessSite($user);
if(sizeof($document->getSkippers()) > 0 || sizeof($document->getBoats()) > 0){
$referents = $this->getDoctrine()->getManager()->getRepository(\App\Entity\Federation\Participation::class)->getReferents($document->getRace(), $document->getBoats(), $document->getSkippers());
if(!empty($referents))
{
foreach ($referents as $key => $referent)
if(!empty($referent['id']))
$referents[$key] = $this->getDoctrine()->getManager()->getRepository(\App\Entity\User\User::class)->find($referent['id']);
}
}
if(isset($referents))
if(in_array($user, $referents) && $document->getStatus() == 1)
$proofValidation = true;
if($document->getDocumentType()->getDirectoryName() == 'documents') {
$pathinfo = pathinfo($document->getFile()['Key']);
$previewUrl = $awsManager->createGetUrlPreviewPresignedRequest($document->getRace()->getDirectoryName(), $document->getFile()['Key'], null, 'application/'.$pathinfo['extension']);
}
return $this->render('Frontend/Views/Document/view-'.$document->getDocumentType()->getDirectoryName().'.html.twig', array(
'document' => $document,
'proofValidation' => $proofValidation,
'cart' => $em->getRepository(Cart::class)->findOneByAccessSite($access),
'previewUrl' => !empty($previewUrl) ? $previewUrl : '',
'application' => !empty($pathinfo['extension']) ? 'application/'.$pathinfo['extension'] : '',
));
}
public function pictureAction(Request $request, Document $document)
{
$proofValidation = false;
$downloadUrls = array();
$em = $this->getDoctrine()->getManager();
$user = $this->get('security.token_storage')->getToken()->getUser();
$form = $this->createForm(DownloadMultipleType::class, null, array());
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$documents = $form['documents']->getData();
foreach($documents as $downloadId)
{
$download = $em->getRepository(Document::class)->find($downloadId);
$parentDocument = $download->getParentDocument();
$this->saveDownload($user, $download);
array_push($downloadUrls, $download->getUri());
}
if(!empty($downloadUrls))
{
$name = str_replace($parentDocument->getDocumentType()->getDirectoryName().'/', '', $parentDocument->getDirectoryName()).'.zip';
$path = 'download/'.$name;
$this->createArchive($downloadUrls, $path);
$response = new BinaryFileResponse($path);
$response->setContentDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT, $name);
$response->deleteFileAfterSend(true);
return $response;
}
}
if(sizeof($document->getSkippers()) > 0 || sizeof($document->getBoats()) > 0){
$referents = $em->getRepository(\App\Entity\Federation\Participation::class)->getReferents($document->getRace(), $document->getBoats(), $document->getSkippers());
foreach ($referents as $key => $referent)
{
if(!empty($referent['id']))
$referents[$key] = $em->getRepository(\App\Entity\User\User::class)->find($referent['id']);
}
}
if(isset($referents))
if(in_array($user, $referents) && $document->getStatus() == 1)
$proofValidation = true;
return $this->render('Frontend/Views/Document/picture.html.twig', array(
'document' => $document,
'proofValidation' => $proofValidation,
'form' => $form->createView()
));
}
public function downloadAction(Document $document, Conversion $conversion = null, AwsManager $aws, DownloadManager $downloadManager, Security $security)
{
$bucket = $document->getRace()->getDirectoryName();
$user = $security->getUser();
$name = Urlizer::urlize($document->getTitle());
if(!is_null($conversion))
$download = $conversion;
else
$download = $document;
$fileName = explode('.', basename($download->getFile()['Key']));
$extension = end($fileName);
if($user && $download)
{
$this->saveDownload($user, $download, $downloadManager);
$generateUrl = $aws->createGetUrlPresignedRequest($bucket, $download->getFile()['Key'], $name.'.'.$extension);
return $this->redirect($generateUrl);
}
exit();
}
public function saveDownload($user, $download, DownloadManager $downloadManager)
{
$downloadManager->saveDownload($download);
}
public function createArchive($urls, $path)
{
$zip = false;
if(!empty($urls))
{
$zip = new \ZipArchive();
$zip->open($path, \ZipArchive::CREATE);
foreach($urls as $url){
$file = file_get_contents($url);
$zip->addFromString(basename($url), $file);
}
$zip->close();
}
return $zip;
}
public function getDocumentsFiltersOptionsAction(Request $request, Category $category, Classe $classe = null, Boat $boat = null, Skipper $skipper = null, SiteManager $siteManager)
{
$response = array(
'classes' => array(),
'boats' => array(),
'skippers' => array()
);
if($request->isXmlHttpRequest()) {
$em = $this->getDoctrine()->getManager();
$race = $siteManager->getCurrentSite()->getRace();
$user = $this->get('security.token_storage')->getToken()->getUser();
$access = $siteManager->userAccessSite($user);
if(is_null($boat)) $response['boats'][] = array('id' => '', 'text' => '');
if(is_null($skipper)) $response['skippers'][] = array('id' => '', 'text' => '');
if(is_null($classe)) $response['classes'][] = array('id' => '', 'text' => '');
if(!is_null($boat))
{
$response['boats'][] = array('id' => $boat->getId(), 'text' => $boat->getName());
$response['classes'][] = array('id' => $boat->getClasse()->getId(), 'text' => $boat->getClasse()->getName());
$participation = $em->getRepository(Participation::class)->findOneBy(array('race' => $race, 'boat' => $boat));
$response['skippers'][] = array('id' => $participation->getSkipper()->getId(), 'text' => $participation->getSkipper()->getName());
} else if(!is_null($skipper)){
$response['skippers'][] = array('id' => $skipper->getId(), 'text' => $skipper->getName());
$participation = $em->getRepository(Participation::class)->findOneBy(array('race' => $race, 'skipper' => $skipper));
$response['boats'][] = array('id' => $participation->getBoat()->getId(), 'text' => $participation->getBoat()->getName());
$response['classes'][] = array('id' => $participation->getBoat()->getClasse()->getId(), 'text' => $participation->getBoat()->getClasse()->getName());
} else if(!is_null($classe)) {
$response['classes'][] = array('id' => $classe->getId(), 'text' => $classe->getName());
$boats = $em->getRepository(Boat::class)->findBy(array('classe' => $classe));
if(sizeof($access->getBoats()) > 0)
{
foreach($access->getBoats() as $boat)
foreach($boats as $b)
if($b == $boat)
$response['boats'][] = array('id' => $boat->getId(), 'text' => $boat->getName());
} else if(sizeof($boats) > 0){
foreach($boats as $boat)
$response['boats'][] = array('id' => $boat->getId(), 'text' => $boat->getName());
}
if(!empty($response['boats']))
{
foreach($response['boats'] as $boat)
{
$participation = $em->getRepository(Participation::class)->findOneBy(array('race' => $race, 'boat' => $boat));
if(!empty($participation))
$response['skippers'][] = array('id' => $participation->getSkipper()->getId(), 'text' => $participation->getSkipper()->getName());
}
}
} else {
$response = $this->getDocumentsFiltersOptionsByAccess($access, $response);
}
}
return new JsonResponse($response, 200);
}
public function searchInOptionsArray($array = null, $id)
{
$find = false;
foreach($array as $value)
if($value['id'] == $id)
$find = true;
return $find;
}
public function getDocumentsFiltersOptionsByAccess(AccessSite $access, $response)
{
$result = $response;
$em = $this->getDoctrine()->getManager();
$participations = $em->getRepository(Participation::class)->findBy(array('race' => $access->getSite()->getRace()));
if(sizeof($access->getClasses()) == 0)
{
foreach($participations as $participation)
if(!$this->searchInOptionsArray($result['classes'], $participation->getBoat()->getClasse()->getId()))
$result['classes'][] = array('id' => $participation->getBoat()->getClasse()->getId(), 'text' => $participation->getBoat()->getClasse()->getName());
} else {
foreach($access->getClasses() as $classe)
$result['classes'][] = array('id' => $classe->getId(), 'text' => $classe->getName());
}
if(sizeof($access->getBoats()) == 0)
{
foreach($participations as $participation)
$result['boats'][] = array('id' => $participation->getBoat()->getId(), 'text' => $participation->getBoat()->getName());
} else {
foreach($access->getBoats() as $boat)
$result['boats'][] = array('id' => $boat->getId(), 'text' => $boat->getName());
}
if(sizeof($access->getSkippers()) == 0)
{
foreach($participations as $participation)
$result['skippers'][] = array('id' => $participation->getSkipper()->getId(), 'text' => $participation->getSkipper()->getName());
} else {
foreach($access->getSkippers() as $skipper)
$result['skippers'][] = array('id' => $skipper->getId(), 'text' => $skipper->getName());
}
return $result;
}
}