Example #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.");
     }
 }
 /**
  * Serializes data in the appropriate format
  *
  * @param mixed  $data    any data
  * @param string $format  format name
  * @param array  $context options normalizers/encoders have access to
  *
  * @return string
  */
 public function serialize($data, $format, array $context = array())
 {
     if ('jsonld' !== $format) {
         throw new UnexpectedValueException('Serialization for the format ' . $format . ' is not supported');
     }
     if (false === is_object($data)) {
         throw new \Exception('Only objects can be serialized');
     }
     return JsonLD::toString($this->doSerialize($data, true), true);
 }
 /**
  * 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);
 }
Example #4
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);
 }
Example #5
0
    }
  ],
  "@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);
Example #6
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;
 }
Example #7
0
 /**
  * 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);
 }
Example #8
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;
     }
 }