129 lines
3.7 KiB
PHP
Raw Normal View History

2023-01-24 19:00:39 +01:00
<?php
/**
* Description of doi
*
* @author may
*/
class doi {
//put your code here
public static $requests = 0;
private $doi="x";
public function __construct() {
}
// retrieves DOI data from thw doi server
public static function fetchData($doi) {
$data = -1;
if (strlen ($doi) < 1) {
return $data;
}
// check if it's already in the DB!
if ($db_id = doi::isPublication($doi)) {
return $db_id;
}
// limit number of requests (testing, importing huge databases, etc.
else if (doi::$requests < DOI_REQ_LIMIT) {
$ch = curl_init();
$headers = array('Accept: application/x-bibtex');
curl_setopt($ch, CURLOPT_URL, 'http://dx.doi.org/' .$doi);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
if ($res = curl_exec($ch)) {
if(!curl_error($ch)) {
$data = doi::_bibtex2arr($res);
}
}
doi::$requests++;
curl_close($ch);
return $data;
}
else {
return $data ." (OVER DOI_REQ_LIMIT!!!)";
}
}
// check if we already have this DOI
public static function isPublication($doi) {
global $PDO;
$d_arr = explode ("doi.org/", $doi);
if (count ($d_arr)> 1) {
$doi = $d_arr[1];
}
try {
$stmt = $PDO->prepare("SELECT id FROM publication where doi=:doi");
$stmt->execute(array($doi));
// this instead of rowCount to make in compatible with non-mysql DB
if ($r = $stmt->fetch(PDO::FETCH_NUM)) {
return $r[0];
}
else {
return false;
}
}
catch (exception $ex) {
common::except ('Err: ' .$ex .' in ' .__DIR__ .'/' .__FILE__ .':' .__LINE__);
return false;
}
return false;
}
// converts from DOI to array (that canbe inserted into the DB)
private static function _bibtex2arr($data) {
$record = array();
/*
@article{R_der_2015,
doi = {10.1111/imre.12113},
url = {https://doi.org/10.1111%2Fimre.12113},
year = 2015,
month = {dec},
publisher = {{SAGE} Publications},
volume = {49},
number = {4},
pages = {1042--1070},
author = {Antje Röder},
title = {Immigrants' Attitudes toward Homosexuality: Socialization) Religion, and Acculturation in European Host Societies},
journal = {International Migration Review}
*
* let's make it universal for all kinds of sources:
- 1 data field (incl. name) per line (explode \n; trim \r; )
- ' = ' is separator; explode, again and name and value. Make sure only to explode ONE TIME
*/
$line_arr = explode ("\n", $data);
foreach ($line_arr as $line) {
$fields = explode ("=", trim($line), 2);
if (count ($fields) == 2) {
$record[trim($fields[0])] = trim($fields[1], " \n\r\t\{\}\,");
}
}
return $record;
}
}