/** Get the data for reuse based off sparql endpoint * @access public * @return array $data * */ public function getInfo($identifier) { $key = md5($identifier . 'ocre'); $uri = self::CRRO . $identifier; if (!$this->getCache()->test($key)) { EasyRdf_Namespace::set('nm', 'http://nomisma.org/id/'); EasyRdf_Namespace::set('nmo', 'http://nomisma.org/ontology#'); EasyRdf_Namespace::set('skos', 'http://www.w3.org/2004/02/skos/core#'); EasyRdf_Namespace::set('rdf', 'http://www.w3.org/1999/02/22-rdf-syntax-ns#'); $request = new EasyRdf_Http_Client(); $request->setUri($uri); $response = $request->request()->getStatus(); if ($response == 200) { $graph = new EasyRdf_Graph($uri); $graph->load(); $data = $graph->resource($uri); $this->getCache()->save($data); } else { $data = NULL; } } else { $data = $this->getCache()->load($key); } return $data; }
/** Register the namespaces with EasyRdf * @access public * @return \Pas_View_Helper_SparqlEasy */ public function registerNameSpaces() { foreach ($this->getNameSpaces() as $k => $v) { EasyRdf_Namespace::set($k, $v); } return $this; }
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."); } }
function init_vocabularies() { $voc_prefixes = array("cc" => "http://creativecommons.org/ns#", "mdc" => "http://purl.org/meducator/repurposing", "rdf" => "http://www.w3.org/1999/02/22-rdf-syntax-ns#", "dcterms" => "http://purl.org/dc/terms", "ebucore" => "http://www.ebu.ch/metadata/ontologies/ebucore/ebucore", "nrl" => "http://www.semanticdesktop.org/ontologies/2007/08/15/nrl", "va" => "http://code-research.eu/ontology/visual-analytics", "ex" => "http://example.org"); foreach ($voc_prefixes as $key => $value) { EasyRdf_Namespace::set($key, $value); } }
/** 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()); } }
/** * Create the DCAT document of the published (non-draft) resources * * @param $pieces array of uri pieces * @return mixed \Data object with a graph of DCAT information */ private function createDcat() { $ns = $this->dcat->getNamespaces(); foreach ($ns as $prefix => $uri) { \EasyRdf_Namespace::set($prefix, $uri); } // Apply paging when fetching the definitions list($limit, $offset) = Pager::calculateLimitAndOffset(); $definition_count = $this->definitions->countPublished(); $definitions = $this->definitions->getAllPublished($limit, $offset); $oldest = $this->definitions->getOldest(); $describedDefinitions = array(); // Add the source type description to the definition foreach ($definitions as $definition) { $definition = array_merge($definition, $this->definitions->getFullDescription($definition['collection_uri'] . '/' . $definition['resource_name'])); array_push($describedDefinitions, $definition); } $graph = $this->dcat->getDcatDocument($describedDefinitions, $oldest); // Return the dcat feed in our internal data object $data_result = new Data(); $data_result->data = $graph; $data_result->is_semantic = true; $data_result->paging = Pager::calculatePagingHeaders($limit, $offset, $definition_count); // Add the semantic configuration for the ARC graph $data_result->semantic = new \stdClass(); $data_result->semantic->conf = array('ns' => $ns); $data_result->definition = new \stdClass(); $data_result->definition->resource_name = 'dcat'; $data_result->definition->collection_uri = 'info'; return $data_result; }
/** * @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 __construct() { // Enable things like: http://linda/lists/frequencies.json?q=trien // cfr. https://github.com/iRail/hyperRail/blob/master/app/controllers/StationController.php#L44 $this->lists = ["frequencies" => [], "organizationtypes" => [], "uses" => []]; \EasyRdf_Namespace::set('linda', 'http://semweb.mmlab.be/ns/linda#'); \EasyRdf_Namespace::set('odapps', 'http://semweb.mmlab.be/ns/odapps#'); }
function getPeople($name, $affil) { EasyRdf_Namespace::set('sd', 'http://symbolicdata.org/Data/Model#'); $query = ' PREFIX sd: <http://symbolicdata.org/Data/Model#> construct { ?a ?b ?c . } from <http://symbolicdata.org/Data/People/> from <http://symbolicdata.org/Data/AuthorIdentification/> from <http://symbolicdata.org/Data/PersonalProfiles/> from <http://symbolicdata.org/Data/BenchmarkReferences/> Where { ?a a foaf:Person ; ?b ?c; foaf:name $n . optional { ?a sd:affiliation $f . } filter regex(?n, "' . $name . '","i") filter regex(?f, "' . $affil . '","i") } LIMIT 100'; $sparql = new EasyRdf_Sparql_Client('http://symbolicdata.org:8890/sparql'); $result = $sparql->query($query); // a CONSTRUCT query returns an EasyRdf_Graph //echo $result->dump("turtle"); /* generate data structure for output table */ $s = array(); foreach ($result->allOfType("foaf:Person") as $v) { $a = $v->getUri(); $label = $v->get('foaf:name'); $loc = $v->get('sd:affiliation'); $hp = $v->get('foaf:homepage'); $zb = $v->get('sd:hasZBMathAuthorID'); $mr = $v->get('sd:hasMRAuthorID'); $bs = $v->get('sd:providesDataAt'); $pp = $v->get('sd:hasPersonalProfile'); $out = '<p><dl> <dt><strong><a href="' . $a . '">' . $label . '</a></strong></dt> '; if (!empty($loc)) { $out .= '<dd>Affiliation: ' . $loc . '.</dd>'; } if (!empty($hp)) { $out .= '<dd>Homepage: <a href="' . $hp . '">' . $hp . '</a></dd>'; } if (!empty($pp)) { $out .= '<dd>Personal FOAF Profile: <a href="' . $pp . '">' . $pp . '</a></dd>'; } if (!empty($zb)) { $out .= '<dd>ZBMath Author Code: <a href="' . $zb . '">' . $zb . '</a></dd>'; } if (!empty($mr)) { $out .= '<dd>MR Author ID: <a href="' . $mr . '">' . $mr . '</a></dd>'; } if (!empty($bs)) { $out .= '<dd>Provides Benchmark References at: <a href="' . $bs . '">' . $bs . '</a></dd>'; } $out .= '</dl></p>'; $s["{$a}"] = $out; } ksort($s); return '<h4>List of entries with foaf:name containing "' . $name . '" and sd:affiliation containing "' . $affil . '"</h4>' . join($s, "\n"); }
public function get_action($data) { EasyRdf_Namespace::set('o311', 'http://ontology.eil.utoronto.ca/open311.owl#'); $sparql = new EasyRdf_Sparql_Client('http://localhost:8890/sparql'); //SAMPLE QUERY: select * where {?sub o311:hasAddress o311:iiitCC3. ?sub o311:has311Subject o311:Waste. ?sub o311:need311Action ?action. ?sub o311:isHandledBy ?authority. ?authority o311:AgencyName ?name. ?authority o311:Phone ?phone. ?authority o311:Email ?email. ?authority o311:AddressType ?address }'; $str = 'SELECT * WHERE {' . '?sub o311:hasAddress o311:' . $data["where"] . ". " . '?sub o311:has311Subject o311:' . $data["what"] . ". " . '?sub o311:isHandledBy ?authority. ' . '?sub o311:need311Action ?action. ' . '?authority o311:AgencyName ?name.' . '?authority o311:Phone ?phone.' . '?authority o311:Email ?email.' . '?authority o311:AddressType ?address.' . '} '; echo "<br><i><font color = 'grey'>{$str}</font></i><br>"; $result = $sparql->query($str); return $result; }
public function indexAction() { $foaf = \EasyRdf_Graph::newAndLoad('http://njh.me/foaf.rdf'); $me = $foaf->primaryTopic(); \EasyRdf_Namespace::set('category', 'http://dbpedia.org/resource/Category:'); \EasyRdf_Namespace::set('dbpedia', 'http://dbpedia.org/resource/'); \EasyRdf_Namespace::set('dbo', 'http://dbpedia.org/ontology/'); \EasyRdf_Namespace::set('dbp', 'http://dbpedia.org/property/'); $sparql = new \EasyRdf_Sparql_Client('http://dbpedia.org/sparql'); $result = $sparql->query('SELECT * WHERE {' . ' ?country rdf:type dbo:Country .' . ' ?country rdfs:label ?label .' . ' ?country dc:subject category:Member_states_of_the_United_Nations .' . ' FILTER ( lang(?label) = "en" )' . '} ORDER BY ?label'); return $this->render('MyAppBlogBundle:Default:index.html.twig', array('name' => $result, 'count' => $result->numRows())); }
public function testSerialiseJson() { \EasyRdf_Namespace::set('', 'http://foo/bar/'); $joe = $this->graph->resource('http://www.example.com/joe#me', 'foaf:Person'); $joe->set('foaf:name', new EasyRdf_Literal('Joe Bloggs', 'en')); $joe->set('foaf:homepage', $this->graph->resource('http://foo/bar/me')); $joe->set('foaf:age', 59); $project = $this->graph->newBNode(); $project->add('foaf:name', 'Project Name'); $joe->add('foaf:project', $project); $json = $this->serialiser->serialise($this->graph, 'json'); $this->assertSame('{"http:\\/\\/www.example.com\\/joe#me":{' . '"http:\\/\\/www.w3.org\\/1999\\/02\\/22-rdf-syntax-ns#type":[' . '{"type":"uri","value":"http:\\/\\/xmlns.com\\/foaf\\/0.1\\/Person"}],' . '"http:\\/\\/xmlns.com\\/foaf\\/0.1\\/name":[' . '{"type":"literal","value":"Joe Bloggs","lang":"en"}],' . '"http:\\/\\/xmlns.com\\/foaf\\/0.1\\/homepage":[{"type":"uri","value":"http:\\/\\/foo\\/bar\\/me"}],' . '"http:\\/\\/xmlns.com\\/foaf\\/0.1\\/age":[' . '{"type":"literal","value":"59","datatype":' . '"http:\\/\\/www.w3.org\\/2001\\/XMLSchema#integer"}],' . '"http:\\/\\/xmlns.com\\/foaf\\/0.1\\/project":[' . '{"type":"bnode","value":"_:genid1"}]},"_:genid1":{' . '"http:\\/\\/xmlns.com\\/foaf\\/0.1\\/name":[' . '{"type":"literal","value":"Project Name"}]}}', $this->serialiser->serialise($this->graph, 'json')); }
function dissertationen($atts) { EasyRdf_Namespace::set('bibo', 'http://purl.org/ontology/bibo/'); EasyRdf_Namespace::set('sd', 'http://symbolicdata.org/Data/Model#'); EasyRdf_Namespace::set('dct', 'http://purl.org/dc/terms/'); $people = new EasyRdf_Graph("http://symbolicdata.org/Data/People/"); $people->parseFile("http://symbolicdata.org/rdf/People.rdf"); //$people->parseFile("/home/graebe/git/SD/web/rdf/People.rdf"); $out = "\n\n<h2 align=\"center\">Habilitationen</h2>\n\n"; $out .= displayAll(getDissertations('habil'), $people); $out .= "\n\n<h2 align=\"center\">Promotionen</h2>\n\n"; $out .= displayAll(getDissertations('phd'), $people); return $out; }
function casystems() { EasyRdf_Namespace::set('sd', 'http://symbolicdata.org/Data/Model#'); EasyRdf_Namespace::set('dct', 'http://purl.org/dc/terms/'); EasyRdf_Namespace::set('owl', 'http://www.w3.org/2002/07/owl#'); $people = new EasyRdf_Graph("http://symbolicdata.org/Data/People/"); $people->parseFile("http://symbolicdata.org/rdf/People.rdf"); //$people->parseFile("/home/graebe/git/SD/web/rdf/People.rdf"); $systems = new EasyRdf_Graph("http://symbolicdata.org/Data/CA-Systems/"); $systems->parseFile("http://symbolicdata.org/rdf/CA-Systems.rdf"); //$systems->parseFile("/home/graebe/git/SD/web/rdf/CA-Systems.rdf"); $out = displaySystems($systems, $people); return $out; }
function getNews() { EasyRdf_Namespace::set('sd', 'http://symbolicdata.org/Data/Model#'); EasyRdf_Namespace::set('sioc', 'http://rdfs.org/sioc/ns#'); $query1 = ' PREFIX sd: <http://symbolicdata.org/Data/Model#> construct { ?a ?b ?c . } from <http://symbolicdata.org/Data/News/> Where { ?a a sioc:BlogPost ; ?b ?c . } '; $query2 = ' PREFIX sd: <http://symbolicdata.org/Data/Model#> construct { ?p foaf:name ?n . } from <http://symbolicdata.org/Data/News/> from <http://symbolicdata.org/Data/People/> Where { ?a a sioc:BlogPost ; dc:publisher ?p . ?p foaf:name ?n . } '; $sparql = new EasyRdf_Sparql_Client('http://symbolicdata.org:8890/sparql'); $result = $sparql->query($query1); // a CONSTRUCT query returns an EasyRdf_Graph //echo $result->dump("turtle"); $people = $sparql->query($query2); //echo $people->dump("turtle"); /* generate data structure for output table */ $s = array(); foreach ($result->allOfType("sioc:BlogPost") as $v) { $a = $v->getUri(); $label = $v->get('rdfs:label'); $created = $v->get('dc:created'); $subject = $v->join('dc:subject'); $abstract = $v->get('dc:abstract'); $publisher = $people->get($v->get('dc:publisher'), 'foaf:name'); $link = $v->get('sioc:link'); $linksTo = $v->get('sioc:links_to'); $out = '<p><dl> <dt><strong><a href="' . $a . '">' . $label . '</a></strong></dt> '; $out .= addLine($created, "Created"); $out .= addLine($subject, "Subject"); $out .= addLine($abstract, "Abstract"); $out .= addLine($publisher, "Publisher"); $out .= addLink($link, "More"); $out .= addLink($linksTo, "Links to"); $out .= '</dl></p>'; $s["{$created_}{$a}"] = $out; } krsort($s); return join($s, "\n"); }
function fddbSuche($gtin) { //$gtin = "4388844009943"; $gtin = preg_replace('/[^0-9]+/', '', $gtin); $data = curlData("http://fddb.mobi/search/?lang=de&cat=mobile-de&search=" . $gtin); $resultblock = between("<!-- %sresultblock% //-->", "<!-- %eresultblock% //-->", $data); $link = between("window.location.href = '", "';", $data); $area = between("<b>100 g:</b>", "<b>1 Packung:</b>", $data); if ($link != false && strlen($gtin) >= 13) { $werte = array("energy" => preg_replace('/[^0-9,.]+/', '', before("(", $area)), "calories" => preg_replace('/[^0-9,.]+/', '', between("(", ")", $area)), "fat" => preg_replace('/[^0-9,.]+/', '', between("Fett: ", "KH:", $area)), "carbonhydrate" => preg_replace('/[^0-9,.]+/', '', between("KH: ", "<br>", $area))); //$werte = array("Energie", "Energie1", "Fett", "Kohlenhydrate"); $naerhwerte = ""; foreach ($werte as $key => $value) { $naerhwerte[$key]["value"] = preg_replace('/[^0-9]+/', '', $werte[$key]); $naerhwerte[$key]["currencie"] = preg_replace('/[^a-zA-Z]+/', '', $werte[$key]); } $result = array("sourecName" => "fddb", "link" => $link, "gtin" => $gtin, "nutriTable" => $werte, "titel" => between("<a href='" . $link . "'><b>", '</b></a>', $resultblock)); $graph = new EasyRdf_Graph(); $namespace = new EasyRdf_Namespace(); $namespace->set('rezept', "http://manke-hosting.de/ns-syntax#"); buildTree($graph, $result["link"], $result, 'rezept'); echo $graph->serialise("turtle"); } }
/** * Processes the enhancements and loads them into an array. * * @param EasyRDF_Graph $graph RDF graph that holds the enhancements * * @return void */ private function _loadEnhancements($graph) { EasyRdf_Namespace::set("stanbol", "http://fise.iks-project.eu/ontology/"); Entity::mapType("foaf:Person", "Person"); $entityAnnotations = $graph->allOfType("http://fise.iks-project.eu/ontology/EntityAnnotation"); foreach ($entityAnnotations as $anno) { $entityAnnotation = new EntityAnnotation(Entity::create($anno)); $entityAnnotation->setId($anno->getUri()); $entityAnnotation->setTextAnnotations($this->_createTextAnnotations($anno->allResources("dc:relation"))); $entityAnnotation->setConfidence($anno->getLiteral("stanbol:confidence")->getValue()); $entityAnnotation->setEntityLabel($anno->getLiteral("stanbol:entity-label")->getValue()); $entityAnnotation->setEntityTypes($anno->allResources("stanbol:entity-type")); array_push($this->_enhancements, $entityAnnotation); } }
/** Get the graph to parse * @access protected * @returns object */ protected function getData() { $key = md5($this->_uri); if (!$this->_cache->test($key)) { $graph = new EasyRdf_Graph($this->_uri); $graph->load(); $data = $graph->resource($this->_uri); $this->_cache->save($data); } else { $data = $this->_cache->load($key); } EasyRdf_Namespace::set('dbpediaowl', 'http://dbpedia.org/ontology/'); EasyRdf_Namespace::set('dbpprop', 'http://dbpedia.org/property/'); EasyRdf_Namespace::set('dbpedia', 'http://dbpedia.org/resource/'); return $data; }
function pastConferences() { EasyRdf_Namespace::set('ical', 'http://www.w3.org/2002/12/cal/ical#'); EasyRdf_Namespace::set('sd', 'http://symbolicdata.org/Data/Model#'); $jahr = empty($_GET['year']) ? "2012" : $_GET['year']; $query = ' PREFIX sd: <http://symbolicdata.org/Data/Model#> PREFIX ical: <http://www.w3.org/2002/12/cal/ical#> construct { ?a ?b ?c . ?a sd:Series ?a2 . } from <http://symbolicdata.org/Data/PastConferences/> from <http://symbolicdata.org/Data/ConferenceSeries/> Where { ?a a sd:Conference ; ?b ?c ; ical:dtstart ?d . optional {?a sd:toConferenceSeries ?a1 . ?a1 rdfs:label ?a2 . } filter regex(?d, "' . $jahr . '") } '; $sparql = new EasyRdf_Sparql_Client('http://symbolicdata.org:8890/sparql'); $result = $sparql->query($query); // a CONSTRUCT query returns an EasyRdf_Graph //echo $result->dump("turtle"); /* generate data structure for output table */ $s = array(); foreach ($result->allOfType("sd:Conference") as $v) { $a = $v->getUri(); $label = $v->get('rdfs:label'); $from = date_format(date_create($v->get('ical:dtstart')), "Y/m/d"); $to = date_format(date_create($v->get('ical:dtend')), "Y/m/d"); $loc = $v->get('ical:location'); $series = $v->get('sd:Series'); $description = $v->get('ical:description'); $out = ' <p><dl> <dt><strong><a href="' . $a . '">' . $label . '</a></strong></dt> <dd>' . $from . ' – ' . $to . ' in ' . $loc . '.</dd>'; foreach ($v->all('ical:url') as $url) { $out .= '<dd> Conference URL: <a href="' . $url . '">' . $url . '</a></dd>'; } if (!empty($series)) { $out .= '<dd> Conference Series: ' . $series . '</dd>'; } $out .= '</dl></p>'; $s["{$from}.{$a}"] = $out; } krsort($s); return join($s, "\n"); }
/** * Create a new dataset * * @param array $config The config of the new dataset * * @return void */ public function add($config) { \EasyRdf_Namespace::set('odapps', 'http://semweb.mmlab.be/ns/odapps#'); // Create a auto-generated subject URI $id = $this->getIncrementalId(); $uri = \URL::to('/apps/' . $id); $context = $this->getContext(); $graph = new \EasyRdf_Graph(); $application = $graph->resource($uri . '#application'); $application->addType('odapps:Application'); foreach ($this->getFields() as $field) { if ($field['domain'] == 'odapps:Application') { if ($field['single_value'] && in_array($field['type'], ['string', 'text', 'list'])) { if (filter_var(trim($config[$field['var_name']]), FILTER_VALIDATE_URL)) { $graph->addResource($application, $field['sem_term'], trim($config[$field['var_name']])); } else { $graph->add($application, $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($application, $field['sem_term'], $val); } else { $graph->add($application, $field['sem_term'], $val); } } } } } } } $serializer = new \EasyRdf_Serialiser_JsonLd(); $jsonld = $serializer->serialise($graph, 'jsonld'); $compact_document = (array) JsonLD::compact($jsonld, $context); $serializer = new \EasyRdf_Serialiser_JsonLd(); $jsonld = $serializer->serialise($graph, 'jsonld'); $compact_document = (array) JsonLD::compact($jsonld, $context); $collection = $this->getMongoCollection(); $collection->insert($compact_document); }
/** * Set all required type mappers * * @return void */ public static function setTypeMappers() { EasyRdf_Namespace::set('spl', 'http://spinrdf.org/spl#'); EasyRdf_Namespace::set('spin', 'http://spinrdf.org/spin#'); EasyRdf_Namespace::set('sp', 'http://spinrdf.org/sp#'); // Query EasyRdf_TypeMapper::set('sp:Ask', 'EasySpinRdf_Query_Ask'); EasyRdf_TypeMapper::set('sp:Select', 'EasySpinRdf_Query_Select'); EasyRdf_TypeMapper::set('sp:Describe', 'EasySpinRdf_Query_Describe'); EasyRdf_TypeMapper::set('sp:Construct', 'EasySpinRdf_Query_Construct'); // Elements EasyRdf_TypeMapper::set('sp:TriplePattern', 'EasySpinRdf_Element_TriplePattern'); EasyRdf_TypeMapper::set('sp:SubQuery', 'EasySpinRdf_Element_SubQuery'); EasyRdf_TypeMapper::set('sp:NamedGraph', 'EasySpinRdf_Element_NamedGraph'); EasyRdf_TypeMapper::set('sp:Optional', 'EasySpinRdf_Element_Optional'); EasyRdf_TypeMapper::set('sp:Union', 'EasySpinRdf_Element_Union'); EasyRdf_TypeMapper::set('sp:Bind', 'EasySpinRdf_Element_Bind'); EasyRdf_TypeMapper::set('sp:Filter', 'EasySpinRdf_Element_Filter'); EasyRdf_TypeMapper::set('sp:TriplePath', 'EasySpinRdf_Element_TriplePath'); }
public function indexAction() { $product = new Product(); for ($i = 0; $i < 100; $i++) { $product->setName('Foo Bar : ' . rand(0, 100)); $product->setPrice(rand(0, 1000)); $dm = $this->get('doctrine_mongodb')->getManager(); $dm->persist($product); $dm->flush(); } $foaf = \EasyRdf_Graph::newAndLoad('http://njh.me/foaf.rdf'); $me = $foaf->primaryTopic(); \EasyRdf_Namespace::set('category', 'http://dbpedia.org/resource/Category:'); \EasyRdf_Namespace::set('dbpedia', 'http://dbpedia.org/resource/'); \EasyRdf_Namespace::set('dbo', 'http://dbpedia.org/ontology/'); \EasyRdf_Namespace::set('dbp', 'http://dbpedia.org/property/'); $sparql = new \EasyRdf_Sparql_Client('http://dbpedia.org/sparql'); $result = $sparql->query('SELECT * WHERE {' . ' ?country rdf:type dbo:Country .' . ' ?country rdfs:label ?label .' . ' ?country dc:subject category:Member_states_of_the_United_Nations .' . ' FILTER ( lang(?label) = "en" )' . '} ORDER BY ?label'); $repository = $this->get('doctrine_mongodb')->getManager()->getRepository('MyAppBlogBundle:Product'); return $this->render('MyAppBlogBundle:Default:index.html.twig', array('name' => $result, 'count' => $result->numRows(), 'products' => $repository->findAll())); }
/** Get all the resources in the graph of a certain type * * If no resources of the type are available and empty * array is returned. * * @param string $type The type of the resource (e.g. foaf:Person) * @return array The array of resources */ public function allOfType($type) { $uri = EasyRdf_Namespace::expand($type); $resource = $this->resource($uri); return $resource->all('-rdf:type'); }
/** * Delete an existing RDF type mapping. * * @param string $type The RDF type (e.g. foaf:Person) */ public static function delete($type) { if (!is_string($type) or $type == null or $type == '') { throw new InvalidArgumentException("\$type should be a string and cannot be null or empty"); } $type = EasyRdf_Namespace::expand($type); if (isset(self::$_map[$type])) { unset(self::$_map[$type]); } }
* * This example uses ARC2's RDFa parser to extract the Google * rich snippets review vocabulary from an HTML page. * * * @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"; ## Load the ARC2 parser require_once "EasyRdf/Parser/Arc.php"; ## Add the Google Vocab namespace EasyRdf_Namespace::set('gv', 'http://rdf.data-vocabulary.org/#'); ?> <html> <head><title>Review Extract</title></head> <body> <h1>Review Extract</h1> <?php echo form_tag(); ?> <p>Please enter the URI of a page with a review on it (marked up with Google Review RDFa):</p> <?php echo text_field_tag('uri', 'http://www.bbc.co.uk/music/reviews/2n8c.html', array('size' => 50)); ?> <br /> <?php echo submit_tag();
/** * Output data in RDF and Turtle format * * @param array $data The items to output * @param string $format The output format * @param string $predicate The predicate for the list * @param string $namespaces An associative array with the namespace, e.g. [ 'foaf' => 'http://xmlns.com/foaf/0.1/' ]. * Note that EasyRDF already adds the standard prefixes, such as dc, foaf, etc. * @param integer $status HTTP status code * * @uses \EasyRdf_Graph * * @throws \SameAsLite\Exception\ContentTypeException An exception may be thrown if the requested MIME type * is not supported */ protected function outputRDF(array $data = array(), $format = 'list', $predicate = 'owl:sameAs', array $namespaces = array(), $status = null) { // how to: escape // array_walk($list, '\SameAsLite\Helper::escapeInputArray'); if (!is_null($status)) { $this->app->response->setStatus($status); } //end if // get the query parameters $symbol = $this->app->request()->params('string'); if (!$symbol) { $symbol = $this->app->request()->params('symbol'); } //end if $symbol = $symbol ? urldecode($symbol) : false; $store = $this->store ? $this->store : false; $storeurl = $this->app->request()->getURL() . $this->app->request()->getRootUri() . '/datasets/' . urlencode($store); // EASY RDF $graph = new \EasyRdf_Graph(); //----------- // namespaces // ---------- if (!empty($namespaces)) { foreach ($namespaces as $prefix => $uri) { \EasyRdf_Namespace::set($prefix, $uri); } } //------------- // result block // ------------ if ($symbol && strpos($symbol, 'http') === 0) { $graph_uri = $meta_uri = $graph->resource($symbol); } else { $graph_uri = $graph->newBNode(); } $result_block = $graph->resource($graph_uri); //------------- // meta block // ------------ $meta_uri = $this->app->request()->getURL() . $_SERVER['REQUEST_URI']; $meta_block = $graph->resource($meta_uri); // if this part is added, EasyRDF will merge the result block with the meta block // $meta_block->add('foaf:primaryTopic', $graph->resource( '_:' . $result_block->getBNodeId() )); $meta_block->set('dc:creator', 'sameAsLite'); // TODO: maybe also add info about store (storename, URI)? if ($store) { $meta_block->set('dc:source', $graph->resource($storeurl)); } // $meta_block->set('dc:title', 'Co-references from sameAs.org for ' . $symbol); if (isset($this->appOptions['license']['url'])) { $meta_block->add('dct:license', $graph->resource($this->appOptions['license']['url'])); } // list if ($format === 'list') { // simple list foreach ($data as $str) { if (strpos($str, 'http') === 0) { // resource $result_block->add($predicate, $graph->resource(urldecode($str))); } else { // literal values - not technically correct, because sameAs expects a resource // but validates in W3C Validator $result_block->add($predicate, $str); } } } elseif ($format === 'table') { // table output // data is in the form of: // [ [header1, header2, ...], [row1_1, row1_2, ...], [row2_1, row2_2, ...] ] $preds = array_shift($data); foreach ($data as $arr) { // if (isset($val['url'])) { // $url = $val['url']; // unset($val['url']); // } else { // $url = $graph_uri; // } $resources = array(); for ($i = 0, $s = count($arr); $i < $s; $i++) { $resources[$i] = $graph->resource($storeurl); // TODO for ($k = 0, $t = count($preds); $k < $t; $k++) { if (strpos($arr[$i], 'http') === 0) { // resource $graph->addResource($resources[$i], $preds[$k], $graph->resource(urldecode($arr[$i]))); } else { // literal $graph->addLiteral($resources[$i], $preds[$k], urldecode($arr[$i])); } } } } } else { // keyed = 'arbitrary' output format (e.g. for analysis) // Accepts data in the form of: // [ [ $key1 => $value1 ], [ $key2 => $value2 ], [...] ] // Will take key as predicate and // value as resource (if url) or literal $resource = $graph->resource($storeurl); foreach ($data as $key => $value) { if (strpos($value, 'http') === 0) { // resource $graph->addResource($resource, $key, $graph->resource(urldecode($value))); } else { // literal $graph->addLiteral($resource, $key, $value); } } } // ------ // output // ------ if ($this->mimeBest === 'application/rdf+xml') { $outFormat = 'rdf'; } else { $outFormat = 'turtle'; } $data = $graph->serialise($outFormat); if (!is_scalar($data)) { $data = var_export($data, true); } $this->app->response->setBody($data); $this->app->stop(); }
/** Add one or more rdf:type properties to a resource * * @param string $resource The resource to add the type to * @param string $type The new type (e.g. foaf:Person) */ public function addType($resource, $types) { $this->checkResourceParam($resource, true); if (!is_array($types)) { $types = array($types); } foreach ($types as $type) { $type = EasyRdf_Namespace::expand($type); $this->add($resource, 'rdf:type', array('type' => 'uri', 'value' => $type)); } }
/** * Namespace which is too short shouldn't apply */ public function testShortNamespace() { EasyRdf_Namespace::set('ex', 'http://example.org/'); $this->assertSame('ex:foo', EasyRdf_Namespace::shorten('http://example.org/foo')); $this->assertNull(EasyRdf_Namespace::shorten('http://example.org/bar/baz')); }
/** * Internal function to serialise an EasyRdf_Graph into a DOT formatted string * * @ignore */ protected function serialiseDot($graph) { $result = "digraph {\n"; // Write the graph attributes foreach ($this->attributes as $k => $v) { $result .= ' ' . $this->escape($k) . '=' . $this->escape($v) . ";\n"; } // Go through each of the properties and write the edges $nodes = array(); $result .= "\n // Edges\n"; foreach ($graph->resources() as $resource) { $name1 = $this->nodeName($resource); foreach ($resource->propertyUris() as $property) { $label = null; if ($this->useLabels) { $label = $graph->resource($property)->label(); } if ($label === null) { if ($this->onlyLabelled == true) { continue; } else { $label = EasyRdf_Namespace::shorten($property); } } foreach ($resource->all("<{$property}>") as $value) { $name2 = $this->nodeName($value); $nodes[$name1] = $resource; $nodes[$name2] = $value; $result .= $this->serialiseRow($name1, $name2, array('label' => $label)); } } } ksort($nodes); $result .= "\n // Nodes\n"; foreach ($nodes as $name => $node) { $type = substr($name, 0, 1); $label = ''; if ($type == 'R') { if ($this->useLabels) { $label = $node->label(); } if (!$label) { $label = $node->shorten(); } if (!$label) { $label = $node->getURI(); } $result .= $this->serialiseRow($name, null, array('URL' => $node->getURI(), 'label' => $label, 'shape' => 'ellipse', 'color' => 'blue')); } elseif ($type == 'B') { if ($this->useLabels) { $label = $node->label(); } $result .= $this->serialiseRow($name, null, array('label' => $label, 'shape' => 'circle', 'color' => 'green')); } else { $result .= $this->serialiseRow($name, null, array('label' => strval($node), 'shape' => 'record')); } } $result .= "}\n"; return $result; }
<?php set_include_path(get_include_path() . PATH_SEPARATOR . '../lib/'); require_once "EasyRdf.php"; ## Add namespaces EasyRdf_Namespace::set('vitro', 'http://vitro.mannlib.cornell.edu/ns/vitro/public#'); EasyRdf_Namespace::set('vivo', 'http://vivoweb.org/ontology/core#'); $uri = 'http://54.235.146.115:8080/vivo/individual/n5642'; $graph = EasyRdf_Graph::newAndLoad($uri); $person = $graph->resource($uri); ?> <html> <head><title>Vivo Reader</title></head> <body> <h1>Vivo Reader</h1> <p> <b>First Name</b>: <?php echo $person->get('foaf:firstName'); ?> <br /> <b>Last Name</b>: <?php echo $person->get('foaf:lastName'); ?> <br /> <b>Title</b>: <?php echo $person->get('vivo:preferredTitle'); ?> <br /> </p>