diff --git a/classes/Convert.php b/classes/Convert.php index d50e794c41b10b6ebcff0b4e4deaf9f57ef6a5da..111c0b4da82b558d77ba80e507e0517b4eb19de2 100644 --- a/classes/Convert.php +++ b/classes/Convert.php @@ -2,114 +2,113 @@ namespace uib\ub\loadspeakr; -//Based (but corrected) from http://www.php.net/manual/en/language.types.object.php#102735 - use Exception; use stdClass; -final class Convert { - # Convert a stdClass to an Array. - static public function object_to_array(stdClass $Class){ - # Typecast to (array) automatically converts stdClass -> array. - $newClass = array(); - - # Iterate through the former properties looking for any stdClass properties. - # Recursively apply (array). - foreach($Class as $key => $value){ - if(is_object($value)&&get_class($value)==='stdClass'){ - $newClass[$key] = self::object_to_array($value); - }else{ - $newClass[$key] = $value; - } - } - 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; - } - } +final class Convert +{ + # Convert a stdClass to an Array. + static public function object_to_array(stdClass $Class) + { + # Typecast to (array) automatically converts stdClass -> array. + $newClass = array(); + + # Iterate through the former properties looking for any stdClass properties. + # Recursively apply (array). + foreach ($Class as $key => $value) { + if (is_object($value) && get_class($value) === 'stdClass') { + $newClass[$key] = self::object_to_array($value); + } else { + $newClass[$key] = $value; + } + } + return $newClass; } - 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; + } + +} diff --git a/classes/Endpoint.php b/classes/Endpoint.php index 69e2bd8b319c46716e9078eac5154d30bda2cbf1..d8b6744a1d41f6dc1be5f95c774957e50ecb177d 100644 --- a/classes/Endpoint.php +++ b/classes/Endpoint.php @@ -3,119 +3,128 @@ namespace uib\ub\loadspeakr; -class Endpoint { - private $sparqlUrl; - private $params; - - public function __construct($sparqlUrl, $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); - } +class Endpoint +{ + private $sparqlUrl; + private $params; + + public function __construct($sparqlUrl, $params) + { + $this->sparqlUrl = $sparqlUrl; + $this->params = $params; } - 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)); + + public function query($q, $output = 'json') + { + global $conf; + if (!empty($this->params['output'])) { + $auxoutput = $this->params['output']; } - } - $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); + $accept = 'application/sparql-results+json'; + if ($output != null) { + $this->params['output'] = $output; } - } - } - 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"); + 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']) { + $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); - return $r; + + public function getSparqlURL() + { + 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; - } - -} +} diff --git a/classes/Exporter.php b/classes/Exporter.php index 7431b2ec4324fa37f6e7a99600cbcb07273478a8..89084dcd72524a74f3fdc3427c84ce0bda060f10 100644 --- a/classes/Exporter.php +++ b/classes/Exporter.php @@ -2,545 +2,538 @@ namespace uib\ub\loadspeakr; - use ARC2; -class Exporter { - private $serialization; - private $graph; - - public function __construct(){ - $this->serialization = ""; - $this->graph = array(); - define("CNT", "http://www.w3.org/2011/content#"); - define("NSVIZON", "http://graves.cl/vizon/"); - define("LS", "http://lodspeakr.org/lda/"); - define("LDA", "http://tw.rpi.edu/lda/"); - define("DC", "http://purl.org/dc/terms/"); - define("RDF", "http://www.w3.org/1999/02/22-rdf-syntax-ns#"); - define("RDFS", "http://www.w3.org/2000/01/rdf-schema#"); - define("OPMV", "http://openprovenance.org/ontology#"); - define("SKOS", "http://www.w3.org/2004/02/skos/core#"); - } - - public function run(){ - global $conf; - $triples = array(); - $t = array(); - $t['s'] = $conf['basedir']; - $t['s_type'] = 'uri'; - $t['p'] = RDF.'type'; - $t['o'] = OPMV.'Agent'; - $t['o_type'] = 'uri'; - array_push($triples, $t); - $t['o'] = SKOS.'Concept'; - array_push($triples, $t); - $t['o'] = LS.'Application'; - array_push($triples, $t); - if($conf['parentApp'] != NULL){ - $t['p'] = OPMV.'wasDerivedFrom'; - $t['o'] = $conf['parentApp']; - array_push($triples, $t); - } - - $t['p'] = LS.'usedParameter'; - $t['o'] = uniqid("_:b"); - $t['o_type'] = 'bnode'; - array_push($triples, $t); - - $t2 = array(); - $t2['s'] = $t['o']; - $t2['s_type'] = 'uri'; - $t2['p'] = RDF.'type'; - $t2['o'] = LS."Parameter"; - $t2['o_type'] = 'uri'; - array_push($triples, $t2); - $t2['p'] = RDFS.'label'; - $t2['o'] = 'root'; - $t2['o_type'] = 'literal'; - array_push($triples, $t2); - $t2['p'] = DC.'hasFormat'; - $t2['o'] = uniqid("_:b"); - $t2['o_type'] = 'bnode'; - array_push($triples, $t2); - - $t2['s'] = $t2['o']; - $t2['s_type'] = 'bnode'; - $t2['p'] = RDF.'type'; - $t2['o'] = CNT."ContentAsText"; - $t2['o_type'] = 'uri'; - array_push($triples, $t2); - $t2['p'] = CNT.'chars'; - $t2['o'] = ($conf['root']); - $t2['o_type'] = 'literal'; - array_push($triples, $t2); - $t2['p'] = DC.'format'; - $t2['o'] = 'text/plain;charset=utf-8'; - $t2['o_type'] = 'literal'; - array_push($triples, $t2); - - - $t['s'] = $conf['basedir'].'endpointManagerComponent'; - $t['s_type'] = 'uri'; - $t['p'] = SKOS.'broader'; - $t['o'] = $conf['basedir']; - $t['o_type'] = 'uri'; - array_push($triples, $t); - $t['p'] = RDF.'type'; - $t['o'] = LS.'LodspeakrEndpointManagerComponent'; - $t['o_type'] = 'uri'; - array_push($triples, $t); - - $t2 = array(); - $t2['s'] = $t['o']; - $t2['s_type'] = 'uri'; - $t2['p'] = RDFS.'subClassOf'; - $t2['o'] = LDA."SparqlEndpointRetriever"; - $t2['o_type'] = 'uri'; - array_push($triples, $t2); - - //Endpoints - foreach($conf['endpoint'] as $k => $v){ - $t['p'] = LS.'usedParameter'; - $t['o'] = uniqid("_:b"); - $t['o_type'] = 'bnode'; - array_push($triples, $t); - - $t2 = array(); - $t2['s'] = $t['o']; - $t2['s_type'] = 'uri'; - $t2['p'] = RDF.'type'; - $t2['o'] = LS."Parameter"; - $t2['o_type'] = 'uri'; - array_push($triples, $t2); - $t2['p'] = RDFS.'label'; - $t2['o'] = $k; - $t2['o_type'] = 'literal'; - array_push($triples, $t2); - $t2['p'] = DC.'hasFormat'; - $t2['o'] = uniqid("_:b"); - $t2['o_type'] = 'bnode'; - array_push($triples, $t2); - - $t2['s'] = $t2['o']; - $t2['s_type'] = 'bnode'; - $t2['p'] = RDF.'type'; - $t2['o'] = CNT."ContentAsText"; - $t2['o_type'] = 'uri'; - array_push($triples, $t2); - $t2['p'] = CNT.'chars'; - $t2['o'] = ($v); - $t2['o_type'] = 'literal'; - array_push($triples, $t2); - $t2['p'] = DC.'format'; - $t2['o'] = 'text/plain;charset=utf-8'; - $t2['o_type'] = 'literal'; - array_push($triples, $t2); - - } - - $t['s'] = $conf['basedir'].'namespaceManagerComponent'; - $t['s_type'] = 'uri'; - $t['p'] = SKOS.'broader'; - $t['o'] = $conf['basedir']; - $t['o_type'] = 'uri'; - array_push($triples, $t); - $t['p'] = RDF.'type'; - $t['o'] = LS.'LodspeakrNamespaceManagerComponent'; - $t['o_type'] = 'uri'; - array_push($triples, $t); - $t2['s'] = $t['o']; - $t2['s_type'] = 'uri'; - $t2['p'] = RDFS.'subClassOf'; - $t2['o'] = LDA."ProcessComponent"; - $t2['o_type'] = 'uri'; - array_push($triples, $t2); - - //Namepsaces - foreach($conf['ns'] as $k => $v){ - $t['p'] = LS.'usedParameter'; - $t['o'] = uniqid("_:b"); - $t['o_type'] = 'bnode'; - array_push($triples, $t); - - $t2 = array(); - $t2['s'] = $t['o']; - $t2['s_type'] = 'uri'; - $t2['p'] = RDF.'type'; - $t2['o'] = LS."Parameter"; - $t2['o_type'] = 'uri'; - array_push($triples, $t2); - $t2['p'] = RDFS.'label'; - $t2['o'] = $k; - $t2['o_type'] = 'literal'; - array_push($triples, $t2); - $t2['p'] = DC.'hasFormat'; - $t2['o'] = uniqid("_:b"); - $t2['o_type'] = 'bnode'; - array_push($triples, $t2); - - $t2['s'] = $t2['o']; - $t2['s_type'] = 'bnode'; - $t2['p'] = RDF.'type'; - $t2['o'] = CNT."ContentAsText"; - $t2['o_type'] = 'uri'; - array_push($triples, $t2); - $t2['p'] = CNT.'chars'; - $t2['o'] = ($v); - $t2['o_type'] = 'literal'; - array_push($triples, $t2); - $t2['p'] = DC.'format'; - $t2['o'] = 'text/plain;charset=utf-8'; - $t2['o_type'] = 'literal'; - array_push($triples, $t2); - - } - - $ser = ARC2::getTurtleSerializer(); - $sparqlComponent = $conf['basedir'].'sparqlComponent';//uniqid("_:b"); - //echo $ser->getSerializedTriples($triples); - //var_dump($this->getComponents($conf['home'].$conf['view']['directory'])); - $models = $this->getComponents($conf['home'].$conf['model']['directory'], ''); - - //Define Process - $t = array(); - $t['s'] = uniqid("_:b"); - $t['s_type'] = 'bnode'; - $t['p'] = RDF.'type'; - $t['o'] = OPMV.'Process'; - $t['o_type'] = 'uri'; - array_push($triples, $t); - foreach($models as $k=>$m){ - - - - //Controlled by - $t['p'] = OPMV.'wasControlledBy'; - $t['o'] = $sparqlComponent; - $t['o_type'] = 'bnode'; - array_push($triples, $t); - - //Associated Agent to this installation - $aux = $t['o']; - $t['s'] = $t['o']; - $t['p'] = SKOS.'broader'; - $t['o'] = $conf['basedir']; - $t['o_type'] = 'uri'; - array_push($triples, $t); - - //Return object for later triple - $t['o'] = $sparqlComponent; - - // Type of query - $t2 = array(); - $t2['s'] = $t['o']; - $t2['s_type'] = 'bnode'; - $t2['p'] = RDF.'type'; - $t2['o'] = LS.'LodspeakrSparqlEndpointRetriever'; - $t2['o_type'] = 'uri'; - - $t3 = array(); - $t3['s'] = $t2['o']; - $t3['s_type'] = 'uri'; - $t3['p'] = RDFS.'subClassOf'; - $t3['o'] = LDA."ProcessComponent"; - $t3['o_type'] = 'uri'; - array_push($triples, $t3); - - array_push($triples, $t2); - $t2['p'] = RDFS.'label'; - $t2['o'] = 'Sparql endpoint component for LODSPeaKr'; - $t2['o_type'] = 'literal'; - array_push($triples, $t2); - - $t['p'] = LS.'usedInput'; - $t['o'] = $conf['basedir'].$conf['model']['directory'].$k; - $t['o_type'] = 'uri'; - array_push($triples, $t); - - $t2 = array(); - $t2['s'] = $t['o']; - $t2['s_type'] = 'uri'; - $t2['p'] = RDF.'type'; - $t2['o'] = LS."Input"; - $t2['o_type'] = 'uri'; - array_push($triples, $t2); - $t2['p'] = RDFS.'label'; - $t2['o'] = $conf['model']['directory'].$k; - $t2['o_type'] = 'literal'; - array_push($triples, $t2); - - $t2['p'] = DC.'hasFormat'; - $t2['o'] = uniqid("_:b"); - $t2['o_type'] = 'bnode'; - array_push($triples, $t2); - - $t2['s'] = $t2['o']; - $t2['s_type'] = 'bnode'; - $t2['p'] = RDF.'type'; - $t2['o'] = CNT."ContentAsText"; - $t2['o_type'] = 'uri'; - array_push($triples, $t2); - $t2['p'] = CNT.'chars'; - $t2['o'] = ($m); - $t2['o_type'] = 'literal'; - array_push($triples, $t2); - $t2['p'] = DC.'format'; - $t2['o'] = 'text/plain;charset=utf-8'; - $t2['o_type'] = 'literal'; - array_push($triples, $t2); - //break; - } - - - //Views - - $viewsComponent = $conf['basedir'].'visualizationComponent';//uniqid("_:b"); - $views = $this->getComponents($conf['home'].$conf['view']['directory'], ''); - - //Define Process - $t = array(); - $t['s'] = uniqid("_:b"); - $t['s_type'] = 'bnode'; - $t['p'] = RDF.'type'; - $t['o'] = OPMV.'Process'; - $t['o_type'] = 'uri'; - array_push($triples, $t); - foreach($views as $k=>$m){ - - - - //Controlled by - $t['p'] = OPMV.'wasControlledBy'; - $t['o'] = $viewsComponent; - $t['o_type'] = 'bnode'; - array_push($triples, $t); - - //Associated Agent to this installation - $aux = $t['o']; - $t['s'] = $t['o']; - $t['p'] = SKOS.'broader'; - $t['o'] = $conf['basedir']; - $t['o_type'] = 'uri'; - array_push($triples, $t); - - //Return object for later triple - $t['o'] = $viewsComponent; - - // Type of query - $t2 = array(); - $t2['s'] = $t['o']; - $t2['s_type'] = 'bnode'; - $t2['p'] = RDF.'type'; - $t2['o'] = LS.'LodspeakrVisualComponent'; - $t2['o_type'] = 'uri'; - array_push($triples, $t2); - - $t3 = array(); - $t3['s'] = $t2['o']; - $t3['s_type'] = 'uri'; - $t3['p'] = RDFS.'subClassOf'; - $t3['o'] = LDA."VisualComponent"; - $t3['o_type'] = 'uri'; - array_push($triples, $t3); - - $t2['p'] = RDFS.'label'; - $t2['o'] = 'Haanga-based visualization component for LODSPeaKr'; - $t2['o_type'] = 'literal'; - array_push($triples, $t2); - - $t['p'] = LS.'usedInput'; - $t['o'] = $conf['basedir'].$conf['view']['directory'].$k; - $t['o_type'] = 'uri'; - array_push($triples, $t); - - - $t2 = array(); - $t2['s'] = $t['o']; - $t2['s_type'] = 'uri'; - $t2['p'] = RDF.'type'; - $t2['o'] = LS."Input"; - $t2['o_type'] = 'uri'; - array_push($triples, $t2); - $t2['p'] = RDFS.'label'; - $t2['o'] = $conf['view']['directory'].$k; - $t2['o_type'] = 'literal'; - array_push($triples, $t2); - $t2['p'] = DC.'hasFormat'; - $t2['o'] = uniqid("_:b"); - $t2['o_type'] = 'bnode'; - array_push($triples, $t2); - - $t2['s'] = $t2['o']; - $t2['s_type'] = 'bnode'; - $t2['p'] = RDF.'type'; - $t2['o'] = CNT."ContentAsText"; - $t2['o_type'] = 'uri'; - array_push($triples, $t2); - $t2['p'] = CNT.'chars'; - $t2['o'] = ($m); - $t2['o_type'] = 'literal'; - array_push($triples, $t2); - $t2['p'] = DC.'format'; - $t2['o'] = 'text/plain;charset=utf-8'; - $t2['o_type'] = 'literal'; - array_push($triples, $t2); - //break; - } - - //Static files - - $staticComponent = $conf['basedir'].'staticComponent';//uniqid("_:b"); - $statics = $this->getComponents($conf['home'].$conf['static']['directory'], ''); - - //Define Process - $t = array(); - $t['s'] = uniqid("_:b"); - $t['s_type'] = 'bnode'; - $t['p'] = RDF.'type'; - $t['o'] = OPMV.'Process'; - $t['o_type'] = 'uri'; - array_push($triples, $t); - foreach($statics as $k=>$m){ - - - - //Controlled by - $t['p'] = OPMV.'wasControlledBy'; - $t['o'] = $staticComponent; - $t['o_type'] = 'bnode'; - array_push($triples, $t); - - //Associated Agent to this installation - $aux = $t['o']; - $t['s'] = $t['o']; - $t['p'] = SKOS.'broader'; - $t['o'] = $conf['basedir']; - $t['o_type'] = 'uri'; - array_push($triples, $t); - - //Return object for later triple - $t['o'] = $staticComponent; - - // Type of query - $t2 = array(); - $t2['s'] = $t['o']; - $t2['s_type'] = 'bnode'; - $t2['p'] = RDF.'type'; - $t2['o'] = LS.'LodspeakrStaticElementsComponent'; - $t2['o_type'] = 'uri'; - array_push($triples, $t2); - - $t3 = array(); - $t3['s'] = $t2['o']; - $t3['s_type'] = 'uri'; - $t3['p'] = RDFS.'subClassOf'; - $t3['o'] = LDA."ProcessComponent"; - $t3['o_type'] = 'uri'; - array_push($triples, $t3); - - array_push($triples, $t2); - $t2['p'] = RDFS.'label'; - $t2['o'] = 'Component of LODSPeaKr in charge of static content'; - $t2['o_type'] = 'literal'; - array_push($triples, $t2); - - $t['p'] = LS.'usedInput'; - $t['o'] = $conf['basedir'].$conf['static']['directory'].$k; - $t['o_type'] = 'uri'; - array_push($triples, $t); - - $t2 = array(); - $t2['s'] = $t['o']; - $t2['s_type'] = 'uri'; - $t2['p'] = RDF.'type'; - $t2['o'] = LS."Input"; - $t2['o_type'] = 'uri'; - array_push($triples, $t2); - $t2['p'] = RDFS.'label'; - $t2['o'] = $conf['static']['directory'].$k; - $t2['o_type'] = 'literal'; - array_push($triples, $t2); - - $t2['p'] = DC.'hasFormat'; - $t2['o'] = uniqid("_:b"); - $t2['o_type'] = 'bnode'; - array_push($triples, $t2); - - $t2['s'] = $t2['o']; - $t2['s_type'] = 'bnode'; - $t2['p'] = RDF.'type'; - $t2['o'] = CNT."ContentAsText"; - $t2['o_type'] = 'uri'; - array_push($triples, $t2); - $t2['p'] = CNT.'chars'; - $t2['o'] = ($m); - $t2['o_type'] = 'literal'; - array_push($triples, $t2); - $t2['p'] = DC.'format'; - $t2['o'] = 'text/plain;charset=utf-8'; - $t2['o_type'] = 'literal'; - array_push($triples, $t2); - //break; - } - - - echo "#You can copy and paste the following data into a new\n"; - echo "#LODSPeaKr instance at http://exampleofinstance.org/import\n"; - echo "#As a side note: this is a turtle document but is served as text/plain to make it easier to copy&paste\n\n\n"; - echo $ser->getSerializedTriples($triples); - } - - private static function getTriple($s, $p, $o){ - } - - private function createParameter($name, $value){ - $s = uniqid("_:b"); - $s_type = 'bnode'; - $p = RDF."type"; - $o = NSVIZON."Parameter"; - $o_type = 'uri'; - - - } - - private function getViews($dir){ - global $conf; - $files = ""; - chdir($dir); - $handle = opendir('.'); - while (false !== ($viewFile = readdir($handle))) { - if($viewFile != "." && $viewFile != ".."){ - $files .= $viewFile.": ".htmlspecialchars(file_get_contents($viewFile))."\n"; - $t = array(); - } - } - chdir(".."); - return $files; - } - - private function getComponents($dir, $prefix){ - global $conf; - $files = array(); - $subDirs = array(); - chdir($dir); - $handle = opendir('.'); - while (false !== ($modelFile = readdir($handle))) { - if($modelFile != "." && $modelFile != ".."){ - if(is_dir($modelFile)){ - //Save it for later, after all the queries in the current directory has been resolved - $subDirs[]=$modelFile; - }else{ - $files[$prefix.$modelFile] = (file_get_contents($modelFile))."\n"; - } - } - } - - foreach($subDirs as $dir){ - //$files[$dir] = array(); - $files = array_merge($files, $this->getComponents($dir, $prefix.$dir."/")); +class Exporter +{ + private $serialization; + private $graph; + + public function __construct() + { + $this->serialization = ""; + $this->graph = array(); + define("CNT", "http://www.w3.org/2011/content#"); + define("NSVIZON", "http://graves.cl/vizon/"); + define("LS", "http://lodspeakr.org/lda/"); + define("LDA", "http://tw.rpi.edu/lda/"); + define("DC", "http://purl.org/dc/terms/"); + define("RDF", "http://www.w3.org/1999/02/22-rdf-syntax-ns#"); + define("RDFS", "http://www.w3.org/2000/01/rdf-schema#"); + define("OPMV", "http://openprovenance.org/ontology#"); + define("SKOS", "http://www.w3.org/2004/02/skos/core#"); + } + + public function run() + { + global $conf; + $triples = array(); + $t = array(); + $t['s'] = $conf['basedir']; + $t['s_type'] = 'uri'; + $t['p'] = RDF . 'type'; + $t['o'] = OPMV . 'Agent'; + $t['o_type'] = 'uri'; + array_push($triples, $t); + $t['o'] = SKOS . 'Concept'; + array_push($triples, $t); + $t['o'] = LS . 'Application'; + array_push($triples, $t); + if ($conf['parentApp'] != null) { + $t['p'] = OPMV . 'wasDerivedFrom'; + $t['o'] = $conf['parentApp']; + array_push($triples, $t); + } + + $t['p'] = LS . 'usedParameter'; + $t['o'] = uniqid("_:b"); + $t['o_type'] = 'bnode'; + array_push($triples, $t); + + $t2 = array(); + $t2['s'] = $t['o']; + $t2['s_type'] = 'uri'; + $t2['p'] = RDF . 'type'; + $t2['o'] = LS . "Parameter"; + $t2['o_type'] = 'uri'; + array_push($triples, $t2); + $t2['p'] = RDFS . 'label'; + $t2['o'] = 'root'; + $t2['o_type'] = 'literal'; + array_push($triples, $t2); + $t2['p'] = DC . 'hasFormat'; + $t2['o'] = uniqid("_:b"); + $t2['o_type'] = 'bnode'; + array_push($triples, $t2); + + $t2['s'] = $t2['o']; + $t2['s_type'] = 'bnode'; + $t2['p'] = RDF . 'type'; + $t2['o'] = CNT . "ContentAsText"; + $t2['o_type'] = 'uri'; + array_push($triples, $t2); + $t2['p'] = CNT . 'chars'; + $t2['o'] = ($conf['root']); + $t2['o_type'] = 'literal'; + array_push($triples, $t2); + $t2['p'] = DC . 'format'; + $t2['o'] = 'text/plain;charset=utf-8'; + $t2['o_type'] = 'literal'; + array_push($triples, $t2); + + + $t['s'] = $conf['basedir'] . 'endpointManagerComponent'; + $t['s_type'] = 'uri'; + $t['p'] = SKOS . 'broader'; + $t['o'] = $conf['basedir']; + $t['o_type'] = 'uri'; + array_push($triples, $t); + $t['p'] = RDF . 'type'; + $t['o'] = LS . 'LodspeakrEndpointManagerComponent'; + $t['o_type'] = 'uri'; + array_push($triples, $t); + + $t2 = array(); + $t2['s'] = $t['o']; + $t2['s_type'] = 'uri'; + $t2['p'] = RDFS . 'subClassOf'; + $t2['o'] = LDA . "SparqlEndpointRetriever"; + $t2['o_type'] = 'uri'; + array_push($triples, $t2); + + //Endpoints + foreach ($conf['endpoint'] as $k => $v) { + $t['p'] = LS . 'usedParameter'; + $t['o'] = uniqid("_:b"); + $t['o_type'] = 'bnode'; + array_push($triples, $t); + + $t2 = array(); + $t2['s'] = $t['o']; + $t2['s_type'] = 'uri'; + $t2['p'] = RDF . 'type'; + $t2['o'] = LS . "Parameter"; + $t2['o_type'] = 'uri'; + array_push($triples, $t2); + $t2['p'] = RDFS . 'label'; + $t2['o'] = $k; + $t2['o_type'] = 'literal'; + array_push($triples, $t2); + $t2['p'] = DC . 'hasFormat'; + $t2['o'] = uniqid("_:b"); + $t2['o_type'] = 'bnode'; + array_push($triples, $t2); + + $t2['s'] = $t2['o']; + $t2['s_type'] = 'bnode'; + $t2['p'] = RDF . 'type'; + $t2['o'] = CNT . "ContentAsText"; + $t2['o_type'] = 'uri'; + array_push($triples, $t2); + $t2['p'] = CNT . 'chars'; + $t2['o'] = ($v); + $t2['o_type'] = 'literal'; + array_push($triples, $t2); + $t2['p'] = DC . 'format'; + $t2['o'] = 'text/plain;charset=utf-8'; + $t2['o_type'] = 'literal'; + array_push($triples, $t2); + } + + $t['s'] = $conf['basedir'] . 'namespaceManagerComponent'; + $t['s_type'] = 'uri'; + $t['p'] = SKOS . 'broader'; + $t['o'] = $conf['basedir']; + $t['o_type'] = 'uri'; + array_push($triples, $t); + $t['p'] = RDF . 'type'; + $t['o'] = LS . 'LodspeakrNamespaceManagerComponent'; + $t['o_type'] = 'uri'; + array_push($triples, $t); + $t2['s'] = $t['o']; + $t2['s_type'] = 'uri'; + $t2['p'] = RDFS . 'subClassOf'; + $t2['o'] = LDA . "ProcessComponent"; + $t2['o_type'] = 'uri'; + array_push($triples, $t2); + + //Namepsaces + foreach ($conf['ns'] as $k => $v) { + $t['p'] = LS . 'usedParameter'; + $t['o'] = uniqid("_:b"); + $t['o_type'] = 'bnode'; + array_push($triples, $t); + + $t2 = array(); + $t2['s'] = $t['o']; + $t2['s_type'] = 'uri'; + $t2['p'] = RDF . 'type'; + $t2['o'] = LS . "Parameter"; + $t2['o_type'] = 'uri'; + array_push($triples, $t2); + $t2['p'] = RDFS . 'label'; + $t2['o'] = $k; + $t2['o_type'] = 'literal'; + array_push($triples, $t2); + $t2['p'] = DC . 'hasFormat'; + $t2['o'] = uniqid("_:b"); + $t2['o_type'] = 'bnode'; + array_push($triples, $t2); + + $t2['s'] = $t2['o']; + $t2['s_type'] = 'bnode'; + $t2['p'] = RDF . 'type'; + $t2['o'] = CNT . "ContentAsText"; + $t2['o_type'] = 'uri'; + array_push($triples, $t2); + $t2['p'] = CNT . 'chars'; + $t2['o'] = ($v); + $t2['o_type'] = 'literal'; + array_push($triples, $t2); + $t2['p'] = DC . 'format'; + $t2['o'] = 'text/plain;charset=utf-8'; + $t2['o_type'] = 'literal'; + array_push($triples, $t2); + } + + $ser = ARC2::getTurtleSerializer(); + $sparqlComponent = $conf['basedir'] . 'sparqlComponent';//uniqid("_:b"); + //echo $ser->getSerializedTriples($triples); + //var_dump($this->getComponents($conf['home'].$conf['view']['directory'])); + $models = $this->getComponents($conf['home'] . $conf['model']['directory'], ''); + + //Define Process + $t = array(); + $t['s'] = uniqid("_:b"); + $t['s_type'] = 'bnode'; + $t['p'] = RDF . 'type'; + $t['o'] = OPMV . 'Process'; + $t['o_type'] = 'uri'; + array_push($triples, $t); + foreach ($models as $k => $m) { + //Controlled by + $t['p'] = OPMV . 'wasControlledBy'; + $t['o'] = $sparqlComponent; + $t['o_type'] = 'bnode'; + array_push($triples, $t); + + //Associated Agent to this installation + $aux = $t['o']; + $t['s'] = $t['o']; + $t['p'] = SKOS . 'broader'; + $t['o'] = $conf['basedir']; + $t['o_type'] = 'uri'; + array_push($triples, $t); + + //Return object for later triple + $t['o'] = $sparqlComponent; + + // Type of query + $t2 = array(); + $t2['s'] = $t['o']; + $t2['s_type'] = 'bnode'; + $t2['p'] = RDF . 'type'; + $t2['o'] = LS . 'LodspeakrSparqlEndpointRetriever'; + $t2['o_type'] = 'uri'; + + $t3 = array(); + $t3['s'] = $t2['o']; + $t3['s_type'] = 'uri'; + $t3['p'] = RDFS . 'subClassOf'; + $t3['o'] = LDA . "ProcessComponent"; + $t3['o_type'] = 'uri'; + array_push($triples, $t3); + + array_push($triples, $t2); + $t2['p'] = RDFS . 'label'; + $t2['o'] = 'Sparql endpoint component for LODSPeaKr'; + $t2['o_type'] = 'literal'; + array_push($triples, $t2); + + $t['p'] = LS . 'usedInput'; + $t['o'] = $conf['basedir'] . $conf['model']['directory'] . $k; + $t['o_type'] = 'uri'; + array_push($triples, $t); + + $t2 = array(); + $t2['s'] = $t['o']; + $t2['s_type'] = 'uri'; + $t2['p'] = RDF . 'type'; + $t2['o'] = LS . "Input"; + $t2['o_type'] = 'uri'; + array_push($triples, $t2); + $t2['p'] = RDFS . 'label'; + $t2['o'] = $conf['model']['directory'] . $k; + $t2['o_type'] = 'literal'; + array_push($triples, $t2); + + $t2['p'] = DC . 'hasFormat'; + $t2['o'] = uniqid("_:b"); + $t2['o_type'] = 'bnode'; + array_push($triples, $t2); + + $t2['s'] = $t2['o']; + $t2['s_type'] = 'bnode'; + $t2['p'] = RDF . 'type'; + $t2['o'] = CNT . "ContentAsText"; + $t2['o_type'] = 'uri'; + array_push($triples, $t2); + $t2['p'] = CNT . 'chars'; + $t2['o'] = ($m); + $t2['o_type'] = 'literal'; + array_push($triples, $t2); + $t2['p'] = DC . 'format'; + $t2['o'] = 'text/plain;charset=utf-8'; + $t2['o_type'] = 'literal'; + array_push($triples, $t2); + //break; + } + + + //Views + + $viewsComponent = $conf['basedir'] . 'visualizationComponent';//uniqid("_:b"); + $views = $this->getComponents($conf['home'] . $conf['view']['directory'], ''); + + //Define Process + $t = array(); + $t['s'] = uniqid("_:b"); + $t['s_type'] = 'bnode'; + $t['p'] = RDF . 'type'; + $t['o'] = OPMV . 'Process'; + $t['o_type'] = 'uri'; + array_push($triples, $t); + foreach ($views as $k => $m) { + //Controlled by + $t['p'] = OPMV . 'wasControlledBy'; + $t['o'] = $viewsComponent; + $t['o_type'] = 'bnode'; + array_push($triples, $t); + + //Associated Agent to this installation + $aux = $t['o']; + $t['s'] = $t['o']; + $t['p'] = SKOS . 'broader'; + $t['o'] = $conf['basedir']; + $t['o_type'] = 'uri'; + array_push($triples, $t); + + //Return object for later triple + $t['o'] = $viewsComponent; + + // Type of query + $t2 = array(); + $t2['s'] = $t['o']; + $t2['s_type'] = 'bnode'; + $t2['p'] = RDF . 'type'; + $t2['o'] = LS . 'LodspeakrVisualComponent'; + $t2['o_type'] = 'uri'; + array_push($triples, $t2); + + $t3 = array(); + $t3['s'] = $t2['o']; + $t3['s_type'] = 'uri'; + $t3['p'] = RDFS . 'subClassOf'; + $t3['o'] = LDA . "VisualComponent"; + $t3['o_type'] = 'uri'; + array_push($triples, $t3); + + $t2['p'] = RDFS . 'label'; + $t2['o'] = 'Haanga-based visualization component for LODSPeaKr'; + $t2['o_type'] = 'literal'; + array_push($triples, $t2); + + $t['p'] = LS . 'usedInput'; + $t['o'] = $conf['basedir'] . $conf['view']['directory'] . $k; + $t['o_type'] = 'uri'; + array_push($triples, $t); + + + $t2 = array(); + $t2['s'] = $t['o']; + $t2['s_type'] = 'uri'; + $t2['p'] = RDF . 'type'; + $t2['o'] = LS . "Input"; + $t2['o_type'] = 'uri'; + array_push($triples, $t2); + $t2['p'] = RDFS . 'label'; + $t2['o'] = $conf['view']['directory'] . $k; + $t2['o_type'] = 'literal'; + array_push($triples, $t2); + $t2['p'] = DC . 'hasFormat'; + $t2['o'] = uniqid("_:b"); + $t2['o_type'] = 'bnode'; + array_push($triples, $t2); + + $t2['s'] = $t2['o']; + $t2['s_type'] = 'bnode'; + $t2['p'] = RDF . 'type'; + $t2['o'] = CNT . "ContentAsText"; + $t2['o_type'] = 'uri'; + array_push($triples, $t2); + $t2['p'] = CNT . 'chars'; + $t2['o'] = ($m); + $t2['o_type'] = 'literal'; + array_push($triples, $t2); + $t2['p'] = DC . 'format'; + $t2['o'] = 'text/plain;charset=utf-8'; + $t2['o_type'] = 'literal'; + array_push($triples, $t2); + //break; + } + + //Static files + + $staticComponent = $conf['basedir'] . 'staticComponent';//uniqid("_:b"); + $statics = $this->getComponents($conf['home'] . $conf['static']['directory'], ''); + + //Define Process + $t = array(); + $t['s'] = uniqid("_:b"); + $t['s_type'] = 'bnode'; + $t['p'] = RDF . 'type'; + $t['o'] = OPMV . 'Process'; + $t['o_type'] = 'uri'; + array_push($triples, $t); + foreach ($statics as $k => $m) { + //Controlled by + $t['p'] = OPMV . 'wasControlledBy'; + $t['o'] = $staticComponent; + $t['o_type'] = 'bnode'; + array_push($triples, $t); + + //Associated Agent to this installation + $aux = $t['o']; + $t['s'] = $t['o']; + $t['p'] = SKOS . 'broader'; + $t['o'] = $conf['basedir']; + $t['o_type'] = 'uri'; + array_push($triples, $t); + + //Return object for later triple + $t['o'] = $staticComponent; + + // Type of query + $t2 = array(); + $t2['s'] = $t['o']; + $t2['s_type'] = 'bnode'; + $t2['p'] = RDF . 'type'; + $t2['o'] = LS . 'LodspeakrStaticElementsComponent'; + $t2['o_type'] = 'uri'; + array_push($triples, $t2); + + $t3 = array(); + $t3['s'] = $t2['o']; + $t3['s_type'] = 'uri'; + $t3['p'] = RDFS . 'subClassOf'; + $t3['o'] = LDA . "ProcessComponent"; + $t3['o_type'] = 'uri'; + array_push($triples, $t3); + + array_push($triples, $t2); + $t2['p'] = RDFS . 'label'; + $t2['o'] = 'Component of LODSPeaKr in charge of static content'; + $t2['o_type'] = 'literal'; + array_push($triples, $t2); + + $t['p'] = LS . 'usedInput'; + $t['o'] = $conf['basedir'] . $conf['static']['directory'] . $k; + $t['o_type'] = 'uri'; + array_push($triples, $t); + + $t2 = array(); + $t2['s'] = $t['o']; + $t2['s_type'] = 'uri'; + $t2['p'] = RDF . 'type'; + $t2['o'] = LS . "Input"; + $t2['o_type'] = 'uri'; + array_push($triples, $t2); + $t2['p'] = RDFS . 'label'; + $t2['o'] = $conf['static']['directory'] . $k; + $t2['o_type'] = 'literal'; + array_push($triples, $t2); + + $t2['p'] = DC . 'hasFormat'; + $t2['o'] = uniqid("_:b"); + $t2['o_type'] = 'bnode'; + array_push($triples, $t2); + + $t2['s'] = $t2['o']; + $t2['s_type'] = 'bnode'; + $t2['p'] = RDF . 'type'; + $t2['o'] = CNT . "ContentAsText"; + $t2['o_type'] = 'uri'; + array_push($triples, $t2); + $t2['p'] = CNT . 'chars'; + $t2['o'] = ($m); + $t2['o_type'] = 'literal'; + array_push($triples, $t2); + $t2['p'] = DC . 'format'; + $t2['o'] = 'text/plain;charset=utf-8'; + $t2['o_type'] = 'literal'; + array_push($triples, $t2); + //break; + } + + + echo "#You can copy and paste the following data into a new\n"; + echo "#LODSPeaKr instance at http://exampleofinstance.org/import\n"; + echo "#As a side note: this is a turtle document but is served as text/plain to make it easier to copy&paste\n\n\n"; + echo $ser->getSerializedTriples($triples); + } + + private static function getTriple($s, $p, $o) + { + } + + private function createParameter($name, $value) + { + $s = uniqid("_:b"); + $s_type = 'bnode'; + $p = RDF . "type"; + $o = NSVIZON . "Parameter"; + $o_type = 'uri'; + } + + private function getViews($dir) + { + global $conf; + $files = ""; + chdir($dir); + $handle = opendir('.'); + while (false !== ($viewFile = readdir($handle))) { + if ($viewFile != "." && $viewFile != "..") { + $files .= $viewFile . ": " . htmlspecialchars(file_get_contents($viewFile)) . "\n"; + $t = array(); + } + } + chdir(".."); + return $files; + } + + private function getComponents($dir, $prefix) + { + global $conf; + $files = array(); + $subDirs = array(); + chdir($dir); + $handle = opendir('.'); + while (false !== ($modelFile = readdir($handle))) { + if ($modelFile != "." && $modelFile != "..") { + if (is_dir($modelFile)) { + //Save it for later, after all the queries in the current directory has been resolved + $subDirs[] = $modelFile; + } else { + $files[$prefix . $modelFile] = (file_get_contents($modelFile)) . "\n"; + } + } + } + + foreach ($subDirs as $dir) { + //$files[$dir] = array(); + $files = array_merge($files, $this->getComponents($dir, $prefix . $dir . "/")); + } + chdir(".."); + return $files; } - chdir(".."); - return $files; - } } diff --git a/classes/HTTPStatus.php b/classes/HTTPStatus.php index 579d6bbda781d33e1fb2326900366a43e18de620..5355dca7c4410ec6e1e858695a6fbe83209e59bf 100644 --- a/classes/HTTPStatus.php +++ b/classes/HTTPStatus.php @@ -4,61 +4,67 @@ namespace uib\ub\loadspeakr; use stdClass; -class HTTPStatus { - - public static function send303($uri, $ext){ - header("HTTP/1.0 303 See Other"); - header("Location: ".$uri); - header("Content-type: ".$ext); - echo HTTPStatus::_getContent("303", $uri); - exit(0); - } +class HTTPStatus +{ + public static function send303($uri, $ext) + { + header("HTTP/1.0 303 See Other"); + header("Location: " . $uri); + header("Content-type: " . $ext); + 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){ - 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"; - - if(file_exists($conf['home'].$file)){ - require_once("Utils.php"); - Utils::showView($lodspk, new stdClass(), $file); - }else{ - return $alt."\n\n"; + if (file_exists($conf['home'] . $file)) { + require_once("Utils.php"); + Utils::showView($lodspk, new stdClass(), $file); + } else { + return $alt . "\n\n"; + } } - } } diff --git a/classes/Importer.php b/classes/Importer.php index 48a9ef3198bcbf86f91e7722eaeebdd7ac31027d..7ace900372e2a1004e0acfc3c31653498b811ebb 100644 --- a/classes/Importer.php +++ b/classes/Importer.php @@ -13,314 +13,322 @@ define("CNT", "http://www.w3.org/2011/content#"); define("RDFS", "http://www.w3.org/2000/01/rdf-schema#"); define("FILE", "settings.inc.php"); -class Importer { - - private $basedir; - private $external_basedir; +class Importer +{ + private $basedir; + private $external_basedir; - public function run(){ - set_time_limit(0); - error_reporting(E_ERROR); - if(is_file(FILE)){ - echo "There is an existing ".FILE." file on this installation. Please remove it before importing a new one"; - exit(0); - } - if(!isset($_GET['import']) && !isset($_POST['importtext'])){ - $this->showInterface(); - exit(0); - } - if(!is_writable('.')){ - echo 'The webserver needs write permissions in "lodspeakr/" "lodspeakr/models/" and "lodspeakr/views/" dirs to import settings.'; - exit(0); - } - - echo $this->external_basedir; - $parser = ARC2::getTurtleParser(); - - if(isset($_GET['import'])){ - $parser->parse($_GET['import']); - $this->external_basedir = str_replace('export', '', $_GET['import']); - }elseif(isset($_POST['importtext'])){ - $parser->parse(RDF, $_POST['importtext']); - }else{ - HTTPStatus::send500(); - exit(0); - } - $triples = $parser->getTriples(); - - $appArr = $this->search($triples, null, RDF.'type', LS.'Application'); - if(!(sizeof($appArr) > 0)){ - echo "I can't find an application from the URL given"; - exit(0); - } - - $app = $appArr[0]['s']; - $this->external_basedir = $app; - $compArr = $this->search($triples, null, SKOS.'broader', $app); - $content = "<?\n\$conf['debug'] = false;\n\$conf['mirror_external_uris'] = true;\n\n"; - - $this->basedir = preg_replace('/import$/', '', (!empty($_SERVER['HTTPS'])) ? "https://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'] : "http://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI']); - - //$arr = explode("lodspeakr/benegesserit", $this->basedir); - //$this->basedir = $arr[0]; - $content .= "\$conf['basedir'] = \"$this->basedir\";\n"; - $content .= "\$conf['parentApp'] = \"$app\";\n"; - $pwd = getcwd(); - $content .= "\$conf['home'] = \"$pwd/\";\n"; - - //App params - - $q = $this->search($triples, $app, LS.'usedParameter', null); - $appParams = array(); - foreach($q as $p){ - $param = $p['o']; - $labelArr = $this->search($triples, $param, RDFS.'label', null); - $label = $labelArr[0]['o']; - $format = $this->search($triples, $param, DC.'hasFormat', null); - $cntArr = $this->search($triples, $format[0]['o'], CNT.'chars', null); - $cnt = $cntArr[0]['o']; - $appParams[$label] = $cnt; - } - foreach($appParams as $k => $v){ - $content .= "\$conf['$k'] = \"$v\";\n"; - } - $content .= "/*ATTENTION: By default this application is available to + public function run() + { + set_time_limit(0); + error_reporting(E_ERROR); + if (is_file(FILE)) { + echo "There is an existing " . FILE . " file on this installation. Please remove it before importing a new one"; + exit(0); + } + if (!isset($_GET['import']) && !isset($_POST['importtext'])) { + $this->showInterface(); + exit(0); + } + if (!is_writable('.')) { + echo 'The webserver needs write permissions in "lodspeakr/" "lodspeakr/models/" and "lodspeakr/views/" dirs to import settings.'; + exit(0); + } + + echo $this->external_basedir; + $parser = ARC2::getTurtleParser(); + + if (isset($_GET['import'])) { + $parser->parse($_GET['import']); + $this->external_basedir = str_replace('export', '', $_GET['import']); + } elseif (isset($_POST['importtext'])) { + $parser->parse(RDF, $_POST['importtext']); + } else { + HTTPStatus::send500(); + exit(0); + } + $triples = $parser->getTriples(); + + $appArr = $this->search($triples, null, RDF . 'type', LS . 'Application'); + if (!(sizeof($appArr) > 0)) { + echo "I can't find an application from the URL given"; + exit(0); + } + + $app = $appArr[0]['s']; + $this->external_basedir = $app; + $compArr = $this->search($triples, null, SKOS . 'broader', $app); + $content = "<?\n\$conf['debug'] = false;\n\$conf['mirror_external_uris'] = true;\n\n"; + + $this->basedir = preg_replace( + '/import$/', + '', + (!empty($_SERVER['HTTPS'])) ? "https://" . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'] : "http://" . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'] + ); + + //$arr = explode("lodspeakr/benegesserit", $this->basedir); + //$this->basedir = $arr[0]; + $content .= "\$conf['basedir'] = \"$this->basedir\";\n"; + $content .= "\$conf['parentApp'] = \"$app\";\n"; + $pwd = getcwd(); + $content .= "\$conf['home'] = \"$pwd/\";\n"; + + //App params + + $q = $this->search($triples, $app, LS . 'usedParameter', null); + $appParams = array(); + foreach ($q as $p) { + $param = $p['o']; + $labelArr = $this->search($triples, $param, RDFS . 'label', null); + $label = $labelArr[0]['o']; + $format = $this->search($triples, $param, DC . 'hasFormat', null); + $cntArr = $this->search($triples, $format[0]['o'], CNT . 'chars', null); + $cnt = $cntArr[0]['o']; + $appParams[$label] = $cnt; + } + foreach ($appParams as $k => $v) { + $content .= "\$conf['$k'] = \"$v\";\n"; + } + $content .= "/*ATTENTION: By default this application is available to * be exported and copied (its configuration) * by others. If you do not want that, * turn the next option as false */ \$conf['export'] = true;\n\n"; - //Components - foreach($compArr as $v){ - $component = $v['s']; - $componentTypeArr = $this->search($triples, $component, RDF.'type', null); - $compType = $componentTypeArr[0]['o']; - - $params = array(); - $q = $this->search($triples, $component, LS.'usedParameter', null); - foreach($q as $p){ - $param = $p['o']; - $labelArr = $this->search($triples, $param, RDFS.'label', null); - $label = $labelArr[0]['o']; - $format = $this->search($triples, $param, DC.'hasFormat', null); - $cntArr = $this->search($triples, $format[0]['o'], CNT.'chars', null); - $cnt = $cntArr[0]['o']; - $params[$label] = $cnt; - } - - $inputs = array(); - $q = $this->search($triples, $component, LS.'usedInput', null); - foreach($q as $p){ - $param = $p['o']; - $labelArr = $this->search($triples, $param, RDFS.'label', null); - if(sizeof($labelArr)>0){ - $label = $labelArr[0]['o']; - $format = $this->search($triples, $param, DC.'hasFormat', null); - $cntArr = $this->search($triples, $format[0]['o'], CNT.'chars', null); - $cnt = $cntArr[0]['o']; - $inputs[$label] = $cnt; - } - } - if($compType == LS."LodspeakrEndpointManagerComponent"){ - $content .= $this->createEndpoints($params); - }elseif($compType == LS."LodspeakrNamespaceManagerComponent"){ - $content .= $this->createNamespaces($params); - }elseif($compType == LS."LodspeakrSparqlEndpointRetriever"){ - $this->createModels($inputs); - }elseif($compType == LS."LodspeakrStaticElementsComponent"){ - $this->createStatics($inputs); - }elseif($compType == LS."LodspeakrVisualComponent"){ - $this->createViews($inputs); - }else{ - if($conf['debug']){ - Logging::log("Component '$component' (of type $compType) not supported", E_USER_WARNING); - } - } - } - $content .= "?>\n"; - try{ - $fh = fopen(FILE, 'a'); - fwrite($fh, $content); - fclose($fh); - } catch (Exception $e) { - echo 'Caught exception while writing settings: ', $e->getMessage(), "\n"; - exit(1); - } - $this->showFinishing(); - } - - private function createEndpoints($ep){ - require('common.inc.php'); - $endpoints = ""; - try{ - foreach($ep as $k => $v){ - if($conf['endpoint'][$k] != $v){ - $endpoints .= "\$conf[\"endpoint\"][\"$k\"] = \"$v\";\n"; - } - } - $endpoints .= "\n\n"; - } catch (Exception $e) { - echo 'Caught exception while importing endpoints: ', $e->getMessage(), "\n"; - exit(1); - } - return $endpoints; - } - - private function createNamespaces($ns){ - require('namespaces.php'); - $namespaces = ""; - try{ - foreach($ns as $k => $v){ - if($conf["ns"][$k] != $v){ - if(preg_match("|^".$this->external_basedir."|", $v)){ - $newns = preg_replace("|^".$this->external_basedir."|", $this->basedir, $v); - $namespaces .= "\$conf[\"ns\"][\"".$k."_ext\"] = \"$newns\";\n"; - } - $namespaces .= "\$conf[\"ns\"][\"$k\"] = \"$v\";\n"; - } - } - $namespaces .= "\$conf[\"ns\"][\"basedir\"] = \"$this->basedir\";\n"; - $namespaces .= "\n\n"; - } catch (Exception $e) { - echo 'Caught exception while importing namespaces: ', $e->getMessage(), "\n"; - exit(1); - } - return $namespaces; - } - - private function createModels($models){ - try{ - foreach($models as $k => $v){ - $path = explode("/", $k); - for($i=0; $i<sizeof($path)-1; $i++){ - if(file_exists($path[$i])){ - if(!is_dir($path[$i])){ - unlink($path[$i]); - mkdir($path[$i]); - } - }else{ - mkdir($path[$i]); - } - chdir($path[$i]); - } - - $fh = fopen(end($path), 'w'); - fwrite($fh, $v); - fclose($fh); - for($i=0; $i<sizeof($path)-1; $i++){ - chdir('..'); - } - } - } catch (Exception $e) { - echo 'Caught exception while importing models: ', $e->getMessage(), "\n"; - exit(1); - } - } - - - private function createViews($views){ - try{ - foreach($views as $k => $v){ - $path = explode("/", $k); - for($i=0; $i<sizeof($path)-1; $i++){ - if(file_exists($path[$i])){ - if(!is_dir($path[$i])){ - unlink($path[$i]); - mkdir($path[$i]); - } - }else{ - mkdir($path[$i]); - } - chdir($path[$i]); - } - - $fh = fopen(end($path), 'w'); - fwrite($fh, $v); - fclose($fh); - for($i=0; $i<sizeof($path)-1; $i++){ - chdir('..'); - } - } - } catch (Exception $e) { - echo 'Caught exception while importing views: ', $e->getMessage(), "\n"; - exit(1); - } - } - - - private function createStatics($statics){ - try{ - foreach($statics as $k => $v){ - $path = explode("/", $k); - for($i=0; $i<sizeof($path)-1; $i++){ - if(file_exists($path[$i])){ - if(!is_dir($path[$i])){ - unlink($path[$i]); - mkdir($path[$i]); - } - }else{ - mkdir($path[$i]); - } - chdir($path[$i]); - } - - $fh = fopen(end($path), 'w'); - fwrite($fh, $v); - fclose($fh); - for($i=0; $i<sizeof($path)-1; $i++){ - chdir('..'); - } - } - } catch (Exception $e) { - echo 'Caught exception while importing statics: ', $e->getMessage(), "\n"; - exit(1); - } - } - - - private function search($graph, $s = null, $p = null, $o = null){ - $results = array(); - foreach($graph as $v){ - $threeOks = 0; - - //Check subject - if($s != null){ - if($v['s'] == $s){ - $threeOks++; - } - }else{ - $threeOks++; - } - - //Check predicate - if($p != null){ - if($v['p'] == $p){ - $threeOks++; - } - }else{ - $threeOks++; - } - - //Check object - if($o != null){ - if($v['o'] == $o){ - $threeOks++; - } - }else{ - $threeOks++; - } - - if($threeOks == 3){ - array_push($results, $v); - } - - } - return $results; - //$this->showFinishing(); - } - - private function showInterface(){ - $doc = "<html> + //Components + foreach ($compArr as $v) { + $component = $v['s']; + $componentTypeArr = $this->search($triples, $component, RDF . 'type', null); + $compType = $componentTypeArr[0]['o']; + + $params = array(); + $q = $this->search($triples, $component, LS . 'usedParameter', null); + foreach ($q as $p) { + $param = $p['o']; + $labelArr = $this->search($triples, $param, RDFS . 'label', null); + $label = $labelArr[0]['o']; + $format = $this->search($triples, $param, DC . 'hasFormat', null); + $cntArr = $this->search($triples, $format[0]['o'], CNT . 'chars', null); + $cnt = $cntArr[0]['o']; + $params[$label] = $cnt; + } + + $inputs = array(); + $q = $this->search($triples, $component, LS . 'usedInput', null); + foreach ($q as $p) { + $param = $p['o']; + $labelArr = $this->search($triples, $param, RDFS . 'label', null); + if (sizeof($labelArr) > 0) { + $label = $labelArr[0]['o']; + $format = $this->search($triples, $param, DC . 'hasFormat', null); + $cntArr = $this->search($triples, $format[0]['o'], CNT . 'chars', null); + $cnt = $cntArr[0]['o']; + $inputs[$label] = $cnt; + } + } + if ($compType == LS . "LodspeakrEndpointManagerComponent") { + $content .= $this->createEndpoints($params); + } elseif ($compType == LS . "LodspeakrNamespaceManagerComponent") { + $content .= $this->createNamespaces($params); + } elseif ($compType == LS . "LodspeakrSparqlEndpointRetriever") { + $this->createModels($inputs); + } elseif ($compType == LS . "LodspeakrStaticElementsComponent") { + $this->createStatics($inputs); + } elseif ($compType == LS . "LodspeakrVisualComponent") { + $this->createViews($inputs); + } else { + if ($conf['debug']) { + Logging::log("Component '$component' (of type $compType) not supported", E_USER_WARNING); + } + } + } + $content .= "?>\n"; + try { + $fh = fopen(FILE, 'a'); + fwrite($fh, $content); + fclose($fh); + } catch (Exception $e) { + echo 'Caught exception while writing settings: ', $e->getMessage(), "\n"; + exit(1); + } + $this->showFinishing(); + } + + private function createEndpoints($ep) + { + require('common.inc.php'); + $endpoints = ""; + try { + foreach ($ep as $k => $v) { + if ($conf['endpoint'][$k] != $v) { + $endpoints .= "\$conf[\"endpoint\"][\"$k\"] = \"$v\";\n"; + } + } + $endpoints .= "\n\n"; + } catch (Exception $e) { + echo 'Caught exception while importing endpoints: ', $e->getMessage(), "\n"; + exit(1); + } + return $endpoints; + } + + private function createNamespaces($ns) + { + require('namespaces.php'); + $namespaces = ""; + try { + foreach ($ns as $k => $v) { + if ($conf["ns"][$k] != $v) { + if (preg_match("|^" . $this->external_basedir . "|", $v)) { + $newns = preg_replace("|^" . $this->external_basedir . "|", $this->basedir, $v); + $namespaces .= "\$conf[\"ns\"][\"" . $k . "_ext\"] = \"$newns\";\n"; + } + $namespaces .= "\$conf[\"ns\"][\"$k\"] = \"$v\";\n"; + } + } + $namespaces .= "\$conf[\"ns\"][\"basedir\"] = \"$this->basedir\";\n"; + $namespaces .= "\n\n"; + } catch (Exception $e) { + echo 'Caught exception while importing namespaces: ', $e->getMessage(), "\n"; + exit(1); + } + return $namespaces; + } + + private function createModels($models) + { + try { + foreach ($models as $k => $v) { + $path = explode("/", $k); + for ($i = 0; $i < sizeof($path) - 1; $i++) { + if (file_exists($path[$i])) { + if (!is_dir($path[$i])) { + unlink($path[$i]); + mkdir($path[$i]); + } + } else { + mkdir($path[$i]); + } + chdir($path[$i]); + } + + $fh = fopen(end($path), 'w'); + fwrite($fh, $v); + fclose($fh); + for ($i = 0; $i < sizeof($path) - 1; $i++) { + chdir('..'); + } + } + } catch (Exception $e) { + echo 'Caught exception while importing models: ', $e->getMessage(), "\n"; + exit(1); + } + } + + private function createViews($views) + { + try { + foreach ($views as $k => $v) { + $path = explode("/", $k); + for ($i = 0; $i < sizeof($path) - 1; $i++) { + if (file_exists($path[$i])) { + if (!is_dir($path[$i])) { + unlink($path[$i]); + mkdir($path[$i]); + } + } else { + mkdir($path[$i]); + } + chdir($path[$i]); + } + + $fh = fopen(end($path), 'w'); + fwrite($fh, $v); + fclose($fh); + for ($i = 0; $i < sizeof($path) - 1; $i++) { + chdir('..'); + } + } + } catch (Exception $e) { + echo 'Caught exception while importing views: ', $e->getMessage(), "\n"; + exit(1); + } + } + + private function createStatics($statics) + { + try { + foreach ($statics as $k => $v) { + $path = explode("/", $k); + for ($i = 0; $i < sizeof($path) - 1; $i++) { + if (file_exists($path[$i])) { + if (!is_dir($path[$i])) { + unlink($path[$i]); + mkdir($path[$i]); + } + } else { + mkdir($path[$i]); + } + chdir($path[$i]); + } + + $fh = fopen(end($path), 'w'); + fwrite($fh, $v); + fclose($fh); + for ($i = 0; $i < sizeof($path) - 1; $i++) { + chdir('..'); + } + } + } catch (Exception $e) { + echo 'Caught exception while importing statics: ', $e->getMessage(), "\n"; + exit(1); + } + } + + private function search($graph, $s = null, $p = null, $o = null) + { + $results = array(); + foreach ($graph as $v) { + $threeOks = 0; + + //Check subject + if ($s != null) { + if ($v['s'] == $s) { + $threeOks++; + } + } else { + $threeOks++; + } + + //Check predicate + if ($p != null) { + if ($v['p'] == $p) { + $threeOks++; + } + } else { + $threeOks++; + } + + //Check object + if ($o != null) { + if ($v['o'] == $o) { + $threeOks++; + } + } else { + $threeOks++; + } + + if ($threeOks == 3) { + array_push($results, $v); + } + } + return $results; + //$this->showFinishing(); + } + + private function showInterface() + { + $doc = "<html> <head> <title>Importing options</title> </head> @@ -335,21 +343,21 @@ class Importer { </form> </body> </html>"; - echo $doc; - } - - private function showFinishing(){ - $doc = "<html> + echo $doc; + } + + private function showFinishing() + { + $doc = "<html> <head> <title>Finishing import</title> </head> <body> <h2>Import finished</h2> - Your new application is ready. Please go to the <a href='".$this->basedir."'>home page</a>. + Your new application is ready. Please go to the <a href='" . $this->basedir . "'>home page</a>. </body> </html>"; - echo $doc; - } - -} + echo $doc; + } +} diff --git a/classes/Logging.php b/classes/Logging.php index efbcc3f314d52c7264145c1ade449c5f55c0c25d..d047d45611b530098a234de3d24f994c7e0186cb 100644 --- a/classes/Logging.php +++ b/classes/Logging.php @@ -2,44 +2,44 @@ namespace uib\ub\loadspeakr; - -class Logging { - - public static function init(){ - $logs = array(); - if ($handle = opendir('cache/')) { - while (false !== ($entry = readdir($handle))) { - if (strpos($entry, ".log") == strlen($entry)-4) { - $logs[] = $entry; +class Logging +{ + public static function init() + { + $logs = array(); + if ($handle = opendir('cache/')) { + while (false !== ($entry = readdir($handle))) { + if (strpos($entry, ".log") == strlen($entry) - 4) { + $logs[] = $entry; + } + } + closedir($handle); } - } - closedir($handle); - } - sort($logs); - $alogs = ""; - $list = array(); - foreach($logs as $v){ - $newtokens = array( ".", "/"); - $oldtokens = array("___DOT___", "___SLASH___"); - $label = str_replace($oldtokens, $newtokens, $v); - $x = explode("_", $label); - $y = array_shift($x); - array_shift($x); - if(!isset($list[$y])){ - $list[$y] = array(); - } - $list[$y][] = array("name" => implode("_", $x), "url" => $v); - //$alogs .= "<p><a href='#lodspeakr/cache/$v'>$label</a></p>"; - } - krsort($list); - foreach($list as $k => $v){ - $alogs .= "<li>".date("H:i:s", $k)."<ul>\n"; - foreach($v as $w){ - $alogs .= " <li><a href='#cache/".$w['url']."'>".$w['name']."</a></li>\n"; // TSL : removed hardcoded "lodspeakr" after # - } - $alogs .="</ul></li>"; - } - echo " + sort($logs); + $alogs = ""; + $list = array(); + foreach ($logs as $v) { + $newtokens = array(".", "/"); + $oldtokens = array("___DOT___", "___SLASH___"); + $label = str_replace($oldtokens, $newtokens, $v); + $x = explode("_", $label); + $y = array_shift($x); + array_shift($x); + if (!isset($list[$y])) { + $list[$y] = array(); + } + $list[$y][] = array("name" => implode("_", $x), "url" => $v); + //$alogs .= "<p><a href='#lodspeakr/cache/$v'>$label</a></p>"; + } + krsort($list); + foreach ($list as $k => $v) { + $alogs .= "<li>" . date("H:i:s", $k) . "<ul>\n"; + foreach ($v as $w) { + $alogs .= " <li><a href='#cache/" . $w['url'] . "'>" . $w['name'] . "</a></li>\n"; // TSL : removed hardcoded "lodspeakr" after # + } + $alogs .= "</ul></li>"; + } + echo " <!DOCTYPE html> <html> <head> @@ -122,27 +122,30 @@ class Logging { </script> </body> </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){ - $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."); + public static function log($msg) + { + global $conf; + $log = array('timestamp' => time()); + $log['message'] = $msg; + if ($conf['logfile'] != null) { + 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; + } } diff --git a/classes/MetaDb.php b/classes/MetaDb.php index 97d448cc3fa8afe71a14d4ddec7a67b73293ec3c..528ac74ba325a0a4724c7896ddcab14430de1529 100644 --- a/classes/MetaDb.php +++ b/classes/MetaDb.php @@ -2,51 +2,55 @@ namespace uib\ub\loadspeakr; - use Exception; use PDO; use PDOException; -class MetaDb { - private $dbLocation; - - public function __construct($location){ - $this->dbLocation = $location; - } - - public function query($q){ +class MetaDb +{ + private $dbLocation; + + public function __construct($location) + { + $this->dbLocation = $location; + } + + public function query($q) + { global $conf; - try{ - $db = new PDO('sqlite:'.$this->dbLocation); - $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING); - - $results = array(); - foreach($db->query($q) as $entry) { - array_push($results, $entry); - } - $db = NULL; - }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"; - exit(10); - } + try { + $db = new PDO('sqlite:' . $this->dbLocation); + $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING); + + $results = array(); + foreach ($db->query($q) as $entry) { + array_push($results, $entry); + } + $db = null; + } 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"; + exit(10); + } return $results; - } - - public function write($q){ + } + + public function write($q) + { global $conf; - try{ - $db = new PDO('sqlite:'.$this->dbLocation); - $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); - $results = $db->exec($q); - $db = NULL; - }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>'"; - if($conf['debug']){ - Logging::log('Exception exec: '.$e->getMessage(), E_USER_ERROR); - } - exit(1); - } + try { + $db = new PDO('sqlite:' . $this->dbLocation); + $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); + $results = $db->exec($q); + $db = null; + } 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>'"; + if ($conf['debug']) { + Logging::log('Exception exec: ' . $e->getMessage(), E_USER_ERROR); + } + exit(1); + } return $results; - } - + } + } diff --git a/classes/Queries.php b/classes/Queries.php index ece59d1b33e807b5bd9e1a7090eebce5029d0775..4c52e09fa8fca24bd7da60d12c6b75c0cec7f133 100644 --- a/classes/Queries.php +++ b/classes/Queries.php @@ -5,9 +5,11 @@ namespace uib\ub\loadspeakr; use Exception; -class Queries { - public static function uriExist($uri, $e){ - $q = "ASK WHERE{ +class Queries +{ + public static function uriExist($uri, $e) + { + $q = "ASK WHERE{ { GRAPH ?g{ {<$uri> ?p1 []} @@ -24,15 +26,16 @@ class Queries { {[] ?p2 <$uri>} } }"; - $r = $e->query($q); - if($r['boolean'] && strtolower($r['boolean']) !== false){ - return true; - } - return false; - } - - public static function getClass($uri, $e){ - $q = "SELECT DISTINCT ?class ?inst WHERE{ + $r = $e->query($q); + if ($r['boolean'] && strtolower($r['boolean']) !== false) { + return true; + } + return false; + } + + public static function getClass($uri, $e) + { + $q = "SELECT DISTINCT ?class ?inst WHERE{ { GRAPH ?g{ { @@ -49,69 +52,67 @@ class Queries { } } }"; - try{ - $r = $e->query($q); - }catch (Exception $ex){ - echo $ex->getMessage(); - } - $result = array(); - /*if(sizeof($r['results']['bindings']) == 0){ - 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 - foreach($r['results']['bindings'] as $v){ - $result[]= $v['class']['value']; - } - return $result; - } - - - public static function getMetadata($uri, $format, $e){ - global $conf; - $q = <<<QUERY + try { + $r = $e->query($q); + } catch (Exception $ex) { + echo $ex->getMessage(); + } + $result = array(); + /*if(sizeof($r['results']['bindings']) == 0){ + 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 + foreach ($r['results']['bindings'] as $v) { + $result[] = $v['class']['value']; + } + return $result; + } + + public static function getMetadata($uri, $format, $e) + { + global $conf; + $q = <<<QUERY SELECT uri, doc, format FROM document WHERE (uri = "$uri" AND format = "$format") OR doc = "$uri" LIMIT 1 QUERY; - $r = $e->query($q); - if(sizeof($r) > 0){ - $u = $r[0]['uri']; - $p = $r[0]['doc']; - $f = $r[0]['format']; - return array($u, $p, $f); - }else{ - return NULL; - } - } - + $r = $e->query($q); + if (sizeof($r) > 0) { + $u = $r[0]['uri']; + $p = $r[0]['doc']; + $f = $r[0]['format']; + return array($u, $p, $f); + } else { + return null; + } + } + + public static function createPage($uri, $localUri, $contentType, $e) + { + global $conf; - public static function createPage($uri, $localUri, $contentType, $e){ - global $conf; - - $ext = 'html'; - $inserts = ""; - foreach($conf['http_accept'] as $extension => $f){ - $page = $localUri.$conf['extension_connector'].$extension; - foreach($f as $v){ - if($contentType == $v){ - $returnPage = $localUri.$conf['extension_connector'].$extension; - } - if($inserts != ""){ - $inserts .= "UNION "; - } - $inserts .= "SELECT '$uri', '$page', '$v' \n"; - if($v == $contentType){ - $ext = $extension; - } - } - } - $q = <<<QUERY + $ext = 'html'; + $inserts = ""; + foreach ($conf['http_accept'] as $extension => $f) { + $page = $localUri . $conf['extension_connector'] . $extension; + foreach ($f as $v) { + if ($contentType == $v) { + $returnPage = $localUri . $conf['extension_connector'] . $extension; + } + if ($inserts != "") { + $inserts .= "UNION "; + } + $inserts .= "SELECT '$uri', '$page', '$v' \n"; + if ($v == $contentType) { + $ext = $extension; + } + } + } + $q = <<<QUERY INSERT INTO document (uri, doc, format) $inserts QUERY; - $r = $e->write($q); - - return $returnPage; - } - -} + $r = $e->write($q); + return $returnPage; + } +} diff --git a/classes/Utils.php b/classes/Utils.php index 7e082224f00955c81dd70dfc265bfaeb67bd87c3..1c4d3540fa4235763ef0d2a53cd184e5845cebf6 100644 --- a/classes/Utils.php +++ b/classes/Utils.php @@ -2,820 +2,853 @@ namespace uib\ub\loadspeakr; - use ARC2; use Exception; use Haanga; use stdClass; -class Utils { - - public static function uri2curie($uri){ - global $conf; - $ns = $conf['ns']; - $curie = $uri; - - $aux = $uri; - foreach($ns as $k => $v){ - $aux = preg_replace("|^$v|", "", $uri); - if($aux != $uri){ - $uriSegments = explode("/", $aux); - $lastSegment = array_pop($uriSegments); - if(sizeof($uriSegments)>0){ - $prefix = $k."_".(implode("_", $uriSegments)); - //Adding "new" namespace - $conf['ns'][$prefix] = $v.implode("/", $uriSegments)."/"; - }else{ - $prefix = $k; - } - $curie = $prefix.":".$lastSegment; - break; - } - } - return $curie; - } - - public static function curie2uri($curie){ - global $conf; - $ns = $conf['ns']; - $parts = explode(':', $curie); - //Avoid if we have a namespace prefix called 'http' - if(preg_match('|^//|', $parts[1])){ - return $curie; - } - if(sizeof($parts)>1 ){ - if(!isset($ns[$parts[0]])){ - $prefixSegments = explode("_", $parts[0]); - $realPrefix = array_shift($prefixSegments); - $conf['ns'][$parts[0]] = $ns[$realPrefix].join("/", $prefixSegments); - return $ns[$realPrefix].join("/", $prefixSegments)."/".$parts[1]; - }else{ - return $ns[$parts[0]].$parts[1]; - } - }else{ - return $curie; - } - } - - public static function getPrefix($curie){ - global $conf; - $ns = $conf['ns']; - $parts = explode(':', $curie); - //Avoid if we have a namespace prefix called 'http' - if(preg_match('|^//|', $parts[1])){ - return $curie; - } - return array('ns' => $ns[$parts[0]], 'prefix' => $parts[0]); - } - - public static function getTemplate($uri){ - $filename = str_replace(":", "_", $uri); - if(file_exists ($filename)){ - include_once($filename); - } - } - - private static function sparqlResult2Obj($data){ - global $conf; - $obj = array(); - if(!isset($data['results'])){ - foreach($data as $k => $v){ - $obj[$k] = Utils::sparqlResult2Obj($v); - } - }else{ - $aux = $data['results']['bindings']; - if(sizeof($aux)>0){ - foreach($aux as $w){ - $row = array(); - foreach($w as $k => $v){ - - $row[$k]['value'] = $v['value']; - if($v['type'] == 'uri'){ - $row[$k]['curie'] = Utils::uri2curie($v['value']); - $exploded = explode(":",$row[$k]['curie']); - $row[$k]['localname'] = array_pop($exploded); - $row[$k]['uri'] = 1; - }elseif($v['type'] == 'bnode'){ - $row[$k]['curie'] = 'blankNode'; - $row[$k]['blank'] = 1; - }else{ - $row[$k]['literal'] = 1; - $row[$k]['curie'] = $v['value']; - if(isset($v['datatype'])){ - $row[$k]['type'] = $v['datatype']; - } - if(isset($v['xml:lang'])){ - $row[$k]['lang'] = $v['xml:lang']; - } - - } - } - /*if(sizeof($aux) == 1){ - $obj = $row; - }*/ - if(sizeof($row) >0){ - array_push($obj, $row); - } - - } - } - } - return $obj; - } - - - - public static function getExtension($accept_string){ - global $conf; - $extension = "html"; - foreach($conf['http_accept'] as $ext => $accept_arr){ - if(in_array($accept_string, $accept_arr)){ - $extension = $ext; - } - } - return $extension; - } - - public static function getBestContentType($accept_string){ - global $conf; - $a = explode(",", $accept_string); - $b = array(); - foreach($a as $v){ - foreach($conf['http_accept'] as $formatTypeArray){ - if(strstr($v, ";")){ - $aux = explode(";", $v); - $aux[0] = trim($aux[0]); - if(in_array($aux[0], $formatTypeArray)){ - $b[$aux[0]] = floatval(trim(str_replace("q=","",$aux[1]))); - } - }else{ - $value = trim($v); - if(in_array($value, $formatTypeArray)){ - $b[$value] = 1.0; - } - } - } - } - $a = $b; - arsort($a); - $ct = 'text/html'; - foreach($a as $k => $v){ - $ct = $k; - break; - } - if($ct == NULL || $ct == "" || $ct == "*/*"){ - $ct = 'text/html'; - } - return $ct; - } - - - private static function travelTree($tree){ - $results = array(); - if(is_string($tree)){ - return $tree; - } - foreach($tree as $t){ - $aux = Utils::travelTree($t); - if(is_array($aux)){ - $results = array_merge($results, $aux); - }else{ - array_push($results, $aux); - } - } - return $results; - } - - - public static function serializeRdf($data, $extension='rdf'){ - global $conf; - global $lodspk; - $ser; - $dPointer; - $docs = Utils::travelTree($data); - $parser = ARC2::getRDFParser(); - $triples = array(); - - foreach($docs as $d){ - $parser->parse($conf['basedir'], $d); - $t = $parser->getTriples(); - $triples = array_merge($triples, $t); - } - if($lodspk['mirror_external_uris']){ - global $uri; - global $localUri; - $t = array(); - $t['s'] = $localUri; - $t['s_type'] = 'uri'; - $t['p'] = "http://www.w3.org/2002/07/owl#sameAs"; - $t['o'] = $uri; - $t['o_type'] = 'uri'; - array_push($triples, $t); - $t['p'] = "http://www.w3.org/2000/10/swap/pim/contact#preferredURI"; - array_push($triples, $t); - } - switch ($extension){ - case 'ttl': - $ser = ARC2::getTurtleSerializer(); - break; - case 'nt': - $ser = ARC2::getNTriplesSerializer(); - break; - case 'json': - $ser = ARC2::getRDFJSONSerializer(); - break; - case 'jsonp': - $ser = ARC2::getRDFJSONSerializer(); - break; - case 'rdf': - $ser = ARC2::getRDFXMLSerializer(); - break; - case 'html': - return array("content" => $triples, "serialized" => false); - break; - default: - $ser = null; - } - if($ser != null){ - $doc = $ser->getSerializedTriples($triples); - }else{ - $doc = var_export($data, true); - } - return array("content" => $doc, "serialized" => true); - } - - public static function processDocument($viewFile, $lodspk, $data){ - global $conf; - global $lodspk; - $contentType = $lodspk['contentType']; - $extension = Utils::getExtension($contentType); - - header('Content-Type: '.$contentType); - if(isset($lodspk['resultRdf']) && $lodspk['resultRdf'] == true){ - $rdfData = Utils::serializeRdf($data, $extension); - if($rdfData["serialized"]){ - echo $rdfData["content"]; - }else{ - $data['rdf'] = new stdClass(); - - $subjectCounter = 0; - $sIndex = array(); - $sCounter = array(); - $spCounter = array(); - foreach($rdfData["content"] as $t){ - //SUBJECT - if($t['s_type'] == 'uri'){ - $subject = $t['s']; - $subjectCurie = Utils::uri2curie($subject); - $subjectMethod = str_replace(":", "__", $subjectCurie); - }else{ - if(isset($sIndex[$t['s']])){ - $subject = $sIndex[$t['s']]; - $subjectCurie = $sIndex[$t['s']]; - $subjectMethod = $sIndex[$t['s']]; - }else{ - $subject = "_bnode".$subjectCounter; - $subjectCurie = "_bnode".$subjectCounter; - $subjectMethod = "_bnode".$subjectCounter; - $sIndex[$t['s']] = "_bnode".$subjectCounter++; - } - } - if(!isset($data['rdf']->subjects)){ - $data['rdf']->subjects = new stdClass(); - } - - if(!isset($data['rdf']->$subjectMethod)){ - $data['rdf']->$subjectMethod = new stdClass(); - $data['rdf']->$subjectMethod->predicates = new stdClass(); - } - $data['rdf']->$subjectMethod->mirroredUri = $subject; - $data['rdf']->$subjectMethod->mirroredCurie = $subjectCurie; - - $data['rdf']->$subjectMethod->value = Utils::getUnMirroredUri($subject); - $data['rdf']->$subjectMethod->curie = Utils::uri2curie( $data['rdf']->$subjectMethod->value); - - if(!isset($data['rdf']->subjects->$subjectMethod)){ - $data['rdf']->subjects->$subjectMethod = $data['rdf']->$subjectMethod; - } - - - - - //PREDICATE - $predicate = $t['p']; - $predicateCurie = Utils::uri2curie($predicate); - $predicateMethod = str_replace(":", "__", $predicateCurie); - if(!isset($data['rdf']->$subjectMethod->$predicateMethod)){ - $data['rdf']->$subjectMethod->$predicateMethod = new stdClass(); - } - - - $data['rdf']->$subjectMethod->$predicateMethod->mirroredUri = $predicate; - $data['rdf']->$subjectMethod->$predicateMethod->mirroredCurie = $predicateCurie; - $data['rdf']->$subjectMethod->$predicateMethod->value = Utils::getUnMirroredUri($predicate); - $data['rdf']->$subjectMethod->$predicateMethod->curie = Utils::uri2curie( $data['rdf']->$subjectMethod->$predicateMethod->value); - - - if(!isset($data['rdf']->$subjectMethod->predicates)){ - $data['rdf']->$subjectMethod->predicates = new stdClass(); - } - if(!isset($sCounter[$subjectMethod])){ - $sCounter[$subjectMethod] = 0; - } - $sCount = $sCounter[$subjectMethod]++; - $data['rdf']->$subjectMethod->predicates->$sCount = $data['rdf']->$subjectMethod->$predicateMethod; - - - //OBJECT - if($t['o_type'] == 'uri'){ - $object = $t['o']; - $objectCurie = Utils::uri2curie($object); - }elseif($t['o_type'] == 'literal'){ - $object = $t['o']; - $objectCurie = $object; - }else{ - if(isset($sIndex[$t['o']])){ - $object = $sIndex[$t['o']]; - $objectCurie = $sIndex[$t['o']]; - }else{ - $object = "_bnode".$objectCounter; - $objectCurie = "_bnode".$objectCounter; - $sIndex[$t['s']] = "_bnode".$objectCounter++; - } - } - - - $obj = new stdClass(); - $obj->mirroredUri = $object; - $obj->mirroredCurie = $objectCurie; - $obj->value = Utils::getUnMirroredUri($object); - $obj->curie = Utils::uri2curie($obj->value); - - - if(!isset($spCounter[$subjectMethod." ".$predicateMethod])){ - $spCounter[$subjectMethod." ".$predicateMethod] = 0; - } - $sCount = $spCounter[$subjectMethod." ".$predicateMethod]++; - $data['rdf']->$subjectMethod->$predicateMethod->objects->$sCount = $obj; - } - Utils::showView($lodspk, $data, $viewFile); - } - }else{ - Utils::showView($lodspk, $data, $viewFile); - } - } - - public static function getResultsType($query){ - global $conf; - global $uri; - if(preg_match("/select/i", $query)){ - return $conf['output']['select']; - }elseif(preg_match("/describe/i", $query)){ - return $conf['output']['describe']; - }elseif(preg_match("/construct/i", $query)){ - return $conf['output']['describe']; - }elseif(preg_match("/ask/i", $query)){ - return $conf['output']['ask']; - }else{ - HTTPStatus::send500($uri); - } - } - - public static function queryDir($modelDir, &$r, &$f){ - global $conf; - global $uri; - global $lodspk; - global $endpoints; - global $results; - $strippedModelDir = str_replace('endpoint.', '', $modelDir); - $lodspk['model'] = $modelDir; - $originalDir = getcwd(); - $subDirs= array(); - if($conf['debug']){ - Logging::log("Entering $strippedModelDir from ".getcwd(), E_USER_NOTICE); - } - chdir($modelDir); - $handle = opendir('.'); - - while (false !== ($modelFile = readdir($handle))) { - if($modelFile != "." && $modelFile != ".." && strpos($modelFile, ".") !== 0){ - if(is_dir($modelFile)){ - if(strpos('endpoint.', $modelFile) == 0){ - if($conf['debug']){ - Logging::log("Save $modelFile for later, after all the queries in the current directory has been resolved", E_USER_NOTICE); - } - $subDirs[]=$modelFile; - } - }else{ - if(preg_match('/\.query$/', $modelFile)){ - $e = null; - if(!isset($endpoints[$strippedModelDir])){ - if($conf['debug']){ - Logging::log("Creating endpoint for $strippedModelDir", E_USER_NOTICE); - } - if(!isset($conf['endpoint'][$strippedModelDir])){ - if($conf['debug']){ - Logging::log("Couldn't find $strippedModelDir as a list of available endpoints. Will continue using 'local'", E_USER_WARNING); - } - $e = $endpoints['local']; - }else{ - $endpoints[$strippedModelDir] = new Endpoint($conf['endpoint'][$strippedModelDir], $conf['endpoint']['config']); - $e = $endpoints[$strippedModelDir]; - } - }else{ - $e = $endpoints[$strippedModelDir]; - } - if($modelDir != $lodspk['type']){ - if(!isset($r[$strippedModelDir]) ){ - $r[$strippedModelDir] = array(); - $f[$strippedModelDir] = array(); - } - Utils::queryFile($modelFile, $e, $r[$strippedModelDir], $f); - }else{ - Utils::queryFile($modelFile, $e, $r, $f); - } - } - } - } - } - closedir($handle); - $originalDir = $lodspk['model']; - if(isset($subDirs)){ - foreach($subDirs as $v){ - if(!isset($r[$modelDir])){ - $r[$modelDir] = array(); - } - if($modelDir != $lodspk['type']){ - Utils::queryDir($v, $r[$strippedModelDir], $f[$strippedModelDir]); - }else{ - Utils::queryDir($v, $r, $f); - } - } - } - // chdir($conf['home']); - //return $data; - } - - - public static function queryFile($modelFile, $e, &$rPointer, &$fPointer){ - global $conf; - global $lodspk; - global $results; - global $firstResults; - global $uri; - $data = array(); - $strippedModelFile = str_replace('endpoint.', '', str_replace('.query', '',$modelFile)); - if(!is_dir($modelFile)){ - require_once($conf['home'].'lib/Haanga/lib/Haanga.php'); - Haanga::configure(array( - 'cache_dir' => $conf['home'].'cache/', - 'autoescape' => FALSE, - )); - - //Haanga supports the dot (.) convention only for objects - if(is_array($lodspk) && !empty($lodspk)){ - $lodspkObj = Convert::array_to_object($lodspk); - $lodspk = $lodspkObj; - } - $r2 = Convert::array_copy($results); - $models = Convert::array_to_object($r2); - $f2 = Convert::array_copy($firstResults); - $first = Convert::array_to_object($f2); - $vars = compact('uri', 'lodspk', 'conf', 'models', 'first'); - $q = file_get_contents($modelFile); - if($q == false){ - HTTPStatus::send500("I can't load ".$modelFile." in ".getcwd()); - } - $fnc = Haanga::compile($q); - $query = $fnc($vars, TRUE); - - if(is_object($lodspk)){ - $lodspkObj = Convert::object_to_array($lodspk); - $lodspk = $lodspkObj; - } - $query = Utils::addPrefixes($query); - if(!empty($lodspk['transform_select_query']) && $lodspk['transform_select_query']==true){ - $parser = ARC2::getSPARQLParser(); - $parser->parse($query); - $sparqlConstruct = array(); - if (!$parser->getErrors()) { - $resultVars = array(); - $q_infos = $parser->getQueryInfos(); - foreach($q_infos['query']['result_vars'] as $v){ - if($v['type'] == 'var'){ - $resultVars[$v['value']] = 1; - } - }; - $x = Utils::extractObj($q_infos['query']['pattern']); - foreach($x as $v){ - if(($resultVars[$v['s']] && $v['s_type'] == 'var') - || ($resultVars[$v['p']] && $v['p_type'] == 'var') - || ($resultVars[$v['o']] && $v['o_type'] == 'var')){ - array_push($sparqlConstruct, $v); - } - } - $construct = ""; - foreach($sparqlConstruct as $v){ - if($v['s_type'] == 'uri'){ - $construct .= "<".$v['s']."> "; - }elseif($v['s_type'] == 'var'){ - $construct .= '?'.$v['s'].' '; - }else{ - $construct.= $v['s']." "; - } - - if($v['p_type'] == 'uri'){ - $construct .= "<".$v['p']."> "; - }elseif($v['p_type'] == 'var'){ - $construct .= '?'.$v['p'].' '; - }else{ - $construct.= $v['p']." "; - } - - if($v['o_type'] == 'uri'){ - $construct .= "<".$v['o']."> "; - }elseif($v['o_type'] == 'literal'){ - $construct .= '"'.$v['o'].'" '; - }elseif($v['o_type'] == 'var'){ - $construct .= '?'.$v['o'].' '; - }else{ - $construct.= $v['o']." "; - } - - $construct .= ".\n"; - } - if($construct == ""){ - if(sizeof($q_infos['query']['result_vars'])>0){ - //For now, assuming variables are in the GRAPH ?g - $query = "CONSTRUCT {?g ?x ?y} WHERE{GRAPH ?g{?g ?x ?y}}"; - }else{ - if(!preg_match('/construct/i', $query)){ - HTTPStatus::send500(); - } - } - }else{ - $query = preg_replace('/select\s*[^{]*\s*(where)?\s*{/i', 'CONSTRUCT {'.$construct.'} WHERE{', $query); - } - }else { - return; - //HTTPStatus::send500("invalid query: " . var_export($parser->getErrors(), true)."\n\nQUERY:\n".$query); - } - } - if($conf['debug']){ - Logging::log($modelFile." against ".$e->getSparqlUrl()); - Logging::log($query); - Logging::log("Running query from ".$modelFile." on endpoint ".$e->getSparqlURL(), E_USER_NOTICE); - } - $initTime = microtime(true); - $aux = $e->query($query, Utils::getResultsType($query)); - $endTime = microtime(true); - if($conf['debug']){ - Logging::log("Execution time: ".($endTime - $initTime)." seconds"); - } - $timeObj = new stdClass(); - $timeObj->query = new stdClass(); - $timeObj->query->value = $strippedModelFile; - $timeObj->time = new stdClass(); - $timeObj->time->value = ($endTime - $initTime); - $lodspk['queryTimes'][$strippedModelFile] = $timeObj; - if($modelFile != $lodspk['type']){ - if(!isset($rPointer[$strippedModelFile])){ - $rPointer[$strippedModelFile] = array(); - $firstResults[$strippedModelFile] = array(); - } - if(Utils::getResultsType($query) == $conf['output']['select']){ - $rPointer[$strippedModelFile] = Utils::sparqlResult2Obj($aux); - if (!empty($rPointer[$strippedModelFile][0])) { - $fPointer[$strippedModelFile] = $rPointer[$strippedModelFile][0]; +class Utils +{ + public static function uri2curie($uri) + { + global $conf; + $ns = $conf['ns']; + $curie = $uri; + + $aux = $uri; + foreach ($ns as $k => $v) { + $aux = preg_replace("|^$v|", "", $uri); + if ($aux != $uri) { + $uriSegments = explode("/", $aux); + $lastSegment = array_pop($uriSegments); + if (sizeof($uriSegments) > 0) { + $prefix = $k . "_" . (implode("_", $uriSegments)); + //Adding "new" namespace + $conf['ns'][$prefix] = $v . implode("/", $uriSegments) . "/"; + } else { + $prefix = $k; + } + $curie = $prefix . ":" . $lastSegment; + break; + } + } + return $curie; + } + + public static function curie2uri($curie) + { + global $conf; + $ns = $conf['ns']; + $parts = explode(':', $curie); + //Avoid if we have a namespace prefix called 'http' + if (preg_match('|^//|', $parts[1])) { + return $curie; + } + if (sizeof($parts) > 1) { + if (!isset($ns[$parts[0]])) { + $prefixSegments = explode("_", $parts[0]); + $realPrefix = array_shift($prefixSegments); + $conf['ns'][$parts[0]] = $ns[$realPrefix] . join("/", $prefixSegments); + return $ns[$realPrefix] . join("/", $prefixSegments) . "/" . $parts[1]; + } else { + return $ns[$parts[0]] . $parts[1]; + } + } else { + return $curie; + } + } + + public static function getPrefix($curie) + { + global $conf; + $ns = $conf['ns']; + $parts = explode(':', $curie); + //Avoid if we have a namespace prefix called 'http' + if (preg_match('|^//|', $parts[1])) { + return $curie; + } + return array('ns' => $ns[$parts[0]], 'prefix' => $parts[0]); + } + + public static function getTemplate($uri) + { + $filename = str_replace(":", "_", $uri); + if (file_exists($filename)) { + include_once($filename); + } + } + + private static function sparqlResult2Obj($data) + { + global $conf; + $obj = array(); + if (!isset($data['results'])) { + foreach ($data as $k => $v) { + $obj[$k] = Utils::sparqlResult2Obj($v); + } + } else { + $aux = $data['results']['bindings']; + if (sizeof($aux) > 0) { + foreach ($aux as $w) { + $row = array(); + foreach ($w as $k => $v) { + $row[$k]['value'] = $v['value']; + if ($v['type'] == 'uri') { + $row[$k]['curie'] = Utils::uri2curie($v['value']); + $exploded = explode(":", $row[$k]['curie']); + $row[$k]['localname'] = array_pop($exploded); + $row[$k]['uri'] = 1; + } elseif ($v['type'] == 'bnode') { + $row[$k]['curie'] = 'blankNode'; + $row[$k]['blank'] = 1; + } else { + $row[$k]['literal'] = 1; + $row[$k]['curie'] = $v['value']; + if (isset($v['datatype'])) { + $row[$k]['type'] = $v['datatype']; + } + if (isset($v['xml:lang'])) { + $row[$k]['lang'] = $v['xml:lang']; + } + } + } + /*if(sizeof($aux) == 1){ + $obj = $row; + }*/ + if (sizeof($row) > 0) { + array_push($obj, $row); } - }else{ - $lodspk['resultRdf'] = true; - $rPointer[$strippedModelFile] = $aux; - } - }else{ - if(Utils::getResultsType($query) == $conf['output']['select']){ - $rPointer = Utils::sparqlResult2Obj($aux); - $fPointer[$strippedModelFile] = $rPointer[0]; - }else{ - $lodspk['resultRdf'] = true; - $rPointer = $aux; - } - } - }else{ - if(strpos('endpoint.', $modelFile) == 0){ - if($conf['debug']){ - Logging::log("$modelFile is a directory, will process it later", E_USER_NOTICE); - } - if($modelFile != $lodspk['type']){ - if(!isset($rPointer[$strippedModelFile])){ - $rPointer[$strippedModelFile] = array(); - } - Utils::queryDir($modelFile, $rPointer[$strippedModelFile], $fPointer[$strippedModelFile]); - }else{ - Utils::queryDir($modelFile, $rPointer, $fPointer); - } - } - } - } - - public static function internalize($array){ - global $conf; - $firstResultsKeyAppearance = true; - foreach($array as $key => $value){ - if(!isset($value['value'])){ - $array[$key] = Utils::internalize($value); - /*if($firstResultsKeyAppearance){ - $firstResultsKeyAppearance = false; - $array['_firstResults']=$array[$key]; - }*/ - }else{ - if(isset($value['uri']) && $value['uri'] == 1){ - //If there is no mirroring, it wouldn't hurt to have available this value (e.g., using templates from a mirrored instance to a non-mirrored one) - $value['mirroredUri'] = $value['value']; - $value['mirroredCurie'] = Utils::uri2curie($value['value']); - if(isset($conf['mirror_external_uris']) && $conf['mirror_external_uris'] != false){ - $value['value'] = Utils::getUnMirroredUri($value['value']); - } - $value['curie'] = Utils::uri2curie($value['value']); - $array[$key] = $value; - } - } - } - return $array; - } - - public static function getfirstResults($array){ - global $conf; - $firstResultsKeyAppearance = true; - if (is_iterable($array)){ - foreach($array as $key => $value){ - if(!isset($value['value'])){ - $aux = Utils::getfirstResults($value); - if(isset($aux['0'])){ - $array[$key] = $aux['0']; - }else{ - $array[$key] = $aux; - } - } - } + } + } + } + return $obj; } - return $array; - } - - - public static function showView($lodspkData, $data, $view){ - global $conf; - global $uri; - global $lodspk; - global $extension; - //$lodspk = $conf['view']['standard']; - $lodspk = $lodspkData; - if(isset($lodspkData['params'])){ - $lodspk['this']['params'] = $lodspkData['params']; - } - if(isset($lodspk['queryTimes'])){ - $lodspk['queryTimes'] = Convert::array_to_object($lodspk['queryTimes']); - } - require_once($conf['home'].'lib/Haanga/lib/Haanga.php'); - $viewAux = explode("/",$view); - $viewFile = array_pop($viewAux); - //$viewFile = $view; - $viewPath = join("/", $viewAux); - Haanga::configure(array( - 'template_dir' => $viewPath, - 'cache_dir' => $conf['home'].'cache/', - )); - $rdf = null; - if(array_key_exists('rdf', $data)){ - $rdf = $data['rdf']; - unset($data['rdf']); - }else{ - } - $models = $data; - Convert::getPaths($models, ""); - $first = $lodspk['firstResults']; - unset($lodspk['firstResults']); - //unset($lodspk); - $vars = compact('uri','lodspk', 'conf', 'models', 'rdf', 'first'); - if($conf['debug']){ - //Logging::log(var_export($vars, true)); - } - if(is_string($data)){ - echo($data); - }elseif(is_file($view)){ - try{ - Haanga::Load($viewFile, $vars); - }catch(Exception $e){ - echo '<pre>'; - echo($e->getMessage()."' in ".$e->getFile().":".$e->getLine()."\nStack trace:\n".$e->getTraceAsString()); - echo '</pre>'; - } - }elseif($view == null){ - $fnc = Haanga::compile('{{models|safe}}'); - $fnc($vars, TRUE); - }else{ - echo $conf['home'].$viewPath." ".$viewFile; - $fnc = Haanga::compile($view); - $fnc($vars, TRUE); - } - - } - - private static function extractObj($obj, $term = 'triple'){ - $triples = array(); - if(is_array($obj)){ - foreach($obj as $k => $v){ - if($v['type'] != 'triple'){ - $aux = Utils::extractObj($v); - if($aux['type'] != 'triple'){ - $triples = array_merge($triples,$aux); - }else{ - $triples = array_merge($triples, $aux); - } - }else{ - array_push($triples, $v); - } - } - } - return $triples; - } - - public static function addPrefixes($q){ - global $conf; - $matches = array(); - $visited = array(); - $newQuery = $q; - if(preg_match_all("|\s(\w+):\w+|", $q, $matches) > 0){ - foreach($matches[1] as $v){ - if(!isset($visited[$v]) && isset($conf['ns'][$v])){ - $newQuery = "PREFIX ".$v.": <".$conf['ns'][$v].">\n".$newQuery; - $visited[$v] = true; - } - } + + public static function getExtension($accept_string) + { + global $conf; + $extension = "html"; + foreach ($conf['http_accept'] as $ext => $accept_arr) { + if (in_array($accept_string, $accept_arr)) { + $extension = $ext; + } + } + return $extension; } - - return $newQuery; - } - - public static function filterTriples($triples, $pattern){ - //Simples match/filter function possible - $result = array(); - foreach($triples as $t){ - if( (($pattern[0] != null && $pattern[0] == $t['s']) || $pattern[0] == null) && - (($pattern[1] != null && $pattern[1] == $t['p']) || $pattern[1] == null) && - (($pattern[2] != null && $pattern[2] == $t['o']) || $pattern[2] == null) ){ - $result[] = array($t['s'], $t['p'], $t['o']); - } + + public static function getBestContentType($accept_string) + { + global $conf; + $a = explode(",", $accept_string); + $b = array(); + foreach ($a as $v) { + foreach ($conf['http_accept'] as $formatTypeArray) { + if (strstr($v, ";")) { + $aux = explode(";", $v); + $aux[0] = trim($aux[0]); + if (in_array($aux[0], $formatTypeArray)) { + $b[$aux[0]] = floatval(trim(str_replace("q=", "", $aux[1]))); + } + } else { + $value = trim($v); + if (in_array($value, $formatTypeArray)) { + $b[$value] = 1.0; + } + } + } + } + $a = $b; + arsort($a); + $ct = 'text/html'; + foreach ($a as $k => $v) { + $ct = $k; + break; + } + if ($ct == null || $ct == "" || $ct == "*/*") { + $ct = 'text/html'; + } + return $ct; } - return $result; - } - - public static function getMirroredUri($localUri){ - global $conf; - $uri = $localUri; - if(isset($conf['mirror_external_uris']) && $conf['mirror_external_uris'] != false){ - if(is_bool($conf['mirror_external_uris'])){ - $uri = preg_replace("|^".$conf['basedir']."|", $conf['ns']['base'], $localUri); - }elseif(is_string($conf['mirror_external_uris'])){ - $uri = preg_replace("|^".$conf['basedir']."|", $conf['mirror_external_uris'], $localUri); - }elseif(is_array($conf['mirror_external_uris'])){ - $defaultKey = ""; //Default namespace is empty string "" - $namespaceFragment = array_shift(split("/", str_replace($conf['basedir'], "", $localUri))); - $uri = preg_replace("|^".$conf['basedir']."|",$conf['mirror_external_uris'][$defaultKey], $localUri); - foreach($conf['mirror_external_uris'] as $k => $v){ - if($namespaceFragment == $k){ - $uri = preg_replace("|^".$conf['basedir'].$k."/"."|",$conf['mirror_external_uris'][$k], $localUri); - break; - } - } - }else{ - HTTPStatus::send500("Error in mirroring configuration"); - exit(1); - } + + private static function travelTree($tree) + { + $results = array(); + if (is_string($tree)) { + return $tree; + } + foreach ($tree as $t) { + $aux = Utils::travelTree($t); + if (is_array($aux)) { + $results = array_merge($results, $aux); + } else { + array_push($results, $aux); + } + } + return $results; } - return $uri; - } - - public static function getUnMirroredUri($uri){ - global $conf; - $localUri = $uri; - if(is_bool($conf['mirror_external_uris'])){ - $localUri = preg_replace("|^".$conf['ns']['local']."|", $conf['basedir'], $uri); - }elseif(is_string($conf['mirror_external_uris'])){ - $localUri = preg_replace("|^".$conf['mirror_external_uris']."|", $conf['basedir'], $uri); - }elseif(is_array($conf['mirror_external_uris'])){ - //Instead of doing expensive regex, jsut use str_replace - foreach($conf['mirror_external_uris'] as $k => $v){ - if(strlen(str_replace($v, "", $uri)) != strlen($uri)){ - $fragment = ($k == "")?$k: $k."/"; - $localUri = preg_replace("|^".$v."|",$conf['basedir'].$fragment, $uri); - break; - } - } - }else{ - HTTPStatus::send500("Error in mirroring configuration"); - exit(1); + + public static function serializeRdf($data, $extension = 'rdf') + { + global $conf; + global $lodspk; + $ser; + $dPointer; + $docs = Utils::travelTree($data); + $parser = ARC2::getRDFParser(); + $triples = array(); + + foreach ($docs as $d) { + $parser->parse($conf['basedir'], $d); + $t = $parser->getTriples(); + $triples = array_merge($triples, $t); + } + if ($lodspk['mirror_external_uris']) { + global $uri; + global $localUri; + $t = array(); + $t['s'] = $localUri; + $t['s_type'] = 'uri'; + $t['p'] = "http://www.w3.org/2002/07/owl#sameAs"; + $t['o'] = $uri; + $t['o_type'] = 'uri'; + array_push($triples, $t); + $t['p'] = "http://www.w3.org/2000/10/swap/pim/contact#preferredURI"; + array_push($triples, $t); + } + switch ($extension) { + case 'ttl': + $ser = ARC2::getTurtleSerializer(); + break; + case 'nt': + $ser = ARC2::getNTriplesSerializer(); + break; + case 'json': + $ser = ARC2::getRDFJSONSerializer(); + break; + case 'jsonp': + $ser = ARC2::getRDFJSONSerializer(); + break; + case 'rdf': + $ser = ARC2::getRDFXMLSerializer(); + break; + case 'html': + return array("content" => $triples, "serialized" => false); + break; + default: + $ser = null; + } + if ($ser != null) { + $doc = $ser->getSerializedTriples($triples); + } else { + $doc = var_export($data, true); + } + return array("content" => $doc, "serialized" => true); } - return $localUri; - } + + public static function processDocument($viewFile, $lodspk, $data) + { + global $conf; + global $lodspk; + $contentType = $lodspk['contentType']; + $extension = Utils::getExtension($contentType); + + header('Content-Type: ' . $contentType); + if (isset($lodspk['resultRdf']) && $lodspk['resultRdf'] == true) { + $rdfData = Utils::serializeRdf($data, $extension); + if ($rdfData["serialized"]) { + echo $rdfData["content"]; + } else { + $data['rdf'] = new stdClass(); + + $subjectCounter = 0; + $sIndex = array(); + $sCounter = array(); + $spCounter = array(); + foreach ($rdfData["content"] as $t) { + //SUBJECT + if ($t['s_type'] == 'uri') { + $subject = $t['s']; + $subjectCurie = Utils::uri2curie($subject); + $subjectMethod = str_replace(":", "__", $subjectCurie); + } else { + if (isset($sIndex[$t['s']])) { + $subject = $sIndex[$t['s']]; + $subjectCurie = $sIndex[$t['s']]; + $subjectMethod = $sIndex[$t['s']]; + } else { + $subject = "_bnode" . $subjectCounter; + $subjectCurie = "_bnode" . $subjectCounter; + $subjectMethod = "_bnode" . $subjectCounter; + $sIndex[$t['s']] = "_bnode" . $subjectCounter++; + } + } + if (!isset($data['rdf']->subjects)) { + $data['rdf']->subjects = new stdClass(); + } + + if (!isset($data['rdf']->$subjectMethod)) { + $data['rdf']->$subjectMethod = new stdClass(); + $data['rdf']->$subjectMethod->predicates = new stdClass(); + } + $data['rdf']->$subjectMethod->mirroredUri = $subject; + $data['rdf']->$subjectMethod->mirroredCurie = $subjectCurie; + + $data['rdf']->$subjectMethod->value = Utils::getUnMirroredUri($subject); + $data['rdf']->$subjectMethod->curie = Utils::uri2curie($data['rdf']->$subjectMethod->value); + + if (!isset($data['rdf']->subjects->$subjectMethod)) { + $data['rdf']->subjects->$subjectMethod = $data['rdf']->$subjectMethod; + } + + + //PREDICATE + $predicate = $t['p']; + $predicateCurie = Utils::uri2curie($predicate); + $predicateMethod = str_replace(":", "__", $predicateCurie); + if (!isset($data['rdf']->$subjectMethod->$predicateMethod)) { + $data['rdf']->$subjectMethod->$predicateMethod = new stdClass(); + } + + + $data['rdf']->$subjectMethod->$predicateMethod->mirroredUri = $predicate; + $data['rdf']->$subjectMethod->$predicateMethod->mirroredCurie = $predicateCurie; + $data['rdf']->$subjectMethod->$predicateMethod->value = Utils::getUnMirroredUri($predicate); + $data['rdf']->$subjectMethod->$predicateMethod->curie = Utils::uri2curie( + $data['rdf']->$subjectMethod->$predicateMethod->value + ); + + + if (!isset($data['rdf']->$subjectMethod->predicates)) { + $data['rdf']->$subjectMethod->predicates = new stdClass(); + } + if (!isset($sCounter[$subjectMethod])) { + $sCounter[$subjectMethod] = 0; + } + $sCount = $sCounter[$subjectMethod]++; + $data['rdf']->$subjectMethod->predicates->$sCount = $data['rdf']->$subjectMethod->$predicateMethod; + + + //OBJECT + if ($t['o_type'] == 'uri') { + $object = $t['o']; + $objectCurie = Utils::uri2curie($object); + } elseif ($t['o_type'] == 'literal') { + $object = $t['o']; + $objectCurie = $object; + } else { + if (isset($sIndex[$t['o']])) { + $object = $sIndex[$t['o']]; + $objectCurie = $sIndex[$t['o']]; + } else { + $object = "_bnode" . $objectCounter; + $objectCurie = "_bnode" . $objectCounter; + $sIndex[$t['s']] = "_bnode" . $objectCounter++; + } + } + + + $obj = new stdClass(); + $obj->mirroredUri = $object; + $obj->mirroredCurie = $objectCurie; + $obj->value = Utils::getUnMirroredUri($object); + $obj->curie = Utils::uri2curie($obj->value); + + + if (!isset($spCounter[$subjectMethod . " " . $predicateMethod])) { + $spCounter[$subjectMethod . " " . $predicateMethod] = 0; + } + $sCount = $spCounter[$subjectMethod . " " . $predicateMethod]++; + $data['rdf']->$subjectMethod->$predicateMethod->objects->$sCount = $obj; + } + Utils::showView($lodspk, $data, $viewFile); + } + } else { + Utils::showView($lodspk, $data, $viewFile); + } + } + + public static function getResultsType($query) + { + global $conf; + global $uri; + if (preg_match("/select/i", $query)) { + return $conf['output']['select']; + } elseif (preg_match("/describe/i", $query)) { + return $conf['output']['describe']; + } elseif (preg_match("/construct/i", $query)) { + return $conf['output']['describe']; + } elseif (preg_match("/ask/i", $query)) { + return $conf['output']['ask']; + } else { + HTTPStatus::send500($uri); + } + } + + public static function queryDir($modelDir, &$r, &$f) + { + global $conf; + global $uri; + global $lodspk; + global $endpoints; + global $results; + $strippedModelDir = str_replace('endpoint.', '', $modelDir); + $lodspk['model'] = $modelDir; + $originalDir = getcwd(); + $subDirs = array(); + if ($conf['debug']) { + Logging::log("Entering $strippedModelDir from " . getcwd(), E_USER_NOTICE); + } + chdir($modelDir); + $handle = opendir('.'); + + while (false !== ($modelFile = readdir($handle))) { + if ($modelFile != "." && $modelFile != ".." && strpos($modelFile, ".") !== 0) { + if (is_dir($modelFile)) { + if (strpos('endpoint.', $modelFile) == 0) { + if ($conf['debug']) { + Logging::log( + "Save $modelFile for later, after all the queries in the current directory has been resolved", + E_USER_NOTICE + ); + } + $subDirs[] = $modelFile; + } + } else { + if (preg_match('/\.query$/', $modelFile)) { + $e = null; + if (!isset($endpoints[$strippedModelDir])) { + if ($conf['debug']) { + Logging::log("Creating endpoint for $strippedModelDir", E_USER_NOTICE); + } + if (!isset($conf['endpoint'][$strippedModelDir])) { + if ($conf['debug']) { + Logging::log( + "Couldn't find $strippedModelDir as a list of available endpoints. Will continue using 'local'", + E_USER_WARNING + ); + } + $e = $endpoints['local']; + } else { + $endpoints[$strippedModelDir] = new Endpoint( + $conf['endpoint'][$strippedModelDir], + $conf['endpoint']['config'] + ); + $e = $endpoints[$strippedModelDir]; + } + } else { + $e = $endpoints[$strippedModelDir]; + } + if ($modelDir != $lodspk['type']) { + if (!isset($r[$strippedModelDir])) { + $r[$strippedModelDir] = array(); + $f[$strippedModelDir] = array(); + } + Utils::queryFile($modelFile, $e, $r[$strippedModelDir], $f); + } else { + Utils::queryFile($modelFile, $e, $r, $f); + } + } + } + } + } + closedir($handle); + $originalDir = $lodspk['model']; + if (isset($subDirs)) { + foreach ($subDirs as $v) { + if (!isset($r[$modelDir])) { + $r[$modelDir] = array(); + } + if ($modelDir != $lodspk['type']) { + Utils::queryDir($v, $r[$strippedModelDir], $f[$strippedModelDir]); + } else { + Utils::queryDir($v, $r, $f); + } + } + } + // chdir($conf['home']); + //return $data; + } + + public static function queryFile($modelFile, $e, &$rPointer, &$fPointer) + { + global $conf; + global $lodspk; + global $results; + global $firstResults; + global $uri; + $data = array(); + $strippedModelFile = str_replace('endpoint.', '', str_replace('.query', '', $modelFile)); + if (!is_dir($modelFile)) { + require_once($conf['home'] . 'lib/Haanga/lib/Haanga.php'); + Haanga::configure(array( + 'cache_dir' => $conf['home'] . 'cache/', + 'autoescape' => false, + )); + + //Haanga supports the dot (.) convention only for objects + if (is_array($lodspk) && !empty($lodspk)) { + $lodspkObj = Convert::array_to_object($lodspk); + $lodspk = $lodspkObj; + } + $r2 = Convert::array_copy($results); + $models = Convert::array_to_object($r2); + $f2 = Convert::array_copy($firstResults); + $first = Convert::array_to_object($f2); + $vars = compact('uri', 'lodspk', 'conf', 'models', 'first'); + $q = file_get_contents($modelFile); + if ($q == false) { + HTTPStatus::send500("I can't load " . $modelFile . " in " . getcwd()); + } + $fnc = Haanga::compile($q); + $query = $fnc($vars, true); + + if (is_object($lodspk)) { + $lodspkObj = Convert::object_to_array($lodspk); + $lodspk = $lodspkObj; + } + $query = Utils::addPrefixes($query); + if (!empty($lodspk['transform_select_query']) && $lodspk['transform_select_query'] == true) { + $parser = ARC2::getSPARQLParser(); + $parser->parse($query); + $sparqlConstruct = array(); + if (!$parser->getErrors()) { + $resultVars = array(); + $q_infos = $parser->getQueryInfos(); + foreach ($q_infos['query']['result_vars'] as $v) { + if ($v['type'] == 'var') { + $resultVars[$v['value']] = 1; + } + }; + $x = Utils::extractObj($q_infos['query']['pattern']); + foreach ($x as $v) { + if (($resultVars[$v['s']] && $v['s_type'] == 'var') + || ($resultVars[$v['p']] && $v['p_type'] == 'var') + || ($resultVars[$v['o']] && $v['o_type'] == 'var')) { + array_push($sparqlConstruct, $v); + } + } + $construct = ""; + foreach ($sparqlConstruct as $v) { + if ($v['s_type'] == 'uri') { + $construct .= "<" . $v['s'] . "> "; + } elseif ($v['s_type'] == 'var') { + $construct .= '?' . $v['s'] . ' '; + } else { + $construct .= $v['s'] . " "; + } + + if ($v['p_type'] == 'uri') { + $construct .= "<" . $v['p'] . "> "; + } elseif ($v['p_type'] == 'var') { + $construct .= '?' . $v['p'] . ' '; + } else { + $construct .= $v['p'] . " "; + } + + if ($v['o_type'] == 'uri') { + $construct .= "<" . $v['o'] . "> "; + } elseif ($v['o_type'] == 'literal') { + $construct .= '"' . $v['o'] . '" '; + } elseif ($v['o_type'] == 'var') { + $construct .= '?' . $v['o'] . ' '; + } else { + $construct .= $v['o'] . " "; + } + + $construct .= ".\n"; + } + if ($construct == "") { + if (sizeof($q_infos['query']['result_vars']) > 0) { + //For now, assuming variables are in the GRAPH ?g + $query = "CONSTRUCT {?g ?x ?y} WHERE{GRAPH ?g{?g ?x ?y}}"; + } else { + if (!preg_match('/construct/i', $query)) { + HTTPStatus::send500(); + } + } + } else { + $query = preg_replace( + '/select\s*[^{]*\s*(where)?\s*{/i', + 'CONSTRUCT {' . $construct . '} WHERE{', + $query + ); + } + } else { + return; + //HTTPStatus::send500("invalid query: " . var_export($parser->getErrors(), true)."\n\nQUERY:\n".$query); + } + } + if ($conf['debug']) { + Logging::log($modelFile . " against " . $e->getSparqlUrl()); + Logging::log($query); + Logging::log("Running query from " . $modelFile . " on endpoint " . $e->getSparqlURL(), E_USER_NOTICE); + } + $initTime = microtime(true); + $aux = $e->query($query, Utils::getResultsType($query)); + $endTime = microtime(true); + if ($conf['debug']) { + Logging::log("Execution time: " . ($endTime - $initTime) . " seconds"); + } + $timeObj = new stdClass(); + $timeObj->query = new stdClass(); + $timeObj->query->value = $strippedModelFile; + $timeObj->time = new stdClass(); + $timeObj->time->value = ($endTime - $initTime); + $lodspk['queryTimes'][$strippedModelFile] = $timeObj; + if ($modelFile != $lodspk['type']) { + if (!isset($rPointer[$strippedModelFile])) { + $rPointer[$strippedModelFile] = array(); + $firstResults[$strippedModelFile] = array(); + } + if (Utils::getResultsType($query) == $conf['output']['select']) { + $rPointer[$strippedModelFile] = Utils::sparqlResult2Obj($aux); + if (!empty($rPointer[$strippedModelFile][0])) { + $fPointer[$strippedModelFile] = $rPointer[$strippedModelFile][0]; + } + } else { + $lodspk['resultRdf'] = true; + $rPointer[$strippedModelFile] = $aux; + } + } else { + if (Utils::getResultsType($query) == $conf['output']['select']) { + $rPointer = Utils::sparqlResult2Obj($aux); + $fPointer[$strippedModelFile] = $rPointer[0]; + } else { + $lodspk['resultRdf'] = true; + $rPointer = $aux; + } + } + } else { + if (strpos('endpoint.', $modelFile) == 0) { + if ($conf['debug']) { + Logging::log("$modelFile is a directory, will process it later", E_USER_NOTICE); + } + if ($modelFile != $lodspk['type']) { + if (!isset($rPointer[$strippedModelFile])) { + $rPointer[$strippedModelFile] = array(); + } + Utils::queryDir($modelFile, $rPointer[$strippedModelFile], $fPointer[$strippedModelFile]); + } else { + Utils::queryDir($modelFile, $rPointer, $fPointer); + } + } + } + } + + public static function internalize($array) + { + global $conf; + $firstResultsKeyAppearance = true; + foreach ($array as $key => $value) { + if (!isset($value['value'])) { + $array[$key] = Utils::internalize($value); + /*if($firstResultsKeyAppearance){ + $firstResultsKeyAppearance = false; + $array['_firstResults']=$array[$key]; + }*/ + } else { + if (isset($value['uri']) && $value['uri'] == 1) { + //If there is no mirroring, it wouldn't hurt to have available this value (e.g., using templates from a mirrored instance to a non-mirrored one) + $value['mirroredUri'] = $value['value']; + $value['mirroredCurie'] = Utils::uri2curie($value['value']); + if (isset($conf['mirror_external_uris']) && $conf['mirror_external_uris'] != false) { + $value['value'] = Utils::getUnMirroredUri($value['value']); + } + $value['curie'] = Utils::uri2curie($value['value']); + $array[$key] = $value; + } + } + } + return $array; + } + + public static function getfirstResults($array) + { + global $conf; + $firstResultsKeyAppearance = true; + if (is_iterable($array)) { + foreach ($array as $key => $value) { + if (!isset($value['value'])) { + $aux = Utils::getfirstResults($value); + if (isset($aux['0'])) { + $array[$key] = $aux['0']; + } else { + $array[$key] = $aux; + } + } + } + } + return $array; + } + + public static function showView($lodspkData, $data, $view) + { + global $conf; + global $uri; + global $lodspk; + global $extension; + //$lodspk = $conf['view']['standard']; + $lodspk = $lodspkData; + if (isset($lodspkData['params'])) { + $lodspk['this']['params'] = $lodspkData['params']; + } + if (isset($lodspk['queryTimes'])) { + $lodspk['queryTimes'] = Convert::array_to_object($lodspk['queryTimes']); + } + require_once($conf['home'] . 'lib/Haanga/lib/Haanga.php'); + $viewAux = explode("/", $view); + $viewFile = array_pop($viewAux); + //$viewFile = $view; + $viewPath = join("/", $viewAux); + Haanga::configure(array( + 'template_dir' => $viewPath, + 'cache_dir' => $conf['home'] . 'cache/', + )); + $rdf = null; + if (array_key_exists('rdf', $data)) { + $rdf = $data['rdf']; + unset($data['rdf']); + } else { + } + $models = $data; + Convert::getPaths($models, ""); + $first = $lodspk['firstResults']; + unset($lodspk['firstResults']); + //unset($lodspk); + $vars = compact('uri', 'lodspk', 'conf', 'models', 'rdf', 'first'); + if ($conf['debug']) { + //Logging::log(var_export($vars, true)); + } + if (is_string($data)) { + echo($data); + } elseif (is_file($view)) { + try { + Haanga::Load($viewFile, $vars); + } catch (Exception $e) { + echo '<pre>'; + echo($e->getMessage() . "' in " . $e->getFile() . ":" . $e->getLine( + ) . "\nStack trace:\n" . $e->getTraceAsString()); + echo '</pre>'; + } + } elseif ($view == null) { + $fnc = Haanga::compile('{{models|safe}}'); + $fnc($vars, true); + } else { + echo $conf['home'] . $viewPath . " " . $viewFile; + $fnc = Haanga::compile($view); + $fnc($vars, true); + } + } + + private static function extractObj($obj, $term = 'triple') + { + $triples = array(); + if (is_array($obj)) { + foreach ($obj as $k => $v) { + if ($v['type'] != 'triple') { + $aux = Utils::extractObj($v); + if ($aux['type'] != 'triple') { + $triples = array_merge($triples, $aux); + } else { + $triples = array_merge($triples, $aux); + } + } else { + array_push($triples, $v); + } + } + } + return $triples; + } + + public static function addPrefixes($q) + { + global $conf; + $matches = array(); + $visited = array(); + $newQuery = $q; + if (preg_match_all("|\s(\w+):\w+|", $q, $matches) > 0) { + foreach ($matches[1] as $v) { + if (!isset($visited[$v]) && isset($conf['ns'][$v])) { + $newQuery = "PREFIX " . $v . ": <" . $conf['ns'][$v] . ">\n" . $newQuery; + $visited[$v] = true; + } + } + } + + return $newQuery; + } + + public static function filterTriples($triples, $pattern) + { + //Simples match/filter function possible + $result = array(); + foreach ($triples as $t) { + if ((($pattern[0] != null && $pattern[0] == $t['s']) || $pattern[0] == null) && + (($pattern[1] != null && $pattern[1] == $t['p']) || $pattern[1] == null) && + (($pattern[2] != null && $pattern[2] == $t['o']) || $pattern[2] == null)) { + $result[] = array($t['s'], $t['p'], $t['o']); + } + } + return $result; + } + + public static function getMirroredUri($localUri) + { + global $conf; + $uri = $localUri; + if (isset($conf['mirror_external_uris']) && $conf['mirror_external_uris'] != false) { + if (is_bool($conf['mirror_external_uris'])) { + $uri = preg_replace("|^" . $conf['basedir'] . "|", $conf['ns']['base'], $localUri); + } elseif (is_string($conf['mirror_external_uris'])) { + $uri = preg_replace("|^" . $conf['basedir'] . "|", $conf['mirror_external_uris'], $localUri); + } elseif (is_array($conf['mirror_external_uris'])) { + $defaultKey = ""; //Default namespace is empty string "" + $namespaceFragment = array_shift(split("/", str_replace($conf['basedir'], "", $localUri))); + $uri = preg_replace( + "|^" . $conf['basedir'] . "|", + $conf['mirror_external_uris'][$defaultKey], + $localUri + ); + foreach ($conf['mirror_external_uris'] as $k => $v) { + if ($namespaceFragment == $k) { + $uri = preg_replace( + "|^" . $conf['basedir'] . $k . "/" . "|", + $conf['mirror_external_uris'][$k], + $localUri + ); + break; + } + } + } else { + HTTPStatus::send500("Error in mirroring configuration"); + exit(1); + } + } + return $uri; + } + + public static function getUnMirroredUri($uri) + { + global $conf; + $localUri = $uri; + if (is_bool($conf['mirror_external_uris'])) { + $localUri = preg_replace("|^" . $conf['ns']['local'] . "|", $conf['basedir'], $uri); + } elseif (is_string($conf['mirror_external_uris'])) { + $localUri = preg_replace("|^" . $conf['mirror_external_uris'] . "|", $conf['basedir'], $uri); + } elseif (is_array($conf['mirror_external_uris'])) { + //Instead of doing expensive regex, jsut use str_replace + foreach ($conf['mirror_external_uris'] as $k => $v) { + if (strlen(str_replace($v, "", $uri)) != strlen($uri)) { + $fragment = ($k == "") ? $k : $k . "/"; + $localUri = preg_replace("|^" . $v . "|", $conf['basedir'] . $fragment, $uri); + break; + } + } + } else { + HTTPStatus::send500("Error in mirroring configuration"); + exit(1); + } + return $localUri; + } + }