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 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 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;
 }
Beispiel #5
0
 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 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;
 }
Beispiel #7
0
 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);
 }
 /**
  * Constructor
  */
 public function init()
 {
     $query = new Erfurt_Sparql_SimpleQuery();
     $query->setProloguePart('SELECT DISTINCT ?subject ?uri')->setWherePart('WHERE {
                 ?subject ?uri <' . (string) $this->_owApp->selectedResource . '> .
             }')->setLimit(6);
     $result = $this->_owApp->selectedModel->sparqlQuery($query, array('result_format' => 'extended'));
     $_predicatesResult = array();
     if (isset($result['results']['bindings'])) {
         foreach ($result['results']['bindings'] as $row) {
             if ($row['subject']['type'] === 'uri') {
                 $_predicatesResult[] = array('uri' => $row['uri']['value']);
             }
         }
     }
     $this->_predicates = $_predicatesResult;
     // I removed the isURI(?subject) here as well as the limit, since the query is way faster
     // without filter! We kick out bnodes manually!
 }
 /**
  * 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));
 }
Beispiel #10
0
 /**
  * Fetches the for all users from the RDF user store.
  * 
  * Stores the user data in an internal array for alter reference.
  *
  * @return void
  */
 public function fetchDataForAllUsers()
 {
     $uris = $this->_getUris();
     require_once 'Erfurt/Sparql/SimpleQuery.php';
     $userSparql = new Erfurt_Sparql_SimpleQuery();
     $userSparql->setProloguePart('SELECT ?subject ?predicate ?object');
     $wherePart = 'WHERE { ?subject ?predicate ?object . ?subject <' . EF_RDF_TYPE . '> <' . $uris['user_class'] . '> }';
     $userSparql->setWherePart($wherePart);
     if ($result = $this->_sparql($userSparql)) {
         foreach ($result as $statement) {
             switch ($statement['predicate']) {
                 case $uris['action_deny']:
                     if ($statement['object'] == $uris['action_login']) {
                         $this->_users[$statement['subject']]['loginForbidden'] = true;
                     }
                     break;
                 case $uris['user_username']:
                     // save username
                     $this->_users[$statement['subject']]['userName'] = $statement['object'];
                     break;
                 case $uris['user_password']:
                     // save password
                     $this->_users[$statement['subject']]['userPassword'] = $statement['object'];
                     break;
                 case $uris['user_mail']:
                     // save e-mail
                     $this->_users[$statement['subject']]['userEmail'] = $statement['object'];
                     break;
                 default:
                     // ignore other statements
             }
         }
         $this->_userDataFetched = true;
     }
 }
Beispiel #11
0
 /**
  * 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;
 }
Beispiel #12
0
 protected function _fetchDescription($maxDepth)
 {
     $query = new Erfurt_Sparql_SimpleQuery();
     $query->setProloguePart('SELECT ?p ?o')->setWherePart(sprintf('{<%s> ?p ?o . }', $this->getIri()));
     $description = array();
     $result = null;
     if ($this->_model) {
         $result = $this->_model->sparqlQuery($query, array('result_format' => 'extended'));
     } else {
         $result = Erfurt_App::getInstance()->getStore()->sparqlQuery($query, array('result_format' => 'extended'));
     }
     if ($maxDepth > 0 && $result) {
         foreach ($result['results']['bindings'] as $row) {
             $property = $row['p']['value'];
             $this->_descriptionResource($property);
             $currentValue = array('type' => $row['o']['type'], 'value' => $row['o']['value']);
             if ($row['o']['type'] == 'uri') {
                 $this->_descriptionResource($row['o']['value']);
             } else {
                 if ($row['o']['type'] == 'typed-literal') {
                     $currentValue['type'] = 'literal';
                     $currentValue['datatype'] = $row['o']['datatype'];
                 } else {
                     if (isset($row['o']['xml:lang'])) {
                         $currentValue['lang'] = $row['o']['xml:lang'];
                     }
                 }
             }
             if (!array_key_exists($property, $description)) {
                 $description[$property] = array();
             }
             array_push($description[$property], $currentValue);
             if ($row['o']['type'] === 'bnode') {
                 $nodeId = $row['o']['value'];
                 $bNode = self::initWithBlankNode($nodeId, $this->_model);
                 $nodeKey = sprintf('_:%s', $nodeId);
                 $description[$nodeKey] = $bNode->getDescription($maxDepth - 1);
             }
         }
     }
     return array($this->getIri() => $description);
 }
Beispiel #13
0
 /** @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;
 }
 /**
  * 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;
 }
Beispiel #15
0
 /**
  * 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;
 }
 /**
  * Searches for properties in the local database.
  *
  * @param array  $termsArray
  * @param string $modelUri
  * @param int    $limit
  *
  * @return array
  */
 private function _searchLocalPropertiesOnly(array $termsArray, $modelUri, $limit)
 {
     require_once 'Erfurt/Sparql/SimpleQuery.php';
     $query = new Erfurt_Sparql_SimpleQuery();
     $query->setProloguePart('SELECT DISTINCT ?uri ?o');
     if (null !== $modelUri) {
         $query->addFrom($modelUri);
     }
     $where = '{ { ?uri ?p ?o . ?uri <' . EF_RDF_TYPE . '> ?o2 .
         FILTER (
             sameTerm(?o2, <http://www.w3.org/1999/02/22-rdf-syntax-ns#Property>) ||
             sameTerm(?o2, <http://www.w3.org/2002/07/owl#DatatypeProperty>) ||
             sameTerm(?o2, <http://www.w3.org/2002/07/owl#ObjectProperty>)
         )
         FILTER ((';
     $uriRegexFilter = array();
     foreach ($termsArray as $t) {
         $uriRegexFilter[] = 'regex(str(?uri), "' . $t . '", "i")';
     }
     $where .= implode(' && ', $uriRegexFilter) . ') || (isLiteral(?o) && ';
     $oRegexFilter = array();
     foreach ($termsArray as $t) {
         $oRegexFilter[] = 'regex(?o, "' . $t . '", "i")';
     }
     $where .= implode(' && ', $oRegexFilter) . ')) } UNION {';
     $where .= '?s ?uri ?o .
               FILTER (';
     $where .= implode(' && ', $uriRegexFilter) . ') } }';
     $query->setWherePart($where);
     $query->setOrderClause('?uri');
     $query->setLimit($limit);
     $store = Erfurt_App::getInstance()->getStore();
     $queryResult = $store->sparqlQuery($query, array('result_format' => 'extended'));
     $tempResult = array();
     foreach ($queryResult['results']['bindings'] as $row) {
         if ($row['o']['type'] === 'literal') {
             $weight = $this->_getWeight($termsArray, $row['uri']['value'], $row['o']['value']);
         } else {
             $weight = $this->_getWeight($termsArray, $row['uri']['value']);
         }
         if (isset($tempResult[$row['uri']['value']])) {
             if ($weight > $tempResult[$row['uri']['value']]) {
                 $tempResult[$row['uri']['value']] = $weight;
             }
         } else {
             $tempResult[$row['uri']['value']] = $weight;
         }
     }
     arsort($tempResult);
     require_once 'OntoWiki/Model/TitleHelper.php';
     require_once 'OntoWiki/Utils.php';
     if (null !== $modelUri) {
         $model = $store->getModel($modelUri, false);
         $titleHelper = new OntoWiki_Model_TitleHelper($model);
     } else {
         $titleHelper = new OntoWiki_Model_TitleHelper();
     }
     $titleHelper->addResources(array_keys($tempResult));
     $translate = $this->_owApp->translate;
     $result = array();
     foreach ($tempResult as $uri => $w) {
         $title = $titleHelper->getTitle($uri);
         if (null !== $title) {
             $result[$uri] = str_replace('|', '&Iota;', $title) . '|' . $uri . '|' . $translate->_('Local Search');
         } else {
             $result[$uri] = OntoWiki_Utils::compactUri($uri) . $uri . '|' . $translate->_('Local Search');
         }
     }
     return $result;
 }
Beispiel #17
0
 /**
  * fetches the PHP/RDF statments array description array
  *
  * @param string       $resourceIri The Iri, which identifies the resource.
  * @param string|false $modelIri    The Iri, which identifies the model or 
  *     false for store wide descriptions
  * @param array        $options     Array of different options:
  *     Erfurt_Store::USE_AC = true|false - use access control
  *     maxDepth = int - how much blank node level
  *     fetchInverse - also fetch incoming properties
  *
  * @return PHP/RDF statements array of the resource
  */
 private function _fetchResourceDescription($resourceIri, $modelIri, $options = array())
 {
     // overwrite result format
     $options[Erfurt_Store::RESULTFORMAT] = Erfurt_Store::RESULTFORMAT_EXTENDED;
     $memoryModel = new Erfurt_Rdf_MemoryModel();
     $query = new Erfurt_Sparql_SimpleQuery();
     $query->setProloguePart('SELECT ?p ?o')->setWherePart("{<{$resourceIri}> ?p ?o . }");
     // prepare an additional query for inverse properties
     if (isset($options['fetchInverse']) && $options['fetchInverse'] === true) {
         $inverseQuery = new Erfurt_Sparql_SimpleQuery();
         $inverseQuery->setProloguePart('SELECT ?s ?p')->setWherePart("{?s ?p <{$resourceIri}> . }");
     } else {
         $inverseQuery = false;
     }
     if ($modelIri === false) {
         // use complete store if modelIri not given
         $result = $this->sparqlQuery($query, $options);
         if ($inverseQuery) {
             $inverseResult = $this->sparqlQuery($inverseQuery, $options);
         }
     } else {
         // if model is given, try to get it
         $ac = Erfurt_App::getInstance()->getAc();
         if ($ac->isModelAllowed('view', $modelIri)) {
             $model = $this->getModel($modelIri, $options[Erfurt_Store::USE_AC]);
         } else {
             $model = false;
         }
         if (!$model) {
             // return an empty description if model not available or allowed
             $result = false;
         } else {
             // use model query method if model valid and readable
             $result = $model->sparqlQuery($query, $options);
             if ($inverseQuery) {
                 $inverseResult = $model->sparqlQuery($inverseQuery, $options);
             }
         }
     }
     if ($result) {
         foreach ($result['results']['bindings'] as $row) {
             // fake the subject array
             $s = array('type' => 'uri', 'value' => $resourceIri);
             $memoryModel->addStatementFromExtendedFormatArray($s, $row['p'], $row['o']);
             // todo: implement blank node fetching here
             //if ($row['o']['type'] === 'bnode') {
             //$nodeId  = $row['o']['value'];
             //$bNode   = self::initWithBlankNode($nodeId, $this->_model);
             //$nodeKey = sprintf('_:%s', $nodeId);
             //$description[$nodeKey] = $bNode->getDescription($maxDepth-1);
             //}
         }
     }
     if (isset($inverseResult) && $inverseResult !== false) {
         foreach ($inverseResult['results']['bindings'] as $row) {
             // fake the object array
             $o = array('type' => 'uri', 'value' => $resourceIri);
             $memoryModel->addStatementFromExtendedFormatArray($row['s'], $row['p'], $o);
         }
     }
     return $memoryModel->getStatements();
 }
Beispiel #18
0
 protected function _sparqlForListResources()
 {
     require_once 'Erfurt/Sparql/SimpleQuery.php';
     $query = new Erfurt_Sparql_SimpleQuery();
     $query->setProloguePart('SELECT ?s ?first ?rest');
     $query->addFrom($this->_graphUri);
     $query->setWherePart('WHERE { ?s <' . EF_RDF_FIRST . '> ?first . ?s <' . EF_RDF_REST . '> ?rest }');
     $result = $this->_store->sparqlQuery($query, array('result_format' => 'extended', 'use_owl_imports' => false, 'use_additional_imports' => false));
     $listArray = array();
     if ($result) {
         foreach ($result['results']['bindings'] as $row) {
             $listArray[$row['s']['value']] = array('first' => $row['first']['value'], 'rest' => $row['rest']['value']);
         }
     }
     $this->_listArray = $listArray;
 }
 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;
     }
 }
Beispiel #20
0
 protected function _buildQuery()
 {
     $query = new Erfurt_Sparql_SimpleQuery();
     $prologue = 'SELECT DISTINCT ?classUri ?sub ?subsub ?subsubsub';
     $query->setProloguePart($prologue);
     $whereSpecs = array();
     $whereSpec = '';
     foreach ($this->_options['object_types'] as $type) {
         $whereSpecs[] = '{?classUri a <' . $type . '>}';
     }
     // optional inference
     if (!$this->_options['entry'] && $this->_inference) {
         // instance retrieval is only applicable for classes
         if ($this->_options['sub_relation'] == EF_RDFS_SUBCLASSOF) {
             $whereSpecs[] = '{?instance a ?classUri.}';
         }
         // entities with a subtype must be a type
         $whereSpecs[] = '{?subtype <' . $this->_options['sub_relation'] . '> ?classUri.}';
     }
     $whereSpec = implode(' UNION ', $whereSpecs);
     $whereSpec .= ' FILTER (isURI(?classUri))';
     // dont't show rdfs/owl entities and subtypes in the first level
     if (!$this->_options['entry']) {
         $whereSpec .= ' FILTER (regex(str(?super), "^' . EF_OWL_NS . '") || !bound(?super))';
     }
     $whereSpec .= ' OPTIONAL {?sub <' . $this->_options['sub_relation'] . '> ?classUri. 
                         OPTIONAL {?subsub <' . $this->_options['sub_relation'] . '> ?sub.
                               OPTIONAL {?subsubsub <' . $this->_options['sub_relation'] . '> ?subsub}
                         }
                     }';
     $whereSpec .= ' OPTIONAL {?classUri <' . $this->_options['sub_relation'] . '> ?super. FILTER(isUri(?super))}';
     // namespaces to be ignored, rdfs/owl-defined objects
     foreach ($this->_options['ignore_ns'] as $ignore) {
         $whereSpec .= ' FILTER (!regex(str(?classUri), "^' . $ignore . '"))';
     }
     // entry point into the class tree
     if ($this->_options['entry']) {
         $whereSpec .= ' FILTER (str(?super) = str(<' . $this->_options['entry'] . '>))';
     }
     $query->setWherePart('WHERE {' . $whereSpec . '}');
     return $query;
 }
Beispiel #21
0
 /**
  * Gets the user rights for the current user.
  * In case the user uri was not fetched, it is fetched.
  * 
  * @param string $userURI The URI of the user.
  * @return array Returns an array that contains the user rights.
  */
 private function _getUserModelRights($userURI)
 {
     if (!isset($this->_userRights[$userURI])) {
         // In this case we need to fetch the rights for the user.
         $userRights = $this->_userRightsTemplate;
         // Super admin, i.e. a user that has database rights (only for debugging purposes and only if
         // enabled in config).
         if ($userURI === $this->_uris['superUserUri'] && (bool) $this->_config->ac->allowDbUser === true) {
             $userRights['userAnyActionAllowed'] = true;
             $userRights['userAnyModelEditAllowed'] = true;
             $userRights['userAnyModelViewAllowed'] = true;
             $this->_userRights[$userURI] = $userRights;
             return $userRights;
         }
         require_once 'Erfurt/Sparql/SimpleQuery.php';
         $sparqlQuery = new Erfurt_Sparql_SimpleQuery();
         $sparqlQuery->setProloguePart('SELECT ?group ?p ?o')->setWherePart('WHERE { 
                             ?group ?p ?o . 
                             ?group <' . $this->_config->ac->group->membership . '> <' . $userURI . '> 
                         }');
         if ($result = $this->_sparql($this->_acModelUri, $sparqlQuery)) {
             $this->_filterAccess($result, $userRights);
         }
         $sparqlQuery = new Erfurt_Sparql_SimpleQuery();
         $sparqlQuery->setProloguePart('SELECT ?s ?p ?o')->setWherePart('WHERE { 
                             ?s ?p ?o . 
                             FILTER (
                                 sameTerm(?s, <' . $userURI . '>) ||
                                 sameTerm(?o, <' . $this->_config->ac->action->class . '>)
                             )
                         }');
         if ($result = $this->_sparql($this->_acModelUri, $sparqlQuery)) {
             $this->_filterAccess($result, $userRights);
         }
         // Now check for forbidden anyModel.
         // view
         if (in_array($this->_uris['propAnyModel'], $userRights['denyModelView'])) {
             $userRights['userAnyModelViewAllowed'] = false;
             $userRights['userAnyModelEditAllowed'] = false;
             $userRights['grantModelView'] = array();
             $userRights['grantModelEdit'] = array();
         }
         // edit
         if (in_array($this->_uris['propAnyModel'], $userRights['denyModelEdit'])) {
             $userRights['userAnyModelEditAllowed'] = false;
             $userRights['grantModelEdit'] = array();
         }
         $this->_userRights[$userURI] = $userRights;
     }
     return $this->_userRights[$userURI];
 }
Beispiel #22
0
 /**
  *
  */
 public function validateHash($hash)
 {
     $config = Erfurt_App::getInstance()->getConfig();
     $store = Erfurt_App::getInstance()->getStore();
     $query = new Erfurt_Sparql_SimpleQuery();
     $query->addFrom($config->ac->modelUri);
     $query->setProloguePart('SELECT ?user');
     $query->setWherePart('{ ?user <' . $config->ac->user->recoveryHash . '> "' . $hash . '" . }');
     $resultUser = $store->sparqlQuery($query, array('use_ac' => false));
     if (!empty($resultUser)) {
         return $resultUser[0]['user'];
     } else {
         require_once 'Erfurt/Auth/Identity/Exception.php';
         throw new Erfurt_Auth_Identity_Exception('Invalid recovery session identifier.');
     }
 }
 protected function getStoredConfigurationUris()
 {
     $dir = $this->_owApp->extensionManager->getExtensionPath('csvimport') . '/configs/';
     if (!is_dir($dir)) {
         return;
     }
     $configurations = array();
     if ($dh = opendir($dir)) {
         while (($file = readdir($dh)) !== false) {
             if ($file == "." || $file == '..') {
                 continue;
             }
             $handle = fopen($dir . $file, 'r');
             $contents = fread($handle, filesize($dir . $file));
             fclose($handle);
             $configurations[] = array('label' => str_replace('.cfg', '', str_replace('_', ' ', $file)), 'config' => $contents);
         }
         closedir($dh);
         return $configurations;
     }
     return array();
     return;
     $sysontUri = $this->_owApp->erfurt->getConfig()->sysont->modelUri;
     $sysOnt = $this->_owApp->erfurt->getStore()->getModel($sysontUri, false);
     $query = new Erfurt_Sparql_SimpleQuery();
     $query->setProloguePart(' SELECT  ?configUri ?configLabel ?configuration');
     $query->setWherePart('  
                 WHERE { ?configUri a <' . $sysontUri . 'CSVImportConfig> .
                         ?configUri <http://www.w3.org/2000/01/rdf-schema#label> ?configLabel .
                         ?configUri <' . $sysontUri . 'CSVImportConfig/configuration> ?configuration} ');
     if ($result = $sysOnt->sparqlQuery($query)) {
         // var_dump($result); die;
         $configurations = array();
         foreach ($result as $entry) {
             //var_dump($entry['configuration']); die;
             $configurations[$entry['configUri']] = array('label' => $entry['configLabel'], 'config' => base64_decode($entry['configuration']));
         }
         //var_dump($configurations);
         return $configurations;
     }
     return array();
 }
 /**
  * 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;
 }
 /**
  * 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();
 }
 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);
 }
Beispiel #27
0
 protected function _serializeResource($resource, $useAc = true, $level = 0)
 {
     require_once 'Erfurt/Sparql/SimpleQuery.php';
     $query = new Erfurt_Sparql_SimpleQuery();
     $query->setProloguePart('SELECT ?s ?p ?o');
     $query->addFrom($this->_graphUri);
     $query->setWherePart('WHERE { ?s ?p ?o . FILTER (sameTerm(?s, <' . $resource . '>))}');
     $query->setOrderClause('?s ?p ?o');
     $query->setLimit(1000);
     $offset = 0;
     $bnObjects = array();
     while (true) {
         $query->setOffset($offset);
         $result = $this->_store->sparqlQuery($query, array('result_format' => 'extended', 'use_owl_imports' => false, 'use_additional_imports' => false, 'use_ac' => $useAc));
         foreach ($result['results']['bindings'] as $row) {
             $s = $row['s']['value'];
             $p = $row['p']['value'];
             $o = $row['o']['value'];
             $sType = $row['s']['type'];
             $oType = $row['o']['type'];
             $lang = isset($row['o']['xml:lang']) ? $row['o']['xml:lang'] : null;
             $dType = isset($row['o']['datatype']) ? $row['o']['datatype'] : null;
             if ($oType === 'bnode') {
                 $bnObjects[] = substr($o, 2);
             }
             $this->_handleStatement($s, $p, $o, $sType, $oType, $lang, $dType);
         }
         if (count($result['results']['bindings']) < 1000) {
             break;
         }
         $offset += 1000;
     }
     $this->_forceWrite();
     // SCBD -> Write Bnodes, too
     if ($level <= 10) {
         foreach ($bnObjects as $bn) {
             $this->_serializeResource($bn, $useAc, $level + 1);
         }
     }
     // We only return SCBD of the TOP resource...
     if ($level > 0) {
         return;
     }
     // SCBD: Do the same for all Resources, that have the resource as object
     $query = new Erfurt_Sparql_SimpleQuery();
     $query->setProloguePart('SELECT ?s ?p ?o');
     $query->addFrom($this->_graphUri);
     $query->setWherePart('WHERE { ?s ?p ?o . ?s ?p2 ?o2 . FILTER (sameTerm(?o2, <' . $resource . '>)) }');
     $query->setOrderClause('?s ?p ?o');
     $query->setLimit(1000);
     $offset = 0;
     $bnObjects = array();
     while (true) {
         $query->setOffset($offset);
         $result = $this->_store->sparqlQuery($query, array('result_format' => 'extended', 'use_owl_imports' => false, 'use_additional_imports' => false, 'use_ac' => $useAc));
         foreach ($result['results']['bindings'] as $row) {
             $s = $row['s']['value'];
             $p = $row['p']['value'];
             $o = $row['o']['value'];
             $sType = $row['s']['type'];
             $oType = $row['o']['type'];
             $lang = isset($row['o']['xml:lang']) ? $row['o']['xml:lang'] : null;
             $dType = isset($row['o']['datatype']) ? $row['o']['datatype'] : null;
             if ($oType === 'bnode') {
                 $bnObjects[] = substr($o, 2);
             }
             $this->_handleStatement($s, $p, $o, $sType, $oType, $lang, $dType);
         }
         if (count($result['results']['bindings']) < 1000) {
             break;
         }
         $offset += 1000;
     }
     $this->_forceWrite();
     // SCBD -> Write Bnodes, too
     if ($level <= 10) {
         foreach ($bnObjects as $bn) {
             $this->_serializeResource($bn, $useAc, $level + 1);
         }
     }
 }