<?php
/**
* Created by PhpStorm.
* User: Mamy
* Date: 25/11/2019
* Time: 14:59
*/
namespace App\Controller;
use App\Entity\Logo;
use App\Entity\Offer;
use App\Entity\Slider;
use App\Entity\Video;
use App\Kernel;
use App\Service\APIRequestService;
use App\Service\Taggage;
use App\Service\Tools;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\ResponseHeaderBag;
use Symfony\Component\Mime\FileinfoMimeTypeGuesser;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpClient\HttpClient;
use App\Service\Mailer;
use Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\DecodingExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\RedirectionExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\ServerExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface;
use Symfony\Contracts\HttpClient\ResponseInterface;
class FrontController extends AbstractController
{
/**
* Home
* @Route("/", name="home", methods={"GET"})
* @param Tools $tools
* @return Response
* @throws ClientExceptionInterface
* @throws DecodingExceptionInterface
* @throws RedirectionExceptionInterface
* @throws ServerExceptionInterface
* @throws TransportExceptionInterface
*/
public function listCatalogs(Tools $tools)
{
$localities = ['saint-denis' => 'Saint-Denis', 'saint-pierre' => 'Saint-Pierre', 'saint-benoit' => 'Saint-Benoit', 'les-avirons' => 'Les Avirons', 'bras-panon' => 'Bras-Panon', 'cilaos' => 'Cilaos', 'entre-deux' => 'Entre-Deux', 'etang-salé' => 'L\'Etang-Salé', 'petite-ile' => 'Petite Ile', 'le-port' => 'Le Port', 'plaine-des-palmistes' => 'La Plaine des Palmistes', 'la-possession' => 'La Possession', 'saint-andré' => 'Saint-Andre', 'sainte-marie' => 'Sainte-Marie', 'sainte-rose' => 'Sainte-Rose', 'sainte-suzanne' => 'Sainte-Suzanne', 'saint-joseph' => 'Saint-Joseph', 'saint-leu' => 'Saint-Leu', 'saint-louis' => 'Saint-Louis', 'saint-paul' => 'Saint-Paul', 'saint-philippe' => 'Saint-Philippe', 'salazie' => 'Salazie', 'le-tampon' => 'Le Tampon', 'trois-bassins' => 'Les Trois-Bassins'];
$home = [
'brands' => [
'brands' => []
],
'catalogue' => [
'title' => '',
'localities' => []
],
'information' => [
'title' => '',
'information' => ''
],
'footer' => [
'copyright' => [
'text' => '',
'tagline' => [
'button_text' => '',
'button_link' => ''
]
]
]
];
try {
$client = HttpClient::create();
$response = $client->request('GET', $this->getParameter('api2_url').'/home',[
'headers' => [
'Accept' => 'application/json',
// 'Authorization' => 'Bearer ' . $this->getConfiguration('api2_token')
],
]);
if ($response->getStatusCode() == 404) {
throw $this->createNotFoundException();
}
$homes = $response->toArray();
if( count($homes) ) {
$home['catalogue'] = [
'localities' => $localities
];
$home['brands'] = $homes['Brands'];
$home['information'] = $homes['Information'];
$home['footer'] = [
'copyright' => $homes['Copyright']
];
}
}catch(\Exception $e) {
}
$sliders = $this->getDoctrine()->getRepository(Slider::class)->findBy(array(
'enabled' => true,
'page' => 'home'
), array(
'priority' => 'ASC',
'priorityUpdatedAt' => 'DESC'
));
foreach ($sliders as $slider) {
$url = $slider->getUrl();
if(!(strpos($url, "http") !== false)){
$url = "https://" . $_SERVER['SERVER_NAME'] . "/" . $url;
$slider->setUrl($url);
}
}
$headerVideo = $this->getDoctrine()->getRepository(Video::class)->findOneBy(array(
'enabled' => true
), array(
'priority' => 'DESC',
'priorityUpdatedAt' => 'DESC'
));
$logos = $this->getDoctrine()->getRepository(Logo::class)->findBy(array(
'enabled' => true
), array(
'priority' => 'ASC',
'priorityUpdatedAt' => 'DESC'
));
$videos = $this->getDoctrine()->getRepository(Video::class)->findBy(array(
'enabled' => true
), array(
'priority' => 'ASC',
'priorityUpdatedAt' => 'DESC'
));
/* pour brand */
$brands = [];
try {
$client = HttpClient::create();
$response = $client->request('GET', $this->getParameter('api2_url').'/brands');
if ($response->getStatusCode() == 404) {
throw $this->createNotFoundException();
}
$marks = $response->toArray();
foreach ($marks as $mark) {
$brands[$mark['id']] = $mark['brand_name'];
}
}catch(\Exception $e) {
}
/* pour catalog */
$catalogs = [];
try {
$client = HttpClient::create();
$response = $client->request('GET', $this->getParameter('api2_url').'/catalogs/actual', [
'headers' => [
'Accept' => 'application/json',
// 'Authorization' => 'Bearer ' . $this->getConfiguration('api2_token')
],
]);
if ($response->getStatusCode() == 404) {
throw $this->createNotFoundException();
}
$catalogs = $response->toArray();
foreach ($catalogs as $idx => $catalog) {
$endDate = date('d-m', strtotime($catalog['date_end']));
$catalogs[$idx]['slug'] = $tools->slugify($catalog['brand_name'].'-'.$endDate.'-'.$catalog['id']);
}
}catch(\Exception $e) {
}
return $this->render('front/catalog/list.html.twig', array(
'home' => $home,
'isProdURI' => $tools->isProdURI(),
'headerVideo' => $headerVideo,
'sliders' => $sliders,
'catalogs' => $catalogs,
'catalogsJson' => json_encode($catalogs),
'logos' => $logos,
'videos' => $videos,
'localities' => $localities
));
}
/**
* List catalogs by locality
* @Route("/commune/{locality}", name="catalogs_by_locality", methods={"GET"})
* @param $locality
* @param Tools $tools
* @return Response
* @throws ClientExceptionInterface
* @throws DecodingExceptionInterface
* @throws RedirectionExceptionInterface
* @throws ServerExceptionInterface
* @throws TransportExceptionInterface
*/
public function listCatalogsByLocality($locality, Tools $tools)
{
$localities = ['saint-denis' => 'Saint-Denis', 'saint-pierre' => 'Saint-Pierre', 'saint-benoit' => 'Saint-Benoit', 'les-avirons' => 'Les Avirons', 'bras-panon' => 'Bras-Panon', 'cilaos' => 'Cilaos', 'entre-deux' => 'Entre-Deux', 'etang-salé' => 'Etang Salé', 'petite-ile' => 'Petite Ile', 'le-port' => 'Le Port', 'plaine-des-palmistes' => 'La Plaine des Palmistes', 'la-possession' => 'La Possession', 'saint-andré' => 'Saint-Andre', 'sainte-marie' => 'Sainte-Marie', 'sainte-rose' => 'Sainte-Rose', 'sainte-suzanne' => 'Sainte-Suzanne', 'saint-joseph' => 'Saint-Joseph', 'saint-leu' => 'Saint-Leu', 'saint-louis' => 'Saint-Louis', 'saint-paul' => 'Saint-Paul', 'saint-philippe' => 'Saint-Philippe', 'salazie' => 'Salazie', 'le-tampon' => 'Le Tampon', 'trois-bassins' => 'Les Trois-Bassins'];
/* pour brand */
$brands = [];
try {
$client = HttpClient::create();
$response = $client->request('GET', $this->getParameter('api2_url').'/brands');
if ($response->getStatusCode() == 404) {
throw $this->createNotFoundException();
}
$marks = $response->toArray();
foreach ($marks as $mark) {
$brands[$mark['id']] = $mark['brand_name'];
}
}catch(\Exception $e) {
}
// getByIdLocation
$filteredCatalogs = [];
try {
$client = HttpClient::create();
$response = $client->request('GET', $this->getParameter('api2_url').'/catalogs/' . $localities[$locality] . '/city', [
'headers' => [
'Accept' => 'application/json',
// 'Authorization' => 'Bearer ' . $this->getConfiguration('api2_token')
],
]);
if ($response->getStatusCode() == 404) {
throw $this->createNotFoundException();
}
$filteredCatalogs = $response->toArray();
foreach ($filteredCatalogs as $idx => $catalog) {
$endDate = date('d-m', strtotime($catalog['date_end']));
$filteredCatalogs[$idx]['slug'] = $tools->slugify($catalog['brand_name'].'-'.$endDate.'-'.$catalog['id']);
}
}catch(\Exception $e){
// perhaps a message
}
return $this->render('front/catalog/catalog-by-locality.html.twig', array(
'isProdURI' => $tools->isProdURI(),
'catalogs' => $filteredCatalogs,
'catalogsJson' => json_encode($filteredCatalogs),
'locality' => $locality,
'localities' => $localities
));
// $pageResponse->setSharedMaxAge($this->getParameter('cache_expiration'));
// $pageResponse->headers->addCacheControlDirective('must-revalidate', true);
// return $pageResponse;
}
/**
* List catalogs
* @Route("/catalogue", name="catalog", methods={"GET"})
* @return RedirectResponse
*/
public function OldListCatalog()
{
return $this->redirectToRoute('home');
}
/**
* View catalog
* @Route("/catalogue/{id}", name="catalog_view", methods={"GET"})
* @param Request $request
* @param $id
* @param Tools $tools
* @return Response
* @throws ClientExceptionInterface
* @throws DecodingExceptionInterface
* @throws RedirectionExceptionInterface
* @throws ServerExceptionInterface
* @throws TransportExceptionInterface
*/
public function viewCatalog(Request $request, $id, Tools $tools)
{
$localities = ['saint-denis' => 'Saint-Denis', 'saint-pierre' => 'Saint-Pierre', 'saint-benoit' => 'Saint-Benoit', 'les-avirons' => 'Les Avirons', 'bras-panon' => 'Bras-Panon', 'cilaos' => 'Cilaos', 'entre-deux' => 'Entre-Deux', 'etang-salé' => 'L\'Etang-Salé', 'petite-ile' => 'Petite Ile', 'le-port' => 'Le Port', 'plaine-des-palmistes' => 'La Plaine des Palmistes', 'la-possession' => 'La Possession', 'saint-andré' => 'Saint-Andre', 'sainte-marie' => 'Sainte-Marie', 'sainte-rose' => 'Sainte-Rose', 'sainte-suzanne' => 'Sainte-Suzanne', 'saint-joseph' => 'Saint-Joseph', 'saint-leu' => 'Saint-Leu', 'saint-louis' => 'Saint-Louis', 'saint-paul' => 'Saint-Paul', 'saint-philippe' => 'Saint-Philippe', 'salazie' => 'Salazie', 'le-tampon' => 'Le Tampon', 'trois-bassins' => 'Les Trois-Bassins'];
$offers = $this->getDoctrine()->getRepository(Offer::class)->findBy(array(
'enabled' => true
), array(
'priority' => 'ASC',
'priorityUpdatedAt' => 'DESC'
));
$videos = $this->getDoctrine()->getRepository(Video::class)->findBy(array(
'enabled' => true
), array(
'priority' => 'ASC',
'priorityUpdatedAt' => 'DESC'
));
/* pour brand */
$brands = [];
try {
$client = HttpClient::create();
$response = $client->request('GET', $this->getParameter('api2_url').'/brands');
if ($response->getStatusCode() == 404) {
throw $this->createNotFoundException();
}
$marks = $response->toArray();
foreach ($marks as $mark) {
$brands[$mark['id']] = [
'brand_name' => $mark['brand_name'],
'brand_logo' => $mark['logo']
];
}
}catch(\Exception $e) {
}
//Get catalog ID from slug
$pathID = explode('-', $id);
$cid = $pathID[count($pathID) - 1];
$client = HttpClient::create();
$response = $client->request('GET', $this->getParameter('api2_url').'/catalogs/'.$cid.'/file', [
'headers' => [
'Accept' => 'application/json',
// 'Authorization' => 'Bearer ' . $this->getConfiguration('api2_token')
],
]);
if ($response->getStatusCode() == 404) {
throw $this->createNotFoundException();
}
if ($response->getStatusCode() == 500) {
throw $this->createNotFoundException();
}
$catalog = $response->toArray();
$page = $request->query->get('page', 1);
// sector
$sectors = strtolower(str_replace([' ','et'], ['',','], $catalog['brand']['category_name']));
$sectors = explode(',', $sectors);
$sectors = array_map(function($value) use($tools) {
$value = strtolower($value);
$value = $tools->slugify($value);
return "secteur=$value";
}, $sectors);
return $this->render('front/catalog/detail.html.twig', array(
'isProdURI' => $tools->isProdURI(),
'catalogID' => $cid,
'catalogTitle' => $catalog['title'],
'catalogSubTitle' => '',
'catalogImage' => '',
'catalogAddresses' => $catalog['addresses'],
'catalog' => [$catalog], //$tools->sortArray($catalog, 'pageNumber'),
'catalogSlug' => $id,
'offers' => $offers,
'videos' => $videos,
'page' => $page,
'currentBreadcrumb' => ucwords($tools->slugify($catalog['title'])),
'thumbnail' => $this->getParameter('api2_url').$catalog['pages'][0]['image']['image_url'],
'announcer' => strtolower($tools->slugify($catalog['brand']['name'])),
'sector' => implode(';', $sectors)
));
// $pageResponse->setSharedMaxAge($this->getParameter('cache_expiration'));
// $pageResponse->headers->addCacheControlDirective('must-revalidate', true);
// return $pageResponse;
}
/**
* About
* @Route("/a-propos", name="about", methods={"GET"})
* @param Tools $tools
* @return Response
* @throws ClientExceptionInterface
* @throws DecodingExceptionInterface
* @throws RedirectionExceptionInterface
* @throws ServerExceptionInterface
* @throws TransportExceptionInterface
*/
public function about(Tools $tools)
{
$headerType = $tools->getConfig('header-type');
$sliders = array();
$headerVideo = null;
if ($headerType == 'image') {
$sliders = $this->getDoctrine()->getRepository(Slider::class)->findBy(array(
'enabled' => true
), array(
'priority' => 'ASC',
'priorityUpdatedAt' => 'DESC'
));
} else {
$headerVideo = $this->getDoctrine()->getRepository(Video::class)->findOneBy(array(
'enabled' => true
), array(
'priority' => 'DESC',
'priorityUpdatedAt' => 'DESC'
));
}
$offers = $this->getDoctrine()->getRepository(Offer::class)->findBy(array(
'enabled' => true
), array(
'priority' => 'ASC',
'priorityUpdatedAt' => 'DESC'
));
$catalogs = [];
try {
$client = HttpClient::create();
$response = $client->request('GET', $this->getParameter('api2_url').'/api/catalogs');
if ($response->getStatusCode() == 404) {
throw $this->createNotFoundException();
}
$catalogs = $response->toArray();
}catch(\Exception $e){
// perhaps a message
}
$logos = $this->getDoctrine()->getRepository(Logo::class)->findBy(array(
'enabled' => true
), array(
'priority' => 'ASC',
'priorityUpdatedAt' => 'DESC'
));
$videos = $this->getDoctrine()->getRepository(Video::class)->findBy(array(
'enabled' => true
), array(
'priority' => 'ASC',
'priorityUpdatedAt' => 'DESC'
));
$videos600 = (count($videos) > 2) ? 2 : count($videos);
$videos1000 = (count($videos) > 3) ? 3 : count($videos);
return $this->render('front/about.html.twig', array(
'isProdURI' => $tools->isProdURI(),
'headerVideo' => $headerVideo,
'sliders' => $sliders,
'offers' => $offers,
'catalogs' => $catalogs,
'logos' => $logos,
'videos' => $videos,
'videos600' => $videos600,
'videos1000' => $videos1000
));
// $pageResponse->setSharedMaxAge($this->getParameter('cache_expiration'));
// $pageResponse->headers->addCacheControlDirective('must-revalidate', true);
// return $pageResponse;
}
/**
* Download pdf
* @Route("/pdf/{filename}", name="download_pdf", methods={"GET"})
* @param $filename
* @return BinaryFileResponse
*/
public function pdf($filename)
{
$file = $this->getParameter('uploads_pdf_dir').$filename;
$response = new BinaryFileResponse($file);
$mimeTypeGuesser = new FileinfoMimeTypeGuesser();
if ($mimeTypeGuesser->isGuesserSupported()) {
$response->headers->set('Content-Type', $mimeTypeGuesser->guessMimeType($file));
} else {
$response->headers->set('Content-Type', 'text/plain');
}
$response->setContentDisposition(
ResponseHeaderBag::DISPOSITION_ATTACHMENT,
$filename
);
return $response;
}
/**
* Download android app
* @Route("/android.html", name="download_android_app", methods={"GET"})
* @return Response
*/
public function android()
{
return $this->render('android.html.twig');
}
/**
* Download ios app
* @Route("/ios.html", name="download_ios_app", methods={"GET"})
* @return Response
*/
public function ios()
{
return $this->render('ios.html.twig');
}
/**
* SiteMap
* @Route("/sitemap.xml", name="sitemap", defaults={"_format"="xml"})
* @param Request $request
* @param Tools $tools
* @return Response|ResponseInterface
* @throws ClientExceptionInterface
* @throws DecodingExceptionInterface
* @throws RedirectionExceptionInterface
* @throws ServerExceptionInterface
* @throws TransportExceptionInterface
*/
public function siteMap(Request $request, Tools $tools)
{
$hostname = $request->getSchemeAndHttpHost();
$urls = [];
//Static urls
$urls[] = ['loc' => $this->generateUrl('home'), 'changefreq' => 'daily', 'priority' => '1.0'];
$urls[] = ['loc' => $this->generateUrl('about'), 'changefreq' => 'weekly', 'priority' => '1.0'];
$urls[] = ['loc' => $this->generateUrl('faq'), 'changefreq' => 'monthly', 'priority' => '1.0'];
$urls[] = ['loc' => $this->generateUrl('covid-19'), 'changefreq' => 'daily', 'priority' => '1.0'];
$urls[] = ['loc' => $this->generateUrl('download_pdf', ['filename' => 'ml-rodzafer.pdf']), 'changefreq' => 'monthly', 'priority' => '0.80'];
$urls[] = ['loc' => $this->generateUrl('download_pdf', ['filename' => 'charte-utilisation-ar.pdf']), 'changefreq' => 'monthly', 'priority' => '0.80'];
$urls[] = ['loc' => $this->generateUrl('download_pdf', ['filename' => 'charte-donnee-rodzafer.pdf']), 'changefreq' => 'monthly', 'priority' => '0.80'];
$client = HttpClient::create();
$response = $client->request('GET', $this->getParameter('api2_url').'/api/catalogs');
if ($response->getStatusCode() == 200) {
$catalogs = $response->toArray()['hits'];
foreach ($catalogs as $idx => $catalog) {
$name = $catalog['company']['name'];
$endDate = date('d-m', strtotime($catalog['dateEnd']));
$urls[] = ['loc' => $this->generateUrl('catalog_view', ['id' => $tools->slugify($name.'-'.$endDate.'-'.$catalog['_id'])]), 'changefreq' => 'daily', 'priority' => '0.80'];
}
}
$response = $this->render('sitemap.html.twig', [
'urls' => $urls,
'hostname' => $hostname
]);
$response->headers->set('Content-Type', 'text/xml');
return $response;
}
/**
* SiteMap
* @Route("/contactez-nous.json", name="contact_nous", defaults={"_format"="json"}, methods={"POST"})
* @param Request $request
* @param Mailer $mailer
* @return Response
* @throws ClientExceptionInterface
* @throws DecodingExceptionInterface
* @throws RedirectionExceptionInterface
* @throws ServerExceptionInterface
* @throws TransportExceptionInterface
*/
public function contactNous(Request $request, Mailer $mailer)
{
$projectRoot = Kernel::getProjectDir();
date_default_timezone_set("Indian/Reunion");
// data item
$item = [
'civ' => $request->request->get('civ'),
'nom' => $request->request->get('nom'),
'prenom' => $request->request->get('prenom'),
'email' => $request->request->get('email'),
'phone' => $request->request->get('phone'),
'activite' => $request->request->get('activite'),
'entreprise' => $request->request->get('entreprise'),
'fonction' => $request->request->get('fonction'),
'internet' => $request->request->get('internet'),
'option_tv' => $request->request->get('option_tv'),
'option_partenaire' => $request->request->get('option_partenaire'),
'comment' => $request->request->get('comment'),
'ip_address' => $request->request->get('ip_address')
];
// retour
$return = [
'error' => false,
'message' => ''
];
$blockMail = $this->blockMail($item['email'], $projectRoot);
// test si l'adresse email est sur la liste noire
if ($blockMail) {
$return = [
'error' => true,
'message' => "Votre adresse email est bloquée"
];
} else {
// check google captcha
$client = HttpClient::create();
$response = $client->request(
'POST',
'https://www.google.com/recaptcha/api/siteverify',
[
'body' => [
'secret' => '6LfaeuQUAAAAABAOWavgf6FnQ5ijlRIL8njokb9i',
'response' => $_POST['g-recaptcha-response'],
'remoteip' => $_SERVER['REMOTE_ADDR']
]
]
);
// test si captcha valid
$google = $response->toArray();
if( !$google['success'] )
{
$return = [
'error' => true,
'message' => 'Temps de validation dépassé ou donnée captcha erroné. veuillez réessayer'
];
}
else
{
// Send email
$mailer->setFrom($this->getParameter('mailer_from'));
$mailer->setFromName($this->getParameter('mailer_from_name'));
$mailer->setTo('[email protected]');
$mailer->setBcc(array('[email protected]','[email protected]','[email protected]'));
$mailer->setSubject('Contact RodZafer');
$mailer->setTemplate($this->renderView('email/contactez-nous.html.twig', array(
'item' => $item
)));
$mailer->send();
$return = [
'error' => false,
'message' => 'Message envoyé'
];
$arr = array(
"email" => $item['email'],
"date" => date("j-n-Y H:i:s"),
"ip_infos" => $item['ip_address']
);
file_put_contents($projectRoot.'/public/log_formulaire/log.log', json_encode($arr), FILE_APPEND);
}
}
return new JsonResponse($return);
}
/**
* Universal link for IOS
* @Route("/product", name="universal_link_ios", methods={"GET"})
* @return Response
*/
public function universalLinkIOS()
{
return new Response('Veuillez cliquer sur le bouton open');
}
/**
* Generate signboards data
* @Route("/data/enseignes.json", name="signboards_data", methods={"GET"})
* @param APIRequestService $requestService
* @return JsonResponse
* @throws ClientExceptionInterface
* @throws DecodingExceptionInterface
* @throws RedirectionExceptionInterface
* @throws ServerExceptionInterface
* @throws TransportExceptionInterface
*/
public function signboardData(APIRequestService $requestService)
{
$signboards = $requestService->get($this->getParameter('api_url').'/point_of_sales?order[signboard]=asc');
foreach ($signboards as $idx => $signboard) {
$signboards[$idx]['id'] = $signboards[$idx]['externalId'];
unset($signboards[$idx]['externalId']);
}
$response = new JsonResponse($signboards);
$response->setEncodingOptions(JSON_UNESCAPED_UNICODE);
return $response;
}
/**
* @Route("/catalogs", methods={"GET"})
* @return RedirectResponse
*/
public function listCatalogsOldUrl()
{
return $this->redirectToRoute('home');
}
/**
* @Route("/catalog", methods={"GET"})
* @return RedirectResponse
*/
public function listCatalogsOldUrl2()
{
return $this->redirectToRoute('home');
}
/**
* @Route("/catalog/{id}", methods={"GET"})
* @param $id
* @return RedirectResponse
*/
public function viewCatalogOldUrl($id)
{
return $this->redirectToRoute('catalog_view', ['id' => $id]);
}
/**
* Compress catalog's image
* @Route("/image/{filename}/{id}", name="compress_image", methods={"GET"}, requirements={"filename":"[a-zA-Z0-9-_\/.]+"})
* @param Request $request
* @param $filename
* @return Response
*/
public function compressImage(Request $request, $filename, $id)
{
$imageUrl = $this->getParameter('api2_url').$filename;
$pathParts = pathinfo($imageUrl);
$directory = $this->getParameter('uploads_catalog_dir').$id;
$file = $directory.'/'.str_replace('/', '_', $filename);
if (!file_exists($this->getParameter('uploads_catalog_dir')))
mkdir($this->getParameter('uploads_catalog_dir'));
if (!file_exists($directory))
mkdir($directory);
if (!file_exists($file)) {
try {
\Tinify\setKey($this->getParameter('tiny_png_key'));
$source = \Tinify\fromUrl($imageUrl);
$source->toFile($file);
} catch (\Tinify\AccountException $e) {
file_put_contents($file, file_get_contents($imageUrl));
} catch(\Tinify\Exception $e) {
file_put_contents($file, file_get_contents($imageUrl));
}
}
//if (strpos($file, 'p-1.jpg')) {
// $this->resize_crop_image(600, 315, $file, str_replace('p-1.jpg', 'thumbnail.jpg', $file));
//}
return new Response('OK');
}
function resize_crop_image($max_width, $max_height, $source_file, $dst_dir, $quality = 80){
$imgsize = getimagesize($source_file);
$width = $imgsize[0];
$height = $imgsize[1];
$mime = $imgsize['mime'];
switch($mime){
case 'image/gif':
$image_create = "imagecreatefromgif";
$image = "imagegif";
break;
case 'image/png':
$image_create = "imagecreatefrompng";
$image = "imagepng";
$quality = 7;
break;
case 'image/jpeg':
$image_create = "imagecreatefromjpeg";
$image = "imagejpeg";
$quality = 80;
break;
default:
return false;
break;
}
$dst_img = imagecreatetruecolor($max_width, $max_height);
$src_img = $image_create($source_file);
$width_new = $height * $max_width / $max_height;
$height_new = $width * $max_height / $max_width;
//if the new width is greater than the actual width of the image, then the height is too large and the rest cut off, or vice versa
if($width_new > $width) {
//cut point by height
$h_point = (($height - $height_new) / 2);
//copy image
imagecopyresampled($dst_img, $src_img, 0, 0, 0, $h_point, $max_width, $max_height, $width, $height_new);
} else {
//cut point by width
$w_point = (($width - $width_new) / 2);
imagecopyresampled($dst_img, $src_img, 0, 0, $w_point, 0, $max_width, $max_height, $width_new, $height);
}
$image($dst_img, $dst_dir, $quality);
if ($dst_img) imagedestroy($dst_img);
if ($src_img) imagedestroy($src_img);
}
private function getConfiguration($configName)
{
$_CONFIGURATION = [];
$user = $this->getParameter('api_user');
$password = $this->getParameter('api_pwd');
// ancien système de token
// $_CONFIGURATION['api2_token'] = $this->getParameter('api2_token');
// nouveau système de récupération de token
$_CONFIGURATION['api2_token'] = $this->getJwt($user, $password);
return $_CONFIGURATION[$configName];
}
private function getJwt($user, $password)
{
$auth_route = $this->getParameter('api2_url').'/auth/local';
$payload = json_encode([
'identifier' => $user,
'password' => $password
]);
$header = ['Content-Type' => 'application/json'];
$client = HttpClient::create();
$response = $client->request('POST', $auth_route,[
'headers' => $header,
'body' => $payload
]);
if ($response->getStatusCode() == 200){
$responseArray = $response->toArray();
if ($responseArray['jwt'])
return $responseArray['jwt'];
}
return null;
}
private function blockMail($mail, $root) {
$data = file_get_contents($root . "/public/log_formulaire/mail.txt");
if (!empty($data)) {
$arr_mails = explode("|", $data);
if (in_array($mail, $arr_mails)) {
return true;
} else {
return false;
}
} else {
return false;
}
}
}