/** * @desc update a modified resource * * @param string modelIri * @param string resourceIri * @param string data * @param string format * @param string origDataHash * * @return string */ public function update($modelIri, $resourceIri, $data, $origDataHash, $format = 'rdfjson') { $model = $this->_store->getModel($modelIri); if (!$model->isEditable()) { return 'Error: Model "' . $modelIri . '" is not available.'; } // TODO check for formats supported by the parser (not yet implemented) // calculate hash of current status and compare to commited hash $currentDataHash = $this->_getCurrentResourceHash($modelIri, $resourceIri); if ($currentDataHash !== $origDataHash) { return 'Error: Resource "' . $resourceIri . '" was edited during your session.'; } // get current statements of resource $resource = $model->getResource($resourceIri); $originalStatements = $resource->getDescription(); // get new statements of resource $parser = Erfurt_Syntax_RdfParser::rdfParserWithFormat($format); $modifiedStatements = $parser->parse($data, Erfurt_Syntax_RdfParser::LOCATOR_DATASTRING); $model->updateWithMutualDifference($originalStatements, $modifiedStatements); return true; }
protected function _importFromManifest($filename, &$queryResultArray) { require_once 'Erfurt/Syntax/RdfParser.php'; $parser = new Erfurt_Syntax_RdfParser(); $parser->initializeWithFormat('turtle'); $manifestResult = $parser->parse($filename, Erfurt_Syntax_RdfParser::LOCATOR_FILE); $mfAction = 'http://www.w3.org/2001/sw/DataAccess/tests/test-manifest#action'; // file auslesen... foreach ($manifestResult as $s => $pArray) { if (isset($pArray[EF_RDF_TYPE]) && $pArray[EF_RDF_TYPE][0]['value'] === 'http://www.w3.org/2001/sw/DataAccess/tests/test-manifest#PositiveSyntaxTest') { $queryFileName = substr(urldecode($pArray[$mfAction][0]['value']), 7); $queryArray = array(); $queryArray['name'] = $s; $queryArray['file_name'] = $queryFileName; $queryArray['group'] = 'Positive syntax tests'; $queryArray['type'] = 'positive'; $handle = fopen($queryFileName, "r"); if ($handle) { $queryArray['query'] = fread($handle, filesize($queryFileName)); fclose($handle); } $queryResultArray[] = array($queryArray); } else { if (isset($pArray[EF_RDF_TYPE]) && $pArray[EF_RDF_TYPE][0]['value'] === 'http://www.w3.org/2001/sw/DataAccess/tests/test-manifest#NegativeSyntaxTest') { $queryFileName = substr($filename, 0, strrpos($filename, '/') + 1) . substr($pArray["{$mfAction}"][0]['value'], strrpos($pArray["{$mfAction}"][0]['value'], '/')); $queryArray = array(); $queryArray['name'] = $s; $queryArray['file_name'] = $queryFileName; $queryArray['group'] = 'Negative syntax tests'; $queryArray['type'] = 'negative'; $handle = fopen($queryFileName, "r"); $queryArray['query'] = fread($handle, filesize($queryFileName)); fclose($handle); $queryResultArray[] = array($queryArray); } else { continue; } } } }
/** * * @param string $modelIri * @param string $locator Either a URL or a absolute file name. * @param string $type One of: * - 'auto' => Tries to detect the type automatically in the following order: * 1. Detect XML by XML-Header => rdf/xml * 2. If this fails use the extension of the file * 3. If this fails throw an exception * - 'xml' * - 'n3' or 'nt' * @param string $locator Denotes whether $data is a local file or a URL. * * @throws Erfurt_Exception */ public function importRdf($modelIri, $data, $type = 'auto', $locator = Erfurt_Syntax_RdfParser::LOCATOR_FILE, $useAc = true) { $queryCache = Erfurt_App::getInstance()->getQueryCache(); $queryCache->invalidateWithModelIri($modelIri); if (!$this->_checkAc($modelIri, 'edit', $useAc)) { throw new Erfurt_Store_Exception("Import failed. Model <{$modelIri}> not found or not writable."); } if ($type === 'auto') { // detect file type if ($locator === Erfurt_Syntax_RdfParser::LOCATOR_FILE && is_readable($data)) { $pathInfo = pathinfo($data); $type = array_key_exists('extension', $pathInfo) ? $pathInfo['extension'] : ''; } if ($locator === Erfurt_Syntax_RdfParser::LOCATOR_URL) { $headers['Location'] = true; // set default content-type header stream_context_get_default(array('http' => array('header' => 'Accept: application/rdf+xml, application/json, text/rdf+n3, text/plain', 'max_redirects' => 1))); do { // follow redirects $flag = false; $isRedirect = false; $headers = @get_headers($data, 1); if (is_array($headers)) { $http = $headers[0]; if (false !== strpos($http, '303')) { $data = (string) $headers['Location']; $isRedirect = true; } } } while ($isRedirect); // restore default empty headers stream_context_get_default(array('http' => array('header' => ''))); if (is_array($headers) && array_key_exists('Content-Type', $headers)) { $ct = $headers['Content-Type']; if (is_array($ct)) { $ct = array_pop($ct); } $ct = strtolower($ct); if (substr($ct, 0, strlen('application/rdf+xml')) === 'application/rdf+xml') { $type = 'rdfxml'; $flag = true; } else { if (substr($ct, 0, strlen('text/plain')) === 'text/plain') { $type = 'rdfxml'; $flag = true; } else { if (substr($ct, 0, strlen('text/rdf+n3')) === 'text/rdf+n3') { $type = 'ttl'; $flag = true; } else { if (substr($ct, 0, strlen('application/json')) === 'application/json') { $type = 'rdfjson'; $flag = true; } else { // RDF/XML is default $type = 'rdfxml'; $flag = true; } } } } } // try file name if (!$flag) { switch (strtolower(strrchr($data, '.'))) { case '.rdf': $type = 'rdfxml'; break; case '.n3': $type = 'ttl'; break; } } } } $result = false; if (array_key_exists($type, $this->_backendAdapter->getSupportedImportFormats())) { $result = $this->_backendAdapter->importRdf($modelIri, $data, $type, $locator); $this->_backendAdapter->init(); } else { $parser = Erfurt_Syntax_RdfParser::rdfParserWithFormat($type); $retVal = $parser->parseToStore($data, $locator, $modelIri, $useAc); // After import re-initialize the backend (e.g. zenddb: fetch model infos again) $this->_backendAdapter->init(); $result = $retVal; } // namespaces may have changed, thus reset allowed models cache for this model unset($this->_allowedModels[$modelIri]); return $result; }
/** * load the doap.n3 file of a extension and transform it into a config array * * @param string $path * @param string $name * * @return array config array */ public static function loadDoapN3($path, $name) { $parser = Erfurt_Syntax_RdfParser::rdfParserWithFormat('n3'); $triples = $parser->parse($path, Erfurt_Syntax_RdfParser::LOCATOR_FILE); $base = $parser->getBaseUri(); $a = self::triples2configArray($triples, $name, $base, $path); return $a; }
public function testUpdateWithMutualDifferenceIssue436DifferentLanguages() { $this->markTestNeedsDatabase(); $this->authenticateDbUser(); $modelUri = 'http://example.org/updateTest/'; $store = Erfurt_App::getInstance()->getStore(); $model = $store->getNewModel($modelUri); $turtle1 = '@base <http://bis.ontowiki.net/> . @prefix bis: <http://bis.ontowiki.net/> . @prefix dc: <http://purl.org/dc/elements/1.1/> . @prefix ldapns: <http://purl.org/net/ldap#> . @prefix swrc: <http://swrc.ontoware.org/ontology#> . @prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> . @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> . @prefix owl: <http://www.w3.org/2002/07/owl#> . @prefix ns: <http://www.w3.org/2003/06/sw-vocab-status/ns#> . @prefix foaf: <http://xmlns.com/foaf/0.1/> . @prefix wot: <http://xmlns.com/wot/0.1/> . bis:PeterPan ldapns:mobile "+49 XXX 123456" ; ldapns:roomNumber "5-XX" ; ldapns:telephoneNumber "+49 341 123456" ; a swrc:FacultyMember ; rdfs:label "Peter Pan 2 de"@de, "Peter Pan 2 nl"@nl, "Peter Pan nl"@nl ; foaf:firstName "Peter" ; foaf:icqChatID "123-456-789" ; foaf:mbox <mailto:peter.pan@informatik.uni-leipzig.de> ; foaf:surname "PanPühn" .'; $turtle2 = '@base <http://bis.ontowiki.net/> . @prefix bis: <http://bis.ontowiki.net/> . @prefix dc: <http://purl.org/dc/elements/1.1/> . @prefix ldapns: <http://purl.org/net/ldap#> . @prefix swrc: <http://swrc.ontoware.org/ontology#> . @prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> . @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> . @prefix owl: <http://www.w3.org/2002/07/owl#> . @prefix ns: <http://www.w3.org/2003/06/sw-vocab-status/ns#> . @prefix foaf: <http://xmlns.com/foaf/0.1/> . @prefix wot: <http://xmlns.com/wot/0.1/> . bis:PeterPan ldapns:mobile "+49 XXX 123456" ; ldapns:roomNumber "5-XX" ; ldapns:telephoneNumber "+49 341 123456" ; a swrc:FacultyMember ; rdfs:label "Peter Pan 2 de"@de ; foaf:firstName "Peter" ; foaf:icqChatID "123-456-789" ; foaf:mbox <mailto:peter.pan@informatik.uni-leipzig.de> ; foaf:surname "PanPühn" .'; $turtleParser = Erfurt_Syntax_RdfParser::rdfParserWithFormat('turtle'); $store->importRdf('http://example.org/updateTest/', $turtle1, 'turtle', Erfurt_Syntax_RdfParser::LOCATOR_DATASTRING, false); $statements1 = $turtleParser->parse($turtle1, Erfurt_Syntax_RdfParser::LOCATOR_DATASTRING); $turtleParser->reset(); $statements2 = $turtleParser->parse($turtle2, Erfurt_Syntax_RdfParser::LOCATOR_DATASTRING); $sparql = 'SELECT * FROM <http://example.org/updateTest/> WHERE {?s ?p ?o}'; $result = $model->sparqlQuery($sparql); $this->assertEquals(12, count($result)); $model->updateWithMutualDifference($statements1, $statements2); $result = $model->sparqlQuery($sparql); $this->assertEquals(10, count($result)); }
/** @see Erfurt_Store_Adapter_Interface */ public function importRdf($modelUri, $data, $type, $locator) { // TODO fix or remove if ($this->_dbConn instanceof Zend_Db_Adapter_Mysqli) { require_once 'Erfurt/Syntax/RdfParser.php'; $parser = Erfurt_Syntax_RdfParser::rdfParserWithFormat($type); $parsedArray = $parser->parse($data, $locator, $modelUri, false); $modelInfoCache = $this->_getModelInfos(); $modelId = $modelInfoCache["{$modelUri}"]['modelId']; // create file $tmpDir = Erfurt_App::getInstance()->getTmpDir(); $filename = $tmpDir . 'import' . md5((string) time()) . '.csv'; $fileHandle = fopen($filename, 'w'); $count = 0; $longStatements = array(); foreach ($parsedArray as $s => $pArray) { if (substr($s, 0, 2) === '_:') { $s = substr($s, 2); $sType = '1'; } else { $sType = '0'; } foreach ($pArray as $p => $oArray) { foreach ($oArray as $o) { // to long values need to be put in a different table, so we can't bulk insert these // values, for they need a foreign key if (strlen($s) > $this->_getSchemaRefThreshold() || strlen($p) > $this->_getSchemaRefThreshold() || strlen($o['value']) > $this->_getSchemaRefThreshold() || isset($o['datatype']) && strlen($o['datatype']) > $this->_getSchemaRefThreshold()) { $longStatements[] = array('s' => $s, 'p' => $p, 'o' => $o); continue; } if ($o['type'] === 'literal') { $oType = '2'; } else { if ($o['type'] === 'bnode') { if (substr($o['value'], 0, 2) === '_:') { $o['value'] = substr($o['value'], 2); } $oType = '1'; } else { $oType = '0'; } } $lineString = $modelId . ';' . $s . ';' . $p . ';' . $o['value'] . ';'; $lineString .= "\\N;\\N;\\N;"; $lineString .= $sType . ';' . $oType . ';'; if (isset($o['lang'])) { $lineString .= $o['lang']; } else { $lineString .= "\\N"; } $lineString .= ';'; if (isset($o['datatype'])) { $lineString .= $o['datatype'] . ";\\N"; } else { $lineString .= "\\N;\\N"; } $lineString .= PHP_EOL; $count++; fputs($fileHandle, $lineString); } } } fclose($fileHandle); if ($count > 10000) { $this->_dbConn->getConnection()->query('ALTER TABLE ef_stmt DISABLE KEYS'); } $sql = "LOAD DATA INFILE '{$filename}' IGNORE INTO TABLE ef_stmt\n FIELDS TERMINATED BY ';'\n (g, s, p, o, s_r, p_r, o_r, st, ot, ol, od, od_r);"; $this->_dbConn->getConnection()->query('START TRANSACTION;'); $this->_dbConn->getConnection()->query($sql); $this->_dbConn->getConnection()->query('COMMIT'); // Delete the temp file unlink($filename); // Now add the long-value-statements foreach ($longStatements as $stm) { $sId = false; $pId = false; $oId = false; $dtId = false; $s = $stm['s']; $p = $stm['p']; $o = $stm['o']['value']; if (strlen($s) > $this->_getSchemaRefThreshold()) { $sHash = md5($s); $sId = $this->_insertValueInto('ef_uri', $modelId, $s, $sHash); $s = substr($s, 0, 128) . $sHash; } if (strlen($p) > $this->_getSchemaRefThreshold()) { $pHash = md5($p); $pId = $this->_insertValueInto('ef_uri', $modelId, $p, $pHash); $p = substr($p, 0, 128) . $pHash; } if (strlen($o) > $this->_getSchemaRefThreshold()) { $oHash = md5($o); if ($stm['o']['type'] === 'literal') { $oId = $this->_insertValueInto('ef_lit', $modelId, $o, $oHash); } else { $oId = $this->_insertValueInto('ef_uri', $modelId, $o, $oHash); } $o = substr($o, 0, 128) . $oHash; } if (isset($stm['o']['datatype']) && strlen($stm['o']['datatype']) > $this->_getSchemaRefThreshold()) { $oDtHash = md5($stm['o']['datatype']); $dtId = $this->_insertValueInto('ef_uri', $modelId, $stm['o']['datatype'], $oDtHash); $oDt = substr($oDt, 0, 128) . $oDtHash; } $sql = "INSERT INTO ef_stmt\n (g,s,p,o,s_r,p_r,o_r,st,ot,ol,od,od_r)\n VALUES ({$modelId},'{$s}','{$p}','{$o}',"; if ($sId !== false) { $sql .= $sId . ','; } else { $sql .= "NULL,"; } if ($pId !== false) { $sql .= $pId . ','; } else { $sql .= "NULL,"; } if ($oId !== false) { $sql .= $oId . ','; } else { $sql .= "NULL,"; } if (substr($stm['s'], 0, 2) === '_:') { $sql .= '1,'; } else { $sql .= '0,'; } if ($stm['o']['type'] === 'literal') { $sql .= '2,'; } else { if ($stm['o']['type'] === 'uri') { $sql .= '0,'; } else { $sql .= '1,'; } } if (isset($stm['o']['lang'])) { $sql .= '"' . $stm['o']['lang'] . '",'; } else { $sql .= "NULL,"; } if (isset($stm['o']['datatype'])) { if ($dtId !== false) { $sql .= '"' . $oDt . '",' . $dtId . ')'; } else { $sql .= '"' . $stm['o']['datatype'] . '",' . "\\N)"; } } else { $sql .= "NULL,NULL)"; } //$this->_dbConn->getConnection()->query($sql); } if ($count > 10000) { $this->_dbConn->getConnection()->query('ALTER TABLE ef_stmt ENABLE KEYS'); } $this->_optimizeTables(); } else { require_once 'Erfurt/Store/Adapter/Exception.php'; throw new Erfurt_Store_Adapter_Exception('CSV import not supported for this database server.'); } }
/** * Returns FOAF data for a given FOAF URI iff available. * Returns false else. * * @param string $foafUri * @return array|bool * */ public static function getFoafData($foafUri) { $client = Erfurt_App::getInstance()->getHttpClient($foafUri, array('maxredirects' => 3, 'timeout' => 30)); $client->setHeaders('Accept', 'application/rdf+xml'); $response = $client->request(); if ($response->getStatus() === 200) { require_once 'Erfurt/Syntax/RdfParser.php'; $parser = Erfurt_Syntax_RdfParser::rdfParserWithFormat('rdfxml'); if ($idx = strrpos($foafUri, '#')) { $base = substr($foafUri, 0, $idx); } else { $base = $foafUri; } try { $result = $parser->parse($response->getBody(), Erfurt_Syntax_RdfParser::LOCATOR_DATASTRING, $base); } catch (Erfurt_Syntax_RdfParserException $e) { return false; } return $result; } else { return false; } }
/** * OntoWiki Update Endpoint * * Only data inserts and deletes are implemented at the moment (e.g. no graph patterns). * * @todo LOAD <> INTO <>, CLEAR GRAPH <>, CREATE[SILENT] GRAPH <>, DROP[ SILENT] GRAPH <> */ public function updateAction() { // service controller needs no view renderer $this->_helper->viewRenderer->setNoRender(); // disable layout for Ajax requests $this->_helper->layout()->disableLayout(); $store = OntoWiki::getInstance()->erfurt->getStore(); $response = $this->getResponse(); $defaultGraph = $this->_request->getParam('default-graph-uri', null); $namedGraph = $this->_request->getParam('named-graph-uri', null); $insertGraph = null; $deleteGraph = null; $insertModel = null; $deleteModel = null; if (isset($this->_request->query)) { // we have a query, enter SPARQL/Update mode $query = $this->_request->getParam('query', ''); OntoWiki::getInstance()->logger->info('SPARQL/Update query: ' . $query); $matches = array(); // insert preg_match('/INSERT\\s+DATA(\\s+INTO\\s*<(.+)>)?\\s*{\\s*([^}]*)/i', $query, $matches); $insertGraph = isset($matches[2]) && $matches[2] !== '' ? $matches[2] : null; $insertTriples = isset($matches[3]) ? $matches[3] : ''; if (null === $insertGraph && $insertTriples !== '') { if (null !== $defaultGraph) { $insertGraph = $defaultGraph; } if (null !== $namedGraph) { $insertGraph = $namedGraph; } } OntoWiki::getInstance()->logger->info('SPARQL/Update insertGraph: ' . $insertGraph); OntoWiki::getInstance()->logger->info('SPARQL/Update insertTriples: ' . $insertTriples); // delete preg_match('/DELETE\\s+DATA(\\s+FROM\\s*<(.+)>)?\\s*{\\s*([^}]*)/i', $query, $matches); $deleteGraph = isset($matches[2]) && $matches[2] !== '' ? $matches[2] : null; $deleteTriples = isset($matches[3]) ? $matches[3] : ''; if (null === $deleteGraph && $deleteTriples !== '') { if (null !== $defaultGraph) { $deleteGraph = $defaultGraph; } if (null !== $namedGraph) { $deleteGraph = $namedGraph; } } // TODO: normalize literals $parser = Erfurt_Syntax_RdfParser::rdfParserWithFormat('nt'); $insert = $parser->parse($insertTriples, Erfurt_Syntax_RdfParser::LOCATOR_DATASTRING); $parser->reset(); $delete = $parser->parse($deleteTriples, Erfurt_Syntax_RdfParser::LOCATOR_DATASTRING); if (null !== $insertGraph) { try { $insertModel = $insertGraph ? $store->getModel($insertGraph) : $store->getModel($namedGraph); } catch (Erfurt_Store_Exception $e) { // TODO: error if (defined('_OWDEBUG')) { OntoWiki::getInstance()->logger->info('Could not instantiate models.'); } return; } } if (null !== $deleteGraph) { try { $deleteModel = $deleteGraph ? $store->getModel($deleteGraph) : $store->getModel($namedGraph); } catch (Erfurt_Store_Exception $e) { // TODO: error if (defined('_OWDEBUG')) { OntoWiki::getInstance()->logger->info('Could not instantiate models.'); } return; } } } else { // no query, inserts and delete triples by JSON via param $insert = json_decode($this->_request->getParam('insert', '{}'), true); $delete = json_decode($this->_request->getParam('delete', '{}'), true); if ($this->_request->has('delete_hashed')) { $hashedObjectStatements = $this->_findStatementsForObjectsWithHashes($namedGraph, json_decode($this->_request->getParam('delete_hashed'), true)); $delete = array_merge_recursive($delete, $hashedObjectStatements); } try { $namedModel = $store->getModel($namedGraph); $insertModel = $namedModel; $deleteModel = $namedModel; } catch (Erfurt_Store_Exception $e) { // TODO: error if (defined('_OWDEBUG')) { OntoWiki::getInstance()->logger->info('Could not instantiate models.'); } return; } } $flag = false; /** * @trigger onUpdateServiceAction is triggered when Service-Controller Update Action is executed. * Event contains following attributes: * deleteModel : model to delete statments from * deleteData : statements payload being deleted * insertModel : model to add statements to * insertDara : statements payload being added */ $event = new Erfurt_Event('onUpdateServiceAction'); $event->deleteModel = $deleteModel; $event->insertModel = $insertModel; $event->deleteData = $delete; $event->insertData = $insert; $event->trigger(); // writeback $delete = $event->deleteData; $insert = $event->insertData; $changes = isset($event->changes) ? $event->changes : null; // delete if ($deleteModel && $deleteModel->isEditable()) { try { $deleteModel->deleteMultipleStatements((array) $delete); $flag = true; if (defined('_OWDEBUG')) { OntoWiki::getInstance()->logger->info(sprintf('Deleted statements from graph <%s>', $deleteModel->getModelUri())); } } catch (Erfurt_Store_Exception $e) { if (defined('_OWDEBUG')) { OntoWiki::getInstance()->logger->info('Could not delete statements from graph: ' . $e->getMessage() . PHP_EOL . 'Statements: ' . print_r($delete, true)); } } } // insert if ($insertModel && $insertModel->isEditable()) { OntoWiki::getInstance()->logger->info('add Statements: ' . print_r($delete, true)); $count = $insertModel->addMultipleStatements((array) $insert); $flag = true; if (defined('_OWDEBUG')) { OntoWiki::getInstance()->logger->info(sprintf('Inserted %i statements into graph <%s>', $count, $insertModel->getModelUri())); } } // nothing done? if (!$flag) { // When no user is given (Anoymous) give the requesting party a chance to authenticate. if (Erfurt_App::getInstance()->getAuth()->getIdentity()->isAnonymousUser()) { // In this case we allow the requesting party to authorize $response->setRawHeader('HTTP/1.1 401 Unauthorized'); $response->setHeader('WWW-Authenticate', 'Basic realm="OntoWiki"'); return; } } if ($changes) { /** * @see {http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.2.2} */ $response->setHttpResponseCode(201); $response->setHeader('Location', $changes['changed']); $response->setHeader('Content-Type', 'application/json'); $response->setBody(json_encode($changes)); } }
/** * Handles the data contained in a response. */ private function _handleResponseBody($response, $baseUri = null) { $contentType = $response->getHeader('Content-type'); if ($pos = strpos($contentType, ';')) { $contentType = substr($contentType, 0, $pos); } $found = false; if ($contentType == 'text/plain' && !empty($baseUri)) { //if the mime type does not reveal anything, try file endings. duh $parts = parse_url($baseUri); $ending = pathinfo($parts['path'], PATHINFO_EXTENSION); $found = true; switch ($ending) { case 'n3': case 'ttl': $type = 'rdfn3'; break; case 'xml': $type = 'rdfxml'; break; case 'json': $type = 'rdfjson'; break; default: $found = false; break; } } if (!$found) { //use the defined mime type switch ($contentType) { case 'application/rdf+xml': case 'application/xml': // Hack for lsi urns // Hack for lsi urns case 'text/plain': $type = 'rdfxml'; break; case 'application/json': $type = 'rdfjson'; break; case 'text/rdf+n3': case 'text/n3': case 'text/turtle': case 'application/x-turtle': $type = 'rdfn3'; break; case 'text/html': return $this->_handleResponseBodyHtml($response, $baseUri); case '': $type = $this->_checkExtension($baseUri); if ($type != false) { break; } default: require_once 'Erfurt/Wrapper/Exception.php'; throw new Erfurt_Wrapper_Exception('Server returned not supported content type: ' . $contentType); } } $data = $response->getBody(); require_once 'Erfurt/Syntax/RdfParser.php'; $parser = Erfurt_Syntax_RdfParser::rdfParserWithFormat($type); $result = $parser->parse($data, Erfurt_Syntax_RdfParser::LOCATOR_DATASTRING, $baseUri); $ns = $parser->getNamespaces(); return array('data' => $result, 'ns' => $ns); }
public static function rdfParserWithFormat($format) { $parser = new Erfurt_Syntax_RdfParser(); $parser->initializeWithFormat($format); return $parser; }
protected function _determineInverseProperty($propertyUri) { $client = Erfurt_App::getInstance()->getHttpClient($propertyUri, array('maxredirects' => 10, 'timeout' => 30)); $client->setHeaders('Accept', 'application/rdf+xml'); try { $response = $client->request(); } catch (Exception $e) { return null; } if ($response->getStatus() === 200) { $data = $response->getBody(); $parser = Erfurt_Syntax_RdfParser::rdfParserWithFormat('rdfxml'); try { $result = $parser->parse($data, Erfurt_Syntax_RdfParser::LOCATOR_DATASTRING); } catch (Exception $e) { return null; } if (isset($result[$propertyUri])) { $pArray = $result[$propertyUri]; if (isset($pArray['http://www.w3.org/2002/07/owl#inverseOf'])) { $oArray = $pArray['http://www.w3.org/2002/07/owl#inverseOf']; return $oArray[0]['value']; } } return null; } }
protected function _discoverPingbackServer($targetUri) { // 1. Retrieve HTTP-Header and check for X-Pingback $headers = get_headers($targetUri, 1); if (!is_array($headers)) { return null; } if (isset($headers['X-Pingback'])) { if (is_array($headers['X-Pingback'])) { $this->_logInfo($headers['X-Pingback'][0]); return $headers['X-Pingback'][0]; } $this->_logInfo($headers['X-Pingback']); return $headers['X-Pingback']; } // 2. Check for (X)HTML Link element, if target has content type text/html // TODO Fetch only the first X bytes...??? $client = Erfurt_App::getInstance()->getHttpClient($targetUri, array('maxredirects' => 0, 'timeout' => 3)); $response = $client->request(); if ($response->getStatus() === 200) { $htmlDoc = new DOMDocument(); $result = @$htmlDoc->loadHtml($response->getBody()); $relElements = $htmlDoc->getElementsByTagName('link'); foreach ($relElements as $relElem) { $rel = $relElem->getAttribute('rel'); if (strtolower($rel) === 'pingback') { return $relElem->getAttribute('href'); } } } // 3. Check RDF/XML require_once 'Zend/Http/Client.php'; $client = Erfurt_App::getInstance()->getHttpClient($targetUri, array('maxredirects' => 10, 'timeout' => 3)); $client->setHeaders('Accept', 'application/rdf+xml'); $response = $client->request(); if ($response->getStatus() === 200) { $rdfString = $response->getBody(); $parser = Erfurt_Syntax_RdfParser::rdfParserWithFormat('rdfxml'); try { $result = $parser->parse($rdfString, Erfurt_Syntax_RdfParser::LOCATOR_DATASTRING); } catch (Exception $e) { $this->_logError($e->getMessage()); return null; } if (isset($result[$targetUri])) { $pArray = $result[$targetUri]; foreach ($pArray as $p => $oArray) { if ($p === 'http://purl.org/net/pingback/service') { return $oArray[0]['value']; } } } } return null; }
/** * Updates the current model with statements sent as JSON */ public function updateAction() { $this->_helper->viewRenderer->setNoRender(); $this->_helper->layout()->disableLayout(); $errors = array(); // check graph parameter if (!$this->_request->has('named-graph-uri')) { $errors[] = "Missing parameter 'named-graph-uri'."; } // Parsing may go wrong, when user types in corrupt data... So we catch all exceptions here... try { $flag = false; // check original graph if ($this->_request->has('original-graph')) { $flag = true; $originalFormat = $this->_request->getParam('original-format', 'rdfjson'); $parser = Erfurt_Syntax_RdfParser::rdfParserWithFormat($originalFormat); $originalStatements = $parser->parse($this->getParam('original-graph', false), Erfurt_Syntax_RdfParser::LOCATOR_DATASTRING); } // check changed graph if ($this->_request->has('modified-graph')) { $flag = true; $modifiedFormat = $this->_request->getParam('modified-format', 'rdfjson'); $parser = Erfurt_Syntax_RdfParser::rdfParserWithFormat($modifiedFormat); $modifiedStatements = $parser->parse($this->getParam('modified-graph', false), Erfurt_Syntax_RdfParser::LOCATOR_DATASTRING); } } catch (Exception $e) { $errors[] = 'Something went wrong: ' . $e->getMessage(); } if (!$flag) { $errors[] = "At least one of the parameters 'original-graph' or 'modified-graph' must be supplied."; } // errors occured... so do not update... instead show error message or mark as bad request if (!empty($errors)) { if (null === $this->_request->getParam('redirect-uri')) { // This means, we do not redirect, so we can mark this request as bad request. $response = $this->getResponse(); $response->setRawHeader('HTTP/1.0 400 Bad Request'); throw new OntoWiki_Controller_Exception(implode(PHP_EOL, $errors)); } else { // We have a redirect uri given, so we do not redirect, but show the error messages foreach ($errors as $e) { $this->_owApp->appendMessage(new OntoWiki_Message($e, OntoWiki_Message::ERROR)); } $server = $this->_request->getServer(); if (isset($server['HTTP_REFERER'])) { $this->_request->setParam('redirect-uri', $server['HTTP_REFERER']); } return; } } // instantiate model $graph = Erfurt_App::getInstance()->getStore()->getModel($this->getParam('named-graph-uri')); // update model $graph->updateWithMutualDifference($originalStatements, $modifiedStatements); }
private function _rdfParser($type) { $parser = Erfurt_Syntax_RdfParser::rdfParserWithFormat($type); if (null !== $this->_httpClientAdapter) { $parser->setHttpClientAdapter($this->_httpClientAdapter); } return $parser; }