Skip to content
Snippets Groups Projects
Commit 05cf5cd8 authored by Stein Magne Bjorklund's avatar Stein Magne Bjorklund
Browse files

Reformat to PSR-12 standard

Since there is no code style lets use PSR-12
https://www.php-fig.org/psr/psr-12/
parent 6188a946
No related branches found
No related tags found
1 merge request!11Haanga with composer
...@@ -2,114 +2,113 @@ ...@@ -2,114 +2,113 @@
namespace uib\ub\loadspeakr; namespace uib\ub\loadspeakr;
//Based (but corrected) from http://www.php.net/manual/en/language.types.object.php#102735
use Exception; use Exception;
use stdClass; use stdClass;
final class Convert { final class Convert
# Convert a stdClass to an Array. {
static public function object_to_array(stdClass $Class){ # Convert a stdClass to an Array.
# Typecast to (array) automatically converts stdClass -> array. static public function object_to_array(stdClass $Class)
$newClass = array(); {
# Typecast to (array) automatically converts stdClass -> array.
# Iterate through the former properties looking for any stdClass properties. $newClass = array();
# Recursively apply (array).
foreach($Class as $key => $value){ # Iterate through the former properties looking for any stdClass properties.
if(is_object($value)&&get_class($value)==='stdClass'){ # Recursively apply (array).
$newClass[$key] = self::object_to_array($value); foreach ($Class as $key => $value) {
}else{ if (is_object($value) && get_class($value) === 'stdClass') {
$newClass[$key] = $value; $newClass[$key] = self::object_to_array($value);
} } else {
} $newClass[$key] = $value;
return $newClass; }
} }
return $newClass;
# Convert an Array to stdClass.
static public function array_to_object(array $array){
# Iterate through our array looking for array values.
# If found recurvisely call itself.
$obj = new stdClass();
foreach($array as $key => $value){
if(is_array($value)){
$obj->$key = self::array_to_object($value);
}else{
$obj->$key = $value;
}
}
# Typecast to (object) will automatically convert array -> stdClass
return $obj;
}
//Taken from http://www.php.net/manual/en/ref.array.php#81081
static public function array_copy (array $aSource) {
// check if input is really an array
if (!is_array($aSource)) {
throw new Exception("Input is not an Array");
}
// initialize return array
$aRetAr = array();
// get array keys
$aKeys = array_keys($aSource);
// get array values
$aVals = array_values($aSource);
// loop through array and assign keys+values to new return array
for ($x=0;$x<count($aKeys);$x++) {
// clone if object
if (is_object($aVals[$x])) {
$aRetAr[$aKeys[$x]]=clone $aVals[$x];
// recursively add array
} elseif (is_array($aVals[$x])) {
$aRetAr[$aKeys[$x]]=self::array_copy ($aVals[$x]);
// assign just a plain scalar value
} else {
$aRetAr[$aKeys[$x]]=$aVals[$x];
}
}
return $aRetAr;
}
static public function getPaths ($r, $path) {
global $lodspk;
global $conf;
$arr = array();
foreach($r as $k => $v){
if($k == "params" ){
continue;
}
if($k == "0"){//if query
return NULL;
}
$next = self::getPaths($r->$k, $path."endpoint.".$k."/", $arr);
if($next == NULL){
$aux = $path.$k;
$root = array();
$pointer = &$root;
$aux2 = explode("/", $aux);
$key = str_ireplace("endpoint.", "", array_shift($aux2));
foreach($aux2 as $w){
$x = str_ireplace("endpoint.", "", $w);
$pointer[$x] = array();
$pointer = &$pointer[$x];
}
$pointer = $lodspk['baseUrl'].'components/'.$conf[$lodspk['module']]['prefix']."/".$lodspk['componentName']."/queries/".$aux.".query"; // TSL : removed hardcoded /lodspeakr
if(isset($lodspk['source'][$key])){
$lodspk['queries'][$key] = array_merge($lodspk['source'][$key], $root);
}else{
$lodspk['queries'][$key] = $root;
}
}
} }
return 1;
}
} # Convert an Array to stdClass.
static public function array_to_object(array $array)
{
# Iterate through our array looking for array values.
# If found recurvisely call itself.
$obj = new stdClass();
foreach ($array as $key => $value) {
if (is_array($value)) {
$obj->$key = self::array_to_object($value);
} else {
$obj->$key = $value;
}
}
# Typecast to (object) will automatically convert array -> stdClass
return $obj;
}
//Taken from http://www.php.net/manual/en/ref.array.php#81081
static public function array_copy(array $aSource)
{
// check if input is really an array
if (!is_array($aSource)) {
throw new Exception("Input is not an Array");
}
// initialize return array
$aRetAr = array();
// get array keys
$aKeys = array_keys($aSource);
// get array values
$aVals = array_values($aSource);
// loop through array and assign keys+values to new return array
for ($x = 0; $x < count($aKeys); $x++) {
// clone if object
if (is_object($aVals[$x])) {
$aRetAr[$aKeys[$x]] = clone $aVals[$x];
// recursively add array
} elseif (is_array($aVals[$x])) {
$aRetAr[$aKeys[$x]] = self::array_copy($aVals[$x]);
// assign just a plain scalar value
} else {
$aRetAr[$aKeys[$x]] = $aVals[$x];
}
}
return $aRetAr;
}
static public function getPaths($r, $path)
{
global $lodspk;
global $conf;
$arr = array();
foreach ($r as $k => $v) {
if ($k == "params") {
continue;
}
if ($k == "0") {//if query
return null;
}
$next = self::getPaths($r->$k, $path . "endpoint." . $k . "/", $arr);
if ($next == null) {
$aux = $path . $k;
$root = array();
$pointer = &$root;
$aux2 = explode("/", $aux);
$key = str_ireplace("endpoint.", "", array_shift($aux2));
foreach ($aux2 as $w) {
$x = str_ireplace("endpoint.", "", $w);
$pointer[$x] = array();
$pointer = &$pointer[$x];
}
$pointer = $lodspk['baseUrl'] . 'components/' . $conf[$lodspk['module']]['prefix'] . "/" . $lodspk['componentName'] . "/queries/" . $aux . ".query"; // TSL : removed hardcoded /lodspeakr
if (isset($lodspk['source'][$key])) {
$lodspk['queries'][$key] = array_merge($lodspk['source'][$key], $root);
} else {
$lodspk['queries'][$key] = $root;
}
}
}
return 1;
}
}
...@@ -3,119 +3,128 @@ ...@@ -3,119 +3,128 @@
namespace uib\ub\loadspeakr; namespace uib\ub\loadspeakr;
class Endpoint { class Endpoint
private $sparqlUrl; {
private $params; private $sparqlUrl;
private $params;
public function __construct($sparqlUrl, $params){
$this->sparqlUrl = $sparqlUrl; public function __construct($sparqlUrl, $params)
$this->params = $params; {
} $this->sparqlUrl = $sparqlUrl;
$this->params = $params;
public function query($q, $output = 'json'){
global $conf;
if (!empty($this->params['output'])){
$auxoutput = $this->params['output'];
}
$accept = 'application/sparql-results+json';
if($output != null){
$this->params['output'] = $output;
}
if($output == 'xml'){
$accept = 'application/sparql-results+xml';
}elseif($output == 'rdf'){
$accept = 'application/rdf+xml';
}
$aux = "";
$modified = 0;
$now = time();
$cacheFile = "";
if(!empty($conf['cache']['global']) && is_int($conf['cache']['global']) && $conf['cache']['global'] > 0){
$cacheFile = $conf['home']."cache/query".md5($this->sparqlUrl.$q);
if(file_exists($cacheFile)){
$modified = filemtime($cacheFile);
}
} }
if(is_int($conf['cache']['global']) && $conf['cache']['global'] > 0 && $modified + $conf['cache']['global'] > $now){
if($conf['debug']){ public function query($q, $output = 'json')
$msg = "Taking data from cache ($cacheFile). Renewal in ".($modified + $conf['cache']['global'] - $now)." seconds\n"; {
Logging::log($msg); global $conf;
echo $msg; if (!empty($this->params['output'])) {
} $auxoutput = $this->params['output'];
$aux = (file_get_contents($cacheFile));
}else{
$c = curl_init();
$context = array();
$context[0] = 'Connection: close';
$context[1] = 'Accept: '.$accept;
$params = $this->params;
$params['query'] = $q;
$url = $this->sparqlUrl.'?'.http_build_query($params, '', '&');
curl_setopt($c, CURLOPT_URL, $url);
curl_setopt($c, CURLOPT_HTTPHEADER, $context);
curl_setopt($c, CURLOPT_USERAGENT, "LODSPeaKr version ".$conf['version']);
curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
$aux = curl_exec($c); // execute the curl command
if($conf['debug']){
if($aux == false){
Logging::log("Error executing SPARQL query (".$this->sparqlUrl."): ".curl_error($c), E_USER_ERROR);
echo("Error executing SPARQL query (".$this->sparqlUrl."): ".curl_error($c));
} }
} $accept = 'application/sparql-results+json';
$http_status = intval(curl_getinfo($c, CURLINFO_HTTP_CODE)); if ($output != null) {
curl_close($c); $this->params['output'] = $output;
if (!empty($auxoutput)) {
$this->params['output'] = $auxoutput;
}
if(is_int($conf['cache']['global']) && $conf['cache']['global'] > 0 && $http_status == 200){
file_put_contents($cacheFile,($aux), LOCK_EX);
if($conf['debug']){
$msg = "Notice: Writing results in ".$cacheFile."\n";
Logging::log($msg, E_USER_NOTICE);
echo($msg);
} }
} if ($output == 'xml') {
} $accept = 'application/sparql-results+xml';
if(preg_match("/select/i", $q)){ } elseif ($output == 'rdf') {
$r = json_decode($aux, true); $accept = 'application/rdf+xml';
if($conf['debug']){ }
if($r == false){ $aux = "";
Logging::log("Warning: Results from a SELECT sparql query couldn't get parsed", E_USER_WARNING); $modified = 0;
echo("Warning: Results from a SELECT sparql query couldn't get parsed"); $now = time();
$cacheFile = "";
if (!empty($conf['cache']['global']) && is_int($conf['cache']['global']) && $conf['cache']['global'] > 0) {
$cacheFile = $conf['home'] . "cache/query" . md5($this->sparqlUrl . $q);
if (file_exists($cacheFile)) {
$modified = filemtime($cacheFile);
}
}
if (is_int(
$conf['cache']['global']
) && $conf['cache']['global'] > 0 && $modified + $conf['cache']['global'] > $now) {
if ($conf['debug']) {
$msg = "Taking data from cache ($cacheFile). Renewal in " . ($modified + $conf['cache']['global'] - $now) . " seconds\n";
Logging::log($msg);
echo $msg;
}
$aux = (file_get_contents($cacheFile));
} else {
$c = curl_init();
$context = array();
$context[0] = 'Connection: close';
$context[1] = 'Accept: ' . $accept;
$params = $this->params;
$params['query'] = $q;
$url = $this->sparqlUrl . '?' . http_build_query($params, '', '&');
curl_setopt($c, CURLOPT_URL, $url);
curl_setopt($c, CURLOPT_HTTPHEADER, $context);
curl_setopt($c, CURLOPT_USERAGENT, "LODSPeaKr version " . $conf['version']);
curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
$aux = curl_exec($c); // execute the curl command
if ($conf['debug']) {
if ($aux == false) {
Logging::log(
"Error executing SPARQL query (" . $this->sparqlUrl . "): " . curl_error($c),
E_USER_ERROR
);
echo("Error executing SPARQL query (" . $this->sparqlUrl . "): " . curl_error($c));
}
}
$http_status = intval(curl_getinfo($c, CURLINFO_HTTP_CODE));
curl_close($c);
if (!empty($auxoutput)) {
$this->params['output'] = $auxoutput;
}
if (is_int($conf['cache']['global']) && $conf['cache']['global'] > 0 && $http_status == 200) {
file_put_contents($cacheFile, ($aux), LOCK_EX);
if ($conf['debug']) {
$msg = "Notice: Writing results in " . $cacheFile . "\n";
Logging::log($msg, E_USER_NOTICE);
echo($msg);
}
}
}
if (preg_match("/select/i", $q)) {
$r = json_decode($aux, true);
if ($conf['debug']) {
if ($r == false) {
Logging::log("Warning: Results from a SELECT sparql query couldn't get parsed", E_USER_WARNING);
echo("Warning: Results from a SELECT sparql query couldn't get parsed");
}
}
return $r;
}
if (preg_match("/describe/i", $q)) {
return $aux;
}
if (preg_match("/construct/i", $q)) {
return $aux;
}
if (preg_match("/ask/i", $q)) {
$r = json_decode($aux, true);
return $r;
} }
}
return $r;
}
if(preg_match("/describe/i", $q)){
return $aux;
} }
if(preg_match("/construct/i", $q)){
return $aux; public function queryPost($q)
{
$params = $this->params;
$params['query'] = $q;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $this->sparqlUrl);
curl_setopt($ch, CURLOPT_POST, count($params));
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//execute post
$result = curl_exec($ch);
return $result;
} }
if(preg_match("/ask/i", $q)){
$r = json_decode($aux, true); public function getSparqlURL()
return $r; {
return $this->sparqlUrl;
} }
}
public function queryPost($q){
$params = $this->params;
$params['query'] = $q;
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$this->sparqlUrl);
curl_setopt($ch,CURLOPT_POST,count($params));
curl_setopt($ch,CURLOPT_POSTFIELDS,http_build_query($params));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//execute post
$result = curl_exec($ch);
return $result;
}
public function getSparqlURL(){
return $this->sparqlUrl;
}
}
}
This diff is collapsed.
...@@ -4,61 +4,67 @@ namespace uib\ub\loadspeakr; ...@@ -4,61 +4,67 @@ namespace uib\ub\loadspeakr;
use stdClass; use stdClass;
class HTTPStatus { class HTTPStatus
{
public static function send303($uri, $ext){ public static function send303($uri, $ext)
header("HTTP/1.0 303 See Other"); {
header("Location: ".$uri); header("HTTP/1.0 303 See Other");
header("Content-type: ".$ext); header("Location: " . $uri);
echo HTTPStatus::_getContent("303", $uri); header("Content-type: " . $ext);
exit(0); echo HTTPStatus::_getContent("303", $uri);
} exit(0);
}
public static function send401($uri)
{
header("HTTP/1.0 401 Forbidden");
echo HTTPStatus::_getContent("401", $uri);
exit(0);
}
public static function send404($uri)
{
header("HTTP/1.0 404 Not Found");
$alt = "LODSPeaKr couldn't find the resource " . $uri;
echo HTTPStatus::_getContent("404", $alt);
exit(0);
}
public static function send406($uri)
{
header("HTTP/1.0 406 Not Acceptable");
$alt = "LODSPeaKr can't return content acceptable according to the Accept headers sent in the request for " . $uri;
echo HTTPStatus::_getContent("406", $alt);
exit(0);
}
public static function send500($uri)
{
header("HTTP/1.0 500 Internal Server Error");
$alt = "There was an internal error when processing " . $uri;
echo HTTPStatus::_getContent("500", $alt);
exit(0);
}
private static function _getContent($n, $alt)
{
global $conf;
global $lodspk;
$lodspk['root'] = $conf['root'];
$lodspk['home'] = $conf['basedir'];
$lodspk['baseUrl'] = $conf['basedir'];
$lodspk['ns'] = $conf['ns'];
$lodspk['this']['value'] = $uri;
$lodspk['this']['curie'] = Utils::uri2curie($uri);
$lodspk['this']['local'] = $localUri;
$file = $conf['httpStatus']['directory'] . "/" . $n . ".template";
public static function send401($uri){ if (file_exists($conf['home'] . $file)) {
header("HTTP/1.0 401 Forbidden"); require_once("Utils.php");
echo HTTPStatus::_getContent("401", $uri); Utils::showView($lodspk, new stdClass(), $file);
exit(0); } else {
} return $alt . "\n\n";
}
public static function send404($uri){
header("HTTP/1.0 404 Not Found");
$alt = "LODSPeaKr couldn't find the resource ".$uri;
echo HTTPStatus::_getContent("404", $alt);
exit(0);
}
public static function send406($uri){
header("HTTP/1.0 406 Not Acceptable");
$alt = "LODSPeaKr can't return content acceptable according to the Accept headers sent in the request for ".$uri;
echo HTTPStatus::_getContent("406", $alt);
exit(0);
}
public static function send500($uri){
header("HTTP/1.0 500 Internal Server Error");
$alt = "There was an internal error when processing ".$uri;
echo HTTPStatus::_getContent("500", $alt);
exit(0);
}
private static function _getContent($n, $alt){
global $conf;
global $lodspk;
$lodspk['root'] = $conf['root'];
$lodspk['home'] = $conf['basedir'];
$lodspk['baseUrl'] = $conf['basedir'];
$lodspk['ns'] = $conf['ns'];
$lodspk['this']['value'] = $uri;
$lodspk['this']['curie'] = Utils::uri2curie($uri);
$lodspk['this']['local'] = $localUri;
$file = $conf['httpStatus']['directory']."/".$n.".template";
if(file_exists($conf['home'].$file)){
require_once("Utils.php");
Utils::showView($lodspk, new stdClass(), $file);
}else{
return $alt."\n\n";
} }
}
} }
This diff is collapsed.
...@@ -2,44 +2,44 @@ ...@@ -2,44 +2,44 @@
namespace uib\ub\loadspeakr; namespace uib\ub\loadspeakr;
class Logging
class Logging { {
public static function init()
public static function init(){ {
$logs = array(); $logs = array();
if ($handle = opendir('cache/')) { if ($handle = opendir('cache/')) {
while (false !== ($entry = readdir($handle))) { while (false !== ($entry = readdir($handle))) {
if (strpos($entry, ".log") == strlen($entry)-4) { if (strpos($entry, ".log") == strlen($entry) - 4) {
$logs[] = $entry; $logs[] = $entry;
}
}
closedir($handle);
} }
} sort($logs);
closedir($handle); $alogs = "";
} $list = array();
sort($logs); foreach ($logs as $v) {
$alogs = ""; $newtokens = array(".", "/");
$list = array(); $oldtokens = array("___DOT___", "___SLASH___");
foreach($logs as $v){ $label = str_replace($oldtokens, $newtokens, $v);
$newtokens = array( ".", "/"); $x = explode("_", $label);
$oldtokens = array("___DOT___", "___SLASH___"); $y = array_shift($x);
$label = str_replace($oldtokens, $newtokens, $v); array_shift($x);
$x = explode("_", $label); if (!isset($list[$y])) {
$y = array_shift($x); $list[$y] = array();
array_shift($x); }
if(!isset($list[$y])){ $list[$y][] = array("name" => implode("_", $x), "url" => $v);
$list[$y] = array(); //$alogs .= "<p><a href='#lodspeakr/cache/$v'>$label</a></p>";
} }
$list[$y][] = array("name" => implode("_", $x), "url" => $v); krsort($list);
//$alogs .= "<p><a href='#lodspeakr/cache/$v'>$label</a></p>"; foreach ($list as $k => $v) {
} $alogs .= "<li>" . date("H:i:s", $k) . "<ul>\n";
krsort($list); foreach ($v as $w) {
foreach($list as $k => $v){ $alogs .= " <li><a href='#cache/" . $w['url'] . "'>" . $w['name'] . "</a></li>\n"; // TSL : removed hardcoded "lodspeakr" after #
$alogs .= "<li>".date("H:i:s", $k)."<ul>\n"; }
foreach($v as $w){ $alogs .= "</ul></li>";
$alogs .= " <li><a href='#cache/".$w['url']."'>".$w['name']."</a></li>\n"; // TSL : removed hardcoded "lodspeakr" after # }
} echo "
$alogs .="</ul></li>";
}
echo "
<!DOCTYPE html> <!DOCTYPE html>
<html> <html>
<head> <head>
...@@ -122,27 +122,30 @@ class Logging { ...@@ -122,27 +122,30 @@ class Logging {
</script> </script>
</body> </body>
</html>"; </html>";
}
public static function log($msg){
global $conf;
$log = array('timestamp' => time());
$log['message'] = $msg;
if($conf['logfile'] != null){
fwrite($conf['logfile'], ", ".json_encode($log));
} }
}
public static function createLogFile($url){ public static function log($msg)
$oldtokens = array( ".", "/"); {
$newtokens = array("___DOT___", "___SLASH___"); global $conf;
$filename = str_replace($oldtokens, $newtokens, $url); $log = array('timestamp' => time());
$logfile = fopen("cache/".time()."_".rand()."_".$filename.".log", "w"); $log['message'] = $msg;
if($logfile === FALSE){ if ($conf['logfile'] != null) {
die("Can't create log file. Check permissions in <tt>cache/</tt> directory."); fwrite($conf['logfile'], ", " . json_encode($log));
}
} }
$initialmsg = array('timestamp' => time(), 'message' => "Starting log for ".$url);
fwrite($logfile, "{ \"logs\": [".json_encode($initialmsg));
return $logfile; public static function createLogFile($url)
} {
$oldtokens = array(".", "/");
$newtokens = array("___DOT___", "___SLASH___");
$filename = str_replace($oldtokens, $newtokens, $url);
$logfile = fopen("cache/" . time() . "_" . rand() . "_" . $filename . ".log", "w");
if ($logfile === false) {
die("Can't create log file. Check permissions in <tt>cache/</tt> directory.");
}
$initialmsg = array('timestamp' => time(), 'message' => "Starting log for " . $url);
fwrite($logfile, "{ \"logs\": [" . json_encode($initialmsg));
return $logfile;
}
} }
...@@ -2,51 +2,55 @@ ...@@ -2,51 +2,55 @@
namespace uib\ub\loadspeakr; namespace uib\ub\loadspeakr;
use Exception; use Exception;
use PDO; use PDO;
use PDOException; use PDOException;
class MetaDb { class MetaDb
private $dbLocation; {
private $dbLocation;
public function __construct($location){
$this->dbLocation = $location; public function __construct($location)
} {
$this->dbLocation = $location;
public function query($q){ }
public function query($q)
{
global $conf; global $conf;
try{ try {
$db = new PDO('sqlite:'.$this->dbLocation); $db = new PDO('sqlite:' . $this->dbLocation);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING); $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
$results = array(); $results = array();
foreach($db->query($q) as $entry) { foreach ($db->query($q) as $entry) {
array_push($results, $entry); array_push($results, $entry);
} }
$db = NULL; $db = null;
}catch(PDOException $e){ } catch (PDOException $e) {
print 'Exception query : '.$e->getMessage()."\nDatabase used:".$this->dbLocation."\nPlease check the webserver has write permissions to the file AND the directory, as well as you have installed the driver for PHP and SQLite"; print 'Exception query : ' . $e->getMessage(
exit(10); ) . "\nDatabase used:" . $this->dbLocation . "\nPlease check the webserver has write permissions to the file AND the directory, as well as you have installed the driver for PHP and SQLite";
} exit(10);
}
return $results; return $results;
} }
public function write($q){ public function write($q)
{
global $conf; global $conf;
try{ try {
$db = new PDO('sqlite:'.$this->dbLocation); $db = new PDO('sqlite:' . $this->dbLocation);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$results = $db->exec($q); $results = $db->exec($q);
$db = NULL; $db = null;
}catch(Exception $e){ } catch (Exception $e) {
echo "Can't write in SQLite database. Please check you have granted write permissions to <tt>meta/</tt> and <tt>meta/db.sqlite</tt>.<br/>Also you can check a list of <a href='https://github.com/alangrafu/lodspeakr/wiki/CommonErrors'>common errors</a> and how to <a href='https://github.com/alangrafu/lodspeakr/wiki/Wipe-out-the-database'>wipe out the database</a>'"; echo "Can't write in SQLite database. Please check you have granted write permissions to <tt>meta/</tt> and <tt>meta/db.sqlite</tt>.<br/>Also you can check a list of <a href='https://github.com/alangrafu/lodspeakr/wiki/CommonErrors'>common errors</a> and how to <a href='https://github.com/alangrafu/lodspeakr/wiki/Wipe-out-the-database'>wipe out the database</a>'";
if($conf['debug']){ if ($conf['debug']) {
Logging::log('Exception exec: '.$e->getMessage(), E_USER_ERROR); Logging::log('Exception exec: ' . $e->getMessage(), E_USER_ERROR);
} }
exit(1); exit(1);
} }
return $results; return $results;
} }
} }
...@@ -5,9 +5,11 @@ namespace uib\ub\loadspeakr; ...@@ -5,9 +5,11 @@ namespace uib\ub\loadspeakr;
use Exception; use Exception;
class Queries { class Queries
public static function uriExist($uri, $e){ {
$q = "ASK WHERE{ public static function uriExist($uri, $e)
{
$q = "ASK WHERE{
{ {
GRAPH ?g{ GRAPH ?g{
{<$uri> ?p1 []} {<$uri> ?p1 []}
...@@ -24,15 +26,16 @@ class Queries { ...@@ -24,15 +26,16 @@ class Queries {
{[] ?p2 <$uri>} {[] ?p2 <$uri>}
} }
}"; }";
$r = $e->query($q); $r = $e->query($q);
if($r['boolean'] && strtolower($r['boolean']) !== false){ if ($r['boolean'] && strtolower($r['boolean']) !== false) {
return true; return true;
} }
return false; return false;
} }
public static function getClass($uri, $e){ public static function getClass($uri, $e)
$q = "SELECT DISTINCT ?class ?inst WHERE{ {
$q = "SELECT DISTINCT ?class ?inst WHERE{
{ {
GRAPH ?g{ GRAPH ?g{
{ {
...@@ -49,69 +52,67 @@ class Queries { ...@@ -49,69 +52,67 @@ class Queries {
} }
} }
}"; }";
try{ try {
$r = $e->query($q); $r = $e->query($q);
}catch (Exception $ex){ } catch (Exception $ex) {
echo $ex->getMessage(); echo $ex->getMessage();
} }
$result = array(); $result = array();
/*if(sizeof($r['results']['bindings']) == 0){ /*if(sizeof($r['results']['bindings']) == 0){
return 'http://www.w3.org/2000/01/rdf-schema#Resource'; //default value if no type is present return 'http://www.w3.org/2000/01/rdf-schema#Resource'; //default value if no type is present
}*/ }*/
//$result[] = 'http://www.w3.org/2000/01/rdf-schema#Resource'; //All resources are rdf:type rdfs:Resource //$result[] = 'http://www.w3.org/2000/01/rdf-schema#Resource'; //All resources are rdf:type rdfs:Resource
foreach($r['results']['bindings'] as $v){ foreach ($r['results']['bindings'] as $v) {
$result[]= $v['class']['value']; $result[] = $v['class']['value'];
} }
return $result; return $result;
} }
public static function getMetadata($uri, $format, $e)
public static function getMetadata($uri, $format, $e){ {
global $conf; global $conf;
$q = <<<QUERY $q = <<<QUERY
SELECT uri, doc, format FROM document WHERE SELECT uri, doc, format FROM document WHERE
(uri = "$uri" AND format = "$format") OR doc = "$uri" (uri = "$uri" AND format = "$format") OR doc = "$uri"
LIMIT 1 LIMIT 1
QUERY; QUERY;
$r = $e->query($q); $r = $e->query($q);
if(sizeof($r) > 0){ if (sizeof($r) > 0) {
$u = $r[0]['uri']; $u = $r[0]['uri'];
$p = $r[0]['doc']; $p = $r[0]['doc'];
$f = $r[0]['format']; $f = $r[0]['format'];
return array($u, $p, $f); return array($u, $p, $f);
}else{ } else {
return NULL; return null;
} }
} }
public static function createPage($uri, $localUri, $contentType, $e)
{
global $conf;
public static function createPage($uri, $localUri, $contentType, $e){ $ext = 'html';
global $conf; $inserts = "";
foreach ($conf['http_accept'] as $extension => $f) {
$ext = 'html'; $page = $localUri . $conf['extension_connector'] . $extension;
$inserts = ""; foreach ($f as $v) {
foreach($conf['http_accept'] as $extension => $f){ if ($contentType == $v) {
$page = $localUri.$conf['extension_connector'].$extension; $returnPage = $localUri . $conf['extension_connector'] . $extension;
foreach($f as $v){ }
if($contentType == $v){ if ($inserts != "") {
$returnPage = $localUri.$conf['extension_connector'].$extension; $inserts .= "UNION ";
} }
if($inserts != ""){ $inserts .= "SELECT '$uri', '$page', '$v' \n";
$inserts .= "UNION "; if ($v == $contentType) {
} $ext = $extension;
$inserts .= "SELECT '$uri', '$page', '$v' \n"; }
if($v == $contentType){ }
$ext = $extension; }
} $q = <<<QUERY
}
}
$q = <<<QUERY
INSERT INTO document (uri, doc, format) $inserts INSERT INTO document (uri, doc, format) $inserts
QUERY; QUERY;
$r = $e->write($q); $r = $e->write($q);
return $returnPage;
}
}
return $returnPage;
}
}
This diff is collapsed.
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment