src/Controller/SearchAuthorsController.php line 216

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\Author;
  4. use App\Entity\Follow;
  5. use App\Entity\Journal;
  6. use App\Entity\User;
  7. use App\Manager\PublicationManager;
  8. use App\Service\Sortpublication;
  9. use Doctrine\ORM\EntityManagerInterface;
  10. use Knp\Component\Pager\PaginatorInterface;
  11. use Psr\Log\LoggerInterface;
  12. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  13. use Symfony\Component\HttpClient\HttpClient;
  14. use Symfony\Component\HttpFoundation\Request;
  15. use Symfony\Component\HttpFoundation\Response;
  16. use Symfony\Component\Routing\Annotation\Route;
  17. use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface;
  18. class SearchAuthorsController extends AbstractController
  19. {
  20.     /** @var EntityManagerInterface */
  21.     private $entityManager;
  22.     /** @var LoggerInterface */
  23.     private $logger;
  24.     /**
  25.      * SearchAuthorsController constructor.
  26.      *
  27.      * @param EntityManagerInterface $entityManager
  28.      * @param LoggerInterface $logger
  29.      */
  30.     public function __construct(EntityManagerInterface $entityManagerLoggerInterface $logger)
  31.     {
  32.         $this->entityManager $entityManager;
  33.         $this->logger $logger;
  34.     }
  35.     /**
  36.      * @Route("/authors" ,name="get_authors")
  37.      *
  38.      * find the authors
  39.      */
  40.     public function callapi(Request $request,PaginatorInterface $paginator)
  41.     {
  42.         ini_set('max_execution_time', -1);
  43.         $exist=null;
  44.         $followers=[];
  45.         $manyRequests=false;
  46.         $entityManager $this->getDoctrine()->getManager();
  47.         $auteur trim($request->get('authorValue'));
  48.         if($auteur==''){
  49.             $requestUri=$request->getRequestUri();
  50.             if (strpos($requestUri'authorValue') !== false) {
  51.                    return $this->redirect('/');
  52.             }
  53.         }
  54.         $checkFollowing=$entityManager->getRepository(Follow::class)->findOneBy(['following'=>trim($auteur)]);
  55.         $author_db=$entityManager->getRepository(User::class)->findBy(['fullName'=>$auteur]);
  56.         if($author_db){
  57.             $author_db=$author_db[0];
  58.         }
  59.         if($checkFollowing){
  60.             $followers=$checkFollowing->getFollowers()->getValues();
  61.             foreach ($followers as $follower){
  62.                     if ($follower &&  $this->getUser() && $follower->getId() == $this->getUser()->getId()) {
  63.                         $exist 1;
  64.                     }
  65.             }
  66.         }
  67.         $countFollowers=count($followers);
  68.         $allFollowers=$entityManager->getRepository(Follow::class)->findAll();
  69.         $test=false;
  70.         if (strpos($request->getUri(), 'authorValue') !== false){
  71.             $test=true;
  72.         }
  73.         $param  urlencode($auteur); // str_replace(' ','+',$auteur);
  74.         $data null;
  75.         $authors=[];
  76.         $array_crossref = array();
  77.         $total=0;
  78.             $param  urlencode($auteur);
  79. //---------------------------------------------
  80.         $checkAuteur=$entityManager->getRepository(Author::class)->searchAuteurByName($auteur);
  81.         if($checkAuteur) {
  82.             foreach ($checkAuteur as $auteur){
  83.                 $auteurName=$auteur->getName();
  84.                 $count=0;
  85.                 $checkFollowingAuteurName=$entityManager->getRepository(Follow::class)->findOneBy(['following'=>trim($auteurName)]);
  86.                 if($checkFollowingAuteurName) {
  87.                     $count count($checkFollowingAuteurName->getFollowers()->getValues());
  88.                 }
  89.                 $array_crossref[]=['name'=>strtolower($auteurName),'count'=>$count];
  90.             }
  91.             $array_crossref array_map("unserialize"array_unique(array_map("serialize"$array_crossref)));
  92.         }
  93.         else {
  94.             $urlOpenAlex "https://api.openalex.org/authors?per-page=100&page=1&search=$auteur";
  95.             $rawData HttpClient::create()
  96.                 ->request('GET'$urlOpenAlex);
  97.             if ($rawData->getStatusCode() === 200) {
  98.                 $rawData $rawData->getContent();
  99.                 $data = \json_decode($rawData);
  100.                 if ($data) {
  101.                     $data $data->results;
  102.                     foreach ($data as $author){
  103.                         $auteurName=$author->display_name;
  104.                         $count=0;
  105.                         $checkFollowingAuteurName=$entityManager->getRepository(Follow::class)->findOneBy(['following'=>trim($auteurName)]);
  106.                         if($checkFollowingAuteurName) {
  107.                             $count count($checkFollowingAuteurName->getFollowers()->getValues());
  108.                         }
  109.                         $array_crossref[]=['name'=>strtolower($auteurName),'count'=>$count];
  110.                         // delete doublons in array crossref by name
  111.                     }
  112.                     $array_crossref array_map("unserialize"array_unique(array_map("serialize"$array_crossref)));
  113.                 }
  114.             }else{
  115.                 try {
  116.                     $rawData HttpClient::create()
  117.                         ->request('GET'"https://api.crossref.org/works?query.author=$auteur&rows=40");
  118.                     if ($rawData->getStatusCode() === 200) {
  119.                         $rawData $rawData->getContent();
  120.                         $data = \json_decode($rawData);
  121.                         if (isset($data->message->items)) {
  122.                             $articles $data->message->items;
  123.                             foreach ($articles as $article) {
  124.                                 $auteurs $article->author;
  125.                                 foreach ($auteurs as $aut) {
  126.                                     $family '';
  127.                                     $firstname '';
  128.                                     $auteurName '';
  129.                                     $total 0;
  130.                                     if (isset($aut->given)) {
  131.                                         $firstname $aut->given;
  132.                                     }
  133.                                     if (isset($aut->family) && strtolower($aut->family) != strtolower($firstname)) {
  134.                                         $family $aut->family;
  135.                                     }
  136.                                     if ($family != '' && $firstname != '') {
  137.                                         $auteurName $firstname ' ' $family;
  138.                                     } elseif ($family != '') {
  139.                                         $auteurName $family;
  140.                                     } elseif ($firstname != '') {
  141.                                         $auteurName $firstname;
  142.                                     }
  143.                                     if ($auteurName
  144.                                         && !in_array(strtolower($auteurName), array_column($array_crossref'name'))
  145.                                         && strpos(strtolower($auteurName), strtolower($auteur)) !== false) {
  146.                                         $count 0;
  147.                                         $checkFollowingAuteurName $entityManager->getRepository(Follow::class)->findOneBy(['following' => trim($auteurName)]);
  148.                                         if ($checkFollowingAuteurName) {
  149.                                             $count count($checkFollowingAuteurName->getFollowers()->getValues());
  150.                                         }
  151.                                         $array_crossref[] = ['name' => strtolower($auteurName), 'count' => $count];
  152.                                     }
  153.                                 }
  154.                             }
  155.                         }
  156.                     }
  157.                 } catch (TransportExceptionInterface $e) {
  158.                 }
  159.             }
  160.         }
  161. //---------------------------------------------
  162.         sort($array_crossref);
  163.         $page $request->get("p"1);
  164.         $perpage 10;
  165.         $authors $paginator->paginate($array_crossref$page10);
  166.         $total count($array_crossref);
  167.         // sort array_crossref by name
  168.         usort($array_crossref, function($a$b) {
  169.             return $a['name'] <=> $b['name'];
  170.         });
  171.         $pages=ceil($total/$perpage);
  172.         return $this->render('refonte/authors/authors-crossref.html.twig',
  173.             [
  174.                 'data'=> $data,
  175.                 'parametre'=>$test,
  176.                 'exist'=>$exist,
  177.                 'countFollowers'=>$countFollowers,
  178.                 'allFollowers'=>$allFollowers,
  179.                 'array_crossref'=>$authors,
  180.                 'total'=>$total,
  181.                 'author_db'=>$author_db,
  182.                 'manyRequests'=>$manyRequests,
  183.                 "auteur"=>$auteur,
  184.                 "pages"=>$pages,
  185.                 "page"=>$page
  186.             ]);
  187.     }
  188.     /**
  189.      * @Route("/authors/publication" ,name="get_authors_publication")
  190.      *
  191.      * find a publications of author
  192.      */
  193.     public function callpubapi(Request $request,PublicationManager $publicationManager){
  194.         if(!$this->getUser()){
  195.             $this->addFlash('info''You must be logged in to access this page');
  196.             return $this->redirectToRoute('registre_user');
  197.         }
  198.         ini_set('default_socket_timeout', -1);
  199.         $exist=null;$followers=[];
  200.         $auteur trim($request->get('auteur'));
  201.         $checkFollowing=$this->entityManager->getRepository(Follow::class)->findOneBy(['following'=>$auteur]);
  202.         $authorDB $this->entityManager->getRepository(User::class)->findOneBy(['fullName'=>$auteur]);
  203.         $publications=[];
  204.         $suggestedJournals=[];
  205.         $selectedAuthors=[];
  206.         $authorList=[];
  207.         if($checkFollowing){
  208.             $followers=$checkFollowing->getFollowers()->getValues();
  209.             foreach ($followers as $follower){
  210.                 if ($follower && $this->getUser() ){
  211.                     if($follower->getId() == $this->getUser()->getId()) {
  212.                         $exist=1;
  213.                     }
  214.                 }
  215.             }
  216.         }
  217.         $countFollowers=count($followers);
  218.         $param=str_replace(' ','+',$auteur);
  219.         $param  urlencode($auteur); // str_replace(' ','+',$auteur);
  220.         $search=false;
  221.         $data null;
  222.         $authors1=[];
  223.         $authors2=[];
  224.         $dd1 = [];
  225.         $array = [];
  226.         $author_db = [];
  227.         $co_authors = [];
  228.         $fullName = [];
  229.         $manyRequests=false;
  230.         $gender='';
  231.         $institution='';
  232.         $country='';
  233.         $topics=[];
  234.         if(isset($data->result->hits->hit)){
  235.                 $search=true;
  236.         }
  237.         // get gender of author
  238. //        $client = HttpClient::create();
  239. //        $response = $client->request('GET', 'https://api.genderize.io', [
  240. //            'query' => [
  241. //                'name' => $auteur
  242. //            ]
  243. //        ]);
  244. //        $statusCode = $response->getStatusCode();
  245. //        if ($statusCode === 200) {
  246. //            $content = $response->toArray();
  247. //            $gender = $content['gender'];
  248. //        }
  249.             // get gender of author end
  250.         $worksData HttpClient::create()
  251.                 ->request('GET'"https://api.crossref.org/works?query.author=$auteur");
  252. //                ->request('GET', "https://api.crossref.org/works?query.bibliographic=$auteur&query.author=$auteur");
  253.         $urlOpenAlex "https://api.openalex.org/authors?search=$auteur&per-page=100&page=1";
  254.         $rawData HttpClient::create()
  255.             ->request('GET'$urlOpenAlex);
  256.            if ($rawData->getStatusCode() === 200) {
  257.             $authorOpenAlex = [];
  258. //            if ($rawData->getStatusCode() === 200) {
  259.                 $rawData $rawData->getContent();
  260.                 $data = \json_decode($rawData);
  261.                 if ($data) {
  262.                     $data $data->results;
  263.                     foreach ($data as $authortop) {
  264.                         $auteurName strtolower($authortop->display_name);
  265.                         if($auteurName==strtolower($auteur) && !in_array($auteurName,$authorOpenAlex)){
  266.                             $authorOpenAlex $authortop;
  267.                             break;
  268.                         }
  269.                     }
  270.                     if($authorOpenAlex){
  271.                         $works=$authorOpenAlex->works_api_url."&per-page=200";
  272.                         $rawData HttpClient::create()
  273.                             ->request('GET'$works);
  274.                         if ($rawData->getStatusCode() === 200) {
  275.                             $rawData $rawData->getContent();
  276.                             $data = \json_decode($rawData);
  277.                             if ($data) {
  278.                                 $data $data->results;
  279.                                 foreach ($data as $publication) {
  280.                                     $pages=0;
  281.                                     $authorsz=[];
  282.                                     $publicationName $publication->display_name;
  283.                                     $year=$publication->publication_year;
  284.                                     $type=$publication->type;
  285.                                     $volume=$publication->biblio->volume;
  286.                                     $authors=$publication->authorships;
  287.                                     $link=$publication->id;
  288.                                     if($publication->biblio->last_page && $publication->biblio->first_page)
  289.                                     {
  290.                                         $pages=intval($publication->biblio->last_page)-intval($publication->biblio->first_page);
  291.                                     }
  292.                                     foreach ($authors as $a){
  293.                                         if(isset($a->raw_author_name)){
  294.                                             $authorsz[]=$a->raw_author_name;
  295.                                             if(!in_array($a->raw_author_name,$selectedAuthors) && strtolower($auteur)!==strtolower($a->raw_author_name)){
  296.                                                 $selectedAuthors[]=$a->raw_author_name;
  297.                                             }
  298.                                         }
  299.                                     }
  300.                                     $publications[] = [
  301.                                         'title' => $publicationName,
  302.                                         'url' => $link,
  303.                                         'authors' => $authorsz,
  304.                                         'year' => $year,
  305.                                         'type' => $type,
  306.                                         'page' => $pages,
  307.                                         'volume' => $volume,
  308.                                         'subject' => [],
  309.                                         'journal' => "",
  310.                                         'reference_count' => 0];
  311.                                 }
  312.                                 //dd('end',$publications);
  313.                             }
  314.                         }
  315.                     }
  316.                 }
  317. //            }
  318.                usort($publications, function ($a$b) {
  319.                    return (int) $b['year'] <=> (int) $a['year'];
  320.                });
  321.                $suggestedJournals array_filter($suggestedJournals);
  322.             $selectedAuthors array_values($selectedAuthors);
  323.             // remove empty values from array journals
  324.             $selectedAuthors array_filter(array_map('trim'$selectedAuthors), function($value) {
  325.                 return $value !== "" && $value !== null;
  326.             });
  327.             // appliquer la fonction strtolower sur chaque élément du tableau
  328.             $selectedAuthors array_map('strtolower'$selectedAuthors);
  329.             $selectedAuthors array_map('trim'$selectedAuthors);
  330.             $selectedAuthors array_unique($selectedAuthors);
  331.             if (($key array_search(strtolower($auteur), $selectedAuthors)) !== false) {
  332.                 unset($selectedAuthors[$key]);
  333.             }
  334.             // 4 items from the array of selectedAuthors
  335.             $selectedAuthors array_slice($selectedAuthors04);
  336.             foreach ($selectedAuthors as $a) {
  337.                 // get gender of author
  338. //        $client = HttpClient::create();
  339. //        $response = $client->request('GET', 'https://api.genderize.io', [
  340. //            'query' => [
  341. //                'name' => $a
  342. //            ]
  343. //        ]);
  344. //        $statusCode = $response->getStatusCode();
  345. //        if ($statusCode === 200) {
  346. //            $content = $response->toArray();
  347. //            $gender = $content['gender'];
  348. //        }
  349.                 // get gender of author end
  350.                 $authorList[] = ['name' => $a'gender' => $gender];
  351.             }
  352.         }
  353.             else {
  354.                 $rawData $worksData->getContent();
  355.                 if ($rawData->getStatusCode() === 200) {
  356.                     $data = \json_decode($rawData);
  357.                     $message $data->message->items;
  358.                     foreach ($message as $item) {
  359.                         if (isset($item->title) && isset($item->type) && $item->type == "journal-article") {
  360.                             $article $item->title[0];
  361.                             $url $item->URL;
  362.                             $authors $item->author;
  363.                             // get given and family name of authors
  364.                             foreach ($authors as $author) {
  365.                                 $given '';
  366.                                 $family '';
  367.                                 if (isset($author->family)) {
  368.                                     $family $author->family;
  369.                                 }
  370.                                 if (isset($author->given)) {
  371.                                     $given $author->given;
  372.                                 }
  373.                                 $fullName[] = $given ' ' $family;
  374.                             }
  375.                             $published = ((get_object_vars($item->published)));
  376.                             $year $published['date-parts'][0];
  377.                             $year $year[0];
  378.                             $title "";
  379.                             $reference_count 0;
  380.                             if (isset($item->{'container-title'}) && is_array($item->{'container-title'})) {
  381.                                 // Access the first element of the 'short-container-title' array
  382.                                 $title $item->{'container-title'}[0];
  383.                             } elseif (isset($item->{'short-container-title'}) && is_array($item->{'short-container-title'})) {
  384.                                 // Access the first element of the 'container-title' array
  385.                                 $title $item->{'short-container-title'}[0];
  386.                             }
  387.                             if (isset($item->{'reference-count'})) {
  388.                                 $reference_count $item->{'reference-count'};
  389.                             }
  390.                             $page $item->page ?? '';
  391.                             $volume $item->volume ?? '';
  392.                             $subject $item->subject ?? '';
  393.                             if ($subject$subject implode(','$subject);
  394.                             if (in_array($given ' ' $family$fullName)) {
  395.                                 $publications[] = ['title' => $article'url' => $url'authors' => $fullName'year' => $year'page' => $page'volume' => $volume'subject' => $subject'journal' => $title'reference_count' => $reference_count];
  396.                             }
  397.                             if (!in_array($title$suggestedJournals)) {
  398.                                 $suggestedJournals[] = $this->entityManager->getRepository(Journal::class)->findOneBy(['title' => $title]);
  399.                             }
  400.                             if (!in_array($fullName$selectedAuthors)) {
  401.                                 $selectedAuthors[] = $fullName;
  402.                             }
  403.                             $fullName = [];
  404.                         }
  405.                     }
  406.                 }
  407.             }
  408.     // check if the author exists in the database
  409.         $author_db=$this->entityManager->getRepository(Author::class)->findOneBy(['name'=>$auteur]);
  410.         if($author_db){
  411.             if($author_db->getLastKnownInstitutions() && count($author_db->getLastKnownInstitutions())>0){
  412.                 $institution=$author_db->getLastKnownInstitutions()[0]->display_name;
  413.                 $country=$author_db->getLastKnownInstitutions()[0]->country_code;
  414.             }
  415.             if($author_db->getTopics()){
  416.                foreach ($author_db->getTopics() as $topic){
  417.                    $topics[]=$topic['field']['display_name'];
  418.                }
  419.             }
  420.            $topics=array_unique($topics);
  421.             // get 10 items from the array of topics
  422.             $topics array_slice($topics06);
  423.         }
  424.         return $this->render('refonte/authors/publications-crossref.html.twig',
  425.             [
  426.                 'dataissn'=>$dd1,
  427.                 'auteur'=> $auteur,
  428.                 'authorDB'=>$authorDB,
  429.                 'co_authors'=> $co_authors,
  430.                 'exist'=> $exist,
  431.                 'countFollowers'=> $countFollowers,
  432.                 'author_db'=> $author_db,
  433.                 'search'=> $search,
  434.                 'manyRequests'=>$manyRequests,
  435.                 'publications'=>$publications,
  436.                 "followers"=>count($followers),
  437.                 "gender"=>$gender,
  438.                 "suggestedJournals"=>$suggestedJournals,
  439.                 "selectedAuthors"=>$authorList,
  440.                 "institution"=>$institution,
  441.                 "country"=>$country,
  442.                 "topics"=>$topics
  443.             ]);
  444.     }
  445.     /**
  446.      * sort by date data gived by dblp api
  447.      * @param $a
  448.      * @param $b
  449.      * @return mixed
  450.      */
  451.     public function sortdblp($a,$b){
  452.         $temp=[];
  453.         for($i=0;$i<$b;$i++){
  454.             for ($j=0;$j<$b;$j++){
  455.                 if ($a[$i]->info->year $a[$j]->info->year)
  456.                 {
  457.                     $temp=$a[$i];
  458.                     $a[$i]=$a[$j];
  459.                     $a[$j]=$temp;
  460.                 }
  461.             }
  462.         }
  463.         return $a;
  464.     }
  465. }