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]);
 }
 /**
  * @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);
 }
Esempio n. 3
0
 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;
 }
Esempio n. 4
0
 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');
 }
Esempio n. 5
0
 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.');
     }
 }
 /**
  * @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);
 }
Esempio n. 7
0
 /**
  * Performs an sparql query on the model using the stores sparqlQuery
  * method and returning the resultset
  * Returns a result depending on the query, e.g. an array or a boolean value.
  *
  * @param mixed $query   The query, as string or object (SimpleQuery or Query2)
  * @param array $options options array
  *
  * @return mixed
  **/
 public function sparqlQuery($query, $options = array())
 {
     $defaultOptions = array(Erfurt_Store::RESULTFORMAT => Erfurt_Store::RESULTFORMAT_PLAIN);
     $options = array_merge($defaultOptions, $options);
     // Do not allow disabling of ac here!
     $options[Erfurt_Store::USE_AC] = true;
     if (is_string($query)) {
         $query = Erfurt_Sparql_SimpleQuery::initWithString($query);
     }
     // restrict to this model
     if ($query instanceof Erfurt_Sparql_SimpleQuery) {
         $query->setFrom(array($this->_graphUri));
     } elseif ($query instanceof Erfurt_Sparql_Query2) {
         $query->setFroms(array($this->_graphUri));
     }
     return $this->getStore()->sparqlQuery($query, $options);
 }
 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);
 }
 /**
  * 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;
 }
 protected function _findStatementsForObjectsWithHashes($graphUri, $indexWithHashedObjects, $hashFunc = 'md5')
 {
     $queryOptions = array('result_format' => 'extended');
     $result = array();
     foreach ($indexWithHashedObjects as $subject => $predicates) {
         foreach ($predicates as $predicate => $hashedObjects) {
             $query = "SELECT ?o FROM <{$graphUri}> WHERE {<{$subject}> <{$predicate}> ?o .}";
             $queryObj = Erfurt_Sparql_SimpleQuery::initWithString($query);
             if ($queryResult = $this->_owApp->erfurt->getStore()->sparqlQuery($queryObj, $queryOptions)) {
                 $bindings = $queryResult['results']['bindings'];
                 for ($i = 0, $max = count($bindings); $i < $max; $i++) {
                     $currentObject = $bindings[$i]['o'];
                     $objectString = Erfurt_Utils::buildLiteralString($currentObject['value'], isset($currentObject['datatype']) ? $currentObject['datatype'] : null, isset($currentObject['xml:lang']) ? $currentObject['xml:lang'] : null);
                     $hash = $hashFunc($objectString);
                     if (in_array($hash, $hashedObjects)) {
                         // add current statement to result
                         if (!isset($result[$subject])) {
                             $result[$subject] = array();
                         }
                         if (!isset($result[$subject][$predicate])) {
                             $result[$subject][$predicate] = array();
                         }
                         $objectSpec = array('value' => $currentObject['value'], 'type' => str_replace('typed-', '', $currentObject['type']));
                         if (isset($currentObject['datatype'])) {
                             $objectSpec['datatype'] = $currentObject['datatype'];
                         } else {
                             if (isset($currentObject['xml:lang'])) {
                                 $objectSpec['lang'] = $currentObject['xml:lang'];
                             }
                         }
                         array_push($result[$subject][$predicate], $objectSpec);
                     }
                 }
             }
         }
     }
     return $result;
 }
Esempio n. 11
0
 public function testSparqlQueryWithSpecialCharUriIssue579()
 {
     $this->markTestNeedsDatabase();
     $this->authenticateDbUser();
     $store = Erfurt_App::getInstance()->getStore();
     $sparql = "SELECT ?p ?o WHERE { <http://umg.kurtisrandom.com/resource/genre-Children's> ?p ?o . }";
     $simpleQuery = Erfurt_Sparql_SimpleQuery::initWithString($sparql);
     $result = $store->sparqlQuery($simpleQuery);
     $this->assertTrue(is_array($result));
 }
Esempio n. 12
0
 public function infoAction()
 {
     OntoWiki::getInstance()->getNavigation()->disableNavigation();
     $this->_owApp->selectedResource = new OntoWiki_Resource($this->_request->getParam('m'), $this->_owApp->selectedModel);
     $store = $this->_owApp->erfurt->getStore();
     $graph = $this->_owApp->selectedModel;
     $resource = $this->_owApp->selectedResource;
     //$navigation = $this->_owApp->navigation;
     $translate = $this->_owApp->translate;
     $event = new Erfurt_Event('onPropertiesAction');
     $event->uri = (string) $resource;
     $event->graph = (string) $resource;
     $event->trigger();
     $windowTitle = $translate->_('Model info');
     $this->view->placeholder('main.window.title')->set($windowTitle);
     $title = $resource->getTitle($this->_owApp->getConfig()->languages->locale);
     $this->view->modelTitle = $title ? $title : OntoWiki_Utils::contractNamespace((string) $resource);
     $resourcesUrl = new OntoWiki_Url(array('route' => 'instances'), array());
     $resourcesUrl->init = true;
     $this->view->resourcesUrl = (string) $resourcesUrl;
     if (!empty($resource)) {
         $model = new OntoWiki_Model_Resource($store, $graph, (string) $resource);
         $values = $model->getValues();
         $predicates = $model->getPredicates();
         $titleHelper = new OntoWiki_Model_TitleHelper($graph);
         $graphs = array_keys($predicates);
         $titleHelper->addResources($graphs);
         $graphInfo = array();
         $editableFlags = array();
         foreach ($graphs as $g) {
             $graphInfo[$g] = $titleHelper->getTitle($g, $this->_config->languages->locale);
             $editableFlags[$g] = false;
         }
         $this->view->graphs = $graphInfo;
         $this->view->resourceIri = (string) $resource;
         $this->view->graphIri = $graph->getModelIri();
         $this->view->values = $values;
         $this->view->predicates = $predicates;
         $this->view->graphBaseIri = $graph->getBaseIri();
         $this->view->namespacePrefixes = $graph->getNamespacePrefixes();
         $this->view->editableFlags = $editableFlags;
         if (!is_array($this->view->namespacePrefixes)) {
             $this->view->namespacePrefixes = array();
         }
         if (!array_key_exists(OntoWiki_Utils::DEFAULT_BASE, $this->view->namespacePrefixes)) {
             $this->view->namespacePrefixes[OntoWiki_Utils::DEFAULT_BASE] = $graph->getBaseIri();
         }
         $infoUris = $this->_config->descriptionHelper->properties;
         //echo (string)$resource;
         if (count($values) > 0) {
             $query = 'ASK FROM <' . (string) $resource . '>' . ' WHERE {' . '     <' . (string) $resource . '> a <http://xmlns.com/foaf/0.1/PersonalProfileDocument>' . ' }';
             $q = Erfurt_Sparql_SimpleQuery::initWithString($query);
             if ($this->_owApp->extensionManager->isExtensionActive('foafprofileviewer') && $store->sparqlAsk($q) === true) {
                 $this->view->showFoafLink = true;
                 $this->view->foafLink = $this->_config->urlBase . 'foafprofileviewer/display';
             }
         }
         $this->view->infoPredicates = array();
         foreach ($infoUris as $infoUri) {
             if (isset($predicates[(string) $graph]) && array_key_exists($infoUri, $predicates[(string) $graph])) {
                 $this->view->infoPredicates[$infoUri] = $predicates[(string) $graph][$infoUri];
             }
         }
     }
     $this->addModuleContext('main.window.modelinfo');
 }
 /**
  * webservice to save a query
  */
 public function savequeryAction()
 {
     $this->_helper->layout()->disableLayout();
     $response = $this->getResponse();
     $response->setHeader('Content-Type', 'text/plain');
     $store = $this->_erfurt->getStore();
     $storeGraph = $this->_owApp->selectedModel;
     $graphUri = (string) $this->_owApp->selectedModel;
     $res = "json or desc missing";
     // checking for post data to save queries
     $params = $this->_request->getParams();
     if (isset($params['json']) && isset($params['json'])) {
         if ($this->_request->getParam('share') == "true") {
             // store in the model itself - everybody can see it
             $storeGraph = $this->_owApp->selectedModel;
         } else {
             //private db - should be configured so only the user can see it
             $storeGraph = $this->getUserQueryDB();
         }
         // checking whether any queries exist yet in this store
         $existingQueriesQuery = Erfurt_Sparql_SimpleQuery::initWithString('SELECT *
              WHERE {
                 ?query <' . EF_RDF_TYPE . '> <' . OntoWiki_Utils::expandNamespace($this->_privateConfig->saving->ClassUri) . '> .
              }');
         $existingQueries = $storeGraph->sparqlQuery($existingQueriesQuery);
         if (empty($existingQueries)) {
             //this is the first query
             $this->insertInitials($storeGraph);
         }
         $hash = md5($this->_request->getParam('json') . $this->_request->getParam('query'));
         $name = (string) $storeGraph . '#Query-' . $hash;
         // checking whether a query with same content (Where-Part) already exists (check by md5 sum)
         $existingDataQuery = Erfurt_Sparql_SimpleQuery::initWithString('SELECT *
              WHERE {
                  <' . $name . '> a <' . OntoWiki_Utils::expandNamespace($this->_privateConfig->saving->ClassUri) . '>
              }');
         $existingData = $storeGraph->sparqlQuery($existingDataQuery);
         if (empty($existingData)) {
             //such a query is not saved yet - lets save it
             $storeGraph->addStatement($name, EF_RDF_TYPE, array('value' => $this->_privateConfig->saving->ClassUri, 'type' => 'uri'), false);
             $storeGraph->addStatement($name, $this->_privateConfig->saving->ModelUri, array('value' => (string) $this->_owApp->selectedModel, 'type' => 'uri'), false);
             $storeGraph->addStatement($name, $this->_privateConfig->saving->NameUri, array('value' => $this->_request->getParam('name'), 'type' => 'literal'), false);
             $storeGraph->addStatement($name, $this->_privateConfig->saving->DateUri, array('value' => (string) date('c'), 'type' => 'literal', 'datatype' => OntoWiki_Utils::expandNamespace('xsd:dateTime')), false);
             $storeGraph->addStatement($name, OntoWiki_Utils::expandNamespace($this->_privateConfig->saving->NumViewsUri), array('value' => '1', 'type' => 'literal', 'datatype' => OntoWiki_Utils::expandNamespace('xsd:integer')), false);
             if ($this->_request->getParam('generator') == "gqb" || $this->_request->getParam('generator') == "qb") {
                 $storeGraph->addStatement($name, $this->_privateConfig->saving->JsonUri, array('value' => $this->_request->getParam('json'), 'type' => 'literal'), false);
             }
             $storeGraph->addStatement($name, $this->_privateConfig->saving->QueryUri, array('value' => $this->_request->getParam('query'), 'type' => 'literal'), false);
             $storeGraph->addStatement($name, $this->_privateConfig->saving->GeneratorUri, array('value' => $this->_request->getParam('generator'), 'type' => 'literal'), false);
             if ($this->_request->getParam('generator') == "gqb") {
                 $storeGraph->addStatement($name, $this->_privateConfig->saving->IdUri, array('value' => $this->_request->getParam('id'), 'type' => 'literal'), false);
                 $storeGraph->addStatement($name, $this->_privateConfig->saving->SelClassUri, array('value' => $this->_request->getParam('type'), 'type' => 'uri'), false);
                 $storeGraph->addStatement($name, $this->_privateConfig->saving->SelClassLabelUri, array('value' => $this->_request->getParam('typelabel'), 'type' => 'literal'), false);
             } else {
                 //TODO gqb uses id - qb not... needed?
                 $storeGraph->addStatement($name, $this->_privateConfig->saving->IdUri, array('value' => $hash, 'type' => 'literal'), false);
             }
             $user = $this->_erfurt->getAuth()->getIdentity();
             $userUri = $user->getUri();
             $storeGraph->addStatement($name, $this->_privateConfig->saving->CreatorUri, array('value' => $userUri, 'type' => 'uri'), false);
             $res = 'All OK';
         } else {
             $res = 'Save failed. (Query with same pattern exists)';
         }
     }
     $response->setBody($res);
 }
Esempio n. 14
0
 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'
         //     ));
         // }
     }
 }
 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;
 }
Esempio n. 16
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;
 }
Esempio n. 17
0
 /**
  * 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;
 }
Esempio n. 18
0
 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);
 }
Esempio n. 19
0
    public function testInitWithString3()
    {
        $queryString = '                PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>                PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
SELECT DISTINCT ?uri ?literal ?domain ?type                FROM <http://localhost/ontowiki/whostat>                WHERE {                    ?uri ?v1 ?literal .
                    {?v2 ?uri ?v3 .} UNION {?uri a rdf:Property .}                    OPTIONAL {?uri rdfs:domain ?domain .}
                                        OPTIONAL {<http://localhost/ontowiki/whostat> a ?type . }                    FILTER (                        isURI(?uri)                         && isLITERAL(?literal)                         && REGEX(?literal, "title", "i")                         && REGEX(?literal, "^.{1,50}$"))                }                LIMIT 5';
        $queryObject = Erfurt_Sparql_SimpleQuery::initWithString($queryString);
        $this->assertQueryEquals($queryString, (string) $queryObject);
    }