protected function getTriples($file)
 {
     if (!file_exists($file)) {
         throw new Exception($file . ' not found');
     }
     // validate the file to import
     $parser = new tao_models_classes_Parser($file, array('extension' => 'rdf'));
     $parser->validate();
     if (!$parser->isValid()) {
         throw new common_Exception('Invalid RDF file ' . $file);
     }
     $modelDefinition = new EasyRdf_Graph();
     $modelDefinition->parseFile($file);
     /*
     $graph = $modelDefinition->toRdfPhp();
     $resources = $modelDefinition->resources();
     */
     $format = EasyRdf_Format::getFormat('php');
     $data = $modelDefinition->serialise($format);
     $triples = array();
     foreach ($data as $subjectUri => $propertiesValues) {
         foreach ($propertiesValues as $prop => $values) {
             foreach ($values as $k => $v) {
                 $triples[] = array('s' => $subjectUri, 'p' => $prop, 'o' => $v['value'], 'l' => isset($v['lang']) ? $v['lang'] : '');
             }
         }
     }
     return $triples;
 }
예제 #2
0
 /**
  * @author "Lionel Lecaque, <*****@*****.**>"
  * @param string $namespace
  * @param string $data xml content
  */
 public function createModel($namespace, $data)
 {
     $modelId = $this->getModelId($namespace);
     if ($modelId === false) {
         common_Logger::d('modelId not found, need to add namespace ' . $namespace);
         $this->addNewModel($namespace);
         //TODO bad way, need to find better
         $modelId = $this->getModelId($namespace);
     }
     $modelDefinition = new EasyRdf_Graph($namespace);
     if (is_file($data)) {
         $modelDefinition->parseFile($data);
     } else {
         $modelDefinition->parse($data);
     }
     $graph = $modelDefinition->toRdfPhp();
     $resources = $modelDefinition->resources();
     $format = EasyRdf_Format::getFormat('php');
     $data = $modelDefinition->serialise($format);
     foreach ($data as $subjectUri => $propertiesValues) {
         foreach ($propertiesValues as $prop => $values) {
             foreach ($values as $k => $v) {
                 $this->addStatement($modelId, $subjectUri, $prop, $v['value'], isset($v['lang']) ? $v['lang'] : null);
             }
         }
     }
     return true;
 }
예제 #3
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));
     }
 }
예제 #4
0
 public function testParseWithFormatObject()
 {
     $format = EasyRdf_Format::getFormat('json');
     $this->_parser->parse($this->_graph, $this->_data, $format, null);
     $joe = $this->_graph->resource('http://www.example.com/joe#me');
     $this->assertStringEquals('Joe Bloggs', $joe->get('foaf:name'));
 }
예제 #5
0
 public function testParseWithFormatObject()
 {
     $data = readFixture('foaf.jsonld');
     $format = EasyRdf_Format::getFormat('jsonld');
     $count = $this->parser->parse($this->graph, $data, $format, null);
     $this->assertSame(14, $count);
     $joe = $this->graph->resource('http://www.example.com/joe#me');
     $this->assertStringEquals('Joe Bloggs', $joe->get('foaf:name'));
 }
예제 #6
0
 /**
  * Export to xml-rdf the ontology of the Class in parameter.
  * All the ontologies are exported if the class is not set
  *
  * @access public
  * @author Jerome Bogaerts, <*****@*****.**>
  * @param  Class source
  * @return string
  */
 public function export(core_kernel_classes_Class $source = null)
 {
     $rdf = '';
     if (is_null($source)) {
         return core_kernel_api_ModelExporter::exportAll();
     }
     $graph = new EasyRdf_Graph();
     if ($source->isClass()) {
         $this->addClass($graph, $source);
     } else {
         $this->addResource($graph, $source);
     }
     $format = EasyRdf_Format::getFormat('rdfxml');
     return $graph->serialise($format);
 }
예제 #7
0
 public static function toFile($filePath, $triples)
 {
     $graph = new \EasyRdf_Graph();
     foreach ($triples as $triple) {
         if (!empty($triple->lg)) {
             $graph->addLiteral($triple->subject, $triple->predicate, $triple->object, $triple->lg);
         } elseif (\common_Utils::isUri($triple->object)) {
             $graph->add($triple->subject, $triple->predicate, $triple->object);
         } else {
             $graph->addLiteral($triple->subject, $triple->predicate, $triple->object);
         }
     }
     $format = \EasyRdf_Format::getFormat('rdfxml');
     return file_put_contents($filePath, $graph->serialise($format));
 }
예제 #8
0
 /**
  * @ignore
  */
 private static function statement2rdf(PDOStatement $statement)
 {
     $graph = new EasyRdf_Graph();
     while ($r = $statement->fetch()) {
         if (isset($r['l_language']) && !empty($r['l_language'])) {
             $graph->addLiteral($r['subject'], $r['predicate'], $r['object'], $r['l_language']);
         } elseif (common_Utils::isUri($r['object'])) {
             $graph->add($r['subject'], $r['predicate'], $r['object']);
         } else {
             $graph->addLiteral($r['subject'], $r['predicate'], $r['object']);
         }
     }
     $format = EasyRdf_Format::getFormat('rdfxml');
     return $graph->serialise($format);
 }
예제 #9
0
 /**
  * Imports the rdf file into the selected class
  * 
  * @param string $file
  * @param core_kernel_classes_Class $class
  * @return common_report_Report
  */
 private function flatImport($file, core_kernel_classes_Class $class)
 {
     $report = common_report_Report::createSuccess(__('Data imported successfully'));
     $graph = new EasyRdf_Graph();
     $graph->parseFile($file);
     // keep type property
     $map = array(RDF_PROPERTY => RDF_PROPERTY);
     foreach ($graph->resources() as $resource) {
         $map[$resource->getUri()] = common_Utils::getNewUri();
     }
     $format = EasyRdf_Format::getFormat('php');
     $data = $graph->serialise($format);
     foreach ($data as $subjectUri => $propertiesValues) {
         $resource = new core_kernel_classes_Resource($map[$subjectUri]);
         $subreport = $this->importProperties($resource, $propertiesValues, $map, $class);
         $report->add($subreport);
     }
     return $report;
 }
예제 #10
0
 public function testRegisterSerialiserForUnknownFormat()
 {
     EasyRdf_Format::registerSerialiser('testRegisterSerialiser', 'MockSerialiserClass');
     $format = EasyRdf_Format::getFormat('testRegisterSerialiser');
     $this->assertNotNull($format);
     $this->assertEquals('MockSerialiserClass', $format->getSerialiserClass());
 }
예제 #11
0
 * can have resource URIs replaced with text based labels and using
 * 'Only Labelled' option, only the resources and properties with
 * a label will be displayed.
 *
 * Rending a graph to an image will only work if you have the
 * GraphViz 'dot' command installed.
 *
 * @package    EasyRdf
 * @copyright  Copyright (c) 2012-2013 Nicholas J Humfrey
 * @license    http://unlicense.org/
 */
set_include_path(get_include_path() . PATH_SEPARATOR . '../lib/');
require_once "EasyRdf.php";
require_once "html_tag_helpers.php";
$formats = array('PNG' => 'png', 'GIF' => 'gif', 'SVG' => 'svg');
$format = EasyRdf_Format::getFormat(isset($_REQUEST['format']) ? $_REQUEST['format'] : 'png');
// Construct a graph of three people
$graph = new EasyRdf_Graph();
$graph->set('foaf:knows', 'rdfs:label', 'knows');
$bob = $graph->resource('http://www.example.com/bob', 'foaf:Person');
$alice = $graph->resource('http://www.example.com/alice', 'foaf:Person');
$carol = $graph->resource('http://www.example.com/carol', 'foaf:Person');
$bob->set('foaf:name', 'Bob');
$alice->set('foaf:name', 'Alice');
$carol->set('foaf:name', 'Carol');
$bob->add('foaf:knows', $alice);
$bob->add('foaf:knows', $carol);
$alice->add('foaf:knows', $bob);
$alice->add('foaf:knows', $carol);
// Create a GraphViz serialiser
$gv = new EasyRdf_Serialiser_GraphViz();
예제 #12
0
 public function testParseFormatObject()
 {
     $format = EasyRdf_Format::getFormat('json');
     $this->assertTrue($this->_parser->parse($this->_graph, $this->_data, $format, null));
 }
 /** Send some graph data to the graph store
  *
  * This method is used by insert() and replace()
  *
  * @ignore
  */
 protected function sendGraph($method, $graph, $uriRef, $format)
 {
     if (is_object($graph) and $graph instanceof EasyRdf_Graph) {
         if ($uriRef == null) {
             $uriRef = $graph->getUri();
         }
         $data = $graph->serialise($format);
     } else {
         $data = $graph;
     }
     $formatObj = EasyRdf_Format::getFormat($format);
     $mimeType = $formatObj->getDefaultMimeType();
     $graphUri = $this->_parsedUri->resolve($uriRef)->toString();
     $dataUrl = $this->urlForGraph($graphUri);
     $client = EasyRdf_Http::getDefaultHttpClient();
     $client->resetParameters(true);
     $client->setUri($dataUrl);
     $client->setMethod($method);
     $client->setRawData($data);
     $client->setHeaders('Content-Type', $mimeType);
     $client->setHeaders('Content-Length', strlen($data));
     $response = $client->request();
     if (!$response->isSuccessful()) {
         throw new EasyRdf_Exception("HTTP request for {$dataUrl} failed: " . $response->getMessage());
     }
     return $response;
 }
예제 #14
0
파일: Graph.php 프로젝트: aWEBoLabs/taxi
 /** Serialise the graph into RDF
  *
  * The $format parameter can be an EasyRdf_Format object, a
  * format name, a mime type or a file extension.
  *
  * Example:
  *   $turtle = $graph->serialise('turtle');
  *
  * @param  mixed $format  The format to serialise to
  * @param  array $options Serialiser-specific options, for fine-tuning the output
  * @return mixed  The serialised graph
  */
 public function serialise($format, array $options = array())
 {
     if (!$format instanceof EasyRdf_Format) {
         $format = EasyRdf_Format::getFormat($format);
     }
     $serialiser = $format->newSerialiser();
     return $serialiser->serialise($this, $format->getName(), $options);
 }
 public function testSerialiseFormatObject()
 {
     $format = EasyRdf_Format::getFormat('json');
     $this->assertTrue($this->_serialiser->serialise($this->_graph, $format));
 }
예제 #16
0
 public static function rdfRenderer(Graph $graph, $formatName)
 {
     $format = Format::getFormat($formatName);
     static::setContentType($format->getDefaultMimeType());
     return $format->newSerialiser()->serialise($graph, $formatName);
 }
    print label_tag('output_format', 'Output Format: ') . select_tag('output_format', $output_format_options) . "<br />\n";
    print label_tag('raw', 'Raw Output: ') . check_box_tag('raw') . "<br />\n";
    print reset_tag() . submit_tag();
    print form_end_tag();
    print "</div>\n";
}
if (isset($_REQUEST['uri']) or isset($_REQUEST['data'])) {
    // Parse the input
    $graph = new EasyRdf_Graph($_REQUEST['uri']);
    if (empty($_REQUEST['data'])) {
        $graph->load($_REQUEST['uri'], $_REQUEST['input_format']);
    } else {
        $graph->parse($_REQUEST['data'], $_REQUEST['input_format'], $_REQUEST['uri']);
    }
    // Lookup the output format
    $format = EasyRdf_Format::getFormat($_REQUEST['output_format']);
    // Serialise to the new output format
    $output = $graph->serialise($format);
    if (!is_scalar($output)) {
        $output = var_export($output, true);
    }
    // Send the output back to the client
    if (isset($_REQUEST['raw'])) {
        header('Content-Type: ' . $format->getDefaultMimeType());
        print $output;
    } else {
        print '<pre>' . htmlspecialchars($output) . '</pre>';
    }
}
if (!isset($_REQUEST['raw'])) {
    print "</body>\n";
예제 #18
0
 /** Serialise the graph into RDF
  *
  * @param  string  $format  The format to serialise to
  * @return mixed   The serialised graph
  */
 public function serialise($format)
 {
     $format = EasyRdf_Format::getFormat($format);
     $serialiser = $format->newSerialiser();
     return $serialiser->serialise($this, $format->getName());
 }
예제 #19
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;
     }
 }