Ejemplo n.º 1
0
 /**
  * @param Resource|Graph $resourceOrGraph
  * @param array    $frame
  *
  * @return Graph
  */
 public function getGraph($resourceOrGraph, $frame = null)
 {
     if ($resourceOrGraph instanceof Graph) {
         return $resourceOrGraph;
     }
     return $resourceOrGraph->getGraph();
 }
Ejemplo n.º 2
0
 public function testMinus()
 {
     $graph1 = new Graph();
     $graph1->add('http://www.example.com/jdoe#jdoe', 'foaf:name', 'John Doe');
     $graph2 = new Graph();
     $graph2->add('http://www.example.com/jdoe#jdoe', 'foaf:name', 'Foo Bar');
     $uow = new UnitOfWork($this->manager, 'fooUrl');
     $this->assertEquals(1, 1);
 }
Ejemplo n.º 3
0
 /**
  * Method to serialise an EasyRdf\Graph to RDF/PHP
  *
  * http://n2.talis.com/wiki/RDF_PHP_Specification
  * docs/appendix-a-rdf-formats-php.md
  *
  * @param Graph  $graph  An EasyRdf\Graph object.
  * @param string $format The name of the format to convert to.
  * @param array  $options
  *
  * @return string The RDF in the new desired format.
  * @throws Exception
  */
 public function serialise(Graph $graph, $format, array $options = array())
 {
     parent::checkSerialiseParams($format);
     if ($format != 'php') {
         throw new Exception(__CLASS__ . " does not support: {$format}");
     }
     // Graph is already stored as RDF/PHP resource-centric array internally within the EasyRdf\Graph object
     return $graph->toRdfPhp();
 }
Ejemplo n.º 4
0
 protected function processUri($uri)
 {
     echo "Accessing {$uri}...\n";
     $retries = 3;
     while (true) {
         try {
             $graph = Graph::newAndLoad($uri);
             break;
         } catch (\Exception $e) {
             $retries--;
             if ($retries < 0) {
                 throw $e;
             }
             echo "Error! Sleeping for 10 secs, then retrying ({$retries} tries left)...\n";
             sleep(10);
         }
     }
     $triples = $graph->serialise('ntriples');
     fwrite($this->handle, $triples);
     $this->visited[] = $uri;
     preg_match_all('/<(https?:\\/\\/[^>]*)>/', $triples, $matches);
     foreach (array_unique($matches[1]) as $uri) {
         $this->enqueue($uri);
     }
 }
Ejemplo n.º 5
0
 /**
  * @throws \Twig_Error_Loader
  */
 public function testSerialize()
 {
     $loader = new JsonLdFrameLoader();
     $loader->addPath(__DIR__ . '/Fixtures', 'namespace');
     $registry = new RdfNamespaceRegistry();
     $foaf = new Graph('http://njh.me/foaf.rdf');
     $foaf->parseFile(__DIR__ . '/Fixtures/foaf.rdf');
     $graphProvider = new SimpleGraphProvider();
     $metadataFactory = $this->getMockBuilder('Metadata\\MetadataFactory')->disableOriginalConstructor()->getMock();
     // new MetadataFactory();
     $resource = $foaf->primaryTopic();
     $serializer = new JsonLdSerializer($registry, $loader, $graphProvider, $metadataFactory);
     $serialized = $serializer->serialize($resource, '@namespace/frame.jsonld');
     $decoded = json_decode($serialized, true);
     $this->assertEquals($resource->get('foaf:name'), $decoded['@graph'][0]['foaf:name']);
 }
Ejemplo n.º 6
0
 /**
  * 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.
  * @param  string            $serialization The serialization which should be used. If null is given the
  *                                          serializer will either apply some default serialization, or
  *                                          the only one it is supporting, or will throw an Exception.
  * @throws \Exception If unknown serilaization was given.
  */
 public function serializeIteratorToStream(StatementIterator $statements, $outputStream, $serialization = null)
 {
     /*
      * 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.');
     }
     // if no format was given, serialize to turtle.
     if (null == $serialization) {
         $format = 'turtle';
     }
     if (false === isset($this->serializationMap[$serialization])) {
         throw new \Exception('Unknown serialization given: ' . $serialization);
     }
     $graph = new 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->serializationMap[$serialization]) . PHP_EOL);
 }
Ejemplo n.º 7
0
 /**
  * Seed the themes
  *
  * return @void
  */
 private function seedThemes()
 {
     $this->info('---- Seeding new themes ----');
     $base_uri = $this->argument('uri');
     $taxonomy_uri = $this->argument('taxonomy_uri');
     if (empty($taxonomy_uri)) {
         $taxonomy_uri = $base_uri;
     }
     // Try to get the themes from the ns.thedatatank.com (semantic data)
     try {
         $this->info('Trying to fetch triples from the uri: ' . $base_uri);
         $themes_graph = Graph::newAndLoad($base_uri);
         if ($themes_graph->isEmpty()) {
             $this->info('We could not reach the online themes.');
         } else {
             $this->info('Found new themes online, removing the old ones.');
             // Empty the themes table
             \Theme::truncate();
         }
         // Fetch the resources with a skos:conceptScheme relationship
         $resources = $themes_graph->allOfType('skos:ConceptScheme');
         $taxonomy_uris = array();
         foreach ($resources as $r) {
             array_push($taxonomy_uris, $r->getUri());
         }
         if (!empty($taxonomy_uris)) {
             if (count($taxonomy_uris) == 1) {
                 $taxonomy_uri = $taxonomy_uris[0];
             } else {
                 // Check if one of the possible taxonomy uris compares to the uri of the document
                 foreach ($taxonomy_uris as $tax_uri) {
                     if ($base_uri == $tax_uri) {
                         $taxonomy_uri = $tax_uri;
                         break;
                     }
                     $this->error('None of the URIs that have the skos:ConceptScheme property matched the URI of the document, please specify the taxonomy URI as a second parameter.');
                 }
             }
         } else {
             $this->error('No resource has been found with a property of skos:ConceptScheme.');
         }
         // Fetch all of the themes
         foreach ($themes_graph->resourcesMatching('skos:inScheme') as $theme) {
             if ($theme->get('skos:inScheme')->getUri() == $taxonomy_uri) {
                 $uri = $theme->getUri();
                 $label = $theme->getLiteral('rdfs:label');
                 if (!empty($label) && !empty($uri)) {
                     $label = $label->getValue();
                     $this->info('Added ' . $uri . ' with label ' . $label);
                     \Theme::create(array('uri' => $uri, 'label' => $label));
                 }
             }
         }
         $this->info('Added new themes.');
     } catch (Exception $ex) {
         $this->info('An error occurred when we tried to fetch online themes.');
     }
 }
Ejemplo n.º 8
0
 /**
  * Seed the themes
  *
  * return @void
  */
 private function seedThemes()
 {
     $this->command->info('---- DCAT Themes ----');
     $uri = 'http://ns.thedatatank.com/dcat/themes#Taxonomy';
     $themes_fetched = false;
     // Try to get the themes from the ns.thedatatank.com (semantic data)
     try {
         $this->command->info('Trying to fetch new themes online.');
         $themes_graph = Graph::newAndLoad($uri);
         if ($themes_graph->isEmpty()) {
             $this->command->info('We could not reach the online themes.');
         } else {
             $themes_fetched = true;
             $this->command->info('Found new themes online, removing the old ones.');
             // Empty the themes table
             \Theme::truncate();
         }
         // Fetch all of the themes
         foreach ($themes_graph->resourcesMatching('skos:inScheme') as $theme) {
             if ($theme->get('skos:inScheme')->getUri() == $uri) {
                 $theme_uri = $theme->getUri();
                 $label = $theme->getLiteral('rdfs:label');
                 if (!empty($label) && !empty($theme_uri)) {
                     $label = $label->getValue();
                     $this->command->info('Added ' . $uri . ' with label ' . $label);
                     \Theme::create(array('uri' => $theme_uri, 'label' => $label));
                 }
             }
         }
         $this->command->info('Added new themes.');
     } catch (Exception $ex) {
         $this->command->info('An error occurred when we tried to fetch online themes.');
     }
     // If it's not available, get them from a file (json)
     if (!$themes_fetched) {
         $this->command->info('Trying to fetch the themes from the local json file containing a default set of themes.');
         $themes = json_decode(file_get_contents(app_path() . '/database/seeds/data/themes.json'));
         if (!empty($themes)) {
             $this->command->info('Found new themes, removing the old ones.');
             // Empty the themes table
             \Theme::truncate();
             foreach ($themes as $theme) {
                 \Theme::create(array('uri' => $theme->uri, 'label' => $theme->label));
             }
             if (!empty($themes)) {
                 $this->command->info('Added themes from the local json file.');
             }
         } else {
             $this->command->info('No themes were found in the local json file, the old ones will not be replaced.');
         }
     }
 }
Ejemplo n.º 9
0
 /**
  * @ignore
  */
 protected function serialiseSubjects(Graph $graph, $filterType)
 {
     $turtle = '';
     foreach ($graph->resources() as $resource) {
         /** @var $resource Resource */
         // If the resource has no properties - don't serialise it
         $properties = $resource->propertyUris();
         if (count($properties) == 0) {
             continue;
         }
         // Is this node of the right type?
         $thisType = $resource->isBNode() ? 'bnode' : 'uri';
         if ($thisType != $filterType) {
             continue;
         }
         if ($thisType == 'bnode') {
             $id = $resource->getBNodeId();
             if (isset($this->outputtedBnodes[$id])) {
                 // Already been serialised
                 continue;
             }
             $this->outputtedBnodes[$id] = true;
             $rpcount = $this->reversePropertyCount($resource);
             if ($rpcount == 0) {
                 $turtle .= '[]';
             } else {
                 $turtle .= $this->serialiseResource($resource);
             }
         } else {
             $turtle .= $this->serialiseResource($resource);
         }
         $turtle .= $this->serialiseProperties($resource);
         $turtle .= "\n";
     }
     return $turtle;
 }
Ejemplo n.º 10
0
 /**
  * Fetch the default licenses
  *
  * @return \EasyRdf_Graph
  */
 private function fetchDefaultGraph()
 {
     $license_uri = $this->licenses_uri . $this->DEFAULT_LICENSE . '.json';
     return Graph::newAndLoad($license_uri, 'jsonld');
 }
Ejemplo n.º 11
0
 /**
  * Serialise an EasyRdf\Graph into a JSON-LD document.
  *
  * @param Graph  $graph  An EasyRdf\Graph object.
  * @param string $format The name of the format to convert to.
  * @param array  $options
  *
  * @return string The RDF in the new desired format.
  * @throws Exception
  */
 public function serialise(Graph $graph, $format, array $options = array())
 {
     parent::checkSerialiseParams($format);
     if ($format != 'jsonld') {
         throw new Exception(__CLASS__ . ' does not support: ' . $format);
     }
     $ld_graph = new LD\Graph();
     $nodes = array();
     // cache for id-to-node association
     foreach ($graph->toRdfPhp() as $resource => $properties) {
         if (array_key_exists($resource, $nodes)) {
             $node = $nodes[$resource];
         } else {
             $node = $ld_graph->createNode($resource);
             $nodes[$resource] = $node;
         }
         foreach ($properties as $property => $values) {
             foreach ($values as $value) {
                 if ($value['type'] == 'bnode' or $value['type'] == 'uri') {
                     if (array_key_exists($value['value'], $nodes)) {
                         $_value = $nodes[$value['value']];
                     } else {
                         $_value = $ld_graph->createNode($value['value']);
                         $nodes[$value['value']] = $_value;
                     }
                 } elseif ($value['type'] == 'literal') {
                     if (isset($value['lang'])) {
                         $_value = new LD\LanguageTaggedString($value['value'], $value['lang']);
                     } elseif (isset($value['datatype'])) {
                         $_value = new LD\TypedValue($value['value'], $value['datatype']);
                     } else {
                         $_value = $value['value'];
                     }
                 } else {
                     throw new Exception("Unable to serialise object to JSON-LD: " . $value['type']);
                 }
                 if ($property == "http://www.w3.org/1999/02/22-rdf-syntax-ns#type") {
                     $node->addType($_value);
                 } else {
                     $node->addPropertyValue($property, $_value);
                 }
             }
         }
     }
     // OPTIONS
     $use_native_types = !(isset($options['expand_native_types']) and $options['expand_native_types'] == true);
     $should_compact = (isset($options['compact']) and $options['compact'] == true);
     $should_frame = isset($options['frame']);
     // expanded form
     $data = $ld_graph->toJsonLd($use_native_types);
     if ($should_frame) {
         $data = LD\JsonLD::frame($data, $options['frame'], $options);
     }
     if ($should_compact) {
         // compact form
         $compact_context = isset($options['context']) ? $options['context'] : null;
         $compact_options = array('useNativeTypes' => $use_native_types, 'base' => $graph->getUri());
         $data = LD\JsonLD::compact($data, $compact_context, $compact_options);
     }
     return LD\JsonLD::toString($data);
 }
Ejemplo n.º 12
0
 /**
  * temp function : converting a result to a graph.
  *
  * @param Result $result
  *
  * @return Graph
  */
 private function resultToGraph($result)
 {
     if ($result instanceof Graph) {
         return $result;
     }
     $graph = new Graph(null);
     foreach ($result as $row) {
         $graph->add($row->subject, $row->predicate, $row->object);
     }
     return $graph;
 }
Ejemplo n.º 13
0
 /**
  * Parses a given stream and returns an iterator containing Statement instances representing the
  * previously read data. The stream parses the data not as a whole but in chunks.
  *
  * @param  string            $inputStream   Filename of the stream to parse which contains RDF
  *                                          serialized data.
  * @param  string            $baseUri       The base URI of the parsed content. If this URI is null
  *                                          the inputStreams URL is taken as base URI.
  * @param  string            $serialization The serialization of the inputStream. If null is given
  *                                          the parser will either apply some standard serialization,
  *                                          or the only one it is supporting, or will try to guess
  *                                          the correct serialization, or will throw an Exception.
  *                                          Supported formats are a subset of the following:
  *                                          json, rdfxml, sparql-xml, rdfa, turtle, ntriples, n3
  * @return StatementIterator A StatementIterator containing all the Statements parsed by the parser to
  *                           far.
  * @throws \Exception        If the base URI $baseUri is no valid URI.
  */
 public function parseStreamToIterator($inputStream, $baseUri = null, $serialization = null)
 {
     $graph = new Graph();
     // let EasyRdf guess the format
     if ($serialization === null) {
         // use PHP's file:// stream, if its a local file
         if (false === strpos($inputStream, '://')) {
             $inputStream = 'file://' . $inputStream;
         }
         $serialization = Format::guessFormat(file_get_contents($inputStream));
     } else {
         $serialization = Format::getFormat($serialization);
     }
     // if format is still null, throw exception, because we dont know what format the given stream is
     if (null === $serialization) {
         throw new \Exception('Either given $format is unknown or i could not guess format.');
     }
     $graph->parseFile($inputStream, $serialization->getName());
     // transform parsed data to PHP array
     return $this->rdfPhpToStatementIterator($graph->toRdfPhp());
 }
Ejemplo n.º 14
0
 /**
  *
  */
 public function setBNodes($uri, $property, Graph $graph)
 {
     $uri = $this->_rm->getNamespaceRegistry()->expand($uri);
     if (empty($this->registeredResources[$uri])) {
         throw new Exception('no parent resource');
     }
     /** @var \Conjecto\Nemrod\Resource $owningResource */
     $owningResource = $this->registeredResources[$uri];
     /* @var Graph $graph */
     $owningGraph = $owningResource->getGraph();
     $owningGraph->delete($uri, $property);
     /** @var BaseResource $res */
     foreach ($graph->allResources($uri, $property) as $res) {
         $bnode = $owningGraph->newBNode();
         $owningGraph->add($uri, $property, $bnode);
         $rdfPhp = $res->getGraph()->toRdfPhp();
         //
         if (!empty($rdfPhp[$res->getUri()])) {
             foreach ($rdfPhp[$res->getUri()] as $prop => $vals) {
                 foreach ($vals as $val) {
                     $bnode->set($prop, $val['value']);
                 }
             }
         }
     }
 }
Ejemplo n.º 15
0
<?php

use EasyRdf\Graph;
use EasyRdf\Format;
use EasyRdf\Serialiser\GraphViz;
$app->get('/image', function () {
    $graph = Graph::newAndLoad(site_base_uri() . '/asset/dataset/countries.rdf');
    $format = Format::getFormat('png');
    $viz = new GraphViz();
    header("Content-Type: " . $format->getDefaultMimeType());
    echo $viz->renderImage($graph, $format);
    die;
})->name('home');
Ejemplo n.º 16
0
 /**
  * Internal function to serialise an EasyRdf\Graph into a DOT formatted string
  *
  * @ignore
  */
 protected function serialiseDot(Graph $graph)
 {
     $result = "digraph {\n";
     // Write the graph attributes
     foreach ($this->attributes as $k => $v) {
         $result .= '  ' . $this->escape($k) . '=' . $this->escape($v) . ";\n";
     }
     // Go through each of the properties and write the edges
     $nodes = array();
     $result .= "\n  // Edges\n";
     foreach ($graph->resources() as $resource) {
         $name1 = $this->nodeName($resource);
         foreach ($resource->propertyUris() as $property) {
             $label = null;
             if ($this->useLabels) {
                 $label = $graph->resource($property)->label();
             }
             if ($label === null) {
                 if ($this->onlyLabelled == true) {
                     continue;
                 } else {
                     $label = RdfNamespace::shorten($property);
                 }
             }
             foreach ($resource->all("<{$property}>") as $value) {
                 $name2 = $this->nodeName($value);
                 $nodes[$name1] = $resource;
                 $nodes[$name2] = $value;
                 $result .= $this->serialiseRow($name1, $name2, array('label' => $label));
             }
         }
     }
     ksort($nodes);
     $result .= "\n  // Nodes\n";
     foreach ($nodes as $name => $node) {
         $type = substr($name, 0, 1);
         $label = '';
         if ($type == 'R') {
             if ($this->useLabels) {
                 $label = $node->label();
             }
             if (!$label) {
                 $label = $node->shorten();
             }
             if (!$label) {
                 $label = $node->getURI();
             }
             $result .= $this->serialiseRow($name, null, array('URL' => $node->getURI(), 'label' => $label, 'shape' => 'ellipse', 'color' => 'blue'));
         } elseif ($type == 'B') {
             if ($this->useLabels) {
                 $label = $node->label();
             }
             $result .= $this->serialiseRow($name, null, array('label' => $label, 'shape' => 'circle', 'color' => 'green'));
         } else {
             $result .= $this->serialiseRow($name, null, array('label' => strval($node), 'shape' => 'record'));
         }
     }
     $result .= "}\n";
     return $result;
 }
Ejemplo n.º 17
0
 /**
  * Serialise an EasyRdf\Graph into N-Triples
  *
  * @param Graph  $graph  An EasyRdf\Graph object.
  * @param string $format The name of the format to convert to.
  * @param array  $options
  *
  * @return string The RDF in the new desired format.
  * @throws Exception
  */
 public function serialise(Graph $graph, $format, array $options = array())
 {
     parent::checkSerialiseParams($format);
     if ($format == 'ntriples') {
         $nt = '';
         foreach ($graph->toRdfPhp() as $resource => $properties) {
             foreach ($properties as $property => $values) {
                 foreach ($values as $value) {
                     $nt .= $this->serialiseResource($resource) . " ";
                     $nt .= "<" . $this->escapeString($property) . "> ";
                     $nt .= $this->serialiseValue($value) . " .\n";
                 }
             }
         }
         return $nt;
     } else {
         throw new Exception(__CLASS__ . " does not support: {$format}");
     }
 }
Ejemplo n.º 18
0
 /**
  * @return object|array|scalar
  */
 public function getResult()
 {
     return $this->graph->serialise($this->format, $this->options);
 }
Ejemplo n.º 19
0
 /**
  * @param UnitOfWork $uow
  */
 public function __construct(UnitOfWork $uow)
 {
     parent::__construct();
     $this->unitOfWork = $uow;
 }
Ejemplo n.º 20
0
 /**
  * Return a DCAT document based on the definitions that are passed
  *
  * @param array Array with definition configurations
  *
  * @return \EasyRdf_Graph
  */
 public function getDcatDocument(array $definitions, $oldest_definition)
 {
     // Create a new EasyRDF graph
     $graph = new Graph();
     $all_settings = $this->settings->getAll();
     $uri = \Request::root();
     // Add the catalog and a title
     $graph->addResource($uri . '/api/dcat', 'a', 'dcat:Catalog');
     $graph->addLiteral($uri . '/api/dcat', 'dct:title', $all_settings['catalog_title']);
     // Fetch the catalog description, issued date and language
     $graph->addLiteral($uri . '/api/dcat', 'dct:description', $all_settings['catalog_description']);
     $graph->addLiteral($uri . '/api/dcat', 'dct:issued', $this->getIssuedDate());
     $lang = $this->languages->getByCode($all_settings['catalog_language']);
     if (!empty($lang)) {
         $graph->addResource($uri . '/api/dcat', 'dct:language', 'http://lexvo.org/id/iso639-3/' . $lang['lang_id']);
         $graph->addResource('http://lexvo.org/id/iso639-3/' . $lang['lang_id'], 'a', 'dct:LinguisticSystem');
     }
     // Fetch the homepage and rights
     $graph->addResource($uri . '/api/dcat', 'foaf:homepage', $uri);
     $graph->addResource($uri . '/api/dcat', 'dct:license', 'http://www.opendefinition.org/licenses/cc-zero');
     $graph->addResource('http://www.opendefinition.org/licenses/cc-zero', 'a', 'dct:LicenseDocument');
     // Add the publisher resource to the catalog
     $graph->addResource($uri . '/api/dcat', 'dct:publisher', $all_settings['catalog_publisher_uri']);
     $graph->addResource($all_settings['catalog_publisher_uri'], 'a', 'foaf:Agent');
     $graph->addLiteral($all_settings['catalog_publisher_uri'], 'foaf:name', $all_settings['catalog_publisher_name']);
     if (count($definitions) > 0) {
         // Add the last modified timestamp in ISO8601
         $graph->addLiteral($uri . '/api/dcat', 'dct:modified', date(\DateTime::ISO8601, strtotime($oldest_definition['updated_at'])));
         foreach ($definitions as $definition) {
             if ($definition['source_type'] != "InspireDefinition" && $definition['source_type'] != "RemoteDefinition") {
                 // Create the dataset uri
                 $dataset_uri = $uri . "/" . $definition['collection_uri'] . "/" . $definition['resource_name'];
                 $dataset_uri = str_replace(' ', '%20', $dataset_uri);
                 $source_type = $definition['type'];
                 // Add the dataset link to the catalog
                 $graph->addResource($uri . '/api/dcat', 'dcat:dataset', $dataset_uri);
                 // Add the dataset resource and its description
                 $graph->addResource($dataset_uri, 'a', 'dcat:Dataset');
                 $title = null;
                 if (!empty($definition['title'])) {
                     $title = $definition['title'];
                 } else {
                     $title = $definition['collection_uri'] . '/' . $definition['resource_name'];
                 }
                 $graph->addLiteral($dataset_uri, 'dct:title', $title);
                 // Add the description, identifier, issued date, modified date, contact point and landing page of the dataset
                 $graph->addLiteral($dataset_uri, 'dct:description', @$definition['description']);
                 $graph->addLiteral($dataset_uri, 'dct:identifier', str_replace(' ', '%20', $definition['collection_uri'] . '/' . $definition['resource_name']));
                 $graph->addLiteral($dataset_uri, 'dct:issued', date(\DateTime::ISO8601, strtotime($definition['created_at'])));
                 $graph->addLiteral($dataset_uri, 'dct:modified', date(\DateTime::ISO8601, strtotime($definition['updated_at'])));
                 $graph->addResource($dataset_uri, 'dcat:landingPage', $dataset_uri);
                 // Backwards compatibility
                 if (!empty($definition['contact_point'])) {
                     $graph->addResource($dataset_uri, 'dcat:contactPoint', $definition['contact_point']);
                 }
                 // Add the publisher resource to the dataset
                 if (!empty($definition['publisher_name']) && !empty($definition['publisher_uri'])) {
                     $graph->addResource($dataset_uri, 'dct:publisher', $definition['publisher_uri']);
                     $graph->addResource($definition['publisher_uri'], 'a', 'foaf:Agent');
                     $graph->addLiteral($definition['publisher_uri'], 'foaf:name', $definition['publisher_name']);
                 }
                 // Add the keywords to the dataset
                 if (!empty($definition['keywords'])) {
                     foreach (explode(',', $definition['keywords']) as $keyword) {
                         $keyword = trim($keyword);
                         $graph->addLiteral($dataset_uri, 'dcat:keyword', $keyword);
                     }
                 }
                 // Add the source resource if it's a URI
                 if (strpos($definition['source'], 'http://') !== false || strpos($definition['source'], 'https://')) {
                     $graph->addResource($dataset_uri, 'dct:source', str_replace(' ', '%20', $definition['source']));
                 }
                 // Optional dct terms
                 $optional = array('date', 'language', 'theme');
                 foreach ($optional as $dc_term) {
                     if (!empty($definition[$dc_term])) {
                         if ($dc_term == 'language') {
                             $lang = $this->languages->getByName($definition[$dc_term]);
                             if (!empty($lang)) {
                                 $graph->addResource($dataset_uri, 'dct:' . $dc_term, 'http://lexvo.org/id/iso639-3/' . $lang['lang_id']);
                                 $graph->addResource('http://lexvo.org/id/iso639-3/' . $lang['lang_id'], 'a', 'dct:LinguisticSystem');
                             }
                         } elseif ($dc_term == 'theme') {
                             $theme = $this->themes->getByLabel($definition[$dc_term]);
                             if (!empty($theme)) {
                                 $graph->addResource($dataset_uri, 'dcat:' . $dc_term, $theme['uri']);
                                 $graph->addLiteral($theme['uri'], 'rdfs:label', $theme['label']);
                             }
                         } else {
                             $graph->addLiteral($dataset_uri, 'dct:' . $dc_term, $definition[$dc_term]);
                         }
                     }
                 }
                 // Add the distribution of the dataset
                 if ($this->isDataGeoFormatted($definition)) {
                     $distribution_uri = $dataset_uri . '.geojson';
                 } else {
                     $distribution_uri = $dataset_uri . '.json';
                 }
                 // Check for spatial properties:
                 if (!empty($definition['spatial']['geometry']['geometry'])) {
                     $spatial = $graph->newBNode();
                     $spatial->setType('dct:Location');
                     $geometry_literal = new Literal($definition['spatial']['geometry']['geometry'], '', '<https://www.iana.org/assignments/media-types/application/vnd.geo+json>');
                     $spatial->addLiteral('locn:geometry', $geometry_literal);
                     if (!empty($definition['spatial']['label']['label'])) {
                         $spatial->addLiteral('skos:prefLabel', $definition['spatial']['label']['label']);
                     }
                     $graph->addResource($dataset_uri, 'dct:spatial', $spatial);
                 }
                 // Check for attribution properties:
                 if (!empty($definition['attributions'])) {
                     foreach ($definition['attributions'] as $attribution) {
                         $attribution_node = $graph->newBNode();
                         $attribution_node->setType('prov:Attribution');
                         $vcard = $graph->newBNode();
                         $vcard->setType('vcard:Kind');
                         $vcard->addLiteral('vcard:fn', $attribution['name']);
                         $vcard->addResource('vcard:hasEmail', 'mailto:' . $attribution['email']);
                         $attribution_node->addResource('prov:Agent', $vcard);
                         $attribution_node->addResource('dc:type', 'http://inspire.ec.europa.eu/metadata-codelist/ResponsiblePartyRole/' . $attribution['role']);
                         $graph->addResource($dataset_uri, 'prov:qualifiedAttribution', $attribution_node);
                     }
                 }
                 $graph->addResource($dataset_uri, 'dcat:distribution', $distribution_uri);
                 $graph->addResource($distribution_uri, 'a', 'dcat:Distribution');
                 $graph->addResource($distribution_uri, 'dcat:accessURL', $dataset_uri);
                 $graph->addResource($distribution_uri, 'dcat:downloadURL', $distribution_uri);
                 $graph->addLiteral($distribution_uri, 'dct:title', $title);
                 $graph->addLiteral($distribution_uri, 'dct:description', 'A json feed of ' . $dataset_uri);
                 $graph->addLiteral($distribution_uri, 'dcat:mediaType', 'application/json');
                 $graph->addLiteral($distribution_uri, 'dct:issued', date(\DateTime::ISO8601, strtotime($definition['created_at'])));
                 // Add the license to the distribution
                 if (!empty($definition['rights'])) {
                     $license = $this->licenses->getByTitle($definition['rights']);
                     if (!empty($license) && !empty($license['url'])) {
                         $graph->addResource($dataset_uri . '.json', 'dct:license', $license['url']);
                         $graph->addResource($license['url'], 'a', 'dct:LicenseDocument');
                     }
                 }
             } else {
                 $turtle_parser = new Turtle();
                 $tmp_graph = new Graph();
                 $turtle_parser->parse($graph, $definition['dcat'], 'turtle', 'http://foo.bar');
             }
         }
     }
     return $graph;
 }
Ejemplo n.º 21
0
 public static function getBody($dataObj)
 {
     // Query parameters
     $query_string = '';
     if (!empty($_GET)) {
         $get_params = \Input::get();
         foreach ($get_params as $param => $val) {
             if (!empty($val)) {
                 $query_string .= "&{$param}={$val}";
             }
         }
         if (!empty($query_string)) {
             $query_string = trim($query_string, '&');
             $query_string = '?' . $query_string;
         }
     }
     // Links to pages
     $prev_link = '';
     $next_link = '';
     if (!empty($dataObj->paging)) {
         $input_array = array_except(\Input::get(), array('limit', 'offset'));
         $query_string = '';
         if (!empty($input_array)) {
             foreach ($get_params as $param => $val) {
                 if (!empty($val)) {
                     $query_string .= "&{$param}={$val}";
                 }
             }
             if (!empty($query_string)) {
                 $query_string = trim($query_string, '&');
                 $query_string = '?' . $query_string;
             }
         }
         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'], [], \Config::get('app.ssl_enabled'));
     // 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 'KML':
             case 'SHP':
                 $view = 'dataset.map';
                 $data = $dataset_link . '.map' . $query_string;
                 break;
             case 'XML':
                 $view = 'dataset.code';
                 $data = self::displayTree($dataObj->data, 'xml');
                 break;
             case 'INSPIRE':
                 $view = 'dataset.inspire';
                 $definitions = \App::make('Tdt\\Core\\Repositories\\Interfaces\\DefinitionRepositoryInterface');
                 $properties = $definitions->getCreateParameters();
                 $data = ['properties' => $properties];
                 break;
             case 'REMOTE':
                 $view = 'dataset.remote';
                 $definitions = \App::make('Tdt\\Core\\Repositories\\Interfaces\\DefinitionRepositoryInterface');
                 $properties = $definitions->getCreateParameters();
                 $data = ['properties' => $properties];
                 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');
                 } elseif ($type == 'SPARQL' && $dataObj->source_definition['query_type'] == 'select') {
                     $data = CSVFormatter::buildTableFromSparqlResult($dataObj->data);
                     $first_row = array_shift($data);
                     array_unshift($data, $first_row);
                     if (is_array($first_row) || is_object($first_row)) {
                         $view = 'dataset.tabular';
                         $data = $data;
                     }
                 } 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 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' || $dataObj->source_definition['type'] == 'KML') {
         $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);
 }
Ejemplo n.º 22
0
 /**
  * Method to serialise an EasyRdf\Graph to RDF/XML
  *
  * @param Graph  $graph  An EasyRdf\Graph object.
  * @param string $format The name of the format to convert to.
  * @param array  $options
  *
  * @return string The RDF in the new desired format.
  * @throws Exception
  */
 public function serialise(Graph $graph, $format, array $options = array())
 {
     parent::checkSerialiseParams($format);
     if ($format != 'rdfxml') {
         throw new Exception("EasyRdf\\Serialiser\\RdfXml does not support: {$format}");
     }
     // store of namespaces to be appended to the rdf:RDF tag
     $this->prefixes = array('rdf' => true);
     // store of the resource URIs we have serialised
     $this->outputtedResources = array();
     $xml = '';
     // Serialise URIs first
     foreach ($graph->resources() as $resource) {
         if (!$resource->isBnode()) {
             $xml .= $this->rdfxmlResource($resource, true);
         }
     }
     // Serialise bnodes afterwards
     foreach ($graph->resources() as $resource) {
         if ($resource->isBnode()) {
             $xml .= $this->rdfxmlResource($resource, true);
         }
     }
     // iterate through namepsaces array prefix and output a string.
     $namespaceStr = '';
     foreach ($this->prefixes as $prefix => $count) {
         $url = RdfNamespace::get($prefix);
         if (strlen($namespaceStr)) {
             $namespaceStr .= "\n        ";
         }
         if (strlen($prefix) === 0) {
             $namespaceStr .= ' xmlns="' . htmlspecialchars($url) . '"';
         } else {
             $namespaceStr .= ' xmlns:' . $prefix . '="' . htmlspecialchars($url) . '"';
         }
     }
     return "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n" . "<rdf:RDF" . $namespaceStr . ">\n" . $xml . "\n</rdf:RDF>\n";
 }
Ejemplo n.º 23
0
 protected function open()
 {
     \EasyRdf\RdfNamespace::set('locn', 'http://www.w3.org/ns/locn#');
     $graph = Graph::newAndLoad($this->extractor->uri, $this->extractor->format);
     $this->datasets = $graph->allOfType('dcat:Dataset');
 }