public function onPropertiesActionData($event) { if ($this->_privateConfig->sort->property) { $store = Erfurt_App::getInstance()->getStore(); $config = Erfurt_App::getInstance()->getConfig(); $data = $event->predicates; foreach ($data as $graphUri => $predicates) { $query = new Erfurt_Sparql_SimpleQuery(); $query->setProloguePart('SELECT DISTINCT *')->addFrom((string) $graphUri)->setWherePart('WHERE { ?p <' . $this->_privateConfig->sort->property . '> ?o . }'); $result = $store->sparqlQuery($query); if (!empty($result)) { $order = array(); foreach ($result as $v) { $order[$v['p']] = $v['o']; } $predicateOrder = array(); foreach (array_keys($predicates) as $predicate) { if (array_key_exists($predicate, $order)) { $predicateOrder[] = (int) $order[$predicate]; } else { $predicateOrder[] = 0; } } array_multisort($predicateOrder, SORT_DESC, SORT_STRING, $predicates); $data[$graphUri] = $predicates; } } $event->predicates = $data; return true; } }
private function filterProperties($properties) { $uriToFilter = array(); $filteredProperties = array(); if ($this->_privateConfig->filterhidden) { $store = $this->_owApp->erfurt->getStore(); //query for hidden properties $query = new Erfurt_Sparql_SimpleQuery(); $query->setProloguePart('PREFIX sysont: <http://ns.ontowiki.net/SysOnt/> SELECT ?uri')->setWherePart('WHERE {?uri sysont:hidden \'true\'.}'); $uriToFilter = $store->sparqlQuery($query); } if ($this->_privateConfig->filterlist) { //get properties to hide from privateconfig $toFilter = $this->_privateConfig->property->toArray(); foreach ($toFilter as $element) { array_push($uriToFilter, array('uri' => $element)); } } foreach ($properties as $property) { $toFilter = false; foreach ($uriToFilter as $element) { if ($element['uri'] == $property['uri']) { $toFilter = true; break; } } if (!$toFilter) { array_push($filteredProperties, $property); } } return $filteredProperties; }
public function onPropertiesActionData($event) { if ($this->_privateConfig->hide->property) { $store = Erfurt_App::getInstance()->getStore(); $config = Erfurt_App::getInstance()->getConfig(); $data = $event->predicates; foreach ($data as $graphUri => $predicates) { $query = new Erfurt_Sparql_SimpleQuery(); $query->setProloguePart('SELECT DISTINCT *')->addFrom((string) $graphUri)->setWherePart('WHERE { ?p <' . $this->_privateConfig->hide->property . '> ?o . }'); $results = $store->sparqlQuery($query); if (!empty($results)) { $publicPredicates = array(); foreach ($data as $element) { foreach ($element as $propertykey => $property) { $hide = false; foreach ($results as $result) { if ($result['p'] == $property['uri']) { $hide = true; break; } } if (!$hide) { $publicPredicates[$propertykey] = $property; } } } $data[$graphUri] = $publicPredicates; } } } $event->predicates = $data; return true; }
public function getContents() { $titleHelper = new OntoWiki_Model_TitleHelper($this->_owApp->selectedModel); $query = new Erfurt_Sparql_SimpleQuery(); $results = false; $_predicates = $this->_predicates; $properties = array(); $instances = array(); $url = new OntoWiki_Url(array('route' => 'properties'), array('r')); $titleHelper->addResources($_predicates, 'uri'); foreach ($_predicates as $predicate) { $predicateUri = $predicate['uri']; $url->setParam('r', $predicateUri, true); // create properties url for the relation $properties[$predicateUri]['uri'] = $predicateUri; $properties[$predicateUri]['url'] = (string) $url; $properties[$predicateUri]['title'] = $titleHelper->getTitle($predicateUri, $this->_lang); $query->resetInstance()->setProloguePart('SELECT DISTINCT ?uri')->setWherePart('WHERE { ?uri <' . $predicateUri . '> <' . (string) $this->_owApp->selectedResource . '> . FILTER (isURI(?uri)) }')->setLimit(OW_SHOW_MAX + 1); if ($subjects = $this->_owApp->selectedModel->sparqlQuery($query)) { $results = true; // has_more is used for the dots if (count($subjects) > OW_SHOW_MAX) { $properties[$predicateUri]['has_more'] = true; $subjects = array_splice($subjects, 0, OW_SHOW_MAX); } else { $properties[$predicateUri]['has_more'] = false; } $subjectTitleHelper = new OntoWiki_Model_TitleHelper($this->_owApp->selectedModel); $subjectTitleHelper->addResources($subjects, 'uri'); foreach ($subjects as $subject) { $subjectUri = $subject['uri']; $subject['title'] = $subjectTitleHelper->getTitle($subjectUri, $this->_lang); // set URL $url->setParam('r', $subjectUri, true); $subject['url'] = (string) $url; if (array_key_exists($predicateUri, $instances)) { if (!array_key_exists($subjectUri, $instances[$predicateUri])) { $instances[$predicateUri][$subjectUri] = $subject; } } else { $instances[$predicateUri] = array($subjectUri => $subject); } } } } $this->view->resource = $this->_owApp->selectedResource; $this->view->properties = $properties; $this->view->instances = $instances; if (!$results) { $this->view->message = 'No matches.'; } return $this->render('linkinghere'); }
public function shouldShow() { $query = new Erfurt_Sparql_SimpleQuery(); $query->setProloguePart('SELECT DISTINCT ?type')->setWherePart('WHERE {<' . (string) $this->_owApp->selectedResource . '> a ?type.}'); if ($results = $this->_owApp->selectedModel->sparqlQuery($query)) { foreach ($results as $result) { if (in_array('http://purl.org/ontology/bibo/Periodical', $result)) { return true; } } } return false; }
public function serializeResourceToString($resource, $graphUri, $pretty = false, $useAc = true, array $additional = array()) { require_once 'Erfurt/Sparql/SimpleQuery.php'; $query = new Erfurt_Sparql_SimpleQuery(); $query->setProloguePart('SELECT ?resourceUri ?p ?o'); $query->addFrom($graphUri); /* * Why not as subject? * Because serializeQueryResultToString() expects ?resourceUri to be bound. */ $query->setWherePart('WHERE { ?resourceUri ?p ?o . FILTER (sameTerm(?resourceUri, <' . $resource . '>))}'); $query->setOrderClause('?resourceUri ?p ?o'); return $this->serializeQueryResultToString($query, $graphUri, $pretty, $useAc); }
public function testResultHeadVarsHaveCorrectName() { $this->markTestNeedsDatabase(); $this->authenticateDbUser(); $store = Erfurt_App::getInstance()->getStore(); $sparql = Erfurt_Sparql_SimpleQuery::initWithString('SELECT ?s ?p ?o WHERE { ?s ?p ?o } LIMIT 10'); $result = $store->sparqlQuery($sparql, array('result_format' => 'extended')); $head = $result['head']; $this->assertEquals('s', $head['vars'][0]); $this->assertEquals('p', $head['vars'][1]); $this->assertEquals('o', $head['vars'][2]); }
public function serializeGraphToString($graphUri, $pretty = false, $useAc = true) { $triples = array(); $store = Erfurt_App::getInstance()->getStore(); require_once 'Erfurt/Sparql/SimpleQuery.php'; $sparql = new Erfurt_Sparql_SimpleQuery(); $sparql->setProloguePart('SELECT ?s ?p ?o'); $sparql->addFrom($graphUri); $sparql->setWherePart('WHERE { ?s ?p ?o }'); $sparql->setOrderClause('?s ?p ?o'); $sparql->setLimit(1000); $offset = 0; while (true) { $sparql->setOffset($offset); $result = $store->sparqlQuery($sparql, array('result_format' => 'extended', 'use_owl_imports' => false, 'use_additional_imports' => false, 'use_ac' => $useAc)); $counter = 0; foreach ($result['results']['bindings'] as $stm) { $s = $stm['s']['value']; $p = $stm['p']['value']; $o = $stm['o']; if (!isset($triples["{$s}"])) { $triples["{$s}"] = array(); } if (!isset($triples["{$s}"]["{$p}"])) { $triples["{$s}"]["{$p}"] = array(); } if ($o['type'] === 'typed-literal') { $triples["{$s}"]["{$p}"][] = array('type' => 'literal', 'value' => $o['value'], 'datatype' => $o['datatype']); } else { if ($o['type'] === 'typed-literal') { $oArray = array('type' => 'literal', 'value' => $o['value']); if (isset($o['xml:lang'])) { $oArray['lang'] = $o['xml:lang']; } $triples["{$s}"]["{$p}"][] = $oArray; } else { $triples["{$s}"]["{$p}"][] = array('type' => $o['type'], 'value' => $o['value']); } } $counter++; } if ($counter < 1000) { break; } $offset += 1000; } return json_encode($triples); }
/** * @desc performs a sparql query on the model * * @param string modelIri * @param string query * * @return string */ public function sparql($modelIri, $query = null) { if (null === $query) { $query = 'SELECT DISTINCT ?resource ?label WHERE {?resource rdfs:label ?label} LIMIT 5'; } $model = $this->_store->getModel($modelIri); $prefixes = $model->getNamespacePrefixes(); foreach ($prefixes as $prefix => $namespace) { $query = 'PREFIX ' . $prefix . ': <' . $namespace . '>' . PHP_EOL . $query; } require_once 'Erfurt/Sparql/SimpleQuery.php'; $query = Erfurt_Sparql_SimpleQuery::initWithString($query); return $model->sparqlQuery($query); }
public function onPropertiesActionTemplate($event) { $store = Erfurt_App::getInstance()->getStore(); $config = Erfurt_App::getInstance()->getConfig(); $model = $event->model; $graph = $event->graph; $resource = $event->resource; $predicates = $model->getPredicates(); $description = $resource->getDescription(); if ($this->_privateConfig->template->restrictive) { foreach ($description as $resource) { if (isset($resource[EF_RDF_TYPE])) { $type = $resource[EF_RDF_TYPE][0]['value']; } else { return false; } } $query = new Erfurt_Sparql_SimpleQuery(); $query->setProloguePart('PREFIX erm: <http://vocab.ub.uni-leipzig.de/bibrm/> SELECT DISTINCT ?uri'); $query->addFrom((string) $event->graph); $query->setWherePart('{?template a <' . $this->_template . '> . ?template erm:providesProperty ?uri . ?template erm:bindsClass <' . $type . '> . } '); $query->setLimit('20'); $result = $store->sparqlQuery($query); } if (!empty($result)) { // flatten Array and flip keys with values to use array_intersect_key $result = array_map(function ($x) { return array_flip($x); }, $result); // FIXME Find a method to add standard properties which will be // displayed by default $result[] = array(EF_RDF_TYPE => "bla"); $result[] = array(EF_RDFS_LABEL => "bla"); $newResult = array(); foreach ($result as $newKey => $newValue) { $newResult = array_merge($newResult, $newValue); } $matched = array_intersect_key($predicates[(string) $graph], $newResult); $matched = array((string) $graph => $matched); $event->predicates = $matched; } else { return false; } return true; }
/** * Returns the queries for the title properties of all resources. * * @return Erfurt_Sparql_SimpleQuery */ public function getTitleQueries() { $currentQuery = null; $queries = array(); $select = 'SELECT DISTINCT ?property ?value'; if ($this->_resources === null) { return array(); } foreach ($this->_resources as $resourceUri) { $where = 'WHERE {' . $this->_getTitleWhere($resourceUri) . '}'; $currentQuery = new Erfurt_Sparql_SimpleQuery(); $currentQuery->setProloguePart($select)->setWherePart($where); $queries[$resourceUri] = $currentQuery; } return $queries; }
public function testRenameResource() { $this->markTestNeedsDatabase(); $this->authenticateDbUser(); $modelUri = 'http://example.org/renameTest/'; $store = Erfurt_App::getInstance()->getStore(); $graphs = array(); foreach (array('old', 'new') as $diff) { $graphs[$diff] = array($modelUri => array(EF_RDF_TYPE => array(array('value' => EF_OWL_ONTOLOGY, 'type' => 'uri'))), $modelUri . $diff => array($modelUri . $diff => array(array('value' => $modelUri . $diff, 'type' => 'uri')), $modelUri . 'p1' => array(array('value' => $modelUri . $diff, 'type' => 'uri')), $modelUri . 'p2' => array(array('value' => $modelUri . $diff, 'type' => 'uri'), array('value' => $modelUri . 'old', 'type' => 'literal'), array('value' => $modelUri . 'o2', 'type' => 'uri')), 'lang' => array(array('value' => 'LANG', 'type' => 'literal', 'lang' => 'en'), array('value' => 'LANG', 'type' => 'literal', 'lang' => 'de'), array('value' => 'LANG', 'type' => 'literal', 'lang' => 'mn')), 'type' => array(array('value' => 'TYPE', 'type' => 'literal', 'datatype' => 'http://www.w3.org/2001/XMLSchema#string'))), $modelUri . 's3' => array($modelUri . $diff => array(array('value' => $modelUri . 'o3', 'type' => 'uri'))), $modelUri . 's4' => array($modelUri . 'p4' => array(array('value' => $modelUri . 'o4', 'type' => 'uri')))); } $model = $store->getNewModel($modelUri); $model->addMultipleStatements($graphs['new']); $query = Erfurt_Sparql_SimpleQuery::initWithString('SELECT ?s ?p ?o FROM <' . $modelUri . '> WHERE { ?s ?p ?o . }'); $result = $store->sparqlQuery($query, array('result_format' => 'extended')); $expected = array(); foreach ($result['results']['bindings'] as $statement) { $expected[$statement['s']['value']][$statement['p']['value']][] = $statement['o']; } $store->deleteModel($modelUri); $model = $store->getNewModel($modelUri); $model->addMultipleStatements($graphs['old']); $model->renameResource($modelUri . 'old', $modelUri . 'new'); $query = Erfurt_Sparql_SimpleQuery::initWithString('SELECT ?s ?p ?o FROM <' . $modelUri . '> WHERE { ?s ?p ?o . }'); $result = $store->sparqlQuery($query, array('result_format' => 'extended')); $got = array(); foreach ($result['results']['bindings'] as $statement) { $got[$statement['s']['value']][$statement['p']['value']][] = $statement['o']; } $this->assertStatementsEqual($expected, $got, 'Graph after resource renaming'); }
private function typeAllowed() { if ($this->_privateConfig->ratingClass) { $classArray = $this->_privateConfig->ratingClass->toArray(); $store = $this->_owApp->erfurt->getStore(); $resource = $this->_owApp->selectedResource; $query = new Erfurt_Sparql_SimpleQuery(); $query->setProloguePart('SELECT *')->setWherePart('WHERE { <' . $resource . '> <' . EF_RDF_TYPE . '> ?type }'); $results = $store->sparqlQuery($query); if (in_array($results[0]['type'], $classArray)) { return true; } else { return false; } } else { return true; } }
public function sparqlQuery($query, $options = array()) { // Make sure, we only query for configured graphs... $q = Erfurt_Sparql_SimpleQuery::initWithString((string) $query); $from = $q->getFrom(); $newFrom = array(); foreach ($from as $f) { if (isset($this->_configuredGraphs[$f])) { $newFrom[] = $f; } } if (count($newFrom) === 0) { return array(); } $q->setFrom($newFrom); $resultform = isset($options[Erfurt_Store::RESULTFORMAT]) ? $options[Erfurt_Store::RESULTFORMAT] : Erfurt_Store::RESULTFORMAT_PLAIN; $url = $this->_serviceUrl . '?query=' . urlencode((string) $q); $client = $this->_getHttpClient($url, array('maxredirects' => 10, 'timeout' => 2000)); if (null !== $this->_username) { if (substr($url, 0, 7) === 'http://') { // We need SSL here! $url = 'https://' . substr($url, 7); } $client->setAuth($this->_username, $this->_password); } $client->setHeaders('Accept', 'application/sparql-results+xml'); $response = $client->request(); if ($response->getStatus() === 200) { // OK if ($response->getBody() === '') { $result = array('head' => array(), 'results' => array('bindings' => array())); } else { $result = $this->_parseSparqlXmlResults($response->getBody()); } } else { $result = array('head' => array(), 'results' => array('bindings' => array())); } switch ($resultform) { case 'plain': $newResult = array(); //could be an ask query if (empty($result['results']['bindings']) && !empty($result['boolean'])) { return $result; } else { foreach ($result['results']['bindings'] as $row) { $newRow = array(); foreach ($row as $var => $value) { // TODO datatype and lang support $newRow[$var] = $value['value']; } $newResult[] = $newRow; } } return $newResult; case 'extended': return $result; break; case 'json': return json_encode($result); break; default: throw new Exception('Result form ' . $resultform . ' not supported yet.'); } }
/** @see Erfurt_Store_Adapter_Interface */ public function countWhereMatches($graphIris, $whereSpec, $countSpec, $distinct = false) { $query = new Erfurt_Sparql_SimpleQuery(); if (!$distinct) { $query->setProloguePart("COUNT DISTINCT {$countSpec}"); // old way: distinct has no effect !!! } else { $query->setProloguePart("COUNT-DISTINCT {$countSpec}"); // i made a (unccol) hack to fix this, the "-" ist there because i didnt want to change tokenization } $query->setFrom($graphIris)->setWherePart($whereSpec); $result = $this->sparqlQuery($query); if ($result) { return $result; } return 0; }
/** * Calculates the transitive closure for a given property and a set of starting nodes. * * @see getTransitiveClosure */ private function _getTransitiveClosure($modelIri, $property, $startResources, $inverse, $maxDepth) { $closure = array(); $classes = $startResources; $usedClasses = array(); $i = 0; $from = ''; foreach ($this->getImportsClosure($modelIri) as $import) { $from .= 'FROM <' . $import . '>' . PHP_EOL; } while (++$i <= $maxDepth) { $where = $inverse ? '?child <' . $property . '> ?parent.' : '?parent <' . $property . '> ?child.'; $subSparql = 'SELECT ?parent ?child FROM <' . $modelIri . '>' . PHP_EOL . $from . ' WHERE { ' . $where . ' OPTIONAL {?child <http://ns.ontowiki.net/SysOnt/order> ?order} FILTER ( ?parent IN (<' . implode('>, <', $classes) . '>) ) } ORDER BY ASC(?order)'; $subSparql = Erfurt_Sparql_SimpleQuery::initWithString($subSparql); // get sub items $result = $this->_backendAdapter->sparqlQuery($subSparql, array(Erfurt_Store::RESULTFORMAT => Erfurt_Store::RESULTFORMAT_PLAIN)); // break on first empty result if (empty($result)) { break; } $classes = array(); foreach ($result as $row) { // $key = $inverse ? $row['child'] : $row['parent']; $key = $inverse ? $row['child'] : $row['parent']; $closure[$key] = array('node' => $inverse ? $row['child'] : $row['parent'], 'parent' => $inverse ? $row['parent'] : $row['child'], 'depth' => $i); $classes[] = $row['child']; } $usedClasses = array_merge($usedClasses, $classes); } // prepare start resources inclusion $merger = array(); $startResources = array_merge($startResources, $merger); foreach ($startResources as $startUri) { $merger[(string) $startUri] = array('node' => $startUri, 'parent' => null, 'depth' => 0); } // add all parent classes if (false === $inverse) { foreach ($usedClasses as $c) { if (false === isset($merger[$c])) { $merger[$c] = array('node' => $c, 'parent' => null, 'depth' => 0); } } } // merge in start resources $closure = array_merge($merger, $closure); return $closure; }
/** * rate a resource */ public function rateAction() { if (!$this->_owApp->selectedModel->isEditable()) { require_once 'Erfurt/Ac/Exception.php'; throw new Erfurt_Ac_Exception("Access control violation. Model not editable."); } $user = $this->_owApp->getUser()->getUri(); $date = date('rating'); // xsd:datetime $resource = (string) $this->_owApp->selectedResource; $aboutProperty = $this->_privateConfig->about->property; $creatorProperty = $this->_privateConfig->creator->property; $ratingType = $this->_privateConfig->rating->type; $noteProperty = $this->_privateConfig->note->property; $dateProperty = $this->_privateConfig->date->property; //get rating Value $ratingValue = $this->getParam('rating'); if (!empty($ratingValue)) { $query = new Erfurt_Sparql_SimpleQuery(); $model = OntoWiki::getInstance()->selectedModel; // $store = $this->_erfurt->getStore(); //query rating and creator of rating $query->setProloguePart(' prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> prefix ns0: <http://rdfs.org/sioc/ns#> prefix ns1: <http://rdfs.org/sioc/types#> SELECT *')->setWherePart('where { ?rating rdf:type ns1:Poll. ?rating ns0:about <' . $this->_owApp->selectedResource . '>. ?rating ns0:has_creator ?creator}'); $results = $model->sparqlQuery($query); if ($results) { $creatorExists = false; foreach ($results as $result) { if ((string) $user == $result['creator']) { $creatorExists = true; $ratingNote = $result['rating']; break; } } if ($creatorExists) { $this->_owApp->selectedModel->deleteMatchingStatements($ratingNote, null, null, array()); } } // make URI $ratingNoteUri = $this->_owApp->selectedModel->createResourceUri('Rating'); // preparing versioning $versioning = $this->_erfurt->getVersioning(); $actionSpec = array(); $actionSpec['type'] = 110; $actionSpec['modeluri'] = (string) $this->_owApp->selectedModel; $actionSpec['resourceuri'] = $ratingNoteUri; $versioning->startAction($actionSpec); // create namespaces (todo: this should be based on used properties) $this->_owApp->selectedModel->getNamespacePrefix('http://rdfs.org/sioc/ns#'); $this->_owApp->selectedModel->getNamespacePrefix('http://rdfs.org/sioc/types#'); $this->_owApp->selectedModel->getNamespacePrefix('http://localhost/OntoWiki/Config/'); // insert rating $this->_owApp->selectedModel->addStatement($ratingNoteUri, $aboutProperty, array('value' => $resource, 'type' => 'uri')); $this->_owApp->selectedModel->addStatement($ratingNoteUri, EF_RDF_TYPE, array('value' => $ratingType, 'type' => 'uri')); $this->_owApp->selectedModel->addStatement($ratingNoteUri, $creatorProperty, array('value' => (string) $user, 'type' => 'uri')); $this->_owApp->selectedModel->addStatement($ratingNoteUri, $dateProperty, array('value' => $date, 'type' => 'literal', 'datatype' => EF_XSD_NS . 'dateTime')); $this->_owApp->selectedModel->addStatement($ratingNoteUri, $noteProperty, array('value' => $ratingValue, 'type' => 'literal')); $cache = $this->_erfurt->getQueryCache(); $ret = $cache->cleanUpCache(array('mode' => 'uninstall')); } // stop Action $versioning->endAction(); }
/** * Get all observations which fits to given DSD, DS and selected compontents. * @param $dataSetUrl URL of a data set * @param $selectedComponentDimensions */ public function getObservations($dataSetUrl, $selectedComponentDimensions = array()) { // generate unique hash using given result and model uri $objectId = md5($this->_model->getModelIri() . $dataSetUrl . json_encode($selectedComponentDimensions)); // check there is already a cached object for this hash $result = $this->_objectCache->load($objectId); if (false === $result) { $this->_queryCache->startTransaction($objectId); /** * Fill SimpleQuery object with live! */ $queryObject = new Erfurt_Sparql_SimpleQuery(); // SELECT $queryObject->setProloguePart('SELECT ?s ?p ?o'); // FROM $queryObject->setFrom(array($this->_model->getModelIri())); // WHERE $where = 'WHERE { ' . "\n" . ' ?s ?p ?o .' . "\n" . ' ?s <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <' . DataCube_UriOf::Observation . '> .' . "\n" . ' ?s <' . DataCube_UriOf::DataSetRelation . '> <' . $dataSetUrl . '> .' . "\n"; // Set selected properties (e.g. ?s <http://data.lod2.eu/scoreboard/properties/year> ?d0 .) $i = 0; foreach ($selectedComponentDimensions as $dimension) { if (0 < count($dimension['__cv_elements'])) { $where .= ' ?s <' . $dimension[DataCube_UriOf::Dimension] . '> ?d' . $i++ . ' .' . "\n"; } } // Set FILTER // e.g.: FILTER (?d1 = "2003" OR ?d1 = "2001" OR ?d1 = "2002") // e.g. 2: FILTER ( ?d0 = <http://data.lod2.eu/scoreboard/indicators/bb_fcov_RURAL_POP__pop> OR // ?d0 = <http://data.lod2.eu/scoreboard/indicators/bb_lines_TOTAL_FBB_nbr_lines> ) $i = 0; foreach ($selectedComponentDimensions as $dimension) { $dimensionElements = $dimension['__cv_elements']; if (0 < count($dimensionElements)) { $filter = array(); foreach ($dimensionElements as $elementUri => $element) { // If __cv_uri is set and an URL if (true == Erfurt_Uri::check($element['__cv_uri'])) { $value = '<' . $element['__cv_uri'] . '>'; $filter[] = ' ?d' . $i . ' = ' . $value . ' '; } else { $value = '"' . $element['__cv_niceLabel'] . '"'; $filter[] = ' xsd:string(?d' . $i . ') = xsd:string(' . $value . ') '; } } $i++; $where .= ' FILTER (' . implode('OR', $filter) . ') ' . "\n"; } } $where .= '}'; $queryObject->setWherePart($where); $result = $this->_model->sparqlQuery((string) $queryObject); // generate associative array out of given observation result $result = $this->generateAssocSPOArrayFromSparqlResult($result, 's', 'p', 'o'); // limit the number of observations $result = array_slice($result, 0, 250); // enrich data with CubeViz sugar $result = $this->enrichResult($result, false); // close the object cache transaction $this->_queryCache->endTransaction($objectId); // save the result value in the object cache $this->_objectCache->save($result, $objectId); } return $result; }
public function getMultiList() { $this->store = $this->_owApp->erfurt->getStore(); $this->model = $this->_owApp->selectedModel; /* prepare schema elements */ // TODO: This should be used from the CommunityController $aboutProperty = $this->_privateConfig->about->property; $creatorProperty = $this->_privateConfig->creator->property; $commentType = $this->_privateConfig->comment->type; $contentProperty = $this->_privateConfig->content->property; $dateProperty = $this->_privateConfig->date->property; $realLimit = $this->_privateConfig->limit + 1; // used for query to check for "more" // get the latest comments $commentSparql = 'SELECT DISTINCT ?resource ?author ?comment ?content ?date #?alabel WHERE { ?comment <' . $aboutProperty . '> ?resource. ?comment a <' . $commentType . '>. ?comment <' . $creatorProperty . '> ?author. ?comment <' . $contentProperty . '> ?content. ?comment <' . $dateProperty . '> ?date. } ORDER BY DESC(?date) LIMIT ' . $realLimit; $query = Erfurt_Sparql_SimpleQuery::initWithString($commentSparql); return $this->model->sparqlQuery($query); }
/** * Returns all existing sync configurations. * * @return array|bool */ private function _listSyncConfigs() { if (null === $this->_syncConfigListCache) { $store = Erfurt_App::getInstance()->getStore(); require_once 'Erfurt/Sparql/SimpleQuery.php'; $query = new Erfurt_Sparql_SimpleQuery(); $query->setProloguePart('SELECT ?s ?p ?o'); $query->addFrom($this->_syncModelUri); $where = 'WHERE { ?s ?p ?o . ?s <' . EF_RDF_TYPE . '> <' . $this->_properties['syncConfigClass'] . '> . }'; $query->setWherePart($where); $result = $store->sparqlQuery($query, array('use_ac' => false)); if (count($result) === 0) { return false; } $retVal = array(); foreach ($result as $row) { if (!isset($retVal[$row['s']])) { $retVal[$row['s']] = array('uri' => $row['s']); } switch ($row['p']) { case $this->_properties['targetModel']: $retVal[$row['s']]['targetModel'] = $row['o']; break; case $this->_properties['syncResource']: $retVal[$row['s']]['syncResource'] = $row['o']; break; case $this->_properties['wrapperName']: $retVal[$row['s']]['wrapperName'] = $row['o']; break; case $this->_properties['lastSyncPayload']: $retVal[$row['s']]['lastSyncPayload'] = unserialize($row['o']); break; case $this->_properties['lastSyncDateTime']: $retVal[$row['s']]['lastSyncDateTime'] = $row['o']; break; case $this->_properties['syncQuery']: $retVal[$row['s']]['syncQuery'] = $row['o']; break; case $this->_properties['checkHasChanged']: $retVal[$row['s']]['checkHasChanged'] = (bool) $row['o']; break; } } $cacheVal = array(); foreach ($retVal as $s => $valueArray) { $hash = $this->_getHash($valueArray['syncResource'], $valueArray['wrapperName'], $valueArray['targetModel']); $cacheVal[$hash] = $valueArray; } $this->_syncConfigListCache = $cacheVal; } return $this->_syncConfigListCache; }
/** * Create the (context) menu for classes and fill it with its default entries */ private function _getClassMenu($resource = null) { $owApp = OntoWiki::getInstance(); $classMenu = new OntoWiki_Menu(); $query = Erfurt_Sparql_SimpleQuery::initWithString('SELECT * FROM <' . (string) $owApp->selectedModel . '> WHERE { <' . $resource . '> a ?type . }'); $results[] = $owApp->erfurt->getStore()->sparqlQuery($query); $query = Erfurt_Sparql_SimpleQuery::initWithString('SELECT * FROM <' . (string) $owApp->selectedModel . '> WHERE { ?inst a <' . $resource . '> . } LIMIT 2'); if (count($owApp->erfurt->getStore()->sparqlQuery($query)) > 0) { $hasInstances = true; } else { $hasInstances = false; } $typeArray = array(); foreach ($results[0] as $row) { $typeArray[] = $row['type']; } if (in_array(EF_RDFS_CLASS, $typeArray) || in_array(EF_OWL_CLASS, $typeArray) || $hasInstances) { $url = new OntoWiki_Url(array('action' => 'list'), array()); $url->setParam('class', $resource, false); $url->setParam('init', "true", true); $classMenu->appendEntry('List Instances', (string) $url); // add class menu entries if ($owApp->erfurt->getAc()->isModelAllowed('edit', $owApp->selectedModel)) { $classMenu->appendEntry('Create Instance', "javascript:createInstanceFromClassURI('{$resource}');"); } } return $classMenu; }
protected function _buildQuery($setup, $forImplicit = false) { if (isset($setup->config->query->deeper) && isset($setup->state->parent)) { //$replace = ; $queryString = str_replace("%resource%", $setup->state->parent, $setup->config->query->deeper); $query = Erfurt_Sparql_SimpleQuery::initWithString($queryString); } else { $query = new Erfurt_Sparql_Query2(); $query->addElements(NavigationHelper::getSearchTriples($setup, $forImplicit, $this->_config->store->backend)); //$query->setCountStar(true); $query->setDistinct(true); $query->addProjectionVar(new Erfurt_Sparql_Query2_Var('resourceUri')); //$query->addProjectionVar(new Erfurt_Sparql_Query2_Var('subResourceUri')); // set to _limit+1, so we can see if there are more than $_limit entries //$query->setLimit($this->_limit + 1); } // sorting if (isset($setup->state->sorting)) { $query->getOrder()->add(new Erfurt_Sparql_Query2_Var('sortRes'), "ASC"); } elseif (isset($setup->config->ordering->relation)) { // set ordering $orderVar = new Erfurt_Sparql_Query2_Var('order'); $query->getWhere()->addElement(new Erfurt_Sparql_Query2_OptionalGraphPattern(array(new Erfurt_Sparql_Query2_Triple(new Erfurt_Sparql_Query2_Var('resourceUri'), new Erfurt_Sparql_Query2_IriRef($setup->config->ordering->relation), $orderVar)))); $query->getOrder()->add($orderVar, $setup->config->ordering->modifier); } // set offset if (isset($setup->state->offset) && $setup->state->lastEvent == 'more') { $query->setLimit($this->_limit + $setup->state->offset + 1); } else { $query->setLimit($this->_limit + 1); } return $query; }
public function sparqlQuery($query, $options = array()) { $resultform = isset($options[Erfurt_Store::RESULTFORMAT]) ? $options[Erfurt_Store::RESULTFORMAT] : Erfurt_Store::RESULTFORMAT_PLAIN; if (!$query instanceof Erfurt_Sparql_SimpleQuery) { $query = Erfurt_Sparql_SimpleQuery::initWithString((string) $query); } $limit = $query->getLimit(); $offset = $query->getOffset(); if (strpos(strtolower($query->getProloguePart()), 'distinct') !== false) { $isDistinct = true; } else { $isDistinct = false; } $queryBackends = array(); foreach ($query->getFrom() as $from) { if (isset($this->_configuredGraphs[$from])) { if (isset($queryBackends[$this->_configuredGraphs[$from]])) { $queryBackends[$this->_configuredGraphs[$from]][] = $from; } else { $queryBackends[$this->_configuredGraphs[$from]] = array($from); } } } foreach ($query->getFromNamed() as $fromNamed) { if (isset($this->_configuredGraphs[$fromNamed])) { if (isset($queryBackends[$this->_configuredGraphs[$fromNamed]])) { $queryBackends[$this->_configuredGraphs[$fromNamed]][] = $fromNamed; } else { $queryBackends[$this->_configuredGraphs[$fromNamed]] = array($fromNamed); } } } // Special care if offset is given and grater zero if (null !== $offset && $offset > 0) { $currentCount = 0; $newBackends = array(); foreach ($queryBackends as $backendId => $graphUris) { $tempQuery = clone $query; if ($isDistinct) { $tempQuery->setProloguePart('COUNT DISTINCT'); } else { $tempQuery->setProloguePart('COUNT'); } $tempQuery->setFrom($graphUris); $tempQuery->setOffset(null); $tempQuery->setLimit(null); $count = $this->_backends[$backendId]->sparqlQuery($tempQuery); $currentCount += $count; if ($offset < $currentCount) { $newBackends[$backendId] = $graphUris; if (null !== $limit && $currentCount >= $offset + $limit) { break; } } else { $offset = $offset - $count; if ($offset < 0) { $offset = 0; } } } $queryBackends = $newBackends; } $result = array(); $currentCount = 0; foreach ($queryBackends as $backendId => $graphUris) { $tempQuery = clone $query; $tempQuery->setFrom($graphUris); $tempQuery->setOffset($offset); $tempQuery->setLimit($limit); $offset = null; $tempResult = $this->_backends[$backendId]->sparqlQuery($tempQuery, $resultform); if (null !== $limit) { if ($resultform === 'plain') { $limit = $limit - count($tempResult); if ($limit < 0) { $limit = 0; } } else { $limit = $limit - count($tempResult['result']['bindings']); if ($limit < 0) { $limit = 0; } } } if ($resultform === 'plain') { $result = array_merge($result, $tempResult); } else { if (empty($result)) { $result['head'] = $tempResult['head']; $result['result']['bindings'] = $tempResult['bindings']; } else { $result['result']['bindings'] = array_merge($result['bindings'], $tempResult['bindings']); } } } // TODO Handle DISTINCT return $result; }
/** * @desc performs a sparql query on the store * * @param string query * * @return string */ public function sparql($query = 'SELECT ?resource ?label WHERE {?resource ?prop ?label} LIMIT 5') { require_once 'Erfurt/Sparql/SimpleQuery.php'; $query = Erfurt_Sparql_SimpleQuery::initWithString($query); return $this->_store->sparqlQuery($query); }
public function onIsDispatchable($event) { if (!$event->getValue()) { // linked data plug-in returned false --> 404 $config = $this->getSiteConfig(); if (isset($config['error'])) { $errorResource = $config['error']; if (isset($config['model'])) { $siteGraph = $config['model']; $store = OntoWiki::getInstance()->erfurt->getStore(); $siteModel = $store->getModel($siteGraph); $sparql = sprintf('ASK FROM <%s> WHERE {<%s> ?p ?o .}', $siteGraph, $errorResource); $query = Erfurt_Sparql_SimpleQuery::initWithString($sparql); $result = $store->sparqlAsk($query); if (true === $result) { OntoWiki::getInstance()->selectedModel = $siteModel; OntoWiki::getInstance()->selectedResource = new OntoWiki_Resource($errorResource, $siteModel); $request = Zend_Controller_Front::getInstance()->getRequest(); $request->setControllerName('site'); $request->setActionName($this->_privateConfig->defaultSite); return true; } else { $response = Zend_Controller_Front::getInstance()->getResponse(); $response->setRawHeader('HTTP/1.0 404 Not Found'); } } } return false; /* * TODO: * if error is 404 * 1. set 404 header * if error resource exists in site model * 2. load site model * 3. set error resource as current resource * 4. render site as normal * fi * else * 2. render default 404 template */ // $errorHandler = Zend_Controller_Front::getInstance()->getPlugin('Zend_Controller_Plugin_ErrorHandler'); // if ($errorHandler) { // $errorHandler->setErrorHandler(array( // 'controller' => 'site', // 'action' => 'error' // )); // } } }
/** * Deletes one or more resources denoted by param 'r' * TODO: This should be done by a evolution pattern in the future */ public function deleteAction() { $this->view->clearModuleCache(); $this->_helper->viewRenderer->setNoRender(); $this->_helper->layout->disableLayout(); $store = $this->_erfurt->getStore(); $model = $this->_owApp->selectedModel; $modelIri = (string) $model; $redirect = $this->_request->getParam('redirect', $this->_config->urlBase); if (isset($this->_request->r)) { $resources = $this->_request->getParam('r', array()); } else { throw new OntoWiki_Exception('Missing parameter r!'); } if (!is_array($resources)) { $resources = array($resources); } // get versioning $versioning = $this->_erfurt->getVersioning(); $count = 0; if ($this->_erfurt->getAc()->isModelAllowed('edit', $modelIri)) { foreach ($resources as $resource) { // if we have only a nice uri, fill to full uri if (Zend_Uri::check($resource) == false) { // check for namespace if (strstr($resource, ':')) { $resource = OntoWiki_Utils::expandNamespace($resource); } else { $resource = $model->getBaseIri() . $resource; } } // action spec for versioning $actionSpec = array(); $actionSpec['type'] = 130; $actionSpec['modeluri'] = $modelIri; $actionSpec['resourceuri'] = $resource; // starting action $versioning->startAction($actionSpec); $stmtArray = array(); // query for all triples to delete them $sparqlQuery = new Erfurt_Sparql_SimpleQuery(); $sparqlQuery->setProloguePart('SELECT ?p, ?o'); $sparqlQuery->addFrom($modelIri); $sparqlQuery->setWherePart('{ <' . $resource . '> ?p ?o . }'); $result = $store->sparqlQuery($sparqlQuery, array('result_format' => 'extended')); // transform them to statement array to be compatible with store methods foreach ($result['results']['bindings'] as $stmt) { $stmtArray[$resource][$stmt['p']['value']][] = $stmt['o']; } $store->deleteMultipleStatements($modelIri, $stmtArray); // stopping action $versioning->endAction(); $count++; } $message = $count . ' resource' . ($count != 1 ? 's' : '') . ($count ? ' successfully' : '') . ' deleted.'; $this->_owApp->appendMessage(new OntoWiki_Message($message, OntoWiki_Message::SUCCESS)); } else { $message = 'not allowed.'; $this->_owApp->appendMessage(new OntoWiki_Message($message, OntoWiki_Message::WARNING)); } $event = new Erfurt_Event('onDeleteResources'); $event->resourceArray = $resources; $event->modelUri = $modelIri; $event->trigger(); $this->_redirect($redirect, array('code' => 302)); }
private function _getTypes() { $typesInferred = array(); $query = new Erfurt_Sparql_SimpleQuery(); $query->setProloguePart('SELECT DISTINCT ?uri')->setWherePart('WHERE { <' . (string) $this->_owApp->selectedResource . '> a ?uri. ?similar a ?uri. FILTER isUri(?uri) }'); if ($result = $this->_owApp->selectedModel->sparqlQuery($query)) { $types = array(); foreach ($result as $row) { array_push($types, $row['uri']); } $typesInferred = $this->_store->getTransitiveClosure((string) $this->_owApp->selectedModel, EF_RDFS_SUBCLASSOF, $types, false); } return array_keys($typesInferred); }
/** * Filters a result regarding the configured sparql query. * * @param array $result * @param string $uri * @param string $wrapperName * @param string $modelUri * * @return array */ private function _filterResult($result, $uri, $wrapperName, $modelUri) { $store = Erfurt_App::getInstance()->getStore(); $syncConfig = $this->_getSyncConfig($uri, $wrapperName, $modelUri); if (!is_array($syncConfig) || count($syncConfig) === 0) { return array(); } $syncConfig = $syncConfig[0]; // TODO We need support for in-memory models... this is a workaround $tempModelUri = $this->_syncModelHelperBase . md5($uri . $wrapperName . $modelUri . time()); $tempModel = $store->getNewModel($tempModelUri, '', 'rdf', false); $store->addMultipleStatements($tempModelUri, $result); $simpleQuery = Erfurt_Sparql_SimpleQuery::initWithString($syncConfig['syncQuery']); $simpleQuery->addFrom($tempModelUri); $sparqlResult = $store->sparqlQuery($simpleQuery, array('result_format' => 'extended', 'use_ac' => false)); $store->deleteModel($tempModelUri); $retVal = array(); foreach ($sparqlResult['results']['bindings'] as $row) { if (!isset($retVal[$row['s']['value']])) { $retVal[$row['s']['value']] = array(); } if (!isset($retVal[$row['s']['value']][$row['p']['value']])) { $retVal[$row['s']['value']][$row['p']['value']] = array(); } $oArray = array('value' => $row['o']['value']); if ($row['o']['type'] === 'typed-literal') { $oArray['type'] = 'literal'; $oArray['dataytpe'] = $row['o']['datatype']; } else { $oArray['type'] = $row['o']['type']; } if (isset($row['o']['xml:lang'])) { $oArray['lang'] = $row['o']['xml:lang']; } $retVal[$row['s']['value']][$row['p']['value']][] = $oArray; } return $retVal; }
private function _matchGraphAndUri($uri) { $graph = null; $actualUri = null; $store = null; try { $store = OntoWiki::getInstance()->erfurt->getStore(); } catch (Exception $e) { // if we can't get the store, we do nothing return; } if ((bool) $this->_privateConfig->fuzzyMatch === true) { // Remove trailing slashes $uri = rtrim($uri, '/'); // Match case-insensitive and optionally with trailing slashes $query = sprintf('SELECT DISTINCT ?uri WHERE {?uri ?p ?o . FILTER (regex(str(?uri), "^%s/*$", "i"))}', $uri); $queryObj = Erfurt_Sparql_SimpleQuery::initWithString($query); $result = $store->sparqlQuery($queryObj); $first = current($result); if (isset($first['uri'])) { $actualUri = $first['uri']; } } else { $actualUri = $uri; } $graphs = $store->getReadableGraphsUsingResource($actualUri, true); return array($graphs[0], $actualUri); }
/** * Checks the local database, whether user exists */ protected function _checkWebId($webId) { $retVal = array('userUri' => false, 'denyLogin' => false); // Query the store. require_once 'Erfurt/Sparql/SimpleQuery.php'; $query = new Erfurt_Sparql_SimpleQuery(); $query->setProloguePart('SELECT ?s ?p ?o'); $query->addFrom($this->_acModelUri); $where = 'WHERE { ?s ?p ?o . ?s <' . EF_RDF_TYPE . '> <' . $this->_uris['user_class'] . "> .\n FILTER (sameTerm(?s, <{$webId}>))\n }"; $query->setWherePart($where); $result = $this->_store->sparqlQuery($query, array('use_ac' => false)); foreach ((array) $result as $row) { // Set user URI if ($retVal['userUri'] === false) { $retVal['userUri'] = $row['s']; } // Check predicates, whether needed. switch ($row['p']) { case $this->_uris['action_deny']: // if login is disallowed if ($row['o'] === $this->_uris['action_login']) { $retVal['denyLogin'] = true; } break; case EF_RDFS_LABEL: $retVal['userLabel'] = $row['o']; break; case $this->_uris['user_username']: $retVal['username'] = $row['o']; break; case $this->_uris['user_mail']: $retVal['email'] = $row['o']; default: // Ignore all other statements. } } return $retVal; }