예제 #1
0
 /**
  * This method takes a json encoded rdf-model and a reference to aa (usually empty) MemModel, parses the json
  * string and adds the statements to the given MemModel.
  *
  * @param string $jsonString The string that contains the rdf model, encoded as a json-string.
  * @param MemModel $model A reference to the model, where to add the statements, usually an empty MemModel.
  */
 public function generateModelFromString($jsonString, $model)
 {
     $jsonModel = array();
     $jsonModel = json_decode($jsonString, true);
     // throws an excpetion if json model was corrupt
     if (!is_array($jsonModel)) {
         throw new Exception('error in json string');
     }
     foreach ($jsonModel as $subject => $remain) {
         foreach ($remain as $predicate => $object) {
             $s = strpos($subject, '_') === 0 ? new BlankNode(substr($subject, 2)) : new Resource($subject);
             $p = new Resource($predicate);
             foreach ($object as $obj) {
                 if ($obj['type'] === 'uri') {
                     $o = new Resource($obj['value']);
                 } else {
                     if ($obj['type'] === 'bnode') {
                         $o = new BlankNode(substr($obj['value'], 2));
                     } else {
                         $dtype = isset($obj['datatype']) ? $obj['datatype'] : '';
                         $lang = isset($obj['lang']) ? $obj['lang'] : '';
                         $oVal = $obj['value'];
                         $o = new Literal($oVal, $lang);
                         $o->setDatatype($dtype);
                     }
                 }
                 $model->add(new Statement($s, $p, $o));
             }
         }
     }
 }
예제 #2
0
 function testGenerateModelFromString()
 {
     $parser = new JsonParser();
     $model = new MemModel('http://example.com/');
     try {
         $parser->generateModelFromString($this->modelString, $model);
     } catch (Exception $e) {
         $this->fail($e->getMessage());
     }
     #echo "<pre>";
     #print_r($model);
     global $short_datatype;
     $model2 = new MemModel('http://example.com/');
     // Ceate new statements and add them to the model
     $statement1 = new Statement(new Resource('http://example.org/about'), new Resource('http://purl.org/dc/elements/1.1/creator'), new Literal('Anna Wilder'));
     $statement2 = new Statement(new Resource('http://example.org/about'), new Resource("http://purl.org/dc/elements/1.1/title"), new Literal('Annas Homepage', 'en'));
     $statement3 = new Statement(new Resource('http://example.org/about'), new Resource('http://xmlns.com/foaf/0.1/maker'), new BlankNode('person'));
     $statement4 = new Statement(new BlankNode('person'), new Resource("http://xmlns.com/foaf/0.1/homepage"), new Resource('http://example.org/about'));
     $statement5 = new Statement(new Resource('http://example.org/about'), new Resource("http://purl.org/dc/elements/1.1/title2"), new Literal('Anns HP', 'en', $short_datatype['STRING']));
     $statement6 = new Statement(new Resource('http://example.org/about'), new Resource("http://purl.org/dc/elements/1.1/title2"), new Literal('Anns HP', 'en', $short_datatype['INTEGER']));
     $statement7 = new Statement(new BlankNode('person'), new Resource("http://example.com/testProp1"), new Literal("\"double quote\nnewline\ttab\rcarriage return\\reverse solidus"));
     $model2->add($statement1);
     $model2->add($statement2);
     $model2->add($statement3);
     $model2->add($statement4);
     $model2->add($statement5);
     $model2->add($statement7);
     $this->assertTrue($model->containsAll($model2));
     $model2->remove($statement5);
     $model2->add($statement6);
     $this->assertFalse($model->containsAll($model2));
     #echo "<pre>";
     #print_r($model2);
     #echo "</pre>";
 }
예제 #3
0
 function _generateModel($num, $ind)
 {
     $model = new MemModel();
     $model->index($ind);
     for ($i = 0; $i < $num; $i++) {
         $subs[$i] = new Resource('http://www.example.org/sub' . $i % 3);
         $preds[$i] = new Resource('http://www.example.org/pred' . $i % 5);
         $objs[$i] = new Resource('http://www.example.org/obj' . $i % 9);
         $stat = new Statement($subs[$i], $preds[$i], $objs[$i]);
         $model->add($stat);
     }
     return $model;
 }
 /**
  * tests listSubjectsWithProperty()
  */
 function testlistSubjectsWithPropertyTest()
 {
     $_SESSION['test'] = 'ResModel listSubjectsWithProperty test';
     $model1 = new MemModel();
     $needle = new Statement(new Resource('http://www.example.org/needle'), new Resource('http://www.example.org/pred'), new Resource('http://www.example.org/ob'));
     $model1->add($needle);
     $resmodel = new ResModel($model1);
     $resresource = $resmodel->createResource('http://www.example.org/testresource');
     $prop = $resmodel->createProperty('http://www.example.org/pred');
     $resresource->addProperty($prop, new ResLiteral('Object'));
     $property = new ResResource('http://www.example.org/pred');
     $res = $resmodel->listSubjectsWithProperty($property);
     $this->assertEqual(1, count($res));
     $model1->close();
 }
예제 #5
0
 /**
  * Create a MemModel containing only the base triples (without inferred 
  * statements) of the current InfModelB.
  *
  * @return object MemModel
  * @access public
  */
 function &getBaseMemModel()
 {
     $return = new MemModel();
     $return->setBaseURI($this->baseURI);
     foreach ($this->triples as $statement) {
         $return->add($statement);
     }
     $retun->addParsedNamespaces($this->getParsedNamespaces());
     return $return;
 }
예제 #6
0
 /**
  * Create a MemModel containing only the base triples 
  * (without inferred statements) of the current InfModelF.
  *
  * @return object MemModel
  * @access public
  */
 function getBaseMemModel()
 {
     $return = new MemModel();
     $return->setBaseURI($this->baseURI);
     foreach ($this->triples as $key => $statement) {
         if (!in_array($key, $this->infPos)) {
             $return->add($statement);
         }
     }
     $retun->addParsedNamespaces($this->getParsedNamespaces());
     return $return;
 }
예제 #7
0
 function testNestBlankAtEnd()
 {
     $mod = new MemModel();
     $b3 = new BlankNode($mod);
     $mod->add(new Statement(new Resource('http://example.org/foo'), new Resource("http://example.org/bar2"), $b3));
     $ser = new N3Serializer();
     $ser->setCompress(true);
     $ser->setNest(true);
     $str = $ser->serialize($mod);
     //test if it can be loaded
     $par = new N3Parser();
     $mod2 = $par->parse2model($str, false);
     //var_dump($str, $mod2->triples);
     $this->compareModelsIgnoringBlankNodes($mod, $mod2);
 }
예제 #8
0
 /**
  *
  */
 function &rewriteURIsInResDescrModel(&$rd_m)
 {
     global $_PUBBY_DATASET;
     global $namespaces;
     $rew_rd_m = new MemModel();
     // uri rewriting + regex filtering
     if ($_PUBBY_DATASET['datasetURIPattern'] != '') {
         $l = strlen($_PUBBY_DATASET['datasetBase']);
         $iter = $rd_m->getStatementIterator();
         while ($iter->hasNext()) {
             $triple = $iter->next();
             $subj = $triple->getSubject();
             // if subjURI is a datasetURI & does not match the pattern
             if (stripos($subj->getURI(), $_PUBBY_DATASET['datasetBase']) === 0 && !preg_match($_PUBBY_DATASET['datasetURIPattern'], substr($subj->getURI(), $l))) {
                 continue;
             } else {
                 // if predURI is a datasetURI & does not match the pattern
                 $pred = $triple->getPredicate();
                 if (stripos($pred->getURI(), $_PUBBY_DATASET['datasetBase']) === 0 && !preg_match($_PUBBY_DATASET['datasetURIPattern'], substr($pred->getURI(), $l))) {
                     continue;
                 } else {
                     // if obj is a Literal & objeURI is a datasetURI & does not match the pattern
                     $obj = $triple->getObject();
                     if (!is_a($obj, "Literal")) {
                         if (stripos($obj->getURI(), $_PUBBY_DATASET['datasetBase']) === 0 && !preg_match($_PUBBY_DATASET['datasetURIPattern'], substr($obj->getURI(), $l))) {
                             continue;
                         } else {
                             $obj = new Resource(RAPpubbyURIrewriter::datasetURItoPubbyURI($obj->getURI()));
                         }
                     }
                     $subj = new Resource(RAPpubbyURIrewriter::datasetURItoPubbyURI($subj->getURI()));
                     $pred = new Resource(RAPpubbyURIrewriter::datasetURItoPubbyURI($pred->getURI()));
                     $rew_rd_m->add(new Statement($subj, $pred, $obj));
                 }
             }
         }
     } else {
         $iter = $rd_m->getStatementIterator();
         while ($iter->hasNext()) {
             $triple = $iter->next();
             $subj = new Resource(RAPpubbyURIrewriter::datasetURItoPubbyURI($triple->getSubject()->getURI()));
             $pred = new Resource(RAPpubbyURIrewriter::datasetURItoPubbyURI($triple->getPredicate()->getURI()));
             $obj = $triple->getObject();
             if (!is_a($obj, "Literal")) {
                 $obj = new Resource(RAPpubbyURIrewriter::datasetURItoPubbyURI($obj->getURI()));
             }
             $rew_rd_m->add(new Statement($subj, $pred, $obj));
         }
     }
     return $rew_rd_m;
 }
예제 #9
0
 /**
  * finds a statement in an index. $pos is the Position in the index
  * and $ind the adequate searchindex
  *
  * @param    String            $pos
  * @param    Object Subject    &$subject
  * @param    Object Predicate  &$predicate
  * @param    Object Object	 &$object
  * @param    int				 &ind
  * @return   MemModel          $res
  * @access   private
  */
 function _findInIndex($pos, &$subject, &$predicate, &$object, $ind)
 {
     $res = new MemModel($this->getBaseURI());
     $res->indexed = -1;
     if (!isset($this->indexArr[$ind][$pos])) {
         return $res;
     }
     foreach ($this->indexArr[$ind][$pos] as $key => $value) {
         $t = $this->triples[$value];
         if ($this->matchStatement($t, $subject, $predicate, $object)) {
             $res->add($t);
         }
     }
     return $res;
 }
 function _generateModelLiteral($stats, $ind)
 {
     $model = new MemModel();
     $model->index($ind);
     for ($i = 0; $i < $stats; $i++) {
         $subs[$i] = new Resource('http://www.example.org/sub' . $i % 3);
         $preds[$i] = new Resource('http://www.example.org/pred' . $i % 5);
         $objs[$i] = new Literal('http://www.example.org/obj' . $i % 9);
         $objs[$i]->setDatatype('test');
     }
     for ($i = 0; $i < $stats; $i++) {
         $model->add(new Statement($subs[$i], $preds[$i], $objs[$i]));
     }
     return $model;
 }
예제 #11
0
 private function addBookToModel(SimpleXMLElement $item, MemModel $model)
 {
     $itemresource = new Resource($this->uri);
     // rdf:type
     $model->add(new Statement($itemresource, new Resource(RDF_NAMESPACE_URI . RDF_TYPE), new Resource("http://sites.wiwiss.fu-berlin.de/suhl/bizer/bookmashup/simpleCommerceVocab01.rdf#Book")));
     // homepage (link to details page @ amazon)
     //$model->add(new Statement($itemresource ,new Resource("http://xmlns.com/foaf/0.1/homepage"),new Resource($item->DetailPageURL)));
     // label
     $model->add(new Statement($itemresource, new Resource("http://www.w3.org/2000/01/rdf-schema#label"), new Literal((string) $item->ItemAttributes->Title)));
     // date
     $model->add(new Statement($itemresource, new Resource("http://purl.org/dc/elements/1.1/date"), new Literal((string) $item->ItemAttributes->PublicationDate)));
     // title
     $model->add(new Statement($itemresource, new Resource("http://purl.org/dc/elements/1.1/title"), new Literal((string) $item->ItemAttributes->Title)));
     //large image
     $model->add(new Statement($itemresource, new Resource("http://xmlns.com/foaf/0.1/depiction"), new Resource((string) $item->LargeImage->URL)));
     // thumbnail
     $model->add(new Statement($itemresource, new Resource("http://xmlns.com/foaf/0.1/thumbnail"), new Resource((string) $item->SmallImage->URL)));
     // isbn
     $model->add(new Statement($itemresource, new Resource("http://purl.org/dc/elements/1.1/identifier"), new Resource("urn:ISBN:" . $item->ItemAttributes->ISBN)));
     // publisher
     $model->add(new Statement($itemresource, new Resource("http://purl.org/dc/elements/1.1/publisher"), new Literal((string) $item->ItemAttributes->Label)));
     // format
     if (isset($item->ItemAttributes->format)) {
         $model->add(new Statement($itemresource, new Resource("http://purl.org/dc/elements/1.1/format"), new Literal((string) $item->ItemAttributes->format)));
     }
     if (isset($item->ItemAttributes->Binding)) {
         $model->add(new Statement($itemresource, new Resource("http://purl.org/dc/elements/1.1/format"), new Literal((string) $item->ItemAttributes->Binding)));
     }
     // reviews
     $i = 1;
     foreach ($item->EditorialReviews->EditorialReview as $index => $review) {
         $newuri = str_replace("/books/", "/reviews/", $this->uri);
         $pos = strrpos($newuri, "/");
         $review = new Resource($newuri . "_" . $index . $i);
         $model->add(new Statement($itemresource, new Resource("http://dannyayers.com/xmlns/rev/#hasReview"), $review));
         $model->add(new Statement($review, new Resource("http://www.w3.org/2000/01/rdf-schema#label"), new Literal("Review number " . $i . " about: " . $item->ItemAttributes->Title)));
         $i++;
     }
     // author
     $newuri = str_replace("/books/", "/persons/", $this->uri);
     $pos = strrpos($newuri, "/");
     if (isset($item->ItemAttributes->Author)) {
         foreach ($item->ItemAttributes->Author as $k => $author) {
             $authorUri = new Resource(substr($newuri, 0, $pos + 1) . urlencode($author));
             $model->add(new Statement($itemresource, new Resource("http://purl.org/dc/elements/1.1/creator"), $authorUri));
             $model->add(new Statement($authorUri, new Resource("http://www.w3.org/2000/01/rdf-schema#label"), new Literal((string) $author)));
         }
     }
     // subject(s)
     $newuri = str_replace("/books/", "/subject/", $this->uri);
     $skosSubject = new Resource("http://www.w3.org/2004/02/skos/core#subject");
     $pos = strrpos($newuri, "/");
     if (isset($item->Subjects)) {
         foreach ($item->Subjects as $k => $subjects) {
             foreach ($subjects as $kk => $subject) {
                 $subjectUri = new Resource(substr($newuri, 0, $pos + 1) . urlencode($subject));
                 $model->add(new Statement($itemresource, $skosSubject, $subjectUri));
                 $model->add(new Statement($subjectUri, new Resource("http://www.w3.org/2000/01/rdf-schema#label"), new Literal((string) $subject)));
             }
         }
     }
     if (isset($item->ItemAttributes->Creator)) {
         foreach ($item->ItemAttributes->Creator as $key => $creator) {
             $creatorUri = new Resource(substr($newuri, 0, $pos + 1) . urlencode($creator));
             $model->add(new Statement($itemresource, new Resource("http://purl.org/dc/elements/1.1/creator"), $creatorUri));
             $model->add(new Statement($creatorUri, new Resource("http://www.w3.org/2000/01/rdf-schema#label"), new Literal((string) $creator)));
         }
     }
     // amazon offer
     $newuri = str_replace("/books/", "/offers/", $this->uri);
     $pos = strrpos($newuri, "/");
     $offer = new Resource($newuri . "amazonOffer");
     $model->add(new Statement($itemresource, new Resource("http://sites.wiwiss.fu-berlin.de/suhl/bizer/bookmashup/simpleCommerceVocab01.rdf#hasOffer"), $offer));
     $model->add(new Statement($offer, new Resource("http://www.w3.org/2000/01/rdf-schema#label"), new Literal("Offer for the book with the ISBN: " . $item->ItemAttributes->ISBN)));
     // create OFFER from google
     $this->addGoogleOffersToModel($model, $this->uri);
     //
     $model->add(new Statement(new Resource($this->document), new Resource("http://www.w3.org/2000/01/rdf-schema#label"), new Literal("RDF document about the book: " . $item->ItemAttributes->Title)));
 }
예제 #12
0
// Include RAP
define("RDFAPI_INCLUDE_DIR", "./../api/");
include RDFAPI_INCLUDE_DIR . "RdfAPI.php";
// Filename of an RDF document
$base = "example1.rdf";
// Create a new MemModel
$model = new MemModel();
// Load and parse document
$model->load($base);
// Output model as HTML table
$model->writeAsHtmlTable();
echo "<P>";
// Ceate new statements and add them to the model
$statement1 = new Statement(new Resource("http://www.w3.org/Home/Lassila"), new Resource("http://description.org/schema/Description"), new Literal("Lassila's personal Homepage", "en"));
$statement2 = new Statement(new Resource("http://www.w3.org/Home/Lassila"), new Resource("http://description.org/schema/Description"), new Literal("Lassilas persönliche Homepage ", "de"));
$model->add($statement1);
$model->add($statement2);
$model->writeAsHtmlTable();
echo "<P>";
// Search model 1
$homepage = new Resource("http://www.w3.org/Home/Lassila");
$res = $model->find($homepage, NULL, NULL);
$res->writeAsHtmlTable();
echo "<P>";
// Search model 2
$description = new Resource("http://description.org/schema/Description");
$statement = $model->findFirstMatchingStatement($homepage, $description, NULL);
// Check if something was found and output result
if ($statement) {
    echo $statement->toString();
} else {
예제 #13
0
 /**
  * Search the attributes listed in $list in the dataset.
  * Modifies $resultGraph
  *
  * @param Array      $list List containing the attributes
  * @param MemModel   $resultGraph The result graph which describes the Resource
  * @return void
  */
 protected function _getAttributes($list, $resultGraph, $varvalue)
 {
     if ($list) {
         foreach ($list as $attribute) {
             if (!$varvalue instanceof Literal) {
                 $iter2 = $this->dataset->findInNamedGraphs(null, $varvalue, new Resource($attribute), null, true);
                 while ($iter2->valid()) {
                     $resultGraph->add($iter2->current());
                     $iter2->next();
                 }
                 $iter3 = $this->dataset->findInDefaultGraph($varvalue, new Resource($attribute), null);
                 while ($iter3->valid()) {
                     $resultGraph->add($iter3->current());
                     $iter3->next();
                 }
             }
         }
     }
 }
예제 #14
0
 /**
  * Perform an RDQL query on this Model. Should work with all types of models.
  * This method returns a MemModel containing the result statements.
  * If $closure is set to TRUE, the result will additionally contain
  * statements found by the findForward-method for blank nodes.
  * !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  * WARNING: If called with $closure = TRUE this method
  *          can be slow with large models.
  * !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  *
  * @author   Anton K�tlbacher <*****@*****.**>
  * @author   code snippets taken from the RAP Netapi by Phil Dawes and Chris Bizer
  * @access   public
  * @param    string $queryString
  * @param    boolean $closure
  * @return   object MemModel
  *
  */
 function &getMemModelByRDQL($queryString, $closure = FALSE)
 {
     require_once RDFAPI_INCLUDE_DIR . PACKAGE_RDQL;
     $parser = new RdqlParser();
     $parsedQuery =& $parser->parseQuery($queryString);
     // If there are variables used in the pattern but not
     // in the select clause, add them to the select clause
     foreach ($parsedQuery['patterns'] as $n => $pattern) {
         foreach ($pattern as $key => $val_1) {
             if ($val_1['value'][0] == '?') {
                 if (!in_array($val_1['value'], $parsedQuery['selectVars'])) {
                     array_push($parsedQuery['selectVars'], $val_1['value']);
                 }
             }
         }
     }
     if (is_a($this, "DbModel")) {
         $engine = new RdqlDbEngine();
         $model = $this;
     } elseif (is_a($this, "MemModel")) {
         $engine = new RdqlMemEngine();
         $model = $this;
     } elseif (is_a($this, "ResModel")) {
         $engine = new RdqlMemEngine();
         $model = $this->model;
     }
     $res = $engine->queryModel($model, $parsedQuery, TRUE);
     $rdqlIter = new RdqlResultIterator($res);
     $newModel = new MemModel();
     // Build statements from RdqlResultIterator
     while ($rdqlIter->hasNext()) {
         $result = $rdqlIter->next();
         foreach ($parsedQuery['patterns'] as $n => $pattern) {
             if (substr($pattern['subject']['value'], 0, 1) == '?') {
                 $subj = $result[$pattern['subject']['value']];
             } else {
                 $subj = new Resource($pattern['subject']['value']);
             }
             if (substr($pattern['predicate']['value'], 0, 1) == '?') {
                 $pred = $result[$pattern['predicate']['value']];
             } else {
                 $pred = new Resource($pattern['predicate']['value']);
             }
             if (substr($pattern['object']['value'], 0, 1) == '?') {
                 $obj = $result[$pattern['object']['value']];
             } else {
                 if (isset($pattern['object']['is_literal'])) {
                     $obj = new Literal($pattern['object']['value']);
                     $obj->setDatatype($pattern['object']['l_dtype']);
                     $obj->setLanguage($pattern['object']['l_lang']);
                 } else {
                     $obj = new Resource($pattern['object']['value']);
                 }
             }
             $statement = new Statement($subj, $pred, $obj);
             $newModel->add($statement);
             // findForward() Statements containing an eventually given blank node
             // and add them to the result, if closure = true
             if (is_a($statement->object(), 'BlankNode') && $closure == True) {
                 $newModel = $model->findForward($statement->object(), NULL, NULL, $newModel);
             }
             if (is_a($statement->subject(), 'BlankNode') && $closure == True) {
                 $newModel = $model->findForward($statement->subject(), NULL, NULL, $newModel);
             }
         }
     }
     return $newModel;
 }
예제 #15
0
<?php 
define("RDFAPI_INCLUDE_DIR", "./../api/");
include RDFAPI_INCLUDE_DIR . "RdfAPI.php";
echo "<h3>1. Generate and show two MemModels</h3>";
// Create empty MemModel
$model = new MemModel();
$model->setbaseURI("http://www.bizer.de");
$model2 = new MemModel();
$model2->setbaseURI("http://www.bizer.de/zwei");
// Create nodes and add statements to models
$myhomepage = new Resource("http://www.bizer.de/welcome.html");
$creator = new Resource("http://purl.org/dc/elements/1.1/creator");
$me = new Resource("mailto:chris@bizer.de");
$model->add(new Statement($myhomepage, $creator, $me));
$model2->add(new Statement($myhomepage, $creator, $me));
$creation_date = new Resource("http://www.example.org/terms/creation-date");
$August16 = new Literal("August 16, 2002");
$model->add(new Statement($myhomepage, $creation_date, $August16));
$model2->add(new Statement($myhomepage, $creation_date, $August16));
$language = new Resource("http://www.example.org/terms/language");
$deutsch = new Literal("Deutsch", "de");
$model->add(new Statement($myhomepage, $language, $deutsch));
$name = new Resource("http://www.example.org/terms/Name");
$chrisbizer = new Literal("Chris Bizer");
$model2->add(new Statement($me, $name, $chrisbizer));
// Output as Table
echo "<h5>Model 1</h5>";
$model->writeAsHtmlTable();
echo "<h5>Model 2</h5>";
$model2->writeAsHtmlTable();
예제 #16
0
 function _generateModelLiteral()
 {
     $model = new MemModel();
     $model->setBaseURI('http://www.example.org');
     $sub = new Resource('http://www.example.org/subject1');
     $pred = new Resource('http://www.example.org/predicate1');
     $obj = new Literal('http://www.example.org/object1');
     $obj->setDatatype('test');
     $obj->setLanguage('DE');
     $model->add(new Statement($sub, $pred, $obj));
     return $model;
 }
예제 #17
0
 /**
  * Constructs a result graph.
  *
  * @param  array         $arVartable       A table containing the result vars and their bindings
  * @param  GraphPattern  $constructPattern The CONSTRUCT pattern
  * @return MemModel      The result graph which matches the CONSTRUCT pattern
  */
 protected function constructGraph($arVartable, $constructPattern)
 {
     $resultGraph = new MemModel();
     if (!$arVartable) {
         return $resultGraph;
     }
     $tp = $constructPattern->getTriplePatterns();
     $bnode = 0;
     foreach ($arVartable as $value) {
         foreach ($tp as $triple) {
             $sub = $triple->getSubject();
             $pred = $triple->getPredicate();
             $obj = $triple->getObject();
             if (is_string($sub) && $sub[1] == '_') {
                 $sub = new BlankNode("_bN" . $bnode);
             }
             if (is_string($pred) && $pred[1] == '_') {
                 $pred = new BlankNode("_bN" . $bnode);
             }
             if (is_string($obj) && $obj[1] == '_') {
                 $obj = new BlankNode("_bN" . $bnode);
             }
             if (is_string($sub)) {
                 $sub = $value[$sub];
             }
             if (is_string($pred)) {
                 $pred = $value[$pred];
             }
             if (is_string($obj)) {
                 $obj = $value[$obj];
             }
             if ($sub !== "" && $pred !== "" && $obj !== "") {
                 $resultGraph->add(new Statement($sub, $pred, $obj));
             }
         }
         $bnode++;
     }
     return $resultGraph;
 }
예제 #18
0
 /**
  * generates a test model containing given number of statements
  * and given indextype.
  *
  * @return Object MemModel $model
  * @param  int $num 
  * @param  int $des
  * @param  int $ind
  * @param  Object MemModel $needle
  */
 function _generateModel($num, $des, $ind, $needle)
 {
     $model = new MemModel();
     // generate Subjects
     for ($i = 0; $i < $num; $i++) {
         $subs[$i] = new Resource('http://www.example.org/Subject' . $i % 6);
     }
     // generate Predicates
     for ($i = 0; $i < $num; $i++) {
         $preds[$i] = new Resource('http://www.example.org/Predicate' . $i % 7);
     }
     // generate Objects
     for ($i = 0; $i < $num; $i++) {
         $objs[$i] = new Resource('http://www.example.org/Object' . $i % 5);
     }
     for ($i = 0; $i < $num; $i++) {
         if ($i == 50) {
             $model->add($needle);
         }
         $model->add(new Statement($subs[$i], $preds[$i], $objs[$i]));
     }
     $model->index($ind);
     return $model;
 }
예제 #19
0
 /**
  * Reifies a statement.
  * Returns a new MemModel that is the reification of the statement.
  * For naming the statement's bNode a Model or bNodeID must be passed to the method.   
  *
  * @access	public 
  * @param		mixed	&$model_or_bNodeID
  * @return	object	model
  */
 function &reify(&$model_or_bNodeID)
 {
     if (is_a($model_or_bNodeID, 'MemModel')) {
         // parameter is model
         $statementModel = new MemModel($model_or_bNodeID->getBaseURI());
         $thisStatement = new BlankNode($model_or_bNodeID);
     } else {
         // parameter is bNodeID
         $statementModel = new MemModel();
         $thisStatement =& $model_or_bNodeID;
     }
     $RDFstatement = new Resource(RDF_NAMESPACE_URI . RDF_STATEMENT);
     $RDFtype = new Resource(RDF_NAMESPACE_URI . RDF_TYPE);
     $RDFsubject = new Resource(RDF_NAMESPACE_URI . RDF_SUBJECT);
     $RDFpredicate = new Resource(RDF_NAMESPACE_URI . RDF_PREDICATE);
     $RDFobject = new Resource(RDF_NAMESPACE_URI . RDF_OBJECT);
     $statementModel->add(new Statement($thisStatement, $RDFtype, $RDFstatement));
     $statementModel->add(new Statement($thisStatement, $RDFsubject, $this->getSubject()));
     $statementModel->add(new Statement($thisStatement, $RDFpredicate, $this->getPredicate()));
     $statementModel->add(new Statement($thisStatement, $RDFobject, $this->Object()));
     return $statementModel;
 }
예제 #20
0
function geoLookup($lat, $long, $radius, &$resultsLabel)
{
    global $FLICKRSERVICE;
    $resURI = DBPEDIA_URI_ROOT . wikipediaEncode($_REQUEST['item']);
    $locationURI = FLICKRWRAPPR_LOCATION_URI_ROOT . $_REQUEST['lat'] . '/' . $_REQUEST['long'] . '/' . $_REQUEST['radius'];
    $dataURI = FLICKRWRAPPR_LOCATION_DATA_URI_ROOT . $_REQUEST['lat'] . '/' . $_REQUEST['long'] . '/' . $_REQUEST['radius'];
    /* Initialize result model */
    $resultModel = new MemModel();
    $resultModel->addNamespace('foaf', 'http://xmlns.com/foaf/0.1/');
    $resultModel->addNamespace('dcterms', 'http://purl.org/dc/terms/');
    $resultModel->addNamespace('rdfs', 'http://www.w3.org/2000/01/rdf-schema#');
    //$resultModel->addNamespace('geonames', 'http://www.geonames.org/ontology#');
    $resultModel->addNamespace('geo', 'http://www.w3.org/2003/01/geo/wgs84_pos#');
    $resultModel->addNamespace('georss', 'http://www.georss.org/georss/');
    /* Perform flickr search */
    $flickrPhotos = $FLICKRSERVICE->getFlickrPhotos('', $lat, $long, $radius / 1000);
    /* Process found photos */
    foreach ($flickrPhotos as $flickrPhoto) {
        /* Provide the picture itself (small version) */
        $resultModel->add(new Statement(new Resource($locationURI), new Resource("http://xmlns.com/foaf/0.1/depiction"), new Resource($flickrPhoto['imgsmall'])));
        /* Provide its page on flickr */
        $resultModel->add(new Statement(new Resource($flickrPhoto['imgsmall']), new Resource("http://xmlns.com/foaf/0.1/page"), new Resource($flickrPhoto['flickrpage'])));
    }
    if ($resultModel->size() > 0) {
        /* Add metadata for location */
        $resultModel->add(new Statement(new Resource($locationURI), new Resource("http://www.w3.org/1999/02/22-rdf-syntax-ns#type"), new Resource("http://www.w3.org/2003/01/geo/wgs84_pos#SpatialThing")));
        $latLiteral = new Literal($lat);
        $latLiteral->setDatatype("http://www.w3.org/2001/XMLSchema#float");
        $resultModel->add(new Statement(new Resource($locationURI), new Resource("http://www.w3.org/2003/01/geo/wgs84_pos#lat"), $latLiteral));
        $longLiteral = new Literal($long);
        $longLiteral->setDatatype("http://www.w3.org/2001/XMLSchema#float");
        $resultModel->add(new Statement(new Resource($locationURI), new Resource("http://www.w3.org/2003/01/geo/wgs84_pos#long"), $longLiteral));
        $radiusLiteral = new Literal($radius);
        $radiusLiteral->setDatatype("http://www.w3.org/2001/XMLSchema#double");
        $resultModel->add(new Statement(new Resource($locationURI), new Resource("http://www.georss.org/georss/radius"), $radiusLiteral));
        /* Add metadata for document */
        $resultModel->add(new Statement(new Resource($dataURI), new Resource("http://www.w3.org/1999/02/22-rdf-syntax-ns#type"), new Resource("http://xmlns.com/foaf/0.1/Document")));
        $resultsLabel = "Photos taken within {$radius} meters of geographic location lat={$lat} long={$long}";
        $resultModel->add(new Statement(new Resource($dataURI), new Resource("http://www.w3.org/2000/01/rdf-schema#label"), new Literal($resultsLabel, "en")));
        $resultModel->add(new Statement(new Resource($dataURI), new Resource("http://xmlns.com/foaf/0.1/primaryTopic"), new Resource($locationURI)));
        $resultModel->add(new Statement(new Resource($dataURI), new Resource("http://purl.org/dc/terms/license"), new Resource(FLICKR_TOS_URL)));
        $resultModel->add(new Statement(new Resource($dataURI), new Resource("http://xmlns.com/foaf/0.1/maker"), new Resource(FLICKRWRAPPR_HOMEPAGE)));
        $resultModel->add(new Statement(new Resource(FLICKRWRAPPR_HOMEPAGE), new Resource("http://www.w3.org/2000/01/rdf-schema#label"), new Literal("flickr(tm) wrappr", "en")));
    }
    return $resultModel;
}
예제 #21
0
파일: spo.php 프로젝트: Gigi33/exif2rdf
/**
 * SPO (also known as "Triples" or "find(spo)") is an experimental minimal query language. 
 * An SPO query is a single triple pattern, with optional subject (parameter "s"), predicate (parameter "p"), 
 * and object (parameter "o", if a URIref, parameter "v" for a string literal). 
 * Absence of a parameter implies "any" for matching that slot of the triple pattern.
 *
 * @version  $Id: spo.php 268 2006-05-15 05:28:09Z tgauss $
 * @author Chris Bizer <*****@*****.**>
 * @author Phil Dawes <*****@*****.**>
 *
 * @package netapi
 * @todo Support typed literals.
 * @access	public
 */
function spoQuery($model, $serializer, $remove = false, $modelId = false)
{
    // Get SPO query from HTTP request
    if (isset($_REQUEST['s'])) {
        $subject = new Resource($_REQUEST['s']);
    } else {
        $subject = NULL;
    }
    if (isset($_REQUEST['p'])) {
        $predicate = new Resource($_REQUEST['p']);
    } else {
        $predicate = NULL;
    }
    if (isset($_REQUEST['o'])) {
        $object = new Resource($_REQUEST['o']);
    } else {
        if (isset($_REQUEST['v'])) {
            $object = new Literal($_REQUEST['v']);
        } else {
            $object = NULL;
        }
    }
    if (isset($_REQUEST['closure'])) {
        if (strtoupper($_REQUEST['closure']) == "TRUE") {
            $closure = True;
        } else {
            $closure = False;
        }
    } else {
        $closure = False;
    }
    $outm = new MemModel();
    $resultmodel = $model->find($subject, $predicate, $object);
    $it = $resultmodel->getStatementIterator();
    while ($it->hasNext()) {
        $stmt = $it->next();
        if ($remove) {
            $model->remove($stmt);
        } else {
            $outm->add(new Statement($stmt->subject(), $stmt->predicate(), $stmt->object()));
            if (is_a($stmt->object(), 'BlankNode') && $closure == True) {
                getBNodeClosure($stmt->object(), $model, $outm);
            }
            if (is_a($stmt->subject(), 'BlankNode') && $closure == True) {
                getBNodeClosure($stmt->subject(), $model, $outm);
            }
        }
    }
    if ($remove) {
        if (substr($modelId, 0, 5) == "file:") {
            $model->saveAs(substr($modelId, 5));
        }
        if ($resultmodel->size() > 0) {
            header('200 - OK');
            echo "200 - OK";
        } else {
            echo "No matching statements";
        }
    } else {
        echo $serializer->Serialize($outm);
    }
    $outm->close();
}
예제 #22
0
 /**
  * Convert an ADORecordSet to a memory Model.
  *
  * Every successful database query returns an ADORecordSet object which is actually
  * a cursor that holds the current row in the array fields[].
  * !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  * !!! This method can only be applied to a RecordSet with array fields[]
  * !!! containing a representation of the database table: statements,
  * !!! with an index corresponding to following table columns:
  * !!! [0] - subject, [1] - predicate, [2] - object, [3] - l_language,
  * !!! [4] - l_datatype, [5] - subject_is, [6] - object_is
  * !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  *
  * @param   object  ADORecordSet
  * @return  object  MemModel
  * @access	private
  */
 function _convertRecordSetToMemModel(&$recordSet)
 {
     $res = new MemModel($this->baseURI);
     while (!$recordSet->EOF) {
         // subject
         if ($recordSet->fields[5] == 'r') {
             $sub = new Resource($recordSet->fields[0]);
         } else {
             $sub = new BlankNode($recordSet->fields[0]);
         }
         // predicate
         $pred = new Resource($recordSet->fields[1]);
         // object
         if ($recordSet->fields[6] == 'r') {
             $obj = new Resource($recordSet->fields[2]);
         } elseif ($recordSet->fields[6] == 'b') {
             $obj = new BlankNode($recordSet->fields[2]);
         } else {
             $obj = new Literal($recordSet->fields[2], $recordSet->fields[3]);
             if ($recordSet->fields[4]) {
                 $obj->setDatatype($recordSet->fields[4]);
             }
         }
         $statement = new Statement($sub, $pred, $obj);
         $res->add($statement);
         $recordSet->moveNext();
     }
     $res->addParsedNamespaces($this->getParsedNamespaces());
     return $res;
 }
예제 #23
0
 /**
  * Adds a new triple to the Model without checking if the statement 
  * is already in the Model.
  * So if you want a duplicate free MemModel use the addWithoutDuplicates()
  * function (which is slower then add())
  * If the statement's predicate label is supported by the inference, 
  * the matching rules are added.
  *
  * @param	object Statement	$statement
  * @access	public
  * @throws	PhpError 
  */
 function add($statement)
 {
     parent::add($statement);
     //if the predicate is supported by the inference
     if (in_array($statement->getLabelPredicate(), $this->supportedInference)) {
         $this->_addToInference($statement);
     }
 }
예제 #24
0
 function testA()
 {
     $n3 = '@prefix : <http://example.org/#> .
         :foo a :bar .
         ';
     $parser =& new N3Parser();
     //$parser->debug = true;
     $model =& $parser->parse2model($n3, false);
     $model2 = new MemModel();
     $model2->add(new Statement(new Resource("http://example.org/#foo"), new Resource("http://www.w3.org/1999/02/22-rdf-syntax-ns#type"), new Resource("http://example.org/#bar")));
     //var_dump($model->triples);
     $this->assertEqual(1, $model->size());
     $this->assertTrue($model->containsAll($model2));
 }