Add namespaces for psr-4 autoloading

This commit is contained in:
Sebastian Meyer 2020-01-24 00:13:17 +01:00
parent fe098b327f
commit 2f8ae34d99
5 changed files with 64 additions and 45 deletions

View File

@ -20,7 +20,9 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
class OAI2Exception extends Exception { namespace OCC\OAI2;
class Exception extends \Exception {
public function __construct($code) { public function __construct($code) {
$this->errorTable = [ $this->errorTable = [

View File

@ -20,7 +20,9 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
class OAI2Response { namespace OCC\OAI2;
class Response {
public $doc; // DOMDocument. Handle of current XML Document object public $doc; // DOMDocument. Handle of current XML Document object
@ -32,7 +34,7 @@ class OAI2Response {
$stylesheet .= $_SERVER['HTTP_HOST'].pathinfo(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH), PATHINFO_DIRNAME).'/Resources/Stylesheet.xsl'; $stylesheet .= $_SERVER['HTTP_HOST'].pathinfo(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH), PATHINFO_DIRNAME).'/Resources/Stylesheet.xsl';
} }
$this->verb = $verb; $this->verb = $verb;
$this->doc = new DOMDocument('1.0', 'UTF-8'); $this->doc = new \DOMDocument('1.0', 'UTF-8');
$this->doc->appendChild($this->doc->createProcessingInstruction('xml-stylesheet', 'type="text/xsl" href="'.$stylesheet.'"')); $this->doc->appendChild($this->doc->createProcessingInstruction('xml-stylesheet', 'type="text/xsl" href="'.$stylesheet.'"'));
$oai_node = $this->doc->createElement('OAI-PMH'); $oai_node = $this->doc->createElement('OAI-PMH');
$oai_node->setAttribute('xmlns', 'http://www.openarchives.org/OAI/2.0/'); $oai_node->setAttribute('xmlns', 'http://www.openarchives.org/OAI/2.0/');
@ -52,11 +54,11 @@ class OAI2Response {
/** /**
* Add a child node to a parent node on a XML Doc: a worker function. * Add a child node to a parent node on a XML Doc: a worker function.
* *
* @param DOMNode $mom_node The target node. * @param \DOMNode $mom_node The target node.
* @param string $name The name of child node is being added. * @param string $name The name of child node is being added.
* @param string $value Text for the adding node if it is a text node. * @param string $value Text for the adding node if it is a text node.
* *
* @return DOMElement $added_node * The newly created node * @return \DOMElement $added_node * The newly created node
*/ */
public function addChild($mom_node, $name, $value = '') { public function addChild($mom_node, $name, $value = '') {
$added_node = $this->doc->createElement($name, $value); $added_node = $this->doc->createElement($name, $value);
@ -85,7 +87,7 @@ class OAI2Response {
* @param string $identifier The identifier string for node <identifier>. * @param string $identifier The identifier string for node <identifier>.
* @param string $timestamp Timestamp in UTC format for node <datastamp>. * @param string $timestamp Timestamp in UTC format for node <datastamp>.
* @param boolean $deleted Deleted status for the record. * @param boolean $deleted Deleted status for the record.
* @param DOMElement $add_to_node Default value is null. * @param \DOMElement $add_to_node Default value is null.
* In normal cases, $add_to_node is the <record> node created previously. * In normal cases, $add_to_node is the <record> node created previously.
* When it is null, the newly created header node is attatched to $this->verbNode. * When it is null, the newly created header node is attatched to $this->verbNode.
* Otherwise it will be attached to the desired node defined in $add_to_node. * Otherwise it will be attached to the desired node defined in $add_to_node.
@ -124,10 +126,10 @@ class OAI2Response {
/** /**
* Imports a XML fragment into a parent node on a XML Doc: a worker function. * Imports a XML fragment into a parent node on a XML Doc: a worker function.
* *
* @param DOMNode $mom_node The target node. * @param \DOMNode $mom_node The target node.
* @param DOMDocument $fragment The XML fragment is being added. * @param \DOMDocument $fragment The XML fragment is being added.
* *
* @return DOMElement $added_node * The newly created node * @return \DOMElement $added_node * The newly created node
*/ */
public function importFragment($mom_node, $fragment) { public function importFragment($mom_node, $fragment) {
$added_node = $mom_node->appendChild($this->doc->importNode($fragment->documentElement, true)); $added_node = $mom_node->appendChild($this->doc->importNode($fragment->documentElement, true));

View File

@ -20,14 +20,13 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
require_once './OAI2Exception.php'; namespace OCC\OAI2;
require_once './OAI2Response.php';
/** /**
* This is an implementation of OAI Data Provider version 2.0. * This is an implementation of OAI Data Provider version 2.0.
* @see http://www.openarchives.org/OAI/2.0/openarchivesprotocol.htm * @see http://www.openarchives.org/OAI/2.0/openarchivesprotocol.htm
*/ */
class OAI2Server { class Server {
public $errors = []; public $errors = [];
private $args = []; private $args = [];
@ -40,7 +39,7 @@ class OAI2Server {
$this->uri = $uri; $this->uri = $uri;
$verbs = ['Identify', 'ListMetadataFormats', 'ListSets', 'ListIdentifiers', 'ListRecords', 'GetRecord']; $verbs = ['Identify', 'ListMetadataFormats', 'ListSets', 'ListIdentifiers', 'ListRecords', 'GetRecord'];
if (empty($args['verb']) || !in_array($args['verb'], $verbs)) { if (empty($args['verb']) || !in_array($args['verb'], $verbs)) {
$this->errors[] = new OAI2Exception('badVerb'); $this->errors[] = new Exception('badVerb');
return; return;
} }
$this->verb = $args['verb']; $this->verb = $args['verb'];
@ -53,7 +52,7 @@ class OAI2Server {
$this->max_records = $config['maxRecords']; $this->max_records = $config['maxRecords'];
$this->token_prefix = $config['tokenPrefix']; $this->token_prefix = $config['tokenPrefix'];
$this->token_valid = $config['tokenValid']; $this->token_valid = $config['tokenValid'];
$this->response = new OAI2Response($this->uri, $this->verb, $this->args); $this->response = new Response($this->uri, $this->verb, $this->args);
call_user_func([$this, $this->verb]); call_user_func([$this, $this->verb]);
} }
@ -61,7 +60,7 @@ class OAI2Server {
if (empty($this->errors)) { if (empty($this->errors)) {
return $this->response->doc; return $this->response->doc;
} }
$errorResponse = new OAI2Response($this->uri, $this->verb, $this->args); $errorResponse = new Response($this->uri, $this->verb, $this->args);
$oai_node = $errorResponse->doc->documentElement; $oai_node = $errorResponse->doc->documentElement;
foreach ($this->errors as $e) { foreach ($this->errors as $e) {
$node = $errorResponse->addChild($oai_node, 'error', $e->getMessage()); $node = $errorResponse->addChild($oai_node, 'error', $e->getMessage());
@ -73,7 +72,7 @@ class OAI2Server {
public function Identify() { public function Identify() {
if (count($this->args) > 0) { if (count($this->args) > 0) {
foreach ($this->args as $key => $val) { foreach ($this->args as $key => $val) {
$this->errors[] = new OAI2Exception('badArgument'); $this->errors[] = new Exception('badArgument');
} }
} else { } else {
foreach ($this->identifyResponse as $key => $val) { foreach ($this->identifyResponse as $key => $val) {
@ -86,7 +85,7 @@ class OAI2Server {
$identifier = ''; $identifier = '';
foreach ($this->args as $argument => $value) { foreach ($this->args as $argument => $value) {
if ($argument != 'identifier') { if ($argument != 'identifier') {
$this->errors[] = new OAI2Exception('badArgument'); $this->errors[] = new Exception('badArgument');
} else { } else {
$identifier = $value; $identifier = $value;
} }
@ -101,9 +100,9 @@ class OAI2Server {
$this->response->addChild($cmf, 'metadataNamespace', $val['namespace']); $this->response->addChild($cmf, 'metadataNamespace', $val['namespace']);
} }
} else { } else {
$this->errors[] = new OAI2Exception('noMetadataFormats'); $this->errors[] = new Exception('noMetadataFormats');
} }
} catch (OAI2Exception $e) { } catch (Exception $e) {
$this->errors[] = $e; $this->errors[] = $e;
} }
} }
@ -112,22 +111,22 @@ class OAI2Server {
public function ListSets() { public function ListSets() {
if (isset($this->args['resumptionToken'])) { if (isset($this->args['resumptionToken'])) {
if (count($this->args) > 1) { if (count($this->args) > 1) {
$this->errors[] = new OAI2Exception('badArgument'); $this->errors[] = new Exception('badArgument');
} else { } else {
$this->errors[] = new OAI2Exception('badResumptionToken'); $this->errors[] = new Exception('badResumptionToken');
} }
} else { } else {
$this->errors[] = new OAI2Exception('noSetHierarchy'); $this->errors[] = new Exception('noSetHierarchy');
} }
} }
public function GetRecord() { public function GetRecord() {
if (!isset($this->args['identifier']) || !isset($this->args['metadataPrefix'])) { if (!isset($this->args['identifier']) || !isset($this->args['metadataPrefix'])) {
$this->errors[] = new OAI2Exception('badArgument'); $this->errors[] = new Exception('badArgument');
} else { } else {
$metadataFormats = call_user_func($this->listMetadataFormatsCallback); $metadataFormats = call_user_func($this->listMetadataFormatsCallback);
if (!isset($metadataFormats[$this->args['metadataPrefix']])) { if (!isset($metadataFormats[$this->args['metadataPrefix']])) {
$this->errors[] = new OAI2Exception('cannotDisseminateFormat'); $this->errors[] = new Exception('cannotDisseminateFormat');
} }
} }
if (empty($this->errors)) { if (empty($this->errors)) {
@ -139,9 +138,9 @@ class OAI2Server {
$this->addMetadata($cur_record, $record['metadata']); $this->addMetadata($cur_record, $record['metadata']);
} }
} else { } else {
$this->errors[] = new OAI2Exception('idDoesNotExist'); $this->errors[] = new Exception('idDoesNotExist');
} }
} catch (OAI2Exception $e) { } catch (Exception $e) {
$this->errors[] = $e; $this->errors[] = $e;
} }
} }
@ -159,49 +158,49 @@ class OAI2Server {
$until = isset($this->args['until']) ? $this->args['until'] : ''; $until = isset($this->args['until']) ? $this->args['until'] : '';
if (isset($this->args['resumptionToken'])) { if (isset($this->args['resumptionToken'])) {
if (count($this->args) > 1) { if (count($this->args) > 1) {
$this->errors[] = new OAI2Exception('badArgument'); $this->errors[] = new Exception('badArgument');
} else { } else {
if (!file_exists($this->token_prefix.$this->args['resumptionToken'])) { if (!file_exists($this->token_prefix.$this->args['resumptionToken'])) {
$this->errors[] = new OAI2Exception('badResumptionToken'); $this->errors[] = new Exception('badResumptionToken');
} else { } else {
if (filemtime($this->token_prefix.$this->args['resumptionToken'])+$this->token_valid < time()) { if (filemtime($this->token_prefix.$this->args['resumptionToken'])+$this->token_valid < time()) {
$this->errors[] = new OAI2Exception('badResumptionToken'); $this->errors[] = new Exception('badResumptionToken');
} else { } else {
if ($readings = $this->readResumptionToken($this->token_prefix.$this->args['resumptionToken'])) { if ($readings = $this->readResumptionToken($this->token_prefix.$this->args['resumptionToken'])) {
list($deliveredRecords, $metadataPrefix, $from, $until) = $readings; list($deliveredRecords, $metadataPrefix, $from, $until) = $readings;
} else { } else {
$this->errors[] = new OAI2Exception('badResumptionToken'); $this->errors[] = new Exception('badResumptionToken');
} }
} }
} }
} }
} else { } else {
if (!isset($this->args['metadataPrefix'])) { if (!isset($this->args['metadataPrefix'])) {
$this->errors[] = new OAI2Exception('badArgument'); $this->errors[] = new Exception('badArgument');
} else { } else {
$metadataFormats = call_user_func($this->listMetadataFormatsCallback); $metadataFormats = call_user_func($this->listMetadataFormatsCallback);
if (!isset($metadataFormats[$this->args['metadataPrefix']])) { if (!isset($metadataFormats[$this->args['metadataPrefix']])) {
$this->errors[] = new OAI2Exception('cannotDisseminateFormat'); $this->errors[] = new Exception('cannotDisseminateFormat');
} }
} }
if (isset($this->args['from'])) { if (isset($this->args['from'])) {
if (!$this->checkDateFormat($this->args['from'])) { if (!$this->checkDateFormat($this->args['from'])) {
$this->errors[] = new OAI2Exception('badArgument'); $this->errors[] = new Exception('badArgument');
} }
} }
if (isset($this->args['until'])) { if (isset($this->args['until'])) {
if (!$this->checkDateFormat($this->args['until'])) { if (!$this->checkDateFormat($this->args['until'])) {
$this->errors[] = new OAI2Exception('badArgument'); $this->errors[] = new Exception('badArgument');
} }
} }
if (isset($this->args['set'])) { if (isset($this->args['set'])) {
$this->errors[] = new OAI2Exception('noSetHierarchy'); $this->errors[] = new Exception('noSetHierarchy');
} }
} }
if (empty($this->errors)) { if (empty($this->errors)) {
try { try {
if (!($records_count = call_user_func($this->listRecordsCallback, $metadataPrefix, $this->formatTimestamp($from), $this->formatTimestamp($until), true))) { if (!($records_count = call_user_func($this->listRecordsCallback, $metadataPrefix, $this->formatTimestamp($from), $this->formatTimestamp($until), true))) {
throw new OAI2Exception('noRecordsMatch'); throw new Exception('noRecordsMatch');
} }
$records = call_user_func($this->listRecordsCallback, $metadataPrefix, $this->formatTimestamp($from), $this->formatTimestamp($until), false, $deliveredRecords, $maxItems); $records = call_user_func($this->listRecordsCallback, $metadataPrefix, $this->formatTimestamp($from), $this->formatTimestamp($until), false, $deliveredRecords, $maxItems);
foreach ($records as $record) { foreach ($records as $record) {
@ -227,7 +226,7 @@ class OAI2Server {
if (isset($restoken)) { if (isset($restoken)) {
$this->response->createResumptionToken($restoken, $expirationDatetime, $records_count, $deliveredRecords-$maxItems); $this->response->createResumptionToken($restoken, $expirationDatetime, $records_count, $deliveredRecords-$maxItems);
} }
} catch (OAI2Exception $e) { } catch (Exception $e) {
$this->errors[] = $e; $this->errors[] = $e;
} }
} }
@ -235,7 +234,7 @@ class OAI2Server {
private function addMetadata($cur_record, $file) { private function addMetadata($cur_record, $file) {
$meta_node = $this->response->addChild($cur_record, 'metadata'); $meta_node = $this->response->addChild($cur_record, 'metadata');
$fragment = new DOMDocument(); $fragment = new \DOMDocument();
$fragment->load($file); $fragment->load($file);
$this->response->importFragment($meta_node, $fragment); $this->response->importFragment($meta_node, $fragment);
} }
@ -281,9 +280,9 @@ class OAI2Server {
} }
private function checkDateFormat($date) { private function checkDateFormat($date) {
$datetime = DateTime::createFromFormat('Y-m-d\TH:i:s\Z', $date); $datetime = \DateTime::createFromFormat('Y-m-d\TH:i:s\Z', $date);
if ($datetime === false) { if ($datetime === false) {
$datetime = DateTime::createFromFormat('Y-m-d', $date); $datetime = \DateTime::createFromFormat('Y-m-d', $date);
} }
return ($datetime !== false) && !array_sum($datetime->getLastErrors()); return ($datetime !== false) && !array_sum($datetime->getLastErrors());
} }

View File

@ -20,8 +20,24 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
require_once './Configuration/Main.php'; namespace OCC\OAI2;
require_once './Classes/OAI2Server.php';
// Register autoloader
spl_autoload_register(function ($class) {
$base_dir = __DIR__.'/Classes/';
$len = strlen(__NAMESPACE__);
if (strncmp(__NAMESPACE__, $class, $len) !== 0) {
return;
}
$relative_class = substr($class, $len);
$file = $base_dir.str_replace('\\', '/', $relative_class).'.php';
if (file_exists($file)) {
require $file;
}
});
// Load configuration
require './Configuration/Main.php';
// Get all available records and their respective status and timestamps // Get all available records and their respective status and timestamps
$records = []; $records = [];
@ -64,7 +80,7 @@ $identifyResponse = [
'granularity' => 'YYYY-MM-DDThh:mm:ssZ' 'granularity' => 'YYYY-MM-DDThh:mm:ssZ'
]; ];
$oai2 = new OAI2Server( $oai2 = new Server(
$baseURL, $baseURL,
$_GET, $_GET,
$identifyResponse, $identifyResponse,
@ -115,7 +131,7 @@ $oai2 = new OAI2Server(
if (!empty($formats)) { if (!empty($formats)) {
return $formats; return $formats;
} else { } else {
throw new OAI2Exception('idDoesNotExist'); throw new Exception('idDoesNotExist');
} }
} else { } else {
return $config['metadataPrefix']; return $config['metadataPrefix'];

View File

@ -22,7 +22,7 @@ if (php_sapi_name() !== 'cli') {
exit; exit;
} }
require_once './Configuration/Main.php'; require './Configuration/Main.php';
/** /**
* Format output string * Format output string