Semantik Web APP und API

This commit is contained in:
M.Scholz 2011-11-26 15:42:11 +01:00
parent df2d29586e
commit f7f9b6117b
6350 changed files with 687593 additions and 0 deletions

Binary file not shown.

View File

@ -0,0 +1,14 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" path="src"/>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.6"/>
<classpathentry kind="lib" path="lib/arq-2.8.7.jar"/>
<classpathentry kind="lib" path="lib/icu4j-3.4.4.jar"/>
<classpathentry kind="lib" path="lib/iri-0.8.jar"/>
<classpathentry kind="lib" path="lib/jena-2.6.4.jar"/>
<classpathentry kind="lib" path="lib/log4j-1.2.13.jar"/>
<classpathentry kind="lib" path="lib/slf4j-api-1.5.8.jar"/>
<classpathentry kind="lib" path="lib/slf4j-log4j12-1.5.8.jar"/>
<classpathentry kind="lib" path="lib/xercesImpl-2.7.1.jar"/>
<classpathentry kind="output" path="bin"/>
</classpath>

View File

@ -0,0 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>JenaExamples</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jdt.core.javanature</nature>
</natures>
</projectDescription>

View File

@ -0,0 +1,12 @@
#Thu Nov 17 11:48:31 CET 2011
eclipse.preferences.version=1
org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6
org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
org.eclipse.jdt.core.compiler.compliance=1.6
org.eclipse.jdt.core.compiler.debug.lineNumber=generate
org.eclipse.jdt.core.compiler.debug.localVariable=generate
org.eclipse.jdt.core.compiler.debug.sourceFile=generate
org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
org.eclipse.jdt.core.compiler.source=1.6

View File

@ -0,0 +1,3 @@
@prefix : <http://example.org/> .
:Madrid :capitalOf :Spain .

View File

@ -0,0 +1,8 @@
@prefix : <http://example.org/> .
@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
:Country a rdfs:Class .
:City a rdfs:Class .
:capitalOf rdfs:subPropertyOf :locatedIn .
:locatedIn rdfs:domain :City ; rdfs:range :Country .

View File

@ -0,0 +1,55 @@
package de.tudarmstadt.ke.sw.gui;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import de.tudarmstadt.ke.sw.logic.CapitalFinder;
public class CapitalTool extends JFrame {
private static final long serialVersionUID = 3222342882423600187L;
private CapitalFinder finder = new CapitalFinder();
private JTextField question;
private JTextField answer;
public CapitalTool() {
JPanel p = new JPanel();
p.setLayout(new GridLayout(2,3));
p.add(new JLabel("Tell me the capital of"));
question = new JTextField();
p.add(question);
JButton b = new JButton("Go!");
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
answer.setText(finder.findCapital(question.getText()));
}
});
p.add(b);
p.add(new JLabel("The answer is"));
answer = new JTextField();
answer.setEditable(false);
p.add(answer);
this.setSize(500,150);
this.setTitle("Yet another great semantic web app");
this.getContentPane().add(p,BorderLayout.CENTER);
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new CapitalTool();
}
}

View File

@ -0,0 +1,22 @@
package de.tudarmstadt.ke.sw.logic;
import com.hp.hpl.jena.query.Query;
import com.hp.hpl.jena.query.QueryExecution;
import com.hp.hpl.jena.query.QueryExecutionFactory;
import com.hp.hpl.jena.query.QueryFactory;
import com.hp.hpl.jena.query.ResultSet;
public class CapitalFinder {
public String findCapital(String country) {
String query = "select ?label2 WHERE { ?country <http://dbpedia.org/ontology/capital> ?city . ?country <http://www.w3.org/2000/01/rdf-schema#label> ?label1 . ?city <http://www.w3.org/2000/01/rdf-schema#label> ?label2 . FILTER (str(?label1) = \"" + country + "\" && LANG(?label2) = \"en\") }";
Query q = QueryFactory.create(query);
QueryExecution qexec = QueryExecutionFactory.sparqlService("http://dbpedia.org/sparql", q);
ResultSet RS = qexec.execSelect();
if(RS.hasNext()) {
return RS.next().get("label2").asLiteral().getLexicalForm();
} else
return "no idea";
}
}

View File

@ -0,0 +1,44 @@
package de.tudarmstadt.ke.sw.logic;
import java.io.FileInputStream;
import java.io.InputStream;
import com.hp.hpl.jena.query.Query;
import com.hp.hpl.jena.query.QueryExecution;
import com.hp.hpl.jena.query.QueryExecutionFactory;
import com.hp.hpl.jena.query.QueryFactory;
import com.hp.hpl.jena.query.ResultSet;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.rdf.model.Statement;
import com.hp.hpl.jena.rdf.model.StmtIterator;
public class JenaReasoning {
public static void main(String args[]) throws Exception {
Model schemaModel = ModelFactory.createDefaultModel();
InputStream IS = new FileInputStream("data/example_schema.n3");
schemaModel.read(IS, null, "N3");
Model dataModel = ModelFactory.createDefaultModel();
IS = new FileInputStream("data/example_data.n3");
dataModel.read(IS, null, "N3");
Model reasoningModel = ModelFactory.createRDFSModel(schemaModel, dataModel);
StmtIterator it = reasoningModel.listStatements();
while(it.hasNext()) {
Statement s = it.next();
System.out.println(s);
}
Query q = QueryFactory.create("SELECT ?t WHERE {<http://example.org/Madrid> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> ?t .}" );
QueryExecution qexec = QueryExecutionFactory.create(q, reasoningModel);
ResultSet rs = qexec.execSelect();
while(rs.hasNext()) {
System.out.println(rs.next().get("t"));
}
}
}

Binary file not shown.

View File

@ -0,0 +1,47 @@
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title></title>
</head>
<body>
<div align=center>
This Page is only a small Semantic Web Application which allows you to find information
about movies using "Linked Movie Data Base" and "Freebase".
</p>
In which Movie are you interested?</tab>
<form method="post" action="">
<input type="text" name="movieTitleByUser" size="45">
<input type="submit" name="buttonPressed" value="Search">
</form>
<?php
include 'logic/controller.php';
if(isset($_POST['buttonPressed'])){
$movieTitleByUser =$_POST['movieTitleByUser'];
echo "</P>Getting Infos for: " . $movieTitleByUser;
echo '</br><progress value=$counter max="100">searching . . .</progress>';
$mainController = new controller();
$mainController->getData($movieTitleByUser);
}
?>
</p>
<a href="http://www.linkedmdb.org/"><img src="logos/mdb.png" alt="linkedmdb.org"></a>
</br>
<a href="http://www.freebase.com/"><img src="logos/freebase.jpg" alt="freebase.com"></a>
</div>
</body>
</html>

View File

@ -0,0 +1,48 @@
<?php
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
* Description of controller
*
* @author Michael
*/
define("RDFAPI_INCLUDE_DIR", "rdfAPI/api/");
//static $RDFAPI_INCLUDE_DIR = 'rdfAPI/api/';
include RDFAPI_INCLUDE_DIR . 'RdfAPI.php';
class controller {
/**
* Funktion organisiert die verschiedenen Quellen und gibt diese
* an die View weiter.
*
*
*/
public function getData($userInput){
$modelURI = "http://dpbedia.org/sparql";
$dbModell = ModelFactory::getDefaultDbModel($modelURI);
$querystring = "select ?label2 WHERE { ?country <http://dbpedia.org/ontology/capital> ?city . ?country <http://www.w3.org/2000/01/rdf-schema#label> ?label1 . ?city <http://www.w3.org/2000/01/rdf-schema#label> ?label2 . FILTER (str(?label1) = \"" . $userInput . "\" && LANG(?label2) = \"en\") ";
$result = $dbModell->sparqlQuery($querystring, 'xml');
echo $dbModell->sparqlQuery($querystring, 'xml');
}
}
?>

View File

@ -0,0 +1,17 @@
<?php
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
* Description of freebaseController
*
* @author Michael
*/
class freebaseController {
//put your code here
}
?>

View File

@ -0,0 +1,17 @@
<?php
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
* Description of mdbController
*
* @author Michael
*/
class mdbController {
//put your code here
}
?>

View File

@ -0,0 +1,5 @@
copy.src.files=false
copy.src.target=
index.file=index.php
run.as=LOCAL
url=http://localhost/solution/

View File

@ -0,0 +1,7 @@
include.path=${php.global.include.path}
php.version=PHP_53
source.encoding=UTF-8
src.dir=.
tags.asp=false
tags.short=true
web.root=.

View File

@ -0,0 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://www.netbeans.org/ns/project/1">
<type>org.netbeans.modules.php.project</type>
<configuration>
<data xmlns="http://www.netbeans.org/ns/php-project/1">
<name>SemanticWebApp</name>
</data>
</configuration>
</project>

View File

@ -0,0 +1,5 @@
K 25
svn:wc:ra_dav:version-url
V 49
/svnroot/rdfapi-php/!svn/ver/556/trunk/rdfapi-php
END

View File

@ -0,0 +1,46 @@
8
dir
556
https://rdfapi-php.svn.sourceforge.net/svnroot/rdfapi-php/trunk/rdfapi-php
https://rdfapi-php.svn.sourceforge.net/svnroot/rdfapi-php
2008-01-22T10:52:48.041272Z
556
fusel2k
svn:special svn:externals svn:needs-lock
b2ee660e-c932-0410-bdee-d8da4d8102f4
test
dir
netapi
dir
tools
dir
rap-pubby
dir
doc
dir
api
dir

View File

@ -0,0 +1,17 @@
K 25
svn:wc:ra_dav:version-url
V 53
/svnroot/rdfapi-php/!svn/ver/556/trunk/rdfapi-php/api
END
constants.php
K 25
svn:wc:ra_dav:version-url
V 67
/svnroot/rdfapi-php/!svn/ver/558/trunk/rdfapi-php/api/constants.php
END
RdfAPI.php
K 25
svn:wc:ra_dav:version-url
V 64
/svnroot/rdfapi-php/!svn/ver/268/trunk/rdfapi-php/api/RdfAPI.php
END

View File

@ -0,0 +1,84 @@
8
dir
556
https://rdfapi-php.svn.sourceforge.net/svnroot/rdfapi-php/trunk/rdfapi-php/api
https://rdfapi-php.svn.sourceforge.net/svnroot/rdfapi-php
2008-01-22T10:52:48.041272Z
556
fusel2k
svn:special svn:externals svn:needs-lock
b2ee660e-c932-0410-bdee-d8da4d8102f4
model
dir
ontModel
dir
rdql
dir
sparql
dir
constants.php
file
558
2008-02-29T15:14:07.085157Z
f305fb172543bc44201542efebec39a9
2008-02-29T15:14:04.958076Z
558
cax
has-props
dataset
dir
syntax
dir
vocabulary
dir
resModel
dir
RdfAPI.php
file
2008-02-29T14:57:56.956719Z
3162507773a5651a21e2224bb9c957b5
2006-05-15T05:28:09.000000Z
268
tgauss
has-props
infModel
dir
util
dir

View File

@ -0,0 +1,9 @@
K 13
svn:eol-style
V 6
native
K 12
svn:keywords
V 23
Author Date Id Revision
END

View File

@ -0,0 +1,9 @@
K 13
svn:eol-style
V 6
native
K 12
svn:keywords
V 23
Author Date Id Revision
END

View File

@ -0,0 +1,19 @@
<?php
// ----------------------------------------------------------------------------------
// RDF API for PHP
// ----------------------------------------------------------------------------------
// @version : $Id$
// Authors : Chris Bizer (chris@bizer.de),
// Radoslaw Oldakowski (radol@gmx.de)
// Description : This file includes constatns and model package.
// ----------------------------------------------------------------------------------
// Include Constants and base Object
require_once( RDFAPI_INCLUDE_DIR . 'constants.php' );
require_once( RDFAPI_INCLUDE_DIR . 'util/Object.php' );
include_once( RDFAPI_INCLUDE_DIR . PACKAGE_MODEL);
?>

View File

@ -0,0 +1,418 @@
<?php
// ----------------------------------------------------------------------------------
// Constants
// ----------------------------------------------------------------------------------
// @version : $Id$
// Authors : Chris Bizer (chris@bizer.de),
// Daniel Westphal (dawe@gmx.de),
// Leandro Mariano Lopez (llopez@xinergiaargentina.com),
// Radoslaw Oldakowski (radol@gmx.de)
//
// Description : Constants and default configuration
// ----------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------
// General
// ----------------------------------------------------------------------------------
define('RDFAPI_ERROR', 'RDFAPI error ');
define('DEFAULT_ALGORITHM', 'MD5');
define('DEFAULT_ENCODING', 'UTF-8');
define('INDENTATION', ' ');
define('LINEFEED', chr(10));
// ----------------------------------------------------------------------------------
// RAP Packages
// ----------------------------------------------------------------------------------
define('PACKAGE_MODEL','model/ModelP.php');
define('PACKAGE_UTILITY','util/Utility.php');
define('PACKAGE_DBASE','model/DBase.php');
define('PACKAGE_SYNTAX_RDF','syntax/SyntaxRDF.php');
define('PACKAGE_SYNTAX_N3','syntax/SyntaxN3.php');
define('PACKAGE_SYNTAX_JSON','syntax/SyntaxJSON.php');
define('PACKAGE_SYNTAX_GRDDL','syntax/SyntaxGRDDL.php');
define('PACKAGE_VOCABULARY','vocabulary/Vocabulary.php');
define('PACKAGE_RDQL','rdql/RDQL.php');
define('PACKAGE_INFMODEL','infModel/InfModelP.php');
define('PACKAGE_RESMODEL','resModel/ResModelP.php');
define('PACKAGE_ONTMODEL','ontModel/OntModelP.php');
define('PACKAGE_DATASET','dataset/DatasetP.php');
define('PACKAGE_SPARQL','sparql/SPARQL.php');
define('PACKAGE_SYNTAX_RSS','syntax/SyntaxRSS.php');
define('PACKAGE_SYNTAX_SPARQLRES','syntax/SyntaxSparqlRes.php');
// ----------------------------------------------------------------------------------
// Model
// ----------------------------------------------------------------------------------
// Defines a prefix used in the ID of automatically created bNodes.
define('BNODE_PREFIX', 'bNode');
// Sets the index of MemModell:
// IND_DEF: Defaultindex over subject, predicate, obeject seperate.
// IND_SPO: Index over subject+predicate+object.
// IND_SP: Index over subject+predicate.
// IND_SO: Index over subject+object.
define('NO_INDEX',-1);
define('IND_DEF',0);
define('IND_SPO',1);
define('IND_SP',2);
define('IND_SO',3);
define('INDEX_TYPE',IND_DEF);
// ----------------------------------------------------------------------------------
// ModelFactory
// ----------------------------------------------------------------------------------
define ('MEMMODEL','MemModel');
define ('DBMODEL','DbModel');
define ('INFMODELF','InfModelF');
define ('INFMODELB','InfModelB');
define ('ONTMODEL','OntModel');
define ('RESMODEL','ResModel');
define ('RDFS_VOCABULARY','RdfsVocabulary.php');
// ----------------------------------------------------------------------------------
// Parser
// ----------------------------------------------------------------------------------
// RdfParser: Set this option to false if you want to use IDs containing CombiningChars or
// Extenders (see http://www.w3.org/TR/REC-xml-names/#NT-NCName). If set to TRUE, they're assumed to be invalid.
define('VALIDATE_IDS', TRUE);
// RdfParser: Set this option to true if you want to parse UNICODE documents.
// WARNING: Setting the option TRUE significantly slows down the RDF-parser.
define('UNIC_RDF', FALSE);
// RdfParser: Set this option to true if you want to make sure that the created RDF-model doesnt contain
// duplicate RDF-statements. WARNING: Setting the option TRUE significantly slows down the RDF-parser.
define('CREATE_MODEL_WITHOUT_DUPLICATES', FALSE);
// N3 and N-Triple-Parser: Set this option to true in order to override the given bnode
// labels and rename them to the defined BNODE_PREFIX
define('FIX_BLANKNODES', TRUE);
define('NAMESPACE_SEPARATOR_CHAR','^');
define('NAMESPACE_SEPARATOR_STRING','^');
define('IN_TOP_LEVEL',0);
define('IN_RDF',1);
define('IN_DESCRIPTION',2);
define('IN_PROPERTY_UNKNOWN_OBJECT',3);
define('IN_PROPERTY_RESOURCE',4);
define('IN_PROPERTY_EMPTY_RESOURCE',5);
define('IN_PROPERTY_LITERAL',6);
define('IN_PROPERTY_PARSE_TYPE_LITERAL',7);
define('IN_PROPERTY_PARSE_TYPE_RESOURCE',8);
define('IN_XML',9);
define('IN_UNKNOWN',10);
define('IN_PROPERTY_PARSE_TYPE_COLLECTION', 11);
define('RDF_SUBJECT_TYPE_URI',0);
define('RDF_SUBJECT_TYPE_DISTRIBUTED',1);
define('RDF_SUBJECT_TYPE_PREFIX',2);
define('RDF_SUBJECT_TYPE_ANONYMOUS',3);
define('RDF_SUBJECT_TYPE_BNODE',4);
define('RDF_OBJECT_TYPE_RESOURCE',0);
define('RDF_OBJECT_TYPE_LITERAL',1);
define('RDF_OBJECT_TYPE_XML',2);
define('RDF_OBJECT_TYPE_BNODE',3);
// ----------------------------------------------------------------------------------
// Serializer
// ----------------------------------------------------------------------------------
// RDF, N3, N-Triple Serializer: set to TRUE in oder to suppres the "Generated by RAP"
// comment in the output files.
define('HIDE_ADVERTISE',FALSE);
// RDF Serializer: Set to TRUE, if the serializer should use entities for URIs.
define('SER_USE_ENTITIES', FALSE );
// RDF Serializer: Set to TRUE, if the serializer should serialize triples as XML
// attributes where possible.
define('SER_USE_ATTRIBUTES', FALSE );
// RDF Serializer: Set to TRUE in order to sort the statements of a model before
// serializing them.
define('SER_SORT_MODEL', FALSE );
// RDF Serializer: Set to TRUE, if the serializer should use qualified names for RDF
// reserved words.
// NOTE: There is only one default namespace allowed within an XML document.
// Therefore if SER_RDF_QNAMES in is set to FALSE and you pass the parameter
// $xml_default_namespace to the method serialize() of class RdfSerializer,
// the model will be serialized as if SER_RDF_QNAMES were set to TRUE.
define('SER_RDF_QNAMES', TRUE );
// RDF Serializer: Set to TRUE, if the serializer should start documents with the
// xml declaration <?xml version="1.0" encoding="UTF-8" >.
define('SER_XML_DECLARATION', TRUE );
// N3 Serializer: Set to TRUE, if the N3 serializer should try to compress the blank node
// syntax using [] whereever possible.
define('N3SER_BNODE_SHORT', FALSE);
// RDF Serializer: Set to TRUE, if the serializer should write text values always as
// escaped CDATA.
define('USE_CDATA', FALSE);
define('USE_ANY_QUOTE', FALSE);
define('GENERAL_PREFIX_BASE','ns');
define('MAX_ALLOWED_ABBREVIATED_LENGTH',60);
// ----------------------------------------------------------------------------------
// Util
// ----------------------------------------------------------------------------------
// Definition of the colors used by the method RDFUtil:writeHTMLTable
define('HTML_TABLE_HEADER_COLOR', '#FFFFFF');
define('HTML_TABLE_RESOURCE_COLOR', '#FFFFCC');
define('HTML_TABLE_LITERAL_COLOR', '#E7E7EF');
define('HTML_TABLE_BNODE_COLOR', '#FFCCFF');
define('HTML_TABLE_RDF_NS_COLOR', '#CCFFCC');
define('HTML_TABLE_NS_ROW_COLOR1', '#FFFFFF');
define('HTML_TABLE_NS_ROW_COLOR0', '#E7E7EF');
// ----------------------------------------------------------------------------------
// RDF
// ----------------------------------------------------------------------------------
define('RDF_NAMESPACE_URI','http://www.w3.org/1999/02/22-rdf-syntax-ns#' );
define('RDF_NAMESPACE_PREFIX','rdf' );
define('RDF_RDF','RDF');
define('RDF_DESCRIPTION','Description');
define('RDF_ID','ID');
define('RDF_ABOUT','about');
define('RDF_ABOUT_EACH','aboutEach');
define('RDF_ABOUT_EACH_PREFIX','aboutEachPrefix');
define('RDF_BAG_ID','bagID');
define('RDF_RESOURCE','resource');
define('RDF_VALUE','value');
define('RDF_PARSE_TYPE','parseType');
define('RDF_PARSE_TYPE_LITERAL','Literal');
define('RDF_PARSE_TYPE_RESOURCE','Resource');
define('RDF_PARSE_TYPE_COLLECTION', 'Collection');
define('RDF_TYPE','type');
define('RDF_BAG','Bag');
define('RDF_SEQ','Seq');
define('RDF_ALT','Alt');
define('RDF_LI','li');
define('RDF_STATEMENT','Statement');
define('RDF_SUBJECT','subject');
define('RDF_PREDICATE','predicate');
define('RDF_OBJECT','object');
define('RDF_NODEID','nodeID');
define('RDF_DATATYPE','datatype');
define('RDF_SEEALSO','seeAlso');
define('RDF_PROPERTY','Property');
define('RDF_LIST','List');
define('RDF_NIL','nil');
define('RDF_REST','rest');
define('RDF_FIRST','first');
define('RDF_XMLLITERAL', 'XMLLiteral');
// ----------------------------------------------------------------------------------
// RDF Schema
// ----------------------------------------------------------------------------------
define('RDF_SCHEMA_URI','http://www.w3.org/2000/01/rdf-schema#' );
define('RDF_DATATYPE_SCHEMA_URI','http://www.w3.org/TR/xmlschema-2' );
define('RDF_SCHEMA_PREFIX', 'rdfs');
define('RDFS_SUBCLASSOF','subClassOf');
define('RDFS_SUBPROPERTYOF','subPropertyOf');
define('RDFS_RANGE','range');
define('RDFS_DOMAIN','domain');
define('RDFS_CLASS','Class');
define('RDFS_RESOURCE','Resource');
define('RDFS_DATATYPE','Datatype');
define('RDFS_LITERAL','Literal');
define('RDFS_SEE_ALSO','seeAlso');
define('RDFS_IS_DEFINED_BY','isDefinedBy');
define('RDFS_LABEL','label');
define('RDFS_COMMENT','comment');
// ----------------------------------------------------------------------------------
// OWL
// ----------------------------------------------------------------------------------
define('OWL_URI','http://www.w3.org/2002/07/owl#' );
define('OWL_PREFIX', 'owl');
define('OWL_SAME_AS','sameAs');
define('OWL_INVERSE_OF','inverseOf');
// ----------------------------------------------------------------------------------
// XML
// ----------------------------------------------------------------------------------
define('XML_NAMESPACE_PREFIX', 'xml');
define('XML_NAMESPACE_DECLARATION_PREFIX', 'xmlns');
define('XML_NAMESPACE_URI','http://www.w3.org/XML/1998/namespace' );
define('XML_LANG','lang');
define('DATATYPE_SHORTCUT_PREFIX','datatype:');
define('XML_SCHEMA','http://www.w3.org/2001/XMLSchema#');
// ----------------------------------------------------------------------------------
// RDF DATATYPE SHORTCUTS (extends datatype shortcuts to the full XML datatype URIs)
// ----------------------------------------------------------------------------------
$short_datatype = array(
'STRING' => RDF_DATATYPE_SCHEMA_URI . '#string',
'DECIMAL' => RDF_DATATYPE_SCHEMA_URI . '#decimal',
'INTEGER' => RDF_DATATYPE_SCHEMA_URI . '#integer',
'INT' => RDF_DATATYPE_SCHEMA_URI . '#int',
'SHORT' => RDF_DATATYPE_SCHEMA_URI . '#short',
'BYTE' => RDF_DATATYPE_SCHEMA_URI . '#byte',
'LONG' => RDF_DATATYPE_SCHEMA_URI . '#long',
'LANGUAGE' => RDF_DATATYPE_SCHEMA_URI . '#language',
'NAME' => RDF_DATATYPE_SCHEMA_URI . '#name'
);
// ----------------------------------------------------------------------------------
// Database
// ----------------------------------------------------------------------------------
if (!defined('ADODB_DB_DRIVER')) {
if (isset($GLOBALS['dbConf'])) {
define('ADODB_DB_DRIVER', $GLOBALS['dbConf']['type']);
define('ADODB_DB_HOST' , $GLOBALS['dbConf']['host']);
define('ADODB_DB_NAME' , $GLOBALS['dbConf']['database']);
define('ADODB_DB_USER' , $GLOBALS['dbConf']['user']);
define('ADODB_DB_PASSWORD', $GLOBALS['dbConf']['password']);
} else {
define('ADODB_DB_DRIVER', 'mysql');
define('ADODB_DB_HOST' , 'localhost');
define('ADODB_DB_NAME' , 'kbrdfdb');
define('ADODB_DB_USER' , 'kbrdf');
define('ADODB_DB_PASSWORD', 'db1');
}
}
if (!defined('ADODB_DEBUG_MODE')) {
define('ADODB_DEBUG_MODE', '0');
}
// ----------------------------------------------------------------------------------
// RDQL Error Messages
// ----------------------------------------------------------------------------------
define('RDQL_ERR','RDQL error ');
define('RDQL_SYN_ERR','RDQL syntax error ');
define('RDQL_SEL_ERR', RDQL_ERR .'in the SELECT clause: ');
define('RDQL_SRC_ERR', RDQL_ERR .'in the SOURCE clause: ');
define('RDQL_WHR_ERR', RDQL_ERR .'in the WHERE clause: ');
define('RDQL_AND_ERR', RDQL_ERR .'in the AND clause: ');
define('RDQL_USG_ERR', RDQL_ERR .'in the USING clause: ');
// ----------------------------------------------------------------------------------
// Vocabulary
// ----------------------------------------------------------------------------------
// namespace declarations
define('ATOM_NS' , 'http://purl.org/atom/ns#');
define('DC_NS' , 'http://purl.org/dc/elements/1.1/');
define('DCTERM_NS' , 'http://purl.org/dc/terms/');
define('DCMITYPE_NS', 'http://purl.org/dc/dcmitype/');
define('FOAF_NS' , 'http://xmlns.com/foaf/0.1/');
define('OWL_NS' , 'http://www.w3.org/2002/07/owl#');
define('RSS_NS' , 'http://purl.org/rss/1.0/');
define('VCARD_NS' , 'http://www.w3.org/2001/vcard-rdf/3.0#');
// ----------------------------------------------------------------------------------
// RDQL, SPARQL and parser default namespace prefixes
// ----------------------------------------------------------------------------------
global $default_prefixes;
$default_prefixes = array(
RDF_NAMESPACE_PREFIX => RDF_NAMESPACE_URI,
RDF_SCHEMA_PREFIX => RDF_SCHEMA_URI,
'xsd' => 'http://www.w3.org/2001/XMLSchema#',
OWL_PREFIX => OWL_URI,
'dc' => 'http://purl.org/dc/elements/1.1/',
'dcterms' => 'http://purl.org/dc/terms/',
'vcard' => 'http://www.w3.org/2001/vcard-rdf/3.0#'
);
// ----------------------------------------------------------------------------------
// InfModel
// ----------------------------------------------------------------------------------
//activate / deactivate reasoning for the following schema constructs
//rdfs:subclass
define('INF_RES_SUBCLASSOF',true);
//rdfs:subproperty
define('INF_RES_SUBPROPERTYOF',true);
//rdfs:range
define('INF_RES_RANGE',true);
//rdfs:domain
define('INF_RES_DOMAIN',true);
//owl:sameAs
define('INF_RES_OWL_SAMEAS',true);
//owl:inverseOf
define('INF_RES_OWL_INVERSEOF',true);
//generic RDFS Rules from the RDF Schema doc:
//see: http://www.w3.org/TR/2004/REC-rdf-mt-20040210/#RDFSRules
define('INF_RES_RULE_RDFS12',false);
define('INF_RES_RULE_RDFS6',false);
define('INF_RES_RULE_RDFS8',false);
define('INF_RES_RULE_RDFS10',false);
define('INF_RES_RULE_RDFS13',false);
// ----------------------------------------------------------------------------------
// GRAPHVIZ
// ----------------------------------------------------------------------------------
// path to the dot binary
define('GRAPHVIZ_PATH', 'C:\/Programme\/ATT\/Graphviz\/bin\/dot.exe');
// directory for temporary files
// Attention: must be write-/readable by the webserver
define('GRAPHVIZ_TEMP', 'C:\/');
// display statistical data in generated images
// currently only number of statements drawn
define('GRAPHVIZ_STAT', TRUE);
// allowed file formats
// for security reasons (to prevent code injection)
define('GRAPHVIZ_FORMAT', 'svg, dot, jpg, png, gif, vrml');
// enable clickable URIs
// only supported by certain formats (e.g. SVG)
define('GRAPHVIZ_URI', FALSE);
// define parameters for the graphical output
// if a paramter is undefined, the default value of graphviz is used
// for further information see: http://www.graphviz.org/Documentation.php
$graphviz_param = array(
'GRAPH_STYLE' => 'rankdir="TB"',
'RESOURCE_STYLE' => 'style="filled",color="#FFD800",fontname="Courier",fontsize="10"',
'LITERAL_STYLE' => 'shape="box",style="filled",color="#B7FFAF",fontname="Courier",fontsize="10"',
'PREDICATE_STYLE' => 'fontname="Courier",fontsize="10"',
'INFERRED_STYLE' => 'style="dotted",fontname="Courier",fontsize="10"',
'BLANKNODE_STYLE' => 'style="filled",color="#DDDDDD",fontname="Courier",fontsize="10"',
'BOX_STYLE' => 'fontname="Courier",fontsize="8",color="#BBBBBB"'
);
// ----------------------------------------------------------------------------------
// SPARQL
// ----------------------------------------------------------------------------------
// Attribute lists for describing Resources. ['resource type'] = array(att1, att2, att3, ...).
//
$sparql_describe = array(
FOAF_NS.'person' => array(FOAF_NS.'name',FOAF_NS.'homepage',FOAF_NS.'mbox')
);
?>

View File

@ -0,0 +1,21 @@
<?php
// ----------------------------------------------------------------------------------
// RDF API for PHP
// ----------------------------------------------------------------------------------
// @version : $Id: RdfAPI.php 268 2006-05-15 05:28:09Z tgauss $
// Authors : Chris Bizer (chris@bizer.de),
// Radoslaw Oldakowski (radol@gmx.de)
// Description : This file includes constatns and model package.
// ----------------------------------------------------------------------------------
// Include Constants and base Object
require_once( RDFAPI_INCLUDE_DIR . 'constants.php' );
require_once( RDFAPI_INCLUDE_DIR . 'util/Object.php' );
include_once( RDFAPI_INCLUDE_DIR . PACKAGE_MODEL);
?>

View File

@ -0,0 +1,418 @@
<?php
// ----------------------------------------------------------------------------------
// Constants
// ----------------------------------------------------------------------------------
// @version : $Id: constants.php 558 2008-02-29 15:14:04Z cax $
// Authors : Chris Bizer (chris@bizer.de),
// Daniel Westphal (dawe@gmx.de),
// Leandro Mariano Lopez (llopez@xinergiaargentina.com),
// Radoslaw Oldakowski (radol@gmx.de)
//
// Description : Constants and default configuration
// ----------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------
// General
// ----------------------------------------------------------------------------------
define('RDFAPI_ERROR', 'RDFAPI error ');
define('DEFAULT_ALGORITHM', 'MD5');
define('DEFAULT_ENCODING', 'UTF-8');
define('INDENTATION', ' ');
define('LINEFEED', chr(10));
// ----------------------------------------------------------------------------------
// RAP Packages
// ----------------------------------------------------------------------------------
define('PACKAGE_MODEL','model/ModelP.php');
define('PACKAGE_UTILITY','util/Utility.php');
define('PACKAGE_DBASE','model/DBase.php');
define('PACKAGE_SYNTAX_RDF','syntax/SyntaxRDF.php');
define('PACKAGE_SYNTAX_N3','syntax/SyntaxN3.php');
define('PACKAGE_SYNTAX_JSON','syntax/SyntaxJSON.php');
define('PACKAGE_SYNTAX_GRDDL','syntax/SyntaxGRDDL.php');
define('PACKAGE_VOCABULARY','vocabulary/Vocabulary.php');
define('PACKAGE_RDQL','rdql/RDQL.php');
define('PACKAGE_INFMODEL','infModel/InfModelP.php');
define('PACKAGE_RESMODEL','resModel/ResModelP.php');
define('PACKAGE_ONTMODEL','ontModel/OntModelP.php');
define('PACKAGE_DATASET','dataset/DatasetP.php');
define('PACKAGE_SPARQL','sparql/SPARQL.php');
define('PACKAGE_SYNTAX_RSS','syntax/SyntaxRSS.php');
define('PACKAGE_SYNTAX_SPARQLRES','syntax/SyntaxSparqlRes.php');
// ----------------------------------------------------------------------------------
// Model
// ----------------------------------------------------------------------------------
// Defines a prefix used in the ID of automatically created bNodes.
define('BNODE_PREFIX', 'bNode');
// Sets the index of MemModell:
// IND_DEF: Defaultindex over subject, predicate, obeject seperate.
// IND_SPO: Index over subject+predicate+object.
// IND_SP: Index over subject+predicate.
// IND_SO: Index over subject+object.
define('NO_INDEX',-1);
define('IND_DEF',0);
define('IND_SPO',1);
define('IND_SP',2);
define('IND_SO',3);
define('INDEX_TYPE',IND_DEF);
// ----------------------------------------------------------------------------------
// ModelFactory
// ----------------------------------------------------------------------------------
define ('MEMMODEL','MemModel');
define ('DBMODEL','DbModel');
define ('INFMODELF','InfModelF');
define ('INFMODELB','InfModelB');
define ('ONTMODEL','OntModel');
define ('RESMODEL','ResModel');
define ('RDFS_VOCABULARY','RdfsVocabulary.php');
// ----------------------------------------------------------------------------------
// Parser
// ----------------------------------------------------------------------------------
// RdfParser: Set this option to false if you want to use IDs containing CombiningChars or
// Extenders (see http://www.w3.org/TR/REC-xml-names/#NT-NCName). If set to TRUE, they're assumed to be invalid.
define('VALIDATE_IDS', TRUE);
// RdfParser: Set this option to true if you want to parse UNICODE documents.
// WARNING: Setting the option TRUE significantly slows down the RDF-parser.
define('UNIC_RDF', FALSE);
// RdfParser: Set this option to true if you want to make sure that the created RDF-model doesnt contain
// duplicate RDF-statements. WARNING: Setting the option TRUE significantly slows down the RDF-parser.
define('CREATE_MODEL_WITHOUT_DUPLICATES', FALSE);
// N3 and N-Triple-Parser: Set this option to true in order to override the given bnode
// labels and rename them to the defined BNODE_PREFIX
define('FIX_BLANKNODES', TRUE);
define('NAMESPACE_SEPARATOR_CHAR','^');
define('NAMESPACE_SEPARATOR_STRING','^');
define('IN_TOP_LEVEL',0);
define('IN_RDF',1);
define('IN_DESCRIPTION',2);
define('IN_PROPERTY_UNKNOWN_OBJECT',3);
define('IN_PROPERTY_RESOURCE',4);
define('IN_PROPERTY_EMPTY_RESOURCE',5);
define('IN_PROPERTY_LITERAL',6);
define('IN_PROPERTY_PARSE_TYPE_LITERAL',7);
define('IN_PROPERTY_PARSE_TYPE_RESOURCE',8);
define('IN_XML',9);
define('IN_UNKNOWN',10);
define('IN_PROPERTY_PARSE_TYPE_COLLECTION', 11);
define('RDF_SUBJECT_TYPE_URI',0);
define('RDF_SUBJECT_TYPE_DISTRIBUTED',1);
define('RDF_SUBJECT_TYPE_PREFIX',2);
define('RDF_SUBJECT_TYPE_ANONYMOUS',3);
define('RDF_SUBJECT_TYPE_BNODE',4);
define('RDF_OBJECT_TYPE_RESOURCE',0);
define('RDF_OBJECT_TYPE_LITERAL',1);
define('RDF_OBJECT_TYPE_XML',2);
define('RDF_OBJECT_TYPE_BNODE',3);
// ----------------------------------------------------------------------------------
// Serializer
// ----------------------------------------------------------------------------------
// RDF, N3, N-Triple Serializer: set to TRUE in oder to suppres the "Generated by RAP"
// comment in the output files.
define('HIDE_ADVERTISE',FALSE);
// RDF Serializer: Set to TRUE, if the serializer should use entities for URIs.
define('SER_USE_ENTITIES', FALSE );
// RDF Serializer: Set to TRUE, if the serializer should serialize triples as XML
// attributes where possible.
define('SER_USE_ATTRIBUTES', FALSE );
// RDF Serializer: Set to TRUE in order to sort the statements of a model before
// serializing them.
define('SER_SORT_MODEL', FALSE );
// RDF Serializer: Set to TRUE, if the serializer should use qualified names for RDF
// reserved words.
// NOTE: There is only one default namespace allowed within an XML document.
// Therefore if SER_RDF_QNAMES in is set to FALSE and you pass the parameter
// $xml_default_namespace to the method serialize() of class RdfSerializer,
// the model will be serialized as if SER_RDF_QNAMES were set to TRUE.
define('SER_RDF_QNAMES', TRUE );
// RDF Serializer: Set to TRUE, if the serializer should start documents with the
// xml declaration <?xml version="1.0" encoding="UTF-8" >.
define('SER_XML_DECLARATION', TRUE );
// N3 Serializer: Set to TRUE, if the N3 serializer should try to compress the blank node
// syntax using [] whereever possible.
define('N3SER_BNODE_SHORT', FALSE);
// RDF Serializer: Set to TRUE, if the serializer should write text values always as
// escaped CDATA.
define('USE_CDATA', FALSE);
define('USE_ANY_QUOTE', FALSE);
define('GENERAL_PREFIX_BASE','ns');
define('MAX_ALLOWED_ABBREVIATED_LENGTH',60);
// ----------------------------------------------------------------------------------
// Util
// ----------------------------------------------------------------------------------
// Definition of the colors used by the method RDFUtil:writeHTMLTable
define('HTML_TABLE_HEADER_COLOR', '#FFFFFF');
define('HTML_TABLE_RESOURCE_COLOR', '#FFFFCC');
define('HTML_TABLE_LITERAL_COLOR', '#E7E7EF');
define('HTML_TABLE_BNODE_COLOR', '#FFCCFF');
define('HTML_TABLE_RDF_NS_COLOR', '#CCFFCC');
define('HTML_TABLE_NS_ROW_COLOR1', '#FFFFFF');
define('HTML_TABLE_NS_ROW_COLOR0', '#E7E7EF');
// ----------------------------------------------------------------------------------
// RDF
// ----------------------------------------------------------------------------------
define('RDF_NAMESPACE_URI','http://www.w3.org/1999/02/22-rdf-syntax-ns#' );
define('RDF_NAMESPACE_PREFIX','rdf' );
define('RDF_RDF','RDF');
define('RDF_DESCRIPTION','Description');
define('RDF_ID','ID');
define('RDF_ABOUT','about');
define('RDF_ABOUT_EACH','aboutEach');
define('RDF_ABOUT_EACH_PREFIX','aboutEachPrefix');
define('RDF_BAG_ID','bagID');
define('RDF_RESOURCE','resource');
define('RDF_VALUE','value');
define('RDF_PARSE_TYPE','parseType');
define('RDF_PARSE_TYPE_LITERAL','Literal');
define('RDF_PARSE_TYPE_RESOURCE','Resource');
define('RDF_PARSE_TYPE_COLLECTION', 'Collection');
define('RDF_TYPE','type');
define('RDF_BAG','Bag');
define('RDF_SEQ','Seq');
define('RDF_ALT','Alt');
define('RDF_LI','li');
define('RDF_STATEMENT','Statement');
define('RDF_SUBJECT','subject');
define('RDF_PREDICATE','predicate');
define('RDF_OBJECT','object');
define('RDF_NODEID','nodeID');
define('RDF_DATATYPE','datatype');
define('RDF_SEEALSO','seeAlso');
define('RDF_PROPERTY','Property');
define('RDF_LIST','List');
define('RDF_NIL','nil');
define('RDF_REST','rest');
define('RDF_FIRST','first');
define('RDF_XMLLITERAL', 'XMLLiteral');
// ----------------------------------------------------------------------------------
// RDF Schema
// ----------------------------------------------------------------------------------
define('RDF_SCHEMA_URI','http://www.w3.org/2000/01/rdf-schema#' );
define('RDF_DATATYPE_SCHEMA_URI','http://www.w3.org/TR/xmlschema-2' );
define('RDF_SCHEMA_PREFIX', 'rdfs');
define('RDFS_SUBCLASSOF','subClassOf');
define('RDFS_SUBPROPERTYOF','subPropertyOf');
define('RDFS_RANGE','range');
define('RDFS_DOMAIN','domain');
define('RDFS_CLASS','Class');
define('RDFS_RESOURCE','Resource');
define('RDFS_DATATYPE','Datatype');
define('RDFS_LITERAL','Literal');
define('RDFS_SEE_ALSO','seeAlso');
define('RDFS_IS_DEFINED_BY','isDefinedBy');
define('RDFS_LABEL','label');
define('RDFS_COMMENT','comment');
// ----------------------------------------------------------------------------------
// OWL
// ----------------------------------------------------------------------------------
define('OWL_URI','http://www.w3.org/2002/07/owl#' );
define('OWL_PREFIX', 'owl');
define('OWL_SAME_AS','sameAs');
define('OWL_INVERSE_OF','inverseOf');
// ----------------------------------------------------------------------------------
// XML
// ----------------------------------------------------------------------------------
define('XML_NAMESPACE_PREFIX', 'xml');
define('XML_NAMESPACE_DECLARATION_PREFIX', 'xmlns');
define('XML_NAMESPACE_URI','http://www.w3.org/XML/1998/namespace' );
define('XML_LANG','lang');
define('DATATYPE_SHORTCUT_PREFIX','datatype:');
define('XML_SCHEMA','http://www.w3.org/2001/XMLSchema#');
// ----------------------------------------------------------------------------------
// RDF DATATYPE SHORTCUTS (extends datatype shortcuts to the full XML datatype URIs)
// ----------------------------------------------------------------------------------
$short_datatype = array(
'STRING' => RDF_DATATYPE_SCHEMA_URI . '#string',
'DECIMAL' => RDF_DATATYPE_SCHEMA_URI . '#decimal',
'INTEGER' => RDF_DATATYPE_SCHEMA_URI . '#integer',
'INT' => RDF_DATATYPE_SCHEMA_URI . '#int',
'SHORT' => RDF_DATATYPE_SCHEMA_URI . '#short',
'BYTE' => RDF_DATATYPE_SCHEMA_URI . '#byte',
'LONG' => RDF_DATATYPE_SCHEMA_URI . '#long',
'LANGUAGE' => RDF_DATATYPE_SCHEMA_URI . '#language',
'NAME' => RDF_DATATYPE_SCHEMA_URI . '#name'
);
// ----------------------------------------------------------------------------------
// Database
// ----------------------------------------------------------------------------------
if (!defined('ADODB_DB_DRIVER')) {
if (isset($GLOBALS['dbConf'])) {
define('ADODB_DB_DRIVER', $GLOBALS['dbConf']['type']);
define('ADODB_DB_HOST' , $GLOBALS['dbConf']['host']);
define('ADODB_DB_NAME' , $GLOBALS['dbConf']['database']);
define('ADODB_DB_USER' , $GLOBALS['dbConf']['user']);
define('ADODB_DB_PASSWORD', $GLOBALS['dbConf']['password']);
} else {
define('ADODB_DB_DRIVER', 'mysql');
define('ADODB_DB_HOST' , 'localhost');
define('ADODB_DB_NAME' , 'kbrdfdb');
define('ADODB_DB_USER' , 'kbrdf');
define('ADODB_DB_PASSWORD', 'db1');
}
}
if (!defined('ADODB_DEBUG_MODE')) {
define('ADODB_DEBUG_MODE', '0');
}
// ----------------------------------------------------------------------------------
// RDQL Error Messages
// ----------------------------------------------------------------------------------
define('RDQL_ERR','RDQL error ');
define('RDQL_SYN_ERR','RDQL syntax error ');
define('RDQL_SEL_ERR', RDQL_ERR .'in the SELECT clause: ');
define('RDQL_SRC_ERR', RDQL_ERR .'in the SOURCE clause: ');
define('RDQL_WHR_ERR', RDQL_ERR .'in the WHERE clause: ');
define('RDQL_AND_ERR', RDQL_ERR .'in the AND clause: ');
define('RDQL_USG_ERR', RDQL_ERR .'in the USING clause: ');
// ----------------------------------------------------------------------------------
// Vocabulary
// ----------------------------------------------------------------------------------
// namespace declarations
define('ATOM_NS' , 'http://purl.org/atom/ns#');
define('DC_NS' , 'http://purl.org/dc/elements/1.1/');
define('DCTERM_NS' , 'http://purl.org/dc/terms/');
define('DCMITYPE_NS', 'http://purl.org/dc/dcmitype/');
define('FOAF_NS' , 'http://xmlns.com/foaf/0.1/');
define('OWL_NS' , 'http://www.w3.org/2002/07/owl#');
define('RSS_NS' , 'http://purl.org/rss/1.0/');
define('VCARD_NS' , 'http://www.w3.org/2001/vcard-rdf/3.0#');
// ----------------------------------------------------------------------------------
// RDQL, SPARQL and parser default namespace prefixes
// ----------------------------------------------------------------------------------
global $default_prefixes;
$default_prefixes = array(
RDF_NAMESPACE_PREFIX => RDF_NAMESPACE_URI,
RDF_SCHEMA_PREFIX => RDF_SCHEMA_URI,
'xsd' => 'http://www.w3.org/2001/XMLSchema#',
OWL_PREFIX => OWL_URI,
'dc' => 'http://purl.org/dc/elements/1.1/',
'dcterms' => 'http://purl.org/dc/terms/',
'vcard' => 'http://www.w3.org/2001/vcard-rdf/3.0#'
);
// ----------------------------------------------------------------------------------
// InfModel
// ----------------------------------------------------------------------------------
//activate / deactivate reasoning for the following schema constructs
//rdfs:subclass
define('INF_RES_SUBCLASSOF',true);
//rdfs:subproperty
define('INF_RES_SUBPROPERTYOF',true);
//rdfs:range
define('INF_RES_RANGE',true);
//rdfs:domain
define('INF_RES_DOMAIN',true);
//owl:sameAs
define('INF_RES_OWL_SAMEAS',true);
//owl:inverseOf
define('INF_RES_OWL_INVERSEOF',true);
//generic RDFS Rules from the RDF Schema doc:
//see: http://www.w3.org/TR/2004/REC-rdf-mt-20040210/#RDFSRules
define('INF_RES_RULE_RDFS12',false);
define('INF_RES_RULE_RDFS6',false);
define('INF_RES_RULE_RDFS8',false);
define('INF_RES_RULE_RDFS10',false);
define('INF_RES_RULE_RDFS13',false);
// ----------------------------------------------------------------------------------
// GRAPHVIZ
// ----------------------------------------------------------------------------------
// path to the dot binary
define('GRAPHVIZ_PATH', 'C:\/Programme\/ATT\/Graphviz\/bin\/dot.exe');
// directory for temporary files
// Attention: must be write-/readable by the webserver
define('GRAPHVIZ_TEMP', 'C:\/');
// display statistical data in generated images
// currently only number of statements drawn
define('GRAPHVIZ_STAT', TRUE);
// allowed file formats
// for security reasons (to prevent code injection)
define('GRAPHVIZ_FORMAT', 'svg, dot, jpg, png, gif, vrml');
// enable clickable URIs
// only supported by certain formats (e.g. SVG)
define('GRAPHVIZ_URI', FALSE);
// define parameters for the graphical output
// if a paramter is undefined, the default value of graphviz is used
// for further information see: http://www.graphviz.org/Documentation.php
$graphviz_param = array(
'GRAPH_STYLE' => 'rankdir="TB"',
'RESOURCE_STYLE' => 'style="filled",color="#FFD800",fontname="Courier",fontsize="10"',
'LITERAL_STYLE' => 'shape="box",style="filled",color="#B7FFAF",fontname="Courier",fontsize="10"',
'PREDICATE_STYLE' => 'fontname="Courier",fontsize="10"',
'INFERRED_STYLE' => 'style="dotted",fontname="Courier",fontsize="10"',
'BLANKNODE_STYLE' => 'style="filled",color="#DDDDDD",fontname="Courier",fontsize="10"',
'BOX_STYLE' => 'fontname="Courier",fontsize="8",color="#BBBBBB"'
);
// ----------------------------------------------------------------------------------
// SPARQL
// ----------------------------------------------------------------------------------
// Attribute lists for describing Resources. ['resource type'] = array(att1, att2, att3, ...).
//
$sparql_describe = array(
FOAF_NS.'person' => array(FOAF_NS.'name',FOAF_NS.'homepage',FOAF_NS.'mbox')
);
?>

View File

@ -0,0 +1,71 @@
K 25
svn:wc:ra_dav:version-url
V 61
/svnroot/rdfapi-php/!svn/ver/486/trunk/rdfapi-php/api/dataset
END
Quad.php
K 25
svn:wc:ra_dav:version-url
V 70
/svnroot/rdfapi-php/!svn/ver/290/trunk/rdfapi-php/api/dataset/Quad.php
END
DatasetDb.php
K 25
svn:wc:ra_dav:version-url
V 75
/svnroot/rdfapi-php/!svn/ver/486/trunk/rdfapi-php/api/dataset/DatasetDb.php
END
NamedGraphDb.php
K 25
svn:wc:ra_dav:version-url
V 78
/svnroot/rdfapi-php/!svn/ver/290/trunk/rdfapi-php/api/dataset/NamedGraphDb.php
END
IteratorAllGraphsDb.php
K 25
svn:wc:ra_dav:version-url
V 85
/svnroot/rdfapi-php/!svn/ver/268/trunk/rdfapi-php/api/dataset/IteratorAllGraphsDb.php
END
IteratorFindQuadsDb.php
K 25
svn:wc:ra_dav:version-url
V 85
/svnroot/rdfapi-php/!svn/ver/290/trunk/rdfapi-php/api/dataset/IteratorFindQuadsDb.php
END
DatasetMem.php
K 25
svn:wc:ra_dav:version-url
V 76
/svnroot/rdfapi-php/!svn/ver/432/trunk/rdfapi-php/api/dataset/DatasetMem.php
END
Dataset.php
K 25
svn:wc:ra_dav:version-url
V 73
/svnroot/rdfapi-php/!svn/ver/344/trunk/rdfapi-php/api/dataset/Dataset.php
END
DatasetP.php
K 25
svn:wc:ra_dav:version-url
V 74
/svnroot/rdfapi-php/!svn/ver/340/trunk/rdfapi-php/api/dataset/DatasetP.php
END
NamedGraphMem.php
K 25
svn:wc:ra_dav:version-url
V 79
/svnroot/rdfapi-php/!svn/ver/425/trunk/rdfapi-php/api/dataset/NamedGraphMem.php
END
IteratorAllGraphsMem.php
K 25
svn:wc:ra_dav:version-url
V 86
/svnroot/rdfapi-php/!svn/ver/290/trunk/rdfapi-php/api/dataset/IteratorAllGraphsMem.php
END
IteratorFindQuadsMem.php
K 25
svn:wc:ra_dav:version-url
V 86
/svnroot/rdfapi-php/!svn/ver/432/trunk/rdfapi-php/api/dataset/IteratorFindQuadsMem.php
END

View File

@ -0,0 +1,171 @@
8
dir
556
https://rdfapi-php.svn.sourceforge.net/svnroot/rdfapi-php/trunk/rdfapi-php/api/dataset
https://rdfapi-php.svn.sourceforge.net/svnroot/rdfapi-php
2007-08-12T11:59:54.054541Z
486
cweiske
svn:special svn:externals svn:needs-lock
b2ee660e-c932-0410-bdee-d8da4d8102f4
Quad.php
file
2008-02-29T14:57:47.506256Z
82f6dad7f83ff7bd38e727dc9fa21e40
2006-06-22T12:23:24.000000Z
290
tgauss
has-props
DatasetDb.php
file
2008-02-29T14:57:47.521877Z
b8eb44f5819b99805c42748686f4577d
2007-08-12T11:59:54.054541Z
486
cweiske
has-props
NamedGraphDb.php
file
2008-02-29T14:57:47.521877Z
56e8ddd0d8aa0251664cda4114355b8c
2006-06-22T12:23:24.000000Z
290
tgauss
has-props
IteratorAllGraphsDb.php
file
2008-02-29T14:57:47.537498Z
59240fdfee65743297fc65a81f1f6f5a
2006-05-15T05:28:09.000000Z
268
tgauss
has-props
IteratorFindQuadsDb.php
file
2008-02-29T14:57:47.537498Z
ad64d93ddc73d832608fcbd14dd35e21
2006-06-22T12:23:24.000000Z
290
tgauss
has-props
DatasetMem.php
file
2008-02-29T14:57:47.553118Z
d396a0892728aa6223f01b1aecc96133
2007-05-01T15:58:57.000000Z
432
cweiske
has-props
Dataset.php
file
2008-02-29T14:57:47.553118Z
bf5304281853bf6676c4b6dc082700fe
2007-02-07T08:24:32.000000Z
344
cweiske
has-props
DatasetP.php
file
2008-02-29T14:57:47.568739Z
ca230297a71d4eaa77755fdacbee0704
2007-01-23T12:20:51.000000Z
340
cweiske
has-props
NamedGraphMem.php
file
2008-02-29T14:57:47.568739Z
c74e213a48c35e2a8d3301edd5ad8ded
2007-05-01T12:59:18.000000Z
425
cweiske
has-props
IteratorAllGraphsMem.php
file
2008-02-29T14:57:47.584359Z
f8e8a5f81b38bc833b72c24e7f23237a
2006-06-22T12:23:24.000000Z
290
tgauss
has-props
IteratorFindQuadsMem.php
file
2008-02-29T14:57:47.584359Z
705c6e4de4b5bc4c05baffb10a77e02e
2007-05-01T15:58:57.000000Z
432
cweiske
has-props

View File

@ -0,0 +1,5 @@
K 13
svn:eol-style
V 6
native
END

View File

@ -0,0 +1,5 @@
K 13
svn:eol-style
V 6
native
END

View File

@ -0,0 +1,5 @@
K 13
svn:eol-style
V 6
native
END

View File

@ -0,0 +1,5 @@
K 13
svn:eol-style
V 6
native
END

View File

@ -0,0 +1,5 @@
K 13
svn:eol-style
V 6
native
END

View File

@ -0,0 +1,5 @@
K 13
svn:eol-style
V 6
native
END

View File

@ -0,0 +1,5 @@
K 13
svn:eol-style
V 6
native
END

View File

@ -0,0 +1,89 @@
<?php
// ----------------------------------------------------------------------------------
// Class: Dataset
// ----------------------------------------------------------------------------------
/**
* Dataset implementation.
* Superclass of datasetMem and datasetDb which contains shared functionality.
*
* @version $Id$
* @author Daniel Westphal (http://www.d-westphal.de)
* @author Chris Bizer <chris@bizer.de>
*
* @package dataset
* @access public
**/
class Dataset
{
/**
* Load a Dataset from a File
*
* @param string
* @access public
*/
function loadFromFile($file)
{
$parser= new TriXParser($this);
$parser->parseFile($file);
}
/**
* Load a Datset from a string
*
* @param string
* @access public
*/
function loadFromString($string)
{
$parser= new TriXParser($this);
$parser->parseString($string);
}
/**
* Serialize the Dataset to File
*
* @param string
* @access public
*/
function serializeToFile($fileName)
{
$serializer= new TriXSerializer($this);
$serializer->serializeToFile($fileName);
}
/**
* Serialize the Dataset to string
*
* @return string
* @access public
*/
function serializeToString()
{
$serializer= new TriXSerializer($this);
return $serializer->serializeToString();
}
/**
* Performs a SPARQL query against an RDF Dataset.
* The result can be retrived in SPARQL Query Results XML Format or
* as an array containing the variables an their bindings.
*
* @param String $query the sparql query string
* @param String $resultform the result form ('xml' for SPARQL Query Results XML Format)
* @return String/array
*/
function sparqlQuery($query,$resultform = false){
include_once(RDFAPI_INCLUDE_DIR.PACKAGE_SPARQL);
$parser = new SparqlParser();
$q = $parser->parse($query);
$eng = SparqlEngine::factory();
return $eng->queryModel($this,$q,$resultform);
}
}
?>

View File

@ -0,0 +1,451 @@
<?php
require_once RDFAPI_INCLUDE_DIR . 'dataset/Dataset.php';
require_once RDFAPI_INCLUDE_DIR . 'model/DbModel.php';
require_once RDFAPI_INCLUDE_DIR . 'dataset/IteratorFindQuadsDb.php';
// ----------------------------------------------------------------------------------
// Class: DatasetDb
// ----------------------------------------------------------------------------------
/**
* Persistent implementation of a Dataset in a database.
* A RDF dataset is a collection of named RDF graphs.
*
* @version $Id$
* @author Daniel Westphal (http://www.d-westphal.de)
* @author Chris Bizer <chris@bizer.de>
*
* @package dataset
* @access public
**/
require_once(RDFAPI_INCLUDE_DIR.PACKAGE_DBASE);
class DatasetDb extends Dataset
{
/**
* Reference to databse connection.
*
* @var resource dbConnection
* @access private
*/
var $dbConnection;
/**
* Reference to the dbStore Object.
*
* @var $dbStore dbStore
* @access private
*/
var $dbStore;
/**
* Name of the Dataset
*
* @var string
* @access private
*/
var $setName;
/**
* Constructor
* You can supply a Dataset name.
*
* @param ADODBConnection
* @param DbStore
* @param string
* @access public
*/
function DatasetDb(&$dbConnection,&$dbStore,$datasetName)
{
$this->dbConnection=& $dbConnection;
$this->dbStore=&$dbStore;
$this->setName= $datasetName;
$this->_initialize();
}
/**
* Initialize
* Read all needed data into the set.
*
*
* @access private
*/
function _initialize()
{
$recordSet =& $this->dbConnection->execute("SELECT defaultModelUri
FROM datasets where datasetName='".$this->setName."'");
$this->defaultGraph=& $this->dbStore->getModel($recordSet->fields[0]);
}
// === Graph level methods ========================
/**
* Sets the Dataset name. Return true on success, false otherwise.
*
* @param string
* @access public
*/
function setDatasetName($datasetName)
{
if ($this->dbStore->datasetExists($datasetName))
return false;
$this->dbConnection->execute("UPDATE datasets SET datasetName='".$datasetName."'
where datasetName='".$this->setName."'");
$this->dbConnection->execute("UPDATE dataset_model SET datasetName='".$datasetName."'
where datasetName='".$this->setName."'");
$this->setName=$datasetName;
return true;
}
/**
* Returns the Datasets name.
*
* @return string
* @access public
*/
function getDatasetName()
{
return $this->setName;
}
/**
* Adds a NamedGraph to the set.
*
* @param NamedGraphDb
*/
function addNamedGraph(&$graph)
{
$graphNameURI=$graph->getGraphName();
$this->removeNamedGraph($graphNameURI);
$this->dbConnection->execute('INSERT INTO dataset_model VALUES('
. $this->dbConnection->qstr($this->setName) . ','
. $this->dbConnection->qstr($graph->modelID) . ','
. $this->dbConnection->qstr($graphNameURI) .')');
}
/**
* Overwrites the existting default graph.
*
* @param DbModel
*/
function setDefaultGraph(&$graph)
{
$this->dbConnection->execute('UPDATE datasets SET defaultModelUri ='
. $this->dbConnection->qstr($graph->modelURI) . ' WHERE datasetName ='
. $this->dbConnection->qstr($this->setName));
}
/**
* Returns a reference to the defaultGraph.
*
* @return NamedGraphDb
*/
function & getDefaultGraph()
{
$defaultGraphURI = $this->dbConnection->GetOne("SELECT defaultModelUri FROM datasets WHERE datasetName ='".$this->setName."'");
return ($this->dbStore->getNamedGraphDb($defaultGraphURI,'http://rdfapi-php/dataset_defaultGraph_'.$this->setName));
}
/**
* Returns true, if a defaultGraph exists. False otherwise.
*
* @return boolean
*/
function hasDefaultGraph()
{
return true;
}
/**
* Removes a NamedGraph from the set. Nothing happens
* if no graph with that name is contained in the set.
*
* @param string
*/
function removeNamedGraph($graphName)
{
$this->dbConnection->execute('DELETE FROM dataset_model WHERE datasetName="'
. $this->dbConnection->qstr($this->setName) . '" AND graphURI ="'
. $this->dbConnection->qstr($graphName) . '"');
}
/**
* Tells wether the Dataset contains a NamedGraph.
*
* @param string
* @return boolean
*/
function containsNamedGraph($graphName)
{
$count= $this->dbConnection->GetOne('SELECT count(*) FROM dataset_model WHERE datasetName="'.$this->setName.'" AND graphURI ="'.$graphName.'"');
return ($count>0);
}
/**
* Returns the NamedGraph with a specific name from the Dataset.
* Changes to the graph will be reflected in the set.
*
* @param string
* @return NamedGraphDb or null
*/
function &getNamedGraph($graphName)
{
if(!$this->containsNamedGraph($graphName))
return null;
$modelVars =& $this->dbConnection->execute("SELECT models.modelURI, models.modelID, models.baseURI
FROM models, dataset_model
WHERE dataset_model.graphURI ='" .$graphName ."' AND dataset_model.modelId= models.modelID");
return new NamedGraphDb($this->dbConnection, $modelVars->fields[0],
$modelVars->fields[1], $graphName ,$modelVars->fields[2]);
}
/**
* Returns the names of the namedGraphs in this set as strings in an array.
*
* @return Array
*/
function listGraphNames()
{
$recordSet =& $this->dbConnection->execute("SELECT graphURI FROM dataset_model WHERE datasetName ='".$this->setName."'");
$return=array();
while (!$recordSet->EOF)
{
$return[] = $recordSet->fields[0];
$recordSet->moveNext();
}
return $return;
}
/**
* Creates a new NamedGraph and adds it to the set. An existing graph with the same name will be replaced. But the old namedGraph remains in the database.
*
* @param string
* @param string
* @return NamedGraphDb
*/
function &createGraph($graphName,$baseURI = null)
{
$graph =& $this->dbStore->getNewNamedGraphDb(uniqid('http://rdfapi-php/namedGraph_'),$graphName,$baseURI);
$this->addNamedGraph($graph);
return $graph;
}
/**
* Deletes all NamedGraphs from the set.
*/
function clear()
{
$this->dbConnection->execute("DELETE FROM dataset_model WHERE datasetName ='".$this->setName."'");
}
/**
* Returns the number of NamedGraphs in the set. Empty graphs are counted.
*
* @return int
*/
function countGraphs()
{
return ($this->dbConnection->GetOne("SELECT count(*) FROM dataset_model WHERE datasetName ='".$this->setName."'"));
}
/**
* Returns an iterator over all {@link NamedGraph}s in the set.
*
* @return IteratorAllGraphsDb
*/
function &listNamedGraphs()
{
$recordSet =& $this->dbConnection->execute("SELECT graphURI FROM dataset_model WHERE datasetName ='".$this->setName."'");
$it = new IteratorAllGraphsDb($recordSet, $this);
return $it;
}
/**
* Tells wether the set contains any NamedGraphs.
*
* @return boolean
*/
function isEmpty()
{
return ($this->countGraphs()==0);
}
/**
* Add all named graphs of the other dataset to this dataset.
*
* @param Dataset
*/
function addAll($otherDataset)
{
for($iterator = $otherDataset->listNamedGraphs(); $iterator->valid(); $iterator->next())
{
$this->addNamedGraph($iterator->current());
};
if ($otherDataset->hasDefaultGraph())
{
$this->defaultGraph = $this->defaultGraph->unite($otherDataset->getDefaultGraph());
}
}
// === Quad level methods ========================
/**
* Adds a quad to the Dataset. The argument must not contain any
* wildcards. If the quad is already present, nothing happens. A new
* named graph will automatically be created if necessary.
*
* @param Quad
*/
function addQuad(&$quad)
{
$graphName=$quad->getGraphName();
$graphName=$graphName->getLabel();
$graph=& $this->getNamedGraph($graphName);
if ($graph===null)
$graph=& $this->createGraph($graphName);
$statement=$quad->getStatement();
$graph->add($statement);
}
/**
* Tells wether the Dataset contains a quad or
* quads matching a pattern.
*
* @param Resource
* @param Resource
* @param Resource
* @param Resource
* @return boolean
*/
function containsQuad($graphName,$subject,$predicate,$object)
{
// static part of the sql statement
$sql = "SELECT count(*)
FROM statements, dataset_model
WHERE datasetName ='".$this->setName."' AND statements.modelID=dataset_model.modelId ";
if($graphName!=null)
{
$sql.= " AND graphURI ='".$graphName->getLabel()."'";
}
// dynamic part of the sql statement
$sql .= DbModel::_createDynSqlPart_SPO($subject, $predicate, $object);
return (($this->dbConnection->GetOne($sql))>0);
}
/**
* Deletes a Quad from the RDF dataset.
*
* @param Quad
*/
function removeQuad($quad)
{
$graphName=$quad->getGraphName();$graphName=$graphName->getLabel();
//find namedGraph IDs
$graphID = $this->dbConnection->GetOne("SELECT modelId FROM dataset_model WHERE graphURI ='$graphName'");
// static part of the sql statement
$sql = "DELETE FROM statements WHERE modelID = $graphID";
// dynamic part of the sql statement
$sql .= DbModel::_createDynSqlPart_SPO($quad->getSubject(), $quad->getPredicate(), $quad->getObject());
// execute the query
if($graphID)
$recordSet =& $this->dbConnection->execute($sql);
}
/**
* Counts the Quads in the RDF dataset. Identical Triples in
* different NamedGraphs are counted individually.
*
* @return int
*/
function countQuads()
{
$sql = "SELECT count(*)
FROM statements, dataset_model
WHERE datasetName ='".$this->setName."' AND statements.modelID=dataset_model.modelId ";
return ((int)$this->dbConnection->GetOne($sql));
}
/**
* Finds Statements that match a quad pattern. The argument may contain
* wildcards.
*
* @param Resource or null
* @param Resource or null
* @param Resource or null
* @param Resource or null
* @return IteratorFindQuadsDb
*/
function &findInNamedGraphs($graphName,$subject,$predicate,$object,$returnAsTriples =false )
{
// static part of the sql statement
$sql = "SELECT subject, predicate, object, l_language, l_datatype, subject_is, object_is, dataset_model.graphURI
FROM statements, dataset_model
WHERE datasetName ='".$this->setName."' AND statements.modelID=dataset_model.modelId ";
if($graphName!=null)
{
$sql.= " AND graphURI ='".$graphName->getLabel()."'";
}
// dynamic part of the sql statement
$sql .= DbModel::_createDynSqlPart_SPO($subject, $predicate, $object);
// execute the query
$recordSet =& $this->dbConnection->execute($sql);
$it = new IteratorFindQuadsDb($recordSet, $this, $returnAsTriples);
return $it;
}
/**
* Finds Statements that match a pattern in the default Graph. The argument may contain
* wildcards.
*
* @param Resource or null
* @param Resource or null
* @param Resource or null
* @return IteratorFindQuadsDb
*/
function &findInDefaultGraph($subject,$predicate,$object)
{
$defaultGraphID = (int)$this->dbConnection->GetOne("SELECT models.modelID FROM datasets, models WHERE datasets.datasetName ='".$this->setName."' AND datasets.defaultModelUri = models.modelURI");
// static part of the sql statement
$sql = "SELECT subject, predicate, object, l_language, l_datatype, subject_is, object_is
FROM statements
WHERE modelID ='$defaultGraphID'";
// dynamic part of the sql statement
$sql .= DbModel::_createDynSqlPart_SPO($subject, $predicate, $object);
// execute the query
$recordSet =& $this->dbConnection->execute($sql);
$it = new IteratorFindQuadsDb($recordSet, $this, true);
return $it;
}
}
?>

View File

@ -0,0 +1,394 @@
<?php
require_once RDFAPI_INCLUDE_DIR . 'dataset/Dataset.php';
require_once RDFAPI_INCLUDE_DIR . 'dataset/NamedGraphMem.php';
require_once RDFAPI_INCLUDE_DIR . 'model/MemModel.php';
// ----------------------------------------------------------------------------------
// Class: DatasetMem
// ----------------------------------------------------------------------------------
/**
* In-memory implementation of a RDF dataset.
* A RDF dataset set is a collection of named RDF graphs.
*
* @version $Id$
* @author Daniel Westphal (http://www.d-westphal.de)
* @author Chris Bizer <chris@bizer.de>
*
* @package dataset
* @access public
**/
class DatasetMem extends Dataset
{
/**
* Reference to a Memmodel that holds the default graph.
*
* @var resource Memmodel
* @access private
*/
var $defaultGraph;
/**
* Name of the DatasetMem.
*
* @var string
* @access private
*/
var $setName;
/**
* List of all NamedGraphs.
*
* @var array
* @access private
*/
var $graphs=array();
/**
* Constructor.
* You can supply a Dataset name.
*
* @param string
* @access public
*/
function DatasetMem($datasetName = null)
{
$this->setDatasetName($datasetName);
$this->defaultGraph=new MemModel();
}
// === Graph level methods ========================
/**
* Sets the Datasets name.
*
* @param string
* @access public
*/
function setDatasetName($datasetName)
{
$this->setName=$datasetName;
}
/**
* Returns the Datasets name.
*
* @return string
* @access public
*/
function getDatasetName()
{
return $this->setName;
}
/**
* Adds a NamedGraph to the set. Will replace a NamedGraph with the same name that is already in the set.
*
* @param NamedGraphMem
*/
function addNamedGraph(&$graph)
{
$graphNameURI=$graph->getGraphName();
$this->graphs[$graphNameURI]=&$graph;
}
/**
* Overwrites the existting default graph.
*
* @param MemModel
*/
function setDefaultGraph(&$graph)
{
$this->defaultGraph=&$graph;
}
/**
* Returns a reference to the defaultGraph
* @return Model
*/
function &getDefaultGraph()
{
return $this->defaultGraph;
}
/**
* Returns true, if an defaultGraph exists. False otherwise .
*
* @return boolean
*/
function hasDefaultGraph()
{
return $this->defaultGraph != null;
}
/**
* Removes a NamedGraph from the set. Nothing happens
* if no graph with that name is contained in the set.
*
* @param string
*/
function removeNamedGraph($graphName)
{
unset($this->graphs[$graphName]);
}
/**
* Tells wether the Dataset contains a NamedGraph.
*
* @param string
* @return boolean
*/
function containsNamedGraph($graphName)
{
return isset($this->graphs[$graphName]) === true;
}
/**
* Returns the NamedGraph with a specific name from the Dataset.
* Changes to the graph will be reflected in the set.
*
* @param string
* @return NamedGraphMem or NULL
*/
function &getNamedGraph($graphName)
{
if (!isset($this->graphs[$graphName])) return NULL;
return $this->graphs[$graphName];
}
/**
* Returns the names of the namedGraphs in this set as strings in an array.
*
* @return Array
*/
function listGraphNames()
{
return array_keys($this->graphs);
}
/**
* Creates a new NamedGraph and adds it to the set. An existing
* graph with the same name will be replaced.The name of the NamedGraph to be created ; must be an URI
*
* @param string
* @param string
* @return NamedGraphMem
*/
function &createGraph($graphName,$baseURI = null)
{
$this->graphs[$graphName]=new NamedGraphMem($graphName,$baseURI);
return $this->getNamedGraph($graphName);
}
/**
* Deletes all NamedGraphs from the set.
*/
function clear()
{
$this->graphs = array();
}
/**
* Returns the number of NamedGraphs in the set. Empty graphs
* are counted.
*
* @return int
*/
function countGraphs()
{
return count($this->graphs);
}
/**
* Returns the NamedGraph with a specific offset in the dataset.
* Changes to the graph will be reflected in the set.
*
* @param int
* @return NamedGraphMem or null
* @access private
*/
function &getGraphWithOffset($offset)
{
$i=0;
foreach ($this->graphs as $graph)
{
if (($i++)==$offset)
return $graph;
}
$n = null;
return $n;
}
/**
* Returns an iterator over all {@link NamedGraph}s in the set.
*
* @return IteratorAllGraphsMem
*/
function &listNamedGraphs()
{
require_once RDFAPI_INCLUDE_DIR . 'dataset/IteratorAllGraphsMem.php';
$m = new IteratorAllGraphsMem($this);
return $m;
}
/**
* Tells wether the set contains any NamedGraphs.
*
* @return boolean
*/
function isEmpty()
{
return $this->countGraphs() == 0;
}
/**
* Adds all named graphs of the other dataset to this dataset.
*
* @param Dataset
*/
function addAll($otherDataset)
{
for($iterator = $otherDataset->listNamedGraphs(); $iterator->valid(); $iterator->next())
{
$current=$iterator->current();
$this->graphs[$current->getGraphName()]=$current;
}
if ($otherDataset->hasDefaultGraph())
{
$this->defaultGraph = $this->defaultGraph->unite($otherDataset->getDefaultGraph());
}
}
// === Quad level methods ========================
/**
* Adds a quad to the Dataset. The argument must not contain any
* wildcards. If the quad is already present, nothing happens. A new
* named graph will automatically be created if necessary.
*
* @param Quad
*/
function addQuad(&$quad)
{
$graphName=$quad->getGraphName();
if ($this->containsNamedGraph($graphName->getLabel())===false)
$this->createGraph($graphName->getLabel());
$this->graphs[$graphName->getLabel()]->add($quad->getStatement());
}
/**
* Tells wether the Dataset contains a quad or
* quads matching a pattern.
*
* @param Resource $graphName
* @param Resource $subject
* @param Resource $predicate
* @param Resource $object
* @return boolean
*/
function containsQuad($graphName,$subject,$predicate,$object)
{
if($graphName!=null)
{
if ($this->containsNamedGraph($graphName->getLabel())!==true)
return false;
return ($this->graphs[$graphName->getLabel()]->findFirstMatchingStatement($subject,$predicate,$object)!=null);
}
foreach ($this->graphs as $graph)
{
if ($graph->findFirstMatchingStatement($subject,$predicate,$object)!=null)
return true;
};
return false;
}
/**
* Deletes a Quad from the RDF dataset.
*
* @param Quad
*/
function removeQuad($quad)
{
$graphName=$quad->getGraphName();
if($graphName!=null)
{
if ($this->containsNamedGraph($graphName->getLabel())!==true)
return;
return ($this->graphs[$graphName->getLabel()]->remove($quad->getStatement())!=null);
}
foreach ($this->graphs as $graph)
{
$graph->remove($quad->getStatement());
};
}
/**
* Counts the Quads in the RDF dataset. Identical Triples in
* different NamedGraphs are counted individually.
*
* @return int
*/
function countQuads()
{
$count=0;
foreach ($this->graphs as $graph)
{
$count+=$graph->size();
}
return $count;
}
/**
* Finds Statements that match a quad pattern. The argument may contain
* wildcards.
*
* @param Resource or Null
* @param Resourceor Null
* @param Resource or Null
* @param Resource or Null
* @return Iterator
*/
function &findInNamedGraphs($graph,$subject,$predicate,$object,$returnAsTriples = false)
{
if ($graph!=null)
{
$findGraph=&$this->getNamedGraph($graph->getLabel());
if($findGraph==null)
$findGraph=new MemModel();
return $findGraph->iterFind($subject,$predicate,$object);
}
require_once RDFAPI_INCLUDE_DIR . 'dataset/IteratorFindQuadsMem.php';
$m = new IteratorFindQuadsMem($subject,$predicate,$object,$this->listNamedGraphs(),$returnAsTriples);
return $m;
}
/**
* Finds Statements that match a pattern in the default Graph. The argument may contain
* wildcards.
*
* @param Resource or Null
* @param Resource or Null
* @param Resource or Null
* @return Iterator
*/
function &findInDefaultGraph($subject,$predicate,$object)
{
return $this->defaultGraph->iterFind($subject,$predicate,$object);
}
}
?>

View File

@ -0,0 +1,25 @@
<?php
// ----------------------------------------------------------------------------------
// dataset Package
// ----------------------------------------------------------------------------------
//
// Description : dataset package
//
// Author: Daniel Westphal <http://www.d-westphal.de>
//
// ----------------------------------------------------------------------------------
// Include ResModel classes
require_once( RDFAPI_INCLUDE_DIR . 'dataset/Dataset.php');
require_once( RDFAPI_INCLUDE_DIR . 'dataset/DatasetMem.php');
require_once( RDFAPI_INCLUDE_DIR . 'dataset/DatasetDb.php');
require_once( RDFAPI_INCLUDE_DIR . 'dataset/NamedGraphMem.php');
require_once( RDFAPI_INCLUDE_DIR . 'dataset/NamedGraphDb.php');
require_once( RDFAPI_INCLUDE_DIR . 'dataset/IteratorAllGraphsMem.php');
require_once( RDFAPI_INCLUDE_DIR . 'dataset/IteratorAllGraphsDb.php');
require_once( RDFAPI_INCLUDE_DIR . 'dataset/Quad.php');
require_once( RDFAPI_INCLUDE_DIR . 'dataset/IteratorFindQuadsMem.php');
require_once( RDFAPI_INCLUDE_DIR . 'dataset/IteratorFindQuadsDb.php');
require_once( RDFAPI_INCLUDE_DIR . 'syntax/TriXParser.php');
require_once( RDFAPI_INCLUDE_DIR . 'syntax/TriXSerializer.php');
?>

View File

@ -0,0 +1,127 @@
<?php
//----------------------------------------------------------------------------------
// Class: IteratorAllGraphsDb
//----------------------------------------------------------------------------------
/**
* Implementation of a Graph iterator.
*
* This Iterator should be used in a for-loop like:
* for($iterator = $dataset->listGraphs(); $iterator->valid(); $iterator->next())
* {
* $currentResource=$iterator->current();
* };
*
* @version $Id$
* @author Daniel Westphal <mail at d-westphal dot de>
*
*
* @package dataset
* @access public
**/
class IteratorAllGraphsDb
{
/**
* Holds a reference to the associated DB resultSet
* @var $dbResultSets ADODB result
* @access private
*/
var $dbResultSet;
/**
* Holds a reference to the associated datasetDb
* @var datasetDb
* @access private
*/
var $datasetDb;
/**
* The current position
* @var integer
* @access private
*/
var $key;
/**
* The current NamedGraph
* @var obejct NamedGraph
* @access private
*/
var $current;
/**
* Constructor.
*
*
* @param ADODBResultSet
* @param DatasetDb
* @access public
*/
function IteratorAllGraphsDb(&$dbResultSet,&$datasetDb)
{
$this->dbResultSet=& $dbResultSet;
$this->datasetDb=& $datasetDb;
$this->current = $this->dbResultSet->fields[0];
}
/**
* Resets iterator list to start
*
* @access public
*/
function rewind()
{
//not supported
}
/**
* Says if there are additional items left in the list
*
* @return boolean
* @access public
*/
function valid()
{
return (!$this->dbResultSet->EOF);
}
/**
* Moves Iterator to the next item in the list
*
* @access public
*/
function next()
{
$this->dbResultSet->moveNext();
$this->current = $this->dbResultSet->fields[0];
}
/**
* Returns the current item
*
* @return mixed
* @access public
*/
function &current()
{
return ($this->datasetDb->getNamedGraph($this->current));
}
/**
* Returns the key of the current item
*
* @return integer
* @access public
*/
function key()
{
return $this->dbResultSet->_currentRow;
}
}
?>

View File

@ -0,0 +1,125 @@
<?php
// ----------------------------------------------------------------------------------
// Class: IteratorAllGraphsMem
// ----------------------------------------------------------------------------------
/**
* Implementation of a Graph iterator.
*
* This Iterator should be used in a for-loop like:
* for($iterator = $dataset->listGraphs(); $iterator->valid(); $iterator->next())
* {
* $currentResource=$it->current();
* };
*
* @version $Id$
* @author Daniel Westphal <mail at d-westphal dot de>
*
*
* @package dataset
* @access public
**/
class IteratorAllGraphsMem
{
/**
* Holds a reference to the associated RDF dataset
*
* @var object dataset
* @access private
*/
var $associatedGraphSet;
/**
* The current position
*
* @var integer
* @access private
*/
var $key;
/**
* If the current resource is valid
*
* @var boolean
* @access private
*/
var $valid;
/**
* The current NamedGraph
*
* @var obejct NamedGraph
* @access private
*/
var $current;
/**
* Constructor.
*
* @param dataset
* @access public
*/
function IteratorAllGraphsMem(&$namedGraphSet)
{
$this->associatedGraphSet=&$namedGraphSet;
$this->rewind();
}
/**
* Resets iterator list to start
*
* @access public
*/
function rewind()
{
$this->key = -1;
$this->next();
}
/**
* Says if there are additional items left in the list.
*
* @return boolean
* @access public
*/
function valid()
{
return $this->valid;
}
/**
* Moves Iterator to the next item in the list.
*
* @access public
*/
function next()
{
$this->current = &$this->associatedGraphSet->getGraphWithOffset(++$this->key);
$this->valid=($this->current!=NULL);
}
/**
* Returns the current item.
*
* @return mixed
* @access public
*/
function &current()
{
return $this->current;
}
/**
* Returns the key of the current item.
*
* @return integer
* @access public
*/
function key()
{
return $this->key;
}
}
?>

View File

@ -0,0 +1,145 @@
<?php
//----------------------------------------------------------------------------------
// Class: IteratorFindQuadsDb
// ----------------------------------------------------------------------------------
/**
* Implementation of a quad iterator.
*
* This Iterator should be used like:
* for($iterator = $dataset->findInNamedGraphs(null,null,null,null); $iterator->valid(); $iterator->next())
* {
* $currentQuad=$iterator->current();
* };
*
*
* @version $Id$
* @author Daniel Westphal (http://www.d-westphal.de)
*
*
* @package dataset
* @access public
**/
class IteratorFindQuadsDb
{
/**
* Holds a reference to the associated DB resultSet.
*
* @var $dbResultSets ADODB result
* @access private
*/
var $dbResultSet;
/**
* Holds a reference to the associated datasetDb.
*
* @var $datasetDb datasetDb
* @access private
*/
var $datasetDb;
/**
* boolean value, if the results should be returned as triples.
*
* @var boolean
* @access private
*/
var $returnAsTriples;
/**
* Constructor.
*
* @param dataset
* @access public
*/
function IteratorFindQuadsDb(&$dbResultSet,&$datasetDb,$returnAsTriples=false)
{
$this->dbResultSet=& $dbResultSet;
$this->datasetDb=& $datasetDb;
$this->returnAsTriples=$returnAsTriples;
}
/**
* Resets iterator list to start.
*
* @access public
*/
function rewind()
{
//not supported
}
/**
* Says if there are additional items left in the list.
*
* @return boolean
* @access public
*/
function valid()
{
if (($this->dbResultSet ===false) OR ($this->dbResultSet->EOF) )
return false;
return true;
}
/**
* Moves Iterator to the next item in the list.
*
* @access public
*/
function next()
{
if ($this->dbResultSet!==false)
$this->dbResultSet->moveNext();
}
/**
* Returns the current item.
*
* @return mixed
* @access public
*/
function &current()
{
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));
}
/**
* Returns the key of the current item.
*
* @return integer
* @access public
*/
function key()
{
return $this->dbResultSet->_currentRow;
}
}
?>

View File

@ -0,0 +1,217 @@
<?php
require_once RDFAPI_INCLUDE_DIR . 'dataset/Quad.php';
// ----------------------------------------------------------------------------------
// Class: IteratorFindQuadsMem
// ----------------------------------------------------------------------------------
/**
* Implementation of a quad iterator.
*
* This Iterator should be used like:
* for($iterator = $dataset->findInNamedGraphs(null,null,null,null); $iterator->valid(); $iterator->next())
* {
* $currentQuad=$it->current();
* };
*
* @version $Id$
* @author Daniel Westphal (http://d-westphal.de)
*
*
* @package dataset
* @access public
**/
class IteratorFindQuadsMem
{
/**
* key value in the current graph.
*
* @var dataset
* @access private
*/
var $graphKey;
/**
* boolean value, if the results should be returned as triples.
*
* @var boolean
* @access private
*/
var $returnAsTriples;
/**
* The current position.
*
* @var integer
* @access private
*/
var $key;
/**
* If the current resource is valid.
*
* @var boolean
* @access private
*/
var $valid;
/**
* The current NamedGraph.
*
* @var NamedGraph
* @access private
*/
var $current;
/**
* The graphName Resource to search for.
*
* @var string
* @access private
*/
var $findGraphName;
/**
* The subject Resource to search for.
*
* @var string
* @access private
*/
var $findSubject;
/**
* The predicate Resource to search for.
*
* @var string
* @access private
*/
var $findPredicate;
/**
* The object Resource to search for.
*
* @var string
* @access private
*/
var $findObject;
/**
* Iterator over all graphs of the RDF dataset.
*
* @var string
* @access private
*/
var $graphIterator;
/**
* Constructor.
*
* $subject, $predicate, and $object are used like find().
* $getSPO supports the strings 's', 'p', and 'o' to return
* either the subject, predicate, or object of the result statements.
*
*
* @param Resource
* @param Resource
* @param Resource
* @param dataset
* @param Boolean
* @access public
*/
function IteratorFindQuadsMem($subject,$predicate,$object,&$graphIterator, $returnAsTriples=false)
{
$this->findSubject=$subject;
$this->findPredicate=$predicate;
$this->findObject=$object;
$this->graphIterator=&$graphIterator;
$this->rewind();
$this->returnAsTriples=$returnAsTriples;
}
/**
* Resets iterator list to start.
*
* @access public
*/
function rewind()
{
$this->graphIterator->rewind();
$this->key = -1;
$this->graphKey=-1;
$this->next();
}
/**
* Says if there are additional items left in the list.
*
* @return boolean
* @access public
*/
function valid()
{
return $this->valid;
}
/**
* Moves Iterator to the next item in the list.
*
* @access public
*/
function next()
{
if($this->graphIterator->valid()===false)
{
$this->valid=false;
return;
}
$currentGraph=&$this->graphIterator->current();
$this->current= $currentGraph->findFirstMatchingStatement($this->findSubject,$this->findPredicate,$this->findObject,++$this->graphKey);
if($this->current==null)
{
do
{
$this->graphIterator->next();
if($this->graphIterator->valid()===false)
{
$this->valid=false;
return;
}
$currentGraph=&$this->graphIterator->current();
$this->graphKey=-1;
$this->current= $currentGraph->findFirstMatchingStatement($this->findSubject,$this->findPredicate,$this->findObject,++$this->graphKey);
} while ($this->current==null);
}
$this->key++;
$this->valid=true;
}
/**
* Returns the current item.
*
* @return mixed
* @access public
*/
function current()
{
if($this->returnAsTriples) return $this->current;
$currentGraph=&$this->graphIterator->current();
return new Quad(new Resource($currentGraph->getGraphName()),$this->current->getSubject(),$this->current->getPredicate(),$this->current->getObject());
}
/**
* Returns the key of the current item.
*
* @return integer
* @access public
*/
function key()
{
return $this->key;
}
}
?>

View File

@ -0,0 +1,70 @@
<?php
// ----------------------------------------------------------------------------------
// Class: NamedGraphDb
// ----------------------------------------------------------------------------------
/**
* Persistent NamedGraph implementation that extends a {@link DbModel}.
* The graphName is not stored in the database. As soon as the namedGraph is added
* to a RDF dataset the graphName is saved.
*
* @version $Id$
* @author Daniel Westphal (http://www.d-westphal.de)
*
* @package dataset
* @access public
**/
class NamedGraphDb extends DbModel
{
/**
* Name of the NamedGraphDb
*
* @var string
* @access private
*/
var $graphName;
/**
* Constructor
* Do not call this directly.
* Use the method getModel,getNewModel or putModel of the Class NamedGraphDb instead.
*
* @param ADODBConnection
* @param string
* @param string
* @param string
* @access public
*/
function NamedGraphDb(&$dbConnection, $modelURI, $modelID,$graphName, $baseURI=NULL)
{
$this->dbConn =& $dbConnection;
$this->modelURI = $modelURI;
$this->modelID = $modelID;
$this->baseURI = $this->_checkBaseURI($baseURI);
$this->graphName = $graphName;
}
/**
* Sets the graph name.
*
* @param string
* @access public
*/
function setGraphName($graphName)
{
$this->graphName=$graphName;
}
/**
* Returns the graph name.
*
* @return string
* @access public
*/
function getGraphName()
{
return $this->graphName;
}
}
?>

View File

@ -0,0 +1,66 @@
<?php
require_once RDFAPI_INCLUDE_DIR . 'model/MemModel.php';
// ----------------------------------------------------------------------------------
// Class: NamedGraphMem
// ----------------------------------------------------------------------------------
/**
* NamedGraph implementation that extends a {@link MemModel}
* with a name.
*
* @version $Id$
* @author Daniel Westphal <http://www.d-westphal.de>
*
* @package dataset
* @access public
**/
class NamedGraphMem extends MemModel
{
/**
* Name of the NamedGraphMem.
*
* @var string
* @access private
*/
var $graphName;
/**
* Constructor
* You have to supply a graph name. You can supply a URI.
*
* @param string
* @param string
* @access public
*/
function NamedGraphMem($graphName,$baseURI = null)
{
$this->setBaseURI($baseURI);
$this->indexed = INDEX_TYPE;
$this->setGraphName($graphName);
}
/**
* Sets the graph name.
*
* @param string
* @access public
*/
function setGraphName($graphName)
{
$this->graphName=$graphName;
}
/**
* Returns the graph name.
*
* @return string
* @access public
*/
function getGraphName()
{
return $this->graphName;
}
}
?>

View File

@ -0,0 +1,147 @@
<?php
// ----------------------------------------------------------------------------------
// Class: Quad
// ----------------------------------------------------------------------------------
/**
*
* A Triple in a RDF dataset, consisting of four Jena Nodes: graphName,
* subject, predicate, and object.
*
* @version $Id$
* @author Daniel Westphal (http://www.d-westphal.de)
*
* @package dataset
* @access public
**/
class Quad
{
/**
* Name of the NamedGraphMem.
*
* @var Resource
* @access private
*/
var $graphName;
/**
* Statement
*
* @var Statement
* @access private
*/
var $statement;
/**
* Constructor
* Creates a Quad from four Nodes.
*
* @param Resource
* @param Resource
* @param Resource
* @param Resource
* @access public
*/
function Quad($graphName,$subject,$predicate,$object)
{
if (!is_a($graphName, 'Resource'))
{
$errmsg = RDFAPI_ERROR .
'(class: Quad; method: new): Resource expected as graphName.';
trigger_error($errmsg, E_USER_ERROR);
}
$this->statement=new Statement($subject,$predicate,$object);
$this->graphName=$graphName;
}
/**
* Sets the graph name.
*
* @param Resource
* @access public
*/
function setGraphName($graphName)
{
$this->graphName=$graphName;
}
/**
* Returns the graph name.
*
* @return Resource
* @access public
*/
function getGraphName()
{
return $this->graphName;
}
/**
* Return a human-readable (sort of) string "graphname { s p o . }"
* describing the quad.
*
* @return string
*/
function toString()
{
return 'GraphName('.$this->graphName->getLabel().') '.$this->statement->toString();
}
/**
* Returns the subject.
*
* @return Resource
* @access public
*/
function getSubject()
{
return $this->statement->getSubject();
}
/**
* Returns the predicate.
*
* @return Resource
* @access public
*/
function getPredicate()
{
return $this->statement->getPredicate();
}
/**
* Returns the object.
*
* @return Resource
* @access public
*/
function getObject()
{
return $this->statement->getObject();
}
/**
* Returns the statement(subject,predicate,object).
*
* @return statement
* @access public
*/
function getStatement()
{
return $this->statement;
}
/**
* Checks if two quads are equal.
*
* @param Quad
* @return boolean
* @access public
*/
function equals($quad)
{
return ($this->graphName->equals($quad->getGraphName()) && $this->statement->equals($quad->getStatement()));
}
}
?>

View File

@ -0,0 +1,89 @@
<?php
// ----------------------------------------------------------------------------------
// Class: Dataset
// ----------------------------------------------------------------------------------
/**
* Dataset implementation.
* Superclass of datasetMem and datasetDb which contains shared functionality.
*
* @version $Id$
* @author Daniel Westphal (http://www.d-westphal.de)
* @author Chris Bizer <chris@bizer.de>
*
* @package dataset
* @access public
**/
class Dataset
{
/**
* Load a Dataset from a File
*
* @param string
* @access public
*/
function loadFromFile($file)
{
$parser= new TriXParser($this);
$parser->parseFile($file);
}
/**
* Load a Datset from a string
*
* @param string
* @access public
*/
function loadFromString($string)
{
$parser= new TriXParser($this);
$parser->parseString($string);
}
/**
* Serialize the Dataset to File
*
* @param string
* @access public
*/
function serializeToFile($fileName)
{
$serializer= new TriXSerializer($this);
$serializer->serializeToFile($fileName);
}
/**
* Serialize the Dataset to string
*
* @return string
* @access public
*/
function serializeToString()
{
$serializer= new TriXSerializer($this);
return $serializer->serializeToString();
}
/**
* Performs a SPARQL query against an RDF Dataset.
* The result can be retrived in SPARQL Query Results XML Format or
* as an array containing the variables an their bindings.
*
* @param String $query the sparql query string
* @param String $resultform the result form ('xml' for SPARQL Query Results XML Format)
* @return String/array
*/
function sparqlQuery($query,$resultform = false){
include_once(RDFAPI_INCLUDE_DIR.PACKAGE_SPARQL);
$parser = new SparqlParser();
$q = $parser->parse($query);
$eng = SparqlEngine::factory();
return $eng->queryModel($this,$q,$resultform);
}
}
?>

View File

@ -0,0 +1,451 @@
<?php
require_once RDFAPI_INCLUDE_DIR . 'dataset/Dataset.php';
require_once RDFAPI_INCLUDE_DIR . 'model/DbModel.php';
require_once RDFAPI_INCLUDE_DIR . 'dataset/IteratorFindQuadsDb.php';
// ----------------------------------------------------------------------------------
// Class: DatasetDb
// ----------------------------------------------------------------------------------
/**
* Persistent implementation of a Dataset in a database.
* A RDF dataset is a collection of named RDF graphs.
*
* @version $Id$
* @author Daniel Westphal (http://www.d-westphal.de)
* @author Chris Bizer <chris@bizer.de>
*
* @package dataset
* @access public
**/
require_once(RDFAPI_INCLUDE_DIR.PACKAGE_DBASE);
class DatasetDb extends Dataset
{
/**
* Reference to databse connection.
*
* @var resource dbConnection
* @access private
*/
var $dbConnection;
/**
* Reference to the dbStore Object.
*
* @var $dbStore dbStore
* @access private
*/
var $dbStore;
/**
* Name of the Dataset
*
* @var string
* @access private
*/
var $setName;
/**
* Constructor
* You can supply a Dataset name.
*
* @param ADODBConnection
* @param DbStore
* @param string
* @access public
*/
function DatasetDb(&$dbConnection,&$dbStore,$datasetName)
{
$this->dbConnection=& $dbConnection;
$this->dbStore=&$dbStore;
$this->setName= $datasetName;
$this->_initialize();
}
/**
* Initialize
* Read all needed data into the set.
*
*
* @access private
*/
function _initialize()
{
$recordSet =& $this->dbConnection->execute("SELECT defaultModelUri
FROM datasets where datasetName='".$this->setName."'");
$this->defaultGraph=& $this->dbStore->getModel($recordSet->fields[0]);
}
// === Graph level methods ========================
/**
* Sets the Dataset name. Return true on success, false otherwise.
*
* @param string
* @access public
*/
function setDatasetName($datasetName)
{
if ($this->dbStore->datasetExists($datasetName))
return false;
$this->dbConnection->execute("UPDATE datasets SET datasetName='".$datasetName."'
where datasetName='".$this->setName."'");
$this->dbConnection->execute("UPDATE dataset_model SET datasetName='".$datasetName."'
where datasetName='".$this->setName."'");
$this->setName=$datasetName;
return true;
}
/**
* Returns the Datasets name.
*
* @return string
* @access public
*/
function getDatasetName()
{
return $this->setName;
}
/**
* Adds a NamedGraph to the set.
*
* @param NamedGraphDb
*/
function addNamedGraph(&$graph)
{
$graphNameURI=$graph->getGraphName();
$this->removeNamedGraph($graphNameURI);
$this->dbConnection->execute('INSERT INTO dataset_model VALUES('
. $this->dbConnection->qstr($this->setName) . ','
. $this->dbConnection->qstr($graph->modelID) . ','
. $this->dbConnection->qstr($graphNameURI) .')');
}
/**
* Overwrites the existting default graph.
*
* @param DbModel
*/
function setDefaultGraph(&$graph)
{
$this->dbConnection->execute('UPDATE datasets SET defaultModelUri ='
. $this->dbConnection->qstr($graph->modelURI) . ' WHERE datasetName ='
. $this->dbConnection->qstr($this->setName));
}
/**
* Returns a reference to the defaultGraph.
*
* @return NamedGraphDb
*/
function & getDefaultGraph()
{
$defaultGraphURI = $this->dbConnection->GetOne("SELECT defaultModelUri FROM datasets WHERE datasetName ='".$this->setName."'");
return ($this->dbStore->getNamedGraphDb($defaultGraphURI,'http://rdfapi-php/dataset_defaultGraph_'.$this->setName));
}
/**
* Returns true, if a defaultGraph exists. False otherwise.
*
* @return boolean
*/
function hasDefaultGraph()
{
return true;
}
/**
* Removes a NamedGraph from the set. Nothing happens
* if no graph with that name is contained in the set.
*
* @param string
*/
function removeNamedGraph($graphName)
{
$this->dbConnection->execute('DELETE FROM dataset_model WHERE datasetName="'
. $this->dbConnection->qstr($this->setName) . '" AND graphURI ="'
. $this->dbConnection->qstr($graphName) . '"');
}
/**
* Tells wether the Dataset contains a NamedGraph.
*
* @param string
* @return boolean
*/
function containsNamedGraph($graphName)
{
$count= $this->dbConnection->GetOne('SELECT count(*) FROM dataset_model WHERE datasetName="'.$this->setName.'" AND graphURI ="'.$graphName.'"');
return ($count>0);
}
/**
* Returns the NamedGraph with a specific name from the Dataset.
* Changes to the graph will be reflected in the set.
*
* @param string
* @return NamedGraphDb or null
*/
function &getNamedGraph($graphName)
{
if(!$this->containsNamedGraph($graphName))
return null;
$modelVars =& $this->dbConnection->execute("SELECT models.modelURI, models.modelID, models.baseURI
FROM models, dataset_model
WHERE dataset_model.graphURI ='" .$graphName ."' AND dataset_model.modelId= models.modelID");
return new NamedGraphDb($this->dbConnection, $modelVars->fields[0],
$modelVars->fields[1], $graphName ,$modelVars->fields[2]);
}
/**
* Returns the names of the namedGraphs in this set as strings in an array.
*
* @return Array
*/
function listGraphNames()
{
$recordSet =& $this->dbConnection->execute("SELECT graphURI FROM dataset_model WHERE datasetName ='".$this->setName."'");
$return=array();
while (!$recordSet->EOF)
{
$return[] = $recordSet->fields[0];
$recordSet->moveNext();
}
return $return;
}
/**
* Creates a new NamedGraph and adds it to the set. An existing graph with the same name will be replaced. But the old namedGraph remains in the database.
*
* @param string
* @param string
* @return NamedGraphDb
*/
function &createGraph($graphName,$baseURI = null)
{
$graph =& $this->dbStore->getNewNamedGraphDb(uniqid('http://rdfapi-php/namedGraph_'),$graphName,$baseURI);
$this->addNamedGraph($graph);
return $graph;
}
/**
* Deletes all NamedGraphs from the set.
*/
function clear()
{
$this->dbConnection->execute("DELETE FROM dataset_model WHERE datasetName ='".$this->setName."'");
}
/**
* Returns the number of NamedGraphs in the set. Empty graphs are counted.
*
* @return int
*/
function countGraphs()
{
return ($this->dbConnection->GetOne("SELECT count(*) FROM dataset_model WHERE datasetName ='".$this->setName."'"));
}
/**
* Returns an iterator over all {@link NamedGraph}s in the set.
*
* @return IteratorAllGraphsDb
*/
function &listNamedGraphs()
{
$recordSet =& $this->dbConnection->execute("SELECT graphURI FROM dataset_model WHERE datasetName ='".$this->setName."'");
$it = new IteratorAllGraphsDb($recordSet, $this);
return $it;
}
/**
* Tells wether the set contains any NamedGraphs.
*
* @return boolean
*/
function isEmpty()
{
return ($this->countGraphs()==0);
}
/**
* Add all named graphs of the other dataset to this dataset.
*
* @param Dataset
*/
function addAll($otherDataset)
{
for($iterator = $otherDataset->listNamedGraphs(); $iterator->valid(); $iterator->next())
{
$this->addNamedGraph($iterator->current());
};
if ($otherDataset->hasDefaultGraph())
{
$this->defaultGraph = $this->defaultGraph->unite($otherDataset->getDefaultGraph());
}
}
// === Quad level methods ========================
/**
* Adds a quad to the Dataset. The argument must not contain any
* wildcards. If the quad is already present, nothing happens. A new
* named graph will automatically be created if necessary.
*
* @param Quad
*/
function addQuad(&$quad)
{
$graphName=$quad->getGraphName();
$graphName=$graphName->getLabel();
$graph=& $this->getNamedGraph($graphName);
if ($graph===null)
$graph=& $this->createGraph($graphName);
$statement=$quad->getStatement();
$graph->add($statement);
}
/**
* Tells wether the Dataset contains a quad or
* quads matching a pattern.
*
* @param Resource
* @param Resource
* @param Resource
* @param Resource
* @return boolean
*/
function containsQuad($graphName,$subject,$predicate,$object)
{
// static part of the sql statement
$sql = "SELECT count(*)
FROM statements, dataset_model
WHERE datasetName ='".$this->setName."' AND statements.modelID=dataset_model.modelId ";
if($graphName!=null)
{
$sql.= " AND graphURI ='".$graphName->getLabel()."'";
}
// dynamic part of the sql statement
$sql .= DbModel::_createDynSqlPart_SPO($subject, $predicate, $object);
return (($this->dbConnection->GetOne($sql))>0);
}
/**
* Deletes a Quad from the RDF dataset.
*
* @param Quad
*/
function removeQuad($quad)
{
$graphName=$quad->getGraphName();$graphName=$graphName->getLabel();
//find namedGraph IDs
$graphID = $this->dbConnection->GetOne("SELECT modelId FROM dataset_model WHERE graphURI ='$graphName'");
// static part of the sql statement
$sql = "DELETE FROM statements WHERE modelID = $graphID";
// dynamic part of the sql statement
$sql .= DbModel::_createDynSqlPart_SPO($quad->getSubject(), $quad->getPredicate(), $quad->getObject());
// execute the query
if($graphID)
$recordSet =& $this->dbConnection->execute($sql);
}
/**
* Counts the Quads in the RDF dataset. Identical Triples in
* different NamedGraphs are counted individually.
*
* @return int
*/
function countQuads()
{
$sql = "SELECT count(*)
FROM statements, dataset_model
WHERE datasetName ='".$this->setName."' AND statements.modelID=dataset_model.modelId ";
return ((int)$this->dbConnection->GetOne($sql));
}
/**
* Finds Statements that match a quad pattern. The argument may contain
* wildcards.
*
* @param Resource or null
* @param Resource or null
* @param Resource or null
* @param Resource or null
* @return IteratorFindQuadsDb
*/
function &findInNamedGraphs($graphName,$subject,$predicate,$object,$returnAsTriples =false )
{
// static part of the sql statement
$sql = "SELECT subject, predicate, object, l_language, l_datatype, subject_is, object_is, dataset_model.graphURI
FROM statements, dataset_model
WHERE datasetName ='".$this->setName."' AND statements.modelID=dataset_model.modelId ";
if($graphName!=null)
{
$sql.= " AND graphURI ='".$graphName->getLabel()."'";
}
// dynamic part of the sql statement
$sql .= DbModel::_createDynSqlPart_SPO($subject, $predicate, $object);
// execute the query
$recordSet =& $this->dbConnection->execute($sql);
$it = new IteratorFindQuadsDb($recordSet, $this, $returnAsTriples);
return $it;
}
/**
* Finds Statements that match a pattern in the default Graph. The argument may contain
* wildcards.
*
* @param Resource or null
* @param Resource or null
* @param Resource or null
* @return IteratorFindQuadsDb
*/
function &findInDefaultGraph($subject,$predicate,$object)
{
$defaultGraphID = (int)$this->dbConnection->GetOne("SELECT models.modelID FROM datasets, models WHERE datasets.datasetName ='".$this->setName."' AND datasets.defaultModelUri = models.modelURI");
// static part of the sql statement
$sql = "SELECT subject, predicate, object, l_language, l_datatype, subject_is, object_is
FROM statements
WHERE modelID ='$defaultGraphID'";
// dynamic part of the sql statement
$sql .= DbModel::_createDynSqlPart_SPO($subject, $predicate, $object);
// execute the query
$recordSet =& $this->dbConnection->execute($sql);
$it = new IteratorFindQuadsDb($recordSet, $this, true);
return $it;
}
}
?>

View File

@ -0,0 +1,394 @@
<?php
require_once RDFAPI_INCLUDE_DIR . 'dataset/Dataset.php';
require_once RDFAPI_INCLUDE_DIR . 'dataset/NamedGraphMem.php';
require_once RDFAPI_INCLUDE_DIR . 'model/MemModel.php';
// ----------------------------------------------------------------------------------
// Class: DatasetMem
// ----------------------------------------------------------------------------------
/**
* In-memory implementation of a RDF dataset.
* A RDF dataset set is a collection of named RDF graphs.
*
* @version $Id$
* @author Daniel Westphal (http://www.d-westphal.de)
* @author Chris Bizer <chris@bizer.de>
*
* @package dataset
* @access public
**/
class DatasetMem extends Dataset
{
/**
* Reference to a Memmodel that holds the default graph.
*
* @var resource Memmodel
* @access private
*/
var $defaultGraph;
/**
* Name of the DatasetMem.
*
* @var string
* @access private
*/
var $setName;
/**
* List of all NamedGraphs.
*
* @var array
* @access private
*/
var $graphs=array();
/**
* Constructor.
* You can supply a Dataset name.
*
* @param string
* @access public
*/
function DatasetMem($datasetName = null)
{
$this->setDatasetName($datasetName);
$this->defaultGraph=new MemModel();
}
// === Graph level methods ========================
/**
* Sets the Datasets name.
*
* @param string
* @access public
*/
function setDatasetName($datasetName)
{
$this->setName=$datasetName;
}
/**
* Returns the Datasets name.
*
* @return string
* @access public
*/
function getDatasetName()
{
return $this->setName;
}
/**
* Adds a NamedGraph to the set. Will replace a NamedGraph with the same name that is already in the set.
*
* @param NamedGraphMem
*/
function addNamedGraph(&$graph)
{
$graphNameURI=$graph->getGraphName();
$this->graphs[$graphNameURI]=&$graph;
}
/**
* Overwrites the existting default graph.
*
* @param MemModel
*/
function setDefaultGraph(&$graph)
{
$this->defaultGraph=&$graph;
}
/**
* Returns a reference to the defaultGraph
* @return Model
*/
function &getDefaultGraph()
{
return $this->defaultGraph;
}
/**
* Returns true, if an defaultGraph exists. False otherwise .
*
* @return boolean
*/
function hasDefaultGraph()
{
return $this->defaultGraph != null;
}
/**
* Removes a NamedGraph from the set. Nothing happens
* if no graph with that name is contained in the set.
*
* @param string
*/
function removeNamedGraph($graphName)
{
unset($this->graphs[$graphName]);
}
/**
* Tells wether the Dataset contains a NamedGraph.
*
* @param string
* @return boolean
*/
function containsNamedGraph($graphName)
{
return isset($this->graphs[$graphName]) === true;
}
/**
* Returns the NamedGraph with a specific name from the Dataset.
* Changes to the graph will be reflected in the set.
*
* @param string
* @return NamedGraphMem or NULL
*/
function &getNamedGraph($graphName)
{
if (!isset($this->graphs[$graphName])) return NULL;
return $this->graphs[$graphName];
}
/**
* Returns the names of the namedGraphs in this set as strings in an array.
*
* @return Array
*/
function listGraphNames()
{
return array_keys($this->graphs);
}
/**
* Creates a new NamedGraph and adds it to the set. An existing
* graph with the same name will be replaced.The name of the NamedGraph to be created ; must be an URI
*
* @param string
* @param string
* @return NamedGraphMem
*/
function &createGraph($graphName,$baseURI = null)
{
$this->graphs[$graphName]=new NamedGraphMem($graphName,$baseURI);
return $this->getNamedGraph($graphName);
}
/**
* Deletes all NamedGraphs from the set.
*/
function clear()
{
$this->graphs = array();
}
/**
* Returns the number of NamedGraphs in the set. Empty graphs
* are counted.
*
* @return int
*/
function countGraphs()
{
return count($this->graphs);
}
/**
* Returns the NamedGraph with a specific offset in the dataset.
* Changes to the graph will be reflected in the set.
*
* @param int
* @return NamedGraphMem or null
* @access private
*/
function &getGraphWithOffset($offset)
{
$i=0;
foreach ($this->graphs as $graph)
{
if (($i++)==$offset)
return $graph;
}
$n = null;
return $n;
}
/**
* Returns an iterator over all {@link NamedGraph}s in the set.
*
* @return IteratorAllGraphsMem
*/
function &listNamedGraphs()
{
require_once RDFAPI_INCLUDE_DIR . 'dataset/IteratorAllGraphsMem.php';
$m = new IteratorAllGraphsMem($this);
return $m;
}
/**
* Tells wether the set contains any NamedGraphs.
*
* @return boolean
*/
function isEmpty()
{
return $this->countGraphs() == 0;
}
/**
* Adds all named graphs of the other dataset to this dataset.
*
* @param Dataset
*/
function addAll($otherDataset)
{
for($iterator = $otherDataset->listNamedGraphs(); $iterator->valid(); $iterator->next())
{
$current=$iterator->current();
$this->graphs[$current->getGraphName()]=$current;
}
if ($otherDataset->hasDefaultGraph())
{
$this->defaultGraph = $this->defaultGraph->unite($otherDataset->getDefaultGraph());
}
}
// === Quad level methods ========================
/**
* Adds a quad to the Dataset. The argument must not contain any
* wildcards. If the quad is already present, nothing happens. A new
* named graph will automatically be created if necessary.
*
* @param Quad
*/
function addQuad(&$quad)
{
$graphName=$quad->getGraphName();
if ($this->containsNamedGraph($graphName->getLabel())===false)
$this->createGraph($graphName->getLabel());
$this->graphs[$graphName->getLabel()]->add($quad->getStatement());
}
/**
* Tells wether the Dataset contains a quad or
* quads matching a pattern.
*
* @param Resource $graphName
* @param Resource $subject
* @param Resource $predicate
* @param Resource $object
* @return boolean
*/
function containsQuad($graphName,$subject,$predicate,$object)
{
if($graphName!=null)
{
if ($this->containsNamedGraph($graphName->getLabel())!==true)
return false;
return ($this->graphs[$graphName->getLabel()]->findFirstMatchingStatement($subject,$predicate,$object)!=null);
}
foreach ($this->graphs as $graph)
{
if ($graph->findFirstMatchingStatement($subject,$predicate,$object)!=null)
return true;
};
return false;
}
/**
* Deletes a Quad from the RDF dataset.
*
* @param Quad
*/
function removeQuad($quad)
{
$graphName=$quad->getGraphName();
if($graphName!=null)
{
if ($this->containsNamedGraph($graphName->getLabel())!==true)
return;
return ($this->graphs[$graphName->getLabel()]->remove($quad->getStatement())!=null);
}
foreach ($this->graphs as $graph)
{
$graph->remove($quad->getStatement());
};
}
/**
* Counts the Quads in the RDF dataset. Identical Triples in
* different NamedGraphs are counted individually.
*
* @return int
*/
function countQuads()
{
$count=0;
foreach ($this->graphs as $graph)
{
$count+=$graph->size();
}
return $count;
}
/**
* Finds Statements that match a quad pattern. The argument may contain
* wildcards.
*
* @param Resource or Null
* @param Resourceor Null
* @param Resource or Null
* @param Resource or Null
* @return Iterator
*/
function &findInNamedGraphs($graph,$subject,$predicate,$object,$returnAsTriples = false)
{
if ($graph!=null)
{
$findGraph=&$this->getNamedGraph($graph->getLabel());
if($findGraph==null)
$findGraph=new MemModel();
return $findGraph->iterFind($subject,$predicate,$object);
}
require_once RDFAPI_INCLUDE_DIR . 'dataset/IteratorFindQuadsMem.php';
$m = new IteratorFindQuadsMem($subject,$predicate,$object,$this->listNamedGraphs(),$returnAsTriples);
return $m;
}
/**
* Finds Statements that match a pattern in the default Graph. The argument may contain
* wildcards.
*
* @param Resource or Null
* @param Resource or Null
* @param Resource or Null
* @return Iterator
*/
function &findInDefaultGraph($subject,$predicate,$object)
{
return $this->defaultGraph->iterFind($subject,$predicate,$object);
}
}
?>

View File

@ -0,0 +1,25 @@
<?php
// ----------------------------------------------------------------------------------
// dataset Package
// ----------------------------------------------------------------------------------
//
// Description : dataset package
//
// Author: Daniel Westphal <http://www.d-westphal.de>
//
// ----------------------------------------------------------------------------------
// Include ResModel classes
require_once( RDFAPI_INCLUDE_DIR . 'dataset/Dataset.php');
require_once( RDFAPI_INCLUDE_DIR . 'dataset/DatasetMem.php');
require_once( RDFAPI_INCLUDE_DIR . 'dataset/DatasetDb.php');
require_once( RDFAPI_INCLUDE_DIR . 'dataset/NamedGraphMem.php');
require_once( RDFAPI_INCLUDE_DIR . 'dataset/NamedGraphDb.php');
require_once( RDFAPI_INCLUDE_DIR . 'dataset/IteratorAllGraphsMem.php');
require_once( RDFAPI_INCLUDE_DIR . 'dataset/IteratorAllGraphsDb.php');
require_once( RDFAPI_INCLUDE_DIR . 'dataset/Quad.php');
require_once( RDFAPI_INCLUDE_DIR . 'dataset/IteratorFindQuadsMem.php');
require_once( RDFAPI_INCLUDE_DIR . 'dataset/IteratorFindQuadsDb.php');
require_once( RDFAPI_INCLUDE_DIR . 'syntax/TriXParser.php');
require_once( RDFAPI_INCLUDE_DIR . 'syntax/TriXSerializer.php');
?>

View File

@ -0,0 +1,127 @@
<?php
//----------------------------------------------------------------------------------
// Class: IteratorAllGraphsDb
//----------------------------------------------------------------------------------
/**
* Implementation of a Graph iterator.
*
* This Iterator should be used in a for-loop like:
* for($iterator = $dataset->listGraphs(); $iterator->valid(); $iterator->next())
* {
* $currentResource=$iterator->current();
* };
*
* @version $Id$
* @author Daniel Westphal <mail at d-westphal dot de>
*
*
* @package dataset
* @access public
**/
class IteratorAllGraphsDb
{
/**
* Holds a reference to the associated DB resultSet
* @var $dbResultSets ADODB result
* @access private
*/
var $dbResultSet;
/**
* Holds a reference to the associated datasetDb
* @var datasetDb
* @access private
*/
var $datasetDb;
/**
* The current position
* @var integer
* @access private
*/
var $key;
/**
* The current NamedGraph
* @var obejct NamedGraph
* @access private
*/
var $current;
/**
* Constructor.
*
*
* @param ADODBResultSet
* @param DatasetDb
* @access public
*/
function IteratorAllGraphsDb(&$dbResultSet,&$datasetDb)
{
$this->dbResultSet=& $dbResultSet;
$this->datasetDb=& $datasetDb;
$this->current = $this->dbResultSet->fields[0];
}
/**
* Resets iterator list to start
*
* @access public
*/
function rewind()
{
//not supported
}
/**
* Says if there are additional items left in the list
*
* @return boolean
* @access public
*/
function valid()
{
return (!$this->dbResultSet->EOF);
}
/**
* Moves Iterator to the next item in the list
*
* @access public
*/
function next()
{
$this->dbResultSet->moveNext();
$this->current = $this->dbResultSet->fields[0];
}
/**
* Returns the current item
*
* @return mixed
* @access public
*/
function &current()
{
return ($this->datasetDb->getNamedGraph($this->current));
}
/**
* Returns the key of the current item
*
* @return integer
* @access public
*/
function key()
{
return $this->dbResultSet->_currentRow;
}
}
?>

View File

@ -0,0 +1,125 @@
<?php
// ----------------------------------------------------------------------------------
// Class: IteratorAllGraphsMem
// ----------------------------------------------------------------------------------
/**
* Implementation of a Graph iterator.
*
* This Iterator should be used in a for-loop like:
* for($iterator = $dataset->listGraphs(); $iterator->valid(); $iterator->next())
* {
* $currentResource=$it->current();
* };
*
* @version $Id$
* @author Daniel Westphal <mail at d-westphal dot de>
*
*
* @package dataset
* @access public
**/
class IteratorAllGraphsMem
{
/**
* Holds a reference to the associated RDF dataset
*
* @var object dataset
* @access private
*/
var $associatedGraphSet;
/**
* The current position
*
* @var integer
* @access private
*/
var $key;
/**
* If the current resource is valid
*
* @var boolean
* @access private
*/
var $valid;
/**
* The current NamedGraph
*
* @var obejct NamedGraph
* @access private
*/
var $current;
/**
* Constructor.
*
* @param dataset
* @access public
*/
function IteratorAllGraphsMem(&$namedGraphSet)
{
$this->associatedGraphSet=&$namedGraphSet;
$this->rewind();
}
/**
* Resets iterator list to start
*
* @access public
*/
function rewind()
{
$this->key = -1;
$this->next();
}
/**
* Says if there are additional items left in the list.
*
* @return boolean
* @access public
*/
function valid()
{
return $this->valid;
}
/**
* Moves Iterator to the next item in the list.
*
* @access public
*/
function next()
{
$this->current = &$this->associatedGraphSet->getGraphWithOffset(++$this->key);
$this->valid=($this->current!=NULL);
}
/**
* Returns the current item.
*
* @return mixed
* @access public
*/
function &current()
{
return $this->current;
}
/**
* Returns the key of the current item.
*
* @return integer
* @access public
*/
function key()
{
return $this->key;
}
}
?>

View File

@ -0,0 +1,145 @@
<?php
//----------------------------------------------------------------------------------
// Class: IteratorFindQuadsDb
// ----------------------------------------------------------------------------------
/**
* Implementation of a quad iterator.
*
* This Iterator should be used like:
* for($iterator = $dataset->findInNamedGraphs(null,null,null,null); $iterator->valid(); $iterator->next())
* {
* $currentQuad=$iterator->current();
* };
*
*
* @version $Id$
* @author Daniel Westphal (http://www.d-westphal.de)
*
*
* @package dataset
* @access public
**/
class IteratorFindQuadsDb
{
/**
* Holds a reference to the associated DB resultSet.
*
* @var $dbResultSets ADODB result
* @access private
*/
var $dbResultSet;
/**
* Holds a reference to the associated datasetDb.
*
* @var $datasetDb datasetDb
* @access private
*/
var $datasetDb;
/**
* boolean value, if the results should be returned as triples.
*
* @var boolean
* @access private
*/
var $returnAsTriples;
/**
* Constructor.
*
* @param dataset
* @access public
*/
function IteratorFindQuadsDb(&$dbResultSet,&$datasetDb,$returnAsTriples=false)
{
$this->dbResultSet=& $dbResultSet;
$this->datasetDb=& $datasetDb;
$this->returnAsTriples=$returnAsTriples;
}
/**
* Resets iterator list to start.
*
* @access public
*/
function rewind()
{
//not supported
}
/**
* Says if there are additional items left in the list.
*
* @return boolean
* @access public
*/
function valid()
{
if (($this->dbResultSet ===false) OR ($this->dbResultSet->EOF) )
return false;
return true;
}
/**
* Moves Iterator to the next item in the list.
*
* @access public
*/
function next()
{
if ($this->dbResultSet!==false)
$this->dbResultSet->moveNext();
}
/**
* Returns the current item.
*
* @return mixed
* @access public
*/
function &current()
{
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));
}
/**
* Returns the key of the current item.
*
* @return integer
* @access public
*/
function key()
{
return $this->dbResultSet->_currentRow;
}
}
?>

View File

@ -0,0 +1,217 @@
<?php
require_once RDFAPI_INCLUDE_DIR . 'dataset/Quad.php';
// ----------------------------------------------------------------------------------
// Class: IteratorFindQuadsMem
// ----------------------------------------------------------------------------------
/**
* Implementation of a quad iterator.
*
* This Iterator should be used like:
* for($iterator = $dataset->findInNamedGraphs(null,null,null,null); $iterator->valid(); $iterator->next())
* {
* $currentQuad=$it->current();
* };
*
* @version $Id$
* @author Daniel Westphal (http://d-westphal.de)
*
*
* @package dataset
* @access public
**/
class IteratorFindQuadsMem
{
/**
* key value in the current graph.
*
* @var dataset
* @access private
*/
var $graphKey;
/**
* boolean value, if the results should be returned as triples.
*
* @var boolean
* @access private
*/
var $returnAsTriples;
/**
* The current position.
*
* @var integer
* @access private
*/
var $key;
/**
* If the current resource is valid.
*
* @var boolean
* @access private
*/
var $valid;
/**
* The current NamedGraph.
*
* @var NamedGraph
* @access private
*/
var $current;
/**
* The graphName Resource to search for.
*
* @var string
* @access private
*/
var $findGraphName;
/**
* The subject Resource to search for.
*
* @var string
* @access private
*/
var $findSubject;
/**
* The predicate Resource to search for.
*
* @var string
* @access private
*/
var $findPredicate;
/**
* The object Resource to search for.
*
* @var string
* @access private
*/
var $findObject;
/**
* Iterator over all graphs of the RDF dataset.
*
* @var string
* @access private
*/
var $graphIterator;
/**
* Constructor.
*
* $subject, $predicate, and $object are used like find().
* $getSPO supports the strings 's', 'p', and 'o' to return
* either the subject, predicate, or object of the result statements.
*
*
* @param Resource
* @param Resource
* @param Resource
* @param dataset
* @param Boolean
* @access public
*/
function IteratorFindQuadsMem($subject,$predicate,$object,&$graphIterator, $returnAsTriples=false)
{
$this->findSubject=$subject;
$this->findPredicate=$predicate;
$this->findObject=$object;
$this->graphIterator=&$graphIterator;
$this->rewind();
$this->returnAsTriples=$returnAsTriples;
}
/**
* Resets iterator list to start.
*
* @access public
*/
function rewind()
{
$this->graphIterator->rewind();
$this->key = -1;
$this->graphKey=-1;
$this->next();
}
/**
* Says if there are additional items left in the list.
*
* @return boolean
* @access public
*/
function valid()
{
return $this->valid;
}
/**
* Moves Iterator to the next item in the list.
*
* @access public
*/
function next()
{
if($this->graphIterator->valid()===false)
{
$this->valid=false;
return;
}
$currentGraph=&$this->graphIterator->current();
$this->current= $currentGraph->findFirstMatchingStatement($this->findSubject,$this->findPredicate,$this->findObject,++$this->graphKey);
if($this->current==null)
{
do
{
$this->graphIterator->next();
if($this->graphIterator->valid()===false)
{
$this->valid=false;
return;
}
$currentGraph=&$this->graphIterator->current();
$this->graphKey=-1;
$this->current= $currentGraph->findFirstMatchingStatement($this->findSubject,$this->findPredicate,$this->findObject,++$this->graphKey);
} while ($this->current==null);
}
$this->key++;
$this->valid=true;
}
/**
* Returns the current item.
*
* @return mixed
* @access public
*/
function current()
{
if($this->returnAsTriples) return $this->current;
$currentGraph=&$this->graphIterator->current();
return new Quad(new Resource($currentGraph->getGraphName()),$this->current->getSubject(),$this->current->getPredicate(),$this->current->getObject());
}
/**
* Returns the key of the current item.
*
* @return integer
* @access public
*/
function key()
{
return $this->key;
}
}
?>

View File

@ -0,0 +1,70 @@
<?php
// ----------------------------------------------------------------------------------
// Class: NamedGraphDb
// ----------------------------------------------------------------------------------
/**
* Persistent NamedGraph implementation that extends a {@link DbModel}.
* The graphName is not stored in the database. As soon as the namedGraph is added
* to a RDF dataset the graphName is saved.
*
* @version $Id$
* @author Daniel Westphal (http://www.d-westphal.de)
*
* @package dataset
* @access public
**/
class NamedGraphDb extends DbModel
{
/**
* Name of the NamedGraphDb
*
* @var string
* @access private
*/
var $graphName;
/**
* Constructor
* Do not call this directly.
* Use the method getModel,getNewModel or putModel of the Class NamedGraphDb instead.
*
* @param ADODBConnection
* @param string
* @param string
* @param string
* @access public
*/
function NamedGraphDb(&$dbConnection, $modelURI, $modelID,$graphName, $baseURI=NULL)
{
$this->dbConn =& $dbConnection;
$this->modelURI = $modelURI;
$this->modelID = $modelID;
$this->baseURI = $this->_checkBaseURI($baseURI);
$this->graphName = $graphName;
}
/**
* Sets the graph name.
*
* @param string
* @access public
*/
function setGraphName($graphName)
{
$this->graphName=$graphName;
}
/**
* Returns the graph name.
*
* @return string
* @access public
*/
function getGraphName()
{
return $this->graphName;
}
}
?>

View File

@ -0,0 +1,66 @@
<?php
require_once RDFAPI_INCLUDE_DIR . 'model/MemModel.php';
// ----------------------------------------------------------------------------------
// Class: NamedGraphMem
// ----------------------------------------------------------------------------------
/**
* NamedGraph implementation that extends a {@link MemModel}
* with a name.
*
* @version $Id$
* @author Daniel Westphal <http://www.d-westphal.de>
*
* @package dataset
* @access public
**/
class NamedGraphMem extends MemModel
{
/**
* Name of the NamedGraphMem.
*
* @var string
* @access private
*/
var $graphName;
/**
* Constructor
* You have to supply a graph name. You can supply a URI.
*
* @param string
* @param string
* @access public
*/
function NamedGraphMem($graphName,$baseURI = null)
{
$this->setBaseURI($baseURI);
$this->indexed = INDEX_TYPE;
$this->setGraphName($graphName);
}
/**
* Sets the graph name.
*
* @param string
* @access public
*/
function setGraphName($graphName)
{
$this->graphName=$graphName;
}
/**
* Returns the graph name.
*
* @return string
* @access public
*/
function getGraphName()
{
return $this->graphName;
}
}
?>

View File

@ -0,0 +1,147 @@
<?php
// ----------------------------------------------------------------------------------
// Class: Quad
// ----------------------------------------------------------------------------------
/**
*
* A Triple in a RDF dataset, consisting of four Jena Nodes: graphName,
* subject, predicate, and object.
*
* @version $Id$
* @author Daniel Westphal (http://www.d-westphal.de)
*
* @package dataset
* @access public
**/
class Quad
{
/**
* Name of the NamedGraphMem.
*
* @var Resource
* @access private
*/
var $graphName;
/**
* Statement
*
* @var Statement
* @access private
*/
var $statement;
/**
* Constructor
* Creates a Quad from four Nodes.
*
* @param Resource
* @param Resource
* @param Resource
* @param Resource
* @access public
*/
function Quad($graphName,$subject,$predicate,$object)
{
if (!is_a($graphName, 'Resource'))
{
$errmsg = RDFAPI_ERROR .
'(class: Quad; method: new): Resource expected as graphName.';
trigger_error($errmsg, E_USER_ERROR);
}
$this->statement=new Statement($subject,$predicate,$object);
$this->graphName=$graphName;
}
/**
* Sets the graph name.
*
* @param Resource
* @access public
*/
function setGraphName($graphName)
{
$this->graphName=$graphName;
}
/**
* Returns the graph name.
*
* @return Resource
* @access public
*/
function getGraphName()
{
return $this->graphName;
}
/**
* Return a human-readable (sort of) string "graphname { s p o . }"
* describing the quad.
*
* @return string
*/
function toString()
{
return 'GraphName('.$this->graphName->getLabel().') '.$this->statement->toString();
}
/**
* Returns the subject.
*
* @return Resource
* @access public
*/
function getSubject()
{
return $this->statement->getSubject();
}
/**
* Returns the predicate.
*
* @return Resource
* @access public
*/
function getPredicate()
{
return $this->statement->getPredicate();
}
/**
* Returns the object.
*
* @return Resource
* @access public
*/
function getObject()
{
return $this->statement->getObject();
}
/**
* Returns the statement(subject,predicate,object).
*
* @return statement
* @access public
*/
function getStatement()
{
return $this->statement;
}
/**
* Checks if two quads are equal.
*
* @param Quad
* @return boolean
* @access public
*/
function equals($quad)
{
return ($this->graphName->equals($quad->getGraphName()) && $this->statement->equals($quad->getStatement()));
}
}
?>

View File

@ -0,0 +1,41 @@
K 25
svn:wc:ra_dav:version-url
V 62
/svnroot/rdfapi-php/!svn/ver/320/trunk/rdfapi-php/api/infModel
END
InfModel.php
K 25
svn:wc:ra_dav:version-url
V 75
/svnroot/rdfapi-php/!svn/ver/290/trunk/rdfapi-php/api/infModel/InfModel.php
END
InfModelP.php
K 25
svn:wc:ra_dav:version-url
V 76
/svnroot/rdfapi-php/!svn/ver/268/trunk/rdfapi-php/api/infModel/InfModelP.php
END
InfModelB.php
K 25
svn:wc:ra_dav:version-url
V 76
/svnroot/rdfapi-php/!svn/ver/290/trunk/rdfapi-php/api/infModel/InfModelB.php
END
InfStatement.php
K 25
svn:wc:ra_dav:version-url
V 79
/svnroot/rdfapi-php/!svn/ver/268/trunk/rdfapi-php/api/infModel/InfStatement.php
END
InfModelF.php
K 25
svn:wc:ra_dav:version-url
V 76
/svnroot/rdfapi-php/!svn/ver/320/trunk/rdfapi-php/api/infModel/InfModelF.php
END
InfRule.php
K 25
svn:wc:ra_dav:version-url
V 74
/svnroot/rdfapi-php/!svn/ver/290/trunk/rdfapi-php/api/infModel/InfRule.php
END

View File

@ -0,0 +1,106 @@
8
dir
556
https://rdfapi-php.svn.sourceforge.net/svnroot/rdfapi-php/trunk/rdfapi-php/api/infModel
https://rdfapi-php.svn.sourceforge.net/svnroot/rdfapi-php
2006-11-21T09:38:51.000000Z
320
tgauss
svn:special svn:externals svn:needs-lock
b2ee660e-c932-0410-bdee-d8da4d8102f4
InfModel.php
file
2008-02-29T14:57:49.005834Z
26bcd3c49686d1c8a402b9b1ff0e128e
2006-06-22T12:23:24.000000Z
290
tgauss
has-props
InfModelP.php
file
2008-02-29T14:57:49.005834Z
e4eb63f504856523cd9460c7cdb887b1
2006-05-15T05:28:09.000000Z
268
tgauss
has-props
InfModelB.php
file
2008-02-29T14:57:49.021455Z
554810af03fa02dfef1b3fcbb9d36fa8
2006-06-22T12:23:24.000000Z
290
tgauss
has-props
InfStatement.php
file
2008-02-29T14:57:49.021455Z
b3b8db445eadddd525f88944aec533f4
2006-05-15T05:28:09.000000Z
268
tgauss
has-props
InfModelF.php
file
2008-02-29T14:57:49.037075Z
20031867ebe5ea70c133653f9651138b
2006-11-21T09:38:51.000000Z
320
tgauss
has-props
InfRule.php
file
2008-02-29T14:57:49.037075Z
caccf06491e8ba11a7f213807c311046
2006-06-22T12:23:24.000000Z
290
tgauss
has-props

View File

@ -0,0 +1,9 @@
K 13
svn:eol-style
V 6
native
K 12
svn:keywords
V 23
Author Date Id Revision
END

View File

@ -0,0 +1,9 @@
K 13
svn:eol-style
V 6
native
K 12
svn:keywords
V 23
Author Date Id Revision
END

View File

@ -0,0 +1,9 @@
K 13
svn:eol-style
V 6
native
K 12
svn:keywords
V 23
Author Date Id Revision
END

View File

@ -0,0 +1,9 @@
K 13
svn:eol-style
V 6
native
K 12
svn:keywords
V 23
Author Date Id Revision
END

View File

@ -0,0 +1,9 @@
K 13
svn:eol-style
V 6
native
K 12
svn:keywords
V 23
Author Date Id Revision
END

View File

@ -0,0 +1,9 @@
K 13
svn:eol-style
V 6
native
K 12
svn:keywords
V 23
Author Date Id Revision
END

View File

@ -0,0 +1,678 @@
<?php
// ----------------------------------------------------------------------------------
// Class: infModel
// ----------------------------------------------------------------------------------
/**
* A InfModel Model extends a MemModel , by adding the ability to infer statements from
* known statements and RDFS/OWL-Schematas.
* It uses the same interface as MemModel, thus making the
* infererence process hidden.
*
* @version $Id$
* @author Daniel Westphal <mail at d-westphal dot de>
*
* @package infModel
* @access public
*/
class InfModel extends MemModel
{
/**
* Array that holds the objects of the class Infrule,
* which were assigned by the _addToInference() function
*
* @var array
* @access private
*/
var $infRules;
/**
* Array of URI-Strings that produces Infrules.
*
* @var array
* @access private
*/
var $supportedInference;
/**
* Array of the connection between the infrules and the statement
* that assigned those rules.
* array[2][3]=true;array[2][5]=true means, that statement 2
* assigned rule 3 & 5 to the model.
*
* @var array
* @access private
*/
var $statementRuleIndex;
/**
* Array of the infRule triggers and the matching infrules.
* $this->infRulesTriggerIndex['s'] for subject index, ['p'] for predicates,
* and ['o'] for objects.
*
* @var array
* @access private
*/
var $infRulesTriggerIndex;
/**
* Array of the infRule entailments and the matching infrules.
* $this->infRulesEntailIndex['s'] for subject index, ['p'] for predicates,
* and ['o'] for objects.
*
* @var array
* @access private
*/
var $infRulesEntailIndex;
/**
* Constructor
* You can supply a base_uri
*
* @param string $baseURI
* @access public
*/
function InfModel ($baseURI = NULL)
{
//call the memmodel constructor method
parent::MemModel($baseURI);
//initialise vars
$this->infRulesTriggerIndex['s']=array();
$this->infRulesTriggerIndex['p']=array();
$this->infRulesTriggerIndex['o']=array();
$this->infRulesEntailIndex['s']=array();
$this->infRulesEntailIndex['p']=array();
$this->infRulesEntailIndex['o']=array();
$this->infRules=array();
$this->statementRuleIndex = array();
//arraylist of predicate labels that shall add inference rules
//to the model
//The constants, wich statements will create rules can be configured in constants.php
if (INF_RES_SUBCLASSOF)
$this->supportedInference[] = RDF_SCHEMA_URI.RDFS_SUBCLASSOF;
if (INF_RES_SUBPROPERTYOF)
$this->supportedInference[] = RDF_SCHEMA_URI.RDFS_SUBPROPERTYOF;
if (INF_RES_RANGE)
$this->supportedInference[] = RDF_SCHEMA_URI.RDFS_RANGE;
if (INF_RES_DOMAIN)
$this->supportedInference[] = RDF_SCHEMA_URI.RDFS_DOMAIN;
if (INF_RES_OWL_SAMEAS)
$this->supportedInference[] = OWL_URI.OWL_SAME_AS;
if (INF_RES_OWL_INVERSEOF)
$this->supportedInference[] = OWL_URI.OWL_INVERSE_OF;
//Rule: rdfs12
if (INF_RES_RULE_RDFS12)
{
$infRule=new InfRule();
$infRule->setTrigger(null,new Resource(RDF_NAMESPACE_URI.RDF_TYPE),new Resource(RDF_SCHEMA_URI.'ContainerMembershipProperty'));
$infRule->setEntailment('<s>',new Resource(RDF_SCHEMA_URI.RDFS_SUBPROPERTYOF),new Resource(RDF_SCHEMA_URI.'member'));
$this->_addInfRule($infRule,'base');
}
//Rule: rdfs6
if (INF_RES_RULE_RDFS6)
{
$infRule=new InfRule();
$infRule->setTrigger(null,new Resource(RDF_NAMESPACE_URI.RDF_TYPE),new Resource(RDF_NAMESPACE_URI.RDF_PROPERTY));
$infRule->setEntailment('<s>',new Resource(RDF_SCHEMA_URI.RDFS_SUBPROPERTYOF),'<s>');
$this->_addInfRule($infRule,'base');
}
//Rule: rdfs8
if (INF_RES_RULE_RDFS8)
{
$infRule=new InfRule();
$infRule->setTrigger(null,new Resource(RDF_NAMESPACE_URI.RDF_TYPE),new Resource(RDF_SCHEMA_URI.RDFS_CLASS));
$infRule->setEntailment('<s>',new Resource(RDF_SCHEMA_URI.RDFS_SUBCLASSOF),new Resource(RDF_SCHEMA_URI.RDFS_RESOURCE));
$this->_addInfRule($infRule,'base');
}
//Rule: rdfs10
if (INF_RES_RULE_RDFS10)
{
$infRule=new InfRule();
$infRule->setTrigger(null,new Resource(RDF_NAMESPACE_URI.RDF_TYPE),new Resource(RDF_SCHEMA_URI.RDFS_CLASS));
$infRule->setEntailment('<s>',new Resource(RDF_SCHEMA_URI.RDFS_SUBCLASSOF),'<s>');
$this->_addInfRule($infRule,'base');
}
//Rule: rdfs13
if (INF_RES_RULE_RDFS13)
{
$infRule=new InfRule();
$infRule->setTrigger(null,new Resource(RDF_NAMESPACE_URI.RDF_TYPE),new Resource(RDF_SCHEMA_URI.RDFS_DATATYPE));
$infRule->setEntailment('<s>',new Resource(RDF_SCHEMA_URI.RDFS_SUBCLASSOF),new Resource(RDF_SCHEMA_URI.RDFS_LITERAL));
$this->_addInfRule($infRule,'base');
}
}
/**
* 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);
};
}
/**
* This function analyses the statement's predicate and adds the
* matching infrule to the model.
*
* @param object Statement $statement
* @access private
*/
function _addToInference($statement)
{
$predicateLabel=$statement->getLabelPredicate();
//get the position of the the statement in the model
end($this->triples);
$statementPosition=key($this->triples);
switch ($predicateLabel)
{
case RDF_SCHEMA_URI.RDFS_SUBPROPERTYOF :
//create a new rule
$infRule=new InfRule();
//set the trigger to match all statements, having a
//predicate, that matches the subject of the statement that
//created this rule.
$infRule->setTrigger(null,$statement->getSubject(),null);
//set the infrule to return a statement, having the same
//subject and object as the statement, that asked for an
//entailment, and having the object of the statement,
//that created this rule as predicate.
$infRule->setEntailment('<s>',$statement->getObject(),'<o>');
//add the infule to Model, Statement/Rule-Index,
//and Rule/Trigger (or Rule/Entailment) index
$this->_addInfRule($infRule,$statementPosition);
break;
case RDF_SCHEMA_URI.RDFS_SUBCLASSOF :
$infRule=new InfRule();
$infRule->setTrigger(null,new Resource(RDF_NAMESPACE_URI.RDF_TYPE),$statement->getSubject());
$infRule->setEntailment('<s>',new Resource(RDF_NAMESPACE_URI.RDF_TYPE),$statement->getObject());
$this->infRules[]=$infRule;
$this->_addInfRule($infRule,$statementPosition);
break;
case RDF_SCHEMA_URI.RDFS_DOMAIN :
$infRule=new InfRule();
$infRule->setTrigger(null,$statement->getSubject(),null);
$infRule->setEntailment('<s>',new Resource(RDF_NAMESPACE_URI.RDF_TYPE),$statement->getObject());
$this->infRules[]=$infRule;
$this->_addInfRule($infRule,$statementPosition);
break;
case RDF_SCHEMA_URI.RDFS_RANGE :
$infRule=new InfRule();
$infRule->setTrigger(null,$statement->getSubject(),null);
$infRule->setEntailment('<o>',new Resource(RDF_NAMESPACE_URI.RDF_TYPE),$statement->getObject());
$this->infRules[]=$infRule;
$this->_addInfRule($infRule,$statementPosition);
break;
case OWL_URI.OWL_INVERSE_OF :
$infRule=new InfRule();
$infRule->setTrigger(null,$statement->getSubject(),null);
$infRule->setEntailment('<o>',$statement->getObject(),'<s>');
$this->infRules[]=$infRule;
$this->_addInfRule($infRule,$statementPosition);
$infRule=new InfRule();
$infRule->setTrigger(null,$statement->getObject(),null);
$infRule->setEntailment('<o>',$statement->getSubject(),'<s>');
$this->infRules[]=$infRule;
$this->_addInfRule($infRule,$statementPosition);
break;
case OWL_URI.OWL_SAME_AS :
$infRule=new InfRule();
$infRule->setTrigger($statement->getSubject(),null,null);
$infRule->setEntailment($statement->getObject(),'<p>','<o>');
$this->_addInfRule($infRule,$statementPosition);
$infRule=new InfRule();
$infRule->setTrigger($statement->getObject(),null,null);
$infRule->setEntailment($statement->getSubject(),'<p>','<o>');
$this->_addInfRule($infRule,$statementPosition);
$infRule=new InfRule();
$infRule->setTrigger(null,$statement->getSubject(),null);
$infRule->setEntailment('<s>',$statement->getObject(),'<o>');
$this->_addInfRule($infRule,$statementPosition);
$infRule=new InfRule();
$infRule->setTrigger(null,$statement->getObject(),null);
$infRule->setEntailment('<s>',$statement->getSubject(),'<o>');
$this->_addInfRule($infRule,$statementPosition);
$infRule=new InfRule();
$infRule->setTrigger(null,null,$statement->getSubject());
$infRule->setEntailment('<s>','<p>',$statement->getObject());
$this->_addInfRule($infRule,$statementPosition);
$infRule=new InfRule();
$infRule->setTrigger(null,null,$statement->getObject());
$infRule->setEntailment('<s>','<p>',$statement->getSubject());
$this->_addInfRule($infRule,$statementPosition);
break;
};
}
/**
* This function checks, which infrules were added by the statement and
* removes those.
*
* @param object Statement $statement
* @return integer
* @access private
*/
function _removeFromInference($statement)
{
$return= array();
$statementPosition=-1;
do
{
//get the position of the statement that should be removed
$statementPosition=$this->findFirstMatchOff($statement->getSubject(),
$statement->getPredicate(),
$statement->getObject(),
$statementPosition+1);
if ($statementPosition!=-1)
{
//if it added any rules
if (isset ($this->statementRuleIndex[$statementPosition]))
{
//remove all rules
foreach ($this->statementRuleIndex[$statementPosition] as $key => $value)
{
//remove from Rule-Trigger Index
if (is_a($this,'InfModelF'))
{
$trigger=$this->infRules[$key]->getTrigger();
if(is_a($trigger['s'],'Node'))
{
$subjectLabel=$trigger['s']->getLabel();
} else
{
$subjectLabel='null';
}
unset ($this->infRulesTriggerIndex['s'][$subjectLabel][array_search($key,$this->infRulesTriggerIndex['s'][$subjectLabel])]);
if(is_a($trigger['p'],'Node'))
{
$predicateLabel=$trigger['p']->getLabel();
} else
{
$predicateLabel='null';
}
unset ($this->infRulesTriggerIndex['p'][$predicateLabel][array_search($key,$this->infRulesTriggerIndex['p'][$predicateLabel])]);
if(is_a($trigger['o'],'Node'))
{
$objectLabel=$trigger['o']->getLabel();
} else
{
$objectLabel='null';
}
unset ($this->infRulesTriggerIndex['o'][$objectLabel][array_search($key,$this->infRulesTriggerIndex['o'][$objectLabel])]);
} else
//remove from Rule-Entailment Index
{
$entailment=$this->infRules[$key]->getEntailment();
if(is_a($entailment['s'],'Node'))
{
$subjectLabel=$entailment['s']->getLabel();
} else
{
$subjectLabel='null';
}
unset ($this->infRulesEntailIndex['s'][$subjectLabel][array_search($key,$this->infRulesEntailIndex['s'][$subjectLabel])]);
if(is_a($entailment['p'],'Node'))
{
$predicateLabel=$entailment['p']->getLabel();
} else
{
$predicateLabel='null';
}
unset ($this->infRulesEntailIndex['p'][$predicateLabel][array_search($key,$this->infRulesEntailIndex['p'][$predicateLabel])]);
if(is_a($entailment['o'],'Node'))
{
$objectLabel=$entailment['o']->getLabel();
} else
{
$objectLabel='null';
}
unset ($this->infRulesEntailIndex['o'][$objectLabel][array_search($key,$this->infRulesEntailIndex['o'][$objectLabel])]);
}
//remove from statement-Rule Index
unset ($this->infRules[$key]);
}
unset($this->statementRuleIndex[$statementPosition]);
$return[]=$statementPosition;
};
}
} while($statementPosition!=-1);
//return the positions of the statements to be removed OR emty array
//if nothing was found.
return $return;
}
/**
* Returns a model, containing all Statements, having a Predicate, that
* is supported by the inference.
*
* @return object Model
* @access public
*/
function getSchema()
{
$res=new MemModel();
//Search the base-model for all statements, having a Predicate, that
//is supported by the inference.
foreach ($this->supportedInference as $inferencePredicateLabel)
{
$res->addModel($this->find(null, new Resource($inferencePredicateLabel), null));
}
return $res;
}
/**
* General method to replace nodes of a MemModel.
* This function is disabled in the Inference Model.
*
* @param object Node $subject
* @param object Node $predicate
* @param object Node $object
* @param object Node $replacement
* @access public
* @throws PhpError
*/
function replace($subject, $predicate, $object, $replacement)
{
$errmsg = RDFAPI_ERROR . '(class: InfModel; method: replace): This function is disabled in the Inference Model';
trigger_error($errmsg, E_USER_ERROR);
}
/**
* Method to search for triples using Perl-style regular expressions.
* NULL input for any parameter will match anything.
* Example: $result = $m->find_regex( NULL, NULL, $regex );
* Finds all triples where the label of the object node matches the regular
* expression.
* Returns an empty MemModel if nothing is found.
*
* This function is disabled in the Inference Model
*
* @param string $subject_regex
* @param string $predicate_regex
* @param string $object_regex
* @return object MemModel
* @access public
*/
function findRegex($subject_regex, $predicate_regex, $object_regex)
{
$errmsg = RDFAPI_ERROR . '(class: InfModel; method: findRegex):
This function is disabled in the
Inference Model';
trigger_error($errmsg, E_USER_ERROR);
}
/**
* Returns all tripels of a certain vocabulary.
* $vocabulary is the namespace of the vocabulary inluding a # : / char at
* the end.
* e.g. http://www.w3.org/2000/01/rdf-schema#
* Returns an empty MemModel if nothing is found.
*
* This function is disabled in the Inference Model.
*
* @param string $vocabulary
* @return object MemModel
* @access public
*/
function findVocabulary($vocabulary)
{
$errmsg = RDFAPI_ERROR . '(class: InfModel; method: findVocabulary):
This function is disabled in the
Inference Model';
trigger_error($errmsg, E_USER_ERROR);
}
/**
* Adds the URI or NULL to the Infrule trigger or entailment index.
*
*
* @param object infrule $infRule
* @param integer $infRulePosition
* @access private
*/
function _addInfruleToIndex(& $infRule,& $infRulePosition)
{
//Add the rule only to the trigger index, if it is a InfFModel
if (is_a($this,'InfModelF'))
{
//get the trigger
$trigger = $infRule->getTrigger();
//evaluate and set the index
if ($trigger['s'] == null)
{
$this->infRulesTriggerIndex['s']['null'][]=$infRulePosition;
} else
{
$this->infRulesTriggerIndex['s'][$trigger['s']->getLabel()][]=$infRulePosition;
};
if ($trigger['p'] == null)
{
$this->infRulesTriggerIndex['p']['null'][]=$infRulePosition;
} else
{
$this->infRulesTriggerIndex['p'][$trigger['p']->getLabel()][]=$infRulePosition;
};
if ($trigger['o'] == null)
{
$this->infRulesTriggerIndex['o']['null'][]=$infRulePosition;
} else
{
$this->infRulesTriggerIndex['o'][$trigger['o']->getLabel()][]=$infRulePosition;
};
} else
//add to entailment Index if it is a BModel
{
//get the entailment
$entailment = $infRule->getEntailment();
//evaluate the entailment and add to index
if (!is_a($entailment['s'],'Node'))
{
$this->infRulesEntailIndex['s']['null'][]=$infRulePosition;
} else
{
$this->infRulesEntailIndex['s'][$entailment['s']->getLabel()][]=$infRulePosition;
};
if (!is_a($entailment['p'],'Node'))
{
$this->infRulesEntailIndex['p']['null'][]=$infRulePosition;
} else
{
$this->infRulesEntailIndex['p'][$entailment['p']->getLabel()][]=$infRulePosition;
};
if (!is_a($entailment['o'],'Node'))
{
$this->infRulesEntailIndex['o']['null'][]=$infRulePosition;
} else
{
$this->infRulesEntailIndex['o'][$entailment['o']->getLabel()][]=$infRulePosition;
};
};
}
/**
* Searches the trigger-index for a matching trigger and returns an
* array of infRule positions.
*
*
* @param object infrule $infRule
* @return array integer
* @access private
*/
function _findRuleTriggerInIndex($statement)
{
$return=array();
//a statement's subject matches all triggers with null and the same URI
$subjectLabel=$statement->getLabelSubject();
$inIndexS=array();
if (isset($this->infRulesTriggerIndex['s']['null']))
$inIndexS=array_values($this->infRulesTriggerIndex['s']['null']);
if (isset($this->infRulesTriggerIndex['s'][$subjectLabel]))
$inIndexS= array_merge($inIndexS,array_values($this->infRulesTriggerIndex['s'][$subjectLabel]));
//a statement's predicate matches all triggers with null and the same URI
$predicateLabel=$statement->getLabelPredicate();
$inIndexP=array();
if (isset($this->infRulesTriggerIndex['p']['null']))
$inIndexP=array_values($this->infRulesTriggerIndex['p']['null']);
if (isset($this->infRulesTriggerIndex['p'][$predicateLabel]))
$inIndexP= array_merge($inIndexP,array_values($this->infRulesTriggerIndex['p'][$predicateLabel]));
//a statement's object matches all triggers with null and the same URI
$objectLabel=$statement->getLabelObject();
$inIndexO=array();
if (isset($this->infRulesTriggerIndex['o']['null']))
$inIndexO=array_values($this->infRulesTriggerIndex['o']['null']);
if (isset($this->infRulesTriggerIndex['o'][$objectLabel]))
$inIndexO= array_merge($inIndexO,array_values($this->infRulesTriggerIndex['o'][$objectLabel]));
//if an infrule position occurs in subject, predicate, and object index, add to result array.
foreach ($inIndexP as $positionP)
{
if (in_array($positionP,$inIndexO))
if (in_array($positionP,$inIndexS))
$return[]=$positionP;
}
return $return;
}
/**
* Searches the Entailment-index for a matching Entailment and returns an
* array of infRule positions.
*
*
* @param node or null $subject
* @param node or null $predicate
* @param node or null $object
* @return array integer
* @access private
*/
function _findRuleEntailmentInIndex($subject,$predicate,$object)
{
$return=array();
//a node matches all entailments with NULL or a matching URI
if(is_a($subject,'Node'))
{
$subjectLabel=$subject->getLabel();
$inIndexS=array();
if (isset($this->infRulesEntailIndex['s']['null'])) $inIndexS=array_values($this->infRulesEntailIndex['s']['null']);
if (isset($this->infRulesEntailIndex['s'][$subjectLabel])) $inIndexS= array_merge($inIndexS,array_values($this->infRulesEntailIndex['s'][$subjectLabel]));
} else
//if the subject search pattern is NULL, every rule will match the subject search patter
{
$inIndexS=array_keys($this->infRules);
}
if(is_a($predicate,'Node'))
{
$predicateLabel=$predicate->getLabel();
$inIndexP=array();
if (isset($this->infRulesEntailIndex['p']['null'])) $inIndexP=array_values($this->infRulesEntailIndex['p']['null']);
if (isset($this->infRulesEntailIndex['p'][$predicateLabel])) $inIndexP= array_merge($inIndexP,array_values($this->infRulesEntailIndex['p'][$predicateLabel]));
} else
{
$inIndexP=array_keys($this->infRules);
}
if(is_a($object,'Node'))
{
$objectLabel=$object->getLabel();
$inIndexO=array();
if (isset($this->infRulesEntailIndex['o']['null'])) $inIndexO=array_values($this->infRulesEntailIndex['o']['null']);
if (isset($this->infRulesEntailIndex['o'][$objectLabel])) $inIndexO= array_merge($inIndexO,array_values($this->infRulesEntailIndex['o'][$objectLabel]));
} else
{
$inIndexO=array_keys($this->infRules);
}
//if an infrule position occurs in subject, predicate, and object index, add to result array.
foreach ($inIndexP as $positionP)
{
if (in_array($positionP,$inIndexO))
if (in_array($positionP,$inIndexS))
$return[]=$positionP;
}
return $return;
}
/**
* Adds an InfRule to the InfModel.
* $statementPosition states the positiion of the statement, that created
* this rule, in the model->triples array.
*
*
* @param object Infrule $infRule
* @param integer $statementPosition
* @access private
*/
function _addInfRule($infRule, $statementPosition)
{
//add the rule
$this->infRules[]=$infRule;
//get the position of the added rule in the model
end($this->infRules);
$rulePosition=key($this->infRules);
//add the information to the index, that this statement
//added this rule.
$this->statementRuleIndex[$statementPosition][$rulePosition]=true;
//add informations to index over trigger & entailment
$this->_addInfruleToIndex($infRule,$rulePosition);
}
}
?>

View File

@ -0,0 +1,515 @@
<?php
// ----------------------------------------------------------------------------------
// Class: InfModelB
// ----------------------------------------------------------------------------------
/**
* A InfModelB extends the InfModel Class, with a backward chaining algorithm.
* Only the loaded or added base-triples are stored.
* A find-query evaluates the inference rules and recursively tries to find the statements.
* InfModelB memorises "Dead-Ends" until the next add() command, thus
* makin a second find much faster.
* InfModelB is safe for loops in Ontologies, that would cause infinite loops.
* WARNING: A find(null,null,null) might take very long.
*
* @version $Id$
* @author Daniel Westphal <mail at d-westphal dot de>
*
* @package infModel
* @access public
**/
class InfModelB extends InfModel
{
/**
* Array that holds combinations of inference rules with distinct
* find-querys, that don't lead to any inference.
*
* @var array
* @access private
*/
var $findDeadEnds;
/**
* Constructor
* You can supply a base_uri
*
* @param string $baseURI
* @access public
*/
function InfModelB($baseURI = null)
{
parent::InfModel($baseURI);
$this->findDeadEnds=array();
}
/**
* Adds a new triple to the Model without checking, if the statement
* is already in the Model. So if you want a duplicate free Model use
* the addWithoutDuplicates() function (which is slower then add())
*
* @param object Statement $statement
* @access public
* @throws PhpError
*/
function add($statement)
{
parent::add($statement);
//Reset the found dead-ends.
$this->findDeadEnds=array();
}
/**
* General method to search for triples.
* NULL input for any parameter will match anything.
* Example: $result = $m->find( NULL, NULL, $node );
* Finds all triples with $node as object.
* Returns an empty MemModel if nothing is found.
* To improve the search speed with big Models, call index(INDEX_TYPE)
* before seaching.
*
* It recursively searches in the statements and rules to find
* matching statements.
*
* @param object Node $subject
* @param object Node $predicate
* @param object Node $object
* @return object MemModel
* @access public
* @throws PhpError
*/
function find($subject,$predicate,$object)
{
$searchStringIndex=array();
$resultModel=new MemModel();
//add all infered statements without duplicates to the result model
foreach ($this->_infFind($subject,$predicate,$object,array())as $statement)
{
$resultModel->addWithoutDuplicates($statement);
};
return $resultModel;
}
/**
* This is the main inference method of the InfModelB
* The algorithm works as follows:
* Find all statements in the base model, that matches the current
* find-query.
* Check all rules, if they are able to deliver infered statements,
* that match the current find-query. Don't use rules with queries,
* that lead to dead-ends and don't use a rule-query-combination that
* was used before in this branch (ontology loops).
* If a rule is possible do deliver such statements, get a new
* find-query, that is possible to find those statements, that are able
* to trigger this rule.
* Call this _infFind method wirh the new find-query and entail the
* resulting statements.
* If this rule, wasn't able to return any statements with this distinct
* query, add this combination to the dead-ends.
* Return the statements from the base triples and those, which were infered.
*
* If $findOnlyFirstMatching is set to true, only the first match in
* the base-statements is entailed an returned (used in contains() and
* findFirstMatchingStatement() methods).
*
* You can set an offset to look for the first matching statement by setting the
* $offset var.
*
* It recursively searches in the statements and rules to find matching
* statements
*
* @param object Node $subject
* @param object Node $predicate
* @param object Node $object
* @param array $searchStringIndex
* @param boolean $findOnlyFirstMatching
* @param integer $offset
* @param integer $resultCount
* @return object array Statements
* @access private
*/
function _infFind ($subject,$predicate,$object, $searchStringIndex, $findOnlyFirstMatching = false, $offset = 0,$resultCount = 0 )
{
$return=array();
//Find all matching statements in the base statements
$findResult=parent::find($subject,$predicate,$object);
//For all found statements
foreach ($findResult->triples as $statement)
{
$return[]=$statement;
$resultCount++;
//Return, if only the firstMatchingStatement was wanted
if ($findOnlyFirstMatching && $resultCount > $offset)
return $return;
};
//Don't infer statements about the schema (rdfs:subClass, etc..)
//is false
if ($predicate == null ||
(is_a($predicate,'Node') &&
!in_array($predicate->getLabel(),$this->supportedInference))
)
//Check only Rules, that the EntailmentIndex returned.
foreach ($this->_findRuleEntailmentInIndex($subject,$predicate,$object) as $ruleKey)
{
$infRule=$this->infRules[$ruleKey];
$serializedRuleStatement=$ruleKey.serialize($subject).serialize($predicate).serialize($object);
//If it is to ontology loop and no dead-end
if (!in_array($serializedRuleStatement, $searchStringIndex) &&
!in_array($serializedRuleStatement, $this->findDeadEnds))
{
//Keep this distinct rule query cobination for
//this branch to detect loops
$searchStringIndex[]=$serializedRuleStatement;
//If the rule is able to deliver statements that match
//this query
if ($infRule->checkEntailment($subject,$predicate,$object))
{
//Get a modified find-query, that matches statements,
//that trigger this rule
$modefiedFind=$infRule->getModifiedFind($subject,$predicate,$object);
//Call this method with the new find-query
$infFindResult=$this->_infFind($modefiedFind['s'],
$modefiedFind['p'],
$modefiedFind['o'],
$searchStringIndex,
$findOnlyFirstMatching,
$offset,
$resultCount) ;
//If it deliverd statements that matches the trigger
if (isset($infFindResult[0]))
{
foreach ($infFindResult as $statement)
{
//Entail the statements and check, if they are not about the
//ontology
$newStatement=$infRule->entail($statement);
if (!in_array($newStatement->getLabelPredicate(),$this->supportedInference))
//Check if, the entailed statements are, what we are looking for
if($this->_nodeEqualsFind($subject,$newStatement->getSubject()) &&
$this->_nodeEqualsFind($predicate,$newStatement->getPredicate()) &&
$this->_nodeEqualsFind($object,$newStatement->getObject() ) )
{
//Add to results
$return[]=$newStatement;
$resultCount++;
//or return at once
if ($findOnlyFirstMatching && $resultCount > $offset)
return $return;
}
}
} else
{
//If there were no results of the rule-query-combination,
//mark this combination as a dead-end.
$this->findDeadEnds[]=$serializedRuleStatement;
}
}
}
}
//Return the array of the found statements
return $return;
}
/**
* Tests if the Model contains the given triple.
* TRUE if the triple belongs to the Model;
* FALSE otherwise.
*
* @param object Statement &$statement
* @return boolean
* @access public
*/
function contains(&$statement)
{
//throws an error, if $statement is not of class Statement
if(!is_a($statement,'Statement'))
trigger_error(RDFAPI_ERROR . '(class: InfModelB; method: contains):
$statement has to be object of class Statement', E_USER_ERROR);
//Call the _infFind method, but let it stop, if it finds the first match.
if (count( $this->_infFind($statement->getSubject(),
$statement->getPredicate(),
$statement->getObject(),
array(),true) ) >0)
{
return true;
} else
{
return false;
};
}
/**
* Searches for triples and returns the first matching statement.
* NULL input for any parameter will match anything.
* Example: $result = $m->findFirstMatchingStatement( NULL, NULL, $node );
* Returns the first statement of the MemModel where the object equals $node.
* Returns an NULL if nothing is found.
* You can define an offset to search for. Default = 0
*
* @param object Node $subject
* @param object Node $predicate
* @param object Node $object
* @param integer $offset
* @return object Statement
* @access public
*/
function findFirstMatchingStatement($subject, $predicate, $object, $offset = 0)
{
//Call the _infFind method, but let it stop, if it finds the
//first match.
$res= $this->_infFind($subject,$predicate,$object,array(),true,$offset);
if (isset($res[$offset]))
{
return $res[$offset];
} else
{
return NULL;
};
}
/**
* Returns a StatementIterator for traversing the Model.
*
* @access public
* @return object StatementIterator
*/
function & getStatementIterator()
{
// Import Package Utility
include_once(RDFAPI_INCLUDE_DIR.PACKAGE_UTILITY);
// Gets a MemModel by executing a find(null,null,null) to get a
//inferable statements.
// WARNING: might be slow
return new StatementIterator($this->getMemModel());
}
/**
* Number of all inferable triples in the Model.
* WARNING: uses a find(null,null,null) to find all statements! (might take a while)
*
* @param boolean
* @return integer
* @access public
*/
function size()
{
// Gets a MemModel by executing a find(null,null,null) to get a
//inferable statements.
// WARNING: might be slow
$res = $this->getMemModel();
return $res->size();
}
/**
* Create a MemModel containing all the triples (including inferred
* statements) of the current InfModelB.
*
* @return object MemModel
* @access public
*/
function & getMemModel()
{
$return=$this->find(null,null,null);
$return->setBaseURI($this->baseURI);
$return->addParsedNamespaces($this->getParsedNamespaces());
return $return;
}
/**
* 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;
}
/**
* Short Dump of the InfModelB.
*
* @access public
* @return string
*/
function toString()
{
return 'InfModelB[baseURI=' . $this->getBaseURI() . '; size=' . $this->size(true) . ']';
}
/**
* Dumps of the InfModelB including ALL inferable triples.
*
* @access public
* @return string
*/
function toStringIncludingTriples()
{
$dump = $this->toString() . chr(13);
$stateIt=new StatementIterator($this->find(null,null,null));
while($statement=$stateIt->next())
{
$dump .= $statement->toString() . chr(13);
}
return $dump;
}
/**
* Saves the RDF,N3 or N-Triple serialization of the full InfModelB
* (including inferred triples) to a file.
* You can decide to which format the model should be serialized by
* using a corresponding suffix-string as $type parameter. If no $type
* parameter is placed this method will serialize the model to XML/RDF
* format.
* Returns FALSE if the InfModelB couldn't be saved to the file.
*
* @access public
* @param string $filename
* @param string $type
* @throws PhpError
* @return boolean
*/
function saveAs($filename, $type ='rdf')
{
$memmodel=$this->getMemModel();
return $memmodel->saveAs($filename, $type);
}
/**
* Writes the RDF serialization of the Model including ALL inferable
* triples as HTML.
*
* @access public
*/
function writeAsHtml()
{
require_once(RDFAPI_INCLUDE_DIR.PACKAGE_SYNTAX_RDF);
$ser = new RdfSerializer();
$rdf =& $ser->serialize($this->getMemModel());
$rdf = htmlspecialchars($rdf, ENT_QUOTES);
$rdf = str_replace(' ', '&nbsp;', $rdf);
$rdf = nl2br($rdf);
echo $rdf;
}
/**
* Writes the RDF serialization of the Model including ALL inferable
* triples as HTML table.
*
* @access public
*/
function writeAsHtmlTable()
{
// Import Package Utility
include_once(RDFAPI_INCLUDE_DIR.PACKAGE_UTILITY);
RDFUtil::writeHTMLTable($this->getMemModel());
}
/**
* Writes the RDF serialization of the Model including ALL inferable
* triples.
*
* @access public
* @return string
*/
function writeRdfToString()
{
// Import Package Syntax
include_once(RDFAPI_INCLUDE_DIR.PACKAGE_SYNTAX_RDF);
$ser = new RdfSerializer();
$rdf =& $ser->serialize($this->getMemModel());
return $rdf;
}
/**
* Removes the triple from the MemModel.
* TRUE if the triple is removed.
* FALSE otherwise.
*
* Checks, if it touches any statements, that added inference rules
* to the model.
*
* @param object Statement $statement
* @return boolean
* @access public
* @throws PhpError
*/
function remove($statement)
{
if (parent::contains($statement))
{
if (in_array($statement->getLabelPredicate(),$this->supportedInference));
while (count($this->_removeFromInference($statement))>0);
$this->findDeadEnds=array();
return parent::remove($statement);
} else
{
return false;
}
}
/**
* Checks, if a single node matches a single find pattern.
* TRUE if the node matches.
* FALSE otherwise.
*
* Checks, if it touches any statements, that added inference rules
* to the model.
*
* @param object Statement $statement
* @return boolean
* @access private
*/
function _nodeEqualsFind(& $find, $node)
{
//If the find pattern is a node, use the nodes equal-method and
//return the result.
if (is_a($find,'Node'))
return $node->equals($find);
//Null-pattern matches anything.
if ($find == null)
{
return true;
} else
{
return false;
}
}
/**
* Returns a FindIterator for traversing the MemModel.
* Disabled in InfModelB.
*
* @access public
* @return object FindIterator
*/
function & findAsIterator($sub=null,$pred=null,$obj=null) {
$errmsg = RDFAPI_ERROR . '(class: InfModelB; method: findAsIterator):
This function is disabled in the
Inference Model';
trigger_error($errmsg, E_USER_ERROR);
}
}
?>

View File

@ -0,0 +1,406 @@
<?php
// ----------------------------------------------------------------------------------
// Class: InfModelF
// ----------------------------------------------------------------------------------
/**
* A InfModelF extends the InfModel Class, with a forward chaining algorithm.
* If a new statement is added, it is enferd at
* once and all the entailed statements are added too.
* When adding or removing a statement, that produced a new inference rule,
* all entailed statements are discarded and the whole base model is infered
* again.
* The InfModelF is safe for loops in Ontologies, that would cause infinite loops.
*
* @version $Id$
* @author Daniel Westphal <mail at d-westphal dot de>
*
* @package infModel
* @access public
**/
class InfModelF extends InfModel
{
/**
* Array that holds the position of the infered statements in the model.
*
* @var array
* @access private
*/
var $infPos;
/**
* Variable that influences the habbit when adding statements.
* Used by the loadModel method to increase performance.
*
* @var boolean
* @access private
*/
var $inferenceEnabled;
/**
* Constructor
* You can supply a base_uri.
*
* @param string $baseURI
* @access public
*/
function InfModelF($baseURI = NULL)
{
parent::InfModel($baseURI);
$this->infPos=array();
$this->inferenceEnabled=true;
}
/**
* Adds a new triple to the MemModel without checking if the statement
* is already in the MemModel.
* So if you want a duplicate free MemModel use the addWithoutDuplicates()
* function (which is slower then add())
* The statement is infered and all entailed statements are added.
*
* @param object Statement $statement
* @access public
* @throws PhpError
*/
function add ($statement)
{
parent::add($statement);
if ($this->inferenceEnabled)
{
foreach ($this->entailStatement($statement) as $state)
{
//a addWithoutDublicates construct
if(!$this->contains($state))
{
parent::add($state);
//save the position of the infered statements
end($this->triples);
$this->infPos[]=key($this->triples);
};
};
//apply the complete inference to the model, if the added statement was able to add a rule
if (in_array($statement->getLabelPredicate(),$this->supportedInference))
$this->applyInference();
}
}
/**
* Checks if a new statement is already in the MemModel and adds
* the statement, if it is not in the MemModel.
* addWithoutDuplicates() is significantly slower then add().
* Retruns TRUE if the statement is added.
* FALSE otherwise.
* The statement is infered and all entailed statements are added.
*
* @param object Statement $statement
* @return boolean
* @access public
* @throws PhpError
*/
function addWithoutDuplicates(& $statement)
{
if(!$this->contains($statement))
{
parent::add($statement);
if ($this->inferenceEnabled)
{
foreach ($this->entailStatement($statement) as $statement)
{
if(!$this->contains($statement))
{
parent::add($statement);
//save the position of the infered statements
end($this->triples);
$this->infPos[]=key($this->triples);
};
};
if (in_array($statement->getLabelPredicate(),$this->supportedInference))
$this->applyInference();
}
return true;
}
return false;
}
/**
* Entails every statement and adds the entailments if not already
* in the model.
*
* @access private
*/
function applyInference()
{
//check every statement in the model
foreach ($this->triples as $statement)
{
//gat all statements, that it recursively entails
foreach ($this->entailStatement($statement) as $statement)
{
if (!$this->contains($statement))
{
parent::add($statement);
//add the InfStatement position to the index
end($this->triples);
$this->infPos[]=key($this->triples);
};
};
};
}
/**
* Entails a statement by recursively using the _entailStatementRec
* method.
*
* @param object Statement $statement
* @return array of statements
* @access public
*/
function entailStatement (& $statement)
{
$infStatementsIndex=array();
return $this->_entailStatementRec($statement,$infStatementsIndex);
}
/**
* Recursive method, that checks the statement with the trigger of
* every rule. If the trigger matches and entails new statements,
* those statements are recursively infered too.
* The $infStatementsIndex array holds lready infered statements
* to prevent infinite loops.
*
*
* @param object Statement $statement
* @param array $infStatementsIndex
* @return array of statements
* @access private
*/
function _entailStatementRec ( $statement,& $infStatementsIndex)
{
$infStatements = array();
$return = array();
//dont entail statements about the supported inference-schema
if (!in_array($statement->getLabelPredicate(),$this->supportedInference))
{
//check only the rules, that were returned by the index
foreach ($this->_findRuleTriggerInIndex($statement) as $key )
{
$infRule=$this->infRules[$key];
$stateString=$key.serialize($statement);
//If the statement wasn't infered before
if (!in_array($stateString,$infStatementsIndex))
{
$infStatementsIndex[]=$stateString;
//Check, if the Statements triggers this rule
if($infRule->checkTrigger($statement))
{
$infStatement=$infRule->entail($statement);
#if(!$this->contains($infStatement))
{
$return[]=$infStatement;
$return=array_merge($return,
$this->_entailStatementRec($infStatement,
$infStatementsIndex));
};
};
};
};
};
return $return;
}
/**
* Removes all infered statements from the model but keeps the
* infernece rules.
*
* @access public
*/
function removeInfered()
{
$indexTmp=$this->indexed;
$this->index(-1);
foreach ($this->infPos as $key)
{
unset($this->triples[$key]);
};
$this->infPos=array();
$this->index($indexTmp);
}
/**
* Load a model from a file containing RDF, N3 or N-Triples.
* This function recognizes the suffix of the filename (.n3 or .rdf) and
* calls a suitable parser, if no $type is given as string
* ("rdf" "n3" "nt");
* If the model is not empty, the contents of the file is added to
* this DbModel.
*
* While loading the model, the inference entailing is disabled, but
* new inference rules are added to increase performance.
*
* @param string $filename
* @param string $type
* @access public
*/
function load($filename, $type = NULL)
{
//Disable entailing to increase performance
$this->inferenceEnabled=false;
parent::load($filename, $type);
//Enable entailing
$this->inferenceEnabled=true;
//Entail all statements
$this->applyInference();
}
/**
* Short Dump of the InfModelF.
*
* @access public
* @return string
*/
function toString() {
return 'InfModelF[baseURI=' . $this->getBaseURI() . ';
size=' . $this->size(true) . ']';
}
/**
* Create a MemModel containing all the triples (including inferred
* statements) of the current InfModelF.
*
* @return object MemModel
* @access public
*/
function & getMemModel()
{
$return= new MemModel();
$return->setBaseURI($this->baseURI);
foreach ($this->triples as $statement)
$return->add($statement);
$return->addParsedNamespaces($this->getParsedNamespaces());
return $return;
}
/**
* 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;
}
/**
* Removes the triple from the MemModel.
* TRUE if the triple is removed.
* FALSE otherwise.
*
* Checks, if it touches any statements, that added inference rules
* to the model
*
* @param object Statement $statement
* @return boolean
* @access public
* @throws PhpError
*/
function remove($statement)
{
//If the statement is in the model
if($this->contains($statement))
{
$inferenceRulesWereTouched=false;
//If the statement was able to add inference rules
if (in_array($statement->getLabelPredicate(),$this->supportedInference))
{
$statementPositions=$this->_removeFromInference($statement);
$inferenceRulesWereTouched=true;
} else
//get the position of all matching statements
{
$statementPositions=array();
//find the positions of the statements
$statementPosition=-1;
do
{
$statementPosition =
$this->findFirstMatchOff($statement->getSubject(),
$statement->getPredicate(),
$statement->getObject(),
$statementPosition+1);
if ($statementPosition!=-1)
$statementPositions[]=$statementPosition;
} while ($statementPosition != -1);
}
//remove matching statements
parent::remove($statement);
foreach ($statementPositions as $statementPosition)
{
//if the statement was infered, remove it from the index of the infered statements.
if (in_array($statementPosition,$this->infPos))
unset ($this->infPos[$statementPosition]);
}
if ($inferenceRulesWereTouched)
{
//remove the statement and re-entail the model
$this->removeInfered();
$this->applyInference();
}
return true;
} else
{
return false;
}
}
/**
* Adds another model to this MemModel.
* Duplicate statements are not removed.
* If you don't want duplicates, use unite().
* If any statement of the model to be added to this model contains a blankNode
* with an identifier already existing in this model, a new blankNode is generated.
*
* @param object Model $model
* @access public
* @throws phpErrpr
*
*/
function addModel(&$model)
{
//Disable entailing to increase performance
$this->inferenceEnabled=false;
parent::addModel($model);
//Enable entailing
$this->inferenceEnabled=true;
//Entail all statements
$this->applyInference();
}
};
?>

View File

@ -0,0 +1,19 @@
<?php
// ----------------------------------------------------------------------------------
// InfModel Package
// ----------------------------------------------------------------------------------
//
// Description : InfModel package
//
//
// Author: Daniel Westphal <mail at d-westphal dot de>
//
// ----------------------------------------------------------------------------------
// Include InfModel classes
require_once( RDFAPI_INCLUDE_DIR . 'infModel/InfRule.php');
require_once( RDFAPI_INCLUDE_DIR . 'infModel/InfStatement.php');
require_once( RDFAPI_INCLUDE_DIR . 'infModel/InfModel.php');
require_once( RDFAPI_INCLUDE_DIR . 'infModel/InfModelB.php');
require_once( RDFAPI_INCLUDE_DIR . 'infModel/InfModelF.php');
?>

View File

@ -0,0 +1,343 @@
<?php
// ----------------------------------------------------------------------------------
// Class: InfRule
// ----------------------------------------------------------------------------------
/**
* This class represents a single rule in a RDFS inference model.
* It primary constists of a trigger and an entailment.
* In the forward-chaining mode (RDFSFModel) a statement is checked,
* if it satisfies the trigger. If it does, a new statement is returned.
* In the backward-chaining mode (RDFSBModel) a find-query is checked
* with the entailment. If this entailment could satify the find-query,
* a new find-query is returned, that searches for statements that
* satisfy the trigger of this rule.
*
* @version $Id$
* @author Daniel Westphal <mail at d-westphal dot de>
*
* @package infModel
* @access public
**/
class InfRule
{
/**
* Array, that hold the trigger subject in key ['s'], the trigger
* predicate in ['p'], and the trigger object in ['o'].
* The array values can be NULL to match anything or be a node that
* has to be matched.
*
* @var array
* @access private
*/
var $trigger;
/**
* Array, that hold the entailment subject in key ['s'], the
* entailment predicate in ['p'], and the entailment object in ['o'].
* The array values can be a node that will be inserted in the
* returning statement, or '<s>' to insert the subject,'<p>' to insert
* the predicate, or '<o>' to insert the object of the checked statement
* to this position in the new returned statement.
*
* @var array
* @access private
*/
var $entailment;
/**
* Constructor
*
*
* @access public
*/
function infRule()
{
//initialising vars
$this->trigger=array();
$this->entailment=array();
}
/**
* Sets the trigger of this rule
* The values can be NULL to match anything or be a node that has to
* be matched.
*
* @param object Node OR NULL $subject
* @param object Node OR NULL $predicate
* @param object Node OR NULL $object
* @access public
* @throws PhpError
*/
function setTrigger ($subject, $predicate, $object)
{
//throw an error if subject, predicate, or object are neither
//node, nor null.
if(!is_a($subject,'Node') && $subject != null)
trigger_error(RDFAPI_ERROR . '(class: Infrule; method:
setTrigger): $subject has to be null or of class Node'
, E_USER_ERROR);
if(!is_a($predicate,'Node') && $predicate != null)
trigger_error(RDFAPI_ERROR . '(class: Infrule; method:
setTrigger): $predicate has to be null or of class Node'
, E_USER_ERROR);
if(!is_a($object,'Node') && $object != null)
trigger_error(RDFAPI_ERROR . '(class: Infrule; method:
setTrigger): $object has to be null or of class Node'
, E_USER_ERROR);
//set the trigger
$this->trigger['s']=$subject;
$this->trigger['p']=$predicate;
$this->trigger['o']=$object;
}
/**
* Sets the entailment of this rule
* The values can be NULL to match anything or be a node that has to
* be matched.
*
* @param object Node OR NULL $subject
* @param object Node OR NULL $predicate
* @param object Node OR NULL $object
* @access public
* @throws PhpError
*/
function setEntailment($subject,$predicate,$object)
{
//throw an error if subject, predicate, or object are neither node,
//nor <s>,<p>,<o>.
if(!is_a($subject,'Node') && !ereg('<[spo]>', $subject))
trigger_error(RDFAPI_ERROR . '(class: Infrule; method:
setEntailment): $subject has to be <s>,<p>,or <o> or of class Node'
, E_USER_ERROR);
if(!is_a($predicate,'Node') && !ereg('<[spo]>', $predicate))
trigger_error(RDFAPI_ERROR . '(class: Infrule; method:
setEntailment): $predicate has to be <s>,<p>,or <o> or of class Node'
, E_USER_ERROR);
if(!is_a($object,'Node') && !ereg('<[spo]>', $object))
trigger_error(RDFAPI_ERROR . '(class: Infrule; method:
setEntailment): $object has to be <s>,<p>,or <o> or of class Node'
, E_USER_ERROR);
$this->entailment['s']=$subject;
$this->entailment['p']=$predicate;
$this->entailment['o']=$object;
}
/**
* Checks, if the statement satisfies the trigger.
*
* @param object Statement
* @return boolean
* @access public
* @throws PhpError
*/
function checkTrigger(& $statement)
{
//is true, if the trigger is null to match anything
//or equals the statement's subject
$shouldFireS = $this->trigger['s'] == null ||
$this->trigger['s']->equals($statement->getSubject());
//is true, if the trigger is null to match anything
//or equals the statement's predicate
$shouldFireP = $this->trigger['p'] == null ||
$this->trigger['p']->equals($statement->getPredicate());
//is true, if the trigger is null to match anything
//or equals the statement's object
$shouldFireO = $this->trigger['o'] == null ||
$this->trigger['o']->equals($statement->getObject());
//returns true, if ALL are true
return $shouldFireS && $shouldFireP && $shouldFireO;
}
/**
* Checks, if this rule could entail a statement that matches
* a find of $subject,$predicate,$object.
*
* @param object Statement
* @return boolean
* @access public
* @throws PhpError
*/
function checkEntailment ($subject, $predicate, $object)
{
//true, if $subject is null, the entailment's subject matches
//anything, or the $subject equals the entailment-subject.
$matchesS= $subject == null ||
!is_a($this->entailment['s'],'Node') ||
$this->entailment['s']->equals($subject);
//true, if $predicate is null, the entailment's predicate matches
//anything, or the $predicate equals the entailment-predicate.
$matchesP= $predicate == null ||
!is_a($this->entailment['p'],'Node') ||
$this->entailment['p']->equals($predicate);
//true, if $object is null, the entailment's object matches
//anything, or the $object equals the entailment-object.
$matchesO= $object == null ||
!is_a($this->entailment['o'],'Node') ||
$this->entailment['o']->equals($object);
//returns true, if ALL are true
return $matchesS && $matchesP && $matchesO;
}
/**
* Returns a infered InfStatement by evaluating the statement with
* the entailment rule.
*
* @param object Statement
* @return object InfStatement
* @access public
* @throws PhpError
*/
function entail(& $statement)
{
//if the entailment's subject is <s>,<p>,or <o>, put the statements
//subject,predicate,or object into the subject of the
//entailed statement. If the entailment's subject is a node,
//add that node to the statement.
switch ($this->entailment['s'])
{
case '<s>':
$entailedSubject=$statement->getSubject();
break;
case '<p>':
$entailedSubject=$statement->getPredicate();
break;
case '<o>':
$entailedSubject=$statement->getObject();
break;
default:
$entailedSubject=$this->entailment['s'];
};
//if the entailment's predicate is <s>,<p>,or <o>, put the
//statements subject,predicate,or object into the predicate of
//the entailed statement. If the entailment's predicate is a node,
//add that node to the statement.
switch ($this->entailment['p'])
{
case '<s>':
$entailedPredicate=$statement->getSubject();
break;
case '<p>':
$entailedPredicate=$statement->getPredicate();
break;
case '<o>':
$entailedPredicate=$statement->getObject();
break;
default:
$entailedPredicate=$this->entailment['p'];
};
//if the entailment's object is <s>,<p>,or <o>, put the
//statements subject,predicate,or object into the object of
//the entailed statement. If the entailment's object is a node,
//add that node to the statement.
switch ($this->entailment['o'])
{
case '<s>':
$entailedObject=$statement->getSubject();
break;
case '<p>':
$entailedObject=$statement->getPredicate();
break;
case '<o>':
$entailedObject=$statement->getObject();
break;
default:
$entailedObject=$this->entailment['o'];
};
//return the infered statement
return (new InfStatement($entailedSubject,$entailedPredicate,$entailedObject));
}
/**
* Returns a find-query that matches statements, whose entailed
* statements would match the supplied find query.
*
* @param Node OR null $subject
* @param Node OR null $predicate
* @param Node OR null $object
* @return array
* @access public
* @throws PhpError
*/
function getModifiedFind( $subject, $predicate, $object)
{
$findSubject=$this->trigger['s'];
$findPredicate=$this->trigger['p'];
$findObject=$this->trigger['o'];
switch ($this->entailment['s'])
{
case '<s>':
$findSubject=$subject;
break;
case '<p>':
$findPredicate=$subject;
break;
case '<o>':
$findObject=$subject;
break;
};
switch ($this->entailment['p'])
{
case '<s>':
$findSubject=$predicate;
break;
case '<p>':
$findPredicate=$predicate;
break;
case '<o>':
$findObject=$predicate;
break;
};
switch ($this->entailment['o'])
{
case '<s>':
$findSubject=$object;
break;
case '<p>':
$findPredicate=$object;
break;
case '<o>':
$findObject=$object;
break;
};
return array('s' => $findSubject,
'p' => $findPredicate,
'o' => $findObject );
}
function getTrigger()
{
return array ( 's' => $this->trigger['s'],
'p' => $this->trigger['p'],
'o' => $this->trigger['o'],
);
}
function getEntailment()
{
return array ( 's' => $this->entailment['s'],
'p' => $this->entailment['p'],
'o' => $this->entailment['o'],
);
}
}
?>

View File

@ -0,0 +1,18 @@
<?php
// ----------------------------------------------------------------------------------
// Class: InfStatement
// ----------------------------------------------------------------------------------
/**
* An RDF statement which was entailed by a inference rule.
* See Statement Class for further information.
*
* @author Daniel Westphal <mail at d-westphal dot de>
* @version $Id$
* @package infModel
*/
class InfStatement extends Statement {
}
?>

View File

@ -0,0 +1,678 @@
<?php
// ----------------------------------------------------------------------------------
// Class: infModel
// ----------------------------------------------------------------------------------
/**
* A InfModel Model extends a MemModel , by adding the ability to infer statements from
* known statements and RDFS/OWL-Schematas.
* It uses the same interface as MemModel, thus making the
* infererence process hidden.
*
* @version $Id: InfModel.php 290 2006-06-22 12:23:24Z tgauss $
* @author Daniel Westphal <mail at d-westphal dot de>
*
* @package infModel
* @access public
*/
class InfModel extends MemModel
{
/**
* Array that holds the objects of the class Infrule,
* which were assigned by the _addToInference() function
*
* @var array
* @access private
*/
var $infRules;
/**
* Array of URI-Strings that produces Infrules.
*
* @var array
* @access private
*/
var $supportedInference;
/**
* Array of the connection between the infrules and the statement
* that assigned those rules.
* array[2][3]=true;array[2][5]=true means, that statement 2
* assigned rule 3 & 5 to the model.
*
* @var array
* @access private
*/
var $statementRuleIndex;
/**
* Array of the infRule triggers and the matching infrules.
* $this->infRulesTriggerIndex['s'] for subject index, ['p'] for predicates,
* and ['o'] for objects.
*
* @var array
* @access private
*/
var $infRulesTriggerIndex;
/**
* Array of the infRule entailments and the matching infrules.
* $this->infRulesEntailIndex['s'] for subject index, ['p'] for predicates,
* and ['o'] for objects.
*
* @var array
* @access private
*/
var $infRulesEntailIndex;
/**
* Constructor
* You can supply a base_uri
*
* @param string $baseURI
* @access public
*/
function InfModel ($baseURI = NULL)
{
//call the memmodel constructor method
parent::MemModel($baseURI);
//initialise vars
$this->infRulesTriggerIndex['s']=array();
$this->infRulesTriggerIndex['p']=array();
$this->infRulesTriggerIndex['o']=array();
$this->infRulesEntailIndex['s']=array();
$this->infRulesEntailIndex['p']=array();
$this->infRulesEntailIndex['o']=array();
$this->infRules=array();
$this->statementRuleIndex = array();
//arraylist of predicate labels that shall add inference rules
//to the model
//The constants, wich statements will create rules can be configured in constants.php
if (INF_RES_SUBCLASSOF)
$this->supportedInference[] = RDF_SCHEMA_URI.RDFS_SUBCLASSOF;
if (INF_RES_SUBPROPERTYOF)
$this->supportedInference[] = RDF_SCHEMA_URI.RDFS_SUBPROPERTYOF;
if (INF_RES_RANGE)
$this->supportedInference[] = RDF_SCHEMA_URI.RDFS_RANGE;
if (INF_RES_DOMAIN)
$this->supportedInference[] = RDF_SCHEMA_URI.RDFS_DOMAIN;
if (INF_RES_OWL_SAMEAS)
$this->supportedInference[] = OWL_URI.OWL_SAME_AS;
if (INF_RES_OWL_INVERSEOF)
$this->supportedInference[] = OWL_URI.OWL_INVERSE_OF;
//Rule: rdfs12
if (INF_RES_RULE_RDFS12)
{
$infRule=new InfRule();
$infRule->setTrigger(null,new Resource(RDF_NAMESPACE_URI.RDF_TYPE),new Resource(RDF_SCHEMA_URI.'ContainerMembershipProperty'));
$infRule->setEntailment('<s>',new Resource(RDF_SCHEMA_URI.RDFS_SUBPROPERTYOF),new Resource(RDF_SCHEMA_URI.'member'));
$this->_addInfRule($infRule,'base');
}
//Rule: rdfs6
if (INF_RES_RULE_RDFS6)
{
$infRule=new InfRule();
$infRule->setTrigger(null,new Resource(RDF_NAMESPACE_URI.RDF_TYPE),new Resource(RDF_NAMESPACE_URI.RDF_PROPERTY));
$infRule->setEntailment('<s>',new Resource(RDF_SCHEMA_URI.RDFS_SUBPROPERTYOF),'<s>');
$this->_addInfRule($infRule,'base');
}
//Rule: rdfs8
if (INF_RES_RULE_RDFS8)
{
$infRule=new InfRule();
$infRule->setTrigger(null,new Resource(RDF_NAMESPACE_URI.RDF_TYPE),new Resource(RDF_SCHEMA_URI.RDFS_CLASS));
$infRule->setEntailment('<s>',new Resource(RDF_SCHEMA_URI.RDFS_SUBCLASSOF),new Resource(RDF_SCHEMA_URI.RDFS_RESOURCE));
$this->_addInfRule($infRule,'base');
}
//Rule: rdfs10
if (INF_RES_RULE_RDFS10)
{
$infRule=new InfRule();
$infRule->setTrigger(null,new Resource(RDF_NAMESPACE_URI.RDF_TYPE),new Resource(RDF_SCHEMA_URI.RDFS_CLASS));
$infRule->setEntailment('<s>',new Resource(RDF_SCHEMA_URI.RDFS_SUBCLASSOF),'<s>');
$this->_addInfRule($infRule,'base');
}
//Rule: rdfs13
if (INF_RES_RULE_RDFS13)
{
$infRule=new InfRule();
$infRule->setTrigger(null,new Resource(RDF_NAMESPACE_URI.RDF_TYPE),new Resource(RDF_SCHEMA_URI.RDFS_DATATYPE));
$infRule->setEntailment('<s>',new Resource(RDF_SCHEMA_URI.RDFS_SUBCLASSOF),new Resource(RDF_SCHEMA_URI.RDFS_LITERAL));
$this->_addInfRule($infRule,'base');
}
}
/**
* 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);
};
}
/**
* This function analyses the statement's predicate and adds the
* matching infrule to the model.
*
* @param object Statement $statement
* @access private
*/
function _addToInference($statement)
{
$predicateLabel=$statement->getLabelPredicate();
//get the position of the the statement in the model
end($this->triples);
$statementPosition=key($this->triples);
switch ($predicateLabel)
{
case RDF_SCHEMA_URI.RDFS_SUBPROPERTYOF :
//create a new rule
$infRule=new InfRule();
//set the trigger to match all statements, having a
//predicate, that matches the subject of the statement that
//created this rule.
$infRule->setTrigger(null,$statement->getSubject(),null);
//set the infrule to return a statement, having the same
//subject and object as the statement, that asked for an
//entailment, and having the object of the statement,
//that created this rule as predicate.
$infRule->setEntailment('<s>',$statement->getObject(),'<o>');
//add the infule to Model, Statement/Rule-Index,
//and Rule/Trigger (or Rule/Entailment) index
$this->_addInfRule($infRule,$statementPosition);
break;
case RDF_SCHEMA_URI.RDFS_SUBCLASSOF :
$infRule=new InfRule();
$infRule->setTrigger(null,new Resource(RDF_NAMESPACE_URI.RDF_TYPE),$statement->getSubject());
$infRule->setEntailment('<s>',new Resource(RDF_NAMESPACE_URI.RDF_TYPE),$statement->getObject());
$this->infRules[]=$infRule;
$this->_addInfRule($infRule,$statementPosition);
break;
case RDF_SCHEMA_URI.RDFS_DOMAIN :
$infRule=new InfRule();
$infRule->setTrigger(null,$statement->getSubject(),null);
$infRule->setEntailment('<s>',new Resource(RDF_NAMESPACE_URI.RDF_TYPE),$statement->getObject());
$this->infRules[]=$infRule;
$this->_addInfRule($infRule,$statementPosition);
break;
case RDF_SCHEMA_URI.RDFS_RANGE :
$infRule=new InfRule();
$infRule->setTrigger(null,$statement->getSubject(),null);
$infRule->setEntailment('<o>',new Resource(RDF_NAMESPACE_URI.RDF_TYPE),$statement->getObject());
$this->infRules[]=$infRule;
$this->_addInfRule($infRule,$statementPosition);
break;
case OWL_URI.OWL_INVERSE_OF :
$infRule=new InfRule();
$infRule->setTrigger(null,$statement->getSubject(),null);
$infRule->setEntailment('<o>',$statement->getObject(),'<s>');
$this->infRules[]=$infRule;
$this->_addInfRule($infRule,$statementPosition);
$infRule=new InfRule();
$infRule->setTrigger(null,$statement->getObject(),null);
$infRule->setEntailment('<o>',$statement->getSubject(),'<s>');
$this->infRules[]=$infRule;
$this->_addInfRule($infRule,$statementPosition);
break;
case OWL_URI.OWL_SAME_AS :
$infRule=new InfRule();
$infRule->setTrigger($statement->getSubject(),null,null);
$infRule->setEntailment($statement->getObject(),'<p>','<o>');
$this->_addInfRule($infRule,$statementPosition);
$infRule=new InfRule();
$infRule->setTrigger($statement->getObject(),null,null);
$infRule->setEntailment($statement->getSubject(),'<p>','<o>');
$this->_addInfRule($infRule,$statementPosition);
$infRule=new InfRule();
$infRule->setTrigger(null,$statement->getSubject(),null);
$infRule->setEntailment('<s>',$statement->getObject(),'<o>');
$this->_addInfRule($infRule,$statementPosition);
$infRule=new InfRule();
$infRule->setTrigger(null,$statement->getObject(),null);
$infRule->setEntailment('<s>',$statement->getSubject(),'<o>');
$this->_addInfRule($infRule,$statementPosition);
$infRule=new InfRule();
$infRule->setTrigger(null,null,$statement->getSubject());
$infRule->setEntailment('<s>','<p>',$statement->getObject());
$this->_addInfRule($infRule,$statementPosition);
$infRule=new InfRule();
$infRule->setTrigger(null,null,$statement->getObject());
$infRule->setEntailment('<s>','<p>',$statement->getSubject());
$this->_addInfRule($infRule,$statementPosition);
break;
};
}
/**
* This function checks, which infrules were added by the statement and
* removes those.
*
* @param object Statement $statement
* @return integer
* @access private
*/
function _removeFromInference($statement)
{
$return= array();
$statementPosition=-1;
do
{
//get the position of the statement that should be removed
$statementPosition=$this->findFirstMatchOff($statement->getSubject(),
$statement->getPredicate(),
$statement->getObject(),
$statementPosition+1);
if ($statementPosition!=-1)
{
//if it added any rules
if (isset ($this->statementRuleIndex[$statementPosition]))
{
//remove all rules
foreach ($this->statementRuleIndex[$statementPosition] as $key => $value)
{
//remove from Rule-Trigger Index
if (is_a($this,'InfModelF'))
{
$trigger=$this->infRules[$key]->getTrigger();
if(is_a($trigger['s'],'Node'))
{
$subjectLabel=$trigger['s']->getLabel();
} else
{
$subjectLabel='null';
}
unset ($this->infRulesTriggerIndex['s'][$subjectLabel][array_search($key,$this->infRulesTriggerIndex['s'][$subjectLabel])]);
if(is_a($trigger['p'],'Node'))
{
$predicateLabel=$trigger['p']->getLabel();
} else
{
$predicateLabel='null';
}
unset ($this->infRulesTriggerIndex['p'][$predicateLabel][array_search($key,$this->infRulesTriggerIndex['p'][$predicateLabel])]);
if(is_a($trigger['o'],'Node'))
{
$objectLabel=$trigger['o']->getLabel();
} else
{
$objectLabel='null';
}
unset ($this->infRulesTriggerIndex['o'][$objectLabel][array_search($key,$this->infRulesTriggerIndex['o'][$objectLabel])]);
} else
//remove from Rule-Entailment Index
{
$entailment=$this->infRules[$key]->getEntailment();
if(is_a($entailment['s'],'Node'))
{
$subjectLabel=$entailment['s']->getLabel();
} else
{
$subjectLabel='null';
}
unset ($this->infRulesEntailIndex['s'][$subjectLabel][array_search($key,$this->infRulesEntailIndex['s'][$subjectLabel])]);
if(is_a($entailment['p'],'Node'))
{
$predicateLabel=$entailment['p']->getLabel();
} else
{
$predicateLabel='null';
}
unset ($this->infRulesEntailIndex['p'][$predicateLabel][array_search($key,$this->infRulesEntailIndex['p'][$predicateLabel])]);
if(is_a($entailment['o'],'Node'))
{
$objectLabel=$entailment['o']->getLabel();
} else
{
$objectLabel='null';
}
unset ($this->infRulesEntailIndex['o'][$objectLabel][array_search($key,$this->infRulesEntailIndex['o'][$objectLabel])]);
}
//remove from statement-Rule Index
unset ($this->infRules[$key]);
}
unset($this->statementRuleIndex[$statementPosition]);
$return[]=$statementPosition;
};
}
} while($statementPosition!=-1);
//return the positions of the statements to be removed OR emty array
//if nothing was found.
return $return;
}
/**
* Returns a model, containing all Statements, having a Predicate, that
* is supported by the inference.
*
* @return object Model
* @access public
*/
function getSchema()
{
$res=new MemModel();
//Search the base-model for all statements, having a Predicate, that
//is supported by the inference.
foreach ($this->supportedInference as $inferencePredicateLabel)
{
$res->addModel($this->find(null, new Resource($inferencePredicateLabel), null));
}
return $res;
}
/**
* General method to replace nodes of a MemModel.
* This function is disabled in the Inference Model.
*
* @param object Node $subject
* @param object Node $predicate
* @param object Node $object
* @param object Node $replacement
* @access public
* @throws PhpError
*/
function replace($subject, $predicate, $object, $replacement)
{
$errmsg = RDFAPI_ERROR . '(class: InfModel; method: replace): This function is disabled in the Inference Model';
trigger_error($errmsg, E_USER_ERROR);
}
/**
* Method to search for triples using Perl-style regular expressions.
* NULL input for any parameter will match anything.
* Example: $result = $m->find_regex( NULL, NULL, $regex );
* Finds all triples where the label of the object node matches the regular
* expression.
* Returns an empty MemModel if nothing is found.
*
* This function is disabled in the Inference Model
*
* @param string $subject_regex
* @param string $predicate_regex
* @param string $object_regex
* @return object MemModel
* @access public
*/
function findRegex($subject_regex, $predicate_regex, $object_regex)
{
$errmsg = RDFAPI_ERROR . '(class: InfModel; method: findRegex):
This function is disabled in the
Inference Model';
trigger_error($errmsg, E_USER_ERROR);
}
/**
* Returns all tripels of a certain vocabulary.
* $vocabulary is the namespace of the vocabulary inluding a # : / char at
* the end.
* e.g. http://www.w3.org/2000/01/rdf-schema#
* Returns an empty MemModel if nothing is found.
*
* This function is disabled in the Inference Model.
*
* @param string $vocabulary
* @return object MemModel
* @access public
*/
function findVocabulary($vocabulary)
{
$errmsg = RDFAPI_ERROR . '(class: InfModel; method: findVocabulary):
This function is disabled in the
Inference Model';
trigger_error($errmsg, E_USER_ERROR);
}
/**
* Adds the URI or NULL to the Infrule trigger or entailment index.
*
*
* @param object infrule $infRule
* @param integer $infRulePosition
* @access private
*/
function _addInfruleToIndex(& $infRule,& $infRulePosition)
{
//Add the rule only to the trigger index, if it is a InfFModel
if (is_a($this,'InfModelF'))
{
//get the trigger
$trigger = $infRule->getTrigger();
//evaluate and set the index
if ($trigger['s'] == null)
{
$this->infRulesTriggerIndex['s']['null'][]=$infRulePosition;
} else
{
$this->infRulesTriggerIndex['s'][$trigger['s']->getLabel()][]=$infRulePosition;
};
if ($trigger['p'] == null)
{
$this->infRulesTriggerIndex['p']['null'][]=$infRulePosition;
} else
{
$this->infRulesTriggerIndex['p'][$trigger['p']->getLabel()][]=$infRulePosition;
};
if ($trigger['o'] == null)
{
$this->infRulesTriggerIndex['o']['null'][]=$infRulePosition;
} else
{
$this->infRulesTriggerIndex['o'][$trigger['o']->getLabel()][]=$infRulePosition;
};
} else
//add to entailment Index if it is a BModel
{
//get the entailment
$entailment = $infRule->getEntailment();
//evaluate the entailment and add to index
if (!is_a($entailment['s'],'Node'))
{
$this->infRulesEntailIndex['s']['null'][]=$infRulePosition;
} else
{
$this->infRulesEntailIndex['s'][$entailment['s']->getLabel()][]=$infRulePosition;
};
if (!is_a($entailment['p'],'Node'))
{
$this->infRulesEntailIndex['p']['null'][]=$infRulePosition;
} else
{
$this->infRulesEntailIndex['p'][$entailment['p']->getLabel()][]=$infRulePosition;
};
if (!is_a($entailment['o'],'Node'))
{
$this->infRulesEntailIndex['o']['null'][]=$infRulePosition;
} else
{
$this->infRulesEntailIndex['o'][$entailment['o']->getLabel()][]=$infRulePosition;
};
};
}
/**
* Searches the trigger-index for a matching trigger and returns an
* array of infRule positions.
*
*
* @param object infrule $infRule
* @return array integer
* @access private
*/
function _findRuleTriggerInIndex($statement)
{
$return=array();
//a statement's subject matches all triggers with null and the same URI
$subjectLabel=$statement->getLabelSubject();
$inIndexS=array();
if (isset($this->infRulesTriggerIndex['s']['null']))
$inIndexS=array_values($this->infRulesTriggerIndex['s']['null']);
if (isset($this->infRulesTriggerIndex['s'][$subjectLabel]))
$inIndexS= array_merge($inIndexS,array_values($this->infRulesTriggerIndex['s'][$subjectLabel]));
//a statement's predicate matches all triggers with null and the same URI
$predicateLabel=$statement->getLabelPredicate();
$inIndexP=array();
if (isset($this->infRulesTriggerIndex['p']['null']))
$inIndexP=array_values($this->infRulesTriggerIndex['p']['null']);
if (isset($this->infRulesTriggerIndex['p'][$predicateLabel]))
$inIndexP= array_merge($inIndexP,array_values($this->infRulesTriggerIndex['p'][$predicateLabel]));
//a statement's object matches all triggers with null and the same URI
$objectLabel=$statement->getLabelObject();
$inIndexO=array();
if (isset($this->infRulesTriggerIndex['o']['null']))
$inIndexO=array_values($this->infRulesTriggerIndex['o']['null']);
if (isset($this->infRulesTriggerIndex['o'][$objectLabel]))
$inIndexO= array_merge($inIndexO,array_values($this->infRulesTriggerIndex['o'][$objectLabel]));
//if an infrule position occurs in subject, predicate, and object index, add to result array.
foreach ($inIndexP as $positionP)
{
if (in_array($positionP,$inIndexO))
if (in_array($positionP,$inIndexS))
$return[]=$positionP;
}
return $return;
}
/**
* Searches the Entailment-index for a matching Entailment and returns an
* array of infRule positions.
*
*
* @param node or null $subject
* @param node or null $predicate
* @param node or null $object
* @return array integer
* @access private
*/
function _findRuleEntailmentInIndex($subject,$predicate,$object)
{
$return=array();
//a node matches all entailments with NULL or a matching URI
if(is_a($subject,'Node'))
{
$subjectLabel=$subject->getLabel();
$inIndexS=array();
if (isset($this->infRulesEntailIndex['s']['null'])) $inIndexS=array_values($this->infRulesEntailIndex['s']['null']);
if (isset($this->infRulesEntailIndex['s'][$subjectLabel])) $inIndexS= array_merge($inIndexS,array_values($this->infRulesEntailIndex['s'][$subjectLabel]));
} else
//if the subject search pattern is NULL, every rule will match the subject search patter
{
$inIndexS=array_keys($this->infRules);
}
if(is_a($predicate,'Node'))
{
$predicateLabel=$predicate->getLabel();
$inIndexP=array();
if (isset($this->infRulesEntailIndex['p']['null'])) $inIndexP=array_values($this->infRulesEntailIndex['p']['null']);
if (isset($this->infRulesEntailIndex['p'][$predicateLabel])) $inIndexP= array_merge($inIndexP,array_values($this->infRulesEntailIndex['p'][$predicateLabel]));
} else
{
$inIndexP=array_keys($this->infRules);
}
if(is_a($object,'Node'))
{
$objectLabel=$object->getLabel();
$inIndexO=array();
if (isset($this->infRulesEntailIndex['o']['null'])) $inIndexO=array_values($this->infRulesEntailIndex['o']['null']);
if (isset($this->infRulesEntailIndex['o'][$objectLabel])) $inIndexO= array_merge($inIndexO,array_values($this->infRulesEntailIndex['o'][$objectLabel]));
} else
{
$inIndexO=array_keys($this->infRules);
}
//if an infrule position occurs in subject, predicate, and object index, add to result array.
foreach ($inIndexP as $positionP)
{
if (in_array($positionP,$inIndexO))
if (in_array($positionP,$inIndexS))
$return[]=$positionP;
}
return $return;
}
/**
* Adds an InfRule to the InfModel.
* $statementPosition states the positiion of the statement, that created
* this rule, in the model->triples array.
*
*
* @param object Infrule $infRule
* @param integer $statementPosition
* @access private
*/
function _addInfRule($infRule, $statementPosition)
{
//add the rule
$this->infRules[]=$infRule;
//get the position of the added rule in the model
end($this->infRules);
$rulePosition=key($this->infRules);
//add the information to the index, that this statement
//added this rule.
$this->statementRuleIndex[$statementPosition][$rulePosition]=true;
//add informations to index over trigger & entailment
$this->_addInfruleToIndex($infRule,$rulePosition);
}
}
?>

View File

@ -0,0 +1,515 @@
<?php
// ----------------------------------------------------------------------------------
// Class: InfModelB
// ----------------------------------------------------------------------------------
/**
* A InfModelB extends the InfModel Class, with a backward chaining algorithm.
* Only the loaded or added base-triples are stored.
* A find-query evaluates the inference rules and recursively tries to find the statements.
* InfModelB memorises "Dead-Ends" until the next add() command, thus
* makin a second find much faster.
* InfModelB is safe for loops in Ontologies, that would cause infinite loops.
* WARNING: A find(null,null,null) might take very long.
*
* @version $Id: InfModelB.php 290 2006-06-22 12:23:24Z tgauss $
* @author Daniel Westphal <mail at d-westphal dot de>
*
* @package infModel
* @access public
**/
class InfModelB extends InfModel
{
/**
* Array that holds combinations of inference rules with distinct
* find-querys, that don't lead to any inference.
*
* @var array
* @access private
*/
var $findDeadEnds;
/**
* Constructor
* You can supply a base_uri
*
* @param string $baseURI
* @access public
*/
function InfModelB($baseURI = null)
{
parent::InfModel($baseURI);
$this->findDeadEnds=array();
}
/**
* Adds a new triple to the Model without checking, if the statement
* is already in the Model. So if you want a duplicate free Model use
* the addWithoutDuplicates() function (which is slower then add())
*
* @param object Statement $statement
* @access public
* @throws PhpError
*/
function add($statement)
{
parent::add($statement);
//Reset the found dead-ends.
$this->findDeadEnds=array();
}
/**
* General method to search for triples.
* NULL input for any parameter will match anything.
* Example: $result = $m->find( NULL, NULL, $node );
* Finds all triples with $node as object.
* Returns an empty MemModel if nothing is found.
* To improve the search speed with big Models, call index(INDEX_TYPE)
* before seaching.
*
* It recursively searches in the statements and rules to find
* matching statements.
*
* @param object Node $subject
* @param object Node $predicate
* @param object Node $object
* @return object MemModel
* @access public
* @throws PhpError
*/
function find($subject,$predicate,$object)
{
$searchStringIndex=array();
$resultModel=new MemModel();
//add all infered statements without duplicates to the result model
foreach ($this->_infFind($subject,$predicate,$object,array())as $statement)
{
$resultModel->addWithoutDuplicates($statement);
};
return $resultModel;
}
/**
* This is the main inference method of the InfModelB
* The algorithm works as follows:
* Find all statements in the base model, that matches the current
* find-query.
* Check all rules, if they are able to deliver infered statements,
* that match the current find-query. Don't use rules with queries,
* that lead to dead-ends and don't use a rule-query-combination that
* was used before in this branch (ontology loops).
* If a rule is possible do deliver such statements, get a new
* find-query, that is possible to find those statements, that are able
* to trigger this rule.
* Call this _infFind method wirh the new find-query and entail the
* resulting statements.
* If this rule, wasn't able to return any statements with this distinct
* query, add this combination to the dead-ends.
* Return the statements from the base triples and those, which were infered.
*
* If $findOnlyFirstMatching is set to true, only the first match in
* the base-statements is entailed an returned (used in contains() and
* findFirstMatchingStatement() methods).
*
* You can set an offset to look for the first matching statement by setting the
* $offset var.
*
* It recursively searches in the statements and rules to find matching
* statements
*
* @param object Node $subject
* @param object Node $predicate
* @param object Node $object
* @param array $searchStringIndex
* @param boolean $findOnlyFirstMatching
* @param integer $offset
* @param integer $resultCount
* @return object array Statements
* @access private
*/
function _infFind ($subject,$predicate,$object, $searchStringIndex, $findOnlyFirstMatching = false, $offset = 0,$resultCount = 0 )
{
$return=array();
//Find all matching statements in the base statements
$findResult=parent::find($subject,$predicate,$object);
//For all found statements
foreach ($findResult->triples as $statement)
{
$return[]=$statement;
$resultCount++;
//Return, if only the firstMatchingStatement was wanted
if ($findOnlyFirstMatching && $resultCount > $offset)
return $return;
};
//Don't infer statements about the schema (rdfs:subClass, etc..)
//is false
if ($predicate == null ||
(is_a($predicate,'Node') &&
!in_array($predicate->getLabel(),$this->supportedInference))
)
//Check only Rules, that the EntailmentIndex returned.
foreach ($this->_findRuleEntailmentInIndex($subject,$predicate,$object) as $ruleKey)
{
$infRule=$this->infRules[$ruleKey];
$serializedRuleStatement=$ruleKey.serialize($subject).serialize($predicate).serialize($object);
//If it is to ontology loop and no dead-end
if (!in_array($serializedRuleStatement, $searchStringIndex) &&
!in_array($serializedRuleStatement, $this->findDeadEnds))
{
//Keep this distinct rule query cobination for
//this branch to detect loops
$searchStringIndex[]=$serializedRuleStatement;
//If the rule is able to deliver statements that match
//this query
if ($infRule->checkEntailment($subject,$predicate,$object))
{
//Get a modified find-query, that matches statements,
//that trigger this rule
$modefiedFind=$infRule->getModifiedFind($subject,$predicate,$object);
//Call this method with the new find-query
$infFindResult=$this->_infFind($modefiedFind['s'],
$modefiedFind['p'],
$modefiedFind['o'],
$searchStringIndex,
$findOnlyFirstMatching,
$offset,
$resultCount) ;
//If it deliverd statements that matches the trigger
if (isset($infFindResult[0]))
{
foreach ($infFindResult as $statement)
{
//Entail the statements and check, if they are not about the
//ontology
$newStatement=$infRule->entail($statement);
if (!in_array($newStatement->getLabelPredicate(),$this->supportedInference))
//Check if, the entailed statements are, what we are looking for
if($this->_nodeEqualsFind($subject,$newStatement->getSubject()) &&
$this->_nodeEqualsFind($predicate,$newStatement->getPredicate()) &&
$this->_nodeEqualsFind($object,$newStatement->getObject() ) )
{
//Add to results
$return[]=$newStatement;
$resultCount++;
//or return at once
if ($findOnlyFirstMatching && $resultCount > $offset)
return $return;
}
}
} else
{
//If there were no results of the rule-query-combination,
//mark this combination as a dead-end.
$this->findDeadEnds[]=$serializedRuleStatement;
}
}
}
}
//Return the array of the found statements
return $return;
}
/**
* Tests if the Model contains the given triple.
* TRUE if the triple belongs to the Model;
* FALSE otherwise.
*
* @param object Statement &$statement
* @return boolean
* @access public
*/
function contains(&$statement)
{
//throws an error, if $statement is not of class Statement
if(!is_a($statement,'Statement'))
trigger_error(RDFAPI_ERROR . '(class: InfModelB; method: contains):
$statement has to be object of class Statement', E_USER_ERROR);
//Call the _infFind method, but let it stop, if it finds the first match.
if (count( $this->_infFind($statement->getSubject(),
$statement->getPredicate(),
$statement->getObject(),
array(),true) ) >0)
{
return true;
} else
{
return false;
};
}
/**
* Searches for triples and returns the first matching statement.
* NULL input for any parameter will match anything.
* Example: $result = $m->findFirstMatchingStatement( NULL, NULL, $node );
* Returns the first statement of the MemModel where the object equals $node.
* Returns an NULL if nothing is found.
* You can define an offset to search for. Default = 0
*
* @param object Node $subject
* @param object Node $predicate
* @param object Node $object
* @param integer $offset
* @return object Statement
* @access public
*/
function findFirstMatchingStatement($subject, $predicate, $object, $offset = 0)
{
//Call the _infFind method, but let it stop, if it finds the
//first match.
$res= $this->_infFind($subject,$predicate,$object,array(),true,$offset);
if (isset($res[$offset]))
{
return $res[$offset];
} else
{
return NULL;
};
}
/**
* Returns a StatementIterator for traversing the Model.
*
* @access public
* @return object StatementIterator
*/
function & getStatementIterator()
{
// Import Package Utility
include_once(RDFAPI_INCLUDE_DIR.PACKAGE_UTILITY);
// Gets a MemModel by executing a find(null,null,null) to get a
//inferable statements.
// WARNING: might be slow
return new StatementIterator($this->getMemModel());
}
/**
* Number of all inferable triples in the Model.
* WARNING: uses a find(null,null,null) to find all statements! (might take a while)
*
* @param boolean
* @return integer
* @access public
*/
function size()
{
// Gets a MemModel by executing a find(null,null,null) to get a
//inferable statements.
// WARNING: might be slow
$res = $this->getMemModel();
return $res->size();
}
/**
* Create a MemModel containing all the triples (including inferred
* statements) of the current InfModelB.
*
* @return object MemModel
* @access public
*/
function & getMemModel()
{
$return=$this->find(null,null,null);
$return->setBaseURI($this->baseURI);
$return->addParsedNamespaces($this->getParsedNamespaces());
return $return;
}
/**
* 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;
}
/**
* Short Dump of the InfModelB.
*
* @access public
* @return string
*/
function toString()
{
return 'InfModelB[baseURI=' . $this->getBaseURI() . '; size=' . $this->size(true) . ']';
}
/**
* Dumps of the InfModelB including ALL inferable triples.
*
* @access public
* @return string
*/
function toStringIncludingTriples()
{
$dump = $this->toString() . chr(13);
$stateIt=new StatementIterator($this->find(null,null,null));
while($statement=$stateIt->next())
{
$dump .= $statement->toString() . chr(13);
}
return $dump;
}
/**
* Saves the RDF,N3 or N-Triple serialization of the full InfModelB
* (including inferred triples) to a file.
* You can decide to which format the model should be serialized by
* using a corresponding suffix-string as $type parameter. If no $type
* parameter is placed this method will serialize the model to XML/RDF
* format.
* Returns FALSE if the InfModelB couldn't be saved to the file.
*
* @access public
* @param string $filename
* @param string $type
* @throws PhpError
* @return boolean
*/
function saveAs($filename, $type ='rdf')
{
$memmodel=$this->getMemModel();
return $memmodel->saveAs($filename, $type);
}
/**
* Writes the RDF serialization of the Model including ALL inferable
* triples as HTML.
*
* @access public
*/
function writeAsHtml()
{
require_once(RDFAPI_INCLUDE_DIR.PACKAGE_SYNTAX_RDF);
$ser = new RdfSerializer();
$rdf =& $ser->serialize($this->getMemModel());
$rdf = htmlspecialchars($rdf, ENT_QUOTES);
$rdf = str_replace(' ', '&nbsp;', $rdf);
$rdf = nl2br($rdf);
echo $rdf;
}
/**
* Writes the RDF serialization of the Model including ALL inferable
* triples as HTML table.
*
* @access public
*/
function writeAsHtmlTable()
{
// Import Package Utility
include_once(RDFAPI_INCLUDE_DIR.PACKAGE_UTILITY);
RDFUtil::writeHTMLTable($this->getMemModel());
}
/**
* Writes the RDF serialization of the Model including ALL inferable
* triples.
*
* @access public
* @return string
*/
function writeRdfToString()
{
// Import Package Syntax
include_once(RDFAPI_INCLUDE_DIR.PACKAGE_SYNTAX_RDF);
$ser = new RdfSerializer();
$rdf =& $ser->serialize($this->getMemModel());
return $rdf;
}
/**
* Removes the triple from the MemModel.
* TRUE if the triple is removed.
* FALSE otherwise.
*
* Checks, if it touches any statements, that added inference rules
* to the model.
*
* @param object Statement $statement
* @return boolean
* @access public
* @throws PhpError
*/
function remove($statement)
{
if (parent::contains($statement))
{
if (in_array($statement->getLabelPredicate(),$this->supportedInference));
while (count($this->_removeFromInference($statement))>0);
$this->findDeadEnds=array();
return parent::remove($statement);
} else
{
return false;
}
}
/**
* Checks, if a single node matches a single find pattern.
* TRUE if the node matches.
* FALSE otherwise.
*
* Checks, if it touches any statements, that added inference rules
* to the model.
*
* @param object Statement $statement
* @return boolean
* @access private
*/
function _nodeEqualsFind(& $find, $node)
{
//If the find pattern is a node, use the nodes equal-method and
//return the result.
if (is_a($find,'Node'))
return $node->equals($find);
//Null-pattern matches anything.
if ($find == null)
{
return true;
} else
{
return false;
}
}
/**
* Returns a FindIterator for traversing the MemModel.
* Disabled in InfModelB.
*
* @access public
* @return object FindIterator
*/
function & findAsIterator($sub=null,$pred=null,$obj=null) {
$errmsg = RDFAPI_ERROR . '(class: InfModelB; method: findAsIterator):
This function is disabled in the
Inference Model';
trigger_error($errmsg, E_USER_ERROR);
}
}
?>

View File

@ -0,0 +1,406 @@
<?php
// ----------------------------------------------------------------------------------
// Class: InfModelF
// ----------------------------------------------------------------------------------
/**
* A InfModelF extends the InfModel Class, with a forward chaining algorithm.
* If a new statement is added, it is enferd at
* once and all the entailed statements are added too.
* When adding or removing a statement, that produced a new inference rule,
* all entailed statements are discarded and the whole base model is infered
* again.
* The InfModelF is safe for loops in Ontologies, that would cause infinite loops.
*
* @version $Id: InfModelF.php 320 2006-11-21 09:38:51Z tgauss $
* @author Daniel Westphal <mail at d-westphal dot de>
*
* @package infModel
* @access public
**/
class InfModelF extends InfModel
{
/**
* Array that holds the position of the infered statements in the model.
*
* @var array
* @access private
*/
var $infPos;
/**
* Variable that influences the habbit when adding statements.
* Used by the loadModel method to increase performance.
*
* @var boolean
* @access private
*/
var $inferenceEnabled;
/**
* Constructor
* You can supply a base_uri.
*
* @param string $baseURI
* @access public
*/
function InfModelF($baseURI = NULL)
{
parent::InfModel($baseURI);
$this->infPos=array();
$this->inferenceEnabled=true;
}
/**
* Adds a new triple to the MemModel without checking if the statement
* is already in the MemModel.
* So if you want a duplicate free MemModel use the addWithoutDuplicates()
* function (which is slower then add())
* The statement is infered and all entailed statements are added.
*
* @param object Statement $statement
* @access public
* @throws PhpError
*/
function add ($statement)
{
parent::add($statement);
if ($this->inferenceEnabled)
{
foreach ($this->entailStatement($statement) as $state)
{
//a addWithoutDublicates construct
if(!$this->contains($state))
{
parent::add($state);
//save the position of the infered statements
end($this->triples);
$this->infPos[]=key($this->triples);
};
};
//apply the complete inference to the model, if the added statement was able to add a rule
if (in_array($statement->getLabelPredicate(),$this->supportedInference))
$this->applyInference();
}
}
/**
* Checks if a new statement is already in the MemModel and adds
* the statement, if it is not in the MemModel.
* addWithoutDuplicates() is significantly slower then add().
* Retruns TRUE if the statement is added.
* FALSE otherwise.
* The statement is infered and all entailed statements are added.
*
* @param object Statement $statement
* @return boolean
* @access public
* @throws PhpError
*/
function addWithoutDuplicates(& $statement)
{
if(!$this->contains($statement))
{
parent::add($statement);
if ($this->inferenceEnabled)
{
foreach ($this->entailStatement($statement) as $statement)
{
if(!$this->contains($statement))
{
parent::add($statement);
//save the position of the infered statements
end($this->triples);
$this->infPos[]=key($this->triples);
};
};
if (in_array($statement->getLabelPredicate(),$this->supportedInference))
$this->applyInference();
}
return true;
}
return false;
}
/**
* Entails every statement and adds the entailments if not already
* in the model.
*
* @access private
*/
function applyInference()
{
//check every statement in the model
foreach ($this->triples as $statement)
{
//gat all statements, that it recursively entails
foreach ($this->entailStatement($statement) as $statement)
{
if (!$this->contains($statement))
{
parent::add($statement);
//add the InfStatement position to the index
end($this->triples);
$this->infPos[]=key($this->triples);
};
};
};
}
/**
* Entails a statement by recursively using the _entailStatementRec
* method.
*
* @param object Statement $statement
* @return array of statements
* @access public
*/
function entailStatement (& $statement)
{
$infStatementsIndex=array();
return $this->_entailStatementRec($statement,$infStatementsIndex);
}
/**
* Recursive method, that checks the statement with the trigger of
* every rule. If the trigger matches and entails new statements,
* those statements are recursively infered too.
* The $infStatementsIndex array holds lready infered statements
* to prevent infinite loops.
*
*
* @param object Statement $statement
* @param array $infStatementsIndex
* @return array of statements
* @access private
*/
function _entailStatementRec ( $statement,& $infStatementsIndex)
{
$infStatements = array();
$return = array();
//dont entail statements about the supported inference-schema
if (!in_array($statement->getLabelPredicate(),$this->supportedInference))
{
//check only the rules, that were returned by the index
foreach ($this->_findRuleTriggerInIndex($statement) as $key )
{
$infRule=$this->infRules[$key];
$stateString=$key.serialize($statement);
//If the statement wasn't infered before
if (!in_array($stateString,$infStatementsIndex))
{
$infStatementsIndex[]=$stateString;
//Check, if the Statements triggers this rule
if($infRule->checkTrigger($statement))
{
$infStatement=$infRule->entail($statement);
#if(!$this->contains($infStatement))
{
$return[]=$infStatement;
$return=array_merge($return,
$this->_entailStatementRec($infStatement,
$infStatementsIndex));
};
};
};
};
};
return $return;
}
/**
* Removes all infered statements from the model but keeps the
* infernece rules.
*
* @access public
*/
function removeInfered()
{
$indexTmp=$this->indexed;
$this->index(-1);
foreach ($this->infPos as $key)
{
unset($this->triples[$key]);
};
$this->infPos=array();
$this->index($indexTmp);
}
/**
* Load a model from a file containing RDF, N3 or N-Triples.
* This function recognizes the suffix of the filename (.n3 or .rdf) and
* calls a suitable parser, if no $type is given as string
* ("rdf" "n3" "nt");
* If the model is not empty, the contents of the file is added to
* this DbModel.
*
* While loading the model, the inference entailing is disabled, but
* new inference rules are added to increase performance.
*
* @param string $filename
* @param string $type
* @access public
*/
function load($filename, $type = NULL)
{
//Disable entailing to increase performance
$this->inferenceEnabled=false;
parent::load($filename, $type);
//Enable entailing
$this->inferenceEnabled=true;
//Entail all statements
$this->applyInference();
}
/**
* Short Dump of the InfModelF.
*
* @access public
* @return string
*/
function toString() {
return 'InfModelF[baseURI=' . $this->getBaseURI() . ';
size=' . $this->size(true) . ']';
}
/**
* Create a MemModel containing all the triples (including inferred
* statements) of the current InfModelF.
*
* @return object MemModel
* @access public
*/
function & getMemModel()
{
$return= new MemModel();
$return->setBaseURI($this->baseURI);
foreach ($this->triples as $statement)
$return->add($statement);
$return->addParsedNamespaces($this->getParsedNamespaces());
return $return;
}
/**
* 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;
}
/**
* Removes the triple from the MemModel.
* TRUE if the triple is removed.
* FALSE otherwise.
*
* Checks, if it touches any statements, that added inference rules
* to the model
*
* @param object Statement $statement
* @return boolean
* @access public
* @throws PhpError
*/
function remove($statement)
{
//If the statement is in the model
if($this->contains($statement))
{
$inferenceRulesWereTouched=false;
//If the statement was able to add inference rules
if (in_array($statement->getLabelPredicate(),$this->supportedInference))
{
$statementPositions=$this->_removeFromInference($statement);
$inferenceRulesWereTouched=true;
} else
//get the position of all matching statements
{
$statementPositions=array();
//find the positions of the statements
$statementPosition=-1;
do
{
$statementPosition =
$this->findFirstMatchOff($statement->getSubject(),
$statement->getPredicate(),
$statement->getObject(),
$statementPosition+1);
if ($statementPosition!=-1)
$statementPositions[]=$statementPosition;
} while ($statementPosition != -1);
}
//remove matching statements
parent::remove($statement);
foreach ($statementPositions as $statementPosition)
{
//if the statement was infered, remove it from the index of the infered statements.
if (in_array($statementPosition,$this->infPos))
unset ($this->infPos[$statementPosition]);
}
if ($inferenceRulesWereTouched)
{
//remove the statement and re-entail the model
$this->removeInfered();
$this->applyInference();
}
return true;
} else
{
return false;
}
}
/**
* Adds another model to this MemModel.
* Duplicate statements are not removed.
* If you don't want duplicates, use unite().
* If any statement of the model to be added to this model contains a blankNode
* with an identifier already existing in this model, a new blankNode is generated.
*
* @param object Model $model
* @access public
* @throws phpErrpr
*
*/
function addModel(&$model)
{
//Disable entailing to increase performance
$this->inferenceEnabled=false;
parent::addModel($model);
//Enable entailing
$this->inferenceEnabled=true;
//Entail all statements
$this->applyInference();
}
};
?>

View File

@ -0,0 +1,19 @@
<?php
// ----------------------------------------------------------------------------------
// InfModel Package
// ----------------------------------------------------------------------------------
//
// Description : InfModel package
//
//
// Author: Daniel Westphal <mail at d-westphal dot de>
//
// ----------------------------------------------------------------------------------
// Include InfModel classes
require_once( RDFAPI_INCLUDE_DIR . 'infModel/InfRule.php');
require_once( RDFAPI_INCLUDE_DIR . 'infModel/InfStatement.php');
require_once( RDFAPI_INCLUDE_DIR . 'infModel/InfModel.php');
require_once( RDFAPI_INCLUDE_DIR . 'infModel/InfModelB.php');
require_once( RDFAPI_INCLUDE_DIR . 'infModel/InfModelF.php');
?>

View File

@ -0,0 +1,343 @@
<?php
// ----------------------------------------------------------------------------------
// Class: InfRule
// ----------------------------------------------------------------------------------
/**
* This class represents a single rule in a RDFS inference model.
* It primary constists of a trigger and an entailment.
* In the forward-chaining mode (RDFSFModel) a statement is checked,
* if it satisfies the trigger. If it does, a new statement is returned.
* In the backward-chaining mode (RDFSBModel) a find-query is checked
* with the entailment. If this entailment could satify the find-query,
* a new find-query is returned, that searches for statements that
* satisfy the trigger of this rule.
*
* @version $Id: InfRule.php 290 2006-06-22 12:23:24Z tgauss $
* @author Daniel Westphal <mail at d-westphal dot de>
*
* @package infModel
* @access public
**/
class InfRule
{
/**
* Array, that hold the trigger subject in key ['s'], the trigger
* predicate in ['p'], and the trigger object in ['o'].
* The array values can be NULL to match anything or be a node that
* has to be matched.
*
* @var array
* @access private
*/
var $trigger;
/**
* Array, that hold the entailment subject in key ['s'], the
* entailment predicate in ['p'], and the entailment object in ['o'].
* The array values can be a node that will be inserted in the
* returning statement, or '<s>' to insert the subject,'<p>' to insert
* the predicate, or '<o>' to insert the object of the checked statement
* to this position in the new returned statement.
*
* @var array
* @access private
*/
var $entailment;
/**
* Constructor
*
*
* @access public
*/
function infRule()
{
//initialising vars
$this->trigger=array();
$this->entailment=array();
}
/**
* Sets the trigger of this rule
* The values can be NULL to match anything or be a node that has to
* be matched.
*
* @param object Node OR NULL $subject
* @param object Node OR NULL $predicate
* @param object Node OR NULL $object
* @access public
* @throws PhpError
*/
function setTrigger ($subject, $predicate, $object)
{
//throw an error if subject, predicate, or object are neither
//node, nor null.
if(!is_a($subject,'Node') && $subject != null)
trigger_error(RDFAPI_ERROR . '(class: Infrule; method:
setTrigger): $subject has to be null or of class Node'
, E_USER_ERROR);
if(!is_a($predicate,'Node') && $predicate != null)
trigger_error(RDFAPI_ERROR . '(class: Infrule; method:
setTrigger): $predicate has to be null or of class Node'
, E_USER_ERROR);
if(!is_a($object,'Node') && $object != null)
trigger_error(RDFAPI_ERROR . '(class: Infrule; method:
setTrigger): $object has to be null or of class Node'
, E_USER_ERROR);
//set the trigger
$this->trigger['s']=$subject;
$this->trigger['p']=$predicate;
$this->trigger['o']=$object;
}
/**
* Sets the entailment of this rule
* The values can be NULL to match anything or be a node that has to
* be matched.
*
* @param object Node OR NULL $subject
* @param object Node OR NULL $predicate
* @param object Node OR NULL $object
* @access public
* @throws PhpError
*/
function setEntailment($subject,$predicate,$object)
{
//throw an error if subject, predicate, or object are neither node,
//nor <s>,<p>,<o>.
if(!is_a($subject,'Node') && !ereg('<[spo]>', $subject))
trigger_error(RDFAPI_ERROR . '(class: Infrule; method:
setEntailment): $subject has to be <s>,<p>,or <o> or of class Node'
, E_USER_ERROR);
if(!is_a($predicate,'Node') && !ereg('<[spo]>', $predicate))
trigger_error(RDFAPI_ERROR . '(class: Infrule; method:
setEntailment): $predicate has to be <s>,<p>,or <o> or of class Node'
, E_USER_ERROR);
if(!is_a($object,'Node') && !ereg('<[spo]>', $object))
trigger_error(RDFAPI_ERROR . '(class: Infrule; method:
setEntailment): $object has to be <s>,<p>,or <o> or of class Node'
, E_USER_ERROR);
$this->entailment['s']=$subject;
$this->entailment['p']=$predicate;
$this->entailment['o']=$object;
}
/**
* Checks, if the statement satisfies the trigger.
*
* @param object Statement
* @return boolean
* @access public
* @throws PhpError
*/
function checkTrigger(& $statement)
{
//is true, if the trigger is null to match anything
//or equals the statement's subject
$shouldFireS = $this->trigger['s'] == null ||
$this->trigger['s']->equals($statement->getSubject());
//is true, if the trigger is null to match anything
//or equals the statement's predicate
$shouldFireP = $this->trigger['p'] == null ||
$this->trigger['p']->equals($statement->getPredicate());
//is true, if the trigger is null to match anything
//or equals the statement's object
$shouldFireO = $this->trigger['o'] == null ||
$this->trigger['o']->equals($statement->getObject());
//returns true, if ALL are true
return $shouldFireS && $shouldFireP && $shouldFireO;
}
/**
* Checks, if this rule could entail a statement that matches
* a find of $subject,$predicate,$object.
*
* @param object Statement
* @return boolean
* @access public
* @throws PhpError
*/
function checkEntailment ($subject, $predicate, $object)
{
//true, if $subject is null, the entailment's subject matches
//anything, or the $subject equals the entailment-subject.
$matchesS= $subject == null ||
!is_a($this->entailment['s'],'Node') ||
$this->entailment['s']->equals($subject);
//true, if $predicate is null, the entailment's predicate matches
//anything, or the $predicate equals the entailment-predicate.
$matchesP= $predicate == null ||
!is_a($this->entailment['p'],'Node') ||
$this->entailment['p']->equals($predicate);
//true, if $object is null, the entailment's object matches
//anything, or the $object equals the entailment-object.
$matchesO= $object == null ||
!is_a($this->entailment['o'],'Node') ||
$this->entailment['o']->equals($object);
//returns true, if ALL are true
return $matchesS && $matchesP && $matchesO;
}
/**
* Returns a infered InfStatement by evaluating the statement with
* the entailment rule.
*
* @param object Statement
* @return object InfStatement
* @access public
* @throws PhpError
*/
function entail(& $statement)
{
//if the entailment's subject is <s>,<p>,or <o>, put the statements
//subject,predicate,or object into the subject of the
//entailed statement. If the entailment's subject is a node,
//add that node to the statement.
switch ($this->entailment['s'])
{
case '<s>':
$entailedSubject=$statement->getSubject();
break;
case '<p>':
$entailedSubject=$statement->getPredicate();
break;
case '<o>':
$entailedSubject=$statement->getObject();
break;
default:
$entailedSubject=$this->entailment['s'];
};
//if the entailment's predicate is <s>,<p>,or <o>, put the
//statements subject,predicate,or object into the predicate of
//the entailed statement. If the entailment's predicate is a node,
//add that node to the statement.
switch ($this->entailment['p'])
{
case '<s>':
$entailedPredicate=$statement->getSubject();
break;
case '<p>':
$entailedPredicate=$statement->getPredicate();
break;
case '<o>':
$entailedPredicate=$statement->getObject();
break;
default:
$entailedPredicate=$this->entailment['p'];
};
//if the entailment's object is <s>,<p>,or <o>, put the
//statements subject,predicate,or object into the object of
//the entailed statement. If the entailment's object is a node,
//add that node to the statement.
switch ($this->entailment['o'])
{
case '<s>':
$entailedObject=$statement->getSubject();
break;
case '<p>':
$entailedObject=$statement->getPredicate();
break;
case '<o>':
$entailedObject=$statement->getObject();
break;
default:
$entailedObject=$this->entailment['o'];
};
//return the infered statement
return (new InfStatement($entailedSubject,$entailedPredicate,$entailedObject));
}
/**
* Returns a find-query that matches statements, whose entailed
* statements would match the supplied find query.
*
* @param Node OR null $subject
* @param Node OR null $predicate
* @param Node OR null $object
* @return array
* @access public
* @throws PhpError
*/
function getModifiedFind( $subject, $predicate, $object)
{
$findSubject=$this->trigger['s'];
$findPredicate=$this->trigger['p'];
$findObject=$this->trigger['o'];
switch ($this->entailment['s'])
{
case '<s>':
$findSubject=$subject;
break;
case '<p>':
$findPredicate=$subject;
break;
case '<o>':
$findObject=$subject;
break;
};
switch ($this->entailment['p'])
{
case '<s>':
$findSubject=$predicate;
break;
case '<p>':
$findPredicate=$predicate;
break;
case '<o>':
$findObject=$predicate;
break;
};
switch ($this->entailment['o'])
{
case '<s>':
$findSubject=$object;
break;
case '<p>':
$findPredicate=$object;
break;
case '<o>':
$findObject=$object;
break;
};
return array('s' => $findSubject,
'p' => $findPredicate,
'o' => $findObject );
}
function getTrigger()
{
return array ( 's' => $this->trigger['s'],
'p' => $this->trigger['p'],
'o' => $this->trigger['o'],
);
}
function getEntailment()
{
return array ( 's' => $this->entailment['s'],
'p' => $this->entailment['p'],
'o' => $this->entailment['o'],
);
}
}
?>

View File

@ -0,0 +1,18 @@
<?php
// ----------------------------------------------------------------------------------
// Class: InfStatement
// ----------------------------------------------------------------------------------
/**
* An RDF statement which was entailed by a inference rule.
* See Statement Class for further information.
*
* @author Daniel Westphal <mail at d-westphal dot de>
* @version $Id: InfStatement.php 268 2006-05-15 05:28:09Z tgauss $
* @package infModel
*/
class InfStatement extends Statement {
}
?>

Some files were not shown because too many files have changed in this diff Show More