/** * 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)); } }
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."); } }
/** * Parses an RDF collection from the response data. * * @return null */ protected function loadEntity() { $input = (string) $this->getResponse()->getBody(); $options = array(""); $this->rdfCollection = new RdfCollection(JsonLD::toRdf($input, $options)); return null; }
/** * Test whether it's valid json-ld. */ public function testJsonLD() { //Launch a query in various ways $jsonld1 = Stations::getStations('Brussel'); $jsonld2 = Stations::getStations(); //Assert whether the json ld is valid $doc1 = JsonLD::getDocument($jsonld1); $doc2 = JsonLD::getDocument($jsonld2); //Assert whether nodes exist //E.g., the default graph of doc1 should be http://irail.be/stations/NMBS?q=Brussel $this->assertTrue($doc1->containsGraph('http://irail.be/stations/NMBS?q=Brussel')); //E.g., the default graph of doc2 should be http://irail.be/stations/NMBS $this->assertTrue($doc2->containsGraph('http://irail.be/stations/NMBS')); }
/** * Parse a JSON-LD document into an EasyRdf_Graph * * Attention: Since JSON-LD supports datasets, a document may contain * multiple graphs and not just one. This parser returns only the * default graph. An alternative would be to merge all graphs. * * @param object EasyRdf_Graph $graph the graph to load the data into * @param string $data the RDF document data * @param string $format the format of the input data * @param string $baseUri the base URI of the data being parsed * @return integer The number of triples added to the graph */ public function parse($graph, $data, $format, $baseUri) { parent::checkParseParams($graph, $data, $format, $baseUri); if ($format != 'jsonld') { throw new EasyRdf_Exception("EasyRdf_Parser_JsonLd does not support {$format}"); } try { $quads = \ML\JsonLD\JsonLD::toRdf($data, array('base' => $baseUri)); } catch (\ML\JsonLD\Exception\JsonLdException $e) { throw new EasyRdf_Parser_Exception($e->getMessage()); } foreach ($quads as $quad) { // Ignore named graphs if (null !== $quad->getGraph()) { continue; } $subject = (string) $quad->getSubject(); if ('_:' === substr($subject, 0, 2)) { $subject = $this->remapBnode($subject); } $predicate = (string) $quad->getProperty(); if ($quad->getObject() instanceof \ML\IRI\IRI) { $object = array('type' => 'uri', 'value' => (string) $quad->getObject()); if ('_:' === substr($object['value'], 0, 2)) { $object = array('type' => 'bnode', 'value' => $this->remapBnode($object['value'])); } } else { $object = array('type' => 'literal', 'value' => $quad->getObject()->getValue()); if ($quad->getObject() instanceof \ML\JsonLD\LanguageTaggedString) { $object['lang'] = $quad->getObject()->getLanguage(); } else { $object['datatype'] = $quad->getObject()->getType(); } } $this->addTriple($subject, $predicate, $object); } return $this->tripleCount; }
/** * 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); }
/** * Constructor. * * @param string $code The error code * @param string $message The error message * @param mixed $snippet The code snippet * @param string $document The document that triggered the error * @param Exception $previous The previous exception */ public function __construct($code, $message = null, $snippet = null, $document = null, \Exception $previous = null) { $this->code = $code; $this->document = $document; $this->snippet = $snippet ? JsonLD::toString($snippet) : $snippet; $this->rawMessage = $message; $this->updateMessage(); parent::__construct($this->message, 0, $previous); }
/** * Tests the document API * * This test intentionally uses the same fixtures as the flattening tests. */ public function testGetDocument() { $path = dirname(__FILE__) . DIRECTORY_SEPARATOR . 'Fixtures' . DIRECTORY_SEPARATOR; $expected = json_decode(file_get_contents($path . 'sample-serialized-document.jsonld')); $input = $path . 'sample-in.jsonld'; $this->assertJsonEquals($expected, JsonLD::getDocument($input)->toJsonLd(), 'Passing the file path'); $input = file_get_contents($input); $this->assertJsonEquals($expected, JsonLD::getDocument($input)->toJsonLd(), 'Passing the raw input (string)'); $input = json_decode($input); $this->assertJsonEquals($expected, JsonLD::getDocument($input)->toJsonLd(), 'Passing the parsed object'); }
/** * 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); }
} ], "@embedChildren": false, "supportedProperties": { "@default": [ ], "@embed": true }, "supportedOperations": { "@default": [ ], "@embed": true, "expects": { "@default": null, "@embed": false }, "statusCodes": { "@default": [], "@embed": true } } } '; $document = JsonLD::toString(JsonLD::frame(JsonLD::expand($document, $options), $frame)); $headers['Content-Type'] = 'application/ld+json'; } catch (Exception $e) { $exceptionName = get_class($e); if (false !== ($pos = strrpos(get_class($e), '\\'))) { $exceptionName = substr($exceptionName, $pos + 1); } header('HTTP/1.1 400 ' . $exceptionName); //Bad Request'); print htmlspecialchars($e->getMessage()); die; } }; $proxy = new AjaxProxy(); if ($debug) { $proxy->setResponseModifier($debugExpansion);
/** * @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); }
/** * @param string $path * @return HydraClass */ public static function fromPath($path) { $doc = JsonLD::getDocument($path); $graph = $doc->getGraph(); return static::fromGraph($graph); }
/** * 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; }
/** * 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); }
/** * Create the document to test. */ protected function setUp() { $this->document = JsonLD::getDocument(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'Fixtures' . DIRECTORY_SEPARATOR . 'dataset.jsonld', array('base' => 'http://example.com/dataset.jsonld')); }
/** * Deserializes JSON-LD data * * @param mixed $data The data to deserialize. * @param object $entity The entity into which the data should be * deserialized. * * @return object The entity. */ private function doDeserialize($data, $entity) { $metadata = $this->hydraApi->getMetadataFor(get_class($entity)); if (null === $metadata) { // TODO Improve this error message throw new \Exception(sprintf('"%s" cannot be serialized as it is not documented.', get_class($data))); } $vocabPrefix = $this->router->generate('hydra_vocab', array(), true) . '#'; $typeIri = $metadata->isExternalReference() ? $metadata->getIri() : $vocabPrefix . $metadata->getIri(); $graph = JsonLD::getDocument($data)->getGraph(); $node = $graph->getNodesByType($typeIri); if (1 !== count($node)) { throw new RuntimeException('The passed data contains ' . count($node) . ' nodes of the type ' . $typeIri . '; expected 1.'); } $node = reset($node); foreach ($metadata->getProperties() as $property) { if ($property->isReadOnly()) { continue; } // TODO Parse route! if (null !== ($route = $property->getRoute())) { continue; // FIXXE Handle properties whose value are URLs } // TODO Recurse!? $propertyIri = $property->isExternalReference() ? $property->getIri() : $vocabPrefix . $property->getIri(); $value = $node->getProperty($propertyIri); if ($value instanceof \ML\JsonLD\Value) { $value = $value->getValue(); } if (!is_null($value) && $this->hydraApi->hasNormalizer($property->getType())) { $normalizer = $this->hydraApi->getNormalizer($property->getType()); $value = $normalizer->denormalize($value, $property->getType()); } $property->setValue($entity, $value); // TODO Fix IRI construction // if (is_array($value) || ($value instanceof \ArrayAccess) || ($value instanceof \Travesable)) { // $result[$property] = array(); // foreach ($value as $val) { // $result[$property][] = $this->doSerialize($val); // } // } else { // $result[$property] = $value; // } } return $entity; }
/** * Parses a JSON-LD document and returns it as a Document * * The document can be supplied directly as a string or by passing a * file path or an IRI. * * Usage: * <code> * $document = Document::load('document.jsonld'); * </code> * * <strong>Please note that currently all data is merged into the * default graph, named graphs are not supported yet!</strong> * * It is possible to configure the processing by setting the options * parameter accordingly. Available options are: * * - <em>base</em> The base IRI of the input document. * * @param string|array|object $document The JSON-LD document to process. * @param null|array|object $options Options to configure the processing. * * @return Document The parsed JSON-LD document. * * @throws ParseException If the JSON-LD input document is invalid. */ public static function load($document, $options = null) { return JsonLD::getDocument($document, $options); }
/** * Tests conversion from quads. * * @param string $name The test name. * @param object $test The test definition. * @param object $options The options to configure the algorithms. * * @group fromRdf * @dataProvider fromRdfProvider */ public function testFromRdf($name, $test, $options) { $expected = json_decode(file_get_contents($this->basedir . $test->{'expect'})); $parser = new NQuads(); $quads = $parser->parse(file_get_contents($this->basedir . $test->{'input'})); $result = JsonLD::fromRdf($quads, $options); $this->assertEquals($expected, $result); }
private function parseJsonLD($uri) { $quads = JsonLD::toRdf($uri); $nquads = new NQuads(); $graph = new Graph(); foreach ($quads as $quad) { $subject = (string) $quad->getSubject(); if ('_:' === substr($subject, 0, 2)) { $subject = $this->remapBnode($subject, $graph); } $predicate = (string) $quad->getProperty(); if ($quad->getObject() instanceof \ML\IRI\IRI) { $object = array('type' => 'uri', 'value' => (string) $quad->getObject()); if ('_:' === substr($object['value'], 0, 2)) { $object = array('type' => 'bnode', 'value' => $this->remapBnode($object['value'], $graph)); } } else { $object = array('type' => 'literal', 'value' => $quad->getObject()->getValue()); if ($quad->getObject() instanceof \ML\JsonLD\LanguageTaggedString) { $object['lang'] = $quad->getObject()->getLanguage(); } else { $object['datatype'] = $quad->getObject()->getType(); } } $graph->add($subject, $predicate, $object); } return $graph; }
/** * 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; } }