/** * Retrieve the latest RDFA version of schema.org and converts it to JSON-LD. * * Note: caches the file in data and retrieves it from there as long as it exists. */ private function getJSONVersionOfSchema() { // Set cachefile $cacheFile = dirname(dirname(__DIR__)) . '/data/schemaorg.cache'; if (!file_exists($cacheFile)) { // Create dir if (!file_exists(dirname($cacheFile))) { mkdir(dirname($cacheFile), 0777, true); } // Load RDFA Schema $graph = new \EasyRdf_Graph(self::RDFA_SCHEMA); $graph->load(self::RDFA_SCHEMA, 'rdfa'); // Lookup the output format $format = \EasyRdf_Format::getFormat('jsonld'); // Serialise to the new output format $output = $graph->serialise($format); if (!is_scalar($output)) { $output = var_export($output, true); } $this->schema = \ML\JsonLD\JsonLD::compact($graph->serialise($format), 'http://schema.org/'); // Write cache file file_put_contents($cacheFile, serialize($this->schema)); } else { $this->schema = unserialize(file_get_contents($cacheFile)); } }
/** * Perform the load. * * @param EasyRdf_Graph $chunk * @return void */ public function execute(&$chunk) { if (!$chunk->isEmpty()) { // Don't use EasyRdf's ntriple serializer, as something might be wrong with its unicode byte characters // After serializing with semsol/arc and easyrdf, the output looks the same (with unicode characters), but after a // binary utf-8 conversion (see $this->serialize()) the outcome is very different, leaving easyrdf's encoding completely different // from the original utf-8 characters, and the semsol/arc encoding correct as the original. $ttl = $chunk->serialise('turtle'); $arc_parser = \ARC2::getTurtleParser(); $ser = \ARC2::getNTriplesSerializer(); $arc_parser->parse('', $ttl); $triples = $ser->getSerializedTriples($arc_parser->getTriples()); preg_match_all("/(<.*\\.)/", $triples, $matches); if ($matches[0]) { $this->buffer = array_merge($this->buffer, $matches[0]); } $triple_count = count($matches[0]); $this->log("Added {$triple_count} triples to the load buffer."); while (count($this->buffer) >= $this->loader->buffer_size) { // Log the time it takes to load the triples into the store $start = microtime(true); $buffer_size = $this->loader->buffer_size; $triples_to_send = array_slice($this->buffer, 0, $buffer_size); $this->addTriples($triples_to_send); $this->buffer = array_slice($this->buffer, $buffer_size); $duration = round((microtime(true) - $start) * 1000, 2); $this->log("Took {$buffer_size} triples from the load buffer, loading them took {$duration} ms."); } } }
/** * @author "Lionel Lecaque, <*****@*****.**>" * @param string $namespace * @param string $data xml content */ public function createModel($namespace, $data) { $modelId = $this->getModelId($namespace); if ($modelId === false) { common_Logger::d('modelId not found, need to add namespace ' . $namespace); $this->addNewModel($namespace); //TODO bad way, need to find better $modelId = $this->getModelId($namespace); } $modelDefinition = new EasyRdf_Graph($namespace); if (is_file($data)) { $modelDefinition->parseFile($data); } else { $modelDefinition->parse($data); } $graph = $modelDefinition->toRdfPhp(); $resources = $modelDefinition->resources(); $format = EasyRdf_Format::getFormat('php'); $data = $modelDefinition->serialise($format); foreach ($data as $subjectUri => $propertiesValues) { foreach ($propertiesValues as $prop => $values) { foreach ($values as $k => $v) { $this->addStatement($modelId, $subjectUri, $prop, $v['value'], isset($v['lang']) ? $v['lang'] : null); } } } return true; }
protected function getTriples($file) { if (!file_exists($file)) { throw new Exception($file . ' not found'); } // validate the file to import $parser = new tao_models_classes_Parser($file, array('extension' => 'rdf')); $parser->validate(); if (!$parser->isValid()) { throw new common_Exception('Invalid RDF file ' . $file); } $modelDefinition = new EasyRdf_Graph(); $modelDefinition->parseFile($file); /* $graph = $modelDefinition->toRdfPhp(); $resources = $modelDefinition->resources(); */ $format = EasyRdf_Format::getFormat('php'); $data = $modelDefinition->serialise($format); $triples = array(); foreach ($data as $subjectUri => $propertiesValues) { foreach ($propertiesValues as $prop => $values) { foreach ($values as $k => $v) { $triples[] = array('s' => $subjectUri, 'p' => $prop, 'o' => $v['value'], 'l' => isset($v['lang']) ? $v['lang'] : ''); } } } return $triples; }
protected function preRun() { $data = parent::getData(); $resourceUri = JURI::base() . "index.php?com_content&view=article&id=" . $data["articleID"]; $annotation = new EasyRdf_Graph($resourceUri); foreach ($data["entityIDs"] as $entityID) { $annotation->addResource($resourceUri, "sioc:about", "http://www.mni.thm.de/user/" . $entityID); } parent::setData($annotation->serialise("rdfxml")); }
/** * @ignore */ private static function statement2rdf(PDOStatement $statement) { $graph = new EasyRdf_Graph(); while ($r = $statement->fetch()) { if (isset($r['l_language']) && !empty($r['l_language'])) { $graph->addLiteral($r['subject'], $r['predicate'], $r['object'], $r['l_language']); } elseif (common_Utils::isUri($r['object'])) { $graph->add($r['subject'], $r['predicate'], $r['object']); } else { $graph->addLiteral($r['subject'], $r['predicate'], $r['object']); } } $format = EasyRdf_Format::getFormat('rdfxml'); return $graph->serialise($format); }
public static function toFile($filePath, $triples) { $graph = new \EasyRdf_Graph(); foreach ($triples as $triple) { if (!empty($triple->lg)) { $graph->addLiteral($triple->subject, $triple->predicate, $triple->object, $triple->lg); } elseif (\common_Utils::isUri($triple->object)) { $graph->add($triple->subject, $triple->predicate, $triple->object); } else { $graph->addLiteral($triple->subject, $triple->predicate, $triple->object); } } $format = \EasyRdf_Format::getFormat('rdfxml'); return file_put_contents($filePath, $graph->serialise($format)); }
/** * Imports the rdf file into the selected class * * @param string $file * @param core_kernel_classes_Class $class * @return common_report_Report */ private function flatImport($file, core_kernel_classes_Class $class) { $report = common_report_Report::createSuccess(__('Data imported successfully')); $graph = new EasyRdf_Graph(); $graph->parseFile($file); // keep type property $map = array(RDF_PROPERTY => RDF_PROPERTY); foreach ($graph->resources() as $resource) { $map[$resource->getUri()] = common_Utils::getNewUri(); } $format = EasyRdf_Format::getFormat('php'); $data = $graph->serialise($format); foreach ($data as $subjectUri => $propertiesValues) { $resource = new core_kernel_classes_Resource($map[$subjectUri]); $subreport = $this->importProperties($resource, $propertiesValues, $map, $class); $report->add($subreport); } return $report; }
/** * Merge two graphs and return the resulting merged graph * * @param EasyRdf_Graph $graph * @param EasyRdf_Graph $input_graph * * @return EasyRdf_Graph */ private function mergeGraph($graph, $input_graph) { $turtle_graph = $input_graph->serialise('turtle'); $graph->parse($turtle_graph, 'turtle'); return $graph; }
<?php echo form_tag(); ?> <?php echo label_tag('uri') . text_field_tag('uri', 'http://www.dajobe.org/foaf.rdf', array('size' => 80)); ?> <br /> <?php echo label_tag('format') . select_tag('format', $format_options, 'rdfxml'); ?> <?php echo submit_tag(); ?> <?php echo form_end_tag(); ?> </div> <?php if (isset($_REQUEST['uri'])) { $graph = new EasyRdf_Graph($_REQUEST['uri']); $data = $graph->serialise($_REQUEST['format']); if (!is_scalar($data)) { $data = var_export($data, true); } print "<pre>" . htmlspecialchars($data) . "</pre>"; } ?> </body> </html>
/** * @see https://github.com/njh/easyrdf/issues/115 */ public function testIssue115() { $triples = <<<RDF <http://example.com/id/1> <http://www.w3.org/2000/01/rdf-schema#type> <http://example.com/ns/animals/dog> . <http://example.com/id/2> <http://www.w3.org/2000/01/rdf-schema#type> <http://example.com/ns/animals/cat> . <http://example.com/id/3> <http://www.w3.org/2000/01/rdf-schema#type> <http://example.com/ns/animals/bird> . <http://example.com/id/4> <http://www.w3.org/2000/01/rdf-schema#type> <http://example.com/ns/animals/reptiles/snake> . RDF; EasyRdf_Namespace::set('id', 'http://example.com/id/'); EasyRdf_Namespace::set('animals', 'http://example.com/ns/animals/'); // parse graph $graph = new EasyRdf_Graph(); $graph->parse($triples, 'ntriples'); // dump as text/turtle $turtle = $graph->serialise('turtle'); $this->assertEquals(readFixture('turtle/gh115-nested-namespaces.ttl'), $turtle); }
} else { mysql_free_result($result); } // autmatically subscribe to local services $tiny = substr(md5(uniqid(microtime(true), true)), 0, 8); $user_hash = substr(sha1($webid), 0, 20); $query = "INSERT INTO pingback SET webid='" . $webid . "', feed_hash='" . $tiny . "', user_hash='" . $user_hash . "'"; $result = mysql_query($query); if (!$result) { $alert .= error('Unable to write to the database!'); } else { mysql_free_result($result); } } // write profile to file $data = $graph->serialise('rdfxml'); if (!is_scalar($data)) { $data = var_export($data, true); } $pf = fopen($user_dir . '/foaf.rdf', 'w') or die('Cannot create profile RDF file in ' . $user_dir . '!'); fwrite($pf, $data); fclose($pf); $pf = fopen($user_dir . '/foaf.txt', 'w') or die('Cannot create profile PHP file!'); fwrite($pf, $data); fclose($pf); // everything is fine $ok = true; // Send the X.509 SSL certificate to the script caller (user) as a file transfer if ($_REQUEST['action'] == 'new' || $_REQUEST['action'] == 'import') { download_identity_x509($x509, $webid); } else {
returnHttpError(300); break; } } } EasyRdf_Namespace::set('adms', 'http://www.w3.org/ns/adms#'); EasyRdf_Namespace::set('cnt', 'http://www.w3.org/2011/content#'); EasyRdf_Namespace::set('dc', 'http://purl.org/dc/elements/1.1/'); EasyRdf_Namespace::set('dcat', 'http://www.w3.org/ns/dcat#'); EasyRdf_Namespace::set('gsp', 'http://www.opengis.net/ont/geosparql#'); EasyRdf_Namespace::set('locn', 'http://www.w3.org/ns/locn#'); EasyRdf_Namespace::set('prov', 'http://www.w3.org/ns/prov#'); $graph = new EasyRdf_Graph(); $graph->parse($rdf, "rdfxml", $rdfxmlURL); header("Content-type: " . $outputFormat); echo $graph->serialise($outputFormats[$outputFormat][1]); exit; /* if ($outputFormat == 'text/html') { $xml = new DOMDocument; $xml->loadXML($rdf) or die(); $xsl = new DOMDocument; $xsl->load(""); $proc = new XSLTProcessor(); $proc->importStyleSheet($xsl); echo $proc->transformToXML($xml); exit; } else { echo $graph->serialise($outputFormats[$outputFormat][1]); exit;
/** * Merge two graphs and return the result * * @param EasyRdf_Graph $graph * @param EasyRdf_Graph $input_graph * * @return EasyRdf_Graph */ private function mergeGraph($graph, $input_graph) { $rdfxml_string = $input_graph->serialise('rdfxml'); $graph->parse($rdfxml_string, 'rdfxml'); return $graph; }
?> <br /> <?php echo reset_tag(); ?> <?php echo submit_tag(); ?> <?php echo form_end_tag(); ?> </div> <?php if (isset($_REQUEST['uri']) or isset($_REQUEST['data'])) { $graph = new EasyRdf_Graph($_REQUEST['uri']); if (empty($_REQUEST['data'])) { $graph->load(); } else { $graph->parse($_REQUEST['data'], $_REQUEST['input_format'], $_REQUEST['uri']); } $output = $graph->serialise($_REQUEST['output_format']); if (!is_scalar($output)) { $output = var_export($output, true); } print "<pre>" . htmlspecialchars($output) . "</pre>"; } ?> </body> </html>
/** * Output data in RDF and Turtle format * * @param array $data The items to output * @param string $format The output format * @param string $predicate The predicate for the list * @param string $namespaces An associative array with the namespace, e.g. [ 'foaf' => 'http://xmlns.com/foaf/0.1/' ]. * Note that EasyRDF already adds the standard prefixes, such as dc, foaf, etc. * @param integer $status HTTP status code * * @uses \EasyRdf_Graph * * @throws \SameAsLite\Exception\ContentTypeException An exception may be thrown if the requested MIME type * is not supported */ protected function outputRDF(array $data = array(), $format = 'list', $predicate = 'owl:sameAs', array $namespaces = array(), $status = null) { // how to: escape // array_walk($list, '\SameAsLite\Helper::escapeInputArray'); if (!is_null($status)) { $this->app->response->setStatus($status); } //end if // get the query parameters $symbol = $this->app->request()->params('string'); if (!$symbol) { $symbol = $this->app->request()->params('symbol'); } //end if $symbol = $symbol ? urldecode($symbol) : false; $store = $this->store ? $this->store : false; $storeurl = $this->app->request()->getURL() . $this->app->request()->getRootUri() . '/datasets/' . urlencode($store); // EASY RDF $graph = new \EasyRdf_Graph(); //----------- // namespaces // ---------- if (!empty($namespaces)) { foreach ($namespaces as $prefix => $uri) { \EasyRdf_Namespace::set($prefix, $uri); } } //------------- // result block // ------------ if ($symbol && strpos($symbol, 'http') === 0) { $graph_uri = $meta_uri = $graph->resource($symbol); } else { $graph_uri = $graph->newBNode(); } $result_block = $graph->resource($graph_uri); //------------- // meta block // ------------ $meta_uri = $this->app->request()->getURL() . $_SERVER['REQUEST_URI']; $meta_block = $graph->resource($meta_uri); // if this part is added, EasyRDF will merge the result block with the meta block // $meta_block->add('foaf:primaryTopic', $graph->resource( '_:' . $result_block->getBNodeId() )); $meta_block->set('dc:creator', 'sameAsLite'); // TODO: maybe also add info about store (storename, URI)? if ($store) { $meta_block->set('dc:source', $graph->resource($storeurl)); } // $meta_block->set('dc:title', 'Co-references from sameAs.org for ' . $symbol); if (isset($this->appOptions['license']['url'])) { $meta_block->add('dct:license', $graph->resource($this->appOptions['license']['url'])); } // list if ($format === 'list') { // simple list foreach ($data as $str) { if (strpos($str, 'http') === 0) { // resource $result_block->add($predicate, $graph->resource(urldecode($str))); } else { // literal values - not technically correct, because sameAs expects a resource // but validates in W3C Validator $result_block->add($predicate, $str); } } } elseif ($format === 'table') { // table output // data is in the form of: // [ [header1, header2, ...], [row1_1, row1_2, ...], [row2_1, row2_2, ...] ] $preds = array_shift($data); foreach ($data as $arr) { // if (isset($val['url'])) { // $url = $val['url']; // unset($val['url']); // } else { // $url = $graph_uri; // } $resources = array(); for ($i = 0, $s = count($arr); $i < $s; $i++) { $resources[$i] = $graph->resource($storeurl); // TODO for ($k = 0, $t = count($preds); $k < $t; $k++) { if (strpos($arr[$i], 'http') === 0) { // resource $graph->addResource($resources[$i], $preds[$k], $graph->resource(urldecode($arr[$i]))); } else { // literal $graph->addLiteral($resources[$i], $preds[$k], urldecode($arr[$i])); } } } } } else { // keyed = 'arbitrary' output format (e.g. for analysis) // Accepts data in the form of: // [ [ $key1 => $value1 ], [ $key2 => $value2 ], [...] ] // Will take key as predicate and // value as resource (if url) or literal $resource = $graph->resource($storeurl); foreach ($data as $key => $value) { if (strpos($value, 'http') === 0) { // resource $graph->addResource($resource, $key, $graph->resource(urldecode($value))); } else { // literal $graph->addLiteral($resource, $key, $value); } } } // ------ // output // ------ if ($this->mimeBest === 'application/rdf+xml') { $outFormat = 'rdf'; } else { $outFormat = 'turtle'; } $data = $graph->serialise($outFormat); if (!is_scalar($data)) { $data = var_export($data, true); } $this->app->response->setBody($data); $this->app->stop(); }
/** * Saves RDF in Fedora. * * @param string $uri Resource URI * @param EasyRdf_Resource $graph Graph to save * @param string $transaction Transaction id * * @return null */ public function saveGraph($uri, \EasyRdf_Graph $graph, $transaction = "") { // Serialze the rdf. $turtle = $graph->serialise('turtle'); // Checksum it. $checksum = sha1($turtle); // Save it. return $this->saveResource($uri, $turtle, ['Content-Type' => 'text/turtle'], $transaction, $checksum); }
<?php require_once __DIR__ . '/../vendor/autoload.php'; // Prepare app $app = new Slim(array('negotiation.enabled' => true)); // Setup routes $app->get('/', function () use($app) { $format = $app->respondTo('html', 'rdf', 'ttl', 'json', 'nt'); switch ($format) { case 'html': return $app->redirect('http://www.aelius.com/njh/', 303); default: $rootUrl = $app->request()->getUrl() . $app->request()->getScriptName(); return $app->redirect("{$rootUrl}/foaf.{$format}", 303); } }); $app->get('/foaf:format', function () use($app) { $format = $app->respondTo('rdf', 'ttl', 'json', 'nt'); $uri = $app->request()->getUrl() . $app->request()->getPath(); $foaf = new EasyRdf_Graph($uri); $foaf->parseFile(__DIR__ . '/../data/foaf.ttl', 'turtle', $uri); $app->response()->body($foaf->serialise($format)); }); // Run app $app->run();
/** * @see https://github.com/njh/easyrdf/issues/209 */ public function testIssue209() { $g = new EasyRdf_Graph(); $g->add('http://example.com/resource', 'rdf:type', new EasyRdf_Resource('foaf:Person')); $g->add('http://example.com/resource', 'rdf:type', new EasyRdf_Resource('http://example.com/TypeA')); $xml = $g->serialise('rdfxml'); $g2 = new EasyRdf_Graph('http://example.com/', $xml, 'rdfxml'); $types = $g2->resource('http://example.com/resource')->typesAsResources(); $expected = array('http://example.com/TypeA', 'http://xmlns.com/foaf/0.1/Person'); $this->assertCount(2, $types); $this->assertContains($types[0]->getUri(), $expected); $this->assertContains($types[1]->getUri(), $expected); }
$uniqid = uniqid(); $suchbegriff = str_replace(" ", "+", $_GET["qname"]); //$suchbegriff='123apfelkuchen'; $rdf = ""; if (isset($_GET["rdf"])) { $rdf = $_GET["rdf"]; } $basedir = dirname(realpath(__FILE__)); $root = $basedir; $ldfu = $root . '/ldfu/bin/ldfu.sh'; $n3_programm = $root . '/n3-files/chefkoch.n3'; $input = 'http://manke-hosting.de/wrapper/index.php/explore/' . $suchbegriff; $output = $root . '/output/' . $suchbegriff . '.nt'; if (!file_exists($output)) { $command = 'sh ' . $ldfu . ' ' . '-i ' . $input . ' ' . '-p ' . $n3_programm . ' ' . '-o ' . $output; shell_exec($command); } $graph->parseFile($output); //$graph ->parseFile('/Users/raphaelmanke/Downloads/linked-data-fu-0.9.9/streuselkuchen3.nt'); //$me = $foaf->primaryTopic(); //echo $graph->dump('html'); $resources = $graph->resources(); $namespace = new EasyRdf_Namespace(); $namespace->set('rezept', "http://manke-hosting.de/ns-syntax#"); $rezepte = $graph->resourcesMatching('rezept:RezeptName'); if ($rdf == "true") { header("Content-Type: text/turtle; charset=utf-8"); echo $graph->serialise("turtle"); } else { include 'results/rezept.php'; }
function convert_to_rdf($path) { //get processed array $uris = get_uris(); $result = process_spreadsheet($path); init_vocabularies(); global $voc_keys; $root = new EasyRdf_Graph(); $courses = $root->newBNode('rdf:Seq'); //create container //iterate through array and create nodes foreach ($result as $key => $value) { $resource_uri = $uris[$key]; $temp_cours = new EasyRdf_Resource($resource_uri, $root); $courses->append($temp_cours); foreach ($value as $propName => $propValue) { if ($propName == null || $propName == "" || $propName == "id") { continue; } $predicate_url = $voc_keys[$propName]; //add to resource predicate with property. probably addLiteral method $temp_cours->addLiteral($predicate_url, $propValue); } } return $root->serialise("rdfxml"); }
public function testSerialiseByFormatObject() { $format = EasyRdf_Format::register('mock', 'Mock Format'); $format->setSerialiserClass('Mock_RdfSerialiser'); $graph = new EasyRdf_Graph(); $this->assertSame("<rdf></rdf>", $graph->serialise($format)); }
function del_friend($uri, $format = 'rdfxml') { $uri = urldecode($uri); $path = $this->get_local_path($this->webid); // Create the new graph object in which we store data $graph = new EasyRdf_Graph($this->webid); $graph->load(); $person = $graph->resource($this->webid); $graph->deleteResource($person, 'foaf:knows', $uri); // write profile to file $data = $graph->serialise($format); if (!is_scalar($data)) { $data = var_export($data, true); } else { $data = print_r($data, true); } $pf = fopen($path . '/foaf.rdf', 'w') or die('Cannot open profile RDF file!'); fwrite($pf, $data); fclose($pf); $pf = fopen($path . '/foaf.txt', 'w') or die('Cannot open profile TXT file!'); fwrite($pf, $data); fclose($pf); // get the user's name $friend = new MyProfile($uri, $this->base_uri, SPARQL_ENDPOINT); $friend->load(); // everything is fine return success("You have just removed " . $friend->get_name() . " from your list of friends."); }
<body> <h1>EasyRdf Serialiser Example</h1> <ul> <?php foreach (EasyRdf_Format::getFormats() as $f) { if ($f->getSerialiserClass()) { if ($f->getName() == $format) { print "<li><b>" . $f->getLabel() . "</b></li>\n"; } else { print "<li><a href='?format={$f}'>"; print $f->getLabel() . "</a></li>\n"; } } } ?> </ul> <pre style="margin: 0.5em; padding:0.5em; background-color:#eee; border:dashed 1px grey;"> <?php $data = $graph->serialise($format); if (!is_scalar($data)) { $data = var_export($data, true); } print htmlspecialchars($data); ?> </pre> </body> </html>
/** * Transforms the statements of a StatementIterator instance into a stream, a file for instance. * * @param StatementIterator $statements The StatementIterator containing all the Statements which * should be serialized by the serializer. * @param string|resource $outputStream Filename or file pointer to the stream to where the serialization * should be written. * @throws \Exception if unknown serilaization was given. */ public function serializeIteratorToStream(StatementIterator $statements, $outputStream) { /* * check parameter $outputStream */ if (is_resource($outputStream)) { // use it as it is } elseif (is_string($outputStream)) { $outputStream = fopen($outputStream, 'w'); } else { throw new \Exception('Parameter $outputStream is neither a string nor resource.'); } $graph = new \EasyRdf_Graph(); // go through all statements foreach ($statements as $statement) { /* * Handle subject */ $stmtSubject = $statement->getSubject(); if ($stmtSubject->isNamed()) { $s = $stmtSubject->getUri(); } elseif ($stmtSubject->isBlank()) { $s = $stmtSubject->getBlankId(); } else { throw new \Exception('Subject can either be a blank node or an URI.'); } /* * Handle predicate */ $stmtPredicate = $statement->getPredicate(); if ($stmtPredicate->isNamed()) { $p = $stmtPredicate->getUri(); } else { throw new \Exception('Predicate can only be an URI.'); } /* * Handle object */ $stmtObject = $statement->getObject(); if ($stmtObject->isNamed()) { $o = array('type' => 'uri', 'value' => $stmtObject->getUri()); } elseif ($stmtObject->isBlank()) { $o = array('type' => 'bnode', 'value' => $stmtObject->getBlankId()); } elseif ($stmtObject->isLiteral()) { $o = array('type' => 'literal', 'value' => $stmtObject->getValue()); } else { throw new \Exception('Object can either be a blank node, an URI or literal.'); } $graph->add($s, $p, $o); } fwrite($outputStream, $graph->serialise($this->serialization) . PHP_EOL); }
public static function getBody($dataObj) { // Query parameters $query_string = ''; if (!empty($_GET)) { $query_string = '?' . http_build_query(\Input::all()); } // Links to pages $prev_link = ''; $next_link = ''; if (!empty($dataObj->paging)) { $input_array = array_except(\Input::all(), array('limit', 'offset')); $query_string = ''; if (!empty($input_array)) { $query_string = '&' . http_build_query($input_array); } if (!empty($dataObj->paging['previous'])) { $prev_link = '?offset=' . $dataObj->paging['previous'][0] . '&limit=' . $dataObj->paging['previous'][1] . $query_string; } if (!empty($dataObj->paging['next'])) { $next_link = '?offset=' . $dataObj->paging['next'][0] . '&limit=' . $dataObj->paging['next'][1] . $query_string; } } // Create the link to the dataset $dataset_link = \URL::to($dataObj->definition['collection_uri'] . "/" . $dataObj->definition['resource_name']); // Append rest parameters if (!empty($dataObj->rest_parameters)) { $dataset_link .= '/' . implode('/', $dataObj->rest_parameters); } if (!empty($dataObj->source_definition)) { $type = $dataObj->source_definition['type']; // Check if other views need to be served switch ($type) { case 'XLS': case 'CSV': $first_row = array_shift($dataObj->data); array_unshift($dataObj->data, $first_row); if (is_array($first_row) || is_object($first_row)) { $view = 'dataset.tabular'; $data = $dataObj->data; } else { $view = 'dataset.code'; $data = self::displayTree($dataObj->data); } break; case 'SHP': $view = 'dataset.map'; $data = $dataset_link . '.map' . $query_string; break; case 'XML': $view = 'dataset.code'; $data = self::displayTree($dataObj->data, 'xml'); break; default: if ($dataObj->is_semantic) { // This data object is always semantic $view = 'dataset.turtle'; // Check if a configuration is given $conf = array(); if (!empty($dataObj->semantic->conf)) { $conf = $dataObj->semantic->conf; } $data = $dataObj->data->serialise('turtle'); } else { $view = 'dataset.code'; $data = self::displayTree($dataObj->data); } break; } } elseif ($dataObj->is_semantic) { // The data object can be semantic without a specified source type $view = 'dataset.code'; $data = $dataObj->data->serialise('turtle'); } else { // Collection view $view = 'dataset.collection'; $data = $dataObj->data; } // Gather meta-data to inject as a JSON-LD document so it can be picked up by search engines $definition = $dataObj->definition; $uri = \Request::root(); $graph = new \EasyRdf_Graph(); // Create the dataset uri $dataset_uri = $uri . "/" . $definition['collection_uri'] . "/" . $definition['resource_name']; $dataset_uri = str_replace(' ', '%20', $dataset_uri); // Add the dataset resource and its description $graph->addResource($dataset_uri, 'a', 'schema:Dataset'); // Add the title to the dataset resource of the catalog if (!empty($definition['title'])) { $graph->addLiteral($dataset_uri, 'schema:headline', $definition['title']); } // Add the description, identifier, issues, modified of the dataset $graph->addLiteral($dataset_uri, 'schema:description', @$definition['description']); $graph->addLiteral($dataset_uri, 'schema:dateCreated', date(\DateTime::ISO8601, strtotime($definition['created_at']))); $graph->addLiteral($dataset_uri, 'schema:dateModified', date(\DateTime::ISO8601, strtotime($definition['updated_at']))); // Add the publisher resource to the dataset if (!empty($definition['publisher_name']) && !empty($definition['publisher_uri'])) { $graph->addResource($dataset_uri, 'schema:publisher', $definition['publisher_uri']); } // Optional dct terms $optional = array('date', 'language'); $languages = \App::make('Tdt\\Core\\Repositories\\Interfaces\\LanguageRepositoryInterface'); $licenses = \App::make('Tdt\\Core\\Repositories\\Interfaces\\LicenseRepositoryInterface'); foreach ($optional as $dc_term) { if (!empty($definition[$dc_term])) { if ($dc_term == 'language') { $lang = $languages->getByName($definition[$dc_term]); if (!empty($lang)) { $graph->addResource($dataset_uri, 'schema:inLanguage', 'http://lexvo.org/id/iso639-3/' . $lang['lang_id']); } } else { $graph->addLiteral($dataset_uri, 'schema:datasetTimeInterval', $definition[$dc_term]); } } } // Add the distribution of the dataset for SEO $format = '.json'; if ($definition['source_type'] == 'ShpDefinition') { $format = '.geojson'; } $dataDownload = $graph->newBNode(); $graph->addResource($dataset_uri, 'schema:distribution', $dataDownload); $graph->addResource($dataDownload, 'a', 'schema:DataDownload'); $graph->addResource($dataDownload, 'schema:contentUrl', $dataset_uri . $format); // Add the license to the distribution if (!empty($definition['rights'])) { $license = $licenses->getByTitle($definition['rights']); if (!empty($license) && !empty($license['url'])) { $graph->addResource($dataset_uri, 'schema:license', $license['url']); } if (!empty($license)) { $dataObj->definition['rights_uri'] = $license['url']; } } $jsonld = $graph->serialise('jsonld'); // Render the view return \View::make($view)->with('title', 'Dataset: ' . $dataObj->definition['collection_uri'] . "/" . $dataObj->definition['resource_name'] . ' | The Datatank')->with('body', $data)->with('page_title', $dataObj->definition['collection_uri'] . "/" . $dataObj->definition['resource_name'])->with('definition', $dataObj->definition)->with('paging', $dataObj->paging)->with('source_definition', $dataObj->source_definition)->with('formats', $dataObj->formats)->with('dataset_link', $dataset_link)->with('prev_link', $prev_link)->with('next_link', $next_link)->with('query_string', $query_string)->with('json_ld', $jsonld); }
print reset_tag() . submit_tag(); print form_end_tag(); print "</div>\n"; } if (isset($_REQUEST['uri']) or isset($_REQUEST['data'])) { // Parse the input $graph = new EasyRdf_Graph($_REQUEST['uri']); if (empty($_REQUEST['data'])) { $graph->load($_REQUEST['uri'], $_REQUEST['input_format']); } else { $graph->parse($_REQUEST['data'], $_REQUEST['input_format'], $_REQUEST['uri']); } // Lookup the output format $format = EasyRdf_Format::getFormat($_REQUEST['output_format']); // Serialise to the new output format $output = $graph->serialise($format); if (!is_scalar($output)) { $output = var_export($output, true); } // Send the output back to the client if (isset($_REQUEST['raw'])) { header('Content-Type: ' . $format->getDefaultMimeType()); print $output; } else { print '<pre>' . htmlspecialchars($output) . '</pre>'; } } if (!isset($_REQUEST['raw'])) { print "</body>\n"; print "</html>\n"; }
public function testSerialiseByMime() { EasyRdf_Format::registerSerialiser('mock', 'Mock_RdfSerialiser'); EasyRdf_Format::register('mock', 'Mock', null, array('mock/mime' => 1.0)); $graph = new EasyRdf_Graph(); $this->assertEquals("<rdf></rdf>", $graph->serialise('mock/mime')); }
// Start building up a RDF graph $doap = new EasyRdf_Graph($composer->homepage . 'doap.rdf'); $easyrdf = $doap->resource('#easyrdf', 'doap:Project', 'foaf:Project'); $easyrdf->addLiteral('doap:name', 'EasyRDF'); $easyrdf->addLiteral('doap:shortname', 'easyrdf'); $easyrdf->addLiteral('doap:revision', $composer->version); $easyrdf->addLiteral('doap:shortdesc', $composer->description, 'en'); $easyrdf->addResource('doap:homepage', $composer->homepage); $easyrdf->addLiteral('doap:programming-language', 'PHP'); $easyrdf->addLiteral('doap:description', 'EasyRdf is a PHP library designed to make it easy to consume and produce RDF. ' . 'It was designed for use in mixed teams of experienced and inexperienced RDF developers. ' . 'It is written in Object Oriented PHP and has been tested extensively using PHPUnit.', 'en'); $easyrdf->addResource('doap:license', 'http://usefulinc.com/doap/licenses/bsd'); $easyrdf->addResource('doap:download-page', 'http://github.com/njh/easyrdf/downloads'); $easyrdf->addResource('doap:download-page', 'http://github.com/njh/easyrdf/downloads'); $easyrdf->addResource('doap:bug-database', 'http://github.com/njh/easyrdf/issues'); $easyrdf->addResource('doap:mailing-list', 'http://groups.google.com/group/easyrdf'); $easyrdf->addResource('doap:category', 'http://dbpedia.org/resource/Resource_Description_Framework'); $easyrdf->addResource('doap:category', 'http://dbpedia.org/resource/PHP'); $easyrdf->addResource('doap:category', 'http://dbpedialite.org/things/24131#id'); $easyrdf->addResource('doap:category', 'http://dbpedialite.org/things/53847#id'); $repository = $doap->newBNode('doap:GitRepository'); $repository->addResource('doap:browse', 'http://github.com/njh/easyrdf'); $repository->addResource('doap:location', 'git://github.com/njh/easyrdf.git'); $easyrdf->addResource('doap:repository', $repository); $njh = $doap->resource('http://njh.me/', 'foaf:Person'); $njh->addLiteral('foaf:name', 'Nicholas J Humfrey'); $njh->addResource('foaf:homepage', 'http://www.aelius.com/njh/'); $easyrdf->add('doap:maintainer', $njh); $easyrdf->add('doap:developer', $njh); $easyrdf->add('foaf:maker', $njh); print $doap->serialise('rdfxml');
<?php include_once "./header.php"; require 'vendor/autoload.php'; require_once "html_tag_helpers.php"; $graph = new EasyRdf_Graph("http://localhost/lod/tcmdemoen.rdf"); $graph->load(); echo "The count is: " . $graph->countTriples(); $data = $graph->serialise('ntriples'); if (!is_scalar($data)) { $data = var_export($data, true); } //print htmlspecialchars($data); //$me = $graph->resource('http://www.example.com/Huperzia_Serrata'); $me = $graph->resource('http://www.example.com/fourGentlemenDecoction'); echo "<p>http://www.example.com/Huperzia_Serrata 的标签是: " . $me->get('rdfs:label') . "</p>"; echo "<p>http://www.example.com/Huperzia_Serrata 的中文标签是: " . $me->label('zh') . "</p>"; echo "<p>http://www.example.com/Huperzia_Serrata 的英文标签是: " . $me->label('en') . "</p>"; $hasMinister = $graph->resource('http://www.example.com/hasMinister'); echo "<p>http://www.example.com/hasMinister 的标签是: " . $hasMinister->get('rdfs:label') . "</p>"; $graph->allResources($me, $hasMinister); foreach ($me->all($hasMinister) as $type) { echo 'start'; $label = $type->label('zh'); if (!$label) { $label = $type->getUri(); } if ($type->isBnode()) { echo "<li>{$label}</li>"; } else { echo "<li>" . link_to_self($label, 'uri=' . urlencode($friend)) . "</li>";