/** * 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)); } } } }
private function characters($parser, $data) { //print_r("characters : $data<p/> \n"); if ($this->curElement == "URI" || $this->curElement == "BNODE" || $this->curElement == "LITERAL") { switch ($this->curVar) { case "Res": //print_r("Neue Resource : $data <p/> \n"); $this->curArray["?Res"] = new Resource($data); break; case "Attr": //print_r("Neues Attr : $data <p/> \n"); $this->curArray["?Attr"] = new Resource($data); break; case "Val": if ($this->curElement != "LITERAL") { //print_r("Neue Resource als Val: $data <p/> \n"); $this->curArray["?Val"] = new Resource($data); } else { $this->curLiteralData .= $data; $l = new Literal($this->curLiteralData); $l->setDatatype($this->curDataType); $this->curArray["?Val"] = $l; } break; } } }
/** * tests if contains returns false if the Literal in the given statement has wrong datatype * using all kinds of indices. */ function testContainsLiteralFalse() { $_SESSION['test'] = 'MemModel contains literal false test'; for ($i = -1; $i < 4; $i++) { $mod = $this->_generateModelLiteral(3, $i); $lit = new Literal('http://www.example.org/obj2'); $lit->setDatatype('notTest'); $stat = new Statement(new Resource('http://www.example.org/sub2'), new Resource('http://www.example.org/pred2'), $lit); $this->assertFalse($mod->contains($stat)); } }
public function accept($extractionResult) { $model1 = ModelFactory::getDefaultModel("http://dbpedia.org/"); // RAP model $count = 0; foreach (new ArrayObject($extractionResult->getTriples()) as $triple) { $count++; $tripleString = explode(">", $triple->toString()); $s = str_replace("<", "", $tripleString[0]); $p = str_replace("<", "", $tripleString[1]); // $s = preg_replace("/<|>/","",$triple->getSubject()); // $p = preg_replace("/<|>/","",$triple->getPredicate()); $o = $tripleString[2]; $subject = new Resource($s); $predicate = new Resource($p); if (strpos($o, "<")) { // echo "<br>" . $s. $p . $p; if (!strpos($o, "^^")) { // echo " a"; $o = str_replace("<", "", $o); $object = new Resource($o); } else { // echo " b"; $pos = strpos($o, "^^"); $literal = substr($o, 0, $pos); $object = new Literal($literal); $object->setDatatype(substr($o, $pos + 3, strlen($o) - $pos - 3)); } } else { // $lang = "en"; if (preg_match("/(.*)(@)([a-zA-Z]+) \\.\$/", $o, $match)) { $o = $match[1]; $lang = $match[3]; $object = new Literal($o, $lang); } else { $object = new Literal($o); } } $statement = new Statement($subject, $predicate, $object); $model1->add($statement); } if ($count > 0) { echo "<br><br><h3>" . $extractionResult->getExtractorID() . "</h3>"; echo $model1->writeAsHtmlTable(); } }
/** * tests if equals() works according to the RDF specifications * */ function testEquals() { $_SESSION['test'] = 'Litras Equals test'; $literal1 = new Literal('test'); $literal2 = new Literal('test'); $this->assertTrue($literal1->equals($literal2)); $literal2->setLanguage('DE'); $this->assertFalse($literal1->equals($literal2)); $literal1->setLanguage('FR'); $this->assertFalse($literal1->equals($literal2)); $literal1->setLanguage('DE'); $this->assertTrue($literal1->equals($literal2)); $literal1->setDatatype("http://www.w3.org/TR/xmlschema-2/integer"); $this->assertFalse($literal1->equals($literal2)); $literal2->setDatatype("http://www.w3.org/TR/xmlschema-2/integer1"); $this->assertFalse($literal1->equals($literal2)); $literal2->setDatatype("http://www.w3.org/TR/xmlschema-2/integer"); $this->assertTrue($literal1->equals($literal2)); }
function generateResultStatementsFromVarResult(&$result, $parsedq, &$outm, $closure, &$model) { foreach ($parsedq['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 ($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']); } } $stmt = new Statement($subj, $pred, $obj); // bNode closure 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); } // Add statement to model $outm->add($stmt); } }
/** * Adds a new statement to the model * This method is called by generateModel(). * * @access private * @param string &$user_data * @param string $subject_type * @param string $subject * @param string $predicate * @param string $ordinal * @param string $object_type * @param string $object * @param string $xml_lang ) * @return object MemModel */ function add_statement_to_model(&$user_data, $subject_type, $subject, $predicate, $ordinal, $object_type, $object, $xml_lang, $datatype) { // ParseUnicode if (UNIC_RDF) { $subject = $this->str2unicode_nfc($subject); $predicate = $this->str2unicode_nfc($predicate); $object = $this->str2unicode_nfc($object); } //create subject if ($subject_type == RDF_SUBJECT_TYPE_BNODE) { $objsub = new BlankNode($subject); } else { $objsub = new Resource($subject); } // create predicate $objpred = new Resource($predicate); // create object if ($object_type == RDF_OBJECT_TYPE_RESOURCE || $object_type == RDF_OBJECT_TYPE_BNODE) { if ($object_type == RDF_OBJECT_TYPE_BNODE) { $objobj = new BlankNode($object); } else { $objobj = new Resource($object); } } else { $objobj = new Literal($object); if ($datatype != '') { $objobj->setDatatype($datatype); } elseif ($xml_lang != '') { $objobj->setLanguage($xml_lang); } } // create statement $statement = new Statement($objsub, $objpred, $objobj); // add statement to model if (CREATE_MODEL_WITHOUT_DUPLICATES == TRUE) { $this->model->addWithoutDuplicates($statement); } else { $this->model->add($statement); } }
function tagClosed($parser, $name) { if ($this->mode == 1) { $lit = new Literal($this->current_literal); if ($this->lang) { $lit->setLanguage($this->lang); } if ($this->dtype) { $lit->setDatatype($this->dtype); } $this->arrOutput[$this->counter][$this->varname] = $lit; $this->mode = -1; } }
/** * Stores all subjects of RDF triples extracted from the RDFa representation of a given fragment in this format: * fragmentURI LOOMP:contains resourceURI . * * @param Resource $fragmentRes Resource Object * @param string $rdfa RDFa representation of a given fragment */ private function _saveResFromRDFa($fragmentRes, $rdfa) { $parser = ARC2::getSemHTMLParser(); $parser->parse('', $rdfa); $parser->extractRDF('rdfa'); $triples = $parser->getTriples(); $res = array(); for ($i = 0, $i_max = count($triples); $i < $i_max; $i++) { $triple = $triples[$i]; if ($triple['s_type'] == "uri") { if (!in_array($triple['s'], $res)) { $res[] = $triple['s']; $this->rdfModel->add(new Statement($fragmentRes, LOOMP::CONTAINS(), new Resource($triple['s']))); } } if ($triple['o_type'] == 'literal') { $obj = new Literal($triple['o'], $triple['o_lang']); if ($triple['o_datatype']) { $obj->setDatatype($triple['o_datatype']); } } else { $obj = new Resource($triple['o']); } $this->rdfModel->add(new Statement(new Resource($triple['s']), new Resource($triple['p']), $obj)); } }
/** * Filter the result-set of query variables by evaluating each filter from the * AND clause of the RDQL query. * * @param array &$finalRes [][?VARNAME] = object Node * @return array [][?VARNAME] = object Node * @access private */ function filterTuples(&$finalRes) { foreach ($this->parsedQuery['filters'] as $filter) { foreach ($finalRes as $n => $fRes) { $evalFilterStr = $filter['evalFilterStr']; // evaluate regex equality expressions of each filter foreach ($filter['regexEqExprs'] as $i => $expr) { preg_match($expr['regex'], $fRes[$expr['var']]->getLabel(), $match); $op = substr($expr['operator'], 0, 1); if ($op != '!' && !isset($match[0]) || $op == '!' && isset($match[0])) { $evalFilterStr = str_replace("##RegEx_{$i}##", 'FALSE', $evalFilterStr); } else { $evalFilterStr = str_replace("##RegEx_{$i}##", 'TRUE', $evalFilterStr); } } // evaluate string equality expressions foreach ($filter['strEqExprs'] as $i => $expr) { $exprBoolVal = 'FALSE'; switch ($expr['value_type']) { case 'variable': if ($fRes[$expr['var']] == $fRes[$expr['value']] && $expr['operator'] == 'eq' || $fRes[$expr['var']] != $fRes[$expr['value']] && $expr['operator'] == 'ne') { $exprBoolVal = 'TRUE'; } break; case 'URI': if (is_a($fRes[$expr['var']], 'Literal')) { if ($expr['operator'] == 'ne') { $exprBoolVal = 'TRUE'; } break; } if ($fRes[$expr['var']]->getLabel() == $expr['value'] && $expr['operator'] == 'eq' || $fRes[$expr['var']]->getLabel() != $expr['value'] && $expr['operator'] == 'ne') { $exprBoolVal = 'TRUE'; } break; case 'Literal': if (!is_a($fRes[$expr['var']], 'Literal')) { if ($expr['operator'] == 'ne') { $exprBoolVal = 'TRUE'; } break; } $filterLiteral = new Literal($expr['value'], $expr['value_lang']); $filterLiteral->setDatatype($expr['value_dtype']); $equal = $fRes[$expr['var']]->equals($filterLiteral); /* if ($fRes[$expr['var']]->getLabel() == $expr['value'] && $fRes[$expr['var']]->getDatatype() == $expr['value_dtype']) { $equal = TRUE; // Lang tags only differentiate literals in rdf:XMLLiterals and plain literals. // Therefore if a literal is datatyped ignore the language tag. if ((($expr['value_dtype'] == NULL) || ($expr['value_dtype'] == 'http://www.w3.org/1999/02/22-rdf-syntax-ns#XMLLiteral') || ($expr['value_dtype'] == 'http://www.w3.org/2001/XMLSchema#string')) && (($fRes[$expr['var']]->getLanguage() != $expr['value_lang']))) $equal = FALSE; }else $equal = FALSE; */ if ($equal && $expr['operator'] == 'eq' || !$equal && $expr['operator'] == 'ne') { $exprBoolVal = 'TRUE'; } else { $exprBoolVal = 'FALSE'; } } $evalFilterStr = str_replace("##strEqExpr_{$i}##", $exprBoolVal, $evalFilterStr); } // evaluate numerical expressions foreach ($filter['numExprVars'] as $varName) { $varValue = "'" . $fRes[$varName]->getLabel() . "'"; $evalFilterStr = str_replace($varName, $varValue, $evalFilterStr); } eval("\$filterBoolVal = {$evalFilterStr}; \$eval_filter_ok = TRUE;"); if (!isset($eval_filter_ok)) { trigger_error(RDQL_AND_ERR . "'" . htmlspecialchars($filter['string']) . "'", E_USER_ERROR); } if (!$filterBoolVal) { unset($finalRes[$n]); } } } return $finalRes; }
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; }
/** * 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; }
/** * tests _node2ResNode() */ function test_node2ResNodeTest() { $_SESSION['test'] = 'ResModel _node2ResNode test'; $model1 = new MemModel(); $resmodel = new ResModel($model1); $literal = new Literal('Literal', 'DE'); $literal->setDatatype('type'); $result = $resmodel->_node2ResNode($literal); $this->assertIsA($result, 'ResLiteral'); $this->assertEqual($result->getLanguage(), 'DE'); $this->assertEqual($result->getDatatype(), 'type'); $model1->close(); }
/** * Creates an RDF object object * contained in the given $dbRecordSet object. * * @see convertFromDbResult() to understand $strVarBase necessity * * @param ADORecordSet $dbRecordSet Record set returned from ADOConnection::Execute() * @param string $strVarBase Prefix of the columns the recordset fields have. * * @return Resource RDF triple object resource object */ protected function createObjectFromDbRecordSetPart(ADORecordSet $dbRecordSet, $strVarBase, $strVar) { $strVarName = (string) $strVar; if ($dbRecordSet->fields[$strVarBase . '.' . $this->sg->arVarAssignments[$strVarName]['sql_value']] === null) { //FIXME: should be NULL, but doesn't pass test return ''; } switch ($dbRecordSet->fields[$strVarBase . '.' . $this->sg->arVarAssignments[$strVarName]['sql_is']]) { case 'r': $object = new Resource($dbRecordSet->fields[$strVarBase . '.' . $this->sg->arVarAssignments[$strVarName]['sql_value']]); break; case 'b': $object = new BlankNode($dbRecordSet->fields[$strVarBase . '.' . $this->sg->arVarAssignments[$strVarName]['sql_value']]); break; default: $object = new Literal($dbRecordSet->fields[$strVarBase . '.' . $this->sg->arVarAssignments[$strVarName]['sql_value']], $dbRecordSet->fields[$strVarBase . '.' . $this->sg->arVarAssignments[$strVarName]['sql_lang']]); if ($dbRecordSet->fields[$strVarBase . '.' . $this->sg->arVarAssignments[$strVarName]['sql_type']]) { $object->setDatatype($dbRecordSet->fields[$strVarBase . '.' . $this->sg->arVarAssignments[$strVarName]['sql_type']]); } } return $object; }
/** * converts a ResResource, ResProperty, or ResLiteral into a Resource, Blanknode, or Literal * * @param object ResNode $resNode * @return object Node * @access private * @throws phpErrpr */ function _resNode2Node($resNode) { if (is_a($resNode, 'ResResource')) { if ($resNode->getIsAnon()) { $return = new BlankNode($resNode->getURI()); } else { $return = new Resource($resNode->getURI()); } return $return; } if (is_a($resNode, 'ResLiteral')) { $literal = new Literal($resNode->getLabel(), $resNode->getLanguage()); if ($resNode->getDatatype() != null) { $literal->setDatatype($resNode->getDatatype()); } return $literal; } }
/** * Returns the current item. * * @return mixed * @access public */ function ¤t() { if ($this->dbResultSet === false) { return null; } // subject if ($this->dbResultSet->fields[5] == 'r') { $sub = new Resource($this->dbResultSet->fields[0]); } else { $sub = new BlankNode($this->dbResultSet->fields[0]); } // predicate $pred = new Resource($this->dbResultSet->fields[1]); // object if ($this->dbResultSet->fields[6] == 'r') { $obj = new Resource($this->dbResultSet->fields[2]); } elseif ($this->dbResultSet->fields[6] == 'b') { $obj = new BlankNode($this->dbResultSet->fields[2]); } else { $obj = new Literal($this->dbResultSet->fields[2], $this->dbResultSet->fields[3]); if ($this->dbResultSet->fields[4]) { $obj->setDatatype($this->dbResultSet->fields[4]); } } if ($this->returnAsTriples) { return new Statement($sub, $pred, $obj); } return new Quad(new Resource($this->dbResultSet->fields[7]), $sub, $pred, $obj); }
/** * Constructs a RAP RDFNode from URI/Literal/Bnode * @access private * @param string $s * @returns object RDFNode **/ function toRDFNode($s, $state) { $ins = substr($s, 1, -1); if ($s[0] == '"' || $s[0] == '\'') { $lang = NULL; if (count($state) > 3) { for ($i = 3; $i < count($state); $i++) { if ($state[$i][0] == '@') { $lang = substr($state[3], 1); } if (substr($state[$i], 0, 2) == '^^') { $dtype = substr($state[$i], 2); if ($dtype[0] == '<') { $dtype = substr($dtype, 1, -1); } } } } if (UNIC_RDF) { $ins = $this->str2unicode_nfc($ins); } $new_Literal = new Literal($ins, $lang); if (isset($dtype)) { $new_Literal->setDatatype($dtype); } return $new_Literal; } else { if (is_int($s)) { $value = new Literal($s); $value->setDatatype(XML_SCHEMA . 'integer'); return $value; } else { if (is_float($s)) { $value = new Literal($s); $value->setDatatype(XML_SCHEMA . 'double'); return $value; } else { if ($s == '@true') { $value = new Literal(true); $value->setDatatype(XML_SCHEMA . 'boolean'); return $value; } else { if ($s == '@false') { $value = new Literal(false); $value->setDatatype(XML_SCHEMA . 'boolean'); return $value; } } } } } if (strstr($s, '_' . BNODE_PREFIX)) { if ($this->FixBnodes || !array_search($s, $this->bNodeMap)) { return new BlankNode($ins); } else { return new BlankNode(trim(substr(array_search($s, $this->bNodeMap), 2))); } } return new Resource($ins); }
/** * return a mathing resource tyoe * * @param string * @param object simpleXMLNode $value * @access private */ function _element2Resource($tag, $value) { switch ($tag) { case 'uri': return new Resource((string) $value); break; case 'id': return new BlankNode((string) $value); break; case 'typedLiteral': $literal = new Literal((string) $value); $literal->setDatatype((string) $value['datatype']); return $literal; break; case 'plainLiteral': $literal = new Literal((string) $value); if (isset($value['xml:lang'])) { $literal->setLanguage((string) $value['xml:lang']); } return $literal; break; } }
function tagData($parser, $tagData) { switch ($this->mode) { case 0: $this->arrOutput[$this->counter][$this->varname] = new Resource($tagData); $this->mode = -1; break; case 1: $lit = new Literal($tagData); if ($this->lang) { $lit->setLanguage($this->lang); } if ($this->dtype) { $lit->setDatatype($this->dtype); } $this->arrOutput[$this->counter][$this->varname] = $lit; $this->mode = -1; break; case 2: if ($tagData == "/") { $bn = "bNode" . $this->bncounter; $this->bncounter++; } else { $bn = $tagData; } $this->arrOutput[$this->counter][$this->varname] = new BlankNode($bn); $this->mode = -1; break; case 3: $this->arrOutput = $tagData; $this->mode = -1; break; } }
/** * 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; }
/** * Constructs a RAP RDFNode from URI/Literal/Bnode * @access private * @param string $s * @returns object RDFNode **/ function toRDFNode($s, $state) { $ins = substr($s, 1, -1); if ($s[0] == "\"") { $lang = NULL; if (count($state) > 3) { for ($i = 3; $i < count($state); $i++) { if ($state[$i][0] == '@') { $lang = substr($state[3], 1); } if (substr($state[$i], 0, 2) == '^^') { $dtype = substr($state[$i], 2); if ($dtype[0] == '<') { $dtype = substr($dtype, 1, -1); } } } } if (UNIC_RDF) { $ins = $this->str2unicode_nfc($ins); } $new_Literal = new Literal($ins, $lang); if (isset($dtype)) { $new_Literal->setDatatype($dtype); } return $new_Literal; } if (strstr($s, '_' . BNODE_PREFIX)) { if ($this->FixBnodes or !array_search($s, $this->bNodeMap)) { return new BlankNode($ins); } else { return new BlankNode(trim(substr(array_search($s, $this->bNodeMap), 2))); } } return new Resource($ins); }
/** * Filter tuples containing variables matching all patterns from the WHERE clause * of an RDQL query. As a result of a database query using ADOdb these tuples * are returned as an ADORecordSet object, which is then passed to this function. * * @param object ADORecordSet &$recordSet * @return array [][?VARNAME]['value'] = string * ['nType'] = string * ['l_lang'] = string * ['l_dtype'] = string * @access private */ function filterQueryResult(&$recordSet) { $queryResult = array(); if (isset($this->parsedQuery['filters'])) { while (!$recordSet->EOF) { foreach ($this->parsedQuery['filters'] as $filter) { $evalFilterStr = $filter['evalFilterStr']; // evaluate regex equality expressions of each filter foreach ($filter['regexEqExprs'] as $i => $expr) { preg_match($expr['regex'], $recordSet->fields[$this->rsIndexes[$expr['var']]['value']], $match); $op = substr($expr['operator'], 0, 1); if ($op != '!' && !isset($match[0]) || $op == '!' && isset($match[0])) { $evalFilterStr = str_replace("##RegEx_{$i}##", 'FALSE', $evalFilterStr); } else { $evalFilterStr = str_replace("##RegEx_{$i}##", 'TRUE', $evalFilterStr); } } // evaluate string equality expressions foreach ($filter['strEqExprs'] as $i => $expr) { $exprBoolVal = 'FALSE'; switch ($expr['value_type']) { case 'variable': if ($recordSet->fields[$this->rsIndexes[$expr['var']]['value']] == $recordSet->fields[$this->rsIndexes[$expr['value']]['value']] && $expr['operator'] == 'eq' || $recordSet->fields[$this->rsIndexes[$expr['var']]['value']] != $recordSet->fields[$this->rsIndexes[$expr['value']]['value']] && $expr['operator'] == 'ne') { $exprBoolVal = 'TRUE'; } break; case 'URI': if (isset($this->rsIndexes[$expr['var']]['nType']) && $recordSet->fields[$this->rsIndexes[$expr['var']]['nType']] == 'l') { if ($expr['operator'] == 'ne') { $exprBoolVal = 'TRUE'; } break; } if ($recordSet->fields[$this->rsIndexes[$expr['var']]['value']] == $expr['value'] && $expr['operator'] == 'eq' || $recordSet->fields[$this->rsIndexes[$expr['var']]['value']] != $expr['value'] && $expr['operator'] == 'ne') { $exprBoolVal = 'TRUE'; } break; case 'Literal': if (!isset($this->rsIndexes[$expr['var']]['nType']) || $recordSet->fields[$this->rsIndexes[$expr['var']]['nType']] != 'l') { if ($expr['operator'] == 'ne') { $exprBoolVal = 'TRUE'; } break; } $filterLiteral = new Literal($expr['value'], $expr['value_lang']); $filterLiteral->setDatatype($expr['value_dtype']); $resultLiteral = new Literal($recordSet->fields[$this->rsIndexes[$expr['var']]['value']]); $resultLiteral->setDatatype($recordSet->fields[$this->rsIndexes[$expr['var']]['l_dtype']]); $resultLiteral->setLanguage($recordSet->fields[$this->rsIndexes[$expr['var']]['l_lang']]); $equal = $resultLiteral->equals($filterLiteral); if ($equal && $expr['operator'] == 'eq' || !$equal && $expr['operator'] == 'ne') { $exprBoolVal = 'TRUE'; } else { $exprBoolVal = 'FALSE'; } } $evalFilterStr = str_replace("##strEqExpr_{$i}##", $exprBoolVal, $evalFilterStr); } // evaluate numerical expressions foreach ($filter['numExprVars'] as $varName) { $varValue = "'" . $recordSet->fields[$this->rsIndexes[$varName]['value']] . "'"; $evalFilterStr = str_replace($varName, $varValue, $evalFilterStr); } eval("\$filterBoolVal = {$evalFilterStr}; \$eval_filter_ok = TRUE;"); if (!isset($eval_filter_ok)) { trigger_error(RDQL_AND_ERR . "'" . htmlspecialchars($filter['string']) . "'", E_USER_ERROR); } if (!$filterBoolVal) { $recordSet->MoveNext(); continue 2; } } $queryResult[] = $this->_convertRsRowToQueryResultRow($recordSet->fields); $recordSet->MoveNext(); } } else { while (!$recordSet->EOF) { $queryResult[] = $this->_convertRsRowToQueryResultRow($recordSet->fields); $recordSet->MoveNext(); } } return $queryResult; }
function MwRdfLiteral($str, $type = null, $lang = null) { static $cache = array(); if (isset($cache["{$type}:{$lang}:{$str}"])) { return $cache["{$type}:{$lang}:{$str}"]; } else { if (isset($lang)) { $lit = new Literal($str, $lang); } else { $lit = new Literal($str); } if (isset($type)) { $lit->setDatatype($type); } $cache["{$type}:{$lang}:{$str}"] = $lit; return $lit; } }
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; }
/** * Checks if the Node is a typed Literal. * * @param String $node * * @return boolean TRUE if typed FALSE if not */ protected function dtypeCheck(&$node) { $patternInt = "/^-?[0-9]+\$/"; $match = preg_match($patternInt, $node, $hits); if ($match > 0) { $node = new Literal($hits[0]); $node->setDatatype(XML_SCHEMA . 'integer'); return true; } $patternBool = "/^(true|false)\$/"; $match = preg_match($patternBool, $node, $hits); if ($match > 0) { $node = new Literal($hits[0]); $node->setDatatype(XML_SCHEMA . 'boolean'); return true; } $patternType = "/^a\$/"; $match = preg_match($patternType, $node, $hits); if ($match > 0) { $node = new Resource(RDF_NAMESPACE_URI . 'type'); return true; } $patternDouble = "/^-?[0-9]+.[0-9]+[e|E]?-?[0-9]*/"; $match = preg_match($patternDouble, $node, $hits); if ($match > 0) { $node = new Literal($hits[0]); $node->setDatatype(XML_SCHEMA . 'double'); return true; } return false; }
} else { $query_subj = new BlankNode($_POST['query_subject']); } $comment_string .= "Subject = " . $_POST['query_subject'] . "<BR>"; } if ($_POST['query_predicate'] != '') { $query_pred = new Resource($_POST['query_predicate']); $comment_string .= "Predicate = " . $_POST['query_predicate'] . "<BR>"; } if ($_POST['query_object'] != '') { if ($_POST['object_kind'] == 'resource') { $query_obj = new Resource($_POST['query_object']); } elseif ($_POST['object_kind'] == 'literal') { $query_obj = new Literal($_POST['query_object']); if ($_POST['query_object_datatype'] != '') { $query_obj->setDatatype($_POST['query_object_datatype']); } } else { $query_obj = new BlankNode($_POST['query_object']); } $comment_string .= "Object = " . $_POST['query_object'] . "<BR>"; } // Execute query and display what has been done $model = $model->find($query_subj, $query_pred, $query_obj); echo $comment_string; } // Reify the model if checked in submitted form if (isset($_POST['reify']) and $_POST['reify'] == "1") { $model =& $model->reify(); echo "<BR><BR><h3>Your original model has been refied.</h3><BR>"; }
$total_results_number = new Literal($service->total_results); $total_results_number->setDatatype(XML_SCHEMA . "int"); $next_page = new Resource(BOOKMASHUP_BASE . "search.php?keywords=" . urlencode($query) . "&page=" . ($service->page + 1) . "&output=rdf"); $model->add(new Statement($document, $rdf_type, $SearchResultPage)); $model->add(new Statement($document, $rdfs_label, new Literal($label))); $model->add(new Statement($document, $searchTerm, new Literal($query))); $model->add(new Statement($document, $page, $page_number)); $model->add(new Statement($document, $totalPages, $total_pages_number)); $model->add(new Statement($document, $totalResults, $total_results_number)); $model->add(new Statement($document, $nextPage, $next_page)); $i = ($service->page - 1) * $service->results_per_page; foreach ($service->results as $book) { $i++; $this_result = new BlankNode("result{$i}"); $rank_number = new Literal($i); $rank_number->setDatatype(XML_SCHEMA . "int"); $model->add(new Statement($document, $searchResult, $this_result)); $model->add(new Statement($this_result, $rank, $rank_number)); $model->add(new Statement($this_result, $item, new Resource($book['uri']))); $model->add(new Statement($this_result, $rdfs_label, new Literal($book['title']))); if ($book['image']) { $model->add(new Statement($this_result, $foaf_depiction, new Resource($book['image']))); } foreach ($book['authors'] as $key => $author) { $this_author = new BlankNode("result{$i}_author" . ($key + 1)); $model->add(new Statement($this_result, $dc_creator, $this_author)); $model->add(new Statement($this_author, $foaf_name, new Literal($author))); } foreach ($book['subjects'] as $key => $subject) { $this_subject = new BlankNode("result{$i}_subject" . ($key + 1)); $model->add(new Statement($this_result, $dc_subject, $this_subject));