Esempio n. 1
0
 public static function getBody($dataObj)
 {
     if ($dataObj->is_semantic) {
         // Check if a configuration is given
         $conf = array();
         if (!empty($dataObj->semantic->conf)) {
             $conf = $dataObj->semantic->conf;
             foreach ($conf['ns'] as $prefix => $uri) {
                 \EasyRdf_Namespace::set($prefix, $uri);
             }
         }
         // Add the configured ontology prefixes
         $ontologies = \App::make('Tdt\\Core\\Repositories\\Interfaces\\OntologyRepositoryInterface');
         $context = array();
         // Only add the common namespaces
         $namespaces = array('hydra', 'rdf', 'rdfs', 'foaf', 'void', 'xsd', 'skos', 'xs');
         foreach ($namespaces as $ns) {
             $namespace = $ontologies->getByPrefix($ns);
             if (!empty($namespace)) {
                 $context[$ns] = $namespace['uri'];
             }
         }
         $output = $dataObj->data->serialise('jsonld');
         // Next, encode the context as JSON
         $jsonContext = json_encode($context);
         // Compact the JsonLD by using @context -> Needs tweaking can only return the
         // URI spaces that are used in the document.
         $compacted = JsonLD::compact($output, $jsonContext);
         // Print the resulting JSON-LD!
         return JsonLD::toString($compacted, true);
     } else {
         \App::abort(400, "The data is not a semantically linked document, a linked data JSON representation is not possible.");
     }
 }
Esempio n. 2
0
 /**
  * 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));
     }
 }
Esempio n. 3
0
 /**
  * Tests the compaction API
  *
  * @group compaction
  */
 public function testCompaction()
 {
     $path = dirname(__FILE__) . DIRECTORY_SEPARATOR . 'Fixtures' . DIRECTORY_SEPARATOR;
     $expected = json_decode(file_get_contents($path . 'sample-compacted.jsonld'));
     $input = $path . 'sample-in.jsonld';
     $context = $path . 'sample-context.jsonld';
     $this->assertJsonEquals($expected, JsonLD::compact($input, $context), 'Passing the file path');
     $input = file_get_contents($input);
     $context = file_get_contents($context);
     $this->assertJsonEquals($expected, JsonLD::compact($input, $context), 'Passing the raw input (string)');
     $input = json_decode($input);
     $context = json_decode($context);
     $this->assertJsonEquals($expected, JsonLD::compact($input, $context), 'Passing the parsed object');
 }
Esempio n. 4
0
 /**
  * Convert a list of L10nResources in a JSON-LD file
  * @param array(L10nResources) $l10nResourceList
  * @return string : JSON-LD document
  */
 public function convertL10nResourceList(array $l10nResourceList)
 {
     $quadList = array();
     $c = 0;
     if (count($l10nResourceList)) {
         foreach ($l10nResourceList as $l10nResource) {
             $bNode = new IRI('_' . $c);
             $quadList[] = new Quad($bNode, new IRI(self::NS . 'key'), new IRI($l10nResource->getIdResource()));
             $quadList[] = new Quad($bNode, new IRI(self::NS . 'localization'), new IRI($l10nResource->getIdLocalization()));
             $valueList = $l10nResource->getValueList();
             foreach ($valueList as $locale => $value) {
                 if (!is_int($locale)) {
                     $value .= '@' . $locale;
                 }
                 $quadList[] = new Quad($bNode, new IRI(self::NS . 'value'), new TypedValue($value, RdfConstants::XSD_STRING));
             }
             $c++;
         }
     }
     $jsonLd = JsonLD::fromRdf($quadList);
     $compacted = JsonLD::compact($jsonLd, '{"@context": {"l10n" : "' . self::NS . '"}}', array('compactArrays' => false));
     return JsonLD::toString($compacted, true);
 }
Esempio n. 5
0
 /**
  * Update a dataset
  *
  * @param $id     integer The id of the dataset
  * @param $config array   The configuration that makes up the dataset
  *
  * @return void
  */
 public function update($id, $config)
 {
     $uri = \URL::to('/users/' . $id);
     // Find the graph in the collection
     $graph = $this->get($id . '#agent');
     $context = $this->getContext();
     if (empty($graph)) {
         return null;
     }
     foreach ($this->getFields() as $field) {
         $domain = $field['domain'];
         if ($domain == 'foaf:Agent') {
             $resource = $graph->resource($uri . "#agent");
             $graph->delete($resource, $field['short_sem_term']);
             if ($field['single_value'] && in_array($field['type'], ['string', 'text', 'list'])) {
                 if (filter_var(trim($config[$field['var_name']]), FILTER_VALIDATE_URL)) {
                     $graph->addResource($resource, $field['sem_term'], trim($config[$field['var_name']]));
                 } else {
                     $graph->add($resource, $field['sem_term'], trim($config[$field['var_name']]));
                 }
             } else {
                 if (!$field['single_value'] && in_array($field['type'], ['string', 'list'])) {
                     if (!empty($config[$field['var_name']])) {
                         foreach ($config[$field['var_name']] as $val) {
                             if (filter_var($val, FILTER_VALIDATE_URL)) {
                                 $graph->addResource($resource, $field['sem_term'], $val);
                             } else {
                                 $graph->add($resource, $field['sem_term'], $val);
                             }
                         }
                     }
                 }
             }
         }
     }
     // Delete the json entry and replace it with the updated one
     $collection = $this->getMongoCollection();
     $serializer = new \EasyRdf_Serialiser_JsonLd();
     $jsonld = $serializer->serialise($graph, 'jsonld');
     $compact_document = (array) JsonLD::compact($jsonld, $context);
     $collection->remove(['@id' => $uri . '#agent']);
     $collection->insert($compact_document);
 }
Esempio n. 6
0
 /**
  * @param \EasyRdf\Graph  $graph
  * @param string          $format
  * @param array           $options
  *
  * @throws Exception
  * @return string
  */
 public function serialise($graph, $format, array $options = array())
 {
     parent::checkSerialiseParams($graph, $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);
 }
Esempio n. 7
0
 /**
  * Download a concept as json-ld or redirect to download the whole vocabulary.
  * @param Request $request
  * @return object json-ld formatted concept.
  */
 public function data($request)
 {
     $vocab = $request->getVocab();
     $format = $request->getQueryParam('format');
     if ($request->getUri()) {
         $uri = $request->getUri();
     } else {
         if ($vocab !== null) {
             // whole vocabulary - redirect to download URL
             $urls = $vocab->getDataURLs();
             if (sizeof($urls) == 0) {
                 return $this->returnError('404', 'Not Found', "No download source URL known for vocabulary {$vocab}");
             }
             $format = $this->negotiateFormat(array_keys($urls), $request->getServerConstant('HTTP_ACCEPT'), $format);
             if (!$format) {
                 return $this->returnError(406, 'Not Acceptable', "Unsupported format. Supported MIME types are: " . implode(' ', array_keys($urls)));
             }
             header("Location: " . $urls[$format]);
             return;
         } else {
             return $this->returnError(400, 'Bad Request', "uri parameter missing");
         }
     }
     $format = $this->negotiateFormat(explode(' ', self::$SUPPORTED_MIME_TYPES), $request->getServerConstant('HTTP_ACCEPT'), $format);
     if (!$format) {
         return $this->returnError(406, 'Not Acceptable', "Unsupported format. Supported MIME types are: " . self::$SUPPORTED_MIME_TYPES);
     }
     $vocid = $vocab ? $vocab->getId() : null;
     $results = $this->model->getRDF($vocid, $uri, $format);
     if ($format == 'application/ld+json' || $format == 'application/json') {
         // further compact JSON-LD document using a context
         $context = array('skos' => 'http://www.w3.org/2004/02/skos/core#', 'isothes' => 'http://purl.org/iso25964/skos-thes#', 'rdfs' => 'http://www.w3.org/2000/01/rdf-schema#', 'owl' => 'http://www.w3.org/2002/07/owl#', 'dct' => 'http://purl.org/dc/terms/', 'dc11' => 'http://purl.org/dc/elements/1.1/', 'uri' => '@id', 'type' => '@type', 'lang' => '@language', 'value' => '@value', 'graph' => '@graph', 'label' => 'rdfs:label', 'prefLabel' => 'skos:prefLabel', 'altLabel' => 'skos:altLabel', 'hiddenLabel' => 'skos:hiddenLabel', 'broader' => 'skos:broader', 'narrower' => 'skos:narrower', 'related' => 'skos:related', 'inScheme' => 'skos:inScheme');
         $compact_jsonld = \ML\JsonLD\JsonLD::compact($results, json_encode($context));
         $results = \ML\JsonLD\JsonLD::toString($compact_jsonld);
     }
     header("Content-type: {$format}; charset=utf-8");
     echo $results;
 }
Esempio n. 8
0
 /**
  * Tests compaction.
  *
  * @param string $name    The test name.
  * @param object $test    The test definition.
  * @param object $options The options to configure the algorithms.
  *
  * @group compaction
  * @dataProvider compactionProvider
  */
 public function testCompaction($name, $test, $options)
 {
     $expected = json_decode(file_get_contents($this->basedir . $test->{'expect'}));
     $result = JsonLD::compact($this->basedir . $test->{'input'}, $this->basedir . $test->{'context'}, $options);
     $this->assertJsonEquals($expected, $result);
 }
Esempio n. 9
0
 /**
  * Update a dataset
  *
  * @param $id     integer The id of the dataset
  * @param $config array   The configuration that makes up the dataset
  *
  * @return void
  */
 public function update($id, $config)
 {
     $uri = \URL::to('/datasets/' . $id);
     // Find the graph in the collection
     $graph = $this->get($id);
     $context = $this->getContext();
     if (empty($graph)) {
         return null;
     }
     // Add the contributor
     $graph->addLiteral($uri, 'http://purl.org/dc/terms/contributor', \URL::to('/users/' . strtolower(str_replace(" ", "", $config['user']))));
     foreach ($this->getFields() as $field) {
         $type = $field['domain'];
         if ($type == 'dcat:Dataset') {
             $resource = $graph->resource($uri . "#dataset");
         } else {
             if ($type == 'dcat:CatalogRecord') {
                 $resource = $graph->resource($uri);
             }
         }
         $graph->delete($resource, $field['short_sem_term']);
         if ($field['single_value'] && in_array($field['type'], ['string', 'text', 'list'])) {
             if (filter_var(trim($config[$field['var_name']]), FILTER_VALIDATE_URL)) {
                 $graph->addResource($resource, $field['sem_term'], trim($config[$field['var_name']]));
             } else {
                 $graph->add($resource, $field['sem_term'], trim($config[$field['var_name']]));
             }
         } else {
             if (!$field['single_value'] && in_array($field['type'], ['string', 'list'])) {
                 if (!empty($config[$field['var_name']])) {
                     foreach ($config[$field['var_name']] as $val) {
                         if (filter_var($val, FILTER_VALIDATE_URL)) {
                             $graph->addResource($resource, $field['sem_term'], $val);
                         } else {
                             $graph->add($resource, $field['sem_term'], $val);
                         }
                     }
                 }
             }
         }
     }
     foreach ($graph->allOfType('dcat:Distribution') as $distribution) {
         $resource = $graph->resource($uri . "#dataset");
         $graph->deleteResource($resource, 'dcat:distribution', $distribution->getUri());
     }
     // Add the distribution resource
     foreach ($config['distributions'] as $distribution) {
         $id = $this->getIncrementalId();
         $distr_uri = $uri . '#distribution' . $id;
         $distributionResource = $graph->resource($distr_uri);
         $distributionResource->addType('dcat:Distribution');
         if (!empty($distribution['license'])) {
             $graph->addResource($distributionResource, 'dct:license', $distribution['license']);
         }
         if (!empty($distribution['usecases'])) {
             foreach ($distribution['usecases'] as $usecase) {
                 $graph->addResource($distributionResource, 'linda:useFor', $usecase);
             }
         }
         // Add the distribution to the dataset
         $graph->addResource($uri . "#dataset", 'dcat:distribution', $distr_uri);
     }
     // Delete the json entry and replace it with the updated one
     $collection = $this->getMongoCollection();
     $serializer = new \EasyRdf_Serialiser_JsonLd();
     $jsonld = $serializer->serialise($graph, 'jsonld');
     $compact_document = (array) JsonLD::compact($jsonld, $context);
     $collection->remove(['@graph' => ['$elemMatch' => ['@id' => $uri]]]);
     $collection->insert($compact_document);
 }
Esempio n. 10
0
 /**
  * Shows a train or train data, based on the accept-header.
  * @param $station_id
  * @param $liveboard_id
  * @return array
  * @throws EasyRdf_Exception
  */
 public function specificTrain($station_id, $liveboard_id)
 {
     $negotiator = new \Negotiation\FormatNegotiator();
     $acceptHeader = Request::header('accept');
     $priorities = array('application/json', 'text/html', '*/*');
     $result = $negotiator->getBest($acceptHeader, $priorities);
     $val = $result->getValue();
     //get the right date-time to query
     $datetime = substr($liveboard_id, 0, 12);
     $datetime = strtotime($datetime);
     $archived = false;
     if ($datetime < strtotime("now")) {
         $archived = true;
     }
     switch ($val) {
         case "text/html":
             // Convert id to string for interpretation by old API
             $stationStringName = \hyperRail\StationString::convertToString($station_id);
             if (!$archived) {
                 // Set up path to old api
                 $URL = "http://api.irail.be/liveboard/?station=" . urlencode($stationStringName->name) . "&date=" . date("mmddyy", $datetime) . "&time=" . date("Hi", $datetime) . "&fast=true&lang=nl&format=json";
                 // Get the contents of this path
                 $data = file_get_contents($URL);
                 // Convert the data to the new liveboard object
                 $newData = \hyperRail\FormatConverter::convertLiveboardData($data, $station_id);
                 // Read new liveboard object and return the page but load data
                 foreach ($newData['@graph'] as $graph) {
                     if (strpos($graph['@id'], $liveboard_id) !== false) {
                         return View::make('stations.departuredetail')->with('station', $graph)->with('departureStation', $stationStringName);
                     }
                 }
                 App::abort(404);
             } else {
                 // If no match is found, attempt to look in the archive
                 // Fetch file using curl
                 $ch = curl_init("http://archive.irail.be/" . 'irail?subject=' . urlencode('http://irail.be/stations/NMBS/' . $station_id . '/departures/' . $liveboard_id));
                 curl_setopt($ch, CURLOPT_HEADER, 0);
                 $request_headers[] = 'Accept: text/turtle';
                 curl_setopt($ch, CURLOPT_HTTPHEADER, $request_headers);
                 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                 $turtle = curl_exec($ch);
                 curl_close($ch);
                 // Convert turtle to json-ld
                 // Create a new graph
                 $graph = new EasyRdf_Graph();
                 if (empty($_REQUEST['data'])) {
                     // Load the sample information
                     $graph->parse($turtle, 'turtle');
                 }
                 // Export to JSON LD
                 $format = EasyRdf_Format::getFormat('jsonld');
                 $output = $graph->serialise($format);
                 if (!is_scalar($output)) {
                     $output = var_export($output, true);
                 }
                 // First, define the context
                 $context = array("delay" => "http://semweb.mmlab.be/ns/rplod/delay", "platform" => "http://semweb.mmlab.be/ns/rplod/platform", "scheduledDepartureTime" => "http://semweb.mmlab.be/ns/rplod/scheduledDepartureTime", "headsign" => "http://vocab.org/transit/terms/headsign", "routeLabel" => "http://semweb.mmlab.be/ns/rplod/routeLabel", "stop" => array("@id" => "http://semweb.mmlab.be/ns/rplod/stop", "@type" => "@id"), "seeAlso" => array("@id" => "http://www.w3.org/2000/01/rdf-schema#seeAlso", "@type" => "@id"));
                 // Next, encode the context as JSON
                 $jsonContext = json_encode($context);
                 // Compact the JsonLD by using @context
                 $compacted = JsonLD::compact($output, $jsonContext);
                 // Print the resulting JSON-LD!
                 $urlToFind = 'NMBS/' . $station_id . '/departures/' . $liveboard_id;
                 $stationDataFallback = json_decode(JsonLD::toString($compacted, true));
                 foreach ($stationDataFallback->{'@graph'} as $graph) {
                     if (strpos($graph->{'@id'}, $urlToFind) !== false) {
                         return View::make('stations.departurearchive')->with('station', $graph)->with('departureStation', $stationStringName);
                     }
                 }
                 App::abort(404);
             }
             break;
         case "application/json":
         case "application/ld+json":
         default:
             $stationStringName = \hyperRail\StationString::convertToString($station_id);
             if (!$archived) {
                 $URL = "http://api.irail.be/liveboard/?station=" . urlencode($stationStringName->name) . "&date=" . date("mmddyy", $datetime) . "&time=" . date("Hi", $datetime) . "&fast=true&lang=nl&format=json";
                 $data = file_get_contents($URL);
                 $newData = \hyperRail\FormatConverter::convertLiveboardData($data, $station_id);
                 foreach ($newData['@graph'] as $graph) {
                     if (strpos($graph['@id'], $liveboard_id) !== false) {
                         $context = array("delay" => "http://semweb.mmlab.be/ns/rplod/delay", "platform" => "http://semweb.mmlab.be/ns/rplod/platform", "scheduledDepartureTime" => "http://semweb.mmlab.be/ns/rplod/scheduledDepartureTime", "headsign" => "http://vocab.org/transit/terms/headsign", "routeLabel" => "http://semweb.mmlab.be/ns/rplod/routeLabel", "stop" => array("@id" => "http://semweb.mmlab.be/ns/rplod/stop", "@type" => "@id"));
                         return array("@context" => $context, "@graph" => $graph);
                     }
                 }
                 App::abort(404);
             } else {
                 // If no match is found, attempt to look in the archive
                 // Fetch file using curl
                 $ch = curl_init("http://archive.irail.be/" . 'irail?subject=' . urlencode('http://irail.be/stations/NMBS/' . $station_id . '/departures/' . $liveboard_id));
                 curl_setopt($ch, CURLOPT_HEADER, 0);
                 $request_headers[] = 'Accept: text/turtle';
                 curl_setopt($ch, CURLOPT_HTTPHEADER, $request_headers);
                 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                 $turtle = curl_exec($ch);
                 curl_close($ch);
                 // Convert turtle to json-ld
                 // Create a new graph
                 $graph = new EasyRdf_Graph();
                 if (empty($_REQUEST['data'])) {
                     // Load the sample information
                     $graph->parse($turtle, 'turtle');
                 }
                 // Export to JSON LD
                 $format = EasyRdf_Format::getFormat('jsonld');
                 $output = $graph->serialise($format);
                 if (!is_scalar($output)) {
                     $output = var_export($output, true);
                 }
                 // First, define the context
                 $context = array("delay" => "http://semweb.mmlab.be/ns/rplod/delay", "platform" => "http://semweb.mmlab.be/ns/rplod/platform", "scheduledDepartureTime" => "http://semweb.mmlab.be/ns/rplod/scheduledDepartureTime", "headsign" => "http://vocab.org/transit/terms/headsign", "routeLabel" => "http://semweb.mmlab.be/ns/rplod/routeLabel", "stop" => array("@id" => "http://semweb.mmlab.be/ns/rplod/stop", "@type" => "@id"), "seeAlso" => array("@id" => "http://www.w3.org/2000/01/rdf-schema#seeAlso", "@type" => "@id"));
                 // Next, encode the context as JSON
                 $jsonContext = json_encode($context);
                 // Compact the JsonLD by using @context
                 $compacted = JsonLD::compact($output, $jsonContext);
                 // Print the resulting JSON-LD!
                 $urlToFind = 'NMBS/' . $station_id . '/departures/' . $liveboard_id;
                 $stationDataFallback = json_decode(JsonLD::toString($compacted, true));
                 foreach ($stationDataFallback->{'@graph'} as $graph) {
                     if (strpos($graph->{'@id'}, $urlToFind) !== false) {
                         return array("@context" => $context, "@graph" => $graph);
                     }
                 }
                 App::abort(404);
             }
             break;
     }
 }