Example #1
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'));
 }
 public function setUp()
 {
     EasyRdf_Http::setDefaultHttpClient($this->_client = new EasyRdf_Http_MockClient());
     $this->_graphStore = new EasyRdf_GraphStore('http://localhost:8080/data/');
     // Ensure that the built-in n-triples parser is used
     EasyRdf_Format::registerSerialiser('ntriples', 'EasyRdf_Serialiser_Ntriples');
 }
 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;
 }
Example #4
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;
 }
Example #5
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));
     }
 }
 public function setup()
 {
     // Reset to built-in parsers
     EasyRdf_Format::registerParser('ntriples', 'EasyRdf_Parser_Ntriples');
     EasyRdf_Format::registerParser('rdfxml', 'EasyRdf_Parser_RdfXml');
     EasyRdf_Format::registerParser('turtle', 'EasyRdf_Parser_Turtle');
 }
 /**
  * @Route("/create-person")
  */
 public function createPersonAction()
 {
     \EasyRdf_Format::registerSerialiser('ntriples', 'EasyRdf_Serialiser_Arc');
     \EasyRdf_Format::registerSerialiser('posh', 'EasyRdf_Serialiser_Arc');
     \EasyRdf_Format::registerSerialiser('rdfxml', 'EasyRdf_Serialiser_Arc');
     \EasyRdf_Format::registerSerialiser('turtle', 'EasyRdf_Serialiser_Arc');
     \EasyRdf_Namespace::set('foaf', 'http://xmlns.com/foaf/0.1/');
     $uri = 'http://www.example.com/emi#me';
     $name = 'Emi Berea';
     $emailStr = '*****@*****.**';
     $homepageStr = 'http://bereae.me/';
     $graph = new \EasyRdf_Graph();
     # 1st Technique
     $me = $graph->resource($uri, 'foaf:Person');
     $me->set('foaf:name', $name);
     if ($emailStr) {
         $email = $graph->resource("mailto:" . $emailStr);
         $me->add('foaf:mbox', $email);
     }
     if ($homepageStr) {
         $homepage = $graph->resource($homepageStr);
         $me->add('foaf:homepage', $homepage);
     }
     # Finally output the graph
     $data = $graph->serialise('rdfxml');
     if (!is_scalar($data)) {
         $data = var_export($data, true);
     }
     var_dump($data);
     die;
 }
 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'));
 }
 public function __construct(EasyRdf_Graph $graph = null)
 {
     if ($graph === null) {
         $graph = new EasyRdf_Graph();
     }
     $this->graph = $graph;
     $this->uriGenerators = array();
     EasyRdf_Format::register('rdfxml', 'RDF/XML', 'http://www.w3.org/TR/rdf-syntax-grammar', 'application/rdf+xml');
     //EasyRdf_Format::registerParser( 'rdfxml', 'EasyRdf_Parser_RdfXml');
     EasyRdf_Format::registerSerialiser('rdfxml', 'EasyRdf_Serialiser_RdfXml');
 }
Example #10
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));
 }
 /**
  * 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);
 }
Example #12
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);
 }
Example #13
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;
 }
 public function addMock($method, $uri, $body, $options = array())
 {
     $match = array();
     $match['method'] = $method;
     $match['uri'] = array();
     if (isset($options['callback'])) {
         $match['callback'] = $options['callback'];
         if (isset($options['callbackArgs'])) {
             $match['callbackArgs'] = $options['callbackArgs'];
         } else {
             $match['callbackArgs'] = array();
         }
     }
     if (!isset($uri)) {
         $match['uri'] = null;
     } else {
         $match['uri'] = strval($uri);
     }
     if ($body instanceof EasyRdf_Http_Response) {
         $response = $body;
     } else {
         if (isset($options['status'])) {
             $status = $options['status'];
         } else {
             $status = 200;
         }
         if (isset($options['headers'])) {
             $headers = $options['headers'];
         } else {
             $headers = array();
             $format = EasyRdf_Format::guessFormat($body);
             if (isset($format)) {
                 $headers['Content-Type'] = $format->getDefaultMimeType();
             }
             if (isset($body)) {
                 $headers['Content-Length'] = strlen($body);
             }
         }
         $response = new EasyRdf_Http_Response($status, $headers, $body);
     }
     $once = isset($options['once']) ? $options['once'] : false;
     $this->_mocks[] = array($match, $response, $once);
 }
 /** 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;
 }
Example #16
0
     *
     * @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 boolean             true if parsing was successful
     */
    public function parse($graph, $data, $format, $baseUri)
    {
        parent::checkParseParams($graph, $data, $format, $baseUri);
        if (array_key_exists($format, self::$_supportedTypes)) {
            $className = self::$_supportedTypes[$format];
        } else {
            throw new EasyRdf_Exception("EasyRdf_Parser_Arc does not support: {$format}");
        }
        $parser = ARC2::getParser($className);
        if ($parser) {
            $parser->parse($baseUri, $data);
            $rdfphp = $parser->getSimpleIndex(false);
            return parent::parse($graph, $rdfphp, 'php', $baseUri);
        } else {
            throw new EasyRdf_Exception("ARC2 failed to get a {$className} parser.");
        }
    }
}
## FIXME: do this automatically
EasyRdf_Format::registerParser('rdfxml', 'EasyRdf_Parser_Arc');
EasyRdf_Format::registerParser('turtle', 'EasyRdf_Parser_Arc');
EasyRdf_Format::registerParser('ntriples', 'EasyRdf_Parser_Arc');
EasyRdf_Format::registerParser('rdfa', 'EasyRdf_Parser_Arc');
Example #17
0
EasyRdf_Format::register('turtle', 'Turtle Terse RDF Triple Language', 'http://www.dajobe.org/2004/01/turtle', array('text/turtle' => 0.8, 'application/turtle' => 0.7, 'application/x-turtle' => 0.7), array('ttl'));
EasyRdf_Format::register('rdfxml', 'RDF/XML', 'http://www.w3.org/TR/rdf-syntax-grammar', array('application/rdf+xml' => 0.8), array('rdf', 'xrdf'));
EasyRdf_Format::register('dot', 'Graphviz', 'http://www.graphviz.org/doc/info/lang.html', array('text/vnd.graphviz' => 0.8), array('gv', 'dot'));
EasyRdf_Format::register('json-triples', 'RDF/JSON Triples');
EasyRdf_Format::register('n3', 'Notation3', 'http://www.w3.org/2000/10/swap/grammar/n3#', array('text/n3' => 0.5, 'text/rdf+n3' => 0.5), array('n3'));
EasyRdf_Format::register('rdfa', 'RDFa', 'http://www.w3.org/TR/rdfa-core/', array('text/html' => 0.4, 'application/xhtml+xml' => 0.4), array('html'));
EasyRdf_Format::register('sparql-xml', 'SPARQL XML Query Results', 'http://www.w3.org/TR/rdf-sparql-XMLres/', array('application/sparql-results+xml' => 1.0));
EasyRdf_Format::register('sparql-json', 'SPARQL JSON Query Results', 'http://www.w3.org/TR/rdf-sparql-json-res/', array('application/sparql-results+json' => 1.0));
EasyRdf_Format::register('png', 'Portable Network Graphics (PNG)', 'http://www.w3.org/TR/PNG/', array('image/png' => 0.3), array('png'));
EasyRdf_Format::register('gif', 'Graphics Interchange Format (GIF)', 'http://www.w3.org/Graphics/GIF/spec-gif89a.txt', array('image/gif' => 0.2), array('gif'));
EasyRdf_Format::register('svg', 'Scalable Vector Graphics (SVG)', 'http://www.w3.org/TR/SVG/', array('image/svg+xml' => 0.3), array('svg'));
/*
   Register default set of parsers and serialisers
*/
EasyRdf_Format::registerParser('json', 'EasyRdf_Parser_Json');
EasyRdf_Format::registerParser('ntriples', 'EasyRdf_Parser_Ntriples');
EasyRdf_Format::registerParser('php', 'EasyRdf_Parser_RdfPhp');
EasyRdf_Format::registerParser('rdfxml', 'EasyRdf_Parser_RdfXml');
EasyRdf_Format::registerParser('turtle', 'EasyRdf_Parser_Turtle');
EasyRdf_Format::registerParser('rdfa', 'EasyRdf_Parser_Rdfa');
EasyRdf_Format::registerSerialiser('json', 'EasyRdf_Serialiser_Json');
EasyRdf_Format::registerSerialiser('n3', 'EasyRdf_Serialiser_Turtle');
EasyRdf_Format::registerSerialiser('ntriples', 'EasyRdf_Serialiser_Ntriples');
EasyRdf_Format::registerSerialiser('php', 'EasyRdf_Serialiser_RdfPhp');
EasyRdf_Format::registerSerialiser('rdfxml', 'EasyRdf_Serialiser_RdfXml');
EasyRdf_Format::registerSerialiser('turtle', 'EasyRdf_Serialiser_Turtle');
EasyRdf_Format::registerSerialiser('dot', 'EasyRdf_Serialiser_GraphViz');
EasyRdf_Format::registerSerialiser('gif', 'EasyRdf_Serialiser_GraphViz');
EasyRdf_Format::registerSerialiser('png', 'EasyRdf_Serialiser_GraphViz');
EasyRdf_Format::registerSerialiser('svg', 'EasyRdf_Serialiser_GraphViz');
Example #18
0
    }
    /**
     * Parse an RDF/XML document into an EasyRdf_Graph
     *
     * @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 boolean             true if parsing was successful
     */
    public function parse($graph, $data, $format, $baseUri)
    {
        parent::checkParseParams($graph, $data, $format, $baseUri);
        if ($format != 'rdfxml') {
            throw new EasyRdf_Exception("EasyRdf_Parser_RdfXml does not support: {$format}");
        }
        $this->init($graph, $baseUri);
        $this->resetBnodeMap();
        /* xml parser */
        $this->initXMLParser();
        /* parse */
        if (!xml_parse($this->_xmlParser, $data, false)) {
            throw new EasyRdf_Exception('XML error: "' . xml_error_string(xml_get_error_code($this->_xmlParser)) . '" at line ' . xml_get_current_line_number($this->_xmlParser));
        }
        xml_parser_free($this->_xmlParser);
        // Success
        return true;
    }
}
EasyRdf_Format::registerParser('rdfxml', 'EasyRdf_Parser_RdfXml');
Example #19
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();
Example #20
0
    public function parse($graph, $data, $format, $baseUri)
    {
        parent::checkParseParams($graph, $data, $format, $baseUri);
        if ($format != 'php') {
            throw new EasyRdf_Exception("EasyRdf_Parser_RdfPhp does not support: {$format}");
        }
        // Reset the bnode mapping
        $this->resetBnodeMap();
        foreach ($data as $subject => $properties) {
            if (substr($subject, 0, 2) === '_:') {
                $subject = $this->remapBnode($graph, $subject);
            } elseif (preg_match('/^\\w+$/', $subject)) {
                # Cope with invalid RDF/JSON serialisations that
                # put the node name in, without the _: prefix
                # (such as net.fortytwo.sesametools.rdfjson)
                $subject = $this->remapBnode($graph, $subject);
            }
            foreach ($properties as $property => $objects) {
                foreach ($objects as $object) {
                    if ($object['type'] === 'bnode') {
                        $object['value'] = $this->remapBnode($graph, $object['value']);
                    }
                    $graph->add($subject, $property, $object);
                }
            }
        }
        return true;
    }
}
EasyRdf_Format::registerParser('php', 'EasyRdf_Parser_RdfPhp');
Example #21
0
 /** Make a query to the SPARQL endpoint
  *
  * SELECT and ASK queries will return an object of type
  * EasyRdf_Sparql_Result.
  *
  * CONSTRUCT and DESCRIBE queries will return an object
  * of type EasyRdf_Graph.
  *
  * @param string $query The query string to be executed
  * @return object EasyRdf_Sparql_Result|EasyRdf_Graph Result of the query.
  */
 public function query($query)
 {
     # Add namespaces to the queryString
     $prefixes = '';
     foreach (EasyRdf_Namespace::namespaces() as $prefix => $uri) {
         if (strpos($query, "{$prefix}:") !== false and strpos($query, "PREFIX {$prefix}:") === false) {
             $prefixes .= "PREFIX {$prefix}: <{$uri}>\n";
         }
     }
     $client = EasyRdf_Http::getDefaultHttpClient();
     $client->resetParameters();
     $client->setUri($this->_uri);
     $client->setMethod('GET');
     $accept = EasyRdf_Format::getHttpAcceptHeader(array('application/sparql-results+json' => 1.0, 'application/sparql-results+xml' => 0.8));
     $client->setHeaders('Accept', $accept);
     $client->setParameterGet('query', $prefixes . $query);
     $response = $client->request();
     if ($response->isSuccessful()) {
         $type = $response->getHeader('Content-Type');
         if (strpos($type, 'application/sparql-results') === 0) {
             return new EasyRdf_Sparql_Result($response->getBody(), $type);
         } else {
             return new EasyRdf_Graph($this->_uri, $response->getBody(), $type);
         }
     } else {
         throw new EasyRdf_Exception("HTTP request for SPARQL query failed: " . $response->getBody());
     }
 }
Example #22
0
        <>  a ldp:DirectContainer, foaf:Document ;
            foaf:primaryTopic :dataset ;
            ldp:membershipResource :dataset ;
            ldp:hasMemberRelation void:dataDump ;
            ldp:insertedContentRelation foaf:primaryTopic ;
            
        .
        :dataset a void:Dataset, prov:Entity ;
            prov:wasGeneratedBy [
                a prov:Activity ;
                prov:used <{queryResource}> ;
                prov:wasAssociatedWith :sparqlServerUser
            ]
        .
        :sparqlServerUser a foaf:Agent;
            foaf:account [
                a foaf:OnlineAccount ;
                foaf:accountServiceHomepage <{endpoint}> ;
                foaf:accountname "{username}" ;
            ]
        .
     ';
}
// fix a bug of Easy RDF
EasyRdf_Format::register('turtle', 'Turtle Terse RDF Triple Language', 'http://www.w3.org/TR/turtle/', array('text/turtle' => 1.0, 'application/turtle' => 0.7, 'application/x-turtle' => 0.7), array('ttl'));
$errorManager = BOTK\Core\ErrorManager::getInstance()->registerErrorHandler();
try {
    echo BOTK\Core\EndPointFactory::make('MyRouter')->run();
} catch (Exception $e) {
    echo $errorManager->render($e);
}
Example #23
0
 public function testParseFormatObject()
 {
     $format = EasyRdf_Format::getFormat('json');
     $this->assertTrue($this->_parser->parse($this->_graph, $this->_data, $format, null));
 }
        }
        $stream = librdf_parser_parse_string_as_stream($parser, $data, $rdfUri);
        if (!$stream) {
            throw new EasyRdf_Exception("Failed to parse RDF stream for: {$rdfUri}");
        }
        do {
            $statement = librdf_stream_get_object($stream);
            if ($statement) {
                $subject = EasyRdf_Parser_Redland::nodeUriString(librdf_statement_get_subject($statement));
                $predicate = EasyRdf_Parser_Redland::nodeUriString(librdf_statement_get_predicate($statement));
                $object = EasyRdf_Parser_Redland::nodeToArray(librdf_statement_get_object($statement));
                $graph->add($subject, $predicate, $object);
            }
        } while (!librdf_stream_next($stream));
        $errorCount = $this->parserErrorCount($parser);
        if ($errorCount) {
            throw new EasyRdf_Exception("{$errorCount} errors while parsing.");
        }
        librdf_free_uri($rdfUri);
        librdf_free_stream($stream);
        librdf_free_parser($parser);
        // Success
        return true;
    }
}
## FIXME: do this automatically
EasyRdf_Format::registerParser('rdfxml', 'EasyRdf_Parser_Redland');
EasyRdf_Format::registerParser('turtle', 'EasyRdf_Parser_Redland');
EasyRdf_Format::registerParser('ntriples', 'EasyRdf_Parser_Redland');
EasyRdf_Format::registerParser('rdfa', 'EasyRdf_Parser_Redland');
    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";
Example #26
0
    }
    /**
     * Serialise an EasyRdf_Graph into RDF format of choice.
     *
     * @param object EasyRdf_Graph $graph   An EasyRdf_Graph object.
     * @param string               $format  The name of the format to convert to.
     * @return string              The RDF in the new desired format.
     */
    public function serialise($graph, $format)
    {
        parent::checkSerialiseParams($graph, $format);
        if (array_key_exists($format, self::$_supportedTypes)) {
            $className = self::$_supportedTypes[$format];
        } else {
            throw new EasyRdf_Exception("EasyRdf_Serialiser_Arc does not support: {$format}");
        }
        $serialiser = ARC2::getSer($className);
        if ($serialiser) {
            return $serialiser->getSerializedIndex(parent::serialise($graph, 'php'));
        } else {
            throw new EasyRdf_Exception("ARC2 failed to get a {$className} serialiser.");
        }
    }
}
# FIXME: to this automatically
EasyRdf_Format::register('posh', 'poshRDF');
EasyRdf_Format::registerSerialiser('ntriples', 'EasyRdf_Serialiser_Arc');
EasyRdf_Format::registerSerialiser('posh', 'EasyRdf_Serialiser_Arc');
EasyRdf_Format::registerSerialiser('rdfxml', 'EasyRdf_Serialiser_Arc');
EasyRdf_Format::registerSerialiser('turtle', 'EasyRdf_Serialiser_Arc');
 * supported input and output formats. These options are then
 * displayed on the HTML form.
 *
 * The input data is loaded or parsed into an EasyRdf_Graph.
 * That graph is than outputted again in the desired output format.
 *
 * @package    EasyRdf
 * @copyright  Copyright (c) 2009-2011 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";
$input_format_options = array('Guess' => 'guess');
$output_format_options = array();
foreach (EasyRdf_Format::getFormats() as $format) {
    if ($format->getSerialiserClass()) {
        $output_format_options[$format->getLabel()] = $format->getName();
    }
    if ($format->getParserClass()) {
        $input_format_options[$format->getLabel()] = $format->getName();
    }
}
?>
<html>
<head><title>EasyRdf Converter</title></head>
<body>
<h1>EasyRdf Converter</h1>

<div style="margin: 10px">
  <?php 
        /* not defined => ignore */
    }
    /**
     * Serialise an EasyRdf_Graph into N-Triples
     *
     * @param object EasyRdf_Graph $graph   An EasyRdf_Graph object.
     * @param string  $format               The name of the format to convert to.
     * @return string                       The RDF in the new desired format.
     */
    public function serialise($graph, $format)
    {
        parent::checkSerialiseParams($graph, $format);
        if ($format != 'ntriples') {
            throw new EasyRdf_Exception("EasyRdf_Serialiser_Ntriples does not support: {$format}");
        }
        $nt = '';
        foreach ($graph->resources() as $resource) {
            foreach ($resource->propertyUris() as $property) {
                $objects = $resource->all($property);
                foreach ($objects as $object) {
                    $nt .= $this->ntriplesResource($resource) . " ";
                    $nt .= "<" . $this->escape($property) . "> ";
                    $nt .= $this->ntriplesObject($object) . " .\n";
                }
            }
        }
        return $nt;
    }
}
EasyRdf_Format::registerSerialiser('ntriples', 'EasyRdf_Serialiser_Ntriples');
Example #29
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());
 }
Example #30
0
    public function __construct()
    {
        require_once 'arc/ARC2.php';
    }
    /**
     * Serialise an EasyRdf_Graph into RDF format of choice.
     *
     * @param EasyRdf_Graph $graph   An EasyRdf_Graph object.
     * @param string        $format  The name of the format to convert to.
     * @param array         $options
     * @throws EasyRdf_Exception
     * @return string              The RDF in the new desired format.
     */
    public function serialise($graph, $format, array $options = array())
    {
        parent::checkSerialiseParams($graph, $format);
        if (array_key_exists($format, self::$supportedTypes)) {
            $className = self::$supportedTypes[$format];
        } else {
            throw new EasyRdf_Exception("EasyRdf_Serialiser_Arc does not support: {$format}");
        }
        $serialiser = ARC2::getSer($className);
        if ($serialiser) {
            return $serialiser->getSerializedIndex(parent::serialise($graph, 'php'));
        } else {
            throw new EasyRdf_Exception("ARC2 failed to get a {$className} serialiser.");
        }
    }
}
EasyRdf_Format::register('posh', 'poshRDF');