function getANodeNeg() { $conf = array('ns' => array('rdf' => 'http://www.w3.org/1999/02/22-rdf-syntax-ns#', 'rdfs' => 'http://www.w3.org/2000/01/rdf-schema#', 'dbpedia' => 'http://dbpedia.org/ontology/', 'foaf' => 'http://xmlns.com/foaf/0.1/', 'xsd' => 'http://www.w3.org/2001/XMLSchema#', 'dcterms' => 'http://purl.org/dc/terms/')); $docNeg = $this->getDOMDocNeg(); $aNodes = $docNeg->source->getElementsByTagName('a'); $conf['source'] = $aNodes->item(0); return ARC2::getComponent('negotiators_ANodePlugin', $conf); }
public function __construct($contextURIs) { global $config; global $graphConfig; $this->store = ARC2::getStore($config); $this->uris = $contextURIs; $this->graph = ARC2::getComponent('PMJ_ResourceGraphPlugin', $graphConfig); }
public function getNegotiators($val, $nArray = false) { $retArray = array(); $nArray = $nArray ? $nArray : $this->negotiators; foreach ($this->negotiators as $n) { if ($this->applyTestOnNegotiator($n, $val)) { $retArray[] = ARC2::getComponent($n); } } }
public function __construct($array) { global $config; global $graphConfig; $this->store = ARC2::getStore($config); if (isset($array['uris'])) { $this->uris = $array['uris']; } if (isset($array['tagURIs'])) { $this->tagURIs = $array['tagURIs']; } $this->graph = ARC2::getComponent('PMJ_ResourceGraphPlugin', $graphConfig); }
public function __construct($vars) { global $config; global $graphConfig; $this->store = ARC2::getStore($config); foreach ($vars as $var => $val) { $this->{$var} = $val; } $this->graph = ARC2::getComponent('PMJ_ResourceGraphPlugin', $graphConfig); $this->setQuery(); $this->doQuery(); $this->processResultSet(); }
public function transform($settings = '') { if ($settings != '') { foreach ($settings as $setting => $value) { $this->{$setting} = $value; } } $this->a = $this->config_ns(); foreach ($this->required as $require) { require_once dirname(__FILE__) . DIRECTORY_SEPARATOR . $require . '.php'; } $this->ARC2 = ARC2::getComponent('RDFTranformrPlugin', $this->a); return $this->query != '' ? $this->json_query($this->query) : $this->transformr_types(); }
public function testAddPropValue() { $res = $this->getRes(); $res->addPropValue('foaf:page', 'http://www.patrickgmj.net/blog'); $this->assertTrue(in_array('http://www.patrickgmj.net/blog', $res->getFlattenedProps('foaf:page'))); $res->addPropValue('rdfs:type', 'foaf:Agent'); $this->assertTrue(in_array('http://xmlns.com/foaf/0.1/Agent', $res->getFlattenedProps('rdfs:type'))); $res2 = ARC2::getComponent('PMJ_ResourcePlusPlugin', array('ns' => array('foaf' => 'http://xmlns.com/foaf/0.1/'))); $res2->setURI('http://example.com'); $res2->addPropValue('rdfs:type', 'foaf:Agent'); $this->assertEquals(1, $res2->triplesCount()); $res2->addPropValue('rdfs:type', 'foaf:Agent'); $this->assertEquals(1, $res2->triplesCount()); }
public function testInit() { $conf = array('ns' => array('rdf' => 'http://www.w3.org/1999/02/22-rdf-syntax-ns#', 'rdfs' => 'http://www.w3.org/2000/01/rdf-schema#', 'dbpedia' => 'http://dbpedia.org/ontology/', 'foaf' => 'http://xmlns.com/foaf/0.1/', 'xsd' => 'http://www.w3.org/2001/XMLSchema#', 'dcterms' => 'http://purl.org/dc/terms/'), 'store' => $this->store); $n = ARC2::getComponent('negotiators_DataNegotiatorPlugin', $conf); $this->assertTrue(isset($n->store)); $this->assertEquals('NegotiatorSelector', get_class($n->selector)); $this->assertTrue(count($n->selector->negotiators) > 0); //test adding to a predefined ns (e.g., sioc prefix already present, but not clobbered on init) $testN = ARC2::getComponent('negotiators_TestPlugin', $conf); $this->assertTrue(array_key_exists('foaf', $testN->ns)); $this->assertTrue(array_key_exists('test', $testN->ns)); //test setting currURI from caller $this->assertEquals($n->currURI, $testN->currURI); //test setting revURI from caller $this->assertEquals($n->currURI, $testN->revURI); }
function preProcess() { date_default_timezone_set('America/New_York'); $linkNodes = $this->xpath->query('link', $this->source); $postPage = $this->trimSlash($linkNodes->item(0)->textContent); $postURI = $postPage . '#this'; $postRes = ARC2::getComponent('PMJ_ResourcePlusPlugin', array('ns' => $this->ns)); $postRes->setURI($postURI); $postRes->addPropValue($this->revProp, $this->revURI); $titleNodes = $this->xpath->query('title', $this->source); $postRes->addPropValue('dcterms:title', $titleNodes->item(0)->textContent); $createdNodes = $this->xpath->query('pubDate', $this->source); $created = $createdNodes->item(0)->textContent; $createdDateTime = date_create($created); $postRes->addPropValue('dcterms:created', $createdDateTime->format('c'), 'literal', 'xsd:dateTime'); $this->graph->addResource($postRes); }
function preProcess() { $linkNodes = $this->xpath->query('//channel/link'); $linkNode = $linkNodes->item(0); $pageURL = $this->trimSlash($linkNode->textContent); $siteURI = $pageURL . "#this"; $siteRes = ARC2::getComponent('PMJ_ResourcePlusPlugin', array('ns' => $this->ns)); $siteRes->setURI($siteURI); $titles = $this->xpath->query('//channel/title'); $siteRes->addPropValue('dcterms:title', $titles->item(0)->textContent, 'literal'); $siteRes->addPropValue('rdf:type', 'sioc:Site'); $siteRes->addPropValue('foaf:page', $pageURL); $this->graph->addResource($siteRes); $items = $this->source->getElementsByTagName('item'); for ($i = 0; $i < $items->length; $i++) { $this->addSubNegotiator('negotiators_RSSItemPlugin', array('source' => $items->item($i), 'revURI' => $siteURI, 'xpath' => $this->xpath)); } }
function curl_get($url) { $reader = ARC2::getComponent('Reader', $conf); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); $headers = array(); $headers[] = 'Accept: text/xml'; curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); try { $content = curl_exec($ch); $error_code = curl_errno($ch); curl_close($ch); } catch (Exception $e) { echo " (curl error): " . $e->getMessage() . PHP_EOL; } return $content; }
$index = ARC2::getSimpleIndex($triples, false); /* false -> non-flat version */ $rdf_doc = $parser->toTurtle($index, $ns); } elseif ($format == 'json' || $format == 'rdf-json') { ini_set("include_path", S3DB_SERVER_ROOT . "/pearlib/arc" . PATH_SEPARATOR . ini_get("include_path")); include_once "ARC2.php"; $a['ns'] = $ns; $parser = ARC2::getComponent('RDFJSONSerializer', $a); $index = ARC2::getSimpleIndex($triples, false); $rdf_doc = $parser->toRDFJSON($index, $ns); } else { $format = 'n3'; ini_set("include_path", S3DB_SERVER_ROOT . "/pearlib/arc" . PATH_SEPARATOR . ini_get("include_path")); include_once "ARC2.php"; $a['ns'] = $ns; $parser = ARC2::getComponent('NTriplesSerializer', $a); $index = ARC2::getSimpleIndex($triples, false); /* false -> non-flat version */ $rdf_doc = $parser->toNTriples($index, $ns); } fwrite($fid, $rdf_doc); fclose($fid); chmod($FinalFfilename, 0777); ##Prepare to output $linkname = random_string('10') . '.' . $format; $filelink = $GLOBALS['URI'] . '/extras/' . $linkname; if (!copy($FinalFfilename, S3DB_SERVER_ROOT . '/extras/' . $linkname)) { echo "Could not copy the file. This could be because Apache does not have 'write' permission on the s3db folder or the /extras/."; exit; } if (in_array('link', array_keys($inputs))) {
//error_reporting(E_ALL); include 'config.php'; include_once 'checkLogin.php'; include ARC_DIR . 'ARC2.php'; include_once CLASSES_DIR . 'RubrickBuilder.php'; include_once CLASSES_DIR . 'Rubric.php'; include_once CLASSES_DIR . 'Context.php'; include_once CLASSES_DIR . 'RubricLine.php'; include_once CLASSES_DIR . 'RubricLineValue.php'; include_once CLASSES_DIR . 'Tagging.php'; header("Content-type: application/json"); $store = ARC2::getStore($config); //$jsonStr = '{"rubricLines":[{"action":"create","fields":[{"Name":["line%201"]},{"Description":["Describe%20the%20skills%20that%20this%20line%20evaluates"]},{"Tags":["Add%20a%20tag"]},{"Public":[1]},{"order":["0"]},{"v5":["Describe%20the%20Rubric%20Value%20here."],"score":1},{"v4":["Describe%20the%20Rubric%20Value%20here."],"score":2},{"v3":["Describe%20the%20Rubric%20Value%20here."],"score":3},{"v2":["Describe%20the%20Rubric%20Value%20here."],"score":4},{"v1":["Describe%20the%20Rubric%20Value%20here."],"score":5}]},{"action":"create","fields":[{"Name":["line%202"]},{"Description":["Describe%20the%20skills%20that%20this%20line%20evaluates"]},{"Tags":["line%20tag"]},{"Public":[1]},{"order":["1"]},{"v5":["Describe%20the%20Rubric%20Value%20here."],"score":1},{"v4":["Describe%20the%20Rubric%20Value%20here."],"score":2},{"v3":["Describe%20the%20Rubric%20Value%20here."],"score":3},{"v2":["Describe%20the%20Rubric%20Value%20here."],"score":4},{"v1":["Describe%20the%20Rubric%20Value%20here."],"score":5}]}],"rubricMeta":{"name":{"rName":["Rubric%20Name"]},"desc":{"rDesc":["Rubric%20Description"]},"tags":{"rTags":["t1","t2"]},"pub":{"rPublic":[1]},"contexts":{"rContexts":["http%3A%2F%2Fdata.rubrick-jetpack.org%2FContext%2F7af867eb16d35a749874fb71a62ecea2714c14b0"]}}}'; $jsonStr = ' { "literals" : [ { "p" : "tagging:tagging" , "o" : "test tag" } , { "p" : "tagging:tagging" , "o" : "stuff" } ]} '; $jsonObj = json_decode($jsonStr); $init = array('post' => $jsonObj); $bigGraph = ARC2::getComponent('PMJ_ResourceGraphPlugin', $graphConfig); $newRes = new Tagging(false, $init); $newRes->buildAddGraph(); //echo count($newRes->aggregates); //$ag = $newRes->aggregates[0]; //echo $ag->getRevTriple(); //echo $ag->revResourceURI; $bigGraph->mergeResourceGraph($newRes->addGraph); foreach ($newRes->aggregates as $ag) { $bigGraph->mergeResourceGraph($ag->addGraph); } echo json_encode($bigGraph->toRDFJSON(true)); //echo count($newRes->aggregates);
function getRDFJSONSerializer($a = '') { return ARC2::getComponent('RDFJSONSerializer', $a); }
$parser->extractRDF('dc rdfa'); $triples = $parser->getTriples(); $q = 'INSERT INTO <> { ' . $parser->toNTriples($triples) . ' } '; $parseRS = $store->query($q); $graph = ARC2::getComponent('PMJ_ResourceGraphPlugin', $graphConfig); $recordingRes = ARC2::getComponent('PMJ_ResourcePlusPlugin', $graphConfig); $userURI = $_SESSION['userURI']; $recordingURI = 'http://data.rubrick-jetpack.org/Recordings/' . sha1($userURI . time()); $recordingRes->setURI($recordingURI); $recordingRes->addPropValue('rdf:type', 'r:Recording', 'uri'); $recordingRes->addPropValue('sioc:has_creator', $userURI, 'uri'); $recordingRes->addPropValue('r:hasPage', $_POST['page'], 'uri'); $recordingRes->addPropValue('dcterms:created', date('c'), 'literal', 'xsd:dateTime'); $recordingRes->addPropValue('r:hasRubric', $_POST['rubric'], 'uri'); if (is_array($_POST['r:hasLineValues'])) { foreach ($_POST['r:hasLineValues'] as $lineValueURI) { $recordingRes->addPropValue('r:hasLineValue', $lineValueURI, 'uri'); } } else { $recordingRes->addPropValue('r:hasLineValue', $_POST['lineValues'], 'uri'); } $contextRes = ARC2::getComponent('PMJ_ResourcePlusPlugin', $graphConfig); $contextRes->setURI($_POST['context']); $contextRes->addPropValue('r:hasRecording', $recordingURI, 'uri'); $graph->addResource($contextRes); $graph->addResource($recordingRes); $q = 'INSERT INTO <> { ' . $graph->toNTriples() . ' } '; //echo htmlspecialchars($graph->toNTriples()); $rs = $store->query($q); $message = 'Data is happily saved!'; echo "{ message : '" . $message . "' }";
public function draw_onto() { $onto_store_config = $this->ontostore_params; $store = ARC2::getStore($onto_store_config); /* configuration */ $config = array('graphviz_path' => 'dot', 'graphviz_temp' => '/tmp/', 'ns' => $this->namespaces); /* instantiation */ $viz = ARC2::getComponent('TriplesVisualizerPlugin', $config); foreach ($this->namespaces as $key => $uri) { $prefix .= "PREFIX " . $key . ": <" . $uri . ">"; } if (isset($_POST['query'])) { $_POST['query'] = $prefix . "\n\t\t\t" . $_POST['query']; } $query = "SELECT * WHERE {\n\t\t\t?s rdf:type owl:Class .\n\t\t\t?s ?p ?o .\n\t\t\tFILTER(!(?p=<http://www.pmbservices.fr/ontology#displayLabel>)) \n\t\t\tFILTER(!(?p=<http://www.w3.org/1999/02/22-rdf-syntax-ns#type>)) \t\n\t\t}"; $classes = $store->query($query, 'rows'); $query = "SELECT * WHERE {\n\t\t\t?s rdf:type owl:ObjectProperty .\n\t\t\t?s ?p ?o .\n\t\t\tFILTER(!(?p=<http://www.pmbservices.fr/ontology#displayLabel>))\n\t\t\tFILTER(!(?p=<http://www.w3.org/1999/02/22-rdf-syntax-ns#type>))\n\t\t\tFILTER(!(?p=<http://www.pmbservices.fr/ontology#datatype>))\n\t\t}"; $properties = $store->query($query, 'rows'); /* display an svg image */ $svg = $viz->draw(array_merge($classes, $properties), 'svg', 'raw'); print $svg; }
/** * addSubNegotiatorsByTest * @param string $testStr */ public function addSubNegotiatorsByTest($testStr, $negsToTestArray = false) { $nArray = $this->selector->applyTestOnNegotiators($testStr, $negsToTestArray); foreach ($nArray as $n) { $this->subNegotiators[$n] = ARC2::getComponent($n); } }
public function testAddResource() { $conf = array('ns' => array('rdf' => 'http://www.w3.org/1999/02/22-rdf-syntax-ns#', 'rdfs' => 'http://www.w3.org/2000/01/rdf-schema#', 'dbpedia' => 'http://dbpedia.org/ontology/', 'foaf' => 'http://xmlns.com/foaf/0.1/', 'xsd' => 'http://www.w3.org/2001/XMLSchema#', 'dcterms' => 'http://purl.org/dc/terms/')); $g = ARC2::getComponent('PMJ_ResourceGraphPlugin', $conf); $r1 = $this->getRes1(); $g->addResource($r1); $r2 = $this->getRes2(); $g->addResource($r2); //is it there? $this->assertEquals(2, $g->resourceCount()); //did I avoid duplicates? $g->addResource($r1); $this->assertEquals(2, $g->resourceCount()); //are the resources merging? $r1tripleCount = $g->resources['http://example.info/resourceplus1']->triplesCount(); $r3 = $this->getRes1(); $r3->addPropValue('rdfs:type', 'foaf:Group'); $g->addResource($r3); $this->assertEquals($r1tripleCount + 1, $g->resources['http://example.info/resourceplus1']->triplesCount()); }
function getSPARQLScriptProcessor($a = '') { return ARC2::getComponent('SPARQLScriptProcessor', $a); }
function __init() { $csIndex = array(); $CSNS = 'http://purl.org/vocab/changeset/schema#'; $utils = ARC2::getComponent('ARC2_IndexUtilsPlugin'); // Get the triples to be added $additions = !empty($this->before) ? $utils->diff($this->after, $this->before) : $this->after; //Get the triples to be removed $removals = !empty($this->after) ? $utils->diff($this->before, $this->after) : $this->before; // Get an array of all the subject uris $subjectIndex = array_merge(array_keys($this->before), array_keys($this->after)); // Get the metadata for all the changesets $date = !empty($this->a['createdDate']) ? $this->a['createdDate'] : date(DATE_ATOM); $creator = !empty($this->a['creatorName']) ? $this->a['creatorName'] : 'Talis ChangeSet Builder plugin'; $reason = !empty($this->a['changeReason']) ? $this->a['changeReason'] : 'Change using Talis ChangeSet Builder plugin'; // for every subject uri, create a new changeset $n = count($subjectIndex); for ($i = 0; $i < $n; $i++) { $csID = '_:cs' . $i; $csIndex[$subjectIndex[$i]] = $csID; $this->addT($csID, 'http://www.w3.org/1999/02/22-rdf-syntax-ns#type', $CSNS . 'ChangeSet', 'uri'); $this->addT($csID, $CSNS . 'subjectOfChange', $subjectIndex[$i], 'uri'); $this->addT($csID, $CSNS . 'createdDate', $date, 'literal'); $this->addT($csID, $CSNS . 'creatorName', $creator, 'literal'); $this->addT($csID, $CSNS . 'changeReason', $reason, 'literal'); /* add extra user-given properties to each changeset*/ if (!empty($this->a['properties'])) { foreach ($this->a['properties'] as $p => $objs) { $this->addT($csID, $p, $objs); } } } /*iterate through the triples to be added, reifying them, and linking to the Statements from the appropriate changeset */ $reifiedAdditions = $utils->reify($additions, 'Add'); foreach ($reifiedAdditions as $nodeID => $props) { $subject = $props['http://www.w3.org/1999/02/22-rdf-syntax-ns#subject'][0]['value']; $csID = $csIndex[$subject]; $this->addT($csID, $CSNS . 'addition', $nodeID, 'bnode'); // if dc:source is given in the instantiating arguments, add it to the statement as provenance if (isset($this->a['http://purl.org/dc/terms/source'])) { $this->addT($nodeID, 'http://purl.org/dc/terms/source', $this->a['http://purl.org/dc/terms/source'], 'uri'); } } /*iterate through the triples to be removed, reifying them, and linking to the Statements from the appropriate changeset */ $reifiedRemovals = $utils->reify($removals, 'Remove'); foreach ($reifiedRemovals as $nodeID => $props) { $subject = $props['http://www.w3.org/1999/02/22-rdf-syntax-ns#subject'][0]['value']; $csID = $csIndex[$subject]; $this->addT($csID, $CSNS . 'removal', $nodeID, 'bnode'); } foreach ($this->__index as $uri => $props) { if (!isset($props[$CSNS . 'removal']) and !isset($props[$CSNS . 'addition'])) { unset($this->__index[$uri]); } } $this->__index = $utils->merge($this->__index, $reifiedAdditions, $reifiedRemovals); parent::__init(); }
$rjson = stripslashes($_POST['rJSON']); $robj = json_decode($rjson); if ($robj == null) { echo 'fail rubric'; echo $rjson; die; } $cjson = stripslashes($_POST['cJSON']); $cobj = json_decode($cjson); if ($cobj == null) { echo 'fail context'; echo $cjson; die; } $cURIs = array(); $newContextsGraph = ARC2::getComponent('PMJ_ResourceGraphPlugin', $config); foreach ($cobj as $key => $newContextObj) { $newContext = new Context($newContextObj); $newContext->buildPrivateGraph(); $newCURI = $newContext->uri; $newContextsGraph->mergeResourceGraph($newContext->graph); if (in_array($key, $robj->rubricMeta[4]->rContexts)) { $cURIs[] = urldecode($newCURI); } } foreach ($robj->rubricMeta[4]->rContexts as $val) { if (substr($val, 0, 3) != 'new') { $cURIs[] = urldecode($val); } } $robj->rubricMeta[4]->rContexts = $cURIs;
protected function getStore() { $url = $this->getSparqlUrl(); if (!empty($url)) { $config = array('endpoint_url' => $url); return ARC2::getComponent('RemoteEndpointPlugin', $config); } drupal_set_message("Configuration error: remote endpoint url is empty for module " . $this->moduleName, 'error'); return NULL; }
/** * Serialise the graph to N-Triples * @see http://www.w3.org/TR/rdf-testcases/#ntriples * @return string the N-Triples version of the graph */ function to_ntriples() { $serializer = ARC2::getComponent('NTriplesSerializer', array()); return $serializer->getSerializedIndex($this->_to_arc_index($this->_index)); }
public function extractGraphAroundProp($pURI) { global $graphConfig; $pURI = $this->expandPName($pURI); $index = array(); foreach ($this->resources as $res) { if ($res->hasProp($pURI)) { $index[$res->uri] = array(); $index[$res->uri][$pURI][] = $res->getProp($pURI); } } $retGraph = ARC2::getComponent('PMJ_ResourceGraphPlugin', $graphConfig); $retGraph->mergeIndex($index); return $retGraph; }
function toExhibitJSON() { $ser = ARC2::getComponent('ARC2_ExhibitJsonSerializerPlugin', array('ns' => $this->ns)); return $ser->getSerializedIndex($this->index); }
function make_rdf_model($triples) { $parser = ARC2::getComponent('RDFXMLParser'); $index = ARC2::getSimpleIndex($triples, false); /* false -> non-flat version */ $rdf_doc = $parser->toRDFXML($index); $filename = S3DB_SERVER_ROOT . '/tmp/' . md5(rand(10000, 200000)); $rr = fopen($filename, 'a+'); fwrite($rr, $rdf_doc); fclose($rr); return $filename; }
<?php include_once '../ARC2.php'; $parser = ARC2::getRDFParser(); /* $parser->parse('http://dbpedia.org/resource/DBpedia'); $index = $parser->getSimpleIndex(0); file_put_contents('dbpediaIndex.txt', serialize($index)); */ $index = unserialize(file_get_contents('dbpediaIndex.txt')); $conf = array('ns' => array('rdf' => 'http://www.w3.org/1999/02/22-rdf-syntax-ns#', 'rdfs' => 'http://www.w3.org/2000/01/rdf-schema#', 'dbpedia-owl' => 'http://dbpedia.org/ontology/', 'foaf' => 'http://xmlns.com/foaf/0.1/', 'xsd' => 'http://www.w3.org/2001/XMLSchema#', 'dcterms' => 'http://purl.org/dc/terms/', 'dbpprop' => 'http://dbpedia.org/property/', 'dbpres' => 'http://dbpedia.org/resource/', 'yago' => 'http://mpii.de/yago/resource/', 'owl' => 'http://www.w3.org/2002/07/owl#')); $g = ARC2::getComponent('PMJ_ResourceGraphPlugin', $conf); $g->mergeIndex($index); $g->removeResourcesWithProp('dbpprop:redirect'); $g->removeResourcesByNameSpace('yago'); echo $g->resourceCount(); echo "<br/><br/>"; echo $g->triplesCount(); echo "<br/><br/>"; $isProductOfs = $g->getResourcesWithProp('dbpprop:products', true); echo $g->toTurtle(); /* foreach($isProductOfs as $producer) { $parser->parse($producer); $g->mergeIndex($parser->getSimpleIndex(0)); } */ $dbpediaRes = $g->getResource('dbpres:DBpedia'); $dbpediaSameAs = $dbpediaRes->getProps('owl:sameAs'); print_r($dbpediaSameAs);
protected function _getEmptyResource() { global $graphConfig; return ARC2::getComponent('PMJ_ResourcePlusPlugin', $graphConfig); }
function sparql($I) { ##Parse the query and build the dataset #global $timer; if (is_file(S3DB_SERVER_ROOT . '/pearlib/Benchmark/Timer.php')) { require_once S3DB_SERVER_ROOT . '/pearlib/Benchmark/Timer.php'; $timer = new Benchmark_Timer(); $timer->start(); } extract($I); ##To use SPARQL with ARC library, we will need it to work with a remote endpoint. That means that we do not want to configure ARC as a datastore, but rather to retrieve the data from s3db deployments, convert it to RDF and then use ARC to run the query on it /* ARC2 static class inclusion */ ini_set("include_path", S3DB_SERVER_ROOT . "/pearlib/arc" . PATH_SEPARATOR . ini_get("include_path")); include_once "ARC2.php"; $s3ql['url'] = $in['url'] != '' ? $in['url'] : $default_uri; $s3ql['key'] = $in['key'] != '' ? $in['key'] : get_user_key($user_id, $db); $q = $in['query']; list($query, $triples, $prefixes) = parse_sparql_query($q, $s3ql); $bq .= "PREFIX " . implode("\n PREFIX ", $query['prefix']) . "\n "; $bq .= "SELECT " . $query['select'][0] . "\n "; $bq .= "FROM" . implode(" FROM ", $query['from']) . "\n "; $bq .= "WHERE " . $query['where'][0] . "\n "; preg_match_all('(\\?[A-Za-z0-9]+) ', $bq, $vars); if ($vars[0]) { $vars = array_unique($vars[0]); $sparql_vars = implode(" ", $vars); } if ($query['select'][0] != "" && $query['select'][0] != "*") { $outputCols = explode(" ", trim($query['select'][0])); $outputCols = array_filter($outputCols); $outputCols = array_intersect($vars, $outputCols); } $sparql = ereg_replace("FROM(.*)WHERE", "WHERE", $bq); #lets preprocess the order by which the must be queries must be performed to optimize speedness list($iterations, $scrambled) = iterationOrder($triples, $prefixes, true); ##$rdf_results will contain the totality of triples retrieved from s3db; ##Start a rdf-api model $iterations = array_values($iterations); $rdf = S3DB_URI_BASE . '/s3dbcore/model.n3'; #base s3db rdf model $filename = md5($rdf); $file_place = $GLOBALS['uploads'] . '/'; #$queryModel = rdf2php($rdf); #$data = $queryModel->sparqlQuery($sparql); #echo '<pre>';print_r($data);exit; if ($timer) { $timer->setMarker('Core model read into results'); } $rdf_results = array(); $performedQueries = array(); $r = 0; foreach ($iterations as $it => $triples2query) { $S3QL = array(); $S3QLfinal = array(); foreach ($triples2query as $i => $tripleInd) { $tripleString = $tripleInd; list($subject, $predicate, $object) = explode(' ', trim($tripleString)); $subject = ereg_replace('^<|>$', '', $subject); $predicate = ereg_replace('^<|>$', '', $predicate); $object = ereg_replace('^<|>$', '', $object); $triple = compact('subject', 'predicate', 'object'); #sparql triple is used to calculate the values of the variables in the triple #$sparql_triple = $sparql_prefixes_default.' SELECT * WHERE { '.ltrim($tripleString).' . }'; #now lets interpret the triple to explore the space of possible queries on S3QL $pack = compact('triple', 's3ql', 'user_id', 'db', 'prefixes', 'varType', 'discoveredData', 'it', 'varTypeWhere', 'collected_data', 'performedQueries'); $sp = sparql_navigator($pack); extract($sp); # if($timer) $timer->setMarker('Built query '.$i); ##Remove queries that were already performed if ($S3QL[0]) { foreach ($S3QL as $s => $q) { $S3QLfinal[] = $q; $queried_elements[] = $element[$s]; } $localQueries[$tripleString] = $localQueries[0]; $remoteQueries[$tripleString] = $remoteQueries[0]; $localQueries = array_filter($localQueries); $remoteQueries = array_filter($remoteQueries); } } $S3QL = $S3QLfinal; ##Remove repeated queries $S3QL = array_unique($S3QL); #if only the s3ql is requested, we can return it now if ($in['output'] == 'S3QL') { foreach ($localQueries as $sparqlVersion => $s3qlVersion) { $Q[]['S3QL'] = S3QLQuery($s3qlVersion); } foreach ($remoteQueries as $rq) { $Q[]['S3QL'] = $rq; } $root = 's3ql'; #root is just the word that xml should parse as the root for each entry $data = $Q; $cols = array('S3QL'); $format = $in['format'] == '' ? 'html' : $in['format']; $z = compact('data', 'cols', 'format', 'root'); $out = outputFormat($z); return array(true, $out); } #If paralel library is activated, use it for the data. Otherwise use the custom version #$query_answers_file = 'sparql_query_ans'.rand(100,200); $a=fopen($query_answers_file, 'a'); if (!empty($S3QL)) { if (extension_loaded('curl') && $goparallel) { // Create cURL handlers if ($timer) { $timer->setMarker('Starting queries from group ' . $it); } foreach ($S3QL as $k => $url) { $qURL = $url; $ch[$k] = curl_init(); // Set options curl_setopt($ch[$k], CURLOPT_URL, $qURL . '&format=php'); curl_setopt($ch[$k], CURLOPT_RETURNTRANSFER, 1); } $mh = curl_multi_init(); foreach ($S3QL as $k => $url) { curl_multi_add_handle($mh, $ch[$k]); } $running = null; do { curl_multi_exec($mh, $running); if ($timer) { $timer->setMarker('Query ' . $k . ' of group ' . $it . ' executed'); } } while ($running > 0); foreach ($S3QL as $k => $url) { $answer[$k] = curl_multi_getcontent($ch[$k]); if (!empty($answer[$k])) { #@fwrite($a, $answer[$k]); ##This is what takes the longest after the query, can it be replaced? $ans = unserialize($answer[$k]); $letter = $queried_elements[$r][0]; if (empty($ans)) { ##is this query part is not optional, then the result will be null ##TO BE DEVELOPED SOON } else { $rdf_results[$letter][] = $ans; } $r++; ##Add the triples to already existing triples #Line up the answer with the model if ($timer) { $timer->setMarker('Query ' . $it . '=>' . $k . ' converted to php '); } } } curl_multi_close($mh); ####Time count #$time_end = microtime(true); #$time = $time_end - $time_start; #echo "Query took ".$time." seconds\n";exit; ### } else { #Now solve the remaining triples with the constants found in this one if (is_array($localQueries) && !empty($localQueries)) { foreach ($localQueries as $sparql_triple => $s3ql) { $s3ql = array_filter(array_diff_key($s3ql, array('url' => ''))); $answer = localQ($s3ql); if (!empty($answer)) { $rdfanswer = rdf2php($answer); #Line up the answer with the model $queryModel->addModel($rdfanswer); #Now perform the query on the small model to find a constant for the remaining queries #list($data,$discovered, $discoveredData,$queryModel) = executeQuery($queryModel,$sparql_triple,$discovered,$format); } } } if (is_array($remoteQueries) && !empty($remoteQueries)) { foreach ($remoteQueries as $remoteQuery) { $answer = remoteQ($remoteQuery); if (!empty($answer)) { $rdfanswer = rdf2php($answer); #Line up the answer with the model $queryModel->addModel($rdfanswer); #Now perform the query on the small model to find a constant for the remaining queries #list($data,$discovered, $discoveredData,$queryModel) = executeQuery($queryModel,$sparql_triple,$discovered,$format); } } } } } } ##Get the data from the file ##Now, add the dictionary data if ($complete) { include_once S3DB_SERVER_ROOT . '/s3dbcore/dictionary.php'; $s3qlN = compact('user_id', 'db'); $s3qlN['from'] = 'link'; $s3qlN['format'] = 'php'; $links = query_user_dictionaries($s3qlN, $db, $user_id); $links = unserialize($links); $rdf_results['E'][0] = $links; $s3qlN = compact('user_id', 'db'); $s3qlN['from'] = 'namespaces'; $s3qlN['format'] = 'php'; $ns = query_user_dictionaries($s3qlN, $db, $user_id); $ns = unserialize($ns); if ($timer) { $timer->setMarker('Dictionary links retrieved'); } } ##Convert the result into an RDF file $data_triples = array(); if (is_array($rdf_results)) { foreach ($rdf_results as $letter => $results2rdfize) { $dont_skip_core_name = false; $dont_skip_serialized = true; if (ereg('S', $letter)) { $dont_skip_serialized = false; } if (ereg('C|R|P', $letter)) { $dont_skip_core_name = true; } foreach ($results2rdfize as $k => $data) { $tmp_triples = rdf_encode($data, $letter, 'array', $s3ql['db'], $ns, $collected_data, $dont_skip_serialized, $dont_skip_core_name); if (is_array($tmp_triples)) { $data_triples = array_merge($data_triples, $tmp_triples); } } } } if (!empty($data_triples)) { $tmp['ns'] = $prefixes; /* #this one for turtle $parser = ARC2::getComponent('TurtleParser', $a); $index = ARC2::getSimpleIndex($triples, false) ; # false -> non-flat version $rdf_doc = $parser->toTurtle($index,$prefixes); */ $parser = ARC2::getComponent('RDFXMLParser', $tmp); $index = ARC2::getSimpleIndex($data_triples, false); /* false -> non-flat version */ $rdf_doc = $parser->toRDFXML($index, $prefixes); $filename = S3DB_SERVER_ROOT . '/tmp/' . random_string(15) . '.rdf'; $rr = fopen($filename, 'a+'); fwrite($rr, $rdf_doc); fclose($rr); if ($timer) { $timer->setMarker(count($data_triples) . ' triples written to file ' . $filename); } ##The better strategy would be to let the client cpu resolve the query; return the graphs with the rdf so that a sparql on the client can handle it if ($return_file_name) { if (filesize($filename) > 0) { return array(true, $filename); } else { return array(false); } exit; } if ($redirect) { ##And now use an external service ( I gave up with ARC) to parse the query $url2search = str_replace(S3DB_SERVER_ROOT, S3DB_URI_BASE, $filename); ##Giving up on ARC, surrender to sparql.com $remote_endpoint = "http://sparql.org/sparql?query="; $bq = ereg_replace("FROM <.*>", "FROM <" . $url2search . ">", $bq); $bq = urlencode($bq); $remote_endpoint .= $bq . '&default-graph-uri=&stylesheet=/xml-to-html.xsl'; return array(true, $remote_endpoint); } #echo $filename;exit; #And finally perform the query on the model. $queryModel = rdf2php($filename); $format = $in['format'] != '' ? $in['format'] : 'html'; unlink($filename); if ($timer) { $timer->setMarker('Data converted to a model the rdf-api can query'); } if (eregi('^(sparql-xml|sparql-html)$', $format)) { switch ($format) { case 'sparql-xml': $result = $queryModel->sparqlQuery($sparql, 'XML'); break; case 'sparql-html': $result = $queryModel->sparqlQuery($sparql, 'HTML'); if ($_REQUEST['su3d']) { $timer->stop(); $profiling = $timer->getProfiling(); echo "Query took " . $profiling[count($profiling) - 1]['total'] . ' sec'; } break; } if ($result) { return array(true, $result); } else { return false; } } elseif ($format == 'html.form') { $form .= ' <html> <head> </head><body> <form method="GET" action="sparql.php" id="sparqlform"> <h5>Target Deployment(s)</h5> <input type="hidden" name="key" value="' . $s3ql['key'] . '"/> <input type="hidden" name="format" value="' . $_REQUEST['format'] . '"/> <input type = "text" id="url" size = "100%" value="' . $GLOBALS['url'] . '" name="url"> <h5>SPARQL <a href="http://www.w3.org/TR/rdf-sparql-query/" target="_blank">(help!!)</a></h5> <br /> <textarea cols="100" id="sparql" rows="10" name = "query">' . stripslashes($sparql) . '</textarea><br /> <input type="submit" value="SPARQL this!" id="submitsparql"></body> </form> '; $form .= '<br />' . count($data) . " rows"; $form .= '<br />Query took ' . (strtotime(date('His')) - $start) . ' sec'; if (count($data) > 0) { return array(true, $form); } else { return array(false); } } else { #and output the result according to requested format $data = $queryModel->sparqlQuery($sparql); if ($timer) { $timer->setMarker('Query on SPARQL data executed by rdf-api.'); } if (is_array($outputCols) && !empty($outputCols)) { ##only this one are to be shown in the final result $vars = $outputCols; } $cleanCols = array(); foreach ($vars as $varname) { $cleanCols[] = ereg_replace('^\\?', '', $varname); } $outputData = array(); if (is_array($data)) { foreach ($data as $s => $sparql_line) { foreach ($sparql_line as $sparql_var => $sparql_var_value) { if ($sparql_var_value->uri != '') { $outputData[$s][ereg_replace('^\\?', '', $sparql_var)] = $sparql_var_value->uri; } elseif ($sparql_var_value->label != '') { $outputData[$s][ereg_replace('^\\?', '', $sparql_var)] = $sparql_var_value->label; } else { $outputData[$s][ereg_replace('^\\?', '', $sparql_var)] = ""; } } } } if ($timer) { $timer->setMarker('Data converted in a format that fun outputformat can read'); } #$timer ->display(); #root is just the word that xml should parse as the root for each entry $root = 'sparql'; if ($timer) { $timer->setMarker('All variables fitted into their places to represent in the final output'); } $data = $outputData; $cols = $cleanCols; if ($_REQUEST['su3d']) { $timer->stop(); $profiling = $timer->getProfiling(); echo "Query took " . $profiling[count($profiling) - 1]['total'] . ' sec<br>'; } $z = compact('data', 'cols', 'format', 'root'); $out = outputFormat($z); echo $out; exit; if (count($data) > 0) { return array(true, $out); } else { return array(false); } } } else { return array(false); } #else { #$out= formatReturn($GLOBALS['error_codes']['no_results'], 'Your query did not return any results.', $format,''); #} }
<?php define('_Transformr', true); include_once '../app/config.php'; include_once '../app/arc/ARC2.php'; $arc_config = array('db_host' => $host, 'db_user' => $user, 'db_pwd' => $passwd, 'db_name' => $dbname, 'store_name' => $storename, 'endpoint_features' => array('ask', 'select', 'describe', 'construct', 'delete'), 'endpoint_timeout' => 60, 'endpoint_max_limit' => 1000, 'serializer_type_nodes' => 1, 'endpoint_write_key' => $writekey); /* init */ $endpoint = ARC2::getComponent('StoreTemplatePlugin', $arc_config); if (!$endpoint->isSetUp()) { $endpoint->setUp(); /* create tables */ } /* go */ print $endpoint->go();