<?php
namespace App\Controller;
use App\Entity\Article;
use App\Entity\Category;
use App\Entity\Channel;
use App\Entity\Media;
use App\Entity\StripeProduct;
use App\Entity\Card;
use App\Service\ArticleEntityService;
use App\Service\CategoryEntityService;
use App\Service\MediaEntityService;
use App\Service\StripeService;
use Bluesquare\ValidatorBundle\Validator;
use Doctrine\ORM\EntityManagerInterface;
use Http\Client\Exception;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Component\HttpFoundation\ParameterBag;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
class CategoryController extends AbstractController
{
private ParameterBagInterface $parameterBag;
public function __construct(ParameterBagInterface $parameterBag)
{
$this->parameterBag = $parameterBag;
}
/**
* @Route("/actualite/{slug}/{page}", name="category.view", defaults={"page"=1})
*/
public function index(Validator $validator,Request $request, ArticleEntityService $articleService, EntityManagerInterface $manager, CategoryEntityService $categoryService, $slug, $page,StripeService $stripeService)
{
$old_storage_url=$this->parameterBag->get('storage_url');
$old_storage_url = str_replace('http://', '', $old_storage_url);
$new_storage_url=$this->parameterBag->get('storage_url_front');
$new_storage_url = str_replace('http://', '', $new_storage_url);
$category = $categoryService->getBySlug($slug);
if (!$category || !($category instanceof Category))
throw $this->createNotFoundException();
$channel = $manager->getRepository(Channel::class)->findOneBy(['active' => true]);
if (!$channel) throw $this->createNotFoundException();
$articleRepository = $manager->getRepository(Article::class);
$page = intval($page);
$page = max(1, $page);
$limit = 50;
$highlightedArticlesIDS = [];
$highlights = $articleService->formatAll($articleRepository->getHighlightedArticles($channel, 5, $category));
foreach ($highlights as $highlight){
array_push($highlightedArticlesIDS, $highlight['id']);
}
$recent_articles = $articleService->formatAll($articleRepository->getRecentArticles($highlightedArticlesIDS,$category, 3));
foreach ($recent_articles as $recent){
array_push($highlightedArticlesIDS, $recent['id']);
}
$articles = $articleService->formatAll($articleRepository->getALLCategoryArticles($highlightedArticlesIDS, $category, 5, $page));
$count_articles = intval($articleRepository->countCategoryArticles($category));
$pages_number = ceil($count_articles/$limit);
$isLastPage = $page == $pages_number;
$user=$this->getUser();
$productSort=[];
$products = $manager->getRepository(StripeProduct::class)->getMagazines();
$products = array_slice($products, 0, 4, true);
$httpClient = \Symfony\Component\HttpClient\HttpClient::create();
foreach ($products as $k => $product){
$products[$k]['url_front'] = '';
$url = $product['file']."_mobile_298_406";
$old_url = $product['file'] ;
$response = $httpClient->request('HEAD', $url);
$statusCode = $response->getStatusCode();
if ($statusCode === 200) {
$products[$k]['url'] = $url;
}else{
$products[$k]['url'] = $old_url;
}
if(str_contains($products[$k]['url'],$old_storage_url)) {
$url_front = str_replace($old_storage_url,$new_storage_url,$products[$k]['url']);
$products[$k]['url_front'] = $url_front;
}
}
$subscriptionStatus=$stripeService->getSubscriptionStatus($this->getUser());
if ($request->isXmlHttpRequest()) {
$articles = $articleService->formatAll($articleRepository->getALLCategoryArticles($highlightedArticlesIDS, $category, $page*5, 1));
return $this->render('themes/theme-5/article/all-articles.html.twig', [
'validator' => $validator,
'highlighted' => $highlights,
'articles' => $articles,
'category' => $category,
'page' => $page,
'is_last_page' => $isLastPage,
'products' => $products,
'userSubscriptionsStatus'=>$subscriptionStatus,
]);
}
return $this->render('category/category.html.twig', [
'validator' => $validator,
'highlighted' => $highlights,
'articles' => $articles,
'category' => $category,
'page' => $page,
'is_last_page' => $isLastPage,
'products' => $products,
'userSubscriptionsStatus'=>$subscriptionStatus,
'recent_articles' =>$recent_articles,
]);
}
/**
* @Route("/actual/{slug}/{page}", name="sous-category.view" , defaults={"page"=1}))
*/
public function show(Validator $validator,Request $request, ArticleEntityService $articleService, EntityManagerInterface $manager, CategoryEntityService $categoryService, $slug, $page,StripeService $stripeService)
{
$old_storage_url=$this->parameterBag->get('storage_url');
$old_storage_url = str_replace('http://', '', $old_storage_url);
$new_storage_url=$this->parameterBag->get('storage_url_front');
$new_storage_url = str_replace('http://', '', $new_storage_url);
$category = $categoryService->getBySlug($slug);
if (!$category || !($category instanceof Category))
throw $this->createNotFoundException();
$channel = $manager->getRepository(Channel::class)->findOneBy(['active' => true]);
if (!$channel) throw $this->createNotFoundException();
$articleRepository = $manager->getRepository(Article::class);
$page = intval($page);
$page = max(1, $page);
$limit = 50;
$highlights = $articleService->formatAll($articleRepository->getHighlightedArticles($channel, 5, $category));
$countHighliteted = count($highlights);
$key = 0;
if($countHighliteted < 3) {
$key = (3 - $countHighliteted) ;
}
elseif ($countHighliteted == 0){
$key = $countHighliteted;
}
$articles = $articleService->formatAll($articleRepository->getCategoryArticles($category, 7+$key, $page));
$count_articles = intval($articleRepository->countCategoryArticles($category));
$pages_number = ceil($count_articles/$limit);
$isLastPage = $page == $pages_number;
$user=$this->getUser();
$productSort=[];
$products = $manager->getRepository(StripeProduct::class)->getMagazines();
$products = array_slice($products, 0, 4, true);
$httpClient = \Symfony\Component\HttpClient\HttpClient::create();
foreach ($products as $k => $product){
$products[$k]['url_front'] = '';
$url = $product['file']."_mobile_298_406";
$old_url = $product['file'] ;
$response = $httpClient->request('HEAD', $url);
$statusCode = $response->getStatusCode();
if ($statusCode === 200) {
$products[$k]['url'] = $url;
}else{
$products[$k]['url'] = $old_url;
}
if(str_contains($products[$k]['url'],$old_storage_url)) {
$url_front = str_replace($old_storage_url,$new_storage_url,$products[$k]['url']);
$products[$k]['url_front'] = $url_front;
}
}
$subscriptionStatus=$stripeService->getSubscriptionStatus($this->getUser());
if ($request->isXmlHttpRequest()) {
$articles = $articleService->formatAll($articleRepository->getCategoryArticles($category, $page*(6+$key), 1));
return $this->render('themes/theme-5/article/all-articles-sous.html.twig', [
'startAt' =>$key,
'validator' => $validator,
'highlighted' => $highlights,
'articles' => $articles,
'category' => $category,
'page' => $page,
'is_last_page' => $isLastPage,
'products' => $products,
'userSubscriptionsStatus'=>$subscriptionStatus,
]);
}
return $this->render('category/sous-category.html.twig', [
'start' =>$key,
'startAt' =>$key,
'type' =>'sous-category',
'validator' => $validator,
'highlighted' => $highlights,
'articles' => $articles,
'category' => $category,
'page' => $page,
'is_last_page' => $isLastPage,
'products' => $products,
'userSubscriptionsStatus'=>$subscriptionStatus,
]);
}
/**
* @Route("/abonn", name="abonn" )
*/
public function abonn()
{
return $this->render('category/abonne.html.twig');
}
/**
* @Route ("videos-podcast", name="video-podcast")
*/
public function getVideoPodcast(Validator $validator,Request $request, ArticleEntityService $articleService, EntityManagerInterface $manager, CategoryEntityService $categoryService,StripeService $stripeService){
$channel = $manager->getRepository(Channel::class)->findOneBy(['active' => true]);
$articleRepository = $manager->getRepository(Article::class);
$videoPodcast =$articleService->formatAll($articleRepository->getArticlesVideoAndPodcasts());
$highlighted =$articleService->formatAll($articleRepository->getHighlightedArticlesVideoAndPodcasts( 6));
$latest = array_slice($videoPodcast,0,3);
$articles = array_slice($videoPodcast,4);
$video = [];
$Podcast = [];
foreach ($articles as $art ){
foreach ($art["categories"] as $cat){
if ($cat['name'] == "Vidéos"){
$video[] = $art ;
}elseif($cat['name'] == "Podcasts"){
$Podcast[] = $art ;
}
}
}
$countVideo = count($video);
$countPodcast = count($Podcast);
$countArticles = max($countVideo, $countPodcast);
$limit = null;
$isReach = false;
if ($request->isXmlHttpRequest()) {
$limit = $request->get('limit');
$offset = $limit - 3;
$articlePodcast = array_slice($Podcast,$offset, 3);
$articleVideo = array_slice($video,$offset, 3);
//dd($articleVideo, $articlePodcast);
if ($limit >= $countArticles){
$isReach = true;
}
return $this->render(
"themes/theme-5/article/_partials/videopodcast-preview.html.twig",
[
'podcasts' => $articlePodcast,
'videos' => $articleVideo,
'isReach' => $isReach,
]
);
}
$articleVideo = array_slice($video,0, 3);
$articlePodcast = array_slice($Podcast,0, 3);
return $this->render(
"article/videospodcast.html.twig",
[
'articles' => $latest,
'highlighted' => $highlighted,
'videos' => $articleVideo,
'podcasts' => $articlePodcast,
'isReach' => false,
]
);
}
/**
* @Route ("/generateWebpImages", name="video-podcast.show")
*/
public function generateWebpImages(EntityManagerInterface $entityManager,ContainerInterface $container,MediaEntityService $entityService){
set_time_limit(1200000);
session_start();
$temp_dir = $container->get('kernel')->getProjectDir().'/var/temp';
$mediaRepository = $entityManager->getRepository(Media::class);
$medias = $mediaRepository->activedImages();
// $medias = array_slice($medias, 0, 100);
/** @var Media $media */
foreach ($medias as $media) {
$file = $media->getOriginalFile() ? $media->getOriginalFile() : $media->getFile();
if ($this->getParameter("storage_path") && !empty($this->getParameter("storage_path"))) {
$path = $this->getParameter('storage_url') . "/" . $this->getParameter("storage_path") . "/media/" . $file;
} else {
$path = $this->getParameter('storage_url') . "/media/" . $file;
}
$path = trim($path);
if(str_contains($file,'.')){
$extension = explode('.', $file)[1];
}else{
if ($media->getType()=="image/jpeg"){
$extension = "jpeg";
}else{
$extension = explode('/', $media->getType())[1];
}
}
$randomBytes_original = random_bytes(4); // 7 octets (14 caractères hexadécimaux)
$randomHash_original = bin2hex($randomBytes_original);
$file_original=$temp_dir."/".$randomHash_original."-".$randomHash_original.".".$extension;
try {
$content = file_get_contents($path);
if ($content !== false) {
file_put_contents($file_original, $content);
}
}catch (\Exception $e) {
echo "An error occurred for $path: " . $e->getMessage() . "\n";
continue;
}
$randomBytes = random_bytes(4); // 7 octets (14 caractères hexadécimaux)
$randomHash = bin2hex($randomBytes);
$webpFilePath = $temp_dir . "/" . $randomHash . "-" . $randomHash. ".webp";
$types = ['image/jpeg', 'image/png'];
$originalImage = null;
if (in_array($media->getType(), $types)) {
if ($media->getType() == 'image/jpeg') {
try {
$originalImage = imagecreatefromjpeg($path);
if (!$originalImage) {
continue;
}
} catch (\Exception $e) {
echo "An error occurred for $path: " . $e->getMessage() . "\n";
continue;
}
} elseif ($media->getType() == 'image/png') {
try {
$originalImage = imagecreatefrompng($path);
if (!$originalImage) {
continue;
}
} catch (\Exception $e) {
echo "An error occurred for $path: " . $e->getMessage() . "\n";
continue;
}
}
}
if ($originalImage) {
if($media->getType() == 'image/png'){
try {
$sourceImage = imagecreatefrompng($path);
if ($sourceImage) {
$rgbImage = imagecreatetruecolor(imagesx($sourceImage), imagesy($sourceImage));
imagecopy($rgbImage, $sourceImage, 0, 0, 0, 0, imagesx($sourceImage), imagesy($sourceImage));
imagewebp($rgbImage, $webpFilePath,50);
}
} catch (\Exception $e) {
$error=$error+1;
continue;
}
}
else{
imagewebp($originalImage, $webpFilePath,50);
}
try {
$webpData = file_get_contents($webpFilePath);
if ($webpData !== false) {
$webpImage = imagecreatefromwebp('data://image/webp;base64,' . base64_encode($webpData));
}
}catch (\Exception $e) {
$error=$error+1;
continue;
}
if ($webpImage !== false) {
// Get the width and height
$this->setOriginalValues($media,$webpImage);
$entityManager->persist($media);
$uploadedFile = new \Symfony\Component\HttpFoundation\File\UploadedFile(
$webpFilePath,
basename($webpFilePath),
mime_content_type($webpFilePath),
filesize($webpFilePath),
false,
true
);
$uploadedFileOriginal = new \Symfony\Component\HttpFoundation\File\UploadedFile(
$file_original,
basename($file_original),
mime_content_type($file_original),
filesize($file_original),
false,
true
);
$entityService->postValidateThumbnail($media, $uploadedFile, $uploadedFileOriginal,true);
$entityManager->persist($media);
$entityManager->flush();
@unlink($file);
}
}
$cover = $entityService->format($media);
}
}
public function setOriginalValues($media,$webpImage){
$width = imagesx($webpImage);
$height = imagesy($webpImage);
$media->setOriginalThumbnail($media->getThumbnail());
$media->setOriginalWidth($media->getWidth());
$media->setOriginalHeight($media->getHeight());
$media->setOriginalType($media->getType());
$media->setOriginalFile($media->getFile());
$media->setOriginalFilename($media->getFilename());
$media->setWidth($width);
$media->setHeight($height);
}
}