<?php
namespace App\Controller;
use App\Entity\Allpublications;
use App\Entity\Category;
use App\Entity\Follow;
use App\Entity\Journal;
use App\Entity\Newsletter;
use App\Entity\User;
use App\Form\AccountType;
use App\Form\AllPublicationCreateType;
use App\Form\AllPublicationType;
use App\Form\DisactivationType;
use App\Form\PasswordChangeType;
use App\Manager\PublicationManager;
use App\Repository\AllPublicationRepository;
use App\Repository\CategoryRepository;
use App\Repository\UserRepository;
use Doctrine\ORM\EntityManagerInterface;
use Knp\Component\Pager\PaginatorInterface;
use MongoDB\Driver\Manager;
use Psr\Log\LoggerInterface;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpClient\HttpClient;
use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface;
/**
* @IsGranted("ROLE_USER")
* @Route("/{_locale}/profile/conference")
*/
class BaseController extends AbstractController
{
/** @var EntityManagerInterface */
private $entityManager;
/**
* BaseController constructor.
* @param LoggerInterface $logger
*/
/** @var LoggerInterface */
private $logger;
private $encoder;
public function __construct(LoggerInterface $logger,EntityManagerInterface $entityManager, UserPasswordEncoderInterface $encoder)
{
$this->logger = $logger;
$this->entityManager = $entityManager;
$this->encoder=$encoder;
}
/**
* @Route("/home", name="homepage__")
*/
public function indexAction()
{
return $this->render('index.html.twig');
}
/**
* @Route("/author_search", name="author_search", methods={"GET"})
*/
public function author_search(Request $request)
{
$emS = $this->getDoctrine()->getManager();
$array_crossref=[];
$exist = $emS->getRepository(Allpublications::class)->findBy(['user' => $this->getUser()]);
$firstname='';$lastname="";$userFirstName="";
$manyRequests=false;
if($this->getUser()){
$firstname=$this->getUser()->getFirstName();
$lastname=$this->getUser()->getLastName();
$userFirstName=$this->getUser()->getFirstName();
}else{
return $this->redirectToRoute('registre_user');
}
$cookies = $request->cookies;
$skipSuggestProfile= $cookies->get('skip-suggest-profile');
if ((empty($exist) && $this->getUser()->getFullName()) || ($skipSuggestProfile && $skipSuggestProfile == 'true')) {
if (str_contains($firstname, '.')) {
$firstname = str_replace('.', "", $firstname);
} if (str_contains($lastname, '.')) {
$lastname = str_replace('.', "", $lastname);
}
return $this->redirectToRoute('publication_index',['firstname'=>$firstname,"lastname"=>$lastname,'id'=>$this->getUser()->getId()]);
} else {
$auteur = $userFirstName;
$test = false;
if (strpos($request->getUri(), 'authorValue') !== false) {
$test = true;
}
$param = urlencode($auteur); // str_replace(' ','+',$auteur);
$data = null;
try {
$rawData = HttpClient::create()
->request('GET', "https://api.crossref.org/works?query.author=$param&rows=40");
if($rawData->getStatusCode()=== 200) {
$rawData = $rawData->getContent();
$data = \json_decode($rawData);
if(isset($data->message->items)) {
$articles=$data->message->items;
foreach ($articles as $article){
$auteurs=$article->author;
foreach ($auteurs as $aut){
$family='';
$given='';
$name='';
if(isset($aut->family)){
$family=strtolower($aut->family);
}if (isset($aut->given)){
$given=strtolower($aut->given);
}
if($family && $given && ($family==strtolower($lastname) || $given==strtolower($firstname))){
$name=strtolower($given).' '.strtolower($family);
}elseif ($family && $family==strtolower($firstname) ){
$name=strtolower($family);
}elseif ($given && $given==strtolower($firstname)){
$name=strtolower($given);
}
if($name && !in_array($name,$array_crossref)) $array_crossref[]=$name;
}
}
}
} else{
return $this->redirectToRoute("publication_index",['firstname'=>$firstname,"lastname"=>$lastname,'id'=>$this->getUser()->getId()]);
}
} catch (TransportExceptionInterface $exception) {
$this->addFlash('error', 'Ooops ! Something wrong happened. Please retry again or contact the support');
$this->logger->critical($exception->getTraceAsString());
}
// set cookie to skip suggest profile true
$response = new Response();
$response->headers->setCookie(new Cookie('skip-suggest-profile', 'true'));
return $this->render('refonte/authors/author_search.html.twig', [
'data' => $array_crossref
]);
}
}
/**
* @Route("/save_url_social", name="save_url_social")
*/
public function save_url_social(Request $request)
{
/** @var User $user */
$user=$this->getUser();
$facebook=$request->get('facebook');
$twitter=$request->get('twitter');
$linkeid=$request->get('linkedin');
$youtube=$request->get('youtube');
$instagram=$request->get('instagram');
if($facebook!=""){
$user->setFacebook($facebook);
}
if($twitter!=""){
$user->setTwitter($twitter);
}
if($linkeid!=""){
$user->setLinkedin($linkeid);
}
if($youtube!=""){
$user->setYoutube($youtube);
}
if($instagram!=""){
$user->setInstagram($instagram);
}
if($facebook!="" || $twitter!="" || $linkeid!="" || $youtube!="" || $instagram!=""){
$em=$this->getDoctrine()->getManager();
$em->persist($user);
$em->flush();
$this->addFlash('success','Your social media links have been successfully saved.');
}
return $this->redirectToRoute('author_search');
}
/**
* @Route("/allpublications" ,name="get_author_allpublication_profile",options = { "expose" = true })
*
*/
public function callAllpubapi(Request $request,EntityManagerInterface $em){
$auteur = $request->get('auteur');
$param=str_replace(' ','+',$auteur);
$data = null;
$data_crossref=null;
$auteur = $request->get('auteur');
$param = urlencode($auteur); // str_replace(' ','+',$auteur);
try {
$rawData = HttpClient::create()
->request('GET', "https://api.crossref.org/works?query.author=$param&rows=40")
->getContent()
;
$data = \json_decode($rawData);
if(isset($data->message->items)) {
$articles=$data->message->items;
foreach ($articles as $article){
$auteurs=$article->author;
foreach ($auteurs as $aut){
$family='';
$given='';
$name='';
if(isset($aut->family)){
$family=strtolower($aut->family);
}if (isset($aut->given)){
$given=strtolower($aut->given);
}
if($family && $given ){
$name=strtolower($given).' '.strtolower($family);
}elseif ($family ){
$name=strtolower($family);
}elseif ($given ){
$name=strtolower($given);
}
}
if($auteur == $name){
$data_crossref[]=$article;
}
}
}
if($data_crossref){
foreach ($data_crossref as $item){
$pub = new Allpublications();
$check = $em->getRepository(Allpublications::class)->findOneBy(['title' => $item->title[0]]);
if(!$check) {
$pub->setType($item->type);
$pub->setUser($this->getUser());
if (isset($item->title) && count($item->title) > 0) {
$pub->setTitle($item->title[0]);
}
if (isset($item->volume)) {
$pub->setVolume($item->volume);
}
if (isset($item->page)) {
$pub->setPages($item->page);
}
if (isset($item->URL)) {
$pub->setUrl($item->URL);
}
if (isset($item->issue)) {
$pub->setIssue($item->issue);
}
if (isset($item->author)) {
$authors = [];
foreach ($item->author as $a) {
$family = '';
$given = '';
$name = '';
if (isset($a->family)) {
$family = strtolower($a->family);
}
if (isset($a->given)) {
$given = strtolower($a->given);
}
if ($family && $given) {
$name = strtolower($given) . ' ' . strtolower($family);
} elseif ($family) {
$name = strtolower($family);
} elseif ($given) {
$name = strtolower($given);
}
if (!in_array($name, $authors)) $authors[] = $name;
}
if ($authors) $pub->setAuthors(implode(",", $authors));
}
if (isset($item->reference)) {
$references = $item->reference;
// parse object references to array
$references = json_decode(json_encode($references), true);
if($references) {
foreach ($references as $ref) {
if (isset($ref['journal-title'])) {
$pub->setName($ref['journal-title']);
}
}
}
}elseif (isset($item->{'container-title'}) && count($item->{'container-title'}) > 0) {
$references = $item->{'container-title'}[0];
$pub->setName($references);
}
if (isset($item->{'published-online'})) {
$date = json_decode(json_encode($item->{'published-online'}), true);
if (isset($date['date-parts'][0][0])) {
$pub->setYear($date['date-parts'][0][0]);
}
}
$em->persist($pub);
$em->flush();
}
}
}
}catch (TransportExceptionInterface $exception){
$this->addFlash('error', 'Ooops ! Something wrong happened. Please retry again or contact the support');
$this->logger->critical($exception->getTraceAsString());
}
$emS = $this->getDoctrine()->getManager();
$emS->flush();
$user=$this->getUser();
return $this->redirectToRoute('publication_index',['id'=>$user->getId(),'firstname'=>$user->getFirstName(),'lastname'=>$user->getLastName()]);
}
/**
* @Route("/all_publication/{id}", name="all_publication_delete", methods={"DELETE"}, requirements={"id":"\d+"})
*/
public function delete(Request $request, Allpublications $publication): Response
{
$user=$this->getUser();
$entityManager = $this->getDoctrine()->getManager();
$entityManager->remove($publication);
$entityManager->flush();
return $this->redirectToRoute('publication_index',['firstname'=>$user->getFirstName(),'lastname'=>$user->getLastName(),'id'=>$user->getId()]);
}
/**
* @Route("/add_follower/{firstname}_{lastname}_{id}/{author}/{exist}/{redirect}", name="add_follower", methods={"GET"}, defaults={"id" = 0,"firstname" = "","lastname" = ""})
*/
public function add_follower(UserRepository $userRepository,Request $request)
{
$entityManager = $this->getDoctrine()->getManager();
$auteur = $request->get('author');
$exist= $request->get('exist');
$searchValue= $request->get('searchValue');
$route= $request->get('redirect');
if($route=="get_authors_publication"){
$parameter="auteur";
}else{
$parameter="authorValue";
}
$currentUser=$this->getUser();
if($currentUser) {
$firstName=$request->get('firstname');
$lastName=$request->get('lastname');
$id=$request->get('id');
/** @var User $user */
$user = $currentUser;
if ($exist == 0) {
$following = $entityManager->getRepository(Follow::class)->findBy(['following' => $auteur]);
if($following) {
$following = $following[0];
$following->addFollower($user);
$entityManager->persist($following);
$entityManager->persist($user);
$entityManager->flush();
}
else{
$follow = new Follow();
$follow->setFollowing($auteur);
$follow->addFollower($user);
$entityManager->persist($user);
$entityManager->flush();
$this->addFlash('success', 'You have successfully followed the author');
}
return $this->redirectToRoute('get_authors_publication',["auteur"=>$auteur]);
}
else {
$following = $entityManager->getRepository(Follow::class)->findBy(['following' => $auteur]);
if($following){
$following=$following[0];
$following->removeFollower($user);
$entityManager->persist($following);
$entityManager->remove($following);
$entityManager->flush();
// add flash message
$this->addFlash('success', 'You have successfully unfollowed the author');
if($route=="authors_list"){
return $this->redirectToRoute($route);
}else{
return $this->redirectToRoute('get_authors_publication',["auteur"=>$auteur]);
}
}
}
}
else {
return $this->redirectToRoute("registre_user");
}
return $this->redirectToRoute('get_authors',["authorValue"=>$searchValue]);
}
/**
* @IsGranted("ROLE_USER")
* @Route("/{firstname}_{lastname}_{id}/followers", name="followers_index", methods={"GET"})
*/
public function followers_index(UserRepository $userRepository,Request $request)
{
$user=$this->getUser();
$firstname=$request->get('firstname');
$lastname=$request->get('lastname');
$id=$request->get('id');
$myProfile=false;
if($user==$this->getUser()) {
$myProfile = true;
}
$entityManager = $this->getDoctrine()->getManager();
$myFollowers=$entityManager->getRepository(Follow::class)->findAllFollowers($user->getFullName());
$allPublication=$entityManager->getRepository(Allpublications::class)->findAll();
$allFollow=$entityManager->getRepository(Follow::class)->findAll();
return $this->render("refonte/follow/followers_index.html.twig",[
'exist'=>$myFollowers,
'myFollowers'=>$myFollowers,
'allPublication'=>$allPublication,
'allFollow'=>$allFollow,
'myProfile'=>$myProfile,
]);
}
/**
* @IsGranted("ROLE_USER")
* @Route("/{firstname}_{lastname}_{id}/following", name="following_index", methods={"GET"})
*/
public function following_index(UserRepository $userRepository,Request $request)
{
$user=$this->getUser();
$firstname=$request->get('firstname');
$lastname=$request->get('lastname');
$id=$request->get('id');
$myProfile=false;
if($user==$this->getUser()) {
$myProfile = true;
}
$entityManager = $this->getDoctrine()->getManager();
$exist=$entityManager->getRepository(Follow::class)->findAllFollowing($user);
$allPublication=$entityManager->getRepository(Allpublications::class)->findAll();
$allFollow=$entityManager->getRepository(Follow::class)->findAll();
return $this->render("follow/following_index.html.twig",[
'exist'=>$exist,
'allPublication'=>$allPublication,
'allFollow'=>$allFollow,
'myProfile'=>$myProfile,
'user'=>$user
]);
}
/**
* @Route("/{firstname}.{lastname}.{id}/co_authors", name="co_authors_index", methods={"GET"})
*/
public function co_authors_index(Request $request,UserRepository $userRepository,PublicationManager $publicationManager,PaginatorInterface $paginator){
/** @var User $user */
$user=$this->getUser();
$firstname=$request->get('firstname');
$lastname=$request->get('lastname');
if($firstname && $lastname || ($firstname || $lastname )){
$user=$userRepository->userFromConctact($firstname,$lastname,$user->getEmail());
if($user){
$user=$user[0];
}
}
$coauthors= $publicationManager->getAuthorsList($user);
return $this->render("refonte/Profile/co_authors.html.twig",
[
'user'=>$user,
"coauthors"=>$coauthors,
'total'=>count($coauthors)
]);
}
/**
* @Route("/co_authors/{author}", name="co_authors_list_author", methods={"GET"})
*/
public function co_authors_list_author(Request $request,UserRepository $userRepository,PublicationManager $publicationManager){
$author_search=$request->get('author');
$authors= $publicationManager->getAuthorsListForAuthor($author_search);
return $this->render("Profile/co_authors.html.twig",
[
'author'=>$author_search,
"authors"=>$authors
]);
}
/**
* @Route("/settings", name="settings", methods={"GET"})
*/
public function settings()
{
$user=$this->getUser();
if($user){
return $this->redirectToRoute("profile_settings",['firstname'=>$user->getFirstName(),'lastname'=>$user->getLastName()]);
}
}
/**
* @Route("/settings/{firstname}.{lastname}", name="profile_settings", methods={"GET"})
*/
public function profile_settings(Request $request)
{
return $this->render('Profile/profile_settings.html.twig');
}
/**
* @Route("/profile/{firstname}.{lastname}.{id}", name="share_your_profile", methods={"GET"})
*/
public function share_your_profile(Request $request,AllPublicationRepository $allPublicationRepository)
{
$firstname=$request->get('firstname');
$lastname=$request->get('lastname');
$id=$request->get('id');
$publications=null;
$countFollowers=0;$countFolling=0;
$em=$this->getDoctrine()->getManager();
$user=$em->getRepository(User::class)->find($id);
if($user) {
$myFollowers=$em->getRepository(Follow::class)->findAllFollowers($user->getFullName());
$myFollowing=$em->getRepository(Follow::class)->findAllFollowing($user);
$countFollowers=count($myFollowers);
$countFolling=count($myFollowing);
}
if($user && $user->getFirstName()==$firstname && ($user->getLastName()==$lastname || $user->getFullName()==$lastname)){
$publications=$allPublicationRepository->allPublications($user);
}
else{
$user=null;
}
return $this->render("Profile/share_your_profile.html.twig",[
'firstname'=>$firstname,
'lastname'=>$lastname,
'id'=>$id,
'publications'=>$publications,
'user'=>$user,
'countFolling'=>$countFolling,
'countFollowers'=>$countFollowers
]);
}
/**
* @Route("/journal-search", name="journalSearch", methods={"GET"})
*/
public function journalSearch()
{
return $this->render("refonte/pages/journalSearch.html.twig");
}
/**
* @Route("/verified-journal", name="verified-journal", methods={"GET"})
*/
public function verifiedJournal()
{
return $this->render("search/verifiedJournal.html.twig");
}
/**
* @Route("/faq", name="faq", methods={"GET"})
*/
public function faq()
{
return $this->render("pages/faq.html.twig");
}
/**
* @Route("/newsletter", name="newsletter", methods={"post"})
*/
public function newsletter(Request $request, \Swift_Mailer $mailer)
{
$em = $this->getDoctrine()->getManager();
$email= $request->request->get("email");
$formSubmitted=$request->request->get("newsletter");
$newsletter= $em->getRepository(Newsletter::class)->findOneBy(["email"=> $email]);
if(!$newsletter && $formSubmitted && $email && $this->validateEmail($email)){
$nl = new Newsletter();
$nl->setEmail($email);
$nl->setStatus(1);
$nl->setLastSendDate(new \DateTime());
$em->persist($nl);
$em->flush();
$this->addFlash('success','You have successfully subscribed to our newsletter.');
}elseif ($newsletter && $formSubmitted){
$this->addFlash('warning','You are already subscribed to our newsletter.');
}else{
$this->addFlash('error','Ooops ! Something wrong happened. Please retry again or contact the support');
}
return $this->redirect("/");
}
/**
* @Route("/ads.txt", name="ads.txt", methods={"GET"})
*/
public function adsText()
{
$file = (\dirname(__DIR__, 2).'/public/assets/ads.txt');
$txt = file_get_contents($file);
$response = new Response($txt);
$response->headers->set('Content-Type', 'text/plain');
$response->sendHeaders();
return $response;
}
/**
* @Route("/savefavoriteCategories", name="save_favorite_categories")
*/
public function saveFavoriteCategories(CategoryRepository $categoryRepository,Request $request,EntityManagerInterface $em): Response
{
$categories=$request->get('selected-categories');
$favoriteCategories = explode(',', $categories);
$referer = $request->headers->get('referer');
$user=$this->getUser();
if(!empty($categories)){
if(empty($user->getCategories()->getValues())) {
foreach ($favoriteCategories as $c) {
/** @var Category $category */
$category = $categoryRepository->find($c);
$user->addCategory($category);
$em->persist($user);
$em->flush();
}
}else{
$oldCategories=$user->getCategories()->getValues();
foreach ($oldCategories as $old){
$user->removeCategory($old);
$em->persist($user);
}
foreach ($favoriteCategories as $c) {
/** @var Category $category */
$category = $categoryRepository->find($c);
$user->addCategory($category);
$em->persist($user);
}
$em->flush();
}
}
if($referer && str_contains($referer, 'categories_list')){
return $this->redirect($referer);
}
return $this->redirect('/');
}
/**
* @Route("/registration" , name="registration-user")
*/
public function registreUser(){
$user = $this->getUser();
if (!$user) return $this->redirectToRoute('registre_user');
return $this->redirect('/');
}
function validateEmail($email) {
// Use filter_var() to validate the email
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
return true; // Email is valid
} else {
return false; // Email is invalid
}
}
}