Index: /Dev/trunk/classes/SurveyRDFReader.php
===================================================================
--- /Dev/trunk/classes/SurveyRDFReader.php	(revision 12)
+++ /Dev/trunk/classes/SurveyRDFReader.php	(revision 12)
@@ -0,0 +1,50 @@
+<?php
+
+// Include RAP Library to write RDF files
+define("RDFAPI_INCLUDE_DIR", "rdfapi/");
+include(RDFAPI_INCLUDE_DIR . "RDFAPI.php");
+
+class SurveyRDFReader
+{
+	var $model;
+	
+	var $resourceURI = 'http:/www.survey.tool/';
+	
+	public function SurveyRDFReader()
+	{
+        // Create empty MemModel
+		$factory = new ModelFactory();
+		$this->model = $factory->getDefaultModel();	
+	}
+	
+	public function loadSurvey($sTitle)
+	{
+		$this->model->load('surveys/'.$sTitle.'.rdf');
+	}
+	
+	public function readSurveyTitle()
+	{
+		$querystring = '
+			PREFIX uri: <' . $this->resourceURI . '>
+			SELECT ?surveyTitle 
+			WHERE { uri:Survey uri:Title ?surveyTitle }';
+			
+		$result = $this->model->sparqlQuery($querystring);
+		
+		return $result;
+	}
+	
+		public function readSurveyDescription()
+	{
+		$querystring = '
+			PREFIX uri: <' . $this->resourceURI . '>
+			SELECT ?surveyDescription 
+			WHERE { uri:Survey uri:Description ?surveyDescription }';
+			
+		$result = $this->model->sparqlQuery($querystring);
+		
+		return $result;
+	}
+}
+
+?>
Index: /Dev/trunk/classes/SurveyRDFWriter.php
===================================================================
--- /Dev/trunk/classes/SurveyRDFWriter.php	(revision 12)
+++ /Dev/trunk/classes/SurveyRDFWriter.php	(revision 12)
@@ -0,0 +1,55 @@
+<?php
+
+// Include RAP Library to write RDF files
+define("RDFAPI_INCLUDE_DIR", "rdfapi/");
+include(RDFAPI_INCLUDE_DIR . "RDFAPI.php");
+
+class SurveyRDFWriter 
+{
+	var $model;
+		
+	var $resourceSurvey;
+	var $resourceTitle;
+	var $resourceDescription;
+	
+    /**
+    * Use SurveyRDFWriter::getInstance() instead of this
+    * constructor.
+    */
+    public function __construct()
+    {
+        // Create empty MemModel
+		$factory = new ModelFactory();
+		$this->model = $factory->getDefaultModel();
+		
+		$this->initResources();
+    }
+
+	function initResources()
+	{
+		$resourceURI = 'http:/www.survey.tool/';
+		
+		$this->resourceSurvey = new Resource($resourceURI.'Survey');
+		$this->resourceTitle = new Resource($resourceURI.'Title');
+		$this->resourceDescription = new Resource($resourceURI.'Description');
+	}
+	
+	public function createSurvey($sTitle, $sDescription)
+	{		
+		$surveyTitle = new Literal($sTitle);
+		$this->model->add(new Statement($this->resourceSurvey,$this->resourceTitle,$surveyTitle));		
+		
+		$surveyDescription = new Literal($sDescription);
+		$this->model->add(new Statement($this->resourceSurvey,$this->resourceDescription,$surveyDescription));	
+	}
+	
+	public function saveSurvey($sTitle)
+	{
+		$this->model->saveAs('surveys/'.$sTitle.'.rdf','rdf');
+		
+		return true;
+	}
+
+}
+
+?>
Index: /Dev/trunk/rdfapi/RdfAPI.php
===================================================================
--- /Dev/trunk/rdfapi/RdfAPI.php	(revision 12)
+++ /Dev/trunk/rdfapi/RdfAPI.php	(revision 12)
@@ -0,0 +1,19 @@
+<?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);
+
+
+?>
Index: /Dev/trunk/rdfapi/constants.php
===================================================================
--- /Dev/trunk/rdfapi/constants.php	(revision 12)
+++ /Dev/trunk/rdfapi/constants.php	(revision 12)
@@ -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')
+);
+
+?>
Index: /Dev/trunk/rdfapi/dataset/Dataset.php
===================================================================
--- /Dev/trunk/rdfapi/dataset/Dataset.php	(revision 12)
+++ /Dev/trunk/rdfapi/dataset/Dataset.php	(revision 12)
@@ -0,0 +1,90 @@
+<?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);
+
+		$sparqlEngine = SparqlEngine::getInstance();
+        $eng = $sparqlEngine->factory();
+        return $eng->queryModel($this,$q,$resultform);
+    }
+
+
+
+}
+?>
Index: /Dev/trunk/rdfapi/dataset/DatasetDb.php
===================================================================
--- /Dev/trunk/rdfapi/dataset/DatasetDb.php	(revision 12)
+++ /Dev/trunk/rdfapi/dataset/DatasetDb.php	(revision 12)
@@ -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;
+	}
+}
+?>
Index: /Dev/trunk/rdfapi/dataset/DatasetMem.php
===================================================================
--- /Dev/trunk/rdfapi/dataset/DatasetMem.php	(revision 12)
+++ /Dev/trunk/rdfapi/dataset/DatasetMem.php	(revision 12)
@@ -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);
+	}
+}
+?>
Index: /Dev/trunk/rdfapi/dataset/DatasetP.php
===================================================================
--- /Dev/trunk/rdfapi/dataset/DatasetP.php	(revision 12)
+++ /Dev/trunk/rdfapi/dataset/DatasetP.php	(revision 12)
@@ -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');
+?>
Index: /Dev/trunk/rdfapi/dataset/IteratorAllGraphsDb.php
===================================================================
--- /Dev/trunk/rdfapi/dataset/IteratorAllGraphsDb.php	(revision 12)
+++ /Dev/trunk/rdfapi/dataset/IteratorAllGraphsDb.php	(revision 12)
@@ -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;
+	}
+}
+?>
Index: /Dev/trunk/rdfapi/dataset/IteratorAllGraphsMem.php
===================================================================
--- /Dev/trunk/rdfapi/dataset/IteratorAllGraphsMem.php	(revision 12)
+++ /Dev/trunk/rdfapi/dataset/IteratorAllGraphsMem.php	(revision 12)
@@ -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;
+	}
+}
+?>
Index: /Dev/trunk/rdfapi/dataset/IteratorFindQuadsDb.php
===================================================================
--- /Dev/trunk/rdfapi/dataset/IteratorFindQuadsDb.php	(revision 12)
+++ /Dev/trunk/rdfapi/dataset/IteratorFindQuadsDb.php	(revision 12)
@@ -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;
+	}
+}
+?>
Index: /Dev/trunk/rdfapi/dataset/IteratorFindQuadsMem.php
===================================================================
--- /Dev/trunk/rdfapi/dataset/IteratorFindQuadsMem.php	(revision 12)
+++ /Dev/trunk/rdfapi/dataset/IteratorFindQuadsMem.php	(revision 12)
@@ -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;
+	}
+}
+?>
Index: /Dev/trunk/rdfapi/dataset/NamedGraphDb.php
===================================================================
--- /Dev/trunk/rdfapi/dataset/NamedGraphDb.php	(revision 12)
+++ /Dev/trunk/rdfapi/dataset/NamedGraphDb.php	(revision 12)
@@ -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;
+	}
+}
+?>
Index: /Dev/trunk/rdfapi/dataset/NamedGraphMem.php
===================================================================
--- /Dev/trunk/rdfapi/dataset/NamedGraphMem.php	(revision 12)
+++ /Dev/trunk/rdfapi/dataset/NamedGraphMem.php	(revision 12)
@@ -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;
+	}
+}
+?>
Index: /Dev/trunk/rdfapi/dataset/Quad.php
===================================================================
--- /Dev/trunk/rdfapi/dataset/Quad.php	(revision 12)
+++ /Dev/trunk/rdfapi/dataset/Quad.php	(revision 12)
@@ -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()));	
+	}
+}
+?>
Index: /Dev/trunk/rdfapi/infModel/InfModel.php
===================================================================
--- /Dev/trunk/rdfapi/infModel/InfModel.php	(revision 12)
+++ /Dev/trunk/rdfapi/infModel/InfModel.php	(revision 12)
@@ -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);
+	}
+ }
+?>
Index: /Dev/trunk/rdfapi/infModel/InfModelB.php
===================================================================
--- /Dev/trunk/rdfapi/infModel/InfModelB.php	(revision 12)
+++ /Dev/trunk/rdfapi/infModel/InfModelB.php	(revision 12)
@@ -0,0 +1,517 @@
+<?php
+// ----------------------------------------------------------------------------------
+// Class: InfModelB
+// ----------------------------------------------------------------------------------
+require_once RDFAPI_INCLUDE_DIR . 'infModel/InfModel.php';
+
+/**
+* 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 575 2008-06-20 12:20:12Z cweiske $
+* @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 = new RDFUtil();
+		$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); 
+	}	  
+}
+?>
Index: /Dev/trunk/rdfapi/infModel/InfModelF.php
===================================================================
--- /Dev/trunk/rdfapi/infModel/InfModelF.php	(revision 12)
+++ /Dev/trunk/rdfapi/infModel/InfModelF.php	(revision 12)
@@ -0,0 +1,407 @@
+<?php
+// ----------------------------------------------------------------------------------
+// Class: InfModelF
+// ----------------------------------------------------------------------------------
+require_once RDFAPI_INCLUDE_DIR . 'infModel/InfModel.php';
+
+/**
+* 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 575 2008-06-20 12:20:12Z cweiske $
+* @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();
+	}
+};
+?>
Index: /Dev/trunk/rdfapi/infModel/InfModelP.php
===================================================================
--- /Dev/trunk/rdfapi/infModel/InfModelP.php	(revision 12)
+++ /Dev/trunk/rdfapi/infModel/InfModelP.php	(revision 12)
@@ -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');
+?>
Index: /Dev/trunk/rdfapi/infModel/InfRule.php
===================================================================
--- /Dev/trunk/rdfapi/infModel/InfRule.php	(revision 12)
+++ /Dev/trunk/rdfapi/infModel/InfRule.php	(revision 12)
@@ -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'],
+ 						);
+ 	}
+}
+?>
Index: /Dev/trunk/rdfapi/infModel/InfStatement.php
===================================================================
--- /Dev/trunk/rdfapi/infModel/InfStatement.php	(revision 12)
+++ /Dev/trunk/rdfapi/infModel/InfStatement.php	(revision 12)
@@ -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  {
+	
+}
+	
+?>
Index: /Dev/trunk/rdfapi/model/Blanknode.php
===================================================================
--- /Dev/trunk/rdfapi/model/Blanknode.php	(revision 12)
+++ /Dev/trunk/rdfapi/model/Blanknode.php	(revision 12)
@@ -0,0 +1,120 @@
+<?php
+require_once RDFAPI_INCLUDE_DIR . 'model/Resource.php';
+
+// ----------------------------------------------------------------------------------
+// Class: BlankNode
+// ----------------------------------------------------------------------------------
+
+
+/**
+ * An RDF blank node. 
+ * In model theory, blank nodes are considered to be drawn from some set of 
+ * 'anonymous' entities which have no label but are unique to the graph.
+ * For serialization they are labeled with a URI or a _:X identifier.
+ * 
+ *
+ * @version  $Id: Blanknode.php 453 2007-06-20 21:19:09Z cweiske $
+ * @authors Chris Bizer <chris@bizer.de>,
+ *          Radoslaw Oldakowski <radol@gmx.de>
+ *
+ * @package model
+ * @access	public
+ *
+ */ 
+ class BlankNode extends Resource {
+  
+   /**
+    * Constructor
+	* You can supply a label or You supply a model and a unique ID is gernerated.
+    *
+    * @param	mixed	$namespace_or_uri_or_model
+ 	* @param 	string $localName
+	* @access	public
+    */
+    function BlankNode($namespace_or_uri_or_model , $localName = NULL) {
+		
+        if (is_a($namespace_or_uri_or_model, 'Model')) {
+			// generate identifier
+			$id = $namespace_or_uri_or_model->getUniqueResourceURI(BNODE_PREFIX);
+			
+			$this->uri = $id;
+
+		} else {
+			// set identifier
+			if ($localName == NULL) {
+				$this->uri = $namespace_or_uri_or_model;
+		  	} else {
+				$this->uri = $namespace_or_uri_or_model . $localName;
+	  	    }
+		 }
+    }
+
+  /**
+   * Returns the ID of the blank node.
+   *
+   * @return 	string
+   * @access	public  
+   */	
+  function getID() {
+  			return $this->uri;
+   }
+
+  /**
+   * Returns the ID of the blank node.
+   *
+   * @return 	string
+   * @access	public  
+   */	
+  function getLabel() {
+  		return $this->uri;
+   }
+
+  /**
+   * Dumps bNode.
+   *
+   * @access	public 
+   * @return	string 
+   */  
+  function toString() {
+
+        return 'bNode("' . $this->uri . '")';
+  }
+	
+  /**
+   * Checks if two blank nodes are equal.
+   * Two blank nodes are equal, if they have the same temporary ID.
+   *
+   * @access	public 
+   * @param		object	resource $that
+   * @return	boolean 
+   */  
+   function equals ($that) {
+	
+	    if ($this == $that) {
+	      return true;
+	    }
+        if (($that == NULL) or !(is_a($that, 'BlankNode'))) {
+	      return false;
+	    }
+	    	
+		if ($this->getURI() == $that->getURI()) {
+	      return true;
+	    }
+	
+	    return false;
+	}
+
+
+    /**
+    *   Doing string magic in PHP5
+    *   @return string String representation of this Blank Node
+    */
+    function __toString()
+    {
+        return $this->toString();
+    }
+
+} // end: BlankNode 
+
+
+?>
Index: /Dev/trunk/rdfapi/model/DBase.php
===================================================================
--- /Dev/trunk/rdfapi/model/DBase.php	(revision 12)
+++ /Dev/trunk/rdfapi/model/DBase.php	(revision 12)
@@ -0,0 +1,17 @@
+<?php
+// ----------------------------------------------------------------------------------
+// DBase
+// ----------------------------------------------------------------------------------
+//
+// Description               : DBase package
+//
+//
+// Author: Tobias Gauß	<tobias.gauss@web.de>
+//
+// ----------------------------------------------------------------------------------
+
+// Include DBase class
+require_once( RDFAPI_INCLUDE_DIR . 'model/DbModel.php' );
+// include adodb classes
+require_once(RDFAPI_INCLUDE_DIR .'util/adodb/adodb.inc.php');
+?>
Index: /Dev/trunk/rdfapi/model/DbModel.php
===================================================================
--- /Dev/trunk/rdfapi/model/DbModel.php	(revision 12)
+++ /Dev/trunk/rdfapi/model/DbModel.php	(revision 12)
@@ -0,0 +1,1319 @@
+<?php
+require_once RDFAPI_INCLUDE_DIR . 'model/Model.php';
+require_once RDFAPI_INCLUDE_DIR . 'model/Blanknode.php';
+require_once RDFAPI_INCLUDE_DIR . 'model/Statement.php';
+
+// ----------------------------------------------------------------------------------
+// Class: DbModel
+// ----------------------------------------------------------------------------------
+
+/**
+* This class provides methods for manipulating DbModels from DbStore.
+* A DbModel is an RDF Model, which is persistently stored in a relational database.
+* This Class uses the ADOdb Database Abstraction Library for PHP (http://adodb.sourceforge.net/).
+*
+*
+* @version  $Id: DbModel.php 533 2007-08-16 09:32:03Z cweiske $
+* @author   Radoslaw Oldakowski <radol@gmx.de>
+*
+* @package model
+* @access	public
+*/
+
+
+class DbModel extends Model{
+
+	/**
+	* Database connection object.
+	*
+	* @var     object ADOConnection
+	* @access	private
+	*/
+	var $dbConn;
+
+	/**
+	* Unique model URI.
+	* Used to identify the DbModel.
+	*
+	* @var     string
+	* @access	private
+	*/
+	var $modelURI;
+
+
+	/**
+	* Database internal modelID.
+	* Used to avoid JOINs.
+	*
+	* @var     string
+	* @access	private
+	*/
+	var $modelID;
+
+
+
+
+	/**
+	* Constructor
+	* Do not call this directly.
+	* Use the method getModel,getNewModel or putModel of the Class DbStore instead.
+	*
+	* @param   object ADOConnection  &$dbConnection
+	* @param   string   $modelURI
+	* @param   string   $modelID
+	* @param   string   $baseURI
+	* @access	public
+	*/
+	function DbModel(&$dbConnection, $modelURI, $modelID, $baseURI=NULL) {
+
+		$this->dbConn =& $dbConnection;
+		$this->modelURI = $modelURI;
+		$this->modelID = $modelID;
+		$this->baseURI = $this->_checkBaseURI($baseURI);
+	}
+
+
+	/**
+	* Set a base URI for the DbModel.
+	* Affects creating of new resources and serialization syntax.
+	*
+	* @param	string	$uri
+	* @throws  SqlError
+	* @access	public
+	*/
+	function setBaseURI($uri) {
+
+		$this->baseURI = $this->_checkBaseURI($uri);
+
+		$rs = $this->dbConn->execute("UPDATE models SET baseURI='" .$this->baseURI ."'
+                                 WHERE modelID=" .$this->modelID);
+		if (!$rs)
+		$this->dbConn->errorMsg();
+	}
+
+
+	/**
+	* Return the number of statements in this DbModel.
+	*
+	* @return	integer
+	* @access	public
+	*/
+	function size() {
+
+		$count =& $this->dbConn->getOne('SELECT COUNT(modelID) FROM statements
+                                    WHERE modelID = ' .$this->modelID);
+		return $count;
+	}
+
+
+	/**
+	* Check if this DbModel is empty.
+	*
+	* @return	boolean
+	* @access	public
+	*/
+	function isEmpty() {
+
+		if ($this->size() == 0)
+			return TRUE;
+		return FALSE;
+	}
+
+
+	/**
+	* Add a new triple to this DbModel.
+	*
+	* @param	object Statement	&$statement
+	* @throws	PhpError
+	* @throws  SqlError
+	* @access	public
+	* @return mixed   true on success, false if the statement is already in the model,
+	*                 error message (string) on failure
+	*/
+	function add(&$statement) {
+
+		if (!is_a($statement, 'Statement')) {
+			$errmsg = RDFAPI_ERROR . '(class: DbModel; method: add): Statement expected.';
+			trigger_error($errmsg, E_USER_ERROR);
+		}
+
+		if (!$this->contains($statement)) {
+
+			$subject_is = $this->_getNodeFlag($statement->subject());
+			$sql = "INSERT INTO statements
+			        (modelID, subject, predicate, object, l_language, l_datatype, subject_is, object_is)
+			        VALUES
+                    (" .$this->modelID .","
+			. $this->dbConn->qstr($statement->getLabelSubject()) .","
+			. $this->dbConn->qstr($statement->getLabelPredicate()) .",";
+
+			if (is_a($statement->object(), 'Literal')) {
+				$quotedLiteral = $this->dbConn->qstr($statement->obj->getLabel());
+				$sql .=        $quotedLiteral .","
+				."'" .$statement->obj->getLanguage() ."',"
+				."'" .$statement->obj->getDatatype() ."',"
+				."'" .$subject_is ."',"
+				."'l')";
+			}else{
+				$object_is = $this->_getNodeFlag($statement->object());
+				$sql .=   $this->dbConn->qstr($statement->obj->getLabel()) .","
+				."'',"
+				."'',"
+				."'" .$subject_is ."',"
+				."'" .$object_is ."')";
+			}
+			$rs =& $this->dbConn->execute($sql);
+			if (!$rs) {
+				return $this->dbConn->errorMsg();
+            } else {
+                return true;
+            }
+		} else {
+			return false;
+		}
+	}
+
+
+	/**
+	* Alias for the method add().
+	*
+	* @param	object Statement	&$statement
+	* @throws	PhpError
+	* @throws  SqlError
+	* @access	public
+	*/
+	function addWithoutDuplicates(&$statement) {
+
+		$this->add($statement);
+	}
+
+
+	/**
+	* Remove the given triple from this DbModel.
+	*
+	* @param	object Statement	&$statement
+	* @throws	PhpError
+	* @throws  SqlError
+	* @access	public
+	*/
+	function remove(&$statement) {
+
+		if (!is_a($statement, 'Statement')) {
+			$errmsg = RDFAPI_ERROR . '(class: DbModel; method: remove): Statement expected.';
+			trigger_error($errmsg, E_USER_ERROR);
+		}
+
+		$sql = 'DELETE FROM statements
+           WHERE modelID=' .$this->modelID;
+		$sql .= $this->_createDynSqlPart_SPO ($statement->subj, $statement->pred, $statement->obj);
+
+		$rs =& $this->dbConn->execute($sql);
+		if (!$rs)
+		$this->dbConn->errorMsg();
+	}
+
+
+	/**
+	* Short dump of the DbModel.
+	*
+	* @return	string
+	* @access	public
+	*/
+	function toString() {
+
+		return 'DbModel[modelURI=' .$this->modelURI .'; baseURI=' .$this->getBaseURI() .';  size=' .$this->size() .']';
+	}
+
+
+	/**
+	* Dump of the DbModel including all triples.
+	*
+	* @return	string
+	* @access	public
+	*/
+	function toStringIncludingTriples() {
+
+		$memModel =& $this->getMemModel();
+		return $memModel->toStringIncludingTriples();
+	}
+
+
+
+	/**
+	* Create a MemModel containing all the triples of the current DbModel.
+	*
+	* @return object MemModel
+	* @access public
+	*/
+	function & getMemModel() {
+
+		$recordSet = $this->_getRecordSet($this);
+		$m = $this->_convertRecordSetToMemModel($recordSet);
+		return $m;
+	}
+
+
+
+    /**
+    * Returns the model id
+    *
+    * @return int Model id number
+    * @access public
+    */
+    function getModelID()
+    {
+        return $this->modelID;
+    }
+
+
+
+    /**
+    * Returns the database connection object
+    *
+    * @return ADOdb Database object
+    * @access public
+    */
+    function &getDbConn()
+    {
+        return $this->dbConn;
+    }
+
+
+
+	/**
+	* Write the RDF serialization of the _DbModel as HTML.
+	*
+	* @access	public
+	*/
+	function writeAsHtml() {
+
+		$memModel =& $this->getMemModel();
+		$memModel->writeAsHtml();
+	}
+
+
+	/**
+	* Write the RDF serialization of the DbModel as HTML table.
+	*
+	* @access	public
+	*/
+	function writeAsHtmlTable() {
+		include_once(RDFAPI_INCLUDE_DIR.PACKAGE_UTILITY);
+		$memModel =& $this->getMemModel();
+		$rdfUtil = new RDFUtil();
+		$rdfUtil->writeHTMLTable($memModel);
+	}
+
+
+	/**
+	* Write the RDF serialization of the DbModel to string.
+	*
+	* @return	string
+	* @access	public
+	*/
+	function writeRdfToString() {
+
+		$memModel =& $this->getMemModel();
+		return $memModel->writeRdfToString();
+	}
+
+
+	/**
+	* Saves the RDF,N3 or N-Triple serialization of the DbModel 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 DbModel 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();
+		$memModel->saveAs($filename, $type);
+
+	}
+
+
+	/**
+	* Check if the DbModel contains the given statement.
+	*
+	* @param object Statement  &$statement
+	* @return	boolean
+	* @access	public
+	*/
+	function contains(&$statement) {
+
+		$sql = 'SELECT modelID FROM statements
+           WHERE modelID = ' .$this->modelID;
+		$sql .= $this->_createDynSqlPart_SPO($statement->subj, $statement->pred, $statement->obj);
+
+		$res =& $this->dbConn->getOne($sql);
+
+		if (!$res)
+			return FALSE;
+		return TRUE;
+	}
+
+
+	/**
+	* Determine if all of the statements in the given model are also contained in this DbModel.
+	*
+	* @param	object Model	&$model
+	* @return	boolean
+	* @access	public
+	*/
+	function containsAll(&$model) {
+
+		if (is_a($model, 'MemModel')) {
+
+			foreach($model->triples as $statement)
+			if(!$this->contains($statement))
+				return FALSE;
+			return TRUE;
+		}
+
+		elseif (is_a($model, 'DbModel')) {
+
+			$recordSet =& $this->_getRecordSet($model);
+			while (!$recordSet->EOF) {
+				if (!$this->_containsRow($recordSet->fields))
+					return FALSE;
+				$recordSet->moveNext();
+			}
+			return TRUE;
+		}
+
+		$errmsg = RDFAPI_ERROR . '(class: DbModel; method: containsAll): Model expected.';
+		trigger_error($errmsg, E_USER_ERROR);
+	}
+
+
+	/**
+	* Determine if any of the statements in the given model are also contained in this DbModel.
+	*
+	* @param	object Model	&$model
+	* @return	boolean
+	* @access	public
+	*/
+	function containsAny(&$model) {
+
+		if (is_a($model, 'MemModel')) {
+
+			foreach($model->triples as $statement)
+			if($this->contains($statement))
+				return TRUE;
+			return FALSE;
+		}
+
+		elseif (is_a($model, 'DbModel')) {
+
+			$recordSet =& $this->_getRecordSet($model);
+			while (!$recordSet->EOF) {
+				if ($this->_containsRow($recordSet->fields))
+					return TRUE;
+				$recordSet->moveNext();
+			}
+			return FALSE;
+		}
+
+		$errmsg = RDFAPI_ERROR . '(class: DbModel; method: containsAny): Model expected.';
+		trigger_error($errmsg, E_USER_ERROR);
+	}
+
+
+	/**
+	* General method to search for triples in the DbModel.
+	* NULL input for any parameter will match anything.
+	* Example:  $result = $m->find( NULL, NULL, $node );
+	*           Finds all triples with $node as object.
+	*
+	* @param	object Resource	$subject
+	* @param	object Resource	$predicate
+	* @param	object Node	$object
+	* @return	object MemModel
+	* @throws	PhpError
+	* @throws  SqlError
+	* @access	public
+	*/
+	function find($subject, $predicate, $object) {
+
+		if ((!is_a($subject, 'Resource') && $subject != NULL) ||
+		(!is_a($predicate, 'Resource') && $predicate != NULL) ||
+		(!is_a($object, 'Node') && $object != NULL)) {
+
+			$errmsg = RDFAPI_ERROR . '(class: DbModel; method: find): Parameters must be subclasses of Node or NULL';
+			trigger_error($errmsg, E_USER_ERROR);
+		}
+
+		// static part of the sql statement
+		$sql = 'SELECT subject, predicate, object, l_language, l_datatype, subject_is, object_is
+           FROM statements
+           WHERE modelID = ' .$this->modelID;
+
+		// dynamic part of the sql statement
+		$sql .= $this->_createDynSqlPart_SPO($subject, $predicate, $object);
+
+		// execute the query
+		$recordSet =& $this->dbConn->execute($sql);
+
+		if (!$recordSet)
+			echo $this->dbConn->errorMsg();
+
+		// write the recordSet into memory Model
+		else
+			return $this->_convertRecordSetToMemModel($recordSet);
+	}
+
+
+	/**
+	* 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.
+	* Return an empty MemModel if nothing is found.
+	* !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+	* WARNING: Mhis method loads a DbModel into memory and performs the search
+	*          on a MemModel, which can be slow with large models.
+	* !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+	*
+	* @param	string	$subject_regex
+	* @param	string	$predicate_regex
+	* @param	string	$object_regex
+	* @return	object MemModel
+	* @throws	PhpError
+	* @throws  SqlError
+	* @access	public
+	*/
+	function findRegex($subject_regex, $predicate_regex, $object_regex) {
+
+		$mm =& $this->getMemModel();
+
+		return $mm->findRegex($subject_regex, $predicate_regex, $object_regex);
+	}
+
+
+	/**
+	* Return 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#
+	* Return an empty model if nothing is found.
+	*
+	* @param	string	$vocabulary
+	* @return	object MemModel
+	* @throws	PhpError
+	* @throws  SqlError
+	* @access	public
+	*/
+	function findVocabulary($vocabulary) {
+
+		$sql = "SELECT subject, predicate, object, l_language, l_datatype, subject_is, object_is
+           FROM statements
+           WHERE modelID = " .$this->modelID ."
+           AND predicate LIKE '" .$vocabulary ."%'";
+
+		$recordSet =& $this->dbConn->execute($sql);
+
+		if (!$recordSet)
+		echo $this->dbConn->errorMsg();
+
+		// write the recordSet into memory Model
+		else
+		return $this->_convertRecordSetToMemModel($recordSet);
+	}
+
+
+	/**
+	* Search for triples and return the first matching statement.
+	* NULL input for any parameter will match anything.
+	* Return an NULL if nothing is found.
+	* You can set an search offset with $offset.
+	*
+	* @param	object Resource	$subject
+	* @param	object Resource	$predicate
+	* @param	object Node	$object
+	* @param	integer	$offset
+	* @return	object Statement
+	* @throws  PhpError
+	* @throws  SqlError
+	* @access	public
+	*/
+	function findFirstMatchingStatement($subject, $predicate, $object, $offset = -1) {
+
+		if ((!is_a($subject, 'Resource') && $subject != NULL) ||
+		(!is_a($predicate, 'Resource') && $predicate != NULL) ||
+		(!is_a($object, 'Node') && $object != NULL)) {
+
+			$errmsg = RDFAPI_ERROR . '(class: DbModel; method: find): Parameters must be subclasses of Node or NULL';
+			trigger_error($errmsg, E_USER_ERROR);
+		}
+
+		// static part of the sql statement
+		$sql = 'SELECT subject, predicate, object, l_language, l_datatype, subject_is, object_is
+           FROM statements
+           WHERE modelID = ' .$this->modelID;
+
+		// dynamic part of the sql statement
+		$sql .= $this->_createDynSqlPart_SPO($subject, $predicate, $object);
+
+		// execute the query
+		$recordSet =& $this->dbConn->selectLimit($sql,1,($offset));
+
+		if (!$recordSet)
+		echo $this->dbConn->errorMsg();
+		else {
+			if (!$recordSet->fields)
+			return NULL;
+			else {
+				$memModel = $this->_convertRecordSetToMemModel($recordSet);
+				return $memModel->triples[0];
+			}
+		}
+	}
+
+
+	/**
+	* Search for triples and return the number of matches.
+	* NULL input for any parameter will match anything.
+	*
+	* @param	object Resource	$subject
+	* @param	object Resource	$predicate
+	* @param	object Node  	$object
+	* @return	integer
+	* @throws	PhpError
+	* @throws  SqlError
+	* @access	public
+	*/
+	function findCount($subject, $predicate, $object) {
+
+		if ((!is_a($subject, 'Resource') && $subject != NULL) ||
+		(!is_a($predicate, 'Resource') && $predicate != NULL) ||
+		(!is_a($object, 'Node') && $object != NULL)) {
+
+			$errmsg = RDFAPI_ERROR . '(class: DbModel; method: find): Parameters must be subclasses of Node or NULL';
+			trigger_error($errmsg, E_USER_ERROR);
+		}
+
+		// static part of the sql statement
+		$sql = 'SELECT COUNT(*)
+           FROM statements
+           WHERE modelID = ' .$this->modelID;
+
+		// dynamic part of the sql statement
+		$sql .= $this->_createDynSqlPart_SPO($subject, $predicate, $object);
+
+		// execute the query
+		$recordSet =& $this->dbConn->execute($sql);
+
+		if (!$recordSet)
+			echo $this->dbConn->errorMsg();
+		else
+			return $recordSet->fields[0];
+	}
+
+
+	/**
+	* Perform an RDQL query on this DbModel.
+	* This method returns an associative array of variable bindings.
+	* The values of the query variables can either be RAP's objects (instances of Node)
+	* if $returnNodes set to TRUE, or their string serialization.
+	*
+	* @access	public
+	* @param string $queryString
+	* @param boolean $returnNodes
+	* @return  array   [][?VARNAME] = object Node  (if $returnNodes = TRUE)
+	*      OR  array   [][?VARNAME] = string
+	*
+	*/
+	function rdqlQuery($queryString, $returnNodes = TRUE) {
+		require_once(RDFAPI_INCLUDE_DIR.PACKAGE_RDQL);
+		$parser = new RdqlParser();
+		$parsedQuery =& $parser->parseQuery($queryString);
+
+		// this method can only query this DbModel
+		// if another model was specified in the from clause throw an error
+		if (isset($parsedQuery['sources'][0]))
+		if($parsedQuery['sources'][0] != $this->modelURI) {
+			$errmsg = RDFAPI_ERROR . '(class: DbModel; method: rdqlQuery):';
+			$errmsg .= ' this method can only query this DbModel';
+			trigger_error($errmsg, E_USER_ERROR);
+		}
+
+		$engine = new RdqlDbEngine();
+		$res =& $engine->queryModel($this, $parsedQuery, $returnNodes);
+
+		return $res;
+	}
+
+
+	/**
+	* Perform an RDQL query on this DBModel.
+	* This method returns an RdqlResultIterator of variable bindings.
+	* The values of the query variables can either be RAP's objects (instances of Node)
+	* if $returnNodes set to TRUE, or their string serialization.
+	*
+	* @access	public
+	* @param string $queryString
+	* @param boolean $returnNodes
+	* @return  object RdqlResultIterator = with values as object Node  (if $returnNodes = TRUE)
+	*      OR  object RdqlResultIterator = with values as strings if (if $returnNodes = FALSE)
+	*
+	*/
+	function rdqlQueryAsIterator($queryString, $returnNodes = TRUE) {
+		require_once(RDFAPI_INCLUDE_DIR.PACKAGE_RDQL);
+		return new RdqlResultIterator($this->rdqlQuery($queryString, $returnNodes));
+	}
+
+	/**
+	* General method to replace nodes of a DbModel.
+	* NULL input for any parameter will match nothing.
+	* Example:  $m->replace($resource, NULL, $node, $replacement);
+	*           Replaces all $node objects beeing subject or object in
+	*           any triple of the model with the $replacement node.
+	* Throw an error in case of a paramter mismatch.
+	*
+	* @param	object Resource	$subject
+	* @param	object Resource	$predicate
+	* @param	object Node	$object
+	* @param	object Node	$replacement
+	* @throws	PhpError
+	* @throws  SqlError
+	* @access	public
+	*/
+	function replace($subject, $predicate, $object, $replacement) {
+
+		// check the correctness of the passed parameters
+		if ( ((!is_a($subject, 'Resource') && $subject != NULL) ||
+		(!is_a($predicate, 'Resource') && $predicate != NULL) ||
+		(!is_a($object, 'Node') && $object != NULL)) ||
+		(($subject != NULL && is_a($replacement, 'Literal')) ||
+		($predicate != NULL && (is_a($replacement, 'Literal') ||
+		is_a($replacement, 'BlankNode')))) )
+		{
+			$errmsg = RDFAPI_ERROR . '(class: DbModel; method: find): Parameter mismatch';
+			trigger_error($errmsg, E_USER_ERROR);
+		}
+
+		if (!(!$subject && !$predicate && !$object)) {
+
+			// create an update sql statement
+			$comma = '';
+			$sql = 'UPDATE statements
+             SET ';
+			if ($subject) {
+				$sql .= " subject ='" .$replacement->getLabel() ."', "
+				." subject_is='" .$this->_getNodeFlag($replacement) ."' ";
+				$comma = ',';
+			}
+			if ($predicate) {
+				$sql .= $comma ." predicate='" .$replacement->getLabel() ."' ";
+				$comma = ',';
+			}
+			if ($object) {
+				$quotedObject = $this->dbConn->qstr($replacement->getLabel());
+				$sql .= $comma .' object=' .$quotedObject
+				.", object_is='" .$this->_getNodeFlag($replacement) ."' ";
+				if (is_a($replacement, 'Literal')) {
+					$sql .= ", l_language='" .$replacement->getLanguage() ."' "
+					.", l_datatype='" .$replacement->getDataType() ."' ";
+				}
+			}
+			$sql .= 'WHERE modelID = ' .$this->modelID;
+			$sql .= $this->_createDynSqlPart_SPO($subject, $predicate, $object);
+
+			// execute the query
+			$rs =& $this->dbConn->execute($sql);
+
+			if (!$rs)
+			echo $this->dbConn->errorMsg();
+		}
+	}
+
+
+	/**
+	* Check if two models are equal.
+	* Two models are equal if and only if the two RDF graphs they represent are isomorphic.
+	*
+	* Warning: This method doesn't work correct with models where the same blank node has different
+	* identifiers in the two models. We will correct this in a future version.
+	*
+	* @param	object	model &$that
+	* @return	boolean
+	* @throws  PhpError
+	* @access	public
+	*/
+
+	function equals(&$that)  {
+
+		if (!is_a($that, 'Model')) {
+			$errmsg = RDFAPI_ERROR . '(class: DbModel; method: equals): Model expected.';
+			trigger_error($errmsg, E_USER_ERROR);
+		}
+
+		if ($this->size() != $that->size())
+		return FALSE;
+
+		include_once(RDFAPI_INCLUDE_DIR. "util/ModelComparator.php");
+		return ModelComparator::compare($this,$that);
+	}
+
+
+	/**
+	* Return a new MemModel that is the set-union the model with another model.
+	*
+	* The result of taking the set-union of two or more RDF graphs (i.e. sets of triples)
+	* is another graph, which we will call the merge of the graphs.
+	* Each of the original graphs is a subgraph of the merged graph. Notice that when forming
+	* a merged graph, two occurrences of a given uriref or literal as nodes in two different
+	* graphs become a single node in the union graph (since by definition they are the same
+	* uriref or literal) but blank nodes are not 'merged' in this way; and arcs are of course
+	* never merged. In particular, this means that every blank node in a merged graph can be
+	* identified as coming from one particular graph in the original set of graphs.
+	*
+	* Notice that one does not, in general, obtain the merge of a set of graphs by concatenating
+	* their corresponding N-triples documents and constructing the graph described by the merged
+	* document, since if some of the documents use the same node identifiers, the merged document
+	* will describe a graph in which some of the blank nodes have been 'accidentally' merged.
+	* To merge Ntriples documents it is necessary to check if the same nodeID is used in two or
+	* more documents, and to replace it with a distinct nodeID in each of them, before merging the
+	* documents. (Not implemented yet !!!!!!!!!!!)
+	*
+	* @param	object Model	$model
+	* @return	object MemModel
+	* @throws PhpError
+	* @access	public
+	*
+	*/
+	function & unite(&$model)  {
+
+		if (!is_a($model, 'Model')) {
+			$errmsg = RDFAPI_ERROR . '(class: DbModel; method: unite): Model expected.';
+			trigger_error($errmsg, E_USER_ERROR);
+		}
+
+		if (is_a($model, 'MemModel')) {
+
+			$thisModel =& $this->getMemModel();
+			return $thisModel->unite($model);
+		}
+
+		elseif (is_a($model, 'DbModel')) {
+
+			$thisModel =& $this->getMemModel();
+			$thatModel =& $model->getMemModel();
+			return $thisModel->unite($thatModel);
+		}
+	}
+
+
+	/**
+	* Return a new MemModel that is the subtraction of another model from this DbModel.
+	*
+	* @param	object Model	$model
+	* @return	object MemModel
+	* @throws PhpError
+	* @access	public
+	*/
+
+	function & subtract(&$model)  {
+
+		if (!is_a($model, 'Model')) {
+			$errmsg = RDFAPI_ERROR . '(class: DbModel; method: subtract): Model expected.';
+			trigger_error($errmsg, E_USER_ERROR);
+		}
+
+		if (is_a($model, 'MemModel')) {
+
+			$thisModel =& $this->getMemModel();
+			return $thisModel->subtract($model);
+		}
+
+		elseif (is_a($model, 'DbModel')) {
+
+			$thisModel =& $this->getMemModel();
+			$thatModel =& $model->getMemModel();
+			return $thisModel->subtract($thatModel);
+		}
+	}
+
+
+	/**
+	* Return a new MemModel containing all the statements which are in both
+	* this model and the given model.
+	*
+	* @param	object Model	$model
+	* @return	object MemModel
+	* @throws  PhpError
+	* @access	public
+	*/
+	function & intersect(&$model)  {
+
+		if (is_a($model, 'MemModel')) {
+
+			$thisModel =& $this->getMemModel();
+			return $thisModel->intersect($model);
+		}
+
+		elseif (is_a($model, 'DbModel')) {
+
+			$thisModel =& $this->getMemModel();
+			$thatModel =& $model->getMemModel();
+			return $thisModel->intersect($thatModel);
+		}
+
+		$errmsg = RDFAPI_ERROR . '(class: DbModel; method: intersect: Model expected.';
+		trigger_error($errmsg, E_USER_ERROR);
+	}
+
+
+	/**
+	* Add the given model to this DbModel.
+	* This function monitors for SQL errors, and will commit if no errors have occured,
+	* otherwise it will rollback.
+	* 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
+	* @throws  PhpError
+	* @access	public
+	*/
+	function addModel(&$model)  {
+
+		if (!is_a($model, 'Model')) {
+			$errmsg = RDFAPI_ERROR . '(class: DbModel; method: addModel): Model expected.';
+			trigger_error($errmsg, E_USER_ERROR);
+		}
+
+		$blankNodes_tmp = array();
+
+		if (is_a($model, 'MemModel')) {
+
+			$this->dbConn->startTrans();
+			foreach ($model->triples as $statement)
+			$this->_addStatementFromAnotherModel($statement, $blankNodes_tmp);
+			$this->addParsedNamespaces($model->getParsedNamespaces());
+
+			$this->dbConn->completeTrans();
+		}
+
+		elseif (is_a($model, 'DbModel')) {
+
+			$this->dbConn->startTrans();
+			$memModel =& $model->getMemModel();
+			foreach($memModel->triples as $statement)
+				$this->_addStatementFromAnotherModel($statement, $blankNodes_tmp);
+			$this->addParsedNamespaces($model->getParsedNamespaces());
+			$this->dbConn->completeTrans();
+		}
+	}
+
+
+	/**
+	* Reify the DbModel.
+	* Return a new MemModel that contains the reifications of all statements of this DbModel.
+	*
+	* @return	object	MemModel
+	* @access	public
+	*/
+	function & reify() {
+
+		$memModel =& $this->getMemModel();
+		return $memModel->reify();
+	}
+
+	/**
+	* Remove this DbModel from database and clean up.
+	* This function monitors for SQL errors, and will commit if no errors have occured,
+	* otherwise it will rollback.
+	*
+	* @throws  SqlError
+	* @access	public
+	*/
+	function delete() {
+
+		$this->dbConn->startTrans();
+		$this->dbConn->execute('DELETE FROM models
+                                  WHERE modelID=' .$this->modelID);
+		$this->dbConn->execute('DELETE FROM statements
+                                  WHERE modelID=' .$this->modelID);
+		$this->dbConn->execute('DELETE FROM namespaces
+                                  WHERE modelID=' .$this->modelID);
+
+		if (!$this->dbConn->completeTrans())
+			echo $this->dbConn->errorMsg();
+		else
+			$this->close();
+	}
+
+
+	/**
+	* Close this DbModel
+	*
+	* @access	public
+	*/
+	function close() {
+
+		unset($this);
+	}
+
+
+	// =============================================================================
+	// **************************** private methods ********************************
+	// =============================================================================
+
+
+
+
+
+	/**
+	* If the URI doesn't end with # : or /, then a # is added to the URI.
+	* Used at setting the baseURI of this DbModel.
+	*
+	* @param   string  $uri
+	* @return  string
+	* @access	private
+	*/
+	function _checkBaseURI($uri)  {
+
+		if ($uri != NULL) {
+			$c = substr($uri, strlen($uri)-1 ,1);
+			if (!($c=='#' || $c==':' || $c=='/' || $c=="\\"))
+			$uri .= '#';
+		}
+		return $uri;
+	}
+
+
+	/**'
+	* Return the flag of the Node object.
+	* r - Resource, b - BlankNode, l - Literal
+	*
+	* @param   object Node $object
+	* @return  string
+	* @access	private
+	*/
+	function _getNodeFlag($object)  {
+
+		return is_a($object,'BlankNode')?'b':(is_a($object,'Resource')?'r':'l');
+	}
+
+
+	/**
+	* Convert an ADORecordSet to a memory Model.
+	*
+	* Every successful database query returns an ADORecordSet object which is actually
+	* a cursor that holds the current row in the array fields[].
+	* !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+	* !!! This method can only be applied to a RecordSet with array fields[]
+	* !!! containing a representation of the database table: statements,
+	* !!! with an index corresponding to following table columns:
+	* !!! [0] - subject, [1] - predicate, [2] - object, [3] - l_language,
+	* !!! [4] - l_datatype, [5] - subject_is, [6] - object_is
+	* !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+	*
+	* @param   object  ADORecordSet
+	* @return  object  MemModel
+	* @access	private
+	*/
+	function _convertRecordSetToMemModel(&$recordSet)  {
+
+		$res = new MemModel($this->baseURI);
+		while (!$recordSet->EOF) {
+
+			// subject
+			if ($recordSet->fields[5] == 'r')
+				$sub = new Resource($recordSet->fields[0]);
+			else
+				$sub = new BlankNode($recordSet->fields[0]);
+
+			// predicate
+			$pred = new Resource($recordSet->fields[1]);
+
+			// object
+			if ($recordSet->fields[6] == 'r')
+				$obj = new Resource($recordSet->fields[2]);
+			elseif ($recordSet->fields[6] == 'b')
+				$obj = new BlankNode($recordSet->fields[2]);
+			else {
+				$obj = new Literal($recordSet->fields[2], $recordSet->fields[3]);
+				if ($recordSet->fields[4])
+				$obj->setDatatype($recordSet->fields[4]);
+			}
+
+			$statement = new Statement($sub, $pred, $obj);
+			$res->add($statement);
+
+			$recordSet->moveNext();
+		}
+		$res->addParsedNamespaces($this->getParsedNamespaces());
+		return $res;
+	}
+
+
+	/**
+	* Create the dynamic part of an sql statement selecting triples with the
+	* given parameters ($subject, $predicate, $object).
+	*
+	* @param	object Resource	$subject
+	* @param	object Resource	$predicate
+	* @param	object Node	$object
+	* @return  string
+	* @access	private
+	*/
+	function _createDynSqlPart_SPO($subject, $predicate, $object) {
+
+		// conditions derived from the parameters passed to the function
+
+		$subject_is=is_a($subject,'BlankNode')?'b':(is_a($subject,'Resource')?'r':'l');
+		$sql='';
+		if ($subject != NULL)
+			$sql .= " AND subject='" .$subject->getLabel() ."'
+                AND subject_is='" .$subject_is ."'";
+		if ($predicate != NULL)
+			$sql .= " AND predicate='" .$predicate->getLabel() ."'";
+		if ($object != NULL) {
+			$object_is = is_a($object,'BlankNode')?'b':(is_a($object,'Resource')?'r':'l');
+			if (is_a($object, 'Resource'))
+				$sql .= " AND object='" .$object->getLabel() ."'
+                   AND object_is ='" .$object_is ."'";
+			else  {
+				$quotedLiteral = $this->dbConn->qstr($object->getLabel());
+				$sql .= " AND object=" .$quotedLiteral ."
+                   AND l_language='" .$object->getLanguage() ."'
+                   AND l_datatype='" .$object->getDataType() ."'
+                   AND object_is ='" .$object_is ."'";
+			}
+		}
+		return $sql;
+	}
+
+
+	/**
+	* Get an ADORecordSet with array fields[] containing a representation of
+	* the given DbModel stored in the table: statements, with an index corresponding
+	* to following table columns:
+	* [0] - subject, [1] - predicate, [2] - object, [3] - l_language,
+	* [4] - l_datatype, [5] - subject_is, [6] - object_is
+	* (This method operates on data from a DbModel without loading it into a memory model
+	*  in order to save resources and improve speed).
+	*
+	* @param	object DbModel	$DbModel
+	* @return  object ADORecordSet
+	* @access	private
+	*/
+	function _getRecordSet (&$dbModel) {
+
+		$sql = 'SELECT subject, predicate, object, l_language, l_datatype, subject_is, object_is
+           FROM statements
+           WHERE modelID = ' .$dbModel->modelID;
+
+		return $recordSet =& $this->dbConn->execute($sql);
+	}
+
+
+	/**
+	* Check if this DbModel contains the given row from the array fields[] of an ADORecordSet
+	* The array index corresponds to following table columns:
+	* [0] - subject, [1] - predicate, [2] - object, [3] - l_language,
+	* [4] - l_datatype, [5] - subject_is, [6] - object_is
+	*
+	* @param   array  $row
+	* @return  boolean
+	* @access	private
+	*/
+	function _containsRow ($row) {
+
+		$sql = "SELECT modelID FROM statements
+           WHERE modelID = " .$this->modelID ."
+           AND subject ="   .$this->dbConn->qstr($row[0]) ."
+           AND predicate =" .$this->dbConn->qstr($row[1]) ."
+           AND object ="    .$this->dbConn->qstr($row[2]) ."
+           AND l_language=" .$this->dbConn->qstr($row[3]) ."
+           AND l_datatype=" .$this->dbConn->qstr($row[4]) ."
+           AND subject_is=" .$this->dbConn->qstr($row[5]) ."
+           AND object_is="  .$this->dbConn->qstr($row[6]);
+
+		$res =& $this->dbConn->getOne($sql);
+
+		if (!$res)
+		  return FALSE;
+		return TRUE;
+	}
+
+
+
+
+
+	/**
+	* Returns the models namespaces.
+	*
+	* @author   Tobias Gauss <tobias.gauss@web.de>
+	* @return mixed Array of key-value pairs. Namespace is the key,
+	*               prefix the value. If no namespaces are found,
+	*               boolean false is returned.
+	*
+	* @access   public
+	*/
+	function getParsedNamespaces(){
+		$sql = "SELECT * FROM namespaces
+           WHERE modelID = " .$this->modelID;
+		$temp = false;
+		$res  = $this->dbConn->execute($sql);
+		if($res){
+			while (!$res->EOF) {
+				$temp[$res->fields[1]]=$res->fields[2];
+				$res->moveNext();
+			}
+		}
+		return $temp;
+	}
+
+
+
+	/**
+	* Adds the namespaces to the model. This method is called by
+	* the parser. !!!! addParsedNamespaces() not overwrites manual
+	* added namespaces in the model !!!!
+	*
+	* @author Tobias Gauss <tobias.gauss@web.de>
+	* @param array $newNs Array of namespace => prefix assignments
+	*
+	* @access   public
+	*/
+	function addParsedNamespaces($newNs){
+		if($newNs)
+		foreach($newNs as $namespace => $prefix){
+			$this->addNamespace($prefix, $namespace);
+		}
+	}
+
+
+	/**
+	* Adds a namespace and prefix to the model.
+	*
+	* @author   Tobias Gauss <tobias.gauss@web.de>
+	* @param string $prefix Prefix
+	* @param string $nmsp   Namespace URI
+    *
+	* @access   public
+	*/
+	function addNamespace($prefix,$nmsp){
+
+		if($nmsp != '' && $prefix !=''){
+			if($this->_checkNamespace($nmsp)){
+				$sql = "UPDATE namespaces SET prefix=".$this->dbConn->qstr($prefix)." WHERE
+				modelID=".$this->modelID." AND namespace=".$this->dbConn->qstr($nmsp);
+			}else{
+				$sql = "INSERT INTO namespaces
+                    (modelID, namespace, prefix)
+                    VALUES
+                    (" .$this->modelID .','
+				. $this->dbConn->qstr($nmsp)   . ','
+				. $this->dbConn->qstr($prefix) . ')';
+			}
+
+			$rs =& $this->dbConn->execute($sql);
+			if (!$rs)
+			$this->dbConn->errorMsg();
+		}
+	}
+
+	/**
+	* checks if a namespace is already in the model.
+	*
+	* @author   Tobias Gauï¿œ<tobias.gauss@web.de>
+	* @access   private
+	* @param    Array $newNs
+	*/
+	function _checkNamespace($nmsp){
+		$res = true;
+		$sql = "SELECT * FROM namespaces
+          	 WHERE modelID = " .$this->modelID." AND
+			namespace=" . $this->dbConn->qstr($nmsp);
+		$rs =& $this->dbConn->execute($sql);
+		if (!$rs){
+			$this->dbConn->errorMsg();
+		}else{
+			if($rs->fields == false)
+			$res = false;
+		}
+		return $res;
+
+
+	}
+
+	/**
+	* Returns a FindIterator for traversing the MemModel.
+	* @access	public
+	* @return	object	FindIterator
+	*/
+	function & iterFind($sub=null,$pred=null,$obj=null) {
+		// Import Package Utility
+		include_once(RDFAPI_INCLUDE_DIR.PACKAGE_UTILITY);
+
+		$if = new IterFind($this,$sub,$pred,$obj);
+		return $if;
+	}
+
+	/**
+	* Removes a single namespace from the model
+	*
+	* @author Tobias Gauss <tobias.gauss@web.de>
+	* @param string $nmsp Namespace URI
+	*
+	* @return mixed True if all went well, error message otherwise
+	*
+	* @access   public
+	*/
+	function removeNamespace($nmsp){
+
+        $sql = 'DELETE FROM namespaces
+           WHERE modelID=' .$this->modelID." AND namespace=". $this->dbConn->qstr($nmsp);
+
+        $rs =& $this->dbConn->execute($sql);
+        if (!$rs)
+            return $this->dbConn->errorMsg();
+        else {
+            return true;
+        }
+	}
+
+
+
+
+	/**
+	* Add the given row from the array fields[] of an ADORecordSet to this DbModel
+	* The array index corresponds to following table columns:
+	* [0] - subject, [1] - predicate, [2] - object, [3] - l_language,
+	* [4] - l_datatype, [5] - subject_is, [6] - object_is
+	*
+	* @param   array  $row
+	* @throws  SqlError
+	* @access	private
+	*
+	function _insertRow ($row) {
+
+	$quotedObject = $this->dbConn->qstr($row[2]);
+	$sql = "INSERT INTO statements VALUES
+	(" .$this->modelID .","
+	."'" .$row[0] ."',"
+	."'" .$row[1] ."',"
+	.""  .$quotedObject .","
+	."'" .$row[3] ."',"
+	."'" .$row[4] ."',"
+	."'" .$row[5] ."',"
+	."'" .$row[6] ."')";
+
+	$rs =& $this->dbConn->execute($sql);
+	if (!$rs)
+	$this->dbConn->errorMsg();
+	}
+	*/
+
+} // end: Class DbModel
+?>
Index: /Dev/trunk/rdfapi/model/DbStore.php
===================================================================
--- /Dev/trunk/rdfapi/model/DbStore.php	(revision 12)
+++ /Dev/trunk/rdfapi/model/DbStore.php	(revision 12)
@@ -0,0 +1,917 @@
+<?php
+require_once RDFAPI_INCLUDE_DIR . 'constants.php';
+require_once RDFAPI_INCLUDE_DIR . 'util/Object.php';
+
+// ----------------------------------------------------------------------------------
+// Class: DbStore
+// ----------------------------------------------------------------------------------
+
+/**
+ * DbStore is a persistent store of RDF data using relational database technology.
+ * DbStore uses ADOdb Library for PHP V3.60 (http://php.weblogs.com/ADODB),
+ * which allows to connect to multiple databases in a portable manner.
+ * This class also provides methods for creating tables for MsAccess, MySQL, and MS SQL Server.
+ * If you want to use other databases, you will have to create tables by yourself
+ * according to the abstract database schema described in the API documentation.
+ *
+ * You can activate debug mode by defining ADODB_DEBUG_MODE to "1".
+ *
+ *
+ * @version  $Id: DbStore.php 560 2008-02-29 15:24:20Z cax $
+ * @author   Radoslaw Oldakowski <radol@gmx.de>
+ * @author   Daniel Westphal (http://www.d-westphal.de)
+ *
+ * @package model
+ * @access	public
+ */
+
+
+class DbStore extends Object
+{
+    /**
+    * Array with all supported database types
+    *
+    * @var array
+    */
+    public static $arSupportedDbTypes = array(
+        "MySQL",
+        "MySQLi",
+        "MSSQL",
+        'MsAccess'
+    );
+
+    /**
+    * Database connection object
+    *
+    * @var     object ADOConnection
+    * @access	private
+    */
+    var $dbConn;
+
+    /**
+    * Database driver name
+    *
+    * @var string
+    */
+    protected $driver = null;
+
+    /**
+    *   SparqlParser so we can re-use it
+    *   @var Parser
+    */
+    var $queryParser = null;
+
+
+/**
+ * Constructor:
+ * Set the database connection with the given parameters.
+ *
+ * @param   string   $dbDriver
+ * @param   string   $host
+ * @param   string   $dbName
+ * @param   string   $user
+ * @param   string   $password
+ * @access	public
+ */
+ function DbStore ($dbDriver=ADODB_DB_DRIVER, $host=ADODB_DB_HOST, $dbName=ADODB_DB_NAME,
+                   $user=ADODB_DB_USER, $password=ADODB_DB_PASSWORD) {
+
+   // include DBase Package
+   require_once(RDFAPI_INCLUDE_DIR.PACKAGE_DBASE);
+
+   // create a new connection object
+   $this->dbConn =& ADONewConnection($dbDriver);
+   $this->driver = $dbDriver;
+
+   //activate the ADOdb DEBUG mode
+   if (ADODB_DEBUG_MODE == '1')
+        $this->dbConn->debug = true;
+
+   // connect to database
+   $r = $this->dbConn->NConnect($host, $user, $password, $dbName);
+   if ($r !== true) {
+      throw new Exception('Could not connect to database');
+   }
+
+   // optimized for speed
+   $this->dbConn->setFetchMode(ADODB_FETCH_NUM);
+   //$ADODB_COUNTRECS = FALSE;
+ }
+
+
+
+/**
+ * List all DbModels stored in the database.
+ *
+ * @return  array
+ * @throws	SqlError
+ * @access	public
+ */
+ function listModels() {
+
+   $recordSet =& $this->dbConn->execute("SELECT modelURI, baseURI
+                                         FROM models");
+   if (!$recordSet)
+      echo $this->dbConn->errorMsg();
+   else {
+      $models = array();
+      $i=0;
+      while (!$recordSet->EOF) {
+
+          $models[$i]['modelURI'] = $recordSet->fields[0];
+          $models[$i]['baseURI'] = $recordSet->fields[1];
+
+          ++$i;
+          $recordSet->moveNext();
+      }
+      return $models;
+   }
+ }
+
+
+/**
+ * Check if the DbModel with the given modelURI is already stored in the database
+ *
+ * @param   string   $modelURI
+ * @return  boolean
+ * @throws	SqlError
+ * @access	public
+ */
+ function modelExists($modelURI) {
+
+   $res =& $this->dbConn->execute("SELECT COUNT(*) FROM models
+                                   WHERE modelURI = '" .$modelURI ."'");
+   if (!$res)
+      echo $this->dbConn->errorMsg();
+   else {
+      if (!$res->fields[0]) {
+          $res->Close();
+         return FALSE;
+      } else {
+          $res->Close();
+          return TRUE;
+      }
+   }
+ }
+
+
+
+    /**
+    * Returns the database connection object
+    *
+    * @return ADOdb Database object
+    * @access public
+    */
+    function &getDbConn()
+    {
+        return $this->dbConn;
+    }
+
+
+/**
+ * Create a new instance of DbModel with the given $modelURI and
+ * load the corresponding values of modelID and baseURI from the database.
+ * Return FALSE if the DbModel does not exist.
+ *
+ * @param   string   $modelURI
+ * @return  object DbModel
+ * @access	public
+ */
+ function getModel($modelURI) {
+
+   if (!$this->modelExists($modelURI))
+      return FALSE;
+   else {
+      $modelVars =& $this->dbConn->execute("SELECT modelURI, modelID, baseURI
+                                            FROM models
+                                            WHERE modelURI='" .$modelURI ."'");
+
+      return new DbModel($this->dbConn, $modelVars->fields[0],
+                         $modelVars->fields[1], $modelVars->fields[2]);
+   }
+ }
+
+
+/**
+ * Create a new instance of DbModel with the given $modelURI
+ * and insert the DbModel variables into the database.
+ * Return FALSE if there is already a model with the given URI.
+ *
+ * @param   string   $modelURI
+ * @param   string   $baseURI
+ * @return  object DbModel
+ * @throws  SqlError
+ * @access	public
+ */
+ function getNewModel($modelURI, $baseURI=NULL) {
+
+   if ($this->modelExists($modelURI))
+      return FALSE;
+   else {
+      $modelID = $this->_createUniqueModelID();
+
+      $rs =& $this->dbConn->execute("INSERT INTO models
+                                            (modelID, modelURI, baseURI)
+                                            VALUES (" .$modelID .",
+                                                    " .$this->dbConn->qstr($modelURI) .",
+                                                    " .$this->dbConn->qstr($baseURI) .")");
+
+      if (!$rs)
+         return $this->dbConn->errorMsg();
+      else
+         return new DbModel($this->dbConn, $modelURI, $modelID, $baseURI);
+   }
+ }
+
+
+/**
+ * Store a MemModel or another DbModel from a different DbStore in the database.
+ * Return FALSE if there is already a model with modelURI matching the modelURI
+ * of the given model.
+ *
+ * @param   object Model  &$model
+ * @param   string $modelURI
+ * @return  boolean
+ * @access	public
+ */
+ function putModel(&$model, $modelURI=NULL) {
+
+   if (!$modelURI) {
+      if (is_a($model, 'MemModel'))
+         $modelURI = 'DbModel-' .$this->_createUniqueModelID();
+      else
+         $modelURI = $model->modelURI;
+   }else
+      if ($this->modelExists($modelURI))
+         return FALSE;
+
+
+   $newDbModel = $this->getNewModel($modelURI, $model->getBaseURI());
+   $newDbModel->addModel($model);
+ }
+
+
+/**
+ * Close the DbStore.
+ * !!! Warning: If you close the DbStore all active instances of DbModel from this
+ * !!!          DbStore will lose their database connection !!!
+ *
+ * @access	public
+ */
+ function close() {
+
+   $this->dbConn->close();
+   unset($this);
+ }
+
+
+// =============================================================================
+// **************************** private methods ********************************
+// =============================================================================
+
+
+/**
+ * Create a unique ID for the DbModel to be insert into the models table.
+ * This method was implemented because some databases do not support auto-increment.
+ *
+ * @return  integer
+ * @access	private
+ */
+ function _createUniqueModelID() {
+
+   $maxModelID =& $this->dbConn->GetOne('SELECT MAX(modelID) FROM models');
+   return ++$maxModelID;
+ }
+
+ /**
+ * Create a unique ID for the dataset to be insert into the datasets table.
+ * This method was implemented because some databases do not support auto-increment.
+ *
+ * @return  integer
+ * @access	private
+ */
+ function _createUniqueDatasetID() {
+
+   $maxDatasetID =& $this->dbConn->GetOne('SELECT MAX(datasetId) FROM datasets');
+   return ++$maxDatasetID;
+ }
+
+
+
+    /**
+     * Sets up tables for RAP.
+     * DOES NOT CHECK IF TABLES ALREADY EXIST
+     *
+     * @param string  $databaseType Database driver name (e.g. MySQL)
+     *
+     * @throws Exception If database type is unsupported
+     * @access public
+     **/
+    public function createTables($databaseType = null)
+    {
+        $driver = $this->getDriver($databaseType);
+        self::assertDriverSupported($driver);
+
+        $createFunc = '_createTables_' . $driver;
+        return $this->$createFunc();
+    }//public function createTables($databaseType="MySQL")
+
+
+
+    /**
+    * Create tables and indexes for MsAccess database
+    *
+    * @return boolean true If all is ok
+    *
+    * @throws Exception
+    */
+    protected function _createTables_MsAccess()
+    {
+        $this->dbConn->startTrans();
+
+        $this->dbConn->execute('CREATE TABLE models
+                                (modelID long primary key,
+                                    modelURI varchar not null,
+                                    baseURI varchar)');
+
+        $this->dbConn->execute('CREATE UNIQUE INDEX m_modURI_idx ON models (modelURI)');
+
+        $this->dbConn->execute('CREATE TABLE statements
+                                (modelID long,
+                                    subject varchar,
+                                    predicate varchar,
+                                    object Memo,
+                                    l_language varchar,
+                                    l_datatype varchar,
+                                    subject_is varchar(1),
+                                    object_is varchar(1),
+                                    primary key (modelID, subject, predicate, object,
+                                    l_language, l_datatype))');
+
+        $this->dbConn->execute('CREATE INDEX s_mod_idx ON statements (modelID)');
+        $this->dbConn->execute('CREATE INDEX s_sub_idx ON statements (subject)');
+        $this->dbConn->execute('CREATE INDEX s_pred_idx ON statements (predicate)');
+        $this->dbConn->execute('CREATE INDEX s_obj_idx ON statements (object)');
+
+        $this->dbConn->execute('CREATE TABLE namespaces
+                            (modelID long,
+                                namespace varchar,
+                                prefix varchar,
+                                primary key (modelID, namespace, prefix))');
+
+        $this->dbConn->execute('CREATE INDEX n_name_idx ON namespaces (namespace)');
+        $this->dbConn->execute('CREATE INDEX n_pref_idx ON namespaces (prefix)');
+
+        $this->dbConn->execute("CREATE TABLE datasets
+                            (datasetName varchar,
+                                defaultModelUri varchar,
+                                primary key (datasetName))");
+
+        $this->dbConn->execute('CREATE INDEX nGS_idx1 ON datasets (datasetName)');
+
+
+        $this->dbConn->execute("CREATE TABLE `dataset_model` (
+                                    datasetName varchar,
+                                    modelId long,
+                                    graphURI varchar,
+                                    PRIMARY KEY  (modelId,datasetName))");
+
+
+        if (!$this->dbConn->completeTrans()) {
+            throw new Exception($this->dbConn->errorMsg());
+        }
+        return true;
+    }
+
+
+
+    /**
+    * Create tables and indexes for MySQL database
+    *
+    * @return boolean true If all is ok
+    *
+    * @throws Exception
+    */
+    function _createTables_MySQL()
+    {
+
+        $this->dbConn->startTrans();
+
+        $this->dbConn->execute("CREATE TABLE models
+                                (modelID bigint NOT NULL,
+                                    modelURI varchar(255) NOT NULL,
+                                    baseURI varchar(255) DEFAULT '',
+                                    primary key (modelID))");
+
+        $this->dbConn->execute('CREATE UNIQUE INDEX m_modURI_idx ON models (modelURI)');
+
+        $this->dbConn->execute("CREATE TABLE statements
+                                (modelID bigint NOT NULL,
+                                    subject varchar(255) NOT NULL,
+                                    predicate varchar(255) NOT NULL,
+                                    object text,
+                                    l_language varchar(255) DEFAULT '',
+                                    l_datatype varchar(255) DEFAULT '',
+                                    subject_is varchar(1) NOT NULL,
+                                    object_is varchar(1) NOT NULL)");
+
+        $this->dbConn->execute("CREATE TABLE namespaces
+                                (modelID bigint NOT NULL,
+                                    namespace varchar(255) NOT NULL,
+                                    prefix varchar(255) NOT NULL,
+                                    primary key (modelID,namespace))");
+
+        $this->dbConn->execute("CREATE TABLE `dataset_model` (
+                                    `datasetName` varchar(255) NOT NULL default '0',
+                                    `modelId` bigint(20) NOT NULL default '0',
+                                    `graphURI` varchar(255) NOT NULL default '',
+                                    PRIMARY KEY  (`modelId`,`datasetName`))");
+
+        $this->dbConn->execute("CREATE TABLE `datasets` (
+                                    `datasetName` varchar(255) NOT NULL default '',
+                                    `defaultModelUri` varchar(255) NOT NULL default '0',
+                                    PRIMARY KEY  (`datasetName`),
+                                    KEY `datasetName` (`datasetName`))");
+
+        $this->dbConn->execute('CREATE INDEX s_mod_idx ON statements (modelID)');
+        $this->dbConn->execute('CREATE INDEX n_mod_idx ON namespaces (modelID)');
+
+        $this->dbConn->execute('CREATE INDEX s_sub_pred_idx ON statements
+                                (subject(200),predicate(200))');
+
+        $this->dbConn->execute('CREATE INDEX s_sub_idx ON statements (subject(200))');
+        $this->dbConn->execute('CREATE INDEX s_pred_idx ON statements (predicate(200))');
+        $this->dbConn->execute('CREATE INDEX s_obj_idx ON statements (object(250))');
+
+        $this->dbConn->execute('CREATE FULLTEXT INDEX s_obj_ftidx ON statements (object)');
+
+        if (!$this->dbConn->completeTrans()) {
+            throw new Exception($this->dbConn->errorMsg());
+        }
+        return true;
+    }
+
+
+
+    /**
+    * Creates tables on a MySQLi database
+    */
+    function _createTables_MySQLi()
+    {
+        return $this->_createTables_MySQL();
+    }//function _createTables_MySQLi()
+
+
+
+    /**
+    * Create tables and indexes for MSSQL database
+    *
+    * @return boolean true If all is ok
+    *
+    * @throws Exception
+    */
+    function _createTables_MSSQL()
+    {
+        $this->dbConn->startTrans();
+
+        $this->dbConn->execute("CREATE TABLE [dbo].[models] (
+                                    [modelID] [int] NOT NULL ,
+                                    [modelURI] [nvarchar] (200) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
+                                    [baseURI] [nvarchar] (200) COLLATE SQL_Latin1_General_CP1_CI_AS NULL
+                                    ) ON [PRIMARY]");
+
+        $this->dbConn->execute("CREATE TABLE [dbo].[statements] (
+                                    [modelID] [int] NOT NULL ,
+                                    [subject] [nvarchar] (200) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
+                                    [predicate] [nvarchar] (200) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
+                                    [object] [text] COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
+                                    [l_language] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
+                                    [l_datatype] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
+                                    [subject_is] [nchar] (1) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
+                                    [object_is] [nchar] (1) COLLATE SQL_Latin1_General_CP1_CI_AS NULL
+                                    ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]");
+
+
+        $this->dbConn->execute("CREATE TABLE [dbo].[namespaces] (
+                                    [modelID] [int] NOT NULL ,
+                                    [namespace] [nvarchar] (200) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
+                                    [prefix] [nvarchar] (200) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
+                                    ) ON [PRIMARY]");
+
+        $this->dbConn->execute("ALTER TABLE [dbo].[models] WITH NOCHECK ADD
+                                    CONSTRAINT [PK_models] PRIMARY KEY  CLUSTERED
+                                    (
+                                        [modelID]
+                                    )  ON [PRIMARY] ");
+        $this->dbConn->execute("ALTER TABLE [dbo].[namespaces] WITH NOCHECK ADD
+                                    CONSTRAINT [PK_namespaces] PRIMARY KEY  CLUSTERED
+                                    (
+                                        [modelID],[namespace]
+                                    )  ON [PRIMARY] ");
+
+        $this->dbConn->execute("CREATE  INDEX [joint index on subject and predicate] ON [dbo].[statements]([subject], [predicate]) ON [PRIMARY]");
+
+
+        if (!$this->dbConn->completeTrans()) {
+            throw new Exception($this->dbConn->errorMsg());
+        }
+        return true;
+    }
+
+
+
+    /**
+     * Checks if tables are setup for RAP
+     *
+     * @param   string  $databaseType
+     * @throws Exception If database type is unsupported
+     * @access public
+     **/
+    public function isSetup($databaseType = null)
+    {
+        $driver = $this->getDriver($databaseType);
+        self::assertDriverSupported($driver);
+
+        $issetupFunc = '_isSetup_' . $driver;
+        return $this->$issetupFunc();
+    }//public function isSetup($databaseType="MySQL")
+
+
+
+    /**
+    * Returns the driver for the database type.
+    * You can pass NULL or omit the parameter to
+    *  use the parameter from the dbstore constructor
+    *
+    * @param string $databaseType Database driver name (e.g. MySQL)
+    *
+    * @return string Database driver string (e.g. MySQL)
+    */
+    public function getDriver($databaseType = null)
+    {
+        if ($databaseType === null) {
+            if ($this->driver === null) {
+                //backward compatibility
+                $databaseType = 'MySQL';
+            } else {
+                $databaseType = $this->driver;
+            }
+        }
+        if (!self::isDriverSupported($databaseType)) {
+            //check if it is a known driver in wrong case
+            $arLowercases = array_map('strtolower', self::$arSupportedDbTypes);
+            $arMapping    = array_combine($arLowercases, self::$arSupportedDbTypes);
+            if (isset($arMapping[strtolower($databaseType)])) {
+                $databaseType = $arMapping[strtolower($databaseType)];
+            }
+        }
+        return $databaseType;
+    }//public function getDriver($databaseType = null)
+
+
+
+    /**
+    * Returns if the given driver is supported
+    *
+    * @return boolean True if it supported, false if not
+    */
+    public static function isDriverSupported($databaseType)
+    {
+        return in_array($databaseType, self::$arSupportedDbTypes);
+    }//public static function isDriverSupported($databaseType)
+
+
+
+    /**
+    * Checks if the given driver is supported and throws an
+    * Exception if not.
+    *
+    * @param string $databaseType Database driver name (e.g. MySQL)
+    *
+    * @return true If it does not fail
+    *
+    * @throws Exception If the driver is not supported
+    */
+    public static function assertDriverSupported($databaseType)
+    {
+        if (!self::isDriverSupported($databaseType)) {
+            throw new Exception(
+                'Unsupported database type, only supported: '
+                . implode(', ', self::$arSupportedDbTypes)
+            );
+        }
+        return true;
+    }//public static function assertDriverSupported($databaseType)
+
+
+
+    /**
+    * Checks if tables are setup for RAP (MySql)
+    *
+    * @throws SqlError
+    * @access private
+    **/
+    function _isSetup_MySQL()
+    {
+        $recordSet =& $this->dbConn->execute("SHOW TABLES");
+        if (!$recordSet) {
+            throw new Exception($this->dbConn->errorMsg());
+        } else {
+            $tables = array();
+            while (!$recordSet->EOF) {
+                $tables[]= $recordSet->fields[0];
+                if (isset($i)) {
+                    ++$i;
+                }
+                $recordSet->moveNext();
+            }
+            if (in_array("models",$tables) && in_array("statements",$tables)
+             && in_array("namespaces",$tables)) {
+                return true;
+            }
+        }
+        return false;
+    }//function _isSetup_MySQL()
+
+
+
+    /**
+    * Checks if tables are setup for RAP (MySQLi)
+    *
+    * @see _isSetup_MySQL()
+    */
+    function _isSetup_MySQLi()
+    {
+        return $this->_isSetup_MySQL();
+    }//function _isSetup_MySQLi()
+
+
+
+    /**
+    * Checks if tables are setup for RAP (MsAccess)
+    *
+    * @throws SqlError
+    * @access private
+    **/
+    function _isSetup_MsAccess()
+    {
+        $tables =& $this->dbConn->MetaTables();
+        if (!$tables) {
+            throw new Exception($this->dbConn->errorMsg());
+        }
+        if (count($tables) == 0) {
+            return false;
+        } else {
+            if (in_array("models",$tables) && in_array("statements",$tables)
+             && in_array("namespaces",$tables)) {
+                return true;
+            } else {
+                return false;
+            }
+        }
+    }//function _isSetup_MsAccess()
+
+
+
+    /**
+    * Checks if tables are setup for RAP (MSSQL)
+    *
+    * @throws SqlError
+    * @access private
+    **/
+    function _isSetup_MSSQL()
+    {
+        $tables =& $this->dbConn->MetaTables();
+        if (!$tables) {
+            throw new Exception($this->dbConn->errorMsg());
+        }
+        if (count($tables) == 0) {
+            return false;
+        } else {
+            if (in_array("models",$tables) && in_array("statements",$tables)
+             && in_array("namespaces",$tables)){
+                return true;
+            } else {
+                return false;
+            }
+        }
+    }//function _isSetup_MSSQL()
+
+
+ /**
+ * Create a new instance of DatasetDb with the given $datasetName
+ * and insert the DatasetDb variables into the database.
+ * Return FALSE if there is already a model with the given URI.
+ *
+ * @param   $datasetName string
+ * @return  object DatasetDB
+ * @throws  SqlError
+ * @access	public
+ */
+ function & getNewDatasetDb($datasetName)
+ {
+
+ 	require_once(RDFAPI_INCLUDE_DIR . PACKAGE_DATASET);
+
+   if ($this->datasetExists($datasetName))
+      return FALSE;
+   else
+   {
+   		$defaultModelUri=uniqid('http://rdfapi-php/dataset_defaultmodel_');
+   		$defaultModel=$this->getNewModel($defaultModelUri);
+
+      	$rs =& $this->dbConn->execute("INSERT INTO datasets
+                                            VALUES ('" .$this->dbConn->qstr($datasetName) ."',
+                                                    '" .$this->dbConn->qstr($defaultModelUri)."')");
+
+      if (!$rs)
+         $this->dbConn->errorMsg();
+      else
+		$return=new DatasetDb($this->dbConn, $this, $datasetName);
+   		return ($return);
+   }
+ }
+
+ /**
+ * Check if the Dataset with the given $datasetName is already stored in the database
+ *
+ * @param   $datasetName string
+ * @return  boolean
+ * @throws	SqlError
+ * @access	public
+ */
+function datasetExists($datasetName) {
+
+   $res =& $this->dbConn->execute("SELECT COUNT(*) FROM datasets
+                                   WHERE datasetName = '" .$datasetName ."'");
+   if (!$res)
+      echo $this->dbConn->errorMsg();
+   else {
+      if (!$res->fields[0])
+         return FALSE;
+      return TRUE;
+   }
+ }
+
+
+ /**
+ * Create a new instance of DatasetDb with the given $datasetName and
+ * load the corresponding values from the database.
+ * Return FALSE if the DbModel does not exist.
+ *
+ * @param   $datasetId string
+ * @return  object DatasetDb
+ * @access	public
+ */
+ function &getDatasetDb($datasetName) {
+    require_once(RDFAPI_INCLUDE_DIR . PACKAGE_DATASET);
+
+    if (!$this->datasetExists($datasetName)) {
+        return FALSE;
+    } else {
+        $return = new DatasetDb($this->dbConn, $this, $datasetName);
+        return ($return);
+    }
+ }
+
+ /**
+ * Create a new instance of namedGraphDb with the given $modelURI and graphName and
+ * load the corresponding values of modelID and baseURI from the database.
+ * Return FALSE if the DbModel does not exist.
+ *
+ * @param   $modelURI string
+ * @param   $graphName string
+ * @return  object NamedGraphMem
+ * @access	public
+ */
+ function getNamedGraphDb($modelURI, $graphName)
+ {
+	require_once(RDFAPI_INCLUDE_DIR . PACKAGE_DATASET);
+
+   if (!$this->modelExists($modelURI))
+      return FALSE;
+   else {
+      $modelVars =& $this->dbConn->execute("SELECT modelURI, modelID, baseURI
+                                            FROM models
+                                            WHERE modelURI='" .$modelURI ."'");
+
+      return new NamedGraphDb($this->dbConn, $modelVars->fields[0],
+                         $modelVars->fields[1], $graphName ,$modelVars->fields[2]);
+   }
+ }
+
+ /**
+ * Create a new instance of namedGraphDb with the given $modelURI and graphName
+ * and insert the DbModel variables into the database (not the graphName. This
+ * is only stored persistently, when added to dataset).
+ * Return FALSE if there is already a model with the given URI.
+ *
+ * @param   $modelURI string
+ * @param  	$graphName string
+ * @param   $baseURI string
+ * @return  object namedGraphDb
+ * @throws  SqlError
+ * @access	public
+ */
+ function getNewNamedGraphDb($modelURI, $graphName, $baseURI=NULL) {
+
+   if ($this->modelExists($modelURI))
+      return FALSE;
+   else {
+      $modelID = $this->_createUniqueModelID();
+
+      $rs =& $this->dbConn->execute("INSERT INTO models
+                                            (modelID, modelURI, baseURI)
+                                            VALUES (" .$modelID ."',
+                                                    " .$this->dbConn->qstr($modelURI) ."',
+                                                    " .$this->dbConn->qstr($baseURI) .")");
+      if (!$rs)
+         $this->dbConn->errorMsg();
+      else
+         return new NamedGraphDb($this->dbConn, $modelURI, $modelID, $graphName, $baseURI);
+   }
+ }
+
+ /**
+ * Removes the graph with all statements from the database.
+ * Warning: A single namedGraph can be added to several datasets. So it'll be
+ * removed from all datasets.
+ *
+ * @param   $modelURI string
+ * @return  boolean
+ * @throws  SqlError
+ * @access	public
+ */
+ function removeNamedGraphDb($modelURI)
+ {
+	if (!$this->modelExists($modelURI))
+		return FALSE;
+
+	$modelID = $this->dbConn->GetOne("SELECT modelID FROM models WHERE modelURI='".$modelURI."'");
+
+	$this->dbConn->execute("DELETE FROM models WHERE modelID=".$modelID);
+	$this->dbConn->execute("DELETE FROM dataset_model WHERE modelId=".$modelID);
+	$this->dbConn->execute("DELETE FROM statements WHERE modelID=".$modelID);
+
+	return true;
+ }
+
+
+
+    /**
+    * Performs a SPARQL query against a model. The model is converted to
+    * 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       Sparql query string
+    * @param mixed $arModelIds    Array of modelIDs, or NULL to use all models
+    * @param  string $resultform  Result form ('xml' for SPARQL Query Results XML Format)
+    * @return string/array
+    */
+    function sparqlQuery($query, $arModelIds = null, $resultform = false)
+    {
+        $engine = $this->_prepareSparql($arModelIds);
+        return $engine->queryModel(
+            null,
+            $this->_parseSparqlQuery($query),
+            $resultform
+        );
+    }//function sparqlQuery($query,$resultform = false)
+
+
+
+    /**
+    *   Prepares everything for SparqlEngine-usage
+    *   Loads the files, creates instances for SparqlEngine and
+    *   Dataset...
+    *
+    *   @return SparqlEngineDb
+    */
+    function _prepareSparql($arModelIds)
+    {
+        require_once RDFAPI_INCLUDE_DIR . 'sparql/SparqlEngineDb.php';
+        return new SparqlEngineDb($this, $arModelIds);
+    }//function _prepareSparql()
+
+
+
+    /**
+    *   Parses an query and returns the parsed form.
+    *   If the query is not a string but a Query object,
+    *   it will just be returned.
+    *
+    *   @param $query mixed String or Query object
+    *   @return Query query object
+    *   @throws Exception If $query is no string and no Query object
+    */
+    function _parseSparqlQuery($query)
+    {
+        if ($this->queryParser === null) {
+            require_once RDFAPI_INCLUDE_DIR . 'sparql/SparqlParser.php';
+            $this->queryParser = new SparqlParser();
+        }
+        return $this->queryParser->parse($query);
+    }//function _parseSparqlQuery($query)
+
+} // end: Class DbStore
+?>
Index: /Dev/trunk/rdfapi/model/Literal.php
===================================================================
--- /Dev/trunk/rdfapi/model/Literal.php	(revision 12)
+++ /Dev/trunk/rdfapi/model/Literal.php	(revision 12)
@@ -0,0 +1,188 @@
+<?php
+require_once RDFAPI_INCLUDE_DIR . 'model/Node.php';
+
+// ----------------------------------------------------------------------------------
+// Class: Literal
+// ----------------------------------------------------------------------------------
+
+/**
+ * An RDF literal.
+ * The literal supports the xml:lang and rdf:datatype property.
+ * For XML datatypes see: http://www.w3.org/TR/xmlschema-2/
+ *
+ * @version  $Id: Literal.php 497 2007-08-13 05:14:26Z cweiske $
+ * @author Chris Bizer <chris@bizer.de>
+ * @author Daniel Westphal <dawe@gmx.de>
+ *
+ * @package model
+ * @access	public
+ *
+ */
+ class Literal extends Node {
+
+	/**
+	* Label of the literal
+	* @var		string
+	* @access	private
+	*/
+    var $label;
+   /**
+	* Language of the literal
+	* @var		string
+	* @access	private
+	*/
+    var $lang;
+
+   /**
+	* Datatype of the literal
+	* @var		string
+	* @access	private
+	*/
+    var $dtype;
+
+
+   /**
+    * Constructor
+    *
+    * @param string $str      label of the literal
+    * @param string $language optional language identifier
+    * @param string $datatype optional datatype
+    *
+    */
+    function Literal($str, $language = NULL, $datatype = null)
+    {
+        $this->label = $str;
+
+        if ($language != NULL) {
+            $this->lang = $language;
+        } else {
+            $this->lang = NULL;
+        }
+
+        if ($datatype != null) {
+            $this->dtype = $datatype;
+        } else {
+            $this->dtype = NULL;
+        }
+    }
+
+  /**
+   * Returns the string value of the literal.
+   *
+   * @access	public
+   * @return	string value of the literal
+   */
+  function getLabel() {
+
+    return $this->label;
+  }
+
+  /**
+   * Returns the language of the literal.
+   *
+   * @access	public
+   * @return	string language of the literal
+   */
+  function getLanguage() {
+
+    return $this->lang;
+  }
+
+  /**
+   * Sets the language of the literal.
+   *
+   * @access	public
+   * @param	    string $lang
+   */
+  function setLanguage($lang) {
+
+    $this->lang = $lang;
+  }
+
+  /**
+   * Returns the datatype of the literal.
+   *
+   * @access	public
+   * @return	string datatype of the literal
+   */
+  function getDatatype() {
+
+    return $this->dtype;
+  }
+
+  /**
+   * Sets the datatype of the literal.
+   * Instead of datatype URI, you can also use an datatype shortcuts like STRING or INTEGER.
+   * The array $short_datatype with the possible shortcuts is definded in ../constants.php
+   *
+   * @access	public
+   * @param		string URI of XML datatype or datatype shortcut
+   *
+   */
+  function setDatatype($datatype) {
+	GLOBAL $short_datatype;
+	if  (stristr($datatype,DATATYPE_SHORTCUT_PREFIX))  {
+		$this->dtype = $short_datatype[substr($datatype,strlen(DATATYPE_SHORTCUT_PREFIX)) ];}
+	else
+	    $this->dtype = $datatype;
+  }
+
+  /**
+   * Checks if ihe literal equals another literal.
+   * Two literals are equal, if they have the same label and they
+   * have the same language/datatype or both have no language/datatype property set.
+   *
+   * @access	public
+   * @param		object	literal $that
+   * @return	boolean
+   */
+  function equals ($that) {
+
+	if (($that == NULL) or !(is_a($that, 'Literal'))) {
+	  return false;
+    }
+
+	if ( ($this->label == $that->getLabel()) && ( ( ($this->lang == $that->getLanguage()) ||
+	   ($this->lang == NULL && $that->getLanguage() == NULL) )  &&
+
+	   (
+	   ($this->dtype == $that->getDatatype() ||
+	   ($this->dtype == NULL && $that->getDatatype() == NULL)) ) ) )
+	     {
+			return true;
+	     }
+
+    return false;
+  }
+
+  /**
+   * Dumps literal.
+   *
+   * @access	public
+   * @return	string
+   */
+  function toString() {
+	$dump = 'Literal("' . $this->label .'"';
+	if ($this->lang != NULL)
+		$dump .= ', lang="' . $this->lang .'"';
+	if ($this->dtype != NULL)
+		$dump .= ', datatype="' . $this->dtype .'"';
+	$dump .= ')';
+    return $dump;
+  }
+
+
+
+    /**
+    *   Doing string magic in PHP5
+    *   @return string String representation of this Literal
+    */
+    function __toString()
+    {
+        return $this->toString();
+    }
+
+
+} // end: Literal
+
+?>
Index: /Dev/trunk/rdfapi/model/MemModel.php
===================================================================
--- /Dev/trunk/rdfapi/model/MemModel.php	(revision 12)
+++ /Dev/trunk/rdfapi/model/MemModel.php	(revision 12)
@@ -0,0 +1,1461 @@
+<?php
+require_once RDFAPI_INCLUDE_DIR . 'model/Model.php';
+// ----------------------------------------------------------------------------------
+// Class: MemModel
+// ----------------------------------------------------------------------------------
+
+/**
+* A MemModel is an RDF Model, which is stored in the main memory.
+* This class provides methods for manipulating MemModels.
+*
+*
+*
+* @version  $Id: MemModel.php 425 2007-05-01 12:59:18Z cweiske $
+* @author Chris Bizer <chris@bizer.de>
+* @author Gunnar AAstrand Grimnes <ggrimnes@csd.abdn.ac.uk>
+* @author Radoslaw Oldakowski <radol@gmx.de>
+* @author Daniel Westphal <mail@d-westphal.de>
+* @author Tobias GauÃ <tobias.gauss@web.de>
+*
+* @package model
+* @access	public
+*/
+
+class MemModel extends Model {
+
+	/**
+	* Triples of the MemModel
+	* @var		array
+	* @access	private
+	*/
+	var $triples = array();
+
+	/**
+	* Array containing the search indices
+	* @var		array['INDEX_TYPE'][]['label'][]['PosInModel']
+	*
+	* @access   private
+	*/
+	var $indexArr ;
+
+
+	/**
+	* depending on which index is used this variable is -1,0,1,2 or 3
+	*
+	* -1 : no index
+	*  0 : default indices over subject, predicate, object separate
+	*  1 : index over subject+predicate+object
+	*  2 : index over subject+predicate
+	*  3 : index over subject+object
+	*
+	* @var		int
+	* @access	private
+	*/
+	var $indexed;
+
+
+
+	/**
+	* Array of namespaces
+	*
+	* @var     array
+	* @access	private
+	*/
+	var $parsedNamespaces=array();
+
+
+
+	/**
+	* Constructor
+	* You can supply a base_uri
+	*
+	* @param string $baseURI
+	* @access	public
+	*/
+	function MemModel($baseURI = NULL) {
+		$this->setBaseURI($baseURI);
+		$this->indexed = INDEX_TYPE;
+	}
+
+	/**
+	* Set a base URI for the MemModel.
+	* Affects creating of new resources and serialization syntax.
+	* If the URI doesn't end with # : or /, then a # is added to the URI.
+	* @param	string	$uri
+	* @access	public
+	*/
+	function setBaseURI($uri) {
+
+		if ($uri != NULL) {
+			$c = substr($uri, strlen($uri)-1 ,1);
+			if (!($c=='#' || $c==':' || $c=='/' || $c=="\\"))
+			$uri .= '#';
+		}
+		$this->baseURI = $uri;
+	}
+
+
+	/**
+	* Number of triples in the MemModel
+	*
+	* @return	integer
+	* @access	public
+	*/
+	function size() {
+		return count($this->triples);
+	}
+
+	/**
+	* Checks if MemModel is empty
+	*
+	* @return	boolean
+	* @access	public
+	*/
+	function isEmpty() {
+		if (count($this->triples) == 0) {
+			return TRUE;
+		} else {
+			return FALSE;
+		};
+	}
+
+
+	/**
+	* 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())
+	*
+	* @param		object Statement	$statement
+	* @access	public
+	* @throws	PhpError
+	*/
+	function add($statement) {
+		if (!is_a($statement, 'Statement')) {
+			$errmsg = RDFAPI_ERROR . '(class: MemModel; method: add): Statement expected.';
+			trigger_error($errmsg, E_USER_ERROR);
+		}
+
+		if($this->indexed != -1){
+			$this->triples[] = $statement;
+			end($this->triples);
+			$k=key($this->triples);
+			if($this->indexed==0){
+				// index over S
+				$this->_indexOpr($statement,$k,4,1);
+				// index over P
+				$this->_indexOpr($statement,$k,5,1);
+				// index over O
+				$this->_indexOpr($statement,$k,6,1);
+			}else{
+				$this->_indexOpr($statement,$k,$this->indexed,1);
+			}
+
+		}else{
+			$this->triples[] = $statement;
+		}
+	}
+
+
+
+	/**
+	* 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.
+	*
+	* @param	object Statement	$statement
+	* @return    boolean
+	* @access	public
+	* @throws	PhpError
+	*/
+	function addWithoutDuplicates($statement) {
+
+		if (!is_a($statement, 'Statement')) {
+			$errmsg = RDFAPI_ERROR . '(class: MemModel; method: addWithoutDuplicates): Statement expected.';
+			trigger_error($errmsg, E_USER_ERROR);
+		}
+
+		if (!$this->contains($statement)) {
+			$this->add($statement);
+			return true;
+		}else{
+			return false;
+		}
+	}
+
+	/**
+	* Removes the triple from the MemModel.
+	* TRUE if the triple is removed.
+	* FALSE otherwise.
+	*
+	* @param		object Statement	$statement
+	* @return    boolean
+	* @access	public
+	* @throws	PhpError
+	*/
+	function remove($statement) {
+
+		if (!is_a($statement, 'Statement')) {
+			$errmsg = RDFAPI_ERROR . '(class: MemModel; method: remove): Statement expected.';
+			trigger_error($errmsg, E_USER_ERROR);
+		}
+		if($this->indexed==-1){
+			$pass=false;
+			foreach($this->triples as $key => $value) {
+				if ($this->matchStatement($value, $statement->subject(), $statement->predicate(), $statement->object())) {
+					unset($this->triples[$key]);
+					$pass= true;
+				}
+			}
+			return $pass;
+		}else{
+			$k= null;
+			if($this->indexed==0){
+				$pass=false;
+				$del=false;
+				while($del!=-1){
+					// index over S
+					$del=$this->_indexOpr($statement,$k,4,0);
+					// index over P
+					$this->_indexOpr($statement,$k,5,0);
+					// index over O
+					$this->_indexOpr($statement,$k,6,0);
+					if($del!=-1){
+						unset($this->triples[$del]);
+						$pass=true;
+					}
+				}
+				return $pass;
+			}else{
+				$pass=false;
+				$del=false;
+				while($del!=-1){
+					$del=$this->_indexOpr($statement,$k,$this->indexed,0);
+					if($del!=-1){
+						unset($this->triples[$del]);
+						$pass=true;
+					}
+				}
+				return $pass;
+			}
+		}
+	}
+
+	/**
+	* Short Dump of the MemModel.
+	*
+	* @access	public
+	* @return	string
+	*/
+	function toString() {
+		return 'MemModel[baseURI=' . $this->getBaseURI() . ';  size=' . $this->size() . ']';
+	}
+
+	/**
+	* Dumps of the MemModel including all triples.
+	*
+	* @access	public
+	* @return	string
+	*/
+	function toStringIncludingTriples() {
+		$dump = $this->toString() . chr(13);
+		foreach($this->triples as $value) {
+			$dump .= $value->toString() . chr(13);
+		}
+		return $dump;
+	}
+
+
+
+
+	/**
+	* Writes the RDF serialization of the MemModel as HTML.
+	*
+	* @access	public
+	*/
+	function writeAsHtml() {
+		require_once(RDFAPI_INCLUDE_DIR.PACKAGE_SYNTAX_RDF);
+		$ser = new RdfSerializer();
+		$rdf =& $ser->serialize($this);
+		$rdf = htmlspecialchars($rdf, ENT_QUOTES);
+		$rdf = str_replace(' ', '&nbsp;', $rdf);
+		$rdf = nl2br($rdf);
+		echo $rdf;
+	}
+
+	/**
+	* Writes the RDF serialization of the MemModel as HTML table.
+	*
+	* @access	public
+	*/
+	function writeAsHtmlTable() {
+		// Import Package Utility
+		include_once(RDFAPI_INCLUDE_DIR.PACKAGE_UTILITY);
+		$rdfUtil = new RDFUtil();
+		$rdfUtil->writeHTMLTable($this);
+	}
+
+
+	/**
+	* Writes the RDF serialization of the MemModel as HTML table.
+	*
+	* @access	public
+	* @return	string
+	*/
+	function writeRdfToString() {
+		// Import Package Syntax
+		include_once(RDFAPI_INCLUDE_DIR.PACKAGE_SYNTAX_RDF);
+		$ser = new RdfSerializer();
+		$rdf =& $ser->serialize($this);
+		return $rdf;
+	}
+
+
+	/**
+	* Saves the RDF,N3 or N-Triple serialization of the MemModel 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 MemModel couldn't be saved to the file.
+	*
+	* @access	public
+	* @param 	string 	$filename
+	* @param 	string 	$type
+	* @throws   PhpError
+	* @return	boolean
+	*/
+	function saveAs($filename, $type ='rdf') {
+
+
+		// get suffix and create a corresponding serializer
+		if ($type=='rdf') {
+			// Import Package Syntax
+			include_once(RDFAPI_INCLUDE_DIR.PACKAGE_SYNTAX_RDF);
+			$ser=new RdfSerializer();
+		}elseif ($type=='nt') {
+			// Import Package Syntax
+			include_once(RDFAPI_INCLUDE_DIR.PACKAGE_SYNTAX_N3);
+			$ser=new NTripleSerializer();
+		}elseif ($type=='n3') {
+			// Import Package Syntax
+			include_once(RDFAPI_INCLUDE_DIR.PACKAGE_SYNTAX_N3);
+			$ser=new N3Serializer();
+		}else {
+			print ('Serializer type not properly defined. Use the strings "rdf","n3" or "nt".');
+			return false;
+		};
+
+		return $ser->saveAs($this, $filename);
+	}
+
+
+	/**
+	* Tests if the MemModel contains the given triple.
+	* TRUE if the triple belongs to the MemModel;
+	* FALSE otherwise.
+	*
+	* @param	object Statement	&$statement
+	* @return	boolean
+	* @access	public
+	*/
+	function contains(&$statement) {
+
+		// no index ->linear contains
+		if ($this->indexed==-1){
+			foreach($this->triples as $value) {
+				if ($value->equals($statement)){
+					return TRUE; }
+			}
+			return false;
+		}
+		if ($this->indexed==0){
+			$res = $this->_containsIndex($statement,4);
+			return $res;
+		}else{
+			return $this->_containsIndex($statement,$this->indexed);
+		}
+	}
+
+
+	/**
+	* Determine if all of the statements in a model are also contained in this MemModel.
+	* True if all of the statements in $model are also contained in this MemModel and false otherwise.
+	*
+	* @param	object Model	&$model
+	* @return	boolean
+	* @access	public
+	*/
+	function containsAll(&$model) {
+
+		if (is_a($model, 'MemModel')) {
+
+			foreach($model->triples as $statement)
+			if(!$this->contains($statement))
+			return FALSE;
+			return TRUE;
+
+		}elseif (is_a($model, 'DbModel'))
+
+		return $model->containsAll($this);
+
+		$errmsg = RDFAPI_ERROR . '(class: MemModel; method: containsAll): Model expected.';
+		trigger_error($errmsg, E_USER_ERROR);
+	}
+
+	/**
+	* Determine if any of the statements in a model are also contained in this MemModel.
+	* True if any of the statements in $model are also contained in this MemModel and false otherwise.
+	*
+	* @param	object Model	&$model
+	* @return	boolean
+	* @access	public
+	*/
+	function containsAny(&$model) {
+
+		if (is_a($model, 'MemModel')) {
+
+			foreach($model->triples as $modelStatement)
+			if($this->contains($modelStatement))
+			return TRUE;
+			return FALSE;
+
+		}elseif (is_a($model, 'DbModel'))
+
+		return $model->containsAny($this);
+
+		$errmsg = RDFAPI_ERROR . '(class: MemModel; method: containsAll): Model expected.';
+		trigger_error($errmsg, E_USER_ERROR);
+	}
+
+
+	/**
+	* Builds a search index for the statements in the MemModel.
+	* The index is used by the find(),contains(),add() and remove() functions.
+	* Performance example using a model with 43000 statements on a Linux machine:
+	* Find without index takes 1.7 seconds.
+	* Indexing takes 1.8 seconds.
+	* Find with index takes 0.001 seconds.
+	* So if you want to query a model more then once, build a index first.
+	* The defaultindex is indices over subject, predicate, object seperate.
+	*
+	* mode = 0    : indices over subject,predicate,object (default)
+	* mode = 1	 : index over subject+predicate+object
+	* mode = 2 	 : index over subject+predicate
+	* mode = 3	 : index over subject+object
+	*
+	* @param     int $mode
+	* @access	public
+	*/
+	function index($mode) {
+
+		unset($this->indexArr);
+		$this->indexArr=array();
+		switch($mode){
+			// unset indices
+			case -1:
+			$this->indexed=-1;
+			unset($this->indexArr);
+			break;
+			// index over SPO
+			case 0:
+			$this->indexed=0;
+			foreach($this->triples as $k => $t) {
+				// index over S
+				$this->_indexOpr($t,$k,4,1);
+				// index over P
+				$this->_indexOpr($t,$k,5,1);
+				// index over O
+				$this->_indexOpr($t,$k,6,1);
+			}
+			break;
+			default:
+			$this->indexed=$mode;
+			foreach($this->triples as $k => $t) {
+				$this->_indexOpr($t,$k,$this->indexed,1);
+			}
+			break;
+		}
+	}
+
+
+	/**
+	* Returns 	true if there is an index, false if not.
+	*
+	* @return	boolean
+	* @access	public
+	*/
+	function isIndexed() {
+		if($this->indexed!=-1){
+			return TRUE;
+		}else{
+			return FALSE;
+		}
+	}
+
+	/**
+	* Returns the indextype:
+	* -1 if there is no index, 0 if there are indices over S,P,O(separate),
+	* 1 if there is an index over SPO, 2 if there is an index over SP and 3 if
+	* there is an index over SO.
+	*
+	* @return int
+	* @access public
+	*
+	*/
+	function getIndexType(){
+		return $this->indexed;
+	}
+
+	/**
+	* 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.
+	*
+	* @param	object Node	$subject
+	* @param	object Node	$predicate
+	* @param	object Node	$object
+	* @return	object MemModel
+	* @access	public
+	* @throws	PhpError
+	*/
+
+	function find($subject,$predicate,$object) {
+
+		if (
+		(!is_a($subject, 'Resource') && $subject != NULL) ||
+		(!is_a($predicate, 'Resource') && $predicate != NULL) ||
+		(!is_a($object, 'Node') && $object != NULL)
+		) {
+			$errmsg = RDFAPI_ERROR . '(class: MemModel; method: find): Parameters must be subclasses of Node or NULL';
+			trigger_error($errmsg, E_USER_ERROR);
+		}
+
+		$res = new MemModel($this->getBaseURI());
+		$res->indexed=-1;
+
+		if($this->isEmpty())
+		return $res;
+
+		if($subject == NULL && $predicate == NULL && $object == NULL)
+		return $this;
+
+		switch($this->indexed){
+			case 1:
+			if($subject!=NULL && $predicate != NULL && $object != NULL){
+				$pos=$subject->getLabel().$predicate->getLabel().$object->getLabel();
+				return $this->_findInIndex($pos,$subject,$predicate,$object,1);
+			}else{
+				break;
+			}
+
+			case 2:
+			if($subject!=NULL && $predicate != NULL){
+				$pos=$subject->getLabel().$predicate->getLabel();
+				return $this->_findInIndex($pos,$subject,$predicate,$object,2);
+			}else{
+				break;
+			}
+
+			case 3:
+			if($subject!=NULL && $object != NULL){
+				$pos=$subject->getLabel().$object->getLabel();
+				return $this->_findInIndex($pos,$subject,$predicate,$object,3);
+			}else{
+				break;
+			}
+			case 0:
+			if($subject!= null){
+				$pos=$subject->getLabel();
+				return $this->_findInIndex($pos,$subject,$predicate,$object,4);
+			}
+			if($predicate!= null){
+				$pos=$predicate->getLabel();
+				return $this->_findInIndex($pos,$subject,$predicate,$object,5);
+			}
+			if($object!= null){
+				$pos=$object->getLabel();
+				return $this->_findInIndex($pos,$subject,$predicate,$object,6);
+			}
+		}
+		// if no index: linear search
+		foreach($this->triples as $value) {
+			if ($this->matchStatement($value, $subject, $predicate, $object))
+			$res->add($value);
+		}
+		return $res;
+
+	}
+
+
+
+
+
+	/**
+	* 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.
+	*
+	* @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) {
+
+		$res = new MemModel($this->getBaseURI());
+
+		if($this->size() == 0)
+		return $res;
+
+		if($subject_regex == NULL && $predicate_regex == NULL && $object_regex == NULL)
+		return $this;
+
+		foreach($this->triples as $value) {
+			if (
+			($subject_regex == NULL || preg_match($subject_regex, $value->subj->getLabel())) &&
+			($predicate_regex == NULL || preg_match($predicate_regex, $value->pred->getLabel())) &&
+			($object_regex == NULL || preg_match($object_regex, $value->obj->getLabel()))
+			) $res->add($value);
+		}
+
+		return $res;
+
+	}
+
+	/**
+	* 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.
+	*
+	* @param	string	$vocabulary
+	* @return	object MemModel
+	* @access	public
+	*/
+	function findVocabulary($vocabulary) {
+
+		if($this->size() == 0)
+		return new MemModel();
+		if($vocabulary == NULL || $vocabulary == '')
+		return $this;
+
+		$res = new MemModel($this->getBaseURI());
+		if($this->indexed==0){
+			foreach($this->indexArr[5] as $key => $value){
+				$pos=strpos($key,'#')+1;
+				if(substr($key,0,$pos)==$vocabulary){
+					for($i=1;$i<=$value[0];$i++){
+						$res->add($this->triples[$value[$i]]);
+					}
+				}
+			}
+			return $res;
+		}else{
+			// Import Package Utility
+			include_once(RDFAPI_INCLUDE_DIR.PACKAGE_UTILITY);
+			foreach($this->triples as $value) {
+				if (RDFUtil::getNamespace($value->getPredicate()) == $vocabulary)
+				$res->add($value);
+			}
+			return $res;
+		}
+	}
+
+	/**
+	* 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) {
+
+		$currentOffset = 0;
+		for($i=0;$i<=$offset;$i++)
+		{
+			$res = $this->findFirstMatchOff($subject, $predicate, $object, $currentOffset);
+			$currentOffset=$res+1;
+		}
+		if ($res != -1) {
+			return $this->triples[$res];
+		} else {
+			return NULL;
+		}
+	}
+
+
+
+
+	/**
+	* Searches for triples and returns the first matching statement from a given offset.
+	* This method is used by the util/findIterator. NULL input for any parameter will match anything.
+	* Example:  $result = $m->findFirstMatchingStatement( NULL, NULL, $node, $off );
+	* Returns the position of the first statement of the MemModel where the object equals $node from the given
+	* offset.
+	* Returns an -1 if nothing is found.
+	*
+	* @param	object Node	$subject
+	* @param	object Node	$predicate
+	* @param	object Node	$object
+	* @param int         $off
+	* @return	int
+	* @access	private
+	*/
+	function findFirstMatchOff($subject,$predicate, $object,$off) {
+
+		if (
+		(!is_a($subject, 'Resource') && $subject != NULL) ||
+		(!is_a($predicate, 'Resource') && $predicate != NULL) ||
+		(!is_a($object, 'Node') && $object != NULL)
+		) {
+			$errmsg = RDFAPI_ERROR . '(class: MemModel; method: find): Parameters must be subclasses of Node or NULL';
+			trigger_error($errmsg, E_USER_ERROR);
+		}
+
+		$match=-1;
+		$ind=$this->indexed;
+		if($subject == NULL && $predicate == NULL && $object == NULL)
+		{
+			foreach ($this->triples as $key => $statement)
+			{
+				if ($key >= $off)
+					return $key;
+			}
+			return -1;
+		}
+
+		switch($ind){
+			case 1:
+			if($subject!=NULL && $predicate != NULL && $object != NULL){
+				$pos=$subject->getLabel().$predicate->getLabel().$object->getLabel();
+				return $this->_findMatchIndex($pos,$subject,$predicate,$object,1,$off);
+			}else{
+				break;
+			}
+
+			case 2:
+			if($subject!=NULL && $predicate != NULL){
+				$pos=$subject->getLabel().$predicate->getLabel();
+				return $this->_findMatchIndex($pos,$subject,$predicate,$object,2,$off);
+			}else{
+				break;
+			}
+
+			case 3:
+			if($subject!=NULL && $object != NULL){
+				$pos=$subject->getLabel().$object->getLabel();
+				return $this->_findMatchIndex($pos,$subject,$predicate,$object,3,$off);
+			}else{
+				break;
+			}
+			case 0:
+			if($subject!= null){
+				$pos=$subject->getLabel();
+				return $this->_findMatchIndex($pos,$subject,$predicate,$object,4,$off);
+			}
+			if($predicate!= null){
+				$pos=$predicate->getLabel();
+				return $this->_findMatchIndex($pos,$subject,$predicate,$object,5,$off);
+			}
+			if($object!= null){
+				$pos=$object->getLabel();
+				return $this->_findMatchIndex($pos,$subject,$predicate,$object,6,$off);
+			}
+			break;
+		}
+		// if no index: linear search
+		foreach($this->triples as $key => $value){
+			if ($this->matchStatement($value, $subject, $predicate, $object)){
+				if($off<=$key){
+					$match=$key;
+					break;
+				}
+			}
+		}
+		return $match;
+	}
+
+
+	/**
+	* Searches for triples and returns the number of matches.
+	* NULL input for any parameter will match anything.
+	* Example:  $result = $m->findCount( NULL, NULL, $node );
+	* Finds all triples with $node as object.
+	*
+	* @param	object Node	$subject
+	* @param	object Node	$predicate
+	* @param	object Node	$object
+	* @return	integer
+	* @access	public
+	*/
+	function findCount($subject, $predicate, $object) {
+
+		$res = $this->find($subject, $predicate, $object);
+		return $res->size();
+
+	}
+
+
+	/**
+	* Perform an RDQL query on this MemModel.
+	* This method returns an associative array of variable bindings.
+	* The values of the query variables can either be RAP's objects (instances of Node)
+	* if $returnNodes set to TRUE, or their string serialization.
+	*
+	* @access	public
+	* @param string $queryString
+	* @param boolean $returnNodes
+	* @return  array   [][?VARNAME] = object Node  (if $returnNodes = TRUE)
+	*      OR  array   [][?VARNAME] = string
+	*
+	*/
+	function rdqlQuery($queryString, $returnNodes = TRUE) {
+
+		// Import RDQL Package
+		include_once(RDFAPI_INCLUDE_DIR.PACKAGE_RDQL);
+
+		$parser = new RdqlParser();
+		$parsedQuery =& $parser->parseQuery($queryString);
+
+		// this method can only query this MemModel
+		// if another model was specified in the from clause throw an error
+		if (isset($parsedQuery['sources'][1])) {
+			$errmsg = RDFAPI_ERROR . '(class: MemModel; method: rdqlQuery):';
+			$errmsg .= ' this method can only query this MemModel';
+			trigger_error($errmsg, E_USER_ERROR);
+		}
+
+		$engine = new RdqlMemEngine();
+		$res =& $engine->queryModel($this, $parsedQuery, $returnNodes);
+
+		return $res;
+	}
+
+	/**
+	* Perform an RDQL query on this MemModel.
+	* This method returns an RdqlResultIterator of variable bindings.
+	* The values of the query variables can either be RAP's objects (instances of Node)
+	* if $returnNodes set to TRUE, or their string serialization.
+	*
+	* @access	public
+	* @param string $queryString
+	* @param boolean $returnNodes
+	* @return  object RdqlResultIterator = with values as object Node  (if $returnNodes = TRUE)
+	*      OR  object RdqlResultIterator = with values as strings if (if $returnNodes = FALSE)
+	*
+	*/
+	function rdqlQueryAsIterator($queryString, $returnNodes = TRUE) {
+		// Import RDQL Package
+		include_once(RDFAPI_INCLUDE_DIR.PACKAGE_RDQL);
+		return new RdqlResultIterator($this->rdqlQuery($queryString, $returnNodes));
+	}
+
+	/**
+	* General method to replace nodes of a MemModel.
+	* NULL input for any parameter will match nothing.
+	* Example:  $m->replace($node, NULL, $node, $replacement);
+	* Replaces all $node objects beeing subject or object in
+	* any triple of the MemModel with the $needle node.
+	*
+	* @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) {
+
+		if (
+		(!is_a($replacement, 'Node')) ||
+		(!is_a($subject, 'Resource') && $subject != NULL) ||
+		(!is_a($predicate, 'Resource') && $predicate != NULL) ||
+		(!is_a($object, 'Node') && $object != NULL)
+		) {
+			$errmsg = RDFAPI_ERROR . '(class: MemModel; method: replace): Parameters must be subclasses of Node or NULL';
+			trigger_error($errmsg, E_USER_ERROR);
+		}
+
+		if($this->size() == 0)
+		break;
+		foreach($this->triples as $key => $value) {
+			if ($this->triples[$key]->subj->equals($subject)) {
+				$this->triples[$key]->subj = $replacement;
+			}
+			if ($this->triples[$key]->pred->equals($predicate))
+			$this->triples[$key]->pred = $replacement;
+			if ($this->triples[$key]->obj->equals($object))
+			$this->triples[$key]->obj = $replacement;
+
+		}
+		$this->index($this->indexed);
+	}
+
+
+	/**
+	* Internal method that checks, if a statement matches a S, P, O or NULL combination.
+	* NULL input for any parameter will match anything.
+	*
+	* @param	object Statement	$statement
+	* @param	object Node	$subject
+	* @param	object Node	$predicate
+	* @param	object Node	$object
+	* @return	boolean
+	* @access	private
+	*/
+	function matchStatement($statement, $subject, $predicate, $object)  {
+
+		if(($subject != NULL) AND !($statement->subj->equals($subject)))
+		return false;
+
+		if($predicate != NULL && !($statement->pred->equals($predicate)))
+		return false;
+
+		if($object != NULL && !($statement->obj->equals($object)))
+		return false;
+
+		return true;
+	}
+
+
+
+
+	/**
+	* Checks if two models are equal.
+	* Two models are equal if and only if the two RDF graphs they represent are isomorphic.
+	*
+	* @access	public
+	* @param		object	model &$that
+	* @throws    phpErrpr
+	* @return	boolean
+	*/
+
+	function equals(&$that)  {
+
+		if (!is_a($that, 'Model')) {
+			$errmsg = RDFAPI_ERROR . '(class: MemModel; method: equals): Model expected.';
+			trigger_error($errmsg, E_USER_ERROR);
+		}
+
+		if ($this->size() != $that->size())
+		return FALSE;
+		/*
+		if (!$this->containsAll($that))
+		return FALSE;
+		return TRUE;
+		*/
+		include_once(RDFAPI_INCLUDE_DIR. "util/ModelComparator.php");
+		return ModelComparator::compare($this,$that);
+	}
+
+	/**
+	* Returns a new MemModel that is the set-union of the MemModel with another model.
+	* Duplicate statements are removed. If you want to allow duplicates, use addModel() which is much faster.
+	*
+	* The result of taking the set-union of two or more RDF graphs (i.e. sets of triples)
+	* is another graph, which we will call the merge of the graphs.
+	* Each of the original graphs is a subgraph of the merged graph. Notice that when forming
+	* a merged graph, two occurrences of a given uriref or literal as nodes in two different
+	* graphs become a single node in the union graph (since by definition they are the same
+	* uriref or literal) but blank nodes are not 'merged' in this way; and arcs are of course
+	* never merged. In particular, this means that every blank node in a merged graph can be
+	* identified as coming from one particular graph in the original set of graphs.
+	*
+	* Notice that one does not, in general, obtain the merge of a set of graphs by concatenating
+	* their corresponding N-triples documents and constructing the graph described by the merged
+	* document, since if some of the documents use the same node identifiers, the merged document
+	* will describe a graph in which some of the blank nodes have been 'accidentally' merged.
+	* To merge Ntriples documents it is necessary to check if the same nodeID is used in two or
+	* more documents, and to replace it with a distinct nodeID in each of them, before merging the
+	* documents. (Not implemented yet !!!!!!!!!!!)
+	*
+	* @param	object Model	$model
+	* @return	object MemModel
+	* @access	public
+	* @throws phpErrpr
+	*
+	*/
+	function & unite(&$model)  {
+
+		if (!is_a($model, 'Model')) {
+			$errmsg = RDFAPI_ERROR . '(class: MemModel; method: unite): Model expected.';
+			trigger_error($errmsg, E_USER_ERROR);
+		}
+
+		$res = $this;
+
+		if (is_a($model, 'MemModel')) {
+            require_once RDFAPI_INCLUDE_DIR . 'util/StatementIterator.php';
+			$stateIt=new StatementIterator($model);
+			while($statement=$stateIt->next())
+			{
+				$res->addWithoutDuplicates($statement);
+			}
+		}
+
+		elseif (is_a($model, 'DbModel')) {
+			$memModel =& $model->getMemModel();
+			foreach($memModel->triples as $value)
+			$res->addWithoutDuplicates($value);
+		}
+
+		return $res;
+	}
+
+	/**
+	* Returns a new MemModel that is the subtraction of another model from this MemModel.
+	*
+	* @param	object Model	$model
+	* @return	object MemModel
+	* @access	public
+	* @throws phpErrpr
+	*/
+
+	function & subtract(&$model)  {
+
+		if (!is_a($model, 'Model')) {
+			$errmsg = RDFAPI_ERROR . '(class: MemModel; method: subtract): Model expected.';
+			trigger_error($errmsg, E_USER_ERROR);
+		}
+
+		$res = $this;
+
+
+		if (is_a($model, 'MemModel'))
+		{
+            require_once RDFAPI_INCLUDE_DIR . 'util/StatementIterator.php';
+			$stateIt=new StatementIterator($model);
+			while($statement=$stateIt->next())
+			{
+				$res->remove($statement);
+			}
+		}
+		elseif (is_a($model, 'DbModel'))
+		{
+			$memModel =& $model->getMemModel();
+			foreach($memModel->triples as $value)
+			$res->remove($value);
+		}
+
+
+		return $res;
+	}
+
+	/**
+	* Returns a new MemModel containing all the statements which are in both this MemModel and another.
+	*
+	* @param	object Model	$model
+	* @return	object MemModel
+	* @access	public
+	* @throws phpErrpr
+	*/
+	function & intersect(&$model)  {
+
+		if (!is_a($model, 'Model')) {
+			$errmsg = RDFAPI_ERROR . '(class: MemModel; method: intersect: Model expected.';
+			trigger_error($errmsg, E_USER_ERROR);
+		}
+
+		$res = new MemModel($this->getBaseURI());
+
+		if (is_a($model, 'DbModel') || is_a($model, 'RDFSBModel'))
+		{
+			$memModel =& $model->getMemModel();
+			foreach($memModel->triples as $value) {
+				if ($this->contains($value))
+				$res->add($value);
+			}
+		}
+
+		elseif (is_a($model, 'MemModel'))
+		{
+			foreach($model->triples as $value) {
+				if ($this->contains($value))
+				$res->add($value);
+			}
+		}
+
+
+
+		return $res;
+	}
+
+
+	/**
+	* 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)  {
+
+		if (!is_a($model, 'Model')) {
+			$errmsg = RDFAPI_ERROR . '(class: MemModel; method: addModel): Model expected.';
+			trigger_error($errmsg, E_USER_ERROR);
+		}
+
+		$blankNodes_tmp = array();
+
+		if (is_a($model, 'MemModel')) {
+            require_once RDFAPI_INCLUDE_DIR . 'util/StatementIterator.php';
+			$stateIt=new StatementIterator($model);
+			while($statement=$stateIt->next())
+			{
+				$this->_addStatementFromAnotherModel($statement, $blankNodes_tmp);
+			};
+			$this->addParsedNamespaces($model->getParsedNamespaces());
+		}
+
+		elseif (is_a($model, 'DbModel')) {
+			$memModel =& $model->getMemModel();
+			foreach($memModel->triples as $value)
+			$this->_addStatementFromAnotherModel($value, $blankNodes_tmp);
+		}
+		$this->index($this->indexed);
+	}
+
+
+	/**
+	* Reifies the MemModel.
+	* Returns a new MemModel that contains the reifications of all statements of this MemModel.
+	*
+	* @access	public
+	* @return	object	MemModel
+	*/
+	function & reify() {
+		$res = new MemModel($this->getBaseURI());
+
+		$stateIt=$this->getStatementIterator();
+		while($statement=$stateIt->next())
+		{
+			$pointer =& $statement->reify($res);
+			$res->addModel($pointer);
+		};
+
+		return $res;
+	}
+
+	/**
+	* Returns a StatementIterator for traversing the MemModel.
+	* @access	public
+	* @return	object	StatementIterator
+	*/
+	function & getStatementIterator() {
+		// Import Package Utility
+        require_once RDFAPI_INCLUDE_DIR . 'util/StatementIterator.php';
+
+		$si = new StatementIterator($this);
+		return $si;
+	}
+
+	/**
+	* Returns a FindIterator for traversing the MemModel.
+	* @access	public
+	* @return	object	FindIterator
+	*/
+	function & findAsIterator($sub=null,$pred=null,$obj=null) {
+		// Import Package Utility
+        require_once RDFAPI_INCLUDE_DIR . 'util/FindIterator.php';
+
+		$if = new FindIterator($this,$sub,$pred,$obj);
+		return $if;
+	}
+
+	/**
+	* Returns a FindIterator for traversing the MemModel.
+	* @access	public
+	* @return	object	FindIterator
+	*/
+	function & iterFind($sub=null,$pred=null,$obj=null) {
+		// Import Package Utility
+        require_once RDFAPI_INCLUDE_DIR . 'util/IterFind.php';
+
+		$if = new IterFind($this,$sub,$pred,$obj);
+		return $if;
+	}
+
+
+	/**
+	* Returns the models namespaces.
+	*
+	* @author   Tobias Gauï¿œ<tobias.gauss@web.de>
+	* @access   public
+	* @return   Array
+	*/
+	function getParsedNamespaces(){
+		if(count($this->parsedNamespaces)!=0){
+			return $this->parsedNamespaces;
+		}else{
+			return false;
+		}
+	}
+
+
+
+	/**
+	* Adds the namespaces to the model. This method is called by
+	* the parser. !!!! addParsedNamespaces() not overwrites manual
+	* added namespaces in the model !!!!
+	*
+	* @author   Tobias Gauï¿œ<tobias.gauss@web.de>
+	* @access   public
+	* @param    Array $newNs
+	*/
+	function addParsedNamespaces($newNs){
+		if($newNs)
+		$this->parsedNamespaces = $this->parsedNamespaces + $newNs;
+	}
+
+
+	/**
+	* Adds a namespace and prefix to the model.
+	*
+	* @author   Tobias Gauï¿œ<tobias.gauss@web.de>
+	* @access   public
+	* @param    String
+	* @param    String
+	*/
+	function addNamespace($prefix, $nmsp){
+		$this->parsedNamespaces[$nmsp]=$prefix;
+	}
+
+	/**
+	* removes a single namespace from the model
+	*
+	* @author   Tobias Gauï¿œ<tobias.gauss@web.de>
+	* @access   public
+	* @param    String $nmsp
+	*/
+	function removeNamespace($nmsp){
+		if(isset($this->parsedNamespaces[$nmsp])){
+			unset($this->parsedNamespaces[$nmsp]);
+			return true;
+		}else{
+			return false;
+		}
+	}
+
+
+
+	/**
+	* Close the MemModel and free up resources held.
+	*
+	* @access	public
+	*/
+	function close() {
+		unset( $this->baseURI );
+		unset( $this->triples );
+	}
+
+	// =============================================================================
+	// *************************** helper functions ********************************
+	// =============================================================================
+	/**
+	* Checks if $statement is in index
+	*
+	* @param  int $ind
+	* @param  Statement &$statement
+	* @return boolean
+	* @access private
+	*/
+	function _containsIndex(&$statement,$ind){
+		switch($ind){
+			case 4:
+			$sub=$statement->getSubject();
+			$pos=$sub->getLabel();
+			break;
+			case 1:
+			$sub=$statement->getSubject();
+			$pred=$statement->getPredicate();
+			$obj=$statement->getObject();
+			$pos=$sub->getLabel().$pred->getLabel().$obj->getLabel();
+			break;
+			case 2:
+			$sub=$statement->getSubject();
+			$pred=$statement->getPredicate();
+			$pos=$sub->getLabel().$pred->getLabel();
+			break;
+			case 3:
+			$sub=$statement->getSubject();
+			$obj=$statement->getObject();
+			$pos=$sub->getLabel().$obj->getLabel();
+			break;
+		}
+
+		if (!isset($this->indexArr[$ind][$pos]))
+		return FALSE;
+		foreach ($this->indexArr[$ind][$pos] as $key => $value) {
+			$t=$this->triples[$value];
+			if ($t->equals($statement))
+			return TRUE;
+		}
+		return FALSE;
+	}
+
+
+
+
+
+	/**
+	* finds a statement in an index. $pos is the Position in the index
+	* and $ind the adequate searchindex
+	*
+	* @param    String            $pos
+	* @param    Object Subject    &$subject
+	* @param    Object Predicate  &$predicate
+	* @param    Object Object	 &$object
+	* @param    int				 &ind
+	* @return   MemModel          $res
+	* @access   private
+	*/
+	function _findInIndex($pos,&$subject,&$predicate,&$object,$ind){
+		$res = new MemModel($this->getBaseURI());
+		$res->indexed=-1;
+		if (!isset($this->indexArr[$ind][$pos]))
+		return $res;
+		foreach($this->indexArr[$ind][$pos] as $key =>$value){
+			$t=$this->triples[$value];
+			if ($this->matchStatement($t,$subject,$predicate,$object))
+			$res->add($t);
+		}
+		return $res;
+	}
+	/**
+	* adds/removes a statement into/from an index.
+	* mode=0 removes the statement from the index;
+	* mode=1 adds the statement into the index.
+	* returns the statements position.
+	*
+	* @param Object Statement &$statement
+	*	@param int              $k
+	*	@param int              $ind
+	* @param int				$mode
+	* @return int             $k
+	* @access private
+	*/
+	function _indexOpr(&$statement,$k,$ind,$mode){
+		// determine position in adequate index
+		switch($ind){
+			case 1:
+			$s=$statement->getSubject();
+			$p=$statement->getPredicate();
+			$o=$statement->getObject();
+			$pos=$s->getLabel().$p->getLabel().$o->getLabel();
+			break;
+			case 2:
+			$s=$statement->getSubject();
+			$p=$statement->getPredicate();
+			$pos=$s->getLabel().$p->getLabel();
+			break;
+			case 3:
+			$s=$statement->getSubject();
+			$o=$statement->getObject();
+			$pos=$s->getLabel().$o->getLabel();
+			break;
+			case 4:
+			$s=$statement->getSubject();
+			$pos=$s->getLabel();
+			break;
+			case 5:
+			$p=$statement->getPredicate();
+			$pos=$p->getLabel();
+			break;
+			case 6:
+			$o=$statement->getObject();
+			$pos=$o->getLabel();
+			break;
+		}
+		switch($mode){
+			// add in Index
+			case 1:
+			if(isset($this->indexArr[$ind][$pos])){
+				$this->indexArr[$ind][$pos][] = $k;
+			}else{
+				$this->indexArr[$ind][$pos][0] = $k;
+			}
+			break;
+			// remove from Index
+			case 0:
+			$subject=$statement->getSubject();
+			$predicate=$statement->getPredicate();
+			$object=$statement->getObject();
+			$k=-1;
+			if(!isset($this->indexArr[$ind][$pos])){
+				return -1;
+			}
+			$num=count($this->indexArr[$ind][$pos]);
+			foreach($this->indexArr[$ind][$pos] as $key => $value){
+				$t=$this->triples[$value];
+				if($this->matchStatement($t,$subject,$predicate,$object)){
+					$k=$value;
+					if($num==1){
+						unset($this->indexArr[$ind][$pos]);
+					}else{
+						unset($this->indexArr[$ind][$pos][$key]);
+					}
+					return $k;
+				}
+			}
+			break;
+		}
+		return $k;
+	}
+
+
+	/**
+	* finds next or previous matching statement.
+	* Returns Position in model or -1 if there is no match.
+	*
+	*
+	* @param	    String
+	* @param     object  Subject
+	* @param	    object	Predicate
+	* @param     object  Object
+	* @param     integer
+	* @param     integer
+	* @return	integer
+	* @access	private
+	*/
+	function _findMatchIndex($pos,&$s,&$p,&$o,$ind,$off){
+		$match=-1;
+		if (!isset($this->indexArr[$ind][$pos])) {
+			return $match;}
+			foreach($this->indexArr[$ind][$pos] as $key =>$value){
+				$t=$this->triples[$value];
+				if ($this->matchStatement($t,$s,$p,$o)){
+					if($off <= $value){
+						$match= $value;
+						return $match;
+					}
+				}
+			}
+
+			return $match;
+
+	}
+
+
+
+
+} // end: MemModel
+
+
+?>
Index: /Dev/trunk/rdfapi/model/Model.php
===================================================================
--- /Dev/trunk/rdfapi/model/Model.php	(revision 12)
+++ /Dev/trunk/rdfapi/model/Model.php	(revision 12)
@@ -0,0 +1,576 @@
+<?php
+require_once RDFAPI_INCLUDE_DIR . 'util/Object.php';
+
+// ----------------------------------------------------------------------------------
+// Class: Model
+// ----------------------------------------------------------------------------------
+
+/**
+ * Abstract superclass of MemModel and DbModel. A model is a programming interface to an RDF graph.
+ * An RDF graph is a directed labeled graph, as described in http://www.w3.org/TR/rdf-mt/.
+ * It can be defined as a set of <S, P, O> triples, where P is a uriref, S is either
+ * a uriref or a blank node, and O is either a uriref, a blank node, or a literal.
+ *
+ *
+ * @version  $Id: Model.php 569 2008-05-19 05:24:39Z p_frischmuth $
+ * @author Radoslaw Oldakowski <radol@gmx.de>
+ * @author Daniel Westphal <mail@d-westphal.de>
+ *
+ * @package model
+ * @access	public
+ */
+class Model extends Object
+{
+    /**
+    * Base URI of the Model.
+    * Affects creating of new resources and serialization syntax.
+    *
+    * @var     string
+    * @access	private
+    */
+    var $baseURI;
+
+    /**
+    * Number of the last assigned bNode.
+    *
+    * @var     integer
+    * @access	private
+    */
+    var $bNodeCount;
+
+    /**
+    *   SparqlParser so we can re-use it
+    *   @var Parser
+    */
+    var $queryParser = null;
+
+
+
+    /**
+    * Notice for people who are used to work with older versions of RAP.
+    *
+    * @throws  PHPError
+    * @access	public
+    */
+    function Model()
+    {
+
+        $errmsg  = 'Since RAP 0.6 the class for manipulating memory models has been renamed to MemModel.';
+        $errmsg .= '<br>Sorry for this inconvenience.<br>';
+
+        trigger_error($errmsg, E_USER_ERROR);
+    }
+
+
+
+    /**
+    * Return current baseURI.
+    *
+    * @return  string
+    * @access	public
+    */
+    function getBaseURI()
+    {
+        return $this->baseURI;
+    }
+
+
+
+    /**
+    * Load a model from a file containing RDF, N3, N-Triples or a xhtml document containing RDF.
+    * 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.
+    *
+    * @param 	string 	$filename
+    * @param 	string 	$type
+    * @param   boolean $stream
+    * @access	public
+    */
+    function load($filename, $type = NULL, $stream=false)
+    {
+        if ((isset($type)) && ($type =='n3') OR ($type =='nt')) {
+            // Import Package Syntax
+            include_once(RDFAPI_INCLUDE_DIR.PACKAGE_SYNTAX_N3);
+            $parser = new N3Parser();
+        }elseif ((isset($type)) && ($type =='rdf')) {
+            // Import Package Syntax
+            include_once(RDFAPI_INCLUDE_DIR.PACKAGE_SYNTAX_RDF);
+            $parser = new RdfParser();
+        }elseif ((isset($type)) && ($type =='grddl')) {
+            // Import Package Syntax
+            include_once(RDFAPI_INCLUDE_DIR.PACKAGE_SYNTAX_GRDDL);
+            $parser = new GRDDLParser();
+        }elseif ((isset($type)) && ($type =='rss')) {
+            // Import Package Syntax
+            include_once(RDFAPI_INCLUDE_DIR.PACKAGE_SYNTAX_RSS);
+            $parser = new RssParser();
+        }else {
+            // create a parser according to the suffix of the filename
+            // if there is no suffix assume the file to be XML/RDF
+            preg_match("/\.([a-zA-Z0-9_]+)$/", $filename, $suffix);
+            if (isset($suffix[1]) && (strtolower($suffix[1]) == 'n3' OR strtolower($suffix[1]) == 'nt')){
+                // Import Package Syntax
+                include_once(RDFAPI_INCLUDE_DIR.PACKAGE_SYNTAX_N3);
+                $parser = new N3Parser();
+            }elseif (isset($suffix[1]) && (strtolower($suffix[1]) == 'htm' OR strtolower($suffix[1]) == 'html' OR strtolower($suffix[1]) == 'xhtml')){
+                    include_once(RDFAPI_INCLUDE_DIR.PACKAGE_SYNTAX_GRDDL);
+                    $parser = new GRDDLParser();
+            }else{
+                // Import Package Syntax
+                include_once(RDFAPI_INCLUDE_DIR.PACKAGE_SYNTAX_RDF);
+                $parser = new RdfParser();
+            }
+        };
+
+        if (($stream && $type=='rdf')||($stream && $type=='n3')) {
+                $temp=&$parser->generateModel($filename,false,$this);
+        } else{
+                $temp=&$parser->generateModel($filename);
+        }
+        $this->addModel($temp);
+        if($this->getBaseURI()== null)
+            $this->setBaseURI($temp->getBaseURI());
+    }
+
+	/**
+	 * This method takes a string conatining data and adds the parsed data to this model.
+	 *
+	 * @param string $str The string containing the data to be parsed and loaded.
+	 * @param type $type The type of the string, currently only 'json' is supported.
+	 */
+	function loadFromString($str, $type) {
+		
+		switch ($type) {
+			case 'json':
+				include_once(RDFAPI_INCLUDE_DIR.PACKAGE_SYNTAX_JSON);
+				$parser = new JsonParser();
+				break;
+			case 'n3':
+			case 'nt':
+				include_once(RDFAPI_INCLUDE_DIR.PACKAGE_SYNTAX_N3);
+				$parser = new N3Parser();
+				break;
+			case 'rdf':
+			case 'rdfxml':
+			case 'xml':
+				include_once(RDFAPI_INCLUDE_DIR.PACKAGE_SYNTAX_RDF);
+				$parser = new RdfParser();
+				break;
+			case 'grddl':
+				include_once(RDFAPI_INCLUDE_DIR.PACKAGE_SYNTAX_GRDDL);
+				$parser = new GRDDLParser();
+				break;
+			case 'rss':
+				include_once(RDFAPI_INCLUDE_DIR.PACKAGE_SYNTAX_RSS);
+				$parser = new RssParser();
+				break;
+			default:
+				trigger_error('(class: Model; method: loadFromString): type ' . $type . 'is currently not supported',
+			 			E_USER_ERROR);
+		}
+		
+		if (($parser instanceof JsonParser) || ($parser instanceof N3Parser)) {
+			$parser->generateModelFromString($str, $this);
+		} else {
+			$temp = $parser->generateModel($str, false, $this);
+			
+			$this->addModel($temp);
+            if($this->getBaseURI() == null) {
+                $this->setBaseURI($temp->getBaseURI());
+            }
+		}
+	} 
+
+    /**
+    * Adds a statement from another model to this model.
+    * If the statement to be added contains a blankNode with an identifier
+    * already existing in this model, a new blankNode is generated.
+    *
+    * @param 	Object Statement   $statement
+    * @access	private
+    */
+    function _addStatementFromAnotherModel($statement, &$blankNodes_tmp)
+    {
+        $subject = $statement->getSubject();
+        $object = $statement->getObject();
+
+        if (is_a($subject, "BlankNode")) {
+            $label = $subject->getLabel();
+            if (!array_key_exists($label, $blankNodes_tmp))
+            {
+                if ($this->findFirstMatchingStatement($subject, NULL, NULL)
+                || $this->findFirstMatchingStatement(NULL, NULL, $subject))
+                {
+                $blankNodes_tmp[$label] = new BlankNode($this);
+                $statement->subj = $blankNodes_tmp[$label];
+                } else {
+                $blankNodes_tmp[$label] = $subject;
+                }
+            } else
+                $statement->subj = $blankNodes_tmp[$label];
+        }
+
+        if (is_a($object, "BlankNode")) {
+            $label = $object->getLabel();
+            if (!array_key_exists($label, $blankNodes_tmp))
+            {
+                if ($this->findFirstMatchingStatement($object, NULL, NULL)
+                || $this->findFirstMatchingStatement(NULL, NULL, $object))
+                {
+                $blankNodes_tmp[$label] = new BlankNode($this);
+                $statement->obj = $blankNodes_tmp[$label];
+                } else {
+                $blankNodes_tmp[$label] = $object;
+                }
+            } else
+                $statement->obj = $blankNodes_tmp[$label];
+        }
+        $this->add($statement);
+    }
+
+
+
+    /**
+    * Internal method, that returns a resource URI that is unique for the Model.
+    * URIs are generated using the base_uri of the DbModel, the prefix and a unique number.
+    * If no prefix is defined, the bNode prefix, defined in constants.php, is used.
+    *
+    * @param	string	$prefix
+    * @return	string
+    * @access	private
+    */
+    function getUniqueResourceURI($prefix = false)
+    {
+        static $bNodeCount;
+        if(!$bNodeCount)
+            $bNodeCount = 0;
+
+        if(!$prefix)
+            $prefix=BNODE_PREFIX;
+
+        return $prefix.++$bNodeCount;
+    }
+
+
+
+    /**
+    * Returns a ResModel with this model as baseModel. This is the same as
+    * ModelFactory::getResModelForBaseModel($this).
+    *
+    * @return	object	ResModel
+    * @access	public
+    */
+    function & getResModel()
+    {
+		$modelFactory = new ModelFactory();
+        return $modelFactory->getResModelForBaseModel($this);
+    }
+
+
+
+    /**
+    * Returns an OntModel with this model as baseModel.
+    * $vocabulary has to be one of the following constants (currently only one is supported):
+    * RDFS_VOCABULARY to select a RDFS Vocabulary.
+    *
+    * This is the same as ModelFactory::getOntModelForBaseModel($this, $vocabulary).
+    *
+    * @param   constant  $vocabulary
+    * @return	object	OntModel
+    * @access	public
+    */
+    function & getOntModel($vocabulary)
+    {
+		$modelFactory = new ModelFactory();
+        return $modelFactory->getOntModelForBaseModel($this, $vocabulary);
+    }
+
+
+
+    /**
+    * Searches for triples using find() and tracks forward blank nodes
+    * until the final objects in the retrieved subgraphs are all named resources.
+    * The method calls itself recursivly until the result is complete.
+    * NULL input for subject, predicate or object will match anything.
+    * Inputparameters are ignored for recursivly found statements.
+    * Returns a new MemModel or adds (without checking for duplicates)
+    * the found statements to a given MemModel.
+    * Returns an empty MemModel, if nothing is found.
+    * !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+    * WARNING: This method can be slow with large models.
+    * NOTE:    Blank nodes are not renamed, they keep the same nodeIDs
+    *          as in the queried model!
+    * !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+    *
+    * @author   Anton Koestlbacher <anton1@koestlbacher.de>
+    * @param    object Node     $subject
+    * @param    object Node     $predicate
+    * @param    object Node     $object
+    * @param    object MemModel $object
+    * @return   object MemModel
+    * @access   public
+    * @throws   PhpError
+    */
+    function findForward($subject, $predicate, $object, &$newModel = NULL)
+    {
+        if (!is_a($newModel, "MemModel"))
+        {
+            $newModel = New MemModel;
+        }
+
+        if (is_a($this, "DbModel"))
+        {
+            $model = $this;
+            $res   = $model->find($subject, $predicate, $object);
+            $it    = $res->getStatementIterator();
+        }
+        elseif (is_a($this, "MemModel")) {
+            $model = $this;
+            $it    = $model->findAsIterator($subject, $predicate, $object);
+        }
+        elseif (is_a($this, "ResModel")) {
+            $model = $this->model;
+            $it    = $model->findAsIterator($subject, $predicate, $object);
+        }
+
+        while ($it->hasNext())
+        {
+            $statement = $it->next();
+            $newModel->add($statement);
+            if (is_a($statement->object(),'BlankNode'))
+            {
+                $model->findForward($statement->object(), NULL, NULL, $newModel);
+            }
+        }
+        return $newModel;
+    }
+
+
+
+    /**
+    * Perform an RDQL query on this Model. Should work with all types of models.
+    * This method returns a MemModel containing the result statements.
+    * If $closure is set to TRUE, the result will additionally contain
+    * statements found by the findForward-method for blank nodes.
+    * !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+    * WARNING: If called with $closure = TRUE this method
+    *          can be slow with large models.
+    * !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+    *
+    * @author   Anton Kï¿œtlbacher <anton1@koestlbacher.de>
+    * @author   code snippets taken from the RAP Netapi by Phil Dawes and Chris Bizer
+    * @access   public
+    * @param    string $queryString
+    * @param    boolean $closure
+    * @return   object MemModel
+    *
+    */
+    function & getMemModelByRDQL($queryString, $closure = FALSE)
+    {
+        require_once(RDFAPI_INCLUDE_DIR.PACKAGE_RDQL);
+        $parser = new RdqlParser();
+        $parsedQuery =& $parser->parseQuery($queryString);
+
+        // If there are variables used in the pattern but not
+        // in the select clause, add them to the select clause
+        foreach ($parsedQuery['patterns'] as $n => $pattern)
+        {
+            foreach ($pattern as $key => $val_1)
+            {
+                if ($val_1['value']{0}=='?')
+                {
+                    if (!in_array($val_1['value'],$parsedQuery['selectVars']))
+                    {
+                    array_push($parsedQuery['selectVars'],$val_1['value']);
+                    }
+                }
+            }
+        }
+
+        if (is_a($this, "DbModel"))
+        {
+            $engine = new RdqlDbEngine();
+            $model  = $this;
+        }
+        elseif (is_a($this, "MemModel"))
+        {
+            $engine = new RdqlMemEngine();
+            $model  = $this;
+        }
+        elseif (is_a($this, "ResModel"))
+        {
+            $engine = new RdqlMemEngine();
+            $model  = $this->model;
+        }
+
+        $res = $engine->queryModel($model,$parsedQuery,TRUE);
+        $rdqlIter = new RdqlResultIterator($res);
+        $newModel = new MemModel();
+
+        // Build statements from RdqlResultIterator
+        while ($rdqlIter->hasNext()) {
+            $result = $rdqlIter->next();
+            foreach ($parsedQuery['patterns'] as $n => $pattern)
+            {
+                if (substr($pattern['subject']['value'], 0, 1) == '?')
+                {
+                    $subj = $result[$pattern['subject']['value']];
+                }
+                else
+                {
+                    $subj = new Resource($pattern['subject']['value']);
+                }
+                if (substr($pattern['predicate']['value'], 0, 1) == '?')
+                {
+                    $pred = $result[$pattern['predicate']['value']];
+                }
+                else
+                {
+                    $pred = new Resource($pattern['predicate']['value']);
+                }
+
+                if (substr($pattern['object']['value'], 0, 1) == '?')
+                {
+                    $obj = $result[$pattern['object']['value']];
+                }
+                else
+                {
+                    if (isset($pattern['object']['is_literal']))
+                    {
+                        $obj = new Literal($pattern['object']['value']);
+                        $obj->setDatatype($pattern['object']['l_dtype']);
+                        $obj->setLanguage($pattern['object']['l_lang']);
+                    }
+                    else
+                    {
+                        $obj = new Resource($pattern['object']['value']);
+                    }
+                }
+
+                $statement = new Statement($subj,$pred,$obj);
+                $newModel->add($statement);
+
+                // findForward() Statements containing an eventually given blank node
+                // and add them to the result, if closure = true
+                if (is_a($statement->object(),'BlankNode') && $closure == True)
+                {
+                    $newModel = $model->findForward($statement->object(),NULL,NULL, $newModel);
+                }
+                if (is_a($statement->subject(),'BlankNode') && $closure == True)
+                {
+                    $newModel = $model->findForward($statement->subject(),NULL,NULL, $newModel);
+                }
+            }
+        }
+        return $newModel;
+    }
+
+
+
+    /**
+    * Alias for RDFUtil::visualiseGraph(&$model, $format, $short_prefix)
+    *
+    * !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+    * Note: See RDFUtil for further Information.
+    * !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+    *
+    * @author   Anton Kï¿œtlbacher <anton1@koestlbacher.de>
+    * @param    string  $format
+    * @param    boolean $short_prefix
+    * @return   string, binary
+    * @access   public
+    * @throws   PhpError
+    */
+    function visualize($format = "dot", $short_prefix = TRUE)
+    {
+		$rdfUtil = new RDFUtil();
+        return $rdfUtil->visualizeGraph($this, $format, $short_prefix);
+    }
+
+
+    /**
+    * Performs a SPARQL query against a model. The model is converted to
+    * 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)
+    {
+        list($engine, $dataset) = $this->_prepareSparql();
+        return $engine->queryModel(
+            $dataset,
+            $this->_parseSparqlQuery($query),
+            $resultform
+        );
+    }//function sparqlQuery($query,$resultform = false)
+
+
+
+    /**
+    *   Prepares a sparql query and returns a prepared statement
+    *   that can be executed with data later on.
+    *
+    *   @param string $query Sparql query to prepare.
+    *   @return SparqlEngine_PreparedStatement  prepared statement object
+    */
+    function sparqlPrepare($query)
+    {
+        list($engine, $dataset) = $this->_prepareSparql();
+        return $engine->prepare(
+            $dataset,
+            $this->_parseSparqlQuery($query)
+         );
+    }//function sparqlPrepare($query)
+
+
+
+    /**
+    *   Prepares everything for SparqlEngine-usage
+    *   Loads the files, creates instances for SparqlEngine and
+    *   Dataset...
+    *
+    *   @return array First value is the sparql engine, second the dataset
+    */
+    function _prepareSparql()
+    {
+        require_once RDFAPI_INCLUDE_DIR . 'sparql/SparqlEngine.php';
+        require_once RDFAPI_INCLUDE_DIR . 'dataset/DatasetMem.php';
+
+        $dataset = new DatasetMem();
+        $dataset->setDefaultGraph($this);
+
+		$sparqlEngine = SparqlEngine::getInstance();
+		
+        return array(
+            $sparqlEngine->factory($this),
+            $dataset
+        );
+    }//function _prepareSparql()
+
+
+
+    /**
+    *   Parses an query and returns the parsed form.
+    *   If the query is not a string but a Query object,
+    *   it will just be returned.
+    *
+    *   @param $query mixed String or Query object
+    *   @return Query query object
+    *   @throws Exception If $query is no string and no Query object
+    */
+    function _parseSparqlQuery($query)
+    {
+        if ($this->queryParser === null) {
+            require_once RDFAPI_INCLUDE_DIR . 'sparql/SparqlParser.php';
+            $this->queryParser = new SparqlParser();
+        }
+        return $this->queryParser->parse($query);
+    }//function _parseSparqlQuery($query)
+
+} // end: Model
+
+?>
Index: /Dev/trunk/rdfapi/model/ModelFactory.php
===================================================================
--- /Dev/trunk/rdfapi/model/ModelFactory.php	(revision 12)
+++ /Dev/trunk/rdfapi/model/ModelFactory.php	(revision 12)
@@ -0,0 +1,288 @@
+<?php
+require_once RDFAPI_INCLUDE_DIR . 'model/DbStore.php';
+
+// ----------------------------------------------------------------------------------
+// Class: ModelFactory
+// ----------------------------------------------------------------------------------
+
+
+/**
+* ModelFactory is a static class which provides methods for creating different
+* types of RAP models. RAP models have to be created trough a ModelFactory
+* instead of creating them directly with the 'new' operator because of RAP's
+* dynamic code inclusion mechanism.
+*
+* @version  $Id: ModelFactory.php 524 2007-08-14 11:12:45Z kobasoft $
+* @author Daniel Westphal <mail at d-westphal.de>
+* @author Richard Cyganiak <richard@cyganiak.de>
+*
+*
+* @package 	model
+* @access	public
+**/
+class ModelFactory
+{
+	/**
+	* Returns a MemModel.
+	* You can supply a base URI
+	*
+	* @param   string  $baseURI
+	* @return	object	MemModel
+	* @access	public
+	*/
+	function & getDefaultModel($baseURI = null)
+	{
+		return ModelFactory::getMemModel($baseURI);
+	}
+
+	/**
+	* Returns a NamedGraphSetMem.
+    * You can supply a GraphSet name.
+    *
+    * @param string $graphSetId
+    * @param string $uri
+	* @access	public
+    */
+	function & getDatasetMem($graphSetId = null)
+	{
+        require_once RDFAPI_INCLUDE_DIR . 'dataset/DatasetMem.php';
+		$m = new DatasetMem($graphSetId);
+		return $m;
+	}
+
+	/**
+	* Returns a MemModel.
+	* You can supply a base URI
+	*
+	* @param   string  $baseURI
+	* @return	object	MemModel
+	* @access	public
+	*/
+	function & getMemModel($baseURI = null)
+	{
+        require_once RDFAPI_INCLUDE_DIR . 'model/MemModel.php';
+		$m = new MemModel($baseURI);
+		return $m;
+	}
+
+	/**
+	* Returns a DbModel with the database connection
+	* defined in constants.php.
+	* You can supply a base URI. If a model with the given base
+	* URI exists in the DbStore, it'll be opened.
+	* If not, a new model will be created.
+	*
+	* @param   string  $baseURI
+	* @return	object	DbModel
+	* @access	public
+	*/
+	function & getDefaultDbModel($baseURI = null)
+	{
+		$dbStore = ModelFactory::getDbStore();
+		$m = ModelFactory::getDbModel($dbStore,$baseURI);
+		return $m;
+	}
+
+	/**
+	* Returns a new DbModel using the database connection
+	* supplied by $dbStore.
+	* You can supply a base URI. If a model with the given base
+	* URI exists in the DbStore, it'll be opened.
+	* If not, a new model will be created.
+	*
+	* @param   object	DbStore  $dbStore
+	* @param   string  $baseURI
+	* @return	object	DbModel
+	* @access	public
+	*/
+	function & getDbModel($dbStore, $baseURI = null)
+	{
+		if ($dbStore->modelExists($baseURI)) {
+			return $dbStore->getModel($baseURI);
+        }
+
+		return $dbStore->getNewModel($baseURI);
+	}
+
+	/**
+	* Returns a database connection with the given parameters.
+	* Paramters, which are not defined are taken from the constants.php
+	*
+	* @param   string   $dbDriver
+	* @param   string   $host
+	* @param   string   $dbName
+	* @param   string   $user
+	* @param   string   $password
+	* @return	object	DbStore
+	* @access	public
+	*/
+	function & getDbStore($dbDriver=ADODB_DB_DRIVER, $host=ADODB_DB_HOST, $dbName=ADODB_DB_NAME,
+                   		$user=ADODB_DB_USER, $password=ADODB_DB_PASSWORD)
+	{
+		$dbs = new DbStore($dbDriver, $host, $dbName,$user, $password);
+		return $dbs;
+	}
+
+	/**
+	* Returns a InfModelF.
+	* (MemModel with forward chaining inference engine)
+	* Configurations can be done in constants.php
+	* You can supply a base URI
+	*
+	* @param   string  $baseURI
+	* @return	object	MemModel
+	* @access	public
+	*/
+	function & getInfModelF($baseURI = null)
+	{
+        require_once RDFAPI_INCLUDE_DIR . 'infModel/InfModelF.php';
+		$mod = new InfModelF($baseURI);
+		return $mod;
+	}
+
+	/**
+	* Returns a InfModelB.
+	* (MemModel with backward chaining inference engine)
+	* Configurations can be done in constants.php
+	* You can supply a base URI
+	*
+	* @param   string  $baseURI
+	* @return	object	MemModel
+	* @access	public
+	*/
+	function & getInfModelB($baseURI = null)
+	{
+        require_once RDFAPI_INCLUDE_DIR . 'infModel/InfModelB.php';
+		$mod = new InfModelB($baseURI);
+		return $mod;
+	}
+
+	/**
+	* Returns a ResModel.
+	* $modelType has to be one of the following constants:
+	* MEMMODEL,DBMODEL,INFMODELF,INFMODELB to create a resmodel with a new
+	* model from defined type.
+	* You can supply a base URI
+	*
+	* @param   constant  $modelType
+	* @param   string  $baseURI
+	* @return	object	ResModel
+	* @access	public
+	*/
+	function & getResModel($modelType, $baseURI = null)
+	{
+		switch ($modelType) {
+			case DBMODEL:
+				$baseModel = ModelFactory::getDefaultDbModel($baseURI);
+				break;
+
+			case INFMODELF:
+				$baseModel = ModelFactory::getInfModelF($baseURI);
+				break;
+
+			case INFMODELB:
+				$baseModel = ModelFactory::getInfModelB($baseURI);
+				break;
+
+			default:
+				$baseModel = ModelFactory::getMemModel($baseURI);
+				break;
+		}
+		return ModelFactory::getResModelForBaseModel($baseModel);
+	}
+
+	/**
+	* Creates a ResModel that wraps an existing base model.
+	*
+	* @param   	object  Model	$baseModel
+	* @return	object	ResModel
+	* @access	public
+	*/
+    function &getResModelForBaseModel(&$baseModel) {
+        require_once RDFAPI_INCLUDE_DIR . 'resModel/ResModel.php';
+        $mod = new ResModel($baseModel);
+        return $mod;
+    }
+
+	/**
+	* Returns an OntModel.
+	* $modelType has to be one of the following constants:
+	* MEMMODEL, DBMODEL, INFMODELF, INFMODELB to create a OntModel
+	* with a new model from defined type.
+	* $vocabulary defines the ontology language. Currently only
+	* RDFS_VOCABULARY is supported. You can supply a model base URI.
+	*
+	* @param   	constant  	$modelType
+	* @param   	constant  	$vocabulary
+	* @param   	string  	$baseURI
+	* @return	object		OntModel
+	* @access	public
+	*/
+	function & getOntModel($modelType,$vocabulary, $baseURI = null)
+	{
+		switch ($modelType)
+		{
+			case DBMODEL:
+				$baseModel = ModelFactory::getDefaultDbModel($baseURI);
+				break;
+
+			case INFMODELF:
+				$baseModel = ModelFactory::getInfModelF($baseURI);
+				break;
+
+			case INFMODELB:
+				$baseModel = ModelFactory::getInfModelB($baseURI);
+				break;
+
+			default:
+				$baseModel = ModelFactory::getMemModel($baseURI);;
+		}
+
+        $mod = ModelFactory::getOntModelForBaseModel($baseModel, $vocabulary);
+        return $mod;
+	}
+
+	/**
+	* Creates an OntModel that wraps an existing base model.
+	* $vocabulary defines the ontology language. Currently only
+	* RDFS_VOCABULARY is supported.
+	*
+	* @param   	object  Model	$baseModel
+	* @param   	constant  	$vocabulary
+	* @return	object		OntModel
+	* @access	public
+	*/
+	function &getOntModelForBaseModel(&$baseModel, $vocabulary)
+	{
+        require_once RDFAPI_INCLUDE_DIR . 'ontModel/OntModel.php';
+
+		switch ($vocabulary)
+		{
+			case RDFS_VOCABULARY:
+				require_once(RDFAPI_INCLUDE_DIR.'ontModel/'.RDFS_VOCABULARY);
+				$vocab_object = new RdfsVocabulary();
+				break;
+			default:
+                trigger_error("Unknown vocabulary constant '$vocabulary'; only RDFS_VOCABULARY is supported", E_USER_WARNING);
+                $vocab_object = null;
+				break;
+		}
+		$mod = new OntModel($baseModel, $vocab_object);
+		return $mod;
+	}
+
+
+
+	/**
+	* Creates a SparqlClient.
+	*
+	* @param   	String  $server	Link to a SPARQL endpoint.
+	* @return	SparqlClient the SparqlClient object.
+	* @access	public
+	*/
+	function & getSparqlClient($server){
+		$cl = new SparqlClient($server);
+		return $cl;
+	}
+}
+?>
Index: /Dev/trunk/rdfapi/model/ModelP.php
===================================================================
--- /Dev/trunk/rdfapi/model/ModelP.php	(revision 12)
+++ /Dev/trunk/rdfapi/model/ModelP.php	(revision 12)
@@ -0,0 +1,27 @@
+<?php
+// ----------------------------------------------------------------------------------
+// Model
+// ----------------------------------------------------------------------------------
+//
+// Description               : Model package
+//
+//
+// Author: Tobias Gauß	<tobias.gauss@web.de>
+//
+// ----------------------------------------------------------------------------------
+
+// Include Model classes
+require_once( RDFAPI_INCLUDE_DIR . 'model/Node.php' );
+require_once( RDFAPI_INCLUDE_DIR . 'model/Literal.php' );
+require_once( RDFAPI_INCLUDE_DIR . 'model/Resource.php' );
+require_once( RDFAPI_INCLUDE_DIR . 'model/Blanknode.php' );
+require_once( RDFAPI_INCLUDE_DIR . 'model/Statement.php' );
+require_once( RDFAPI_INCLUDE_DIR . 'model/Model.php' );
+require_once( RDFAPI_INCLUDE_DIR . 'model/MemModel.php' );
+require_once( RDFAPI_INCLUDE_DIR . 'model/DbStore.php' );
+require_once( RDFAPI_INCLUDE_DIR . 'util/StatementIterator.php' );
+require_once( RDFAPI_INCLUDE_DIR . 'model/ModelFactory.php' );
+require_once( RDFAPI_INCLUDE_DIR . 'sparql/SparqlClient.php' );
+require_once( RDFAPI_INCLUDE_DIR . 'sparql/ClientQuery.php' );
+
+?>
Index: /Dev/trunk/rdfapi/model/Node.php
===================================================================
--- /Dev/trunk/rdfapi/model/Node.php	(revision 12)
+++ /Dev/trunk/rdfapi/model/Node.php	(revision 12)
@@ -0,0 +1,25 @@
+<?php
+require_once RDFAPI_INCLUDE_DIR . '/util/Object.php';
+
+// ----------------------------------------------------------------------------------
+// Class: Node
+// ----------------------------------------------------------------------------------
+
+/**
+ * An abstract RDF node.
+ * Can either be resource, literal or blank node.
+ * Node is used in some comparisons like is_a($obj, "Node"),
+ * meaning is $obj a resource, blank node or literal.
+ *
+ *
+ * @version $Id: Node.php 348 2007-03-12 10:04:10Z cweiske $
+ * @author Chris Bizer <chris@bizer.de>
+ * @package model
+ * @abstract
+ *
+ */
+ class Node extends Object {
+ } // end:RDFNode
+
+
+?>
Index: /Dev/trunk/rdfapi/model/Resource.php
===================================================================
--- /Dev/trunk/rdfapi/model/Resource.php	(revision 12)
+++ /Dev/trunk/rdfapi/model/Resource.php	(revision 12)
@@ -0,0 +1,143 @@
+<?php
+require_once RDFAPI_INCLUDE_DIR . 'model/Node.php';
+
+// ----------------------------------------------------------------------------------
+// Class: Resource
+// ----------------------------------------------------------------------------------
+
+/**
+ * An RDF resource.
+ * Every RDF resource must have a URIref.
+ * URIrefs are treated as logical constants, i.e. as names which denote something
+ * (the things are called 'resources', but no assumptions are made about the nature of resources.)
+ * Many RDF resources are pieces of vocabulary. They typically have a namespace
+ * and a local name. In this case, a URI is composed as a
+ * concatenation of the namespace and the local name.
+ *
+ *
+ * @version  $Id: Resource.php 453 2007-06-20 21:19:09Z cweiske $
+ * @author Chris Bizer <chris@bizer.de>
+ *
+ * @package model
+ * @access	public
+ *
+ */
+ class Resource extends Node {
+
+ 	/**
+	* URIref to the resource
+	* @var		string
+	* @access	private
+	*/
+    var $uri;
+
+
+   /**
+    * Constructor
+	* Takes an URI or a namespace/localname combination
+    *
+    * @param	string	$namespace_or_uri
+ 	* @param string $localName
+	* @access	public
+    */
+    function Resource($namespace_or_uri , $localName = NULL) {
+		if ($localName == NULL) {
+			$this->uri = $namespace_or_uri;
+	  	} else {
+			$this->uri = $namespace_or_uri . $localName;
+  	    }
+	}
+
+
+  /**
+   * Returns the URI of the resource.
+   * @return string
+   * @access	public
+   */
+  function getURI() {
+  			return $this->uri;
+   }
+
+	/**
+	 * Returns the label of the resource, which is the URI of the resource.
+     * @access	public
+	 * @return string
+	 */
+    function getLabel() {
+    	return $this->getURI();
+    }
+
+  /**
+   * Returns the namespace of the resource. May return null.
+   * @access	public
+   * @return string
+   */
+  function getNamespace() {
+  	// Import Package Utility
+   	include_once(RDFAPI_INCLUDE_DIR.PACKAGE_UTILITY);
+	$rdfUtil = new RDFUtil();
+   	return $rdfUtil->guessNamespace($this->uri);
+  }
+
+  /**
+   * Returns the local name of the resource.
+   * @access	public
+   * @return string
+   */
+    function getLocalName() {
+    	// Import Package Utility
+   		include_once(RDFAPI_INCLUDE_DIR.PACKAGE_UTILITY);
+		
+		$rdfUtil = new RDFUtil();		
+	    return $rdfUtil->guessName($this->uri);
+  	}
+
+  /**
+   * Dumps resource.
+   * @access	public
+   * @return string
+   */
+  function toString() {
+	return 'Resource("' . $this->uri .'")';
+  }
+
+  /**
+   * Checks if the resource equals another resource.
+   * Two resources are equal, if they have the same URI
+   *
+   * @access	public
+   * @param		object	resource $that
+   * @return	boolean
+   */
+   function equals ($that) {
+
+	    if ($this == $that) {
+	      return true;
+	    }
+
+	    if (($that == NULL) or !(is_a($that, 'Resource')) or (is_a($that, 'BlankNode'))) {
+	      return false;
+	    }
+
+		if ($this->getURI() == $that->getURI()) {
+	      return true;
+	    }
+
+	    return false;
+	}
+
+
+
+
+    /**
+    *   Doing string magic in PHP5
+    *   @return string String representation of this Resource
+    */
+    function __toString()
+    {
+        return $this->toString();
+    }
+
+}
+
+?>
Index: /Dev/trunk/rdfapi/model/Statement.php
===================================================================
--- /Dev/trunk/rdfapi/model/Statement.php	(revision 12)
+++ /Dev/trunk/rdfapi/model/Statement.php	(revision 12)
@@ -0,0 +1,313 @@
+<?php
+
+// ----------------------------------------------------------------------------------
+// Class: Statement
+// ----------------------------------------------------------------------------------
+
+/**
+ * An RDF statement.
+ * In this implementation, a statement is not itself a resource. 
+ * If you want to use a a statement as subject or object of other statements,
+ * you have to reify it first.
+ *  
+ * @author Chris Bizer <chris@bizer.de>
+ * @version  $Id: Statement.php 268 2006-05-15 05:28:09Z tgauss $
+ * @package model
+ */
+class Statement extends Object {
+	
+	/**
+	* Subject of the statement
+	*
+	* @var		object resource	
+	* @access	private
+	*/	
+	 var $subj;
+
+	/**
+	* Predicate of the statement
+	*
+	* @var		object resource	
+	* @access	private
+	*/		
+    var $pred;
+	
+  	/**
+	* Object of the statement
+	*
+	* @var		object node	
+	* @access	private
+	*/		
+    var $obj;
+
+  /**
+   * The parameters to constructor are instances of classes and not just strings
+   *
+   * @param	object	node $subj
+   * @param	object	node $pred
+   * @param	object	node $obj
+	* @throws	PhpError
+   */
+  function Statement($subj, $pred, $obj) {
+
+    if (!is_a($subj, 'Resource')) {
+		$errmsg = RDFAPI_ERROR . 
+		          '(class: Statement; method: new): Resource expected as subject.';
+		trigger_error($errmsg, E_USER_ERROR); 
+	}
+	if (!is_a($pred, 'Resource') || is_a($pred, 'BlankNode')) {
+		$errmsg = RDFAPI_ERROR . 
+		          '(class: Statement; method: new): Resource expected as predicate, no blank node allowed.';
+		trigger_error($errmsg, E_USER_ERROR); 
+	}
+	if (!(is_a($obj, 'Resource') or is_a($obj, 'Literal'))) {
+		$errmsg = RDFAPI_ERROR . 
+		          '(class: Statement; method: new): Resource or Literal expected as object.';
+		trigger_error($errmsg, E_USER_ERROR); 
+	}
+		
+	$this->pred = $pred;
+    $this->subj = $subj;
+    $this->obj = $obj;
+  }
+
+  /**
+   * Returns the subject of the triple.
+   * @access	public 
+   * @return	object node
+   */
+  function getSubject() {
+    return $this->subj;
+  }
+
+  /**
+   * Returns the predicate of the triple.
+   * @access	public 
+   * @return	object node
+   */
+    function getPredicate() {
+    return $this->pred;
+  }
+
+  /**
+   * Returns the object of the triple.
+   * @access	public 
+   * @return	object node
+   */
+   function getObject() {
+     return $this->obj;
+   }
+  
+  /**
+   * Alias for getSubject()
+   * @access	public 
+   * @return	object node
+   */
+  function subject() {
+    return $this->subj;
+  }
+
+  /**
+   * Alias for getPredicate()
+   * @access	public 
+   * @return	object node
+   */
+    function predicate() {
+    return $this->pred;
+  }
+
+  /**
+   * Alias for getObject()
+   * @access	public 
+   * @return object node
+   */
+   function object() {
+     return $this->obj;
+   }
+    /**
+   * Retruns the hash code of the triple.	
+   * @access	public 
+   * @return string
+   */
+   function hashCode()  {
+      return md5($this->subj->getLabel() . $this->pred->getLabel()  . $this->obj->getLabel());
+   }
+
+  /**
+   * Dumps the triple.	
+   * @access	public 
+   * @return string
+   */  
+
+  function toString() { 
+    return  'Triple(' . $this->subj->toString() . ', ' . $this->pred->toString() . ', ' . $this->obj->toString() . ')';
+	
+  }
+
+  /**
+   * Returns a toString() serialization of the statements's subject.
+   *
+   * @access	public 
+   * @return	string 
+   */  
+   function toStringSubject() {
+       return $this->subj->toString();
+   }
+
+  /**
+   * Returns a toString() serialization of the statements's predicate.
+   *
+   * @access	public 
+   * @return	string 
+   */  
+   function toStringPredicate() {
+       return $this->pred->toString();
+   }
+
+  /**
+   * Reurns a toString() serialization of the statements's object.
+   *
+   * @access	public 
+   * @return	string 
+   */  
+   function toStringObject() {
+       return $this->obj->toString();
+   }
+
+  /**
+   * Returns the URI or bNode identifier of the statements's subject.
+   *
+   * @access	public 
+   * @return	string 
+   */  
+   function getLabelSubject() {
+       return $this->subj->getLabel();
+   }
+
+  /**
+   * Returns the URI of the statements's predicate.
+   *
+   * @access	public 
+   * @return	string 
+   */  
+   function getLabelPredicate() {
+       return $this->pred->getLabel();
+   }
+
+  /**
+   * Reurns the URI, text or bNode identifier of the statements's object.
+   *
+   * @access	public 
+   * @return	string 
+   */  
+   function getLabelObject() {
+       return $this->obj->getLabel();
+   }
+  
+  /**
+   * Checks if two statements are equal.
+   * Two statements are considered to be equal if they have the
+   * same subject, predicate and object. A statement can only be equal 
+   * to another statement object. 
+   * @access	public 
+   * @param		object	statement $that
+   * @return	boolean 
+   */  
+
+  function equals ($that) {
+    
+	    if ($this == $that) {
+	      return true;
+	    }
+	    if ($that == NULL || !(is_a($that, 'Statement'))) {
+	      return false;
+	    }
+  
+	    return
+		$this->subj->equals($that->subject()) &&
+		$this->pred->equals($that->predicate()) &&
+		$this->obj->equals($that->object());
+	  }
+
+  /**
+   * Compares two statements and returns integer less than, equal to, or greater than zero.
+   * Can be used for writing sorting function for models or with the PHP function usort(). 
+   *
+   * @access	public 
+   * @param		object	statement &$that
+   * @return	boolean 
+   */  
+
+  function compare(&$that) {
+	  return statementsorter($this, $that);
+	  // statementsorter function see below
+  } 
+      
+	  
+  /**
+   * Reifies a statement.
+   * Returns a new MemModel that is the reification of the statement.
+   * For naming the statement's bNode a Model or bNodeID must be passed to the method.   
+   *
+   * @access	public 
+   * @param		mixed	&$model_or_bNodeID
+   * @return	object	model
+   */  
+
+  function & reify(&$model_or_bNodeID) {
+		
+		if (is_a($model_or_bNodeID, 'MemModel')) {
+			// parameter is model
+			$statementModel = new MemModel($model_or_bNodeID->getBaseURI());
+			$thisStatement = new BlankNode($model_or_bNodeID);
+		} else {
+			// parameter is bNodeID
+			$statementModel = new MemModel();
+			$thisStatement = &$model_or_bNodeID;
+		} 
+		
+		$RDFstatement = new Resource(RDF_NAMESPACE_URI . RDF_STATEMENT);
+		$RDFtype = new Resource(RDF_NAMESPACE_URI . RDF_TYPE);
+		$RDFsubject = new Resource(RDF_NAMESPACE_URI . RDF_SUBJECT);
+		$RDFpredicate = new Resource(RDF_NAMESPACE_URI . RDF_PREDICATE);
+		$RDFobject = new Resource(RDF_NAMESPACE_URI . RDF_OBJECT);
+		
+		$statementModel->add(new Statement($thisStatement, $RDFtype, $RDFstatement));
+		$statementModel->add(new Statement($thisStatement, $RDFsubject, $this->getSubject()));
+		$statementModel->add(new Statement($thisStatement, $RDFpredicate, $this->getPredicate()));
+		$statementModel->add(new Statement($thisStatement, $RDFobject, $this->Object()));
+		
+		return $statementModel;
+  }
+  
+} // end: Statement
+
+
+/**
+* Comparison function for comparing two statements.
+* statementsorter() is used by the PHP function usort ( array array, callback cmp_function)
+*
+* @access	private 
+* @param		object Statement	$a
+* @param		object Statement	$b
+* @return	integer less than, equal to, or greater than zero  
+* @throws phpErrpr
+*/  
+function statementsorter($a,$b) {
+	  //Compare subjects
+	  $x=$a->getSubject();
+	  $y=$b->getSubject();
+	  $r=strcmp($x->getLabel(),$y->getLabel());
+	  if ($r!=0) return $r;
+	  //Compare predicates
+	  $x=$a->getPredicate();
+	  $y=$b->getPredicate();
+	  $r=strcmp($x->getURI(),$y->getURI());
+	  if ($r!=0) return $r;
+	  //Final resort, compare objects
+	  $x=$a->getObject();
+	  $y=$b->getObject();
+	  return strcmp($x->toString(),$y->toString());
+}
+	
+?>
Index: /Dev/trunk/rdfapi/ontModel/Individual.php
===================================================================
--- /Dev/trunk/rdfapi/ontModel/Individual.php	(revision 12)
+++ /Dev/trunk/rdfapi/ontModel/Individual.php	(revision 12)
@@ -0,0 +1,39 @@
+<?php
+// ----------------------------------------------------------------------------------
+// Class: Individual
+// ----------------------------------------------------------------------------------
+
+
+
+/**
+* Interface that encapsulates an individual in an ontology, sometimes referred
+* to as a fact or assertion.
+* In order to be recognised as an individual, rather than a generic resource, 
+* at least one rdf:type statement, referring to a known class, must be present 
+* in the model.
+*
+
+* @version  $Id: Individual.php 320 2006-11-21 09:38:51Z tgauss $
+* @author Daniel Westphal <mail at d-westphal dot de>
+*
+*
+* @package 	ontModel
+* @access	public
+**/	
+
+class Individual extends OntResource   
+{
+	
+	/**
+    * Constructor
+	* You can supply a uri
+    *
+    * @param string $uri 
+	* @access	public
+    */		
+	function Individual($uri = null)
+	{
+		parent::OntResource($uri);
+	}
+} 
+?>
Index: /Dev/trunk/rdfapi/ontModel/OWLVocabulary.php
===================================================================
--- /Dev/trunk/rdfapi/ontModel/OWLVocabulary.php	(revision 12)
+++ /Dev/trunk/rdfapi/ontModel/OWLVocabulary.php	(revision 12)
@@ -0,0 +1,369 @@
+<?php
+
+// ----------------------------------------------------------------------------------
+// Class: OWLVocabulary
+// ----------------------------------------------------------------------------------
+
+/**
+* OWL vocabulary items
+*
+* @version  $Id: OWLVocabulary.php 320 2006-11-21 09:38:51Z tgauss $
+* @author Daniel Westphal <mail at d-westphal dot de>
+*
+*
+* @package 	ontModel
+* @access	public
+**/
+class OWLVocabulary extends OntVocabulary 
+{
+
+	/**
+	* Answer the resource that represents the class 'class' in this vocabulary.
+	*
+   	* @return	object ResResource 
+   	* @access	public
+   	*/
+	function ONTCLASS()
+	{
+		return new ResResource(OWL_NS.'Class');	
+	}
+
+	/**
+	* Answer the predicate that denotes the domain of a property.
+	*
+   	* @return	object ResProperty 
+   	* @access	public
+   	*/
+	function DOMAIN()
+	{
+		return new ResProperty(RDF_SCHEMA_URI.RDFS_DOMAIN);	
+	}
+	
+	 
+ 	/**
+	* Answer the predicate that denotes comment annotation on an ontology element.
+	*
+   	* @return	object ResProperty 
+   	* @access	public
+   	*/
+	function COMMENT()
+	{
+		return new ResProperty(RDF_SCHEMA_URI.RDFS_COMMENT);	
+	}
+	
+ 	/**
+	* Answer the predicate that denotes isDefinedBy annotation on an ontology element
+	*
+   	* @return	object ResProperty 
+   	* @access	public
+   	*/
+	function IS_DEFINED_BY()
+	{
+		return new ResProperty(RDF_SCHEMA_URI.RDFS_IS_DEFINED_BY);
+	}
+	
+	/**
+	* Answer the predicate that denotes label annotation on an ontology element
+	*
+   	* @return	object ResProperty 
+   	* @access	public
+   	*/
+	function LABEL()
+	{
+		return new ResProperty(RDF_SCHEMA_URI.RDFS_LABEL);
+	}
+	
+	/**
+	* Answer the predicate that denotes the domain of a property.
+	*
+   	* @return	object ResProperty 
+   	* @access	public
+   	*/
+	function RANGE()
+	{
+		return new ResProperty(RDF_SCHEMA_URI.RDFS_RANGE);
+	}
+	
+	/**
+	* Answer the predicate that denotes seeAlso annotation on an ontology element
+	*
+   	* @return	object ResProperty 
+   	* @access	public
+   	*/
+	function SEE_ALSO()
+	{
+		return new ResProperty(RDF_SCHEMA_URI.RDFS_SEE_ALSO);
+	}
+	
+	/**
+	* Answer the predicate that denotes that one class is a sub-class of another.
+	*
+   	* @return	object ResProperty 
+   	* @access	public
+   	*/
+	function SUB_CLASS_OF()
+	{
+		return new ResProperty(RDF_SCHEMA_URI.RDFS_SUBCLASSOF);
+	}
+	
+	/**
+	* Answer the predicate that denotes that one property is a sub-property of another.
+	*
+   	* @return	object ResProperty 
+   	* @access	public
+   	*/
+	function SUB_PROPERTY_OF()
+	{
+		return new ResProperty(RDF_SCHEMA_URI.RDFS_SUBPROPERTYOF);
+	}
+	
+	
+	
+	function ANNOTATION_PROPERTY()
+	{
+		return new ResProperty(OWL_NS . 'AnnotationProperty');	
+	}
+
+	function ALL_DIFFERENT()
+	{
+		return new ResProperty(OWL_NS . 'AllDifferent');	
+	}
+	
+	function ALL_VALUES_FROM()
+	{
+		return new ResProperty(OWL_NS . 'allValuesFrom');
+	}
+
+	function BACKWARD_COMPATIBLE_WITH()
+	{
+		return new ResProperty(OWL_NS . 'backwardCompatibleWith');
+	}
+	
+	function CARDINALITY()
+	{
+		return new ResProperty(OWL_NS . 'cardinality');
+	}
+
+	function COMPLEMENT_OF()
+	{
+		return new ResProperty(OWL_NS . 'complementOf');
+	}
+	
+	function DATATYPE()
+	{
+		return new ResProperty(OWL_NS . 'Datatype');
+	}
+	
+	function DATATYPE_PROPERTY()
+	{
+		return new ResProperty(OWL_NS . 'DatatypeProperty');
+	}
+
+	function DATA_RANGE()
+	{
+		return new ResProperty(OWL_NS . 'DataRange');
+	}
+
+	function DATATYPE_RESTRICTION()
+	{
+		return new ResProperty(OWL_NS . 'DatatypeRestriction');
+	}
+
+	function DEPRECATED_CLASS()
+	{
+		return new ResProperty(OWL_NS . 'DeprecatedClass');
+	}
+
+	function DEPRECATED_PROPERTY()
+	{
+		return new ResProperty(OWL_NS . 'DeprecatedProperty');
+	}
+
+	function DISTINCT_MEMBERS()
+	{
+		return new ResProperty(OWL_NS . 'distinctMembers');
+	}
+
+	function DIFFERENT_FROM()
+	{
+		return new ResProperty(OWL_NS . 'differentFrom');
+	}
+
+	function DISJOINT_WITH()
+	{
+		return new ResProperty(OWL_NS . 'disjointWith');
+	}
+
+	function EQUIVALENT_CLASS()
+	{
+		return new ResProperty(OWL_NS . 'equivalentClass');
+	}
+
+	function EQUIVALENT_PROPERTY()
+	{
+		return new ResProperty(OWL_NS . 'equivalentProperty');
+	}
+
+	function FUNCTIONAL_PROPERTY()
+	{
+		return new ResProperty(OWL_NS . 'FunctionalProperty');
+	}
+
+	function HAS_VALUE()
+	{
+		return new ResProperty(OWL_NS . 'hasValue');
+	}
+
+	function INCOMPATIBLE_WITH()
+	{
+		return new ResProperty(OWL_NS . 'incompatibleWith');
+	}
+
+	function IMPORTS()
+	{
+		return new ResProperty(OWL_NS . 'imports');
+	}
+
+	function INTERSECTION_OF()
+	{
+		return new ResProperty(OWL_NS . 'intersectionOf');
+	}
+
+	function INVERSE_FUNCTIONAL_PROPERTY()
+	{
+		return new ResProperty(OWL_NS . 'InverseFunctionalProperty');
+	}
+
+	function INVERSE_OF()
+	{
+		return new ResProperty(OWL_NS . 'inverseOf');
+	}
+
+	function MAX_CARDINALITY()
+	{
+		return new ResProperty(OWL_NS . 'maxCardinality');
+	}
+
+	function MIN_CARDINALITY()
+	{
+		return new ResProperty(OWL_NS . 'minCardinality');
+	}
+
+	function NOTHING()
+	{
+		return new ResProperty(OWL_NS . 'Nothing');
+	}
+
+	function OBJECT_CLASS()
+	{
+		return new ResProperty(OWL_NS . 'ObjectClass');
+	}
+
+	function OBJECT_PROPERTY()
+	{
+		return new ResProperty(OWL_NS . 'ObjectProperty');
+	}
+
+	function OBJECT_RESTRICTION()
+	{
+		return new ResProperty(OWL_NS . 'ObjectRestriction');
+	}
+
+	function ONE_OF()
+	{
+		return new ResProperty(OWL_NS . 'oneOf');
+	}
+
+	function ON_PROPERTY()
+	{
+		return new ResProperty(OWL_NS . 'onProperty');
+	}
+
+	function ONTOLOGY()
+	{
+		return new ResProperty(OWL_NS . 'Ontology');
+		
+	}
+
+	function PRIOR_VERSION()
+	{
+		return new ResProperty(OWL_NS . 'priorVersion');
+	}
+
+	function PROPERTY()
+	{
+		return new ResProperty(OWL_NS . 'Property');
+	}
+
+	function RESTRICTION()
+	{
+		return new ResProperty(OWL_NS . 'Restriction');
+	}
+
+	function SAME_AS()
+	{
+		return new ResProperty(OWL_NS . 'sameAs');
+	}
+
+	function SAME_CLASS_AS()
+	{
+		return new ResProperty(OWL_NS . 'sameClassAs');
+	}
+
+	function SAME_INDIVIDUAL_AS()
+	{
+		return new ResProperty(OWL_NS . 'sameIndividualAs');
+	}
+
+	function SAME_PROPERTY_AS()
+	{
+		return new ResProperty(OWL_NS . 'samePropertyAs');
+	}
+
+	function SOME_VALUES_FROM()
+	{
+		return new ResProperty(OWL_NS . 'someValuesFrom');
+	}
+
+	function SYMMETRIC_PROPERTY()
+	{
+		return new ResProperty(OWL_NS . 'SymmetricProperty');
+	}
+
+	function THING()
+	{
+		return new ResProperty(OWL_NS . 'Thing');
+	}
+
+	function TRANSITIVE_PROPERTY()
+	{
+		return new ResProperty(OWL_NS . 'TransitiveProperty');
+	}
+
+	function UNION_OF()
+	{
+		return new ResProperty(OWL_NS . 'unionOf');
+	}
+
+	function VERSION_INFO()
+	{
+		return new ResProperty(OWL_NS . 'versionInfo');
+	}
+
+	function NAMESPACE()
+	{
+		return OWL_NS;
+	}
+
+	/**
+	* Answer the predicate that denotes the rdf:type property.
+	*
+   	* @return	object ResProperty 
+   	* @access	public
+   	*/
+	function TYPE()
+	{
+		return new ResProperty(RDF_NAMESPACE_URI.RDF_TYPE);
+	}
+} 
+?>
Index: /Dev/trunk/rdfapi/ontModel/OntClass.php
===================================================================
--- /Dev/trunk/rdfapi/ontModel/OntClass.php	(revision 12)
+++ /Dev/trunk/rdfapi/ontModel/OntClass.php	(revision 12)
@@ -0,0 +1,285 @@
+<?php
+// ----------------------------------------------------------------------------------
+// Class: OntClass
+// ----------------------------------------------------------------------------------
+
+
+
+/**
+* Class that represents an ontology node characterising a class description.
+*
+* @version  $Id: OntClass.php 320 2006-11-21 09:38:51Z tgauss $
+* @author Daniel Westphal <mail at d-westphal dot de>
+*
+*
+* @package 	ontModel
+* @access	public
+**/
+class OntClass extends OntResource 
+{
+	/**
+    * Constructor
+	* You can supply a uri
+    *
+    * @param string $uri 
+	* @access	public
+    */		
+	function OntClass($uri = null)
+	{
+		parent::OntResource($uri);
+	}
+
+	/**
+	* Add a sub-class of this class.
+	*
+   	* @param	object ResResource		$resResource
+   	* @return	boolean 
+   	* @access	public
+   	*/
+	function addSubClass($resResource)
+	{
+		return $resResource->addProperty($this->vocabulary->SUB_CLASS_OF(),$this);
+	}
+	
+	/**
+	* Add a super-class of this class.
+	*
+   	* @param	object ResResource		$resResource
+   	* @return	boolean 
+   	* @access	public
+   	*/
+	function addSuperClass($resResource)
+	{
+		return $this->addProperty($this->vocabulary->SUB_CLASS_OF(),$resResource);
+	}
+	
+	/**
+	* Answer a class that is the sub-class of this class. 
+	* If there is more than one such class, an arbitrary selection is made.
+	*
+   	* @return	object OntClass or NULL
+   	* @access	public
+   	*/
+	function getSubClass()
+	{
+		$statement = $this->model->findFirstMatchingStatement(null,$this->vocabulary->SUB_CLASS_OF(),$this);
+		if ($statement !== null)
+			return $this->model->createOntClass($statement->getLabelSubject());
+		
+		return null;
+	}
+	
+	/**
+	* Answer a class that is the super-class of this class. 
+	* If there is more than one such class, an arbitrary selection is made.
+	*
+   	* @return	object OntClass or NULL
+   	* @access	public
+   	*/
+	function getSuperClass()
+	{
+		return $this->getPropertyValue($this->vocabulary->SUB_CLASS_OF(),'OntClass');
+	}
+	
+	/**
+	* Answer true if the given class is a sub-class of this class.
+	* $direct - If true, only search the classes that are directly 
+	* adjacent to this class in the class hierarchy. 
+	*
+   	* @param	object ResResource		$resResource
+  	* @param	boolean			$direct
+   	* @return	boolean 
+   	* @access	public
+   	*/
+	function hasSubclass($resResource, $direct = true)
+	{
+		if ($direct)
+			return $resResource->hasProperty($this->vocabulary->SUB_CLASS_OF(),$this);
+		
+		$index=array();
+		return ($this->_getSubAttributeStatementsRec($this,$this->vocabulary->SUB_CLASS_OF(),$index,$resResource) === true);
+	}
+	
+	/**
+	* Answer true if the given class is a super-class of this class.
+	* $direct - If true, only search the classes that are directly 
+	* adjacent to this class in the class hierarchy. 
+	*
+   	* @param	object ResResource		$resResource
+  	* @param	boolean			$direct
+   	* @return	boolean 
+   	* @access	public
+   	*/
+	function hasSuperClass($resResource, $direct = true)
+	{
+		if ($direct)
+			return $this->hasProperty($this->vocabulary->SUB_CLASS_OF(),$resResource);
+		
+		$index=array();
+		return ($this->_getSuperAttributeStatementsRec($this,$this->vocabulary->SUB_CLASS_OF(),$index,$resResource) === true);
+	}
+	
+	/**
+	* Answer an ResIterator over the individuals in the model that have this class 
+	* among their types.
+	*
+   	* @return	object ResIterator 
+   	* @access	public
+   	*/
+	function listInstances()
+	{
+		/*
+		$statements= $this->model->find(null,$this->vocabulary->TYPE(),$this);
+		$return = array();
+		$returnIndex=array();
+		foreach ($statements as $statement) 
+		{
+			$subjectLabel=$statement->getLabelSubject();
+			if (!in_array($subjectLabel,$returnIndex))
+			{
+				$returnIndex[]=$subjectLabel;
+				$return[]=$statement->getSubject();
+			}	
+		}	
+		return $return;	
+		*/
+		return new ResIterator(null,$this->vocabulary->TYPE(),$this,'s',$this->model,'Individual');
+	
+	}
+	
+	/**
+	* Answer an array over the classes that are declared to be sub-classes of this class. 
+	* Each element of the array will be an OntClass.
+	* $direct - If true, only search the classes that are directly 
+	* adjacent to this class in the class hierarchy. 
+	*
+   	* @param	boolean		$direct
+   	* @return	array 
+   	* @access	public
+   	*/
+	function listSubClasses($direct = true)
+	{
+		$return = array();
+		if ($direct)
+		{
+			$statements = $this->model->find(null,$this->vocabulary->SUB_CLASS_OF(),$this);
+		} else 
+		{
+			$index = array();
+			$statements = $this->_getSubAttributeStatementsRec($this,$this->vocabulary->SUB_CLASS_OF(),$index);
+		}
+		
+		$returnIndex=array();
+		foreach ($statements as $statement) 
+		{
+			$subjectLabel=$statement->getLabelSubject();
+			if (!in_array($subjectLabel,$returnIndex))
+			{
+				$returnIndex[]=$subjectLabel;
+				$return[]=$this->model->createOntClass($subjectLabel);
+			}	
+		}	
+		return $return;	
+	}
+	
+	/**
+	* Answer an array over the classes that are declared to be super-classes of this class. 
+	* Each element of the array will be an OntClass.
+	* $direct - If true, only search the classes that are directly 
+	* adjacent to this class in the class hierarchy. 
+	*
+   	* @param	boolean		$direct
+   	* @return	array 
+   	* @access	public
+   	*/
+	function listSuperClasses($direct = true)
+	{
+		$return = array();
+		if ($direct)
+			return $this->listProperty($this->vocabulary->SUB_CLASS_OF(),'OntClass');
+			
+		$index=array();	
+		$statements = $this->_getSuperAttributeStatementsRec($this,$this->vocabulary->SUB_CLASS_OF(),$index);
+		$returnIndex=array();
+		foreach ($statements as $statement) 
+		{
+			$objectLabel=$statement->getLabelObject();
+			if (!in_array($objectLabel,$returnIndex))
+			{
+				$returnIndex[]=$objectLabel;
+				$return[]=$this->model->createOntClass($objectLabel);
+			}	
+		}	
+		return $return;	
+	}
+	
+	/**
+	* Remove the given class from the sub-classes of this class.
+	*
+   	* @param	object ResResource	$resResource
+   	* @return	boolean 
+   	* @access	public
+   	*/
+	function removeSubClass($resResource)
+	{
+		return	$this->model->remove(new Statement($resResource,$this->vocabulary->SUB_CLASS_OF(),$this));
+	}
+	
+	/**
+	* Remove the given class from the super-classes of this class.
+	*
+   	* @param	object ResResource		$resResource
+   	* @return	boolean 
+   	* @access	public
+   	*/
+	function removeSuperClass($resResource)
+	{
+		return $this->removeProperty($this->vocabulary->SUB_CLASS_OF(),$resResource);
+	}
+	
+	/**
+	* Assert that this class is super-class of the given class. 
+	* Any existing statements for subClassOf on prop will be removed.
+	*
+   	* @param	object ResResource		$resResource
+   	* @access	public
+   	*/
+	function setSubClass($resResource)
+	{
+		foreach ($this->listSubClasses() as $oldRes) 
+		{
+			$this->removeSubClass($oldRes);
+		}
+		$this->addSubClass($resResource);
+	}
+	
+	/**
+	* Assert that this class is sub-class of the given class. 
+	* Any existing statements for subClassOf on prop will be removed.
+	*
+   	* @param	object ResResource		$resResource
+   	* @access	public
+   	*/
+	function setSuperClass($resResource)
+	{
+		$this->setPropertyValue($this->vocabulary->SUB_CLASS_OF(),$resResource);
+	}
+	
+	/**
+	* Answer a resource that represents an instance of this OntClass and Individual
+	* node in this model.
+	* If a resource with the given uri exists in the model, it will be re-used. 
+	* If not, a new one is created in the updateable sub-model of the ontology model.
+	*
+   	* @param	string	$uri
+   	* @return	object Individual 
+   	* @access	public
+   	*/	
+	function createInstance($uri = null)
+	{
+		$instance = $this->model->createIndividual($uri);
+		$instance->setInstanceRdfType($this);
+		return $instance;
+	}
+} 
+?>
Index: /Dev/trunk/rdfapi/ontModel/OntModel.php
===================================================================
--- /Dev/trunk/rdfapi/ontModel/OntModel.php	(revision 12)
+++ /Dev/trunk/rdfapi/ontModel/OntModel.php	(revision 12)
@@ -0,0 +1,169 @@
+<?php
+
+// ----------------------------------------------------------------------------------
+// Class: OntModel
+// ----------------------------------------------------------------------------------
+
+
+/**
+* Enhanced view of the model that is known to contain ontology data, under a
+* given ontology vocabulary (such as RDFS). OntModel together with OntClass
+* and OntResource provide ontology specific methods like addSubClass(),
+* listSubClasses(), hasSuperProperty(), addDomain() and  listInstances(). This class does not by 
+* itself compute the deductive extension of the graph under the semantic 
+* rules of the language. Instead, we wrap an underlying model with this 
+* ontology interface, that presents a convenience syntax for accessing the 
+* language elements. Depending on the inference capability of the underlying 
+* model, the OntModel will appear to contain more or less triples. 
+* For example, if this class is used to wrap a MemModel or DBModel, only the 
+* relationships asserted by the document will be reported through this 
+* convenience API. 
+* Alternatively, if the OntModel wraps an InfModel (InfModelF / InfModelB), 
+* the inferred triples from the extension will be reported as well. 
+*
+*
+* @version  $Id: OntModel.php 320 2006-11-21 09:38:51Z tgauss $
+* @author Daniel Westphal <mail at d-westphal dot de>
+*
+*
+* @package 	ontModel
+* @access	public
+**/
+class OntModel extends ResModel 
+{
+	/**
+	* Holds a reference to the assoiated vocabulary.
+	* @var		object
+	* @access	private
+	*/
+	var $vocabulary;
+	
+	
+	/**
+    * Constructor.
+	* You have to supply a memmodel/dbmodel/infmodel to save the statements and a vocabulary
+    *
+    * @param object Model $model 
+	* @access	public
+    */	
+	function OntModel(& $model,& $vocabulary)
+	{
+		parent::ResModel($model);
+		$this->vocabulary = & $vocabulary;
+	}
+	
+	/**
+	* Answer a resource that represents a class description node in this model. 
+	* If a resource with the given uri exists in the model, it will be re-used. 
+	* If not, a new one is created in the updateable sub-model of the ontology model.
+	*
+   	* @param	string	$uri
+   	* @return	object OntClass 
+   	* @access	public
+   	*/
+	function createOntClass($uri = null)
+	{
+		$class = new OntClass($uri);
+		$class->setAssociatedModel($this);
+		$class->setVocabulary($this->vocabulary);
+		$class->setInstanceRdfType($this->vocabulary->ONTCLASS());
+		return $class;
+	}
+	
+	/**
+	* Answer a resource that represents an Individual node in this model.
+	* If a resource with the given uri exists in the model, it will be re-used. 
+	* If not, a new one is created in the updateable sub-model of the ontology model.
+	*
+   	* @param	string	$uri
+   	* @return	object Individual 
+   	* @access	public
+   	*/
+	function createIndividual($uri = null)
+	{
+		$individual = new Individual($uri);
+		$individual->setAssociatedModel($this);
+		$individual->setVocabulary($this->vocabulary);
+		return $individual;
+	}
+	
+	/**
+	* Answer a resource that represents an OntProperty node in this model.
+	* If a resource with the given uri exists in the model, it will be re-used. 
+	* If not, a new one is created in the updateable sub-model of the ontology model.
+	*
+   	* @param	string	$uri
+   	* @return	object OntProperty 
+   	* @access	public
+   	*/
+	function createOntProperty($uri = null)
+	{
+		$ontProperty = new OntProperty($uri);
+		$ontProperty->setAssociatedModel($this);
+		$ontProperty->setVocabulary($this->vocabulary);
+		$ontProperty->setInstanceRdfType($this->createResource(RDF_NAMESPACE_URI.RDF_PROPERTY));
+		return $ontProperty;	
+	}
+	
+	/**
+	* Answer an array that ranges over all of the various forms of class 
+	* description resource in this model. 
+	* Class descriptions include  domain/range definitions, named  classes and subClass constructs.
+	*
+   	* @return	array of object ResResource 
+   	* @access	public
+   	*/
+	function listClasses()
+	{
+		//get all statements, with an rdf:type as property
+		$statements= $this->find(null,$this->vocabulary->TYPE(),null);
+		$return = array();
+		$returnIndex=array();
+		foreach ($statements as $statement) 
+		{
+			$objectLabel=$statement->getLabelObject();
+			//if it's about a typed Individual	
+			if ($objectLabel!=RDF_SCHEMA_URI.RDFS_CLASS)
+			{
+				if (!in_array($objectLabel,$returnIndex))
+				{
+					$returnIndex[]=$objectLabel;
+					$return[]=$statement->getObject();
+				}
+			} else 
+			//if it's a "class1 rdf:type rdf:class" construct
+			{
+				$subjectLabel=$statement->getLabelSubject();
+				if (!in_array($subjectLabel,$returnIndex))
+				{
+					$returnIndex[]=$subjectLabel;
+					$return[]=$statement->getSubject();
+				}
+			}	
+		}
+		//find all statements about SubClassConstructs
+		$statements= $this->find(null,$this->vocabulary->SUB_CLASS_OF(),null);
+		foreach ($statements as $statement) 
+		{
+			//add the statements object to the result
+			$objectLabel=$statement->getLabelObject();
+			if (!in_array($objectLabel,$returnIndex))
+			{
+				$returnIndex[]=$objectLabel;
+				$return[]=$statement->getObject();
+			}	
+		}	
+		foreach ($statements as $statement) 
+		{
+			//add the statements subject to the result
+			$objectLabel=$statement->getLabelSubject();
+			if (!in_array($objectLabel,$returnIndex))
+			{
+				$returnIndex[]=$objectLabel;
+				$return[]=$statement->getSubject();
+			}	
+		}
+		return $return;	
+	}
+} 
+?>
Index: /Dev/trunk/rdfapi/ontModel/OntModelP.php
===================================================================
--- /Dev/trunk/rdfapi/ontModel/OntModelP.php	(revision 12)
+++ /Dev/trunk/rdfapi/ontModel/OntModelP.php	(revision 12)
@@ -0,0 +1,24 @@
+<?php
+/**
+* ----------------------------------------------------------------------------------
+* OntModel Package
+* ----------------------------------------------------------------------------------
+*
+* Description               : OntModel package
+*
+* Author: Daniel Westphal	<mail at d-westphal dot de>
+* @package ontModel
+*
+* ----------------------------------------------------------------------------------
+*/
+// Include OntModel classes
+include_once( RDFAPI_INCLUDE_DIR . PACKAGE_RESMODEL);
+require_once( RDFAPI_INCLUDE_DIR . 'ontModel/OntVocabulary.php');
+require_once( RDFAPI_INCLUDE_DIR . 'ontModel/RdfsVocabulary.php');
+require_once( RDFAPI_INCLUDE_DIR . 'ontModel/OntModel.php');
+require_once( RDFAPI_INCLUDE_DIR . 'ontModel/OntResource.php');
+require_once( RDFAPI_INCLUDE_DIR . 'ontModel/OntProperty.php');
+require_once( RDFAPI_INCLUDE_DIR . 'ontModel/OntClass.php');
+require_once( RDFAPI_INCLUDE_DIR . 'ontModel/Individual.php');
+
+?>
Index: /Dev/trunk/rdfapi/ontModel/OntProperty.php
===================================================================
--- /Dev/trunk/rdfapi/ontModel/OntProperty.php	(revision 12)
+++ /Dev/trunk/rdfapi/ontModel/OntProperty.php	(revision 12)
@@ -0,0 +1,390 @@
+<?php
+
+// ----------------------------------------------------------------------------------
+// Class: OntProperty
+// ----------------------------------------------------------------------------------
+
+
+/**
+* Class encapsulating a property in an ontology.
+*
+* @version  $Id: OntProperty.php 320 2006-11-21 09:38:51Z tgauss $
+* @author Daniel Westphal <mail at d-westphal dot de>
+*
+*
+* @package 	ontModel
+* @access	public
+**/
+
+class OntProperty extends OntResource    
+{
+	/**
+    * Constructor.
+	* You can supply a URI.
+    *
+    * @param string $uri 
+	* @access	public
+    */
+	function OntProperty($uri = null)
+	{
+		parent::OntResource($uri);
+	}
+	
+	/**
+	* Add a resource representing the domain of this property.
+	*
+   	* @param	object ResResource	$resResource
+   	* @return	boolean 
+   	* @access	public
+   	*/
+	function addDomain($resResource)
+	{
+		return $this->addProperty($this->vocabulary->DOMAIN(),$resResource);
+	}
+	
+	/**
+	* Add a resource representing the range of this property.
+	*
+   	* @param	object ResResource	$resResource
+   	* @return	boolean 
+   	* @access	public
+   	*/
+	function addRange($resResource)
+	{
+		return $this->addProperty($this->vocabulary->RANGE(),$resResource);
+	}
+	
+	/**
+	* Add a sub-property of this property.
+	*
+   	* @param	object ResProperty	$resProperty
+   	* @return	boolean 
+   	* @access	public
+   	*/	
+	function addSubProperty($resProperty)
+	{
+		return $resProperty->addProperty($this->vocabulary->SUB_PROPERTY_OF(),$this);
+	}
+	
+	/**
+	* Add a super-property of this property.
+	*
+   	* @param	object ResProperty	$resProperty
+   	* @return	boolean 
+   	* @access	public
+   	*/
+	function addSuperProperty($resProperty)
+	{
+		return $this->addProperty($this->vocabulary->SUB_PROPERTY_OF(),$resProperty);
+	}
+	
+	/**
+	* Answer a OntClass that represents the domain class of this property. 
+	* If there is more than one such resource, an arbitrary selection is made.
+	*
+   	* @return	object OntClass 
+   	* @access	public
+   	*/
+	function getDomain()
+	{
+		return $this->getPropertyValue($this->vocabulary->DOMAIN(),'OntClass');
+	}
+
+	/**
+	* Answer a OntClass that represents the range class of this property. 
+	* If there is more than one such resource, an arbitrary selection is made.
+	*
+   	* @return	object OntClass 
+   	* @access	public
+   	*/
+	function getRange()
+	{
+		return $this->getPropertyValue($this->vocabulary->RANGE(),'OntClass');
+	}
+	
+	/**
+	* Answer a property that is the sub-property of this property. 
+	* If there is more than one such property, an arbitrary selection is made.
+	*
+   	* @return	object OntProperty 
+   	* @access	public
+   	*/
+	function getSubProperty()
+	{
+		$statement = $this->model->findFirstMatchingStatement(null,$this->vocabulary->SUB_PROPERTY_OF(),$this);
+		if ($statement !== null)
+			return new OntProperty($statement->getLabelSubject());
+		
+		return null;
+	}
+	
+	/**
+	* Answer a property that is the super-property of this property. 
+	* If there is more than one such property, an arbitrary selection is made.
+	*
+   	* @return	object OntProperty 
+   	* @access	public
+   	*/
+	function getSuperProperty()
+	{
+		return $this->getPropertyValue($this->vocabulary->SUB_PROPERTY_OF(),'OntProperty');
+	}
+	
+	/**
+	* Answer true if the given resource a class specifying the domain of this property.
+	*
+   	* @param	object ResResource	$resResource
+   	* @return	boolean 
+   	* @access	public
+   	*/
+	function hasDomain($resResource)
+	{
+		return $this->hasProperty($this->vocabulary->DOMAIN(),$resResource);
+	}
+	
+	/**
+	* Answer true if the given resource a class specifying the range of this property.
+	*
+   	* @param	object ResResource	$resResource
+   	* @return	boolean 
+   	* @access	public
+   	*/
+	function hasRange($resResource)
+	{
+		return $this->hasProperty($this->vocabulary->RANGE(),$resResource);
+	}
+	
+	/**
+	* Answer true if the given property is a sub-property of this property.
+	* If $direct is set to true, only consider the direcly adjacent 
+	* properties in the property hierarchy
+	*
+   	* @param	object ResResource	$resProperty
+   	* @param	boolean	$direct
+   	* @return	boolean 
+   	* @access	public
+   	*/
+	function hasSubProperty($resProperty, $direct = true)
+	{
+		if ($direct)
+			return $resProperty->hasProperty($this->vocabulary->SUB_PROPERTY_OF(),$this);
+		
+		$index=array();
+		return ($this->_getSubAttributeStatementsRec($this,$this->vocabulary->SUB_PROPERTY_OF(),$index,$resProperty) === true);
+	}
+	
+	/**
+	* Answer true if the given property is a super-property of this property.
+	* If $direct is set to true, only consider the direcly adjacent 
+	* properties in the property hierarchy
+	*
+   	* @param	object ResResource	$resProperty
+   	* @param	boolean	$direct
+   	* @return	boolean 
+   	* @access	public
+   	*/
+	function hasSuperProperty($resProperty, $direct = true)
+	{
+		if ($direct)
+			return $this->hasProperty($this->vocabulary->SUB_PROPERTY_OF(),$resProperty);
+		
+		$index=array();
+		return ($this->_getSuperAttributeStatementsRec($this,$this->vocabulary->SUB_PROPERTY_OF(),$index,$resProperty) === true);
+	}
+	
+	/**
+	* Answer an array of all of the declared domain classes of this property. 
+	* Each element of the iterator will be an OntClass.
+	*
+   	* @return	array of OntClasses
+   	* @access	public
+   	*/
+	function listDomain()
+	{
+		return $this->listProperty($this->vocabulary->DOMAIN(),'OntClass');
+	}
+	
+	/**
+	* Answer an array of all of the declared range classes of this property. 
+	* Each element of the iterator will be an OntClass.
+	*
+   	* @return	array of OntClasses
+   	* @access	public
+   	*/
+	function listRange()
+	{
+		return $this->listProperty($this->vocabulary->RANGE(),'OntClass');
+	}
+	
+	/**
+	* Answer an array of all the properties that are declared to be 
+	* sub-properties of this property. Each element of the iterator will be an 
+	* OntProperty.
+	* If $direct is set to true, only consider the direcly adjacent 
+	* properties in the property hierarchy
+	*
+   	* @param	boolean	$direct
+   	* @return	array of OntProperties 
+   	* @access	public
+   	*/
+	function listSubProperties($direct = true)
+	{
+		$return = array();
+		if ($direct)
+		{
+			$statements = $this->model->find(null,$this->vocabulary->SUB_PROPERTY_OF(),$this);
+		} else 
+		{
+			$index = array();
+			$statements = $this->_getSubAttributeStatementsRec($this,$this->vocabulary->SUB_PROPERTY_OF(),$index);
+		}
+		
+		$returnIndex=array();
+		foreach ($statements as $statement) 
+		{
+			$objectLabel=$statement->getLabelSubject();
+			if (!in_array($objectLabel,$returnIndex))
+			{
+				$returnIndex[]=$objectLabel;
+				$return[]=new OntProperty($statement->getLabelSubject());
+			}	
+		}	
+		return $return;	
+	}
+	
+	/**
+	* Answer an array of all the properties that are declared to be 
+	* super-properties of this property. Each element of the iterator will be an 
+	* OntProperty.
+	* If $direct is set to true, only consider the direcly adjacent 
+	* properties in the property hierarchy
+	*
+   	* @param	boolean	$direct
+   	* @return	array of OntProperties 
+   	* @access	public
+   	*/
+	function listSuperProperties($direct = true)
+	{
+		$return = array();
+		if ($direct)
+			return $this->listProperty($this->vocabulary->SUB_PROPERTY_OF(),'OntProperty');
+			
+		$index=array();	
+		$statements = $this->_getSuperAttributeStatementsRec($this,$this->vocabulary->SUB_PROPERTY_OF(),$index);
+		$returnIndex=array();
+		foreach ($statements as $statement) 
+		{
+			$objectLabel=$statement->getLabelObject();
+			if (!in_array($objectLabel,$returnIndex))
+			{
+				$returnIndex[]=$objectLabel;
+				$return[]=new OntProperty($statement->getLabelObject());
+			}	
+		}	
+		return $return;	
+	}
+	
+	/**
+	* Remove the given class from the stated domain(s) of this property.
+	*
+   	* @param	object ResResource $resResource
+   	* @return	boolean 
+   	* @access	public
+   	*/
+	function removeDomain($resResource)
+	{
+		return $this->removeProperty($this->vocabulary->DOMAIN(),$resResource);
+	}
+	
+	/**
+	* Remove the given class from the stated range(es) of this property.
+	*
+   	* @param	object ResResource $resResource
+   	* @return	boolean 
+   	* @access	public
+   	*/
+	function removeRange($resResource)
+	{
+		return $this->removeProperty($this->vocabulary->RANGE(),$resResource);
+	}
+	
+	/**
+	* Remove the given property from the sub-properties of this property.
+	*
+   	* @param	object ResProperty $resProperty
+   	* @return	boolean 
+   	* @access	public
+   	*/
+	function removeSubProperty($resProperty)
+	{
+		return	$this->model->remove(new Statement($resProperty,$this->vocabulary->SUB_PROPERTY_OF(),$this));
+	}
+	
+	/**
+	* Remove the given property from the super-properties of this property.
+	*
+   	* @param	object ResProperty $resProperty
+   	* @return	boolean 
+   	* @access	public
+   	*/
+	function removeSuperProperty($resProperty)
+	{
+		return $this->removeProperty($this->vocabulary->SUB_PROPERTY_OF(),$resProperty);
+	}
+
+	/**
+	* Assert that the given resource represents the class of individuals 
+	* that form the domain of this property. Any existing domain statements 
+	* for this property are removed.
+	*
+   	* @param	object ResResource $resResource
+   	* @access	public
+   	*/
+	function setDomain($resResource)
+	{
+		$this->setPropertyValue($this->vocabulary->DOMAIN(),$resResource);
+	}
+	
+	/**
+	* Assert that the given resource represents the class of individuals 
+	* that form the range of this property. Any existing range statements 
+	* for this property are removed.
+	*
+   	* @param	object ResResource $resResource
+   	* @access	public
+   	*/
+	function setRange($resResource)
+	{
+		$this->setPropertyValue($this->vocabulary->RANGE(),$resResource);
+	}
+	
+	/**
+	* Assert that this property is super-property of the given property. 
+	* Any existing statements for superPropertyOf on prop will be removed.
+	*
+   	* @param	object ResProperty $resProperty
+   	* @access	public
+   	*/
+	function setSubProperty($resProperty)
+	{
+		foreach ($this->listSubProperties() as $oldResProperty) 
+		{
+			$this->removeSubProperty($oldResProperty);
+		}
+		
+		$this->addSubProperty($resProperty);
+	}
+	
+	/**
+	* Assert that this property is sub-property of the given property. 
+	* Any existing statements for subPropertyOf on prop will be removed.
+	*
+   	* @param	object ResProperty $resProperty
+   	* @access	public
+   	*/
+	function setSuperProperty($resProperty)
+	{
+		$this->setPropertyValue($this->vocabulary->SUB_PROPERTY_OF(),$resProperty);
+	}
+} 
+?>
Index: /Dev/trunk/rdfapi/ontModel/OntResource.php
===================================================================
--- /Dev/trunk/rdfapi/ontModel/OntResource.php	(revision 12)
+++ /Dev/trunk/rdfapi/ontModel/OntResource.php	(revision 12)
@@ -0,0 +1,739 @@
+<?php 
+// ----------------------------------------------------------------------------------
+// Class: OntResource
+// ----------------------------------------------------------------------------------
+
+
+/**
+* Provides a common super-type for all of the abstractions in 
+* this ontology representation package.
+*
+* @version  $Id: OntResource.php 268 2006-05-15 05:28:09Z tgauss $
+* @author Daniel Westphal <mail at d-westphal dot de>
+*
+*
+* @package 	ontModel
+* @access	public
+**/
+class OntResource extends ResResource 
+{
+	/**
+	* Holds a reference to the assoiated vocabulary
+	* @var		object
+	* @access	private
+	*/
+	var $vocabulary;
+	
+	/**
+	* Holds a resResource of the type, which is this ontResource of.
+	* If this value is set, the ontModel will add an additional 
+    * statement about this resource and the fiven rdf:type
+	* @var		object
+	* @access	private
+	*/
+	var $rdfType;
+	
+	
+	/**
+    * Constructor
+	* You can supply a uri
+    *
+    * @param string $uri 
+	* @access	public
+    */
+	function OntResource($uri = null)
+	{
+		$this->rdfType=false;
+		parent::ResResource($uri);
+	}
+	
+	/**
+	* Sets the reference to the assoiated vocabulary
+	*
+   	* @param	object OntVocabulary	$vocabulary
+   	* @access	public
+   	*/
+	function setVocabulary(& $vocabulary)
+	{
+		$this->vocabulary = & $vocabulary;
+	}
+	
+	/**
+	* Add the given comment to this resource.
+	*
+   	* @param	object ResLiteral	$comment
+   	* @return	boolean 
+   	* @access	public
+   	*/
+	function addComment($comment)
+	{
+		return $this->addProperty($this->vocabulary->COMMENT(),$comment);
+	}
+	
+	/**
+	* Answer the comment string for this object. If there is more than one such resource, an arbitrary selection is made.
+	*
+   	* @return	object ResLiteral or NULL 
+   	* @access	public
+   	*/
+	function getComment()
+	{
+		return $this->getPropertyValue($this->vocabulary->COMMENT());
+	}
+	
+	/**
+	* Add a resource that is declared to provide a definition of this resource.
+	*
+   	* @param	object ResResource	$resResource
+   	* @return	boolean 
+   	* @access	public
+   	*/
+	function addIsDefinedBy($resResource)
+	{
+		return $this->addProperty($this->vocabulary->IS_DEFINED_BY(),$resResource);
+	}
+	
+	/**
+	* Answer a resource that is declared to provide a definition of this resource. 
+	* If there is more than one such resource, an arbitrary selection is made.
+	*
+   	* @return	object ResResource 
+   	* @access	public
+   	*/
+	function getIsDefinedBy()
+	{
+		return $this->getPropertyValue($this->vocabulary->IS_DEFINED_BY());
+	}
+	
+	/**
+	* Add the given Label to this resource
+	*
+   	* @param	object ResLiteral	$resLiteral
+   	* @return	boolean 
+   	* @access	public
+   	*/
+	function addLabelProperty($resLiteral)
+	{
+		return $this->addProperty($this->vocabulary->LABEL(),$resLiteral);
+	}
+	
+	/**
+	* Answer the label ResLiteral for this object. 
+	* If there is more than one such resource, an arbitrary selection is made.
+	*
+   	* @param	string	$uri
+   	* @return	object ResResource
+   	* @access	public
+   	*/
+	function getLabelProperty()
+	{
+		return $this->getPropertyValue($this->vocabulary->LABEL());
+	}
+	
+	/**
+	* Add the given class as one of the rdf:type's for this resource.
+	*
+   	* @param	object ResResource	$resResource
+   	* @return	boolean 
+   	* @access	public
+   	*/
+	function addRDFType($resResource)
+	{
+		return $this->addProperty($this->vocabulary->TYPE(),$resResource);
+	}
+	
+	/**
+	* Answer the rdf:type (ie the class) of this resource. 
+	* If there is more than one type for this resource, the return value will 
+	* be one of the values, but it is not specified which one 
+	* (nor that it will consistently be the same one each time).
+	*
+   	* @return	object ResResource 
+   	* @access	public
+   	*/
+	function getRDFType()
+	{
+		return $this->getPropertyValue($this->vocabulary->TYPE());
+	}
+	
+	/**
+	* Add a resource that is declared to provided additional 
+	* information about the definition of this resource.
+	*
+   	* @param	object ResResource	$resResource
+   	* @return	boolean 
+   	* @access	public
+   	*/
+	function addSeeAlso($resResource)
+	{
+		return $this->addProperty($this->vocabulary->SEE_ALSO(),$resResource);
+	}
+	
+	/**
+	* Answer a resource that provides additional information about this resource. 
+	* If more than one such resource is defined, make an arbitrary choice.
+	*
+   	* @return	object ResResource 
+   	* @access	public
+   	*/
+	function getSeeAlso()
+	{
+		return $this->getPropertyValue($this->vocabulary->SEE_ALSO());
+	}
+	
+	/**
+	* Answer a view of this resource as a class
+	*
+   	* @return	object OntClass 
+   	* @access	public
+   	*/
+	function asClass()
+	{
+		return  $this->model->createOntClass($this->uri);
+	}
+	
+	/**
+	* Answer a view of this resource as an Individual
+	*
+   	* @return	object Individual 
+   	* @access	public
+   	*/
+	function asIndividual()
+	{
+		return  $this->model->createIndividual($this->uri);
+	}
+	
+	/**
+	* Answer a view of this resource as a property
+	*
+   	* @return	object OntProperty
+   	* @access	public
+   	*/
+	function asOntProperty()
+	{
+		return  $this->model->createOntProperty($this->uri);
+	}
+	
+	/**
+	* Answer a reference to the ontology language profile that governs the 
+	* ontology model to which this ontology resource is attached.
+	*
+   	* @param	string	$uri
+   	* @return	object OntClass 
+   	* @access	public
+   	*/
+	function getVocabulary()
+	{
+		return $this->vocabulary ;
+	}
+	
+	/**
+	* Answer the value of a given RDF property for this resource as $returnType, or null 
+	* if it doesn't have one. If there is more than one RDF statement with 
+	* the given property for the current value, it is not defined which of 
+	* the values will be returned.
+	* The following return Types are supported: 'OntClass', 'OntProperty', 'Individual', and 'ResResource'
+	* Default is 'ResResource'
+	*
+   	* @param	object ResResource	$property
+   	* @param	string	$returnType
+   	* @return	object OntClass 
+   	* @access	public
+   	*/
+	function getPropertyValue($property, $returnType = 'ResResource')
+	{
+		$statement=$this->getProperty($property);
+		if ($statement===null)
+			return null;
+			
+			switch ($returnType) 
+			{
+				case 'OntClass':
+					return $this->model->createOntClass($statement->getLabelObject());		
+					break;
+					
+				case 'OntProperty':
+					return $this->model->createOntProperty($statement->getLabelObject());		
+					break;
+				
+				case 'Individual':
+					return $this->model->createIndividual($statement->getLabelObject());		
+					break;
+			
+				default:
+					return $statement->getObject();
+					break;	
+			}	
+	}
+	
+	/**
+	* Answer true if this resource has the given comment.
+	*
+   	* @param	object ResLiteral	$resLiteral
+   	* @return	boolean 
+   	* @access	public
+   	*/
+	function hasComment($resLiteral)
+	{
+		return $this->hasProperty($this->vocabulary->COMMENT(),$resLiteral);
+	}
+	
+	/**
+	* Answer true if this resource has the given label.
+	*
+   	* @param	object ResLiteral	$resLiteral
+   	* @return	boolean 
+   	* @access	public
+   	*/
+	function hasLabelProperty($resLiteral)
+	{
+		return $this->hasProperty($this->vocabulary->LABEL(),$resLiteral);
+	}
+	
+	/**
+	* Answer true if this resource has the given rdf:type.
+	*
+   	* @param	object ResResource	$ontClass
+   	* @return	boolean 
+   	* @access	public
+   	*/
+	function hasRDFType($ontClass)
+	{
+		return $this->hasProperty($this->vocabulary->TYPE(),$ontClass);
+	}
+	
+	/**
+	* Answer true if this resource has the given resource as a source 
+	* of additional information.
+	*
+   	* @param	object ResResource	$resResource
+   	* @return	boolean 
+   	* @access	public
+   	*/
+	function hasSeeAlso($resResource)
+	{
+		return $this->hasProperty($this->vocabulary->SEE_ALSO(),$resResource);
+	}
+	
+	/**
+	* Answer true if this resource is defined by the given resource.
+	*
+   	* @param	object ResResource	$resResource
+   	* @return	boolean 
+   	* @access	public
+   	*/
+	function isDefinedBy($resResource)
+	{
+		return $this->hasProperty($this->vocabulary->IS_DEFINED_BY(),$resResource);
+	}
+	
+	/**
+	* Answer an array of all of the comment literals for this resource.
+	*
+   	* @param	string	$language
+   	* @return	array
+   	* @access	public
+   	*/
+	function listComments($language)
+	{
+		$return=$this->listProperty($this->vocabulary->COMMENT());
+		if ($language === false)
+			return $return;
+					
+		foreach ($return as $key => $resLiteral) 
+		{
+			if (!is_a($resLiteral,'ResLiteral') || $resLiteral->getLanguage() != $language)
+				unset ($return[$key]);	
+		}
+		return $return;	
+	}
+	
+	/**
+	* Answer an array of all of the resources that are declared to define this resource.
+	*
+   	* @return	array
+   	* @access	public
+   	*/
+	function listIsDefinedBy()
+	{
+		return $this->listProperty($this->vocabulary->IS_DEFINED_BY());
+	}
+	
+	/**
+	* Answer an array of all of the label literals for this resource, with the given
+	* language, if $language is set.
+	*
+   	* @return	array
+   	* @access	public
+   	*/
+	function listLabelProperties($language = false)
+	{
+		$return=$this->listProperty($this->vocabulary->LABEL());
+		if ($language === false)
+			return $return;
+					
+		foreach ($return as $key => $resLiteral) 
+		{
+			if (!is_a($resLiteral,'ResLiteral') || $resLiteral->getLanguage() != $language)
+				unset ($return[$key]);	
+		}
+		return $return;	
+	
+	}
+	
+	/**
+	* Answer an array of the RDF classes to which this resource belongs.
+	* If $direct is true, only answer those resources that are direct types of 
+	* this resource, not the super-classes of the class etc.
+	* 
+   	* @param	boolean	$direct
+   	* @return	array Array of ResResources
+   	* @access	public
+   	*/
+	function listRDFTypes($direct = true)
+	{
+		return $this->listProperty($this->vocabulary->TYPE());		
+	}
+	
+	/**
+	* Answer an array of all of the resources that are declared to 
+	* provide addition information about this resource.
+	*	
+   	* @return	array Array of ResResources
+   	* @access	public
+   	*/
+	function listSeeAlso()
+	{
+		return $this->listProperty($this->vocabulary->SEE_ALSO());	
+	}
+	
+	/**
+	* Answer an array of values of a given RDF property for this resource as $returnType, or null 
+	* if it doesn't have one. 
+	* The following return Types are supported: 'OntClass', 'OntProperty', 'Individual', and 'ResResource'
+	* Default is 'ResResource'
+	*
+   	* @param	object ResResource	$property
+   	* @param	string	$returnType
+   	* @return	array of ResResources 
+   	* @access	public
+   	*/
+	function listProperty($property, $returnType = 'OntResource')
+	{
+		$return=array();
+		$resArray = $this->listProperties($property);
+		foreach ($resArray as $statement) 
+		{
+			switch ($returnType) 
+			{
+				case 'OntClass':
+					$return[]=$this->model->createOntClass($statement->getLabelObject());		
+					break;
+					
+				case 'OntProperty':
+					$return[]=$this->model->createOntProperty($statement->getLabelObject());		
+					break;
+				
+				case 'Individual':
+					$return[]=$this->model->createIndividual($statement->getLabelObject());		
+					break;
+			
+				default:
+					$return[]=$statement->getObject();
+					break;
+			}	
+		}
+		return $return;	
+	}
+	
+	/**
+	* Remove the statement that the given ResLiteral is a comment on this resource.
+	* Returns true, if a statement was removed
+	*
+   	* @param	object ResLiteral $resLiteral
+   	* @return	boolean
+   	* @access	public
+   	*/
+	function removeComment($resLiteral)
+	{
+		return $this->removeProperty($this->vocabulary->COMMENT(),$resLiteral);
+	}
+	
+	/**
+	* Remove the statement that this resource is defined by the given resource.
+	*
+   	* @param	object ResResource $resResource
+   	* @return	boolean 
+   	* @access	public
+   	*/
+	function removeDefinedBy($resResource)
+	{
+		return $this->removeProperty($this->vocabulary->IS_DEFINED_BY(),$resResource);
+	}
+	
+	/**
+	* Remove the statement that the given ResLiteral is a label on this resource.
+	* Returns true, if a statement was removed
+	*
+   	* @param	object ResLiteral $resLiteral
+   	* @return	boolean
+   	* @access	public
+   	*/
+	function removeLabelProperty($resLiteral)
+	{
+		return $this->removeProperty($this->vocabulary->LABEL(),$resLiteral);
+	}
+	
+	/**
+	* Remove the specific property-value pair from this resource.
+	*
+   	* @param	object ResResource	$property
+   	* @param	object ResResource	$value
+   	* @return	boolean 
+   	* @access	public
+   	*/
+	function removeProperty($property, $value)
+	{
+		return $this->model->remove(new Statement($this,$property,$value));
+	}
+	
+	/**
+	* Remove the statement that this resource is of the given RDF type.
+	*
+   	* @param	object ResResource $resResource
+   	* @return	boolean 
+   	* @access	public
+   	*/
+	function removeRDFType($resResource)
+	{
+		return $this->removeProperty($this->vocabulary->TYPE(),$resResource);
+	}
+	
+	/**
+	* Remove the statement indicating the given resource as a source of 
+	* additional information about this resource. 
+	*
+   	* @param	object ResResource $resResource
+   	* @return	boolean 
+   	* @access	public
+   	*/
+	function removeSeeAlso($resResource)
+	{
+		return $this->removeProperty($this->vocabulary->SEE_ALSO(),$resResource);
+	}
+	
+	/**
+	* Assert that the given string is the comment on this resource. 
+	* Any existing statements for comment will be removed.
+	*
+   	* @param	object ResLiteral	$resLiteral 
+   	* @access	public
+   	*/
+	function setComment($resLiteral)
+	{
+		$this->setPropertyValue($this->vocabulary->COMMENT(),$resLiteral);
+	}
+	
+	/**
+	* Assert that the given resource provides a source of definitions about this resource. 
+	* Any existing statements for isDefinedBy will be removed.
+	*
+   	* @param	object ResResource	$resResource 
+   	* @access	public
+   	*/
+	function setIsDefinedBy($resResource)
+	{
+		$this->setPropertyValue($this->vocabulary->IS_DEFINED_BY(),$resResource);
+	}
+	
+	/**
+	* Assert that the given string is the label on this resource. 
+	* Any existing statements for comment will be removed.
+	*
+   	* @param	object ResLiteral	$resLiteral 
+   	* @access	public
+   	*/
+	function setLabelProperty($resLiteral)
+	{
+		$this->setPropertyValue($this->vocabulary->LABEL(),$resLiteral);
+	}
+	
+	/**
+	* Set the value of the given property of this ontology resource to the given value. 
+	* Maintains the invariant that there is at most one value of the property for a 
+	* given resource, so existing property values are first removed. 
+	* To add multiple properties, use addProperty.
+	*
+   	* @param	object ResResource	$property
+   	* @param	object ResResource	$value  
+   	* @access	public
+   	*/
+	function setPropertyValue($property, $value)
+	{
+		$this->removeAll($property);
+		$this->addProperty($property,$value);
+	}
+	
+	/**
+	* Set the RDF type (ie the class) for this resource, 
+	* replacing any existing rdf:type property. Any existing statements 
+	* for the RDF type will first be removed.
+	*
+   	* @param	object ResResource	$resResource 
+   	* @access	public
+   	*/
+	function setRDFType($resResource)
+	{
+		$this->setPropertyValue($this->vocabulary->TYPE(),$resResource);
+	}
+	
+	/**
+	* Add a resource that is declared to provided additional information 
+	* about the definition of this resource
+	*
+   	* @param	object ResResource	$resResource 
+   	* @access	public
+   	*/
+	function setSeeAlso($resResource)
+	{
+		$this->setPropertyValue($this->vocabulary->SEE_ALSO(),$resResource);
+	}
+	
+	/**
+	* Returns an array of ResResources that are recursively connected by $attribute 
+	* in superProperty direction.
+	* If $onlyFindThisResResource is set to a ResResource, this function returns boolean
+	* if this distinct resource recursively is connected to the $startResource.
+	*
+   	* @param	object ResResource	$startResource
+   	* @param	object ResResource	$attribute
+	* @param	array				$attribute
+	* @param	object ResResource	$onlyFindThisResResource	
+   	* @return	array OR boolean 
+   	* @access	private
+   	*/
+	function _getSuperAttributeStatementsRec(& $startResource,& $attribute,& $attributeIndex, $onlyFindThisResResource = false)
+	{
+
+		$return = $startResource->listProperties($attribute);
+		
+		if ($onlyFindThisResResource)
+		{
+			foreach ($return as $statement)
+			{
+				if ($onlyFindThisResResource->equals($statement->getObject()))
+					return true;
+			}	
+		}
+		
+		foreach ($return as $statement)
+		{
+			$attributeLabel=$statement->getLabelObject();
+			if (!in_array($attributeLabel,$attributeIndex))
+			{
+				$attributeIndex[]=$attributeLabel;
+				$subReturn = $this->_getSuperAttributeStatementsRec($statement->getObject(), $attribute, $attributeIndex, $onlyFindThisResResource);
+			} 
+		}
+		if (isset($subReturn))
+		{
+			if ($subReturn === true)
+				return true;
+			return array_merge($return,$subReturn);
+		}	
+		
+		return $return;
+	}
+	
+	/**
+	* Returns an array of ResResources that are recursively connected by $attribute 
+	* in subProperty direction.
+	* If $onlyFindThisResResource is set to a ResResource, this function returns boolean
+	* if this distinct resource recursively is connected to the $startResource.
+	*
+   	* @param	object ResResource	$startResource
+   	* @param	object ResResource	$attribute
+	* @param	array				$attribute
+	* @param	object ResResource	$onlyFindThisResResource	
+   	* @return	array OR boolean 
+   	* @access	private
+   	*/
+	function _getSubAttributeStatementsRec(& $startResource,& $attribute,& $attributeIndex, $onlyFindThisResResource = false)
+	{
+
+		$return = $this->model->find(null,$attribute,$startResource);
+		
+		if ($onlyFindThisResResource)
+		{
+			foreach ($return as $statement)
+			{
+				if ($onlyFindThisResResource->equals($statement->getSubject()))
+					return true;
+			}	
+		}
+		
+		foreach ($return as $statement)
+		{
+			$attributeLabel=$statement->getLabelSubject();
+			if (!in_array($attributeLabel,$attributeIndex))
+			{
+				$attributeIndex[]=$attributeLabel;
+				$subReturn = $this->_getSubAttributeStatementsRec($statement->getSubject(), $attribute, $attributeIndex, $onlyFindThisResResource);
+			} 
+		}
+		if (isset($subReturn))
+		{
+			if ($subReturn === true)
+				return true;
+			return array_merge($return,$subReturn);
+		}
+			
+		return $return;
+	}
+	
+	/**
+	* Add a property to this resource.
+	* A statement with this resource as the subject, p as the predicate and o 
+	* as the object is added to the model associated with this resource.
+	* If $this->rdfType is set, an additional statement about it's type
+	* is added.
+	*
+   	* @param	ResResource				$property
+   	* @param	ResResource/ResLiteral	$object
+   	* @return	object ResResource 
+   	* @access	public
+   	*/
+	function addProperty($property,$object)
+	{
+		if ($this->rdfType !== false)
+			if (!$this->hasRDFType($this->rdfType))
+					$this->model->add(new Statement($this,$this->vocabulary->TYPE(),$this->rdfType));
+	
+		return parent:: addProperty($property,$object);
+	}
+	
+	/**
+    * Sets the rdf:type, that this distinct resource is instance of.
+    * If this value is set, the ontModel will add an additional 
+    * statement about this resource and the fiven rdf:type
+    *
+    * @param object ResResource $resResource 
+	* @access	public
+    */
+	function setInstanceRdfType($resResource)
+	{
+		$this->rdfType = $resResource;
+	}
+	
+	/**
+    * returns the rdf:type, that this distinct resource is instance of.
+    *
+    * @return object ResResource $resResource 
+	* @access	public
+    */
+	function getInstanceRdfType()
+	{
+		return $this->rdfType;
+	}
+} 
+?>
Index: /Dev/trunk/rdfapi/ontModel/OntVocabulary.php
===================================================================
--- /Dev/trunk/rdfapi/ontModel/OntVocabulary.php	(revision 12)
+++ /Dev/trunk/rdfapi/ontModel/OntVocabulary.php	(revision 12)
@@ -0,0 +1,25 @@
+<?php
+// ----------------------------------------------------------------------------------
+// Class: OntVocabulary
+// ----------------------------------------------------------------------------------
+
+
+/**
+* Base Class that encapsulates the elements of a general vocabulary 
+* corresponding to a particular ontology language. The intent is that, 
+* using a given vocabulary, a given RDF model can be processed as an 
+* ontology description, without binding knowledge of the vocabulary 
+* into this Class
+*
+* @version  $Id: OntVocabulary.php 320 2006-11-21 09:38:51Z tgauss $
+* @author Daniel Westphal <mail at d-westphal dot de>
+*
+*
+* @package 	ontModel
+* @access	public
+**/
+class OntVocabulary
+{
+	
+}
+?>
Index: /Dev/trunk/rdfapi/ontModel/RdfsVocabulary.php
===================================================================
--- /Dev/trunk/rdfapi/ontModel/RdfsVocabulary.php	(revision 12)
+++ /Dev/trunk/rdfapi/ontModel/RdfsVocabulary.php	(revision 12)
@@ -0,0 +1,143 @@
+<?php
+
+// ----------------------------------------------------------------------------------
+// Class: RdfsVocabulary
+// ----------------------------------------------------------------------------------
+
+/**
+* RDFS vocabulary items
+*
+*
+* @version  $Id: RdfsVocabulary.php 320 2006-11-21 09:38:51Z tgauss $
+* @author Daniel Westphal <mail at d-westphal dot de>
+*
+*
+* @package 	ontModel
+* @access	public
+**/
+class RdfsVocabulary extends OntVocabulary 
+{
+
+	/**
+	* Answer the resource that represents the class 'class' in this vocabulary.
+	*
+   	* @return	object ResResource 
+   	* @access	public
+   	*/
+	function ONTCLASS()
+	{
+		return new ResResource(RDF_SCHEMA_URI.RDFS_CLASS);	
+	}
+	
+	/**
+	* Answer the predicate that denotes the domain of a property.
+	*
+   	* @return	object ResProperty 
+   	* @access	public
+   	*/
+	function DOMAIN()
+	{
+		return new ResProperty(RDF_SCHEMA_URI.RDFS_DOMAIN);	
+	}
+	
+	 
+ 	/**
+	* Answer the predicate that denotes comment annotation on an ontology element.
+	*
+   	* @return	object ResProperty 
+   	* @access	public
+   	*/
+	function COMMENT()
+	{
+		return new ResProperty(RDF_SCHEMA_URI.RDFS_COMMENT);	
+	}
+	
+ 	/**
+	* Answer the predicate that denotes isDefinedBy annotation on an ontology element
+	*
+   	* @return	object ResProperty 
+   	* @access	public
+   	*/
+	function IS_DEFINED_BY()
+	{
+		return new ResProperty(RDF_SCHEMA_URI.RDFS_IS_DEFINED_BY);
+	}
+	
+	/**
+	* Answer the predicate that denotes label annotation on an ontology element
+	*
+   	* @return	object ResProperty 
+   	* @access	public
+   	*/
+	function LABEL()
+	{
+		return new ResProperty(RDF_SCHEMA_URI.RDFS_LABEL);
+	}
+	
+	/**
+	* Answer the predicate that denotes the domain of a property.
+	*
+   	* @return	object ResProperty 
+   	* @access	public
+   	*/
+	function RANGE()
+	{
+		return new ResProperty(RDF_SCHEMA_URI.RDFS_RANGE);
+	}
+	
+	/**
+	* Answer the predicate that denotes seeAlso annotation on an ontology element
+	*
+   	* @return	object ResProperty 
+   	* @access	public
+   	*/
+	function SEE_ALSO()
+	{
+		return new ResProperty(RDF_SCHEMA_URI.RDFS_SEE_ALSO);
+	}
+	
+	/**
+	* Answer the predicate that denotes that one class is a sub-class of another.
+	*
+   	* @return	object ResProperty 
+   	* @access	public
+   	*/
+	function SUB_CLASS_OF()
+	{
+		return new ResProperty(RDF_SCHEMA_URI.RDFS_SUBCLASSOF);
+	}
+	
+	/**
+	* Answer the predicate that denotes that one property is a sub-property of another.
+	*
+   	* @return	object ResProperty 
+   	* @access	public
+   	*/
+	function SUB_PROPERTY_OF()
+	{
+		return new ResProperty(RDF_SCHEMA_URI.RDFS_SUBPROPERTYOF);
+	}
+
+	/**
+	* Answer the string that is the namespace prefix for this vocabulary
+	*
+   	* @return	string
+   	* @access	public
+   	*/
+	function NAMESPACE()
+	{
+		return RDF_SCHEMA_URI;
+	}
+	
+	/**
+	* Answer the predicate that denotes the rdf:type property.
+	*
+   	* @return	object ResProperty 
+   	* @access	public
+   	*/
+	function TYPE()
+	{
+		return new ResProperty(RDF_NAMESPACE_URI.RDF_TYPE);
+	}
+} 
+?>
Index: /Dev/trunk/rdfapi/rdql/RDQL.php
===================================================================
--- /Dev/trunk/rdfapi/rdql/RDQL.php	(revision 12)
+++ /Dev/trunk/rdfapi/rdql/RDQL.php	(revision 12)
@@ -0,0 +1,17 @@
+<?php
+// ----------------------------------------------------------------------------------
+// RDQL
+// ----------------------------------------------------------------------------------
+//
+// Description               : Rdql package
+// ----------------------------------------------------------------------------------
+
+
+// include RDQL classes
+require_once( RDFAPI_INCLUDE_DIR . 'rdql/RdqlParser.php' );
+require_once( RDFAPI_INCLUDE_DIR . 'rdql/RdqlEngine.php' );
+require_once( RDFAPI_INCLUDE_DIR . 'rdql/RdqlDbEngine.php' );
+require_once( RDFAPI_INCLUDE_DIR . 'rdql/RdqlMemEngine.php' );
+require_once( RDFAPI_INCLUDE_DIR . 'rdql/RdqlResultIterator.php' );
+
+?>
Index: /Dev/trunk/rdfapi/rdql/RdqlDbEngine.php
===================================================================
--- /Dev/trunk/rdfapi/rdql/RdqlDbEngine.php	(revision 12)
+++ /Dev/trunk/rdfapi/rdql/RdqlDbEngine.php	(revision 12)
@@ -0,0 +1,506 @@
+<?php
+
+// ----------------------------------------------------------------------------------
+// Class: RdqlDbEngine
+// ----------------------------------------------------------------------------------
+
+/**
+ * This class performs as RDQL query on a DbModel.
+ *
+ * Provided an rdql query parsed into an array of php variables and constraints
+ * at first the engine generates an sql statement and queries the database for
+ * tuples matching all patterns from the WHERE clause of the given RDQL query.
+ * Subsequently the result set is is filtered with evaluated boolean expressions
+ * from the AND clause of the given RDQL query.
+ *
+ * @version  $Id: RdqlDbEngine.php 559 2008-02-29 15:21:35Z cax $
+ * @author   Radoslaw Oldakowski <radol@gmx.de>
+ *
+ * @package rdql
+ * @access public
+ */
+
+Class RdqlDbEngine extends RdqlEngine {
+
+
+/**
+ * Parsed query variables and constraints.
+ *
+ * @var     array   ['selectVars'][] = ?VARNAME
+ *                  ['sources'][] = URI
+ *                  ['patterns'][]['subject']['value'] = VARorURI
+ *                                ['predicate']['value'] = VARorURI
+ *                                ['object']['value'] = VARorURIorLiterl
+ *                                          ['is_literal'] = boolean
+ *                                          ['l_lang'] = string
+ *                                          ['l_dtype'] = string
+ *                  ['filters'][]['string'] = string
+ *                               ['evalFilterStr'] = string
+ *                               ['reqexEqExprs'][]['var'] = ?VARNAME
+ *                                                 ['operator'] = (eq | ne)
+ *                                                 ['regex'] = string
+ *                               ['strEqExprs'][]['var'] = ?VARNAME
+ *                                               ['operator'] = (eq | ne)
+ *                                               ['value'] = string
+ *                                               ['value_type'] = ('variable' | 'URI' | 'Literal')
+ *                                               ['value_lang'] = string
+ *                                               ['value_dtype'] = string
+ *                               ['numExpr']['vars'][] = ?VARNAME
+ *                         ( [] stands for an integer index - 0..N )
+ * @access	private
+ */
+ var $parsedQuery;
+
+
+/**
+ * When an RDQL query is performed on a DbModel, in first step the engine searches
+ * in database for triples matching the Rdql-WHERE clause. A recordSet is returned.
+ * $rsIndexes maps select and filter variables to their corresponding indexes
+ * in the returned recordSet.
+ *
+ * @var     array [?VARNAME]['value'] = integer
+ *                          ['nType'] = integer
+ *                          ['l_lang'] = integer
+ *                          ['l_dtype'] = integer
+ * @access	private
+ */
+ var $rsIndexes;
+
+
+ /**
+ * Perform an RDQL Query on the given DbModel.
+ *
+ * @param   object  DbModel $dbModel
+ * @param   array   &$parsedQuery  (the same format as $this->parsedQuery)
+ * @param   boolean $returnNodes
+ * @return  array   [][?VARNAME] = object Node  (if $returnNodes = TRUE)
+ *      OR  array   [][?VARNAME] = string
+ * @access  public
+ */
+ function & queryModel(&$dbModel, &$parsedQuery, $returnNodes = TRUE) {
+
+   $this->parsedQuery = &$parsedQuery;
+
+   $sql = $this->generateSql($dbModel->modelID);
+   $recordSet =& $dbModel->dbConn->execute($sql);
+   $queryResult = $this->filterQueryResult($recordSet);
+
+   if ($returnNodes)
+      $ret = $this->toNodes($queryResult);
+   else
+      $ret = $this->toString($queryResult);
+   return $ret;
+ }
+
+
+ /**
+ * Generate an SQL string to query the database for tuples matching all patterns
+ * of $parsedQuery.
+ *
+ * @param   integer $modelID
+ * @return  string
+ * @access	private
+ */
+ function generateSql($modelID) {
+
+   $sql  = $this->generateSql_SelectClause();
+   $sql .= $this->generateSql_FromClause();
+   $sql .= $this->generateSql_WhereClause($modelID);
+   return $sql;
+ }
+
+
+/**
+ * Generate SQL SELECT clause.
+ *
+ * @return  string
+ * @throws  PHPError
+ * @access	private
+ */
+ function generateSql_SelectClause() {
+
+   $sql_select = 'SELECT';
+   $index = 0;
+   $this->rsIndexes = array();
+
+   foreach ($this->parsedQuery['selectVars'] as $var)
+     $sql_select .= $this->_generateSql_SelectVar($var, $index);
+
+   if (isset($this->parsedQuery['filters'])) {
+       foreach ($this->parsedQuery['filters'] as $n => $filter) {
+
+         // variables from numeric expressions
+         foreach ($filter['numExprVars'] as $numVar)
+           $sql_select .= $this->_generateSql_SelectVar($numVar, $index);
+
+         // variables from regex equality expressions
+         foreach ($filter['regexEqExprs'] as $regexEqExpr)
+           $sql_select .= $this->_generateSql_SelectVar($regexEqExpr['var'], $index);
+
+         // variables from string equality expressions
+         foreach ($filter['strEqExprs'] as $strEqVar)
+             $sql_select .= $this->_generateSql_SelectVar($strEqVar['var'], $index);
+       }
+   }
+
+   return rtrim($sql_select, " , ");
+ }
+
+
+/**
+ * Generate SQL FROM clause
+ *
+ * @return  string
+ * @access	private
+ */
+ function generateSql_FromClause() {
+
+   $sql_from = ' FROM';
+   foreach ($this->parsedQuery['patterns'] as $n => $v)
+     $sql_from .= ' statements s' .($n+1) .' , ';
+
+   return rtrim($sql_from, ' , ');
+ }
+
+
+/**
+ * Generate an SQL WHERE clause
+ *
+ * @param   integer $modelID
+ * @return  string
+ * @access	private
+ */
+ function generateSql_WhereClause($modelID) {
+
+   $sql_where = ' WHERE';
+   $count_patterns = count($this->parsedQuery['patterns']);
+   foreach ($this->parsedQuery['patterns'] as $n => $pattern) {
+     $sql_where .= ' s' .($n+1) .'.modelID=' .$modelID .' AND';
+     foreach ($pattern as $key => $val_1)
+       if ($val_1['value'] && $val_1['value']{0}=='?') {
+         $sql_tmp = ' s' .($n+1) .'.' .$key .'=';
+         // find internal bindings
+         switch ($key) {
+           case 'subject':
+                    if ($pattern['subject']['value'] == $pattern['predicate']['value'])
+                       $sql_where .= $sql_tmp .'s' .($n+1) .'.predicate AND';
+                    elseif ($pattern['subject']['value'] == $pattern['object']['value'])
+                       $sql_where .= $sql_tmp .'s' .($n+1) .'.object AND';
+                    break;
+           case 'predicate':
+                    if ($pattern['predicate']['value'] == $pattern['object']['value'])
+                       $sql_where .= $sql_tmp .'s' .($n+1) .'.object AND';
+         }
+         // find external bindings
+         for ($i=$n+1; $i<$count_patterns; $i++)
+             foreach ($this->parsedQuery['patterns'][$i] as $key2 => $val_2)
+               if ($val_1['value']==$val_2['value']) {
+                  $sql_where .= $sql_tmp .'s' .($i+1) .'.' .$key2 .' AND';
+                  break 2;
+               }
+       }else {
+          $sql_where .= ' s' .($n+1) .'.' .$key ."='" .$val_1['value'] ."' AND";
+          if ($key == 'object' && isset($val_1['is_literal'])) {
+              $sql_where .= ' s' .($n+1) .".object_is='l' AND";
+              $sql_where .= ' s' .($n+1) .".l_datatype='" .$val_1['l_dtype'] ."' AND";
+              $sql_where .= ' s' .($n+1) .".l_language='" .$val_1['l_lang'] ."' AND";
+          }
+       }
+   }
+   return rtrim($sql_where, ' AND');
+ }
+
+
+/**
+ * Filter tuples containing variables matching all patterns from the WHERE clause
+ * of an RDQL query. As a result of a database query using ADOdb these tuples
+ * are returned as an ADORecordSet object, which is then passed to this function.
+ *
+ * @param   object ADORecordSet &$recordSet
+ * @return  array  [][?VARNAME]['value']   = string
+ *                             ['nType']   = string
+ *                             ['l_lang']  = string
+ *                             ['l_dtype'] = string
+ * @access	private
+ */
+ function filterQueryResult(&$recordSet) {
+   $queryResult=array();
+
+   if (isset($this->parsedQuery['filters'])) {
+
+       while (!$recordSet->EOF) {
+
+         foreach ($this->parsedQuery['filters'] as $filter) {
+
+           $evalFilterStr = $filter['evalFilterStr'];
+
+           // evaluate regex equality expressions of each filter
+           foreach ($filter['regexEqExprs'] as $i => $expr) {
+               preg_match($expr['regex'], $recordSet->fields[$this->rsIndexes[$expr['var']]['value']], $match);
+               $op = substr($expr['operator'], 0,1);
+               if (($op != '!' && !isset($match[0])) || ($op == '!' && isset($match[0])))
+                  $evalFilterStr = str_replace("##RegEx_$i##", 'FALSE', $evalFilterStr);
+               else
+                  $evalFilterStr = str_replace("##RegEx_$i##", 'TRUE', $evalFilterStr);
+           }
+
+           // evaluate string equality expressions
+           foreach ($filter['strEqExprs'] as $i => $expr) {
+
+             $exprBoolVal = 'FALSE';
+
+             switch ($expr['value_type']) {
+
+               case 'variable':
+                    if (($recordSet->fields[$this->rsIndexes[$expr['var']]['value']] ==
+                           $recordSet->fields[$this->rsIndexes[$expr['value']]['value']] &&
+                         $expr['operator'] == 'eq') ||
+                        ($recordSet->fields[$this->rsIndexes[$expr['var']]['value']] !=
+                           $recordSet->fields[$this->rsIndexes[$expr['value']]['value']] &&
+                         $expr['operator'] == 'ne'))
+
+                       $exprBoolVal = 'TRUE';
+                    break;
+
+               case 'URI':
+
+                      if (isset($this->rsIndexes[$expr['var']]['nType']) &&
+                           $recordSet->fields[$this->rsIndexes[$expr['var']]['nType']] == 'l') {
+
+                         if ($expr['operator'] == 'ne')
+                            $exprBoolVal = 'TRUE';
+                         break;
+                      }
+
+                    if (($recordSet->fields[$this->rsIndexes[$expr['var']]['value']] ==
+                           $expr['value'] && $expr['operator'] == 'eq') ||
+                        ($recordSet->fields[$this->rsIndexes[$expr['var']]['value']] !=
+                           $expr['value'] && $expr['operator'] == 'ne'))
+                       $exprBoolVal = 'TRUE';
+                    break;
+
+               case 'Literal':
+
+                    if (!isset($this->rsIndexes[$expr['var']]['nType']) ||
+                           $recordSet->fields[$this->rsIndexes[$expr['var']]['nType']] != 'l') {
+
+                       if ($expr['operator'] == 'ne')
+                          $exprBoolVal = 'TRUE';
+                       break;
+                    }
+
+                    $filterLiteral= new Literal($expr['value'],$expr['value_lang']);
+                    $filterLiteral->setDatatype($expr['value_dtype']);
+
+                    $resultLiteral=new Literal($recordSet->fields[$this->rsIndexes[$expr['var']]['value']]);
+                    $resultLiteral->setDatatype($recordSet->fields[$this->rsIndexes[$expr['var']]['l_dtype']]);
+                    $resultLiteral->setLanguage($recordSet->fields[$this->rsIndexes[$expr['var']]['l_lang']]);
+
+                    $equal=$resultLiteral->equals($filterLiteral);
+
+                    if (($equal && $expr['operator'] == 'eq') ||
+                        (!$equal && $expr['operator'] == 'ne'))
+                       $exprBoolVal = 'TRUE';
+                    else
+                       $exprBoolVal = 'FALSE';
+
+             }
+
+             $evalFilterStr = str_replace("##strEqExpr_$i##", $exprBoolVal, $evalFilterStr);
+          }
+
+          // evaluate numerical expressions
+          foreach ($filter['numExprVars'] as $varName) {
+            $varValue = "'" .$recordSet->fields[$this->rsIndexes[$varName]['value']] ."'";
+            $evalFilterStr = str_replace($varName, $varValue, $evalFilterStr);
+          }
+
+          eval("\$filterBoolVal = $evalFilterStr; \$eval_filter_ok = TRUE;");
+          if (!isset($eval_filter_ok))
+             trigger_error(RDQL_AND_ERR ."'" .htmlspecialchars($filter['string']) ."'", E_USER_ERROR);
+
+          if (!$filterBoolVal) {
+             $recordSet->MoveNext();
+             continue 2;
+          }
+
+        }
+        $queryResult[] = $this->_convertRsRowToQueryResultRow($recordSet->fields);
+        $recordSet->MoveNext();
+      }
+
+   }else
+      while (!$recordSet->EOF) {
+        $queryResult[] = $this->_convertRsRowToQueryResultRow($recordSet->fields);
+        $recordSet->MoveNext();
+      }
+   return $queryResult;
+ }
+
+
+/**
+ * Serialize variable values of $queryResult to string.
+ *
+ * @param   array  &$queryResult [][?VARNAME]['value']   = string
+ *                                           ['nType']   = string
+ *                                           ['l_lang']  = string
+ *                                           ['l_dtype'] = string
+ * @return  array  [][?VARNAME] = string
+ * @access	private
+ */
+ function toString(&$queryResult) {
+
+   // if a result set is empty return only variable sames
+   if (count($queryResult) == 0) {
+      foreach ($this->parsedQuery['selectVars'] as $selectVar)
+         $res[0][$selectVar] = NULL;
+      return $res;
+   }
+
+   $res = array();
+   foreach ($queryResult as $n => $var)
+     foreach ($var as $varname => $varProperties)
+       if ($varProperties['nType'] == 'r' || $varProperties['nType'] == 'b')
+          $res[$n][$varname] = '<' .$varProperties['value'] .'>';
+       else {
+          $res[$n][$varname] = '"' .$varProperties['value'] .'"';
+          if ($varProperties['l_lang'] != NULL)
+             $res[$n][$varname] .= ' (xml:lang="' .$varProperties['l_lang'] .'")';
+          if ($varProperties['l_dtype'] != NULL)
+             $res[$n][$varname] .= ' (rdf:datatype="' .$varProperties['l_dtype'] .'")';
+       }
+   return $res;
+ }
+
+
+/**
+ * Convert variable values of $queryResult to objects (Node).
+ *
+ * @param   array  &$queryResult [][?VARNAME]['value']   = string
+ *                                           ['nType']   = string
+ *                                           ['l_lang']  = string
+ *                                           ['l_dtype'] = string
+ * @return  array  [][?VARNAME] = object Node
+ * @access	private
+ */
+ function toNodes(&$queryResult) {
+
+   // if a result set is empty return only variable sames
+   if (count($queryResult) == 0) {
+      foreach ($this->parsedQuery['selectVars'] as $selectVar)
+         $res[0][$selectVar] = NULL;
+      return $res;
+   }
+
+   $res = array();
+   foreach ($queryResult as $n => $var)
+     foreach ($var as $varname => $varProperties)
+       if ($varProperties['nType'] == 'r')
+          $res[$n][$varname] = new Resource($varProperties['value']);
+       elseif ($varProperties['nType'] == 'b')
+          $res[$n][$varname] = new BlankNode($varProperties['value']);
+       else {
+          $res[$n][$varname] = new Literal($varProperties['value'], $varProperties['l_lang']);
+          if ($varProperties['l_dtype'] != NULL)
+             $res[$n][$varname]->setDataType($varProperties['l_dtype']);
+       }
+   return $res;
+ }
+
+
+/**
+ * Generate a piece of an sql select statement for a variable.
+ * Look first if the given variable is defined as a pattern object.
+ * (So you can select the node type, literal lang and dtype)
+ * If not found - look for subjects and select node label and type.
+ * If there is no result either go to predicates.
+ * Predicates are always resources therefore select only the node label.
+ *
+ * @param   string $varName
+ * @return  string
+ * @access	private
+ */
+function _generateSql_SelectVar ($varName, &$index) {
+
+  $sql_select = '';
+
+  if (array_key_exists($varName, $this->rsIndexes))
+     return NULL;
+
+  foreach ($this->parsedQuery['patterns'] as $n => $pattern)
+    if ($varName == $pattern['object']['value']) {
+
+       // select the object label
+       $sql_select .= " s" .++$n .".object as _" .ltrim($varName, "?") ." , ";
+       $this->rsIndexes[$varName]['value'] = $index++;
+       // select the node type
+       $sql_select .= " s" .$n .".object_is , ";
+       $this->rsIndexes[$varName]['nType'] = $index++;
+       // select the object language
+       $sql_select .= " s" .$n .".l_language , ";
+       $this->rsIndexes[$varName]['l_lang'] = $index++;
+       // select the object dtype
+       $sql_select .= " s" .$n .".l_datatype , ";
+       $this->rsIndexes[$varName]['l_dtype'] = $index++;
+
+       return $sql_select;
+    }
+
+  foreach ($this->parsedQuery['patterns'] as $n => $pattern)
+    if ($varName == $pattern['subject']['value']) {
+
+       // select the object label
+       $sql_select .= " s" .++$n .".subject as _" .ltrim($varName, "?") ." , ";
+       $this->rsIndexes[$varName]['value'] = $index++;
+       // select the node type
+       $sql_select .= " s" .$n .".subject_is , ";
+       $this->rsIndexes[$varName]['nType'] = $index++;
+
+       return $sql_select;
+    }
+
+  foreach ($this->parsedQuery['patterns'] as $n => $pattern)
+    if ($varName == $pattern['predicate']['value']) {
+
+       // select the object label
+       $sql_select .= " s" .++$n .".predicate as _" .ltrim($varName, "?") ." , ";
+       $this->rsIndexes[$varName]['value'] = $index++;
+
+       return $sql_select;
+    }
+ }
+
+
+/**
+ * Converts a single row of ADORecordSet->fields array to the format of
+ * $queryResult array using pointers to indexes ($this->rsIndexes) in RecordSet->fields.
+ *
+ * @param   array  &$record [] = string
+ * @return  array  [?VARNAME]['value']   = string
+ *                           ['nType']   = string
+ *                           ['l_lang']  = string
+ *                           ['l_dtype'] = string
+ * @access	private
+ */
+ function _convertRsRowToQueryResultRow(&$record) {
+
+   // return only select variables (without conditional variables from the AND clause)
+   foreach ($this->parsedQuery['selectVars'] as $selectVar) {
+     $resultRow[$selectVar]['value'] = $record[$this->rsIndexes[$selectVar]['value']];
+     if (isset($this->rsIndexes[$selectVar]['nType']))
+        $resultRow[$selectVar]['nType'] = $record[$this->rsIndexes[$selectVar]['nType']];
+     // is a predicate then
+     else
+        $resultRow[$selectVar]['nType'] = 'r';
+
+     if ($resultRow[$selectVar]['nType'] == 'l') {
+        $resultRow[$selectVar]['l_lang'] = $record[$this->rsIndexes[$selectVar]['l_lang']];
+        $resultRow[$selectVar]['l_dtype'] = $record[$this->rsIndexes[$selectVar]['l_dtype']];
+     }
+   }
+   return $resultRow;
+ }
+
+} // end: Class RdqlDbEngine
+
+?>
Index: /Dev/trunk/rdfapi/rdql/RdqlEngine.php
===================================================================
--- /Dev/trunk/rdfapi/rdql/RdqlEngine.php	(revision 12)
+++ /Dev/trunk/rdfapi/rdql/RdqlEngine.php	(revision 12)
@@ -0,0 +1,70 @@
+<?php
+
+// ----------------------------------------------------------------------------------
+// Class: RdqlEngine
+// ----------------------------------------------------------------------------------
+
+/**
+ * Some general methods common for RdqlMemEngine and RdqlDbEngine
+ *
+ * @version  $Id: RdqlEngine.php 268 2006-05-15 05:28:09Z tgauss $
+ * @author   Radoslaw Oldakowski <radol@gmx.de>
+ *
+ * @package rdql
+ * @access public
+ */
+
+Class RdqlEngine extends Object{
+
+	
+
+/**
+ * Prints a query result as HTML table.
+ * You can change the colors in the configuration file.
+ *
+ * @param array $queryResult [][?VARNAME] = object Node
+ * @access private
+ */
+ function writeQueryResultAsHtmlTable($queryResult) {
+ 	  // Import Package Utility
+   	 include_once(RDFAPI_INCLUDE_DIR.PACKAGE_UTILITY);
+
+   if (current($queryResult[0]) == NULL) {
+      echo 'no match<br>';
+      return;
+   }
+
+   $rdfUtil = new RDFUtil();
+        echo '<table border="1" cellpadding="3" cellspacing="0"><tr><td><b>No.</b></td>';
+   foreach ($queryResult[0] as $varName => $value)
+     echo "<td align='center'><b>$varName</b></td>";
+     echo '</tr>';
+
+   foreach ($queryResult as $n => $var) {
+
+   		
+     echo '<tr><td width="20" align="right">' .($n + 1) .'.</td>';
+     foreach ($var as $varName => $value) {
+       echo INDENTATION . INDENTATION . '<td bgcolor="';
+   	   echo $rdfutil->chooseColor($value);
+       echo '">';
+       echo '<p>';
+
+       $lang  = NULL;
+       $dtype = NULL;
+       if (is_a($value, 'Literal')) {
+    	   if ($value->getLanguage() != NULL)
+               $lang = ' <b>(xml:lang="' . $value->getLanguage() . '") </b> ';
+		   if ($value->getDatatype() != NULL)
+  			  $dtype = ' <b>(rdf:datatype="' . $value->getDatatype() . '") </b> ';
+       }
+  	   echo  $rdfutil->getNodeTypeName($value) .$value->getLabel() . $lang . $dtype .'</p>';
+     }
+     echo '</tr>';
+   }
+   echo '</table>';
+ }
+ 
+} // end: Class RdqlEngine
+
+?>
Index: /Dev/trunk/rdfapi/rdql/RdqlMemEngine.php
===================================================================
--- /Dev/trunk/rdfapi/rdql/RdqlMemEngine.php	(revision 12)
+++ /Dev/trunk/rdfapi/rdql/RdqlMemEngine.php	(revision 12)
@@ -0,0 +1,555 @@
+<?php
+
+// ----------------------------------------------------------------------------------
+// Class: RdqlMemEngine
+// ----------------------------------------------------------------------------------
+
+/**
+ * This class performes as RDQL query on a MemModel.
+ *
+ * Provided an rdql query parsed into an array of php variables and constraints
+ * at first the engine searches for tuples matching all patterns from the WHERE clause
+ * of the given RDQL query. Then the query result set is filtered with evaluated
+ * boolean expressions from the AND clause of the given RDQL query.
+ *
+ * @version  $Id: RdqlMemEngine.php 268 2006-05-15 05:28:09Z tgauss $
+ * @author   Radoslaw Oldakowski <radol@gmx.de>
+ *
+ * @package rdql
+ * @access public
+ */
+
+Class RdqlMemEngine extends RdqlEngine {
+
+
+/**
+ * Parsed query variables and constraints.
+ *
+ * @var     array   ['selectVars'][] = ?VARNAME
+ *                  ['sources'][] = URI
+ *                  ['patterns'][]['subject']['value'] = VARorURI
+ *                                ['predicate']['value'] = VARorURI
+ *                                ['object']['value'] = VARorURIorLiterl
+ *                                          ['is_literal'] = boolean
+ *                                          ['l_lang'] = string
+ *                                          ['l_dtype'] = string
+ *                  ['filters'][]['string'] = string
+ *                               ['evalFilterStr'] = string
+ *                               ['reqexEqExprs'][]['var'] = ?VARNAME
+ *                                                 ['operator'] = (eq | ne)
+ *                                                 ['regex'] = string
+ *                               ['strEqExprs'][]['var'] = ?VARNAME
+ *                                               ['operator'] = (eq | ne)
+ *                                               ['value'] = string
+ *                                               ['value_type'] = ('variable' | 'URI' | 'Literal')
+ *                                               ['value_lang'] = string
+ *                                               ['value_dtype'] = string
+ *                               ['numExpr']['vars'][] = ?VARNAME
+ *                         ( [] stands for an integer index - 0..N )
+ * @access	private
+ */
+ var $parsedQuery;
+
+
+ /**
+ * Perform an RDQL Query on the given MemModel.
+ *
+ * @param   object  MemModel &$memModel
+ * @param   array   &$parsedQuery  (the same format as $this->parsedQuery)
+ * @param   boolean $returnNodes
+ * @return  array   [][?VARNAME] = object Node  (if $returnNodes = TRUE)
+ *      OR  array   [][?VARNAME] = string
+ *
+ * @access  public
+ */
+ function & queryModel(&$memModel, &$parsedQuery, $returnNodes = TRUE) {
+
+   $this->parsedQuery = $parsedQuery;
+
+   // find tuples matching all patterns
+   $res = $this->findTuplesMatchingAllPatterns($memModel);
+
+   // filter tuples
+   if (isset($parsedQuery['filters']))
+      $res = $this->filterTuples($res);
+
+   // select variables to be returned
+   $res = $this->selectVariables($res);
+
+   if(!$returnNodes)
+     return $this->toString($res);
+
+   return $res;
+ }
+ 
+
+ /**
+ * Find triples matching all patterns of an RDQL query and return an array
+ * with variables from all patterns and their corresponding values.
+ * The variable values returned are instances of object Node.
+ *
+ * @param   object  MemModel  &$memModel
+ * @return  array   [][?VARNAME] = object Node
+ *
+ * @access  private
+ */
+ function findTuplesMatchingAllPatterns(&$memModel) {
+
+   $resultSet = $this->findTuplesMatchingOnePattern($memModel, $this->parsedQuery['patterns'][0]);
+   for ($i=1; $i<count($this->parsedQuery['patterns']); $i++) {
+       $rs = $this->findTuplesMatchingOnePattern($memModel, $this->parsedQuery['patterns'][$i]);
+       $resultSet = $this->joinTuples($resultSet, $rs);
+   }
+   return $resultSet;
+ }
+
+
+/**
+ * Find tuples matching one pattern and return an array with pattern
+ * variables and their corresponding values (instances of object Node).
+ *
+ * @param   object  MemModel &$memModel
+ * @param   array  &$pattern ['subject']['value'] = VARorURI
+ *                           ['predicate']['value'] = VARorURI
+ *                           ['object']['value'] = VARorURIorLiterl
+ *                                     ['is_literal'] = boolean
+ *                                     ['l_lang'] = string
+ *                                     ['l_dtype'] = string
+ * @return  array   [][?VARNAME] = object Node
+ *
+ * @access  private
+ */
+ function findTuplesMatchingOnePattern(&$memModel, &$pattern) {
+
+   $resultSet = array();
+   $i = 0;
+   // parameters to be passed to the method findTriplesMatchingPattern
+   foreach ($pattern as $key => $v) {     
+     if ($v['value'] && $v['value']{0} == '?') {
+        if ($key == 'object') {
+            $param['object']['is_a'] = 'ANY';
+            $param['object']['string'] = 'ANY';
+            $param['object']['lang'] = NULL;
+            $param['object']['dtype'] = NULL;
+        } else         	
+     		$param[$key] = 'ANY';
+        $var[$i]['key'] = $key;
+        $var[$i++]['val'] = $v['value'];
+     }else
+        if (isset($v['is_literal'])) {
+          $param[$key]['is_a'] = 'Literal';
+          $param[$key]['string'] = $v['value'];
+          $param[$key]['lang'] = $v['l_lang'];
+          $param[$key]['dtype'] = $v['l_dtype'];
+        }else{
+          if ($key == 'object') {
+             $param[$key]['is_a'] = 'Resource';
+             $param[$key]['string'] = $v['value'];
+             $param[$key]['lang'] = NULL;
+             $param[$key]['dtype'] = NULL;
+          }else
+            $param[$key] = $v['value'];
+        }
+   }
+   
+   // find pattern internal bindings e.g. (?x, ?z, ?x)
+   $intBindings = NULL;
+   for ($i=0; $i<count($var); $i++)
+       foreach($var as $n => $v)
+         if ($i != $n && $var[$i]['val'] == $v['val'])
+            $intBindings[] = $var[$i]['key'];
+
+   // find triples of the $memModel matching $pattern
+   $resModel = $this->findTriplesMatchingPattern($memModel, $param['subject'],
+                                                            $param['predicate'],
+                                                            $param['object']['is_a'],
+                                                            $param['object']['string'],
+                                                            $param['object']['lang'],
+                                                            $param['object']['dtype'],
+                                                 $intBindings);
+
+   // set values of the pattern variables to be returned
+   if ($pattern['subject']['value']{0} == '?') {
+      $n = 0;
+      foreach ($resModel->triples as $triple)
+        $resultSet[$n++][$pattern['subject']['value']] = $triple->subj;
+   }
+   if ($pattern['predicate']['value']{0} == '?') {
+      $n = 0;
+      foreach ($resModel->triples as $triple)
+        $resultSet[$n++][$pattern['predicate']['value']] = $triple->pred;
+   }
+   if ($pattern['object']['value'] && $pattern['object']['value']{0} == '?') {
+      $n = 0;
+      foreach ($resModel->triples as $triple)
+        $resultSet[$n++][$pattern['object']['value']] = $triple->obj;
+   }
+   return $resultSet;
+ }
+
+
+/**
+ * Search in $memModel for triples matching one pattern from the WHERE clause.
+ * 'ANY' input for $subjLabel..$objLabel, $obj_is will match anything.
+ * NULL input for $objDtype will only match obj->dtype = NULL
+ * NULL input for $objLanguage will match obj->lang = NULL or anything if a
+ * literal is datatyped (except for XMLLiterals and plain literals)
+ * This method also checks internal bindings if provided.
+ *
+ * @param   object MemModel $memModel
+ * @param   string $subjLabel
+ * @param   string $predLabel
+ * @param   string $objLabel
+ * @param   string $obj_is
+ * @param   string $objLanguage
+ * @param   string $objDtype
+ * @param   array  $intBindings [] = string
+ * @return  object MemModel
+ * @access	private
+ */
+ function findTriplesMatchingPattern(&$memModel, $subjLabel, $predLabel, $obj_is,
+                                      $objLabel, $objLang, $objDtype, &$intBindings) {
+
+   $res = new MemModel();
+
+   if($memModel->isEmpty())
+    return $res;
+
+   if ($subjLabel=='ANY')
+   {
+       $subj=NULL;
+   } else
+   {
+       $subj=new Resource($subjLabel);
+   };
+   if ($predLabel=='ANY')
+   {
+       $pred=NULL;
+   } else
+   {
+       $pred=new Resource($predLabel);
+   }; 
+            
+   if ($objLabel=='ANY')
+   {
+       $obj=NULL;
+   } else
+   {
+       if ($obj_is == 'Literal')
+       {
+           $obj=new Literal($objLabel);
+           $obj->setDatatype($objDtype);
+           $obj->setLanguage($objLang);
+       } else {
+           $obj=new Resource($objLabel);
+       }
+   };
+   
+   $res=$memModel->find($subj,$pred,$obj);
+
+     if ($intBindings)
+              foreach ($res->triples as $triple)
+        {
+            if (!$this->_checkIntBindings($triple, $intBindings))
+            {
+                  $res->remove($triple);
+            }
+        }
+
+  return $res;
+}
+
+ 
+/**
+ * Perform an SQL-like inner join on two resultSets.
+ *
+ * @param   array   &$finalRes [][?VARNAME] = object Node
+ * @param   array   &$res      [][?VARNAME] = object Node
+ * @return  array              [][?VARNAME] = object Node
+ *
+ * @access  private
+ */
+ function joinTuples(&$finalRes, &$res) {
+
+   if (count($finalRes) == 0 || count($res) == 0)
+      return array();
+
+   // find joint variables and new variables to be added to $finalRes
+   $jointVars = array();
+   $newVars = array();
+   foreach ($res[0] as $varname => $node) {
+     if (array_key_exists($varname, $finalRes[0]))
+        $jointVars[] = $varname;
+     else
+        $newVars[] = $varname;
+   }
+
+   // eliminate rows of $finalRes in which the values of $jointVars do not have
+   // a corresponding row in $res.
+   foreach ($finalRes as $n => $fRes) {
+     foreach ($res as $i => $r) {
+       $ok = TRUE;
+       foreach ($jointVars as $j_varname)
+         if ($r[$j_varname] != $fRes[$j_varname]) {
+            $ok = FALSE;
+            break;
+         }
+       if ($ok)
+          break;
+     }
+     if (!$ok)
+        unset($finalRes[$n]);
+   }
+
+   // join $res and $finalRes
+   $joinedRes = array();
+   foreach ($res as $i => $r) {
+     foreach ($finalRes as $n => $fRes) {
+       $ok = TRUE;
+       foreach ($jointVars as $j_varname)
+         if ($r[$j_varname] != $fRes[$j_varname]) {
+            $ok = FALSE;
+            break;
+         }
+       if ($ok) {
+          $joinedRow = $finalRes[$n];
+          foreach($newVars as $n_varname)
+            $joinedRow[$n_varname] = $r[$n_varname];
+          $joinedRes[] = $joinedRow;
+       }
+     }
+   }
+   
+   return $joinedRes;
+ }
+ 
+
+/**
+ * Filter the result-set of query variables by evaluating each filter from the
+ * AND clause of the RDQL query.
+ *
+ * @param   array  &$finalRes  [][?VARNAME] = object Node
+ * @return  array  [][?VARNAME] = object Node
+ * @access	private
+ */
+ function filterTuples(&$finalRes) {
+
+   foreach ($this->parsedQuery['filters'] as $filter) {
+
+      foreach ($finalRes as $n => $fRes) {
+        $evalFilterStr = $filter['evalFilterStr'];
+
+        // evaluate regex equality expressions of each filter
+        foreach ($filter['regexEqExprs'] as $i => $expr) {
+
+          preg_match($expr['regex'], $fRes[$expr['var']]->getLabel(), $match);
+          $op = substr($expr['operator'], 0,1);
+          if (($op != '!' && !isset($match[0])) || ($op == '!' && isset($match[0])))
+             $evalFilterStr = str_replace("##RegEx_$i##", 'FALSE', $evalFilterStr);
+          else
+             $evalFilterStr = str_replace("##RegEx_$i##", 'TRUE', $evalFilterStr);
+
+        }
+
+        // evaluate string equality expressions
+        foreach ($filter['strEqExprs'] as $i => $expr) {
+
+          $exprBoolVal = 'FALSE';
+          
+          switch ($expr['value_type']) {
+
+            case 'variable':
+                 if (($fRes[$expr['var']] == $fRes[$expr['value']] && $expr['operator'] == 'eq') ||
+                     ($fRes[$expr['var']] != $fRes[$expr['value']] && $expr['operator'] == 'ne'))
+                    $exprBoolVal = 'TRUE';
+                 break;
+                 
+            case 'URI':
+
+                 if (is_a($fRes[$expr['var']], 'Literal')) {
+                    if ($expr['operator'] == 'ne')
+                       $exprBoolVal = 'TRUE';
+                    break;
+                 }
+
+                 if (($fRes[$expr['var']]->getLabel() == $expr['value'] && $expr['operator'] == 'eq') ||
+                     ($fRes[$expr['var']]->getLabel() != $expr['value'] && $expr['operator'] == 'ne'))
+                    $exprBoolVal = 'TRUE';
+                 break;
+                 
+            case 'Literal':
+
+                 if (!is_a($fRes[$expr['var']], 'Literal')) {
+                    if ($expr['operator'] == 'ne')
+                       $exprBoolVal = 'TRUE';
+                    break;
+                 }
+
+                 $filterLiteral= new Literal($expr['value'],$expr['value_lang']);
+                 $filterLiteral->setDatatype($expr['value_dtype']);
+                 
+                $equal=$fRes[$expr['var']]->equals($filterLiteral);
+/*                 if ($fRes[$expr['var']]->getLabel() == $expr['value'] &&
+                     $fRes[$expr['var']]->getDatatype() == $expr['value_dtype']) {
+                     
+                    $equal = TRUE;
+                     
+                    // Lang tags only differentiate literals in rdf:XMLLiterals and plain literals.
+                    // Therefore if a literal is datatyped ignore the language tag.
+                    if ((($expr['value_dtype'] == NULL) ||
+                         ($expr['value_dtype'] == 'http://www.w3.org/1999/02/22-rdf-syntax-ns#XMLLiteral') ||
+                         ($expr['value_dtype'] == 'http://www.w3.org/2001/XMLSchema#string')) &&
+                        (($fRes[$expr['var']]->getLanguage() != $expr['value_lang'])))
+                        
+                        $equal = FALSE;
+                 }else
+                    $equal = FALSE;
+     */               
+                 if (($equal && $expr['operator'] == 'eq') ||
+                     (!$equal && $expr['operator'] == 'ne'))
+                    $exprBoolVal = 'TRUE';
+                 else
+                    $exprBoolVal = 'FALSE';
+
+          }
+          $evalFilterStr = str_replace("##strEqExpr_$i##", $exprBoolVal, $evalFilterStr);
+       }
+
+        // evaluate numerical expressions
+        foreach ($filter['numExprVars'] as $varName) {
+          $varValue = "'" .$fRes[$varName]->getLabel() ."'";
+          $evalFilterStr = str_replace($varName, $varValue, $evalFilterStr);
+        }
+
+        eval("\$filterBoolVal = $evalFilterStr; \$eval_filter_ok = TRUE;");
+        if (!isset($eval_filter_ok))
+           trigger_error(RDQL_AND_ERR ."'" .htmlspecialchars($filter['string']) ."'", E_USER_ERROR);
+
+        if (!$filterBoolVal)
+           unset($finalRes[$n]);
+      }
+   }
+
+   return $finalRes;
+ }
+
+
+/**
+ * Remove all conditional variables from the result-set and leave only variables
+ * specified in the SELECT clause of the RDQL query.
+ *
+ * @param   array  &$finalRes  [][?VARNAME] = object Node
+ * @return  array  [][?VARNAME] = object Node
+ * @access	private
+ */
+ function selectVariables(&$finalRes) {
+
+   // if nothing has been found return only one row of $finalRes
+   // with select variables having empty values
+   if (count($finalRes) == 0) {
+      foreach ($this->parsedQuery['selectVars'] as $selectVar)
+         $finalRes[0][$selectVar] = NULL;
+      return $finalRes;
+   }
+   
+   // return only selectVars in the same order as given in the RDQL query
+   // and reindex $finalRes.
+   $n = 0;
+   foreach($finalRes as $key => $val) {
+     foreach ($this->parsedQuery['selectVars'] as $selectVar)
+       $resultSet[$n][$selectVar] = $val[$selectVar];
+     unset($finalRes[$key]);
+     ++$n;
+   }
+
+   return $resultSet;
+ }
+
+
+/**
+ * Convert the variable values of $finalRes from objects to their string serialization.
+ *
+ * @param   array  &$finalRes  [][?VARNAME] = object Node
+ * @return  array  [][?VARNAME] = string
+ * @access	private
+ */
+ function toString(&$finalRes) {
+
+   foreach ($finalRes as $n => $tuple)
+     foreach ($tuple as $varname => $node) {
+       if (is_a($node, 'Resource'))
+          $res[$n][$varname] = '<' .$node->getLabel() .'>';
+       elseif (is_a($node, 'Literal')) {
+          $res[$n][$varname] = '"' .$node->getLabel() .'"';
+          if ($node->getLanguage())
+             $res[$n][$varname] .= ' (xml:lang="' .$node->getLanguage() .'")';
+          if ($node->getDatatype())
+             $res[$n][$varname] .= ' (rdf:datatype="' .$node->getDatatype() .'")';
+       }else
+          $res[$n][$varname] = $node;
+     }
+   return $res;
+ }
+
+
+/**
+ * Check if the given triple meets pattern internal bindings
+ * e.g. (?x, ?z, ?x) ==> statement subject must be identical with the statement object
+ *
+ * @param   object statement &$triple
+ * @param   array  &$intBindings [] = string
+ * @return  boolean
+ * @access	private
+ */
+ function _checkIntBindings (&$triple, &$intBindings) {
+
+   if (in_array('subject', $intBindings)) {
+      if (in_array('predicate', $intBindings))
+         if ($triple->subj != $triple->pred)
+            return FALSE;
+      if (in_array('object', $intBindings)) {
+         if (is_a($triple->obj, 'Literal'))
+            return FALSE;
+         elseif ($triple->subj != $triple->obj)
+            return FALSE;
+      }
+      return TRUE;
+   }
+   if (in_array('predicate', $intBindings)) {
+      if (is_a($triple->obj, 'Literal'))
+         return FALSE;
+      elseif ($triple->pred != $triple->obj)
+             return FALSE;
+      return TRUE;
+   }
+ }
+
+
+/**
+ * Check if the lang and dtype of the passed object Literal are equal $lang and $dtype
+ * !!! Language only differentiates literals in rdf:XMLLiterals and plain literals (xsd:string).
+ * !!! Therefore if a literal is datatyped ignore the language.
+ *
+ * @param  object  Literal $literal
+ * @param  string  $dtype1
+ * @param  string  $dtype2
+ * @return boolean
+ * @access private
+ */
+ function _equalsLangDtype ($literal, $lang, $dtype) {
+
+   if ($dtype == $literal->getDatatype()) {
+      if (($dtype == NULL ||
+           $dtype == 'http://www.w3.org/2001/XMLSchema#string' ||
+           $dtype == 'http://www.w3.org/1999/02/22-rdf-syntax-ns#XMLLiteral') &&
+          ($lang != $literal->getLanguage()))
+         return FALSE;
+      return TRUE;
+   }
+   return FALSE;
+ }
+ 
+ 
+} // end: Class RdqlMemEngine
+
+?>
Index: /Dev/trunk/rdfapi/rdql/RdqlParser.php
===================================================================
--- /Dev/trunk/rdfapi/rdql/RdqlParser.php	(revision 12)
+++ /Dev/trunk/rdfapi/rdql/RdqlParser.php	(revision 12)
@@ -0,0 +1,1063 @@
+<?php
+
+// ----------------------------------------------------------------------------------
+// Class: RdqlParser
+// ----------------------------------------------------------------------------------
+
+/**
+ * This class contains methods for parsing an Rdql query string into PHP variables.
+ * The output of the RdqlParser is an array with variables and constraints
+ * of each query clause (Select, From, Where, And, Using).
+ * To perform an RDQL query this array has to be passed to the RdqlEngine.
+ *
+ * @version  $Id: RdqlParser.php 282 2006-06-08 06:25:14Z tgauss $
+ * @author   Radoslaw Oldakowski <radol@gmx.de>
+ *
+ * @package rdql
+ * @access public
+ */
+
+
+Class RdqlParser extends Object{
+
+/**
+ * Parsed query variables and constraints.
+ * { } are only used within the parser class and are not returned as parsed query.
+ * ( [] stands for an integer index - 0..N )  
+ *
+ * @var     array   ['selectVars'][] = ?VARNAME
+ *                  ['sources'][]{['value']} = URI | QName
+ *								 {['is_qname'] = boolean}
+ *                  ['patterns'][]['subject']['value'] = VARorURI
+ *											{['is_qname'] = boolean}
+ *                                ['predicate']['value'] = VARorURI
+ *											  {['is_qname'] = boolean}
+ *                                ['object']['value'] = VARorURIorLiterl
+ *							     		   {['is_qname'] = boolean} 
+ *                                          ['is_literal'] = boolean
+ *                                          ['l_lang'] = string
+ *                                          ['l_dtype'] = string
+ *                                         {['l_dtype_is_qname'] = boolean}
+ *                  ['filters'][]['string'] = string
+ *                               ['evalFilterStr'] = string
+ *                               ['reqexEqExprs'][]['var'] = ?VARNAME
+ *                                                 ['operator'] = (eq | ne)
+ *                                                 ['regex'] = string
+ *                               ['strEqExprs'][]['var'] = ?VARNAME
+ *                                               ['operator'] = (eq | ne)
+ *                                               ['value'] = string
+ *                                               ['value_type'] = ('variable' | 'URI' | 'QName' | 'Literal')
+ *                                               ['value_lang'] = string
+ *                                               ['value_dtype'] = string
+ *                                              {['value_dtype_is_qname'] = boolean}
+ *                               ['numExpr']['vars'][] = ?VARNAME
+ *                 {['ns'][PREFIX] = NAMESPACE}    
+ * @access	private
+ */
+ var $parsedQuery;
+
+
+/**
+ * Query string divided into a sequence of tokens.
+ * A token is either: ' ' or "\n" or "\r" or "\t" or ',' or '(' or ')'
+ * or a string containing any characters except from the above.
+ *
+ * @var     array
+ * @access	private
+ */
+ var $tokens;
+
+
+/**
+ * Parse the given RDQL query string and return an array with query variables and constraints.
+ *
+ * @param   string  $queryString
+ * @return  array   $this->parsedQuery
+ * @access	public
+ */
+ function & parseQuery($queryString) {
+
+   $cleanQueryString = $this->removeComments($queryString);
+   $this->tokenize($cleanQueryString);
+   $this->startParsing();
+   if ($this->parsedQuery['selectVars'][0] == '*')
+      $this->parsedQuery['selectVars'] = $this->findAllQueryVariables();
+   else
+      $this->_checkSelectVars();
+   $this->replaceNamespacePrefixes();
+
+   return $this->parsedQuery;
+ }
+
+
+/**
+ *  Remove comments from the passed query string.
+ *
+ *  @param  string  $query
+ *  @return string
+ *  @throws PHPError
+ *  @access private
+ */
+ function removeComments($query) {
+ 
+   $last = strlen($query)-1;
+   $query .= ' ';
+   $clean = '';
+   for ($i=0; $i<=$last; $i++) {
+     // don't search for comments inside a 'literal'@lang^^dtype or "literal"@lang^^dtype
+     if ($query{$i} == "'" || $query{$i} == '"') {
+        $quotMark = $query{$i};
+        do
+          $clean .= $query{$i++};
+        while($i < $last && $query{$i} != $quotMark);
+        $clean .= $query{$i};
+        // language
+        if ($query{$i+1} == '@') {
+           do{
+             if ($query{$i+1} == '^' && $query{$i+2} == '^')
+                break;
+             $clean .= $query{++$i};
+           }while ($i < $last && $query{$i} != ' '  && $query{$i} != "\t"
+                              && $query{$i} != "\n" && $query{$i} != "\r");
+        }
+        // datatype
+        if ($query{$i+1} == '^' && $query{$i+2} == '^') {
+            do
+              $clean .= $query{++$i};
+            while ($i < $last && $query{$i} != ' '  && $query{$i} != "\t"
+                             && $query{$i} != "\n" && $query{$i} != "\r" );
+        }
+     // don't search for comments inside an <URI> either
+     }elseif ($query{$i} == '<') {
+        do{
+           $clean .= $query{$i++};
+        }while($i < $last && $query{$i} != '>');
+        $clean .= $query{$i};
+     }elseif ($query{$i} == '/') {
+        // clear: // comment
+        if ($i < $last && $query{$i+1} == '/') {
+            while($i < $last && $query{$i} != "\n" && $query{$i} != "\r")
+              ++$i;
+            $clean .= ' ';
+        // clear: /*comment*/
+        }elseif ($i < $last-2 && $query{$i+1} == '*') {
+            $i += 2;
+            while($i < $last  && ($query{$i} != '*' || $query{$i+1} != '/'))
+              ++$i;
+            if ($i >= $last && ($query{$last-1} != '*' || $query{$last} != '/'))
+               trigger_error(RDQL_SYN_ERR .": unterminated comment - '*/' missing", E_USER_ERROR);
+            ++$i;
+        }else
+          $clean .= $query{$i};
+     }else
+        $clean .= $query{$i};
+   }
+   return $clean;
+ }
+
+
+/**
+ * Divide the query string into tokens.
+ * A token is either: ' ' or "\n" or "\r" or '\t' or ',' or '(' or ')'
+ * or a string containing any character except from the above.
+ *
+ * @param   string  $queryString
+ * @access	private
+ */
+ function tokenize($queryString) {
+
+   $queryString = trim($queryString, " \r\n\t");
+   $specialChars = array (" ", "\t", "\r", "\n", ",", "(", ")");
+   $len = strlen($queryString);
+   $this->tokens[0]='';
+   $n = 0;
+
+   for ($i=0; $i<$len; ++$i) {
+       if (!in_array($queryString{$i}, $specialChars))
+          $this->tokens[$n] .= $queryString{$i};
+       else {
+          if ($this->tokens[$n] != '')
+             ++$n;
+          $this->tokens[$n] = $queryString{$i};
+          $this->tokens[++$n] = '';
+       }
+   }
+ }
+
+
+/**
+ * Start parsing of the tokenized query string.
+ *
+ * @access private
+ */
+ function startParsing() {
+
+   $this->parseSelect();
+ }
+
+
+/**
+ * Parse the SELECT clause of an Rdql query.
+ * When the parsing of the SELECT clause is finished, this method will call
+ * a suitable method to parse the subsequent clause.
+ *
+ * @throws	PhpError
+ * @access	private
+ */
+  function parseSelect() {
+
+   $this->_clearWhiteSpaces();
+
+   // Check if the queryString contains a "SELECT" token
+   if (strcasecmp('SELECT', current($this->tokens)))
+      trigger_error(RDQL_SEL_ERR  ."'" .current($this->tokens)
+                                  ."' - SELECT keyword expected", E_USER_ERROR);
+   unset($this->tokens[key($this->tokens)]);
+   $this->_clearWhiteSpaces();
+
+   // Parse SELECT *
+   if (current($this->tokens) == '*') {
+      unset($this->tokens[key($this->tokens)]);
+      $this->parsedQuery['selectVars'][0] = '*';
+      $this->_clearWhiteSpaces();
+      if (strcasecmp('FROM', current($this->tokens))
+          && strcasecmp('SOURCE', current($this->tokens))
+          && strcasecmp('WHERE', current($this->tokens)))
+        trigger_error(RDQL_SYN_ERR .": '" .htmlspecialchars(current($this->tokens))
+                               ."' - SOURCE or WHERE clause expected", E_USER_ERROR);
+   }
+
+   // Parse SELECT ?Var (, ?Var)*
+   $commaExpected = FALSE;
+   $comma = FALSE;
+   while (current($this->tokens) != NULL) {
+     $k = key($this->tokens);
+     $token = $this->tokens[$k];
+
+     switch ($token) {
+        case ',': if (!$commaExpected)
+                     trigger_error(RDQL_SEL_ERR ." ',' - unexpected comma", E_USER_ERROR);
+                  $comma = TRUE;
+                  $commaExpected = FALSE;
+                  break;
+        case '(':
+        case ')': trigger_error(RDQL_SEL_ERR ." '$token' - illegal input", E_USER_ERROR);
+                  break;
+        default :
+                  if (!strcasecmp('FROM', $token) || !strcasecmp('SOURCE', $token)) {
+                     if ($comma)
+                        trigger_error(RDQL_SEL_ERR ." ',' - unexpected comma", E_USER_ERROR);
+                     unset($this->tokens[$k]);
+                     return $this->parseFrom();
+                  }elseif (!strcasecmp('WHERE', $token) && !$comma) {
+                     if ($comma)
+                        trigger_error(RDQL_SEL_ERR ." ',' - unexpected comma", E_USER_ERROR);
+                     unset($this->tokens[$k]);
+                     return $this->parseWhere();
+                  }
+                  if ($token{0} == '?') {
+                     $this->parsedQuery['selectVars'][] = $this->_validateVar($token, RDQL_SEL_ERR);
+                     $commaExpected = TRUE;
+                     $comma = FALSE;
+                  }else
+                     trigger_error(RDQL_SEL_ERR ." '$token' - '?' missing", E_USER_ERROR);
+     }
+     unset($this->tokens[$k]);
+     $this->_clearWhiteSpaces();
+   }
+   trigger_error(RDQL_SYN_ERR . ': WHERE clause missing', E_USER_ERROR);
+ }
+
+
+/**
+ * Parse the FROM/SOURCES clause of an Rdql query
+ * When the parsing of this clause is finished, parseWhere() will be called.
+ *
+ * @throws	PhpError
+ * @access	private
+ */
+ function parseFrom() {
+
+   $comma = FALSE;
+   $commaExpected = FALSE;
+   $i = -1;
+   while (current($this->tokens) != NULL) {
+
+      $this->_clearWhiteSpaces();
+      if (!strcasecmp('WHERE', current($this->tokens)) && count($this->parsedQuery['sources']) != 0) {
+         if ($comma)
+            trigger_error(RDQL_SEL_ERR ." ',' - unexpected comma", E_USER_ERROR);
+         unset($this->tokens[key($this->tokens)]);
+         return $this->parseWhere();
+      }
+      if (current($this->tokens) == ',') {
+         if ($commaExpected) {
+            $comma = TRUE;
+            $commaExpected = FALSE;
+            unset($this->tokens[key($this->tokens)]);
+         }else
+            trigger_error(RDQL_SRC_ERR ."',' - unecpected comma", E_USER_ERROR);
+      }else{
+        $token = current($this->tokens);
+        $this->parsedQuery['sources'][++$i]['value'] = $this->_validateURI($token, RDQL_SRC_ERR);
+        if ($token{0} != '<')
+        	$this->parsedQuery['sources'][$i]['is_qname'] = TRUE;
+        $commaExpected = TRUE;
+        $comma = FALSE;
+      }
+   }
+   trigger_error(RDQL_SYN_ERR .': WHERE clause missing', E_USER_ERROR);
+ }
+
+
+/**'
+ * Parse the WHERE clause of an Rdql query.
+ * When the parsing of the WHERE clause is finished, this method will call
+ * a suitable method to parse the subsequent clause if provided.
+ *
+ * @throws	PhpError
+ * @access	private
+ */
+ function parseWhere() {
+
+   $comma = FALSE;
+   $commaExpected = FALSE;
+   $i=0;
+
+   do {
+     $this->_clearWhiteSpaces();
+     if (!strcasecmp('AND', current($this->tokens))
+         && count($this->parsedQuery['patterns']) != 0){
+        if ($comma)
+            trigger_error(RDQL_WHR_ERR ." ',' - unexpected comma", E_USER_ERROR);
+        unset($this->tokens[key($this->tokens)]);
+        return $this->parseAnd();
+     }elseif (!strcasecmp('USING', current($this->tokens))
+              && count($this->parsedQuery['patterns']) != 0) {
+        if ($comma)
+            trigger_error(RDQL_WHR_ERR ." ',' - unexpected comma", E_USER_ERROR);
+        unset($this->tokens[key($this->tokens)]);
+        return $this->parseUsing();
+     }
+
+     if (current($this->tokens) == ',') {
+        $comma = TRUE;
+        $this->_checkComma($commaExpected, RDQL_WHR_ERR);
+
+     }else{
+
+        if (current($this->tokens) != '(')
+           trigger_error(RDQL_WHR_ERR ."'" .current($this->tokens)
+                                      ."' - '(' expected", E_USER_ERROR);
+        unset($this->tokens[key($this->tokens)]);
+        $this->_clearWhiteSpaces();
+
+        $this->parsedQuery['patterns'][$i]['subject'] = $this->_validateVarUri(current($this->tokens));
+        $this->_checkComma(TRUE, RDQL_WHR_ERR);
+        $this->parsedQuery['patterns'][$i]['predicate'] = $this->_validateVarUri(current($this->tokens));
+        $this->_checkComma(TRUE, RDQL_WHR_ERR);
+        $this->parsedQuery['patterns'][$i++]['object'] = $this->_validateVarUriLiteral(current($this->tokens));
+        $this->_clearWhiteSpaces();
+
+       if (current($this->tokens) != ')')
+          trigger_error(RDQL_WHR_ERR ."'" .current($this->tokens) ."' - ')' expected", E_USER_ERROR);
+       unset($this->tokens[key($this->tokens)]);
+       $this->_clearWhiteSpaces();
+       $commaExpected = TRUE;
+       $comma = FALSE;
+     }
+   }while(current($this->tokens) != NULL);
+
+   if ($comma)
+      trigger_error(RDQL_WHR_ERR ." ',' - unexpected comma", E_USER_ERROR);
+ }
+
+
+/**
+ * Parse the AND clause of an Rdql query
+ *
+ * @throws	PhpError
+ * @access	private
+ * @todo clear comments
+ */
+ function parseAnd() {
+
+   $this->_clearWhiteSpaces();
+   $n = 0;
+   $filterStr = '';
+
+   while(current($this->tokens) != NULL) {
+     $k = key($this->tokens);
+     $token = $this->tokens[$k];
+
+     if (!strcasecmp('USING', $token)) {
+        $this->parseFilter($n, $filterStr);
+        unset($this->tokens[$k]);
+        return $this->parseUsing();
+     }elseif ($token == ',') {
+        $this->parseFilter($n, $filterStr);
+        $filterStr = '';
+        $token = '';
+        ++$n;
+     }
+     $filterStr .= $token;
+     unset($this->tokens[$k]);
+   }
+   $this->parseFilter($n, $filterStr);
+ }
+ 
+ 
+/**
+ * Parse the USING clause of an Rdql query
+ *
+ * @throws	PhpError
+ * @access	private
+ */
+ function parseUsing() {
+
+  $commaExpected = FALSE;
+  $comma = FALSE;
+
+  do {
+    $this->_clearWhiteSpaces();
+    if (current($this->tokens) == ',') {
+        $comma = TRUE;
+        $this->_checkComma($commaExpected, RDQL_USG_ERR);
+    }else{
+       $prefix = $this->_validatePrefix(current($this->tokens));
+       $this->_clearWhiteSpaces();
+
+       if (strcasecmp('FOR', current($this->tokens)))
+          trigger_error(RDQL_USG_ERR ." keyword: 'FOR' missing in the namespace declaration: '", E_USER_ERROR);
+       unset($this->tokens[key($this->tokens)]);
+       $this->_clearWhiteSpaces();
+
+       $this->parsedQuery['ns'][$prefix] = $this->_validateUri(current($this->tokens), RDQL_USG_ERR);
+       $this->_clearWhiteSpaces();
+       $commaExpected = TRUE;
+       $comma = FALSE;
+    }
+  }while(current($this->tokens) != NULL);
+
+  if ($comma)
+      trigger_error(RDQL_WHR_ERR ." ',' - unexpected comma", E_USER_ERROR);
+ }
+
+
+/**
+ * Check if a filter from the AND clause contains an equal number of '(' and ')'
+ * and parse filter expressions.
+ *
+ * @param   integer $n
+ * @param   string  $filter
+ * @throws  PHPError
+ * @access	private
+ */
+ function parseFilter($n, $filter) {
+
+   if ($filter == NULL)
+      trigger_error(RDQL_AND_ERR ." ',' - unexpected comma", E_USER_ERROR);
+   $paren = substr_count($filter, '(') - substr_count($filter, ')');
+   if ($paren != 0) {
+      if ($paren > 0)
+         $errorMsg = "'" .htmlspecialchars($filter) ."' - ')' missing ";
+      elseif ($paren < 0)
+         $errorMsg = "'" .htmlspecialchars($filter) ."' - too many ')' ";
+      trigger_error(RDQL_AND_ERR .$errorMsg, E_USER_ERROR);
+   }
+
+   $this->parsedQuery['filters'][$n] = $this->parseExpressions($filter);
+ }
+
+
+/**
+ * Parse expressions inside the passed filter:
+ * 1)  regex equality expressions:    ?var [~~ | =~ | !~ ] REG_EX
+ * 2a) string equality expressions:   ?var  [eq | ne] "literal"@lang^^dtype.
+ * 2b) string equality expressions:   ?var [eq | ne] <URI> or ?var [eq | ne] prefix:local_name
+ * 3)  numerical expressions: e.q.    (?var1 - ?var2)*4 >= 20
+ *
+ * In cases 1-2 parse each expression of the given filter into an array of variables.
+ * For each parsed expression put a place holder (e.g. ##RegEx_1##) into the filterStr.
+ * The RDQLengine will then replace each place holder with the outcomming boolean value
+ * of the corresponding expression.
+ * The remaining filterStr contains only numerical expressions and place holders.
+ *
+ * @param   string  $filteStr
+ * @return  array   ['string'] = string
+ *                  ['evalFilterStr'] = string
+ *                  ['reqexEqExprs'][]['var'] = ?VARNAME
+ *                                    ['operator'] = (eq | ne)
+ *                                    ['regex'] = string
+ *                  ['strEqExprs'][]['var'] = ?VARNAME
+ *                                 ['operator'] = (eq | ne)
+ *                                 ['value'] = string
+ *                                 ['value_type'] = ('variable' | 'URI' | 'QName'| 'Literal')
+ *                                 ['value_lang'] = string
+ *                                 ['value_dtype'] = string
+ *								   ['value_dtype_is_qname'] = boolean
+ *                  ['numExpr']['vars'][] = ?VARNAME
+ * @access	private
+ */
+ function parseExpressions($filterStr) {
+
+   $parsedFilter['string'] = $filterStr;
+   $parsedFilter['regexEqExprs'] = array();
+   $parsedFilter['strEqExprs'] = array();
+   $parsedFilter['numExprVars'] = array();
+
+   // parse regex string equality expressions, e.g. ?x ~~ !//foo.com/r!i
+   $reg_ex  = "/(\?[a-zA-Z0-9_]+)\s+([~!=]~)\s+(['|\"])?([^\s'\"]+)(['|\"])?/";
+   preg_match_all($reg_ex, $filterStr, $eqExprs);
+   foreach ($eqExprs[0] as $i => $eqExpr) {
+     $this->_checkRegExQuotation($filterStr, $eqExprs[3][$i], $eqExprs[5][$i]);
+     $parsedFilter['regexEqExprs'][$i]['var'] = $this->_isDefined($eqExprs[1][$i]);
+     $parsedFilter['regexEqExprs'][$i]['operator'] = $eqExprs[2][$i];
+     $parsedFilter['regexEqExprs'][$i]['regex'] = $eqExprs[4][$i];
+
+     $filterStr = str_replace($eqExpr, " ##RegEx_$i## ", $filterStr);
+   }
+
+   // parse ?var  [eq | ne] "literal"@lang^^dtype
+   $reg_ex  = "/(\?[a-zA-Z0-9_]+)\s+(eq|ne)\s+(\'[^\']*\'|\"[^\"]*\")";
+   $reg_ex .= "(@[a-zA-Z]+)?(\^{2}\S+:?\S+)?/i";
+   preg_match_all($reg_ex, $filterStr, $eqExprs);
+   foreach ($eqExprs[0] as $i => $eqExpr) {
+     $parsedFilter['strEqExprs'][$i]['var'] = $this->_isDefined($eqExprs[1][$i]);#
+     $parsedFilter['strEqExprs'][$i]['operator'] = strtolower($eqExprs[2][$i]);
+     $parsedFilter['strEqExprs'][$i]['value'] = trim($eqExprs[3][$i],"'\"");
+     $parsedFilter['strEqExprs'][$i]['value_type'] = 'Literal';
+     $parsedFilter['strEqExprs'][$i]['value_lang'] = substr($eqExprs[4][$i], 1);     
+     $dtype = substr($eqExprs[5][$i], 2);
+     if ($dtype) {
+        $parsedFilter['strEqExprs'][$i]['value_dtype'] = $this->_validateUri($dtype, RDQL_AND_ERR);
+        if ($dtype{0} != '<')
+	       $parsedFilter['strEqExprs'][$i]['value_dtype_is_qname'] = TRUE; 	 
+     }else 
+        $parsedFilter['strEqExprs'][$i]['value_dtype'] = '';
+
+     $filterStr = str_replace($eqExprs[0][$i], " ##strEqExpr_$i## ", $filterStr);
+   }
+   
+   // parse ?var [eq | ne] ?var
+   $ii = count($parsedFilter['strEqExprs']);
+   $reg_ex  = "/(\?[a-zA-Z0-9_]+)\s+(eq|ne)\s+(\?[a-zA-Z0-9_]+)/i";
+   preg_match_all($reg_ex, $filterStr, $eqExprs);
+   foreach ($eqExprs[0] as $i => $eqExpr) {
+     $parsedFilter['strEqExprs'][$ii]['var'] = $this->_isDefined($eqExprs[1][$i]);
+     $parsedFilter['strEqExprs'][$ii]['operator'] = strtolower($eqExprs[2][$i]);
+     $parsedFilter['strEqExprs'][$ii]['value'] = $this->_isDefined($eqExprs[3][$i]);
+     $parsedFilter['strEqExprs'][$ii]['value_type'] = 'variable';
+
+     $filterStr = str_replace($eqExprs[0][$i], " ##strEqExpr_$ii## ", $filterStr);
+     $ii++;
+   }
+
+   // parse ?var [eq | ne] <URI> or ?var [eq | ne] prefix:local_name
+   $reg_ex  = "/(\?[a-zA-Z0-9_]+)\s+(eq|ne)\s+((<\S+>)|(\S+:\S*))/i";
+   preg_match_all($reg_ex, $filterStr, $eqExprs);
+   foreach ($eqExprs[0] as $i => $eqExpr) {
+     $parsedFilter['strEqExprs'][$ii]['var'] = $this->_isDefined($eqExprs[1][$i]);
+     $parsedFilter['strEqExprs'][$ii]['operator'] = strtolower($eqExprs[2][$i]);
+     if ($eqExprs[4][$i]) {
+     	$parsedFilter['strEqExprs'][$ii]['value'] = trim($eqExprs[4][$i], "<>");
+     	$parsedFilter['strEqExprs'][$ii]['value_type'] = 'URI';
+     }else if($eqExprs[5][$i]){
+     	$this->_validateQName($eqExprs[5][$i], RDQL_AND_ERR);
+     	$parsedFilter['strEqExprs'][$ii]['value'] = $eqExprs[5][$i];
+     	$parsedFilter['strEqExprs'][$ii]['value_type'] = 'QName';
+     }
+
+     $filterStr = str_replace($eqExprs[0][$i], " ##strEqExpr_$ii## ", $filterStr);
+     $ii++;
+   }  
+   
+   $parsedFilter['evalFilterStr'] = $filterStr;
+
+   // all that is left are numerical expressions and place holders for the above expressions
+   preg_match_all("/\?[a-zA-Z0-9_]+/", $filterStr, $vars);
+   foreach ($vars[0] as $var) {
+     $parsedFilter['numExprVars'][] = $this->_isDefined($var);
+   }
+
+   return $parsedFilter;
+ }
+
+
+/**
+ * Find all query variables used in the WHERE clause.
+ *
+ * @return  array [] = ?VARNAME
+ * @access	private
+ */
+ function findAllQueryVariables() {
+
+   $vars = array();
+   foreach ($this->parsedQuery['patterns'] as $pattern) {
+     $count = 0;
+     foreach ($pattern as $v) {
+       if ($v['value'] && $v['value']{0} == '?') {
+          ++$count;
+          if (!in_array($v['value'], $vars))
+             $vars[] = $v['value'];
+       }
+     }
+     if (!$count)
+        trigger_error(RDQL_WHR_ERR .'pattern contains no variables', E_USER_ERROR);
+   }
+
+   return $vars;
+ }
+
+
+/**
+ * Replace all namespace prefixes in the pattern and constraint clause of an rdql query
+ * with the namespaces declared in the USING clause and default namespaces.
+ *
+ * @access	private
+ */
+ function replaceNamespacePrefixes() {
+
+   global $default_prefixes;
+
+   if (!isset($this->parsedQuery['ns']))
+      $this->parsedQuery['ns'] = array();
+
+   // add default namespaces
+   // if in an rdql query a reserved prefix (e.g. rdf: rdfs:) is used
+   // it will be overridden by the default namespace defined in constants.php
+   $this->parsedQuery['ns'] = array_merge($this->parsedQuery['ns'], $default_prefixes);
+
+   // replace namespace prefixes in the FROM clause
+   if (isset($this->parsedQuery['sources']))
+   	  foreach ($this->parsedQuery['sources'] as $n => $source) {
+   	  	if (isset($source['is_qname']))
+   	  	   $this->parsedQuery['sources'][$n] = $this->_replaceNamespacePrefix($source['value'], RDQL_SRC_ERR);
+   	  	else {
+   	  	   foreach ($this->parsedQuery['ns'] as $prefix => $uri) 
+   	  	     $source['value'] = preg_replace("$prefix:", $uri, $source['value']);   	  	   	  	   	  	     
+   	  	   $this->parsedQuery['sources'][$n] = $source['value'];
+   	  	}   	  	   
+   	  	   
+   	  }
+   
+   // replace namespace prefixes in the where clause
+   foreach ($this->parsedQuery['patterns'] as $n => $pattern) {
+     foreach ($pattern as $key => $v)
+       if ($v['value'] && $v['value']{0} != '?') {
+       	  if (isset($v['is_qname'])) {      	  	       	  	
+          	 $this->parsedQuery['patterns'][$n][$key]['value']
+          	 	= $this->_replaceNamespacePrefix($v['value'], RDQL_WHR_ERR);
+          	 unset($this->parsedQuery['patterns'][$n][$key]['is_qname']);	 
+       	  } else { // is quoted URI (== <URI>) or Literal          	
+              if (isset($this->parsedQuery['patterns'][$n][$key]['is_literal'])) {
+              	 if (isset($this->parsedQuery['patterns'][$n][$key]['l_dtype_is_qname'])) {   
+          	 		$this->parsedQuery['patterns'][$n][$key]['l_dtype']
+          	 			= $this->_replaceNamespacePrefix($v['l_dtype'], RDQL_WHR_ERR);          	 			
+          	 		unset($this->parsedQuery['patterns'][$n][$key]['l_dtype_is_qname']);	
+              	 }else {
+              	   foreach ($this->parsedQuery['ns'] as $prefix => $uri)
+                     $this->parsedQuery['patterns'][$n][$key]['l_dtype']
+                       = preg_replace("'$prefix:'", $uri, $this->parsedQuery['patterns'][$n][$key]['l_dtype']);
+              	 }     
+       	      }else {
+                 foreach ($this->parsedQuery['ns'] as $prefix => $uri)
+               	   $this->parsedQuery['patterns'][$n][$key]['value']
+                     = preg_replace("'$prefix:'", $uri, $this->parsedQuery['patterns'][$n][$key]['value']);
+              }
+       	  }
+       }
+   }
+
+   // replace prefixes in the constraint clause
+   if (isset($this->parsedQuery['filters']))
+      foreach ($this->parsedQuery['filters'] as $n => $filter)
+        foreach ($filter['strEqExprs'] as $i => $expr) {
+          if ($expr['value_type'] == 'QName') {         	
+          	 $this->parsedQuery['filters'][$n]['strEqExprs'][$i]['value']
+          	 	= $this->_replaceNamespacePrefix($expr['value'], RDQL_AND_ERR);        	 	
+			 $this->parsedQuery['filters'][$n]['strEqExprs'][$i]['value_type'] = 'URI';          	 	 	
+          }
+          if ($expr['value_type'] == 'URI')
+             foreach ($this->parsedQuery['ns'] as $prefix => $uri)
+               $this->parsedQuery['filters'][$n]['strEqExprs'][$i]['value']
+                 = preg_replace("'$prefix:'", $uri,
+                    $this->parsedQuery['filters'][$n]['strEqExprs'][$i]['value']);
+          elseif ($expr['value_type'] == 'Literal') {
+          	 if (isset($expr['value_dtype_is_qname'])) {
+          	 	$this->parsedQuery['filters'][$n]['strEqExprs'][$i]['value_dtype']
+          	 	   = $this->_replaceNamespacePrefix($expr['value_dtype'], RDQL_AND_ERR);          	 	   
+          	 	unset($this->parsedQuery['filters'][$n]['strEqExprs'][$i]['value_dtype_is_qname']);		
+          	 } else {
+               foreach ($this->parsedQuery['ns'] as $prefix => $uri)
+                 $this->parsedQuery['filters'][$n]['strEqExprs'][$i]['value_dtype']
+                   = preg_replace("$prefix:", $uri,
+                      $this->parsedQuery['filters'][$n]['strEqExprs'][$i]['value_dtype']);
+          	 }
+          }
+        }
+
+   unset($this->parsedQuery['ns']);
+ }
+
+
+// =============================================================================
+// *************************** helper functions ********************************
+// =============================================================================
+
+
+/**
+ * Remove whitespace-tokens from the array $this->tokens
+ *
+ * @access	private
+ */
+ function _clearWhiteSpaces() {
+
+   while (current($this->tokens) == ' '  ||
+          current($this->tokens) == "\n" ||
+          current($this->tokens) == "\t" ||
+          current($this->tokens) == "\r")
+
+      unset($this->tokens[key($this->tokens)]);
+ }
+
+
+/**
+ * Check if the query string of the given clause contains an undesired ','.
+ * If a comma was correctly placed then remove it and clear all whitespaces.
+ *
+ * @param   string  $commaExpected
+ * @param   string  $clause_error
+ * @throws  PHPError
+ * @access  private
+ */
+ function _checkComma($commaExpected, $clause_error) {
+
+   $this->_clearWhiteSpaces();
+   if (current($this->tokens) == ',') {
+      if (!$commaExpected)
+         trigger_error($clause_error ."',' - unexpected comma", E_USER_ERROR);
+      else {
+         unset($this->tokens[key($this->tokens)]);
+         $this->_checkComma(FALSE, $clause_error);
+      }
+   }
+ }
+ 
+
+/**
+ * Check if the given token is either a variable (?var) or the first token of an URI (<URI>).
+ * In case of an URI this function returns the whole URI string.
+ *
+ * @param   string  $token
+ * @return  array ['value'] = string
+ * @throws  PHPError
+ * @access	private
+ */
+ function _validateVarUri($token) {
+ 	
+   if ($token{0} == '?') {
+      $token_res['value'] = $this->_validateVar($token, RDQL_WHR_ERR);
+   } else {
+   	  $token_res['value'] = $this->_validateUri($token, RDQL_WHR_ERR);
+   	  if ($token{0} != '<')
+   	  	$token_res['is_qname'] = TRUE;   	  
+   }           
+   return $token_res;
+ }
+
+
+/**
+ * Check if the given token is either a variable (?var) or the first token
+ * of either an URI (<URI>) or a literal ("Literal").
+ * In case of a literal return an array with literal properties (value, language, datatype).
+ * In case of a variable or an URI return only ['value'] = string.
+ *
+ * @param   string  $token
+ * @return  array ['value'] = string
+ *				  ['is_qname'] = boolean
+ *                ['is_literal'] = boolean
+ *                ['l_lang'] = string
+ *                ['l_dtype'] = string
+ * @throws  PHPError
+ * @access	private
+ */
+ function _validateVarUriLiteral($token) {
+ 
+   if ($token{0} == '?')
+      $statement_object['value'] = $this->_validateVar($token, RDQL_WHR_ERR);   
+   elseif ($token{0} == "'" || $token{0} == '"')
+      $statement_object = $this->_validateLiteral($token);
+   elseif ($token{0} == '<')
+      $statement_object['value'] = $this->_validateUri($token, RDQL_WHR_ERR);      
+   elseif (ereg(':', $token)) {
+   	  $statement_object['value'] = $this->_validateUri($token, RDQL_WHR_ERR);
+   	  $statement_object['is_qname'] = TRUE;
+   }else
+   	  trigger_error(RDQL_WHR_ERR ." '$token' - ?Variable, &lt;URI&gt;, QName, or \"LITERAL\" expected", E_USER_ERROR);   
+   return $statement_object;      
+ }
+ 
+
+/**
+ * Check if the given token is a valid variable name (?var).
+ *
+ * @param   string  $token
+ * @param   string  $clause_error
+ * @return  string
+ * @throws  PHPError
+ * @access	private
+ */
+ function _validateVar($token, $clause_error) {
+
+   preg_match("/\?[a-zA-Z0-9_]+/", $token, $match);
+   if (!isset($match[0]) || $match[0] != $token)
+      trigger_error($clause_error ."'" .htmlspecialchars($token)
+                    ."' - variable name contains illegal characters", E_USER_ERROR);
+   unset($this->tokens[key($this->tokens)]);
+   return $token;
+ }
+
+
+/**
+ * Check if $token is the first token of a valid URI (<URI>) and return the whole URI string
+ *
+ * @param   string  $token
+ * @param   string  $clause_error
+ * @return  string
+ * @throws  PHPError
+ * @access	private
+ */
+ function _validateUri($token, $clause_error) {
+
+   if ($token{0} != '<') {
+      if (strpos($token, ':') && $this->_validateQName($token, $clause_error)) {
+      	unset($this->tokens[key($this->tokens)]);
+      	return rtrim($token, ':');
+      }
+      $errmsg = $clause_error .'\'' .htmlspecialchars($token) .'\' ';
+      if ($clause_error == RDQL_WHR_ERR)
+         $errmsg .= "- ?Variable or &lt;URI&gt; or QName expected";
+      else
+         $errmsg .= "- &lt;URI&gt; or QName expected";
+      trigger_error($errmsg, E_USER_ERROR);
+   }else{
+      $token_res = $token;
+      while($token{strlen($token)-1} != '>' && $token != NULL) {
+        if ($token == '(' || $token == ')' || $token == ',' ||
+            $token == ' ' || $token == "\n" || $token == "\r") {
+           trigger_error($clause_error .'\'' .htmlspecialchars($token_res)
+                          ."' - illegal input: '$token' - '>' missing", E_USER_ERROR);
+        }
+        unset($this->tokens[key($this->tokens)]);
+        $token = current($this->tokens);
+        $token_res .= $token;
+      }
+      if ($token == NULL)
+         trigger_error($clause_error .'\'' .htmlspecialchars($token_res) ."' - '>' missing", E_USER_ERROR);
+      unset($this->tokens[key($this->tokens)]);
+      return trim($token_res, '<>');
+   }
+ }
+
+
+/**
+ * Check if $token is the first token of a valid literal ("LITERAL") and
+ * return an array with literal properties (value, language, datatype).
+ *
+ * @param   string  $token
+ * @return  array   ['value'] = string
+ *                  ['is_literal'] = boolean
+ *                  ['l_lang'] = string
+ *                  ['l_dtype'] = string
+ *					['l_dtype_is_qname'] = boolean
+ * @throws  PHPError
+ * @access	private
+ */
+ function _validateLiteral($token) {
+
+   $quotation_mark = $token{0};
+   $statement_object = array ('value' => '',
+                              'is_literal' => TRUE,
+                              'l_lang' => '',
+                              'l_dtype' => '');
+   $this->tokens[key($this->tokens)] = substr($token,1);
+
+   $return = FALSE;
+   foreach ($this->tokens as $k => $token) {
+
+     if ($token != NULL && $token{strlen($token)-1} == $quotation_mark) {
+         $token = rtrim($token, $quotation_mark);
+         $return = TRUE;
+
+      // parse @language(^^datatype)?
+     }elseif (strpos($token, $quotation_mark .'@') || substr($token, 0, 2)  == $quotation_mark .'@') {
+        $lang = substr($token, strpos($token, $quotation_mark .'@')+2);
+        if (strpos($lang, '^^') || substr($lang, 0,2) == '^^') {
+           $dtype = substr($lang, strpos($lang, '^^')+2);
+           if (!$dtype)
+              trigger_error(RDQL_WHR_ERR .$quotation_mark .$statement_object['value']
+                                         .$token  ." - datatype expected" ,E_USER_ERROR);
+                                         
+		   $statement_object['l_dtype'] = $this->_validateUri($dtype, RDQL_WHR_ERR);
+		   if ($dtype{0} != '<')
+		      $statement_object['l_dtype_is_qname'] = TRUE;		      
+        
+           $lang = substr($lang, 0, strpos($lang, '^^'));
+        }
+        if (!$lang)
+           trigger_error(RDQL_WHR_ERR .$quotation_mark .$statement_object['value']
+                                      .$token ." - language expected" ,E_USER_ERROR);
+        $statement_object['l_lang'] = $lang;
+        $token = substr($token, 0, strpos($token, $quotation_mark .'@'));
+        $return = TRUE;
+
+     // parse ^^datatype
+     }elseif (strpos($token, $quotation_mark .'^^') || substr($token, 0, 3)  == $quotation_mark .'^^') {
+        $dtype = substr($token, strpos($token, $quotation_mark .'^^')+3);
+        if (!$dtype)
+           trigger_error(RDQL_WHR_ERR .$quotation_mark .$statement_object['value']
+                                      .$token  ." - datatype expected" ,E_USER_ERROR);       
+
+        $statement_object['l_dtype'] = $this->_validateUri($dtype, RDQL_WHR_ERR);
+		if ($dtype{0} != '<')
+		   $statement_object['l_dtype_is_qname'] = TRUE;		   
+
+        $token = substr($token, 0, strpos($token, $quotation_mark .'^^'));
+        $return = TRUE;
+     }elseif (strpos($token, $quotation_mark))
+        trigger_error(RDQL_WHR_ERR ."'$token' - illegal input", E_USER_ERROR);
+     $statement_object['value'] .= $token;
+     unset($this->tokens[$k]);
+     if ($return)
+        return $statement_object;
+   }
+   trigger_error(RDQL_WHR_ERR ."quotation end mark: $quotation_mark missing", E_USER_ERROR);
+ }
+
+ 
+/**
+ * Check if the given token is a valid QName. 
+ *
+ * @param   string  $token
+ * @param   string  $clause_error
+ * @return  boolean
+ * @throws  PHPError
+ * @access	private
+ */
+function _validateQName($token, $clause_error) {
+ 
+  $parts = explode(':', $token);
+  if (count($parts) > 2)
+  	trigger_error($clause_error ."illegal QName: '$token'", E_USER_ERROR);
+  if (!$this->_validateNCName($parts[0]))
+  	trigger_error($clause_error ."illegal prefix in QName: '$token'", E_USER_ERROR);
+  if ($parts[1] && !$this->_validateNCName($parts[1]))
+  	trigger_error($clause_error ."illegal local part in QName: '$token'", E_USER_ERROR);
+  	
+  return TRUE;
+}
+
+
+/**
+ * Check if the given token is a valid NCName. 
+ *
+ * @param   string  $token
+ * @return  boolean
+ * @access	private
+ */ 
+function _validateNCName($token) {
+	
+  preg_match("/[a-zA-Z_]+[a-zA-Z_0-9.\-]*/", $token, $match);
+  if (isset($match[0]) && $match[0] == $token)
+  	return TRUE;
+  return FALSE;	
+}
+
+
+/**
+ * Check if the given token is a valid namespace prefix.
+ *
+ * @param   string  $token
+ * @return  string
+ * @throws  PHPError
+ * @access	private
+ */
+ function _validatePrefix($token) {
+
+   if (!$this->_validateNCName($token))
+      trigger_error(RDQL_USG_ERR ."'" .htmlspecialchars($token)
+                                 ."' - illegal input, namespace prefix expected", E_USER_ERROR);
+   unset($this->tokens[key($this->tokens)]);
+   return $token;
+ }
+
+/**
+ * Replace a prefix in a given QName and return a full URI.
+ *
+ * @param   string  $qName
+ * @param   string  $clasue_error
+ * @return  string
+ * @throws  PHPError
+ * @access	private
+ */ 
+ function _replaceNamespacePrefix($qName, $clause_error) {
+
+   $qName_parts = explode(':', $qName);
+   if (!array_key_exists($qName_parts[0], $this->parsedQuery['ns']))
+      trigger_error($clause_error .'undefined prefix: \'' .$qName_parts[0] .'\' in: \'' .$qName .'\'', E_USER_ERROR);
+   return $this->parsedQuery['ns'][$qName_parts[0]] .$qName_parts[1];
+ } 
+          	 	
+          	 	
+/**
+ * Check if all variables from the SELECT clause are defined in the WHERE clause
+ *
+ * @access private
+ */
+ function _checkSelectVars() {
+
+   foreach ($this->parsedQuery['selectVars'] as $var)
+     $this->_isDefined($var);
+ }
+
+
+/**
+ * Check if the given variable is defined in the WHERE clause.
+ *
+ * @param $var string
+ * @return     string
+ * @throws PHPError
+ * @access private
+ */
+ function _isDefined($var) {
+
+   $allQueryVars = $this->findAllQueryVariables();
+
+   if (!in_array($var, $allQueryVars))
+      trigger_error(RDQL_SYN_ERR .": '$var' - variable must be defined in the WHERE clause", E_USER_ERROR);
+   return $var;
+ }
+
+
+/**
+ * Throw an error if the regular expression from the AND clause is not quoted.
+ *
+ * @param  string $filterString
+ * @param  string $lQuotMark
+ * @param  string $rQuotMark
+ * @throws PHPError
+ * @access private
+ */
+ function _checkRegExQuotation($filterString, $lQuotMark, $rQuotMark) {
+
+   if (!$lQuotMark)
+      trigger_error(RDQL_AND_ERR ."'$filterString' - regular expressions must be quoted", E_USER_ERROR);
+
+   if ($lQuotMark != $rQuotMark)
+      trigger_error(RDQL_AND_ERR ."'$filterString' - quotation end mark in the regular expression missing", E_USER_ERROR);
+ }
+
+} // end: Class RdqlParser
+
+?>
Index: /Dev/trunk/rdfapi/rdql/RdqlResultIterator.php
===================================================================
--- /Dev/trunk/rdfapi/rdql/RdqlResultIterator.php	(revision 12)
+++ /Dev/trunk/rdfapi/rdql/RdqlResultIterator.php	(revision 12)
@@ -0,0 +1,193 @@
+<?php
+
+// ----------------------------------------------------------------------------------
+// Class: RdqlResultIterator
+// ----------------------------------------------------------------------------------
+
+/**
+ * Iterator for traversing Rdql results. 
+ * This class can be used for iterating forward and backward trough Rdql results.
+ * It should be instanced using the rdqlQueryAsIterator() method of a MemModel or a DBModel.
+ * 
+ * @version  $Id: RdqlResultIterator.php 268 2006-05-15 05:28:09Z tgauss $
+ * @author Daniel Westphal <mail@d-westphal.de>, Chris Bizer <chris@bizer.de>
+ *
+ * @package rdql
+ * @access	public
+ *
+ */ 
+ class RdqlResultIterator extends Object {
+
+ 	/**
+	* Reference to the Rdql result
+	* @var		array RdqlResult
+	* @access	private
+	*/	
+    var $RdqlResult;
+
+ 	/**
+	* Current position
+	* RdqlResultIterator does not use the build in PHP array iterator,
+	* so you can use serveral iterators on a single Rdql result.
+	* @var		integer
+	* @access	private
+	*/	
+    var $position;
+   
+  
+   /**
+    * Constructor
+    *
+    * @param	object RdqlResult
+	* @access	public
+    */
+    function RdqlResultIterator(&$RdqlResult) {
+    	
+     	$noResult = TRUE;
+    	foreach($RdqlResult[0] as $value) 
+      		if ($value != NULL) {
+      	   		$noResult = FALSE;
+      	   		break;
+      		} 	
+      		
+      	if($noResult)  	     	
+       		$this->RdqlResult = NULL;
+       	else 
+       		$this->RdqlResult = $RdqlResult;	
+
+		$this->position = -1;
+	}
+ 
+  /**
+   * Returns the labels of the result as array.
+   * @return	array of strings with the result labels OR null if there are no results.
+   * @access	public  
+   */
+  function getResultLabels() {
+		if(count($this->RdqlResult)>0) {
+  			return array_keys($this->RdqlResult[0]);
+		} else return null;
+   }
+
+   /**
+   * Returns the number of results.
+   * @return	integer
+   * @access	public  
+   */
+  function countResults() {
+		
+  			return count($this->RdqlResult);
+
+   }
+  /**
+   * Returns TRUE if there are more results.
+   * @return	boolean
+   * @access	public  
+   */
+  function hasNext() {
+  		if ($this->position < count($this->RdqlResult) - 1 ) {			
+  			return TRUE;
+		} else {
+			return FALSE;
+		}
+   }
+
+  /**
+   * Returns TRUE if the first result has not been reached.
+   * @return	boolean
+   * @access	public  
+   */
+  function hasPrevious() {
+  		if ($this->position > 0) {
+			return TRUE;
+		} else {
+			return FALSE;
+		}   }   
+   
+  /**
+   * Returns the next result array.
+   * @param 	integer $element	
+   * @return	result array OR single result if $element was specified OR NULL if there is no next result.
+   * @access	public  
+   */
+  function next($element = null) {
+  		if ($this->position < count($this->RdqlResult) - 1) {
+  			$this->position++;
+			if ($element) {return $this->RdqlResult[$this->position][$element];}
+  				else return $this->RdqlResult[$this->position];
+		} else {
+			return NULL;
+		}
+   }
+
+  /**
+   * Returns the previous result.
+   * @param 	integer $element	
+   * @return	result array OR single result if $element was specified OR NULL if there is no next result.
+   * @access	public  
+   */
+  function previous($element = null) {
+    	if ($this->position > 0) {
+  			$this->position--;
+			if ($element) {return $this->RdqlResult[$this->position][$element];}
+  				else return $this->RdqlResult[$this->position];
+		} else {
+			return NULL;
+		}   
+  }
+
+  /**
+   * Returns the current result.
+   * @param 	integer $element	
+   * @return	result array OR single result if $element was specified OR NULL if there is no next result.
+   * @access	public  
+   */
+  function current($element = null) {
+  		if (($this->position >= 0) && ($this->position < count($this->RdqlResult))) {
+			if ($element) {return $this->RdqlResult[$this->position][$element];}
+  				else return $this->RdqlResult[$this->position];
+		} else {
+			return NULL;
+		} 
+   }
+   
+  /**
+   * Moves the pointer to the first result.
+   * @return	void
+   * @access	public  
+   */
+  function moveFirst() {
+  			$this->position = 0;
+   }
+
+  /**
+   * Moves the pointer to the last result.
+   * @return	void
+   * @access	public  
+   */
+  function moveLast() {
+  			$this->position = count($this->RdqlResult) - 1;
+   }
+   
+     /**
+   * Moves the pointer to a specific result.
+   * If you set an off-bounds value, next(), previous() and current() will return NULL
+   * @return	void
+   * @access	public  
+   */
+  function moveTo($position) {
+  			$this->position = $position;
+   }
+   
+     /**
+   * Returns the current position of the iterator.
+   * @return	integer
+   * @access	public  
+   */
+  function getCurrentPosition() {
+  	 		return $this->position;
+   }
+  
+} 
+
+?>
Index: /Dev/trunk/rdfapi/resModel/ResAlt.php
===================================================================
--- /Dev/trunk/rdfapi/resModel/ResAlt.php	(revision 12)
+++ /Dev/trunk/rdfapi/resModel/ResAlt.php	(revision 12)
@@ -0,0 +1,78 @@
+<?php
+// ----------------------------------------------------------------------------------
+// Class: ResAlt
+// ----------------------------------------------------------------------------------
+
+/**
+* This interface defines methods for accessing RDF Alternative resources. 
+* These methods operate on the RDF statements contained in a model.
+*
+* @version  $Id: ResAlt.php 320 2006-11-21 09:38:51Z tgauss $
+* @author Daniel Westphal <mail at d-westphal dot de>
+*
+* @package 	resModel
+* @access	public
+**/
+class ResAlt extends ResContainer 
+{
+	
+	/**
+    * Constructor
+	* You can supply a URI
+    *
+    * @param string $uri 
+	* @access	public
+    */	
+	function ResAlt($uri = null)
+	{
+		parent::ResContainer($uri);
+		$this->containerType=new ResResource(RDF_NAMESPACE_URI.RDF_ALT);
+	}
+	
+	/**
+	*  Return the default value for this resource
+	*
+   	* @return	object ResResource/ResLiteral 
+   	* @access	public
+   	*/
+	function getDefault()
+	{
+		//get the first memeber
+		$statements=$this->listProperties($this->_getMembershipPropertyWithIndex(1));
+		if(isset($statements[0]))
+		{
+			//return the value
+			return $statements[0]->getObject();
+		} else 
+		{
+			return null;
+		}
+	}
+	
+	/**
+	*  Set the default value of this container.
+	*
+   	* @param	object ResResource/ResLiteral $object
+   	* @access	public
+   	*/
+	function setDefault($object)
+	{
+		//remember the old default value
+		$oldDefaultObject=$this->getDefault();
+		//if there wasn't a default value before
+		if($oldDefaultObject === null)
+		{
+			//add the new value
+			$this->addProperty($this->_getMembershipPropertyWithIndex(1),$object);
+		} else 
+		{
+			//remove the old value
+			$this->removeAll($this->_getMembershipPropertyWithIndex(1));
+			//set the new value
+			$this->addProperty($this->_getMembershipPropertyWithIndex(1),$object);
+			//add the old default value at the end
+			$this->add($oldDefaultObject);
+		}
+	}
+}
+?>
Index: /Dev/trunk/rdfapi/resModel/ResBag.php
===================================================================
--- /Dev/trunk/rdfapi/resModel/ResBag.php	(revision 12)
+++ /Dev/trunk/rdfapi/resModel/ResBag.php	(revision 12)
@@ -0,0 +1,32 @@
+<?php
+// ----------------------------------------------------------------------------------
+// Class: ResBag
+// ----------------------------------------------------------------------------------
+
+/**
+* This interface defines methods for accessing RDF Bag resources. 
+* These methods operate on the RDF statements contained in a model.
+*
+* @version  $Id: ResBag.php 320 2006-11-21 09:38:51Z tgauss $
+* @author Daniel Westphal <mail at d-westphal dot de>
+*
+* @package 	resModel
+* @access	public
+**/
+class ResBag extends ResContainer 
+{
+	
+	/**
+    * Constructor
+	* You can supply a URI
+    *
+    * @param string $uri 
+	* @access	public
+    */		
+	function ResBag($uri = null)
+	{
+		parent::ResContainer($uri);
+		$this->containerType=new ResResource(RDF_NAMESPACE_URI.RDF_BAG);
+	}
+}
+?>
Index: /Dev/trunk/rdfapi/resModel/ResContainer.php
===================================================================
--- /Dev/trunk/rdfapi/resModel/ResContainer.php	(revision 12)
+++ /Dev/trunk/rdfapi/resModel/ResContainer.php	(revision 12)
@@ -0,0 +1,219 @@
+<?php
+// ----------------------------------------------------------------------------------
+// Class: ResContainer
+// ----------------------------------------------------------------------------------
+
+/**
+* An RDF Container.
+* This Class defines methods for accessing RDF container resources. 
+* These methods operate on the RDF statements contained in a model. 
+*
+* @version  $Id: ResContainer.php 320 2006-11-21 09:38:51Z tgauss $
+* @author Daniel Westphal <mail at d-westphal dot de>
+*
+* @package 	resModel
+* @access	public
+**/
+
+class ResContainer extends ResResource 
+{
+	/**
+	* Holds a ResResource of this container type rdf:Seq, rdf:Alt, or rdf:Bag
+	* @var		ResResource
+	* @access	private
+	*/
+	var $containerType;
+	
+	
+	/**
+    * Constructor
+	* You can supply a URI
+    *
+    * @param string $uri 
+	* @access	public
+    */	
+	function ResContainer($uri = null)
+	{
+		parent::ResResource($uri);
+	}	
+	
+	/**
+	* Add a new value to a container.
+	* The new value is added as the last element of the container.
+	*
+   	* @param	object ResResource/ResLiteral	$object
+   	* @access	public
+   	*/
+	function add($object)
+	{
+		//type this container, if it isn't already typed
+		if(!$this->hasProperty(new ResResource(RDF_NAMESPACE_URI.RDF_TYPE)))
+			$this->addProperty(new ResResource(RDF_NAMESPACE_URI.RDF_TYPE),$this->containerType);
+		//get the current size
+		$actualSize=$this->size();
+		//add the object to the last position
+		$this->addProperty(new ResResource(RDF_NAMESPACE_URI.'_'.($actualSize+1)),$object);
+	}
+	
+	/**
+	* Determine whether the container contains a value
+	*
+   	* @param	obejct ResResource/ResLiteral	$resResource
+   	* @return	boolean 
+   	* @access	public
+   	*/
+	function contains($resResource)
+	{
+		//get all container's properties 
+		foreach ($this->listProperties() as $statement)
+		{
+			//if the property matches a container membership property
+			if ($this->_predicateLabelMatchesMembershipProperty($statement->getLabelPredicate()))
+			{
+				//check, if it's the value, we're looking for. 
+				if ($resResource->equals($statement->getObject()))
+					return true;
+			}	
+		}
+		return false;
+	}
+	
+	/**
+	* Returns true, if this resource is a container from type rdf:Alt
+	*
+   	* @return	boolean 
+   	* @access	public
+   	*/	
+	function isAlt()
+	{
+		return ($this->containerType->getURI()==RDF_NAMESPACE_URI.RDF_ALT);
+	}
+	
+	/**
+	* Returns true, if this resource is a container from type rdf:Bag
+	*
+   	* @return	boolean 
+   	* @access	public
+   	*/	
+	function isBag()
+	{
+		return ($this->containerType->getURI()==RDF_NAMESPACE_URI.RDF_BAG);
+	}
+
+	/**
+	* Returns true, if this resource is a container from type rdf:Seq
+	*
+   	* @return	boolean 
+   	* @access	public
+   	*/	
+	function isSeq()
+	{
+		return ($this->containerType->getURI()==RDF_NAMESPACE_URI.RDF_SEQ);
+	}
+	
+	/**
+	* Get an array of all resources that are values of this container
+	*
+   	* @return	array 
+   	* @access	public
+   	*/	
+	function getMembers()
+	{
+		$return=array();
+		foreach ($this->listProperties() as $statement)
+		{
+			$predicateLabel=$statement->getLabelPredicate();
+			if ($this->_predicateLabelMatchesMembershipProperty($predicateLabel))
+			{
+				$return[$this->_getMemberIndexNrFromMembershipPropertyLabel($predicateLabel)] = $statement->getObject();
+			}	
+		}
+		return $return;
+	}
+	
+	/**
+	* Remove a value from the container.
+	* 
+	* Once removed, the values in the container with a higher ordinal value are renumbered. 
+	* The renumbering algorithm depends on the type of container.
+	*
+   	* @param	obejct ResResource/ResLiteral	$resResource
+   	* @access	public
+   	*/
+	function remove($object)
+	{
+		$deleteFromIndex=array();
+		//get all container members
+		$memberIndex=$this->getMembers();
+		
+		//check each container member if it equals the resoure to be removed
+		foreach ($memberIndex as $key => $value)
+		{
+			//save the statements positio in the container
+			if($object->equals($value))
+					$deleteFromIndex[]=$key;	
+		}
+
+		//delete all found container members
+		foreach ($deleteFromIndex as $index)
+		{
+			$this->removeAll($this->_getMembershipPropertyWithIndex($index));
+
+			//renumber all members with higher ordinal numbers than the deleted one
+			for ($i = $index;$i < count($memberIndex); $i++)
+			{
+				$this->removeAll($this->_getMembershipPropertyWithIndex($i+1));
+				$this->addProperty($this->_getMembershipPropertyWithIndex($i),$memberIndex[$i+1]);
+			}		
+		}
+		
+	}
+	
+	/**
+	* Returns the number values in the container.
+	*
+   	* @return	integer 
+   	* @access	public
+   	*/	
+	function size()
+	{
+		return count($this->getMembers());
+	}
+	
+	/**
+	* Checks, if a predicate label fits a container membership property rdf:_n
+	*
+   	* @param	string	$predicateLabel
+   	* @return	boolean 
+   	* @access	private
+   	*/
+	function _predicateLabelMatchesMembershipProperty($predicateLabel)
+	{
+		return substr($predicateLabel,0,strlen(RDF_NAMESPACE_URI.'_')) == RDF_NAMESPACE_URI.'_';
+	}
+	
+	/**
+	* Get the ordinal number from a membership property rdf:_n
+	*
+   	* @param	string	$predicateLabel
+   	* @return	integer 
+   	* @access	private
+   	*/
+	function _getMemberIndexNrFromMembershipPropertyLabel($predicateLabel)
+	{
+		return (int)substr($predicateLabel,strlen(RDF_NAMESPACE_URI.'_'));
+	}
+	
+	/**
+	* Get a membership property rdf:_n with index $int 
+	*
+   	* @param	intger	$int
+   	* @return	string 
+   	* @access	private
+   	*/
+	function _getMembershipPropertyWithIndex($int)
+	{
+		return new ResResource(RDF_NAMESPACE_URI.'_'.$int);	
+	}
+}
+?>
Index: /Dev/trunk/rdfapi/resModel/ResIterator.php
===================================================================
--- /Dev/trunk/rdfapi/resModel/ResIterator.php	(revision 12)
+++ /Dev/trunk/rdfapi/resModel/ResIterator.php	(revision 12)
@@ -0,0 +1,298 @@
+<?php 
+/**
+* ----------------------------------------------------------------------------------
+* Class: ResIterator
+* ----------------------------------------------------------------------------------
+*
+* @package 	resModel
+*/
+
+
+/**
+* Implementation of a resource iterator.
+*
+* This Iterator should be used in a for-loop like:
+* $it = $ontClass->listInstances();
+* for ($it->rewind(); $it->valid(); $it->next())
+* {
+*	$currentResource=$it->current();
+* };
+*
+*
+* @version  $Id: ResIterator.php 522 2007-08-14 09:22:22Z cweiske $
+* @author Daniel Westphal <mail at d-westphal dot de>
+*
+*
+* @package 	resModel
+* @access	public
+**/
+class ResIterator
+{
+	/**
+	* Holds a reference to the assoiated ResModel / OntModel
+	* @var		object Model
+	* @access	private
+	*/
+	var $associatedModel;
+	
+	/**
+	* The current position
+	* @var		integer
+	* @access	private
+	*/
+	var $key;
+	
+	/**
+	* If the current resource is valid
+	* @var		boolean
+	* @access	private
+	*/
+	var $valid;
+	
+	/**
+	* The current resource
+	* @var obejct ResResource
+	* @access	private
+	*/
+	var $currentResource;
+	
+	/**
+	* The subject to search for.
+	* @var		object ResResource
+	* @access	private
+	*/
+	var $searchSubject;
+	
+	/**
+	* The predicate to search for.
+	* @var		object ResResource
+	* @access	private
+	*/
+	var $searchPredicate;
+	
+	/**
+	* The object to search for.
+	* @var		object ResResource
+	* @access	private
+	*/
+	var $searchObject;
+	
+	/**
+	* If the resource, we're intrested in is the subject (s), predicate(p), 
+	* or object (o) of the found statements
+	* 
+	* @var		string
+	* @access	private
+	*/
+	var $getSPO;
+	
+	/**
+	* Defines the type of resource, we'd like to receive.
+	* 
+	* @var		string
+	* @access	private
+	*/
+	var $returnType;
+	
+	/**
+	* If set, each resource will first be checked, if it's
+	* language fits.
+	* 
+	* @var		string
+	* @access	private
+	*/
+	var $findLiteralWithLang;
+	
+	
+	/**
+    * Constructor.
+    *
+	* $subject, $predicate, and $object are used like inf find().
+	* $getSPO supports the strings 's', 'p', and 'o' to return
+	* either the subject, predicate, or object of the result statements.
+	* $returnType supports the strings 'ResProperty', 'ResLiteral',
+	* 'OntProperty', 'OntClass', and 'Individual' and returns the resources
+	* as the matching type.
+    *
+    * @param object ResResource  $subject
+    * @param object ResResource  $predicate
+    * @param object ResResource  $object
+    * @param string				 $getSPO
+    * @param object ResModel	 $associatedModel
+    * @param string				 $returnType
+	* @access	public
+    */
+	function ResIterator($subject,$predicate,$object,$getSPO,& $associatedModel,$returnType = false)
+	{
+		$this->searchSubject =& $subject;
+		$this->searchPredicate =& $predicate;
+		$this->searchObject =& $object;
+		$this->getSPO = $getSPO;
+		$this->returnType = $returnType;
+		$this->associatedModel =& $associatedModel;
+		$this->findLiteralWithLang = false;
+	}
+	
+	/**
+    * 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->key++;
+		$this->valid=($this->_getNextResource());
+	}
+	
+	/**
+    * Returns the current item
+    *
+    * @return	mixed
+	* @access	public
+    */
+	function current()
+	{
+		return $this->currentResource;
+	}
+	
+	/**
+    * Returns the next Resource (subject, predicate, 
+    * or object of the next matching statement).
+    *
+    * @return	object resResource
+	* @access	private
+    */
+	function _getNextResource()
+	{
+		if ($this->findLiteralWithLang)
+		{ 
+			do 
+			{
+				$nextStatement = $this->associatedModel->findFirstMatchingStatement($this->searchSubject,$this->searchPredicate,$this->searchObject,$this->key);
+				if ($nextStatement === null)
+					return false;
+					
+				$object = $nextStatement->getObject();
+				if ($object->getLanguage() != $this->findLiteralWithLang)
+				{
+					$hasCorrectLanguage=false;
+					$this->key++;
+				} else 
+				{
+					$hasCorrectLanguage=true;
+				}
+					
+			} while (!$hasCorrectLanguage);
+		} else 
+		{
+			$nextStatement = $this->associatedModel->findFirstMatchingStatement($this->searchSubject,$this->searchPredicate,$this->searchObject,$this->key);
+		}
+		if ($nextStatement === null)
+			return false;
+		
+		switch ($this->getSPO) 
+		{
+			case 's':
+				 $this->currentResource = $this->_getResourceAs($nextStatement->getSubject());
+				break;
+
+			case 'p':
+				 $this->currentResource = $this->_getResourceAs($nextStatement->getPredicate());
+				break;
+				
+			case 'o':
+				 $this->currentResource = $this->_getResourceAs($nextStatement->getObject());
+				break;
+		}
+		return (true);
+	}
+	
+	/**
+    * Returns the key of the current item
+    *
+    * @return	integer
+	* @access	public
+    */
+	function key()
+	{
+		return $this->key;
+	}
+	
+	/**
+    * Sets that only Literals with the matching 
+    * language should be returned
+    *
+    * @param	string
+	* @access	public
+    */
+	function setFindLiteralWithLang($language)
+	{
+		$this->findLiteralWithLang = $language;
+	}
+	
+	/**
+    * Returns the $resource as an instance of the type
+    * specified in $this->returnType.
+    *
+    * @param	object ResResource
+    * @return	object ResResource
+	* @access	private
+    */
+	function _getResourceAs($resource)
+	{
+		if ($this->findLiteralWithLang && $resource->getLanguage() != $this->findLiteralWithLang)
+			$this->_getNextResource();
+
+		if($this->returnType)	
+			switch ($this->returnType) {
+		
+				case 'ResProperty':
+						return $this->associatedModel->createProperty($resource->getLabel());
+					break;
+					
+				case 'ResLiteral':
+						$newLiteral = $this->associatedModel->createLiteral($resource->getLabel(),$resource->getLanguage());
+						$newLiteral->setDatatype($resource->getDatatype());
+						return $newLiteral;
+					break;
+					
+				case 'OntProperty':
+
+						return $this->associatedModel->createOntProperty($resource->getLabel());
+					break;
+					
+				case 'OntClass':
+						return $this->associatedModel->createOntClass($resource->getLabel());
+					break;
+					
+				case 'Individual':
+					return $this->associatedModel->createIndividual($resource->getLabel());
+				break;
+			}
+		return $resource;
+	}
+}
+
+?>
Index: /Dev/trunk/rdfapi/resModel/ResList.php
===================================================================
--- /Dev/trunk/rdfapi/resModel/ResList.php	(revision 12)
+++ /Dev/trunk/rdfapi/resModel/ResList.php	(revision 12)
@@ -0,0 +1,635 @@
+<?php
+// ----------------------------------------------------------------------------------
+// Class: ResList
+// ----------------------------------------------------------------------------------
+
+/**
+* Implementation of an rdf:Collection (rdf:List)
+* Provides a convenience encapsulation for lists formed from 
+* chains of RDF statements arranged to form a head/tail cons-cell 
+* structure. 
+* 
+* A well-formed list has cells that are made up of three statements: 
+* one denoting the rdf:type of the list cell, one denoting the link 
+* to the value of the list at that point, and one pointing to the 
+* list tail. If a list cell is not well-formed, list operations may 
+* fail in unpredictable ways. However, to explicitly check that the 
+* list is well-formed at all times is expensive, but you can call
+* the isValid() method to manually check, if the list is well formed.
+*
+*
+* @version  $Id: ResList.php 320 2006-11-21 09:38:51Z tgauss $
+* @author Daniel Westphal <mail at d-westphal dot de>
+
+*
+* @package resModel
+* @access	public
+*/
+class ResList extends ResResource 
+{
+	/**
+	* Holds a ResResource with the uri rdf:rest
+	* @var		ResResource
+	* @access	private
+	*/
+	var $rdfRestResource;
+	
+	/**
+	* Holds a ResResource with the uri rdf:first
+	* @var		ResResource
+	* @access	private
+	*/
+	var $rdfFirstResource;
+		
+	/**
+	* Holds a ResResource with the uri rdf:nil
+	* @var		ResResource
+	* @access	private
+	*/
+	var $rdfNilResource;
+	
+	
+	/**
+    * Constructor
+	* You can supply a URI
+    *
+    * @param string $uri 
+	* @access	public
+    */		
+	function ResList($uri = null)
+	{
+		//call the parent's constructor
+		parent::ResResource($uri);
+		//initialize vars
+		$this->rdfRestResource = new ResResource(RDF_NAMESPACE_URI.RDF_REST);
+		$this->rdfFirstResource = new ResResource(RDF_NAMESPACE_URI.RDF_FIRST);
+		$this->rdfNilResource = new ResResource(RDF_NAMESPACE_URI.RDF_NIL);
+	}
+
+	/**
+	* Returns the value of the list element at the specified position or null.
+	*
+   	* @param	integer	$position
+   	* @return	ResResource 
+   	* @access	public
+   	*/
+	function get($position)
+	{
+		//init
+		$listElement=$this;
+		//walk through the list until the position in the list is reached
+		for ($i=0;$i<$position;$i++)
+		{
+			$listElement=$this->_getRestElement($listElement);
+			if($listElement===null)
+				return null;	
+		}
+		//return the associated value
+		return $this->_getValue($listElement);	
+	}	
+
+	/**
+	*  Add the given value to the end of the list. 
+	*  it is only defined if this is not the empty list.
+	*
+   	* @param	object ResResource	$resource
+   	* @return	boolean 
+   	* @access	public
+   	*/
+	function add($resource)
+	{
+		//return false if this list is the empty list
+		if($this->uri==RDF_NAMESPACE_URI.RDF_NIL)
+			return false;
+		
+		//if this is the first value	
+		if ($this->isEmpty())
+		{
+			$newLastElement =& $this;
+		} else
+		//if there are other values in the list 
+		{
+			//get the last list element
+			$lastElement=$this->_getListElement();
+			//remove the rdf:rest property
+			$lastElement->removeAll($this->rdfRestResource);
+			//create a new list element
+			$newLastElement=$this->model->createResource();
+			//concatenate the new list element with the list
+			$lastElement->addProperty($this->rdfRestResource,$newLastElement);
+		}
+		//add the value
+		$newLastElement->addProperty($this->rdfFirstResource,$resource);
+		//ad the rdf:nil property to the last list element
+		$newLastElement->addProperty($this->rdfRestResource,$this->rdfNilResource);
+		
+		return true;
+	}
+	
+	/**
+	*  Update the head of the list to have the given value, 
+	*  and return the previous value.
+	*
+   	* @param	object ResResource	$value
+   	* @return	ResResource 
+   	* @access	public
+   	*/
+	//todo: error handling, when empty list
+	function setHead($value)
+	{	
+		//save the old value	
+		$oldValue=$this->getHead();
+		//remove the old value
+		$this->removeAll($this->rdfFirstResource);
+		//add the new value
+		$this->addProperty($this->rdfFirstResource,$value);
+		
+		//return the old value
+		return $oldValue;
+	}
+	
+	/**
+	* Get the value that is associated with the head of the list.
+	*
+   	* @return	ResResource 
+   	* @access	public
+   	*/
+	//todo: error handling, falls empty list
+	function getHead()
+	{
+		return $this->_getValue($this);
+	}
+	
+	/**
+	*  Remove the head of the list. The tail of the list 
+	*  remains in the model. Note that no changes are made to 
+	*  list cells that point to this list cell as their tail. 	
+	*
+   	* @return	ResList 
+   	* @access	public
+   	*/
+	function removeHead()
+	{
+		//get the second list element
+		$rest=$this->_getRestElement($this);
+		//remove the first element
+		$this->removeAll($this->rdfFirstResource);
+		$this->removeAll($this->rdfRestResource);
+		//change this Resource URI to that of the second list element
+		//thus makin it the fist element
+		$this->uri=$rest->getURI();
+		
+		//return the new list
+		return $this;
+	}	
+
+	/**
+	* Get the Position of the first occurrence of the given value in the list, 
+	* or -1 if the value is not in the list.
+	* You can supply an offset to search for values. (First element has offset 0)
+	* Default is 0
+	*
+   	* @param	object ResResource	$resource
+    * @param	integer	$offset
+   	* @return	integer 
+   	* @access	public
+   	*/
+	function indexOf($resource, $offset = 0)
+	{
+		//init
+		$element=$this;
+		$actualIndex=0;
+
+		//walk through the list until the value is found and the position is higher than
+		//the offset
+		while ($actualIndex < $offset || !$resource->equals($this->_getValue($element)))
+		{
+			//get next list element
+			$element=$this->_getRestElement($element);
+			$actualIndex++;
+			
+			//if the end of the list is reached and the value isn't found
+			if ($element===null)
+				return null;
+		}
+		//return the index value
+		return $actualIndex;	
+	}
+	
+	/**
+	* Replace the value at the i'th position in the list with the given value
+	*
+   	* @param	integer				$index
+   	* @param	object ResResource	$resource
+   	* @return	object ResResource 
+   	* @access	public
+   	*/
+	function replace($index, $resource)
+	{
+		//get the list element at the $index position
+		$listElement=$this->_getListElement($index);
+		//get the old value
+		$oldValue=$this->_getValue($listElement);
+		//remove the old value
+		$listElement->removeAll($this->rdfFirstResource);
+		//add the new value
+		$listElement->addProperty($this->rdfFirstResource,$resource);
+		//return the old value
+		return $oldValue;
+	}
+	
+	/**
+	* Answer true if the given node appears as the value of a value 
+	* of any of the cells of this list.
+	*
+   	* @param	object ResResource	$value
+   	* @return	boolean 
+   	* @access	public
+   	*/
+	function contains($value)
+	{
+		//return true, if a position was found.
+		$result=$this->indexOf($value);
+		return ($result!==null);
+	}
+	
+	/**
+	* Get the list that is the tail of this list.
+	*
+   	* @return	object ResList 
+   	* @access	public
+   	*/
+	function getTail()
+	{
+		//get the second list element
+		$nextListElement= $this->_getRestElement($this);
+		//return the second element as new list
+		return $this->model->createList($nextListElement->getURI());	
+	}
+	
+	/**
+	* Remove all of the components of this list from the model. 
+	* Note that this is operation is only removing the list cells 
+	* themselves, not the resources referenced by the list - 
+	* unless being the object of an rdf:first  statement is the 
+	* only mention of that resource in the model.
+	*
+   	* @return	boolean 
+   	* @access	public
+   	*/
+	function removeList()
+	{
+		$element=$this;
+
+		while ($element!==null)
+		{
+			$nextElement=$this->_getRestElement($element);
+			
+			$element->removeAll($this->rdfFirstResource);
+			$element->removeAll($this->rdfRestResource);
+					
+			if (($nextElement !== null) && ($nextElement->getURI()!==RDF_NAMESPACE_URI.RDF_NIL))
+			{
+				$element=$nextElement;
+			} else 
+			{
+				return true;
+			}
+		}
+		return false;
+	}
+	
+	/**
+	* Returns true, if this list is empty
+	*
+   	* @param	object Statement	$statement
+   	* @return	integer 
+   	* @access	public
+   	*/
+	function isEmpty()
+	{
+		return !$this->hasProperty($this->rdfFirstResource);
+	}
+	
+	/**
+	* Get all values in the list as an array of ResResources
+	*
+   	* @return	array 
+   	* @access	public
+   	*/
+	function getContentInArray()
+	{
+		$result=array();
+		$element=$this;
+
+		while ($element!==null)
+		{
+			//add the value of the current element to the result if is set.
+			$value=$this->_getValue($element);
+			if ($value!==null)
+				$result[]=$value;
+			
+			//walk through the list until it's end		
+			$nextElement=$this->_getRestElement($element);
+			if (($nextElement !== null) && ($nextElement->getURI()!==RDF_NAMESPACE_URI.RDF_NIL))
+			{
+				$element=$nextElement;
+			} else 
+			{
+				break;
+			}
+		}
+		//return the result
+		return $result;
+	}
+	
+	/**
+	* Change the tail of this list to point to the given list, so that this list 
+	* becomes the list of the concatenation of the elements of 
+	* both lists. This is a side-effecting operation on this list; 
+	* for a non side-effecting alternative, see append. 
+	* 
+	*
+   	* @param	object ResList	$ResList
+   	* @access	public
+   	*/
+	function concatenate($ResList)
+	{
+		//get the last list element
+		$lastElement=$this->_getListElement();
+		//remove the old tail (rdf:nil)
+		$lastElement->removeAll($this->rdfRestResource);
+		//add the $ResList as new tail
+		$lastElement->addProperty($this->rdfRestResource,$ResList);
+	}
+	
+	/**
+	* Answer a new list that is formed by adding each element of 
+	* this list to the head of the given list. This is a non 
+	* side-effecting operation on either this list or the given 
+	* list, but generates a copy of this list. For a more storage 
+	* efficient alternative, see concatenate
+	*
+   	* @param	object ResList	$ResList
+   	* @return	object ResList 
+   	* @access	public
+   	*/
+	function append($resList)
+	{
+		//get a copy of this list
+		$newList=$this->copy();
+		
+		//add all values from the $resList to the new list
+		foreach ($resList->getContentInArray() as $value)
+		{
+			$newList->add($value);	
+		}
+		//return the new list
+		return $newList;
+	}
+	
+	/**
+	* Answer a list that contains all of the elements of this 
+	* list in the same order, but is a duplicate copy in the 
+	* underlying model.
+	*
+   	* @return	object ResList 
+   	* @access	public
+   	*/
+	function copy()
+	{
+		//create a new list in the model
+		$newList=$this->model->createList();
+		//add all values from this list to the new list
+		foreach ($this->getContentInArray() as $value)
+		{
+			$newList->add($value);	
+		}
+		//return the new list
+		return $newList;
+	}
+	
+	/**
+	* Return a reference to a new list cell whose head is value  
+	* and whose tail is this list.
+	*
+   	* @param	object ResResource	$value
+   	* @return	object ResList 
+   	* @access	public
+   	*/
+	function cons($value)
+	{
+		//create a new list
+		$newList=$this->model->createList();
+		//add the new value
+		$newList->add($value);
+		//set this list as the tail of the new list
+		$newList->setTail($this);
+		
+		//return the new list
+		return $newList;
+	}
+	
+	/**
+	* Update the list cell at the front of the list to have the 
+	* given list as tail. The old tail is returned, and remains 
+	* in the model.
+	*
+   	* @param	object ResList	$resList
+   	* @return	object Reslist 
+   	* @access	public
+   	*/
+	function setTail($resList)
+	{
+		//save the old tail
+		$oldTail=$this->getTail();
+		//remove the old tail
+		$this->removeAll($this->rdfRestResource);
+		//add the $resList as new Tail
+		$this->addProperty($this->rdfRestResource,$resList);
+		
+		//return the old tail
+		return $oldTail;
+	}
+	
+	/**
+	* Answer true if this list has the same elements in the 
+	* same order as the given list. Note that the standard equals 
+	* test just tests for equality of two given list cells. 
+	* While such a test is sufficient for many purposes, this 
+	* test provides a broader equality definition, but is 
+	* correspondingly more expensive to test.
+	*
+   	* @param	object ResList	$resList
+   	* @return	boolean 
+   	* @access	public
+   	*/
+	function sameListAs($resList)
+	{
+		//init
+		$indexPos=0;
+		do
+		{
+			//get the values for both lists at the actual position
+			$thisValue=$this->get($indexPos);
+			$thatValue=$resList->get($indexPos);
+			//if the values aren't equal, return false
+			if (($thisValue !== null) && !$thisValue->equals($thatValue))
+				return false;
+				
+			$indexPos++;
+			//walk until this list reaches a null value (end)	
+		} while ($thisValue!==null);
+		
+		//if the other list has a null value at this position too, return true
+		//else return false
+		return ($thatValue===null);
+	}
+	
+	/**
+	* Remove the given value from this list. 
+	* If value does not occur in the list, no action is taken. Since removing the 
+	* head of the list will invalidate the list head cell, in 
+	* general the list must return the list that results from 
+	* this operation. However, in many cases the return value 
+	* will be the same as the object that this method is invoked 
+	* on.
+	*
+   	* @param	object ResResource	$value
+   	* @return	object ResList 
+   	* @access	public
+   	*/
+	function remove($value)
+	{
+		//if the value is the value of the first list element(head)
+		//call the remove head position and return the new head
+		if ($value->equals($this->_getValue($this)))
+			return $this->removeHead();
+	
+		$element=$this;
+		do
+		{	
+			$newElement=$this->_getRestElement($element);
+			
+			//if the value equals the value of the current list element
+			if ($newElement !== null && $value->equals($this->_getValue($newElement)))
+			{
+				//remove the link to the list element to be removed
+				$element->removeAll($this->rdfRestResource);
+				//add a link to the list element AFTER the element to be deleted
+				$element->addProperty($this->rdfRestResource,$this->_getRestElement($newElement));
+				//remove the list element with values
+				$newElement->removeAll($this->rdfFirstResource);
+				$newElement->removeAll($this->rdfRestResource);
+				//return this ResList
+				return $this;	
+			}
+			$element=$newElement;
+		} while ($element!==null);
+		//return this list
+		return $this;	
+	}
+	
+	/**
+	* Answer true if the list is well-formed, by checking that each 
+	* node is correctly typed, and has a head and tail pointer from 
+	* the correct vocabulary
+	*
+   	* @return	boolean 
+   	* @access	public
+   	*/
+	function isValid()
+	{
+		$element=$this;	
+		if ($this->_getValue($this)=== null && $this->_getRestElement($this) === null)
+			return true;
+		do 
+		{
+			//return true if the last element is a rdf:nil
+			if ($element->getURI() == RDF_NAMESPACE_URI.RDF_NIL)
+				return true;
+			//return false, if the current element has no associated value
+			if ($this->_getValue($element) === null)
+				return false;
+						
+			$element=$this->_getRestElement($element);	
+		} while ($element !== null);
+		//return false, if the current element has no rdf:rest property
+		return false;
+	}
+	
+	/**
+	* Get the associated rdf:rest Resource from the suplied ResList element
+	*
+   	* @param	object ResList	$listElement
+   	* @return	object ResList 
+   	* @access	private
+   	*/
+	function _getRestElement($listElement)
+	{
+		//get the rdf:rest property
+		$statement= $this->model->getProperty($listElement,$this->rdfRestResource);
+		//return null, if this property isn't set
+		if ($statement === null)
+			return null;
+			
+		//return the value of the rdf:rest property	
+		return $statement->getObject();	
+	}
+	
+	/**
+	* Returns the list element at the $index position.
+	*
+	* If to $index is suplied, the last list element will be returned
+	
+   	* @param	integer	$index
+   	* @return	object ResResource 
+   	* @access	private
+   	*/
+	function _getListElement($index = null)
+	{
+		$element=$this;
+		$actualIndex=0;
+
+		while ($element!=null)
+		{
+			//return the current element if index matches the current index
+			if ($actualIndex === $index)
+				return $element;
+			
+			//return the current element if it the last one		
+			if ($element->hasProperty($this->rdfRestResource,$this->rdfNilResource))
+				return $element;
+			
+			$nextElement=$this->_getRestElement($element);
+			
+			if ($nextElement!==null)
+			{
+				$element=$nextElement;
+				$actualIndex++;
+			} else 
+			{
+				break;
+			}
+		}
+		return $element;
+	}
+	
+	/**
+	* Get the value associated to the $listResource by the rdf:first property
+	*
+   	* @param	object ResList	$listResource
+   	* @return	object ResResource 
+   	* @access	private
+   	*/
+	function _getValue($listResource)
+	{
+		//Return the value of the rdf:first property or null, if it isn't set
+		$statement=$this->model->getProperty($listResource,$this->rdfFirstResource);
+		if ($statement===null)
+			return null;
+
+		return $statement->getObject();	
+	}
+}
+?>
Index: /Dev/trunk/rdfapi/resModel/ResLiteral.php
===================================================================
--- /Dev/trunk/rdfapi/resModel/ResLiteral.php	(revision 12)
+++ /Dev/trunk/rdfapi/resModel/ResLiteral.php	(revision 12)
@@ -0,0 +1,65 @@
+<?php
+// ----------------------------------------------------------------------------------
+// Class: ResLiteral
+// ----------------------------------------------------------------------------------
+
+/**
+* An RDF literal.
+* The literal supports the xml:lang and rdf:datatype property.
+* For XML datatypes see: http://www.w3.org/TR/xmlschema-2/
+* 
+* @version  $Id: ResLiteral.php 320 2006-11-21 09:38:51Z tgauss $
+* @author Daniel Westphal <mail at d-westphal dot de>
+
+*
+* @package resModel
+* @access	public
+**/
+
+class ResLiteral extends Literal 
+{
+	/**
+	* Holds a reference to the associated model
+	* @var		ResModel
+	* @access	private
+	*/
+	var $model;
+	
+	
+	/**
+    * Constructor
+	* You have to supply a string.
+    *
+	* @param	string	$str		label of the literal
+	* @param 	string $language	optional language identifier
+    */	
+	function ResLiteral($str,$language = null)
+	{
+		parent::Literal($str,$language);
+
+	}
+	
+	/**
+    * Sets the reference to the assocoated model.
+    *
+	* @param	object model	$model
+	* @access public
+    */
+	function setAssociatedModel(& $model)
+	{
+		$this->model=& $model;
+	}
+	
+	/**
+    * Get the reference to the assocoated model.
+    *
+	* @return	object model	$model
+	* @access public
+    */
+	function & getAssociatedModel()
+	{
+		return $this->model;
+	}
+
+} 
+?>
Index: /Dev/trunk/rdfapi/resModel/ResModel.php
===================================================================
--- /Dev/trunk/rdfapi/resModel/ResModel.php	(revision 12)
+++ /Dev/trunk/rdfapi/resModel/ResModel.php	(revision 12)
@@ -0,0 +1,876 @@
+<?php
+// ----------------------------------------------------------------------------------
+// Class: ResModel
+// ----------------------------------------------------------------------------------
+
+/**
+* A ResModel provides an resource centric view on an underlying RDF model.
+* ResModels show information not as statements but as resources with
+* properties, similar to Jena models. ResModels may create Resources [URI
+* nodes and bnodes]. Creating a Resource does not make the Resource visible to
+* the model; Resources are only "in" Models if Statements about them are added
+* to the Model. Similarly the only way to "remove" a Resource from a Model is
+* to remove all the Statements that mention it.
+* 
+* When a Resource or Literal is created by a Model, the Model is free to re-use an existing 
+* Resource or Literal object with the correct values, or it may create a fresh one.
+*
+* @version  $Id: ResModel.php 562 2008-02-29 15:30:18Z cax $
+* @author Daniel Westphal <mail at d-westphal dot de>
+*
+*
+* @package 	resModel
+* @access	public
+**/
+ 
+class ResModel
+{
+	
+	/**
+	* Holds a reference to the assoiated memmodel/dbmodel/infmodel
+	* @var		ResResource
+	* @access	private
+	*/
+	var $model;
+
+	
+	/**
+    * Constructor
+	* You have to supply a memmodel/dbmodel/infmodel to save the statements.
+    *
+    * @param object model $model 
+	* @access	public
+    */	
+	function ResModel(& $model)
+	{
+		if (!is_a($model,'Model'))
+			trigger_error(RDFAPI_ERROR . '(class: ResourceLayer; method: ResourceLayer): 
+				$model has to be object of class Model', E_USER_ERROR);	
+		
+		$this->model =& $model;			
+	}
+	
+	/**
+	* Create a new resource associated with this model. 
+	* If the uri string isn't set, this creates a bnode. 
+	* Otherwise it creates a URI node. 
+	* A URI resource is .equals() to any other URI Resource with the same URI 
+	* (even in a different model - be warned).
+	* 
+	* This method may return an existing Resource with the correct URI and model, 
+	* or it may construct a fresh one, as it sees fit.
+	*
+	* Operations on the result Resource may change this model. 
+	*
+   	* @param	string	$uri
+   	* @return	object ResResource 
+   	* @access	public
+   	*/
+	function createResource($uri = null)
+	{
+		$resResource = new ResResource($uri);
+		//associate the resource with this model, and get a unique identifier
+		//if it is bnode.
+		$resResource->setAssociatedModel($this);
+		
+		return $resResource;
+	} 
+	
+	/**
+	* Create a new Property associated with this model. 
+	* This method may return an existing property with the correct URI and model, 
+	* or it may construct a fresh one, as it sees fit.
+	*
+	* Subsequent operations on the returned property may modify this model. 
+	*  
+	*
+   	* @param	string	$uri
+   	* @return	object ResProperty 
+   	* @access	public
+   	*/
+	function createProperty($uri = null)
+	{
+		$resProperty = new ResProperty($uri);
+		$resProperty->setAssociatedModel($this);
+			
+		return $resProperty;
+	}
+	
+	/**
+	* Create an untyped literal from a String value with a specified language.
+	*
+	* If you want to type this literal, you have to set a datatype before
+	* adding it to the model.
+	*  
+	*
+   	* @param	string	$label
+   	* @param	string	$languageTag
+   	* @return	object ResLiteral 
+   	* @access	public
+   	*/	
+	function createLiteral($label,$languageTag = null)
+	{
+		$resLiteral = new ResLiteral($label,$languageTag);
+		$resLiteral->setAssociatedModel($this);
+		
+		return $resLiteral;
+	}
+	
+	/**
+	* General method to search for triples.
+	* NULL input for any parameter will match anything.
+	* Example:  $result = $m->find( NULL, NULL, $node );
+	* Finds all Statements with $node as object.
+	* Returns an array of statements with ResResources.
+	*
+	* @param	object ResResource	$subject
+	* @param	object ResResource	$predicate
+	* @param	object ResResource	$object
+	* @return	array
+	* @access	public
+	* @throws	PhpError
+	*/
+	function find($subject,$predicate, $object)
+	{
+		$result=array();
+		//convert ResResources to Resources and Blanknodes
+		$resmodel=$this->model->find(	$this->_resNode2Node($subject),
+										$this->_resNode2Node($predicate),
+										$this->_resNode2Node($object)
+									 );
+		//convert Resources, Blanknodes to ResResources							 
+		foreach ($resmodel->triples as $statement) 
+		{
+			$result[]=new Statement($this->_node2ResNode($statement->getSubject()),
+									$this->_node2ResNode($statement->getPredicate(),true),
+									$this->_node2ResNode($statement->getObject())
+								    );
+		};
+		return $result;
+		
+	}
+	
+	/**
+	* 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 with ResResources of the Model where the object equals $node.
+	* Returns an NULL if nothing is found.
+	* You can define an offset to search.
+	*
+	* @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)
+	{
+	
+		$statement = $this->model->findFirstMatchingStatement(	$this->_resNode2Node($subject),
+																$this->_resNode2Node($predicate),
+																$this->_resNode2Node($object),
+																$offset
+															  );
+		if ($statement!==null)
+		{											
+			return new Statement(	$this->_node2ResNode($statement->getSubject()),
+									$this->_node2ResNode($statement->getPredicate(),true),
+									$this->_node2ResNode($statement->getObject())
+							    );
+		} else 
+		{
+			return null;
+		}
+	}
+	
+	/**
+	* 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())
+	* Expects a statements with ResResources(ResLiterals)
+	*
+	* @param	object Statement	$statement
+	* @access	public
+	* @throws	PhpError 
+	*/
+	function add($statement)
+	{
+		return $this->model->add(new Statement(	$this->_resNode2Node($statement->getSubject()),
+												$this->_resNode2Node($statement->getPredicate()),
+												$this->_resNode2Node($statement->getObject()))
+											   );		
+	}
+	/**
+	* Checks if a new statement is already in the Model and adds the statement, if it is not in the Model.
+	* addWithoutDuplicates() is significantly slower then add(). 
+	* Retruns TRUE if the statement is added.
+	* FALSE otherwise.
+	* Expects a statements with ResResources(ResLiterals)
+	*
+	* @param	object Statement	$statement
+	* @return   boolean
+	* @access	public
+	* @throws	PhpError 
+	*/
+	function addWithoutDuplicates($statement)
+	{
+		return $this->model->addWithoutDuplicates(new Statement($this->_resNode2Node($statement->getSubject()),
+																$this->_resNode2Node($statement->getPredicate()),
+																$this->_resNode2Node($statement->getObject()))
+															    );	
+	}
+	
+	/**
+	* Tests if the Model contains the given statement.
+	* TRUE if the statement belongs to the model;
+	* FALSE otherwise.
+	* Expects a statement of ResResources(ResLiterals)
+	*
+	* @param	object Statement	$statement
+	* @return	boolean
+	* @access	public
+	*/
+	function contains(& $statement)
+	{
+		
+		return $this->model->contains(new Statement($this->_resNode2Node($statement->getSubject()),
+													$this->_resNode2Node($statement->getPredicate()),
+													$this->_resNode2Node($statement->getObject()))
+													);
+	}
+	
+	/**
+	* Determine if all of the statements in a model are also contained in this model.
+	* True if all of the statements in $model are also contained in this model and false otherwise.
+	*
+	* @param	object Model	&$model
+	* @return	boolean
+	* @access	public
+	*/
+	function containsAll(& $model)
+	{
+		if (is_a($model,'ResModel'))
+			return $this->model->containsAll($model->getModel());
+		
+		return $this->model->containsAll($model);
+	}
+	
+	/**
+	* Determine if any of the statements in a model are also contained in this model.
+	* True if any of the statements in $model are also contained in this model and false otherwise.
+	*
+	* @param	object Model	&$model
+	* @return	boolean
+	* @access	public
+	*/	
+	function containsAny(& $model)
+	{
+		if (is_a($model,'ResModel'))
+			return $this->model->containsAny($model->getModel());
+		return $this->model->containsAny($model);
+	}
+	
+	/**
+	* Determine if the node (ResResource / ResLiteral) $node appears in any statement of this model.
+	*
+	* @param	object Node	&$node
+	* @return	boolean
+	* @access	public
+	*/	
+	function containsResource(& $node)
+	{
+		if ($this->findFirstMatchingStatement($node,null,null) === null)
+			if ($this->findFirstMatchingStatement(null,$node,null) === null)
+				if ($this->findFirstMatchingStatement(null,null,$node) === null)
+					return false;
+					
+		return true;
+	}
+	
+	/**
+	* Create a literal from a String value with the $dtype Datatype 
+	* An existing literal of the right value may be returned, or a fresh one created. 
+	*
+	* @param	string	$value
+	* @param	string 	$dtype
+	* @return 	object ResLiteral
+	* @access	public
+	*/
+	function createTypedLiteral($value,$dtype)
+	{
+		$resLiteral = new ResLiteral($value);
+		$resLiteral->setDatatype($dtype);
+		$resLiteral->setAssociatedModel($this);
+		
+		return $resLiteral;
+	}
+	
+	/**
+	* Checks if two models are equal.
+	* Two models are equal if and only if the two RDF graphs they represent are isomorphic.
+	* 
+	* Warning: This method doesn't work correct with models where the same blank node has different 
+	* identifiers in the two models. We will correct this in a future version.
+	*
+	* @access	public 
+	* @param	object	model &$that
+	* @throws    phpErrpr
+	* @return	boolean 
+	*/		
+	function equals(& $that)
+	{
+		if (is_a($that,'ResModel'))
+			return $this->model->equals($that->getModel());
+		return $this->model->equals($that);	
+	}
+	
+	/** 
+	* Returns a new model that is the subtraction of another model from this model.
+	*
+	* @param	object Model $model
+	* @return	object MemModel
+	* @access	public
+	* @throws phpErrpr
+	*/ 
+	function subtract($model)
+	{
+		if (is_a($model,'ResModel'))
+			return $this->model->subtract($model->getModel());
+		return $this->model->subtract($model);
+	}
+	
+	/** 
+	* Answer a statement find(s, p, null) with ResResources(ResLiterals) from this model. 
+	* If none exist, return null; if several exist, pick one arbitrarily.
+	*
+	* @param	object ResResource $subject
+	* @param	object ResResource $property
+	* @return	object Statement
+	* @access	public
+	* @throws phpErrpr
+	*/ 
+	function getProperty($subject,$property)
+	{
+	
+		$statement= $this->model->findFirstMatchingStatement(	$this->_resNode2Node($subject),
+																$this->_resNode2Node($property),
+																null
+															);
+		if ($statement === null)
+			return null;
+																
+		return new Statement($this->_node2ResNode($statement->getSubject()),
+									$this->_node2ResNode($statement->getPredicate(),true),
+									$this->_node2ResNode($statement->getObject())
+							);
+													
+	}
+	
+	/**
+	* Checks if MemModel is empty
+	*
+	* @return	boolean
+	* @access	public
+	*/
+	function isEmpty()
+	{
+		return $this->model->isEmpty();
+	}
+	
+	/** 
+	* Returns a ResIterator with all objects in a model.
+	*
+	* @return	object ResIterator
+	* @access	public
+	* @throws phpErrpr
+	*/
+	function listObjects()
+	{
+		return $this->listObjectsOfProperty(null);
+	}
+	
+	/** 
+	* Returns a ResIterator with all objects with a given property and property value.
+	*
+	* @param	object ResResource	$property
+	* @param	object ResResource	$value
+	* @return	object ResIterator
+	* @access	public
+	*/
+	function listObjectsOfProperty($property, $value = null)
+	{
+		return new ResIterator(null,$property,$value,'o',$this);
+	}
+
+	
+	/** 
+	* Returns a ResIterator with all subjects in a model.
+	*
+	* @return	object ResIterator
+	* @access	public
+	* @throws phpErrpr
+	*/
+	function listSubjects()
+	{
+		return $this->listSubjectsWithProperty(null);
+	}
+	
+	/** 
+	* Returns a ResIterator with all subjects with a given property and property value.
+	*
+	* @param	object ResResource	$property
+	* @param	object ResResource	$value
+	* @return	object ResIterator
+	* @access	public
+	* @throws phpErrpr
+	*/
+	function listSubjectsWithProperty($property,$value = null)
+	{
+		return new ResIterator(null,$property,$value,'s',$this);
+	}
+	
+	/**
+	* Removes the statement of ResResources(ResTriples) from the MemModel. 
+	* TRUE if the statement is removed.
+	* FALSE otherwise.
+	*
+	* @param	object Statement	$statement
+	* @return   boolean
+	* @access	public
+	* @throws	PhpError
+	*/	
+	function remove($statement)
+	{
+		return $this->model->remove(new Statement(	$this->_resNode2Node($statement->getSubject()),
+													$this->_resNode2Node($statement->getPredicate()),
+													$this->_resNode2Node($statement->getObject())
+												  ));
+	}
+	
+	/**
+	* Number of statements in the MemModel
+	*
+	* @return	integer
+	* @access	public
+	*/
+	function size()
+	{
+		return $this->model->size();
+	}
+	
+	/** 
+	* Returns a new Model that is the set-union of the model with another model.
+	* Duplicate statements are removed. If you want to allow duplicates, use addModel() which is much faster.
+	*
+	* The result of taking the set-union of two or more RDF graphs (i.e. sets of triples) 
+	* is another graph, which we will call the merge of the graphs. 
+	* Each of the original graphs is a subgraph of the merged graph. Notice that when forming 
+	* a merged graph, two occurrences of a given uriref or literal as nodes in two different 
+	* graphs become a single node in the union graph (since by definition they are the same 
+	* uriref or literal) but blank nodes are not 'merged' in this way; and arcs are of course 
+	* never merged. In particular, this means that every blank node in a merged graph can be 
+	* identified as coming from one particular graph in the original set of graphs.
+	* 
+	* Notice that one does not, in general, obtain the merge of a set of graphs by concatenating 
+	* their corresponding N-triples documents and constructing the graph described by the merged 
+	* document, since if some of the documents use the same node identifiers, the merged document 
+	* will describe a graph in which some of the blank nodes have been 'accidentally' merged. 
+	* To merge Ntriples documents it is necessary to check if the same nodeID is used in two or 
+	* more documents, and to replace it with a distinct nodeID in each of them, before merging the 
+	* documents. (Not implemented yet !!!!!!!!!!!)
+	*
+	* @param	object Model	$model
+	* @return	object MemModel
+	* @access	public
+	* @throws phpErrpr
+	*
+	*/
+	function & unite(& $model)
+	{
+		if (is_a($model,'ResModel'))
+			return $this->model->unite($model->getModel());
+		return $this->model->unite($model);
+	}
+	
+	/** 
+	* 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)  
+	{
+		if (is_a($model,'ResModel'))
+			return $this->model->addModel($model->getModel());
+		return $this->model->addModel($model);
+	}
+	
+	/**
+	* Create a new RDF Container from type rdf:Alt 
+	* This method may return an existing container with the correct URI and model, 
+	* or it may construct a fresh one, as it sees fit.
+	*
+	* Subsequent operations on the returned Container may modify this model. 
+	*  
+	*
+   	* @param	string	$uri
+   	* @return	object ResProperty 
+   	* @access	public
+   	*/
+	function createAlt($uri = null)
+	{
+		$resAlt = new ResAlt($uri);
+		$resAlt->setAssociatedModel($this);
+			
+		return $resAlt;		
+	}
+	
+	/**
+	* Create a new RDF Container from type rdf:Bag 
+	* This method may return an existing container with the correct URI and model, 
+	* or it may construct a fresh one, as it sees fit.
+	*
+	* Subsequent operations on the returned Container may modify this model. 
+	*  
+	*
+   	* @param	string	$uri
+   	* @return	object ResProperty 
+   	* @access	public
+   	*/
+	function createBag($uri = null)
+	{
+		$resBag = new ResBag($uri);
+		$resBag->setAssociatedModel($this);
+			
+		return $resBag;
+	}
+	
+	/**
+	* Create a new RDF Container from type rdf:Seq 
+	* This method may return an existing container with the correct URI and model, 
+	* or it may construct a fresh one, as it sees fit.
+	*
+	* Subsequent operations on the returned Container may modify this model. 
+	*  
+	*
+   	* @param	string	$uri
+   	* @return	object ResProperty 
+   	* @access	public
+   	*/
+	function createSeq($uri = null)
+	{
+		$resSeq = new ResSeq($uri);
+		$resSeq->setAssociatedModel($this);
+			
+		return $resSeq;
+	}	
+	
+	/**
+	* Create a new RDF Collection from type rdf:List 
+	* This method may return an existing container with the correct URI and model, 
+	* or it may construct a fresh one, as it sees fit.
+	*
+	* Subsequent operations on the returned Container may modify this model. 
+	*  
+	*
+   	* @param	string	$uri
+   	* @return	object ResProperty 
+   	* @access	public
+   	*/
+	function createList($uri = null)
+	{
+		$resList = new ResList($uri);
+		$resList->setAssociatedModel($this);
+			
+		return $resList;	
+	}
+	
+	/**
+	* Returns a reference to the underlying model (Mem/DB/InfModel) that contains the statements 
+	*  
+	*
+   	* @return	object Model 
+   	* @access	public
+   	*/	
+	function & getModel()
+	{
+		return  $this->model;
+	}
+	
+	
+	/**
+	* Internal method, that returns a resource URI that is unique for the Model.
+	* URIs are generated using the base_uri of the Model, the prefix and a unique number.
+	* If no prefix is defined, the bNode prefix, defined in constants.php, is used.
+	*
+	* @param	string	$prefix
+	* @return	string
+	* @access	private
+	*/
+	function getUniqueResourceURI($bnodePrefix)
+	{
+		return $this->model->getUniqueResourceURI($bnodePrefix);
+	}
+	
+	/**
+	* 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.
+	*
+	* @param 	string 	$filename
+	* @param 	string 	$type
+	* @param   boolean $stream
+	* @access	public
+	*/
+	function load($filename, $type = NULL, $stream=false)
+	{
+		$this->model->load($filename, $type, $stream);
+	}
+	
+	/**
+	* Return current baseURI.
+	*
+	* @return  string
+	* @access	public
+	*/
+	function getBaseURI()  
+	{
+		return $this->model->getBaseURI();
+	}
+
+	/**
+	* Saves the RDF,N3 or N-Triple serialization of the MemModel 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 MemModel couldn't be saved to the file.
+	*
+	* @access	public 
+	* @param 	string 	$filename
+	* @param 	string 	$type
+	* @throws   PhpError
+	* @return	boolean   
+	*/  
+	function saveAs($filename, $type ='rdf') 
+	{
+		return $this->model->saveAs($filename, $type ='rdf');
+	}
+	
+	/**
+	* Writes the RDF serialization of the MemModel as HTML table.
+	*
+	* @access	public 
+	*/  
+	function writeAsHTMLTable()
+	{
+		$this->model->writeAsHtmlTable();
+	}
+	
+	/** 
+	* Returns a new model containing all the statements which are in both this model and another.
+	*
+	* @param	object Model	$model
+	* @return	object MemModel
+	* @access	public
+	* @throws phpErrpr
+	*/ 
+	function & intersect(& $model)
+	{
+		if (is_a($model,'ResModel'))
+			return $this->model->intersect($model->getModel());
+		return $this->model->intersect($model);
+	}
+	
+	/** 
+	* converts a Resource,Blanknode,Literal into a ResResource, ResProperty, or ResLiteral
+	*
+	* @param	object Node	$node
+	* @param	boolean		$isProperty
+	* @return	object ResResource / ResProperty / ResLiteral
+	* @access	private
+	* @throws phpErrpr
+	*/ 
+	function _node2ResNode($node, $isProperty = false)
+	{
+		if (is_a($node,'Literal'))
+		{
+			$return= new ResLiteral($node->getLabel(),$node->getLanguage());
+			$return->setDatatype($node->getDatatype());
+			$return->setAssociatedModel($this);
+
+			return $return;
+		}
+		if (is_a($node,'Resource'))
+		{
+			if ($isProperty)
+			{
+				$res= new ResProperty($node->getLabel());
+			} else 
+			{
+				$res= new ResResource($node->getLabel());
+			}
+			$res->setAssociatedModel($this);
+			if (is_a($node,'Blanknode'))
+				$res->setIsAnon(true);	
+		
+			return $res;
+		}
+	}
+	
+	/** 
+	* converts a ResResource, ResProperty, or ResLiteral into a Resource, Blanknode, or Literal
+	*
+	* @param	object ResNode	$resNode
+	* @return	object Node
+	* @access	private
+	* @throws phpErrpr
+	*/ 
+	function _resNode2Node($resNode)
+	{
+		if (is_a($resNode,'ResResource'))
+		{
+			if ($resNode->getIsAnon())	
+			{
+				$return=new BlankNode($resNode->getURI());
+			} else 
+			{
+				$return=new Resource($resNode->getURI());	
+			}	
+		return $return;	
+		}
+		
+		if (is_a($resNode,'ResLiteral'))
+		{
+			$literal=new Literal($resNode->getLabel(),$resNode->getLanguage());
+			if ($resNode->getDatatype() != null)
+				$literal->setDatatype($resNode->getDatatype());
+			return $literal;
+		}
+	}
+	
+	/**
+	* Set a base URI for the MemModel.
+	* Affects creating of new resources and serialization syntax.
+	* If the URI doesn't end with # : or /, then a # is added to the URI. 
+	* @param	string	$uri
+	* @access	public
+	*/
+	function setBaseURI($uri) 
+	{
+		$this->model->setBaseURI($uri);
+	}
+	
+	/**
+	* Writes the RDF serialization of the MemModel as HTML table.
+	*
+	* @access	public 
+	* @return	string 
+	*/  
+	function writeRdfToString() 
+	{
+		return $this->model->writeRdfToString();	
+	}
+	
+	/**
+	* Perform an RDQL query on this MemModel.
+	* This method returns an associative array of variable bindings.
+	* The values of the query variables can either be RAP's objects (instances of Node)
+	* if $returnNodes set to TRUE, or their string serialization.
+	*
+	* @access	public
+	* @param string $queryString
+	* @param boolean $returnNodes
+	* @return  array   [][?VARNAME] = object Node  (if $returnNodes = TRUE)
+	*      OR  array   [][?VARNAME] = string
+	*
+	*/
+	function & rdqlQuery($queryString, $returnNodes = TRUE) 
+	{
+		$ret = $this->model->rdqlQuery($queryString, $returnNodes);
+		return $ret;
+	}
+	
+	/**
+	* Perform an RDQL query on this MemModel.
+	* This method returns an RdqlResultIterator of variable bindings.
+	* The values of the query variables can either be RAP's objects (instances of Node)
+	* if $returnNodes set to TRUE, or their string serialization.
+	*
+	* @access	public
+	* @param string $queryString
+	* @param boolean $returnNodes
+	* @return  object RdqlResultIterator = with values as object Node  (if $returnNodes = TRUE)
+	*      OR  object RdqlResultIterator = with values as strings if (if $returnNodes = FALSE)
+	*
+	*/
+	function rdqlQueryAsIterator($queryString, $returnNodes = TRUE) 
+	{
+		return $this->model->rdqlQueryAsIterator($queryString, $returnNodes);
+	}
+	
+	
+	/**
+	* Returns the models namespaces.
+	*
+	* @author   Tobias Gauß <tobias.gauss@web.de>
+	* @access   public
+	* @return   Array
+	*/
+	function getParsedNamespaces(){
+		return $this->model->getParsedNamespaces();
+	}
+
+
+
+	/**
+	* Adds the namespaces to the model. This method is called by 
+	* the parser. !!!! addParsedNamespaces() not overwrites manual
+	* added namespaces in the model !!!!
+	*
+	* @author   Tobias Gauß <tobias.gauss@web.de>
+	* @access   public
+	* @param    Array $newNs
+	*/
+	function addParsedNamespaces($newNs){
+		$this->model->addParsedNamespaces($newNs);
+	}
+
+
+	/**
+	* Adds a namespace and prefix to the model.
+	*
+	* @author   Tobias Gauß <tobias.gauss@web.de>
+	* @access   public
+	* @param    String $prefix, String $nmsp
+	*/
+	function addNamespace($prefix, $namespace){
+		$this->model->addNamespace($prefix, $namespace);
+	}
+	
+	/**
+	* removes a single namespace from the model
+	*
+	* @author   Tobias Gauß <tobias.gauss@web.de>
+	* @access   public
+	* @param    String $nmsp
+	*/
+	function removeNamespace($nmsp){
+		return $this->model->removeNamespace($nmsp);
+	}
+
+	
+	
+	
+	
+	
+}
+
+?>
Index: /Dev/trunk/rdfapi/resModel/ResModelP.php
===================================================================
--- /Dev/trunk/rdfapi/resModel/ResModelP.php	(revision 12)
+++ /Dev/trunk/rdfapi/resModel/ResModelP.php	(revision 12)
@@ -0,0 +1,24 @@
+<?php
+// ----------------------------------------------------------------------------------
+// ResModel Package
+// ----------------------------------------------------------------------------------
+//
+// Description               : ResModel package
+//
+// Author: Daniel Westphal	<mail at d-westphal dot de>
+//
+// ----------------------------------------------------------------------------------
+
+// Include ResModel classes
+require_once( RDFAPI_INCLUDE_DIR . 'resModel/ResModel.php');
+require_once( RDFAPI_INCLUDE_DIR . 'resModel/ResResource.php');
+require_once( RDFAPI_INCLUDE_DIR . 'resModel/ResContainer.php');
+require_once( RDFAPI_INCLUDE_DIR . 'resModel/ResAlt.php');
+require_once( RDFAPI_INCLUDE_DIR . 'resModel/ResBag.php');
+require_once( RDFAPI_INCLUDE_DIR . 'resModel/ResLiteral.php');
+require_once( RDFAPI_INCLUDE_DIR . 'resModel/ResProperty.php');
+require_once( RDFAPI_INCLUDE_DIR . 'resModel/ResSeq.php');
+require_once( RDFAPI_INCLUDE_DIR . 'resModel/ResIterator.php');
+require_once( RDFAPI_INCLUDE_DIR . 'resModel/ResList.php');
+
+?>
Index: /Dev/trunk/rdfapi/resModel/ResProperty.php
===================================================================
--- /Dev/trunk/rdfapi/resModel/ResProperty.php	(revision 12)
+++ /Dev/trunk/rdfapi/resModel/ResProperty.php	(revision 12)
@@ -0,0 +1,32 @@
+<?php
+// ----------------------------------------------------------------------------------
+// Class: ResProperty
+// ----------------------------------------------------------------------------------
+
+/**
+* An RDF Property.
+*
+*
+* @version  $Id: ResProperty.php 320 2006-11-21 09:38:51Z tgauss $
+* @author Daniel Westphal <mail at d-westphal dot de>
+*
+*
+* @package resModel
+* @access	public
+**/
+class ResProperty extends ResResource  
+{
+	
+	/**
+    * Constructor
+	* You can supply a URI
+    *
+    * @param string $uri 
+	* @access	public
+    */	
+	function ResProperty($uri)
+	{
+		parent::ResResource($uri);
+	}
+} 
+?>
Index: /Dev/trunk/rdfapi/resModel/ResResource.php
===================================================================
--- /Dev/trunk/rdfapi/resModel/ResResource.php	(revision 12)
+++ /Dev/trunk/rdfapi/resModel/ResResource.php	(revision 12)
@@ -0,0 +1,212 @@
+<?php
+/**
+* ----------------------------------------------------------------------------------
+* Class: ResResource
+* ----------------------------------------------------------------------------------
+* @package resModel
+**/
+
+/**
+* An RDF Resource.
+* Resource instances, when created, are associated with a specific model. They support a 
+* range of methods, such as getProperty() and addProperty() which will access or modify 
+* that model. This enables the programmer to write code in a compact and easy style.
+*
+* @version  $Id: ResResource.php 320 2006-11-21 09:38:51Z tgauss $
+* @author Daniel Westphal <mail at d-westphal dot de>
+*
+*
+* @package resModel
+* @access	public
+**/
+class ResResource extends Resource 
+{
+	/**
+	* Holds a reference to the associated model
+	* @var		ResModel
+	* @access	private
+	*/
+	var $model;
+	
+	/**
+	* Is true, if this resource is an anonymous node.
+	* @var		boolean
+	* @access	private
+	*/
+	var $isAnon;
+	
+	
+	/**
+    * Constructor
+	* You can supply a uri
+    *
+    * @param string $uri 
+	* @access	public
+    */		
+	function ResResource($uri)
+	{
+			parent::Resource($uri);
+			$this->isAnon = ($uri === null);		
+	}
+	
+	/**
+    * Sets the reference to the assocoated model.
+    *
+	* @param	object Model	$model
+	* @access public
+    */	
+	function setAssociatedModel(& $model)
+	{
+		$this->model=& $model;
+		if ($this->isAnon)
+			$this->uri=$this->model->getUniqueResourceURI(BNODE_PREFIX);
+	}
+	
+	/**
+    * Get the reference to the assocoated model.
+    *
+	* @return	object Model	$model
+	* @access public
+    */
+	function getAssociatedModel()
+	{
+		return $this->model;
+	}
+	
+	/**
+    * Sets the URI of this resource
+    *
+	* @param	string $uri
+	* @access public
+    */	
+	function setURI($uri)
+	{
+		$this->uri = $uri;
+	}
+	
+	/**
+	* Add a property to this resource.
+	* A statement with this resource as the subject, p as the predicate and o 
+	* as the object is added to the model associated with this resource.
+	*
+   	* @param	ResResource				$property
+   	* @param	ResResource/ResLiteral	$object
+   	* @return	object ResResource 
+   	* @access	public
+   	*/
+	function addProperty($property,$object)
+	{
+		$this->model->add(new Statement($this,$property,$object));
+
+		return $this;
+	}
+	
+	/**
+	* List all the values with the property p as statements in an array.
+	*
+   	* @param	ResResource		$property
+   	* @return	ResIterator 
+   	* @access	public
+   	*/
+	function listProperties($property = null)
+	{
+		return $this->model->find($this,$property,null);
+	}
+	
+	/**
+	* Answer some statement (this, p, O) in the associated model. 
+	* If there are several such statements, any one of them may be returned. 
+	* If no such statements exist, null is returned.
+	*
+   	* @param	ResResource				$property
+   	* @return	object ResResource 
+   	* @access	public
+   	*/	
+	function getProperty($property)
+	{
+		return $this->model->getProperty($this,$property);
+	}
+	
+	/**
+	* Determine whether this resource has any values for a given property.
+	*
+   	* @param	ResResource		$property
+   	* @param	ResResource		$value
+   	* @return	object ResResource 
+   	* @access	public
+   	*/	
+	function hasProperty($property, $value = null)
+	{
+		$ret= $this->model->findFirstMatchingStatement($this,$property,$value);
+		
+		return ($ret!==null);	
+	}
+	
+	/**
+	* Determine whether this resource is an anonymous resource
+	*
+   	* @return	boolean
+   	* @access	public
+   	*/		
+	function getIsAnon()
+	{
+		return $this->isAnon;	
+	}
+	
+	/**
+	* Set whether this resource is an anonymous resource
+	*
+   	* @param	boolean
+   	* @access	public
+   	*/	
+	function setIsAnon($isAnon)
+	{
+		 $this->isAnon=$isAnon;	
+	}
+		
+	/**
+	* Checks if the resource equals another resource.
+	* Two resources are equal, if they have the same URI
+	*
+	* @access	public 
+	* @param	object	resource $that
+	* @return	boolean 
+	*/  
+	function equals ($that) 
+	{
+		if (is_a($that,'ResLiteral'))
+			return $that->equals($this);
+			
+	    return ($that!==null && ($this->getURI() == $that->getURI()));
+	}
+	
+	/**
+	* Delete all the statements with predicate p for this resource from 
+	* its associated model.
+	*
+	* @access	public 
+	* @param	object	resource $property
+	* @return	object ResResource 
+	*/ 
+	function removeAll($property = null)
+	{	
+		foreach ($this->model->find($this,$property,null) as $statement)
+		{
+			$this->model->remove($statement);	
+		}
+		return $this;
+	}
+	
+	/**
+	* Delete all the properties for this resource from the associated model.
+	*
+	* @access	public 
+	* @return	object ResResource 
+	*/ 
+	function removeProperties()
+	{
+		$this->removeAll();
+		return $this;
+	}
+}
+?>
Index: /Dev/trunk/rdfapi/resModel/ResSeq.php
===================================================================
--- /Dev/trunk/rdfapi/resModel/ResSeq.php	(revision 12)
+++ /Dev/trunk/rdfapi/resModel/ResSeq.php	(revision 12)
@@ -0,0 +1,153 @@
+<?php
+// ----------------------------------------------------------------------------------
+// Class: ResSeq
+// ----------------------------------------------------------------------------------
+
+/**
+* This interface defines methods for accessing RDF Sequence resources. 
+* These methods operate on the RDF statements contained in a model.
+*
+* @version  $Id: ResSeq.php 320 2006-11-21 09:38:51Z tgauss $
+* @author Daniel Westphal <mail at d-westphal dot de>
+*
+* @package 	resModel
+* @access	public
+**/
+class ResSeq extends ResContainer 
+{
+	
+	/**
+    * Constructor
+	* You can supply a URI
+    *
+    * @param string $uri 
+	* @access	public
+    */		
+	function ResSeq($uri = null)
+	{
+		parent::ResContainer($uri);
+		$this->containerType=new ResResource(RDF_NAMESPACE_URI.RDF_SEQ);
+	}
+	
+	/**
+	* Insert a new member into the sequence at the specified position.
+	* The existing member at that position, and all others with higher indexes, 
+	* have their index increased by one.
+	*
+	* @param 	integer	$index
+   	* @param	object ResResource/ResLiteral	$resResource
+   	* @return	boolean 
+   	* @access	public
+   	*/
+	function addAtIndex($index, $object)
+	{
+		//get a members index
+		$memberIndex= $this->getMembers();
+				
+		//type this container, if it isn't already typed
+		if(!$this->hasProperty(new ResResource(RDF_NAMESPACE_URI.RDF_TYPE)))
+			$this->addProperty(new ResResource(RDF_NAMESPACE_URI.RDF_TYPE),$this->containerType);
+		
+		//renumber all higher members
+		for ($i = count($memberIndex);$i >= $index ; $i--)
+		{
+			$this->removeAll($this->_getMembershipPropertyWithIndex($i));
+			$this->addProperty($this->_getMembershipPropertyWithIndex($i+1),$memberIndex[$i]);
+		}	
+		//remove the old value at this position
+		$this->removeAll($this->_getMembershipPropertyWithIndex($index));
+		//add the new value
+		$this->addProperty($this->_getMembershipPropertyWithIndex($index),$object);
+				
+		return $this;
+	}
+	
+	/**
+	* Get the member at a given index
+	*
+	* @param 	integer	$index
+   	* @return	object ResResource/ResLiteral 
+   	* @access	public
+   	*/
+	function getMember($index)
+	{
+		$result=$this->listProperties($this->_getMembershipPropertyWithIndex($index));
+		if (isset($result[0]))
+		{
+			return $result[0];
+		} 
+		else 
+		{
+			return null;
+		}
+	}
+	
+	/**
+	* Return the index of a given member of the sequence.
+	* If the same value appears more than once in the sequence, it is undefined 
+	* which of the indexes will be returned.
+	* If the member is not found in this sequence, a value of 0 is returned.
+	*
+	* @param 	object ResResource/ResLiteral $object
+   	* @return	integer
+   	* @access	public
+   	*/
+	function indexOf($object)
+	{
+		//check all members, until $object is found
+		foreach ($this->listProperties() as $statement)
+		{
+			$predicateLabel=$statement->getLabelPredicate();
+			if ($this->_predicateLabelMatchesMembershipProperty($predicateLabel))
+			{
+				if($object->equals($statement->getObject()))
+					//analyze the container membership property and return the index
+					return $this->_getMemberIndexNrFromMembershipPropertyLabel($predicateLabel);
+			}	
+		}
+		//return 0 if $object wasn't found
+		return 0;
+	}
+	
+	/**
+	* Remove the member at the specified index.
+	* All other members with a higher index will have their index reduced by one.
+	*
+	* @param 	integer	$index	 
+   	* @access	public
+   	*/
+	function removeAtIndex($index)
+	{
+		$memberIndex= $this->getMembers();
+
+
+		$this->removeAll($this->_getMembershipPropertyWithIndex($index));
+
+		for ($i = $index;$i < count($memberIndex); $i++)
+		{
+			$this->removeAll($this->_getMembershipPropertyWithIndex($i+1));
+			$this->addProperty($this->_getMembershipPropertyWithIndex($i),$memberIndex[$i+1]);
+		}		
+		return $this;
+	}
+	
+	/**
+	* Set the value at a given index in the sequence.
+	*
+	* If the index is not in the range of the sequence, false is returned
+	*
+	* @param 	integer	$index
+   	* @return	boolean
+   	* @access	public
+   	*/
+	function set($index, $object)
+	{
+		if (!$this->hasProperty($this->_getMembershipPropertyWithIndex($index)))
+			return false;
+			
+		$this->removeAll($this->_getMembershipPropertyWithIndex($index));
+		$this->addProperty($this->_getMembershipPropertyWithIndex($index),$object);
+		return true;
+	}
+}
+?>
Index: /Dev/trunk/rdfapi/sparql/ClientQuery.php
===================================================================
--- /Dev/trunk/rdfapi/sparql/ClientQuery.php	(revision 12)
+++ /Dev/trunk/rdfapi/sparql/ClientQuery.php	(revision 12)
@@ -0,0 +1,56 @@
+<?php
+
+// ----------------------------------------------------------------------------------
+// Class: ClientQuery
+// ----------------------------------------------------------------------------------
+
+/**
+* ClientQuery Object to run a SPARQL Query against a SPARQL server.
+*
+* @version  $Id: ClientQuery.php 465 2007-06-27 16:47:57Z cweiske $
+* @author   Tobias Gauï¿œ <tobias.gauss@web.de>
+* @license http://www.gnu.org/licenses/lgpl.html LGPL
+*
+* @package sparql
+*/
+
+class ClientQuery extends Object {
+
+	var $default  = array();
+	var $named    = array();
+	var $prefixes = array();
+	var $query;
+
+	/**
+	* Adds a default graph to the query object.
+	*
+	* @param String  $default  default graph name
+	*/
+	function addDefaultGraph($default){
+		if(!in_array($this->named,$this->default))
+		$this->default[] = $default;
+	}
+	/**
+	* Adds a named graph to the query object.
+	*
+	* @param String  $default  named graph name
+	*/
+	function addNamedGraph($named){
+		if(!in_array($named,$this->named))
+		$this->named[] = $named;
+	}
+	/**
+	* Adds the SPARQL query string to the query object.
+	*
+	* @param String  $query the query string
+	*/
+	function query($query){
+		$this->query = $query;
+	}
+
+}
+
+
+
+
+?>
Index: /Dev/trunk/rdfapi/sparql/Constraint.php
===================================================================
--- /Dev/trunk/rdfapi/sparql/Constraint.php	(revision 12)
+++ /Dev/trunk/rdfapi/sparql/Constraint.php	(revision 12)
@@ -0,0 +1,95 @@
+<?php
+require_once RDFAPI_INCLUDE_DIR . 'util/Object.php';
+// ---------------------------------------------
+// class: Constraint.php
+// ---------------------------------------------
+
+
+/**
+* Represents a constraint. A value constraint is a boolean- valued expression
+* of variables and RDF Terms.
+*
+* @author   Tobias Gauss <tobias.gauss@web.de>
+* @version	 $Id$
+* @license http://www.gnu.org/licenses/lgpl.html LGPL
+*
+* @package sparql
+*/
+Class Constraint extends Object{
+
+    /**
+    * The expression string.
+    * @var string
+    */
+    protected $expression;
+
+    /**
+    *  True if it is an outer filter, false if not.
+    * @var boolean
+    */
+    protected $outer;
+
+    /**
+    *   The expression tree
+    *   @var array
+    */
+    protected $tree = null;
+
+    /**
+    * Adds an expression string.
+    *
+    * @param  String $exp the expression String
+    * @return void
+    */
+    public function addExpression($exp)
+    {
+        $this->expression = $exp;
+    }
+
+    /**
+    * Returns the expression string.
+    *
+    * @return String  the expression String
+    */
+    public function getExpression()
+    {
+        return $this->expression;
+    }
+
+
+    /**
+    * Sets the filter type to outer or inner filter.
+    * True for outer false for inner.
+    *
+    * @param  boolean $boolean
+    * @return void
+    */
+    public function setOuterFilter($boolean)
+    {
+        $this->outer = $boolean;
+    }
+
+    /**
+    * Returns true if this constraint is an outer filter- false if not.
+    *
+    * @return boolean
+    */
+    public function isOuterFilter()
+    {
+        return $this->outer;
+    }
+
+
+    public function getTree()
+    {
+        return $this->tree;
+    }//public function getTree()
+
+    public function setTree($tree)
+    {
+        $this->tree = $tree;
+    }//public function setTree($tree)
+
+}
+// end class: Constraint.php
+?>
Index: /Dev/trunk/rdfapi/sparql/FilterFunctions.php
===================================================================
--- /Dev/trunk/rdfapi/sparql/FilterFunctions.php	(revision 12)
+++ /Dev/trunk/rdfapi/sparql/FilterFunctions.php	(revision 12)
@@ -0,0 +1,137 @@
+<?php
+/**
+* List of functions used to evaluate the FILTER statements in
+* SPARQL queries.
+*
+* @package sparql
+* @author   Tobias Gauss <tobias.gauss@web.de>
+* @version	 $Id$
+* @license http://www.gnu.org/licenses/lgpl.html LGPL
+*
+*/
+
+ 
+
+
+/**
+* Evaluates the regex() function. Returns true if the regex is matched false if not.
+*
+* @param String  $string   the string which has to be evaluated
+* @param String  $pattern  the regex pattern
+* @param String  $flags    additional flags like "i"
+* @return boolean
+*/
+function regex($string,$pattern,$flags = ''){
+	$string = trim($string);
+	$pattern = trim($pattern);
+	if(strpos($string,"str_")===0){
+		$string = substr($string,4);
+		$pattern = substr($pattern,4);
+		$flags = substr($flags,4);
+	}else{
+		return false;
+	}
+	if(preg_match('/'.$pattern.'/'.$flags,$string))
+	return true;
+	else
+	return false;
+}
+
+/**
+* Evaluates the dateTime() function.Tries to convert a date string into
+* a unix timestamp.
+*
+* @param  String $string the date string
+* @return integer        the corresponding unix timestamp
+*/
+function dateTime($string){
+	$string = trim($string);
+	if(strpos($string,"str_")===0)
+	$string = substr($string,4);
+
+	$time = strtotime($string);
+	if($time == -1)
+	return $string;
+	else
+	return $time;
+}
+
+
+/**
+* Evaluates the langMatches() function. Return true if the lang tag matches false if not.
+*
+* @param String $lang_range the string.
+* @param String $lang_tag the regex pattern
+* @return boolean
+*/
+function langMatches($lang_range,$lang_tag){
+
+	if($lang_range == null)
+	return false;
+
+	if(strpos($lang_range,"str_")===0)
+	$lang_range = substr($lang_range,4);
+	if(strpos($lang_tag,"str_")===0)
+	$lang_tag = substr($lang_tag,4);
+
+	if(strtolower($lang_range) == strtolower($lang_tag))
+	return true;
+	$tags =  preg_match_all("/[^\-\s].[^\-\s]*/",$lang_range,$hits);
+	if($tags){
+		if($lang_tag == '*')
+		return true;
+		foreach($hits[0] as $tag){
+			if(strtolower($tag) == strtolower($lang_tag))
+			return true;
+		}
+		return false;
+	}else{
+		return false;
+	}
+}
+
+/**
+* Evaluates the str() function. Returns the string representation of a 
+* variable or RDF term.
+*
+* @param  String $string the string
+* @return boolean
+*/
+function str($string){
+	$str = preg_match("/\".[^\"]*\"|\'.[^\']*\'/",$string,$hits);
+	if($str != 0){
+		return "str_".$hits[0];
+	}else{
+		if(strpos($string,"str_")===0){
+			return $string;
+		}else{
+			if(strpos($string,"uri_")===0)
+				return "str_".substr($string,4);
+			if(strpos($string,'<')==0)
+				return "str_".substr($string,1,-1);
+		}
+	}
+	return false;
+}
+
+/**
+* Evaluates the lang() function. Returns lang tag of a Literal.
+*
+* @param  String $string the string.
+* @return String the lang tag or false if there is no language tag.
+*/
+function lang($string){
+	$str = preg_match("/\".[^\"]*\"@(.[^\s]*)|\'.[^\']*\'@(.[^\s]*)/",$string,$hits);
+	if($str){
+		if($hits[1] != null)
+		return $hits[1];
+		else
+		return $hits[2];
+	}else{
+		return false;
+	}
+}
+
+
+
+?>
Index: /Dev/trunk/rdfapi/sparql/GraphPattern.php
===================================================================
--- /Dev/trunk/rdfapi/sparql/GraphPattern.php	(revision 12)
+++ /Dev/trunk/rdfapi/sparql/GraphPattern.php	(revision 12)
@@ -0,0 +1,295 @@
+<?php
+// ---------------------------------------------
+// class: GraphPattern
+// ---------------------------------------------
+
+/**
+* A graph pattern which consists of triple patterns, optional
+* or union graph patterns and filters.
+*
+* @author   Tobias Gauss <tobias.gauss@web.de>
+* @version     $Id$
+* @license http://www.gnu.org/licenses/lgpl.html LGPL
+*
+* @package sparql
+*/
+
+class GraphPattern extends Object{
+
+    /**
+    * Graphname. 0 if its in the default graph.
+    */
+    protected $graphname = null;
+
+    /**
+    * Array of QueryTriple objects
+    * @var array
+    */
+    protected $triplePatterns = array();
+
+    /**
+    * A List of Constraint objects
+    * @var array
+    */
+    protected $constraints = array();
+
+    /**
+    * @var int Pointer to optional pattern.
+    */
+    protected $optional = null;
+
+    /**
+    * @var int Pointer to union pattern.
+    */
+    protected $union = null;
+
+    /**
+    * ID of the pattern in the pattern list that
+    * this pattern is subpattern of.
+    * @var int
+    */
+    protected $subpatternOf = null;
+
+    /**
+    * @var boolean TRUE if the pattern is open- FALSE if closed.
+    */
+    public $open = false;
+
+    /**
+    * @var boolean TRUE if the GraphPattern is a construct pattern.
+    */
+    public $isConstructPattern = false;
+
+
+    /**
+    * @var int The GraphPatterns id.
+    */
+    public $patternId = null;
+
+
+    /**
+    * Constructor
+    */
+    public function GraphPattern() {
+        $this->open               = true;
+        $this->isConstructPattern = false;
+        $this->constraints        = array();
+        $this->triplePatterns     = array();
+    }
+
+    /**
+    * Returns the graphname.
+    *
+    * @return String
+    */
+    public function getGraphname(){
+        return $this->graphname;
+    }
+
+    /**
+    * Returns the triple pattern of the graph pattern.
+    *
+    * @return Array
+    */
+    public function getTriplePatterns(){
+        return $this->triplePatterns;
+    }
+
+    /**
+    * Returns a constraint if there is one false if not.
+    *
+    * @return Constraint
+    */
+    public function getConstraints() {
+        return $this->constraints;
+    }
+
+    /**
+    * Returns a pointer to an optional graph pattern.
+    *
+    * @return integer
+    */
+    public function getOptional() {
+        return $this->optional;
+    }
+
+    /**
+    * Returns a pointer to the parent pattern this pattern
+    * is subpattern of.
+    *
+    * @return integer
+    */
+    public function getSubpatternOf() {
+        return $this->subpatternOf;
+    }
+
+    /**
+    * Returns a pointer to a union graph pattern.
+    *
+    * @return integer
+    */
+    public function getUnion() {
+        return $this->union;
+    }
+
+    /**
+    * Sets the graphname.
+    *
+    * @param  String $name
+    * @return void
+    */
+    public function setGraphname($name) {
+        $this->graphname = $name;
+    }
+
+    /**
+    * Adds List of QueryTriples to the GraphPattern.
+    *
+    * @param  array $trpP
+    * @return void
+    */
+    public function addTriplePatterns($trpP) {
+        $this->triplePatterns = array_merge($this->triplePatterns, $trpP);
+    }
+
+    /**
+    * Sets the List of QueryTriples to the GraphPattern.
+    *
+    * @param  array $trpP
+    * @return void
+    */
+    public function setTriplePatterns($trpP) {
+        $this->triplePatterns = $trpP;
+    }
+
+    /**
+    * Adds a single Constraint to the GraphPattern.
+    *
+    * @param  Constraint $cons
+    */
+    public function addConstraint(&$cons) {
+        $this->constraints[] = $cons;
+    }
+
+    /**
+    * Adds an array of Constraint objects to the GraphPattern.
+    *
+    * @param  array $cons
+    */
+    public function addConstraints(&$cons) {
+        $this->constraints = array_merge($this->constraints, $cons);
+    }
+
+    /**
+    * Adds a pointer to an optional graphPattern.
+    *
+    * @param  integer $patternId
+    * @return void
+    */
+    public function setOptional($patternId) {
+        $this->optional = &$patternId;
+    }
+
+    /**
+    * Adds a pointer to a union graphPattern.
+    *
+    * @param  integer $patternId
+    * @return void
+    */
+    public function setUnion($patternId) {
+        $this->union = &$patternId;
+    }
+
+    /**
+    * Adds a pointer to a pattern that
+    * this one is subpattern of
+    *
+    * @param  integer $patternId
+    */
+    public function setSubpatternOf($patternId) {
+        $this->subpatternOf = $patternId;
+    }
+
+
+    /**
+    * Sets the GraphPatterns Id.
+    *
+    * @param  integer $id
+    * @return void
+    */
+    public function setId($id){
+        $this->patternId = $id;
+    }
+
+    /**
+    * Returns the GraphPatterns id.
+    *
+    * @return integer
+    */
+    public function getId(){
+        return $this->patternId;
+    }
+
+
+
+    /**
+    *   Returns an array of all variables used in this
+    *   graph pattern.
+    *   All variables are listed only once (unique).
+    *
+    *   @return array   Array of variable names
+    */
+    public function getVariables()
+    {
+        $arVars = array();
+
+        foreach ($this->triplePatterns as $pattern) {
+            $arVars = array_merge($arVars, $pattern->getVariables());
+        }
+
+        return array_unique($arVars);
+    }//public function getVariables()
+
+
+
+    /**
+    *   Checks if the graph pattern is empty (contains no
+    *   usable data).
+    *   Occurs when using "{}" without pre- or suffixes
+    *   WHERE
+    *   {
+    *    { ?person rdf:type foaf:Person } .
+    *   }
+    *
+    *   @return boolean     True if the pattern is empty.
+    */
+    public function isEmpty()
+    {
+        return
+               count($this->triplePatterns) == 0
+            && count($this->constraints)    == 0
+            && $this->getGraphname()        === null
+        ;
+    }//public function isEmpty()
+
+
+
+    /**
+    *   When cloning, we need to clone some subobjects, too
+    */
+    public function __clone()
+    {
+        if (count($this->triplePatterns) > 0) {
+            foreach ($this->triplePatterns as $nId => $pattern) {
+                $this->triplePatterns[$nId] = clone $this->triplePatterns[$nId];
+            }
+        }
+        if (count($this->constraints) > 0) {
+            foreach ($this->constraints as $nId => $constraint) {
+                $this->constraints[$nId] = clone $this->constraints[$nId];
+            }
+        }
+    }
+
+}// end class: GraphPattern.php
+?>
Index: /Dev/trunk/rdfapi/sparql/Query.php
===================================================================
--- /Dev/trunk/rdfapi/sparql/Query.php	(revision 12)
+++ /Dev/trunk/rdfapi/sparql/Query.php	(revision 12)
@@ -0,0 +1,685 @@
+<?php
+require_once RDFAPI_INCLUDE_DIR . 'sparql/GraphPattern.php';
+
+/**
+* The Class Query represents a SPARQL query.
+*
+*
+* @author  Tobias Gauss <tobias.gauss@web.de>
+* @version $Id$
+* @license http://www.gnu.org/licenses/lgpl.html LGPL
+*
+* @package sparql
+*/
+class Query extends Object
+{
+    /**
+    * The BASE part of the SPARQL query.
+    * @var string
+    */
+    protected $base;
+
+    /**
+    * Original SPARQL query string
+    * @var string
+    */
+    protected $queryString = null;
+
+    /**
+    * Array that contains used prefixes and namespaces.
+    * Key is the prefix, value the namespace.
+    *
+    * @example
+    * array(8) {
+    *  ["rdf"] => string(43) "http://www.w3.org/1999/02/22-rdf-syntax-ns#"
+    *  ["rdfs"]=> string(37) "http://www.w3.org/2000/01/rdf-schema#"
+    * }
+    *
+    * @var array
+    */
+    public $prefixes = array();
+
+    /**
+    * Array of result variables that shall be returned.
+    * E.g. "?name", "?mbox"
+    *
+    * @var array
+    */
+    protected $resultVars = array();
+
+    /**
+    * What form/type of result should be returned.
+    *
+    * One of:
+    * - "ask"
+    * - "count"
+    * - "construct"
+    * - "describe"
+    * - "select"
+    * - "select distinct"
+    *
+    * @var string
+    * @see http://www.w3.org/TR/rdf-sparql-query/#QueryForms
+    */
+    protected $resultForm = null;
+
+    /**
+    * Contains the result part of the SPARQL query.
+    * Array of GraphPattern
+    *
+    * @var array
+    */
+    protected $resultPart = array();
+
+    /**
+    *  Contains the FROM part of the SPARQL query.
+    * @var array
+    */
+    protected $fromPart = array();
+
+    /**
+    * Contains the FROM NAMED part of the SPARQL query.
+    * @var array
+    */
+    protected $fromNamedPart = array();
+
+    /**
+    * Optional solution modifier of the query.
+    * Array with three keys:
+    *  "order by", "limit", "offset"
+    * If they are not set, their value is null
+    *
+    * "order by" can be an array with subarrays, each of those
+    *  subarrays having two keys: "val" and "type".
+    *  "val" determines the variable ("?mbox"), "type" is
+    *  "asc" or "desc"
+    *
+    * @var array
+    */
+    protected $solutionModifier = array();
+
+    /**
+    *  Blanknode counter.
+    * How many blank nodes are in $resultPart
+    *
+    * @var int
+    */
+    protected $bnodeCounter = 0;
+
+    /**
+    * GraphPattern counter.
+    * How many GraphPattern are in $resultPart
+    *
+    * @var int
+    */
+    public $graphPatternCounter = 0;
+
+    /**
+    * List of all vars used in the query.
+    * Key is the variable (e.g. "?x"), value
+    * is boolean true
+    *
+    * @var array
+    */
+    public $usedVars = array();
+
+    /**
+    * If the query type is CONSTRUCT this variable contains the
+    * CONSTRUCT graph pattern.
+    */
+    protected $constructPattern = null;
+
+    /**
+    * TRUE if the query is empty FALSE if not.
+    *
+    * @var boolean
+    */
+    public $isEmpty = null;
+
+    /**
+    *   Language of variables. NULL if the variable has no
+    *   language tag (e.g. @en) set.
+    *   $varname => $language tag
+    *   @var array
+    */
+    public $varLanguages = array();
+
+    /**
+    *   Datatype of variables. NULL if the variable has no
+    *   data type (e.g. ^^xsd::integer) set.
+    *   $varname => $datatype
+    *   @var array
+    */
+    public $varDatatypes = array();
+
+
+
+    /**
+    * Constructor
+    */
+    public function Query(){
+        $this->resultForm = null;
+        $this->solutionModifier['order by'] = null;
+        $this->solutionModifier['limit']    = null;
+        $this->solutionModifier['offset']   = null;
+        $this->bnodeCounter = 0;
+        $this->graphPatternCounter = 0;
+
+    }
+
+    /**
+    * Returns the BASE part of the query.
+    *
+    * @return String
+    */
+    public function getBase(){
+        return $this->base;
+    }
+
+    /**
+    * Returns the prefix map of the query.
+    *
+    * @return Array
+    */
+    public function getPrefixes(){
+        return $this->prefixes;
+    }
+    
+    /**
+    * Returns a list containing the result vars.
+    *
+    * @return Array
+    */
+    public function getResultVar($strName) {
+        foreach ($this->resultVars as $var) {
+            if ($var->getVariable() == $strName) {
+                return $var;
+            }
+        }
+        return false;
+    }
+
+    /**
+    * Returns a list containing the result vars.
+    *
+    * @return Array
+    */
+    public function getResultVars(){
+        return $this->resultVars;
+    }
+
+    /**
+    * Returns the type the result shall have.
+    * E.g. "select", "select distinct", "ask", ...
+    *
+    * @see $resultForm
+    *
+    * @return string
+    */
+    public function getResultForm(){
+        return $this->resultForm;
+    }
+
+    /**
+    * Returns a list containing the graph patterns of the query.
+    *
+    * @return Array
+    */
+    public function getResultPart(){
+        return $this->resultPart;
+    }
+
+    /**
+    * Returns the FROM clause of the query.
+    *
+    * @return String
+    */
+    public function getFromPart(){
+        return $this->fromPart;
+    }
+
+    /**
+    * Returns the FROM NAMED clause of the query.
+    *
+    * @return Array
+    */
+    public function getFromNamedPart(){
+        return $this->fromNamedPart;
+    }
+
+    /**
+    * Returns $isEmpty variable
+    * @return boolean
+    */
+    public function isEmpty() {
+        return $this->isEmpty;
+    }
+
+    /**
+    * Returns an unused Bnode label.
+    *
+    * @return String
+    */
+    public function getBlanknodeLabel(){
+        return "_:bN".$this->bnodeCounter++;
+    }
+
+
+    /**
+    * Sets the base part.
+    *
+    * @param String $base
+    * @return void
+    */
+    public function setBase($base){
+        $this->base = $base;
+    }
+
+
+    /**
+    * Adds a prefix to the list of prefixes.
+    *
+    * @param  String $prefix
+    * @param  String $label
+    * @return void
+    */
+    public function addPrefix($prefix, $label){
+        $this->prefixes[$prefix]= $label;
+    }
+
+    /**
+    * Adds a variable to the list of result variables.
+    *
+    * @param  String $var
+    * @return void
+    */
+    public function addResultVar($var){
+        $this->resultVars[] = $var;
+        $var->setDatatype($this->getDatatype($var));
+
+        $this->varLanguages[$var->getId()] = self::getLanguageTag($var);
+        $this->varDatatypes[$var->getId()] = $this->getDatatype($var);
+    }
+
+
+    /**
+    * Sets the result form.
+    *
+    * @param  String $form
+    * @return void
+    */
+    public function setResultForm($form){
+        $this->resultForm = strtolower($form);
+    }
+
+
+    /**
+    * Sets the result part.
+    *
+    * @param  array Array of graph patterns
+    */
+    public function setResultPart($resultPart) {
+        $this->resultPart = $resultPart;
+    }
+
+    /**
+    * Adds a graph pattern to the result part.
+    *
+    * @param  GraphPattern $pattern
+    * @return void
+    */
+    public function addGraphPattern($pattern){
+        $pattern->setId($this->graphPatternCounter);
+        $this->resultPart[] = $pattern;
+        $this->graphPatternCounter++;
+    }
+
+    /**
+    * Adds a construct graph pattern to the query.
+    *
+    * @param  GraphPattern $pattern
+    * @return void
+    */
+    public function addConstructGraphPattern($pattern){
+        $this->constructPattern = $pattern;
+    }
+
+
+    /**
+    * Adds a graphuri to the from part.
+    *
+    * @param  String $graphURI
+    * @return void
+    */
+    public function addFrom($graphURI){
+        $this->fromPart[] = $graphURI;
+    }
+
+    /**
+    * Adds a graphuri to the from named part.
+    *
+    * @param  String $graphURI
+    * @return void
+    */
+    public function addFromNamed($graphURI){
+        $this->fromNamedPart[] = $graphURI;
+    }
+
+    /**
+    * Sets a solution modifier.
+    *
+    * @param  String $name
+    * @param  Value  $value
+    * @return void
+    */
+    public function setSolutionModifier($name, $value){
+        $this->solutionModifier[$name] = $value;
+    }
+
+
+    /**
+    * Generates a new GraphPattern. If it is a CONSTRUCT graph pattern
+    * $constr has to set to TRUE, FALSE if not.
+    *
+    * @param  boolean $constr
+    * @return GraphPattern
+    */
+    public function getNewPattern($constr = false){
+        $pattern = new GraphPattern();
+        if ($constr) {
+            $this->addConstructGraphPattern($pattern);
+        } else {
+            $this->addGraphPattern($pattern);
+        }
+        return $pattern;
+    }
+
+    /**
+    * Adds a new variable to the variable list.
+    *
+    * @param  String $var
+    * @return void
+    */
+    public function addUsedVar($var){
+        $this->usedVars[$var]=true;
+    }
+
+    /**
+    * Returns a list with all used variables.
+    *
+    * @return Array
+    */
+    public function getAllVars(){
+        return array_keys($this->usedVars);
+    }
+
+    /**
+    * Gets the solution modifiers of the query.
+    * $solutionModifier['order by'] = value
+    *                  ['limit']    = vlaue
+    *                  ['offset']   = value
+    *
+    *
+    * @return Array
+    */
+    public function getSolutionModifier(){
+        return $this->solutionModifier;
+    }
+
+
+    /**
+    * Returns the construvtGraphPattern of the query if there is one.
+    *
+    * @return GraphPattern
+    */
+    public function getConstructPattern(){
+        return $this->constructPattern;
+    }
+
+
+
+    /**
+    *   Returns a list of variables used in the construct patterns.
+    *
+    *   @return array Array of variable names, unique.
+    */
+    public function getConstructPatternVariables()
+    {
+        $arVars = array();
+/*
+        if (count($this->resultPart) > 0) {
+            foreach ($this->resultPart as $pattern) {
+                $arVars = array_merge($arVars, $pattern->getVariables());
+            }
+        }
+*/
+        if ($this->constructPattern) {
+            $arVars = array_merge($arVars, $this->constructPattern->getVariables());
+        }
+
+        return array_unique($arVars);
+    }//public function getConstructPatternVariables()
+
+
+
+    /**
+    *   Returns the language of a variable if the tag is set (e.g. @en)
+    *   Returns NULL if no language is set.
+    *
+    *   @param string Sparql variable name
+    *   @return mixed NULL or language tag
+    */
+    public static function getLanguageTag($var)
+    {
+        $nAt = strpos($var, '@');
+        if ($nAt === false) {
+            return null;
+        }
+        //in case @ and ^^ are combined
+        $nHatHat = strpos($var, '^^', $nAt + 1);
+        if ($nHatHat === false) {
+            $tag = substr($var, $nAt + 1);
+        } else {
+            $tag = substr($var, $nAt + 1, $nHatHat - $nAt - 1);
+        }
+        return $tag;
+    }//public static function getLanguageTag($var)
+
+
+
+    /**
+    *   Returns the datatype of a variable if it is set.
+    *
+    *   @param string Sparql variable name
+    *   @return mixed NULL or datatype
+    */
+    public function getDatatype($var)
+    {
+        $nHatHat = strpos($var, '^^');
+        if ($nHatHat === false) {
+            return null;
+        }
+        $nAt = strpos($var, '@', $nHatHat + 2);
+        if ($nAt === false) {
+            $type = substr($var, $nHatHat + 2);
+        } else {
+            $type = substr($var, $nHatHat + 2, $nAt - $nHatHat - 2);
+        }
+
+        $fullUri = $this->getFullUri($type);
+        if ($fullUri === false) {
+            $fullUri = $type;
+            if ($fullUri[0] == '<' && substr($fullUri, -1) == '>') {
+                $fullUri = substr($fullUri, 1, -1);
+            }
+        }
+
+        return $fullUri;
+    }//public function getDatatype($var)
+
+
+
+    /**
+    * Gets the full URI of a qname token.
+    *
+    * @param  string $token
+    * @return string The complete URI of a given token, false if $token is not
+    *                a qname or the prefix is not defined
+    */
+    public function getFullUri($token)
+    {
+        $pattern="/^([^:]*):([^:]*)$/";
+        if (preg_match($pattern, $token, $hits) > 0) {
+
+            if (isset($this->prefixes{$hits{1}})) {
+                return substr($this->base, 1, -1)
+                     . $this->prefixes{$hits{1}}
+                     . $hits{2};
+            }
+            if ($hits{1}=='_') {
+                return "_".$hits{2};
+            }
+        }
+
+        return false;
+    }
+
+
+
+    /**
+    *   Checks if the query is complete
+    *   (so that querying is possible)
+    *
+    *   @return boolean true if the query is complete
+    */
+    public function isComplete()
+    {
+        if ($this->resultForm === null) {
+            return false;
+        }
+        //TODO: maybe check selected vars and construct pattern depending
+        // on the resultform
+        return true;
+    }//public function isIncomplete()
+
+
+
+    /**
+    * Sets the orignal query string
+    *
+    * @param string $queryString SPARQL query string
+    */
+    public function setQueryString($queryString)
+    {
+        $this->queryString = $queryString;
+    }//public function setQueryString($queryString)
+
+
+
+    /**
+    * Returns the orignal query string
+    *
+    * @return string SPARQL query string
+    */
+    public function getQueryString()
+    {
+        return $this->queryString;
+    }//public function getQueryString()
+
+}// end class: Query.php
+
+
+
+class Query_ResultVariable
+{
+    public $variable = null;
+    public $datatype = null;
+    public $language = null;
+    public $alias    = null;
+    public $func     = null;
+
+
+    public function __construct($variable)
+    {
+        $this->variable = $variable;
+        $this->language = Query::getLanguageTag($variable);
+    }
+
+
+
+    public function setAlias($alias)
+    {
+        $this->alias = $alias;
+    }
+
+
+
+    public function setFunc($func)
+    {
+        $this->func = $func;
+    }
+
+
+
+    public function setDatatype($datatype)
+    {
+        $this->datatype = $datatype;
+    }
+
+
+
+    public function getId()
+    {
+        //FIXME
+        return $this->variable;
+    }
+
+
+
+    public function getFunc()
+    {
+        return $this->func;
+    }
+
+
+
+    public function getLanguage()
+    {
+        return $this->language;
+    }
+
+
+
+    public function getDatatype()
+    {
+        return $this->datatype;
+    }
+
+
+
+    public function getName()
+    {
+        if ($this->alias !== null) {
+            return $this->alias;
+        }
+        //FIXME: support for nested(functions())
+        return $this->variable;
+    }
+
+
+
+    public function getVariable()
+    {
+        return $this->variable;
+    }
+
+
+
+    public function __toString()
+    {
+        return $this->getName();
+    }
+
+}//class Query_ResultVariable
+
+?>
Index: /Dev/trunk/rdfapi/sparql/QueryTriple.php
===================================================================
--- /Dev/trunk/rdfapi/sparql/QueryTriple.php	(revision 12)
+++ /Dev/trunk/rdfapi/sparql/QueryTriple.php	(revision 12)
@@ -0,0 +1,123 @@
+<?php
+// ---------------------------------------------
+// Class: QueryTriple
+// ---------------------------------------------
+require_once RDFAPI_INCLUDE_DIR . 'sparql/SparqlVariable.php';
+
+/**
+* Represents a query triple with subject, predicate and object.
+*
+* @author   Tobias Gauss <tobias.gauss@web.de>
+* @version	$Id$
+* @license http://www.gnu.org/licenses/lgpl.html LGPL
+*
+* @package sparql
+*/
+class QueryTriple extends Object
+{
+
+    /**
+    * The QueryTriples Subject.
+    * Can be a BlankNode or Resource, string in
+    * case of a variable
+    * @var Node/string
+    */
+    protected $subject;
+
+    /**
+    * The QueryTriples Predicate.
+    * Normally only a Resource, string in
+    * case of a variable
+    * @var Node/string
+    */
+    protected $predicate;
+
+    /**
+    * The QueryTriples Object.
+    * Can be BlankNode, Resource or Literal, string in
+    * case of a variable
+    * @var Node/string
+    */
+    protected $object;
+
+
+
+    /**
+    * Constructor
+    *
+    * @param Node $sub  Subject
+    * @param Node $pred Predicate
+    * @param Node $ob   Object
+    */
+    public function QueryTriple($sub,$pred,$ob)
+    {
+        $this->subject   = $sub;
+        $this->predicate = $pred;
+        $this->object    = $ob;
+    }
+
+    /**
+    * Returns the Triples Subject.
+    *
+    * @return Node
+    */
+    public function getSubject()
+    {
+        return $this->subject;
+    }
+
+    /**
+    * Returns the Triples Predicate.
+    *
+    * @return Node
+    */
+    public function getPredicate()
+    {
+        return $this->predicate;
+    }
+
+    /**
+    * Returns the Triples Object.
+    *
+    * @return Node
+    */
+    public function getObject()
+    {
+        return $this->object;
+    }
+
+
+
+    /**
+    *   Returns an array of all variables in this triple.
+    *
+    *   @return array   Array of variable names
+    */
+    public function getVariables()
+    {
+        $arVars = array();
+
+        foreach (array('subject', 'predicate', 'object') as $strVar) {
+            if (SparqlVariable::isVariable($this->$strVar)) {
+                $arVars[] = $this->$strVar;
+            }
+        }
+
+        return $arVars;
+    }//public function getVariables()
+
+
+
+    public function __clone()
+    {
+        foreach (array('subject', 'predicate', 'object') as $strVar) {
+            if (is_object($this->$strVar)) {
+                $this->$strVar = clone $this->$strVar;
+            }
+        }
+    }//public function __clone()
+
+}//class QueryTriple extends Object
+
+// end class: QueryTriple.php
+?>
Index: /Dev/trunk/rdfapi/sparql/SPARQL.php
===================================================================
--- /Dev/trunk/rdfapi/sparql/SPARQL.php	(revision 12)
+++ /Dev/trunk/rdfapi/sparql/SPARQL.php	(revision 12)
@@ -0,0 +1,20 @@
+<?php
+// ----------------------------------------------------------------------------------
+// SPARQL
+// ----------------------------------------------------------------------------------
+//
+// Description               : Sparql package
+// ----------------------------------------------------------------------------------
+
+// include SPARQL classes
+require_once( RDFAPI_INCLUDE_DIR . 'sparql/FilterFunctions.php' );
+require_once( RDFAPI_INCLUDE_DIR . 'sparql/Constraint.php' );
+require_once( RDFAPI_INCLUDE_DIR . 'sparql/GraphPattern.php' );
+require_once( RDFAPI_INCLUDE_DIR . 'sparql/Query.php' );
+require_once( RDFAPI_INCLUDE_DIR . 'sparql/QueryTriple.php' );
+require_once( RDFAPI_INCLUDE_DIR . 'sparql/SparqlParserException.php' );
+require_once( RDFAPI_INCLUDE_DIR . 'sparql/SparqlParser.php' );
+require_once( RDFAPI_INCLUDE_DIR . 'sparql/SparqlEngine.php' );
+require_once( RDFAPI_INCLUDE_DIR . 'sparql/SparqlEngineDb.php' );
+
+?>
Index: /Dev/trunk/rdfapi/sparql/SparqlClient.php
===================================================================
--- /Dev/trunk/rdfapi/sparql/SparqlClient.php	(revision 12)
+++ /Dev/trunk/rdfapi/sparql/SparqlClient.php	(revision 12)
@@ -0,0 +1,151 @@
+<?php
+
+// ----------------------------------------------------------------------------------
+// Class: SparqlEngine
+// ----------------------------------------------------------------------------------
+
+/**
+* Client for querying a sparql server.
+*
+* @version  $Id: SparqlClient.php 573 2008-05-26 09:04:29Z cyganiak $
+* @author   Tobias GauÃ <tobias.gauss@web.de>
+* @license http://www.gnu.org/licenses/lgpl.html LGPL
+*
+* @package sparql
+*/
+
+class SparqlClient extends Object {
+
+	var $server;
+	var $output;	
+
+	/**
+	* Constructor of SparlClient.
+	*
+	* @param String  $server   server address.
+	*/
+	function SparqlClient($server){
+		$this->server = $server;
+		$this->output = "array";
+	}
+
+
+	/**
+	* Sets the output format for a SELECT or ASK query. Possible formats are "xml" for
+	* Sparql Query Results XML Format (http://www.w3.org/TR/rdf-sparql-XMLres/) or array
+	* for the format described in our SparqlEngine.
+	*
+	* @param String  $format   the format.
+	*/
+	function setOutputFormat($format){
+		if(strtolower($format)=="xml")
+		$this->output = "xml";
+		if(strtolower($format)=="array")
+		$this->output = "array";
+
+	}
+
+	/**
+	* Main function of SparqlClient.
+	*
+	* @param ClientQuery  $query   the ClientQuery object.
+	* @return mixed returns an array that contains the variables an their bindings or a MemModel
+	*
+	*/
+	function query($query){
+		if(!is_a($query,"ClientQuery"))
+		die;//ErrorHandling
+
+		$url    = $this->_buildurl($query);
+		$result = $this->_http_get($url);
+		return $this->returnResult($result);
+
+	}
+
+
+	/**
+	* Helper function that builds the url.
+	*
+	* @param ClientQuery  $query   the ClientQuery Object.
+	*/
+
+	function _buildurl($query){
+		$url = "";
+		$url = $this->server."?query=".urlencode($query->query);
+		foreach($query->default as $defaultg){
+			$url = $url."&default-graph-uri=".$defaultg;
+		}
+		foreach($query->named as $namedg){
+			$url = $url."&named-graph-uri=".$namedg;
+		}
+
+		return $url;
+
+	}
+
+	/**
+	* Returns the query result.
+	*
+	* @param String  $result  the result.
+	* @return mixed
+	*/
+	function returnResult($result){
+
+		if(strpos($result,"<rdf:RDF")){
+			include_once(RDFAPI_INCLUDE_DIR.PACKAGE_SYNTAX_RDF);
+			$parser = new RdfParser();
+			return $parser->generateModel(substr($result,strpos($result,"<rdf:RDF")));
+		}
+
+		if($this->output == "xml"){
+			$pos = strpos($result,"<?xml");
+			return substr($result,$pos);
+		}
+		if($this->output == "array"){
+			//	$pos = strpos($buffer,"<?xml");
+			return $this->parseResult($result);
+		}
+		return $result;
+	}
+
+
+	function parseResult($buffer){
+		include_once(RDFAPI_INCLUDE_DIR.PACKAGE_SYNTAX_SPARQLRES);
+		$parser = new SparqlResultParser();
+		return $parser->parse($buffer);
+	}
+
+
+	/**
+	* Executes the GET Request.
+	*
+	* @param String  $url  the url.
+	* @return String result.
+	*/
+	function _http_get($url)
+	{
+		$url = parse_url($url);
+		$port = isset($url['port']) ? $url['port'] : 80;
+
+		$fp = fsockopen($url['host'], $port);
+
+		$replace = $url['path'];
+
+		fputs($fp, "GET ".$replace."?".$url['query']." HTTP/1.0\r\n");
+		fputs($fp, "Host: ". $url['host']."\r\n");
+		fputs($fp, "Accept: application/sparql-results+xml, application/rdf+xml\r\n");
+		fputs($fp, "Connection: close\r\n\r\n");
+
+		$buffer = "";
+		while ($tmp = fread($fp, 1024))
+		{
+			$buffer .= $tmp;
+		}
+
+		return preg_replace("/^.*?(\r\n\r\n|\n\n)/s", "", $buffer);
+	}
+}
+
+
+
+?>
Index: /Dev/trunk/rdfapi/sparql/SparqlEngine.php
===================================================================
--- /Dev/trunk/rdfapi/sparql/SparqlEngine.php	(revision 12)
+++ /Dev/trunk/rdfapi/sparql/SparqlEngine.php	(revision 12)
@@ -0,0 +1,1180 @@
+<?php
+require_once RDFAPI_INCLUDE_DIR . 'util/Object.php';
+require_once RDFAPI_INCLUDE_DIR . 'sparql/FilterFunctions.php';
+require_once RDFAPI_INCLUDE_DIR . 'sparql/SparqlEngine/ResultConverter.php';
+
+// ----------------------------------------------------------------------------------
+// Class: SparqlEngine
+// ----------------------------------------------------------------------------------
+
+/**
+* This engine executes SPARQL queries against an RDF Datatset.
+*
+* @version  $Id$
+* @author   Tobias GauÃ <tobias.gauss@web.de>
+* @license http://www.gnu.org/licenses/lgpl.html LGPL
+*
+* @package sparql
+*/
+
+Class SparqlEngine extends Object{
+
+
+    /**
+    *   The query object.
+    *   @var Query
+    */
+    protected $query;
+
+    /**
+    *   The RDF Dataset.
+    *   @var Dataset
+    */
+    protected $dataset;
+
+	// Store the single instance of Database 
+    protected static $instance;
+
+
+    /**
+    * Use SparqlEngine::factory() instead of this
+    * constructor.
+    */
+    protected function __construct()
+    {
+        //protected to prevent direct instantiation
+    }
+
+	public static function getInstance() 
+    { 
+        if (!self::$instance) 
+        { 
+            self::$instance = new SparqlEngine(); 
+        } 
+
+        return self::$instance; 
+    }
+
+    /**
+    * Creates a new instance of the SparqlEngine, depending on the
+    * given model. For example, if you pass a DbModel, you will
+    * get a SparqlEngine specialized on databases.
+    *
+    * @param Model $model   RDF model that uses the engine
+    */
+    public function factory($model = null)
+    {
+        if ($model !== null && $model instanceof DbModel) {
+            require_once RDFAPI_INCLUDE_DIR . 'sparql/SparqlEngineDb.php';
+            return new SparqlEngineDb($model);
+        } else {
+            return new SparqlEngine();
+        }
+    }
+
+
+
+    /**
+    * The query engine's main method.
+    *
+    * @param  Dataset       $dataset    the RDF Dataset
+    * @param  mixed         $query      the parsed SPARQL query
+    * @param  String        $resultform the result form. If set to 'xml' the result will be
+    *                                   SPARQL Query Results XML Format as described in http://www.w3.org/TR/rdf-sparql-XMLres/ .
+    * @return Array/String  Type of the result depends on $resultform.
+    */
+    public function queryModel($dataset, Query $query, $resultform = false)
+    {
+        $this->query   = $query;
+        $this->dataset = $dataset;
+
+        if($this->query->isEmpty){
+            $vartable[0]['patternResult'] = null;
+            return SparqlEngine_ResultConverter::convertFromResult(
+                $vartable,
+                $this,
+                $resultform
+            );
+        }
+
+        $graphlist = $this->preselectGraphs();
+        /// match graph patterns against the RDF Dataset
+        $patternlist = $this->matchPatterns($graphlist);
+        // filter results- apply inner filters
+        $patternlist = $this->filterPatterns($patternlist,false);
+        // join pattern results
+        $vartable = $this->joinResults($patternlist);
+        // filter results- apply outer filters
+        $vartable = $this->filterPatterns($vartable,true);
+
+        if ($vartable[0]['patternResult'] != null) {
+            // sort vars (ORDER BY, LIMIT, OFFSET)
+            $vartable = $this->sortVars($vartable[0]['patternResult']);
+            $qrf      = $this->query->getResultForm();
+            if ($qrf == 'select' || $qrf == 'select distinct') {
+                $vars     = $this->query->getResultVars();
+                $vartable = $this->selectVars($vartable, $vars);
+                if ($qrf == 'select distinct') {
+                    $vartable = $this->distinct($vartable);
+                }
+            }
+        } else {
+            $vartable = null;
+        }
+
+        return SparqlEngine_ResultConverter::convertFromResult(
+            $vartable,
+            $this,
+            $resultform
+        );
+    }//public function queryModel($dataset, Query $query, $resultform = false)
+
+
+
+    /**
+    * Matches all graph Patterns against the dataset and generates an array which
+    * contains the result sets for every given GraphPattern.
+    *
+    * @param  Array      $graphlist   the graphlist which contains the names of the named
+    *                    graphs which has to be queried.
+    * @return Array
+    */
+    protected function matchPatterns($graphlist){
+        $patternlist = array();
+        // get the result part from the query
+        $resultPart = $this->query->getResultPart();
+        // for each GrapPattern in the result part
+        if($resultPart)
+        foreach($resultPart as $graphPattern){
+            $this->matchPattern($patternlist, $graphlist, $graphPattern);
+        }
+        return $patternlist;
+    }
+
+
+
+    /**
+    * Finds tuples that match one graph pattern.
+    *
+    * @param  Array        $patternlist list that contains the graphPatterns
+    * @param  array        $graphlist   the graphlist
+    * @param  GraphPattern $graphPattern the pattern which has to be matched
+    * @return void
+    */
+    protected function matchPattern(&$patternlist, $graphlist, &$graphPattern) {
+        // generate an empty result set
+        $finalRes = null;
+        // if the GraphPattern has triple patterns
+        if (count($graphPattern->getTriplePatterns()) > 0) {
+            // check if the pattern has a GRAPH clause and if this Iri is in $graphlist
+            $newGraphList = $this->_checkGraphs($graphPattern,$graphlist);
+            if($newGraphList){
+                $qt = $graphPattern->getTriplePatterns();
+                $resultSet = $this->findTuplesMatchingOnePattern($qt[0], $newGraphList);
+                for ($i=1; $i<count($qt); $i++) {
+                    $rs = $this->findTuplesMatchingOnePattern($qt[$i], $newGraphList);
+                    $resultSet = $this->joinTuples($resultSet, $rs);
+                    if(!$resultSet)
+                    break;
+                }
+                if($finalRes != null){
+                    $finalRes = $this->joinTuples($finalRes,$resultSet);
+                }else{
+                    $finalRes = $resultSet;
+                }
+            }
+        }
+        // dependencies between pattern results
+        $patternlist[$graphPattern->getId()]['hasOptional']     = 0;
+        $patternlist[$graphPattern->getId()]['hasUnion']        = 0;
+        $patternlist[$graphPattern->getId()]['patternResult']   = $finalRes;
+
+        $op = $graphPattern->getOptional();
+        $un = $graphPattern->getUnion();
+
+        $patternlist[$graphPattern->getId()]['optionalTo']      = $op;
+        if(is_int($op))
+        $patternlist[$op]['hasOptional']++;
+
+        $patternlist[$graphPattern->getId()]['unionWith']       = $un;
+        if(is_int($un))
+        $patternlist[$un]['hasUnion']++;
+
+        $constraint = $graphPattern->getConstraints();
+        if(count($constraint) > 0){
+            foreach($constraint as $constr){
+                if($constr->isOuterFilter()){
+                    $patternlist[$graphPattern->getId()]['outerFilter'][]          = $constr;
+                    $patternlist[$graphPattern->getId()]['innerFilter'][]          = null;
+                }else{
+                    $patternlist[$graphPattern->getId()]['innerFilter'][]          = $constr;
+                    $patternlist[$graphPattern->getId()]['outerFilter'][]          = null;
+                }
+            }
+        }else{
+            $patternlist[$graphPattern->getId()]['innerFilter']          = null;
+            $patternlist[$graphPattern->getId()]['outerFilter']          = null;
+        }
+    }
+
+
+    /**
+    * Finds Tuples matching one TriplePattern.
+    *
+    * @param  TriplePattern $pattern
+    * @param  Array         $graphlist
+    * @return Array
+    */
+    protected function findTuplesMatchingOnePattern($pattern, $graphlist){
+        $var = null;
+        $sub  = $pattern->getSubject();
+        $pred = $pattern->getPredicate();
+        $obj  = $pattern->getObject();
+
+        if(is_string($sub)||$sub instanceof BlankNode){
+            if(is_string($sub))
+            $var['sub'] = $sub;
+            $sub = null;
+        }
+        if(is_string($pred)||$pred instanceof BlankNode ){
+            if(is_string($pred))
+            $var['pred'] = $pred;
+            $pred = null;
+        }
+        if(is_string($obj)||$obj instanceof BlankNode){
+            if(is_string($obj))
+            $var['obj'] = $obj;
+            $obj = null;
+        }
+        $intBindings = $this->_buildIntBindings($var);
+        $k = 0;
+
+        $key = 0;
+        // search in named graphs
+        if($graphlist['var'][0] != null||$graphlist['list'][0] != null){
+            foreach($graphlist['list'] as $key => $graphnode){
+
+                // query the dataset
+                $it = $this->dataset->findInNamedGraphs($graphnode,$sub,$pred,$obj,false);
+                if($it->valid()){
+                    // add statements to the result list
+                    while($it->valid()){
+                        if($graphnode == null){
+                            $element = $it->current()->getStatement();
+                            $grname  = $it->current()->getGraphname();
+                        }else{
+                            if($it->current() instanceof Quad)
+                                $element = $it->current()->getStatement();
+                            else
+                                $element = $it->current();
+
+                            $grname  = $graphnode;
+                        }
+                        if($this->checkIntBindings($element,$intBindings)){
+                            $resmodel['trip'][$k]  = $element;
+                            $resmodel['graph'][$k] = $grname;
+                        //    $resmodel['graphvar'][$k] = $graphlist['var'][$key];
+                            $resmodel['graphvar'][$k] = $graphlist['var'][0];
+                            $k++;
+
+                        }
+                        $it->next();
+                    }
+                }
+
+            }
+        }
+        // search in the default graph
+        if($graphlist['list'][0] == null && $graphlist['var'][0] == null){
+
+
+            $gr = $this->dataset->getDefaultGraph();
+
+            $res = $gr->find($sub,$pred,$obj);
+
+            foreach($res->triples as $innerkey => $element){
+                if($this->checkIntBindings($element,$intBindings)){
+                        $resmodel['trip'][$k]  = $element;
+                        $resmodel['graph'][$k] = null;
+                        $resmodel['graphvar'][$k] = $graphlist['var'][$key];
+                        $k++;
+                    }
+            }
+        }
+        if($k == 0)
+        return false;
+        return $this->_buildResultSet($pattern,$resmodel);
+    }
+
+    /**
+    * Checks it there are internal bindings between variables.
+    *
+    * @param  Triple  $trip
+    * @param  Array   $intBindings
+    * @return boolean
+    */
+    protected function checkIntBindings($trip, $intBindings){
+        switch($intBindings){
+            case -1:
+            return true;
+            break;
+            case 0:
+            if($trip->subj != $trip->pred)
+            return false;
+            break;
+            case 1:
+            if(is_a($trip->obj,'Literal'))
+            return false;
+            if($trip->subj != $trip->obj)
+            return false;
+            break;
+            case 2:
+            if(is_a($trip->obj,'Literal'))
+            return false;
+            if($trip->pred != $trip->obj)
+            return false;
+            break;
+            case 3:
+            if(is_a($trip->obj,'Literal'))
+            return false;
+            if($trip->pred != $trip->obj || $trip->pred != $trip->subj )
+            return false;
+            break;
+        }
+        return true;
+    }
+
+
+    /**
+    * Perform an SQL-like inner join on two resultSets.
+    *
+    * @param   Array   &$finalRes
+    * @param   Array   &$res
+    * @return  Array
+    */
+    protected function joinTuples(&$finalRes, &$res) {
+
+        if (!$finalRes || !$res)
+        return array();
+
+        // find joint variables and new variables to be added to $finalRes
+        $jointVars = array();
+        $newVars = array();
+        $k = key($res);
+
+        foreach ($res[$k] as $varname => $node) {
+            if (array_key_exists($varname, $finalRes[0]))
+            $jointVars[] = $varname;
+            else
+            $newVars[] = $varname;
+        }
+
+        // eliminate rows of $finalRes in which the values of $jointVars do not have
+        // a corresponding row in $res.
+        foreach ($finalRes as $n => $fRes) {
+            foreach ($res as $i => $r) {
+                $ok = TRUE;
+                foreach ($jointVars as $j_varname)
+                if ($r[$j_varname] != $fRes[$j_varname]) {
+                    $ok = FALSE;
+                    break;
+                }
+                if ($ok)
+                break;
+            }
+            if (!$ok)
+            unset($finalRes[$n]);
+        }
+
+        // join $res and $finalRes
+        $joinedRes = array();
+        foreach ($res as $r) {
+            foreach ($finalRes as $n => $fRes) {
+                $ok = TRUE;
+                foreach ($jointVars as $j_varname)
+                if ($r[$j_varname] != $fRes[$j_varname]) {
+                    $ok = FALSE;
+                    break;
+                }
+                if ($ok) {
+                    $joinedRow = $finalRes[$n];
+                    foreach($newVars as $n_varname)
+                    $joinedRow[$n_varname] = $r[$n_varname];
+                    $joinedRes[] = $joinedRow;
+                }
+            }
+        }
+        return $joinedRes;
+    }
+
+
+    /**
+    * Joins OPTIONAL pattern results.
+    *
+    * @param   Array   &$finalRes
+    * @param   Array   &$res
+    * @return  Array    the joined Array
+    */
+    protected function joinOptionalTuples(&$finalRes, &$res) {
+
+        if(!$finalRes && !$res)
+        return array();
+
+        if(!$finalRes)
+        return $res;
+
+        if(!$res)
+        return $finalRes;
+
+        // find joint variables and new variables to be added to $finalRes
+        $jointVars = array();
+        $newVars = array();
+        $result = array();
+
+        $k = key($res);
+
+        foreach ($res[$k] as $varname => $node) {
+            if (array_key_exists($varname, $finalRes[0])){
+                $jointVars[] = $varname;
+            }else{
+                $newVars[] = $varname;
+            }
+        }
+        $joined = array();
+        $joinc = 0;
+        foreach($finalRes as $i =>$fRes){
+            foreach($res as $n =>$r){
+                $join = false;
+                foreach($jointVars as $j_varname){
+                    if($r[$j_varname]==$fRes[$j_varname]){
+                        $join = true;
+                        //break;
+                    }else{
+                        $join = false;
+                    }
+                }
+                if($join){
+                    $result[$joinc] = $fRes;
+                    foreach($newVars as $n_varname)
+                    $result[$joinc][$n_varname] = $r[$n_varname];
+                    $joined[]=$n;
+                    $joinc++;
+                }
+
+            }
+        }
+
+        $count = count($result);
+        foreach($res as $k =>$val){
+            if(!in_array($k,$joined)){
+                $result[$count] = $finalRes[0];
+                foreach($result[$count] as $varname => $varVal){
+                    $result[$count][$varname]='';
+                }
+
+                foreach($val as $varname2 => $varVal2){
+                    $result[$count][$varname2]=$varVal2;
+                }
+                $count++;
+            }
+        }
+        return $result;
+    }
+
+
+
+    /**
+    * Looks in from and from named part of the query and
+    * adds the graphs to the graphlist.
+    *
+    * @return Array
+    */
+    protected function preselectGraphs(){
+        $fromNamed = $this->query->getFromNamedPart();
+        if($fromNamed == null)
+        $fromNamed[] = null;
+        return $fromNamed;
+    }
+
+
+    /**
+    * Evaluates the GRPAH clause if there is one. Checks if
+    * the GRAPH clause contains an IRI, variable or nothing.
+    * Returns an array which contains the graphs that has to be matched.
+    *
+    * @param  GraphPattern $pattern
+    * @param  Array        $graphlist
+    * @return Array
+    */
+    protected function _checkGraphs(&$pattern,$graphlist){
+
+        $gr = $pattern->getGraphname();
+        if($gr instanceof Resource ){
+            if($graphlist[0]==null || in_array($gr,$graphlist)){
+                $newGraphList['list'][] = $gr;
+                $newGraphList['var'][]  = null;
+            }else{
+                return false;
+            }
+        }elseif (is_string($gr)){
+            $newGraphList['list'] = $graphlist;
+            $newGraphList['var'][]  = $gr;
+        }else{
+            $newGraphList['list'] = $graphlist;
+            $newGraphList['var'][]  = null;
+        }
+        return $newGraphList;
+    }
+
+    /**
+    * Marks triples with internal bindings.
+    * int bindings -1 :none 0:sub=pred 1:sub=obj 2:pred=obj 3:sub=pred=obj.
+    *
+    * @param  Array $var
+    * @return Array
+    */
+    protected function _buildIntBindings($var){
+        $intBindings = -1;
+        if(!$var)
+        return $intBindings;
+
+        if(isset($var['sub'])){
+            if(isset($var['pred']))
+            if($var['sub'] == $var['pred'])
+            $intBindings = 0;
+            if(isset($var['obj']))
+            if($var['sub'] == $var['obj']){
+                if( $intBindings == 0){
+                    $intBindings = 3;
+                }else{
+                    $intBindings = 1;
+                }
+            }
+        }
+        if(isset($var['pred'])){
+            if(isset($var['obj']))
+            if($var['pred']==$var['obj']&&$intBindings!=3)
+            $intBindings = 2;
+        }
+        return $intBindings;
+    }
+
+    /**
+    * Builds the resultset.
+    *
+    * @param  GraphPattern $pattern
+    * @param  Array        $resmodel
+    * @return Array
+    */
+    protected function _buildResultSet($pattern,$resmodel){
+        // determine variables and their corresponding values
+        $result = null;
+        if(is_string($pattern->getSubject())){
+            $n = 0;
+            foreach($resmodel['trip'] as $key => $triple){
+                if(isset($resmodel['graphvar'][$key]))
+                $result[$n][$resmodel['graphvar'][$key]] = $resmodel['graph'][$key];
+                $result[$n++][$pattern->getSubject()] = $triple->subj;
+            }
+        }
+        if(is_string($pattern->getPredicate())){
+            $n = 0;
+            foreach($resmodel['trip'] as $key => $triple){
+                if(isset($resmodel['graphvar'][$key]))
+                $result[$n][$resmodel['graphvar'][$key]] = $resmodel['graph'][$key];
+                $result[$n++][$pattern->getPredicate()] = $triple->pred;
+            }
+        }
+        if(is_string($pattern->getObject())){
+            $n = 0;
+            foreach($resmodel['trip'] as $key => $triple){
+                if(isset($resmodel['graphvar'][$key]))
+                $result[$n][$resmodel['graphvar'][$key]] = $resmodel['graph'][$key];
+                $result[$n++][$pattern->getObject()] = $triple->obj;
+            }
+        }
+        return $result;
+    }
+
+    /**
+    * Selects the result variables and builds a result table.
+    *
+    * @param  Array  $table the result table
+    * @param  Array  $vars the result variables
+    * @return Array
+    */
+    protected function selectVars($table,$vars){
+        if($vars[0]=='*')
+        $vars = $this->query->getAllVars();
+        $resTable = array();
+        $hits = 0;
+        foreach($table as $val){
+            foreach($vars as $var){
+                if(isset($val[(string)$var])){
+                    $resTable[$hits][(string)$var]=$val[(string)$var];
+                }else{
+                    $resTable[$hits][(string)$var]="";
+                }
+            }
+            $hits++;
+        }
+        return $resTable;
+    }
+
+    /**
+    * Joins the results of the different Graphpatterns.
+    *
+    * @param  Array $patternlist
+    * @return Array
+    */
+    protected function joinResults($patternlist){
+        $joined[0]['patternResult'] = null;
+        $joined[0]['outerFilter'] = null;
+
+        while(count($patternlist)>0){
+            foreach($patternlist as $key => $pattern){
+                if($pattern['hasOptional'] == 0 && $pattern['hasUnion'] == 0){
+                    if(is_int($pattern['optionalTo'])){
+                        $patternlist[$pattern['optionalTo']]['hasOptional']--;
+                        $patternlist[$pattern['optionalTo']]['patternResult'] = $this->joinOptionalTuples($pattern['patternResult'],$patternlist[$pattern['optionalTo']]['patternResult']);
+                        unset($patternlist[$key]);
+                        break;
+                    }
+                    else if(is_int($pattern['unionWith'])){
+                        $patternlist[$pattern['unionWith']]['hasUnion']--;
+                        foreach($pattern['patternResult'] as $value)
+                        array_push($patternlist[$pattern['unionWith']]['patternResult'],$value);
+                        unset($patternlist[$key]);
+                        break;
+                    }else{
+                        if($joined[0]['patternResult'] == null){
+                            $joined[0]['patternResult'] = $pattern['patternResult'];
+                            if($joined[0]['outerFilter'] == null )
+                            $joined[0]['outerFilter']  = $pattern['outerFilter'];
+                            unset($patternlist[$key]);
+                            break;
+                        }
+                    //    if($pattern['patternResult'] !=null ){
+                            $joined[0]['patternResult'] = $this->joinTuples($joined[0]['patternResult'],$pattern['patternResult']);
+                            $joined[0]['outerFilter']   = $pattern['outerFilter'];
+                            unset($patternlist[$key]);
+                            break;
+                    //    }
+                    }
+                }
+            }
+        }
+        return $joined;
+    }
+
+    /**
+    * Filters the pattern results.
+    *
+    * @param  Array   $patternlist list containing the results of the GraphPatterns
+    * @param  boolean $outer TRUE if its an outer filter FALSE if not
+    * @return Array   the filtered patternlist
+    */
+    protected function filterPatterns($patternlist,$outer){
+        if($outer)
+        $filter = 'outerFilter';
+        else
+        $filter = 'innerFilter';
+        foreach($patternlist as $patkey => $pattern){
+            // get constraints
+            $constraint = $pattern[$filter];
+
+            if(count($constraint)>0){
+                foreach($constraint as $constr){
+                    if($constr != null){
+                        // extract Vars and function calls
+                        $evalString = $constr->getExpression();
+                        preg_match_all("/\?.[^\s\)\,]*/",$evalString,$vars);
+                        preg_match_all("/bound\((.[^\)]*)\)/i",$evalString,$boundcalls);
+                        preg_match_all("/isuri\((.[^\)]*)\)/i",$evalString,$isUricalls);
+                        preg_match_all("/isblank\((.[^\)]*)\)/i",$evalString,$isBlankcalls);
+                        preg_match_all("/isLiteral\((.[^\)]*)\)/i",$evalString,$isLiteralcalls);
+                        preg_match_all("/lang\((.[^\)]*)\)/i",$evalString,$langcalls);
+                        preg_match_all("/datatype\((.[^\)]*)\)/i",$evalString,$datatypecalls);
+                        preg_match_all("/str\((.[^\)]*)\)/i",$evalString,$stringcalls);
+
+                        // is Bound
+                        if(count($boundcalls[1])>0)
+                        $function['bound'] = $boundcalls[1];
+                        else
+                        $function['bound'] = false;
+
+                        // is URI
+                        if(count($isUricalls[1])>0)
+                        $function['isUri'] = $isUricalls[1];
+                        else
+                        $function['isUri'] = false;
+
+                        // is Blank
+                        if(count($isBlankcalls[1])>0)
+                        $function['isBlank'] = $isBlankcalls[1];
+                        else
+                        $function['isBlank'] = false;
+
+                        // is Literal
+                        if(count($isLiteralcalls[1])>0)
+                        $function['isLiteral'] = $isLiteralcalls[1];
+                        else
+                        $function['isLiteral'] = false;
+
+                        // lang
+                        if(count($langcalls[1])>0)
+                        $function['lang'] = $langcalls[1];
+                        else
+                        $function['lang'] = false;
+
+                        // datatype
+                        if(count($datatypecalls[1])>0)
+                        $function['datatype'] = $datatypecalls[1];
+                        else
+                        $function['datatype'] = false;
+
+                        // string
+                        if(count($stringcalls[1])>0)
+                        $function['string'] = $stringcalls[1];
+                        else
+                        $function['string'] = false;
+
+
+                        foreach($pattern['patternResult'] as $key => $res){
+                            $result = false;
+                            $evalString = $this->fillConstraintString($vars,$res,$constr,$function);
+                            $evalString = '$result =('.$evalString.');';
+                            // evaluate Constraint
+                            @eval($evalString);
+
+                            if(!$result)
+                            unset($patternlist[$patkey]['patternResult'][$key]);
+
+                        }
+                    }
+                }
+            }
+        }
+        return $patternlist;
+    }
+
+    /**
+    * Builds an evaluation string to determine wether the result passes
+    * the filter or not. This string is evaluatet by the php buildin eval() function
+    *
+    * @param  Array      $vars a list which contains the used variables
+    * @param  Array      $res  the result part which have to be evaluated
+    * @param  Constraint $constraint the Constrain object
+    * @param  Array      $function an Array which contains the used functions
+    * @return String
+    */
+
+    protected function fillConstraintString($vars,$res,$constraint,$function){
+
+        $boundExpr = false;
+        $evalString = $constraint->getExpression();
+
+        // extract Literals
+        $pattern1 = "/\".[^\"]*\"[^\^\@]/";
+        $pattern2 = "/\'.[^\']*\'[^\^\@]/";
+        preg_match_all($pattern1,$evalString,$hits1);
+        preg_match_all($pattern2,$evalString,$hits2);
+
+        foreach($hits1[0] as $k => $val){
+            $evalString = preg_replace('/\".[^\"]*\"[^\^]/','_REPLACED1_'.$k++,$evalString,1);
+        }
+        foreach($hits2[0] as $k => $val){
+            $evalString = preg_replace('/\".[^\"]*\"[^\^]/','_REPLACED2_'.$k++,$evalString,1);
+        }
+
+        // replace namespaces
+        $prefs = $this->query->getPrefixes();
+        foreach($prefs as $key => $val){
+            if($key == '')
+            $key = ' ';
+            $evalString = preg_replace("/^(".$key."\:)(.[^\s]*)|([\s\(]?[^\^])(".$key."\:)(.[^\s\)]*)([\s\)]?)/","$3'<".$val."$2$5>'$6",$evalString);
+
+            $evalString = preg_replace("/(\^)(".$key."\:)(.[^\s]*)/","$1<".$val."$3>",$evalString);
+        }
+
+        $xsd = "http\:\/\/www.w3.org\/2001\/XMLSchema\#";
+
+        // evaluate bound calls
+        if($function['bound']){
+            $boundExpr = true;
+            foreach($function['bound'] as $var){
+                if(isset($res[$var]) && $res[$var]!=="")
+                $replacement = 'true';
+                else
+                $replacement = 'false';
+                $evalString = preg_replace("/bound\(\\".$var."\)/i",$replacement,$evalString);
+            }
+
+        }
+        // evaluate isBlank calls
+        if($function['isBlank']){
+            foreach($function['isBlank'] as $var){
+                if(isset($res[$var]) && $res[$var]!=="" && $res[$var] instanceof BlankNode )
+                $replacement = 'true';
+                else
+                $replacement = 'false';
+                $evalString = preg_replace("/isBlank\(\\".$var."\)/i",$replacement,$evalString);
+            }
+
+        }
+        // evaluate isLiteral calls
+        if($function['isLiteral']){
+            foreach($function['isLiteral'] as $var){
+                if(isset($res[$var]) && $res[$var]!=="" && $res[$var] instanceof Literal  )
+                $replacement = 'true';
+                else
+                $replacement = 'false';
+                $evalString = preg_replace("/isLiteral\(\\".$var."\)/i",$replacement,$evalString);
+            }
+
+        }
+        // evaluate isUri calls
+        if($function['isUri']){
+            foreach($function['isUri'] as $var){
+                if(isset($res[$var]) && $res[$var]!=="" && $res[$var] instanceof Resource && $res[$var]->getUri() && !$res[$var] instanceof BlankNode )
+                $replacement = 'true';
+                else
+                $replacement = 'false';
+                $evalString = preg_replace("/isUri\(\\".$var."\)/i",$replacement,$evalString);
+            }
+        }
+        // evaluate lang calls
+        if($function['lang']){
+            foreach($function['lang'] as $var){
+                if(isset($res[$var]) && $res[$var]!=="" && $res[$var] instanceof Literal && $res[$var]->getLanguage() )
+                $replacement = '"'.$res[$var]->getLanguage().'"';
+                else
+                $replacement = 'null';
+                $evalString = preg_replace("/lang\(\\".$var."\)/i",$replacement,$evalString);
+            }
+        }
+        // evaluate datatype calls
+        if($function['datatype']){
+            foreach($function['datatype'] as $var){
+                if(isset($res[$var]) && $res[$var]!=="" && $res[$var] instanceof Literal && $res[$var]->getDatatype() )
+                $replacement = '\'<'.$res[$var]->getDatatype().'>\'';
+                else
+                $replacement = 'false';
+                $evalString = preg_replace("/datatype\(\\".$var."\)/i",$replacement,$evalString);
+            }
+        }
+        // evaluate string calls
+        if($function['string']){
+            foreach($function['string'] as $var){
+                if($var{0}=='?' || $var{0}=='$'){
+                    if(isset($res[$var]) && $res[$var]!==""){
+                        $replacement = "'str_".$res[$var]->getLabel()."'";
+                        if($res[$var] instanceof BlankNode)
+                        $replacement = "''";
+                    }else{
+                        $replacement = 'false';
+                    }
+                    $evalString = preg_replace("/str\(\\".$var."\)/i",$replacement,$evalString);
+                }else{
+                    if($var{0}=='<'){
+                        $evalString = preg_replace("/str\(\s*\<(.[^\>]*)\>\s*\)/i","'str_$1'",$evalString);
+                    }
+                    if($var{0}=='"'){
+                        $evalString = preg_replace("/str\(\s*\"(.[^\>]*)\"\@[a-z]*\s*\)/i","'str_$1'",$evalString);
+                    }
+                }
+
+            }
+        }
+        // evaluate VARS
+        foreach($vars[0] as $var){
+            if(isset($res[$var])&&$res[$var]!== ""){
+                //$replacement = "'".$res[$var]->getLabel()."'";
+                $replacement = '" "';
+                if($res[$var] instanceof Literal){
+                    if($res[$var]->getDatatype()!= null){
+                        if($res[$var]->getDatatype() == XML_SCHEMA.'boolean')
+                        $replacement = $res[$var]->getLabel();
+                        if($res[$var]->getDatatype() == XML_SCHEMA.'double')
+                        $replacement = $res[$var]->getLabel();
+                        if($res[$var]->getDatatype() == XML_SCHEMA.'integer')
+                        $replacement = $res[$var]->getLabel();
+                        if($res[$var]->getDatatype() == XML_SCHEMA.'dateTime')
+                        $replacement = strtotime($res[$var]->getLabel());
+                    }else{
+                        if($res[$var]->getLabel()=="")
+                        $replacement = 'false';
+                        else
+                        $replacement = "'str_".$res[$var]->getLabel()."'";
+                    }
+                }else{
+                    if($res[$var] instanceof Resource){
+                        $replacement = "'<".$res[$var]->getLabel().">'";
+                    }
+                }
+                $evalString = preg_replace("/\\".$var."/",$replacement,$evalString);
+            }
+
+            // problem with PHP: false < 13 is true
+            if(isset($res[$var])){
+                if($res[$var] === ""){
+                    if($boundExpr)
+                    $evalString = preg_replace("/\\".$var."/","false",$evalString);
+                    else
+                    $evalString = 'false';
+                }
+            }else{
+                $evalString = preg_replace("/\\".$var."/","false",$evalString);
+            }
+
+        }
+
+        // replace '=' with '=='
+        $evalString = preg_replace("/(.[^\=])(\=)(.[^\=])/","$1==$3",$evalString);
+
+
+        // rewrite Literals
+        foreach($hits1[0] as $k => $val){
+            $pattern = '/_REPLACED1_'.$k.'/';
+            $evalString = preg_replace($pattern,$hits1[0][$k],$evalString,1);
+        }
+
+        foreach($hits2[0] as $k => $val){
+            $pattern = '/_REPLACED2_'.$k.'/';
+            $evalString = preg_replace($pattern,$hits2[0][$k],$evalString,1);
+        }
+
+        // replace xsd:boolean expressions
+        $pattern = $pattern = '/\"\s?true\s?\"\^\^\<'.$xsd.'boolean\>|\'\s?true\s?\'\^\^xsd:boolean/';
+        $evalString = preg_replace($pattern,"true",$evalString);
+
+        $pattern = $pattern = '/\"\s?false\s?\"\^\^\<'.$xsd.'boolean\>|\'\s?false\s?\'\^\^xsd:boolean/';
+        $evalString = preg_replace($pattern,"false",$evalString);
+
+        // replace xsd:date expressions
+        $pattern = "/\"(.[^\"]*)\"\^\^".$xsd."dateTime/";
+        preg_match_all($pattern,$evalString,$hits);
+
+        foreach($hits[1] as $dummy)
+        $evalString = preg_replace("/\".[^\"]*\"\^\^".$xsd."dateTime/",strtotime($dummy),$evalString,1);
+
+
+        $evalString = preg_replace("/(\'\<".$xsd."dateTime\()(.[^\)]*\))\>\'/","dateTime($2",$evalString);
+
+        $evalString = preg_replace("/(\'\<".$xsd."integer\()(.[^\)]*\))\>\'/","integer($2",$evalString);
+
+        // tag plain literals
+        $evalString = preg_replace("/\"(.[^\"]*)\"([^\^])|\"(.[^\"]*)\"$/","'str_$1$3'$2",$evalString);
+
+        return $evalString;
+    }
+
+    /**
+    * Sorts the results.
+    *
+    * @param  Array  $vartable List containing the unsorted result vars
+    * @return Array  List containing the sorted result vars
+    */
+    protected function sortVars($vartable)
+    {
+        $newTable = array();
+        $mod = $this->query->getSolutionModifier();
+        // if no ORDER BY solution modifier return vartable
+        if($mod['order by']!= null){
+            $order = $mod['order by'];
+            $map = $this->buildVarmap($order,$vartable);
+            foreach($map as $val){
+                $newTable[] = $vartable[$val];
+            }
+        }else{
+            $newTable = $vartable;
+        }
+
+        if($mod['offset'] != null){
+            $newTable = array_slice ($newTable, $mod['offset']);
+        }
+        if($mod['limit'] != null){
+            $newTable = array_slice($newTable,0,$mod['limit']);
+        }
+
+        return $newTable;
+    }
+
+    /**
+    * Sorts the result table.
+    *
+    * @param  String $order (ASC/DESC)
+    * @param  Array  $vartable the vartable
+    * @return Array  A map that contains the new order of the result vars
+    */
+    protected function buildVarmap($order, $vartable)
+    {
+        $n= 0;
+        $result = array();
+        $num_var = array();
+        foreach($order as $variable)
+        $num_var[$variable['val']] = 0;
+
+        foreach($vartable as $k => $x){
+            foreach($order as $value){
+                // if the value is a typed Literal try to determine if it
+                // a numeric datatype
+                if($x[$value['val']] instanceof Literal){
+                    $dtype = $x[$value['val']]->getDatatype();
+                    if($dtype){
+                        switch($dtype){
+                            case XML_SCHEMA."integer":
+                            $num_var[$value['val']]++;
+                            break;
+                            case XML_SCHEMA."double":
+                            $num_var[$value['val']]++;
+                            break;
+
+                        }
+                    }
+                }
+                if($x[$value['val']]){
+                    if($x[$value['val']]instanceof Literal){
+                        $pref = "2";
+                    }
+                    if($x[$value['val']]instanceof Resource){
+                        $pref = "1";
+                    }
+                    if($x[$value['val']]instanceof BlankNode){
+                        $pref = "0";
+                    }
+                    $result[$value['val']][$n] = $pref.$x[$value['val']]->getLabel();
+                }else{
+                    $result[$value['val']][$n] = "";
+                }
+            }
+            $result['oldKey'][$n] = $k;
+            $n++;
+        }
+        $sortString = "";
+        foreach($order as $value){
+            if($num_var[$value['val']] == $n)
+            $sort = SORT_NUMERIC;
+            else
+            $sort = SORT_STRING;
+
+            if($value['type'] == 'asc')
+            $type = SORT_ASC;
+            else
+            $type = SORT_DESC;
+
+            $sortString = $sortString.'$result["'.$value['val'].'"],'.$type.','.$sort.',';
+        }
+        $sortString = "array_multisort(".$sortString.'$result["oldKey"]);';
+
+        @eval($sortString);
+        return $result['oldKey'];
+    }
+
+
+
+    /**
+    * Eliminates duplicate results.
+    *
+    * @param  Array  $vartable a table that contains the result vars and their bindings
+    * @return Array the result table without duplicate results
+    */
+    protected function distinct($vartable)
+    {
+        $index = array();
+        foreach($vartable as $key => $value){
+            $key_index="";
+            foreach($value as $k => $v)
+            if($v instanceof Object)
+                $key_index = $key_index.$k.$v->toString();
+            if(isset($index[$key_index]))
+            unset($vartable[$key]);
+            else
+            $index[$key_index]= 1;
+        }
+        return $vartable;
+    }
+
+
+    /**
+    * Prints a query result as HTML table.
+    * You can change the colors in the configuration file.
+    *
+    * @param array $queryResult [][?VARNAME] = object Node
+    * @return void
+    */
+    public function writeQueryResultAsHtmlTable($queryResult) {
+        // Import Package Utility
+        include_once(RDFAPI_INCLUDE_DIR.PACKAGE_UTILITY);
+
+        if ( $queryResult[0] == null) {
+            echo 'no match<br>';
+            return;
+        }
+        if ( $queryResult == 'false') {
+            echo 'boolean: false<br>';
+            return;
+        }
+        if ( $queryResult == 'true') {
+            echo 'boolean: true<br>';
+            return;
+        }
+
+
+        echo '<table border="1" cellpadding="3" cellspacing="0"><tr><td><b>No.</b></td>';
+        foreach ($queryResult[0] as $varName => $value)
+        echo "<td align='center'><b>$varName</b></td>";
+        echo '</tr>';
+
+        foreach ($queryResult as $n => $var) {
+
+
+            echo '<tr><td width="20" align="right">' .($n + 1) .'.</td>';
+            foreach ($var as $varName => $value) {
+                if($value !=''){
+                    echo INDENTATION . INDENTATION . '<td bgcolor="';
+                    echo RDFUtil::chooseColor($value);
+                    echo '">';
+                    echo '<p>';
+
+                    $lang  = NULL;
+                    $dtype = NULL;
+                    if (is_a($value, 'Literal')) {
+                        if ($value->getLanguage() != NULL)
+                        $lang = ' <b>(xml:lang="' . $value->getLanguage() . '") </b> ';
+                        if ($value->getDatatype() != NULL)
+                        $dtype = ' <b>(rdf:datatype="' . $value->getDatatype() . '") </b> ';
+                    }
+                    echo  RDFUtil::getNodeTypeName($value) .$value->getLabel() . $lang . $dtype .'</p>';
+                }else{
+                    echo "<td bgcolor='white'>unbound";
+                }
+            }
+            echo '</tr>';
+        }
+        echo '</table>';
+    }
+
+
+
+    /*
+    *   Dumb getters
+    */
+
+
+
+    public function getQuery()
+    {
+        return $this->query;
+    }//public function getQuery()
+
+
+
+    public function getDataset()
+    {
+        return $this->dataset;
+    }//public function getDataset()
+
+} // end: Class SparqlEngine
+
+?>
Index: /Dev/trunk/rdfapi/sparql/SparqlEngine/PreparedStatement.php
===================================================================
--- /Dev/trunk/rdfapi/sparql/SparqlEngine/PreparedStatement.php	(revision 12)
+++ /Dev/trunk/rdfapi/sparql/SparqlEngine/PreparedStatement.php	(revision 12)
@@ -0,0 +1,17 @@
+<?php
+/**
+*   A prepared statement that can be execute()d later multiple
+*   times with different variable values.
+*
+*   @license http://www.gnu.org/licenses/lgpl.html LGPL
+*   @package sparql
+*/
+class SparqlEngine_PreparedStatement
+{
+    public function execute($arVariables, $resultform)
+    {
+        //FIXME
+    }
+
+}
+?>
Index: /Dev/trunk/rdfapi/sparql/SparqlEngine/ResultConverter.php
===================================================================
--- /Dev/trunk/rdfapi/sparql/SparqlEngine/ResultConverter.php	(revision 12)
+++ /Dev/trunk/rdfapi/sparql/SparqlEngine/ResultConverter.php	(revision 12)
@@ -0,0 +1,115 @@
+<?php
+require_once RDFAPI_INCLUDE_DIR . 'sparql/SparqlEngine/ResultRenderer.php';
+
+/**
+*   Converts a memory result into a proper
+*   rdf statement triple array
+*
+*   @author Christian Weiske <cweiske@cweiske.de>
+*   @license http://www.gnu.org/licenses/lgpl.html LGPL
+*
+*   @package sparql
+*/
+class SparqlEngine_ResultConverter
+{
+    /**
+    *   Determines the correct renderer and calls it.
+    *
+    *   The $resultform may be:
+    *   - false: The default renderer is taken then
+    *   - an object that implements SparqlEngine_ResultRenderer interface
+    *   - a string like "HTML" or "XML". The appropriate renderer is used then.
+    *   - a full class name, e.g. SparqlEngine_ResultRenderer_XML
+    *
+    *   @param array $arVartable        Variable table
+    *   @param SparqlEngine $engine   Sparql database engine.
+    *   @param mixed    $resultform     Which format the results shall be in (false or "xml")
+    *
+    *   @return mixed   Most likely an array or a boolean value,
+    *                   or anything else as determined by $resultform
+    */
+    public static function convertFromResult($arVartable, SparqlEngine $engine, $resultform = false)
+    {
+        if (is_object($resultform)) {
+            if ($resultform instanceof SparqlEngine_ResultRenderer) {
+                return $resultform->convertFromResult(
+                    $arVartable,
+                    $engine->getQuery(),
+                    $engine
+                );
+            } else {
+                throw new Exception(
+                    'Result renderer object needs to implement'
+                    . ' SparqlEngine_ResultRenderer interface'
+                );
+            }
+        }
+
+        if ($resultform === false) {
+            $resultform = 'Default';
+        } else if ($resultform == 'xml') {
+            //kept for BC reasons
+            $resultform = 'XML';
+        }
+
+        if ($strClass = self::loadClass($resultform)) {
+            $rrObj = new $strClass();
+            if ($rrObj instanceof SparqlEngine_ResultRenderer) {
+                return $rrObj->convertFromResult(
+                    $arVartable,
+                    $engine->getQuery(),
+                    $engine
+                );
+            } else {
+                throw new Exception(
+                    'Result renderer class "' . $strClass . '" needs to implement'
+                    . ' SparqlEngine_ResultRenderer interface'
+                );
+            }
+        } else {
+            throw new Exception(
+                'Result renderer class "' . $resultform . '" could not be loaded.'
+            );
+        }
+    }//public static function convertFromResult($arVartable, SparqlEngine $engine, $resultform = false)
+
+
+
+    /**
+    *   Tries to load a given class if it doesn't exist,
+    *   and returns true if the class can be used.
+    *
+    *   @param string $strClass Classname
+    *   @return mixed Class name if the class is loaded and can be used, false if not.
+    */
+    protected static function loadClass($strClass)
+    {
+        if (class_exists($strClass, false)) {
+            return $strClass;
+        }
+
+        //RAP style, shortcut notation
+        $strFile = 'SparqlEngine/ResultRenderer/' . $strClass . '.php';
+        @include_once RDFAPI_INCLUDE_DIR . 'sparql/' . $strFile;
+        if (class_exists('SparqlEngine_ResultRenderer_' . $strClass, false)) {
+            return 'SparqlEngine_ResultRenderer_' . $strClass;
+        }
+
+        //RAP style
+        $strFile = str_replace('_', '/', $strClass) . '.php';
+        @include_once RDFAPI_INCLUDE_DIR . 'sparql/' . $strFile;
+        if (class_exists($strClass, false)) {
+            return $strClass;
+        }
+
+        //PEAR style
+        @include_once $strFile;
+        if (class_exists($strClass, false)) {
+            return $strClass;
+        }
+
+        return false;
+    }//protected static function loadClass($strClass)
+
+}//class SparqlEngine_ResultConverter
+?>
Index: /Dev/trunk/rdfapi/sparql/SparqlEngine/ResultRenderer.php
===================================================================
--- /Dev/trunk/rdfapi/sparql/SparqlEngine/ResultRenderer.php	(revision 12)
+++ /Dev/trunk/rdfapi/sparql/SparqlEngine/ResultRenderer.php	(revision 12)
@@ -0,0 +1,29 @@
+<?php
+
+/**
+*   Result renderer interface that any result renderer needs to implement.
+*   A result renderer converts results into a
+*   - for the user - usable result format, e.g. php arrays, xml, json and
+*   so on.
+*
+*   @author Christian Weiske <cweiske@cweiske.de>
+*   @license http://www.gnu.org/licenses/lgpl.html LGPL
+*
+*   @package sparql
+*/
+interface SparqlEngine_ResultRenderer
+{
+    /**
+    *   Converts the database results into the desired output format
+    *   and returns the result.
+    *
+    *   @param array $arVartable    Variable table
+    *   @param Query $query         SPARQL query object
+    *   @param SparqlEngine $engine Sparql Engine to query the database
+    *   @return mixed   The result as rendered by the result renderers.
+    */
+    public function convertFromResult($arVartable, Query $query, SparqlEngine $engine);
+
+}//interface SparqlEngine_ResultRenderer
+
+?>
Index: /Dev/trunk/rdfapi/sparql/SparqlEngine/ResultRenderer/Default.php
===================================================================
--- /Dev/trunk/rdfapi/sparql/SparqlEngine/ResultRenderer/Default.php	(revision 12)
+++ /Dev/trunk/rdfapi/sparql/SparqlEngine/ResultRenderer/Default.php	(revision 12)
@@ -0,0 +1,262 @@
+<?php
+require_once RDFAPI_INCLUDE_DIR . 'sparql/SparqlEngineDb/ResultRenderer.php';
+
+/**
+*   Default result renderer for SparqlEngine
+*
+*   @author Tobias GauÃ <tobias.gauss@web.de>
+*   @author Christian Weiske <cweiske@cweiske.de>
+*   @license http://www.gnu.org/licenses/lgpl.html LGPL
+*
+*   @package sparql
+*/
+class SparqlEngine_ResultRenderer_Default implements SparqlEngine_ResultRenderer
+{
+    /**
+    *   Converts the database results into the output format
+    *   and returns the result.
+    *
+    *   @param array $arVartable    Variable table
+    *   @param Query $query         SPARQL query object
+    *   @param SparqlEngine $engine Sparql Engine to query the database
+    *   @return mixed               Most likely an array
+    */
+    public function convertFromResult($arVartable, Query $query, SparqlEngine $engine)
+    {
+        $this->query   = $query;
+        $this->engine  = $engine;
+        $this->dataset = $engine->getDataset();
+
+        $result = false;
+        $qrf    = $this->query->getResultForm();
+
+        if ($arVartable != null) {
+            switch ($qrf) {
+                case 'ask':
+                    if (count($arVartable) > 0) {
+                        $result = true;
+                    } else {
+                        $result = false;
+                    }
+                    break;
+                case 'count':
+                    $result = count($arVartable);
+                    break;
+                case 'construct':
+                    $result = $this->constructGraph(
+                        $arVartable,
+                        $this->query->getConstructPattern()
+                    );
+                    break;
+                case 'describe':
+                    $result = $this->describeGraph($arVartable);
+                    break;
+                default:
+                    $result = $arVartable;
+                    break;
+            }
+        } else if ($qrf == 'describe'){
+            $result = $this->describeGraph(null);
+        } else if ($qrf == 'construct'){
+            $result = $this->constructGraph(
+                false,
+                $this->query->getConstructPattern()
+            );
+        }
+
+        return $result;
+    }//public function convertFromResult($arVartable, Query $query, SparqlEngine $engine)
+
+
+
+    /**
+    * Constructs a result graph.
+    *
+    * @param  array         $arVartable       A table containing the result vars and their bindings
+    * @param  GraphPattern  $constructPattern The CONSTRUCT pattern
+    * @return MemModel      The result graph which matches the CONSTRUCT pattern
+    */
+    function constructGraph($arVartable, $constructPattern)
+    {
+        $resultGraph = new MemModel();
+
+        if (!$arVartable) {
+            return $resultGraph;
+        }
+
+        $tp = $constructPattern->getTriplePatterns();
+
+        $bnode = 0;
+        foreach ($arVartable as $value) {
+            foreach ($tp as $triple) {
+                $sub  = $triple->getSubject();
+                $pred = $triple->getPredicate();
+                $obj  = $triple->getObject();
+
+                if (is_string($sub)  && $sub{1} == '_') {
+                    $sub  = new BlankNode("_bN".$bnode);
+                }
+                if (is_string($pred) && $pred{1} == '_') {
+                    $pred = new BlankNode("_bN".$bnode);
+                }
+                if (is_string($obj)  && $obj{1} == '_') {
+                    $obj  = new BlankNode("_bN".$bnode);
+                }
+
+
+                if (is_string($sub)) {
+                    $sub  = $value[$sub];
+                }
+                if (is_string($pred)) {
+                    $pred = $value[$pred];
+                }
+                if (is_string($obj)) {
+                    $obj  = $value[$obj];
+                }
+
+                if ($sub !== "" && $pred !== "" && $obj !== "") {
+                    $resultGraph->add(new Statement($sub,$pred,$obj));
+                }
+            }
+            $bnode++;
+        }
+        return $resultGraph;
+    }//function constructGraph($arVartable, $constructPattern)
+
+
+
+    /**
+    * Builds a describing named graph. To define an attribute list for a
+    * several rdf:type look at constants.php
+    *
+    * @param  array      $arVartable
+    * @return MemModel
+    */
+    function describeGraph($arVartable)
+    {
+        // build empty named graph
+        $resultGraph = new MemModel();
+        // if no where clause fill $arVartable
+        $vars = $this->query->getResultVars();
+        if ($arVartable == null) {
+            if ($vars) {
+                $arVartable[0] = array('?x' => new Resource(substr($vars[0],1,-1)));
+                $vars[0] = '?x';
+            }
+        }
+        // fetch attribute list from constants.php
+        global $sparql_describe;
+        // for each resultset
+        foreach ($arVartable as $resultset) {
+            foreach ($vars as $varname) {
+                $varvalue = $resultset[$varname];
+                // try to determine rdf:type of the variable
+                $type = $this->_determineType($varvalue, $resultGraph);
+                // search attribute list defined in constants.php
+                $list = null;
+                if ($type) {
+                    $strLuri = strtolower($type->getUri());
+                    if (isset($sparql_describe[$strLuri])) {
+                        $list = $sparql_describe[$strLuri] ;
+                    }
+                }
+                // search in dataset
+                $this->_getAttributes($list, $resultGraph, $varvalue);
+            }
+        }
+
+        return $resultGraph;
+    }//function describeGraph($arVartable)
+
+
+
+    /**
+    * Tries to determine the rdf:type of the variable.
+    *
+    * @param  Node       $var The variable
+    * @param  MemModel   $resultGraph The result graph which describes the Resource
+    * @return String     Uri of the rdf:type
+    */
+    protected function _determineType($var, $resultGraph)
+    {
+        $type = null;
+        // find in namedGraphs
+        if (!$var instanceof Literal) {
+            $iter = $this->dataset->findInNamedGraphs(
+                null,
+                $var,
+                new Resource(RDF_NAMESPACE_URI.'type'),
+                null,
+                true
+            );
+            while ($iter->valid()) {
+                $statement = $iter->current();
+                $type = $statement->getObject();
+                $resultGraph->add($iter->current());
+                break;
+            }
+        }
+        // if no type information found find in default graph
+        if (!$type) {
+            if (!$var instanceof Literal) {
+                $iter1 = $this->dataset->findInDefaultGraph(
+                    $var,
+                    new Resource(RDF_NAMESPACE_URI.'type'),
+                    null
+                );
+                $type = null;
+                while ($iter1->valid()) {
+                    $statement = $iter1->current();
+                    $type      = $statement->getObject();
+                    $resultGraph->add($iter1->current());
+                    break;
+                }
+            }
+        }
+        return $type;
+    }//protected function _determineType($var, $resultGraph)
+
+
+
+    /**
+    * Search the attributes listed in $list in the dataset.
+    * Modifies $resultGraph
+    *
+    * @param Array      $list List containing the attributes
+    * @param MemModel   $resultGraph The result graph which describes the Resource
+    * @return void
+    */
+    protected function _getAttributes($list, $resultGraph, $varvalue)
+    {
+        if ($list){
+            foreach ($list as $attribute) {
+                if (!$varvalue instanceof Literal) {
+                    $iter2 = $this->dataset->findInNamedGraphs(
+                        null,
+                        $varvalue,
+                        new Resource($attribute),
+                        null,
+                        true
+                    );
+                    while ($iter2->valid()) {
+                        $resultGraph->add($iter2->current());
+                        $iter2->next();
+                    }
+                    $iter3 = $this->dataset->findInDefaultGraph(
+                        $varvalue,
+                        new Resource($attribute),
+                        null
+                    );
+                    while ($iter3->valid()) {
+                        $resultGraph->add($iter3->current());
+                        $iter3->next();
+                    }
+                }
+            }
+        }
+    }//protected function _getAttributes($list, $resultGraph, $varvalue)
+
+
+}//class SparqlEngine_ResultRenderer_Default implements SparqlEngine_ResultRenderer
+
+?>
Index: /Dev/trunk/rdfapi/sparql/SparqlEngine/ResultRenderer/HTML.php
===================================================================
--- /Dev/trunk/rdfapi/sparql/SparqlEngine/ResultRenderer/HTML.php	(revision 12)
+++ /Dev/trunk/rdfapi/sparql/SparqlEngine/ResultRenderer/HTML.php	(revision 12)
@@ -0,0 +1,201 @@
+<?php
+require_once RDFAPI_INCLUDE_DIR . 'sparql/SparqlEngineDb/ResultRenderer.php';
+require_once RDFAPI_INCLUDE_DIR . 'util/RdfUtil.php';
+
+/**
+*   XML result renderer for SparqlEngine
+*
+*   @author Tobias GauÃ <tobias.gauss@web.de>
+*   @author Christian Weiske <cweiske@cweiske.de>
+*   @license http://www.gnu.org/licenses/lgpl.html LGPL
+*
+*   @package sparql
+*/
+class SparqlEngine_ResultRenderer_HTML implements SparqlEngine_ResultRenderer
+{
+    /**
+    *   If the result HTML should be wrapped in a div
+    *   @var boolean
+    */
+    protected $bWrap = true;
+
+
+
+    /**
+    *   Converts the database results into the output format
+    *   and returns the result.
+    *
+    *   @param array $arVartable    Variable table
+    *   @param Query $query         SPARQL query object
+    *   @param SparqlEngine $engine Sparql Engine to query the database
+    *   @return string HTML result
+    */
+    public function convertFromResult($arVartable, Query $query, SparqlEngine $engine)
+    {
+        $this->query   = $query;
+        $this->engine  = $engine;
+        $this->dataset = $engine->getDataset();
+
+        $strCode     = '';
+
+        $strResultForm = $query->getResultForm();
+        switch ($strResultForm) {
+            case 'select':
+            case 'select distinct':
+                $strCode = $this->createTableFromRecords($arVartable);
+                break;
+
+            case 'construct':
+            case 'describe':
+                throw new Exception(
+                    'Construct and describe are currently not supported by the'
+                    . ' HTML renderer'
+                );
+
+            case 'count':
+            case 'ask':
+                $nCount = count($arVartable);
+
+                if ($strResultForm == 'ask') {
+                    $strCode = 'There were results.';
+                } else {
+                    $strCode = 'There are ' . $nCount . ' results.';
+                }
+                break;
+
+            default:
+                throw new Exception('Unsupported result form: ' . $strResultForm);
+        }
+
+        return $this->wrapCode($strCode);
+    }//public function convertFromResult($arVartable, Query $query, SparqlEngine $engine)
+
+
+
+    protected function wrapCode($strCode)
+    {
+        if (!$this->bWrap) {
+            return $strCode;
+        }
+
+        return
+            '<div class="SparqlEngine_ResultRenderer_HTML_result">' . "\n"
+            . $strCode . "\n"
+            . "</div>\n";
+    }//protected function wrapCode($strCode)
+
+
+
+    protected function createTableFromRecords($arVartable)
+    {
+        if (count($arVartable) == 0) {
+            return 'No result rows.';
+        }
+
+        $arResult = array();
+        foreach ($arVartable as $row) {
+            $arResultRow = array();
+            foreach ($row as $strVarName => $value) {
+                $arResultRow[$strVarName] = $this->createValue($value);
+            }
+            $arResult[] = $arResultRow;
+        }
+
+        //I always wanted to to this :)
+        return
+            "<table border='1'>\n"
+            . " <caption>SPARQL result with " . count($arResult) . " rows</caption>\n"
+            . " <thead><th>"
+                . implode('</th><th>', array_keys(reset($arResult)))
+            . "</th></thead>\n"
+            . " <tbody>\n  <tr>"
+            . implode(
+                "</tr>\n  <tr>",
+                array_map(
+                    create_function(
+                        '$ar',
+                        'return implode("", $ar);'
+                    ),
+                    $arResult
+                )
+              )
+            . "</tr>\n </tbody>\n"
+            . "</table>\n";
+    }//protected function createTableFromRecords($arRecordSets)
+
+
+
+    /**
+    *   Creates an RDF object object
+    *   contained in the given $dbRecordSet object.
+    *
+    *   @see convertFromDbResult() to understand $strVarBase necessity
+    *
+    *   @param ADORecordSet $dbRecordSet    Record set returned from ADOConnection::Execute()
+    *   @param string       $strVarBase     Prefix of the columns the recordset fields have.
+    *
+    *   @return string HTML code
+    */
+    protected function createValue($value)
+    {
+        if ($value === null) {
+            $strCode = $this->getHtmlNull();
+        }
+        if ($value instanceof Literal) {
+            $strCode = $this->getHtmlLiteral(
+                $value->getLabel(),
+                $value->getLanguage(),
+                $value->getDatatype()
+            );
+        } else if ($value instanceof Resource) {
+            $strCode = $this->getHtmlResource($value->getURI());
+        } else {
+            $strCode = $this->getHtmlBlank();
+        }
+		
+		$rdfUtil = new RdfUtil();
+
+        return '<td style="background-color: '
+               . $rdfUtil->chooseColor($value) . '">'
+               . $strCode
+               . '</td>';
+    }//protected function createObjectFromDbRecordSetPart(ADORecordSet $dbRecordSet, $strVarBase, $strVarName)
+
+
+
+    protected function getHtmlNull()
+    {
+        return '<pre>NULL</pre>';
+    }//protected function getHtmlNull()
+
+
+
+    protected function getHtmlBlank($value)
+    {
+        return '<i>Blank node</i>';
+    }//protected function getHtmlBlank($value)
+
+
+
+    protected function getHtmlResource($value)
+    {
+        return htmlspecialchars($value);
+    }//protected function getHtmlResource($value)
+
+
+
+    protected function getHtmlLiteral($value, $language, $datatype)
+    {
+        $strCode = htmlspecialchars($value);
+        if ($language) {
+            $strCode .= '<br/>&nbsp;&nbsp;<i>xml:lang</i>=' . $language;
+        }
+        if ($datatype) {
+            $strCode .= '<br/>&nbsp;&nbsp;<i>rdf:type</i>=' . $datatype;
+        }
+        return $strCode;
+    }//protected function getHtmlLiteral($value, $language, $datatype)
+
+}//class SparqlEngine_ResultRenderer_HTML implements SparqlEngine_ResultRenderer
+
+?>
Index: /Dev/trunk/rdfapi/sparql/SparqlEngine/ResultRenderer/XML.php
===================================================================
--- /Dev/trunk/rdfapi/sparql/SparqlEngine/ResultRenderer/XML.php	(revision 12)
+++ /Dev/trunk/rdfapi/sparql/SparqlEngine/ResultRenderer/XML.php	(revision 12)
@@ -0,0 +1,125 @@
+<?php
+require_once RDFAPI_INCLUDE_DIR . 'sparql/SparqlEngineDb/ResultRenderer.php';
+
+/**
+*   XML result renderer for SparqlEngine
+*
+*   @author Tobias GauÃ <tobias.gauss@web.de>
+*   @author Christian Weiske <cweiske@cweiske.de>
+*   @license http://www.gnu.org/licenses/lgpl.html LGPL
+*
+*   @package sparql
+*/
+class SparqlEngine_ResultRenderer_XML implements SparqlEngine_ResultRenderer
+{
+    /**
+    *   Converts the database results into the output format
+    *   and returns the result.
+    *
+    *   @param array $arVartable    Variable table
+    *   @param Query $query         SPARQL query object
+    *   @param SparqlEngine $engine Sparql Engine to query the database
+    *   @return string XML result
+    */
+    public function convertFromResult($arVartable, Query $query, SparqlEngine $engine)
+    {
+        $this->query   = $query;
+        $this->engine  = $engine;
+        $this->dataset = $engine->getDataset();
+
+        if ($arVartable instanceof NamedGraphMem) {
+            return $arVartable->writeRdfToString();
+        }
+
+        $result = '<sparql xmlns="http://www.w3.org/2005/sparql-results#">';
+        $header = '<head>';
+
+        // build header
+        if (is_array($arVartable)) {
+            $vars = $this->query->getResultVars();
+            $header = '<head>';
+            foreach ($vars as $value) {
+                $header = $header
+                        . '<variable name="' . substr($value, 1) . '"/>';
+            }
+            $header = $header . '</head>';
+
+            // build results
+            $solm = $this->query->getSolutionModifier();
+            $sel  = $this->query->getResultForm();
+
+            $distinct = 'false';
+            if ($sel == 'select distinct') {
+                $distinct = 'true';
+            }
+
+            $ordered = 'false';
+            if ($solm['order by'] != 0) {
+                $ordered = 'true';
+            }
+
+            $results = '<results ordered="'.$ordered.'" distinct="'.$distinct.'">';
+            foreach ($arVartable as $value) {
+                $results = $results.'<result>';
+                foreach ($value as $varname => $varvalue) {
+                    $results = $results
+                            . $this->_getBindingString(
+                                substr($varname, 1),
+                                $varvalue
+                            );
+                }
+                $results = $results . '</result>';
+            }
+            $results = $results . '</results>';
+        } else {
+            $results = '</head><boolean>' . $vartable . '</boolean>';
+        }
+
+        $result = $result . $header . $results . '</sparql>';
+        $result = simplexml_load_string($result);
+        return $result->asXML();
+    }//public function convertFromResult($arVartable, Query $query, SparqlEngine $engine)
+
+
+
+    /**
+    * Helper Function for function buildXmlResult($vartable). Generates
+    * an xml string for a single variable an their corresponding value.
+    *
+    * @param  String  $varname The variables name
+    * @param  Node    $varvalue The value of the variable
+    * @return String  The xml string
+    */
+    protected function _getBindingString($varname, $varvalue)
+    {
+        $binding = '<binding name="'.$varname.'">';
+        $value = '<unbound/>';
+
+        if ($varvalue instanceof BlankNode) {
+            $value = '<bnode>' . $varvalue->getLabel() . '</bnode>';
+        } else if ($varvalue instanceof Resource) {
+            $value = '<uri>' . $varvalue->getUri() . '</uri>';
+        } else if ($varvalue instanceof Literal) {
+            $label = htmlspecialchars($varvalue->getLabel());
+            $value = '<literal>'.$label.'</literal>';
+            if ($varvalue->getDatatype() != null) {
+                $value = '<literal datatype="'
+                        . $varvalue->getDatatype() . '">'
+                        . $label
+                        . '</literal>';
+            }
+            if ($varvalue->getLanguage() != null) {
+                $value = '<literal xml:lang="'
+                        . $varvalue->getLanguage() . '">'
+                        . $label
+                        . '</literal>';
+            }
+        }
+        $binding = $binding . $value . '</binding>';
+
+        return $binding;
+    }//protected function _getBindingString($varname, $varvalue)
+
+}//class SparqlEngine_ResultRenderer_XML implements SparqlEngine_ResultRenderer
+
+?>
Index: /Dev/trunk/rdfapi/sparql/SparqlEngineDb.php
===================================================================
--- /Dev/trunk/rdfapi/sparql/SparqlEngineDb.php	(revision 12)
+++ /Dev/trunk/rdfapi/sparql/SparqlEngineDb.php	(revision 12)
@@ -0,0 +1,391 @@
+<?php
+require_once RDFAPI_INCLUDE_DIR . 'sparql/SparqlEngine.php';
+require_once RDFAPI_INCLUDE_DIR . 'sparql/SparqlEngineDb/Offsetter.php';
+require_once RDFAPI_INCLUDE_DIR . 'sparql/SparqlEngineDb/QuerySimplifier.php';
+require_once RDFAPI_INCLUDE_DIR . 'sparql/SparqlEngineDb/ResultConverter.php';
+require_once RDFAPI_INCLUDE_DIR . 'sparql/SparqlEngineDb/SqlGenerator.php';
+require_once RDFAPI_INCLUDE_DIR . 'sparql/SparqlEngineDb/SqlMerger.php';
+
+/**
+*   SPARQL engine optimized for databases.
+*   Generates SQL statements to directly query the database,
+*   letting the database system do all the hard work like
+*   selecting, joining, filtering and ordering results.
+*
+*   @author Christian Weiske <cweiske@cweiske.de>
+*   @license http://www.gnu.org/licenses/lgpl.html LGPL
+*
+*   @package sparql
+*/
+class SparqlEngineDb
+{
+    /**
+    *   Sparql Query object.
+    *
+    *   @var Query
+    */
+    protected $query;
+
+    /**
+    *   RDF dataset object.
+    *   @var Dataset
+    */
+    protected $dataset;
+
+    /**
+    *   Database connection object.
+    *   @var ADOConnection
+    */
+    protected $dbConn;
+
+    /**
+    *   Internal ID for our graph model.
+    *   Stored in the database along the statements.
+    *   Can be of different types:
+    *   - array: array of modelIds
+    *   - null: all models
+    *
+    *   @var array OR null
+    */
+    protected $arModelIds;
+
+    /**
+    *   Prepared SQL statements are stored in here.
+    *   @var array
+    */
+    protected $arPrepared    = null;
+
+    /**
+    *   If the prepared statement is really prepared, or if we just emulate it.
+    *   @var boolean
+    */
+    protected $bRealPrepared = false;
+
+    /**
+    *   SQL generator instance
+    *   @var SparqlEngineDb_SqlGenerator
+    */
+    protected $sg = null;
+
+    /**
+    *   Type sorting instance
+    *   @var SparqlEngineDb_TypeSorter
+    */
+    protected $ts = null;
+
+    /**
+    *   Prepared statments preparator instance
+    *   @var SparqlEngineDb_Preparator
+    */
+    protected $pr = null;
+
+
+
+    /**
+    *   Use SparqlEngine::factory() to create the instance
+    *
+    *   @param mixed $model         DbModel or DbStore
+    *   @param mixed $arModelIds    Array of modelIds, or NULL to use all models
+    */
+    public function __construct($model, $arModelIds = null)
+    {
+        //parent::__construct();
+        if ($model instanceof DbModel) {
+            $this->dbConn     = $model->getDbConn();
+            $this->arModelIds = array($model->getModelID());
+        } else if ($model instanceof DbStore) {
+            $this->dbConn     = $model->getDbConn();
+            $this->arModelIds = $arModelIds;
+        }
+    }//public function __construct(DbModel $model, $arModelIds = null)
+
+
+
+    /**
+    *   Query the database with the given SPARQL query.
+    *
+    *
+    *   @param  Dataset       $dataset    RDF Dataset
+    *   @param  Query         $query      Parsed SPARQL query
+    *   @param  string        $resultform Result form. If set to 'xml' the result will be
+    *                                   SPARQL Query Results XML Format as described in http://www.w3.org/TR/rdf-sparql-XMLres/ .
+    *
+    *   @return array/string  array of triple arrays, or XML. Format depends on
+    *                                   $resultform parameter.
+    */
+    public function queryModel($dataset, Query $query, $resultform = false)
+    {
+        if (isset($GLOBALS['debugSparql']) && $GLOBALS['debugSparql']) {
+            echo "\n" . 'SPARQL query: ' . $query->getQueryString() . "\n";
+        }
+
+        $this->query   = $query;
+        $this->dataset = $dataset;
+
+        $qsimp = new SparqlEngineDb_QuerySimplifier();
+        $qsimp->simplify($this->query);
+
+        $this->sg = new SparqlEngineDb_SqlGenerator   ($this->query, $this->dbConn, $this->arModelIds);
+        $this->rc = new SparqlEngineDb_ResultConverter($this->query, $this->sg, $this);
+        $this->ts = new SparqlEngineDb_TypeSorter     ($this->query, $this->dbConn);
+
+        $this->setOptions();
+
+        if ($this->query->isEmpty()){
+            $vartable[0]['patternResult'] = null;
+            return $this->returnResult($vartable, $resultform);
+        }
+
+
+        $arSqls = $this->sg->createSql();
+        $this->ts->setData($this->sg);
+
+        return
+            SparqlEngineDb_ResultConverter::convertFromDbResults(
+                $this->queryMultiple(
+                    $this->ts->getOrderifiedSqls(
+                        $arSqls
+                    )
+                ),
+                $this,
+                $resultform
+            );
+    }//public function queryModel($dataset, Query $query, $resultform = false)
+
+
+
+    /**
+    *   Create a prepared statement that can be executed later.
+    *
+    *   @param  Dataset       $dataset    RDF Dataset
+    *   @param  Query         $query      Parsed SPARQL query
+    *
+    *   @return SparqlEngineDb_PreparedStatement Prepared statment that can
+    *           be execute()d later.
+    */
+    public function prepare(Dataset $dataset, Query $query)
+    {
+        require_once RDFAPI_INCLUDE_DIR . 'sparql/SparqlEngineDb/PreparedStatement.php';
+        require_once RDFAPI_INCLUDE_DIR . 'sparql/SparqlEngineDb/Preparator.php';
+
+        $this->query   = $query;
+        $this->dataset = $dataset;
+        $this->sg = new SparqlEngineDb_SqlGenerator   ($this->query, $this->dbConn, $this->arModelIds);
+        $this->rc = new SparqlEngineDb_ResultConverter($this->query, $this->sg, $this);
+        $this->ts = new SparqlEngineDb_TypeSorter     ($this->query, $this->dbConn);
+        $this->pr = new SparqlEngineDb_Preparator     ($this->query, $this->dbConn);
+
+        $this->arPrepared = $this->sg->createSql();
+        $this->ts->setData($this->sg);
+
+        if ($this->ts->willBeDataDependent()) {
+            $this->bRealPrepared = false;
+        } else {
+            $this->bRealPrepared     = true;
+            list($strSelect, $strFrom, $strWhere) = $this->arPrepared;
+            $this->arPreparedQueries = $this->ts->getOrderifiedSqls(
+                $strSelect,
+                $strFrom,
+                $strWhere
+            );
+            $this->arDbStatements    = $this->pr->prepareInDb(
+                $this->arPreparedQueries,
+                $this->sg->getPlaceholders()
+            );
+        }
+
+
+        return new SparqlEngineDb_PreparedStatement(
+            $this
+        );
+    }//public function prepare(Dataset $dataset, Query $query)
+
+
+
+    /**
+    *   Execute a prepared statement by filling it with variables
+    *
+    *   @param array $arVariables   Array with (variable name => value) pairs
+    *   @param string $resultform   Which form the result should have
+    *
+    *   @return mixed   Result according to $resultform
+    */
+    public function execute($arVariables, $resultform = false)
+    {
+        if ($this->arPrepared === null) {
+            throw new Exception('You need to prepare() the query first.');
+        }
+
+        if ($this->bRealPrepared) {
+            return
+                SparqlEngineDb_ResultConverter::convertFromDbResults(
+                    $this->pr->execute(
+                        $this->arDbStatements,
+                        $arVariables
+                    ),
+                    $this,
+                    $resultform
+                );
+        } else {
+            list($strSelect, $strFrom, $strWhere) = $this->arPrepared;
+
+            return SparqlEngineDb_ResultConverter::convertFromDbResults(
+                $this->queryMultiple(
+                    $this->ts->getOrderifiedSqls(
+                        $strSelect,
+                        $strFrom,
+                        $this->pr->replacePlaceholdersWithVariables(
+                            $strWhere,
+                            $this->sg->getPlaceholders(),
+                            $arVariables
+                        )
+                    )
+                ),
+                $this,
+                $resultform
+            );
+        }
+    }//public function execute($arVariables, $resultform)
+
+
+
+    /**
+    *   Executes multiple SQL queries and returns an array
+    *   of results.
+    *
+    *   @param array $arSqls     Array of SQL queries
+    *   @return array   Array of query results
+    */
+    protected function queryMultiple($arSqls)
+    {
+        $arSM = $this->query->getSolutionModifier();
+        if ($arSM['limit'] === null && $arSM['offset'] === null) {
+            $nOffset = 0;
+            $nLimit  = null;
+            $nSql    = 0;
+        } else {
+            $offsetter = new SparqlEngineDb_Offsetter($this->dbConn, $this->query);
+            list($nSql, $nOffset) = $offsetter->determineOffset($arSqls);
+            $nLimit    = $arSM['limit'];
+        }
+
+        $nCount    = 0;
+        $arResults = array();
+        foreach ($arSqls as $nId => $arSql) {
+            if ($nId < $nSql) { continue; }
+
+            if ($nLimit != null) {
+                $nCurrentLimit = $nLimit - $nCount;
+            } else {
+                $nCurrentLimit = null;
+            }
+
+            $dbResult    = $this->queryDb($arSql, $nOffset, $nCurrentLimit);
+            $nCount     += $dbResult->RowCount();
+            $arResults[] = $dbResult;
+            $nOffset = 0;
+            if ($nLimit !== null && $nCount >= $nLimit) {
+                break;
+            }
+        }
+
+        return $arResults;
+        //return array_map(array($this, 'queryDb'), $arSql);
+    }//protected function queryMultiple($arSql)
+
+
+
+    /**
+    *   Sends the sql to the database and returns the results.
+    *
+    *   @internal Switches between ADOConnection::Execute() and
+    *    ADOConnection::SelectLimit() depending on the $query parameter's
+    *    $solutionModifier "limit" and "offset" settings.
+    *   Uses $query variable.
+    *
+    *   @param array $arSql     Array that gets a SQL query string once imploded
+    *
+    *   @return mixed           Anything ADOConnection::Execute() may return
+    *   @throws Exception       If Database query does not work
+    */
+    function queryDb($arSql, $nOffset, $nLimit)
+    {
+        $strSql = SparqlEngineDb_SqlMerger::getSelect($this->query, $arSql);
+
+        if ($strSql == '()') {
+            return new ADORecordSet(false);
+        }
+
+        // I want associative arrays.
+        $oldmode = $this->dbConn->SetFetchMode(ADODB_FETCH_ASSOC);
+
+        if (isset($GLOBALS['debugSparql']) && $GLOBALS['debugSparql']) {
+            echo 'SQL query: ' . $strSql . "\n";
+        }
+
+        if ($nLimit === null && $nOffset == 0) {
+            $ret = $this->dbConn->execute($strSql);
+        } else if ($nLimit === null) {
+            $ret = $this->dbConn->SelectLimit($strSql, -1, $nOffset);
+        } else {
+            $ret = $this->dbConn->SelectLimit($strSql, $nLimit, $nOffset);
+        }
+
+        //... but others maybe not
+        $this->dbConn->SetFetchMode($oldmode);
+
+        if (!$ret) {
+            //Error occured
+            throw new Exception(
+                'ADOdb error: ' . $this->dbConn->ErrorMsg() . "\n"
+                . $strSql
+            );
+        }
+
+        return $ret;
+    }//function queryDb($sql)
+
+
+
+    /**
+    *   Set options to subobjects like SqlGenerator
+    */
+    protected function setOptions()
+    {
+        //allow changing the statements' table name
+        if (isset($GLOBALS['RAP']['conf']['database']['tblStatements'])) {
+            $this->sg->setStatementsTable(
+                $GLOBALS['RAP']['conf']['database']['tblStatements']
+            );
+        }
+    }//protected function setOptions()
+
+
+
+    /*
+    *   Dumb getters
+    */
+
+
+
+    public function getQuery()
+    {
+        return $this->query;
+    }//public function getQuery()
+
+
+
+    public function getSqlGenerator()
+    {
+        return $this->sg;
+    }//public function getSqlGenerator()
+
+
+
+    public function getTypeSorter()
+    {
+        return $this->ts;
+    }//public function getTypeSorter()
+
+}//class SparqlEngineDb
+?>
Index: /Dev/trunk/rdfapi/sparql/SparqlEngineDb/FilterGenerator.php
===================================================================
--- /Dev/trunk/rdfapi/sparql/SparqlEngineDb/FilterGenerator.php	(revision 12)
+++ /Dev/trunk/rdfapi/sparql/SparqlEngineDb/FilterGenerator.php	(revision 12)
@@ -0,0 +1,846 @@
+<?php
+require_once RDFAPI_INCLUDE_DIR . 'sparql/SparqlVariable.php';
+
+/**
+*   Generates SQL from Sparql FILTER parts
+*
+*   @author Christian Weiske <cweiske@cweiske.de>
+*   @license http://www.gnu.org/licenses/lgpl.html LGPL
+*
+*   @package sparql
+*/
+class SparqlEngineDb_FilterGenerator
+{
+    /**
+    *   SQL Generator
+    *   @var SparqlEngineDb_SqlGenerator
+    */
+    protected $sg = null;
+
+    /**
+    *   If the filter is in an optional statement
+    *   @var boolean
+    */
+    protected $bOptional    = false;
+
+    /**
+    *   Number of parameters for the functions supported.
+    *   First value is minimum, second is maximum.
+    *   @var array
+    */
+    protected static $arFuncParamNumbers = array(
+        'bound'         => array(1, 1),
+        'datatype'      => array(1, 1),
+        'isblank'       => array(1, 1),
+        'isiri'         => array(1, 1),
+        'isliteral'     => array(1, 1),
+        'isuri'         => array(1, 1),
+        'lang'          => array(1, 1),
+        'langmatches'   => array(2, 2),
+        'regex'         => array(2, 3),
+        'sameterm'      => array(2, 2),
+        'str'           => array(1, 1),
+        'xsd:datetime'  => array(1, 1),
+    );
+
+    /**
+    *   List of operators and their counterpart if operands are switched.
+    *   (a > b) => (b < a)
+    *   @var array
+    */
+    protected static $arOperatorSwitches = array(
+        '>'     => '<',
+        '<'     => '>',
+        '>='    => '<=',
+        '<='    => '>=',
+    );
+
+    protected static $arDumbOperators = array(
+        '&&', '||'
+    );
+
+    protected static $typeXsdBoolean  = 'http://www.w3.org/2001/XMLSchema#boolean';
+    protected static $typeXsdDateTime = 'http://www.w3.org/2001/XMLSchema#dateTime';
+    protected static $typeXsdDouble   = 'http://www.w3.org/2001/XMLSchema#double';
+    protected static $typeXsdInteger  = 'http://www.w3.org/2001/XMLSchema#integer';
+    protected static $typeXsdString   = 'http://www.w3.org/2001/XMLSchema#string';
+    protected static $typeVariable    = 'variable';
+
+
+
+    public function __construct(SparqlEngineDb_SqlGenerator $sg)
+    {
+        $this->sg = $sg;
+    }//public function __construct(SparqlEngineDb_SqlGenerator $sqlgen)
+
+
+
+    /**
+    *   Creates the SQL representing a Sparql FILTER.
+    *
+    *   @param array $tree  Filter element tree as returned by
+    *                       SparqlParser::parseConstraintTree()
+    *   @param boolean $bOptional   If the filter is in an optional statement
+    *   @return string  SQL WHERE part with prefixed AND
+    */
+    public function createFilterSql($tree, $bOptional, $nUnionCount)
+    {
+        if (count($tree) == 0) {
+            //empty filter pattern?
+            return '';
+        }
+
+        $this->bOptional = $bOptional;
+        $this->nUnionCount = $nUnionCount;
+
+        return ' AND ' . $this->createTreeSql($tree, null);
+    }//public function createFilterSql($tree)
+
+
+
+    /**
+    *
+    */
+    protected function createTreeSql($tree, $parent)
+    {
+        switch ($tree['type']) {
+            case 'equation':
+                $sql = $this->createEquation($tree);
+                break;
+            case 'value':
+                if ($parent != null) {
+                    $bDumbParent = $parent['type'] == 'equation'
+                        && in_array($parent['operator'], self::$arDumbOperators);
+                } else {
+                    $bDumbParent = true;
+                }
+                $sql = $this->createValue($tree, $bDumbParent);
+                break;
+            case 'function':
+                $sql = $this->createFunction($tree);
+                break;
+            default:
+                //var_dump($tree);
+                throw new SparqlEngineDb_SqlGeneratorException('Unsupported tree type: ' . $tree['type']);
+                break;
+        }
+
+        if (isset($tree['negated'])) {
+            $sql = '!(' . $sql . ')';
+        }
+
+        return $sql;
+    }//protected function createTreeSql($tree, $strParentType)
+
+
+
+    /**
+    *   Creates the sql for an element of type "value".
+    *
+    *   @param array $tree  Element
+    *   @param boolean $bDumbParent True if the parent is a boolean equation or null.
+    */
+    protected function createValue($tree, $bDumbParent)
+    {
+        $strValue = stripslashes($tree['value']);
+        if (SparqlVariable::isVariable($strValue)) {
+            if (!isset($this->sg->arUnionVarAssignments[$this->nUnionCount][$strValue])) {
+                throw new SparqlEngineDb_SqlGeneratorException(
+                    'Unknown variable in filter: ' . $strValue
+                );
+            }
+
+            if ($bDumbParent) {
+                return $this->createBooleanValue($tree);
+            } else if ($this->isObject($tree)) {
+                //convert datetime to datetime if necessary
+                return self::mkVal(
+                    '(CASE'
+                    . ' WHEN ' . $this->getDatatypeCol($tree) . ' = "' . self::$typeXsdBoolean . '"'
+                        . ' THEN IF(LOWER(' . $this->getValueCol($tree) . ') = "true", TRUE, FALSE)'
+                    . ' ELSE ' . $this->getValueCol($tree)
+                    . ' END)',
+                    self::$typeVariable
+                );
+            } else {
+                return self::mkVal(
+                    $this->getValueCol($tree),
+                    self::$typeVariable
+                );
+            }
+        }
+
+        if ($this->isNumber($tree)) {
+            return $strValue;
+        } else if ($tree['quoted'] === false &&
+          (!isset($tree['datatype']) || $tree['datatype'] != self::$typeXsdBoolean)
+        ) {
+            $strValueNew = $this->sg->query->getFullUri($strValue);
+            if ($strValueNew === false) {
+                if ($strValue[0] == '<' && substr($strValue, -1) == '>') {
+                    $strValue = substr($strValue, 1, -1);
+                } else {
+var_dump($tree);
+                    throw new SparqlEngineDb_SqlGeneratorException(
+                        'Unexpected value "' . $strValue . '" (expected datatype)'
+                    );
+                }
+            } else {
+                $strValue = $strValueNew;
+            }
+        } else if (isset($tree['datatype'])) {
+            switch ($tree['datatype']) {
+                case self::$typeXsdBoolean:
+                    if (strtolower($strValue) == 'false') {
+                        //fix: (bool)"false" === true
+                        $strValue = false;
+                    }
+                    return self::mkVal(
+                        (bool)$strValue ? 'TRUE' : 'FALSE',
+                        self::$typeXsdBoolean
+                    );
+
+                default:
+                    throw new SparqlEngineDb_SqlGeneratorException(
+                        'Unsupported datatype "' . $tree['datatype']
+                    );
+            }
+        }
+
+        return self::mkVal(
+            '"' . addslashes($strValue) . '"',
+            self::$typeXsdString
+        );
+    }//protected function createValue($tree)
+
+
+
+    protected function createBooleanValue($tree)
+    {
+        list($strTable, $chType) = $this->sg->arUnionVarAssignments[$this->nUnionCount][$tree['value']];
+        if (!$this->isObject($tree)) {
+            //Maybe needs a fix
+            $strSqlCol = SparqlEngineDb_SqlGenerator::$arTableColumnNames[$chType]['value'];
+            return self::mkVal(
+                $strTable . '.' . $strSqlCol . ' != ""',
+                self::$typeXsdBoolean
+            );
+        }
+
+        $cType  = $strTable . '.l_datatype';
+        $cValue = $strTable . '.object';
+        $xsd    = 'http://www.w3.org/2001/XMLSchema';
+
+        return self::mkVal(
+            '('
+            . "(($cType = '' || $cType = '$xsd#string') AND $cValue != '')"
+            . " OR ($cType = '$xsd#boolean' AND $cValue != 'false')"
+            . " OR (($cType = '$xsd#integer' || $cType = '$xsd#double') AND CAST($cValue AS DECIMAL(15,10)) != 0)"
+            //plain check for all unknown datatypes
+            . " OR ($cType != '' AND $cType != '$xsd#string' AND $cType != '$xsd#boolean' AND $cType != '$xsd#integer' AND $cType != '$xsd#double' AND $cValue != '')"
+            . ')',
+            self::$typeXsdBoolean
+        );
+    }//protected function createBooleanValue($tree)
+
+
+
+    protected function createFunction($tree)
+    {
+        $strFuncName = strtolower($tree['name']);
+        if (!isset(self::$arFuncParamNumbers[$strFuncName])) {
+            throw new SparqlEngineDb_SqlGeneratorException(
+                'Unsupported FILTER function: ' . $strFuncName
+            );
+        }
+
+        $nParams     = count($tree['parameter']);
+        if ($nParams < self::$arFuncParamNumbers[$strFuncName][0]
+         || $nParams > self::$arFuncParamNumbers[$strFuncName][1]
+        ) {
+            throw new SparqlEngineDb_SqlGeneratorException(
+                'Wrong parameter count for FILTER function: ' . $strFuncName
+                . ' (got ' . $nParams . ', expected '
+                . self::$arFuncParamNumbers[$strFuncName][0]
+                . '-' . self::$arFuncParamNumbers[$strFuncName][1]
+            );
+        }
+
+        $strThisFunc = 'createFunction_' . str_replace(':', '_', $strFuncName);
+        return $this->$strThisFunc($tree);
+    }//protected function createFunction($tree)
+
+
+
+    protected function createEquation($tree)
+    {
+        $strExtra       = '';
+        $strIsNull      = '';
+        $strIsNullEnd   = '';
+
+        if (($this->isNumber($tree['operand1']) || $this->isPlainString($tree['operand1']))
+            && $this->isObject($tree['operand2'])
+        ) {
+            //switch operands and operator
+            $tmp = $tree['operand1'];
+            $tree['operand1'] = $tree['operand2'];
+            $tree['operand2'] = $tmp;
+            $tree['operator'] = self::switchOperator($tree['operator']);
+        }
+
+        $val1 = $this->createTreeSql($tree['operand1'], $tree);
+        $val2 = $this->createTreeSql($tree['operand2'], $tree);
+
+        if ($this->isObject($tree['operand1'])) {
+            if ($this->bOptional) {
+                $strIsNull    = '(';
+                $strIsNullEnd = ' OR ' . $val1 . ' IS NULL)';
+            }
+            if (isset($tree['operand2']['language'])) {
+                $strColLanguage = $this->getLangCol($tree['operand1']);
+                $strExtra .= ' AND ' . $strColLanguage . ' = "'
+                    . addslashes($tree['operand2']['language'])
+                    . '"';
+            }
+
+            if ($this->isNumber($tree['operand2'])) {
+                $strColDatatype = $this->getDatatypeCol($tree['operand1']);
+                $strExtra .= ' AND (' . $strColDatatype . '  = "' . self::$typeXsdDouble . '"'
+                    . ' OR ' . $strColDatatype . '  = "' . self::$typeXsdInteger . '"'
+                    . ')';
+                return $strIsNull . '('
+                    . 'CAST(' . $val1 . ' AS DECIMAL(15,10))'
+                    . ' ' . $tree['operator'] . ' '
+                    . $val2
+                    . $strExtra
+                    . ')' . $strIsNullEnd;
+            }
+        }
+
+        //I don't check the operator since it is already checked in the parser
+        return $strIsNull . '('
+            . '('
+                . $val1
+                . ' ' . $tree['operator'] . ' '
+                . $val2
+                . $strExtra
+            . ')'
+            . $this->createTypeEquation(
+                $tree['operator'], $val1, $val2,
+                $tree['operand1'], $tree['operand2']
+            )
+            . ')' . $strIsNullEnd;
+    }//protected function createEquation($tree)
+
+
+
+    /**
+    *   Generates sql code to make sure the datatypes of the two operands match
+    */
+    protected function createTypeEquation($operator, $val1, $val2, $tree1, $tree2)
+    {
+        if (in_array($operator, array('&&', '||'))) {
+            return '';
+        }
+
+        if ($val1->type != self::$typeVariable && $val2->type != self::$typeVariable) {
+            //both are not variables -> type needs to be the same
+            return $val1->type == $val2->type ? '' : ' AND FALSE';
+        }
+        $so1 = $this->isObjectOrSubject($tree1);
+        $so2 = $this->isObjectOrSubject($tree2);
+        $o1  = $this->isObject($tree1);
+        $o2  = $this->isObject($tree2);
+
+        if ($so1 && $so2) {
+            $sql = ' AND ' . $this->getIsCol($tree1) . ' = ' . $this->getIsCol($tree2);
+            if ($o1 && $o2) {
+                //maybe needs string fix
+                $sql .= ' AND ' . $this->getDatatypeCol($tree1) . ' = '
+                    . $this->getDatatypeCol($tree2);
+            }
+            return $sql;
+        }
+
+        if ($o1 && $val2->type != self::$typeVariable) {
+            return $this->createSingleTypeCheck($val2, $tree1);
+        } else if ($o2 && $val1->type != self::$typeVariable) {
+            return $this->createSingleTypeCheck($val1, $tree2);
+        }
+
+        //fixme
+        return '';
+    }//protected function createTypeEquation($operator, $val1, $val2, $tree1, $tree2)
+
+
+
+    /**
+    *   Creates sql to ensure the type between $val and variable $tree
+    *   is the same.
+    */
+    protected function createSingleTypeCheck($val, $tree)
+    {
+        if ($val->type == self::$typeXsdString) {
+            //string can be empty type or xsd type
+            return ' AND ('
+                . $this->getDatatypeCol($tree) . ' = "' . $val->type . '"'
+                . ' OR '
+                . $this->getDatatypeCol($tree) . ' = ""'
+                . ')';
+        }
+        return ' AND ' . $this->getDatatypeCol($tree) . ' = "' . $val->type . '"';
+    }//protected function createSingleTypeCheck($val, $tree)
+
+
+
+    /*
+    *   SQL generation functions
+    */
+
+
+
+    /**
+    *   Creates an sql statement that returns if the element is a blank node
+    */
+    protected function createFunction_bound($tree)
+    {
+        if ($this->isVariable($tree['parameter'][0])) {
+            return self::mkVal(
+                $this->getValueCol($tree['parameter'][0]) . ' IS NOT NULL',
+                self::$typeXsdBoolean
+            );
+        }
+
+        //We'll see which other cases occur here
+        return self::mkVal('TRUE', self::$typeXsdBoolean);
+    }//protected function createFunction_bound($tree)
+
+
+
+    protected function createFunction_datatype($tree)
+    {
+        if (!$this->isObject($tree['parameter'][0])) {
+            throw new SparqlEngineDb_SqlGeneratorException(
+                'datatype\'s first parameter needs to be an object'
+            );
+        }
+
+        return self::mkVal(
+            $this->getDatatypeCol($tree['parameter'][0]),
+            self::$typeXsdString
+        );
+    }//protected function createFunction_datatype($tree)
+
+
+
+    /**
+    *   Creates an sql statement that returns if the element is a blank node
+    */
+    protected function createFunction_isblank($tree)
+    {
+        if (!$this->isObjectOrSubject($tree['parameter'][0])) {
+            throw new SparqlEngineDb_SqlGeneratorException(
+                'isBlank\'s first parameter needs to be an object or subject'
+            );
+        }
+
+        return self::mkVal(
+            $this->getIsCol($tree['parameter'][0]) . ' = "b"',
+            self::$typeXsdBoolean
+        );
+    }//protected function createFunction_isblank($tree)
+
+
+
+    protected function createFunction_isiri($tree)
+    {
+        return $this->createFunction_isuri($tree);
+    }//protected function createFunction_isiri($tree)
+
+
+
+    /**
+    *   Creates an sql statement that returns the language of the object
+    */
+    protected function createFunction_isliteral($tree)
+    {
+        if ($this->isObjectOrSubject($tree['parameter'][0])) {
+            return $this->getIsCol($tree['parameter'][0]) . ' = "l"';
+        }
+
+        //This does not take combined functions into account (subfunctions)
+        return self::mkVal(
+            $this->isPlainString($tree) ? 'TRUE' : 'FALSE',
+            self::$typeXsdBoolean
+        );
+    }//protected function createFunction_isliteral($tree)
+
+
+
+    protected function createFunction_isuri($tree)
+    {
+        if ($this->isObjectOrSubject($tree['parameter'][0])) {
+            return self::mkVal(
+                $this->getIsCol($tree['parameter'][0]) . ' = "r"',
+                self::$typeXsdBoolean
+            );
+        } else {
+            //predicates are iris
+            return self::mkVal('TRUE', self::$typeXsdBoolean);
+        }
+    }//protected function createFunction_isuri($tree)
+
+
+
+    /**
+    *   Creates an sql statement that returns the language of the object
+    */
+    protected function createFunction_lang($tree)
+    {
+        if (!$this->isObject($tree['parameter'][0])) {
+            throw new SparqlEngineDb_SqlGeneratorException(
+                'lang\'s first parameter needs to be an object'
+            );
+        }
+        return self::mkVal(
+            $this->getLangCol($tree['parameter'][0]),
+            self::$typeXsdString
+        );
+    }//protected function createFunction_lang($tree)
+
+
+
+    /**
+    *   Creates an sql statement that checks if the variable
+    *   matches a given language
+    */
+    protected function createFunction_langmatches($tree)
+    {
+        //those two restrictions are needed until we have a mysql-only
+        // langmatches function
+        if ($tree['parameter'][0]['type'] != 'function'
+         || $tree['parameter'][0]['name'] != 'lang'
+        ) {
+            throw new SparqlEngineDb_SqlGeneratorException(
+                'langMatches\' first parameter needs to be a lang() function'
+            );
+        }
+
+        if (!$this->isPlainString($tree['parameter'][1])) {
+            throw new SparqlEngineDb_SqlGeneratorException(
+                'langMatches\' second parameter needs to be a string'
+            );
+        }
+
+        $lang  = $tree['parameter'][1]['value'];
+        $col   = $this->createTreeSql($tree['parameter'][0], $tree);
+
+        switch ($lang) {
+            case '*':
+                //anything but nothing
+                $sql = $col . ' != ""';
+                break;
+            case '':
+                //nothing
+                $sql = $col . ' = ""';
+                break;
+            default:
+                //language, maybe with different subcode
+                // en -> en, en-US
+                $sql = '(' . $col . ' = "' . addslashes($lang) . '" OR '
+                    . $col . ' LIKE "' . addslashes($lang) . '-%")';
+                break;
+        }
+
+        return self::mkVal($sql, self::$typeXsdBoolean);
+    }//protected function createFunction_isuri($tree)
+
+
+
+    /**
+    *   Creates an sql statement that checks if the given part matches
+    *   an regex
+    */
+    protected function createFunction_regex($tree)
+    {
+        $strVar   = $this->createTreeSql($tree['parameter'][0], $tree);
+        $strRegex = $this->createTreeSql($tree['parameter'][1], $tree);
+
+        if (isset($tree['parameter'][2])) {
+            //is quoted
+            $strMod = $this->createTreeSql($tree['parameter'][2], $tree);
+            switch ($strMod) {
+                case '':
+                case '""':
+                    $sql = $strVar . ' REGEXP ' . $strRegex;
+                    break;
+
+                case '"i"':
+                    $sql = 'CAST(' . $strVar . ' AS CHAR) REGEXP ' . $strRegex;
+                    break;
+
+                default:
+                    throw new SparqlEngineDb_SqlGeneratorException(
+                        'Unsupported regex modifier "'
+                        . $strMod
+                        . '"'
+                    );
+            }
+        } else {
+            $sql = $strVar . ' REGEXP ' . $strRegex;
+        }
+
+        if ($this->isObject($tree['parameter'][0])) {
+            $col = $this->getIsCol($tree['parameter'][0]);
+            $sql = "($sql AND $col = 'l')";
+        }
+
+        return self::mkVal($sql, self::$typeXsdBoolean);
+    }//protected function createFunction_regex($tree)
+
+
+
+    /**
+    *   Creates an sql statement that checks if both terms are the same
+    */
+    protected function createFunction_sameterm($tree)
+    {
+        //FIXME: dead simple implementation that does not cover all cases
+        return self::mkVal(
+            $this->createTreeSql($tree['parameter'][0], $tree)
+                . ' = '
+                . $this->createTreeSql($tree['parameter'][1], $tree),
+            self::$typeXsdBoolean
+        );
+    }//protected function createFunction_sameterm($tree)
+
+
+
+    /**
+    *   Creates an sql statement that returns the string representation
+    *   of the given element
+    */
+    protected function createFunction_str($tree)
+    {
+        if ($this->isObject($tree['parameter'][0])) {
+            return self::mkVal(
+                '(CASE ' . $this->getIsCol($tree['parameter'][0])
+                . ' WHEN "b" THEN ""'
+                . ' ELSE ' . $this->getValueCol($tree['parameter'][0])
+                . ' END)',
+                self::$typeXsdString
+            );
+        }
+
+        return $this->createTreeSql($tree['parameter'][0], $tree);
+    }//protected function createFunction_str($tree)
+
+
+
+    /**
+    *   Creates an sql statement that returns the datetime representation
+    *   of the given element
+    */
+    protected function createFunction_xsd_datetime($tree)
+    {
+        $val = $this->createTreeSql($tree['parameter'][0], $tree);
+        if ($val->type == self::$typeXsdDateTime
+         || $val->type == self::$typeVariable) {
+            //no need to cast again
+            return $val;
+        }
+        return self::mkVal(
+            $this->getDateConversionSql($val),
+            self::$typeXsdDateTime
+        );
+    }//protected function createFunction_xsd_datetime($tree)
+
+
+
+
+    /*
+    *   Helper methods
+    */
+
+
+
+    protected static function mkVal($value, $type = null) {
+        return new SparqlEngineDb_FilterGenerator_Value($value, $type);
+    }
+
+
+
+    protected function getCol($tree, $type)
+    {
+        list($strTable, $chType) = $this->sg->arUnionVarAssignments[$this->nUnionCount][$tree['value']];
+        if (!isset(SparqlEngineDb_SqlGenerator::$arTableColumnNames[$chType][$type])) {
+            return false;
+        }
+        $strSqlCol = SparqlEngineDb_SqlGenerator::$arTableColumnNames[$chType][$type];
+        return $strTable . '.' . $strSqlCol;
+    }
+
+
+
+    protected function getDatatypeCol($tree)
+    {
+        list($strTable, $chType) = $this->sg->arUnionVarAssignments[$this->nUnionCount][$tree['value']];
+        return $strTable . '.l_datatype';
+    }
+
+
+
+    protected function getDateConversionSql($strValue)
+    {
+        return 'STR_TO_DATE(' . $strValue . ', "%Y-%m-%dT%H:%i:%sZ")';
+    }//protected function getDateConversionSql($strValue)
+
+
+
+    protected function getIsCol($tree)
+    {
+        return $this->getCol($tree, 'is');
+    }
+
+
+
+    protected function getLangCol($tree)
+    {
+        list($strTable, $chType) = $this->sg->arUnionVarAssignments[$this->nUnionCount][$tree['value']];
+        return $strTable . '.l_language';
+    }
+
+
+
+    protected function getValueCol($tree)
+    {
+        return $this->getCol($tree, 'value');
+    }
+
+
+
+    protected function isNumber($tree)
+    {
+        return $tree['type'] == 'value'
+         && $tree['quoted'] === false
+         && preg_match('#^[0-9.]+$#', $tree['value'])
+         && floatval($tree['value']) == $tree['value'];
+    }//protected function isNumber($tree)
+
+
+
+    /**
+    *   Checks if the given tree element is a variable
+    *   and the variable is actually an object in the database.
+    *
+    *   @param array $tree  Tree element
+    *   @return boolean True if the element is an object
+    */
+    protected function isObject($tree)
+    {
+        return $this->isVariable($tree)
+         && $this->sg->arUnionVarAssignments[$this->nUnionCount][$tree['value']][1] == 'o';
+    }//protected function isVariable($tree)
+
+
+
+    /**
+    *   Checks if the given tree element is a variable
+    *   and the variable is actually an object or a subject in the database.
+    *
+    *   @param array $tree  Tree element
+    *   @return boolean True if the element is an object or an subject
+    */
+    protected function isObjectOrSubject($tree)
+    {
+        return $this->isVariable($tree)
+         && (
+            $this->sg->arUnionVarAssignments[$this->nUnionCount][$tree['value']][1] == 'o'
+         || $this->sg->arUnionVarAssignments[$this->nUnionCount][$tree['value']][1] == 's'
+        );
+    }//protected function isObjectOrSubject($tree)
+
+
+
+    /**
+    *   Checks if the given tree element is a plain string (no variable)
+    *
+    *   @param array $tree  Tree element
+    *   @return boolean True if the element is a string
+    */
+    protected function isPlainString($tree)
+    {
+        return $tree['type'] == 'value'
+         && $tree['quoted'] === true;
+    }//protected function isPlainString($tree)
+
+
+
+    protected function isValueButNotVariableNorString($tree)
+    {
+        return $tree['type'] == 'value'
+         && $tree['type']['quoted'] === false
+         && !SparqlVariable::isVariable($tree['value']);
+    }//protected function isValueButNotVariableNorString($tree)
+
+
+
+    /**
+    *   Checks if the given tree element is a variable
+    *
+    *   @param array $tree  Tree element
+    *   @return boolean True if the element is a variable
+    */
+    protected function isVariable($tree)
+    {
+        return $tree['type'] == 'value'
+         && $tree['quoted'] === false
+         && SparqlVariable::isVariable($tree['value'])
+         && isset($this->sg->arUnionVarAssignments[$this->nUnionCount][$tree['value']]);
+    }//protected function isVariable($tree)
+
+
+
+    protected static function switchOperator($op)
+    {
+        if (!isset(self::$arOperatorSwitches[$op])) {
+            return $op;
+        } else {
+            return self::$arOperatorSwitches[$op];
+        }
+    }//protected static function switchOperator($op)
+
+}//class SparqlEngineDb_FilterGenerator
+
+
+
+
+/**
+*   Value class that holds some arbitrary value
+*   and a datatype.
+*   Objects of this class can transparently be used in strings since
+*   its __toString() returns the value.
+*/
+class SparqlEngineDb_FilterGenerator_Value
+{
+    public $value = null;
+    public $type  = null;
+
+
+
+    public function __construct($value, $type = null)
+    {
+        $this->value = $value;
+        $this->type  = $type;
+    }
+
+
+
+    public function __toString()
+    {
+        return $this->value;
+    }
+
+}//class SparqlEngineDb_FilterGenerator_Value
+
+?>
Index: /Dev/trunk/rdfapi/sparql/SparqlEngineDb/Offsetter.php
===================================================================
--- /Dev/trunk/rdfapi/sparql/SparqlEngineDb/Offsetter.php	(revision 12)
+++ /Dev/trunk/rdfapi/sparql/SparqlEngineDb/Offsetter.php	(revision 12)
@@ -0,0 +1,102 @@
+<?php
+require_once RDFAPI_INCLUDE_DIR . 'sparql/SparqlEngineDb/SqlMerger.php';
+
+/**
+*   Determines the offset in a row of sql queries.
+*
+*   @author Christian Weiske <cweiske@cweiske.de>
+*   @license http://www.gnu.org/licenses/lgpl.html LGPL
+*
+*   @package sparql
+*/
+class SparqlEngineDb_Offsetter
+{
+    public function __construct(ADOConnection $dbConn, Query $query)
+    {
+        $this->dbConn   = $dbConn;
+        $this->query    = $query;
+    }//public function __construct(ADOConnection $dbConn, Query $query)
+
+
+
+    /**
+    *   Determines the offset in the sqls, the position to start form.
+    *
+    *   @param array $arSqls    Array of SQL query parts as returned by
+    *                           SparqlEngine_TypeSorter::getOrderifiedSqls()
+    *   @return array   Array of two values: The first determines the
+    *                   index of the sql query to begin with, the second
+    *                   is the row offset that should be used in the final
+    *                   SQL query.
+    */
+    public function determineOffset($arSqls)
+    {
+        $arSM = $this->query->getSolutionModifier();
+        if ($arSM['offset'] === null) {
+            return array(0, 0);
+        }
+
+        $nCount = 0;
+        foreach ($arSqls as $nId => $arSql) {
+            $nCurrentCount = $this->getCount($arSql);
+            if ($nCurrentCount + $nCount > $arSM['offset']) {
+                return array($nId, $arSM['offset'] - $nCount);
+            }
+            $nCount += $nCurrentCount;
+        }
+        //nothing found - no results for this offset
+        return array(count($arSqls), 0);
+    }//public function determineOffset($arSql)
+
+
+
+    /**
+    *   Returns the number of rows that the given query will return.
+    *
+    *   @param array $arSql Array with sql parts and at least keys
+    *                'from' and 'where' set.
+    *   @return int     Number of rows returned.
+    */
+    protected function getCount($arSql)
+    {
+        $sql = SparqlEngineDb_SqlMerger::getCount($this->query, $arSql);
+        $dbResult = $this->dbConn->execute($sql);
+
+        $nCount = 0;
+        foreach ($dbResult as $row) {
+            $nCount = intval($row[0]);
+            break;
+        }
+        return $nCount;
+    }//protected function getCount($arSql)
+
+
+
+    /**
+    *   Creates a sql LIMIT statement if the sparql query needs one.
+    *   This method is needed because AdoDb does not support limits with
+    *   prepared statements. It's a pity.
+    *
+    *   @return string  SQL command to be appended to a query, to limit
+    *                   the number of result rows returned.
+    */
+    public static function getLimitSql(Query $query, ADOConnection $dbConn)
+    {
+        $arSM = $query->getSolutionModifier();
+        if ($arSM['limit'] === null && $arSM['offset'] === null) {
+            return '';
+        }
+        //this here is mysql syntax. if anyone has problems, write it
+        //dependent on $dbConn's type
+        if ($arSM['offset'] === null) {
+            return ' LIMIT ' . $arSM['limit'];
+        } else if ($arSM['limit'] === null) {
+            return ' LIMIT ' . $arSM['offset'] . ', 18446744073709551615';
+        } else {
+            return ' LIMIT ' . $arSM['offset'] . ', ' . $arSM['limit'];
+        }
+    }//public static function getLimitSql(Query $query, ADOConnection $dbConn)
+
+}//class SparqlEngineDb_Offsetter
+
+?>
Index: /Dev/trunk/rdfapi/sparql/SparqlEngineDb/Preparator.php
===================================================================
--- /Dev/trunk/rdfapi/sparql/SparqlEngineDb/Preparator.php	(revision 12)
+++ /Dev/trunk/rdfapi/sparql/SparqlEngineDb/Preparator.php	(revision 12)
@@ -0,0 +1,229 @@
+<?php
+require_once RDFAPI_INCLUDE_DIR . 'sparql/SparqlEngineDb/Offsetter.php';
+
+/**
+*   This class takes care of prepared statements:
+*   Preparing them in the database, replacing
+*
+*   @author Christian Weiske <cweiske@cweiske.de>
+*   @license http://www.gnu.org/licenses/lgpl.html LGPL
+*
+*   @package sparql
+*/
+class SparqlEngineDb_Preparator
+{
+
+
+
+    public function __construct(Query $query, ADOConnection $dbConn)
+    {
+        $this->query        = $query;
+        $this->dbConn       = $dbConn;
+        $this->arPrefixes   = $this->query->getPrefixes();
+    }//public function __construct(Query $query, ADOConnection $dbConn)
+
+
+
+    /**
+    *   Converts the given queries into sql prepared statments,
+    *   calls the prepare command in the database and returns
+    *   an array consisting of subarrays. They contain
+    *   the db's prepared statement as first value, and an array
+    *   of variable positions as second value (key is the position,
+    *   the sparql variable is the value).
+    *
+    *   @param array $arQueries      Array of sql queries part arrays
+    *   @param array $arPlaceholders Array of sparql (variable name =>
+    *                                placeholder name) pairs
+    *   @return array  Array of (prepared statment, variable positions) pairs
+    */
+    public function prepareInDb($arQueries, $arPlaceholders)
+    {
+        $arDbStatements = array();
+
+        foreach ($arQueries as $arQuery) {
+            list($strPrepared, $arVariablePositions) = $this->replacePlaceholders(
+                implode('', $arQuery),
+                $arPlaceholders
+            );
+            if (count($arQueries) == 1) {
+                //I currently haven't seens one case in which the count was > 1
+                //if that happens, we will need to add a fix
+                $strPrepared .= SparqlEngineDb_Offsetter::getLimitSql(
+                    $this->query,
+                    $this->dbConn
+                );
+            }
+            $stmt = $this->dbConn->Prepare($strPrepared);
+            $arDbStatements[] = array(
+                $stmt,
+                $arVariablePositions
+            );
+        }
+
+        return $arDbStatements;
+    }//public function prepareInDb($arQueries, $arPlaceholders)
+
+
+
+    /**
+    *   Replaces the placeholders in the given SQL statement with real
+    *   SQL prepared statements placeholders.
+    *
+    *   @param string $strQuery SQL query with placeholders
+    *   @param array $arPlaceholders Array of sparql (variable name =>
+    *                                placeholder name) pairs
+    *   @return array (prepared sql query string, variable positions) pair
+    */
+    protected function replacePlaceholders($strQuery, $arPlaceholders)
+    {
+        $arVariablePositions = array();
+        $this->arTmpVariablePositions = array();
+        $this->arTmpPlaceholders      = $arPlaceholders;
+        $strQuery = preg_replace_callback(
+            '/@\\$%_PLACEHOLDER_[0-9]+_%\\$@/',
+            array($this, 'replacePlaceholdersCb'),
+            $strQuery
+        );
+        return array($strQuery, $this->arTmpVariablePositions);
+    }//protected function replacePlaceholders($strQuery, $arPlaceholders)
+
+
+
+    /**
+    *   Callback method internally used by replacePlaceholders() method.
+    */
+    protected function replacePlaceholdersCb($matches)
+    {
+        $strPlaceholder     = $matches[0];
+        $strSparqlVariable  = array_search(
+            $strPlaceholder,
+            $this->arTmpPlaceholders
+        );
+        $strDbPlaceholder   = $this->dbConn->Param($strSparqlVariable);
+        $this->arTmpVariablePositions[] = $strSparqlVariable;
+
+        return $strDbPlaceholder;
+    }//protected function replacePlaceholdersCb($matches)
+
+
+
+    /**
+    *   Executes the given prepared statments, filling the placeholders
+    *   with the given values.
+    *
+    *   @param array $arDbStatements    Return value of prepareInDb()
+    *   @param array $arVariableValues      Array of (variable name, value) pairs
+    *
+    *   @return array Array of database results as returned by Execute()
+    */
+    public function execute($arDbStatements, $arVariableValues)
+    {
+        $arResults = array();
+        $oldmode = $this->dbConn->SetFetchMode(ADODB_FETCH_ASSOC);
+
+        foreach ($arDbStatements as $arStatement) {
+            list($stmt, $arVariablePositions) = $arStatement;
+            $arVariables = $this->createVariableArray(
+                $arVariablePositions,
+                $arVariableValues
+            );
+            $arResults[] = $this->dbConn->Execute($stmt, $arVariables);
+        }
+
+        $this->dbConn->SetFetchMode($oldmode);
+
+        return $arResults;
+    }//public function execute($arDbStatements, $arVariableValues)
+
+
+
+    /**
+    *   Creates an array full of variables to be passed to the Execute() method
+    *   of the database connection object.
+    *   Uses the variable positions array to get the positions of the variables
+    *   in the result array, and the variable value array to get the actual
+    *   values for the prepared statement.
+    *
+    *   @param array $arVariablePositions   Positions of the variables as returned
+    *                                       by replacePlaceholders().
+    *   @param array $arVariableValues      Array of (variable name, value) pairs
+    *
+    *   @return array Array of variable values
+    */
+    protected function createVariableArray($arVariablePositions, $arVariableValues)
+    {
+        $arVariables = array();
+
+        foreach ($arVariablePositions as $nPos => $strVariable) {
+            if (!isset($arVariableValues[$strVariable])) {
+                throw new Exception('No value for variable "' . $strVariable . '" in prepared statement');
+            }
+
+            $strValue = self::replacePrefix(
+                $arVariableValues[$strVariable],
+                $this->arPrefixes
+            );
+
+            $arVariables[$nPos] = $strValue;
+        }
+
+        return $arVariables;
+    }//protected function createVariableArray($arVariablePositions, $arVariableValues)
+
+
+
+    /**
+    *   Replaces all placeholders with their actual values.
+    */
+    public function replacePlaceholdersWithVariables($strQuery, $arPlaceholders, $arVariableValues)
+    {
+        $this->arTmpPlaceholders   = $arPlaceholders;
+        $this->arTmpVariableValues = $arVariableValues;
+
+        $strQuery = preg_replace_callback(
+            '/@\\$%_PLACEHOLDER_[0-9]+_%\\$@/',
+            array($this, 'replacePlaceholdersWithVariablesCb'),
+            $strQuery
+        );
+
+        return $strQuery;
+    }//public function replacePlaceholdersWithVariables($strQuery, $arPlaceholders, $arVariableValues)
+
+
+
+    /**
+    *   Callback method internally used by
+    *   replacePlaceholdersWithVariables() method.
+    */
+    protected function replacePlaceholdersWithVariablesCb($matches)
+    {
+        $strPlaceholder     = $matches[0];
+        $strSparqlVariable  = array_search(
+            $strPlaceholder,
+            $this->arTmpPlaceholders
+        );
+        return $this->dbConn->qstr(
+            self::replacePrefix(
+                $this->arTmpVariableValues[$strSparqlVariable],
+                $this->arPrefixes
+            )
+        );
+    }//protected function replacePlaceholdersWithVariablesCb($matches)
+
+
+
+    protected static function replacePrefix($strValue, $arPrefixes)
+    {
+        //replace prefixes?
+        if (count($arParts = explode(':', $strValue, 2)) == 2) {
+            if (isset($arPrefixes[$arParts[0]])) {
+                $strValue = $arPrefixes[$arParts[0]] . $arParts[1];
+            }
+        }
+        return $strValue;
+    }//protected static function replacePrefix($strValue, $arPrefixes)
+
+}//class SparqlEngineDb_Preparator
+
+?>
Index: /Dev/trunk/rdfapi/sparql/SparqlEngineDb/PreparedStatement.php
===================================================================
--- /Dev/trunk/rdfapi/sparql/SparqlEngineDb/PreparedStatement.php	(revision 12)
+++ /Dev/trunk/rdfapi/sparql/SparqlEngineDb/PreparedStatement.php	(revision 12)
@@ -0,0 +1,38 @@
+<?php
+require_once RDFAPI_INCLUDE_DIR . 'sparql/SparqlEngine/PreparedStatement.php';;
+
+/**
+*   A prepared statement that can be execute()d later multiple
+*   times with different variable values.
+*
+*   @author Christian Weiske <cweiske@cweiske.de>
+*   @license http://www.gnu.org/licenses/lgpl.html LGPL
+*
+*   @package sparql
+*/
+class SparqlEngineDb_PreparedStatement extends SparqlEngine_PreparedStatement
+{
+    protected $sparqlEngine = null;
+
+
+    public function __construct(SparqlEngineDb $sparqlEngine)
+    {
+        $this->sparqlEngine = $sparqlEngine;
+    }//public function __construct(SparqlEngineDb $sparqlEngine)
+
+
+
+    /**
+    *   Execute the prepared statement and returns the result.
+    *
+    *   @param array $arVariables   Array of sparql query variables => values
+    *   @param string $resultform   Which result form you need
+    *   @return mixed   Anything a sparql query can return
+    */
+    public function execute($arVariables, $resultform = false)
+    {
+        return $this->sparqlEngine->execute($arVariables, $resultform);
+    }//public function execute($arVariables, $resultform)
+
+}//class SparqlEngineDb_PreparedStatement extends SparqlEngine_PreparedStatement
+?>
Index: /Dev/trunk/rdfapi/sparql/SparqlEngineDb/QuerySimplifier.php
===================================================================
--- /Dev/trunk/rdfapi/sparql/SparqlEngineDb/QuerySimplifier.php	(revision 12)
+++ /Dev/trunk/rdfapi/sparql/SparqlEngineDb/QuerySimplifier.php	(revision 12)
@@ -0,0 +1,169 @@
+<?php
+
+/**
+*   Simplifies ("flattens") Query objects that have graph
+*   patterns which are subpatterns of other patterns.
+*
+*   Example:
+*      ?g ?h ?i .
+*      {
+*        {?person <some://typ/e> 'asd'}
+*        UNION
+*        {?person3 <some://typ/es2> 'three'}
+*      }
+*    is represented internally as three graph patterns, the latter
+*    two referencing the first to be their pattern (they are subpatternOf).
+*    Now this can be flattened to this which is the same:
+*      {?g ?h ?i . ?person <some://typ/e> 'asd'}
+*      UNION
+*      {?g ?h ?i .?person3 <some://typ/es2> 'three'}
+*
+*   This class does this.
+*
+*   @author Christian Weiske <cweiske@cweiske.de>
+*   @license http://www.gnu.org/licenses/lgpl.html LGPL
+*/
+class SparqlEngineDb_QuerySimplifier
+{
+
+    /**
+    *   Simplify the query by flattening out subqueries.
+    *   Modifies the passed query object directly.
+    */
+    public function simplify(Query $query)
+    {
+        $arPatterns = $query->getResultPart();
+        self::dropEmpty($arPatterns);
+        $arPlan     = $this->createPlan($arPatterns);
+        if (count($arPlan) == 0) {
+            $query->setResultPart($arPatterns);
+            return 0;
+        }
+
+        $this->executePlan($arPatterns, $arPlan);
+        $query->setResultPart($arPatterns);
+    }//public function simplify(Query $query)
+
+
+
+    /**
+    *   Creates a plan what to do.
+    *
+    *   @return array Array of arrays. Key is the parent pattern id,
+    *               value is an array of subpatterns that belong to
+    *               that parental pattern.
+    */
+    protected function createPlan(&$arPatterns)
+    {
+        $arNumbers = $this->getNumbers($arPatterns);
+        if (count($arNumbers) == 0) {
+            return array();
+        }
+
+        $arPlan    = array();
+
+        foreach ($arNumbers as $nId => $nPatternCount) {
+            $nParent = $arPatterns[$nId]->getSubpatternOf();
+            $arPlan[$nParent][$nId] = true;
+        }
+
+        return $arPlan;
+    }//protected function createPlan(&$arPatterns)
+
+
+
+    /**
+    *   Executes the plan
+    *
+    *   @param array $arPatterns  Array of GraphPatterns
+    *   @param array $arPlan      Plan array as returned by createPlan()
+    */
+    protected function executePlan(&$arPatterns, &$arPlan)
+    {
+        foreach ($arPlan as $nParent => $arChildren) {
+            $base        = $arPatterns[$nParent];
+            $grandParent = $base->getSubpatternOf();
+            $nNextId     = $nParent;
+            foreach ($arChildren as $nChild => $null) {
+                $new = clone $base;
+                $new->addTriplePatterns($arPatterns[$nChild]->getTriplePatterns());
+                $new->addConstraints(   $arPatterns[$nChild]->getConstraints());
+                $new->setId($nNextId);
+                if ($nParent != $nNextId) {
+                    $new->setUnion($nParent);
+                }
+                $arPatterns[$nNextId] = $new;
+
+                if ($grandParent !== null) {
+                    //dynamically adjust plan
+                    $arPlan[$grandParent][$nNextId] = true;
+                }
+
+                $nNextId = $nChild;
+            }
+            //last one is not not needed anymore
+            unset($arPatterns[$nNextId]);
+        }
+    }//protected function executePlan(&$arPatterns, &$arPlan)
+
+
+
+    /**
+    *   Returns an array of id-value pairs determining
+    *   which pattern IDs (array id) are deepest nested
+    *   (higher value).
+    *   Array is sorted in reverse order, highest values
+    *   first.
+    *
+    *   @param array $arPatterns    Array with GraphPatterns
+    *   @return array Array with key-value pairs
+    */
+    protected function getNumbers(&$arPatterns)
+    {
+        $arNumbers = array();
+        foreach ($arPatterns as $nId => &$pattern) {
+            $nParent = $pattern->getSubpatternOf();
+            if ($nParent !== null) {
+                $arNumbers[$nId] = $arNumbers[$nParent] + 1;
+            } else {
+                $arNumbers[$nId] = 0;
+            }
+        }
+        //remove the not so interesting ones
+        foreach ($arNumbers as $nId => $nNumber) {
+            if ($nNumber == 0) {
+                unset($arNumbers[$nId]);
+            }
+        }
+
+        arsort($arNumbers);
+
+        return $arNumbers;
+    }//protected function getNumbers(&$arPatterns)
+
+
+
+    /**
+    *   Removes all empty graph patterns from the array.
+    *   Modifies it directly.
+    */
+    protected static function dropEmpty(&$arPatterns)
+    {
+        foreach ($arPatterns as $nId => &$pattern) {
+            if ($pattern->isEmpty()) {
+                unset($arPatterns[$nId]);
+            }
+        }
+
+        foreach ($arPatterns as $nId => &$pattern) {
+            $nParent = $pattern->getSubpatternOf();
+            if (!isset($arPatterns[$nParent])) {
+                $arPatterns[$nId]->setSubpatternOf(null);
+            }
+        }
+        //FIXME: continued indexes?
+    }//protected static function dropEmpty(&$arPatterns)
+
+}//class SparqlEngineDb_QuerySimplifier
+
+?>
Index: /Dev/trunk/rdfapi/sparql/SparqlEngineDb/ResultConverter.php
===================================================================
--- /Dev/trunk/rdfapi/sparql/SparqlEngineDb/ResultConverter.php	(revision 12)
+++ /Dev/trunk/rdfapi/sparql/SparqlEngineDb/ResultConverter.php	(revision 12)
@@ -0,0 +1,115 @@
+<?php
+require_once RDFAPI_INCLUDE_DIR . 'sparql/SparqlEngineDb/ResultRenderer.php';
+
+/**
+*   Converts a database result into a proper
+*   rdf statement triple array
+*
+*   @author Christian Weiske <cweiske@cweiske.de>
+*   @license http://www.gnu.org/licenses/lgpl.html LGPL
+*
+*   @package sparql
+*/
+class SparqlEngineDb_ResultConverter
+{
+    /**
+    *   Determines the correct renderer and calls it.
+    *
+    *   The $resultform may be:
+    *   - false: The default renderer is taken then
+    *   - an object that implements SparqlEngineDb_ResultRenderer interface
+    *   - a string like "HTML" or "XML". The appropriate renderer is used then.
+    *   - a full class name, e.g. SparqlEngineDb_ResultRenderer_XML
+    *
+    *   @param array    $arRecordSets   Array of anything ADOConnection::Execute() can return
+    *   @param SparqlEngineDb $engine   Sparql database engine.
+    *   @param mixed    $resultform     Which format the results shall be in (false or "xml")
+    *
+    *   @return mixed   Most likely an array or a boolean value,
+    *                   or anything else as determined by $resultform
+    */
+    public static function convertFromDbResults($arRecordSets, SparqlEngineDb $engine, $resultform = false)
+    {
+        if (is_object($resultform)) {
+            if ($resultform instanceof SparqlEngineDb_ResultRenderer) {
+                return $resultform->convertFromDbResults(
+                    $arRecordSets,
+                    $engine->getQuery(),
+                    $engine
+                );
+            } else {
+                throw new Exception(
+                    'Result renderer object needs to implement'
+                    . ' SparqlEngineDb_ResultRenderer interface'
+                );
+            }
+        }
+
+        if ($resultform === false) {
+            $resultform = 'Default';
+        } else if ($resultform == 'xml') {
+            //kept for BC reasons
+            $resultform = 'XML';
+        }
+
+        if ($strClass = self::loadClass($resultform)) {
+            $rrObj = new $strClass();
+            if ($rrObj instanceof SparqlEngineDb_ResultRenderer) {
+                return $rrObj->convertFromDbResults(
+                    $arRecordSets,
+                    $engine->getQuery(),
+                    $engine
+                );
+            } else {
+                throw new Exception(
+                    'Result renderer class "' . $strClass . '" needs to implement'
+                    . ' SparqlEngineDb_ResultRenderer interface'
+                );
+            }
+        } else {
+            throw new Exception(
+                'Result renderer class "' . $resultform . '" could not be loaded.'
+            );
+        }
+    }//public static function convertFromDbResults($arRecordSets, SparqlEngineDb $engine, $resultform = false)
+
+
+
+    /**
+    *   Tries to load a given class if it doesn't exist,
+    *   and returns true if the class can be used.
+    *
+    *   @param string $strClass Classname
+    *   @return mixed Class name if the class is loaded and can be used, false if not.
+    */
+    protected static function loadClass($strClass)
+    {
+        if (class_exists($strClass, false)) {
+            return $strClass;
+        }
+
+        //RAP style, shortcut notation
+        $strFile = 'SparqlEngineDb/ResultRenderer/' . $strClass . '.php';
+        @include_once RDFAPI_INCLUDE_DIR . 'sparql/' . $strFile;
+        if (class_exists('SparqlEngineDb_ResultRenderer_' . $strClass, false)) {
+            return 'SparqlEngineDb_ResultRenderer_' . $strClass;
+        }
+
+        //RAP style
+        $strFile = str_replace('_', '/', $strClass) . '.php';
+        @include_once RDFAPI_INCLUDE_DIR . 'sparql/' . $strFile;
+        if (class_exists($strClass, false)) {
+            return $strClass;
+        }
+
+        //PEAR style
+        @include_once $strFile;
+        if (class_exists($strClass, false)) {
+            return $strClass;
+        }
+
+        return false;
+    }//protected static function loadClass($strClass)
+
+}//class SparqlEngineDb_ResultConverter
+?>
Index: /Dev/trunk/rdfapi/sparql/SparqlEngineDb/ResultRenderer.php
===================================================================
--- /Dev/trunk/rdfapi/sparql/SparqlEngineDb/ResultRenderer.php	(revision 12)
+++ /Dev/trunk/rdfapi/sparql/SparqlEngineDb/ResultRenderer.php	(revision 12)
@@ -0,0 +1,29 @@
+<?php
+
+/**
+*   Result renderer interface that any result renderer needs to implement.
+*   A result renderer converts the raw database results into a
+*   - for the user - usable result format, e.g. php arrays, xml, json and
+*   so on.
+*
+*   @author Christian Weiske <cweiske@cweiske.de>
+*   @license http://www.gnu.org/licenses/lgpl.html LGPL
+*
+*   @package sparql
+*/
+interface SparqlEngineDb_ResultRenderer
+{
+    /**
+    *   Converts the database results into the desired output format
+    *   and returns the result.
+    *
+    *   @param array $arRecordSets  Array of (possibly several) SQL query results.
+    *   @param Query $query     SPARQL query object
+    *   @param SparqlEngineDb $engine   Sparql Engine to query the database
+    *   @return mixed   The result as rendered by the result renderers.
+    */
+    public function convertFromDbResults($arRecordSets, Query $query, SparqlEngineDb $engine);
+
+}//interface SparqlEngineDb_ResultRenderer
+
+?>
Index: /Dev/trunk/rdfapi/sparql/SparqlEngineDb/ResultRenderer/Default.php
===================================================================
--- /Dev/trunk/rdfapi/sparql/SparqlEngineDb/ResultRenderer/Default.php	(revision 12)
+++ /Dev/trunk/rdfapi/sparql/SparqlEngineDb/ResultRenderer/Default.php	(revision 12)
@@ -0,0 +1,339 @@
+<?php
+require_once RDFAPI_INCLUDE_DIR . 'sparql/SparqlEngineDb/ResultRenderer.php';
+
+/**
+*   Default RAP result renderer.
+*
+*   @author Christian Weiske <cweiske@cweiske.de>
+*   @license http://www.gnu.org/licenses/lgpl.html LGPL
+*
+*   @package sparql
+*/
+class SparqlEngineDb_ResultRenderer_Default implements SparqlEngineDb_ResultRenderer
+{
+
+    /**
+    *   Defines the methods needed to create the types
+    *   in $arVarAssignments.
+    *   Key is the type (e.g. "s" for subject), and
+    *   value the method's name.
+    *
+    *   @see $arVarAssignments
+    *
+    *   @var array
+    */
+    protected $arCreationMethods = array(
+        's' => 'createSubjectFromDbRecordSetPart',
+        'p' => 'createPredicateFromDbRecordSetPart',
+        'o' => 'createObjectFromDbRecordSetPart'
+    );
+
+
+
+    /**
+    *   Converts the database results into the desired output format
+    *   and returns the result.
+    *
+    *   @param array $arRecordSets  Array of (possibly several) SQL query results.
+    *   @param Query $query     SPARQL query object
+    *   @param SparqlEngineDb $engine   Sparql Engine to query the database
+    *   @return mixed   The result as rendered by the result renderers.
+    */
+    public function convertFromDbResults($arRecordSets, Query $query, SparqlEngineDb $engine)
+    {
+        $this->query    = $query;
+        $this->engine   = $engine;
+        $this->sg       = $engine->getSqlGenerator();
+
+        $strResultForm = $this->query->getResultForm();
+        switch ($strResultForm) {
+            case 'construct':
+            case 'select':
+            case 'select distinct':
+                $arResult = $this->getVariableArrayFromRecordSets($arRecordSets, $strResultForm);
+
+                //some result forms need more modification
+                switch ($strResultForm) {
+                    case 'construct';
+                        $arResult = $this->constructGraph(
+                            $arResult,
+                            $this->query->getConstructPattern()
+                        );
+                        break;
+                    case 'describe';
+                        $arResult = $this->describeGraph($arResult);
+                        break;
+                }
+
+                return $arResult;
+                break;
+
+            case 'count':
+            case 'ask':
+                if (count($arRecordSets) > 1) {
+                    throw new Exception(
+                        'More than one result set for a '
+                        . $strResultForm . ' query!'
+                    );
+                }
+
+                $nCount = 0;
+                $dbRecordSet = reset($arRecordSets);
+                foreach ($dbRecordSet as $row) {
+                    $nCount += intval($row['count']);
+                    break;
+                }
+
+                if ($strResultForm == 'ask') {
+                    return $nCount > 0;
+                } else {
+                    return $nCount;
+                }
+                break;
+
+            case 'describe':
+            default:
+                throw new Exception('Unsupported result form: ' . $strResultForm);
+        }
+
+    }//public function convertFromDbResults($arRecordSets, Query $query, SparqlEngineDb $engine)
+
+
+
+
+    protected function getVariableArrayFromRecordSets($arRecordSets, $strResultForm)
+    {
+        $arResult = array();
+        foreach ($arRecordSets as $dbRecordSet) {
+            $arResult = array_merge(
+                $arResult,
+                $this->getVariableArrayFromRecordSet($dbRecordSet, $strResultForm)
+            );
+        }
+        return $arResult;
+    }//protected function getVariableArrayFromRecordSets($arRecordSets, $strResultForm)
+
+
+
+    /**
+    *   Converts a ADORecordSet object into an array of "rows" that
+    *   are subarrays of variable => value pairs.
+    *
+    *   @param ADORecordSet $dbRecordSet    Anything ADOConnection::Execute() can return
+    *   @return array
+    */
+    protected function getVariableArrayFromRecordSet(ADORecordSet $dbRecordSet, $strResultForm)
+    {
+        $arResult       = array();
+        switch ($strResultForm) {
+            case 'construct':
+                $arResultVars = $this->query->getConstructPatternVariables();
+                break;
+            default:
+                $arResultVars = $this->query->getResultVars();
+                break;
+        }
+
+        if (in_array('*', $arResultVars)) {
+            $arResultVars   = array_keys($this->sg->arVarAssignments);
+        }
+
+        //work around bug in adodb:
+        // ADORecordSet_empty does not implement php5 iterators
+        if ($dbRecordSet->RowCount() <= 0) {
+            return array();
+        }
+
+        foreach ($dbRecordSet as $row) {
+            $arResultRow = array();
+            foreach ($arResultVars as $strVar) {
+                $strVarName = (string)$strVar;
+                if (!isset($this->sg->arVarAssignments[$strVarName])) {
+                    //variable is in select, but not in result (test: q-select-2)
+                    $arResultRow[$strVarName] = '';
+                } else {
+                    $arVarSettings  = $this->sg->arVarAssignments[$strVarName];
+                    $strMethod      = $this->arCreationMethods[$arVarSettings[1]];
+                    $arResultRow[$strVarName] = $this->$strMethod($dbRecordSet, $arVarSettings[0], $strVar);
+                }
+            }
+            $arResult[] = $arResultRow;
+        }
+        return $arResult;
+    }//function getVariableArrayFromRecordSet(ADORecordSet $dbRecordSet)
+
+
+
+    /**
+    *   Creates an RDF Statement object for one of the variables
+    *   contained in the given $dbRecordSet object.
+    *
+    *   @see convertFromDbResult() to understand $strVarBase necessity
+    *
+    *   @param ADORecordSet $dbRecordSet    Record set returned from ADOConnection::Execute()
+    *   @param string       $strVarBase     Prefix of the columns the recordset fields have.
+    *
+    *   @return Statement   RDF statement object
+    */
+    protected function createStatementFromDbRecordSetPart(ADORecordSet $dbRecordSet, $strVarBase)
+    {
+        return new Statement(
+            $this->createSubjectFromDbRecordSetPart  ($dbRecordSet, $strVarBase),
+            $this->createPredicateFromDbRecordSetPart($dbRecordSet, $strVarBase),
+            $this->createObjectFromDbRecordSetPart   ($dbRecordSet, $strVarBase)
+        );
+    }//protected function createStatementFromDbRecordSetPart(ADORecordSet $dbRecordSet, $strVarBase)
+
+
+
+    /**
+    *   Creates an RDF subject object
+    *   contained in the given $dbRecordSet object.
+    *
+    *   @see convertFromDbResult() to understand $strVarBase necessity
+    *
+    *   @param ADORecordSet $dbRecordSet    Record set returned from ADOConnection::Execute()
+    *   @param string       $strVarBase     Prefix of the columns the recordset fields have.
+    *
+    *   @return Resource   RDF triple subject resource object
+    */
+    protected function createSubjectFromDbRecordSetPart(ADORecordSet $dbRecordSet, $strVarBase, $strVar)
+    {
+        $strVarName = (string)$strVar;
+        if ($dbRecordSet->fields[$strVarBase . '.' . $this->sg->arVarAssignments[$strVarName]['sql_value']] === null) {
+            //FIXME: should be NULL, but doesn't pass test
+            return '';
+        }
+
+        if ($dbRecordSet->fields[$strVarBase . '.' . $this->sg->arVarAssignments[$strVarName]['sql_is']] == 'r'
+            //null should be predicate which is always a resource
+         || $dbRecordSet->fields[$strVarBase . '.' . $this->sg->arVarAssignments[$strVarName]['sql_is']] === null
+        ) {
+            $subject    = new Resource ($dbRecordSet->fields[$strVarBase . '.' . $this->sg->arVarAssignments[$strVarName]['sql_value']]);
+        } else {
+            $subject    = new BlankNode($dbRecordSet->fields[$strVarBase . '.' . $this->sg->arVarAssignments[$strVarName]['sql_value']]);
+        }
+        return $subject;
+    }//protected function createSubjectFromDbRecordSetPart(ADORecordSet $dbRecordSet, $strVarBase, $strVarName)
+
+
+
+    /**
+    *   Creates an RDF predicate object
+    *   contained in the given $dbRecordSet object.
+    *
+    *   @see convertFromDbResult() to understand $strVarBase necessity
+    *
+    *   @param ADORecordSet $dbRecordSet    Record set returned from ADOConnection::Execute()
+    *   @param string       $strVarBase     Prefix of the columns the recordset fields have.
+    *
+    *   @return Resource   RDF triple predicate resource object
+    */
+    protected function createPredicateFromDbRecordSetPart(ADORecordSet $dbRecordSet, $strVarBase, $strVar)
+    {
+        $strVarName = (string)$strVar;
+        if ($dbRecordSet->fields[$strVarBase . '.' . $this->sg->arVarAssignments[$strVarName]['sql_value']] === null) {
+            //FIXME: should be NULL, but doesn't pass test
+            return '';
+        }
+        $predicate      = new Resource ($dbRecordSet->fields[$strVarBase . '.' . $this->sg->arVarAssignments[$strVarName]['sql_value']]);
+        return $predicate;
+    }//protected function createPredicateFromDbRecordSetPart(ADORecordSet $dbRecordSet, $strVarBase, $strVarName)
+
+
+
+    /**
+    *   Creates an RDF object object
+    *   contained in the given $dbRecordSet object.
+    *
+    *   @see convertFromDbResult() to understand $strVarBase necessity
+    *
+    *   @param ADORecordSet $dbRecordSet    Record set returned from ADOConnection::Execute()
+    *   @param string       $strVarBase     Prefix of the columns the recordset fields have.
+    *
+    *   @return Resource   RDF triple object resource object
+    */
+    protected function createObjectFromDbRecordSetPart(ADORecordSet $dbRecordSet, $strVarBase, $strVar)
+    {
+        $strVarName = (string)$strVar;
+        if ($dbRecordSet->fields[$strVarBase . '.' . $this->sg->arVarAssignments[$strVarName]['sql_value']] === null) {
+            //FIXME: should be NULL, but doesn't pass test
+            return '';
+        }
+        switch ($dbRecordSet->fields[$strVarBase . '.' . $this->sg->arVarAssignments[$strVarName]['sql_is']]) {
+            case 'r':
+                $object = new Resource ($dbRecordSet->fields[$strVarBase . '.' . $this->sg->arVarAssignments[$strVarName]['sql_value']]);
+                break;
+            case 'b':
+                $object = new BlankNode($dbRecordSet->fields[$strVarBase . '.' . $this->sg->arVarAssignments[$strVarName]['sql_value']]);
+                break;
+            default:
+                $object = new Literal(
+                    $dbRecordSet->fields[$strVarBase . '.' . $this->sg->arVarAssignments[$strVarName]['sql_value']],
+                    $dbRecordSet->fields[$strVarBase . '.' . $this->sg->arVarAssignments[$strVarName]['sql_lang']]
+                );
+                if ($dbRecordSet->fields[$strVarBase . '.' . $this->sg->arVarAssignments[$strVarName]['sql_type']]) {
+                    $object->setDatatype($dbRecordSet->fields[$strVarBase . '.' . $this->sg->arVarAssignments[$strVarName]['sql_type']]);
+                }
+        }
+        return $object;
+    }//protected function createObjectFromDbRecordSetPart(ADORecordSet $dbRecordSet, $strVarBase, $strVarName)
+
+
+
+    /**
+    * Constructs a result graph.
+    *
+    * @param  array         $arVartable       A table containing the result vars and their bindings
+    * @param  GraphPattern  $constructPattern The CONSTRUCT pattern
+    * @return MemModel      The result graph which matches the CONSTRUCT pattern
+    */
+    protected function constructGraph($arVartable, $constructPattern)
+    {
+        $resultGraph = new MemModel();
+
+        if (!$arVartable) {
+            return $resultGraph;
+        }
+
+        $tp = $constructPattern->getTriplePatterns();
+
+        $bnode = 0;
+        foreach ($arVartable as $value) {
+            foreach ($tp as $triple) {
+                $sub  = $triple->getSubject();
+                $pred = $triple->getPredicate();
+                $obj  = $triple->getObject();
+
+                if (is_string($sub)  && $sub{1} == '_') {
+                    $sub  = new BlankNode("_bN".$bnode);
+                }
+                if (is_string($pred) && $pred{1} == '_') {
+                    $pred = new BlankNode("_bN".$bnode);
+                }
+                if (is_string($obj)  && $obj{1} == '_') {
+                    $obj  = new BlankNode("_bN".$bnode);
+                }
+
+
+                if (is_string($sub)) {
+                    $sub  = $value[$sub];
+                }
+                if (is_string($pred)) {
+                    $pred = $value[$pred];
+                }
+                if (is_string($obj)) {
+                    $obj  = $value[$obj];
+                }
+
+                if ($sub !== "" && $pred !== "" && $obj !== "") {
+                    $resultGraph->add(new Statement($sub,$pred,$obj));
+                }
+            }
+            $bnode++;
+        }
+        return $resultGraph;
+    }//protected function constructGraph($arVartable, $constructPattern)
+
+}//class SparqlEngineDb_ResultRenderer_Default implements SparqlEngineDb_ResultRenderer
+?>
Index: /Dev/trunk/rdfapi/sparql/SparqlEngineDb/ResultRenderer/HTML.php
===================================================================
--- /Dev/trunk/rdfapi/sparql/SparqlEngineDb/ResultRenderer/HTML.php	(revision 12)
+++ /Dev/trunk/rdfapi/sparql/SparqlEngineDb/ResultRenderer/HTML.php	(revision 12)
@@ -0,0 +1,297 @@
+<?php
+require_once RDFAPI_INCLUDE_DIR . 'sparql/SparqlEngineDb/ResultRenderer.php';
+
+/**
+*   Sparql DB HTML result renderer.
+*
+*   @author Christian Weiske <cweiske@cweiske.de>
+*   @license http://www.gnu.org/licenses/lgpl.html LGPL
+*
+*   @package sparql
+*/
+class SparqlEngineDb_ResultRenderer_HTML implements SparqlEngineDb_ResultRenderer
+{
+    /**
+    *   If the result HTML should be wrapped in a div
+    *   @var boolean
+    */
+    protected $bWrap = true;
+
+    /**
+    *   Defines the methods needed to create the types
+    *   in $arVarAssignments.
+    *   Key is the type (e.g. "s" for subject), and
+    *   value the method's name.
+    *
+    *   @see $arVarAssignments
+    *
+    *   @var array
+    */
+    protected $arCreationMethods = array(
+        's' => 'createSubjectFromDbRecordSetPart',
+        'p' => 'createPredicateFromDbRecordSetPart',
+        'o' => 'createObjectFromDbRecordSetPart'
+    );
+
+
+
+    /**
+    *   Converts the database results into nice HTML.
+    *
+    *   @param array $arRecordSets  Array of (possibly several) SQL query results.
+    *   @param Query $query     SPARQL query object
+    *   @param SparqlEngineDb $engine   Sparql Engine to query the database
+    *   @return mixed   HTML code
+    */
+    public function convertFromDbResults($arRecordSets, Query $query, SparqlEngineDb $engine)
+    {
+        $this->query = $query;
+        $this->sg    = $engine->getSqlGenerator();
+        $strCode     = '';
+
+        $strResultForm = $query->getResultForm();
+        switch ($strResultForm) {
+            case 'select':
+            case 'select distinct':
+                $strCode = $this->createTableFromRecords($arRecordSets);
+                break;
+
+            case 'construct':
+            case 'describe':
+                throw new Exception(
+                    'Construct and describe are currently not supported by the'
+                    . ' HTML renderer'
+                );
+
+            case 'count':
+            case 'ask':
+                if (count($arRecordSets) > 1) {
+                    throw new Exception(
+                        'More than one result set for a '
+                        . $strResultForm . ' query!'
+                    );
+                }
+
+                $nCount = 0;
+                $dbRecordSet = reset($arRecordSets);
+                foreach ($dbRecordSet as $row) {
+                    $nCount += intval($row['count']);
+                    break;
+                }
+
+                if ($strResultForm == 'ask') {
+                    $strCode = 'There were results.';
+                } else {
+                    $strCode = 'There are ' . $nCount . ' results.';
+                }
+                break;
+
+            default:
+                throw new Exception('Unsupported result form: ' . $strResultForm);
+        }
+
+        return $this->wrapCode($strCode);
+    }//public function convertFromDbResults($arRecordSets, Query $query, SparqlEngineDb $engine)
+
+
+
+    protected function wrapCode($strCode)
+    {
+        if (!$this->bWrap) {
+            return $strCode;
+        }
+
+        return
+            '<div class="SparqlEngineDb_ResultRenderer_HTML_result">' . "\n"
+            . $strCode . "\n"
+            . "</div>\n";
+    }//protected function wrapCode($strCode)
+
+
+
+    protected function createTableFromRecords($arRecordSets)
+    {
+        $arResultVars = $this->query->getResultVars();
+
+        if (in_array('*', $arResultVars)) {
+            $arResultVars   = array_keys($this->sg->arVarAssignments);
+        }
+
+        $arResult = array();
+        foreach ($arRecordSets as $dbRecordSet) {
+            //work around bug in adodb:
+            // ADORecordSet_empty does not implement php5 iterators
+            if ($dbRecordSet->RowCount() <= 0) {
+                return array();
+            }
+
+            foreach ($dbRecordSet as $row) {
+                $arResultRow = array();
+                foreach ($arResultVars as $strVar) {
+                    $strVarName = (string)$strVar;
+                    if (!isset($this->sg->arVarAssignments[$strVarName])) {
+                        //variable is in select, but not in result (test: q-select-2)
+                        $arResultRow[$strVarName] = '';
+                    } else {
+                        $arVarSettings  = $this->sg->arVarAssignments[$strVarName];
+                        $strMethod      = $this->arCreationMethods[$arVarSettings[1]];
+                        list($strCode, $strColor) = $this->$strMethod($dbRecordSet, $arVarSettings[0], $strVar);
+                        $arResultRow[$strVarName] = '<td style="background-color: '
+                            . $strColor . '">' . $strCode . '</td>';
+                    }
+                }
+                $arResult[] = $arResultRow;
+            }
+        }
+
+        //I always wanted to to this :)
+        return
+            "<table border='1'>\n"
+            . " <caption>SPARQL result with " . count($arResult) . " rows</caption>\n"
+            . " <thead><th>"
+                . implode('</th><th>', array_keys(reset($arResult)))
+            . "</th></thead>\n"
+            . " <tbody>\n  <tr>"
+            . implode(
+                "</tr>\n  <tr>",
+                array_map(
+                    create_function(
+                        '$ar',
+                        'return implode("", $ar);'
+                    ),
+                    $arResult
+                )
+              )
+            . "</tr>\n </tbody>\n"
+            . "</table>\n";
+    }//protected function createTableFromRecords($arRecordSets)
+
+
+
+    /**
+    *   Creates an RDF subject object
+    *   contained in the given $dbRecordSet object.
+    *
+    *   @see convertFromDbResult() to understand $strVarBase necessity
+    *
+    *   @param ADORecordSet $dbRecordSet    Record set returned from ADOConnection::Execute()
+    *   @param string       $strVarBase     Prefix of the columns the recordset fields have.
+    *
+    *   @return string HTML code
+    */
+    protected function createSubjectFromDbRecordSetPart(ADORecordSet $dbRecordSet, $strVarBase, $strVar)
+    {
+        $strVarName = (string)$strVar;
+        if ($dbRecordSet->fields[$strVarBase . '.' . $this->sg->arVarAssignments[$strVarName]['sql_value']] === null) {
+            return $this->getHtmlNull();
+        }
+        if ($dbRecordSet->fields[$strVarBase . '.' . $this->sg->arVarAssignments[$strVarName]['sql_is']] == 'r'
+            //null should be predicate which is always a resource
+         || $dbRecordSet->fields[$strVarBase . '.' . $this->sg->arVarAssignments[$strVarName]['sql_is']] === null
+        ) {
+            return $this->getHtmlResource($dbRecordSet->fields[$strVarBase . '.' . $this->sg->arVarAssignments[$strVarName]['sql_value']]);
+        } else {
+            return $this->getHtmlBlank($dbRecordSet->fields[$strVarBase . '.' . $this->sg->arVarAssignments[$strVarName]['sql_value']]);
+        }
+    }//protected function createSubjectFromDbRecordSetPart(ADORecordSet $dbRecordSet, $strVarBase, $strVar)
+
+
+
+    /**
+    *   Creates an RDF predicate object
+    *   contained in the given $dbRecordSet object.
+    *
+    *   @see convertFromDbResult() to understand $strVarBase necessity
+    *
+    *   @param ADORecordSet $dbRecordSet    Record set returned from ADOConnection::Execute()
+    *   @param string       $strVarBase     Prefix of the columns the recordset fields have.
+    *
+    *   @return string HTML code
+    */
+    protected function createPredicateFromDbRecordSetPart(ADORecordSet $dbRecordSet, $strVarBase, $strVar)
+    {
+        $strVarName = (string)$strVar;
+        if ($dbRecordSet->fields[$strVarBase .  '.' . $this->sg->arVarAssignments[$strVarName]['sql_value']] === null) {
+            return $this->getHtmlNull();
+        }
+
+        return $this->getHtmlResource($dbRecordSet->fields[$strVarBase .  '.' . $this->sg->arVarAssignments[$strVarName]['sql_value']]);
+    }//protected function createPredicateFromDbRecordSetPart(ADORecordSet $dbRecordSet, $strVarBase, $strVar)
+
+
+
+    /**
+    *   Creates an RDF object object
+    *   contained in the given $dbRecordSet object.
+    *
+    *   @see convertFromDbResult() to understand $strVarBase necessity
+    *
+    *   @param ADORecordSet $dbRecordSet    Record set returned from ADOConnection::Execute()
+    *   @param string       $strVarBase     Prefix of the columns the recordset fields have.
+    *
+    *   @return string HTML code
+    */
+    protected function createObjectFromDbRecordSetPart(ADORecordSet $dbRecordSet, $strVarBase, $strVar)
+    {
+        $strVarName = (string)$strVar;
+        if ($dbRecordSet->fields[$strVarBase . '.' . $this->sg->arVarAssignments[$strVarName]['sql_value']] === null) {
+            return $this->getHtmlNull();
+        }
+        switch ($dbRecordSet->fields[$strVarBase . '.' . $this->sg->arVarAssignments[$strVarName]['sql_is']]) {
+            case 'r':
+                return $this->getHtmlResource($dbRecordSet->fields[$strVarBase . '.' . $this->sg->arVarAssignments[$strVarName]['sql_value']]);
+                break;
+            case 'b':
+                return $this->getHtmlBlank($dbRecordSet->fields[$strVarBase . '.' . $this->sg->arVarAssignments[$strVarName]['sql_value']]);
+                break;
+            default:
+                return $this->getHtmlLiteral(
+                    $dbRecordSet->fields[$strVarBase . '.' . $this->sg->arVarAssignments[$strVarName]['sql_value']],
+                    $dbRecordSet->fields[$strVarBase . '.' . $this->sg->arVarAssignments[$strVarName]['sql_lang']],
+                    $dbRecordSet->fields[$strVarBase . '.' . $this->sg->arVarAssignments[$strVarName]['sql_type']]
+                );
+        }
+    }//protected function createObjectFromDbRecordSetPart(ADORecordSet $dbRecordSet, $strVarBase, $strVar)
+
+
+
+    protected function getHtmlNull()
+    {
+        return array('<pre>NULL</pre>', '#FFF');
+    }//protected function getHtmlNull()
+
+
+
+    protected function getHtmlBlank($value)
+    {
+        return array('<i>Blank node</i>', HTML_TABLE_BNODE_COLOR);
+    }//protected function getHtmlBlank($value)
+
+
+
+    protected function getHtmlResource($value)
+    {
+        return array(
+            htmlspecialchars($value),
+            HTML_TABLE_RESOURCE_COLOR
+        );
+    }//protected function getHtmlResource($value)
+
+
+
+    protected function getHtmlLiteral($value, $language, $datatype)
+    {
+        $strCode = htmlspecialchars($value);
+        if ($language) {
+            $strCode . ' <i>xml:lang</i>=' . $language;
+        }
+        if ($datatype) {
+            $strCode . ' <i>rdf:type</i>=' . $datatype;
+        }
+        return array($strCode, HTML_TABLE_LITERAL_COLOR);
+    }//protected function getHtmlLiteral($value, $language, $datatype)
+
+
+}//class SparqlEngineDb_ResultRenderer_HTML implements SparqlEngineDb_ResultRenderer
+
+?>
Index: /Dev/trunk/rdfapi/sparql/SparqlEngineDb/ResultRenderer/JSON.php
===================================================================
--- /Dev/trunk/rdfapi/sparql/SparqlEngineDb/ResultRenderer/JSON.php	(revision 12)
+++ /Dev/trunk/rdfapi/sparql/SparqlEngineDb/ResultRenderer/JSON.php	(revision 12)
@@ -0,0 +1,174 @@
+<?php
+require_once RDFAPI_INCLUDE_DIR . 'sparql/SparqlEngineDb/ResultRenderer.php';
+
+/**
+*   Sparql DB JSON Renderer. Roughly follows http://www.w3.org/2001/sw/DataAccess/json-sparql/;
+*
+*   @author Christoph Rieß
+*   @license http://www.gnu.org/licenses/lgpl.html LGPL
+*
+*   @package sparql
+*/
+class SparqlEngineDb_ResultRenderer_JSON implements SparqlEngineDb_ResultRenderer
+{
+
+    /**
+    *   Converts the database results into JSON Format
+    *
+    *   @param array $arRecordSets  Array of (possibly several) SQL query results.
+    *   @param Query $query     SPARQL query object
+    *   @param SparqlEngineDb $engine   Sparql Engine to query the database
+    *   @return mixed   HTML code
+    */
+    public function convertFromDbResults($arRecordSets, Query $query, SparqlEngineDb $engine) {
+    	
+        $this->query = $query;
+        $this->sg    = $engine->getSqlGenerator();
+        $strResultForm = $query->getResultForm();
+        
+        foreach ($this->getResultVars() as $var)
+        	$ResultVarsTemp[] = substr($var,1);
+        
+        switch ($strResultForm) {
+            case 'select':
+            case 'select distinct':
+                $results = $this->createFromRecords($arRecordSets, $strResultForm);
+				$strCode = json_encode(array(
+				'head' => array('vars'=>$ResultVarsTemp),
+				'results'=>array('bindings'=>$results))
+				);
+				//$strCode = str_replace(',{',','.PHP_EOL.'{',$strCode);
+                break;
+			case 'construct':
+            case 'describe':
+                throw new Exception(
+                    'Construct and describe are not supported by the'
+                    . ' JSON renderer'
+                );
+
+            case 'count':
+            case 'ask':
+                if (count($arRecordSets) > 1) {
+                    throw new Exception(
+                        'More than one result set for a '
+                        . $strResultForm . ' query not supported by JSON Renderer'
+                    );
+                }
+
+                $nCount = 0;
+                $dbRecordSet = reset($arRecordSets);
+                foreach ($dbRecordSet as $row) {
+                    $nCount += intval($row['count']);
+                    break;
+                }
+
+                if ($strResultForm == 'ask') {
+                    $strcode = json_encode(array('boolean' => ($nCount > 0)));
+                } else {
+                    $strcode = json_encode(array('int' => $nCount ));
+                }
+                break;
+            default:
+            	throw new Exception('Error');
+        }
+        
+        return $strCode;
+        
+
+    }
+    /**
+     * Method to create from record with specific resultform (not used yet)
+     *
+     * @param array $arRecordSets  Array of (possibly several) SQL query results.
+     * @param unknown_type $strResultForm
+     * @return array ready for json conversion
+     */
+	protected function createFromRecords($arRecordSets, $strResultForm) {
+		
+		$arVarAssignments = $this->sg->arVarAssignments;
+		$code = '';
+		$arResultVars = $this ->getResultVars();
+		$results = array();
+		foreach ($arRecordSets[0] as $value) {
+			$node = array();
+			foreach ($arResultVars as $ResultVar) {
+				$nodeType = $value[$arVarAssignments[$ResultVar][0].'.'.$arVarAssignments[$ResultVar]['sql_is']];
+				if ($nodeType == 'r') {
+					$node[substr($ResultVar,1)] = array('type'=> 'uri','value'=>$value[$arVarAssignments[$ResultVar][0].'.'.$arVarAssignments[$ResultVar]['sql_value']]);
+					
+				}
+				
+				if ($value[$arVarAssignments[$ResultVar][0].'.'.$arVarAssignments[$ResultVar]['sql_is']] == 'l') {
+					$literalType = $value[$arVarAssignments[$ResultVar][0] . 
+						'.' . $arVarAssignments[$ResultVar]['sql_type']];
+					$literalLang = $value[$arVarAssignments[$ResultVar][0] . 
+						'.' . $arVarAssignments[$ResultVar]['sql_lang']];
+					$literalValue = $value[$arVarAssignments[$ResultVar][0] . 
+						'.' . $arVarAssignments[$ResultVar]['sql_value']];
+					$node[substr($ResultVar,1)] = $this->getLiteral($literalValue,$literalLang,$literalType);
+				}
+				
+				if ($nodeType === 'b') {
+					$literalValue = $value[$arVarAssignments[$ResultVar][0].'.'.$arVarAssignments[$ResultVar]['sql_value']];
+					$node[substr($ResultVar,1)] = array ('type'=>'bnode' ,'value'=>$value[$arVarAssignments[$ResultVar][0].'.'.$arVarAssignments[$ResultVar]['sql_value']]);
+				}
+			}
+			$results[]=$node;
+			
+			
+		}
+		return $results;
+
+	}
+	
+	/**
+	 * COnverting Literals to array ready for json
+	 *
+	 * @param unknown_type $value
+	 * @param unknown_type $lang
+	 * @param unknown_type $type
+	 * @return unknown
+	 */
+	private function getLiteral($value, $lang , $type) {
+		
+		$ret = array();
+		
+		$type = 'literal';
+		
+		if ($value != 'literal') {
+			$ret['value'] = $value;
+		}
+		
+		if ($lang != '') {
+			$ret['lang'] = $lang;
+		}
+		
+		if ($type != '') {
+			$ret['type'] = $type; 
+		}
+		
+		return $ret;
+	}
+	
+	/**
+	 * Giving array of used Vars also resolves the all-quantifier *
+	 *
+	 * @return array of vars as strings
+	 */
+	protected function getResultVars() {
+		$arResultVars = $this->query->getResultVars();
+		if (in_array('*', $arResultVars)) {
+			$arResultVars   = array_keys($this->sg->arVarAssignments);
+		} else {
+			$arResultVars = array();
+			foreach ($this->query->getResultVars() as $Var) {
+				$arResultVars[] = (string) $Var;
+			}
+		}
+		
+		return $arResultVars;
+	}
+
+}
+
+?>
Index: /Dev/trunk/rdfapi/sparql/SparqlEngineDb/ResultRenderer/PlainText.php
===================================================================
--- /Dev/trunk/rdfapi/sparql/SparqlEngineDb/ResultRenderer/PlainText.php	(revision 12)
+++ /Dev/trunk/rdfapi/sparql/SparqlEngineDb/ResultRenderer/PlainText.php	(revision 12)
@@ -0,0 +1,363 @@
+<?php
+require_once RDFAPI_INCLUDE_DIR . 'sparql/SparqlEngineDb/ResultRenderer.php';
+
+/**
+*   Result renderer that creates a text array
+*
+*   @author Christian Weiske <cweiske@cweiske.de>
+*   @license http://www.gnu.org/licenses/lgpl.html LGPL
+*
+*   @package sparql
+*/
+class SparqlEngineDb_ResultRenderer_PlainText implements SparqlEngineDb_ResultRenderer
+{
+
+    /**
+    *   Defines the methods needed to create the types
+    *   in $arVarAssignments.
+    *   Key is the type (e.g. "s" for subject), and
+    *   value the method's name.
+    *
+    *   @see $arVarAssignments
+    *
+    *   @var array
+    */
+    protected $arCreationMethods = array(
+        's' => 'createSubjectFromDbRecordSetPart',
+        'p' => 'createPredicateFromDbRecordSetPart',
+        'o' => 'createObjectFromDbRecordSetPart'
+    );
+
+
+
+    /**
+    *   Converts the database results into the desired output format
+    *   and returns the result.
+    *
+    *   @param array $arRecordSets  Array of (possibly several) SQL query results.
+    *   @param Query $query     SPARQL query object
+    *   @param SparqlEngineDb $engine   Sparql Engine to query the database
+    *   @return mixed   The result as rendered by the result renderers.
+    */
+    public function convertFromDbResults($arRecordSets, Query $query, SparqlEngineDb $engine)
+    {
+        $this->query    = $query;
+        $this->engine   = $engine;
+        $this->sg       = $engine->getSqlGenerator();
+
+        $strResultForm = $this->query->getResultForm();
+        switch ($strResultForm) {
+            case 'construct':
+            case 'select':
+            case 'select distinct':
+                $arResult = $this->getVariableArrayFromRecordSets($arRecordSets, $strResultForm);
+
+                //some result forms need more modification
+                switch ($strResultForm) {
+                    case 'construct';
+                        $arResult = $this->constructGraph(
+                            $arResult,
+                            $this->query->getConstructPattern()
+                        );
+                        break;
+                    case 'describe';
+                        $arResult = $this->describeGraph($arResult);
+                        break;
+                }
+
+                return $arResult;
+                break;
+
+            case 'count':
+            case 'ask':
+                if (count($arRecordSets) > 1) {
+                    throw new Exception(
+                        'More than one result set for a '
+                        . $strResultForm . ' query!'
+                    );
+                }
+
+                $nCount = 0;
+                $dbRecordSet = reset($arRecordSets);
+                foreach ($dbRecordSet as $row) {
+                    $nCount += intval($row['count']);
+                    break;
+                }
+
+                if ($strResultForm == 'ask') {
+                    return $nCount > 0;
+                } else {
+                    return $nCount;
+                }
+                break;
+
+            case 'describe':
+            default:
+                throw new Exception('Unsupported result form: ' . $strResultForm);
+        }
+
+    }//public function convertFromDbResults($arRecordSets, Query $query, SparqlEngineDb $engine)
+
+
+
+
+    protected function getVariableArrayFromRecordSets($arRecordSets, $strResultForm)
+    {
+        $arResult = array();
+        foreach ($arRecordSets as $dbRecordSet) {
+            $arResult = array_merge(
+                $arResult,
+                $this->getVariableArrayFromRecordSet($dbRecordSet, $strResultForm)
+            );
+        }
+        return $arResult;
+    }//protected function getVariableArrayFromRecordSets($arRecordSets, $strResultForm)
+
+
+
+    /**
+    *   Converts a ADORecordSet object into an array of "rows" that
+    *   are subarrays of variable => value pairs.
+    *
+    *   @param ADORecordSet $dbRecordSet    Anything ADOConnection::Execute() can return
+    *   @return array
+    */
+    protected function getVariableArrayFromRecordSet(ADORecordSet $dbRecordSet, $strResultForm)
+    {
+        $arResult       = array();
+        switch ($strResultForm) {
+            case 'construct':
+                $arResultVars = $this->query->getConstructPatternVariables();
+                break;
+            default:
+                $arResultVars = $this->query->getResultVars();
+                break;
+        }
+
+        if (in_array('*', $arResultVars)) {
+            $arResultVars   = array_keys($this->sg->arVarAssignments);
+        }
+
+        //work around bug in adodb:
+        // ADORecordSet_empty does not implement php5 iterators
+        if ($dbRecordSet->RowCount() <= 0) {
+            return array();
+        }
+
+        foreach ($dbRecordSet as $row) {
+            $arResultRow = array();
+            foreach ($arResultVars as $strVar) {
+                $strVarName = (string)$strVar;
+                if (!isset($this->sg->arVarAssignments[$strVarName])) {
+                    //variable is in select, but not in result (test: q-select-2)
+                    $arResultRow[$strVarName] = '';
+                } else {
+                    $arVarSettings  = $this->sg->arVarAssignments[$strVarName];
+                    $strMethod      = $this->arCreationMethods[$arVarSettings[1]];
+                    $arResultRow[$strVarName] = $this->$strMethod($dbRecordSet, $arVarSettings[0], $strVar);
+                }
+            }
+            $arResult[] = $arResultRow;
+        }
+        return $arResult;
+    }//function getVariableArrayFromRecordSet(ADORecordSet $dbRecordSet)
+
+
+
+    /**
+    *   Creates an RDF Statement object for one of the variables
+    *   contained in the given $dbRecordSet object.
+    *
+    *   @see convertFromDbResult() to understand $strVarBase necessity
+    *
+    *   @param ADORecordSet $dbRecordSet    Record set returned from ADOConnection::Execute()
+    *   @param string       $strVarBase     Prefix of the columns the recordset fields have.
+    *
+    *   @return Statement   RDF statement object
+    */
+    protected function createStatementFromDbRecordSetPart(ADORecordSet $dbRecordSet, $strVarBase)
+    {
+        return new Statement(
+            $this->createSubjectFromDbRecordSetPart  ($dbRecordSet, $strVarBase),
+            $this->createPredicateFromDbRecordSetPart($dbRecordSet, $strVarBase),
+            $this->createObjectFromDbRecordSetPart   ($dbRecordSet, $strVarBase)
+        );
+    }//protected function createStatementFromDbRecordSetPart(ADORecordSet $dbRecordSet, $strVarBase)
+
+
+
+    /**
+    *   Creates an RDF subject object
+    *   contained in the given $dbRecordSet object.
+    *
+    *   @see convertFromDbResult() to understand $strVarBase necessity
+    *
+    *   @param ADORecordSet $dbRecordSet    Record set returned from ADOConnection::Execute()
+    *   @param string       $strVarBase     Prefix of the columns the recordset fields have.
+    *
+    *   @return Resource   RDF triple subject resource object
+    */
+    protected function createSubjectFromDbRecordSetPart(ADORecordSet $dbRecordSet, $strVarBase, $strVar)
+    {
+        $strVarName = (string)$strVar;
+        if ($dbRecordSet->fields[$strVarBase . '.' . $this->sg->arVarAssignments[$strVarName]['sql_value']] === null) {
+            //FIXME: should be NULL, but doesn't pass test
+            return '';
+        }
+
+        if ($dbRecordSet->fields[$strVarBase . '.' . $this->sg->arVarAssignments[$strVarName]['sql_is']] == 'r'
+            //null should be predicate which is always a resource
+         || $dbRecordSet->fields[$strVarBase . '.' . $this->sg->arVarAssignments[$strVarName]['sql_is']] === null
+        ) {
+            return $this->createResource($dbRecordSet->fields[$strVarBase . '.' . $this->sg->arVarAssignments[$strVarName]['sql_value']]);
+        } else {
+            return $this->createBlankNode($dbRecordSet->fields[$strVarBase . '.' . $this->sg->arVarAssignments[$strVarName]['sql_value']]);
+        }
+        return $subject;
+    }//protected function createSubjectFromDbRecordSetPart(ADORecordSet $dbRecordSet, $strVarBase, $strVar)
+
+
+
+    /**
+    *   Creates an RDF predicate object
+    *   contained in the given $dbRecordSet object.
+    *
+    *   @see convertFromDbResult() to understand $strVarBase necessity
+    *
+    *   @param ADORecordSet $dbRecordSet    Record set returned from ADOConnection::Execute()
+    *   @param string       $strVarBase     Prefix of the columns the recordset fields have.
+    *
+    *   @return Resource   RDF triple predicate resource object
+    */
+    protected function createPredicateFromDbRecordSetPart(ADORecordSet $dbRecordSet, $strVarBase, $strVar)
+    {
+        $strVarName = (string)$strVar;
+        if ($dbRecordSet->fields[$strVarBase . '.' . $this->sg->arVarAssignments[$strVarName]['sql_value']] === null) {
+            //FIXME: should be NULL, but doesn't pass test
+            return '';
+        }
+        return $this->createResource($dbRecordSet->fields[$strVarBase . '.' . $this->sg->arVarAssignments[$strVarName]['sql_value']]);
+    }//protected function createPredicateFromDbRecordSetPart(ADORecordSet $dbRecordSet, $strVarBase, $strVar)
+
+
+
+    /**
+    *   Creates an RDF object object
+    *   contained in the given $dbRecordSet object.
+    *
+    *   @see convertFromDbResult() to understand $strVarBase necessity
+    *
+    *   @param ADORecordSet $dbRecordSet    Record set returned from ADOConnection::Execute()
+    *   @param string       $strVarBase     Prefix of the columns the recordset fields have.
+    *
+    *   @return Resource   RDF triple object resource object
+    */
+    protected function createObjectFromDbRecordSetPart(ADORecordSet $dbRecordSet, $strVarBase, $strVar)
+    {
+        $strVarName = (string)$strVar;
+        if ($dbRecordSet->fields[$strVarBase . '.' . $this->sg->arVarAssignments[$strVarName]['sql_value']] === null) {
+            //FIXME: should be NULL, but doesn't pass test
+            return '';
+        }
+        switch ($dbRecordSet->fields[$strVarBase . '.' . $this->sg->arVarAssignments[$strVarName]['sql_is']]) {
+            case 'r':
+                return $this->createResource($dbRecordSet->fields[$strVarBase . '.' . $this->sg->arVarAssignments[$strVarName]['sql_value']]);
+                break;
+            case 'b':
+                return $this->createBlankNode($dbRecordSet->fields[$strVarBase . '.' . $this->sg->arVarAssignments[$strVarName]['sql_value']]);
+                break;
+            default:
+                return $this->createLiteral(
+                    $dbRecordSet->fields[$strVarBase . '.' . $this->sg->arVarAssignments[$strVarName]['sql_value']],
+                    $dbRecordSet->fields[$strVarBase . '.' . $this->sg->arVarAssignments[$strVarName]['sql_lang']],
+                    $dbRecordSet->fields[$strVarBase . '.' . $this->sg->arVarAssignments[$strVarName]['sql_type']]
+                );
+        }
+    }//protected function createObjectFromDbRecordSetPart(ADORecordSet $dbRecordSet, $strVarBase, $strVar)
+
+
+
+    /**
+    * Constructs a result graph.
+    *
+    * @param  array         $arVartable       A table containing the result vars and their bindings
+    * @param  GraphPattern  $constructPattern The CONSTRUCT pattern
+    * @return MemModel      The result graph which matches the CONSTRUCT pattern
+    */
+    protected function constructGraph($arVartable, $constructPattern)
+    {
+        $resultGraph = new MemModel();
+
+        if (!$arVartable) {
+            return $resultGraph;
+        }
+
+        $tp = $constructPattern->getTriplePatterns();
+
+        $bnode = 0;
+        foreach ($arVartable as $value) {
+            foreach ($tp as $triple) {
+                $sub  = $triple->getSubject();
+                $pred = $triple->getPredicate();
+                $obj  = $triple->getObject();
+
+                if (is_string($sub)  && $sub{1} == '_') {
+                    $sub  = new BlankNode("_bN".$bnode);
+                }
+                if (is_string($pred) && $pred{1} == '_') {
+                    $pred = new BlankNode("_bN".$bnode);
+                }
+                if (is_string($obj)  && $obj{1} == '_') {
+                    $obj  = new BlankNode("_bN".$bnode);
+                }
+
+
+                if (is_string($sub)) {
+                    $sub  = $value[$sub];
+                }
+                if (is_string($pred)) {
+                    $pred = $value[$pred];
+                }
+                if (is_string($obj)) {
+                    $obj  = $value[$obj];
+                }
+
+                if ($sub !== "" && $pred !== "" && $obj !== "") {
+                    $resultGraph->add(new Statement($sub,$pred,$obj));
+                }
+            }
+            $bnode++;
+        }
+        return $resultGraph;
+    }//protected function constructGraph($arVartable, $constructPattern)
+
+
+
+    protected function createResource($uri)
+    {
+        return 'R<' . $uri . '>';
+    }//protected function createResource($uri)
+
+
+
+    protected function createBlankNode($id)
+    {
+        return 'B(' . $id . ')';
+    }//protected function createBlankNode($id)
+
+
+
+    protected function createLiteral($value, $language, $datatype)
+    {
+        $v = 'L(' . $value;
+        if ($language != null) {
+            $v .= '@' . $language;
+        }
+        if ($datatype != null) {
+            $v .= '^^' . $datatype;
+        }
+        return $v . ')';
+    }//protected function createLiteral($value, $language, $datatype)
+
+}//class SparqlEngineDb_ResultRenderer_PlainText implements SparqlEngineDb_ResultRenderer
+?>
Index: /Dev/trunk/rdfapi/sparql/SparqlEngineDb/ResultRenderer/XML.php
===================================================================
--- /Dev/trunk/rdfapi/sparql/SparqlEngineDb/ResultRenderer/XML.php	(revision 12)
+++ /Dev/trunk/rdfapi/sparql/SparqlEngineDb/ResultRenderer/XML.php	(revision 12)
@@ -0,0 +1,336 @@
+<?php
+require_once RDFAPI_INCLUDE_DIR . 'sparql/SparqlEngineDb/ResultRenderer.php';
+
+/**
+*   Sparql DB XML result renderer as defined by
+*   http://www.w3.org/TR/rdf-sparql-XMLres/
+*
+*   @author Christian Weiske <cweiske@cweiske.de>
+*   @license http://www.gnu.org/licenses/lgpl.html LGPL
+*
+*   @package sparql
+*/
+class SparqlEngineDb_ResultRenderer_XML implements SparqlEngineDb_ResultRenderer
+{
+
+    /**
+    *   Defines the methods needed to create the types
+    *   in $arVarAssignments.
+    *   Key is the type (e.g. "s" for subject), and
+    *   value the method's name.
+    *
+    *   @see $arVarAssignments
+    *
+    *   @var array
+    */
+    protected $arCreationMethods = array(
+        's' => 'createSubjectFromDbRecordSetPart',
+        'p' => 'createPredicateFromDbRecordSetPart',
+        'o' => 'createObjectFromDbRecordSetPart'
+    );
+
+
+
+    /**
+    *   Converts the database results into nice HTML.
+    *
+    *   @param array $arRecordSets  Array of (possibly several) SQL query results.
+    *   @param Query $query     SPARQL query object
+    *   @param SparqlEngineDb $engine   Sparql Engine to query the database
+    *   @return mixed   HTML code
+    */
+    public function convertFromDbResults($arRecordSets, Query $query, SparqlEngineDb $engine)
+    {
+        $this->query = $query;
+        $this->sg    = $engine->getSqlGenerator();
+        $strCode     = '';
+
+        $strResultForm = $query->getResultForm();
+        switch ($strResultForm) {
+            case 'select':
+            case 'select distinct':
+                $strCode = $this->createFromRecords($arRecordSets, $strResultForm);
+                break;
+
+            case 'construct':
+            case 'describe':
+                throw new Exception(
+                    'Construct and describe are not supported by the'
+                    . ' XML renderer'
+                );
+
+            case 'count':
+            case 'ask':
+                if (count($arRecordSets) > 1) {
+                    throw new Exception(
+                        'More than one result set for a '
+                        . $strResultForm . ' query!'
+                    );
+                }
+
+                $nCount = 0;
+                $dbRecordSet = reset($arRecordSets);
+                foreach ($dbRecordSet as $row) {
+                    $nCount += intval($row['count']);
+                    break;
+                }
+
+                if ($strResultForm == 'ask') {
+                    $strCode = $this->getHead()
+                        . '  <boolean>'
+                        . self::getSpokenBoolean($nCount > 0)
+                        . '</boolean>';
+                } else {
+                    $strCode = $this->getHead()
+                        . '  <int>'
+                        . $nCount
+                        . '</int>';
+                }
+                break;
+
+            default:
+                throw new Exception('Unsupported result form: ' . $strResultForm);
+        }
+
+        return $this->wrapCode($strCode);
+    }//public function convertFromDbResults($arRecordSets, Query $query, SparqlEngineDb $engine)
+
+
+
+    protected function wrapCode($strCode)
+    {
+        return <<<EOT
+<?xml version="1.0"?>
+<sparql xmlns="http://www.w3.org/2005/sparql-results#">
+
+EOT
+            . $strCode . "\n"
+            . "</sparql>\n";
+    }//protected function wrapCode($strCode)
+
+
+
+    protected function getHead($strXml = '')
+    {
+        return "  <head>\n"
+            . $strXml
+            . "  </head>\n";
+    }//protected function getHead($strXml = '')
+
+
+
+    protected function createFromRecords($arRecordSets, $strResultForm)
+    {
+        $arResultVars = $this->query->getResultVars();
+
+        if (in_array('*', $arResultVars)) {
+            $arResultVars   = array_keys($this->sg->arVarAssignments);
+        }
+		
+        $strVarXML = '';
+        foreach ($arResultVars as $var) {
+        	$strVarXML .= "    <variable name=\"" . substr((string)$var,1) . "\"/>\n";
+        }
+        
+        $strHeadXml = $this->getHead($strVarXML);
+
+        $arResult = array();
+        foreach ($arRecordSets as $dbRecordSet) {
+            //work around bug in adodb:
+            // ADORecordSet_empty does not implement php5 iterators
+            if ($dbRecordSet->RowCount() <= 0) {
+                
+            	return 
+            		$strHeadXml
+            		. '  <results ordered="'
+                	. self::getSpokenBoolean($arSM['order by'] !== null)
+					. '" distinct="'
+                	. self::getSpokenBoolean($strResultForm == 'select distinct')
+                	. '">' . "\n"
+            		. '    <!-- empty result -->' . PHP_EOL 
+            		. "  </results>\n";
+            }
+
+            foreach ($dbRecordSet as $row) {
+                $arResultRow = array();
+                foreach ($arResultVars as $strVar) {
+                    $strVarName = (string)$strVar;
+                    if (!isset($this->sg->arVarAssignments[$strVarName])) {
+                        //variable is in select, but not in result (test: q-select-2)
+                        $arResultRow[$strVarName] = '';
+                    } else {
+                        $arVarSettings  = $this->sg->arVarAssignments[$strVarName];
+                        $strMethod      = $this->arCreationMethods[$arVarSettings[1]];
+                        $arResultRow[$strVarName] = $this->$strMethod($dbRecordSet, $arVarSettings[0], $strVar);
+                    }
+                }
+                $arResult[] = $arResultRow;
+            }
+        }
+
+
+        $arSM = $this->query->getSolutionModifier();
+
+        return
+            $strHeadXml
+            . '  <results ordered="'
+                . self::getSpokenBoolean($arSM['order by'] !== null)
+                . '" distinct="'
+                . self::getSpokenBoolean($strResultForm == 'select distinct')
+                . '">' . "\n"
+            . $this->getResultXml($arResult)
+            . "  </results>\n";
+    }//protected function createFromRecords($arRecordSets)
+
+
+
+    protected function getResultXml($arResult)
+    {
+        $strCode = '';
+        foreach ($arResult as $arSet) {
+            $strCode .= "    <result>\n";
+            foreach ($arSet as $strVarName => $strValue) {
+                if ($strValue !== null) {
+                    $strCode .= '      <binding name="' . substr($strVarName,1) . '">'
+                        . $strValue
+                        . "</binding>\n";
+                }
+            }
+            $strCode .= "    </result>\n";
+        }
+        return $strCode;
+    }//protected function getResultXml($arResult)
+
+
+
+    protected static function getSpokenBoolean($b)
+    {
+        return $b ? 'true' : 'false';
+    }//protected static function getSpokenBoolean($b)
+
+
+
+    /**
+    *   Creates an RDF subject object
+    *   contained in the given $dbRecordSet object.
+    *
+    *   @see convertFromDbResult() to understand $strVarBase necessity
+    *
+    *   @param ADORecordSet $dbRecordSet    Record set returned from ADOConnection::Execute()
+    *   @param string       $strVarBase     Prefix of the columns the recordset fields have.
+    *
+    *   @return string HTML code
+    */
+    protected function createSubjectFromDbRecordSetPart(ADORecordSet $dbRecordSet, $strVarBase, $strVar)
+    {
+        $strVarName = (string)$strVar;
+        if ($dbRecordSet->fields[$strVarBase . '.' . $this->sg->arVarAssignments[$strVarName]['sql_value']] === null) {
+            return $this->getXmlNull();
+        }
+        if ($dbRecordSet->fields[$strVarBase . '.' . $this->sg->arVarAssignments[$strVarName]['sql_is']] == 'r'
+            //null should be predicate which is always a resource
+         || $dbRecordSet->fields[$strVarBase . '.' . $this->sg->arVarAssignments[$strVarName]['sql_is']] === null
+        ) {
+            return $this->getXmlResource($dbRecordSet->fields[$strVarBase . '.' . $this->sg->arVarAssignments[$strVarName]['sql_value']]);
+        } else {
+            return $this->getXmlBlank($dbRecordSet->fields[$strVarBase . '.' . $this->sg->arVarAssignments[$strVarName]['sql_value']]);
+        }
+    }//protected function createSubjectFromDbRecordSetPart(ADORecordSet $dbRecordSet, $strVarBase, $strVar)
+
+
+
+    /**
+    *   Creates an RDF predicate object
+    *   contained in the given $dbRecordSet object.
+    *
+    *   @see convertFromDbResult() to understand $strVarBase necessity
+    *
+    *   @param ADORecordSet $dbRecordSet    Record set returned from ADOConnection::Execute()
+    *   @param string       $strVarBase     Prefix of the columns the recordset fields have.
+    *
+    *   @return string HTML code
+    */
+    protected function createPredicateFromDbRecordSetPart(ADORecordSet $dbRecordSet, $strVarBase, $strVar)
+    {
+        $strVarName = (string)$strVar;
+        if ($dbRecordSet->fields[$strVarBase . '.' . $this->sg->arVarAssignments[$strVarName]['sql_value']] === null) {
+            return $this->getXmlNull();
+        }
+
+        return $this->getXmlResource($dbRecordSet->fields[$strVarBase . '.' . $this->sg->arVarAssignments[$strVarName]['sql_value']]);
+    }//protected function createPredicateFromDbRecordSetPart(ADORecordSet $dbRecordSet, $strVarBase, $strVar)
+
+
+
+    /**
+    *   Creates an RDF object object
+    *   contained in the given $dbRecordSet object.
+    *
+    *   @see convertFromDbResult() to understand $strVarBase necessity
+    *
+    *   @param ADORecordSet $dbRecordSet    Record set returned from ADOConnection::Execute()
+    *   @param string       $strVarBase     Prefix of the columns the recordset fields have.
+    *
+    *   @return string HTML code
+    */
+    protected function createObjectFromDbRecordSetPart(ADORecordSet $dbRecordSet, $strVarBase, $strVar)
+    {
+        $strVarName = (string)$strVar;
+        if ($dbRecordSet->fields[$strVarBase . '.' . $this->sg->arVarAssignments[$strVarName]['sql_value']] === null) {
+            return $this->getXmlNull();
+        }
+        switch ($dbRecordSet->fields[$strVarBase . '.' . $this->sg->arVarAssignments[$strVarName]['sql_is']]) {
+            case 'r':
+                return $this->getXmlResource($dbRecordSet->fields[$strVarBase . '.' . $this->sg->arVarAssignments[$strVarName]['sql_value']]);
+                break;
+            case 'b':
+                return $this->getXmlBlank($dbRecordSet->fields[$strVarBase . '.' . $this->sg->arVarAssignments[$strVarName]['sql_value']]);
+                break;
+            default:
+                return $this->getXmlLiteral(
+                    $dbRecordSet->fields[$strVarBase . '.' . $this->sg->arVarAssignments[$strVarName]['sql_value']],
+                    $dbRecordSet->fields[$strVarBase . '.' . $this->sg->arVarAssignments[$strVarName]['sql_lang']],
+                    $dbRecordSet->fields[$strVarBase . '.' . $this->sg->arVarAssignments[$strVarName]['sql_type']]
+                );
+        }
+    }//protected function createObjectFromDbRecordSetPart(ADORecordSet $dbRecordSet, $strVarBase, $strVar)
+
+
+
+    protected function getXmlNull()
+    {
+        return null;
+    }//protected function getHtmlNull()
+
+
+
+    protected function getXmlBlank($value)
+    {
+        return '<bnode>' . $value . '</bnode>';
+    }//protected function getHtmlBlank($value)
+
+
+
+    protected function getXmlResource($value)
+    {
+        return '<uri>' . htmlspecialchars($value) . '</uri>';
+    }//protected function getHtmlResource($value)
+
+
+
+    protected function getXmlLiteral($value, $language, $datatype)
+    {
+        $strCode = '<literal';
+        if ($language) {
+            $strCode . ' xml:lang="' . $language . '"';
+        }
+        if ($datatype) {
+            $strCode . ' datatype="' . $datatype . '"';
+        }
+        $strCode .= '>' . htmlspecialchars($value) . '</literal>';
+        return $strCode;
+    }//protected function getHtmlLiteral($value, $language, $datatype)
+
+}//class SparqlEngineDb_ResultRenderer_XML implements SparqlEngineDb_ResultRenderer
+
+?>
Index: /Dev/trunk/rdfapi/sparql/SparqlEngineDb/SqlGenerator.php
===================================================================
--- /Dev/trunk/rdfapi/sparql/SparqlEngineDb/SqlGenerator.php	(revision 12)
+++ /Dev/trunk/rdfapi/sparql/SparqlEngineDb/SqlGenerator.php	(revision 12)
@@ -0,0 +1,999 @@
+<?php
+require_once RDFAPI_INCLUDE_DIR . 'sparql/SparqlVariable.php';
+require_once RDFAPI_INCLUDE_DIR . 'sparql/SparqlEngineDb/TypeSorter.php';
+require_once RDFAPI_INCLUDE_DIR . 'sparql/SparqlEngineDb/FilterGenerator.php';
+require_once RDFAPI_INCLUDE_DIR . 'sparql/SparqlEngineDb/SqlGeneratorException.php';
+
+/**
+*   Creates sql statements from a Query object
+*
+*   @author Christian Weiske <cweiske@cweiske.de>
+*   @license http://www.gnu.org/licenses/lgpl.html LGPL
+*
+*   @package sparql
+*/
+class SparqlEngineDb_SqlGenerator
+{
+    public $query = null;
+
+    /**
+    *   Determines which variables can be found
+    *   in which SQL result column.
+    *   @example
+    *   array(
+    *       '?person' => array('t1', 's'),
+    '       '?p'      => array('t1', 'p'),
+    *       '?mbox'   => array('t2', 'o')
+    *   )
+    *   Would express that variable ?person is the subject
+    *   in result table t1, and ?mbox is the object in
+    *   table t2.
+    *
+    *   @see $arCreationMethods
+    *
+    *   @internal The array is created in createSql()
+    *   and used in convertFromDbResult().
+    *
+    *   @var array
+    */
+    public $arVarAssignments = array();
+
+    /**
+    *   Array of variable name => table.col assignments
+    *   for all variables used in the query not only
+    *   the ones that shall be returned.
+    *
+    *   @example
+    *   array(
+    *       '?person'   => 't0.subject'
+    *   )
+    *
+    *   @var array
+    */
+    public $arUsedVarAssignments = array();
+
+    /**
+    *   Array of arrays that contain all variable names
+    *   which are to be found in the result of
+    *   an sql statement in a union.
+    *
+    *   @example
+    *   array(
+    *       0 => array(
+    *           '?person' => 's',
+    *           '?p' => 'o'
+    *       ),
+    *       1 => array(
+    *           '?person' => 's',
+    *           '?mbox' => 'o'
+    *       )
+    *   )
+    *
+    *   @var array
+    */
+    public $arUnionVarAssignments = array();
+
+    /**
+    *   Which variables have been used as which type?
+    *   key is variable name, value is an array of
+    *   max. three keys (s, p, o)
+    *
+    *   @example
+    *   array(
+    *       '?person' => array(
+    *           's' => true
+    *       ),
+    *       '?mbox' => array(
+    *           'o' => true
+    *       )
+    *   )
+    *
+    *   @var array
+    */
+    protected $arUsedVarTypes = array();
+
+    /**
+    *   Array with placeholders of prepared statements variables.
+    *   key is the variable name (without "??"), value is the
+    *   placeholder.
+    *   @var array
+    */
+    protected $arPlaceholders = array();
+
+    /**
+    *   Column names for subjects, predicates and
+    *   objects for easy access via their character
+    *   names (spo).
+    *
+    *   @var array
+    */
+    public static $arTableColumnNames = array(
+        's' => array(
+            'value' => 'subject',
+            'is'    => 'subject_is'
+        ),
+        'p' => array(
+            'value' => 'predicate'
+        ),
+        'o' => array(
+            'value' => 'object',
+            'is'    => 'object_is'
+        )
+    );
+
+    /**
+    *   Current UNION part number
+    *   @var int
+    */
+    protected $nUnionCount = 0;
+
+    protected $nSqlVariableNameCount = 0;
+
+    /**
+    *   Name of the statements table
+    */
+    protected $tblStatements = 'statements';
+
+
+
+    public function __construct(Query $query, ADOConnection $dbConn, $arModelIds)
+    {
+        $this->query      = $query;
+        $this->dbConn     = $dbConn;
+        $this->arModelIds = $arModelIds;
+    }//public function __construct(Query $query, ADOConnection $dbConn, $arModelIds)
+
+
+
+    /**
+    *   Creates an SQL query string from the given Sparql query object.
+    *
+    *   @internal uses $query variable
+    *
+    *   @return array       Array of arrays of SQL query string parts: select, from and where
+    *
+    *   @throws SparqlEngineDb_SqlGeneratorException   If there is no variable in the result set.
+    */
+    function createSql()
+    {
+//var_dump($this->query);
+        $arSelect   = array();
+        $arFrom     = array();
+        $arWhere    = array();
+
+        $strResultForm = $this->query->getResultForm();
+        $filterGen     = new SparqlEngineDb_FilterGenerator($this);
+        switch ($strResultForm) {
+            case 'construct':
+                $arResultVars = $this->query->getConstructPatternVariables();
+                break;
+            default:
+                $arResultVars = $this->query->getResultVars();
+                break;
+        }
+
+        $this->nTableId                 = 0;
+        $this->nGraphPatternCount       = 0;
+        $this->nUnionCount              = 0;
+        $this->nUnionTriplePatternCount = 0;
+        $this->arUnionVarAssignments[0] = array();
+
+        foreach ($this->query->getResultPart() as $graphPattern) {
+            if ($graphPattern->isEmpty()) {
+                continue;
+            }
+            if ($graphPattern->getUnion() !== null) {
+                ++$this->nUnionCount;
+                $this->nTableId                 = 0;
+                $this->nUnionTriplePatternCount = 0;
+                $this->nGraphPatternCount = 0;
+                $this->arUnionVarAssignments[$this->nUnionCount] = array();
+            }
+            $this->nTriplePatternCount = 0;
+            $arTriplePattern = $graphPattern->getTriplePatterns();
+            if ($arTriplePattern != null) {
+                foreach ($arTriplePattern as $triplePattern) {
+                    list (
+                        $arSelect[$this->nUnionCount][],
+                        $arFrom  [$this->nUnionCount][],
+                        $arWhere [$this->nUnionCount][]
+                    ) =
+                        $this->getTripleSql(
+                            $triplePattern,
+                            $graphPattern,
+                            $arResultVars
+                        );
+                    ++$this->nTableId;
+                    ++$this->nTriplePatternCount;
+                    ++$this->nUnionTriplePatternCount;
+                }
+            }
+            ++$this->nGraphPatternCount;
+
+        }
+
+        //constraints extra. needed, since OPTIONAL parts are put after
+        // the current pattern while the constraint already refers to variables
+        // defined in there
+        $this->nGraphPatternCount       = 0;
+        $this->nUnionCount              = 0;
+        foreach ($this->query->getResultPart() as $graphPattern) {
+            if ($graphPattern->getUnion() !== null) {
+                ++$this->nUnionCount;
+            }
+            $arConstraints = $graphPattern->getConstraints();
+            if ($arConstraints != null) {
+                foreach ($arConstraints as $constraint) {
+                    $arWhere[$this->nUnionCount][count($arWhere[$this->nUnionCount]) - 1]
+                     .= $filterGen->createFilterSql(
+                        $constraint->getTree(),
+                        $graphPattern->getOptional() !== null,
+                        $this->nUnionCount
+                    );
+                }
+            }
+            ++$this->nGraphPatternCount;
+        }
+
+        $arSelect    = $this->createEqualSelects($arSelect);
+        $arStrSelect = array();
+
+        switch ($strResultForm) {
+            case 'construct':
+            case 'describe':
+                $strSelectType = 'SELECT';
+            case 'select':
+            case 'select distinct':
+                if (!isset($strSelectType)) {
+                    $strSelectType = $strResultForm;
+                }
+                foreach ($arSelect as $nUnionCount => $arSelectPart) {
+                    $arSelectPart = self::removeNull($arSelectPart);
+                    if (count($arSelectPart) == 0
+                    || (count($arSelectPart) == 1 && $arSelectPart[0] == '')) {
+                        //test "test-1-07" suggests we return no rows in this case
+                        //throw new SparqlEngineDb_SqlGeneratorException('No variable that could be returned.');
+                    } else {
+                        $arStrSelect[$nUnionCount] = strtoupper($strSelectType) . ' ' . implode(', '   , $arSelectPart);
+                    }
+                }
+                break;
+
+            case 'ask':
+            case 'count':
+                $arStrSelect = array('SELECT COUNT(*) as count');
+                break;
+
+            default:
+                throw new SparqlEngineDb_SqlGeneratorException('Unsupported query type "' . $strResultForm . '"');
+                break;
+        }
+
+        $arSqls = array();
+        foreach ($arStrSelect as $nUnionCount => $arSelectPart) {
+            $arSqls[] = array(
+                'select'    => $arStrSelect[$nUnionCount],
+                'from'      => ' FROM '  . implode(' '    , self::removeNull($arFrom[$nUnionCount])),
+                'where'     => ' WHERE ' . self::fixWhere(
+                            implode(' '  , self::removeNull($arWhere[$nUnionCount]))
+                )
+            );
+        }
+        return $arSqls;
+    }//function createSql()
+
+
+
+    /**
+    *   Creates some SQL statements from the given triple pattern
+    *   array.
+    *
+    *   @param QueryTriple  $triple                 Array containing subject, predicate and object
+    *   @param GraphPattern $graphPattern           Graph pattern object
+    *
+    *   @return array   Array consisting of on array and two string values:
+    *                   SELECT, FROM and WHERE part
+    */
+    function getTripleSql(QueryTriple $triple, GraphPattern $graphPattern, $arResultVars)
+    {
+        $arSelect  = array();
+        $strFrom    = null;
+        $strWhere   = null;
+        $strWhereEquality        = '';
+        $bWhereEqualitySubject   = false;
+        $bWhereEqualityPredicate = false;
+        $bWhereEqualityObject    = false;
+
+        $subject    = $triple->getSubject();
+        $predicate  = $triple->getPredicate();
+        $object     = $triple->getObject();
+
+        $arRefVars      = array();
+        $strTablePrefix = 't' . $this->nTableId;
+
+        /**
+        *   SELECT part
+        *   We do select only the columns we need for variables
+        */
+        if (SparqlVariable::isVariable($subject)) {
+            if (isset($this->arUnionVarAssignments[$this->nUnionCount][$subject])) {
+                //already selected -> add equality check
+                $bWhereEqualitySubject = true;
+                $this->arUsedVarTypes[$subject]['s'] = true;
+            } else {
+                if (isset($this->arVarAssignments[$subject][0])) {
+                    $strTablePrefix = $this->arVarAssignments[$subject][0];
+                }
+                $this->arVarAssignments[$subject] = array($strTablePrefix, 's');
+                $this->arUnionVarAssignments[$this->nUnionCount][$subject] = array($strTablePrefix, 's');
+                $this->arUsedVarTypes[$subject]['s'] = true;
+                if (self::isResultVar($subject, $arResultVars)) {
+                    //new variable that needs to be selected
+                    $arSelect[$subject] = $this->createVariableSelectArray(
+                        's', $subject, $strTablePrefix
+                    );
+                    if (isset($this->arUsedVarAssignments[$subject])) {
+                        $arRefVars[$subject] = $strTablePrefix . '.subject';
+                    } else {
+                        $this->arUsedVarAssignments[$subject] = $strTablePrefix . '.subject';
+                    }
+                }
+            }
+        }
+
+        if (SparqlVariable::isVariable($predicate)) {
+            if (isset($this->arUnionVarAssignments[$this->nUnionCount][$predicate])) {
+                //already selected -> add equality check
+                $bWhereEqualityPredicate = true;
+                $this->arUsedVarTypes[$predicate]['p'] = true;
+            } else {
+                if (isset($this->arVarAssignments[$predicate][0])) {
+                    $strTablePrefix = $this->arVarAssignments[$predicate][0];
+                }
+                $this->arVarAssignments[$predicate] = array($strTablePrefix, 'p');
+                $this->arUnionVarAssignments[$this->nUnionCount][$predicate] = array($strTablePrefix, 'p');
+                $this->arUsedVarTypes[$predicate]['p'] = true;
+                if (self::isResultVar($predicate, $arResultVars)) {
+                    $arSelect[$predicate] = $this->createVariableSelectArray(
+                        'p', $predicate, $strTablePrefix
+                    );
+                    if (isset($this->arUsedVarAssignments[$predicate])) {
+                        $arRefVars[$predicate] = $strTablePrefix . '.predicate';
+                    } else {
+                        $this->arUsedVarAssignments[$predicate] = $strTablePrefix . '.predicate';
+                    }
+                }
+            }
+        }
+
+        if (SparqlVariable::isVariable($object)) {
+            if (isset($this->arUnionVarAssignments[$this->nUnionCount][$object])) {
+                //already selected -> add equality check
+                $bWhereEqualityObject = true;
+                $this->arUsedVarTypes[$object]['o'] = true;
+            } else {
+                if (isset($this->arVarAssignments[$object][0])) {
+                    $strTablePrefix = $this->arVarAssignments[$object][0];
+                }
+                $this->arVarAssignments[$object] = array($strTablePrefix, 'o');
+                $this->arUnionVarAssignments[$this->nUnionCount][$object] = array($strTablePrefix, 'o');
+                $this->arUsedVarTypes[$object]['o'] = true;
+                if (self::isResultVar($object, $arResultVars)) {
+                    $arSelect[$object] = $this->createVariableSelectArray(
+                        'o', $object, $strTablePrefix
+                    );
+                    if (isset($this->arUsedVarAssignments[$object])) {
+                        $arRefVars[$object] = $strTablePrefix . '.object';
+                    } else {
+                        $this->arUsedVarAssignments[$object] = $strTablePrefix . '.object';
+                    }
+                }
+                if (isset($this->query->varLanguages[$object])
+                 && $this->query->varLanguages[$object] !== null
+                ) {
+                    $strWhereEquality .=
+                        ' AND ' . $strTablePrefix . '.l_language = "'
+                        . addslashes($this->query->varLanguages[$object]) . '"';
+                }
+                if (isset($this->query->varDatatypes[$object])
+                 && $this->query->varDatatypes[$object] !== null
+                ) {
+                    $strWhereEquality .=
+                        ' AND ' . $strTablePrefix . '.l_datatype = "'
+                        . addslashes($this->query->varDatatypes[$object]) . '"';
+                }
+            }
+        }
+
+        /**
+        * WhereEquality - needs to be done now because strTablePrefix may change
+        */
+        if ($bWhereEqualitySubject) {
+            $strWhereEquality .= ' AND ' . self::getSqlEqualityCondition(
+                            array($strTablePrefix, 's'),
+                            $this->arVarAssignments[$subject]
+                        );
+        }
+        if ($bWhereEqualityPredicate) {
+            $strWhereEquality .= ' AND ' . self::getSqlEqualityCondition(
+                            array($strTablePrefix, 'p'),
+                            $this->arVarAssignments[$predicate]
+                        );
+        }
+        if ($bWhereEqualityObject) {
+            $strWhereEquality .= ' AND ' . self::getSqlEqualityCondition(
+                            array($strTablePrefix, 'o'),
+                            $this->arVarAssignments[$object]
+                        );
+        }
+
+
+        /**
+        *   FROM part
+        */
+        if ($this->nUnionTriplePatternCount == 0) {
+            //first FROM
+            $strFrom    = $this->tblStatements . ' as ' . $strTablePrefix;
+        } else {
+            //normal join
+            if (count($this->arModelIds) == 1) {
+                $strFrom    = 'LEFT JOIN ' . $this->tblStatements . ' as ' . $strTablePrefix
+                            . ' ON t0.modelID = ' . $strTablePrefix . '.modelID';
+            } else if (count($this->arModelIds) > 1) {
+                $arIDs     = array();
+                foreach ($this->arModelIds as $nId) {
+                    $arIDs[] = $strTablePrefix . '.modelID = ' . intval($nId);
+                }
+                $strFrom  = 'LEFT JOIN ' . $this->tblStatements . ' as ' . $strTablePrefix
+                          . ' ON (' . implode(' OR ', $arIDs) . ')';
+            } else {
+                $strFrom    = 'LEFT JOIN ' . $this->tblStatements . ' as ' . $strTablePrefix
+                            . ' ON t0.modelID = ' . $strTablePrefix . '.modelID';
+            }
+
+            foreach ($arRefVars as $strRefVar => $strSqlVar) {
+                $strFrom .= ' AND ' . $this->arUsedVarAssignments[$strRefVar] . ' = ' . $strSqlVar;
+            }
+
+            if ($graphPattern->getOptional() !== null) {
+                $strFrom .=  $this->getSqlCondition($subject  , $strTablePrefix, 'subject')
+                           . $this->getSqlCondition($predicate, $strTablePrefix, 'predicate')
+                           . $this->getSqlCondition($object   , $strTablePrefix, 'object')
+                           . $strWhereEquality;
+            }
+        }
+
+
+        /**
+        *   WHERE part
+        */
+        if ($this->nUnionTriplePatternCount == 0) {
+            if (count($this->arModelIds) == 1) {
+                $strWhere  = $strTablePrefix . '.modelID = ' . intval(reset($this->arModelIds));
+            } else if (count($this->arModelIds) > 1) {
+                $arIDs     = array();
+                foreach ($this->arModelIds as $nId) {
+                    $arIDs[] = $strTablePrefix . '.modelID = ' . intval($nId);
+                }
+                $strWhere  = '(' . implode(' OR ', $arIDs) . ')';
+            } else {
+                //so that we can append an AND
+                $strWhere = '1';
+            }
+        }
+        if ($graphPattern->getOptional() === null || $this->nGraphPatternCount == 0) {
+            $strWhere .=  $this->getSqlCondition($subject  , $strTablePrefix, 'subject')
+                        . $this->getSqlCondition($predicate, $strTablePrefix, 'predicate')
+                        . $this->getSqlCondition($object   , $strTablePrefix, 'object')
+                        . $strWhereEquality;
+        }
+
+        return array($arSelect, $strFrom, $strWhere);
+    }//function getTripleSql(QueryTriple $triple)
+
+
+
+
+    protected function createVariableSelectArray($chType, $varname, $strTablePrefix)
+    {
+        $var = $this->query->getResultVar($varname);
+        if ($var !== false) {
+            if ((string)$var != $varname) {
+                //copy over var assignments
+                $this->arVarAssignments[(string)$var] = $this->arVarAssignments[$varname];
+            }
+
+            //works on non-* only
+            $func = $var->getFunc();
+            if ($func != null) {
+                if ($func == 'datatype') {
+                    if ($chType != 'o') {
+                        throw new SparqlEngineDb_SqlGeneratorException(
+                            'datatype() works on objects only'
+                        );
+                    }
+                    return array(
+                        $strTablePrefix . '.l_datatype as "' . $strTablePrefix . '.' . $this->getSqlVariableNameValue($var) . '"',
+                        '"r"' .                      ' as "' . $strTablePrefix . '.' . $this->getSqlVariableNameIs($var) . '"',
+                        '""' .                       ' as "' . $strTablePrefix . '.' . $this->getSqlVariableNameLanguage($var) . '"',
+                        '""' .                       ' as "' . $strTablePrefix . '.' . $this->getSqlVariableNameDatatype($var) . '"',
+                    );
+                } else if ($func == 'lang') {
+                    if ($chType != 'o') {
+                        throw new SparqlEngineDb_SqlGeneratorException(
+                            'lang() works on objects only'
+                        );
+                    }
+                    return array(
+                        $strTablePrefix . '.l_language as "' . $strTablePrefix . '.' . $this->getSqlVariableNameValue($var) . '"',
+                        '"l"' .                      ' as "' . $strTablePrefix . '.' . $this->getSqlVariableNameIs($var) . '"',
+                        '""' .                       ' as "' . $strTablePrefix . '.' . $this->getSqlVariableNameLanguage($var) . '"',
+                        '""' .                       ' as "' . $strTablePrefix . '.' . $this->getSqlVariableNameDatatype($var) . '"',
+                    );
+                } else {
+                    throw new SparqlEngineDb_SqlGeneratorException(
+                        'Unsupported function for select "' . $func . '"'
+                    );
+                }
+            }
+        }
+
+        switch ($chType) {
+            case 's':
+                return array(
+                    $strTablePrefix . '.subject as "'    . $strTablePrefix . '.' . $this->getSqlVariableNameValue($varname) . '"',
+                    $strTablePrefix . '.subject_is as "' . $strTablePrefix . '.' . $this->getSqlVariableNameIs($varname) . '"'
+                );
+            case 'p':
+                return array(
+                    $strTablePrefix . '.predicate as "' . $strTablePrefix . '.' . $this->getSqlVariableNameValue($varname) . '"'
+                );
+            case 'o':
+                return array(
+                    $strTablePrefix . '.object as "'     . $strTablePrefix . '.' . $this->getSqlVariableNameValue($varname) . '"',
+                    $strTablePrefix . '.object_is as "'  . $strTablePrefix . '.' . $this->getSqlVariableNameIs($varname) . '"',
+                    $strTablePrefix . '.l_language as "' . $strTablePrefix . '.' . $this->getSqlVariableNameLanguage($varname) . '"',
+                    $strTablePrefix . '.l_datatype as "' . $strTablePrefix . '.' . $this->getSqlVariableNameDatatype($varname) . '"',
+                );
+            default:
+                throw new SparqlEngineDb_SqlGeneratorException(
+                    'Unknown sentence type "' . $chType . "', one of (s,p,o) expected"
+                );
+        }
+    }//protected function createVariableSelectArray($chType, $value, $strTablePrefix)
+
+
+
+    /**
+    *   Creates SELECT statements that have the same number of columns.
+    *   Needed for UNIONs.
+    *
+    *   @param array $arSelect  Array of arrays.
+    *       array(
+    *           //for each union part one
+    *           0 => array(
+    *               //foreach triple pattern
+    *               0 => array(
+    *                   '?person'   => array(
+    *                       't0.subject as "t0.subject"'
+    *                   )
+    *               )
+    *           )
+    *       )
+    *   @return array Array of SELECT strings
+    */
+    protected function createEqualSelects($arSelect)
+    {
+        $arNewSelect = array();
+        if (count($arSelect) == 1) {
+            if ($arSelect[0] == array(array())) {
+                //ASK and COUNT
+                return array(array(''));
+            }
+
+            foreach ($arSelect[0] as $arTripleVars) {
+                $ar = array();
+                foreach ($arTripleVars as $arVarParts) {
+                    $ar[] = implode(', ', $arVarParts);
+                }
+                if (count($ar) > 0) {
+                    $arNewSelect[0][] = implode(', ', $ar);
+                }
+            }
+            return $arNewSelect;
+        }
+
+        $arVars = array();
+         foreach ($arSelect as $arUnionVars) {
+            foreach ($arUnionVars as $arTripleVars) {
+                $arVars = array_merge($arVars, array_keys($arTripleVars));
+            }
+        }
+        $arVars = array_unique($arVars);
+
+        foreach ($arSelect as $nUnionCount => $arUnionVars) {
+            $arSelectVars = array();
+            foreach ($arUnionVars as $arTripleVars) {
+                foreach ($arTripleVars as $strVar => $arVarParts) {
+                    $arSelectVars[$strVar] = $arVarParts;
+                }
+            }
+
+            $ars = array();
+            foreach ($arVars as $strVar) {
+                if (isset($arSelectVars[$strVar])) {
+                    $ar     = $arSelectVars[$strVar];
+                    $nCount = count($arSelectVars[$strVar]);
+                } else {
+                    $ar     = array();
+                    $nCount = 0;
+                }
+
+                if ($nCount == 0) {
+                    //nothing of this variable in this union part
+                    $ar[] = 'NULL as '
+                        . '"' . $this->arVarAssignments[$strVar][0] . '.' . $this->arVarAssignments[$strVar]['sql_value'] . '"';
+                }
+                if ((
+                    isset($this->arUsedVarTypes[$strVar]['o'])
+                    || isset($this->arUsedVarTypes[$strVar]['s'])
+                    ) && $nCount < 2
+                ) {
+                    //it's a subject or object, but we don't want the type
+                    $ar[] = 'NULL as '
+                        . '"' . $this->arVarAssignments[$strVar][0] . '.' . $this->arVarAssignments[$strVar]['sql_is'] . '"';
+                }
+                if (isset($this->arUsedVarTypes[$strVar]['o']) && $nCount < 4) {
+                    //it's a subject or object, but we don't want the type
+                    if (isset($this->arVarAssignments[$strVar]['sql_lang'])) {
+                        $strColLanguage = $this->arVarAssignments[$strVar]['sql_lang'];
+                    } else {
+                        $strColLanguage = 'dummyLang';
+                    }
+                    if (isset($this->arVarAssignments[$strVar]['sql_type'])) {
+                        $strColDatatype = $this->arVarAssignments[$strVar]['sql_type'];
+                    } else {
+                        $strColDatatype = 'dummyType';
+                    }
+                    $ar[] = 'NULL as '
+                        . '"' . $this->arVarAssignments[$strVar][0] . '.' . $strColLanguage . '"';
+                    $ar[] = 'NULL as '
+                        . '"' . $this->arVarAssignments[$strVar][0] . '.' . $strColDatatype . '"';
+                }
+                $ars[] = implode(', ', $ar);
+            }
+            $arNewSelect[$nUnionCount] = $ars;
+        }
+
+        return $arNewSelect;
+    }//protected function createEqualSelects($arSelect)
+
+
+
+    /**
+    *   Creates an SQL statement that checks for the value
+    *   of some subject/predicate/object
+    *
+    *   @param mixed    $bject          subject|predicate|object
+    *   @param string   $strTablePrefix Table prefix (e.g. "t0")
+    *   @param string   $strType        Type of $bject ('subject'|'predicate'|'object')
+    *   @return string  Part of the SQL query (prefixed with AND)
+    */
+    function getSqlCondition($bject, $strTablePrefix, $strType)
+    {
+        if (is_string($bject)) {
+            if (SparqlVariable::isVariable($bject)) {
+                //variable?
+                if (self::isPreparedVariable($bject)) {
+                    //no, not really
+                    $value = $this->getPreparedVariablePlaceholder($bject);
+                } else {
+                    //yes
+                    return null;
+                }
+            } else {
+                $value = $this->dbConn->qstr($bject);
+            }
+            //literal
+            return ' AND ' . $strTablePrefix . '.' . $strType . ' = ' . $value;
+        }
+
+        if ($bject instanceof BlankNode) {
+            //Blank node
+            throw new SparqlEngineDb_SqlGeneratorException(
+                'FIXME: Querying for blank nodes not supported'
+            );
+
+        } else if ($bject instanceof Resource) {
+            //Resource
+            $r = ' AND ' . $strTablePrefix . '.' . $strType . ' = '
+                . $this->dbConn->qstr($bject->getURI());
+            if ($strType !== 'predicate') {
+                $r .= ' AND ' . $strTablePrefix . '.' . $strType . '_is ='
+                . ' "r"';
+            }
+            return $r;
+
+        } else if ($bject instanceof Literal) {
+            //Literal
+            //I'm doubling Filter code here, but what the hell
+            $strColDatatype = $strTablePrefix . '.l_datatype';
+            if ($bject->dtype == 'http://www.w3.org/2001/XMLSchema#integer'
+             || $bject->dtype == 'http://www.w3.org/2001/XMLSchema#double'
+            ) {
+                $strVariable = 'CAST(' . $strTablePrefix . '.' . $strType . ' AS DECIMAL(15,10))';
+                $strValue    = $bject->getLabel();
+            } else {
+                $strVariable = $strTablePrefix . '.' . $strType;
+                $strValue    = $this->dbConn->qstr($bject->getLabel());
+            }
+            $r = ' AND ' . $strVariable . ' = ' . $strValue;
+            if ($strType !== 'predicate') {
+                $r .= ' AND ' . $strTablePrefix . '.' . $strType . '_is ='
+                . ' "l"';
+            }
+
+            if ($strType == 'object') {
+                if ($bject->dtype == '' || $bject->dtype == 'http://www.w3.org/2001/XMLSchema#string') {
+                    //string
+                    $r .= ' AND ('
+                        . $strColDatatype . ' = ""'
+                        . ' OR ' . $strColDatatype . ' = "http://www.w3.org/2001/XMLSchema#string"'
+                        . ')';
+                } else {
+                    $r .= ' AND ' . $strColDatatype . ' = "'
+                        . $bject->dtype
+                        . '"';
+                }
+            }
+
+            if ($bject->lang != '') {
+                $strColLanguage = $strTablePrefix . '.l_language';
+                $r .= ' AND ' . $strColLanguage . ' = '
+                   . $this->dbConn->qstr($bject->lang);
+            }
+            return $r;
+
+        } else {
+            throw new SparqlEngineDb_SqlGeneratorException(
+                'Unsupported sentence part: ' . get_class($bject)
+            );
+        }
+    }//function getSqlCondition($bject, $strTablePrefix, $strType)
+
+
+
+    /**
+    *   Checks if the sentence part (subject, predicate or object) in
+    *   $arNew has the same content as $arOld.
+    *   Required for queries like ":x ?a ?a" where predicate and object
+    *   need to have the same value
+    *
+    *   @param array    $arNew  array($strTablePrefix, $strType = s|p|o)
+    *   @param array    $arOld  array($strTablePrefix, $strType = s|p|o)
+    *   @return string
+    */
+    protected static function getSqlEqualityCondition($arNew, $arOld)
+    {
+        $chTypeNew         = $arNew[1]; $chTypeOld         = $arOld[1];
+        $strTablePrefixNew = $arNew[0]; $strTablePrefixOld = $arOld[0];
+
+        if ($chTypeNew == 'p' || $chTypeOld == 'p') {
+            //just check value
+            //FIXME: it might be I need to check for resource type in object and subject
+            return
+                  $strTablePrefixNew . '.' . self::$arTableColumnNames[$chTypeNew]['value']
+                . ' = '
+                . $strTablePrefixOld . '.' . self::$arTableColumnNames[$chTypeOld]['value']
+                ;
+        } else if ($chTypeNew == 's' || $chTypeOld == 's') {
+            //check value and type
+            return
+                  $strTablePrefixNew . '.' . self::$arTableColumnNames[$chTypeNew]['value']
+                . ' = '
+                . $strTablePrefixOld . '.' . self::$arTableColumnNames[$chTypeOld]['value']
+                . ' AND '
+                . $strTablePrefixNew . '.' . self::$arTableColumnNames[$chTypeNew]['is']
+                . ' = '
+                . $strTablePrefixOld . '.' . self::$arTableColumnNames[$chTypeOld]['is']
+                ;
+        } else {
+            //two objects -> check everything
+            return
+                  $strTablePrefixNew . '.object = '     . $strTablePrefixOld . '.object'
+                . ' AND '
+                . $strTablePrefixNew . '.object_is = '  . $strTablePrefixOld . '.object_is'
+                . ' AND '
+                . $strTablePrefixNew . '.l_language = ' . $strTablePrefixOld . '.l_language'
+                . ' AND '
+                . $strTablePrefixNew . '.l_datatype = ' . $strTablePrefixOld . '.l_datatype'
+                ;
+        }
+    }//protected static function getSqlEqualityCondition($arNew, $arOld)
+
+
+
+    /**
+    *   Checks if the given variable name is part of the result
+    *   variables list.
+    *   Needed since $arResultVars may contain "*" that captures all variables.
+    *
+    *   @param string   $strVar         Variable name (e.g. "?p")
+    *   @param array    $arResultVars   Array with result variables
+    *   @return boolean     true if it is a result variable
+    */
+    protected static function isResultVar($strVar, &$arResultVars)
+    {
+        foreach ($arResultVars as $var) {
+            if ($var == '*') {
+                return true;
+            } else if ((is_string($var) && $var == $strVar)
+                || (is_object($var) && $var->getVariable() == $strVar)) {
+                return true;
+            }
+        }
+        return false;
+    }//protected static function isResultVar($strVar, &$arResultVars)
+
+
+
+    /**
+    *   Checks if the given variable is a replacement
+    *   for a prepared statement.
+    *
+    *   @return boolean
+    */
+    public static function isPreparedVariable($bject)
+    {
+        return is_string($bject) && strlen($bject) >= 3
+             && ($bject[0] == '?' || $bject[0] == '$')
+             && ($bject[1] == '?' || $bject[1] == '$')
+        ;
+    }//public static function isPreparedVariable($bject)
+
+
+
+    /**
+    *   Returns a placeholder to be included in the sql statement.
+    *   It will be replaced with a real prepared statement variable later on.
+    *   Also adds it to the internal placeholder array.
+    *
+    *   @param string $strVariable  The variable to get a placeholder for
+    *   @return string placeholder
+    */
+    protected function getPreparedVariablePlaceholder($strVariable)
+    {
+        $strName = substr($strVariable, 2);
+        if (!isset($this->arPlaceholders[$strName])) {
+            $this->arPlaceholders[$strName] = '@$%_PLACEHOLDER_'
+                . count($this->arPlaceholders) . '_%$@';
+        }
+        return $this->arPlaceholders[$strName];
+    }//protected function getPreparedVariablePlaceholder($strVariable)
+
+
+
+    public function getPlaceholders()
+    {
+        return $this->arPlaceholders;
+    }//public function getPlaceholders()
+
+
+
+    public function getVarAssignments()
+    {
+        return $this->arVarAssignments;
+    }//public function getVarAssignments()
+
+
+
+    public function getUsedVarAssignments()
+    {
+        return $this->arUsedVarAssignments;
+    }//public function getUsedVarAssignments()
+
+
+
+    public function getUsedVarTypes()
+    {
+        return $this->arUsedVarTypes;
+    }//public function getUsedVarTypes()
+
+
+
+    /**
+    *   Removes all NULL values from an array and returns it.
+    *
+    *   @param array $array     Some array
+    *   @return array $array without the NULL values.
+    */
+    protected static function removeNull($array)
+    {
+        foreach ($array as $key => &$value) {
+            if ($value === null) {
+                unset($array[$key]);
+            }
+        }
+        return $array;
+    }//protected static function removeNull($array)
+
+
+
+    /**
+    *   Removes a leading AND from the where clause which would render
+    *   the sql illegal.
+    */
+    protected function fixWhere($strWhere)
+    {
+        $strWhere = ltrim($strWhere);
+        if (substr($strWhere, 0, 4) == 'AND ') {
+            $strWhere = substr($strWhere, 4);
+        }
+        return $strWhere;
+    }//protected function fixWhere($strWhere)
+
+
+
+    protected function getSqlVariableName($var)
+    {
+        $strSparqlVar = (string)$var;
+        if (!isset($this->arVarAssignments[$strSparqlVar]['sqlname'])) {
+            if (preg_match('/[a-zA-Z0-9]+/', substr($strSparqlVar, 1))) {
+                $strName = 'v_' . substr($strSparqlVar, 1);
+            } else {
+                $strName = 'va_' . $this->nSqlVariableNameCount++;
+            }
+            $this->arVarAssignments[$strSparqlVar]['sqlname'] = $strName;
+        }
+        return $this->arVarAssignments[$strSparqlVar]['sqlname'];
+    }//protected function getSqlVariableName($var)
+
+
+
+    protected function getSqlVariableNameValue($var)
+    {
+        $strSparqlVar = (string)$var;
+        $this->arVarAssignments[$strSparqlVar]['sql_value'] =
+            'value_' . $this->getSqlVariableName($var);
+        return $this->arVarAssignments[$strSparqlVar]['sql_value'];
+    }//protected function getSqlVariableNameValue($var)
+
+
+
+    protected function getSqlVariableNameIs($var)
+    {
+        $strSparqlVar = (string)$var;
+        $this->arVarAssignments[$strSparqlVar]['sql_is'] =
+            'is_' . $this->getSqlVariableName($var);
+        return $this->arVarAssignments[$strSparqlVar]['sql_is'];
+    }//protected function getSqlVariableNameIs($var)
+
+
+
+    protected function getSqlVariableNameLanguage($var)
+    {
+        $strSparqlVar = (string)$var;
+        $this->arVarAssignments[$strSparqlVar]['sql_lang'] =
+            'lang_' . $this->getSqlVariableName($var);
+        return $this->arVarAssignments[$strSparqlVar]['sql_lang'];
+    }//protected function getSqlVariableNameLanguage($var)
+
+
+
+    protected function getSqlVariableNameDatatype($var)
+    {
+        $strSparqlVar = (string)$var;
+        $this->arVarAssignments[$strSparqlVar]['sql_type'] =
+            'type_' . $this->getSqlVariableName($var);
+        return $this->arVarAssignments[$strSparqlVar]['sql_type'];
+    }//protected function getSqlVariableNameDatatype($var)
+
+
+
+    public function setStatementsTable($tblStatements)
+    {
+        $this->tblStatements = $tblStatements;
+    }//public function setStatementsTable($tblStatements)
+
+}//class SparqlEngineDb_SqlGenerator
+?>
Index: /Dev/trunk/rdfapi/sparql/SparqlEngineDb/SqlGeneratorException.php
===================================================================
--- /Dev/trunk/rdfapi/sparql/SparqlEngineDb/SqlGeneratorException.php	(revision 12)
+++ /Dev/trunk/rdfapi/sparql/SparqlEngineDb/SqlGeneratorException.php	(revision 12)
@@ -0,0 +1,14 @@
+<?php
+/**
+*   Exception when generating the SQL statement
+*
+*   @author Christian Weiske <cweiske@cweiske.de>
+*   @license http://www.gnu.org/licenses/lgpl.html LGPL
+*
+*   @package sparql
+*/
+class SparqlEngineDb_SqlGeneratorException extends Exception
+{
+}
+
+?>
Index: /Dev/trunk/rdfapi/sparql/SparqlEngineDb/SqlMerger.php
===================================================================
--- /Dev/trunk/rdfapi/sparql/SparqlEngineDb/SqlMerger.php	(revision 12)
+++ /Dev/trunk/rdfapi/sparql/SparqlEngineDb/SqlMerger.php	(revision 12)
@@ -0,0 +1,46 @@
+<?php
+
+/**
+*   Creates an sql string from an sql array
+*
+*   @author Christian Weiske <cweiske@cweiske.de>
+*   @license http://www.gnu.org/licenses/lgpl.html LGPL
+*
+*   @package sparql
+*/
+class SparqlEngineDb_SqlMerger
+{
+    public static function getSelect(Query $query, $arSqls, $strAdditional = '')
+    {
+        if (count($arSqls) == 1) {
+            return implode('', $arSqls[0]) . $strAdditional;
+        }
+
+        //union
+        $strUnion = 'UNION' .
+            ($query->getResultForm() == 'select distinct' ? '' : ' ALL');
+        $ar = array();
+        foreach ($arSqls as $arSql) {
+            $ar[] = implode('', $arSql) . $strAdditional;
+        }
+        return '(' . implode(') ' . $strUnion . ' (', $ar) . ')';
+    }//public static function getSelect(Query $query, $arSqls, $strAdditional = '')
+
+
+
+    public static function getCount(Query $query, $arSqls, $strAdditional = '')
+    {
+        if (count($arSqls) == 1) {
+            return 'SELECT COUNT(*) as count ' . $arSqls[0]['from'] . $arSqls[0]['where'] . $strAdditional;
+        }
+
+        $ar = array();
+        foreach ($arSqls as $arSql) {
+            $ar[] = implode('', $arSql) . $strAdditional;
+        }
+        return 'SELECT (' . implode(') + (', $ar) . ') as count';
+    }//public static function getCount(Query $query, $arSqls, $strAdditional = '')
+
+}//class SparqlEngineDb_SqlMerger
+
+?>
Index: /Dev/trunk/rdfapi/sparql/SparqlEngineDb/TypeSorter.php
===================================================================
--- /Dev/trunk/rdfapi/sparql/SparqlEngineDb/TypeSorter.php	(revision 12)
+++ /Dev/trunk/rdfapi/sparql/SparqlEngineDb/TypeSorter.php	(revision 12)
@@ -0,0 +1,450 @@
+<?php
+/**
+*   Sorts database types as the Sparql specs want it.
+*
+*   @author Christian Weiske <cweiske@cweiske.de>
+*   @license http://www.gnu.org/licenses/lgpl.html LGPL
+*
+*   @package sparql
+*/
+class SparqlEngineDb_TypeSorter
+{
+    /**
+    *   Defines the sort order for value types in the database,
+    *   so that they get sorted correctly as the specs want it.
+    *   @var array
+    */
+    public static $arTypeNumbers = array(
+        null    => 0,//empty
+        'b'     => 1,//blank
+        'r'     => 2,//resource
+        'l'     => 3,//literal
+    );
+
+    /**
+    *   SQL types to cast XSD schema types to, so that they will get
+    *   sorted correctly.
+    *   @var array
+    */
+    public static $arCastTypes = array(
+        'http://www.w3.org/2001/XMLSchema#integer'  => 'SIGNED INTEGER',
+        'http://www.w3.org/2001/XMLSchema#decimal'  => 'DECIMAL',
+        //yes, this does not work with multiple time zones.
+        'http://www.w3.org/2001/XMLSchema#dateTime' => 'CHAR',
+        'http://www.w3.org/2001/XMLSchema#date'     => 'CHAR',
+    );
+
+
+
+    public function __construct(Query $query, ADOConnection $dbConn)
+    {
+        $this->dbConn   = $dbConn;
+        $this->query    = $query;
+    }
+
+
+    /**
+    *   Needs to be executed before getOrderifiedSqls and willBeDataDependent
+    *
+    *   @param SparqlEngineDb_SqlGenerator $sg  SQL generator object
+    */
+    public function setData(SparqlEngineDb_SqlGenerator $sg)
+    {
+        $this->arUsedVarTypes       = $sg->getUsedVarTypes();
+        $this->arUsedVarAssignments = $sg->getUsedVarAssignments();
+        $this->arVarAssignments     = $sg->getVarAssignments();
+    }//public function setData(SparqlEngineDb_SqlGenerator $sg)
+
+
+
+    /**
+    *   Returns an array of sql statements that need to be executed
+    *   and deliver the full result set when combined.
+    *
+    *   Execute setData() before this.
+    *
+    *   @internal It is not possible (ok, it is - but it would really complicate
+    *   the queries and the code here) to use UNION to combine the sqls to
+    *   a single one - UNION merges the results and does not keep the order
+    *   of the rows. Citing the mysql manual:
+    *       Use of ORDER BY for individual SELECT statements implies nothing
+    *       about the order in which the rows appear in the final result because
+    *       UNION by default produces an unordered set of rows. If ORDER BY
+    *       appears with LIMIT, it is used to determine the subset of the
+    *       selected rows to retrieve for the SELECT, but does not necessarily
+    *       affect the order of those rows in the final UNION result.
+    *       If ORDER BY appears without LIMIT in a SELECT, it is
+    *       optimized away because it will have no effect anyway.
+    *
+    *   @param string $strSelect    SELECT clause
+    *   @param string $strFrom      FROM clause
+    *   @param string $strWhere     WHERE clause
+    *   @return array   Array of arrays. Imploding an array will give
+    *                    a complete sql statement. The array will have the keys
+    *                    select/from/where/order.
+    */
+    public function getOrderifiedSqls($arSqls)
+    {
+        if (count($arSqls) == 0) {
+            return $arSqls;
+        }
+
+        $strSelect = $arSqls[0]['select'];
+        $strFrom   = $arSqls[0]['from'];
+        $strWhere  = $arSqls[0]['where'];
+
+        $strResultForm = $this->query->getResultForm();
+        if ($strResultForm == 'ask' || $strResultForm == 'count') {
+            return array(
+                $arSqls
+            );
+        }
+
+        $arSpecial = $this->getSpecialOrderVariables();
+        if (count($arSpecial) == 0) {
+            $strOrder = $this->getSqlOrderBy();
+            foreach ($arSqls as &$arSql) {
+                $arSql['order'] = $strOrder;
+            }
+            return array(
+                $arSqls
+            );
+        }
+
+        $arTypeSets = $this->orderTypeSets(
+            $this->getTypeSets($arSpecial, $strFrom, $strWhere)
+        );
+
+        $arNewSqls = array();
+        foreach ($arTypeSets as $arTypeSet) {
+            $arSqlParts = array();
+            foreach ($arSqls as $arSql) {
+                $arSql['where'] .= $this->getTypesetWhereClause($arTypeSet);
+                $arSql['order']  = $this->getSqlOrderBy($arTypeSet);
+                $arSqlParts[] = $arSql;
+            }
+            $arNewSqls[] = $arSqlParts;
+        }
+
+        return $arNewSqls;
+    }//public function getOrderifiedSqls($arUsedVarAssignments, $strSelect, $strFrom, $strWhere)
+
+
+
+    /**
+    *   Returns wether the returned queries will depend on the data or not.
+    *   If the queries depend on the data, they cannot be prepare()d and
+    *   thus won't be that fast when executing.
+    *
+    *   Execute setData() before this.
+    *
+    *   @return boolean
+    */
+    public function willBeDataDependent()
+    {
+        $strResultForm = $this->query->getResultForm();
+        return !(
+            $strResultForm == 'ask' || $strResultForm == 'count'
+            || count($this->getSpecialOrderVariables()) == 0
+        );
+    }//public function willBeDataDependent()
+
+
+
+    /**
+    *   Returns an array of variables that the result is going to be
+    *   ordered by and that need to be sorted multiple times
+    *   (because they may contain different data types)
+    *
+    *   @return array Array of sparql variable names
+    */
+    protected function getSpecialOrderVariables()
+    {
+        $arSM = $this->query->getSolutionModifier();
+        if ($arSM['order by'] === null) {
+            return array();
+        }
+
+        $arSpecial = array();
+        foreach ($arSM['order by'] as $arVar) {
+            if ($this->isSpecialOrderVariable($arVar['val'])) {
+                $arSpecial[] = $arVar['val'];
+            }
+        }
+        return $arSpecial;
+    }//protected function getSpecialOrderVariables()
+
+
+
+    /**
+    *   Checks if a given variable name is a variable that
+    *   needs special care when used in ORDER BY statements.
+    *
+    *   @param string $strVar SPARQL variable name
+    *   @return boolean true if the variable needs special care
+    */
+    protected function isSpecialOrderVariable($strVar)
+    {
+        return !isset($this->arUsedVarTypes[$strVar]['s'])
+            && !isset($this->arUsedVarTypes[$strVar]['p']);
+    }//protected function isSpecialOrderVariable($arVar)
+
+
+
+    /**
+    *   Determines the type sets in the query results.
+    *   A type set is a distinct set of variables and their types,
+    *   e.g. the variable and its type (r/b/l) and its datatype
+    *   if its an object.
+    *
+    *   @param array $arSpecialVars     Special variables as returned by
+    *                                   getSpecialOrderVariables()
+    *   @param string $strFrom          FROM part of the sql query
+    *   @param string $strWhere         WHERE part of the sql query
+    *
+    *   @return array   Key is the sparql variable name, value is an
+    *                   array. This one has one key 'type' with a
+    *                   value of b/l/r. It might have another key
+    *                   'datatype' with the resource's datatype.
+    */
+    protected function getTypeSets($arSpecialVars, $strFrom, $strWhere)
+    {
+        $arSel = array();
+        foreach ($arSpecialVars as $strSparqlVar) {
+            if ($this->arVarAssignments[$strSparqlVar][1] == 'o') {
+                $arSel[] = $this->arVarAssignments[$strSparqlVar][0] . '.l_datatype'
+                    . ' as "' . $strSparqlVar . '-datatype"';
+            }
+            $strTypeCol = $this->arVarAssignments[$strSparqlVar][1] == 'o'
+                ? 'object_is' : 'subject_is';
+            $this->arVarAssignments[$strSparqlVar][2] = $strTypeCol;
+            $arSel[] = $this->arVarAssignments[$strSparqlVar][0] . '.' . $strTypeCol
+                . ' as "' . $strSparqlVar . '-type"';
+        }
+
+        $oldmode  = $this->dbConn->SetFetchMode(ADODB_FETCH_ASSOC);
+        $sql      = 'SELECT DISTINCT ' . implode(', ', $arSel) . ' ' . $strFrom . $strWhere;
+        $arResult = $this->dbConn->execute($sql);
+        $this->dbConn->SetFetchMode($oldmode);
+
+        if ($arResult === false) {
+            throw new SparqlEngineDb_SqlGeneratorException(
+                'Error reading typesets: ' . $sql
+            );
+        }
+
+        $arTypes = array();
+        foreach ($arResult as $arRow) {
+            $nLine = count($arTypes);
+            foreach ($arRow as $key => $value) {
+                list($strSparqlVar, $strType) = explode('-', $key);
+                $arTypes[$nLine][$strSparqlVar][$strType] = $value;
+            }
+        }
+
+        return $arTypes;
+    }//protected function getTypeSets($arSpecialVars, $strFrom, $strWhere)
+
+
+
+    /**
+    *   Takes an array of type sets (as returned by getTypeSets()) and
+    *   sorts the variables according to the SPARQL specs.
+    *
+    *   @param array $arTypes Array of type sets
+    *   @return array Ordered array of type sets
+    */
+    protected function orderTypeSets($arTypes)
+    {
+        $arSM = $this->query->getSolutionModifier();
+        if ($arSM['order by'] !== null) {
+            $this->arDirection = array();
+            foreach ($arSM['order by'] as $arVar) {
+                $this->arDirection[$arVar['val']] =
+                    (strtoupper($arVar['type']) == 'ASC' ? 1 : -1);
+            }
+        }
+
+        usort($arTypes, array($this, 'compareTypeSet'));
+
+        return $arTypes;
+    }//protected function orderTypeSets($arTypes)
+
+
+
+    /**
+    *   Compares two type sets. Works like a normal comparision
+    *   method that returns -1/0/1 for use in usort()
+    *
+    *   @param array $arTs1     First typeset
+    *   @param array $arTs2     Second typeset
+    *   @return int Comparison value
+    */
+    public function compareTypeSet($arTs1, $arTs2)
+    {
+        foreach ($arTs1 as $strSparqlVar => $arType1) {
+            //compare types
+            $n = self::$arTypeNumbers[$arType1['type']]
+                - self::$arTypeNumbers[$arTs2[$strSparqlVar]['type']];
+            if ($n != 0) {
+                //and take ASC/DESC into account
+                return $n * $this->arDirection[$strSparqlVar];
+            }
+
+            //compare the datatypes
+            $n = self::compareXsdType(
+                $arType1['datatype'],
+                $arTs2[$strSparqlVar]['datatype']
+            );
+            //if they are not equal, return the value
+            if ($n != 0) {
+                //and take ASC/DESC into account
+                return $n * $this->arDirection[$strSparqlVar];
+            }
+        }
+
+        //they are equal
+        return 0;
+    }//public function compareTypeSet($arTs1, $arTs2)
+
+
+
+    /**
+    *   Compares two XSD data types and returns the comparison number.
+    *
+    *   @param string $strType1     First data type
+    *   @param string $strType2     Second data type
+    *   @return int     Comparison number (<0 if $strType1 is less than
+    *                   $strType2, 0 if equal, >0 if type2 is greater)
+    */
+    public static function compareXsdType($strType1, $strType2)
+    {
+        return self::getXsdTypeNumber($strType1) - self::getXsdTypeNumber($strType2);
+    }//public static function compareXsdType($strType1, $strType2)
+
+
+
+    /**
+    *   Returns the type number for an xsd data type.
+    *
+    *   @param string $strType  XSD data type
+    *   @return int  Some integer to compare two types.
+    */
+    public static function getXsdTypeNumber($strType)
+    {
+        if ($strType === null) {
+            return 0;
+        } else if ($strType == '') {
+            return 1;
+        } else {
+            return 2;
+        }
+    }//public static function getXsdTypeNumber($strType)
+
+
+
+    /**
+    *   Returns the ORDER BY sql query string
+    *   if neccessary for the query. The returned string
+    *   already has ORDER BY prefixed.
+    *
+    *   @internal Also takes care of casting the data if the type
+    *   is listed in $arCastTypes. See getCastMethod() for more info.
+    *
+    *   @param arrray $arTypeSet Single typeset
+    *   @return string      ORDER BY ... string or empty string
+    */
+    function getSqlOrderBy($arTypeSet = array())
+    {
+        $arSM = $this->query->getSolutionModifier();
+        if ($arSM['order by'] === null) {
+            return '';
+        }
+
+        $sqlOrder = array();
+        foreach ($arSM['order by'] as $arVar) {
+            $strSparqlVar = $arVar['val'];
+            if (isset($this->arUsedVarAssignments[$strSparqlVar])) {
+                if (!isset($arTypeSet[$strSparqlVar]['datatype'])
+                  || $arTypeSet[$strSparqlVar]['datatype'] == '') {
+                    $sqlOrder[] = $this->arUsedVarAssignments[$strSparqlVar] . ' ' . strtoupper($arVar['type']);
+                } else {
+                    $sqlOrder[] = self::getCastMethod(
+                        $arTypeSet[$strSparqlVar]['datatype'],
+                        $this->arUsedVarAssignments[$strSparqlVar]
+                    ) . ' ' . strtoupper($arVar['type']);
+                }
+            }
+        }
+
+        return ' ORDER BY ' . implode(', ', $sqlOrder);
+    }//function getSqlOrderBy($arTypeSet = array())
+
+
+
+    /**
+    *   Returns the SQL statement needed to case the given variable to
+    *   the given type.
+    *
+    *   @param string $strType      XML data type
+    *   @param string $strSqlVar    SQL variable name
+    *   @return string  SQL command to cast the variable
+    */
+    protected static function getCastMethod($strType, $strSqlVar)
+    {
+        if (isset(self::$arCastTypes[$strType])) {
+            return 'CAST(' . $strSqlVar . ' as ' . self::$arCastTypes[$strType] . ')';
+        } else {
+            //unsupported type!
+            throw new Exception('Unsupported cast type in order by: ' . $strType);
+            return $strSqlVar;
+        }
+    }//protected static function getCastMethod($strType, $strSqlVar)
+
+
+
+    /**
+    *   Creates and returns the SQL WHERE clauses needed to get only
+    *   data in the given typeset.
+    *
+    *   @param array $arTypeSet     Typeset
+    *   @return string  Clauses for the WHERE part in an SQL query
+    */
+    protected function getTypesetWhereClause($arTypeSet)
+    {
+        $strWhereTypes = '';
+        foreach ($arTypeSet as $strSparqlVar => $arType) {
+            //check type
+            $strWhereTypes .= ' AND ' . $this->arVarAssignments[$strSparqlVar][0]
+                . '.' . $this->arVarAssignments[$strSparqlVar][2]
+                . $this->getStringNullComparison($arType['type']);
+            //check datatype
+            if (isset($arType['datatype'])) {
+                $strWhereTypes .= ' AND ' . $this->arVarAssignments[$strSparqlVar][0]
+                    . '.l_datatype '
+                    . $this->getStringNullComparison($arType['datatype']);
+            }
+        }
+        return $strWhereTypes;
+    }//protected function getTypesetWhereClause($arTypeSet)
+
+
+
+    /**
+    *   Returns the correct sql string comparison method.
+    *
+    *   @internal If the string is NULL, an "IS NULL" sql statment
+    *   will be returned, and a normal "= 'something'" if it is
+    *   a normal string.
+    */
+    protected function getStringNullComparison($str)
+    {
+        if ($str === null) {
+            return ' IS NULL';
+        } else {
+            return ' = ' . $this->dbConn->qstr($str) . '';
+        }
+    }//protected function getStringNullComparison($str)
+
+}//class SparqlEngineDb_TypeSorter
+?>
Index: /Dev/trunk/rdfapi/sparql/SparqlParser.php
===================================================================
--- /Dev/trunk/rdfapi/sparql/SparqlParser.php	(revision 12)
+++ /Dev/trunk/rdfapi/sparql/SparqlParser.php	(revision 12)
@@ -0,0 +1,1551 @@
+<?php
+// ---------------------------------------------
+// Class: SparqlParser
+// ---------------------------------------------
+require_once RDFAPI_INCLUDE_DIR . 'model/Literal.php';
+require_once RDFAPI_INCLUDE_DIR . 'model/Resource.php';
+require_once RDFAPI_INCLUDE_DIR . 'sparql/Constraint.php';
+require_once RDFAPI_INCLUDE_DIR . 'sparql/Query.php';
+require_once RDFAPI_INCLUDE_DIR . 'sparql/QueryTriple.php';
+require_once RDFAPI_INCLUDE_DIR . 'sparql/SparqlParserException.php';
+
+/**
+* Parses a SPARQL Query string and returns a Query Object.
+*
+* @author   Tobias Gauss <tobias.gauss@web.de>
+* @author   Christian Weiske <cweiske@cweiske.de>
+* @version     $Id$
+* @license http://www.gnu.org/licenses/lgpl.html LGPL
+*
+* @package sparql
+*/
+class SparqlParser extends Object
+{
+
+    /**
+    * The query Object
+    * @var Query
+    */
+    protected $query;
+
+    /**
+    * The Querystring
+    * @var string
+    */
+    protected $queryString;
+
+    /**
+    * The tokenized Query
+    * @var array
+    */
+    protected $tokens = array();
+
+    /**
+    * Last parsed graphPattern
+    * @var int
+    */
+    protected $tmp;
+
+    /**
+    * Operators introduced by sparql
+    * @var array
+    */
+    protected static $sops = array(
+        'regex',
+        'bound',
+        'isuri',
+        'isblank',
+        'isliteral',
+        'str',
+        'lang',
+        'datatype',
+        'langmatches'
+    );
+
+    /**
+    *   Which order operators are to be treated.
+    *   (11.3 Operator Mapping)
+    *   @var array
+    */
+    protected static $operatorPrecedence = array(
+        '||'    => 0,
+        '&&'    => 1,
+        '='     => 2,
+        '!='    => 3,
+        '<'     => 4,
+        '>'     => 5,
+        '<='    => 6,
+        '>='    => 7,
+        '*'     => 0,
+        '/'     => 0,
+        '+'     => 0,
+        '-'     => 0,
+    );
+
+
+
+    /**
+    * Constructor of SparqlParser
+    */
+    public function SparqlParser()
+    {
+    }
+
+
+
+    /**
+    * Main function of SparqlParser. Parses a query string.
+    *
+    * @param  String $queryString The SPARQL query
+    * @return Query  The query object
+    * @throws SparqlParserException
+    */
+    public function parse($queryString = false)
+    {
+        $this->prepare();
+
+        if ($queryString) {
+            $this->query->setQueryString($queryString);
+            $uncommentedQuery  = $this->uncomment($queryString);
+            $this->queryString = $uncommentedQuery;
+            $this->tokens      = self::tokenize($uncommentedQuery);
+            $this->parseQuery();
+            if (!$this->query->isComplete()) {
+                throw new SparqlParserException(
+                    "Query is incomplete.",
+                    null,
+                    $queryString
+                );
+            }
+        } else {
+            throw new SparqlParserException(
+                "Querystring is empty.",
+                null,
+                key($this->tokens)
+            );
+            $this->query->isEmpty = true;
+        }
+        return $this->query;
+    }//public function parse($queryString = false)
+
+
+
+    /**
+    *   Set all internal variables to a clear state
+    *   before we start parsing.
+    */
+    protected function prepare()
+    {
+        $this->query          = new Query();
+        $this->queryString    = null;
+        $this->tokens         = array();
+        $this->tmp            = null;
+        // add the default prefixes defined in constants.php
+        global $default_prefixes;
+        $this->query->prefixes = $default_prefixes;
+    }//protected function prepare()
+
+
+
+    /**
+    * Tokenizes the query string into $tokens.
+    * The query may not contain any comments.
+    *
+    * @param  string $queryString Query to split into tokens
+    *
+    * @return array Tokens
+    */
+    public static function tokenize($queryString)
+    {
+        $queryString  = trim($queryString);
+        $specialChars = array(' ', "\t", "\r", "\n", ',', '\\', '(', ')','{','}','"',"'",';','[',']');
+        $len          = strlen($queryString);
+        $tokens       = array('');
+        $n            = 0;
+
+        for ($i = 0; $i < $len; ++$i) {
+            if (!in_array($queryString{$i}, $specialChars)) {
+                $tokens[$n] .= $queryString{$i};
+            } else {
+                if ($tokens[$n] != '') {
+                    ++$n;
+                    if (!isset($tokens[$n])) {
+                        $tokens[$n] = '';
+                    }
+                }
+                if ($queryString{$i} == "'" && $n > 1
+                  && $tokens[$n - 2] == "'" && $tokens[$n - 1] == "'"
+                ) {
+                    //special ''' quotation
+                    $tokens[$n - 2] = "'''";
+                    $tokens[$n - 1] = '';
+                    unset($tokens[$n]);
+                    --$n;
+                    continue;
+                } else if ($queryString{$i} == '"' && $n > 1
+                  && $tokens[$n - 2] == '"' && $tokens[$n - 1] == '"'
+                ) {
+                    //special """ quotation
+                    $tokens[$n - 2] = '"""';
+                    $tokens[$n - 1] = '';
+                    unset($tokens[$n]);
+                    --$n;
+                    continue;
+                } else if ($queryString{$i} == '\\') {
+                    $tokens[$n] .= substr($queryString, $i, 2);
+                    ++$i;
+                    continue;
+                }
+                $tokens[$n] = $queryString{$i};
+                $tokens[++$n] = '';
+            }
+        }
+//var_dump($tokens);
+        return $tokens;
+    }//public static function tokenize($queryString)
+
+
+
+    /**
+    * Removes comments in the query string. Comments are
+    * indicated by '#'.
+    *
+    * @param  String $queryString
+    * @return String The uncommented query string
+    */
+    protected function uncomment($queryString)
+    {
+        $regex ="/((\"[^\"]*\")|(\'[^\']*\')|(\<[^\>]*\>))|(#.*)/";
+        return preg_replace($regex,'\1',$queryString);
+    }//protected function uncomment($queryString)
+
+
+
+    /**
+    * Starts parsing the tokenized SPARQL Query.
+    *
+    * @return void
+    */
+    protected function parseQuery()
+    {
+        do {
+            switch (strtolower(current($this->tokens))) {
+                case "base":
+                    $this->parseBase();
+                    break;
+                case "prefix":
+                    $this->parsePrefix();
+                    break;
+                case "select":
+                    $this->parseSelect();
+                    break;
+                case "describe":
+                    $this->parseDescribe();
+                    break;
+                case "ask":
+                    $this->parseAsk('ask');
+                    break;
+                case "count":
+                    $this->parseAsk('count');
+                    break;
+                case "from":
+                    $this->parseFrom();
+                    break;
+                case "construct":
+                    $this->parseConstruct();
+                    break;
+                case "where":
+                    $this->parseWhere();
+                    $this->parseModifier();
+                    break;
+                case "{":
+                    prev($this->tokens);
+                    $this->parseWhere();
+                    $this->parseModifier();
+                    break;
+            }
+        } while (next($this->tokens));
+
+    }//protected function parseQuery()
+
+
+
+    /**
+    * Parses the BASE part of the query.
+    *
+    * @return void
+    * @throws SparqlParserException
+    */
+    protected function parseBase()
+    {
+        $this->_fastForward();
+        if ($this->iriCheck(current($this->tokens))) {
+            $this->query->setBase(current($this->tokens));
+        } else {
+            $msg = current($this->tokens);
+            $msg = preg_replace('/</', '&lt;', $msg);
+            throw new SparqlParserException(
+                "IRI expected",
+                null,
+                key($this->tokens)
+            );
+        }
+    }
+
+
+
+    /**
+    * Adds a new namespace prefix to the query object.
+    *
+    * @return void
+    * @throws SparqlParserException
+    */
+    protected function parsePrefix()
+    {
+        $this->_fastForward();
+        $prefix = substr(current($this->tokens), 0, -1);
+        $this->_fastForward();
+        if ($this->iriCheck(current($this->tokens))) {
+            $uri = substr(current($this->tokens), 1, -1);
+            $this->query->addPrefix($prefix, $uri);
+        } else {
+            $msg = current($this->tokens);
+            $msg = preg_replace('/</', '&lt;', $msg);
+            throw new SparqlParserException(
+                "IRI expected",
+                null,
+                key($this->tokens)
+            );
+        }
+    }
+
+
+
+    /**
+    * Parses the SELECT part of a query.
+    *
+    * @return void
+    * @throws SparqlParserException
+    */
+    protected function parseSelect()
+    {
+        $this->_fastForward();
+        $curLow = strtolower(current($this->tokens));
+        prev($this->tokens);
+        if ($curLow == 'distinct') {
+            $this->query->setResultForm('select distinct');
+        } else {
+            $this->query->setResultForm('select');
+        }
+
+        $currentVar = null;
+        $currentFunc = null;
+        $bWaitForRenaming = false;
+        while ($curLow != 'from' && $curLow != 'where' &&
+               $curLow != "{"
+        ){
+            $this->_fastForward();
+            $curTok = current($this->tokens);
+            $curLow = strtolower($curTok);
+
+            if ($this->varCheck($curTok) || $curLow == '*') {
+                if ($bWaitForRenaming) {
+                    $bWaitForRenaming = false;
+                    $currentVar->setAlias($curTok);
+                    if ($currentFunc != null) {
+                        $currentVar->setFunc($currentFunc);
+                    }
+                    $this->query->addResultVar($currentVar);
+                    $currentVar = null;
+                } else {
+                    if ($currentVar != null) {
+                        $this->query->addResultVar($currentVar);
+                        $currentVar = null;
+                    }
+                    $currentVar = new Query_ResultVariable($curTok);
+                    if ($currentFunc != null) {
+                        $currentVar->setFunc($currentFunc);
+                    }
+                }
+                $currentFunc = null;
+            } else if ($curLow == 'as') {
+                if ($currentVar === null) {
+                    throw new SparqlParserException(
+                        'AS requires a variable left and right',
+                        null,
+                        key($this->tokens)
+                    );
+                }
+                $bWaitForRenaming = true;
+            } else if (in_array($curLow, self::$sops)) {
+                $currentFunc = $curLow;
+            }
+
+            if (!current($this->tokens)) {
+                throw new SparqlParserException(
+                    "Unexpected end of File.",
+                    null,
+                    key($this->tokens)
+                );
+            }
+        }
+
+        if ($currentVar != null) {
+            $this->query->addResultVar($currentVar);
+        }
+        prev($this->tokens);
+
+        if (count($this->query->getResultVars()) == 0) {
+            throw new SparqlParserException(
+                "Variable or '*' expected.",
+                null,
+                key($this->tokens)
+            );
+        }
+    }//protected function parseSelect()
+
+
+    /**
+    * Adds a new variable to the query and sets result form to 'DESCRIBE'.
+    *
+    * @return void
+    */
+    protected function parseDescribe()
+    {
+        while(strtolower(current($this->tokens))!='from'& strtolower(current($this->tokens))!='where'){
+            $this->_fastForward();
+            if($this->varCheck(current($this->tokens))|$this->iriCheck(current($this->tokens))){
+                $this->query->addResultVar(current($this->tokens));
+                if(!$this->query->getResultForm())
+                    $this->query->setResultForm('describe');
+            }
+            if(!current($this->tokens))
+            break;
+        }
+        prev($this->tokens);
+    }
+
+    /**
+    * Sets result form to 'ASK' and 'COUNT'.
+    *
+    * @param string $form  if it's an ASK or COUNT query
+    * @return void
+    */
+    protected function parseAsk($form){
+        $this->query->setResultForm($form);
+        $this->_fastForward();
+        if(current($this->tokens)=="{")
+            $this->_rewind();
+        $this->parseWhere();
+        $this->parseModifier();
+    }
+
+    /**
+    * Parses the FROM clause.
+    *
+    * @return void
+    * @throws SparqlParserException
+    */
+    protected function parseFrom(){
+        $this->_fastForward();
+        if(strtolower(current($this->tokens))!='named'){
+            if($this->iriCheck(current($this->tokens))||$this->qnameCheck(current($this->tokens))){
+                $this->query->addFrom(new Resource(substr(current($this->tokens),1,-1)));
+            }else if($this->varCheck(current($this->tokens))){
+                $this->query->addFrom(current($this->tokens));
+            }else{
+                throw new SparqlParserException("Variable, Iri or qname expected in FROM ",null,key($this->tokens));
+            }
+            $this->query->addFrom(current($this->tokens));
+        }else{
+            $this->_fastForward();
+            if($this->iriCheck(current($this->tokens))||$this->qnameCheck(current($this->tokens))){
+                $this->query->addFromNamed(new Resource(substr(current($this->tokens),1,-1)));
+            }else if($this->varCheck(current($this->tokens))){
+                $this->query->addFromNamed(current($this->tokens));
+            }else{
+                throw new SparqlParserException("Variable, Iri or qname expected in FROM NAMED ",null,key($this->tokens));
+            }
+        }
+    }
+
+
+    /**
+    * Parses the CONSTRUCT clause.
+    *
+    * @return void
+    * @throws SparqlParserException
+    */
+    protected function parseConstruct(){
+        $this->_fastForward();
+        $this->query->setResultForm('construct');
+        if(current($this->tokens)=="{"){
+            $this->parseGraphPattern(false,false,false,true);
+        }else{
+            throw new SparqlParserException("Unable to parse CONSTRUCT part. '{' expected. ",null,key($this->tokens));
+        }
+        $this->parseWhere();
+        $this->parseModifier();
+    }
+
+
+    /**
+    * Parses the WHERE clause.
+    *
+    * @return void
+    * @throws SparqlParserException
+    */
+    protected function parseWhere(){
+        $this->_fastForward();
+        if(current($this->tokens)=="{"){
+            $this->parseGraphPattern();
+        }else{
+            throw new SparqlParserException("Unable to parse WHERE part. '{' expected in Query. ",null,key($this->tokens));
+        }
+    }
+
+
+
+    /**
+    * Checks if $token is a variable.
+    *
+    * @param  String  $token The token
+    * @return boolean TRUE if the token is a variable false if not
+    */
+    protected function varCheck($token)
+    {
+        if (isset($token[0]) && ($token{0} == '$' || $token{0} == '?')) {
+            $this->query->addUsedVar($token);
+            return true;
+        }
+        return false;
+    }
+
+    /**
+    * Checks if $token is an IRI.
+    *
+    * @param  String  $token The token
+    * @return boolean TRUE if the token is an IRI false if not
+    */
+    protected function iriCheck($token){
+        $pattern="/^<[^>]*>\.?$/";
+        if(preg_match($pattern,$token)>0)
+        return true;
+        return false;
+    }
+
+
+    /**
+    * Checks if $token is a Blanknode.
+    *
+    * @param  String  $token The token
+    * @return boolean TRUE if the token is BNode false if not
+    */
+    protected function bNodeCheck($token){
+        if($token{0} == "_")
+        return true;
+        else
+        return false;
+    }
+
+
+    /**
+    * Checks if $token is a qname.
+    *
+    * @param  String  $token The token
+    * @return boolean TRUE if the token is a qname false if not
+    * @throws SparqlParserException
+    */
+    protected function qnameCheck($token)
+    {
+        $pattern="/^([^:^\<]*):([^:]*)$/";
+        if (preg_match($pattern,$token,$hits)>0) {
+            $prefs = $this->query->getPrefixes();
+            if (isset($prefs{$hits{1}})) {
+                return true;
+            }
+            if ($hits{1} == "_") {
+                return true;
+            }
+            throw new SparqlParserException("Unbound Prefix: <i>".$hits{1}."</i>",null,key($this->tokens));
+        } else {
+            return false;
+        }
+    }
+
+
+
+    /**
+    * Checks if $token is a Literal.
+    *
+    * @param string $token The token
+    *
+    * @return boolean TRUE if the token is a Literal false if not
+    */
+    protected function literalCheck($token)
+    {
+        $pattern = "/^[\"\'].*$/";
+        if (preg_match($pattern,$token) > 0) {
+            return true;
+        }
+        return false;
+    }//protected function literalCheck($token)
+
+
+
+    /**
+    * FastForward until next token which is not blank.
+    *
+    * @return void
+    */
+    protected function _fastForward()
+    {
+        next($this->tokens);
+        while(current($this->tokens)==" "|current($this->tokens)==chr(10)|current($this->tokens)==chr(13)|current($this->tokens)==chr(9)){
+            next($this->tokens);
+        }
+    }//protected function _fastForward()
+
+
+
+    /**
+    * Rewind until next token which is not blank.
+    *
+    * @return void
+    */
+    protected function _rewind()
+    {
+        prev($this->tokens);
+        while(current($this->tokens)==" "|current($this->tokens)==chr(10)|current($this->tokens)==chr(13)|current($this->tokens)==chr(9)){
+            prev($this->tokens);
+        }
+        return;
+    }//protected function _rewind()
+
+
+
+    /**
+    * Parses a graph pattern.
+    *
+    * @param  int     $optional Optional graph pattern
+    * @param  int     $union    Union graph pattern
+    * @param  string  $graph    Graphname
+    * @param  boolean $constr   TRUE if the pattern is a construct pattern
+    * @param  boolean $external If the parsed pattern shall be returned
+    * @param  int     $subpattern If the new pattern is subpattern of the
+    *                               pattern with the given id
+    * @return void
+    */
+    protected function parseGraphPattern(
+      $optional = false, $union    = false, $graph = false,
+      $constr   = false, $external = false, $subpattern = false
+    ){
+        $pattern = $this->query->getNewPattern($constr);
+        if (is_int($optional)) {
+            $pattern->setOptional($optional);
+        } else {
+            $this->tmp = $pattern->getId();
+        }
+        if (is_int($union)) {
+            $pattern->setUnion($union);
+        }
+        if (is_int($subpattern)) {
+            $pattern->setSubpatternOf($subpattern);
+        }
+        if ($graph != false) {
+            $pattern->setGraphname($graph);
+        }
+
+        $this->_fastForward();
+
+        do {
+            switch (strtolower(current($this->tokens))) {
+                case "graph":
+                    $this->parseGraph();
+                    break;
+                case "union":
+                    $this->_fastForward();
+                    $this->parseGraphPattern(
+                        false, $this->tmp, false, false, false, $subpattern
+                    );
+                    break;
+                case "optional":
+                    $this->_fastForward();
+                    $this->parseGraphPattern(
+                        $this->tmp, false, false, false, false, $subpattern
+                    );
+                    break;
+                case "filter":
+                    $this->parseConstraint(
+                        $pattern, true, false, false, false, $subpattern
+                    );
+                    $this->_fastForward();
+                    break;
+                case ".":
+                    $this->_fastForward();
+                    break;
+                case "{":
+                    if (!is_int($subpattern)) {
+                        $subpattern = $pattern->getId();
+                    }
+
+                    $this->parseGraphPattern(
+                        false, false, false, false, false, $subpattern
+                    );
+                    break;
+                case "}":
+                    $pattern->open = false;
+                    break;
+                default:
+                    $this->parseTriplePattern($pattern);
+                    break;
+            }
+        } while ($pattern->open);
+
+        if ($external) {
+            return $pattern;
+        }
+        $this->_fastForward();
+    }
+
+    /**
+    * Parses a triple pattern.
+    *
+    * @param  GraphPattern $pattern
+    * @return void
+    */
+    protected function parseTriplePattern(&$pattern)
+    {
+        $trp      = array();
+        $prev     = false;
+        $prevPred = false;
+        $cont     = true;
+        $sub      = "";
+        $pre      = "";
+        $tmp      = "";
+        $tmpPred  = "";
+        $obj      = "";
+        do {
+//echo strtolower(current($this->tokens)) . "\n";
+            switch (strtolower(current($this->tokens))) {
+                case false:
+                    $cont          = false;
+                    $pattern->open = false;
+                    break;
+                case "filter":
+                    $this->parseConstraint($pattern,false);
+                    $this->_fastForward();
+                    break;
+                case "optional":
+                    $this->_fastForward();
+                    $this->parseGraphPattern($pattern->getId(),false);
+                    $cont = false;
+                    break;
+                case "union":
+                    $this->_fastForward();
+                    $this->parseGraphPattern(
+                        false, $this->tmp, false, false, false, $pattern->getId()
+                    );
+                    break;
+                case ";":
+                    $prev = true;
+                    $this->_fastForward();
+                    break;
+                case ".":
+                    $prev = false;
+                    $this->_fastForward();
+                    break;
+                case "graph":
+                    $this->parseGraph();
+                    break;
+                case ",":
+                    $prev     = true;
+                    $prevPred = true;
+                    $this->_fastForward();
+                    break;
+                case "}":
+                    $prev = false;
+                    $pattern->open = false;
+                    $cont = false;
+                    break;
+                case '{':
+                    //subpatterns opens
+                    $this->parseGraphPattern(
+                        false, false, false, false, false, $pattern->getId()
+                    );
+                    break;
+                case "[":
+                    $prev = true;
+                    $tmp  = $this->parseNode($this->query->getBlanknodeLabel());
+                    $this->_fastForward();
+                    break;
+                case "]":
+                    $prev = true;
+                    $this->_fastForward();
+                    break;
+                case "(":
+                    $prev = true;
+                    $tmp = $this->parseCollection($trp);
+                    $this->_fastForward();
+                    break;
+                case false:
+                    $cont = false;
+                    $pattern->open = false;
+                    break;
+                default:
+                    if ($prev) {
+                        $sub = $tmp;
+                    } else {
+                        $sub = $this->parseNode();
+                        $this->_fastForward();
+                        $tmp     = $sub;
+                    }
+                    if ($prevPred) {
+                        $pre = $tmpPred;
+                    } else {
+                        $pre = $this->parseNode();
+                        $this->_fastForward();
+                        $tmpPred = $pre;
+                    }
+                    if (current($this->tokens)=="[") {
+                        $tmp  = $this->parseNode($this->query->getBlanknodeLabel());
+                        $prev = true;
+                        $obj = $tmp;
+                    } else if (current($this->tokens)=="(") {
+                        $obj = $this->parseCollection($trp);
+                    } else {
+                        $obj = $this->parseNode();
+                    }
+                    $trp[] = new QueryTriple($sub,$pre,$obj);
+                    $this->_fastForward();
+                    break;
+
+            }
+        } while ($cont);
+
+        if (count($trp) > 0) {
+            $pattern->addTriplePatterns($trp);
+        }
+    }
+
+
+
+    /**
+    * Parses a value constraint.
+    *
+    * @param GraphPattern $pattern
+    * @param boolean $outer     If the constraint is an outer one.
+    * @return void
+    */
+    protected function parseConstraint(&$pattern, $outer)
+    {
+        $constraint = new Constraint();
+        $constraint->setOuterFilter($outer);
+        $this->_fastForward();
+        $this->_rewind();
+        $nBeginKey = key($this->tokens);
+        $constraint->setTree(
+            $t = $this->parseConstraintTree()
+        );
+
+        $nEndKey = key($this->tokens);
+        if (current($this->tokens) == '}') {
+            prev($this->tokens);
+        }
+
+        //for backwards compatibility with the normal sparql engine
+        // which does not use the tree array currently
+        $expression = trim(implode(
+            '',
+            array_slice(
+                    $this->tokens,
+                    $nBeginKey + 1,
+                    $nEndKey - $nBeginKey - 1
+            )
+        ));
+        if ($expression[0] == '(' && substr($expression, -1) == ')') {
+            $expression = trim(substr($expression, 1, -1));
+        }
+        $constraint->addExpression($expression);
+
+        $pattern->addConstraint($constraint);
+    }//protected function parseConstraint(&$pattern, $outer)
+
+
+
+    /**
+    *   Parses a constraint string recursively.
+    *
+    *   The result array is one "element" which may contain subelements.
+    *   All elements have one key "type" that determines which other
+    *   array keys the element array has. Valid types are:
+    *   - "value":
+    *       Just a plain value with a value key, nothing else
+    *   - "function"
+    *       A function has a name and an array of parameter(s). Each parameter
+    *       is an element.
+    *   - "equation"
+    *       An equation has an operator, and operand1 and operand2 which
+    *       are elements themselves
+    *   Any element may have the "negated" value set to true, which means
+    *   that is is - negated (!).
+    *
+    *   @internal The functionality of this method is being unit-tested
+    *   in testSparqlParserTests::testParseFilter()
+    *   "equation'-elements have another key "level" which is to be used
+    *   internally only.
+    *
+    *   @return array Nested tree array representing the filter
+    */
+    protected function parseConstraintTree($nLevel = 0, $bParameter = false)
+    {
+        $tree       = array();
+        $part       = array();
+        $chQuotes   = null;
+        $litQuotes  = null;
+        $strQuoted  = '';
+
+        while ($tok = next($this->tokens)) {
+//var_dump(array($tok, $tok[strlen($tok) - 1]));
+            if ($chQuotes !== null && $tok != $chQuotes) {
+                $strQuoted .= $tok;
+                continue;
+            } else if ($litQuotes !== null) {
+                $strQuoted .= $tok;
+                if ($tok[strlen($tok) - 1] == '>') {
+                    $tok = '>';
+                } else {
+                    continue;
+                }
+            } else if ($tok == ')' || $tok == '}' || $tok == '.') {
+                break;
+            }
+
+            switch ($tok) {
+                case '"':
+                case '\'':
+                    if ($chQuotes === null) {
+                        $chQuotes  = $tok;
+                        $strQuoted = '';
+                    } else {
+                        $chQuotes = null;
+                        $part[] = array(
+                            'type'  => 'value',
+                            'value' => $strQuoted,
+                            'quoted'=> true
+                        );
+                    }
+                    continue 2;
+                    break;
+
+                case '>':
+                    $litQuotes = null;
+                    $part[] = array(
+                        'type'  => 'value',
+                        'value' => $strQuoted,
+                        'quoted'=> false
+                    );
+                    continue 2;
+                    break;
+
+                case '(':
+                    $bFunc1 = isset($part[0]['type']) && $part[0]['type'] == 'value';
+                    $bFunc2 = isset($tree['type'])    && $tree['type']    == 'equation'
+                           && isset($tree['operand2']) && isset($tree['operand2']['value']);
+                    $part[] = $this->parseConstraintTree(
+                        $nLevel + 1,
+                        $bFunc1 || $bFunc2
+                    );
+
+                    if ($bFunc1) {
+                        $tree['type']       = 'function';
+                        $tree['name']       = $part[0]['value'];
+                        self::fixNegationInFuncName($tree);
+                        if (isset($part[1]['type'])) {
+                            $part[1] = array($part[1]);
+                        }
+                        $tree['parameter']  = $part[1];
+                        $part = array();
+                    } else if ($bFunc2) {
+                        $tree['operand2']['type']       = 'function';
+                        $tree['operand2']['name']       = $tree['operand2']['value'];
+                        self::fixNegationInFuncName($tree['operand2']);
+                        $tree['operand2']['parameter']  = $part[0];
+                        unset($tree['operand2']['value']);
+                        unset($tree['operand2']['quoted']);
+                        $part = array();
+                    }
+                    continue 2;
+                    break;
+
+                case ' ':
+                case "\t":
+                    continue 2;
+
+                case '=':
+                case '>':
+                case '<':
+                case '<=':
+                case '>=':
+                case '!=':
+                case '&&':
+                case '||':
+                    if (isset($tree['type']) && $tree['type'] == 'equation'
+                        && isset($tree['operand2'])) {
+                        //previous equation open
+                        $part = array($tree);
+                    } else if (isset($tree['type']) && $tree['type'] != 'equation') {
+                        $part = array($tree);
+                        $tree = array();
+                    }
+                    $tree['type']       = 'equation';
+                    $tree['level']      = $nLevel;
+                    $tree['operator']   = $tok;
+                    $tree['operand1']   = $part[0];
+                    unset($tree['operand2']);
+                    $part = array();
+                    continue 2;
+                    break;
+
+                case '!':
+                    if ($tree != array()) {
+                        throw new SparqlParserException(
+                            'Unexpected "!" negation in constraint.'
+                        );
+                    }
+                    $tree['negated'] = true;
+                    continue 2;
+
+                case ',':
+                    //parameter separator
+                    if (count($part) == 0 && !isset($tree['type'])) {
+                        throw new SparqlParserException(
+                            'Unexpected comma'
+                        );
+                    }
+                    $bParameter = true;
+                    if (count($part) == 0) {
+                        $part[] = $tree;
+                        $tree = array();
+                    }
+                    continue 2;
+
+                default:
+                    break;
+            }
+
+            if ($this->varCheck($tok)) {
+                $part[] = array(
+                    'type'      => 'value',
+                    'value'     => $tok,
+                    'quoted'    => false
+                );
+            } else if (substr($tok, 0, 2) == '^^') {
+                $part[count($part) - 1]['datatype']
+                    = $this->query->getFullUri(substr($tok, 2));
+            } else if ($tok[0] == '@') {
+                $part[count($part) - 1]['language'] = substr($tok, 1);
+            } else if ($tok[0] == '<') {
+                if ($tok[strlen($tok) - 1] == '>') {
+                    //single-tokenized <> uris
+                    $part[] = array(
+                        'type'      => 'value',
+                        'value'     => $tok,
+                        'quoted'    => false
+                    );
+                } else {
+                    //iris split over several tokens
+                    $strQuoted = $tok;
+                    $litQuotes = true;
+                }
+            } else if ($tok == 'true' || $tok == 'false') {
+                $part[] = array(
+                    'type'      => 'value',
+                    'value'     => $tok,
+                    'quoted'    => false,
+                    'datatype'  => 'http://www.w3.org/2001/XMLSchema#boolean'
+                );
+            } else {
+                $part[] = array(
+                    'type'      => 'value',
+                    'value'     => $tok,
+                    'quoted'    => false
+                );
+            }
+
+            if (isset($tree['type']) && $tree['type'] == 'equation' && isset($part[0])) {
+                $tree['operand2'] = $part[0];
+                self::balanceTree($tree);
+                $part = array();
+            }
+        }
+
+        if (!isset($tree['type']) && $bParameter) {
+            return $part;
+        } else if (isset($tree['type']) && $tree['type'] == 'equation'
+            && isset($tree['operand1']) && !isset($tree['operand2'])
+            && isset($part[0])) {
+            $tree['operand2'] = $part[0];
+            self::balanceTree($tree);
+        }
+
+        if (!isset($tree['type']) && isset($part[0])) {
+            if (isset($tree['negated'])) {
+                $part[0]['negated'] = true;
+            }
+            return $part[0];
+        }
+
+        return $tree;
+    }//protected function parseConstraintTree($nLevel = 0, $bParameter = false)
+
+
+
+    /**
+    *   "Balances" the filter tree in the way that operators on the same
+    *   level are nested according to their precedence defined in
+    *   $operatorPrecedence array.
+    *
+    *   @param array $tree  Tree to be modified
+    */
+    protected static function balanceTree(&$tree)
+    {
+        if (
+            isset($tree['type']) && $tree['type'] == 'equation'
+         && isset($tree['operand1']['type']) && $tree['operand1']['type'] == 'equation'
+         && $tree['level'] == $tree['operand1']['level']
+         && self::$operatorPrecedence[$tree['operator']] > self::$operatorPrecedence[$tree['operand1']['operator']]
+        ) {
+            $op2 = array(
+                'type'      => 'equation',
+                'level'     => $tree['level'],
+                'operator'  => $tree['operator'],
+                'operand1'  => $tree['operand1']['operand2'],
+                'operand2'  => $tree['operand2']
+            );
+            $tree['operator']   = $tree['operand1']['operator'];
+            $tree['operand1']   = $tree['operand1']['operand1'];
+            $tree['operand2']   = $op2;
+        }
+    }//protected static function balanceTree(&$tree)
+
+
+
+    protected static function fixNegationInFuncName(&$tree)
+    {
+        if ($tree['type'] == 'function' && $tree['name'][0] == '!') {
+            $tree['name'] = substr($tree['name'], 1);
+            if (!isset($tree['negated'])) {
+                $tree['negated'] = true;
+            } else {
+                unset($tree['negated']);
+            }
+            //perhaps more !!
+            self::fixNegationInFuncName($tree);
+        }
+    }//protected static function fixNegationInFuncName(&$tree)
+
+
+
+    /**
+    * Parses a bracketted expression.
+    *
+    * @param  Constraint $constraint
+    * @return void
+    * @throws SparqlParserException
+    */
+    protected function parseBrackettedExpression(&$constraint)
+    {
+        $open = 1;
+        $exp = "";
+        $this->_fastForward();
+        while ($open != 0 && current($this->tokens)!= false) {
+            switch (current($this->tokens)) {
+                case "(":
+                    $open++;
+                    $exp = $exp . current($this->tokens);
+                    break;
+                case ")":
+                    $open--;
+                    if($open != 0){
+                        $exp = $exp . current($this->tokens);
+                    }
+                    break;
+                case false:
+                    throw new SparqlParserException(
+                        "Unexpected end of query.",
+                        null,
+                        key($this->tokens)
+                    );
+                default:
+                    $exp = $exp . current($this->tokens);
+                    break;
+            }
+            next($this->tokens);
+        }
+        $constraint->addExpression($exp);
+    }
+
+
+    /**
+    * Parses an expression.
+    *
+    * @param  Constraint  $constrain
+    * @return void
+    * @throws SparqlParserException
+    */
+    protected function parseExpression(&$constraint)
+    {
+        $exp = "";
+        while (current($this->tokens) != false && current($this->tokens) != "}") {
+            switch (current($this->tokens)) {
+                case false:
+                    throw new SparqlParserException(
+                        "Unexpected end of query.",
+                        null,
+                        key($this->tokens)
+                    );
+                case ".":
+                    break;
+                    break;
+                default:
+                    $exp = $exp . current($this->tokens);
+                    break;
+            }
+            next($this->tokens);
+        }
+        $constraint->addExpression($exp);
+    }
+
+    /**
+    * Parses a GRAPH clause.
+    *
+    * @param  GraphPattern $pattern
+    * @return void
+    * @throws SparqlParserException
+    */
+    protected function parseGraph(){
+        $this->_fastForward();
+        $name = current($this->tokens);
+        if(!$this->varCheck($name)&!$this->iriCheck($name)&&!$this->qnameCheck($name)){
+            $msg = $name;
+            $msg = preg_replace('/</', '&lt;', $msg);
+            throw new SparqlParserException(" IRI or Var expected. ",null,key($this->tokens));
+        }
+        $this->_fastForward();
+
+        if($this->iriCheck($name)){
+            $name = new Resource(substr($name,1,-1));
+        }else if($this->qnameCheck($name)){
+            $name = new Resource($this->query->getFullUri($name));
+        }
+        $this->parseGraphPattern(false,false,$name);
+        if(current($this->tokens)=='.')
+        $this->_fastForward();
+    }
+
+    /**
+    * Parses the solution modifiers of a query.
+    *
+    * @return void
+    * @throws SparqlParserException
+    */
+    protected function parseModifier(){
+        do{
+            switch(strtolower(current($this->tokens))){
+                case "order":
+                $this->_fastForward();
+                if(strtolower(current($this->tokens))=='by'){
+                    $this->_fastForward();
+                    $this->parseOrderCondition();
+                }else{
+                    throw new SparqlParserException("'BY' expected.",null,key($this->tokens));
+                }
+                break;
+                case "limit":
+                $this->_fastForward();
+                $val = current($this->tokens);
+                $this->query->setSolutionModifier('limit',$val);
+                break;
+                case "offset":
+                $this->_fastForward();
+                $val = current($this->tokens);
+                $this->query->setSolutionModifier('offset',$val);
+                break;
+                default:
+                break;
+            }
+        }while(next($this->tokens));
+    }
+
+    /**
+    * Parses order conditions of a query.
+    *
+    * @return void
+    * @throws SparqlParserException
+    */
+    protected function parseOrderCondition(){
+        $valList = array();
+        $val = array();
+        while(strtolower(current($this->tokens))!='limit'
+        & strtolower(current($this->tokens))!= false
+        & strtolower(current($this->tokens))!= 'offset'){
+            switch (strtolower(current($this->tokens))){
+                case "desc":
+                $this->_fastForward();
+                $this->_fastForward();
+                if($this->varCheck(current($this->tokens))){
+                    $val['val'] = current($this->tokens);
+                }else{
+                    throw new SparqlParserException("Variable expected in ORDER BY clause. ",null,key($this->tokens));
+                }
+                $this->_fastForward();
+                if(current($this->tokens)!=')')
+                throw new SparqlParserException("missing ')' in ORDER BY clause.",null,key($this->tokens));
+                $val['type'] = 'desc';
+                $this->_fastForward();
+                break;
+                case "asc" :
+                $this->_fastForward();
+                $this->_fastForward();
+                if($this->varCheck(current($this->tokens))){
+                    $val['val'] = current($this->tokens);
+                }else{
+                    throw new SparqlParserException("Variable expected in ORDER BY clause. ",null,key($this->tokens));
+                }
+                $this->_fastForward();
+                if(current($this->tokens)!=')')
+                throw new SparqlParserException("missing ')' in ORDER BY clause.",null,key($this->tokens));
+                $val['type'] = 'asc';
+                $this->_fastForward();
+                break;
+                default:
+                if($this->varCheck(current($this->tokens))){
+                    $val['val'] = current($this->tokens);
+                    $val['type'] = 'asc';
+                }else{
+                    throw new SparqlParserException("Variable expected in ORDER BY clause. ",null,key($this->tokens));
+                }
+                $this->_fastForward();
+                break;
+            }
+            $valList[] = $val;
+        }
+        prev($this->tokens);
+        $this->query->setSolutionModifier('order by',$valList);
+    }
+
+    /**
+    * Parses a String to an RDF node.
+    *
+    * @param  String $node
+    *
+    * @return Node   The parsed RDF node
+    * @throws SparqlParserException
+    */
+    protected function parseNode($node = false)
+    {
+        //$eon = false;
+        if ($node) {
+            $node = $node;
+        } else {
+            $node = current($this->tokens);
+        }
+        if ($node{strlen($node)-1} == '.') {
+            $node = substr($node,0,-1);
+        }
+        if ($this->dtypeCheck($node)) {
+            return $node;
+        }
+        if ($this->bNodeCheck($node)) {
+            $node = '?'.$node;
+            $this->query->addUsedVar($node);
+            return $node;
+        }
+        if ($node == '[') {
+            $node = '?' . substr($this->query->getBlanknodeLabel(), 1);
+            $this->query->addUsedVar($node);
+            $this->_fastForward();
+            if(current($this->tokens)!=']') {
+                prev($this->tokens);
+            }
+            return $node;
+        }
+        if ($this->iriCheck($node)){
+            $base = $this->query->getBase();
+            if ($base!=null) {
+                $node = new Resource(substr(substr($base,0,-1).substr($node,1),1,-1));
+            } else {
+                $node = new Resource(substr($node,1,-1));
+            }
+            return $node;
+        } else if ($this->qnameCheck($node)) {
+            $node = $this->query->getFullUri($node);
+            $node = new Resource($node);
+            return $node;
+        } else if ($this->literalCheck($node)) {
+            $ch     = substr($node, 0, 1);
+            $chLong = str_repeat($ch, 3);
+            if (substr($node, 0, 3) == $chLong) {
+                $ch = $chLong;
+            }
+            $this->parseLiteral($node, $ch);
+        } else if ($this->varCheck($node)) {
+            $pos = strpos($node,'.');
+            if ($pos) {
+                return substr($node,0,$pos);
+            } else {
+                return $node;
+            }
+        } else if ($node[0] == '<') {
+            //partial IRI? loop tokens until we find a closing >
+            while (next($this->tokens)) {
+                $node .= current($this->tokens);
+                if (substr($node, -1) == '>') {
+                    break;
+                }
+            }
+            if (substr($node, -1) != '>') {
+                throw new SparqlParserException(
+                    "Unclosed IRI: " . $node,
+                    null,
+                    key($this->tokens)
+                );
+            }
+            return $this->parseNode($node);
+        } else {
+            throw new SparqlParserException(
+                '"' . $node . '" is neither a valid rdf- node nor a variable.',
+                null,
+                key($this->tokens)
+            );
+        }
+        return $node;
+    }//protected function parseNode($node = false)
+
+
+
+    /**
+    * Checks if there is a datatype given and appends it to the node.
+    *
+    * @param string $node Node to check
+    *
+    * @return void
+    */
+    protected function checkDtypeLang(&$node, $nSubstrLength = 1)
+    {
+        $this->_fastForward();
+        switch (substr(current($this->tokens), 0, 1)) {
+            case '^':
+                if (substr(current($this->tokens),0,2)=='^^') {
+                    $node = new Literal(substr($node,1,-1));
+                    $node->setDatatype(
+                        $this->query->getFullUri(
+                            substr(current($this->tokens), 2)
+                        )
+                    );
+                }
+                break;
+            case '@':
+                $node = new Literal(
+                    substr($node, $nSubstrLength, -$nSubstrLength),
+                    substr(current($this->tokens), $nSubstrLength)
+                );
+                break;
+            default:
+                prev($this->tokens);
+                $node = new Literal(substr($node, $nSubstrLength, -$nSubstrLength));
+                break;
+
+        }
+    }//protected function checkDtypeLang(&$node, $nSubstrLength = 1)
+
+
+
+    /**
+    * Parses a literal.
+    *
+    * @param String $node
+    * @param String $sep used separator " or '
+    *
+    * @return void
+    */
+    protected function parseLiteral(&$node, $sep)
+    {
+        do {
+            next($this->tokens);
+            $node = $node.current($this->tokens);
+        } while (current($this->tokens) != $sep);
+        $this->checkDtypeLang($node, strlen($sep));
+    }//protected function parseLiteral(&$node, $sep)
+
+
+
+    /**
+    * Checks if the Node is a typed Literal.
+    *
+    * @param String $node
+    *
+    * @return boolean TRUE if typed FALSE if not
+    */
+    protected function dtypeCheck(&$node)
+    {
+        $patternInt = "/^-?[0-9]+$/";
+        $match = preg_match($patternInt,$node,$hits);
+        if($match>0){
+            $node = new Literal($hits[0]);
+            $node->setDatatype(XML_SCHEMA.'integer');
+            return true;
+        }
+        $patternBool = "/^(true|false)$/";
+        $match = preg_match($patternBool,$node,$hits);
+        if($match>0){
+            $node = new Literal($hits[0]);
+            $node->setDatatype(XML_SCHEMA.'boolean');
+            return true;
+        }
+        $patternType = "/^a$/";
+        $match = preg_match($patternType,$node,$hits);
+        if($match>0){
+            $node = new Resource(RDF_NAMESPACE_URI.'type');
+            return true;
+        }
+        $patternDouble = "/^-?[0-9]+.[0-9]+[e|E]?-?[0-9]*/";
+        $match = preg_match($patternDouble,$node,$hits);
+        if($match>0){
+            $node = new Literal($hits[0]);
+            $node->setDatatype(XML_SCHEMA.'double');
+            return true;
+        }
+        return false;
+    }//protected function dtypeCheck(&$node)
+
+
+
+    /**
+    * Parses an RDF collection.
+    *
+    * @param  TriplePattern $trp
+    *
+    * @return Node          The first parsed label
+    */
+    protected function parseCollection(&$trp)
+    {
+        $tmpLabel = $this->query->getBlanknodeLabel();
+        $firstLabel = $this->parseNode($tmpLabel);
+        $this->_fastForward();
+        $i = 0;
+        while (current($this->tokens)!=")") {
+            if($i>0)
+            $trp[] = new QueryTriple($this->parseNode($tmpLabel),new Resource("http://www.w3.org/1999/02/22-rdf-syntax-ns#rest"),$this->parseNode($tmpLabel = $this->query->getBlanknodeLabel()));
+            $trp[] = new QueryTriple($this->parseNode($tmpLabel),new Resource("http://www.w3.org/1999/02/22-rdf-syntax-ns#first"),$this->parseNode());
+            $this->_fastForward();
+            $i++;
+        }
+        $trp[] = new QueryTriple($this->parseNode($tmpLabel),new Resource("http://www.w3.org/1999/02/22-rdf-syntax-ns#rest"),new Resource("http://www.w3.org/1999/02/22-rdf-syntax-ns#nil"));
+        return $firstLabel;
+    }//protected function parseCollection(&$trp)
+
+}// end class: SparqlParser.php
+
+?>
Index: /Dev/trunk/rdfapi/sparql/SparqlParserException.php
===================================================================
--- /Dev/trunk/rdfapi/sparql/SparqlParserException.php	(revision 12)
+++ /Dev/trunk/rdfapi/sparql/SparqlParserException.php	(revision 12)
@@ -0,0 +1,33 @@
+<?php
+// ---------------------------------------------
+// class: SparqlParserExecption
+// ---------------------------------------------
+/**
+* A SPARQL Parser Execption for better errorhandling.
+*
+* @author   Tobias Gauss <tobias.gauss@web.de>
+* @version	 $Id$
+* @license http://www.gnu.org/licenses/lgpl.html LGPL
+*
+* @package sparql
+*/
+Class SparqlParserException extends Exception{
+ 
+	private $tokenPointer;
+
+	public function __construct($message, $code = 0, $pointer){
+
+		$this->tokenPointer = $pointer;
+		parent::__construct($message, $code);
+	}
+
+	/**
+	* Returns a pointer to the token which caused the exception.
+	* @return int
+	*/
+	public function getPointer(){
+		return $this->tokenPointer;
+	}
+
+}
+?>
Index: /Dev/trunk/rdfapi/sparql/SparqlVariable.php
===================================================================
--- /Dev/trunk/rdfapi/sparql/SparqlVariable.php	(revision 12)
+++ /Dev/trunk/rdfapi/sparql/SparqlVariable.php	(revision 12)
@@ -0,0 +1,40 @@
+<?php
+require_once RDFAPI_INCLUDE_DIR . '/model/Node.php';
+require_once RDFAPI_INCLUDE_DIR . '/util/Object.php';
+
+/**
+*   Object representation of a SPARQL variable.
+*   @license http://www.gnu.org/licenses/lgpl.html LGPL
+*/
+class SparqlVariable extends Object
+{
+    public $name;
+
+    public function __construct($name)
+    {
+        $this->name = $name;
+    }
+
+
+
+    public function __toString()
+    {
+        return $this->name;
+    }
+
+
+
+    /**
+    *   Checks if the given subject/predicate/object
+    *   is a variable name.
+    *
+    *   @return boolean
+    */
+    public static function isVariable($bject)
+    {
+        return is_string($bject) && strlen($bject) >= 2
+             && ($bject[0] == '?' || $bject[0] == '$');
+    }//public static function isVariable($bject)
+
+}
+?>
Index: /Dev/trunk/rdfapi/syntax/GRDDLParser.php
===================================================================
--- /Dev/trunk/rdfapi/syntax/GRDDLParser.php	(revision 12)
+++ /Dev/trunk/rdfapi/syntax/GRDDLParser.php	(revision 12)
@@ -0,0 +1,120 @@
+<?php
+// ----------------------------------------------------------------------------------
+// Class: RdfParser
+// ----------------------------------------------------------------------------------
+
+
+/**
+ * A GRDDLParser. 
+ * This class extracts rdf data from xhtml documents. It uses the PHP xsltprocessor.
+ * Gleaning Resource Descriptions from Dialects of Languages (GRDDL):
+ * (http://www.w3.org/TR/grddl/)
+ * 
+ * @version  $Id: GRDDLParser.php 320 2006-11-21 09:38:51Z tgauss $
+ * @author Tobias Gauß <tobias.gauss@web.de>, 
+ *
+ * @package syntax
+ * @access	public
+ *
+ */   
+class GRDDLParser extends Object{
+	
+	
+	/**
+ 	* Document link
+ 	* 
+ 	*
+ 	* @var     String
+ 	* @access	private
+ 	*/
+	var $doclink;
+	
+	
+	/**
+ 	* Stylesheet link
+ 	* 
+ 	*
+ 	* @var     String[]
+ 	* @access	private
+ 	*/
+	var $stylelinks;
+	
+	
+	/**
+ 	* DomDocument
+ 	* 
+ 	* @var     DomDocument
+ 	* @access	private
+ 	*/
+	var $domdoc;
+	
+	
+	/**
+	* generates a MemModel and creates the DomDocument.
+	*
+	* @param String $doc
+	* @access public
+	* @return MemModel $model
+	*/
+	function generateModel($doc){
+		$model = new MemModel();
+		$this->doclink=$doc;
+		$this->domdoc = new DomDocument; 
+		$this->domdoc->load($doc);
+		$this->_getStyles();
+		$model = $this->_generateRDF();
+		return $model;
+	}
+	
+
+	/**
+	* gets the used xsl stylesheets.
+	*
+	* @access private
+	*/
+	function _getStyles(){
+		$link=$this->domdoc->getElementsByTagName('link');
+		$i=0;
+		while($link->item($i)!=''){
+			$item = $link->item($i);
+			if($item->getAttributeNode('rel')->value=='transformation'){
+				$temp = $item->getAttributeNode('href')->value;
+				if(substr($temp,0,1)=='/'){
+					$pos = strrpos($this->doclink,'/');
+					$part = substr($this->doclink,0,$pos);
+					$this->stylelink[]=$part.$temp;
+				}else{
+					$this->stylelink[]=$temp;
+				}
+			}
+			$i++;
+		}
+	}
+	
+	/*
+	* uses the PHP build in xslt processor to
+	* generate the RDF statements and uses the 
+	* RDF- Parser to generate the model
+	*
+	* @access private
+	* @return MemModel $model
+	*/
+	function _generateRDF(){
+		$model=new MemModel();
+		$model->setBaseURI($this->doclink);
+		$proc = new xsltprocessor;
+		include_once(RDFAPI_INCLUDE_DIR.PACKAGE_SYNTAX_RDF);
+		$pars=new RdfParser();
+		foreach($this->stylelink as $key => $value){
+			$xsl = new DomDocument;
+			$xsl->load($value);
+			$proc->importStyleSheet($xsl);
+			$model->addModel($pars->generateModel($proc->transformToXML($this->domdoc),$this->doclink));
+		}
+		return $model;
+	}
+
+	
+	
+}
+?>
Index: /Dev/trunk/rdfapi/syntax/JsonParser.php
===================================================================
--- /Dev/trunk/rdfapi/syntax/JsonParser.php	(revision 12)
+++ /Dev/trunk/rdfapi/syntax/JsonParser.php	(revision 12)
@@ -0,0 +1,54 @@
+<?php
+/**
+ * This class provides capabilities to parse json encoded rdf models.
+ *
+ * @package syntax
+ * @author Philipp Frischmuth <philipp@frischmuth24.de>
+ * @version $Id: JsonParser.php 555 2007-12-11 20:27:34Z p_frischmuth $
+ */
+class JsonParser extends Object {
+	
+	/**
+	 * This method takes a json encoded rdf-model and a reference to aa (usually empty) MemModel, parses the json
+	 * string and adds the statements to the given MemModel.
+	 *
+	 * @param string $jsonString The string that contains the rdf model, encoded as a json-string.
+	 * @param MemModel $model A reference to the model, where to add the statements, usually an empty MemModel.
+	 */
+	public function generateModelFromString($jsonString, $model) {
+		
+		$jsonModel = array();
+		$jsonModel = json_decode($jsonString, true);
+		
+		// throws an excpetion if json model was corrupt
+		if (!is_array($jsonModel)) {
+			throw new Exception('error in json string');
+		}
+		
+		foreach ($jsonModel as $subject=>$remain) {
+			foreach ($remain as $predicate=>$object) {
+				$s = (strpos($subject, '_') === 0) ? new BlankNode(substr($subject, 2)) : new Resource($subject);
+				$p = new Resource($predicate);
+				
+				foreach ($object as $obj) {
+					if ($obj['type'] === 'uri') {
+						$o = new Resource($obj['value']);
+					} else if ($obj['type'] === 'bnode') {
+						$o = new BlankNode(substr($obj['value'], 2));
+					} else {
+						$dtype = (isset($obj['datatype'])) ? $obj['datatype'] : '';
+						$lang = (isset($obj['lang'])) ? $obj['lang'] : '';
+
+						$oVal = $obj['value'];
+
+						$o = new Literal($oVal, $lang);
+						$o->setDatatype($dtype);
+					}
+					
+					$model->add(new Statement($s, $p, $o));
+				}
+			}
+		}
+	}
+}
+?>
Index: /Dev/trunk/rdfapi/syntax/JsonSerializer.php
===================================================================
--- /Dev/trunk/rdfapi/syntax/JsonSerializer.php	(revision 12)
+++ /Dev/trunk/rdfapi/syntax/JsonSerializer.php	(revision 12)
@@ -0,0 +1,163 @@
+<?php
+/**
+ * This class provides capabilities to serialize MemModels to json strings.
+ *
+ * @package syntax
+ * @author Philipp Frischmuth <philipp@frischmuth24.de>
+ * @version $Id: JsonSerializer.php 555 2007-12-11 20:27:34Z p_frischmuth $
+ */
+class JsonSerializer extends Object {
+	
+	/**
+	 * This method takes a MemModel object ad parameter and serializes all contained triples to rdf/json format.
+	 * 
+	 * @see http://n2.talis.com/wiki/RDF_JSON_Specification#rdf.2Fjson
+	 * @param MemModel $model
+	 * @return string Returns a string containing the serialized model.
+	 */
+	public function serialize(MemModel $model) {
+		
+		// create the root json object (root object)
+		$jsonString = '{';
+		$subjects = array();
+		
+		// sort triples by subject
+		foreach ($model->triples as $triple) {
+			$subjects[$triple->toStringSubject()][] = $triple;
+		}
+		
+		// sort alphabetically
+		ksort($subjects);
+			
+		// triples are sorted by subject now, each key is a subject uri, containing all triples with this subject uri
+		$i = 0;
+		foreach ($subjects as $predicatesArray) {
+			$predicates = array();
+			
+			if ($i > 0) {
+				$jsonString .= ',';
+			}
+			$i++;
+			
+			$subj = $predicatesArray[0]->getSubject();
+			
+			// add special _: sequence for blank node only
+			if ($subj instanceof BlankNode) {
+				$jsonString .= '"_:' . $this->_escapeValue($subj->getLabel()) . '":';
+			} else {
+				$jsonString .= '"' . $this->_escapeValue($subj->getLabel()) . '":';
+			}
+			
+			
+			
+			// create a json object for each subject (subject object)
+			$jsonString .= '{';
+			
+			// sort triples with current subject by predicate
+			foreach ($predicatesArray as $triple) {	
+				$predicates[$triple->toStringPredicate()][] = $triple;
+			}
+			
+			// sort alphabetically
+			ksort($predicates);
+			
+			$j = 0;
+			foreach ($predicates as $valueArray) {
+				
+				if ($j > 0) {
+					$jsonString .= ',';
+				}
+				$j++;
+				
+				$jsonString .= '"' . $this->_escapeValue($valueArray[0]->getLabelPredicate()) . '":';
+				
+				// create a json array (value array) 
+				$jsonString .= '[';
+				
+				$k = 0;
+				foreach ($valueArray as $triple) {
+					if ($k > 0) {
+						$jsonString .= ',';
+					}
+					$k++;
+					
+					// create json value object (value object)
+					$jsonString .= '{';
+					
+					$obj = $triple->getObject();
+					
+					// add special _: sequence for blank nodes only
+					if ($obj instanceof BlankNode) {
+						$jsonString .= '"value":"_:' . $this->_escapeValue($obj->getLabel()) . '",';
+					} else if ($obj instanceof Literal) {
+						$jsonString .= '"value":"' . $this->_escapeValue($obj->getLabel()) . '",';
+					} else {
+						$jsonString .= '"value":"' . $this->_escapeValue($obj->getLabel()) . '",';
+					}
+					
+					// add type of object
+					if ($obj instanceof Literal) {
+						$jsonString .= '"type":"literal"';
+					} else if ($obj instanceof BlankNode) {
+						$jsonString .= '"type":"bnode"';
+					} else {
+						$jsonString .= '"type":"uri"';
+					}
+					
+					if ($obj instanceof Literal) {
+						if ($obj->getLanguage() != '') {
+							$jsonString .= ',"lang":"' . $this->_escapeValue($obj->getLanguage()) . '"';
+						}
+						if ($obj->getDatatype() != '') {
+							$jsonString .= ',"datatype":"' . $this->_escapeValue($obj->getDatatype()) . '"';
+						}
+						
+					}
+					
+					// close value object
+					$jsonString .= '}';
+				}
+				
+				// close the value array
+				$jsonString .= ']';
+			}
+			
+			// close the json object (for the subject) (subject object)
+			$jsonString .= '}';
+		}
+		
+		// close root json object (root object)
+		$jsonString .= '}';
+		
+		return $jsonString;
+	}
+	
+	/*
+	 * Escapes the following chars as specified at json.org:
+	 * 
+	 * " -> \"
+	 * \ -> \\
+	 * / -> \/
+	 * \b -> \\b
+	 * \f -> \\f
+	 * \n -> \\n
+	 * \r -> \\r
+	 * \t -> \\t
+	 * \uXXXX -> \\uXXXX
+	 */
+	protected function _escapeValue($value) {
+		
+		
+		$value = str_replace("\\", '\\\\', $value);
+		#$value = str_replace("/", '\/', $value);
+		$value = str_replace("\n", '\\n', $value);
+		$value = str_replace("\t", '\\t', $value);
+		$value = str_replace("\r", '\\r', $value);
+		$value = str_replace("\b", '\\b', $value);
+		$value = str_replace("\f", '\\f', $value);
+		$value = str_replace('"', '\"', $value);
+		
+		return $value;
+	}
+}
+?>
Index: /Dev/trunk/rdfapi/syntax/N3Parser.php
===================================================================
--- /Dev/trunk/rdfapi/syntax/N3Parser.php	(revision 12)
+++ /Dev/trunk/rdfapi/syntax/N3Parser.php	(revision 12)
@@ -0,0 +1,1143 @@
+<?php
+require_once RDFAPI_INCLUDE_DIR . 'util/Object.php';
+require_once RDFAPI_INCLUDE_DIR . 'model/Blanknode.php';
+require_once RDFAPI_INCLUDE_DIR . 'model/Resource.php';
+require_once RDFAPI_INCLUDE_DIR . 'model/Literal.php';
+require_once RDFAPI_INCLUDE_DIR . 'model/Statement.php';
+require_once RDFAPI_INCLUDE_DIR . 'model/MemModel.php';
+require_once RDFAPI_INCLUDE_DIR . 'constants.php';
+
+// ----------------------------------------------------------------------------------
+// Class: N3Parser
+// ----------------------------------------------------------------------------------
+
+
+/**
+ * PHP Notation3 Parser
+ *
+ * This parser can parse a subset of n3, reporting triples to a callback function
+ * or constructing a RAP Model ( http://www.wiwiss.fu-berlin.de/suhl/bizer/rdfapi )
+ *
+ * Supported N3 features:
+ * <ul>
+ *   <li>Standard things, repeated triples ( ; and , ), blank nodes using [ ], self-reference ('<>')</li>
+ *   <li>@prefix mappings</li>
+ *   <li>= maps to owl#sameAs</li>
+ *   <li>a maps to rdf-syntax-ns#type</li>
+ *   <li>Literal datytype- and xmlLanguageTag support
+ * </ul>
+ * Un-supported N3 Features include:
+ * <ul>
+ *   <li>Reification using { }</li>
+ *   <li>. and ^ operators for tree traversal</li>
+ *   <li>Any log operators, like log:forAll etc.</li>
+ * </ul>
+ *
+ * This parser is based on n3.py from Epp released 2nd March, 2002.
+ * by Sean B. Palmer
+ * ( http://infomesh.net/2002/eep/20020302-013802/n3.py )
+ *
+ * This parser is released under the GNU GPL license.
+ * ( http://www.gnu.org/licenses/gpl.txt )
+ *
+ *
+ *
+ * @author Sean B. Palmer <sean@mysterylights.com>
+ * @author Gunnar AA. Grimnes <ggrimnes@csd.abdn.ac.uk>
+ * @author Daniel Westphal <mail@d-westphal.de>
+ * @version $Id: N3Parser.php 569 2008-05-19 05:24:39Z p_frischmuth $
+ * @license GPL http://www.gnu.org/licenses/gpl.txt
+ * @package syntax
+ * @access public
+ **/
+
+class N3Parser extends Object {
+
+
+  /* ==================== Variables ==================== */
+
+  var $Tokens;
+  var $bNode;
+  var $RDF_NS, $DAML_NS, $OWL_NS;
+  var $debug;
+  var $parseError;
+  var $parsedNamespaces = array();
+
+  /* ==================== Public Methods ==================== */
+
+  /**
+   * Constructor
+   * @access public
+   **/
+  function N3Parser() {
+    //Regular expressions:
+     $Name     = '[A-Za-z0-9_@\.]+[^\.,;\[\]\s\) ]*';
+     $URI      = '<[^> ]*>';
+     $bNode    = '_:'.$Name;
+     $Univar   = '\?'.$Name;
+     $QName    = '(?:[A-Za-z][A-Za-z0-9_@\.]*)?:'.$Name;
+     $Literal  = '(?:'
+               . '"(\\\"|[^"])*"'
+               . '|'
+               . "'(\\\'|[^'])*'"
+               . ')';
+               # '"(?:\\"|[^"])*"'
+     $Number   = '[-+]?[0-9]+(\\.[0-9]+)?([eE][-+]?[0-9]+)?';
+     $Boolean  = '@(?:true|false)';
+//   $Literal  = '"[^"\\\\]*(?:\\.\\[^"\\]*)*"'; # '"(?:\\"|[^"])*"'
+     $LangTag  = '@[A-Za-z\-]*[^ \^\.\;\,]';
+     $Datatype = '(\^\^)[^ ,\.;)]+';
+     $Datatype_URI = '(\^\^)'.$URI;
+     //     $LLiteral = '"""[^"\\\\]*(?:(?:.|"(?!""))[^"\\\\]*)*"""';
+     $LLiteral = '(?:'
+                 . '"""[^"\\\\]*(?:(?:\\\\.|"(?!""))[^"\\\\]*)*"""'
+                 . '|'
+                 . "'''[^'\\\\]*(?:(?:\\\\.|'(?!''))[^\"\\\\]*)*'''"
+                 . ')';
+     //          '"""[^"\\]*(?:(?:\\.|"(?!""))[^"\\]*)*"""'
+     $Comment    = '#.*$';
+     $Prefix     = '(?:[A-Za-z][A-Za-z0-9_]*)?:';
+     $PrefixDecl = '@prefix';
+     $WS         = '[ \t]';
+     $this->RDF_NS  = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#'; # for 'a' keyword
+     $this->DAML_NS = 'http://www.daml.org/2001/03/daml+oil#'; # for '=' keyword
+     $this->OWL_NS  = 'http://www.w3.org/2002/07/owl#';
+
+     //     $t = array( $LLiteral, $URI); //, $Literal, $PrefixDecl, $QName, $bNode, $Prefix,
+     //	    $Univar, 'a', '{', '}', '\(', '\)', '\[', '\]', ',', ';', '\.', $WS, $Comment);
+     $t = array(
+            $Datatype_URI, $Datatype, $LLiteral, $URI, $Literal,
+            $PrefixDecl, $QName, $Number, $Boolean, $bNode,
+            $Prefix, $Univar, 'a','=',
+            '{', '}', '\(', '\)', '\[', '\]', ',', ';', '\.',
+            $WS, $Comment,$LangTag
+     );
+     $this->Tokens = "/(".join($t,"|").")/m";
+
+     $this->bNode      = 0;
+     $this->debug      = 0;
+     $this->bNodeMap   = array();
+     $this->FixBnodes  = FIX_BLANKNODES;
+     $this->parseError =false;
+  }
+
+
+  /**
+   * Sets, if BlankNode labels should be replaced by the generic label from the constants.php file
+   * default is "false" -> the used label in n3 is parsed to the model
+   * @param boolean
+   * @access public
+   **/
+  function setFixBnodes($set) {
+
+  	if (($set===true) OR ($set===false)) $this->FixBnodes = $set;
+  }
+
+
+  /**
+   * This parses a N3 string and prints out the triples
+   * @param string $s
+   * @access public
+   **/
+  function parse($s) {
+    //   """Get a string, tokenize, create list, convert to Eep store."""
+    $stat=$this->n3tolist($s);
+    foreach ( $stat as $t) {
+
+      if (count($t)>3) {
+        $object=$t[2];
+
+        for ($i = 3; $i < 5; $i++){
+          if ($t[$i][0]=='@')$object.=$t[$i];
+          if (substr($t[$i],0,2)=='^^')$object.=$t[$i];
+        };
+      } else {$object=$t[2];};
+
+      print '('.$t[0].', '.$t[1].', '.$object.")\n";
+
+    }
+    //   return [[eep.Article(t[0]), eep.Article(t[1]), eep.Article(t[2])]
+    //              for t in n3tolist(s)]
+  }
+
+
+  /**
+   * This parses a N3 string and calls func($subject, $predicate, $object) with each triple
+   * @param string $s
+   * @param string $func
+   * @access public
+   **/
+  function uparse($s,$func) {
+    //   """Get a string, tokenize, create list, convert to Eep store."""
+    $stat=$this->n3tolist($s);
+    foreach ( $stat as $t) {
+
+    	if (count($t)>3) {
+        $object=$t[2];
+
+        for ($i = 3; $i < 5; $i++){
+          if ($t[$i][0]=='@')$object.=$t[$i];
+          if (substr($t[$i],0,2)=='^^')$object.=$t[$i];
+        };
+      } else {$object=$t[2];};
+    	//    print "(".$t[0].", ".$t[1].", ".$t[2].")";
+
+      $func($t[0],$t[1],$object);
+    }
+    //   return [[eep.Article(t[0]), eep.Article(t[1]), eep.Article(t[2])]
+    //              for t in n3tolist(s)]
+  }
+
+
+  /**
+   * This parses a N3 string and returns a memmodel
+   * @param string $s
+   * @access public
+   * @return object Model
+   **/
+
+  function parse2model($s,$model = false) {
+	if($model == false){
+	    $m=new MemModel();
+	}else{
+		$m=$model;
+	}
+    //   """Get a string, tokenize, create list, convert to Eep store."""
+    $stat=$this->n3tolist($s);
+
+    foreach ( $stat as $t) {
+      $s=$this->toRDFNode($t[0],$t);
+      $p=$this->toRDFNode($t[1],$t);
+      $o=$this->toRDFNode($t[2],$t);
+
+       $new_statement= new Statement($s,$p,$o);
+
+      $m->add($new_statement);
+      //    print "(".$t[0].", ".$t[1].", ".$t[2].")";
+    }
+    //   return [[eep.Article(t[0]), eep.Article(t[1]), eep.Article(t[2])]
+    //              for t in n3tolist(s)]
+    $m->addParsedNamespaces($this->parsedNamespaces);
+    return $m;
+  }
+
+/**
+ * Generate a new MemModel from an URI or file.
+ *
+ * @access	public
+ * @param $path
+ * @throws PhpError
+ * @return object MemModel
+ */
+  function & generateModel($path,$dummy=false,$model=false) {
+
+    $handle = fopen($path,'r') or die("N3 Parser: Could not open File: '$path' - Stopped parsing.");
+	$done=false;
+	$input="";
+	while(!$done)
+	{
+	  $input .= fread( $handle, 512 );
+	  $done = feof($handle);
+
+	};
+
+
+    fclose($handle);
+
+    $m = $this->parse2model($input,$model);
+    return $m;
+  }
+  
+  function generateModelFromString($n3String, $model) {
+      
+      $m = $this->parse2model($n3String, $model);
+      $m->addModel($m);
+  }
+
+
+  /* ==================== Private Methods from here ==================== */
+
+  //  General list processing functions
+
+/**
+ * Returns FALSE if argument is a whitespace character
+ * @access private
+ * @param string $s
+ **/
+  function isWS($s) {
+    return !preg_match('/^(#.*|\s*)$/', $s);
+  }
+
+
+
+  /**
+   * Returns true if the string is not a comment
+   * @access private
+   * @param string $s
+   * @returns boolean
+   **/
+  function notComment($s) {
+    if ($s=="") return false;
+    $N3Comment = '^[ \t]*\#';
+
+    if (ereg($N3Comment,$s)) return false;
+    else return true;
+  }
+
+  /**
+   * Removes all whitespace tokens from list
+   * @access private
+   * @param array $list
+   **/
+  function filterWs($list) {
+    //    var_dump($list);
+    //  """Filter whitespace from a list."""
+
+    return array_filter($list, array($this,"isWS"));
+  }
+
+/**
+* converts a string to its unicode NFC form (e.g. \uHHHH or \UHHHHHHHH).
+*
+* @param String $str
+* @return String
+* @access private
+*
+*/
+function str2unicode_nfc($str=""){
+	$result="";
+	/* try to detect encoding */
+	$tmp=str_replace("?", "", $str);
+	if(strpos(utf8_decode($tmp), "?")===false){
+		$str=utf8_decode($str);
+	}
+	for($i=0,$i_max=strlen($str);$i<$i_max;$i++){
+		$nr=0;/* unicode dec nr */
+		/* char */
+		$char=$str[$i];
+		/* utf8 binary */
+		$utf8_char=utf8_encode($char);
+		$bytes=strlen($utf8_char);
+		if($bytes==1){
+			/* 0####### (0-127) */
+			$nr=ord($utf8_char);
+		}
+		elseif($bytes==2){
+			/* 110##### 10###### = 192+x 128+x */
+			$nr=((ord($utf8_char[0])-192)*64) + (ord($utf8_char[1])-128);
+		}
+		elseif($bytes==3){
+			/* 1110#### 10###### 10###### = 224+x 128+x 128+x */
+			$nr=((ord($utf8_char[0])-224)*4096) + ((ord($utf8_char[1])-128)*64) + (ord($utf8_char[2])-128);
+		}
+		elseif($bytes==4){
+			/* 1111#### 10###### 10###### 10###### = 240+x 128+x 128+x 128+x */
+			$nr=((ord($utf8_char[0])-240)*262144) + ((ord($utf8_char[1])-128)*4096) + ((ord($utf8_char[2])-128)*64) + (ord($utf8_char[3])-128);
+		}
+		/* result (see http://www.w3.org/TR/rdf-testcases/#ntrip_strings) */
+		if($nr<9){/* #x0-#x8 (0-8) */
+			$result.="\\u".sprintf("%04X",$nr);
+		}
+		elseif($nr==9){/* #x9 (9) */
+			$result.='\t';
+		}
+		elseif($nr==10){/* #xA (10) */
+			$result.='\n';
+		}
+		elseif($nr<13){/* #xB-#xC (11-12) */
+			$result.="\\u".sprintf("%04X",$nr);
+		}
+		elseif($nr==13){/* #xD (13) */
+			$result.='\t';
+		}
+		elseif($nr<32){/* #xE-#x1F (14-31) */
+			$result.="\\u".sprintf("%04X",$nr);
+		}
+		elseif($nr<34){/* #x20-#x21 (32-33) */
+			$result.=$char;
+		}
+		elseif($nr==34){/* #x22 (34) */
+			$result.='\"';
+		}
+		elseif($nr<92){/* #x23-#x5B (35-91) */
+			$result.=$char;
+		}
+		elseif($nr==92){/* #x5C (92) */
+			$result.='\\';
+		}
+		elseif($nr<127){/* #x5D-#x7E (93-126) */
+			$result.=$char;
+		}
+		elseif($nr<65536){/* #x7F-#xFFFF (128-65535) */
+			$result.="\\u".sprintf("%04X",$nr);
+		}
+		elseif($nr<1114112){/* #x10000-#x10FFFF (65536-1114111) */
+			$result.="\\U".sprintf("%08X",$nr);
+		}
+		else{
+			/* other chars are not defined => ignore */
+		}
+	}
+	return $result;
+}
+
+
+
+  /**
+   * Gets a slice of an array.
+   * Returns the wanted slice, as well as the remainder of the array.
+   * e.g. getSpan(['p', 'q', 'r'], 1, 2) gives (['q'], ['p', 'r'])
+   * @return array
+   * @access private
+   * @param array $list
+   * @param integer $start
+   * @param integer $end
+   **/
+  function getSpan($list, $start, $end) {
+
+    $pre=array_slice($list, 0, $start);
+    $post=array_slice($list, $end);
+
+    return array(array_slice($list, $start,$end-$start),$this->array_concat($pre,$post));
+  }
+
+
+  /**
+   * Concatenates two arrays
+   * @param array $a
+   * @param array $b
+   * @returns array
+   * @access private
+   **/
+  function array_concat($a, $b) {
+    array_splice($a,count($a),0,$b);
+    return $a;
+  }
+
+  /**
+   * Returns an array with all indexes where item appears in list
+   * @param array $list
+   * @param string $item
+   * @returns array
+   * @access private
+   **/
+  function posns($list, $item) {
+    $res=array();
+    $i=0;
+    foreach ( $list as $k=>$v) {
+      if ($v === $item ) $res[]=$i;
+      $i++;
+    }
+    $res[]=$i;
+    return $res;
+  }
+
+
+  /* More N3 specific functions */
+
+  /**
+   * Returns a list of tokens
+   * @param string $s
+   * @returns array
+   * @access private
+   **/
+  function toke($s) {
+
+    //    print "$s\n";
+    //   """Notation3 tokenizer. Takes in a string, returns a raw token list."""
+    if (strlen($s) == 0) die('Document has no content!');
+
+    $s=str_replace("\r\n","\n",$s);
+    $s=str_replace("\r","\n",$s);
+
+
+    //$lines=explode("\n",$s);
+
+    //$reallines=array_filter($lines, array($this, "notComment"));
+    //    print "LINES: ".join($reallines, " ")." :LINES\n";
+    //array_walk($reallines, array($this, "trimLine"));
+    //$res=array();
+
+    //    foreach ($reallines as $l) {
+    //preg_match_all($this->Tokens, $l, $newres);
+    //$res=$this->array_concat($res,$newres[0]);
+    //}
+
+    $res=array();
+    preg_match_all($this->Tokens, $s, $newres);
+    $res=$this->array_concat($res, array_map('trim', $newres[0]));
+//var_dump($newres[0]);
+    return $res;
+  }
+
+  /**
+   * Returns a list with the elements between start and end as one quoted string
+   * e.g. listify(["a","b","c","d"],1,2) => ["a","b c", "d"]
+   * @param array $list
+   * @param integer $start
+   * @param integer $end
+   * @returns array
+   * @access private
+   **/
+  function listify($list, $start, $end) {
+
+    //Re-form a list, merge elements start->end into one quoted element
+    //Start and end are offsets...
+
+    $l=$end-$start;
+
+    $s=array_slice($list, 0, $start);
+    $m=array_slice($list, $start,$l);
+    $e=array_slice($list, $end);
+
+    //  array_push($s,"\"".join($m," ")."\"");
+    array_push($s,$m);
+
+    return $this->array_concat($s,$e);
+  }
+
+  /**
+   * Returns an array with prefixes=>namespace mappings
+   * @param array $list
+   * @access private
+   * @returns array
+   **/
+  function getPrefixes($list) {
+
+    $prefixes=array();
+    $ns=1;
+    $name=2;
+    foreach ($list as $l) {
+      if ($l=='@prefix') {
+	//   while '@prefix' in list {
+
+	$pos=current($list);
+	//pos = list.index('@prefix')
+	$r = $this->getSpan($list, $pos, ($pos+4)); # processes the prefix tokens
+	$binding=$r[0];
+	$list=$r[1];
+	$prefixes[$binding[$ns]] = substr($binding[$name],1,-1);
+	$this->parsedNamespaces[substr($binding[$name],1,-1)] = substr($binding[$ns],0,-1);
+      }
+    }
+
+	if (count($prefixes)<1) $list= array_slice($list,0);
+
+    return array($prefixes, $list);
+  }
+
+  /**
+   * Callback function for replacing "a" elements with the right RDF uri.
+   * @param string $l
+   * @access private
+   **/
+  function replace_a_type(&$l,$p) {
+    if ($l=='a') $l='<'.$this->RDF_NS.'type>';
+  }
+
+  /**
+   * Callback function for replacing "=" elements with the right DAML+OIL uri.
+   * @param string $l
+   * @access private
+   **/
+  function replace_equal(&$l,$p) {
+    if ($l=='=') $l='<'.$this->OWL_NS.'sameAs>';
+  }
+
+  /**
+   * Callback function for replacing "this" elements with the right RDF uri.
+   * @param string $l
+   * @access private
+   **/
+  function replace_this($l,$p) {
+    if ($l=='this') $l='<urn:urn-n:this>';
+  }
+
+    /**
+    * Applies stuff :)
+    * Expands namespace prefixes etc.
+    * @param array $prefixes
+    * @param array $list
+    * @returns $list
+    * @access private
+    **/
+    function applyStuff($prefixes, $list)
+    {
+        array_walk($list, array($this, 'replace_a_type'));
+        array_walk($list, array($this, 'replace_equal'));
+        array_walk($list, array($this, 'replace_this'));
+
+        for ($i = 0; $i < count($list); $i++) {
+
+            if ($list[$i]=='<>') {
+                if (!isset($path)) {
+                    if (!isset($_SERVER['SERVER_ADDR'])) {
+                        $_SERVER['SERVER_ADDR'] = 'localhost';
+                    }
+                    if (!isset($_SERVER['REQUEST_URI'])) {
+                        $_SERVER['REQUEST_URI'] = '/rdfapi-php';
+                    }
+                    $list[$i] = '<http://'.$_SERVER['SERVER_ADDR'].$_SERVER['REQUEST_URI'].'#generate_timestamp_'.time().'>';
+                } else {
+                    $list[$i] = '<'.$path.'>';
+                };
+            };
+
+
+            if (preg_match('/^[-+]?[0-9]+$/', $list[$i])) {
+                //integer
+                $list[$i] = intval($list[$i]);
+            } else if (is_numeric($list[$i])) {
+                //float or decimal
+                // After conversion we cannot distinguish between both
+                $list[$i] = floatval($list[$i]);
+            } else if ((!strstr('<_"\'?.;,{}[]()@', $list[$i]{0}))
+             && (substr($list[$i],0,3) != '^^<')
+            ) {
+                //prefix or unknown
+                $_r   = explode(':', $list[$i]);
+                $ns   = $_r[0] . ':';
+                $name = $_r[1];
+
+                if (isset($prefixes[$ns])) {
+                    $list[$i] = '<'.$prefixes[$ns].$name.'>';
+                } else if (isset($prefixes[substr($ns, 2)])) {
+                    $list[$i] = '^^' . $prefixes[substr($ns, 2)] . $name . '';
+                } else {
+                    //die('Prefix not declared:'.$ns);
+                    $this->parseError = true;
+                    trigger_error('Prefix not declared: '.$ns, E_USER_ERROR);
+                    break;
+                }
+
+            } else {
+                if ($list[$i]{0} == '"') {
+                    $bLiteral = true;
+                    $chBase   = '"';
+                } else if ($list[$i]{0} == '\'') {
+                    $bLiteral = true;
+                    $chBase   = '\'';
+                } else {
+                    $bLiteral = false;
+                }
+                if ($bLiteral) {
+                    $tripleBase = $chBase . $chBase . $chBase;
+                    // Congratulations - it's a literal!
+                    if (substr($list[$i], 0, 3) == $tripleBase) {
+                        if (substr($list[$i],-3,3) == $tripleBase) {
+                            // A big literal...
+                            $lit = substr($list[$i],3,-3);
+                            //	      print "++$lit++";
+                            $lit=str_replace('\n', '\\n',$lit);
+
+                            //$lit=ereg_replace("[^\\]" . $chBase, "\\" . $chBase, $lit);
+                            $lit = stripslashes($lit);
+
+                            $list[$i] = $chBase . $lit . $chBase;
+                        } else {
+                            die ('Incorrect string formatting: '.substr($list[$i],-3,3));
+                        }
+                    } else {
+                        if (strstr($list[$i],"\n")) {
+                            die('Newline in literal: ' . $list[$i]);
+                        }
+                        $list[$i] = stripslashes($list[$i]);
+                    }
+                }
+            }
+
+            if (substr($list[$i],0,2)=='^^') {
+                if ($list[$i][2]!='<') {
+                    $list[$i] = '^^<' . substr($list[$i], 2) . '>';
+                }
+            };
+
+        }//foreach list item
+
+        return $list;
+    }//function applyStuff($prefixes, $list)
+
+
+
+  /**
+   * Returns an array of triples extracted from the list of n3 tokens
+   * @param array $list
+   * @returns array
+   * @access private
+   **/
+  function getStatements($list) {
+
+
+    $statements = array();
+
+    while (in_array('.', $list)) {
+      //  for($i=0;$i<count($list); $i++) {
+      //    if ($list[$i]==".") {
+      //   while '.' in list {
+      $pos=array_search('.',$list);
+
+      $r=$this->getSpan($list, 0, $pos+1);
+
+      $statement=$r[0];
+      $list = $r[1];
+
+      array_pop($statement);
+      $statements[]=$statement;
+    }
+
+    return $statements;
+  }
+
+  /**
+   * Gets a list of triples with same subject
+   * e.g. :Gunnar :firstname "Gunnar" ; :lastname "Grimnes.
+   * @param array $list
+   * @returns array
+   * @acces private
+   **/
+  function getPovs($list) {
+    $povs = array();
+    while (in_array(';', $list)) {
+      $r=$this->posns($list,';');
+      $pos=array_slice($r,0,2);
+      $r = $this->getSpan($list, $pos[0], $pos[1]);
+      $pov=$r[0];
+      $list=$r[1];
+
+      // skip lone semicolons, e.g. "<a> <b> <c> ; ."
+      if (count($pov) == 1) continue;
+
+      $povs[]=array_slice($pov,1);
+    }
+
+    return array($list, $povs);
+  }
+
+  /**
+   * Gets a list of triples with same predicate
+   * e.g. :Gunnar :likes "Cheese", "Wine".
+   * @access private
+   * @param array $list
+   * @returns array
+   **/
+  function getObjs($list) {
+
+
+    $objs = array();
+    while (in_array(",",$list)) {
+      $pos=array_search(",",$list);
+      //  for($i=0;$i<count($list); $i++) {
+      //    if ($list[$i]==",") {
+      //   while ',' in list {
+
+
+      $get_array_fields=2;
+      if (isset ($list[$pos+2])) {
+      	if (@$list[$pos+2][0]=='@') $get_array_fields++;
+        if (@$list[$pos+2][0]=='^') $get_array_fields++;
+      };
+      if (isset ($list[$pos+3])) { if (@$list[$pos+3][0]=='^') $get_array_fields++;};
+
+
+      $r=$this->getSpan($list, $pos, ($pos+$get_array_fields));
+
+      $obj=$r[0];
+      if (!isset($obj[2])) $obj[2]=' ';
+      if (!isset($obj[3])) $obj[3]=' ';
+
+      $list=$r[1];
+
+
+      $objs[]=$obj;
+
+
+    }
+
+    return array($list, $objs);
+  }
+
+  /**
+   * Does the real work, returns a list of subject, predicate, object triples.
+   * @param array $list
+   * @returns array
+   * @access private
+   **/
+  function statementize($list) {
+
+    if (count($list) == 1 && preg_match("/_".BNODE_PREFIX."[0-9]+_/",$list[0])) {
+	if ($this->debug) print "Ignored bNode exists statement. $list\n";
+	return array();
+    }
+
+
+
+    if (count($list) == 3) return array($list);
+    if (count($list) < 3) {
+        throw new Exception(
+            'N3 statement too short,'
+            . ' only ' . count($list) . ' elements instead of 3:' . "\n"
+            . implode("\n", $list)
+        );
+    }
+
+    //Get all ;
+    $r=$this->getPovs($list);
+    $spo=$r[0];
+    $po=$r[1];
+    $all=array();
+
+
+
+    //      (spo, po), all = getPovs(list), []
+    $subject = $spo[0];
+    foreach ($po as $pop) {
+      //  for pop in po {
+      $r=$this->getObjs($pop);
+
+      $myPo=$r[0];
+      $obj=$r[1];
+      //myPo, obj = getObjs(pop)
+
+      if (!isset($myPo[2])) $myPo[2]=' ';
+      if (!isset($myPo[3])) $myPo[3]=' ';
+
+
+      $predicate = $myPo[0];
+      $all[]=array($subject,$predicate,$myPo[1],$myPo[2],$myPo[3]);
+      //    all.append([subject, predicate, myPo[1]])
+
+
+
+      foreach ($obj as $o) $all[]=array($subject,$predicate, $o[1],$o[2],$o[3]);
+      //         for x in obj: all.append([subject, predicate, x])
+
+    }
+
+
+
+    $r = $this->getObjs($spo);
+    $spo=$r[0];
+
+    $objs=$r[1];
+
+    //spo, objs = getObjs(spo)
+    $subject=$spo[0];
+    $predicate=$spo[1];
+
+
+    if(!isset($spo[3])) $spo[3]=' ';
+    if(!isset($spo[4])) $spo[4]=' ';
+
+    $all[]=array($subject, $predicate, $spo[2],$spo[3],$spo[4]);
+
+    foreach ($objs as $obj) $all[]=array($subject, $predicate, $obj[1],$obj[2],$obj[3]);
+
+    return $all;
+  }
+
+  /**
+   * Makes lists of elements in list into a seperate array element.
+   * e.g. doLists(["a","b","[","c","]","d"], "[","]")=> ["a","b", ["c"], "d"]
+   * @param array $list
+   * @param string $schar
+   * @param string $echar
+   * @returns array
+   * @access private
+   **/
+  function doLists($list, $schar, $echar) {
+
+    while (in_array($schar, $list)) {
+      //   while schar in list {
+      $ndict        = array();
+      $nestingLevel = 0;
+      $biggest      = 0;
+      for ($i = 0; $i < count($list); $i++) {
+        if ($list[$i] == $schar) {
+            $nestingLevel += 1;
+            if (!in_array($nestingLevel, array_keys($ndict))) {
+              $ndict[$nestingLevel] = array(array($i));
+            } else {
+              $ndict[$nestingLevel][]=array($i);
+            }
+        }
+        if ($list[$i] == $echar) {
+          if (!in_array($nestingLevel, array_keys($ndict))) {
+            $ndict[$nestingLevel]=array(array($i));
+          } else {
+            $ndict[$nestingLevel][count($ndict[$nestingLevel])-1][]=$i;
+            $nestingLevel-= 1;
+# elif type(list[i]) == type([]) {
+#    list[i] = doLists(list[i], schar, echar)
+          }
+        }
+      }
+      foreach (array_keys($ndict) as $key) {
+        if ($key > $biggest)  $biggest = $key;
+      }
+
+      $tol  = $ndict[$biggest][0];
+      $list = $this->listify($list, $tol[0], ($tol[1]+1));
+    }
+    return $list;
+  }
+
+  /**
+   * Apply doLists for all different types of list.
+   * @param array
+   * @returns array
+   * @access private
+   **/
+  function listStuff($list) {
+# y, z = zip(['[', ']'], ['{', '}'], ['(', ')'])
+# return map(doLists, [list, list, list], y, z).pop()
+    $list = $this->doLists($list, '[', ']');
+    $list = $this->doLists($list, '{', '}');
+    return $this->doLists($list, '(', ')');
+  }
+
+  /**
+   * Generates a new node id.
+   * @access private
+   * @returns string
+   **/
+  function bnodeID() {
+
+    $this->bNode++;
+    return "_".BNODE_PREFIX.$this->bNode."_";
+  }
+
+  /**
+   * This makes bNodes out of variables like _:a etc.
+   * @access private
+   * @param array $list
+   * @returns array
+   **/
+  function fixAnon($list) {
+//    $map=array();
+    for($i=0;$i<count($list);$i++) {
+      $l=$list[$i];
+      if (substr($l,0,2)=="_:") {
+	  if (!isset($this->bNodeMap[$l])) {
+	  $a=$this->bnodeID();
+	  $this->bNodeMap[$l]=$a;
+	} else $a=$this->bNodeMap[$l];
+	$list[$i]=$a;
+      }
+    }
+    return $list;
+  }
+
+  /**
+   * This makes [ ] lists into bnodes.
+   * @access private
+   * @param array $list
+   * @return array
+   **/
+  function expandLists($list) {
+
+    for($i=0;$i<count($list);$i++) {
+      if (is_array($list[$i])) {
+	if ( $list[$i][0]=='[' ) {
+	  $bnode=$this->bnodeID();
+	  $prop=$list[$i];
+	  $list[$i]=$bnode;
+	  $list[]=$bnode;
+	  $list=$this->array_concat($list, array_slice($prop,1,-1));
+	  $list[]='.';
+	}elseif($list[$i][0]=='(') {
+
+	    $rdfNil = '<'. RDF_NAMESPACE_URI . RDF_NIL .'>';
+	    $rdfFirst = '<'. RDF_NAMESPACE_URI . RDF_FIRST .'>';
+	    $rdfRest = '<'. RDF_NAMESPACE_URI . RDF_REST .'>';
+
+	    // local copy of list without "(" and ")"
+	    $t_list = array_slice($list[$i], 1, -1);
+
+	    //prepare bnodes
+	    $fromBnode = $this->bnodeID();
+	    $toBnode = $this->bnodeID();
+
+	    //link first bnode into graph
+	    $list[$i] = $fromBnode;
+
+	    $count = count($t_list);
+
+	    //loop through list, convert to RDF linked list
+	    for ($idx = 0; $idx < $count; $idx++){
+
+	        // set rdf:first
+	        $list[] = $fromBnode;
+	        $list[] = $rdfFirst;
+	        $list[] = $t_list[$idx];
+	        $list[] = '.';
+
+	        // set rdf:rest (nil or next bnode)
+	        if ($idx == $count - 1) {
+	            $list[] = $fromBnode;
+	            $list[] = $rdfRest;
+	            $list[] = $rdfNil;
+	            $list[] = '.';
+	        }
+	        else {
+	            $list[] = $fromBnode;
+	            $list[] = $rdfRest;
+	            $list[] = $toBnode;
+	            $list[] = '.';
+
+	            $fromBnode = $toBnode;
+	            $toBnode = $this->bnodeID();
+	        }
+	    }
+	}
+	else {
+	    die('Only [ ] and () lists are supported!');
+	}
+    }
+
+
+    }
+    return $list;
+  }
+
+  /**
+   * Main work-horse function. This converts a N3 string to a list of statements
+   * @param string $s
+   * @returns array
+   * @access private
+   **/
+  function n3tolist($s) {
+
+    //   """Convert an N3 string into a list of triples as strings."""
+    $result = array();
+
+   $t = $this->filterWs($this->toke($s)); # tokenize the stream, and filter whitespace tokens
+
+    if ($this->debug) {
+      print "Filter WS:\n";
+      var_dump($t);
+    }
+    $r=$this->getPrefixes($t); # get the prefix directives, and add to a dict
+    $prefixes=$r[0];
+    $t=$r[1];
+    if ($this->debug) {
+      print "Prefixes:\n";
+      var_dump($prefixes);
+      print "***\n";
+      var_dump($t);
+    }
+    $t=$this->applyStuff($prefixes, $t);#apply prefixes, keywords, and string formatting
+    if ($this->debug) {
+      print "Stuff applied:\n";
+      var_dump($t);
+    }
+
+    $t=$this->fixAnon($t); # fix _:a anons
+    if ($this->debug) {
+      print "Fix anon:\n";
+      var_dump($t);
+    }
+
+    $t = $this->listStuff($t); # apply list stuff: todo
+    if ($this->debug) {
+      print "Lists done:\n";
+      var_dump($t);
+    }
+    $t=$this->expandLists($t);
+    if ($this->debug) {
+      print "Lists applied:\n";
+      var_dump($t);
+    }
+    $t = $this->getStatements($t); # get all of the "statements" from the stream
+
+    foreach ($t as $stat) {
+      $stats = $this->statementize($stat);
+
+      foreach ($stats as $y) {
+        $result[]=$y;
+      }
+    }
+
+    //   for x in [statementize(stat) for stat in t] {
+    //      for y in x: result.append(y)
+    return $result;
+  }
+
+
+
+    /**
+     * Constructs a RAP RDFNode from URI/Literal/Bnode
+     * @access private
+     * @param string $s
+     * @returns object RDFNode
+     **/
+    function toRDFNode($s, $state)
+    {
+        $ins = substr($s, 1, -1);
+        if ($s{0} == '"' || $s{0} == '\'') {
+            $lang = NULL;
+
+            if (count($state)>3) {
+                for ($i = 3; $i < count($state); $i++) {
+                    if ($state[$i][0]=='@') {
+                        $lang = substr($state[3], 1);
+                    }
+                    if (substr($state[$i],0,2) == '^^') {
+                        $dtype = substr($state[$i],2);
+                        if ($dtype[0]=='<') {
+                            $dtype = substr($dtype,1,-1);
+                        }
+                    }
+                }
+            }
+
+
+            if (UNIC_RDF) {
+                $ins = $this->str2unicode_nfc($ins);
+            }
+            $new_Literal = new Literal($ins, $lang);
+            if (isset($dtype)) {
+                $new_Literal->setDatatype($dtype);
+            }
+            return  $new_Literal;
+        } else if (is_int($s)) {
+            $value = new Literal($s);
+            $value->setDatatype(XML_SCHEMA . 'integer');
+            return $value;
+        } else if (is_float($s)) {
+            $value = new Literal($s);
+            $value->setDatatype(XML_SCHEMA . 'double');
+            return $value;
+        } else if ($s == '@true') {
+            $value = new Literal(true);
+            $value->setDatatype(XML_SCHEMA . 'boolean');
+            return $value;
+        } else if ($s == '@false') {
+            $value = new Literal(false);
+            $value->setDatatype(XML_SCHEMA . 'boolean');
+            return $value;
+        }
+
+        if (strstr($s, '_' . BNODE_PREFIX)) {
+            if (($this->FixBnodes) || (!array_search($s,$this->bNodeMap))) {
+                return new BlankNode($ins);
+            } else {
+                return new BlankNode(
+                    trim(
+                        substr(
+                            array_search($s, $this->bNodeMap),
+                            2
+                        )
+                    )
+                );
+            };
+        }
+
+        return new Resource($ins);
+    }//function toRDFNode($s, $state)
+
+
+
+
+} //end: N3Parser
+
+?>
Index: /Dev/trunk/rdfapi/syntax/N3Serializer.php
===================================================================
--- /Dev/trunk/rdfapi/syntax/N3Serializer.php	(revision 12)
+++ /Dev/trunk/rdfapi/syntax/N3Serializer.php	(revision 12)
@@ -0,0 +1,526 @@
+<?php
+
+// ----------------------------------------------------------------------------------
+// Class: N3Serializer
+// ----------------------------------------------------------------------------------
+
+/**
+ * PHP Notation3 Serializer
+ *
+ * This class serialises models to N3 Syntax.
+ *
+ * Supported N3 features:
+ * <ul>
+ *   <li>Using [ ] for blank nodes, or _: if necessary</li>
+ *   <li>Literal datatype- and xmlLanguageTag support</li>
+ * </ul>
+ *
+ * Un-supported N3 Features include:
+ * <ul>
+ *   <li>Reification</li>
+ * </ul>
+ *
+ *
+ * @author Gunnar AA. Grimnes <ggrimnes@csd.abdn.ac.uk>
+ * @author Daniel Westphal <mail@d-westphal.de>
+ * @author Christian Weiske <cweiske@cweiske.de>
+ * @version $Id: N3Serializer.php 556 2008-01-22 10:52:48Z fusel2k $
+ * @package syntax
+ * @access public
+ **/
+
+define('MAGIC_STRING', '~~~');
+
+class N3Serializer extends Object
+{
+
+    var $debug = false;
+
+    var $prefixes   = array();
+    var $noPrefixes = array();
+
+    var $done;  // keeps track of already serialized resources
+    var $resourcetext;
+    var $resourcetext_taken;
+    var $model;
+    var $res;
+    var $anon;
+
+    var $styleCompress = false;
+    var $stylePretty   = false;
+    var $styleNest     = false;
+
+    /**
+    * Constructor
+    *
+    * @access   public
+    */
+    function N3Serializer()
+    {
+        $this->debug = false;
+    }
+
+
+    /**
+    * Adds a new namespace prefix to use.
+    * Unknown namespaces will become ns0, ns1 etc.
+    * @access public
+    * @param string $s
+    * @returns void
+    **/
+    function addNSPrefix($ns, $prefix)
+    {
+        $this->prefixes[$ns] = $prefix;
+    }
+
+
+
+    /**
+    * Clears all previously set namespace prefixes
+    */
+    function clearNSPrefixes()
+    {
+        $this->prefixes = array();
+    }
+
+
+
+    /**
+    *   Add a namespace that shall not get shortened by using a prefix.
+    *
+    *   @param string $ns Namespace URI like "http://example.com/"
+    */
+    function addNoNSPrefix($ns)
+    {
+        $this->noPrefixes[$ns] = true;
+    }
+
+
+
+    /**
+    * Clears all previously set noNamespace prefixes
+    */
+    function clearNoNSPrefixes()
+    {
+        $this->noPrefixes = array();
+    }
+
+
+
+    /**
+    * Serializes a model to N3 syntax.
+    *
+    * @param     object Model $model
+    * @return    string
+    * @access    public
+    */
+    function &serialize(&$m)
+    {
+        if (is_a($m, 'DbModel')) {
+            $m=$m->getMemModel();
+        }
+
+        $this->reset();
+        $this->model = $m;
+        $this->res   = "";
+
+        // copy default namespaces
+        global $default_prefixes;
+        foreach($default_prefixes as $prefix => $namespace) {
+            $this->addNSPrefix($namespace,$prefix);
+        }
+
+        $nps= $this->model->getParsedNamespaces();
+        if ($nps!=false) {
+            foreach ($nps as $uri => $prefix){
+                $this->addNSPrefix($uri,$prefix);
+            }
+        }
+
+        $namespaces = array();
+        $count      = array();
+        $resources  = array();
+        foreach ($this->model->triples as $t) {
+            $s = $t->getSubject();
+            if (is_a($s, 'Resource')) {
+                $namespaces[$s->getNamespace()] = 1;
+            }
+            $p = $t->getPredicate();
+            if (is_a($p, 'Resource')) {
+                $namespaces[$p->getNamespace()] = 1;
+            }
+            $o = $t->getObject();
+            if (is_a($o, 'Resource')) {
+                $namespaces[$o->getNamespace()] = 1;
+            }
+            $uri = $s->getURI();
+
+            if (isset($count[$uri])) {
+                $count[$uri]++;
+            } else {
+                $count[$uri]     = 0;
+                $resources[$uri] = $s;
+            }
+
+            if ($this->styleNest && is_a($s, 'BlankNode')) {
+                //make sure blank nodes are sorted *after* normal nodes
+                //so that they can be included
+                $count[$uri] -= 0.00001;
+            }
+        }
+
+        if (!HIDE_ADVERTISE) {
+            $this->res .= '# Generated by N3Serializer.php from RDF RAP.'.LINEFEED
+                        .'# http://www.wiwiss.fu-berlin.de/suhl/bizer/rdfapi/index.html'
+                        .LINEFEED.LINEFEED;
+        }
+
+        $this->doNamespaces($namespaces);
+
+        $this->res .= LINEFEED.LINEFEED;
+
+        arsort($count);
+
+        foreach ( $count as $k => $v) {
+            $this->doResource($resources[$k]);
+            //      $this->res.=" .\n";
+        }
+
+        //make all replacements
+        do {
+            $bReplacements = false;
+            foreach ($this->resourcetext as $r => $t) {
+                if (preg_match_all('/'.MAGIC_STRING.'([^ ]+)'.MAGIC_STRING.'/', $t, $ms, PREG_SET_ORDER)) {
+                    foreach ($ms as $mseach) {
+                        $rp = $this->resourcetext[$mseach[1]];
+                        $this->resourcetext[$r] = preg_replace('/'.MAGIC_STRING.$mseach[1].MAGIC_STRING.'/', $rp, $t);
+                        $bReplacements = true;
+                    }
+                }
+
+            }
+        } while ($bReplacements);
+
+        //after all replacements took place, put the lines out
+        $c = 0;
+        foreach ($this->resourcetext as $r => $t) {
+            if ($this->debug) {
+                $this->res .= $c . ': ';
+            }
+            if (!(isset($this->resourcetext_taken[$r]) && $this->resourcetext_taken[$r]>0)) {
+                $this->res .= $t . ' .' . LINEFEED;
+                if ($this->stylePretty) {
+                    $this->res .= LINEFEED;
+                }
+            } else if ($this->debug ) {
+                $this->res.=' Skipping : '.$t.LINEFEED;
+            }
+            $c++;
+        }
+
+    //     $max=-1111;
+    //     $maxkey="";
+    //     foreach ($count as $k=>$c) {
+    //       if ( $c>$max) { $maxkey=$k; $max=$c; }
+    //     }
+
+    //     if ($this->debug) {
+    //       print "$maxkey is subject of most triples! ($max) \n";
+    //     }
+
+        return $this->res;
+    }//function &serialize(&$m)
+
+
+
+    /**
+    * Serializes a model and saves it into a file.
+    * Returns FALSE if the model couldn't be saved to the file.
+    *
+    * @param     object MemModel $model
+    * @param     string $filename
+    * @return    boolean
+    * @access    public
+    */
+    function saveAs(&$model, $filename)
+    {
+        // serialize model
+        $n3 = $this->serialize($model);
+
+        // write serialized model to file
+        $file_handle = @fopen($filename, 'w');
+        if ($file_handle) {
+            fwrite($file_handle, $n3);
+            fclose($file_handle);
+            return true;
+        } else {
+            return false;
+        };
+    }
+
+
+
+    /**
+    * Set to true, if the N3 serializer should try to compress the blank node
+    *  syntax using [] whereever possible.
+    */
+    function setCompress($compress)
+    {
+        $this->styleCompress = $compress;
+    }
+
+
+
+    /**
+    * Enables pretty printing in semicolon delimited sentences.
+    */
+    function setPrettyPrint($prettyPrint)
+    {
+        $this->stylePretty = $prettyPrint;
+    }
+
+
+
+    /**
+    * Enables nesting of blank nodes with [] if
+    * compression is activated via @see setCompress
+    */
+    function setNest($nest)
+    {
+        $this->styleNest = $nest;
+    }
+
+  /* ==================== Private Methods from here ==================== */
+
+
+    /**
+    * Readies this object for serializing another model
+    * @access private
+    * @param void
+    * @returns void
+    **/
+    function reset()
+    {
+        $this->anon               = 0;
+        $this->done               = array();
+        $this->resourcetext_taken = array();
+        $this->resourcetext       = array();
+        $this->res                = '';
+        $this->model              = null;
+    }
+
+
+
+    /**
+    * Makes ns0, ns1 etc. prefixes for unknown prefixes.
+    * Outputs @prefix lines.
+    * @access private
+    * @param array $n
+    * @returns void
+    **/
+    function doNamespaces(&$n)
+    {
+        $c = 0;
+        foreach ($n as $ns => $nonsense) {
+            if (!$ns || isset($this->noPrefixes[$ns])) {
+                continue;
+            }
+            if (isset($this->prefixes[$ns])) {
+                $p = $this->prefixes[$ns];
+            } else {
+                $p = 'ns' . $c;
+                $this->prefixes[$ns] = $p;
+                $c++;
+            }
+            $this->res .= "@prefix $p: <".$ns.'> .'.LINEFEED;
+        }
+    }
+
+
+
+    /**
+    * Fill in $resourcetext for a single resource.
+    * Will recurse into Objects of triples, but should never look ? (really?)
+    * @param object Resource $r
+    * @returns boolean
+    * @access private
+    **/
+    function doResource(&$r, $bEmbedded = false, $strIndent = '    ')
+    {
+        //var_dump($r->getURI());
+
+        $ts = $this->model->find($r, null, null);
+        if (count($ts->triples) == 0) {
+            if ($bEmbedded) {
+                $this->resourcetext[$r->getURI()] = '_:' . $r->getLabel();
+            }
+            return;
+        }
+
+        $out = '';
+
+        if (isset($this->done[$r->getURI()]) && $this->done[$r->getURI()]) {
+            if (!$this->styleNest && is_a($r, 'BlankNode')) {
+                if ($this->resourcetext_taken[$r->getURI()] == 1) {
+                    //Oh bother, we must use the _:blah construct.
+                    $a = $this->resourcetext[$r->getURI()];
+                    $this->resourcetext[$r->getURI()]='_:anon'.$this->anon;
+                    $this->resourcetext['_:anon'.$this->anon]=$this->fixAnon($a, '_:anon'.$this->anon);
+                    $this->resourcetext_taken[$r->getURI()]=2;
+                    $this->anon++;
+                }
+            }
+            return false;
+        }
+
+        $this->done[$r->getURI()] = true;
+        $compress = false;
+
+        if (is_a($r, 'Resource')) {
+            if (is_a($r, 'BlankNode')) {
+                //test if this blanknode is referenced somewhere
+                $rbn      = $this->model->find(null, null, $r);
+                $compress = (N3SER_BNODE_SHORT || $this->styleCompress)
+                            && (
+                                count($rbn->triples) == 0
+                                || (count($rbn->triples) == 1 && $bEmbedded)
+                            );
+                if ($compress) {
+                    $out.='[';
+                } else {
+                    $out.='_:'.$r->getLabel();
+                }
+            } else {
+                $this->doURI($r, $out);
+            }
+        }
+
+        usort($ts->triples, 'statementsorter');
+        $lastp = '';
+        $out  .= ' ';
+
+        foreach ($ts->triples as $t) {
+            $p = $t->getPredicate();
+
+            if ($p === $lastp) {
+                $out .= ' , ';
+            } else {
+                if ($lastp!='') {
+                    if ($this->stylePretty) {
+                        $out .= ";\n" . $strIndent;
+                    } else {
+                        $out .= ' ; ';
+                    }
+                }
+                $this->doURI($p, $out);
+                $lastp = $p;
+            }
+
+            $out .= ' ';
+
+            $o = $t->getObject();
+
+            if (is_a($o, 'Literal')) {
+                $l = $o->getLabel();
+                if (strpos($l, LINEFEED) === false) {
+                    $long = false;
+                } else {
+                    $long = true;
+                }
+
+                //try to be intelligent
+                $quoteSingle = strpos($l, '\'') !== false;
+                $quoteDouble = strpos($l, '"')  !== false;
+                if ($quoteSingle && !$quoteDouble) {
+                    $quoteChar = $long ? '"""' : '"';
+                } else if ($quoteDouble && !$quoteSingle) {
+                    $quoteChar = $long ? '\'\'\'' : '\'';
+                } else if ($quoteDouble && $quoteSingle) {
+                    //both quotation chars inside
+                    $quoteChar = $long ? '"""' : '"';
+                    $l = addslashes($l);
+                } else {
+                    //no quotation chars
+                    $quoteChar = $long ? '"""' : '"';
+                }
+                $out .= $quoteChar . $l . $quoteChar;
+
+                if ( $o->getLanguage()!='' ) {
+                    $out.='@'.$o->getLanguage();
+                }
+                if ( $o->getDatatype()!='' ) {
+                    $out.='^^<'.$o->getDatatype().'>';
+                }
+            }
+
+            if (is_a($o, 'Resource')) {
+                if ($this->debug) {
+                    print 'Doing object: '.$o->getURI().LINEFEED;
+                }
+                if (is_a($o, 'BlankNode')) {
+                    if ($this->styleNest && $this->styleCompress
+                     && !isset($this->done[$o->getURI()])
+                    ) {
+                        $this->doResource($o, true, $strIndent . '    ');
+                        $out .= MAGIC_STRING . $o->getURI() . MAGIC_STRING;
+                        //$out .= $this->resourcetext[$o->getURI()];
+                        $this->resourcetext_taken[$o->getURI()] = 1;
+                    } else {
+                        $out .= '_:'.$o->getLabel();
+                    }
+                } else {
+                    $this->doURI($o, $out);
+                }
+            }
+        }
+
+        if ($compress) {
+            $out .= ' ]';
+        };
+
+        $this->resourcetext[$r->getURI()]=$out;
+
+        return true;
+    }//function doResource(&$r)
+
+
+
+    /**
+    * Format a single URI
+    * @param string $s
+    * @return void
+    * @access private
+    **/
+    function doURI(&$r, &$out)
+    {
+        if ($r->getURI() == 'http://www.w3.org/1999/02/22-rdf-syntax-ns#type') {
+            $out .= 'a';
+            return;
+        }
+        $ns = $r->getNamespace();
+        if ($ns != '' && !isset($this->noPrefixes[$ns])) {
+            $out .= $this->prefixes[$ns].':'.$r->getLocalName();
+        } else {
+            //Will this ever happen? It does, now.
+            $out .= '<' . $r->getURI() . '>';
+        }
+    }
+
+
+
+    /**
+    * Fix the resourcetext for a blanknode where the _: construct was used
+    * @param string $s
+    * @param string $a
+    * @access private
+    * @return void
+    **/
+    function fixAnon($t,$a)
+    {
+        $t = preg_replace("/( \] $|^\[ )/", '', $t);
+        return $a . $t;
+    }
+
+}
+
+?>
Index: /Dev/trunk/rdfapi/syntax/NTripleSerializer.php
===================================================================
--- /Dev/trunk/rdfapi/syntax/NTripleSerializer.php	(revision 12)
+++ /Dev/trunk/rdfapi/syntax/NTripleSerializer.php	(revision 12)
@@ -0,0 +1,133 @@
+<?php
+
+// ----------------------------------------------------------------------------------
+// Class: NTripleSerializer
+// ----------------------------------------------------------------------------------
+
+
+/**
+ * PHP N-Triple Serializer
+ * 
+ * This class serialises models to N-Triple Syntax.
+ * 
+ *
+ *
+ * @author Daniel Westphal <mail@d-westphal.de>
+ * @version $Id: NTripleSerializer.php 268 2006-05-15 05:28:09Z tgauss $
+ * @package syntax
+ * @access public
+ **/
+
+
+
+class NTripleSerializer extends Object {
+
+  var $debug; 
+  var $model;
+  var $res; 
+
+  
+  
+  
+
+   /**
+    * Constructor
+    *
+    * @access   public
+    */
+  function NTripleSerializer() { 
+    $this->debug=FALSE;
+  }
+ 
+  /**
+   * Serializes a model to N Triple syntax.
+   *
+   * @param     object Model $model
+   * @return    string
+   * @access    public
+   */
+  function & serialize(&$m) { 
+
+        if (is_a($m, 'DbModel')) $m = $m->getMemModel();
+    
+    $this->reset();
+    if (!HIDE_ADVERTISE) {
+        $this->res .= '# Generated by NTripleSerializer.php from RDF RAP.' .
+            LINEFEED . '# http://www.wiwiss.fu-berlin.de/suhl/bizer/rdfapi/index.html'.
+            LINEFEED . LINEFEED;
+    }
+
+    foreach ($m->triples as $t) { 
+
+      $s=$t->getSubject();
+      if (is_a($s, 'Blanknode')) {
+      	$subject='_:'.$s->getURI();
+      } else {
+          $subject = '<' . preg_replace("' '", "''", $s->getURI()) . '>';
+      }
+
+	  $p=$t->getPredicate();  
+	  $predicate='<'.preg_replace("' '", "''", $p->getURI()).'>';
+
+	  $o=$t->getObject();     
+      if (is_a($o, 'literal')) {
+	  	$object='"'.$o->getLabel().'"';
+	  	if ($o->getLanguage()!='') $object.='@'.$o->getLanguage();		  	
+	  	if ($o->getDatatype()!='') $object.='^^<'.$o->getDatatype().">";		  	
+	  } elseif (is_a($o, 'Blanknode')) {
+	    $object='_:'.$o->getURI();
+	  } else {$object='<'.preg_replace("' '", "''", $o->getURI()).'>';};	
+		
+      $this->res.=$subject.' '.$predicate.' '.$object.' .';
+      $this->res.=LINEFEED.LINEFEED;
+    }
+   
+    return $this->res;
+  } 
+  
+
+/**
+ * Serializes a model and saves it into a file.
+ * Returns FALSE if the model couldn't be saved to the file.
+ *
+ * @access	public
+ * @param     object MemModel $model
+ * @param     string $filename
+ * @return    boolean
+ * @access    public
+ */
+ function  saveAs(&$model, $filename) {
+
+   // serialize model
+   $n3 = $this->serialize($model);
+
+   // write serialized model to file
+   $file_handle = @fopen($filename, 'w');
+   if ($file_handle) {
+      fwrite($file_handle, $n3);
+      fclose($file_handle);
+      return TRUE;
+   }else{
+      return FALSE;
+   };
+ }
+  
+
+  /* ==================== Private Methods from here ==================== */
+
+
+/**
+ * Readies this object for serializing another model
+ * @access private
+ * @param void
+ * @returns void 
+ **/
+  function reset() {
+    $this->res="";
+    $this->model=NULL;
+  }
+
+}
+
+
+?>
Index: /Dev/trunk/rdfapi/syntax/RdfParser.php
===================================================================
--- /Dev/trunk/rdfapi/syntax/RdfParser.php	(revision 12)
+++ /Dev/trunk/rdfapi/syntax/RdfParser.php	(revision 12)
@@ -0,0 +1,2365 @@
+<?php
+
+// ----------------------------------------------------------------------------------
+// Class: RdfParser
+// ----------------------------------------------------------------------------------
+
+
+/**
+ * An RDF paser.
+ * This class reads RDF data from files or URIs and generates models out of it. All valid
+ * RDF XML syntaxes defined by the W3C in RDF/XML Syntax Specification (Revised)
+ * - W3C Working Draft 10 October 2003
+ * (http://www.w3.org/TR/2003/WD-rdf-syntax-grammar-20031010/) are supported.
+ * The parser is based on the PHP version of repat
+ * (http://phpxmlclasses.sourceforge.net/show_doc.php?class=class_rdf_parser.html)
+ * by Luis Argerich (lrargerich@yahoo.com).
+ *
+ * @version  $Id: RdfParser.php 493 2007-08-12 17:43:07Z cweiske $
+ * @author Luis Argerich <lrargerich@yahoo.com>,
+ *         Chris Bizer <chris@bizer.de>,
+ *         Radoslaw Oldakowski <radol@gmx.de>
+ *		   Daniel Westphal <mail@d-westphal.de>
+ * @package syntax
+ * @access	public
+ *
+ */
+
+class RdfParser extends Object {
+
+var $rdf_parser;
+var $model;
+
+/* Private Methods */
+
+
+/**
+* converts a string to its unicode NFC form (e.g. \uHHHH or \UHHHHHHHH).
+*
+* @param String $str
+* @return String
+* @access private
+*
+*/
+function str2unicode_nfc($str=""){
+	$result="";
+	/* try to detect encoding */
+	$tmp=str_replace("?", "", $str);
+	if(strpos(utf8_decode($tmp), "?")===false){
+		$str=utf8_decode($str);
+	}
+	for($i=0,$i_max=strlen($str);$i<$i_max;$i++){
+		$nr=0;/* unicode dec nr */
+		/* char */
+		$char=$str[$i];
+		/* utf8 binary */
+		$utf8_char=utf8_encode($char);
+		$bytes=strlen($utf8_char);
+		if($bytes==1){
+			/* 0####### (0-127) */
+			$nr=ord($utf8_char);
+		}
+		elseif($bytes==2){
+			/* 110##### 10###### = 192+x 128+x */
+			$nr=((ord($utf8_char[0])-192)*64) + (ord($utf8_char[1])-128);
+		}
+		elseif($bytes==3){
+			/* 1110#### 10###### 10###### = 224+x 128+x 128+x */
+			$nr=((ord($utf8_char[0])-224)*4096) + ((ord($utf8_char[1])-128)*64) + (ord($utf8_char[2])-128);
+		}
+		elseif($bytes==4){
+			/* 1111#### 10###### 10###### 10###### = 240+x 128+x 128+x 128+x */
+			$nr=((ord($utf8_char[0])-240)*262144) + ((ord($utf8_char[1])-128)*4096) + ((ord($utf8_char[2])-128)*64) + (ord($utf8_char[3])-128);
+		}
+		/* result (see http://www.w3.org/TR/rdf-testcases/#ntrip_strings) */
+		if($nr<9){/* #x0-#x8 (0-8) */
+			$result.="\\u".sprintf("%04X",$nr);
+		}
+		elseif($nr==9){/* #x9 (9) */
+			$result.='\t';
+		}
+		elseif($nr==10){/* #xA (10) */
+			$result.='\n';
+		}
+		elseif($nr<13){/* #xB-#xC (11-12) */
+			$result.="\\u".sprintf("%04X",$nr);
+		}
+		elseif($nr==13){/* #xD (13) */
+			$result.='\t';
+		}
+		elseif($nr<32){/* #xE-#x1F (14-31) */
+			$result.="\\u".sprintf("%04X",$nr);
+		}
+		elseif($nr<34){/* #x20-#x21 (32-33) */
+			$result.=$char;
+		}
+		elseif($nr==34){/* #x22 (34) */
+			$result.='\"';
+		}
+		elseif($nr<92){/* #x23-#x5B (35-91) */
+			$result.=$char;
+		}
+		elseif($nr==92){/* #x5C (92) */
+			$result.='\\';
+		}
+		elseif($nr<127){/* #x5D-#x7E (93-126) */
+			$result.=$char;
+		}
+		elseif($nr<65536){/* #x7F-#xFFFF (128-65535) */
+			$result.="\\u".sprintf("%04X",$nr);
+		}
+		elseif($nr<1114112){/* #x10000-#x10FFFF (65536-1114111) */
+			$result.="\\U".sprintf("%08X",$nr);
+		}
+		else{
+			/* other chars are not defined => ignore */
+		}
+	}
+	return $result;
+}
+
+
+
+
+/**
+ * @access	private
+ */
+function _new_element()
+{
+    $e['parent']=Array();  // Parent is a blank Array
+    $e['state']=0;
+    $e['has_property_atributes']=0;
+    $e['has_member_attributes']=0;
+    $e['subject_type']=0;
+    $e['subject']='';
+    $e['predicate']='';
+    $e['ordinal']=0;
+    $e['members']=0;
+    $e['data']='';
+    $e['xml_lang']='';
+    $e['bag_id']='';
+    $e['statements']=0;
+    $e['statement_id']='';
+    $e['datatype']='';
+    $e['element_base_uri'] = '';
+
+    return $e;
+}
+
+/**
+
+ * @param string $source
+ * @param string &$destination
+ *
+ * @access	private
+ */
+function _copy_element($source, &$destination )
+{
+    if( $source )
+    {
+        $destination['parent'] = $source;
+        $destination['state'] = $source['state'];
+        $destination['xml_lang'] = $source['xml_lang'];
+    	$destination['element_base_uri'] = $source['element_base_uri'];
+    }
+}
+
+  /**
+   * @param string &$e
+   * @access	private
+   */
+function _clear_element(&$e)
+{
+        $e['subject']='';
+        $e['predicate']='';
+        $e['data']='';
+        $e['bag_id']='';
+        $e['statement_id']='';
+
+        if(isset($e['parent'])) {
+          if( $e['parent'] )
+          {
+              if( $e['parent']['xml_lang'] != $e['xml_lang'] )
+              {
+                  $e['xml_lang']='';
+              }
+          }
+          else
+          {
+              $e['xml_lang']='';
+          }
+        } else {
+            $e['xml_lang']='';
+        }
+
+        $e['parent']=Array();
+        $e['state']=0;
+        $e['has_property_attributes']=0;
+        $e['has_member_attributes']=0;
+        $e['subject_type']=0;
+        $e['subject']='';
+        $e['predicate']='';
+        $e['ordinal']=0;
+        $e['members']=0;
+        $e['data']='';
+        $e['xml_lang']='';
+        $e['bag_id']='';
+        $e['statements']=0;
+        $e['statement_id']='';
+		$e['datatype']='';
+    	$e['element_base_uri'] = '';
+}
+
+  /**
+   * @access	private
+   */
+function _push_element()
+{
+    if(!isset($this->rdf_parser['free'])) {
+        $this->rdf_parser['free']=Array();
+    }
+    if(count($this->rdf_parser['free'])>0)
+    {
+        $e = $this->rdf_parser['free'];
+        if(isset($e['parent'])) {
+          $this->rdf_parser['free'] = $e['parent'];
+        } else {
+          $this->rdf_parser['free']=$this->_new_element();
+        }
+    }
+    else
+    {
+        $e = $this->_new_element();
+    }
+    if(!isset($this->rdf_parser['top'])) {
+      $this->rdf_parser['top']=Array();
+    }
+    $this->_copy_element( $this->rdf_parser['top'], $e );
+    $this->rdf_parser['top'] = $e;
+}
+
+  /**
+   * @access	private
+   */
+function _pop_element()
+{
+    $e = $this->rdf_parser['top'];
+    $this->rdf_parser['top'] = $e['parent'];
+    $this->_clear_element( $e );
+    $this->rdf_parser['free'] = $e;
+}
+
+  /**
+   * @param string $local_name
+   * @access	private
+   */
+function _is_rdf_property_attribute_resource($local_name )
+{
+    return ( $local_name == RDF_TYPE );
+}
+
+  /**
+   * @param string $local_name
+   * @access	private
+   */
+function _is_rdf_property_attribute_literal($local_name )
+{
+    return ( $local_name == RDF_VALUE )
+		|| ( $local_name == RDF_BAG )
+		|| ( $local_name == RDF_SEQ )
+		|| ( $local_name == RDF_ALT )
+		|| ( $local_name == RDF_STATEMENT )
+		|| ( $local_name == RDF_PROPERTY )
+		|| ( $local_name == RDF_LIST );
+}
+
+  /**
+   * @param string $local_name
+   * @access	private
+   */
+function _is_rdf_ordinal( $local_name )
+{
+    $ordinal = -1;
+
+    if( $local_name{0} ==  '_'  )
+    {
+        $ordinal =  substr($local_name,1) + 1 ;
+    }
+
+    return ( $ordinal > 0 ) ? $ordinal : 0;
+}
+
+  /**
+   * @param string $local_name
+   * @access	private
+   */
+function _is_rdf_property_attribute( $local_name )
+{
+    return $this->_is_rdf_property_attribute_resource( $local_name )
+        || $this->_is_rdf_property_attribute_literal( $local_name );
+}
+
+function _is_forbidden_rdf_property_attribute($local_name)
+{
+	return ( $local_name == RDF_RDF )
+		|| ( $local_name == RDF_DESCRIPTION)
+        || ( $local_name == RDF_ID)
+        || ( $local_name == RDF_ABOUT )
+        || ( $local_name == RDF_BAG_ID )
+        || ( $local_name == RDF_PARSE_TYPE )
+        || ( $local_name == RDF_RESOURCE )
+        || ( $local_name == RDF_NODEID )
+        || ( $local_name == RDF_LI )
+        || ( $local_name == RDF_ABOUT_EACH )
+		|| ( $local_name == RDF_ABOUT_EACH_PREFIX )
+		|| ( $local_name == RDF_DATATYPE );
+}
+
+  /**
+   * @param string $local_name
+   * @access	private
+   */
+function _is_rdf_property_element( $local_name )
+{
+    return (  $local_name == RDF_TYPE )
+        || (  $local_name == RDF_SUBJECT )
+        || (  $local_name == RDF_PREDICATE )
+        || (  $local_name == RDF_OBJECT )
+        || (  $local_name == RDF_VALUE )
+        || (  $local_name == RDF_LI )
+        || (  $local_name == RDF_SEEALSO )
+		|| ( $local_name == RDF_BAG )
+		|| ( $local_name == RDF_SEQ )
+		|| ( $local_name == RDF_ALT )
+		|| ( $local_name == RDF_STATEMENT )
+		|| ( $local_name == RDF_PROPERTY )
+		|| ( $local_name == RDF_LIST )
+		|| ( $local_name == RDF_FIRST )
+		|| ( $local_name == RDF_REST )
+        || (  $local_name{0} == '_'  );
+}
+
+  /**
+   * @param string $local_name
+   * @access	private
+   */
+function _is_forbidden_rdf_property_element ($local_name)
+{
+	return ( $local_name == RDF_RDF )
+		|| ( $local_name == RDF_DESCRIPTION)
+        || ( $local_name == RDF_ID)
+        || ( $local_name == RDF_ABOUT )
+        || ( $local_name == RDF_BAG_ID )
+        || ( $local_name == RDF_PARSE_TYPE )
+        || ( $local_name == RDF_RESOURCE )
+        || ( $local_name == RDF_NODEID )
+        || ( $local_name == RDF_ABOUT_EACH )
+		|| ( $local_name == RDF_ABOUT_EACH_PREFIX )
+		|| ( $local_name == RDF_DATATYPE );
+}
+
+
+  /**
+   * @param string $local_name
+   * @access	private
+   */
+function _is_rdf_node_element( $local_name )
+{
+    return ( $local_name == RDF_DESCRIPTION )
+        || ( $local_name == RDF_STATEMENT )
+        || ( $local_name == RDF_SUBJECT )
+        || ( $local_name == RDF_PREDICATE )
+        || ( $local_name == RDF_OBJECT )
+        || ( $local_name == RDF_PROPERTY )
+		|| ( $local_name == RDF_TYPE )
+        || ( $local_name == RDF_VALUE )
+		|| ( $local_name == RDF_BAG )
+		|| ( $local_name == RDF_SEQ )
+		|| ( $local_name == RDF_ALT )
+        || ( $local_name == RDF_SEEALSO )
+		|| ( $local_name == RDF_LIST )
+		|| ( $local_name == RDF_FIRST )
+		|| ( $local_name == RDF_REST )
+		|| ( $local_name == RDF_NIL )
+        || ( $local_name{0} == '_'  );
+}
+
+  /**
+   * @param string $local_name
+   * @access	private
+   */
+function _is_forbidden_rdf_node_element ($local_name)
+{
+	return ( $local_name == RDF_RDF )
+        || ( $local_name == RDF_ID)
+        || ( $local_name == RDF_ABOUT )
+        || ( $local_name == RDF_BAG_ID )
+        || ( $local_name == RDF_PARSE_TYPE )
+        || ( $local_name == RDF_RESOURCE )
+        || ( $local_name == RDF_NODEID )
+		|| ( $local_name == RDF_LI )
+        || ( $local_name == RDF_ABOUT_EACH )
+		|| ( $local_name == RDF_ABOUT_EACH_PREFIX )
+		|| ( $local_name == RDF_DATATYPE );
+}
+
+  /**
+   * @param string $val
+   * @access	private
+   */
+function _istalnum($val) {
+  return preg_match('/([A-Za-z0-9])/',$val);
+}
+  /**
+   * @param string $val
+   * @access	private
+   */
+function _istalpha($val) {
+  return preg_match('/([A-Za-z])/',$val);
+}
+
+  /**
+   * @param string $uri
+   * @access	private
+   */
+function _is_absolute_uri($uri )
+{
+    $result = false;
+        $uri_p=0;
+    if( $uri && $this->_istalpha( $uri{$uri_p} ) )
+    {
+        ++$uri_p;
+
+        while( ($uri_p<strlen($uri))
+            && ( $this->_istalnum( $uri{$uri_p} )
+                || ( $uri{$uri_p} ==  '+'  )
+                || ( $uri{$uri_p} == '-'  )
+                || ( $uri{$uri_p} ==  '.'  ) ) )
+        {
+                ++$uri_p;
+        }
+
+        $result = ( $uri{$uri_p} == ':'  );
+    }
+    return $result;
+}
+
+
+/*
+   * This function returns an associative array returning any of the various components of the URL that are present. This includes the
+   * $arr=parse_url($url)
+   * scheme - e.g. http
+   * host
+   * port
+   * user
+   * pass
+   * path
+   * query - after the question mark ?
+   * fragment - after the hashmark #
+   *
+   * @param string $uri
+   * @param string $buffer
+   * @param string &$scheme
+   * @param string &$authority
+   * @param string &$path
+   * @param string &$query
+   * @param string &$fragment
+   * @access	private
+*/
+function _parse_uri($uri,$buffer,&$scheme,&$authority,&$path,&$query,&$fragment ) {
+
+  $parsed=parse_url($uri);
+  if(isset($parsed['scheme'])) {
+    $scheme=$parsed['scheme'];
+  } else {
+    $scheme='';
+  }
+  if(isset($parsed['host'])) {
+    $host=$parsed['host'];
+  } else {
+    $host='';
+  }
+  if(isset($parsed['host'])) {
+    $authority=$parsed['host'];
+  } else {
+    $authority='';
+  }
+  if(isset($parsed['path'])) {
+    $path=$parsed['path'];
+  } else {
+    $path='';
+  }
+  if(isset($parsed['query'])) {
+    $query=$parsed['query'];
+  } else {
+    $query='';
+  }
+  if(isset($parsed['fragment'])) {
+    $fragment=$parsed['fragment'];
+  } else {
+    $fragment='';
+  }
+
+}
+
+/**
+   * @param string $base_uri
+   * @param string $reference_uri
+   * @param string &$buffer
+   * @access	private
+*/
+function _resolve_uri_reference($base_uri,$reference_uri,&$buffer )
+{
+	if ($reference_uri == '')
+		return ($buffer = preg_replace("/\#[^\/\\\]*$/", '', $base_uri));
+
+    $base_buffer='';
+    $reference_buffer='';
+    $path_buffer='';
+
+    $buffer = '';
+
+    $this->_parse_uri($reference_uri,
+    				  $reference_buffer,
+    				  $reference_scheme,
+    				  $reference_authority,
+                      $reference_path,
+                      $reference_query,
+                      $reference_fragment );
+
+    $this->_parse_uri($base_uri,
+            		  $base_buffer,
+            		  $base_scheme,
+            		  $base_authority,
+            		  $base_path,
+            		  $base_query,
+            	      $base_fragment );
+
+    if( $reference_scheme == ''
+        && $reference_authority == ''
+        && $reference_path == ''
+        && $reference_query == '' )
+    {
+        $buffer=$base_uri;
+
+        if( $reference_fragment != '' )
+        {
+			if ($base_path == '' || $base_path == '/' || $base_path == "\\") {
+			   $buffer = $this->rdf_parser['document_base_uri'];
+			}
+			else
+			{
+				$buffer = preg_replace("/\#[^\/\\\]*$/", '', $base_uri);
+			}
+
+            // CB: Changed for base URI
+			$c = substr($buffer, strlen($buffer)-1 ,1);
+	        if (!($c=='#' || $c==':' || $c=='/' || $c=="\\"))
+			       $buffer.= '#' ;
+            $buffer.=$reference_fragment;
+
+        }
+    }
+    else if( $reference_scheme != '' )
+    {
+        $buffer=$reference_uri;
+    }
+    else
+    {
+        $result_scheme = $base_scheme;
+        $result_path = '';
+
+        if( $reference_authority != '' )
+        {
+            $result_authority = $reference_authority;
+        }
+        else
+        {
+            $result_authority = $base_authority;
+
+            if ($reference_path != '')
+            {
+            	if ($reference_path{0} == '/' || $reference_path{0} == "\\")
+            	{
+            		if ($reference_path{1} == '/' || $reference_path{1} == "\\")
+            		{
+						$result_authority = '';
+						$result_path = $reference_path;
+            		}
+            		else
+            			$result_path = $reference_path;
+            	}
+            	elseif (substr($reference_path, 0, 3) == '../' ||
+            	        substr($reference_path, 0, 3) == '..\\')
+            	{
+            		$slash = $reference_path{2};
+            		while($base_path != '' && ( substr($reference_path, 0, 3) == '../'
+            	                             || substr($reference_path, 0, 3) == '..\\'))
+            	    {
+            		  	$base_path = preg_replace("/((\/)|(\\\))[^\/\\\]*$/", '', $base_path);
+            		  	if ($base_path != '') {
+            		  	   $base_path = preg_replace("/((\/)|(\\\))[^\/\\\]*$/", '', $base_path);
+            		  	   $reference_path = substr($reference_path, 3);
+            		  	}
+            		}
+
+                    $result_path = $base_path .$slash .$reference_path;
+            	}
+            	else
+            	{
+            		if ($base_path)
+            			$result_path = preg_replace("/[^\/\\\]*$/", $reference_path, $base_path, 1);
+					else
+					    $result_path = '/' .$reference_path;
+            	}
+            }
+
+        }
+
+        if( $result_scheme != '' )
+        {
+            $buffer=$result_scheme;
+            $buffer.=':';
+        }
+
+        if( $result_authority != '' )
+        {
+            $buffer.="//";
+            $buffer.=$result_authority;
+        }
+
+        if( $result_path != '' )
+        {
+            $buffer.=$result_path;
+        }
+
+        if( $reference_query != '' )
+        {
+            $buffer.='?';
+            $buffer.=$reference_query;
+        }
+
+        if( $reference_fragment != '' )
+        {
+            $buffer.='#';
+            $buffer.=$reference_fragment;
+        }
+    }
+}
+
+
+/**
+   * IDs which contain CombiningChars or Extenders
+   * (see http://www.w3.org/TR/REC-xml-names/#NT-NCName) are assumed to be invalid.
+   * If you want to use IDs containing these characters you can turn off
+   * the validating by setting the constant VALIDATE_IDS to FALSE (see constants.php).
+   *
+   * @param string $id
+   * @access	private
+*/
+function is_valid_id($id )
+{
+	if (!VALIDATE_IDS)
+		return TRUE;
+
+    $result = FALSE;
+
+    if( $id )
+    {
+        if( $this->_istalpha($id{0}) || $id{0} == '_')
+        {
+            $result = TRUE;
+            $i=0;
+            $len = strlen($id);
+			while( $result != FALSE && ++$i < $len )
+            {
+                if( !($this->_istalnum( $id{$i})
+                      || $id{$i} == '.'
+                      || $id{$i} == '-'
+                      || $id{$i} == '_'))
+                {
+                   $result = FALSE;
+                }
+            }
+        }
+    }
+
+    if (!$result)
+    	$this->_report_error('illegal ID, nodeID or bagID attribute value');
+    else
+    	return TRUE;
+}
+
+/**
+   * @param string $id
+   * @param string &$buffer
+   * @access	private
+*/
+function _resolve_id($id,&$buffer )
+{
+    $id_buffer='';
+
+    if( $this->is_valid_id($id) )
+    {
+        $id_buffer="#$id";
+    }
+
+    $this->_resolve_uri_reference( $this->rdf_get_base(), $id_buffer, $buffer );
+
+}
+
+/**
+   * @param string $name
+   * @param string &$buffer
+   * @param string &$namespace_uri
+   * @param string &$local_name
+   * @access	private
+*/
+function _split_name($name, &$buffer, &$namespace_uri, &$local_name )
+{
+    static $nul = 0;
+    $buffer=$name;
+
+        if(  strstr( $buffer, NAMESPACE_SEPARATOR_CHAR ) )
+        {
+            $cosas=explode(NAMESPACE_SEPARATOR_CHAR,$buffer);
+            $namespace_uri = $cosas[0];
+            $local_name = $cosas[1];
+        }
+        else
+        {
+            if( ( $buffer{ 0 } ==  'x'  )
+                && ( $buffer{ 1 } ==  'm'  )
+                && ( $buffer{ 2 } ==  'l'  )
+                && ( $buffer{ 3 } ==  ':'  ) )
+            {
+                $namespace_uri = XML_NAMESPACE_URI;
+                $local_name = substr($buffer,4);
+            }
+            else
+            {
+                $namespace_uri = '';
+                $local_name = $buffer;
+            }
+        }
+}
+/**
+   * @param string &$buf
+   * @access	private
+*/
+function _generate_anonymous_uri(&$buf )
+{
+    $id='';
+    if(!isset($this->rdf_parser['anonymous_id'])) {
+      $this->rdf_parser['anonymous_id']=0;
+    }
+    $this->rdf_parser['anonymous_id']++;
+
+    $buf= BNODE_PREFIX . $this->rdf_parser['anonymous_id'];
+
+}
+/**
+   * @param string $subject_type
+   * @param string $subject
+   * @param string $predicate
+   * @param string $ordinal
+   * @param string $object_type
+   * @param string $object
+   * @param string $xml_lang
+   * @param string $bag_id
+   * @param string $statements
+   * @param string $statement_id
+   * @access	private
+*/
+function _report_statement( $subject_type, $subject, $predicate, $ordinal, $object_type,  $object, $xml_lang, $bag_id, $statements, $statement_id, $datatype )
+{
+    $statement_id_type = RDF_SUBJECT_TYPE_URI;
+    $statement_id_buffer='';
+    $predicate_buffer='';
+    if (!$xml_lang && $object_type == RDF_OBJECT_TYPE_LITERAL && isset($this->rdf_parser['document_xml_lang']))
+    	$xml_lang = $this->rdf_parser['document_xml_lang'];
+
+	 // call add statement
+	 $this->add_statement_to_model($this->rdf_parser['user_data'],$subject_type,$subject,$predicate,$ordinal,$object_type,$object,$xml_lang, $datatype );
+
+        if( $bag_id )
+        {
+            if( $statements == '' )
+            {
+                $this->_report_statement(RDF_SUBJECT_TYPE_URI,
+                    $bag_id,
+                    RDF_NAMESPACE_URI.RDF_TYPE,
+                    0,
+                    RDF_OBJECT_TYPE_RESOURCE,
+                    RDF_NAMESPACE_URI.RDF_BAG,
+                    '',
+                    '',
+                    '',
+                    '',
+					$datatype );
+            }
+
+            if( ! $statement_id )
+            {
+                $statement_id_type = RDF_SUBJECT_TYPE_BNODE;
+                $this->_generate_anonymous_uri( $statement_id_buffer );
+                $statement_id = $statement_id_buffer;
+            }
+            $statements++;
+            $predicate_buffer='RDF_NAMESPACE_URI_'.$statements;
+
+            $this->_report_statement(
+                RDF_SUBJECT_TYPE_URI,
+                $bag_id,
+                $predicate_buffer,
+                $statements,
+                RDF_OBJECT_TYPE_BNODE,
+                $statement_id,
+                '',
+                '',
+                '',
+                '',
+				$datatype );
+        }
+
+        if( $statement_id )
+        {
+            // rdf:type = rdf:Statement
+            $this->_report_statement(
+                $statement_id_type,
+                $statement_id,
+                RDF_NAMESPACE_URI.RDF_TYPE,
+                0,
+                RDF_OBJECT_TYPE_RESOURCE,
+                RDF_NAMESPACE_URI.RDF_STATEMENT,
+                '',
+                '',
+                '',
+                '',
+				$datatype );
+
+			if ($subject_type == RDF_SUBJECT_TYPE_BNODE)
+			   $obj_type = RDF_OBJECT_TYPE_BNODE;
+			else
+			   $obj_type = RDF_OBJECT_TYPE_RESOURCE;
+
+
+            // rdf:subject
+            $this->_report_statement(
+                $statement_id_type,
+                $statement_id,
+                RDF_NAMESPACE_URI.RDF_SUBJECT,
+                0,
+				$obj_type,
+                $subject,
+                '',
+                '',
+                '',
+                '',
+				$datatype );
+
+            // rdf:predicate
+            $this->_report_statement(
+                $statement_id_type,
+                $statement_id,
+                RDF_NAMESPACE_URI.RDF_PREDICATE,
+                0,
+                RDF_OBJECT_TYPE_RESOURCE,
+                $predicate,
+                '',
+                '',
+                '',
+                '',
+				$datatype );
+
+            // rdf:object
+            $this->_report_statement(
+                $statement_id_type,
+                $statement_id,
+                RDF_NAMESPACE_URI.RDF_OBJECT,
+                0,
+                $object_type,
+                $object,
+                '',
+                '',
+                '',
+                '',
+				$datatype );
+        }
+}
+/**
+   * @param string $subject_type
+   * @param string $subject
+   * @param string $attributes
+   * @param string $xml_lang
+   * @param string $bag_id
+   * @param string $statements
+ * @access	private
+*/
+function _handle_property_attributes($subject_type, $subject, $attributes, $xml_lang, $bag_id, $statements )
+{
+    $i=0;
+
+    $attribute='';
+    $predicate='';
+
+    $attribute_namespace_uri='';
+    $attribute_local_name='';
+    $attribute_value='';
+
+    $ordinal=0;
+
+    for( $i = 0; isset($attributes[ $i ]); $i += 2 )
+    {
+        $this->_split_name(
+            $attributes[ $i ],
+            $attribute,
+            $attribute_namespace_uri,
+            $attribute_local_name );
+
+        $attribute_value = $attributes[ $i + 1 ];
+
+        $predicate=$attribute_namespace_uri;
+        $predicate.=$attribute_local_name;
+
+        if( RDF_NAMESPACE_URI == $attribute_namespace_uri )
+        {
+            if( $this->_is_rdf_property_attribute_literal( $attribute_local_name ) )
+            {
+				$this->_report_statement(
+                    $subject_type,
+                    $subject,
+                    $predicate,
+                    0,
+                    RDF_OBJECT_TYPE_LITERAL,
+                    $attribute_value,
+                    $xml_lang,
+                    $bag_id,
+                    $statements,
+                    '',
+					'');
+            }
+            else if( $this->_is_rdf_property_attribute_resource( $attribute_local_name ) )
+            {
+				$this->_report_statement(
+                    $subject_type,
+                    $subject,
+                    $predicate,
+                    0,
+                    RDF_OBJECT_TYPE_RESOURCE,
+                    $attribute_value,
+                    '',
+                    $bag_id,
+                    $statements,
+                    '',
+					'');
+            }
+            else if( ( $ordinal = $this->_is_rdf_ordinal( $attribute_local_name ) ) != 0 )
+            {
+				$this->_report_statement(
+                    $subject_type,
+                    $subject,
+                    $predicate,
+                    $ordinal,
+                    RDF_OBJECT_TYPE_LITERAL,
+                    $attribute_value,
+                    $xml_lang,
+                    $bag_id,
+                    $statements,
+                    '',
+					'' );
+            }
+            else if (   ($attribute_local_name != RDF_ABOUT)
+                     && ($attribute_local_name != RDF_RDF)
+                     && ($attribute_local_name != RDF_DESCRIPTION)
+                     && ($attribute_local_name != RDF_ID)
+                     && ($attribute_local_name != RDF_ABOUT_EACH)
+                     && ($attribute_local_name != RDF_ABOUT_EACH_PREFIX)
+                     && ($attribute_local_name != RDF_BAG_ID)
+                     && ($attribute_local_name != RDF_RESOURCE)
+                     && ($attribute_local_name != RDF_PARSE_TYPE)
+                     && ($attribute_local_name != RDF_PARSE_TYPE_LITERAL)
+                     && ($attribute_local_name != RDF_PARSE_TYPE_RESOURCE)
+                     && ($attribute_local_name != RDF_LI)
+                     && ($attribute_local_name != RDF_SUBJECT)
+                     && ($attribute_local_name != RDF_PREDICATE)
+                     && ($attribute_local_name != RDF_OBJECT)
+                     && ($attribute_local_name != RDF_NODEID)
+                     && ($attribute_local_name != RDF_DATATYPE)
+                     && ($attribute_local_name != RDF_SEEALSO)
+                     && ($attribute_local_name != RDF_NIL)
+                     && ($attribute_local_name != RDF_REST)
+                     && ($attribute_local_name != RDF_FIRST)
+                    )
+            {
+            	$this->_report_statement(
+                	$subject_type,
+                	$subject,
+                	$predicate,
+                	0,
+                	RDF_OBJECT_TYPE_LITERAL,
+                	$attribute_value,
+                	$xml_lang,
+                	$bag_id,
+                	$statements,
+                	'',
+					'' );
+            }
+        }
+        else if( XML_NAMESPACE_URI == $attribute_namespace_uri )
+        {
+			if ($attribute_local_name == 'base')
+			{
+    			$this->rdf_parser['top']['element_base_uri'] = $attribute_value;
+			}
+        }
+        else if( $attribute_namespace_uri )
+        {
+            // is it required that property attributes be in an explicit namespace?
+
+			$this->_report_statement(
+                $subject_type,
+                $subject,
+                $predicate,
+                0,
+                RDF_OBJECT_TYPE_LITERAL,
+                $attribute_value,
+                $xml_lang,
+                $bag_id,
+                $statements,
+                '',
+				'' );
+        }
+    }
+}
+
+
+
+/**
+   * @param string $warning
+ * @access	private
+*/
+function _report_warning($warning)
+{
+	$errmsg = RDFAPI_ERROR . '(class: parser): ' . $warning .'.';
+	trigger_error($errmsg, E_USER_WARNING);
+}
+
+
+function _report_error($error)
+{
+	$errmsg = RDFAPI_ERROR . '(class: parser): ' . $error .'.';
+	trigger_error($errmsg, E_USER_ERROR);
+}
+
+
+/**
+   * @param string $namespace_uri
+   * @param string $local_name
+   * @param string $attributes
+   * @param string $parent
+ * @access	private
+*/
+function _handle_resource_element( $namespace_uri, $local_name, $attributes, $parent )
+{
+    $subjects_found = 0;
+    $aux=$attributes;
+    $aux2=Array();
+    foreach($attributes as $atkey=>$atvalue) {
+      $aux2[]=$atkey;
+      $aux2[]=$atvalue;
+    }
+    $attributes=$aux2;
+    $id = '';
+    $about = '';
+
+    $bag_id = '';
+    $node_id = '';
+    $datatype = '';
+
+    $i=0;
+
+    $attribute='';
+
+    $attribute_namespace_uri='';
+    $attribute_local_name='';
+    $attribute_value='';
+
+    $id_buffer='';
+
+    $type='';
+
+    $this->rdf_parser['top']['has_property_attributes'] = false;
+    $this->rdf_parser['top']['has_member_attributes'] = false;
+
+
+    if( $namespace_uri == RDF_NAMESPACE_URI )
+    {
+       if( ! $this->_is_rdf_node_element( $local_name ) )
+       {
+		  $msg = 'unknown or out of context rdf node element: '.$local_name;
+
+		  if ($this->_is_forbidden_rdf_node_element($local_name))
+		  	 $this->_report_error($msg);
+		  else
+		  	 $this->_report_warning($msg);
+       }
+    }
+
+    // examine each attribute for the standard RDF "keywords"
+    for( $i = 0; isset($attributes[$i]); $i += 2 )
+    {
+        $this->_split_name(
+            $attributes[ $i ],
+            $attribute,
+            $attribute_namespace_uri,
+            $attribute_local_name );
+
+        $attribute_value = $attributes[ $i + 1 ];
+
+        // if the attribute is not in any namespace
+        //   or the attribute is in the RDF namespace
+        if( ( $attribute_namespace_uri == '' )
+            || (  $attribute_namespace_uri == RDF_NAMESPACE_URI  ))
+        {
+            if( $attribute_local_name == RDF_ID )
+            {
+                $id = $attribute_value;
+                ++$subjects_found;
+            } else if( $attribute_local_name == RDF_ABOUT ) {
+				$about = '_'.$attribute_value;
+                ++$subjects_found;
+            } else if( $attribute_local_name == RDF_NODEID) {
+                $node_id = $attribute_value;
+				++$subjects_found;
+            } else if(  $attribute_local_name == RDF_ABOUT_EACH ) {
+				$error = 'aboutEach has been removed from the RDF specifications';
+				$this->_report_error($error);
+            } else if( $attribute_local_name == RDF_ABOUT_EACH_PREFIX ) {
+				$error = 'aboutEachPrefix has been removed from the RDF specifications';
+				$this->_report_error($error);
+            } else if( $attribute_local_name == RDF_BAG_ID) {
+                $bag_id = $attribute_value;
+            } else if( $attribute_local_name == RDF_DATATYPE) {
+                $datatype = $attribute_value;
+            } else if( $this->_is_rdf_property_attribute( $attribute_local_name )) {
+                $this->rdf_parser['top']['has_property_attributes'] = true;
+            } else if( $this->_is_rdf_ordinal( $attribute_local_name )) {
+                $this->rdf_parser['top']['has_property_attributes'] = true;
+                $this->rdf_parser['top']['has_member_attributes'] = true;
+            } else {
+				$this->rdf_parser['top']['has_property_attributes'] = true;
+				$msg = 'unknown or out of context rdf attribute: '.$attribute_local_name;
+
+		  		if ($this->_is_forbidden_rdf_property_attribute($attribute_local_name))
+		  			$this->_report_error($msg);
+		  		else
+		  			$this->_report_warning($msg);
+            }
+        }
+        else if(  $attribute_namespace_uri == XML_NAMESPACE_URI )
+        {
+            if( $attribute_local_name == XML_LANG )
+            {
+                $this->rdf_parser['top']['xml_lang'] = $attribute_value;
+            }
+    		elseif ($attribute_local_name == 'base')
+    		{
+    			$this->rdf_parser['top']['element_base_uri'] = $attribute_value;
+    		}
+        }
+        else if( $attribute_namespace_uri )
+        {
+            $this->rdf_parser['top']['has_property_attributes'] = true;
+        }
+    }
+
+    // if no subjects were found, generate one.
+    if( $subjects_found == 0 )
+    {
+        $this->_generate_anonymous_uri( $id_buffer );
+        $this->rdf_parser['top']['subject']=$id_buffer;
+		$this->rdf_parser['top']['subject_type'] = RDF_SUBJECT_TYPE_BNODE;
+    }
+    else if( $subjects_found > 1 )
+    {
+		 $this->_report_error('ID, about and nodeID are mutually exclusive');
+    }
+    else if( $id )
+    {
+        $this->_resolve_id( $id, $id_buffer );
+        $this->rdf_parser['top']['subject_type'] = RDF_SUBJECT_TYPE_URI;
+        $this->rdf_parser['top']['subject']=$id_buffer;
+    }
+    else if( $about )
+    {
+		$this->_resolve_uri_reference( $this->rdf_get_base(), substr($about,1), $id_buffer );
+        $this->rdf_parser['top']['subject_type'] = RDF_SUBJECT_TYPE_URI;
+        $this->rdf_parser['top']['subject']=$id_buffer;
+    }
+    else if( $node_id )
+    {
+    	$this->is_valid_id($node_id);
+        $this->rdf_parser['top']['subject_type'] = RDF_SUBJECT_TYPE_BNODE;
+        $this->rdf_parser['top']['subject']=$node_id;
+    }
+
+    // if the subject is empty, assign it the document uri
+    if( $this->rdf_parser['top']['subject'] == '' )
+    {
+		$this->rdf_parser['top']['subject']=$this->rdf_get_base();
+    }
+
+    if( $bag_id )
+    {
+        $this->_resolve_id( $bag_id, $id_buffer );
+        $this->rdf_parser['top']['bag_id']=$id_buffer;
+    }
+
+    // only report the type for non-rdf:Description elements.
+    if( ($local_name != RDF_DESCRIPTION )
+        || ( $namespace_uri != RDF_NAMESPACE_URI ) )
+    {
+        $type=$namespace_uri;
+        $type.=$local_name;
+
+		$this->_report_statement(
+            $this->rdf_parser['top']['subject_type'],
+            $this->rdf_parser['top']['subject'],
+            RDF_NAMESPACE_URI.RDF_TYPE,
+            0,
+            RDF_OBJECT_TYPE_RESOURCE,
+            $type,
+            '',
+            $this->rdf_parser['top']['bag_id'],
+            $this->rdf_parser['top']['statements'],
+            '',
+			$datatype);
+
+    }
+
+    // if this element is the child of some property,
+    //   report the appropriate statement.
+    if( $parent )
+    {
+        if ($this->rdf_parser['top']['subject_type'] == RDF_SUBJECT_TYPE_BNODE)
+        	$objtype = RDF_OBJECT_TYPE_BNODE;
+        else
+        	$objtype = RDF_OBJECT_TYPE_RESOURCE;
+
+    	$this->_report_statement(
+            $parent['parent']['subject_type'],
+            $parent['parent']['subject'],
+            $parent['predicate'],
+            $parent['ordinal'],
+            $objtype,
+            $this->rdf_parser['top']['subject'],
+            '',
+            $parent['parent']['bag_id'],
+            $parent['parent']['statements'],
+            $parent['statement_id'],
+			$parent['datatype']);
+
+    }
+
+    if( $this->rdf_parser['top']['has_property_attributes'] )
+    {
+        $this->_handle_property_attributes(
+            $this->rdf_parser['top']['subject_type'],
+            $this->rdf_parser['top']['subject'],
+            $attributes,
+            $this->rdf_parser['top']['xml_lang'],
+            $this->rdf_parser['top']['bag_id'],
+            $this->rdf_parser['top']['statements'] );
+    }
+}
+
+/**
+   * @param string &$namespace_uri
+   * @param string &$local_name
+   * @param string &$attributes
+ * @access	private
+*/
+function _handle_property_element( &$namespace_uri, &$local_name, &$attributes )
+{
+    $buffer='';
+
+    $i=0;
+
+    $aux=$attributes;
+    $aux2=Array();
+    foreach($attributes as $atkey=>$atvalue) {
+      $aux2[]=$atkey;
+      $aux2[]=$atvalue;
+    }
+    $attributes=$aux2;
+
+    $attribute_namespace_uri='';
+    $attribute_local_name='';
+    $attribute_value = '';
+
+    $resource = NULL;
+    $statement_id = '';
+    $bag_id = '';
+    $parse_type = '';
+	$node_id = '';
+	$datatype = '';
+
+    $this->rdf_parser['top']['ordinal'] = 0;
+
+    if( $namespace_uri == RDF_NAMESPACE_URI )
+    {
+       if( ! $this->_is_rdf_property_element( $local_name ) )
+        {
+			$msg = 'unknown or out of context rdf property element: '.$local_name;
+
+		  	if ($this->_is_forbidden_rdf_property_element($local_name))
+		  		$this->_report_error($msg);
+		  	else
+		  		$this->_report_warning($msg);
+        }
+
+    }
+
+    $buffer=$namespace_uri;
+
+    if( ( $namespace_uri == RDF_NAMESPACE_URI )
+        &&  ( $local_name == RDF_LI ) )
+    {
+        $this->rdf_parser['top']['parent']['members']++;
+        $this->rdf_parser['top']['ordinal'] = $this->rdf_parser['top']['parent']['members'];
+
+        $this->rdf_parser['top']['ordinal']=$this->rdf_parser['top']['ordinal'];
+
+        $buffer.='_'.$this->rdf_parser['top']['ordinal'];
+
+    }
+    else
+    {
+        $buffer.=$local_name;
+    }
+
+    $this->rdf_parser['top']['predicate']=$buffer;
+
+    $this->rdf_parser['top']['has_property_attributes'] = false;
+    $this->rdf_parser['top']['has_member_attributes'] = false;
+
+
+    for( $i = 0; isset($attributes[$i]); $i += 2 )
+    {
+        $this->_split_name(
+            $attributes[$i],
+            $buffer,
+            $attribute_namespace_uri,
+            $attribute_local_name );
+
+        $attribute_value = $attributes[$i + 1];
+
+        // if the attribute is not in any namespace
+        //   or the attribute is in the RDF namespace
+        if( ( $attribute_namespace_uri == '' )
+            || (  $attribute_namespace_uri == RDF_NAMESPACE_URI ) )
+        {
+            if( ( $attribute_local_name == RDF_ID )  )
+            {
+                $statement_id = $attribute_value;
+            }
+            else if( $attribute_local_name == RDF_PARSE_TYPE )
+            {
+                $parse_type = $attribute_value;
+            }
+            else if(  $attribute_local_name == RDF_RESOURCE )
+            {
+                $resource = $attribute_value;
+            }
+			else if(  $attribute_local_name == RDF_NODEID )
+            {
+				$node_id = $attribute_value;
+            }
+            else if(  $attribute_local_name == RDF_BAG_ID )
+            {
+                $bag_id = $attribute_value;
+            }
+			else if(  $attribute_local_name == RDF_DATATYPE )
+            {
+				$datatype = $attribute_value;
+				$this->rdf_parser['top']['datatype'] = $attribute_value;
+            }
+            else if( $this->_is_rdf_property_attribute( $attribute_local_name ) )
+            {
+                $this->rdf_parser['top']['has_property_attributes'] = true;
+            }
+            else
+            {
+                $this->_report_warning('unknown rdf attribute: '.$attribute_local_name );
+                return;
+            }
+        }
+        else if(  $attribute_namespace_uri == XML_NAMESPACE_URI  )
+        {
+            if( $attribute_local_name == XML_LANG  )
+            {
+                $this->rdf_parser['top']['xml_lang'] = $attribute_value;
+            }
+    		elseif ($attribute_local_name == 'base')
+    		{
+    			$this->rdf_parser['top']['element_base_uri'] = $attribute_value;
+    		}
+        }
+        else if( $attribute_namespace_uri )
+        {
+            $this->rdf_parser['top']['has_property_attributes'] = true;
+        }
+    }
+
+    if( $statement_id )
+    {
+	    $this->_resolve_id($statement_id, $buffer );
+        $this->rdf_parser['top']['statement_id']=$buffer;
+    }
+
+	if ($node_id)
+	{
+		$this->is_valid_id($node_id);
+
+		if ($resource)
+		{
+			$this->_report_error('nodeID and resource are mutually exclusive');
+		}
+       	if ($statement_id)
+       	{
+       		// reify statement
+       		$this->_report_statement(
+        		$this->rdf_parser['top']['parent']['subject_type'],
+        		$this->rdf_parser['top']['parent']['subject'],
+        		$this->rdf_parser['top']['predicate'],
+        		$this->rdf_parser['top']['ordinal'],
+        		RDF_OBJECT_TYPE_BNODE,
+        		$node_id,
+        		'',
+        		$this->rdf_parser['top']['parent']['bag_id'],
+        		$this->rdf_parser['top']['parent']['statements'],
+        		$this->rdf_parser['top']['statement_id'],
+				'');
+			$statement_id = '';
+       	}
+       	else
+       	{
+			$this->_report_statement(
+	           $this->rdf_parser['top']['parent']['subject_type'],
+	           $this->rdf_parser['top']['parent']['subject'],
+	           $this->rdf_parser['top']['predicate'],
+	           $this->rdf_parser['top']['ordinal'],
+	           RDF_OBJECT_TYPE_BNODE,
+	           $node_id,
+	           '',
+	           $this->rdf_parser['top']['parent']['bag_id'],
+	           $this->rdf_parser['top']['parent']['statements'],
+	           '',
+			   $datatype );
+       	}
+
+       	$this->rdf_parser['top']['state'] = IN_PROPERTY_EMPTY_RESOURCE;
+	}
+
+    if( $parse_type )
+	{
+        if( $resource ) {
+			$this->_report_error('property elements with rdf:parseType do not allow rdf:resource' );
+        }
+
+        if( $bag_id ) {
+            $this->_report_warning('property elements with rdf:parseType do not allow rdf:bagID' );
+            return;
+        }
+
+        if( $this->rdf_parser['top']['has_property_attributes'] )
+        {
+				$this->_report_error('property elements with rdf:parseType do not allow property attributes');
+            return;
+        }
+
+        if(  $attribute_value == RDF_PARSE_TYPE_RESOURCE )
+        {
+            $this->_generate_anonymous_uri( $buffer );
+            // since we are sure that this is now a resource property we can report it
+            $this->_report_statement(
+                $this->rdf_parser['top']['parent']['subject_type'],
+                $this->rdf_parser['top']['parent']['subject'],
+                $this->rdf_parser['top']['predicate'],
+                0,
+                RDF_OBJECT_TYPE_BNODE,
+                $buffer,
+                '',
+                $this->rdf_parser['top']['parent']['bag_id'],
+                $this->rdf_parser['top']['parent']['statements'],
+				$this->rdf_parser['top']['statement_id'],
+				$datatype );
+
+            $this->_push_element( );
+
+            $this->rdf_parser['top']['state'] = IN_PROPERTY_PARSE_TYPE_RESOURCE;
+            $this->rdf_parser['top']['subject_type'] = RDF_SUBJECT_TYPE_BNODE;
+            $this->rdf_parser['top']['subject']=$buffer;
+            $this->rdf_parser['top']['bag_id']='';
+			$this->rdf_parser['top']['datatype']= $datatype;
+
+        }
+       	elseif (  $attribute_value == RDF_PARSE_TYPE_LITERAL )
+       	{
+       		$this->rdf_parser['top']['state'] = IN_PROPERTY_PARSE_TYPE_LITERAL;
+       		$this->rdf_parser['top']['datatype']= RDF_NAMESPACE_URI .RDF_XMLLITERAL;
+       		$this->rdf_parser['xml_literal']['buffer'] = '';
+       		$this->rdf_parser['xml_literal']['depth'] = 0;
+       	}
+		elseif ($attribute_value == RDF_PARSE_TYPE_COLLECTION)
+		{
+			$this->_generate_anonymous_uri( $buffer );
+            $this->_report_statement(
+                $this->rdf_parser['top']['parent']['subject_type'],
+                $this->rdf_parser['top']['parent']['subject'],
+                $this->rdf_parser['top']['predicate'],
+                0,
+                RDF_OBJECT_TYPE_BNODE,
+                $buffer,
+                '',
+                $this->rdf_parser['top']['parent']['bag_id'],
+                $this->rdf_parser['top']['parent']['statements'],
+				$this->rdf_parser['top']['statement_id'],
+				$datatype );
+
+			$this->rdf_parser['top']['state'] = IN_PROPERTY_PARSE_TYPE_COLLECTION;
+			$this->rdf_parser['top']['collection']['first_blank_node_id'] = $buffer;
+		}
+
+        else
+        {
+
+			$this->_report_statement(
+                $this->rdf_parser['top']['parent']['subject_type'],
+                $this->rdf_parser['top']['parent']['subject'],
+                $this->rdf_parser['top']['predicate'],
+                0,
+                RDF_OBJECT_TYPE_XML,
+                '',
+                '',
+                $this->rdf_parser['top']['parent']['bag_id'],
+                $this->rdf_parser['top']['parent']['statements'],
+				$this->rdf_parser['top']['statement_id'],
+    			$datatype );
+
+            $this->rdf_parser['top']['state'] = IN_PROPERTY_PARSE_TYPE_LITERAL;
+        }
+    }
+    else if( $resource !== NULL || $bag_id || $this->rdf_parser['top']['has_property_attributes'] )
+    	{
+        if( $resource !== NULL )
+        {
+            $subject_type = RDF_SUBJECT_TYPE_URI;
+			$this->_resolve_uri_reference( $this->rdf_get_base(), $resource, $buffer );
+        	$object_type=RDF_OBJECT_TYPE_RESOURCE;
+        }
+        else
+        {
+			$subject_type = RDF_SUBJECT_TYPE_BNODE;
+            $this->_generate_anonymous_uri( $buffer );
+            $object_type=RDF_OBJECT_TYPE_BNODE;
+        }
+        $this->rdf_parser['top']['state'] = IN_PROPERTY_EMPTY_RESOURCE;
+
+        // since we are sure that this is now a resource property we can report it.
+		$this->_report_statement(
+            $this->rdf_parser['top']['parent']['subject_type'],
+            $this->rdf_parser['top']['parent']['subject'],
+            $this->rdf_parser['top']['predicate'],
+            $this->rdf_parser['top']['ordinal'],
+            $object_type,
+            $buffer,
+            '',
+            $this->rdf_parser['top']['parent']['bag_id'],
+            $this->rdf_parser['top']['parent']['statements'],
+			$this->rdf_parser['top']['statement_id'],
+			$datatype ); // should we allow IDs?
+
+        if( $bag_id )
+        {
+            $this->_resolve_id( $bag_id, $buffer );
+            $this->rdf_parser['top']['bag_id']=$buffer;
+        }
+
+        if( $this->rdf_parser['top']['has_property_attributes'] )
+        {
+            $this->_handle_property_attributes(
+                $subject_type,
+                $buffer,
+                $attributes,
+                $this->rdf_parser['top']['xml_lang'],
+                $this->rdf_parser['top']['bag_id'],
+                $this->rdf_parser['top']['statements'] );
+        }
+    }
+}
+
+/**
+   * @param string &$namespace_uri
+   * @param string &$local_name
+   * @param string &$attributes
+   * @access	private
+*/
+function _handle_collection_element(&$namespace_uri, &$local_name, &$attributes)
+{
+	$aux2=Array();
+    foreach($attributes as $atkey=>$atvalue) {
+      $aux2[]=$atkey;
+      $aux2[]=$atvalue;
+    }
+    $attributes=$aux2;
+/* collection construction site
+// old:
+	if (   ($namespace_uri == RDF_NAMESPACE_URI || $namespace_uri == '')
+	    && ($local_name == RDF_DESCRIPTION || $local_name == RDF_LI) )
+	{
+		for( $i = 0; isset($attributes[$i]); $i += 2 )
+    	{
+			$this->_split_name(
+            	$attributes[ $i ],
+            	$attribute,
+            	$attribute_namespace_uri,
+            	$attribute_local_name );
+
+        	$attribute_value = $attributes[ $i + 1 ];
+
+        	if( $attribute_namespace_uri == '' || $attribute_namespace_uri == RDF_NAMESPACE_URI  )
+	        {
+        	    if( $attribute_local_name == RDF_ABOUT ||
+        	        $attribute_local_name == RDF_RESOURCE)
+        	    {
+					$this->rdf_parser['top']['parent']['collection']['object_type'][] = RDF_OBJECT_TYPE_RESOURCE;
+        	    }
+        	    elseif ( $attribute_local_name == RDF_NODEID ) {
+        	    	$this->rdf_parser['top']['parent']['collection']['object_type'][] = RDF_OBJECT_TYPE_BNODE;
+        	    }
+        	    $this->rdf_parser['top']['parent']['collection']['object_label'][] = $attribute_value;
+    		}
+    	}
+	}
+*/
+// new
+
+		for( $i = 0; isset($attributes[$i]); $i += 2 )
+    	{
+			$this->_split_name(
+            	$attributes[ $i ],
+            	$attribute,
+            	$attribute_namespace_uri,
+            	$attribute_local_name );
+
+        	$attribute_value = $attributes[ $i + 1 ];
+
+        	if( $attribute_namespace_uri == '' || $attribute_namespace_uri == RDF_NAMESPACE_URI  )
+	        {
+	        	$tmp_subject_type = RDF_SUBJECT_TYPE_URI;
+        	    if( $attribute_local_name == RDF_ABOUT ||
+        	        $attribute_local_name == RDF_RESOURCE)
+        	    {
+					$this->rdf_parser['top']['parent']['collection']['object_type'][] = RDF_OBJECT_TYPE_RESOURCE;
+        	    }
+        	    elseif ( $attribute_local_name == RDF_NODEID ) {
+        	    	$this->rdf_parser['top']['parent']['collection']['object_type'][] = RDF_OBJECT_TYPE_BNODE;
+        	    	$tmp_subject_type = RDF_SUBJECT_TYPE_BNODE;
+        	    }
+        	    $id_buffer = '';
+        	    $this->_resolve_uri_reference( $this->rdf_get_base(), $attribute_value, $id_buffer );
+        	    $this->rdf_parser['top']['parent']['collection']['object_label'][] = $id_buffer;
+
+       	    	if (!(   ($namespace_uri == RDF_NAMESPACE_URI || $namespace_uri == '')
+	 			      && ($local_name == RDF_DESCRIPTION || $local_name == RDF_LI) ))
+				   {
+					  $this->_report_statement(
+							$tmp_subject_type,
+							$id_buffer,
+							RDF_NAMESPACE_URI.RDF_TYPE,
+							'',
+							RDF_OBJECT_TYPE_RESOURCE,
+							$namespace_uri.$local_name,
+							'',
+							'',
+							'',
+							'',
+							'');
+				   }
+    		}
+    	}
+
+
+// collection construction site
+}
+
+/**
+   * @param string &$namespace_uri
+   * @param string &$local_name
+   * @param string &$attributes
+   * @access	private
+*/
+function _handle_xml_start_element(&$namespace_uri, &$local_name, &$attributes)
+{
+	$aux2=Array();
+    foreach($attributes as $atkey=>$atvalue) {
+      $aux2[]=$atkey;
+      $aux2[]=$atvalue;
+    }
+    $attributes=$aux2;
+
+    $element = '<' .$this->_join_name_and_declare_prefix($namespace_uri, $local_name);
+
+    for( $i = 0; isset($attributes[$i]); $i += 2 )
+    	{
+			$this->_split_name(
+            	$attributes[ $i ],
+            	$attribute,
+            	$attribute_namespace_uri,
+            	$attribute_local_name );
+
+        	$attribute_value = $attributes[ $i + 1 ];
+
+			$element .= ' ' .$this->_join_name_and_declare_prefix($attribute_namespace_uri, $attribute_local_name);
+			$element .= '=\"' .$attribute_value .'\"';
+    	}
+    $element .= '>';
+
+    $this->rdf_parser['xml_literal']['buffer'] .= $element;
+}
+
+/**
+   * @param string $name
+   * @access	private
+*/
+function _handle_xml_end_element($name)
+{
+	$buffer='';
+	$namespace_uri='';
+    $local_name='';
+
+	$this->_split_name(
+        $name,
+       	$buffer,
+       	$namespace_uri,
+       	$local_name );
+
+    $element = '</';
+
+	if ($namespace_uri && isset($this->rdf_parser['default_namespace'])
+	    &&$namespace_uri != $this->rdf_parser['default_namespace'])
+	{
+ 		$element .= $this->rdf_parser['namespaces'][$namespace_uri] .':';
+	}
+
+    $element .= $local_name .'>';
+
+    $this->rdf_parser['xml_literal']['buffer'] .= $element;
+    $depth = $this->rdf_parser['xml_literal']['depth']--;
+
+    if (isset($this->rdf_parser['xml_literal']['declared_ns']))
+      	foreach ($this->rdf_parser['xml_literal']['declared_ns'] as $prefix => $_depth)
+    {
+    	if ($depth == $_depth)
+        	unset($this->rdf_parser['xml_literal']['declared_ns'][$prefix]);
+    }
+}
+
+/**
+   * @param string $namespace_uri
+   * @param string $local_name
+   * @access	private
+*/
+function _join_name_and_declare_prefix($namespace_uri, $local_name) {
+
+	$name = '';
+
+	if ($namespace_uri)
+	{
+		if (isset($this->rdf_parser['default_namespace'])
+		    && $namespace_uri == $this->rdf_parser['default_namespace'])
+		{
+			$name .= $local_name;
+
+			if (!isset($this->rdf_parser['xml_literal']['declared_ns']['_DEFAULT_'])
+				&& $namespace_uri != XML_NAMESPACE_URI)
+			{
+				$name .= ' xmlns=' . '\"' .$namespace_uri .'\"';
+
+				$this->rdf_parser['xml_literal']['declared_ns']['_DEFAULT_']
+					= $this->rdf_parser['xml_literal']['depth'];
+			}
+		}
+		else
+		{
+			$ns_prefix = $this->rdf_parser['namespaces'][$namespace_uri];
+			$name .= $ns_prefix .':' .$local_name;
+
+			if (!isset($this->rdf_parser['xml_literal']['declared_ns'][$ns_prefix])
+				&& $namespace_uri != XML_NAMESPACE_URI)
+			{
+				$name .= " xmlns:$ns_prefix=" . '\"' .$namespace_uri .'\"';
+
+				$this->rdf_parser['xml_literal']['declared_ns'][$ns_prefix]
+					= $this->rdf_parser['xml_literal']['depth'];
+			}
+		}
+
+	}
+	else
+		$name .= $local_name;
+
+	return $name;
+
+}
+
+/**
+  * @access	private
+*/
+function _end_collection() {
+
+	if (isset($this->rdf_parser['top']['collection']))
+	{
+
+		$subject = $this->rdf_parser['top']['collection']['first_blank_node_id'];
+
+		for ($i=0; isset($this->rdf_parser['top']['collection']['object_label'][$i]); $i++)
+		{
+
+			$this->_report_statement(
+				RDF_SUBJECT_TYPE_BNODE,
+				$subject,
+				RDF_NAMESPACE_URI.RDF_FIRST,
+				'',
+				$this->rdf_parser['top']['collection']['object_type'][$i],
+				$this->rdf_parser['top']['collection']['object_label'][$i],
+				'',
+				'',
+				'',
+				'',
+				'');
+
+			if (!isset($this->rdf_parser['top']['collection']['object_label'][$i+1]))
+			{
+				$obj_type_2 = RDF_OBJECT_TYPE_RESOURCE;
+				$object_2 = RDF_NAMESPACE_URI.RDF_NIL;
+			}
+			else
+			{
+				$obj_type_2= RDF_OBJECT_TYPE_BNODE;
+				$this->_generate_anonymous_uri($object_2);
+			}
+
+
+			$this->_report_statement(
+				RDF_SUBJECT_TYPE_BNODE,
+				$subject,
+				RDF_NAMESPACE_URI.RDF_REST,
+				'',
+				$obj_type_2,
+				$object_2,
+				'',
+				'',
+				'',
+				'',
+				'');
+
+			$subject = $object_2;
+		}
+	}
+}
+
+/**
+   * @param string $parser
+   * @param string $name
+   * @param string $attributes
+   * @access	private
+*/
+function _start_element_handler($parser, $name, $attributes )
+{
+    $buffer='';
+
+    $namespace_uri='';
+    $local_name='';
+
+    $this->_push_element();
+
+
+    $this->_split_name(
+        $name,
+        $buffer,
+        $namespace_uri,
+        $local_name );
+
+    switch( $this->rdf_parser['top']['state'] )
+    {
+    case IN_TOP_LEVEL:
+		// set base_uri, if possible
+		foreach ($attributes as $key => $value) {
+	         if($key == XML_NAMESPACE_URI . NAMESPACE_SEPARATOR_CHAR . 'base') {
+			 		$this->rdf_parser['base_uri'] = $value;
+					$this->rdf_parser['document_base_uri'] = $value;
+
+					$c = substr($value, strlen($value)-1 ,1);
+					if (!($c=='#' || $c==':' || $c=='/' || $c=="\\"))
+						 $this->rdf_parser['normalized_base_uri'] = $value . '#';
+					else
+						$this->rdf_parser['normalized_base_uri'] = $value;
+
+			  }
+			  elseif ($key == XML_NAMESPACE_URI . NAMESPACE_SEPARATOR_CHAR .'lang')
+			  	$this->rdf_parser['document_xml_lang'] = $value;
+echo "";
+		}
+
+
+		if( RDF_NAMESPACE_URI.NAMESPACE_SEPARATOR_STRING.RDF_RDF == $name )
+        {
+			$this->rdf_parser['top']['state'] = IN_RDF;
+
+			break;
+        }
+    case IN_RDF:
+        $this->rdf_parser['top']['state'] = IN_DESCRIPTION;
+        $this->_handle_resource_element( $namespace_uri, $local_name, $attributes, '' );
+        break;
+    case IN_DESCRIPTION:
+    case IN_PROPERTY_PARSE_TYPE_RESOURCE:
+ 		$this->rdf_parser['top']['state'] = IN_PROPERTY_UNKNOWN_OBJECT;
+        $this->_handle_property_element( $namespace_uri, $local_name, $attributes );
+        break;
+   	case IN_PROPERTY_PARSE_TYPE_COLLECTION:
+		$this->_handle_collection_element($namespace_uri, $local_name, $attributes);
+		break;
+    case IN_PROPERTY_UNKNOWN_OBJECT:
+        /* if we're in a property with an unknown object type and we encounter
+           an element, the object must be a resource, */
+        $this->rdf_parser['top']['data']='';
+        $this->rdf_parser['top']['parent']['state'] = IN_PROPERTY_RESOURCE;
+        $this->rdf_parser['top']['state'] = IN_DESCRIPTION;
+        $this->_handle_resource_element(
+            $namespace_uri,
+            $local_name,
+            $attributes,
+            $this->rdf_parser['top']['parent'] );
+        break;
+    case IN_PROPERTY_LITERAL:
+        $this->_report_warning( 'no markup allowed in literals' );
+        break;
+    case IN_PROPERTY_PARSE_TYPE_LITERAL:
+    	$this->rdf_parser['top']['state'] = IN_XML;
+        /* fall through */
+    case IN_XML:
+		$this->rdf_parser['xml_literal']['depth']++;
+		$this->_handle_xml_start_element($namespace_uri, $local_name, $attributes);
+        break;
+    case IN_PROPERTY_RESOURCE:
+        $this->_report_warning(
+                     'only one element allowed inside a property element' );
+        break;
+    case IN_PROPERTY_EMPTY_RESOURCE:
+        $this->_report_warning(
+                    'no content allowed in property with rdf:resource, rdf:bagID, or property attributes' );
+        break;
+    case IN_UNKNOWN:
+        break;
+    }
+}
+
+/**
+    property elements with text only as content set the state to
+    IN_PROPERTY_LITERAL. as character data is received from expat,
+    it is saved in a buffer and reported when the end tag is
+    received.
+  * @access	private
+*/
+function _end_literal_property()
+{
+    if(!isset($this->rdf_parser['top']['statement_id'])) {
+      $this->rdf_parser['top']['statement_id']='';
+    }
+    if(!isset($this->rdf_parser['top']['parent']['subject_type'])) {
+      $this->rdf_parser['top']['parent']['subject_type']='';
+    }
+    if(!isset($this->rdf_parser['top']['parent']['subject'])) {
+      $this->rdf_parser['top']['parent']['subject']='';
+    }
+    if(!isset($this->rdf_parser['top']['parent']['bag_id'])) {
+      $this->rdf_parser['top']['parent']['bag_id']='';
+    }
+    if(!isset($this->rdf_parser['top']['parent']['statements'])) {
+      $this->rdf_parser['top']['parent']['statements']=0;
+    }
+    if(!isset($this->rdf_parser['top']['predicate'])) {
+      $this->rdf_parser['top']['predicate']='';
+    }
+    if(!isset($this->rdf_parser['top']['datatype'])) {
+      $this->rdf_parser['top']['datatype']='';
+    }
+    if(!isset($this->rdf_parser['top']['ordinal'])) {
+      $this->rdf_parser['top']['ordinal']=0;
+    }
+    $this->_report_statement(
+        $this->rdf_parser['top']['parent']['subject_type'],
+        $this->rdf_parser['top']['parent']['subject'],
+        $this->rdf_parser['top']['predicate'],
+        $this->rdf_parser['top']['ordinal'],
+        RDF_OBJECT_TYPE_LITERAL,
+        $this->rdf_parser['top']['data'],
+        $this->rdf_parser['top']['xml_lang'],
+        $this->rdf_parser['top']['parent']['bag_id'],
+        $this->rdf_parser['top']['parent']['statements'],
+        $this->rdf_parser['top']['statement_id'],
+		$this->rdf_parser['top']['datatype']);
+
+}
+
+/**
+   * @param string $parser
+   * @param string $name
+   * @access	private
+*/
+function _end_element_handler( $parser, $name )
+{
+    switch( $this->rdf_parser['top']['state'] )
+    {
+    case IN_TOP_LEVEL:
+		break;
+    case IN_XML:
+		$this->_handle_xml_end_element($name);
+        break;
+    case IN_PROPERTY_UNKNOWN_OBJECT:
+    case IN_PROPERTY_LITERAL:
+        $this->_end_literal_property( );
+        break;
+    case IN_PROPERTY_PARSE_TYPE_RESOURCE:
+        $this->_pop_element(  );
+        break;
+    case IN_PROPERTY_PARSE_TYPE_LITERAL:
+//		$search =  array((0) => chr(10), (1) => chr(13), (2) => chr(9));
+//		$replace = array((0) => '\n'   , (1) => '\r'   , (2) => '\t');
+//		$this->rdf_parser["xml_literal"]["buffer"]
+//			= str_replace($search, $replace, $this->rdf_parser["xml_literal"]["buffer"]);
+
+		$this->rdf_parser['top']['data'] = $this->rdf_parser['xml_literal']['buffer'];
+		$this->_end_literal_property();
+		$this->rdf_parser['xml_literal']['buffer'] = '';
+
+        break;
+	case IN_PROPERTY_PARSE_TYPE_COLLECTION:
+	    $this->_end_collection();
+		break;
+    case IN_RDF:
+    case IN_DESCRIPTION:
+    case IN_PROPERTY_RESOURCE:
+    case IN_PROPERTY_EMPTY_RESOURCE:
+    case IN_UNKNOWN:
+        break;
+    }
+
+    $this->_pop_element();
+}
+
+/**
+   * @param string $parser
+   * @param string $s
+   * @access	private
+*/
+function _character_data_handler( $parser,$s)
+{
+    $len=strlen($s);
+    switch( $this->rdf_parser['top']['state'] )
+    {
+    case IN_PROPERTY_LITERAL:
+    case IN_PROPERTY_UNKNOWN_OBJECT:
+        if( isset($this->rdf_parser['top']['data']) )
+        {
+            $n = strlen( $this->rdf_parser['top']['data'] );
+            $this->rdf_parser['top']['data'].= $s;
+
+        }
+        else
+        {
+            $this->rdf_parser['top']['data']=$s;
+        }
+
+        if( $this->rdf_parser['top']['state'] == IN_PROPERTY_UNKNOWN_OBJECT )
+        {
+            /* look for non-whitespace */
+            for( $i = 0; (( $i < $len ) && (  preg_match("' |\n|\t'",$s{ $i }) )); $i++ );
+            /* if we found non-whitespace, this is a literal */
+            if( $i < $len )
+            {
+                $this->rdf_parser['top']['state'] = IN_PROPERTY_LITERAL;
+            }
+        }
+
+        break;
+    case IN_TOP_LEVEL:
+    	break;
+    case IN_PROPERTY_PARSE_TYPE_LITERAL:
+    case IN_XML:
+        $this->rdf_parser['xml_literal']['buffer'] .= $s;
+        break;
+    case IN_RDF:
+    case IN_DESCRIPTION:
+    case IN_PROPERTY_RESOURCE:
+    case IN_PROPERTY_EMPTY_RESOURCE:
+    case IN_PROPERTY_PARSE_TYPE_RESOURCE:
+    case IN_UNKNOWN:
+        break;
+    }
+}
+
+
+  /**
+   * Adds a new statement to the model
+   * This method is called by generateModel().
+   *
+   * @access	private
+   * @param	string	&$user_data
+   * @param	string	$subject_type
+   * @param	string	$subject
+   * @param	string	$predicate
+   * @param	string	$ordinal
+   * @param	string	$object_type
+   * @param	string	$object
+   * @param	string	$xml_lang )
+   * @return	object MemModel
+   */
+function add_statement_to_model(
+	&$user_data,
+	$subject_type,
+	$subject,
+	$predicate,
+	$ordinal,
+	$object_type,
+	$object,
+	$xml_lang,
+	$datatype )
+{
+
+	// ParseUnicode
+	if(UNIC_RDF){
+		$subject=$this->str2unicode_nfc($subject);
+		$predicate=$this->str2unicode_nfc($predicate);
+		$object=$this->str2unicode_nfc($object);
+	}
+
+	//create subject
+	if ($subject_type == RDF_SUBJECT_TYPE_BNODE)
+			$objsub = new BlankNode($subject);
+	    else
+			$objsub = new Resource($subject);
+
+	// create predicate
+	$objpred = new Resource($predicate);
+
+	// create object
+	if (($object_type == RDF_OBJECT_TYPE_RESOURCE) || ($object_type == RDF_OBJECT_TYPE_BNODE)) {
+			if ($object_type == RDF_OBJECT_TYPE_BNODE)
+					$objobj = new BlankNode($object);
+				else
+					$objobj = new Resource($object);
+	} else {
+
+		$objobj = new Literal($object);
+		if ($datatype != '') {
+			$objobj->setDatatype($datatype);
+		}
+		elseif ($xml_lang !='') {
+			$objobj->setLanguage($xml_lang);
+		}
+	}
+
+	// create statement
+	$statement = new Statement($objsub, $objpred, $objobj);
+
+	// add statement to model
+	if(CREATE_MODEL_WITHOUT_DUPLICATES == TRUE){
+		$this->model->addWithoutDuplicates($statement);
+	}else
+		$this->model->add($statement);
+	}
+
+
+/* public functions */
+
+  /**
+   * Generates a new MemModel from a URI, a file or from memory.
+   * If you want to parse an RDF document, pass the URI or location in the filesystem
+   * of the RDF document. You can also pass RDF code direct to the function. If you pass
+   * RDF code directly to the parser and there is no xml:base included, you should set
+   * the base URI manually using the optional second parameter $rdfBaseURI.
+   * Make sure that here are proper namespace declarations in your input document.
+   *
+   * @access	public
+   * @param		string	 $base
+   * @param     boolean  $rdfBaseURI
+   * @return	object MemModel
+   */
+function & generateModel($base,$rdfBaseURI = false, $model = false) {
+
+	// Check if $base is a URI or filename or a string containing RDF code.
+	if (substr(ltrim($base),0 ,1) != '<') {
+
+	// $base is URL or filename
+	$this->model = $model?$model:new MemModel($base);
+
+	$input = fopen($base,'r') or die("RDF Parser: Could not open File: $base. Stopped parsing.");
+	$this->rdf_parser_create( NULL );
+	$this->rdf_set_base($base);
+	$done=false;
+	while(!$done)
+	{
+	  $buf = fread( $input, 512 );
+	  $done = feof($input);
+
+	  if ( ! $this->rdf_parse( $buf, feof($input) ) )
+	  {
+	    $err_code = xml_get_error_code( $this->rdf_get_xml_parser());
+		$line = xml_get_current_line_number($this->rdf_get_xml_parser() );
+	    $errmsg = RDFAPI_ERROR . '(class: parser; method: generateModel): XML-parser-error ' . $err_code .' in Line ' . $line .' of input document.';
+	    trigger_error($errmsg, E_USER_ERROR);
+	  }
+	}
+	/* close file. */
+	fclose( $input );
+
+	} else {
+	// $base is RDF string
+    $this->model = $model?$model:new MemModel($base);
+
+	$this->rdf_parser_create( NULL );
+
+	if ($rdfBaseURI!==false)
+	{
+		$this->rdf_set_base($rdfBaseURI);
+	} else
+	{
+		$this->rdf_set_base( NULL );
+	}
+
+	  if ( ! $this->rdf_parse( $base, TRUE ) )
+	  {
+	    $err_code = xml_get_error_code( $this->rdf_get_xml_parser());
+		$line = xml_get_current_line_number($this->rdf_get_xml_parser() );
+	    $errmsg = RDFAPI_ERROR . '(class: parser; method: generateModel): XML-parser-error ' . $err_code .' in Line ' . $line .' of input document.';
+	    trigger_error($errmsg, E_USER_ERROR);
+	  }
+	}
+	// base_uri could have changed while parsing
+	$this->model->setBaseURI($this->rdf_parser['base_uri']);
+
+	if(isset($this->rdf_parser['namespaces'])){
+		$this->model->addParsedNamespaces($this->rdf_parser['namespaces']);
+	}
+
+	$this->rdf_parser_free();
+
+	return $this->model;
+
+}
+
+/**
+ * @param		string	 $encoding
+
+ * @access	private
+*/
+function rdf_parser_create( $encoding )
+{
+
+    $parser = xml_parser_create_ns( $encoding, NAMESPACE_SEPARATOR_CHAR );
+
+    xml_parser_set_option($parser,XML_OPTION_CASE_FOLDING,0);
+    $this->rdf_parser['xml_parser'] = $parser;
+
+    xml_set_object($this->rdf_parser['xml_parser'], $this);
+    xml_set_element_handler( $this->rdf_parser['xml_parser'], '_start_element_handler', '_end_element_handler' );
+    xml_set_character_data_handler( $this->rdf_parser['xml_parser'], '_character_data_handler' );
+	xml_set_start_namespace_decl_handler($this->rdf_parser['xml_parser'], '_start_ns_declaration_handler');
+
+    return $this->rdf_parser;
+}
+
+/**
+ * @param	resource	&$parser
+ * @param   string		$ns_prefix
+ * @param	string		$ns_uri
+ * @access	private
+*/
+function _start_ns_declaration_handler(&$parser, $ns_prefix, $ns_uri)
+{
+	if (!$ns_prefix)
+		$this->rdf_parser['default_namespace'] = $ns_uri;
+	else
+		$this->rdf_parser['namespaces'][$ns_uri] = $ns_prefix;
+}
+
+
+/**
+ * @access	private
+*/
+function rdf_parser_free( )
+{
+    $z=3;
+
+    $this->rdf_parser['base_uri']='';
+	$this->rdf_parser['document_base_uri'] = '';
+
+    unset( $this->rdf_parser );
+}
+
+/**
+   * @param		string	 $s
+   * @param		string	 $is_final
+ * @access	private
+*/
+function rdf_parse( $s, $is_final )
+{
+    return XML_Parse( $this->rdf_parser['xml_parser'], $s, $is_final );
+}
+
+/**
+ * @access	private
+*/
+function rdf_get_xml_parser()
+{
+    return ( $this->rdf_parser['xml_parser']);
+}
+
+/**
+   * @param		string	 $base
+ * @access	private
+*/
+function rdf_set_base($base )
+{
+
+    $this->rdf_parser['base_uri']=$base;
+
+	$c = substr($base, strlen($base)-1 ,1);
+	if (!($c=='#' || $c==':' || $c=='/' || $c=="\\"))
+		 $this->rdf_parser['normalized_base_uri'] = $base . '#';
+	else
+		$this->rdf_parser['normalized_base_uri'] = $base;
+
+    return 0;
+}
+
+/**
+ * @access	private
+*/
+function rdf_get_base()
+{
+		if ($this->rdf_parser['top']['element_base_uri'])
+			return $this->rdf_parser['top']['element_base_uri'];
+		else
+			return $this->rdf_parser['base_uri'];
+}
+
+
+} // end: rdf_parser
+
+?>
Index: /Dev/trunk/rdfapi/syntax/RdfSerializer.php
===================================================================
--- /Dev/trunk/rdfapi/syntax/RdfSerializer.php	(revision 12)
+++ /Dev/trunk/rdfapi/syntax/RdfSerializer.php	(revision 12)
@@ -0,0 +1,723 @@
+<?php
+
+
+// ----------------------------------------------------------------------------------
+// Class: RdfSerializer
+// ----------------------------------------------------------------------------------
+
+/**
+* An RDF seralizer.
+* Seralizes models to RDF syntax. It supports the xml:base, xml:lang, rdf:datatype and
+* rdf:nodeID directive.
+* You can choose between different output syntaxes by using the configuration methods
+* or changing the configuration default values in constants.php.
+* This class is based on the java class edu.unika.aifb.rdf.api.syntax.RDFSerializer by Boris Motik.
+*
+* @version  $Id: RdfSerializer.php 316 2006-08-24 07:55:29Z tgauss $
+* @author Chris Bizer <chris@bizer.de>, Boris Motik <motik@fzi.de>, Daniel Westphal <dawe@gmx.de>, Leandro Mariano Lopez <llopez@xinergiaargentina.com>
+*
+* @package syntax
+* @access  public
+*
+*/
+class RdfSerializer extends Object {
+
+	// configuration
+	var $use_entities;
+	var $use_attributes;
+	var $sort_model;
+	var $rdf_qnames;
+	var $use_xml_declaration;
+
+	// properties
+	var  $m_defaultNamespaces  = array();
+	var  $m_namespaces = array();
+	var  $m_nextAutomaticPrefixIndex;
+	var  $m_out;
+	var  $m_baseURI;
+	var  $m_statements = array();
+	var  $m_currentSubject;
+	var  $m_rdfIDElementText;
+	var  $m_rdfAboutElementText;
+	var  $m_rdfResourceElementText;
+	var  $m_groupTypeStatement;
+	var  $m_attributeStatements = array();
+	var  $m_contentStatements = array();
+	var  $rdf_qname_prefix;
+
+	/**
+	* Constructor
+	*
+	* @access   public
+	*/
+	function RdfSerializer() {
+
+		// default serializer configuration
+		$this->use_entities = SER_USE_ENTITIES;
+		$this->use_attributes = SER_USE_ATTRIBUTES;
+		$this->sort_model = SER_SORT_MODEL;
+		$this->rdf_qnames = SER_RDF_QNAMES;
+		$this->use_xml_declaration = SER_XML_DECLARATION;
+
+		global $default_prefixes;
+		foreach($default_prefixes as $key => $value){
+			$this->addNamespacePrefix($key,$value);
+		}
+
+		require_once(RDFAPI_INCLUDE_DIR.PACKAGE_UTILITY);
+	}
+
+	/**
+	* Serializer congiguration: Sort Model
+	* Flag if the serializer should sort the model by subject before serializing.
+	* TRUE makes the RDF code more compact.
+	* TRUE is default. Default can be changed in constants.php.
+	*
+	* @param     boolean
+	* @access    public
+	*/
+	function configSortModel($bool) {
+		$this->sort_model = $bool;
+	}
+
+	/**
+	* Serializer congiguration: Use Entities
+	* Flag if the serializer should use entities for URIs.
+	* TRUE makes the RDF code more compact.
+	* FALSE is default. Default can be changed in constants.php.
+	*
+	* @param     boolean
+	* @access    public
+	*/
+	function configUseEntities($bool) {
+		$this->use_entities = $bool;
+	}
+
+	/**
+	* Serializer congiguration: Use Attributes
+	* Flag if the serializer should serialize triples as XML attributes where possible.
+	* TRUE makes the RDF code more compact.
+	* FALSE is default. Default can be changed in constants.php.
+	*
+	* @param     boolean
+	* @access    public
+	*/
+	function configUseAttributes($bool) {
+		$this->use_attributes = $bool;
+	}
+
+	/**
+	* Serializer congiguration: Use Qnames
+	* Flag if the serializer should use qualified names for RDF reserved words.
+	* TRUE makes the RDF code more compact.
+	* TRUE is default. Default can be changed in constants.php.
+	*
+	* @param     boolean
+	* @access    public
+	*/
+	function configUseQnames($bool) {
+		$this->rdf_qnames = $bool;
+	}
+
+	/**
+	* Serializer congiguration: Use XML Declaration
+	* Flag if the serializer should start documents with the xml declaration
+	* <?xml version="1.0" encoding="UTF-8" ?>.
+	* TRUE is default. Default can be changed in constants.php.
+	*
+	* @param             boolean
+	* @access    public
+	*/
+	function configUseXmlDeclaration($bool) {
+		$this->use_xml_declaration = $bool;
+	}
+
+
+	/**
+	* Adds a new prefix/namespace combination.
+	*
+	* @param     String $prefix
+	* @param     String $namespace
+	* @access    public
+	*/
+	function addNamespacePrefix($prefix, $namespace) {
+		$this->m_defaultNamespaces[$prefix] = $namespace;
+	}
+
+	/**
+	* Serializes a model to RDF syntax.
+	* RDF syntax can be changed by config_use_attributes($boolean), config_use_entities($boolean),
+	* config_sort_model($boolean).
+	* NOTE: There is only one default namespace allowed within an XML document.
+	*       Therefore if SER_RDF_QNAMES in constants.php is set to FALSE and you pass
+	*       another $xml_default_namespace as parameter, the model will be serialized
+	*       as if SER_RDF_QNAMES were set to TRUE.
+	*
+	* @param     object MemModel $model
+	* @param     String $encoding
+	* @return    string
+	* @access    public
+	*/
+	function & serialize(&$model, $xml_default_namespace = NULL, $encoding = DEFAULT_ENCODING) {
+
+		if ($xml_default_namespace) {
+
+			if ($xml_default_namespace == RDF_NAMESPACE_URI) {
+				$this->rdf_qnames = FALSE;
+				unset($this->m_defaultNamespaces[RDF_NAMESPACE_PREFIX]);
+			}
+			elseif ($xml_default_namespace == RDF_SCHEMA_URI) {
+				unset($this->m_defaultNamespaces[RDF_SCHEMA_PREFIX]);
+			}
+			elseif (!SER_RDF_QNAMES)
+			$this->rdf_qnames = TRUE;
+
+			$this->addNamespacePrefix(NULL, $xml_default_namespace);
+		}
+
+		//copy parsed namespaces
+		$nsps = array();
+		$nsps = $model->getParsedNamespaces();
+		foreach($this->m_defaultNamespaces as $prefix => $namespace){
+			if(!isset ($nsps[$namespace]))
+			$nsps[$namespace] = $prefix;
+		}
+
+		// define rdf prefix (qname or not)
+		if ($this->rdf_qnames){
+			if(isset($nsps[RDF_NAMESPACE_URI])){
+				$this->rdf_qname_prefix = $nsps[RDF_NAMESPACE_URI].':';
+			}else{
+				$this->rdf_qname_prefix = RDF_NAMESPACE_PREFIX . ':';
+			}
+
+		}else{
+			$this->rdf_qname_prefix = '';
+		}
+		// check if model is empty
+		if ($model->size() == 0) return "<". $this->rdf_qname_prefix . RDF_RDF ." xmlns:rdf='".RDF_NAMESPACE_URI."' />";
+
+		foreach($nsps as $ns => $pre){
+			$this->m_namespaces[$pre] = $ns;
+		}
+
+
+		// set base URI
+		if ($model->getBaseURI()==NULL)
+		$this->m_baseURI="opaque:uri";
+		else
+		$this->m_baseURI=$model->getBaseURI();
+
+
+		if ($this->sort_model) {
+			// sort the array of statements
+
+			foreach($model->triples as $key => $statement) {
+				$stmkey = $statement->subj->getURI() .
+				$statement->pred->getURI() .
+				(is_a($statement->obj,'Literal')?'"'.$statement->obj->getLabel().'"@'.$statement->obj->getLanguage().'^^'.$statement->obj->getDatatype():$statement->obj->getURI());
+				$this->m_statements[$stmkey] = $statement;
+			}
+			ksort($this->m_statements);
+
+			/*
+			// Sort using the PHP usort() function. Slower :-(
+			$this->m_statements = $model->triples;
+			usort($this->m_statements, "statementsorter");
+			*/
+		} else {
+			$this->m_statements = $model->triples;
+		}
+		// collects namespaces
+		$this->m_nextAutomaticPrefixIndex=0;
+		$this->collectNamespaces($model);
+
+		// start writing the contents
+		$this->m_out="";
+		if ($this->use_xml_declaration)
+		$this->m_out .= '<?xml version="1.0" encoding="' . $encoding . '" ?>' . LINEFEED;
+		if (!HIDE_ADVERTISE)
+		$this->m_out.="<!-- Generated by RdfSerializer.php from RDF RAP.".LINEFEED."# http://www.wiwiss.fu-berlin.de/suhl/bizer/rdfapi/index.html !-->".LINEFEED.LINEFEED ;
+
+		// write entitie declarations
+		if($this->use_entities) {
+			$this->m_out .= '<!DOCTYPE ' . $this->rdf_qname_prefix .
+			RDF_RDF.' [' . LINEFEED;
+			$this->writeEntityDeclarations();
+			$this->m_out .= LINEFEED . ']>' . LINEFEED;
+		}
+
+		// start the RDF text
+		$this->m_out .= '<' . $this->rdf_qname_prefix . RDF_RDF;
+
+		// write the xml:base
+		if ($model->getBaseURI() != NULL)
+		$this->m_out .= LINEFEED. INDENTATION .'xml:base="'.$model->getBaseURI().'"';
+
+		// write namespaces declarations
+		$this->writeNamespaceDeclarations();
+		$this->m_out .='>'. LINEFEED;
+
+		// write triples
+		$this->writeDescriptions();
+
+		$this->m_out .= LINEFEED;
+		$this->m_out .='</' . $this->rdf_qname_prefix . RDF_RDF .'>';
+
+		$this->m_namespaces=null;
+		$this->m_statements=null;
+		$this->m_currentSubject=null;
+		$this->m_groupTypeStatement=null;
+		$this->m_attributeStatements=null;
+		$this->m_contentStatements=null;
+		$this->m_rdfResourceElementText=null;
+
+		return $this->m_out;
+	}
+
+	/**
+	* Serializes a model and saves it into a file.
+	* Returns FALSE if the model couldn't be saved to the file.
+	*
+	* @param     object MemModel $model
+	* @param     String $encoding
+	* @return    boolean
+	* @access    public
+	*/
+	function  saveAs(&$model, $filename, $encoding = DEFAULT_ENCODING) {
+		// serialize model
+		$RDF = $this->serialize($model, NULL, $encoding);
+
+		//write serialized model to file
+		$file_handle = @fopen($filename, 'w');
+		if ($file_handle) {
+			fwrite($file_handle, $RDF);
+			fclose($file_handle);
+			return TRUE;
+		} else {
+			return FALSE;
+		};
+	}
+
+	/**
+	* @access   private
+	*/
+	function writeEntityDeclarations() {
+		foreach($this->m_namespaces as $prefix => $namespace) {
+			$this->m_out .= INDENTATION . '<!ENTITY '. $prefix . " '" . $namespace ."'>".LINEFEED;
+		}
+	}
+
+	/**
+	* @access   private
+	*/
+	function writeNamespaceDeclarations() {
+		foreach($this->m_namespaces as $prefix => $namespace) {
+
+			if ($prefix == RDF_NAMESPACE_PREFIX && !$this->rdf_qnames) {
+
+				if($this->use_entities) {
+					$this->m_out .= LINEFEED . INDENTATION .XML_NAMESPACE_DECLARATION_PREFIX .
+					'="&' . $prefix . ';"';
+				} else {
+					$this->m_out .= LINEFEED . INDENTATION .XML_NAMESPACE_DECLARATION_PREFIX .
+					'="' . $namespace . '"';
+				}
+			} else {
+				if ($prefix == NULL)
+				$colon_prefix = $prefix;
+				else
+				$colon_prefix = ":" .$prefix;
+
+				if($this->use_entities) {
+					$this->m_out .= LINEFEED . INDENTATION .XML_NAMESPACE_DECLARATION_PREFIX
+					.$colon_prefix .'="&' . $prefix . ';"';
+				} else {
+					$this->m_out .= LINEFEED . INDENTATION .XML_NAMESPACE_DECLARATION_PREFIX
+					.$colon_prefix .'="' . $namespace . '"';
+				}
+			}
+		}
+	}
+
+	/**
+	* @access   private
+	*/
+	function writeDescriptions()  {
+
+		$this->m_groupTypeStatement = NULL;
+		$this->m_attributeStatements = array();
+		$this->m_contentStatements = array();
+		$this->m_currentSubject = NULL;
+
+		foreach($this->m_statements as $key => $statement) {
+			$subject = $statement->getSubject();
+			$predicate = $statement->getPredicate();
+			$object = $statement->getobject();
+
+			// write Group and update current subject if nessesary
+			if ($this->m_currentSubject==NULL || !$this->m_currentSubject->equals($subject)) {
+				$this->writeGroup();
+				$this->m_currentSubject=$subject;
+			}
+
+			// classify the statement
+            if (($predicate->getURI() == RDF_NAMESPACE_URI.RDF_TYPE) && is_a($object, 'Resource') && !$this->m_groupTypeStatement) {
+                $this->writeGroup();
+                $this->m_groupTypeStatement = $statement;
+            } 
+			elseif ($this->canAbbreviateValue($object) &&
+			$this->use_attributes &&
+			$this->checkForDoubleAttributes($predicate))
+			{
+				if (is_a($object, 'Literal')) {
+					if ($object->getDatatype() == NULL) {
+						$this->m_attributeStatements[] = $statement;
+					} else {
+						$this->m_contentStatements[] = $statement;
+					}
+				} else {
+					$this->m_attributeStatements[] = $statement;
+				}
+			} else {
+				$this->m_contentStatements[] = $statement;
+			}
+		}
+		$this->writeGroup();
+	}
+
+	/**
+	* @access   private
+	*/
+	function writeGroup() {
+		if ($this->m_currentSubject==NULL || ($this->m_groupTypeStatement==NULL && (count($this->m_attributeStatements)==0) && (count($this->m_contentStatements)==0)))
+		return;
+		if ($this->m_groupTypeStatement!=NULL)
+		$outerElementName=$this->getElementText($this->m_groupTypeStatement->obj->getURI());
+		else
+		$outerElementName = $this->rdf_qname_prefix . RDF_DESCRIPTION;
+		$this->m_out .= LINEFEED . '<';
+		$this->m_out .= $outerElementName;
+
+		$this->m_out .= ' ';
+
+
+		$this->writeSubjectURI($this->m_currentSubject);
+
+		// attribute Statements
+		if ($this->use_attributes)
+		$this->writeAttributeStatements();
+
+		if (count($this->m_contentStatements)==0)
+		$this->m_out .= '/>' . LINEFEED;
+		else {
+			$this->m_out .= '>' . LINEFEED;
+
+			// content statements
+			$this->writeContentStatements();
+
+			$this->m_out .= '</';
+			$this->m_out .= $outerElementName;
+			$this->m_out .= '>'. LINEFEED;
+		}
+		$this->m_groupTypeStatement = NULL;
+		$this->m_attributeStatements = array();
+		$this->m_contentStatements = array();
+	}
+
+	/**
+	* @param object Node $predicate
+	* @access   private
+	*/
+	function checkForDoubleAttributes($predicate) {
+		foreach($this->m_attributeStatements as $key => $statement) {
+			if ($statement->pred->equals($predicate))
+			return FALSE;
+		}
+		return TRUE;
+	}
+
+	/**
+	* @param STRING $uri
+	* @access   private
+	*/
+	function relativizeURI($uri) {
+		$rdfUtil=new RDFUtil();
+		$uri_namespace = $rdfUtil->guessNamespace($uri);
+		if ($uri_namespace == $this->m_baseURI) {
+			return $rdfUtil->guessName($uri);
+		} else {
+			return $uri;
+		}
+	}
+
+	/**
+	* @param object Node $subject_node
+	*
+	* @access   private
+	*/
+
+	function writeSubjectURI($subject_node) {
+		$currentSubjectURI = $subject_node->getURI();
+		$relativizedURI = $this->relativizeURI($currentSubjectURI);
+
+		// if submitted subject ist a blank node, use rdf:nodeID
+		if (is_a($this->m_currentSubject, 'BlankNode')) {
+			$this->m_out .= $this->rdf_qname_prefix . RDF_NODEID;
+			$this->m_out .= '="';
+			$this->m_out .= $relativizedURI;
+		} else {
+
+
+			if (!($relativizedURI == $currentSubjectURI)) {
+				$this->m_out .= $this->rdf_qname_prefix . RDF_ID;
+				$this->m_out .= '="';
+				$this->m_out .= $relativizedURI;
+			} else {
+				$this->m_out .= $this->rdf_qname_prefix . RDF_ABOUT;
+				$this->m_out .= '="';
+				$this->writeAbsoluteResourceReference($relativizedURI);
+			};
+		};
+		$this->m_out .= '"';
+	}
+
+	/**
+	* @access   private
+	*/
+	function writeAttributeStatements() {
+		foreach($this->m_attributeStatements as $key => $statement) {
+			$this->m_out .= LINEFEED;
+			$this->m_out .= INDENTATION;
+			$this->m_out .= $this->getElementText($statement->pred->getURI());
+			$this->m_out .= '=';
+			$value=$statement->obj->getLabel();
+			$quote=$this->getValueQuoteType($value);
+			$this->m_out .= $quote;
+			$this->m_out .= $value;
+			$this->m_out .= $quote;
+		}
+	}
+
+	/**
+	* @access   private
+	*/
+	function writeContentStatements()  {
+		foreach($this->m_contentStatements as $key => $statement) {
+			$this->m_out .= INDENTATION;
+			$this->m_out .= '<';
+			$predicateElementText=$this->getElementText($statement->pred->getURI());
+			$this->m_out .= $predicateElementText;
+
+			if (is_a($statement->obj, 'Resource')) {
+				$this->writeResourceReference($statement->obj);
+				$this->m_out .= '/>' . LINEFEED;
+			} else {
+				if(is_a($statement->obj, 'Literal')) {
+					if ($statement->obj->getDatatype()!= NULL)
+					if ($statement->obj->getDatatype()== RDF_NAMESPACE_URI . RDF_XMLLITERAL) {
+						$this->m_out .= ' ' . RDF_NAMESPACE_PREFIX . ':' . RDF_PARSE_TYPE . '="' . RDF_PARSE_TYPE_LITERAL . '"';
+					} else {
+						$this->m_out .= ' ' . RDF_NAMESPACE_PREFIX . ':' . RDF_DATATYPE . '="' . $statement->obj->getDatatype() . '"';
+					}
+					if ($statement->obj->getLanguage()!= NULL)
+					$this->m_out .= ' ' . XML_NAMESPACE_PREFIX . ':' . XML_LANG . '="' . $statement->obj->getLanguage() . '"';
+				};
+				$this->m_out .= '>';
+				if ($statement->obj->getDatatype()== RDF_NAMESPACE_URI . RDF_XMLLITERAL) {
+					$this->m_out .= $statement->obj->getLabel();
+				} else {
+					$this->writeTextValue($statement->obj->getLabel());
+				}
+				$this->m_out .= '</';
+				$this->m_out .= $predicateElementText;
+				$this->m_out .= '>' . LINEFEED;
+			}
+		}
+	}
+
+	/**
+	* @param Object $object_node
+	* @access   private
+	*/
+	function writeResourceReference($object_node)  {
+		$rebaseURI = $object_node->getURI();
+		$this->m_out .= ' ';
+		if (is_a($object_node, 'BlankNode')) {
+			$this->m_out .= $this->rdf_qname_prefix . RDF_NODEID;
+		} else {
+			$this->m_out .= $this->rdf_qname_prefix . RDF_RESOURCE;
+		};
+
+		$this->m_out .= '="';
+		$relativizedURI = $this->relativizeURI($rebaseURI);
+		if (!($relativizedURI == $rebaseURI))
+		if (!is_a($object_node, 'BlankNode'))
+		$this->m_out .= '#' . $relativizedURI;
+		else
+		$this->m_out .=  $relativizedURI;
+		else
+		$this->writeAbsoluteResourceReference($rebaseURI);
+		$this->m_out .= '"';
+	}
+
+
+	/**
+	* @param String $rebaseURI
+	* @access   private
+	*/
+	function writeAbsoluteResourceReference($rebaseURI) {
+		$rdfUtil=new RDFUtil();
+		$namespace=$rdfUtil->guessNamespace($rebaseURI);
+		$localName=$rdfUtil->guessName($rebaseURI);
+		$text=$rebaseURI;
+		if ($namespace!='' and $this->use_entities) {
+			$prefix= array_search($namespace, $this->m_namespaces);
+			$text='&'.$prefix.';'.$localName;
+		} else $text = $rdfUtil->escapeValue($text);
+		$this->m_out .= $text;
+	}
+
+	/**
+	* @param STRING $textValue
+	* @access   private
+	*/
+	function writeTextValue($textValue) {
+		if ($this->getValueQuoteType($textValue)==USE_CDATA)
+		$this->writeEscapedCDATA($textValue);
+		else
+		$this->m_out .= $textValue;
+	}
+
+	/**
+	* @param STRING $textValue
+	* @access   private
+	*/
+	function writeEscapedCDATA($textValue) {
+		$this->m_out .= '<![CDATA[' . $textValue . ']]>';
+	}
+
+	/**
+	* @param STRING $textValue
+	* @access   private
+	*/
+	function getValueQuoteType($textValue) {
+		$quote=USE_ANY_QUOTE;
+		$hasBreaks=FALSE;
+		$whiteSpaceOnly=TRUE;
+		for ($i=0; $i<strlen($textValue); $i++) {
+			$c=$textValue{$i};
+			if ($c=='<' || $c=='>' || $c=='&')
+			return USE_CDATA;
+			if ($c==LINEFEED)
+			$hasBreaks=TRUE;
+			if ($c=='"' || $c=="\'") {
+				if ($quote==USE_ANY_QUOTE)
+				$quote=($c=='"') ? "\'" : "\"";
+				elseif ($c==$quote)
+				return USE_CDATA;
+			}
+			if (!($c == ' '))
+			$whiteSpaceOnly = FALSE;
+		}
+		if ($whiteSpaceOnly || $hasBreaks)
+		return USE_CDATA;
+		return $quote==USE_ANY_QUOTE ? '"' : $quote;
+	}
+
+	/**
+	* @param object Node $node
+	* @access   private
+	*/
+	function canAbbreviateValue($node) {
+		if (is_a($node, 'Literal')) {
+			$value= $node->getLabel();
+			if (strlen($value)<MAX_ALLOWED_ABBREVIATED_LENGTH) {
+				$c=$this->getValueQuoteType($value);
+				return $c=='"' || $c=='\'';
+			}
+		}
+		return FALSE;
+	}
+
+	/**
+	* @param STRING $elementName
+	* @access   private
+	*/
+	function getElementText($elementName)  {
+		$rdfUtil=new RDFUtil();
+		$namespace=$rdfUtil->guessNamespace($elementName);
+		$localName=$rdfUtil->guessName($elementName);
+		if ($namespace=="")
+		return $localName;
+		$prefix=array_search($namespace, $this->m_namespaces);
+
+		if ($prefix===FALSE) {
+			$errmsg = RDFAPI_ERROR . "(class: Serializer; method: getElementText): Prefix for element '" . $elementName . "' cannot be found.";
+			trigger_error($errmsg, E_USER_ERROR);
+		}
+		switch ($prefix) {
+			case RDF_NAMESPACE_PREFIX:
+			return $this->rdf_qname_prefix . $localName;
+			case NULL:
+			return $localName;
+			default:
+			return $prefix. ":" .$localName;
+		}
+	}
+
+	/**
+	* @param object MemModel $model
+	* @access   private
+	*/
+	function collectNamespaces($model)  {
+		foreach($model->triples as $key => $value) {
+
+			if ($this->use_entities) {
+				$this->collectNamespace($value->getSubject());
+				if(!is_a($value->getObject(), 'Literal'))
+				$this->collectNamespace($value->getObject());
+
+			} else {
+
+				if  ($value->pred->getURI() == RDF_NAMESPACE_URI.RDF_TYPE)
+				$this->collectNamespace($value->getObject());
+				elseif
+				(($value->pred->getURI() == RDF_NAMESPACE_URI.RDFS_SUBCLASSOF) ||
+				($value->pred->getURI() == RDF_NAMESPACE_URI.RDFS_SUBPROPERTYOF)) {
+					$this->collectNamespace($value->getSubject());
+					$this->collectNamespace($value->getObject());
+				}
+			}
+
+			$this->collectNamespace($value->getPredicate());
+
+		}
+	}
+
+	/**
+	* @param object Resource $resource
+	* @access   private
+	*/
+	function collectNamespace($resource)  {
+
+		$rdfUtil=new RDFUtil();
+		$namespace=$rdfUtil->getNamespace($resource);
+		if (!in_array($namespace, $this->m_namespaces)&&$namespace!='') {
+			$prefix = array_search( $namespace, $this->m_defaultNamespaces);
+			if ($prefix===FALSE)
+			$prefix=$this->getNextNamespacePrefix();
+			$this->m_namespaces[$prefix] = $namespace;
+		}
+	}
+
+	/**
+	* @access   private
+	*/
+	function getNextNamespacePrefix() {
+		$this->m_nextAutomaticPrefixIndex++;
+		return GENERAL_PREFIX_BASE . $this->m_nextAutomaticPrefixIndex;
+	}
+
+}
+?>
Index: /Dev/trunk/rdfapi/syntax/RssParser.php
===================================================================
--- /Dev/trunk/rdfapi/syntax/RssParser.php	(revision 12)
+++ /Dev/trunk/rdfapi/syntax/RssParser.php	(revision 12)
@@ -0,0 +1,246 @@
+<?php
+
+// ----------------------------------------------------------------------------------
+// Class: RSS/ATOM Parser
+// ----------------------------------------------------------------------------------
+
+
+/**
+ * RSS/ATOM Parser
+ * 
+ * This class uses the MagpieRSS Parser by Kellan Elliott-McCrea <kellan@protest.net>. MagpieRSS is 
+ * compatible with RSS 0.9 through RSS 1.0. Also parses RSS 1.0's modules, RSS 2.0, and Atom (with a few exceptions). 
+ * Magpie is distributed under the GPL license. (http://magpierss.sourceforge.net/)
+ * 
+ *
+ *
+ * @author Tobias Gauß <tobias.gauss@web.de>
+ * @version $Id: RssParser.php 301 2006-06-26 10:22:25Z tgauss $
+ * @package syntax
+ * @access public
+ **/
+
+class RssParser extends Object {
+	var $type;
+	
+	/**
+	* Main function
+	*
+	* @param $url location of the document
+	* @return parsed model
+	*/
+	function generateModel($url){
+		$rss = null;
+		if(substr($url,0,7)=="http://"){
+			$rss = fetch_rss($url);
+		}else{
+				$string = file_get_contents($url);
+				$rss = new MagpieRSS($string);	
+		}
+		
+		$modelFactory = new ModelFactory();
+		$model = $modelFactory->getMemModel();	
+		$bn = new Resource($url);
+		
+		$this->type = $rss->feed_type;
+		$version = $rss->feed_version;
+		
+		$nmsp = null;
+	 	if($version == "1.0")
+	 	 		$nmsp = "http://purl.org/rss/1.0/";
+	 	if($version == "0.91")
+	 	 		$nmsp = "http://my.netscape.com/publish/formats/rss-spec-0.91.html#";
+	 	if($version == "2.0")
+	 	 		$nmsp = "http://purl.org/rss/1.0/";
+	 	if($this->type == "Atom")
+	 	 		$nmsp = "http://www.w3.org/2005/Atom";
+	 	 
+		if($this->type == "Atom")
+			$this->channel($model,$rss,$bn,$nmsp,"feed");
+		else 
+			$this->channel($model,$rss,$bn,$nmsp,"channel");
+		$this->image($model,$rss,$bn,$nmsp);
+		$this->items($model,$rss,$bn,$nmsp);
+		$model->addNamespace("rdf","http://www.w3.org/1999/02/22-rdf-syntax-ns#");
+		if($nmsp!= null)
+			$model->addNamespace($this->type,$nmsp);
+		return $model;
+	}
+
+	/**
+	* Parses the image if there is one.
+	*
+	* @param $model the model
+	* @param $rss the magpie parser object
+	* @param $bnOrg the node which represents the channel
+	* @param $nmsp the
+	*/
+	function image(&$model,&$rss,&$bnOrg,&$nmsp){		
+		if(count($rss->image)>0){
+			if(isset($rss->image['about'])){
+				$bn = new Resource($rss->image['about']);
+			}else if(isset($rss->image['url'])){
+				$bn = new Resource($rss->image['url']);
+			}else{
+				$bn = new BlankNode("image");
+			}
+			$model->add(new Statement($bnOrg,new Resource($nmsp."image"),$bn));
+			$model->add(new Statement($bn,new Resource("http://www.w3.org/1999/02/22-rdf-syntax-ns#type"),new Resource($nmsp."image")));
+		}
+		foreach($rss->image as $key => $value){
+		$statement = null;	
+		switch($key){
+					case "dc":
+						$this->dc($bn,$model,$value);
+					break;
+					case "sy":
+						$this->sy($bn,$model,$value);
+					break;
+					default :
+						$statement = new Statement($bn,new Resource($nmsp.$key), new Literal($value));
+					break;
+				}
+			if($statement != null){
+				$model->add($statement);
+			}
+		}
+	
+	}
+	
+	/**
+	* Parses the rss items/ atom entries.
+	*
+	* @param $model the model
+	* @param $rss the magpie parser object
+	* @param $bnOrg the node which represents the channel
+	* @param $nmsp the
+	*/
+	function items(&$model,&$rss,&$bnOrg,&$nmsp){		
+		$items = new BlankNode("items");
+		$model->add(new Statement($bnOrg,new Resource($nmsp."items"),$items));
+		$model->add(new Statement($items,new Resource("http://www.w3.org/1999/02/22-rdf-syntax-ns#type"),new Resource("http://www.w3.org/1999/02/22-rdf-syntax-ns#Seq")));
+		$i = 1;
+		foreach($rss->items as $outerKey => $outerValue){
+			if(isset($outerValue['about'])){
+				$bn = new Resource($outerValue['about']);
+			}else if(isset($outerValue['guid'])){
+				$bn = new Resource($outerValue['guid']);
+			}else if(isset($outerValue['id'])){
+				$bn = new Resource($outerValue['id']);
+			}else{
+				$bn = new Blanknode("item".$i);
+			}
+			$model->add(new Statement($items,new Resource("http://www.w3.org/1999/02/22-rdf-syntax-ns#_".$i),$bn));
+			if($this->type == "Atom"){
+				$model->add(new Statement($bn,new Resource("http://www.w3.org/1999/02/22-rdf-syntax-ns#type"),new Resource("http://www.w3.org/2005/Atomentry")));
+			}else{
+				$model->add(new Statement($bn,new Resource("http://www.w3.org/1999/02/22-rdf-syntax-ns#type"),new Resource("http://purl.org/rss/1.0/item")));
+			}
+			foreach($outerValue as $key => $value){
+				$statement = null;
+				switch($key){
+					case "about":
+						break;
+					case "guid":
+						break;
+					case "dc":
+						$this->dc($bn,$model,$value);
+					break;
+					case "sy":
+						$this->sy($bn,$model,$value);
+					break;
+					default :
+						if($value != null)
+						$statement = new Statement($bn,new Resource($nmsp.$key), new Literal($value));
+					break;
+				}
+				if($statement != null){
+					$model->add($statement);
+				}
+			}
+			$i++;
+		}
+		
+	}
+	
+	/**
+	* Adds the dc namespace.
+	*
+	* @param $node the node
+	* @param $model the model
+	* @param $dc Array which contains the dc objects
+	*/
+	function dc(&$node,&$model,&$dc){
+		$model->addNamespace("dc","http://purl.org/dc/elements/1.1/");
+		foreach($dc as $key => $value){
+				$statement = null;
+				$statement = new Statement($node,new Resource("http://purl.org/dc/elements/1.1/".$key), new Literal($value));
+			if($statement != null){
+				$model->add($statement);
+			}
+		}
+	}
+	
+	/**
+	* Adds the sy namespace.
+	*
+	* @param $node the node
+	* @param $model the model
+	* @param $sy Array which contains the sy objects
+	*/
+	function sy(&$node,&$model,&$sy){
+		$model->addNamespace("sy","http://purl.org/rss/1.0/modules/syndication/");
+		foreach($sy as $key => $value){
+				$statement = null;
+				$statement = new Statement($node,new Resource("http://purl.org/rss/1.0/modules/syndication/".$key), new Literal($value));
+			if($statement != null){
+				$model->add($statement);
+			}
+		}
+		
+	}
+	
+	
+	/**
+	* Parses the rss channel/ atom feed.
+	*
+	* @param $model the model
+	* @param $rss the magpie parser object
+	* @param $node the node which represents the channel
+	* @param $nmsp the
+	*/
+	function channel(&$model,&$rss,&$node,&$nmsp,$type){
+	 	// Channel
+	 	$statement = new Statement($node,new Resource('http://www.w3.org/1999/02/22-rdf-syntax-ns#type'), new Resource($nmsp.$type));
+		$model->add($statement);
+		
+	 	foreach($rss->channel as $key => $value){
+			$statement = null;	
+			switch($key){
+						case "dc":
+							$this->dc($node,$model,$value);
+						break;
+						case "sy":
+							$this->sy($node,$model,$value);
+						break;
+						case "items":	
+						break;
+						case "tagline":	
+						break;
+						case "items_seq":
+						break;
+						default :
+							$statement = new Statement($node,new Resource($nmsp.$key), new Literal($value));
+						break;
+					}
+			if($statement != null){
+				$model->add($statement);
+		}
+	}
+}
+
+  
+  
+} //end: RssParser
+
+?>
Index: /Dev/trunk/rdfapi/syntax/SparqlResultParser.php
===================================================================
--- /Dev/trunk/rdfapi/syntax/SparqlResultParser.php	(revision 12)
+++ /Dev/trunk/rdfapi/syntax/SparqlResultParser.php	(revision 12)
@@ -0,0 +1,164 @@
+<?php
+// ----------------------------------------------------------------------------------
+// Class: SparqlResultParser
+// ----------------------------------------------------------------------------------
+
+/**
+* Parses an xml document in SPARQL Result XML Format.
+*
+* @version  $Id: SparqlResultParser.php 442 2007-06-01 16:19:26Z cax $
+* @author   Tobias Gauß <tobias.gauss@web.de>
+*
+* @package sparql
+*/
+
+class SparqlResultParser extends Object {
+
+
+	var $arrOutput = array();
+	var $resParser;
+	var $strXmlData;
+	var $counter = -1;
+	var $mode = -1;
+	var $varname;
+	var $dtype;
+	var $lang;
+	var $varlist;
+	var $bncounter = 0;
+	var $current_literal;	
+	
+	
+/**
+* Main function of SparqlResultParser
+*
+* @param String  $strInputXML  input document.
+*/
+	function parse($strInputXML) {
+
+		$this->resParser = xml_parser_create ();
+
+		xml_set_object($this->resParser,$this);
+		xml_set_element_handler($this->resParser, "tagOpen", "tagClosed");
+
+		xml_set_character_data_handler($this->resParser, "tagData");
+
+		$this->strXmlData = xml_parse($this->resParser,$strInputXML );
+		if(!$this->strXmlData) {
+			echo "unable to parse result<br>".
+			"server returned: <br>"
+			.$strInputXML;
+			
+			return "false";
+		
+		}
+
+		xml_parser_free($this->resParser);
+
+		return $this->arrOutput;
+	}
+	
+// private parser functions from here //	
+	function tagOpen($parser, $name, $attrs) {
+		//  $tag=array("name"=>$name,"attrs"=>$attrs);
+		//  array_push($this->arrOutput,$tag);
+		if(strtolower($name)=="variable"){
+			if(isset($attrs['name']))
+				$this->varlist[]=$attrs['name'];
+			if(isset($attrs['NAME']))
+				$this->varlist[]=$attrs['NAME'];
+		}
+		
+		if(strtolower($name)=="result"){
+			$this->counter++;
+			if($this->counter > -1){
+				foreach($this->varlist as $value){
+					if(!isset($this->arrOutput[$this->counter][$value]))
+						$this->arrOutput[$this->counter]["?".$value]='';
+				}	
+			}
+			
+		}
+		if(strtolower($name)=="boolean"){
+			$this->counter++;
+			$this->mode = 3;
+		}
+		if(strtolower($name)=="binding"){
+			$this->varname = null;
+			$this->dtype   = null;
+			$this->lang    = null;
+			
+			if(isset($attrs['name'])){
+				$this->varname = "?".$attrs['name'];
+			}else{
+				$this->varname = "?".$attrs['NAME'];
+			}
+		}
+		if(strtolower($name)=="uri"){
+			$this->mode = 0;
+		}
+		if(strtolower($name)=="literal"){
+			$this->mode = 1;
+			$this->current_literal = "";
+			if(isset($attrs['datatype'])){
+				$this->dtype = $attrs['datatype'];
+			}else if(isset($attrs['DATATYPE'])){
+				$this->dtype = $attrs['DATATYPE'];
+			}
+			if(isset($attrs['xml:lang'])){
+				$this->lang = $attrs['datatype'];
+			}else if(isset($attrs['XML:lang'])){
+				$this->lang = $attrs['XML:lang'];
+			}else if(isset($attrs['XML:LANG'])){
+				$this->lang = $attrs['XML:LANG'];
+			}else if(isset($attrs['xml:LANG'])){
+				$this->lang = $attrs['xml:LANG'];
+			}
+		}
+		if(strtolower($name)=="bnode"){
+			$this->mode = 2;
+		}
+	}
+
+	function tagData($parser, $tagData) {
+		switch($this->mode){
+			case 0 :
+			$this->arrOutput[$this->counter][$this->varname] = new Resource($tagData);
+			$this->mode = -1;
+			break;
+			case 1:
+			$this->current_literal .= $tagData;
+			break;
+			case 2:
+			if($tagData=="/"){
+				$bn = "bNode".$this->bncounter;
+				$this->bncounter++;
+			}else{
+				$bn = $tagData;
+			}
+			$this->arrOutput[$this->counter][$this->varname] = new BlankNode($bn);
+			$this->mode = -1;
+			break;
+			case 3:
+			$this->arrOutput = $tagData;
+			$this->mode = -1;
+			break;
+
+		}
+		
+	}
+
+	function tagClosed($parser, $name) {
+		if ($this->mode == 1) {
+			$lit = new Literal($this->current_literal);
+			if($this->lang)
+				$lit->setLanguage($this->lang);
+			if($this->dtype)
+				$lit->setDatatype($this->dtype);
+			$this->arrOutput[$this->counter][$this->varname] = $lit ;
+			$this->mode = -1;
+		}		
+	}
+}
+
+
+?>
Index: /Dev/trunk/rdfapi/syntax/SyntaxGRDDL.php
===================================================================
--- /Dev/trunk/rdfapi/syntax/SyntaxGRDDL.php	(revision 12)
+++ /Dev/trunk/rdfapi/syntax/SyntaxGRDDL.php	(revision 12)
@@ -0,0 +1,16 @@
+<?php
+// ----------------------------------------------------------------------------------
+// Syntax RDF
+// ----------------------------------------------------------------------------------
+//
+// Description               : Syntax RDF package
+//
+//
+// Author: Tobias Gauß	<tobias.gauss@web.de>
+//
+// ----------------------------------------------------------------------------------
+
+
+// Include Syntax classes
+require_once( RDFAPI_INCLUDE_DIR . 'syntax/GRDDLParser.php' );
+?>
Index: /Dev/trunk/rdfapi/syntax/SyntaxJSON.php
===================================================================
--- /Dev/trunk/rdfapi/syntax/SyntaxJSON.php	(revision 12)
+++ /Dev/trunk/rdfapi/syntax/SyntaxJSON.php	(revision 12)
@@ -0,0 +1,6 @@
+<?php
+// Include Syntax classes
+// $Id: SyntaxJSON.php 552 2007-11-23 09:12:11Z p_frischmuth $
+require_once( RDFAPI_INCLUDE_DIR . 'syntax/JsonParser.php' );
+require_once( RDFAPI_INCLUDE_DIR . 'syntax/JsonSerializer.php' );
+?>
Index: /Dev/trunk/rdfapi/syntax/SyntaxN3.php
===================================================================
--- /Dev/trunk/rdfapi/syntax/SyntaxN3.php	(revision 12)
+++ /Dev/trunk/rdfapi/syntax/SyntaxN3.php	(revision 12)
@@ -0,0 +1,18 @@
+<?php
+// ----------------------------------------------------------------------------------
+// Syntax N3 and NTriple
+// ----------------------------------------------------------------------------------
+//
+// Description               : Syntax N3 and NTriple package
+//
+//
+// Author: Tobias Gauß	<tobias.gauss@web.de>
+//
+// ----------------------------------------------------------------------------------
+
+
+// Include Syntax classes
+require_once( RDFAPI_INCLUDE_DIR . 'syntax/N3Parser.php' );
+require_once( RDFAPI_INCLUDE_DIR . 'syntax/N3Serializer.php' );
+require_once( RDFAPI_INCLUDE_DIR . 'syntax/NTripleSerializer.php' );
+?>
Index: /Dev/trunk/rdfapi/syntax/SyntaxRDF.php
===================================================================
--- /Dev/trunk/rdfapi/syntax/SyntaxRDF.php	(revision 12)
+++ /Dev/trunk/rdfapi/syntax/SyntaxRDF.php	(revision 12)
@@ -0,0 +1,17 @@
+<?php
+// ----------------------------------------------------------------------------------
+// Syntax RDF
+// ----------------------------------------------------------------------------------
+//
+// Description               : Syntax RDF package
+//
+// Author: Tobias Gauß	<tobias.gauss@web.de>
+//
+// ----------------------------------------------------------------------------------
+
+
+// Include Syntax classes
+require_once( RDFAPI_INCLUDE_DIR . 'syntax/RdfParser.php' );
+require_once( RDFAPI_INCLUDE_DIR . 'syntax/RdfSerializer.php' );
+require_once( RDFAPI_INCLUDE_DIR . 'syntax/NTripleSerializer.php' );
+?>
Index: /Dev/trunk/rdfapi/syntax/SyntaxRSS.php
===================================================================
--- /Dev/trunk/rdfapi/syntax/SyntaxRSS.php	(revision 12)
+++ /Dev/trunk/rdfapi/syntax/SyntaxRSS.php	(revision 12)
@@ -0,0 +1,17 @@
+<?php
+// ----------------------------------------------------------------------------------
+// Syntax RSS
+// ----------------------------------------------------------------------------------
+//
+// Description               : Syntax RSS package
+//
+// Author: Tobias Gauß	<tobias.gauss@web.de>
+//
+// ----------------------------------------------------------------------------------
+
+
+// Include Syntax classes
+require_once( RDFAPI_INCLUDE_DIR . 'util/magpie/rss_fetch.inc' );
+require_once( RDFAPI_INCLUDE_DIR . 'util/magpie/rss_parse.inc' );
+require_once( RDFAPI_INCLUDE_DIR . 'syntax/RssParser.php' );
+?>
Index: /Dev/trunk/rdfapi/syntax/SyntaxSparqlRes.php
===================================================================
--- /Dev/trunk/rdfapi/syntax/SyntaxSparqlRes.php	(revision 12)
+++ /Dev/trunk/rdfapi/syntax/SyntaxSparqlRes.php	(revision 12)
@@ -0,0 +1,15 @@
+<?php
+// ----------------------------------------------------------------------------------
+// Syntax SparqlRes
+// ----------------------------------------------------------------------------------
+//
+// Description               : Syntax Sparql Result package
+//
+// Author: Tobias Gauß	<tobias.gauss@web.de>
+//
+// ----------------------------------------------------------------------------------
+
+
+// Include Syntax classes
+require_once( RDFAPI_INCLUDE_DIR . 'syntax/SparqlResultParser.php' );
+?>
Index: /Dev/trunk/rdfapi/syntax/TriXParser.php
===================================================================
--- /Dev/trunk/rdfapi/syntax/TriXParser.php	(revision 12)
+++ /Dev/trunk/rdfapi/syntax/TriXParser.php	(revision 12)
@@ -0,0 +1,135 @@
+<?php
+// ----------------------------------------------------------------------------------
+// Class: TriXParser
+// ----------------------------------------------------------------------------------
+
+/**
+* Temporary implementation of a TriX-Parser (Usable only with PHP > V5)
+* Currently, it doesn't support any namespaces and has problems with typed literals.
+* So this parser only works with TRIX documents where the default namespace is the TRIX namespace.
+*
+* @version  $Id$
+* @author Daniel Westphal (http://www.d-westphal.de)
+*
+* @package 	dataset
+* @access	public
+**/
+class TriXParser  
+{
+	/**
+	* Reference to the graphSet
+	*
+	* @var		GraphSet
+	* @access	private
+	*/
+	var $graphSet;
+	
+	/**
+	* Constructor
+	* Needs a reference to a graphSet
+	*
+	* @param    GraphSet 
+	* @access	public
+	*/		
+	function TriXParser(&$graphSet)
+	{
+		$this->graphSet=&$graphSet;	
+	}
+
+	/**
+	* Parse an XML string
+	*
+	* @param   string
+	* @access	public
+	*/
+	function parseString($string)
+	{
+		$this->_populateGraphSet(simplexml_load_string($string));
+	}
+	
+	/**
+	* Parse from a file
+	*
+	* @param   string
+	* @access	public
+	*/
+	function parseFile($pathToFile)
+	{
+		$this->_populateGraphSet(simplexml_load_file($pathToFile));
+	}
+	
+	/**
+	* Populates the graphSet with namedGraphs and triples.
+	*
+	* @param   object simpleXMLModel  $xmlModel
+	* @access	private
+	*/
+	function _populateGraphSet(&$xmlModel)
+	{
+		$defaultGraphOccurred=false;
+		
+		foreach ($xmlModel->graph as $graph) 
+		{
+			if (isset($graph->uri)) 
+			{
+				$graphName=(string)$graph->uri;
+				$namedGraph=& $this->graphSet->getNamedGraph($graphName);
+				if ($namedGraph ==null)
+					$namedGraph=& $this->graphSet->createGraph($graphName);
+			} else 
+			{
+				if ($defaultGraphOccurred)
+					trigger_error('Only one unnamed Graph per file allowed', E_USER_ERROR);
+				
+				$namedGraph=& $this->graphSet->getDefaultGraph();
+				$defaultGraphOccurred=true;
+			}	
+						
+			foreach ($graph->triple as $triple)
+			{
+				$tripleCount=0;
+				$tripleArray=array();
+				foreach ($triple->children() as $tag => $value)
+				{
+					$tripleArray[$tripleCount++]=$this->_element2Resource((string)$tag,$value);
+				};
+				$namedGraph->add(new Statement($tripleArray[0],$tripleArray[1],$tripleArray[2]));	
+			};
+		};
+	}
+	
+	/**
+	* return a mathing resource tyoe
+	*
+	* @param   string  
+	* @param   object simpleXMLNode $value
+	* @access	private
+	*/
+	function _element2Resource($tag,$value)
+	{
+		switch ($tag) 
+		{
+				case 'uri':
+					return new Resource((string)$value);
+				break;
+		
+				case 'id':
+					return new BlankNode((string)$value);
+				break;
+				
+				case 'typedLiteral':
+					$literal=new Literal((string)$value);
+					$literal->setDatatype((string)$value['datatype']);
+					return $literal;
+				break;
+					
+				case 'plainLiteral':
+					$literal=new Literal((string)$value);
+					if(isset($value['xml:lang']))
+						$literal->setLanguage((string)$value['xml:lang']);
+					return $literal;
+				break;
+		}
+	}
+}
+?>
Index: /Dev/trunk/rdfapi/syntax/TriXSerializer.php
===================================================================
--- /Dev/trunk/rdfapi/syntax/TriXSerializer.php	(revision 12)
+++ /Dev/trunk/rdfapi/syntax/TriXSerializer.php	(revision 12)
@@ -0,0 +1,151 @@
+<?php
+// ----------------------------------------------------------------------------------
+// Class: TriXSerializer
+// ----------------------------------------------------------------------------------
+
+/**
+* Temporary implementation of a TriX-Serializer
+* 
+* @version  $Id$
+* @author Daniel Westphal (http://www.d-westphal.de)
+*
+* @package 	dataset
+* @access	public
+**/
+class TriXSerializer  
+{
+	
+	/**
+	* Reference to the graphSet
+	*
+	* @var		object GraphSet
+	* @access	private
+	*/
+	var $graphSet;
+	
+
+	/**
+	* Constructor
+	* Needs a reference to a graphSet
+	*
+	* @param    GraphSet
+	* @access	public
+	*/		
+	function TriXSerializer(&$graphSet)
+	{
+		$this->graphSet=&$graphSet;
+	}
+
+	/**
+	* Serialize the dataset to a TriX string
+	*
+	* @return   string
+	* @access	public
+	*/
+	function & serializeToString()
+	{
+		return $this->_serialize();
+	}
+	
+	/**
+	* Serialize the dataset to a TriX string and save in file
+	*
+	* @param   string
+	* @access	public
+	*/
+	function serializeToFile($fileName)
+	{
+		$serializedString=&$this->_serialize();
+		$handle = fopen($fileName, 'w');
+	   	fwrite($handle, $serializedString);
+		fclose($handle);
+	}
+	
+	
+	/**
+	* Serialize the dataset to a TriX string
+	*
+	* @return   string
+	* @access	private
+	*/
+	function & _serialize()
+	{
+		//Trix header
+		$serializedString=
+			'<?xml version="1.0" encoding="utf-8"?>'.
+			'<TriX xmlns="http://www.w3.org/2004/03/trix/trix-1/">';
+		
+		//serialize defaultGraph if it is not empty
+		$defaultGraph=& $this->graphSet->getDefaultGraph();
+		if ($defaultGraph->isEmpty()===false)
+		{
+			$serializedString.='<graph>';
+			for($iterator = $this->graphSet->findInDefaultGraph(null,null,null); $iterator->valid(); $iterator->next()) 
+			{
+				$serializedString.='<triple>';
+				
+				$statement=$iterator->current();
+				
+				$serializedString.=$this->_node2string($statement->getSubject());
+				$serializedString.=$this->_node2string($statement->getPredicate());
+				$serializedString.=$this->_node2string($statement->getObject());
+				
+				$serializedString.='</triple>';
+			};
+			$serializedString.='</graph>';
+		}		
+			
+		//serialize namedGraphs	
+		foreach ($this->graphSet->listGraphNames() as $graphName)
+		{
+			$serializedString.='<graph>';
+			$serializedString.='<uri>'.$graphName.'</uri>';
+			for($iterator = $this->graphSet->findInNamedGraphs(new Resource($graphName),null,null,null); $iterator->valid(); $iterator->next()) 
+			{
+				$serializedString.='<triple>';
+				
+				$statement=$iterator->current();
+				
+				$serializedString.=$this->_node2string($statement->getSubject());
+				$serializedString.=$this->_node2string($statement->getPredicate());
+				$serializedString.=$this->_node2string($statement->getObject());
+				
+				$serializedString.='</triple>';
+			};
+			$serializedString.='</graph>';
+		};		
+		//TriX footer	
+		$serializedString.='</TriX>';	
+		return $serializedString;
+	}
+	
+	/**
+	* Serialize node to a TriX string
+	*
+	* @param Node
+	* @return   string
+	* @access	private
+	*/
+	function _node2string($node)
+	{
+		switch ($node)
+		{
+			case (is_a($node,'BlankNode')):
+				return ('<id>'.$node->getLabel().'</id>');
+			
+			case (is_a($node,'Resource')):
+				return ('<uri>'.$node->getLabel().'</uri>');
+			
+			case (is_a($node,'Literal')):
+			
+				if ($node->dtype!=null)
+					return ('<typedLiteral datatype="'.htmlentities($node->dtype).'">'.$node->getLabel().'</typedLiteral>');
+
+				if ($node->lang!=null)
+					return ('<plainLiteral xml:lang="'.htmlentities($node->lang).'">'.$node->getLabel().'</plainLiteral>');
+					
+				return ('<plainLiteral>'.htmlentities($node->getLabel()).'</plainLiteral>');
+		}
+	}
+}
+?>
Index: /Dev/trunk/rdfapi/util/FindIterator.php
===================================================================
--- /Dev/trunk/rdfapi/util/FindIterator.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/FindIterator.php	(revision 12)
@@ -0,0 +1,119 @@
+<?php
+
+// ----------------------------------------------------------------------------------
+// Class: FindIterator
+// ----------------------------------------------------------------------------------
+
+/**
+ * Iterator for traversing statements matching a searchpattern. 
+ * FindIterators are returned by model->findAsIterator()
+ * Using a find iterator is significantly faster than using model->find() which returns
+ * a new result model.
+ * 
+ * 
+ * @version  $Id: FindIterator.php 268 2006-05-15 05:28:09Z tgauss $
+ * @author Tobias Gauß <tobias.gauss@web.de>
+ *
+ * @package utility
+ * @access	public
+ *
+ */ 
+ class FindIterator extends Object {
+
+ 	/**
+	* Reference to the MemModel
+	* @var		object MemModel
+	* @access	private
+	*/	
+    var $model;
+    
+
+
+ 	/**
+	* Current position
+	* FindIterator does not use the build in PHP array iterator,
+	* so you can use serveral iterators on a single MemModel.
+	* @var		integer
+	* @access	private
+	*/	
+    var $position;
+    
+    
+    /**
+	* Searchpattern
+	* 
+	* @var		Object Subject,Predicate,Object
+	* @access	private
+	*/	
+
+    var $subject;
+    var $predicate;
+    var $object;
+   
+    
+   /**
+    * Constructor
+    *
+    * @param	object	MemModel
+    * @param    object  Subject
+    * @param    object  Predicate
+    * @param    object  Object
+	* @access	public
+    */
+    function FindIterator(&$model,$sub,$pred,$obj) {
+		$this->model = &$model;
+		$this->subject=$sub;
+		$this->predicate=$pred;
+		$this->object=$obj;
+		$this->position=-1;
+	}
+	
+	
+ 	/**
+    * Returns TRUE if there are more matching statements.
+    * @return	boolean
+    * @access	public  
+    */
+    function hasNext() {
+  		if($this->model->findFirstMatchOff($this->subject,$this->predicate,$this->object,$this->position+1)>-1){
+  			return TRUE;
+  		}else{
+  			return FALSE;
+  		}
+    }
+
+   
+    /**
+    * Returns the next matching statement.
+    * @return	statement or NULL if there is no next matching statement.
+    * @access	public  
+    */
+    function next() {
+  			$res=$this->model->findFirstMatchOff($this->subject,$this->predicate,$this->object,$this->position+1);	
+  			if($res>-1){
+  				$this->position=$res;
+  				return $this->model->triples[$res];
+  			}else{
+  				return Null;
+  			}		
+    }
+   
+   
+ 
+
+    /**
+    * Returns the current matching statement.
+    * @return	statement or NULL if there is no current matching statement.
+    * @access	public  
+    */
+    function current() {
+  		if (($this->position >= -1)&&(isset($this->model->triples[$this->position]))) {
+			return $this->model->triples[$this->position];
+		} else {
+			return NULL;
+		} 
+    }  
+  
+ } 
+
+?>
Index: /Dev/trunk/rdfapi/util/IterFind.php
===================================================================
--- /Dev/trunk/rdfapi/util/IterFind.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/IterFind.php	(revision 12)
@@ -0,0 +1,174 @@
+<?php 
+
+// ----------------------------------------------------------------------------------
+// Class: IterFind
+// ----------------------------------------------------------------------------------
+
+
+/**
+* Implementation of a find-iterator which delivers statements or quads.
+*
+* This Iterator should be used in a for-loop like:
+* for($iterator = $memmodel->iterFind(null,null,null,null); $iterator->valid(); $iterator->next()) 
+* {
+*	$statement=$iterator->current();
+* };
+*
+* @version  $Id$
+* @author Daniel Westphal (http://www.d-westphal.de)
+*
+*
+* @package 	utility
+* @access	public
+**/
+class IterFind
+{
+	
+	/**
+	* The current position
+	* @var		integer
+	* @access	private
+	*/
+	var $key;
+	
+	/**
+	* boolean value, if the results should be returned as Quads
+	* @var		boolean
+	* @access	private
+	*/
+	var $returnAsQuads;
+	
+	/**
+	* If the current resource is valid
+	* @var		boolean
+	* @access	private
+	*/
+	var $valid;
+	
+	/**
+	* The current NamedGraph
+	* @var obejct NamedGraph
+	* @access	private
+	*/
+	var $current;
+	
+	/**
+	* The graph to look in.
+	* @var string 
+	* @access	private
+	*/	
+	var $findGraph;
+	
+	/**
+	* 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;
+	
+	
+	
+	/**
+    * Constructor.
+    *
+	* $subject, $predicate, and $object are used like find().
+	* $graph has to be a reference to the graph to search in.
+	*
+	* 
+    *
+    * @param $graph Resource
+    * @param $subject Resource
+    * @param $predicate Resource
+    * @param $object Resource
+    * @param $returnAsQuads boolean
+	* @access	public
+    */
+	function IterFind($graph,$subject,$predicate,$object,$returnAsQuads=false)
+	{
+		if ($graph==NULL)
+		{
+			$this->valid=false;
+			return;	
+		}		
+		$this->findGraph=&$graph;
+		$this->findSubject=$subject;
+		$this->findPredicate=$predicate;
+		$this->findObject=$object;
+		$this->rewind();
+		$this->returnAsQuads=$returnAsQuads;
+	}
+	
+	/**
+    * 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->findGraph->findFirstMatchingStatement($this->findSubject,$this->findPredicate,$this->findObject,++$this->key);
+		$this->valid=($this->current!=NULL);
+	}
+	
+	/**
+    * Returns the current item
+    *
+    * @return	mixed
+	* @access	public
+    */
+	function current()
+	{
+		if($this->returnAsQuads)
+		return new Quad(new Resource($this->findGraph->getGraphName()),$this->current->getSubject(),$this->current->getPredicate(),$this->current->getObject());
+		//else
+		return $this->current;
+	}
+	
+	
+	/**
+    * Returns the key of the current item
+    *
+    * @return	integer
+	* @access	public
+    */
+	function key()
+	{
+		return $this->key;
+	}
+}
+?>
Index: /Dev/trunk/rdfapi/util/ModelComparator.php
===================================================================
--- /Dev/trunk/rdfapi/util/ModelComparator.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/ModelComparator.php	(revision 12)
@@ -0,0 +1,158 @@
+<?php
+
+// ----------------------------------------------------------------------------------
+// Class: ModelComparator
+// ----------------------------------------------------------------------------------
+
+
+/**
+ * This class compares to models. This comparator bases on the labelling algorithm 
+ * described in <href="http://www.hpl.hp.com/techreports/2003/HPL-2003-142.pdf" >Signing RDF Graphs</href> 
+ * by Jeremy J. Carroll.
+ *
+ *
+ * @version  $Id$
+ * @author Tobias Gauß <tobias.gauss at web.de>
+ *
+ * @package utility
+ * @access	public
+ *
+ **/ 
+ class ModelComparator extends Object {
+ 	
+ 	/**
+ 	* Compares two models.
+ 	*
+ 	* @param $thisModel First Model.
+ 	* @param $thatModel Second Model.
+ 	*
+ 	* @return boolean
+ 	*/
+ 	function compare($thisModel, $thatModel){
+ 	
+ 	$thisModeltriples = null;
+ 	$thatModeltriples = null;
+ 	
+ 		if(is_a($thisModel,"DbModel")){
+ 			$thisModeltriples = 	$thisModel->getMemModel();
+ 		}else{
+ 			$thisModeltriples = 	$thisModel;
+ 		}
+ 		
+ 		if(is_a($thatModel,"DbModel")){
+ 			$thatModeltriples = 	$thatModel->getMemModel();
+ 		}else{
+ 			$thatModeltriples = 	$thatModel;
+ 		}
+ 			
+ 		$sortArray1 = ModelComparator::buildSortArray($thisModeltriples->triples);
+		$sortArray2 = ModelComparator::buildSortArray($thatModeltriples->triples);	
+		
+		$renamedArray1 = ModelComparator::renameBlanks($sortArray1);
+		$renamedArray2 = ModelComparator::renameBlanks($sortArray2);
+		
+		return ModelComparator::compareTriples($renamedArray1,$renamedArray2);
+ 	}
+ 		
+ 	
+ 	/**
+ 	* Builds a sorted array. 
+ 	*
+ 	* @param $tripleList A List that contains the models triples.
+ 	*
+ 	* @return Array
+ 	*/
+ 	function buildSortArray($tripleList){
+ 		$sortedArray = Array();
+ 		
+ 		foreach($tripleList as $index => $triple){
+ 			$sub = null;
+ 			$obj = null;
+ 			$orgSub  = $triple->getSubject();
+ 			$orgObj  = $triple->getObject();
+ 			
+ 			if(is_a($orgSub,"Blanknode")){
+ 				$sub = $orgSub->getID();
+ 				$triple->subj = new Blanknode("~");
+ 			}
+ 			if(is_a($orgObj,"Blanknode")){
+ 				$obj = $orgObj->getID();
+ 				$triple->obj = new Blanknode("~");
+ 			}
+ 			$sortedArray[$index]['string']  = $triple->toString();
+ 			$sortedArray[$index]['index']  = $index;
+ 			$sortedArray[$index]['triple'] = $triple;
+ 			$sortedArray[$index]['sub']    = $sub;
+ 			$sortedArray[$index]['obj']    = $obj;	
+ 		}
+ 		sort($sortedArray);
+ 		return $sortedArray;
+ 	}
+ 	
+ 	/**
+ 	* Renames the models Blanknodes. 
+ 	*
+ 	* @param $sortedArray A List that contains the models triples.
+ 	*
+ 	* @return Array
+ 	*/
+ 	function renameBlanks($sortedArray){
+ 	$i = 0;
+ 	$labelmap = Array();
+ 		
+ 		foreach ($sortedArray as $value){	
+ 			//new label
+ 			if($value['sub']!=null){
+ 				$label = null;
+ 				if(isset($labelmap[$value['sub']])){
+ 					$label = $labelmap[$value['sub']];
+ 					$value['triple']->subj = new BlankNode($labelmap[$value['sub']]);
+ 				}else{
+ 					$label = $i."Bnode";
+ 					$labelmap[$value['sub']]=$label;
+ 					$value['triple']->subj = new BlankNode($labelmap[$value['sub']]);
+ 					$i++;
+ 				}
+ 			}
+ 			
+ 			if($value['obj']!=null){
+ 				$label = null;
+ 				if(isset($labelmap[$value['obj']])){
+ 					$label = $labelmap[$value['obj']];
+ 					$value['triple']->obj = new BlankNode($labelmap[$value['obj']]);
+ 				}else{
+ 					$label = $i."Bnode";
+ 					$labelmap[$value['obj']]=$label;
+ 					$value['triple']->obj = new BlankNode($labelmap[$value['obj']]);
+ 					$i++;
+ 				}
+ 			}
+ 			
+ 		}
+ 		return $sortedArray;
+ 	
+ 	}
+ 	
+ 	/**
+ 	* Compares the Triples in the lists. 
+ 	*
+ 	* @param $tripleList A List that contains the models triples.
+ 	* @param $tripleList A List that contains the models triples.
+ 	*
+ 	* @return boolean
+ 	*/
+ 	function compareTriples($array1, $array2){
+ 		foreach($array1 as $key => $value){
+ 			if(!$value['triple']->equals($array2[$key]['triple']))
+ 				return false;
+ 		}
+ 		return true;
+ 	
+ 	}
+ 	
+ 
+ }
+ 
+ 
+ 
+ ?>
Index: /Dev/trunk/rdfapi/util/Object.php
===================================================================
--- /Dev/trunk/rdfapi/util/Object.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/Object.php	(revision 12)
@@ -0,0 +1,37 @@
+<?php
+
+// ----------------------------------------------------------------------------------
+// Class: Object
+// ----------------------------------------------------------------------------------
+
+/**
+ * An abstract object.
+ * Root object with some general methods, that should be overloaded. 
+ * 
+ *
+ * @version  $Id: Object.php 295 2006-06-23 06:45:53Z tgauss $
+ * @author Chris Bizer <chris@bizer.de>
+ *
+ * @abstract
+ * @package utility
+ *
+ **/
+ class Object {
+
+  /**
+   * Serializes a object into a string
+   *
+   * @access	public
+   * @return	string		
+   */    
+	function toString() {
+    	$objectvars = get_object_vars($this);
+		foreach($objectvars as $key => $value) 
+			$content .= $key ."='". $value. "'; ";
+		return "Instance of " . get_class($this) ."; Properties: ". $content;
+	}
+
+ }
+
+
+?>
Index: /Dev/trunk/rdfapi/util/RdfUtil.php
===================================================================
--- /Dev/trunk/rdfapi/util/RdfUtil.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/RdfUtil.php	(revision 12)
@@ -0,0 +1,563 @@
+<?php
+
+// ----------------------------------------------------------------------------------
+// Class: RDFUtil
+// ----------------------------------------------------------------------------------
+
+/**
+* Useful utility methods.
+* Static class.
+*
+* @version  $Id: RdfUtil.php 295 2006-06-23 06:45:53Z tgauss $
+* @author Chris Bizer <chris@bizer.de>, Daniel Westphal <dawe@gmx.de>
+* @author   Anton Köstlbacher <anton1@koestlbacher.de>
+* @package utility
+* @access	public
+**/
+class RDFUtil extends Object {
+
+	/**
+	* Extracts the namespace prefix out of a URI.
+	*
+	* @param	String	$uri
+	* @return	string
+	* @access	public
+	*/
+	function guessNamespace($uri) {
+		$l = RDFUtil::getNamespaceEnd($uri);
+		return $l > 1 ? substr($uri ,0, $l) : "";
+	}
+
+	/**
+	* Delivers the name out of the URI (without the namespace prefix).
+	*
+	* @param	String	$uri
+	* @return	string
+	* @access	public
+	*/
+	function guessName($uri) {
+		return substr($uri,RDFUtil::getNamespaceEnd($uri));
+	}
+
+	/**
+	* Extracts the namespace prefix out of the URI of a Resource.
+	*
+	* @param	Object Resource	$resource
+	* @return	string
+	* @access	public
+	*/
+	function getNamespace($resource) {
+		return RDFUtil::guessNamespace($resource->getURI());
+	}
+
+	/**
+	* Delivers the Localname (without the namespace prefix) out of the URI of a Resource.
+	*
+	* @param	Object Resource	$resource
+	* @return	string
+	* @access	public
+	*/
+	function getLocalName($resource) {
+		return RDFUtil::guessName($resource->getURI());
+	}
+
+	/**
+	* Position of the namespace end
+	* Method looks for # : and /
+	* @param	String	$uri
+	* @access	private
+	*/
+	function getNamespaceEnd($uri) {
+		$l = strlen($uri)-1;
+		do {
+			$c = substr($uri, $l, 1);
+			if($c == '#' || $c == ':' || $c == '/')
+			break;
+			$l--;
+		} while ($l >= 0);
+		$l++;
+		return $l;
+	}
+
+		/**
+	* Short Prefix for known Namespaces by given URI
+	* @param	String	$uri
+	* @access	public
+	*/
+	function getPrefix($uri) {
+            switch (RDFUtil::guessNamespace($uri))
+	    {
+                case RDF_NAMESPACE_URI:
+                $prefix = RDF_NAMESPACE_PREFIX;
+                break;
+
+                case RDF_SCHEMA_URI:
+                $short_p = RDF_SCHEMA_PREFIX;
+                break;
+
+                case OWL_URI:
+                $short_p = OWL_PREFIX;
+                break;
+
+                default:
+                $short_p = $statement->getLabelPredicate();
+            }
+            return $short_p;
+	}
+
+
+	/**
+	* Tests if the URI of a resource belongs to the RDF syntax/model namespace.
+	*
+	* @param	Object Resource	$resource
+	* @return	boolean
+	* @access	public
+	*/
+	function isRDF($resource) {
+		return ($resource != NULL && RDFUtil::getNamespace($resource) == RDF_NAMESPACE_URI);
+	}
+
+	/**
+	* Escapes < > and &
+	*
+	* @param	String	$textValue
+	* @return	String
+	* @access	public
+	*/
+	function escapeValue($textValue) {
+
+		$textValue = str_replace('<', '&lt;', $textValue);
+		$textValue = str_replace('>', '&gt;', $textValue);
+		$textValue = str_replace('&', '&amp;', $textValue);
+
+		return $textValue;
+	}
+
+	/**
+	* Converts an ordinal RDF resource to an integer.
+	* e.g. Resource(RDF:_1) => 1
+	*
+	* @param	object Resource	$resource
+	* @return	Integer
+	* @access	public
+	*/
+	function getOrd($resource)  {
+		if($resource == NULL || !is_a($resource, 'Resource') || !RDFUtil::isRDF($resource))
+		return -1;
+		$name = RDFUtil::getLocalName($resource);
+		echo substr($name, 1).' '.RDFUtil::getLocalName($resource);
+		$n = substr($name, 1);
+		//noch rein : chekcen ob $n Nummer ist !!!!!!!!!!!!!!!!!!!!!!if($n)
+		return $n;
+		return -1;
+	}
+
+	/**
+	* Creates ordinal RDF resource out of an integer.
+	*
+	* @param	Integer	$num
+	* @return	object Resource
+	* @access	public
+	*/
+	function createOrd($num)  {
+		return new Resource(RDF_NAMESPACE_URI . '_' . $num);
+	}
+
+	/**
+	* Prints a MemModel as HTML table.
+	* You can change the colors in the configuration file.
+	*
+	* @param	object MemModel 	&$model
+	* @access	public
+	*/
+	function writeHTMLTable(&$model)  {
+		$nms = $model->getParsedNamespaces();
+		$names = '';
+		$pre = '';
+
+
+		echo '<table border="1" cellpadding="3" cellspacing="0" width="100%">' . LINEFEED;
+		echo INDENTATION . '<tr bgcolor="' . HTML_TABLE_HEADER_COLOR . '">' . LINEFEED . INDENTATION . INDENTATION . '<td td width="68%" colspan="3">';
+		echo '<p><b>Base URI:</b> ' . $model->getBaseURI() . '</p></td>' . LINEFEED;
+		echo INDENTATION . INDENTATION . '<td width="32%"><p><b>Size:</b> ' . $model->size() . '</p></td>' . LINEFEED . INDENTATION . '</tr>';
+
+		echo '<tr><td><b>Prefix:</b>'.'<br/></td><td colspan="3"><b>Namespace:</b>'.'<br/></td></tr>';
+		$i=0;
+		if($nms != false){
+			foreach($nms as $namespace => $prefix){
+				if($i==0){
+					$col = HTML_TABLE_NS_ROW_COLOR0;
+				}else{
+					$col = HTML_TABLE_NS_ROW_COLOR1;
+				}
+				echo '<tr bgcolor="'.$col.'"><td>'.$prefix.'</td><td colspan="3">'.$namespace.'</td></tr>';
+				$i++;
+				$i%=2;
+			}
+		}else{
+			echo '<tr><td>-</td><td colspan="3">-</td></tr>';
+		}
+
+
+
+
+		echo INDENTATION . '<tr bgcolor="' . HTML_TABLE_HEADER_COLOR . '">' . LINEFEED . INDENTATION . INDENTATION . '<td width="4%"><p align=center><b>No.</b></p></td>' . LINEFEED . INDENTATION . INDENTATION . '<td width="32%"><p><b>Subject</b></p></td>' . LINEFEED . INDENTATION . INDENTATION . '<td width="32%"><p><b>Predicate</b></p></td>' . LINEFEED . INDENTATION . INDENTATION . '<td width="32%"><p><b>Object</b></p></td>' . LINEFEED . INDENTATION . '</tr>' . LINEFEED;
+
+		$i = 1;
+		foreach($model->triples as $key => $statement) {
+			$infered='';
+			if (is_a($statement,'InfStatement')) $infered='<small>(infered)</small>';
+			echo INDENTATION . '<tr valign="top">' . LINEFEED . INDENTATION . INDENTATION . '<td><p align=center>' . $i . '.<BR>'.$infered.'</p></td>' . LINEFEED;
+			// subject
+			echo INDENTATION . INDENTATION . '<td bgcolor="';
+			echo RDFUtil::chooseColor($statement->getSubject());
+			echo '">';
+			echo '<p>' .  RDFUtil::getNodeTypeName($statement->getSubject());
+			if(is_a($statement->subj,'Resource')){
+				$ns = $statement->subj->getNamespace();
+				if(isset($nms[$ns])){
+					echo $nms[$ns].':'.RDFUtil::getLocalName($statement->subj);
+				}else{
+					echo $statement->subj->getLabel();
+				}
+			}
+			echo '</p></td>' .  LINEFEED;
+			// predicate
+			echo INDENTATION . INDENTATION . '<td bgcolor="';
+			echo RDFUtil::chooseColor($statement->getPredicate());
+			echo '">';
+			echo '<p>' . RDFUtil::getNodeTypeName($statement->getPredicate());
+			if(is_a($statement->pred,'Resource')){
+				$ns = $statement->pred->getNamespace();
+				if(isset($nms[$ns])){
+					echo $nms[$ns].':'.RDFUtil::getLocalName($statement->pred);
+				}else{
+					echo $statement->pred->getLabel();
+				}
+			}
+			echo '</p></td>' .  LINEFEED;
+			// object
+			echo INDENTATION . INDENTATION . '<td bgcolor="';
+			echo RDFUtil::chooseColor($statement->getObject());
+			echo '">';
+			echo '<p>';
+			if (is_a($statement->getObject(), 'Literal')) {
+				if ($statement->obj->getLanguage() != null) {
+					$lang = ' <b>(xml:lang="' . $statement->obj->getLanguage() . '") </b> ';
+				} ELSE $lang = '';
+				if ($statement->obj->getDatatype() != null) {
+					$dtype = ' <b>(rdf:datatype="' . $statement->obj->getDatatype() . '") </b> ';
+				} ELSE $dtype = '';
+			} else {
+				$lang = '';
+				$dtype = '';
+			}
+			$label = $statement->obj->getLabel();
+			if(is_a($statement->obj,'Resource')){
+				$ns = $statement->obj->getNamespace();
+				if(isset($nms[$ns])){
+					$label = $nms[$ns].':'.RDFUtil::getLocalName($statement->obj);
+				}else{
+					$label = $statement->obj->getLabel();
+				}
+			}
+
+			echo  RDFUtil::getNodeTypeName($statement->getObject())
+			.nl2br(htmlspecialchars($label)) . $lang . $dtype;
+
+			echo '</p></td>' . LINEFEED;
+			echo INDENTATION . '</tr>' . LINEFEED;
+			$i++;
+		}
+		echo '</table>' . LINEFEED;
+	}
+
+	/**
+	* Chooses a node color.
+	* Used by RDFUtil::writeHTMLTable()
+	*
+	* @param	object Node	$node
+	* @return	object Resource
+	* @access	private
+	*/
+	function chooseColor($node)  {
+		if (is_a($node, 'BlankNode'))
+		return HTML_TABLE_BNODE_COLOR;
+		elseif (is_a($node, 'Literal'))
+		return HTML_TABLE_LITERAL_COLOR;
+		else {
+			if (RDFUtil::getNamespace($node) == RDF_NAMESPACE_URI ||
+			RDFUtil::getNamespace($node) == RDF_SCHEMA_URI ||
+			RDFUtil::getNamespace($node) == OWL_URI
+			)
+
+			return HTML_TABLE_RDF_NS_COLOR;
+		}
+		return HTML_TABLE_RESOURCE_COLOR;
+
+	}
+
+	/**
+	* Get Node Type.
+	* Used by RDFUtil::writeHTMLTable()
+	*
+	* @param	object Node	$node
+	* @return	object Resource
+	* @access	private
+	*/
+	function getNodeTypeName($node)  {
+		if (is_a($node, "BlankNode"))
+		return 'Blank Node: ';
+		elseif (is_a($node, 'Literal'))
+		return 'Literal: ';
+		else {
+			if (RDFUtil::getNamespace($node) == RDF_NAMESPACE_URI ||
+			RDFUtil::getNamespace($node) == RDF_SCHEMA_URI ||
+			RDFUtil::getNamespace($node) == OWL_URI)
+			return 'RDF Node: ';
+		}
+		return 'Resource: ';
+
+	}
+
+
+ /**
+ * Short Prefix for known and/or parsed Namespaces by given URI and Model
+ * Uses $default_prefixes defined in constants.php and getParsedNamespaces()
+ * Returns FALSE if no matching prefix is found
+ *
+ * @author   Anton Köstlbacher <anton1@koestlbacher.de>
+ * @param    string  $uri
+ * @param    object $model
+ * @return   string, boolean
+ * @access   public
+ * @throws   PhpError
+ */
+
+ function guessPrefix($uri, &$model)
+ {
+     global $default_prefixes;
+     $namespace = RDFUtil::guessNamespace($uri);
+     $par_nms   = $model->getParsedNamespaces();
+     if (isset($par_nms[$namespace]))
+     {
+         $prefix = $par_nms[$namespace];
+     }
+     else
+     {
+         $prefix = array_search($namespace, $default_prefixes);
+     }
+     if($prefix !== false)
+     {
+        return $prefix;
+     }
+     else
+     {
+        return false;
+     }
+ }
+
+
+ /**
+ * Generates a dot-file for drawing graphical output with the
+ * graphviz-application which can be downloaded at http://www.graphviz.org
+ * If the graphviz-application is installed and its path is set to the
+ * correct value in constants.php we can directly generate any
+ * file format graphviz supports, e.g. SVG, PNG
+ * Parameters: model to visualize, output format, use prefixes
+ *
+ * !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+ * WARNING: Graphviz can be slow with large models.
+ * !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+ *
+ * @author   Anton Köstlbacher <anton1@koestlbacher.de>
+ * @param    object  Model
+ * @param    string  $format
+ * @param    boolean $short_prefix
+ * @return   string, binary
+ * @access   public
+ * @throws   PhpError
+ */
+
+ function visualizeGraph(&$model, $format = "input_dot", $short_prefix = TRUE)
+ {
+     global $graphviz_param;
+     $i = 0;
+
+     foreach ($model->triples as $key => $statement)
+     {
+         $subject   = $statement->getLabelSubject();
+         $predicate = $statement->getLabelPredicate();
+         $object    = $statement->getLabelObject();
+
+         // format subject
+         if (!isset($attrib[$subject]))
+         {
+             if (is_a($statement->subject(),'BlankNode'))
+             {
+                 $attrib[$subject] = $graphviz_param['BLANKNODE_STYLE'];
+             }
+             else
+             {
+                 if ($short_prefix == TRUE && RDFUtil::guessPrefix($subject, $model) != FALSE)
+                 {
+                     $prefix = RDFUtil::guessPrefix($subject, $model);
+                     $subject_label = $prefix.":".RDFUtil::guessName($subject);
+                     $attrib[$subject] = "label=\"".$subject_label."\" ";
+                     if(!isset($prefix_array[$prefix]))
+                     {
+                         $prefix_array[$prefix] = RDFUtil::guessNamespace($subject);
+                     }
+                 }
+                 if (GRAPHVIZ_URI == TRUE)
+                 {
+                     $attrib[$subject] .= "URL=\"".$subject."\"";
+                 }
+             }
+         }
+
+         // format predicate
+         if ($short_prefix == TRUE && RDFUtil::guessPrefix($predicate, $model) != FALSE)
+         {
+             $prefix = RDFUtil::guessPrefix($predicate, $model);
+             $predicate_label = "label=\"".$prefix.":".RDFUtil::guessName($predicate)."\"";
+             if(!isset($prefix_array[$prefix]))
+             {
+                 $prefix_array[$prefix] = RDFUtil::guessNamespace($predicate);
+             }
+         }
+         else
+         {
+             $predicate_label = "label=\"".$predicate."\"";
+         }
+
+	if (is_a($statement,'InfStatement'))
+         {
+             $predicate_label .= " ".$graphviz_param['INFERRED_STYLE'];
+         }
+         else
+         {
+             if (GRAPHVIZ_URI == TRUE)
+             {
+                 $predicate_label .= "URL=\"".$predicate."\"";
+             }
+         }
+
+         // format object
+         if (!isset($attrib[$object]))
+         {
+             if (is_a($statement->object(),'BlankNode'))
+             {
+                 $attrib[$object] = $graphviz_param['BLANKNODE_STYLE'];
+             }
+             elseif (is_a($statement->object(),'Literal'))
+             {
+                 $object_label = $object;
+                 $object = "literal".$i;
+                 $i++;
+                 $attrib[$object] = "label=\"$object_label\" ".$graphviz_param['LITERAL_STYLE'];
+             }
+             else
+             {
+                 if ($short_prefix == TRUE && RDFUtil::guessPrefix($object, $model) != FALSE)
+                 {
+                     $prefix = RDFUtil::guessPrefix($object, $model);
+                     $object_label = $prefix.":".RDFUtil::guessName($object);
+                     $attrib[$object] = "label=\"".$object_label."\" ";
+                     if(!isset($prefix_array[$prefix]))
+                     {
+                         $prefix_array[$prefix] = RDFUtil::guessNamespace($object);
+                     }
+                 }
+                 if (GRAPHVIZ_URI == TRUE)
+                 {
+                     $attrib[$object] .= "URL=\"".$object."\"";
+                 }
+             }
+         }
+
+         // fill graph array
+         $graph[] = "\"".$subject."\" -> \"".$object."\" [".$predicate_label."];";
+     }
+
+     //generate DOT-file
+     $dot = "digraph G { ".$graphviz_param['GRAPH_STYLE']."\n edge [".$graphviz_param['PREDICATE_STYLE']."]\n node [".$graphviz_param['RESOURCE_STYLE']."]\n";
+     if (isset($attrib))
+     {
+         foreach ($attrib AS $key => $value)
+         {
+             $dot .= "\"$key\" [$value];\n";
+         }
+     }
+     if (!isset($graph))
+     {
+         $dot .= "error [shape=box,label=\"No Statements found!\"]";
+     }
+     else
+     {
+         $dot .= implode("\n", $graph);
+     }
+
+
+     if (GRAPHVIZ_STAT == TRUE)
+     {
+     	$stat_label = "| ".$model->size()." Statements drawn";
+     }
+     if ((strstr($graphviz_param['GRAPH_STYLE'], 'rankdir="LR"') === FALSE) && (strstr($graphviz_param['GRAPH_STYLE'], 'rankdir=LR') === FALSE))
+     {
+         $sep1 = "}";
+         $sep2 = "";
+     }
+     else
+     {
+         $sep1 = "";
+         $sep2 = "}";
+     }
+
+     if ($short_prefix == TRUE && isset($prefix_array))
+     {
+         $struct_label = "{ { Base URI: ".$model->getBaseURI()." $sep1 | { { ".implode("|", array_keys($prefix_array))." } | { ".implode("|", $prefix_array)." } } $stat_label } $sep2";
+     }
+     else
+     {
+         $struct_label = "{ { Base URI: ".$model->getBaseURI()."$sep1 ".$stat_label." } }";
+     }
+
+     $dot .= "\n struct [shape=Mrecord,label=\"$struct_label\",".$graphviz_param['BOX_STYLE']."];\n";
+     $dot .= " vocabulary [style=invis];\n struct -> vocabulary [style=invis];\n}";
+
+     // if needed call dot.exe
+     if (($format != "input_dot") && (defined('GRAPHVIZ_PATH')) && (strstr(GRAPHVIZ_FORMAT, $format) !== FALSE))
+     {
+         mt_srand((double)microtime()*1000000);
+         $filename=GRAPHVIZ_TEMP.md5(uniqid(mt_rand())).".dot";
+         $file_handle = @fopen($filename, 'w');
+         if ($file_handle)
+         {
+             fwrite($file_handle, $dot);
+             fclose($file_handle);
+         }
+         $dotinput = " -T".$format." ".$filename;
+
+         ob_start();
+	passthru(GRAPHVIZ_PATH.$dotinput);
+         $output = ob_get_contents();
+	ob_end_clean();
+         unlink($filename);
+         echo $output;
+         return TRUE;
+     }
+     elseif ($format == "input_dot")
+     {
+         echo $dot;
+         return TRUE;
+     }
+     else
+     {
+         return FALSE;
+     }
+ }
+
+} // end: RDfUtil
+
+?>
Index: /Dev/trunk/rdfapi/util/StatementIterator.php
===================================================================
--- /Dev/trunk/rdfapi/util/StatementIterator.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/StatementIterator.php	(revision 12)
@@ -0,0 +1,208 @@
+<?php
+
+// ----------------------------------------------------------------------------------
+// Class: StatementIterator
+// ----------------------------------------------------------------------------------
+
+/**
+ * Iterator for traversing models. 
+ * This class can be used for iterating forward and backward trough MemModels.
+ * It should be instanced using the getIterator() method of a MemModel.
+ * 
+ * @version  $Id: StatementIterator.php 268 2006-05-15 05:28:09Z tgauss $
+ * @author Daniel Westphal <mail at d-westphal dot de>
+ * @author Chris Bizer <chris@bizer.de>
+ *
+ * @package utility
+ * @access	public
+ *
+ */ 
+ class StatementIterator extends Object {
+
+ 	/**
+	* Reference to the MemModel
+	* @var		object MemModel
+	* @access	private
+	*/	
+    var $model;
+
+ 	/**
+	* Current position
+	* StatementIterator does not use the build in PHP array iterator,
+	* so you can use serveral iterators on a single MemModel.
+	* @var		integer
+	* @access	private
+	*/	
+    var $position;
+   
+  
+   /**
+    * Constructor
+    *
+    * @param	object	MemModel
+	* @access	public
+    */
+    function StatementIterator(&$model) {
+		$this->model = $model;
+		reset($this->model->triples);
+		$this->position = -1;
+	}
+ 
+  /**
+   * Returns TRUE if there are more statements.
+   * @return	boolean
+   * @access	public  
+   */
+  function hasNext() {
+  		if ($this->position == -1)
+  		{ 
+  			if(current($this->model->triples)!=NULL)
+  			{
+  				return TRUE;	
+  			} else 
+  			{
+  				return FALSE;
+  			}
+  		};
+
+  		if (next($this->model->triples)!=NULL ) 
+  		{	
+  			prev($this->model->triples);		
+  			return TRUE;
+		} else 
+		{
+			end($this->model->triples);
+			return FALSE;
+		};
+   }
+
+  /**
+   * Returns TRUE if the first statement has not been reached.
+   * @return	boolean
+   * @access	public  
+   */
+  function hasPrevious() {
+  		if (prev($this->model->triples)!=NULL) 
+  		{
+  			next($this->model->triples);
+			return TRUE;
+		} else {
+			reset($this->model->triples);
+			return FALSE;
+		};
+  }     
+   
+  /**
+   * Returns the next statement.
+   * @return	statement or NULL if there is no next statement.
+   * @access	public  
+   */
+  function next() {
+  		if ($this->position == -1)
+  		{ 
+  			if($return=current($this->model->triples))
+  			{
+  				$this->position=key($this->model->triples);
+  				return $return;	
+  			} else 
+  			{
+  				$this->position=key($this->model->triples);
+  				return NULL;
+  			};
+  		};
+  		
+  		
+  		if ($return=next($this->model->triples)) {
+  			$this->position=key($this->model->triples);
+			return $return;
+		} else {
+			$this->position=key($this->model->triples);
+			return NULL;
+		};
+   }
+
+  /**
+   * Returns the previous statement.
+   * @return	statement or NULL if there is no previous statement.
+   * @access	public  
+   */
+  function previous() {
+  		if ($return=prev($this->model->triples)) {
+  			$this->position=key($this->model->triples);
+			return $return;
+		} else {
+			$this->position=key($this->model->triples);
+			return NULL;
+		}   
+  }
+
+  /**
+   * Returns the current statement.
+   * @return	statement or NULL if there is no current statement.
+   * @access	public  
+   */
+  function current() {
+  		if ($this->position==-1) return NULL;
+  	
+  		if ($return=current($this->model->triples)) {
+			return $return;
+		} else {
+			return NULL;
+		}
+   }
+   
+  /**
+   * Moves the pointer to the first statement.
+   * @return	void
+   * @access	public  
+   */
+  function moveFirst() {
+  			reset($this->model->triples);
+  			$this->position=0;
+   }
+
+  /**
+   * Moves the pointer to the last statement.
+   * @return	void
+   * @access	public  
+   */
+  function moveLast() {
+  			end($this->model->triples);
+  			$this->position=key($this->model->triples);
+   }
+   
+     /**
+   * Moves the pointer to a specific statement.
+   * If you set an off-bounds value, the position will be set to the last element
+   * @param 	integer
+   * @return	void
+   * @access	public  
+   */
+  function moveTo($position) {
+  	
+  			if ($position + 1 > count($this->model->triples))
+  			{
+  				end($this->model->triples);
+  			} else 
+  			{
+	  			reset($this->model->triples);
+	  			
+				for ($i = 1; $i < $position; $i++) {
+				   next($this->model->triples);
+				}
+  			};
+  			$this->position=key($this->model->triples);
+   }
+   
+     /**
+   * Returns the current position of the iterator.
+   * @return	integer
+   * @access	public  
+   */
+  function getCurrentPosition() {
+  	 		return key($this->model->triples);
+   }
+  
+} 
+
+?>
Index: /Dev/trunk/rdfapi/util/Utility.php
===================================================================
--- /Dev/trunk/rdfapi/util/Utility.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/Utility.php	(revision 12)
@@ -0,0 +1,20 @@
+<?php
+// ----------------------------------------------------------------------------------
+// Utility
+// ----------------------------------------------------------------------------------
+//
+// Description               : Utility package
+//
+//
+// Author: Tobias Gauß	<tobias.gauss@web.de>
+//
+// ----------------------------------------------------------------------------------
+
+// include utility classes
+require_once( RDFAPI_INCLUDE_DIR . 'util/RdfUtil.php' );
+require_once( RDFAPI_INCLUDE_DIR . 'util/FindIterator.php' );
+require_once( RDFAPI_INCLUDE_DIR . 'util/IterFind.php' );
+
+// experimental
+require_once( RDFAPI_INCLUDE_DIR . 'util/ModelComparator.php' );
+?>
Index: /Dev/trunk/rdfapi/util/adodb/adodb-active-record.inc.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/adodb-active-record.inc.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/adodb-active-record.inc.php	(revision 12)
@@ -0,0 +1,622 @@
+<?php
+/*
+
+@version V4.94 23 Jan 2007  (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
+  Latest version is available at http://adodb.sourceforge.net
+ 
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence.
+  
+  Active Record implementation. Superset of Zend Framework's.
+  
+  Version 0.07
+  
+  See http://www-128.ibm.com/developerworks/java/library/j-cb03076/?ca=dgr-lnxw01ActiveRecord 
+  	for info on Ruby on Rails Active Record implementation
+*/
+
+global $_ADODB_ACTIVE_DBS;
+global $ADODB_ACTIVE_CACHESECS; // set to true to enable caching of metadata such as field info
+
+// array of ADODB_Active_DB's, indexed by ADODB_Active_Record->_dbat
+$_ADODB_ACTIVE_DBS = array();
+
+
+class ADODB_Active_DB {
+	var $db; // ADOConnection
+	var $tables; // assoc array of ADODB_Active_Table objects, indexed by tablename
+}
+
+class ADODB_Active_Table {
+	var $name; // table name
+	var $flds; // assoc array of adofieldobjs, indexed by fieldname
+	var $keys; // assoc array of primary keys, indexed by fieldname
+	var $_created; // only used when stored as a cached file
+}
+
+// returns index into $_ADODB_ACTIVE_DBS
+function ADODB_SetDatabaseAdapter(&$db)
+{
+	global $_ADODB_ACTIVE_DBS;
+	
+		foreach($_ADODB_ACTIVE_DBS as $k => $d) {
+			if (PHP_VERSION >= 5) {
+				if ($d->db === $db) return $k;
+			} else {
+				if ($d->db->_connectionID === $db->_connectionID && $db->database == $d->db->database) 
+					return $k;
+			}
+		}
+		
+		$obj = new ADODB_Active_DB();
+		$obj->db =& $db;
+		$obj->tables = array();
+		
+		$_ADODB_ACTIVE_DBS[] = $obj;
+		
+		return sizeof($_ADODB_ACTIVE_DBS)-1;
+}
+
+
+class ADODB_Active_Record {
+	var $_dbat; // associative index pointing to ADODB_Active_DB eg. $ADODB_Active_DBS[_dbat]
+	var $_table; // tablename, if set in class definition then use it as table name
+	var $_tableat; // associative index pointing to ADODB_Active_Table, eg $ADODB_Active_DBS[_dbat]->tables[$this->_tableat]
+	var $_where; // where clause set in Load()
+	var $_saved = false; // indicates whether data is already inserted.
+	var $_lasterr = false; // last error message
+	var $_original = false; // the original values loaded or inserted, refreshed on update
+	
+	// should be static
+	function SetDatabaseAdapter(&$db) 
+	{
+		return ADODB_SetDatabaseAdapter($db);
+	}
+	
+	// php4 constructor
+	function ADODB_Active_Record($table = false, $pkeyarr=false, $db=false)
+	{
+		ADODB_Active_Record::__construct($table,$pkeyarr,$db);
+	}
+	
+	// php5 constructor
+	function __construct($table = false, $pkeyarr=false, $db=false)
+	{
+	global $ADODB_ASSOC_CASE,$_ADODB_ACTIVE_DBS;
+	
+		if ($db == false && is_object($pkeyarr)) {
+			$db = $pkeyarr;
+			$pkeyarr = false;
+		}
+		
+		if (!$table) { 
+			if (!empty($this->_table)) $table = $this->_table;
+			else $table = $this->_pluralize(get_class($this));
+		}
+		if ($db) {
+			$this->_dbat = ADODB_Active_Record::SetDatabaseAdapter($db);
+		} else
+			$this->_dbat = sizeof($_ADODB_ACTIVE_DBS)-1;
+		
+		
+		if ($this->_dbat < 0) $this->Error("No database connection set; use ADOdb_Active_Record::SetDatabaseAdapter(\$db)",'ADODB_Active_Record::__constructor');
+		
+		$this->_table = $table;
+		$this->_tableat = $table; # reserved for setting the assoc value to a non-table name, eg. the sql string in future
+		$this->UpdateActiveTable($pkeyarr);
+	}
+	
+	function __wakeup()
+	{
+  		$class = get_class($this);
+  		new $class;
+	}
+	
+	function _pluralize($table)
+	{
+		$ut = strtoupper($table);
+		$len = strlen($table);
+		$lastc = $ut[$len-1];
+		$lastc2 = substr($ut,$len-2);
+		switch ($lastc) {
+		case 'S':
+			return $table.'es';	
+		case 'Y':
+			return substr($table,0,$len-1).'ies';
+		case 'X':	
+			return $table.'es';
+		case 'H': 
+			if ($lastc2 == 'CH' || $lastc2 == 'SH')
+				return $table.'es';
+		default:
+			return $table.'s';
+		}
+	}
+	
+	//////////////////////////////////
+	
+	// update metadata
+	function UpdateActiveTable($pkeys=false,$forceUpdate=false)
+	{
+	global $ADODB_ASSOC_CASE,$_ADODB_ACTIVE_DBS , $ADODB_CACHE_DIR, $ADODB_ACTIVE_CACHESECS;
+	
+		$activedb =& $_ADODB_ACTIVE_DBS[$this->_dbat];
+
+		$table = $this->_table;
+		$tables = $activedb->tables;
+		$tableat = $this->_tableat;
+		if (!$forceUpdate && !empty($tables[$tableat])) {
+			$tobj =& $tables[$tableat];
+			foreach($tobj->flds as $name => $fld) 
+				$this->$name = null;
+			return;
+		}
+		
+		$db =& $activedb->db;
+		$fname = $ADODB_CACHE_DIR . '/adodb_' . $db->databaseType . '_active_'. $table . '.cache';
+		if (!$forceUpdate && $ADODB_ACTIVE_CACHESECS && $ADODB_CACHE_DIR && file_exists($fname)) {
+			$fp = fopen($fname,'r');
+			@flock($fp, LOCK_SH);
+			$acttab = unserialize(fread($fp,100000));
+			fclose($fp);
+			if ($acttab->_created + $ADODB_ACTIVE_CACHESECS - (abs(rand()) % 16) > time()) { 
+				// abs(rand()) randomizes deletion, reducing contention to delete/refresh file
+				// ideally, you should cache at least 32 secs
+				$activedb->tables[$table] = $acttab;
+				
+				//if ($db->debug) ADOConnection::outp("Reading cached active record file: $fname");
+			  	return;
+			} else if ($db->debug) {
+				ADOConnection::outp("Refreshing cached active record file: $fname");
+			}
+		}
+		$activetab = new ADODB_Active_Table();
+		$activetab->name = $table;
+		
+		
+		$cols = $db->MetaColumns($table);
+		if (!$cols) {
+			$this->Error("Invalid table name: $table",'UpdateActiveTable'); 
+			return false;
+		}
+		$fld = reset($cols);
+		if (!$pkeys) {
+			if (isset($fld->primary_key)) {
+				$pkeys = array();
+				foreach($cols as $name => $fld) {
+					if (!empty($fld->primary_key)) $pkeys[] = $name;
+				}
+			} else	
+				$pkeys = $this->GetPrimaryKeys($db, $table);
+		}
+		if (empty($pkeys)) {
+			$this->Error("No primary key found for table $table",'UpdateActiveTable');
+			return false;
+		}
+		
+		$attr = array();
+		$keys = array();
+		
+		switch($ADODB_ASSOC_CASE) {
+		case 0:
+			foreach($cols as $name => $fldobj) {
+				$name = strtolower($name);
+				$this->$name = null;
+				$attr[$name] = $fldobj;
+			}
+			foreach($pkeys as $k => $name) {
+				$keys[strtolower($name)] = strtolower($name);
+			}
+			break;
+			
+		case 1: 
+			foreach($cols as $name => $fldobj) {
+				$name = strtoupper($name);
+				$this->$name = null;
+				$attr[$name] = $fldobj;
+			}
+			
+			foreach($pkeys as $k => $name) {
+				$keys[strtoupper($name)] = strtoupper($name);
+			}
+			break;
+		default:
+			foreach($cols as $name => $fldobj) {
+				$name = ($fldobj->name);
+				$this->$name = null;
+				$attr[$name] = $fldobj;
+			}
+			foreach($pkeys as $k => $name) {
+				$keys[$name] = $cols[$name]->name;
+			}
+			break;
+		}
+		
+		$activetab->keys = $keys;
+		$activetab->flds = $attr;
+
+		if ($ADODB_ACTIVE_CACHESECS && $ADODB_CACHE_DIR) {
+			$activetab->_created = time();
+			$s = serialize($activetab);
+			if (!function_exists('adodb_write_file')) include(ADODB_DIR.'/adodb-csvlib.inc.php');
+			adodb_write_file($fname,$s);
+		}
+		$activedb->tables[$table] = $activetab;
+	}
+	
+	function GetPrimaryKeys(&$db, $table)
+	{
+		return $db->MetaPrimaryKeys($table);
+	}
+	
+	// error handler for both PHP4+5. 
+	function Error($err,$fn)
+	{
+	global $_ADODB_ACTIVE_DBS;
+	
+		$fn = get_class($this).'::'.$fn;
+		$this->_lasterr = $fn.': '.$err;
+		
+		if ($this->_dbat < 0) $db = false;
+		else {
+			$activedb = $_ADODB_ACTIVE_DBS[$this->_dbat];
+			$db =& $activedb->db;
+		}
+		
+		if (function_exists('adodb_throw')) {	
+			if (!$db) adodb_throw('ADOdb_Active_Record', $fn, -1, $err, 0, 0, false);
+			else adodb_throw($db->databaseType, $fn, -1, $err, 0, 0, $db);
+		} else
+			if (!$db || $db->debug) ADOConnection::outp($this->_lasterr);
+		
+	}
+	
+	// return last error message
+	function ErrorMsg()
+	{
+		if (!function_exists('adodb_throw')) {
+			if ($this->_dbat < 0) $db = false;
+			else $db = $this->DB();
+		
+			// last error could be database error too
+			if ($db && $db->ErrorMsg()) return $db->ErrorMsg();
+		}
+		return $this->_lasterr;
+	}
+	
+	function ErrorNo() 
+	{
+		if ($this->_dbat < 0) return -9999; // no database connection...
+		$db = $this->DB();
+		
+		return (int) $db->ErrorNo();
+	}
+
+
+	// retrieve ADOConnection from _ADODB_Active_DBs
+	function &DB()
+	{
+	global $_ADODB_ACTIVE_DBS;
+	
+		if ($this->_dbat < 0) {
+			$false = false;
+			$this->Error("No database connection set: use ADOdb_Active_Record::SetDatabaseAdaptor(\$db)", "DB");
+			return $false;
+		}
+		$activedb = $_ADODB_ACTIVE_DBS[$this->_dbat];
+		$db =& $activedb->db;
+		return $db;
+	}
+	
+	// retrieve ADODB_Active_Table
+	function &TableInfo()
+	{
+	global $_ADODB_ACTIVE_DBS;
+	
+		$activedb = $_ADODB_ACTIVE_DBS[$this->_dbat];
+		$table =& $activedb->tables[$this->_tableat];
+		return $table;
+	}
+	
+	// set a numeric array (using natural table field ordering) as object properties
+	function Set(&$row)
+	{
+		$db =& $this->DB();
+		
+		if (!$row) {
+			$this->_saved = false;		
+			return false;
+		}
+		
+		$this->_saved = true;
+		
+		$table =& $this->TableInfo();
+		if (sizeof($table->flds) != sizeof($row)) {
+			$this->Error("Table structure of $this->_table has changed","Load");
+			return false;
+		}
+		
+		$cnt = 0;
+		foreach($table->flds as $name=>$fld) {
+			$this->$name = $row[$cnt];
+			$cnt += 1;
+		}
+		$this->_original = $row;
+		return true;
+	}
+	
+	// get last inserted id for INSERT
+	function LastInsertID(&$db,$fieldname)
+	{
+		if ($db->hasInsertID)
+			$val = $db->Insert_ID($this->_table,$fieldname);
+		else
+			$val = false;
+			
+		if (is_null($val) || $val === false) {
+			// this might not work reliably in multi-user environment
+			return $db->GetOne("select max(".$fieldname.") from ".$this->_table);
+		}
+		return $val;
+	}
+	
+	// quote data in where clause
+	function doquote(&$db, $val,$t)
+	{
+		switch($t) {
+		case 'D':
+		case 'T':
+			if (empty($val)) return 'null';
+			
+		case 'C':
+		case 'X':
+			if (is_null($val)) return 'null';
+			
+			if (strncmp($val,"'",1) != 0 && substr($val,strlen($val)-1,1) != "'") { 
+				return $db->qstr($val);
+				break;
+			}
+		default:
+			return $val;
+			break;
+		}
+	}
+	
+	// generate where clause for an UPDATE/SELECT
+	function GenWhere(&$db, &$table)
+	{
+		$keys = $table->keys;
+		$parr = array();
+		
+		foreach($keys as $k) {
+			$f = $table->flds[$k];
+			if ($f) {
+				$parr[] = $k.' = '.$this->doquote($db,$this->$k,$db->MetaType($f->type));
+			}
+		}
+		return implode(' and ', $parr);
+	}
+	
+	
+	//------------------------------------------------------------ Public functions below
+	
+	function Load($where,$bindarr=false)
+	{
+		$db =& $this->DB(); if (!$db) return false;
+		$this->_where = $where;
+		
+		$save = $db->SetFetchMode(ADODB_FETCH_NUM);
+		$row = $db->GetRow("select * from ".$this->_table.' WHERE '.$where,$bindarr);
+		$db->SetFetchMode($save);
+		
+		return $this->Set($row);
+	}
+	
+	// false on error
+	function Save()
+	{
+		if ($this->_saved) $ok = $this->Update();
+		else $ok = $this->Insert();
+		
+		return $ok;
+	}
+	
+	// false on error
+	function Insert()
+	{
+		$db =& $this->DB(); if (!$db) return false;
+		$cnt = 0;
+		$table =& $this->TableInfo();
+		
+		$valarr = array();
+		$names = array();
+		$valstr = array();
+
+		foreach($table->flds as $name=>$fld) {
+			$val = $this->$name;
+			if(!is_null($val) || !array_key_exists($name, $table->keys)) {
+				$valarr[] = $val;
+				$names[] = $name;
+				$valstr[] = $db->Param($cnt);
+				$cnt += 1;
+			}
+		}
+		
+		if (empty($names)){
+			foreach($table->flds as $name=>$fld) {
+				$valarr[] = null;
+				$names[] = $name;
+				$valstr[] = $db->Param($cnt);
+				$cnt += 1;
+			}
+		}
+		$sql = 'INSERT INTO '.$this->_table."(".implode(',',$names).') VALUES ('.implode(',',$valstr).')';
+		$ok = $db->Execute($sql,$valarr);
+		
+		if ($ok) {
+			$this->_saved = true;
+			$autoinc = false;
+			foreach($table->keys as $k) {
+				if (is_null($this->$k)) {
+					$autoinc = true;
+					break;
+				}
+			}
+			if ($autoinc && sizeof($table->keys) == 1) {
+				$k = reset($table->keys);
+				$this->$k = $this->LastInsertID($db,$k);
+			}
+		}
+		
+		$this->_original = $valarr;
+		return !empty($ok);
+	}
+	
+	function Delete()
+	{
+		$db =& $this->DB(); if (!$db) return false;
+		$table =& $this->TableInfo();
+		
+		$where = $this->GenWhere($db,$table);
+		$sql = 'DELETE FROM '.$this->_table.' WHERE '.$where;
+		$ok = $db->Execute($sql);
+		
+		return $ok ? true : false;
+	}
+	
+	// returns an array of active record objects
+	function &Find($whereOrderBy,$bindarr=false,$pkeysArr=false)
+	{
+		$db =& $this->DB(); if (!$db || empty($this->_table)) return false;
+		$arr =& $db->GetActiveRecordsClass(get_class($this),$this->_table, $whereOrderBy,$bindarr,$pkeysArr);
+		return $arr;
+	}
+	
+	// returns 0 on error, 1 on update, 2 on insert
+	function Replace()
+	{
+	global $ADODB_ASSOC_CASE;
+		
+		$db =& $this->DB(); if (!$db) return false;
+		$table =& $this->TableInfo();
+		
+		$pkey = $table->keys;
+		
+		foreach($table->flds as $name=>$fld) {
+			$val = $this->$name;
+			/*
+			if (is_null($val)) {
+				if (isset($fld->not_null) && $fld->not_null) {
+					if (isset($fld->default_value) && strlen($fld->default_value)) continue;
+					else {
+						$this->Error("Cannot update null into $name","Replace");
+						return false;
+					}
+				}
+			}*/
+			if (is_null($val) && !empty($fld->auto_increment)) {
+            	continue;
+            }
+			$t = $db->MetaType($fld->type);
+			$arr[$name] = $this->doquote($db,$val,$t);
+			$valarr[] = $val;
+		}
+		
+		if (!is_array($pkey)) $pkey = array($pkey);
+		
+		
+		if ($ADODB_ASSOC_CASE == 0) 
+			foreach($pkey as $k => $v)
+				$pkey[$k] = strtolower($v);
+		elseif ($ADODB_ASSOC_CASE == 0) 
+			foreach($pkey as $k => $v)
+				$pkey[$k] = strtoupper($v);
+				
+		$ok = $db->Replace($this->_table,$arr,$pkey);
+		if ($ok) {
+			$this->_saved = true; // 1= update 2=insert
+			if ($ok == 2) {
+				$autoinc = false;
+				foreach($table->keys as $k) {
+					if (is_null($this->$k)) {
+						$autoinc = true;
+						break;
+					}
+				}
+				if ($autoinc && sizeof($table->keys) == 1) {
+					$k = reset($table->keys);
+					$this->$k = $this->LastInsertID($db,$k);
+				}
+			}
+			
+			$this->_original =& $valarr;
+		} 
+		return $ok;
+	}
+
+	// returns 0 on error, 1 on update, -1 if no change in data (no update)
+	function Update()
+	{
+		$db =& $this->DB(); if (!$db) return false;
+		$table =& $this->TableInfo();
+		
+		$where = $this->GenWhere($db, $table);
+		
+		if (!$where) {
+			$this->error("Where missing for table $table", "Update");
+			return false;
+		}
+		$valarr = array(); 
+		$neworig = array();
+		$pairs = array();
+		$i = -1;
+		$cnt = 0;
+		foreach($table->flds as $name=>$fld) {
+			$i += 1;
+			$val = $this->$name;
+			$neworig[] = $val;
+			
+			if (isset($table->keys[$name])) {
+				continue;
+			}
+			
+			if (is_null($val)) {
+				if (isset($fld->not_null) && $fld->not_null) {
+					if (isset($fld->default_value) && strlen($fld->default_value)) continue;
+					else {
+						$this->Error("Cannot set field $name to NULL","Update");
+						return false;
+					}
+				}
+			}
+			
+			if (isset($this->_original[$i]) && $val == $this->_original[$i]) {
+				continue;
+			}			
+			$valarr[] = $val;
+			$pairs[] = $name.'='.$db->Param($cnt);
+			$cnt += 1;
+		}
+		
+		
+		if (!$cnt) return -1;
+		$sql = 'UPDATE '.$this->_table." SET ".implode(",",$pairs)." WHERE ".$where;
+		$ok = $db->Execute($sql,$valarr);
+		if ($ok) {
+			$this->_original =& $neworig;
+			return 1;
+		}
+		return 0;
+	}
+	
+	function GetAttributeNames()
+	{
+		$table =& $this->TableInfo();
+		if (!$table) return false;
+		return array_keys($table->flds);
+	}
+	
+};
+
+?>
Index: /Dev/trunk/rdfapi/util/adodb/adodb-csvlib.inc.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/adodb-csvlib.inc.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/adodb-csvlib.inc.php	(revision 12)
@@ -0,0 +1,312 @@
+<?php
+
+// security - hide paths
+if (!defined('ADODB_DIR')) die();
+
+global $ADODB_INCLUDED_CSV;
+$ADODB_INCLUDED_CSV = 1;
+
+/* 
+
+  V4.94 23 Jan 2007  (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence. See License.txt. 
+  Set tabs to 4 for best viewing.
+  
+  Latest version is available at http://adodb.sourceforge.net
+  
+  Library for CSV serialization. This is used by the csv/proxy driver and is the 
+  CacheExecute() serialization format. 
+  
+  ==== NOTE ====
+  Format documented at http://php.weblogs.com/ADODB_CSV
+  ==============
+*/
+
+	/**
+ 	 * convert a recordset into special format
+	 *
+	 * @param rs	the recordset
+	 *
+	 * @return	the CSV formated data
+	 */
+	function _rs2serialize(&$rs,$conn=false,$sql='')
+	{
+		$max = ($rs) ? $rs->FieldCount() : 0;
+		
+		if ($sql) $sql = urlencode($sql);
+		// metadata setup
+		
+		if ($max <= 0 || $rs->dataProvider == 'empty') { // is insert/update/delete
+			if (is_object($conn)) {
+				$sql .= ','.$conn->Affected_Rows();
+				$sql .= ','.$conn->Insert_ID();
+			} else
+				$sql .= ',,';
+			
+			$text = "====-1,0,$sql\n";
+			return $text;
+		}
+		$tt = ($rs->timeCreated) ? $rs->timeCreated : time();
+		
+		## changed format from ====0 to ====1
+		$line = "====1,$tt,$sql\n";
+		
+		if ($rs->databaseType == 'array') {
+			$rows =& $rs->_array;
+		} else {
+			$rows = array();
+			while (!$rs->EOF) {	
+				$rows[] = $rs->fields;
+				$rs->MoveNext();
+			} 
+		}
+		
+		for($i=0; $i < $max; $i++) {
+			$o =& $rs->FetchField($i);
+			$flds[] = $o;
+		}
+	
+		$savefetch = isset($rs->adodbFetchMode) ? $rs->adodbFetchMode : $rs->fetchMode;
+		$class = $rs->connection->arrayClass;
+		$rs2 = new $class();
+		$rs2->sql = $rs->sql;
+		$rs2->oldProvider = $rs->dataProvider; 
+		$rs2->InitArrayFields($rows,$flds);
+		$rs2->fetchMode = $savefetch;
+		return $line.serialize($rs2);
+	}
+
+	
+/**
+* Open CSV file and convert it into Data. 
+*
+* @param url  		file/ftp/http url
+* @param err		returns the error message
+* @param timeout	dispose if recordset has been alive for $timeout secs
+*
+* @return		recordset, or false if error occured. If no
+*			error occurred in sql INSERT/UPDATE/DELETE, 
+*			empty recordset is returned
+*/
+	function &csv2rs($url,&$err,$timeout=0, $rsclass='ADORecordSet_array')
+	{
+		$false = false;
+		$err = false;
+		$fp = @fopen($url,'rb');
+		if (!$fp) {
+			$err = $url.' file/URL not found';
+			return $false;
+		}
+		@flock($fp, LOCK_SH);
+		$arr = array();
+		$ttl = 0;
+		
+		if ($meta = fgetcsv($fp, 32000, ",")) {
+			// check if error message
+			if (strncmp($meta[0],'****',4) === 0) {
+				$err = trim(substr($meta[0],4,1024));
+				fclose($fp);
+				return $false;
+			}
+			// check for meta data
+			// $meta[0] is -1 means return an empty recordset
+			// $meta[1] contains a time 
+	
+			if (strncmp($meta[0], '====',4) === 0) {
+			
+				if ($meta[0] == "====-1") {
+					if (sizeof($meta) < 5) {
+						$err = "Corrupt first line for format -1";
+						fclose($fp);
+						return $false;
+					}
+					fclose($fp);
+					
+					if ($timeout > 0) {
+						$err = " Illegal Timeout $timeout ";
+						return $false;
+					}
+					
+					$rs = new $rsclass($val=true);
+					$rs->fields = array();
+					$rs->timeCreated = $meta[1];
+					$rs->EOF = true;
+					$rs->_numOfFields = 0;
+					$rs->sql = urldecode($meta[2]);
+					$rs->affectedrows = (integer)$meta[3];
+					$rs->insertid = $meta[4];	
+					return $rs;
+				} 
+			# Under high volume loads, we want only 1 thread/process to _write_file
+			# so that we don't have 50 processes queueing to write the same data.
+			# We use probabilistic timeout, ahead of time.
+			#
+			# -4 sec before timeout, give processes 1/32 chance of timing out
+			# -2 sec before timeout, give processes 1/16 chance of timing out
+			# -1 sec after timeout give processes 1/4 chance of timing out
+			# +0 sec after timeout, give processes 100% chance of timing out
+				if (sizeof($meta) > 1) {
+					if($timeout >0){ 
+						$tdiff = (integer)( $meta[1]+$timeout - time());
+						if ($tdiff <= 2) {
+							switch($tdiff) {
+							case 4:
+							case 3:
+								if ((rand() & 31) == 0) {
+									fclose($fp);
+									$err = "Timeout 3";
+									return $false;
+								}
+								break;
+							case 2: 
+								if ((rand() & 15) == 0) {
+									fclose($fp);
+									$err = "Timeout 2";
+									return $false;
+								}
+								break;
+							case 1:
+								if ((rand() & 3) == 0) {
+									fclose($fp);
+									$err = "Timeout 1";
+									return $false;
+								}
+								break;
+							default: 
+								fclose($fp);
+								$err = "Timeout 0";
+								return $false;
+							} // switch
+							
+						} // if check flush cache
+					}// (timeout>0)
+					$ttl = $meta[1];
+				}
+				//================================================
+				// new cache format - use serialize extensively...
+				if ($meta[0] === '====1') {
+					// slurp in the data
+					$MAXSIZE = 128000;
+					
+					$text = fread($fp,$MAXSIZE);
+					if (strlen($text)) {
+						while ($txt = fread($fp,$MAXSIZE)) {
+							$text .= $txt;
+						}
+					}
+					fclose($fp);
+					$rs = unserialize($text);
+					if (is_object($rs)) $rs->timeCreated = $ttl;
+					else {
+						$err = "Unable to unserialize recordset";
+						//echo htmlspecialchars($text),' !--END--!<p>';
+					}
+					return $rs;
+				}
+				
+				$meta = false;
+				$meta = fgetcsv($fp, 32000, ",");
+				if (!$meta) {
+					fclose($fp);
+					$err = "Unexpected EOF 1";
+					return $false;
+				}
+			}
+
+			// Get Column definitions
+			$flds = array();
+			foreach($meta as $o) {
+				$o2 = explode(':',$o);
+				if (sizeof($o2)!=3) {
+					$arr[] = $meta;
+					$flds = false;
+					break;
+				}
+				$fld = new ADOFieldObject();
+				$fld->name = urldecode($o2[0]);
+				$fld->type = $o2[1];
+				$fld->max_length = $o2[2];
+				$flds[] = $fld;
+			}
+		} else {
+			fclose($fp);
+			$err = "Recordset had unexpected EOF 2";
+			return $false;
+		}
+		
+		// slurp in the data
+		$MAXSIZE = 128000;
+		
+		$text = '';
+		while ($txt = fread($fp,$MAXSIZE)) {
+			$text .= $txt;
+		}
+			
+		fclose($fp);
+		@$arr = unserialize($text);
+		//var_dump($arr);
+		if (!is_array($arr)) {
+			$err = "Recordset had unexpected EOF (in serialized recordset)";
+			if (get_magic_quotes_runtime()) $err .= ". Magic Quotes Runtime should be disabled!";
+			return $false;
+		}
+		$rs = new $rsclass();
+		$rs->timeCreated = $ttl;
+		$rs->InitArrayFields($arr,$flds);
+		return $rs;
+	}
+	
+
+	/**
+	* Save a file $filename and its $contents (normally for caching) with file locking
+	*/
+	function adodb_write_file($filename, $contents,$debug=false)
+	{ 
+	# http://www.php.net/bugs.php?id=9203 Bug that flock fails on Windows
+	# So to simulate locking, we assume that rename is an atomic operation.
+	# First we delete $filename, then we create a $tempfile write to it and 
+	# rename to the desired $filename. If the rename works, then we successfully 
+	# modified the file exclusively.
+	# What a stupid need - having to simulate locking.
+	# Risks:
+	# 1. $tempfile name is not unique -- very very low
+	# 2. unlink($filename) fails -- ok, rename will fail
+	# 3. adodb reads stale file because unlink fails -- ok, $rs timeout occurs
+	# 4. another process creates $filename between unlink() and rename() -- ok, rename() fails and  cache updated
+		if (strncmp(PHP_OS,'WIN',3) === 0) {
+			// skip the decimal place
+			$mtime = substr(str_replace(' ','_',microtime()),2); 
+			// getmypid() actually returns 0 on Win98 - never mind!
+			$tmpname = $filename.uniqid($mtime).getmypid();
+			if (!($fd = @fopen($tmpname,'a'))) return false;
+			$ok = ftruncate($fd,0);			
+			if (!fwrite($fd,$contents)) $ok = false;
+			fclose($fd);
+			chmod($tmpname,0644);
+			// the tricky moment
+			@unlink($filename);
+			if (!@rename($tmpname,$filename)) {
+				unlink($tmpname);
+				$ok = false;
+			}
+			if (!$ok) {
+				if ($debug) ADOConnection::outp( " Rename $tmpname ".($ok? 'ok' : 'failed'));
+			}
+			return $ok;
+		}
+		if (!($fd = @fopen($filename, 'a'))) return false;
+		if (flock($fd, LOCK_EX) && ftruncate($fd, 0)) {
+			$ok = fwrite( $fd, $contents );
+			fclose($fd);
+			chmod($filename,0644);
+		}else {
+			fclose($fd);
+			if ($debug)ADOConnection::outp( " Failed acquiring lock for $filename<br>\n");
+			$ok = false;
+		}
+	
+		return $ok;
+	}
+?>
Index: /Dev/trunk/rdfapi/util/adodb/adodb-datadict.inc.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/adodb-datadict.inc.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/adodb-datadict.inc.php	(revision 12)
@@ -0,0 +1,889 @@
+<?php
+
+/**
+  V4.94 23 Jan 2007  (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence.
+	
+  Set tabs to 4 for best viewing.
+ 
+ 	DOCUMENTATION:
+	
+		See adodb/tests/test-datadict.php for docs and examples.
+*/
+
+/*
+	Test script for parser
+*/
+
+// security - hide paths
+if (!defined('ADODB_DIR')) die();
+
+function Lens_ParseTest()
+{
+$str = "`zcol ACOL` NUMBER(32,2) DEFAULT 'The \"cow\" (and Jim''s dog) jumps over the moon' PRIMARY, INTI INT AUTO DEFAULT 0, zcol2\"afs ds";
+print "<p>$str</p>";
+$a= Lens_ParseArgs($str);
+print "<pre>";
+print_r($a);
+print "</pre>";
+}
+
+
+if (!function_exists('ctype_alnum')) {
+	function ctype_alnum($text) {
+		return preg_match('/^[a-z0-9]*$/i', $text);
+	}
+}
+
+//Lens_ParseTest();
+
+/**
+	Parse arguments, treat "text" (text) and 'text' as quotation marks.
+	To escape, use "" or '' or ))
+	
+	Will read in "abc def" sans quotes, as: abc def
+	Same with 'abc def'.
+	However if `abc def`, then will read in as `abc def`
+	
+	@param endstmtchar    Character that indicates end of statement
+	@param tokenchars     Include the following characters in tokens apart from A-Z and 0-9 
+	@returns 2 dimensional array containing parsed tokens.
+*/
+function Lens_ParseArgs($args,$endstmtchar=',',$tokenchars='_.-')
+{
+	$pos = 0;
+	$intoken = false;
+	$stmtno = 0;
+	$endquote = false;
+	$tokens = array();
+	$tokens[$stmtno] = array();
+	$max = strlen($args);
+	$quoted = false;
+	$tokarr = array();
+	
+	while ($pos < $max) {
+		$ch = substr($args,$pos,1);
+		switch($ch) {
+		case ' ':
+		case "\t":
+		case "\n":
+		case "\r":
+			if (!$quoted) {
+				if ($intoken) {
+					$intoken = false;
+					$tokens[$stmtno][] = implode('',$tokarr);
+				}
+				break;
+			}
+			
+			$tokarr[] = $ch;
+			break;
+		
+		case '`':
+			if ($intoken) $tokarr[] = $ch;
+		case '(':
+		case ')':	
+		case '"':
+		case "'":
+			
+			if ($intoken) {
+				if (empty($endquote)) {
+					$tokens[$stmtno][] = implode('',$tokarr);
+					if ($ch == '(') $endquote = ')';
+					else $endquote = $ch;
+					$quoted = true;
+					$intoken = true;
+					$tokarr = array();
+				} else if ($endquote == $ch) {
+					$ch2 = substr($args,$pos+1,1);
+					if ($ch2 == $endquote) {
+						$pos += 1;
+						$tokarr[] = $ch2;
+					} else {
+						$quoted = false;
+						$intoken = false;
+						$tokens[$stmtno][] = implode('',$tokarr);
+						$endquote = '';
+					}
+				} else
+					$tokarr[] = $ch;
+					
+			}else {
+			
+				if ($ch == '(') $endquote = ')';
+				else $endquote = $ch;
+				$quoted = true;
+				$intoken = true;
+				$tokarr = array();
+				if ($ch == '`') $tokarr[] = '`';
+			}
+			break;
+			
+		default:
+			
+			if (!$intoken) {
+				if ($ch == $endstmtchar) {
+					$stmtno += 1;
+					$tokens[$stmtno] = array();
+					break;
+				}
+			
+				$intoken = true;
+				$quoted = false;
+				$endquote = false;
+				$tokarr = array();
+	
+			}
+			
+			if ($quoted) $tokarr[] = $ch;
+			else if (ctype_alnum($ch) || strpos($tokenchars,$ch) !== false) $tokarr[] = $ch;
+			else {
+				if ($ch == $endstmtchar) {			
+					$tokens[$stmtno][] = implode('',$tokarr);
+					$stmtno += 1;
+					$tokens[$stmtno] = array();
+					$intoken = false;
+					$tokarr = array();
+					break;
+				}
+				$tokens[$stmtno][] = implode('',$tokarr);
+				$tokens[$stmtno][] = $ch;
+				$intoken = false;
+			}
+		}
+		$pos += 1;
+	}
+	if ($intoken) $tokens[$stmtno][] = implode('',$tokarr);
+	
+	return $tokens;
+}
+
+
+class ADODB_DataDict {
+	var $connection;
+	var $debug = false;
+	var $dropTable = 'DROP TABLE %s';
+	var $renameTable = 'RENAME TABLE %s TO %s'; 
+	var $dropIndex = 'DROP INDEX %s';
+	var $addCol = ' ADD';
+	var $alterCol = ' ALTER COLUMN';
+	var $dropCol = ' DROP COLUMN';
+	var $renameColumn = 'ALTER TABLE %s RENAME COLUMN %s TO %s';	// table, old-column, new-column, column-definitions (not used by default)
+	var $nameRegex = '\w';
+	var $nameRegexBrackets = 'a-zA-Z0-9_\(\)';
+	var $schema = false;
+	var $serverInfo = array();
+	var $autoIncrement = false;
+	var $dataProvider;
+	var $invalidResizeTypes4 = array('CLOB','BLOB','TEXT','DATE','TIME'); // for changetablesql
+	var $blobSize = 100; 	/// any varchar/char field this size or greater is treated as a blob
+							/// in other words, we use a text area for editting.
+	
+	function GetCommentSQL($table,$col)
+	{
+		return false;
+	}
+	
+	function SetCommentSQL($table,$col,$cmt)
+	{
+		return false;
+	}
+	
+	function MetaTables()
+	{
+		if (!$this->connection->IsConnected()) return array();
+		return $this->connection->MetaTables();
+	}
+	
+	function MetaColumns($tab, $upper=true, $schema=false)
+	{
+		if (!$this->connection->IsConnected()) return array();
+		return $this->connection->MetaColumns($this->TableName($tab), $upper, $schema);
+	}
+	
+	function MetaPrimaryKeys($tab,$owner=false,$intkey=false)
+	{
+		if (!$this->connection->IsConnected()) return array();
+		return $this->connection->MetaPrimaryKeys($this->TableName($tab), $owner, $intkey);
+	}
+	
+	function MetaIndexes($table, $primary = false, $owner = false)
+	{
+		if (!$this->connection->IsConnected()) return array();
+		return $this->connection->MetaIndexes($this->TableName($table), $primary, $owner);
+	}
+	
+	function MetaType($t,$len=-1,$fieldobj=false)
+	{
+		return ADORecordSet::MetaType($t,$len,$fieldobj);
+	}
+	
+	function NameQuote($name = NULL,$allowBrackets=false)
+	{
+		if (!is_string($name)) {
+			return FALSE;
+		}
+		
+		$name = trim($name);
+		
+		if ( !is_object($this->connection) ) {
+			return $name;
+		}
+		
+		$quote = $this->connection->nameQuote;
+		
+		// if name is of the form `name`, quote it
+		if ( preg_match('/^`(.+)`$/', $name, $matches) ) {
+			return $quote . $matches[1] . $quote;
+		}
+		
+		// if name contains special characters, quote it
+		$regex = ($allowBrackets) ? $this->nameRegexBrackets : $this->nameRegex;
+		
+		if ( !preg_match('/^[' . $regex . ']+$/', $name) ) {
+			return $quote . $name . $quote;
+		}
+		
+		return $name;
+	}
+	
+	function TableName($name)
+	{
+		if ( $this->schema ) {
+			return $this->NameQuote($this->schema) .'.'. $this->NameQuote($name);
+		}
+		return $this->NameQuote($name);
+	}
+	
+	// Executes the sql array returned by GetTableSQL and GetIndexSQL
+	function ExecuteSQLArray($sql, $continueOnError = true)
+	{
+		$rez = 2;
+		$conn = &$this->connection;
+		$saved = $conn->debug;
+		foreach($sql as $line) {
+			
+			if ($this->debug) $conn->debug = true;
+			$ok = $conn->Execute($line);
+			$conn->debug = $saved;
+			if (!$ok) {
+				if ($this->debug) ADOConnection::outp($conn->ErrorMsg());
+				if (!$continueOnError) return 0;
+				$rez = 1;
+			}
+		}
+		return $rez;
+	}
+	
+	/**
+	 	Returns the actual type given a character code.
+		
+		C:  varchar
+		X:  CLOB (character large object) or largest varchar size if CLOB is not supported
+		C2: Multibyte varchar
+		X2: Multibyte CLOB
+		
+		B:  BLOB (binary large object)
+		
+		D:  Date
+		T:  Date-time 
+		L:  Integer field suitable for storing booleans (0 or 1)
+		I:  Integer
+		F:  Floating point number
+		N:  Numeric or decimal number
+	*/
+	
+	function ActualType($meta)
+	{
+		return $meta;
+	}
+	
+	function CreateDatabase($dbname,$options=false)
+	{
+		$options = $this->_Options($options);
+		$sql = array();
+		
+		$s = 'CREATE DATABASE ' . $this->NameQuote($dbname);
+		if (isset($options[$this->upperName]))
+			$s .= ' '.$options[$this->upperName];
+		
+		$sql[] = $s;
+		return $sql;
+	}
+	
+	/*
+	 Generates the SQL to create index. Returns an array of sql strings.
+	*/
+	function CreateIndexSQL($idxname, $tabname, $flds, $idxoptions = false)
+	{
+		if (!is_array($flds)) {
+			$flds = explode(',',$flds);
+		}
+		
+		foreach($flds as $key => $fld) {
+			# some indexes can use partial fields, eg. index first 32 chars of "name" with NAME(32)
+			$flds[$key] = $this->NameQuote($fld,$allowBrackets=true);
+		}
+		
+		return $this->_IndexSQL($this->NameQuote($idxname), $this->TableName($tabname), $flds, $this->_Options($idxoptions));
+	}
+	
+	function DropIndexSQL ($idxname, $tabname = NULL)
+	{
+		return array(sprintf($this->dropIndex, $this->NameQuote($idxname), $this->TableName($tabname)));
+	}
+	
+	function SetSchema($schema)
+	{
+		$this->schema = $schema;
+	}
+	
+	function AddColumnSQL($tabname, $flds)
+	{
+		$tabname = $this->TableName ($tabname);
+		$sql = array();
+		list($lines,$pkey,$idxs) = $this->_GenFields($flds);
+		// genfields can return FALSE at times
+		if ($lines  == null) $lines = array();
+		$alter = 'ALTER TABLE ' . $tabname . $this->addCol . ' ';
+		foreach($lines as $v) {
+			$sql[] = $alter . $v;
+		}
+		if (is_array($idxs)) {
+			foreach($idxs as $idx => $idxdef) {
+				$sql_idxs = $this->CreateIndexSql($idx, $tabname, $idxdef['cols'], $idxdef['opts']);
+				$sql = array_merge($sql, $sql_idxs);
+			}
+		}
+		return $sql;
+	}
+	
+	/**
+	 * Change the definition of one column
+	 *
+	 * As some DBM's can't do that on there own, you need to supply the complete defintion of the new table,
+	 * to allow, recreating the table and copying the content over to the new table
+	 * @param string $tabname table-name
+	 * @param string $flds column-name and type for the changed column
+	 * @param string $tableflds='' complete defintion of the new table, eg. for postgres, default ''
+	 * @param array/string $tableoptions='' options for the new table see CreateTableSQL, default ''
+	 * @return array with SQL strings
+	 */
+	function AlterColumnSQL($tabname, $flds, $tableflds='',$tableoptions='')
+	{
+		$tabname = $this->TableName ($tabname);
+		$sql = array();
+		list($lines,$pkey,$idxs) = $this->_GenFields($flds);
+		// genfields can return FALSE at times
+		if ($lines == null) $lines = array();
+		$alter = 'ALTER TABLE ' . $tabname . $this->alterCol . ' ';
+		foreach($lines as $v) {
+			$sql[] = $alter . $v;
+		}
+		if (is_array($idxs)) {
+			foreach($idxs as $idx => $idxdef) {
+				$sql_idxs = $this->CreateIndexSql($idx, $tabname, $idxdef['cols'], $idxdef['opts']);
+				$sql = array_merge($sql, $sql_idxs);
+			}
+
+		}
+		return $sql;
+	}
+	
+	/**
+	 * Rename one column
+	 *
+	 * Some DBM's can only do this together with changeing the type of the column (even if that stays the same, eg. mysql)
+	 * @param string $tabname table-name
+	 * @param string $oldcolumn column-name to be renamed
+	 * @param string $newcolumn new column-name
+	 * @param string $flds='' complete column-defintion-string like for AddColumnSQL, only used by mysql atm., default=''
+	 * @return array with SQL strings
+	 */
+	function RenameColumnSQL($tabname,$oldcolumn,$newcolumn,$flds='')
+	{
+		$tabname = $this->TableName ($tabname);
+		if ($flds) {
+			list($lines,$pkey,$idxs) = $this->_GenFields($flds);
+			// genfields can return FALSE at times
+			if ($lines == null) $lines = array();
+			list(,$first) = each($lines);
+			list(,$column_def) = split("[\t ]+",$first,2);
+		}
+		return array(sprintf($this->renameColumn,$tabname,$this->NameQuote($oldcolumn),$this->NameQuote($newcolumn),$column_def));
+	}
+		
+	/**
+	 * Drop one column
+	 *
+	 * Some DBM's can't do that on there own, you need to supply the complete defintion of the new table,
+	 * to allow, recreating the table and copying the content over to the new table
+	 * @param string $tabname table-name
+	 * @param string $flds column-name and type for the changed column
+	 * @param string $tableflds='' complete defintion of the new table, eg. for postgres, default ''
+	 * @param array/string $tableoptions='' options for the new table see CreateTableSQL, default ''
+	 * @return array with SQL strings
+	 */
+	function DropColumnSQL($tabname, $flds, $tableflds='',$tableoptions='')
+	{
+		$tabname = $this->TableName ($tabname);
+		if (!is_array($flds)) $flds = explode(',',$flds);
+		$sql = array();
+		$alter = 'ALTER TABLE ' . $tabname . $this->dropCol . ' ';
+		foreach($flds as $v) {
+			$sql[] = $alter . $this->NameQuote($v);
+		}
+		return $sql;
+	}
+	
+	function DropTableSQL($tabname)
+	{
+		return array (sprintf($this->dropTable, $this->TableName($tabname)));
+	}
+	
+	function RenameTableSQL($tabname,$newname)
+	{
+		return array (sprintf($this->renameTable, $this->TableName($tabname),$this->TableName($newname)));
+	}	
+	
+	/**
+	 Generate the SQL to create table. Returns an array of sql strings.
+	*/
+	function CreateTableSQL($tabname, $flds, $tableoptions=array())
+	{
+		list($lines,$pkey,$idxs) = $this->_GenFields($flds, true);
+		// genfields can return FALSE at times
+		if ($lines == null) $lines = array();
+		
+		$taboptions = $this->_Options($tableoptions);
+		$tabname = $this->TableName ($tabname);
+		$sql = $this->_TableSQL($tabname,$lines,$pkey,$taboptions);
+		
+		// ggiunta - 2006/10/12 - KLUDGE:
+        // if we are on autoincrement, and table options includes REPLACE, the
+        // autoincrement sequence has already been dropped on table creation sql, so
+        // we avoid passing REPLACE to trigger creation code. This prevents
+        // creating sql that double-drops the sequence
+        if ($this->autoIncrement && isset($taboptions['REPLACE']))
+        	unset($taboptions['REPLACE']);
+		$tsql = $this->_Triggers($tabname,$taboptions);
+		foreach($tsql as $s) $sql[] = $s;
+		
+		if (is_array($idxs)) {
+			foreach($idxs as $idx => $idxdef) {
+				$sql_idxs = $this->CreateIndexSql($idx, $tabname,  $idxdef['cols'], $idxdef['opts']);
+				$sql = array_merge($sql, $sql_idxs);
+			}
+		}
+
+		return $sql;
+	}
+	
+	function _GenFields($flds,$widespacing=false)
+	{
+		if (is_string($flds)) {
+			$padding = '     ';
+			$txt = $flds.$padding;
+			$flds = array();
+			$flds0 = Lens_ParseArgs($txt,',');
+			$hasparam = false;
+			foreach($flds0 as $f0) {
+				$f1 = array();
+				foreach($f0 as $token) {
+					switch (strtoupper($token)) {
+					case 'INDEX':
+						$f1['INDEX'] = '';
+						// fall through intentionally
+					case 'CONSTRAINT':
+					case 'DEFAULT': 
+						$hasparam = $token;
+						break;
+					default:
+						if ($hasparam) $f1[$hasparam] = $token;
+						else $f1[] = $token;
+						$hasparam = false;
+						break;
+					}
+				}
+				// 'index' token without a name means single column index: name it after column
+				if (array_key_exists('INDEX', $f1) && $f1['INDEX'] == '') {
+					$f1['INDEX'] = isset($f0['NAME']) ? $f0['NAME'] : $f0[0];
+					// check if column name used to create an index name was quoted
+					if (($f1['INDEX'][0] == '"' || $f1['INDEX'][0] == "'" || $f1['INDEX'][0] == "`") &&
+						($f1['INDEX'][0] == substr($f1['INDEX'], -1))) {
+						$f1['INDEX'] = $f1['INDEX'][0].'idx_'.substr($f1['INDEX'], 1, -1).$f1['INDEX'][0];
+					}
+					else
+						$f1['INDEX'] = 'idx_'.$f1['INDEX'];
+				}
+				// reset it, so we don't get next field 1st token as INDEX...
+				$hasparam = false;
+
+				$flds[] = $f1;
+				
+			}
+		}
+		$this->autoIncrement = false;
+		$lines = array();
+		$pkey = array();
+		$idxs = array();
+		foreach($flds as $fld) {
+			$fld = _array_change_key_case($fld);
+			
+			$fname = false;
+			$fdefault = false;
+			$fautoinc = false;
+			$ftype = false;
+			$fsize = false;
+			$fprec = false;
+			$fprimary = false;
+			$fnoquote = false;
+			$fdefts = false;
+			$fdefdate = false;
+			$fconstraint = false;
+			$fnotnull = false;
+			$funsigned = false;
+			$findex = '';
+			$funiqueindex = false;
+			
+			//-----------------
+			// Parse attributes
+			foreach($fld as $attr => $v) {
+				if ($attr == 2 && is_numeric($v)) $attr = 'SIZE';
+				else if (is_numeric($attr) && $attr > 1 && !is_numeric($v)) $attr = strtoupper($v);
+				
+				switch($attr) {
+				case '0':
+				case 'NAME': 	$fname = $v; break;
+				case '1':
+				case 'TYPE': 	$ty = $v; $ftype = $this->ActualType(strtoupper($v)); break;
+				
+				case 'SIZE': 	
+								$dotat = strpos($v,'.'); if ($dotat === false) $dotat = strpos($v,',');
+								if ($dotat === false) $fsize = $v;
+								else {
+									$fsize = substr($v,0,$dotat);
+									$fprec = substr($v,$dotat+1);
+								}
+								break;
+				case 'UNSIGNED': $funsigned = true; break;
+				case 'AUTOINCREMENT':
+				case 'AUTO':	$fautoinc = true; $fnotnull = true; break;
+				case 'KEY':
+                // a primary key col can be non unique in itself (if key spans many cols...)
+				case 'PRIMARY':	$fprimary = $v; $fnotnull = true; /*$funiqueindex = true;*/ break;
+				case 'DEF':
+				case 'DEFAULT': $fdefault = $v; break;
+				case 'NOTNULL': $fnotnull = $v; break;
+				case 'NOQUOTE': $fnoquote = $v; break;
+				case 'DEFDATE': $fdefdate = $v; break;
+				case 'DEFTIMESTAMP': $fdefts = $v; break;
+				case 'CONSTRAINT': $fconstraint = $v; break;
+				// let INDEX keyword create a 'very standard' index on column
+				case 'INDEX': $findex = $v; break;
+				case 'UNIQUE': $funiqueindex = true; break;
+				} //switch
+			} // foreach $fld
+			
+			//--------------------
+			// VALIDATE FIELD INFO
+			if (!strlen($fname)) {
+				if ($this->debug) ADOConnection::outp("Undefined NAME");
+				return false;
+			}
+			
+			$fid = strtoupper(preg_replace('/^`(.+)`$/', '$1', $fname));
+			$fname = $this->NameQuote($fname);
+			
+			if (!strlen($ftype)) {
+				if ($this->debug) ADOConnection::outp("Undefined TYPE for field '$fname'");
+				return false;
+			} else {
+				$ftype = strtoupper($ftype);
+			}
+			
+			$ftype = $this->_GetSize($ftype, $ty, $fsize, $fprec);
+			
+			if ($ty == 'X' || $ty == 'X2' || $ty == 'B') $fnotnull = false; // some blob types do not accept nulls
+			
+			if ($fprimary) $pkey[] = $fname;
+			
+			// some databases do not allow blobs to have defaults
+			if ($ty == 'X') $fdefault = false;
+			
+			// build list of indexes
+			if ($findex != '') {
+				if (array_key_exists($findex, $idxs)) {
+					$idxs[$findex]['cols'][] = ($fname);
+					if (in_array('UNIQUE', $idxs[$findex]['opts']) != $funiqueindex) {
+						if ($this->debug) ADOConnection::outp("Index $findex defined once UNIQUE and once not");
+					}
+					if ($funiqueindex && !in_array('UNIQUE', $idxs[$findex]['opts']))
+						$idxs[$findex]['opts'][] = 'UNIQUE';
+				}
+				else
+				{
+					$idxs[$findex] = array();
+					$idxs[$findex]['cols'] = array($fname);
+					if ($funiqueindex)
+						$idxs[$findex]['opts'] = array('UNIQUE');
+					else
+						$idxs[$findex]['opts'] = array();
+				}
+			}
+
+			//--------------------
+			// CONSTRUCT FIELD SQL
+			if ($fdefts) {
+				if (substr($this->connection->databaseType,0,5) == 'mysql') {
+					$ftype = 'TIMESTAMP';
+				} else {
+					$fdefault = $this->connection->sysTimeStamp;
+				}
+			} else if ($fdefdate) {
+				if (substr($this->connection->databaseType,0,5) == 'mysql') {
+					$ftype = 'TIMESTAMP';
+				} else {
+					$fdefault = $this->connection->sysDate;
+				}
+			} else if ($fdefault !== false && !$fnoquote) {
+				if ($ty == 'C' or $ty == 'X' or 
+					( substr($fdefault,0,1) != "'" && !is_numeric($fdefault))) {
+
+					if (($ty == 'D' || $ty == 'T') && strtolower($fdefault) != 'null') {
+						// convert default date into database-aware code
+						if ($ty == 'T')
+						{
+							$fdefault = $this->connection->DBTimeStamp($fdefault);
+						}
+						else
+						{
+							$fdefault = $this->connection->DBDate($fdefault);
+						}
+					}
+					else
+					if (strlen($fdefault) != 1 && substr($fdefault,0,1) == ' ' && substr($fdefault,strlen($fdefault)-1) == ' ') 
+						$fdefault = trim($fdefault);
+					else if (strtolower($fdefault) != 'null')
+						$fdefault = $this->connection->qstr($fdefault);
+				}
+			}
+			$suffix = $this->_CreateSuffix($fname,$ftype,$fnotnull,$fdefault,$fautoinc,$fconstraint,$funsigned);
+			
+			// add index creation
+			if ($widespacing) $fname = str_pad($fname,24);
+			
+			 // check for field names appearing twice
+            if (array_key_exists($fid, $lines)) {
+            	 ADOConnection::outp("Field '$fname' defined twice");
+            }
+			
+			$lines[$fid] = $fname.' '.$ftype.$suffix;
+			
+			if ($fautoinc) $this->autoIncrement = true;
+		} // foreach $flds
+		
+		return array($lines,$pkey,$idxs);
+	}
+
+	/**
+		 GENERATE THE SIZE PART OF THE DATATYPE
+			$ftype is the actual type
+			$ty is the type defined originally in the DDL
+	*/
+	function _GetSize($ftype, $ty, $fsize, $fprec)
+	{
+		if (strlen($fsize) && $ty != 'X' && $ty != 'B' && strpos($ftype,'(') === false) {
+			$ftype .= "(".$fsize;
+			if (strlen($fprec)) $ftype .= ",".$fprec;
+			$ftype .= ')';
+		}
+		return $ftype;
+	}
+	
+	
+	// return string must begin with space
+	function _CreateSuffix($fname,$ftype,$fnotnull,$fdefault,$fautoinc,$fconstraint)
+	{	
+		$suffix = '';
+		if (strlen($fdefault)) $suffix .= " DEFAULT $fdefault";
+		if ($fnotnull) $suffix .= ' NOT NULL';
+		if ($fconstraint) $suffix .= ' '.$fconstraint;
+		return $suffix;
+	}
+	
+	function _IndexSQL($idxname, $tabname, $flds, $idxoptions)
+	{
+		$sql = array();
+		
+		if ( isset($idxoptions['REPLACE']) || isset($idxoptions['DROP']) ) {
+			$sql[] = sprintf ($this->dropIndex, $idxname);
+			if ( isset($idxoptions['DROP']) )
+				return $sql;
+		}
+		
+		if ( empty ($flds) ) {
+			return $sql;
+		}
+		
+		$unique = isset($idxoptions['UNIQUE']) ? ' UNIQUE' : '';
+	
+		$s = 'CREATE' . $unique . ' INDEX ' . $idxname . ' ON ' . $tabname . ' ';
+		
+		if ( isset($idxoptions[$this->upperName]) )
+			$s .= $idxoptions[$this->upperName];
+		
+		if ( is_array($flds) )
+			$flds = implode(', ',$flds);
+		$s .= '(' . $flds . ')';
+		$sql[] = $s;
+		
+		return $sql;
+	}
+	
+	function _DropAutoIncrement($tabname)
+	{
+		return false;
+	}
+	
+	function _TableSQL($tabname,$lines,$pkey,$tableoptions)
+	{
+		$sql = array();
+		
+		if (isset($tableoptions['REPLACE']) || isset ($tableoptions['DROP'])) {
+			$sql[] = sprintf($this->dropTable,$tabname);
+			if ($this->autoIncrement) {
+				$sInc = $this->_DropAutoIncrement($tabname);
+				if ($sInc) $sql[] = $sInc;
+			}
+			if ( isset ($tableoptions['DROP']) ) {
+				return $sql;
+			}
+		}
+		$s = "CREATE TABLE $tabname (\n";
+		$s .= implode(",\n", $lines);
+		if (sizeof($pkey)>0) {
+			$s .= ",\n                 PRIMARY KEY (";
+			$s .= implode(", ",$pkey).")";
+		}
+		if (isset($tableoptions['CONSTRAINTS'])) 
+			$s .= "\n".$tableoptions['CONSTRAINTS'];
+		
+		if (isset($tableoptions[$this->upperName.'_CONSTRAINTS'])) 
+			$s .= "\n".$tableoptions[$this->upperName.'_CONSTRAINTS'];
+		
+		$s .= "\n)";
+		if (isset($tableoptions[$this->upperName])) $s .= $tableoptions[$this->upperName];
+		$sql[] = $s;
+		
+		return $sql;
+	}
+	
+	/**
+		GENERATE TRIGGERS IF NEEDED
+		used when table has auto-incrementing field that is emulated using triggers
+	*/
+	function _Triggers($tabname,$taboptions)
+	{
+		return array();
+	}
+	
+	/**
+		Sanitize options, so that array elements with no keys are promoted to keys
+	*/
+	function _Options($opts)
+	{
+		if (!is_array($opts)) return array();
+		$newopts = array();
+		foreach($opts as $k => $v) {
+			if (is_numeric($k)) $newopts[strtoupper($v)] = $v;
+			else $newopts[strtoupper($k)] = $v;
+		}
+		return $newopts;
+	}
+	
+	/**
+	"Florian Buzin [ easywe ]" <florian.buzin#easywe.de>
+	
+	This function changes/adds new fields to your table. You don't
+	have to know if the col is new or not. It will check on its own.
+	*/
+	function ChangeTableSQL($tablename, $flds, $tableoptions = false)
+	{
+	global $ADODB_FETCH_MODE;
+	
+		$save = $ADODB_FETCH_MODE;
+		$ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
+		if ($this->connection->fetchMode !== false) $savem = $this->connection->SetFetchMode(false);
+		
+		// check table exists
+		$save_handler = $this->connection->raiseErrorFn;
+		$this->connection->raiseErrorFn = '';
+		$cols = $this->MetaColumns($tablename);
+		$this->connection->raiseErrorFn = $save_handler;
+		
+		if (isset($savem)) $this->connection->SetFetchMode($savem);
+		$ADODB_FETCH_MODE = $save;
+		
+		if ( empty($cols)) { 
+			return $this->CreateTableSQL($tablename, $flds, $tableoptions);
+		}
+		
+		if (is_array($flds)) {
+		// Cycle through the update fields, comparing
+		// existing fields to fields to update.
+		// if the Metatype and size is exactly the
+		// same, ignore - by Mark Newham
+			$holdflds = array();
+			foreach($flds as $k=>$v) {
+				if ( isset($cols[$k]) && is_object($cols[$k]) ) {
+					// If already not allowing nulls, then don't change
+					$obj = $cols[$k];
+					if (isset($obj->not_null) && $obj->not_null)
+						$v = str_replace('NOT NULL','',$v);
+
+					$c = $cols[$k];
+					$ml = $c->max_length;
+					$mt = $this->MetaType($c->type,$ml);
+					if ($ml == -1) $ml = '';
+					if ($mt == 'X') $ml = $v['SIZE'];
+					if (($mt != $v['TYPE']) ||  $ml != $v['SIZE']) {
+						$holdflds[$k] = $v;
+					}
+				} else {
+					$holdflds[$k] = $v;
+				}		
+			}
+			$flds = $holdflds;
+		}
+	
+
+		// already exists, alter table instead
+		list($lines,$pkey,$idxs) = $this->_GenFields($flds);
+		// genfields can return FALSE at times
+		if ($lines == null) $lines = array();
+		$alter = 'ALTER TABLE ' . $this->TableName($tablename);
+		$sql = array();
+
+		foreach ( $lines as $id => $v ) {
+			if ( isset($cols[$id]) && is_object($cols[$id]) ) {
+			
+				$flds = Lens_ParseArgs($v,',');
+				
+				//  We are trying to change the size of the field, if not allowed, simply ignore the request.
+				if ($flds && in_array(strtoupper(substr($flds[0][1],0,4)),$this->invalidResizeTypes4)) {
+					echo "<h3>$this->alterCol cannot be changed to $flds currently</h3>";
+					continue;	 
+	 			}
+				$sql[] = $alter . $this->alterCol . ' ' . $v;
+			} else {
+				$sql[] = $alter . $this->addCol . ' ' . $v;
+			}
+		}
+		
+		return $sql;
+	}
+} // class
+?>
Index: /Dev/trunk/rdfapi/util/adodb/adodb-error.inc.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/adodb-error.inc.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/adodb-error.inc.php	(revision 12)
@@ -0,0 +1,258 @@
+<?php
+/** 
+ * @version V4.94 23 Jan 2007 (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
+ * Released under both BSD license and Lesser GPL library license. 
+ * Whenever there is any discrepancy between the two licenses, 
+ * the BSD license will take precedence. 
+ *
+ * Set tabs to 4 for best viewing.
+ * 
+ * The following code is adapted from the PEAR DB error handling code.
+ * Portions (c)1997-2002 The PHP Group.
+ */
+
+
+if (!defined("DB_ERROR")) define("DB_ERROR",-1);
+
+if (!defined("DB_ERROR_SYNTAX")) {
+	define("DB_ERROR_SYNTAX",              -2);
+	define("DB_ERROR_CONSTRAINT",          -3);
+	define("DB_ERROR_NOT_FOUND",           -4);
+	define("DB_ERROR_ALREADY_EXISTS",      -5);
+	define("DB_ERROR_UNSUPPORTED",         -6);
+	define("DB_ERROR_MISMATCH",            -7);
+	define("DB_ERROR_INVALID",             -8);
+	define("DB_ERROR_NOT_CAPABLE",         -9);
+	define("DB_ERROR_TRUNCATED",          -10);
+	define("DB_ERROR_INVALID_NUMBER",     -11);
+	define("DB_ERROR_INVALID_DATE",       -12);
+	define("DB_ERROR_DIVZERO",            -13);
+	define("DB_ERROR_NODBSELECTED",       -14);
+	define("DB_ERROR_CANNOT_CREATE",      -15);
+	define("DB_ERROR_CANNOT_DELETE",      -16);
+	define("DB_ERROR_CANNOT_DROP",        -17);
+	define("DB_ERROR_NOSUCHTABLE",        -18);
+	define("DB_ERROR_NOSUCHFIELD",        -19);
+	define("DB_ERROR_NEED_MORE_DATA",     -20);
+	define("DB_ERROR_NOT_LOCKED",         -21);
+	define("DB_ERROR_VALUE_COUNT_ON_ROW", -22);
+	define("DB_ERROR_INVALID_DSN",        -23);
+	define("DB_ERROR_CONNECT_FAILED",     -24);
+	define("DB_ERROR_EXTENSION_NOT_FOUND",-25);
+	define("DB_ERROR_NOSUCHDB",           -25);
+	define("DB_ERROR_ACCESS_VIOLATION",   -26);
+}
+
+function adodb_errormsg($value)
+{
+global $ADODB_LANG,$ADODB_LANG_ARRAY;
+
+	if (empty($ADODB_LANG)) $ADODB_LANG = 'en';
+	if (isset($ADODB_LANG_ARRAY['LANG']) && $ADODB_LANG_ARRAY['LANG'] == $ADODB_LANG) ;
+	else {
+		include_once(ADODB_DIR."/lang/adodb-$ADODB_LANG.inc.php");
+    }
+	return isset($ADODB_LANG_ARRAY[$value]) ? $ADODB_LANG_ARRAY[$value] : $ADODB_LANG_ARRAY[DB_ERROR];
+}
+
+function adodb_error($provider,$dbType,$errno)
+{
+	//var_dump($errno);
+	if (is_numeric($errno) && $errno == 0) return 0;
+	switch($provider) { 
+	case 'mysql': $map = adodb_error_mysql(); break;
+	
+	case 'oracle':
+	case 'oci8': $map = adodb_error_oci8(); break;
+	
+	case 'ibase': $map = adodb_error_ibase(); break;
+	
+	case 'odbc': $map = adodb_error_odbc(); break;
+	
+	case 'mssql':
+	case 'sybase': $map = adodb_error_mssql(); break;
+	
+	case 'informix': $map = adodb_error_ifx(); break;
+	
+	case 'postgres': return adodb_error_pg($errno); break;
+	
+	case 'sqlite': return $map = adodb_error_sqlite(); break;
+	default:
+		return DB_ERROR;
+	}	
+	//print_r($map);
+	//var_dump($errno);
+	if (isset($map[$errno])) return $map[$errno];
+	return DB_ERROR;
+}
+
+//**************************************************************************************
+
+function adodb_error_pg($errormsg)
+{
+	if (is_numeric($errormsg)) return (integer) $errormsg;
+    static $error_regexps = array(
+            '/(Table does not exist\.|Relation [\"\'].*[\"\'] does not exist|sequence does not exist|class ".+" not found)$/' => DB_ERROR_NOSUCHTABLE,
+            '/Relation [\"\'].*[\"\'] already exists|Cannot insert a duplicate key into (a )?unique index.*/'      => DB_ERROR_ALREADY_EXISTS,
+            '/divide by zero$/'                     => DB_ERROR_DIVZERO,
+            '/pg_atoi: error in .*: can\'t parse /' => DB_ERROR_INVALID_NUMBER,
+            '/ttribute [\"\'].*[\"\'] not found|Relation [\"\'].*[\"\'] does not have attribute [\"\'].*[\"\']/' => DB_ERROR_NOSUCHFIELD,
+            '/parser: parse error at or near \"/'   => DB_ERROR_SYNTAX,
+            '/referential integrity violation/'     => DB_ERROR_CONSTRAINT,
+			'/Relation [\"\'].*[\"\'] already exists|Cannot insert a duplicate key into (a )?unique index.*|duplicate key violates unique constraint/'     
+			 	 => DB_ERROR_ALREADY_EXISTS
+        );
+	reset($error_regexps);
+    while (list($regexp,$code) = each($error_regexps)) {
+        if (preg_match($regexp, $errormsg)) {
+            return $code;
+        }
+    }
+    // Fall back to DB_ERROR if there was no mapping.
+    return DB_ERROR;
+}
+	
+function adodb_error_odbc()
+{
+static $MAP = array(
+            '01004' => DB_ERROR_TRUNCATED,
+            '07001' => DB_ERROR_MISMATCH,
+            '21S01' => DB_ERROR_MISMATCH,
+            '21S02' => DB_ERROR_MISMATCH,
+            '22003' => DB_ERROR_INVALID_NUMBER,
+            '22008' => DB_ERROR_INVALID_DATE,
+            '22012' => DB_ERROR_DIVZERO,
+            '23000' => DB_ERROR_CONSTRAINT,
+            '24000' => DB_ERROR_INVALID,
+            '34000' => DB_ERROR_INVALID,
+            '37000' => DB_ERROR_SYNTAX,
+            '42000' => DB_ERROR_SYNTAX,
+            'IM001' => DB_ERROR_UNSUPPORTED,
+            'S0000' => DB_ERROR_NOSUCHTABLE,
+            'S0001' => DB_ERROR_NOT_FOUND,
+            'S0002' => DB_ERROR_NOSUCHTABLE,
+            'S0011' => DB_ERROR_ALREADY_EXISTS,
+            'S0012' => DB_ERROR_NOT_FOUND,
+            'S0021' => DB_ERROR_ALREADY_EXISTS,
+            'S0022' => DB_ERROR_NOT_FOUND,
+			'S1000' => DB_ERROR_NOSUCHTABLE,
+            'S1009' => DB_ERROR_INVALID,
+            'S1090' => DB_ERROR_INVALID,
+            'S1C00' => DB_ERROR_NOT_CAPABLE
+        );
+		return $MAP;
+}
+
+function adodb_error_ibase()
+{
+static $MAP = array(
+            -104 => DB_ERROR_SYNTAX,
+            -150 => DB_ERROR_ACCESS_VIOLATION,
+            -151 => DB_ERROR_ACCESS_VIOLATION,
+            -155 => DB_ERROR_NOSUCHTABLE,
+            -157 => DB_ERROR_NOSUCHFIELD,
+            -158 => DB_ERROR_VALUE_COUNT_ON_ROW,
+            -170 => DB_ERROR_MISMATCH,
+            -171 => DB_ERROR_MISMATCH,
+            -172 => DB_ERROR_INVALID,
+            -204 => DB_ERROR_INVALID,
+            -205 => DB_ERROR_NOSUCHFIELD,
+            -206 => DB_ERROR_NOSUCHFIELD,
+            -208 => DB_ERROR_INVALID,
+            -219 => DB_ERROR_NOSUCHTABLE,
+            -297 => DB_ERROR_CONSTRAINT,
+            -530 => DB_ERROR_CONSTRAINT,
+            -803 => DB_ERROR_CONSTRAINT,
+            -551 => DB_ERROR_ACCESS_VIOLATION,
+            -552 => DB_ERROR_ACCESS_VIOLATION,
+            -922 => DB_ERROR_NOSUCHDB,
+            -923 => DB_ERROR_CONNECT_FAILED,
+            -924 => DB_ERROR_CONNECT_FAILED
+        );
+		
+		return $MAP;
+}
+
+function adodb_error_ifx()
+{
+static $MAP = array(
+            '-201'    => DB_ERROR_SYNTAX,
+            '-206'    => DB_ERROR_NOSUCHTABLE,
+            '-217'    => DB_ERROR_NOSUCHFIELD,
+            '-329'    => DB_ERROR_NODBSELECTED,
+            '-1204'   => DB_ERROR_INVALID_DATE,
+            '-1205'   => DB_ERROR_INVALID_DATE,
+            '-1206'   => DB_ERROR_INVALID_DATE,
+            '-1209'   => DB_ERROR_INVALID_DATE,
+            '-1210'   => DB_ERROR_INVALID_DATE,
+            '-1212'   => DB_ERROR_INVALID_DATE
+       );
+	   
+	   return $MAP;
+}
+
+function adodb_error_oci8()
+{
+static $MAP = array(
+			 1 => DB_ERROR_ALREADY_EXISTS,
+            900 => DB_ERROR_SYNTAX,
+            904 => DB_ERROR_NOSUCHFIELD,
+            923 => DB_ERROR_SYNTAX,
+            942 => DB_ERROR_NOSUCHTABLE,
+            955 => DB_ERROR_ALREADY_EXISTS,
+            1476 => DB_ERROR_DIVZERO,
+            1722 => DB_ERROR_INVALID_NUMBER,
+            2289 => DB_ERROR_NOSUCHTABLE,
+            2291 => DB_ERROR_CONSTRAINT,
+            2449 => DB_ERROR_CONSTRAINT
+        );
+	   
+	return $MAP;
+}
+
+function adodb_error_mssql()
+{
+static $MAP = array(
+		  208 => DB_ERROR_NOSUCHTABLE,
+          2601 => DB_ERROR_ALREADY_EXISTS
+       );
+	   
+	return $MAP;
+}
+
+function adodb_error_sqlite()
+{
+static $MAP = array(
+		  1 => DB_ERROR_SYNTAX
+       );
+	   
+	return $MAP;
+}
+
+function adodb_error_mysql()
+{
+static $MAP = array(
+           1004 => DB_ERROR_CANNOT_CREATE,
+           1005 => DB_ERROR_CANNOT_CREATE,
+           1006 => DB_ERROR_CANNOT_CREATE,
+           1007 => DB_ERROR_ALREADY_EXISTS,
+           1008 => DB_ERROR_CANNOT_DROP,
+		   1045 => DB_ERROR_ACCESS_VIOLATION,
+           1046 => DB_ERROR_NODBSELECTED,
+		   1049 => DB_ERROR_NOSUCHDB,
+           1050 => DB_ERROR_ALREADY_EXISTS,
+           1051 => DB_ERROR_NOSUCHTABLE,
+           1054 => DB_ERROR_NOSUCHFIELD,
+           1062 => DB_ERROR_ALREADY_EXISTS,
+           1064 => DB_ERROR_SYNTAX,
+           1100 => DB_ERROR_NOT_LOCKED,
+           1136 => DB_ERROR_VALUE_COUNT_ON_ROW,
+           1146 => DB_ERROR_NOSUCHTABLE,
+           1048 => DB_ERROR_CONSTRAINT,
+		    2002 => DB_ERROR_CONNECT_FAILED,
+			2005 => DB_ERROR_CONNECT_FAILED
+       );
+	   
+	return $MAP;
+}
+?>
Index: /Dev/trunk/rdfapi/util/adodb/adodb-errorhandler.inc.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/adodb-errorhandler.inc.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/adodb-errorhandler.inc.php	(revision 12)
@@ -0,0 +1,79 @@
+<?php
+/**
+ * @version V4.94 23 Jan 2007  (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
+ * Released under both BSD license and Lesser GPL library license.
+ * Whenever there is any discrepancy between the two licenses,
+ * the BSD license will take precedence.
+ *
+ * Set tabs to 4 for best viewing.
+ *
+ * Latest version is available at http://php.weblogs.com
+ *
+*/
+
+
+// added Claudio Bustos  clbustos#entelchile.net
+if (!defined('ADODB_ERROR_HANDLER_TYPE')) define('ADODB_ERROR_HANDLER_TYPE',E_USER_ERROR); 
+
+if (!defined('ADODB_ERROR_HANDLER')) define('ADODB_ERROR_HANDLER','ADODB_Error_Handler');
+
+/**
+* Default Error Handler. This will be called with the following params
+*
+* @param $dbms		the RDBMS you are connecting to
+* @param $fn		the name of the calling function (in uppercase)
+* @param $errno		the native error number from the database
+* @param $errmsg	the native error msg from the database
+* @param $p1		$fn specific parameter - see below
+* @param $p2		$fn specific parameter - see below
+* @param $thisConn	$current connection object - can be false if no connection object created
+*/
+function ADODB_Error_Handler($dbms, $fn, $errno, $errmsg, $p1, $p2, &$thisConnection)
+{
+	if (error_reporting() == 0) return; // obey @ protocol
+	switch($fn) {
+	case 'EXECUTE':
+		$sql = $p1;
+		$inputparams = $p2;
+
+		$s = "$dbms error: [$errno: $errmsg] in $fn(\"$sql\")\n";
+		break;
+
+	case 'PCONNECT':
+	case 'CONNECT':
+		$host = $p1;
+		$database = $p2;
+
+		$s = "$dbms error: [$errno: $errmsg] in $fn($host, '****', '****', $database)\n";
+		break;
+	default:
+		$s = "$dbms error: [$errno: $errmsg] in $fn($p1, $p2)\n";
+		break;
+	}
+	/*
+	* Log connection error somewhere
+	*	0 message is sent to PHP's system logger, using the Operating System's system
+	*		logging mechanism or a file, depending on what the error_log configuration
+	*		directive is set to.
+	*	1 message is sent by email to the address in the destination parameter.
+	*		This is the only message type where the fourth parameter, extra_headers is used.
+	*		This message type uses the same internal function as mail() does.
+	*	2 message is sent through the PHP debugging connection.
+	*		This option is only available if remote debugging has been enabled.
+	*		In this case, the destination parameter specifies the host name or IP address
+	*		and optionally, port number, of the socket receiving the debug information.
+	*	3 message is appended to the file destination
+	*/
+	if (defined('ADODB_ERROR_LOG_TYPE')) {
+		$t = date('Y-m-d H:i:s');
+		if (defined('ADODB_ERROR_LOG_DEST'))
+			error_log("($t) $s", ADODB_ERROR_LOG_TYPE, ADODB_ERROR_LOG_DEST);
+		else
+			error_log("($t) $s", ADODB_ERROR_LOG_TYPE);
+	}
+
+
+	//print "<p>$s</p>";
+	trigger_error($s,ADODB_ERROR_HANDLER_TYPE); 
+}
+?>
Index: /Dev/trunk/rdfapi/util/adodb/adodb-errorpear.inc.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/adodb-errorpear.inc.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/adodb-errorpear.inc.php	(revision 12)
@@ -0,0 +1,88 @@
+<?php
+/** 
+ * @version V4.94 23 Jan 2007 (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
+ * Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence. 
+ *
+ * Set tabs to 4 for best viewing.
+ * 
+ * Latest version is available at http://php.weblogs.com
+ * 
+*/
+include_once('PEAR.php');
+
+if (!defined('ADODB_ERROR_HANDLER')) define('ADODB_ERROR_HANDLER','ADODB_Error_PEAR');
+
+/*
+* Enabled the following if you want to terminate scripts when an error occurs
+*/
+//PEAR::setErrorHandling (PEAR_ERROR_DIE);
+
+/*
+* Name of the PEAR_Error derived class to call.
+*/
+if (!defined('ADODB_PEAR_ERROR_CLASS')) define('ADODB_PEAR_ERROR_CLASS','PEAR_Error');
+
+/*
+* Store the last PEAR_Error object here
+*/
+global $ADODB_Last_PEAR_Error; $ADODB_Last_PEAR_Error = false;
+
+  /**
+* Error Handler with PEAR support. This will be called with the following params
+*
+* @param $dbms		the RDBMS you are connecting to
+* @param $fn		the name of the calling function (in uppercase)
+* @param $errno		the native error number from the database 
+* @param $errmsg	the native error msg from the database
+* @param $p1		$fn specific parameter - see below
+* @param $P2		$fn specific parameter - see below
+	*/
+function ADODB_Error_PEAR($dbms, $fn, $errno, $errmsg, $p1=false, $p2=false)
+{
+global $ADODB_Last_PEAR_Error;
+	
+	if (error_reporting() == 0) return; // obey @ protocol
+	switch($fn) {
+	case 'EXECUTE':
+		$sql = $p1;
+		$inputparams = $p2;
+		
+		$s = "$dbms error: [$errno: $errmsg] in $fn(\"$sql\")";
+		break;
+		
+	case 'PCONNECT':
+	case 'CONNECT':
+		$host = $p1;
+		$database = $p2;
+		
+		$s = "$dbms error: [$errno: $errmsg] in $fn('$host', ?, ?, '$database')";
+		break;
+		
+	default:
+		$s = "$dbms error: [$errno: $errmsg] in $fn($p1, $p2)";
+		break;
+	}
+	
+	$class = ADODB_PEAR_ERROR_CLASS;
+	$ADODB_Last_PEAR_Error = new $class($s, $errno,
+		$GLOBALS['_PEAR_default_error_mode'],
+		$GLOBALS['_PEAR_default_error_options'], 
+		$errmsg);
+		
+	//print "<p>!$s</p>";
+}
+
+/**
+* Returns last PEAR_Error object. This error might be for an error that
+* occured several sql statements ago.
+*/
+function &ADODB_PEAR_Error()
+{
+global $ADODB_Last_PEAR_Error;
+
+	return $ADODB_Last_PEAR_Error;
+}
+		
+?>
Index: /Dev/trunk/rdfapi/util/adodb/adodb-exceptions.inc.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/adodb-exceptions.inc.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/adodb-exceptions.inc.php	(revision 12)
@@ -0,0 +1,82 @@
+<?php
+
+/**
+ * @version V4.94 23 Jan 2007  (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
+ * Released under both BSD license and Lesser GPL library license.
+ * Whenever there is any discrepancy between the two licenses,
+ * the BSD license will take precedence.
+ *
+ * Set tabs to 4 for best viewing.
+ *
+ * Latest version is available at http://php.weblogs.com
+ *
+ * Exception-handling code using PHP5 exceptions (try-catch-throw).
+ */
+
+
+if (!defined('ADODB_ERROR_HANDLER_TYPE')) define('ADODB_ERROR_HANDLER_TYPE',E_USER_ERROR); 
+define('ADODB_ERROR_HANDLER','adodb_throw');
+
+class ADODB_Exception extends Exception {
+var $dbms;
+var $fn;
+var $sql = '';
+var $params = '';
+var $host = '';
+var $database = '';
+	
+	function __construct($dbms, $fn, $errno, $errmsg, $p1, $p2, $thisConnection)
+	{
+		switch($fn) {
+		case 'EXECUTE':
+			$this->sql = $p1;
+			$this->params = $p2;
+			$s = "$dbms error: [$errno: $errmsg] in $fn(\"$p1\")\n";
+			break;
+	
+		case 'PCONNECT':
+		case 'CONNECT':
+			$user = $thisConnection->user;
+			$s = "$dbms error: [$errno: $errmsg] in $fn($p1, '$user', '****', $p2)\n";
+			break;
+		default:
+			$s = "$dbms error: [$errno: $errmsg] in $fn($p1, $p2)\n";
+			break;
+		}
+	
+		$this->dbms = $dbms;
+		if ($thisConnection) {
+			$this->host = $thisConnection->host;
+			$this->database = $thisConnection->database;
+		}
+		$this->fn = $fn;
+		$this->msg = $errmsg;
+				
+		if (!is_numeric($errno)) $errno = -1;
+		parent::__construct($s,$errno);
+	}
+}
+
+/**
+* Default Error Handler. This will be called with the following params
+*
+* @param $dbms		the RDBMS you are connecting to
+* @param $fn		the name of the calling function (in uppercase)
+* @param $errno		the native error number from the database
+* @param $errmsg	the native error msg from the database
+* @param $p1		$fn specific parameter - see below
+* @param $P2		$fn specific parameter - see below
+*/
+
+function adodb_throw($dbms, $fn, $errno, $errmsg, $p1, $p2, $thisConnection)
+{
+global $ADODB_EXCEPTION;
+	
+	if (error_reporting() == 0) return; // obey @ protocol
+	if (is_string($ADODB_EXCEPTION)) $errfn = $ADODB_EXCEPTION;
+	else $errfn = 'ADODB_EXCEPTION';
+	throw new $errfn($dbms, $fn, $errno, $errmsg, $p1, $p2, $thisConnection);
+}
+
+
+?>
Index: /Dev/trunk/rdfapi/util/adodb/adodb-iterator.inc.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/adodb-iterator.inc.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/adodb-iterator.inc.php	(revision 12)
@@ -0,0 +1,85 @@
+<?php
+
+/*
+  V4.94 23 Jan 2007  (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence.
+  
+  Set tabs to 4.
+  
+  Declares the ADODB Base Class for PHP5 "ADODB_BASE_RS", and supports iteration with 
+  the ADODB_Iterator class.
+  
+  		$rs = $db->Execute("select * from adoxyz");
+		foreach($rs as $k => $v) {
+			echo $k; print_r($v); echo "<br>";
+		}
+		
+		
+	Iterator code based on http://cvs.php.net/cvs.php/php-src/ext/spl/examples/cachingiterator.inc?login=2
+ */
+ 
+
+ class ADODB_Iterator implements Iterator {
+
+    private $rs;
+
+    function __construct($rs) 
+	{
+        $this->rs = $rs;
+    }
+    function rewind() 
+	{
+        $this->rs->MoveFirst();
+    }
+
+	function valid() 
+	{
+        return !$this->rs->EOF;
+    }
+	
+    function key() 
+	{
+        return $this->rs->_currentRow;
+    }
+	
+    function current() 
+	{
+        return $this->rs->fields;
+    }
+	
+    function next() 
+	{
+        $this->rs->MoveNext();
+    }
+	
+	function __call($func, $params)
+	{
+		return call_user_func_array(array($this->rs, $func), $params);
+	}
+
+	
+	function hasMore()
+	{
+		return !$this->rs->EOF;
+	}
+
+}
+
+
+class ADODB_BASE_RS implements IteratorAggregate {
+    function getIterator() {
+        return new ADODB_Iterator($this);
+    }
+	
+	/* this is experimental - i don't really know what to return... */
+	function __toString()
+	{
+		include_once(ADODB_DIR.'/toexport.inc.php');
+		return _adodb_export($this,',',',',false,true);
+	}
+} 
+
+
+?>
Index: /Dev/trunk/rdfapi/util/adodb/adodb-lib.inc.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/adodb-lib.inc.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/adodb-lib.inc.php	(revision 12)
@@ -0,0 +1,1137 @@
+<?php
+
+// security - hide paths
+if (!defined('ADODB_DIR')) die();
+
+global $ADODB_INCLUDED_LIB;
+$ADODB_INCLUDED_LIB = 1;
+
+/* 
+ @version V4.94 23 Jan 2007 (c) 2000-2007 John Lim (jlim\@natsoft.com.my). All rights reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence. See License.txt. 
+  Set tabs to 4 for best viewing.
+  
+  Less commonly used functions are placed here to reduce size of adodb.inc.php. 
+*/ 
+
+function adodb_probetypes(&$array,&$types,$probe=8)
+{
+// probe and guess the type
+	$types = array();
+	if ($probe > sizeof($array)) $max = sizeof($array);
+	else $max = $probe;
+	
+	
+	for ($j=0;$j < $max; $j++) {
+		$row =& $array[$j];
+		if (!$row) break;
+		$i = -1;
+		foreach($row as $v) {
+			$i += 1;
+
+			if (isset($types[$i]) && $types[$i]=='C') continue;
+			
+			//print " ($i ".$types[$i]. "$v) ";
+			$v = trim($v);
+			
+			if (!preg_match('/^[+-]{0,1}[0-9\.]+$/',$v)) {
+				$types[$i] = 'C'; // once C, always C
+				
+				continue;
+			}
+			if ($j == 0) { 
+			// If empty string, we presume is character
+			// test for integer for 1st row only
+			// after that it is up to testing other rows to prove
+			// that it is not an integer
+				if (strlen($v) == 0) $types[$i] = 'C';
+				if (strpos($v,'.') !== false) $types[$i] = 'N';
+				else  $types[$i] = 'I';
+				continue;
+			}
+			
+			if (strpos($v,'.') !== false) $types[$i] = 'N';
+			
+		}
+	}
+	
+}
+
+function  adodb_transpose(&$arr, &$newarr, &$hdr, &$fobjs)
+{
+	$oldX = sizeof(reset($arr));
+	$oldY = sizeof($arr);	
+	
+	if ($hdr) {
+		$startx = 1;
+		$hdr = array('Fields');
+		for ($y = 0; $y < $oldY; $y++) {
+			$hdr[] = $arr[$y][0];
+		}
+	} else
+		$startx = 0;
+
+	for ($x = $startx; $x < $oldX; $x++) {
+		if ($fobjs) {
+			$o = $fobjs[$x];
+			$newarr[] = array($o->name);
+		} else
+			$newarr[] = array();
+			
+		for ($y = 0; $y < $oldY; $y++) {
+			$newarr[$x-$startx][] = $arr[$y][$x];
+		}
+	}
+}
+
+// Force key to upper. 
+// See also http://www.php.net/manual/en/function.array-change-key-case.php
+function _array_change_key_case($an_array)
+{
+	if (is_array($an_array)) {
+		$new_array = array();
+		foreach($an_array as $key=>$value)
+			$new_array[strtoupper($key)] = $value;
+
+	   	return $new_array;
+   }
+
+	return $an_array;
+}
+
+function _adodb_replace(&$zthis, $table, $fieldArray, $keyCol, $autoQuote, $has_autoinc)
+{
+		if (count($fieldArray) == 0) return 0;
+		$first = true;
+		$uSet = '';
+		
+		if (!is_array($keyCol)) {
+			$keyCol = array($keyCol);
+		}
+		foreach($fieldArray as $k => $v) {
+			if ($autoQuote && !is_numeric($v) and strncmp($v,"'",1) !== 0 and strcasecmp($v,$zthis->null2null)!=0) {
+				$v = $zthis->qstr($v);
+				$fieldArray[$k] = $v;
+			}
+			if (in_array($k,$keyCol)) continue; // skip UPDATE if is key
+			
+			if ($first) {
+				$first = false;			
+				$uSet = "$k=$v";
+			} else
+				$uSet .= ",$k=$v";
+		}
+		 
+		$where = false;
+		foreach ($keyCol as $v) {
+			if (isset($fieldArray[$v])) {
+				if ($where) $where .= ' and '.$v.'='.$fieldArray[$v];
+				else $where = $v.'='.$fieldArray[$v];
+			}
+		}
+		
+		if ($uSet && $where) {
+			$update = "UPDATE $table SET $uSet WHERE $where";
+
+			$rs = $zthis->Execute($update);
+			
+			
+			if ($rs) {
+				if ($zthis->poorAffectedRows) {
+				/*
+				 The Select count(*) wipes out any errors that the update would have returned. 
+				http://phplens.com/lens/lensforum/msgs.php?id=5696
+				*/
+					if ($zthis->ErrorNo()<>0) return 0;
+					
+				# affected_rows == 0 if update field values identical to old values
+				# for mysql - which is silly. 
+			
+					$cnt = $zthis->GetOne("select count(*) from $table where $where");
+					if ($cnt > 0) return 1; // record already exists
+				} else {
+					if (($zthis->Affected_Rows()>0)) return 1;
+				}
+			} else
+				return 0;
+		}
+		
+	//	print "<p>Error=".$this->ErrorNo().'<p>';
+		$first = true;
+		foreach($fieldArray as $k => $v) {
+			if ($has_autoinc && in_array($k,$keyCol)) continue; // skip autoinc col
+			
+			if ($first) {
+				$first = false;			
+				$iCols = "$k";
+				$iVals = "$v";
+			} else {
+				$iCols .= ",$k";
+				$iVals .= ",$v";
+			}				
+		}
+		$insert = "INSERT INTO $table ($iCols) VALUES ($iVals)"; 
+		$rs = $zthis->Execute($insert);
+		return ($rs) ? 2 : 0;
+}
+
+// Requires $ADODB_FETCH_MODE = ADODB_FETCH_NUM
+function _adodb_getmenu(&$zthis, $name,$defstr='',$blank1stItem=true,$multiple=false,
+			$size=0, $selectAttr='',$compareFields0=true)
+{
+	$hasvalue = false;
+
+	if ($multiple or is_array($defstr)) {
+		if ($size==0) $size=5;
+		$attr = ' multiple size="'.$size.'"';
+		if (!strpos($name,'[]')) $name .= '[]';
+	} else if ($size) $attr = ' size="'.$size.'"';
+	else $attr ='';
+	
+	$s = '<select name="'.$name.'"'.$attr.' '.$selectAttr.'>';
+	if ($blank1stItem) 
+		if (is_string($blank1stItem))  {
+			$barr = explode(':',$blank1stItem);
+			if (sizeof($barr) == 1) $barr[] = '';
+			$s .= "\n<option value=\"".$barr[0]."\">".$barr[1]."</option>";
+		} else $s .= "\n<option></option>";
+
+	if ($zthis->FieldCount() > 1) $hasvalue=true;
+	else $compareFields0 = true;
+	
+	$value = '';
+    $optgroup = null;
+    $firstgroup = true;
+    $fieldsize = $zthis->FieldCount();
+	while(!$zthis->EOF) {
+		$zval = rtrim(reset($zthis->fields));
+
+		if ($blank1stItem && $zval=="") {
+			$zthis->MoveNext();
+			continue;
+		}
+
+        if ($fieldsize > 1) {
+			if (isset($zthis->fields[1]))
+				$zval2 = rtrim($zthis->fields[1]);
+			else
+				$zval2 = rtrim(next($zthis->fields));
+		}
+		$selected = ($compareFields0) ? $zval : $zval2;
+		
+        $group = '';
+		if ($fieldsize > 2) {
+            $group = rtrim($zthis->fields[2]);
+        }
+/* 
+        if ($optgroup != $group) {
+            $optgroup = $group;
+            if ($firstgroup) {
+                $firstgroup = false;
+                $s .="\n<optgroup label='". htmlspecialchars($group) ."'>";
+            } else {
+                $s .="\n</optgroup>";
+                $s .="\n<optgroup label='". htmlspecialchars($group) ."'>";
+            }
+		}
+*/
+		if ($hasvalue) 
+			$value = " value='".htmlspecialchars($zval2)."'";
+		
+		if (is_array($defstr))  {
+			
+			if (in_array($selected,$defstr)) 
+				$s .= "\n<option selected='selected'$value>".htmlspecialchars($zval).'</option>';
+			else 
+				$s .= "\n<option".$value.'>'.htmlspecialchars($zval).'</option>';
+		}
+		else {
+			if (strcasecmp($selected,$defstr)==0) 
+				$s .= "\n<option selected='selected'$value>".htmlspecialchars($zval).'</option>';
+			else
+				$s .= "\n<option".$value.'>'.htmlspecialchars($zval).'</option>';
+		}
+		$zthis->MoveNext();
+	} // while
+	
+    // closing last optgroup
+    if($optgroup != null) {
+        $s .= "\n</optgroup>";
+	}
+	return $s ."\n</select>\n";
+}
+
+// Requires $ADODB_FETCH_MODE = ADODB_FETCH_NUM
+function _adodb_getmenu_gp(&$zthis, $name,$defstr='',$blank1stItem=true,$multiple=false,
+			$size=0, $selectAttr='',$compareFields0=true)
+{
+	$hasvalue = false;
+
+	if ($multiple or is_array($defstr)) {
+		if ($size==0) $size=5;
+		$attr = ' multiple size="'.$size.'"';
+		if (!strpos($name,'[]')) $name .= '[]';
+	} else if ($size) $attr = ' size="'.$size.'"';
+	else $attr ='';
+	
+	$s = '<select name="'.$name.'"'.$attr.' '.$selectAttr.'>';
+	if ($blank1stItem) 
+		if (is_string($blank1stItem))  {
+			$barr = explode(':',$blank1stItem);
+			if (sizeof($barr) == 1) $barr[] = '';
+			$s .= "\n<option value=\"".$barr[0]."\">".$barr[1]."</option>";
+		} else $s .= "\n<option></option>";
+
+	if ($zthis->FieldCount() > 1) $hasvalue=true;
+	else $compareFields0 = true;
+	
+	$value = '';
+    $optgroup = null;
+    $firstgroup = true;
+    $fieldsize = sizeof($zthis->fields);
+	while(!$zthis->EOF) {
+		$zval = rtrim(reset($zthis->fields));
+
+		if ($blank1stItem && $zval=="") {
+			$zthis->MoveNext();
+			continue;
+		}
+
+        if ($fieldsize > 1) {
+			if (isset($zthis->fields[1]))
+				$zval2 = rtrim($zthis->fields[1]);
+			else
+				$zval2 = rtrim(next($zthis->fields));
+		}
+		$selected = ($compareFields0) ? $zval : $zval2;
+		
+        $group = '';
+		if (isset($zthis->fields[2])) {
+            $group = rtrim($zthis->fields[2]);
+        }
+ 
+        if ($optgroup != $group) {
+            $optgroup = $group;
+            if ($firstgroup) {
+                $firstgroup = false;
+                $s .="\n<optgroup label='". htmlspecialchars($group) ."'>";
+            } else {
+                $s .="\n</optgroup>";
+                $s .="\n<optgroup label='". htmlspecialchars($group) ."'>";
+            }
+		}
+	
+		if ($hasvalue) 
+			$value = " value='".htmlspecialchars($zval2)."'";
+		
+		if (is_array($defstr))  {
+			
+			if (in_array($selected,$defstr)) 
+				$s .= "\n<option selected='selected'$value>".htmlspecialchars($zval).'</option>';
+			else 
+				$s .= "\n<option".$value.'>'.htmlspecialchars($zval).'</option>';
+		}
+		else {
+			if (strcasecmp($selected,$defstr)==0) 
+				$s .= "\n<option selected='selected'$value>".htmlspecialchars($zval).'</option>';
+			else
+				$s .= "\n<option".$value.'>'.htmlspecialchars($zval).'</option>';
+		}
+		$zthis->MoveNext();
+	} // while
+	
+    // closing last optgroup
+    if($optgroup != null) {
+        $s .= "\n</optgroup>";
+	}
+	return $s ."\n</select>\n";
+}
+
+
+/*
+	Count the number of records this sql statement will return by using
+	query rewriting heuristics...
+	
+	Does not work with UNIONs, except with postgresql and oracle.
+	
+	Usage:
+	
+	$conn->Connect(...);
+	$cnt = _adodb_getcount($conn, $sql);
+	
+*/
+function _adodb_getcount(&$zthis, $sql,$inputarr=false,$secs2cache=0) 
+{
+	$qryRecs = 0;
+	
+	 if (!empty($zthis->_nestedSQL) || preg_match("/^\s*SELECT\s+DISTINCT/is", $sql) || 
+	 	preg_match('/\s+GROUP\s+BY\s+/is',$sql) || 
+		preg_match('/\s+UNION\s+/is',$sql)) {
+		// ok, has SELECT DISTINCT or GROUP BY so see if we can use a table alias
+		// but this is only supported by oracle and postgresql...
+		if ($zthis->dataProvider == 'oci8') {
+			
+			$rewritesql = preg_replace('/(\sORDER\s+BY\s[^)]*)/is','',$sql);
+			
+			// Allow Oracle hints to be used for query optimization, Chris Wrye
+			if (preg_match('#/\\*+.*?\\*\\/#', $sql, $hint)) {
+				$rewritesql = "SELECT ".$hint[0]." COUNT(*) FROM (".$rewritesql.")"; 
+			} else
+				$rewritesql = "SELECT COUNT(*) FROM (".$rewritesql.")"; 
+			
+		} else if (strncmp($zthis->databaseType,'postgres',8) == 0)  {
+			$rewritesql = preg_replace('/(\sORDER\s+BY\s[^)]*)/is','',$sql);
+			$rewritesql = "SELECT COUNT(*) FROM ($rewritesql) _ADODB_ALIAS_";
+		}
+	} else {
+		// now replace SELECT ... FROM with SELECT COUNT(*) FROM
+		$rewritesql = preg_replace(
+					'/^\s*SELECT\s.*\s+FROM\s/Uis','SELECT COUNT(*) FROM ',$sql);
+
+		
+		
+		// fix by alexander zhukov, alex#unipack.ru, because count(*) and 'order by' fails 
+		// with mssql, access and postgresql. Also a good speedup optimization - skips sorting!
+		// also see http://phplens.com/lens/lensforum/msgs.php?id=12752
+		if (preg_match('/\sORDER\s+BY\s*\(/i',$rewritesql))
+			$rewritesql = preg_replace('/(\sORDER\s+BY\s.*)/is','',$rewritesql);
+		else
+			$rewritesql = preg_replace('/(\sORDER\s+BY\s[^)]*)/is','',$rewritesql);
+	}
+	
+	
+	
+	if (isset($rewritesql) && $rewritesql != $sql) {
+		if (preg_match('/\sLIMIT\s+[0-9]+/i',$sql,$limitarr)) $rewritesql .= $limitarr[1];
+		 
+		if ($secs2cache) {
+			// we only use half the time of secs2cache because the count can quickly
+			// become inaccurate if new records are added
+			$qryRecs = $zthis->CacheGetOne($secs2cache/2,$rewritesql,$inputarr);
+			
+		} else {
+			$qryRecs = $zthis->GetOne($rewritesql,$inputarr);
+	  	}
+		if ($qryRecs !== false) return $qryRecs;
+	}
+	//--------------------------------------------
+	// query rewrite failed - so try slower way...
+	
+	
+	// strip off unneeded ORDER BY if no UNION
+	if (preg_match('/\s*UNION\s*/is', $sql)) $rewritesql = $sql;
+	else $rewritesql = preg_replace('/(\sORDER\s+BY\s.*)/is','',$sql); 
+	
+	if (preg_match('/\sLIMIT\s+[0-9]+/i',$sql,$limitarr)) $rewritesql .= $limitarr[0];
+		
+	$rstest = &$zthis->Execute($rewritesql,$inputarr);
+	if (!$rstest) $rstest = $zthis->Execute($sql,$inputarr);
+	
+	if ($rstest) {
+	  		$qryRecs = $rstest->RecordCount();
+		if ($qryRecs == -1) { 
+		global $ADODB_EXTENSION;
+		// some databases will return -1 on MoveLast() - change to MoveNext()
+			if ($ADODB_EXTENSION) {
+				while(!$rstest->EOF) {
+					adodb_movenext($rstest);
+				}
+			} else {
+				while(!$rstest->EOF) {
+					$rstest->MoveNext();
+				}
+			}
+			$qryRecs = $rstest->_currentRow;
+		}
+		$rstest->Close();
+		if ($qryRecs == -1) return 0;
+	}
+	return $qryRecs;
+}
+
+/*
+ 	Code originally from "Cornel G" <conyg@fx.ro>
+
+	This code might not work with SQL that has UNION in it	
+	
+	Also if you are using CachePageExecute(), there is a strong possibility that
+	data will get out of synch. use CachePageExecute() only with tables that
+	rarely change.
+*/
+function &_adodb_pageexecute_all_rows(&$zthis, $sql, $nrows, $page, 
+						$inputarr=false, $secs2cache=0) 
+{
+	$atfirstpage = false;
+	$atlastpage = false;
+	$lastpageno=1;
+
+	// If an invalid nrows is supplied, 
+	// we assume a default value of 10 rows per page
+	if (!isset($nrows) || $nrows <= 0) $nrows = 10;
+
+	$qryRecs = false; //count records for no offset
+	
+	$qryRecs = _adodb_getcount($zthis,$sql,$inputarr,$secs2cache);
+	$lastpageno = (int) ceil($qryRecs / $nrows);
+	$zthis->_maxRecordCount = $qryRecs;
+	
+
+
+	// ***** Here we check whether $page is the last page or 
+	// whether we are trying to retrieve 
+	// a page number greater than the last page number.
+	if ($page >= $lastpageno) {
+		$page = $lastpageno;
+		$atlastpage = true;
+	}
+	
+	// If page number <= 1, then we are at the first page
+	if (empty($page) || $page <= 1) {	
+		$page = 1;
+		$atfirstpage = true;
+	}
+	
+	// We get the data we want
+	$offset = $nrows * ($page-1);
+	if ($secs2cache > 0) 
+		$rsreturn = &$zthis->CacheSelectLimit($secs2cache, $sql, $nrows, $offset, $inputarr);
+	else 
+		$rsreturn = &$zthis->SelectLimit($sql, $nrows, $offset, $inputarr, $secs2cache);
+
+	
+	// Before returning the RecordSet, we set the pagination properties we need
+	if ($rsreturn) {
+		$rsreturn->_maxRecordCount = $qryRecs;
+		$rsreturn->rowsPerPage = $nrows;
+		$rsreturn->AbsolutePage($page);
+		$rsreturn->AtFirstPage($atfirstpage);
+		$rsreturn->AtLastPage($atlastpage);
+		$rsreturn->LastPageNo($lastpageno);
+	}
+	return $rsreturn;
+}
+
+// Iván Oliva version
+function &_adodb_pageexecute_no_last_page(&$zthis, $sql, $nrows, $page, $inputarr=false, $secs2cache=0) 
+{
+
+	$atfirstpage = false;
+	$atlastpage = false;
+	
+	if (!isset($page) || $page <= 1) {	// If page number <= 1, then we are at the first page
+		$page = 1;
+		$atfirstpage = true;
+	}
+	if ($nrows <= 0) $nrows = 10;	// If an invalid nrows is supplied, we assume a default value of 10 rows per page
+	
+	// ***** Here we check whether $page is the last page or whether we are trying to retrieve a page number greater than 
+	// the last page number.
+	$pagecounter = $page + 1;
+	$pagecounteroffset = ($pagecounter * $nrows) - $nrows;
+	if ($secs2cache>0) $rstest = &$zthis->CacheSelectLimit($secs2cache, $sql, $nrows, $pagecounteroffset, $inputarr);
+	else $rstest = &$zthis->SelectLimit($sql, $nrows, $pagecounteroffset, $inputarr, $secs2cache);
+	if ($rstest) {
+		while ($rstest && $rstest->EOF && $pagecounter>0) {
+			$atlastpage = true;
+			$pagecounter--;
+			$pagecounteroffset = $nrows * ($pagecounter - 1);
+			$rstest->Close();
+			if ($secs2cache>0) $rstest = &$zthis->CacheSelectLimit($secs2cache, $sql, $nrows, $pagecounteroffset, $inputarr);
+			else $rstest = &$zthis->SelectLimit($sql, $nrows, $pagecounteroffset, $inputarr, $secs2cache);
+		}
+		if ($rstest) $rstest->Close();
+	}
+	if ($atlastpage) {	// If we are at the last page or beyond it, we are going to retrieve it
+		$page = $pagecounter;
+		if ($page == 1) $atfirstpage = true;	// We have to do this again in case the last page is the same as the first
+			//... page, that is, the recordset has only 1 page.
+	}
+	
+	// We get the data we want
+	$offset = $nrows * ($page-1);
+	if ($secs2cache > 0) $rsreturn = &$zthis->CacheSelectLimit($secs2cache, $sql, $nrows, $offset, $inputarr);
+	else $rsreturn = &$zthis->SelectLimit($sql, $nrows, $offset, $inputarr, $secs2cache);
+	
+	// Before returning the RecordSet, we set the pagination properties we need
+	if ($rsreturn) {
+		$rsreturn->rowsPerPage = $nrows;
+		$rsreturn->AbsolutePage($page);
+		$rsreturn->AtFirstPage($atfirstpage);
+		$rsreturn->AtLastPage($atlastpage);
+	}
+	return $rsreturn;
+}
+
+function _adodb_getupdatesql(&$zthis,&$rs, $arrFields,$forceUpdate=false,$magicq=false,$force=2)
+{
+	global $ADODB_QUOTE_FIELDNAMES;
+
+		if (!$rs) {
+			printf(ADODB_BAD_RS,'GetUpdateSQL');
+			return false;
+		}
+	
+		$fieldUpdatedCount = 0;
+		$arrFields = _array_change_key_case($arrFields);
+
+		$hasnumeric = isset($rs->fields[0]);
+		$setFields = '';
+		
+		// Loop through all of the fields in the recordset
+		for ($i=0, $max=$rs->FieldCount(); $i < $max; $i++) {
+			// Get the field from the recordset
+			$field = $rs->FetchField($i);
+
+			// If the recordset field is one
+			// of the fields passed in then process.
+			$upperfname = strtoupper($field->name);
+			if (adodb_key_exists($upperfname,$arrFields,$force)) {
+				
+				// If the existing field value in the recordset
+				// is different from the value passed in then
+				// go ahead and append the field name and new value to
+				// the update query.
+				
+				if ($hasnumeric) $val = $rs->fields[$i];
+				else if (isset($rs->fields[$upperfname])) $val = $rs->fields[$upperfname];
+				else if (isset($rs->fields[$field->name])) $val =  $rs->fields[$field->name];
+				else if (isset($rs->fields[strtolower($upperfname)])) $val =  $rs->fields[strtolower($upperfname)];
+				else $val = '';
+				
+			
+				if ($forceUpdate || strcmp($val, $arrFields[$upperfname])) {
+					// Set the counter for the number of fields that will be updated.
+					$fieldUpdatedCount++;
+
+					// Based on the datatype of the field
+					// Format the value properly for the database
+					$type = $rs->MetaType($field->type);
+						
+
+					if ($type == 'null') {
+						$type = 'C';
+					}
+					
+					if ((strpos($upperfname,' ') !== false) || ($ADODB_QUOTE_FIELDNAMES))
+						$fnameq = $zthis->nameQuote.$upperfname.$zthis->nameQuote;
+					else
+						$fnameq = $upperfname;
+					
+					
+                // is_null requires php 4.0.4
+                //********************************************************//
+                if (is_null($arrFields[$upperfname])
+					|| (empty($arrFields[$upperfname]) && strlen($arrFields[$upperfname]) == 0)
+                    || $arrFields[$upperfname] === $zthis->null2null
+                    )
+                {
+                    switch ($force) {
+
+                        //case 0:
+                        //    //Ignore empty values. This is allready handled in "adodb_key_exists" function.
+                        //break;
+
+                        case 1:
+                            //Set null
+                            $setFields .= $field->name . " = null, ";
+                        break;
+							
+                        case 2:
+                            //Set empty
+                            $arrFields[$upperfname] = "";
+                            $setFields .= _adodb_column_sql($zthis, 'U', $type, $upperfname, $fnameq,$arrFields, $magicq);
+                        break;
+						default:
+                        case 3:
+                            //Set the value that was given in array, so you can give both null and empty values
+                            if (is_null($arrFields[$upperfname]) || $arrFields[$upperfname] === $zthis->null2null) {
+                                $setFields .= $field->name . " = null, ";
+                            } else {
+                                $setFields .= _adodb_column_sql($zthis, 'U', $type, $upperfname, $fnameq,$arrFields, $magicq);
+                            }
+                        break;
+                    }
+                //********************************************************//
+                } else {
+						//we do this so each driver can customize the sql for
+						//DB specific column types. 
+						//Oracle needs BLOB types to be handled with a returning clause
+						//postgres has special needs as well
+						$setFields .= _adodb_column_sql($zthis, 'U', $type, $upperfname, $fnameq,
+														  $arrFields, $magicq);
+					}
+				}
+			}
+		}
+
+		// If there were any modified fields then build the rest of the update query.
+		if ($fieldUpdatedCount > 0 || $forceUpdate) {
+					// Get the table name from the existing query.
+			if (!empty($rs->tableName)) $tableName = $rs->tableName;
+			else {
+				preg_match("/FROM\s+".ADODB_TABLE_REGEX."/is", $rs->sql, $tableName);
+				$tableName = $tableName[1];
+			}
+			// Get the full where clause excluding the word "WHERE" from
+			// the existing query.
+			preg_match('/\sWHERE\s(.*)/is', $rs->sql, $whereClause);
+			
+			$discard = false;
+			// not a good hack, improvements?
+			if ($whereClause) {
+			#var_dump($whereClause);
+				if (preg_match('/\s(ORDER\s.*)/is', $whereClause[1], $discard));
+				else if (preg_match('/\s(LIMIT\s.*)/is', $whereClause[1], $discard));
+				else if (preg_match('/\s(FOR UPDATE.*)/is', $whereClause[1], $discard));
+				else preg_match('/\s.*(\) WHERE .*)/is', $whereClause[1], $discard); # see http://sourceforge.net/tracker/index.php?func=detail&aid=1379638&group_id=42718&atid=433976
+			} else
+				$whereClause = array(false,false);
+				
+			if ($discard)
+				$whereClause[1] = substr($whereClause[1], 0, strlen($whereClause[1]) - strlen($discard[1]));
+			
+			$sql = 'UPDATE '.$tableName.' SET '.substr($setFields, 0, -2);
+			if (strlen($whereClause[1]) > 0) 
+				$sql .= ' WHERE '.$whereClause[1];
+
+			return $sql;
+
+		} else {
+			return false;
+	}
+}
+
+function adodb_key_exists($key, &$arr,$force=2)
+{
+	if ($force<=0) {
+		// the following is the old behaviour where null or empty fields are ignored
+		return (!empty($arr[$key])) || (isset($arr[$key]) && strlen($arr[$key])>0);
+	}
+
+	if (isset($arr[$key])) return true;
+	## null check below
+	if (ADODB_PHPVER >= 0x4010) return array_key_exists($key,$arr);
+	return false;
+}
+
+/**
+ * There is a special case of this function for the oci8 driver.
+ * The proper way to handle an insert w/ a blob in oracle requires
+ * a returning clause with bind variables and a descriptor blob.
+ * 
+ * 
+ */
+function _adodb_getinsertsql(&$zthis,&$rs,$arrFields,$magicq=false,$force=2)
+{
+static $cacheRS = false;
+static $cacheSig = 0;
+static $cacheCols;
+	global $ADODB_QUOTE_FIELDNAMES;
+
+	$tableName = '';
+	$values = '';
+	$fields = '';
+	$recordSet = null;
+	$arrFields = _array_change_key_case($arrFields);
+	$fieldInsertedCount = 0;
+	
+	if (is_string($rs)) {
+		//ok we have a table name
+		//try and get the column info ourself.
+		$tableName = $rs;			
+	
+		//we need an object for the recordSet
+		//because we have to call MetaType.
+		//php can't do a $rsclass::MetaType()
+		$rsclass = $zthis->rsPrefix.$zthis->databaseType;
+		$recordSet = new $rsclass(-1,$zthis->fetchMode);
+		$recordSet->connection = &$zthis;
+		
+		if (is_string($cacheRS) && $cacheRS == $rs) {
+			$columns =& $cacheCols;
+		} else {
+			$columns = $zthis->MetaColumns( $tableName );
+			$cacheRS = $tableName;
+			$cacheCols = $columns;
+		}
+	} else if (is_subclass_of($rs, 'adorecordset')) {
+		if (isset($rs->insertSig) && is_integer($cacheRS) && $cacheRS == $rs->insertSig) {
+			$columns =& $cacheCols;
+		} else {
+			for ($i=0, $max=$rs->FieldCount(); $i < $max; $i++) 
+				$columns[] = $rs->FetchField($i);
+			$cacheRS = $cacheSig;
+			$cacheCols = $columns;
+			$rs->insertSig = $cacheSig++;
+		}
+		$recordSet =& $rs;
+	
+	} else {
+		printf(ADODB_BAD_RS,'GetInsertSQL');
+		return false;
+	}
+
+	// Loop through all of the fields in the recordset
+	foreach( $columns as $field ) { 
+		$upperfname = strtoupper($field->name);
+		if (adodb_key_exists($upperfname,$arrFields,$force)) {
+			$bad = false;
+			if ((strpos($upperfname,' ') !== false) || ($ADODB_QUOTE_FIELDNAMES))
+				$fnameq = $zthis->nameQuote.$upperfname.$zthis->nameQuote;
+			else
+				$fnameq = $upperfname;
+			
+			$type = $recordSet->MetaType($field->type);
+			
+            /********************************************************/
+            if (is_null($arrFields[$upperfname])
+                || (empty($arrFields[$upperfname]) && strlen($arrFields[$upperfname]) == 0)
+                || $arrFields[$upperfname] === $zthis->null2null
+				)
+               {
+                    switch ($force) {
+
+                        case 0: // we must always set null if missing
+							$bad = true;
+							break;
+							
+                        case 1:
+                            $values  .= "null, ";
+                        break;
+		
+                        case 2:
+                            //Set empty
+                            $arrFields[$upperfname] = "";
+                            $values .= _adodb_column_sql($zthis, 'I', $type, $upperfname, $fnameq,$arrFields, $magicq);
+                        break;
+
+						default:
+                        case 3:
+                            //Set the value that was given in array, so you can give both null and empty values
+							if (is_null($arrFields[$upperfname]) || $arrFields[$upperfname] === $zthis->null2null) { 
+								$values  .= "null, ";
+							} else {
+                        		$values .= _adodb_column_sql($zthis, 'I', $type, $upperfname, $fnameq, $arrFields, $magicq);
+             				}
+              			break;
+             		} // switch
+
+            /*********************************************************/
+			} else {
+				//we do this so each driver can customize the sql for
+				//DB specific column types. 
+				//Oracle needs BLOB types to be handled with a returning clause
+				//postgres has special needs as well
+				$values .= _adodb_column_sql($zthis, 'I', $type, $upperfname, $fnameq,
+											   $arrFields, $magicq);
+			}
+			
+			if ($bad) continue;
+			// Set the counter for the number of fields that will be inserted.
+			$fieldInsertedCount++;
+			
+			
+			// Get the name of the fields to insert
+			$fields .= $fnameq . ", ";
+		}
+	}
+
+
+	// If there were any inserted fields then build the rest of the insert query.
+	if ($fieldInsertedCount <= 0)  return false;
+	
+	// Get the table name from the existing query.
+	if (!$tableName) {
+		if (!empty($rs->tableName)) $tableName = $rs->tableName;
+		else if (preg_match("/FROM\s+".ADODB_TABLE_REGEX."/is", $rs->sql, $tableName))
+			$tableName = $tableName[1];
+		else 
+			return false;
+	}		
+
+	// Strip off the comma and space on the end of both the fields
+	// and their values.
+	$fields = substr($fields, 0, -2);
+	$values = substr($values, 0, -2);
+
+	// Append the fields and their values to the insert query.
+	return 'INSERT INTO '.$tableName.' ( '.$fields.' ) VALUES ( '.$values.' )';
+}
+
+
+/**
+ * This private method is used to help construct
+ * the update/sql which is generated by GetInsertSQL and GetUpdateSQL.
+ * It handles the string construction of 1 column -> sql string based on
+ * the column type.  We want to do 'safe' handling of BLOBs
+ * 
+ * @param string the type of sql we are trying to create
+ *                'I' or 'U'. 
+ * @param string column data type from the db::MetaType() method  
+ * @param string the column name
+ * @param array the column value
+ * 
+ * @return string
+ * 
+ */
+function _adodb_column_sql_oci8(&$zthis,$action, $type, $fname, $fnameq, $arrFields, $magicq) 
+{
+    $sql = '';
+    
+    // Based on the datatype of the field
+    // Format the value properly for the database
+    switch($type) {
+    case 'B':
+        //in order to handle Blobs correctly, we need
+        //to do some magic for Oracle
+
+        //we need to create a new descriptor to handle 
+        //this properly
+        if (!empty($zthis->hasReturningInto)) {
+            if ($action == 'I') {
+                $sql = 'empty_blob(), ';
+            } else {
+                $sql = $fnameq. '=empty_blob(), ';
+            }
+            //add the variable to the returning clause array
+            //so the user can build this later in
+            //case they want to add more to it
+            $zthis->_returningArray[$fname] = ':xx'.$fname.'xx';
+        } else if (empty($arrFields[$fname])){
+            if ($action == 'I') {
+                $sql = 'empty_blob(), ';
+            } else {
+                $sql = $fnameq. '=empty_blob(), ';
+            }            
+        } else {
+            //this is to maintain compatibility
+            //with older adodb versions.
+            $sql = _adodb_column_sql($zthis, $action, $type, $fname, $fnameq, $arrFields, $magicq,false);
+        }
+        break;
+
+    case "X":
+        //we need to do some more magic here for long variables
+        //to handle these correctly in oracle.
+
+        //create a safe bind var name
+        //to avoid conflicts w/ dupes.
+       if (!empty($zthis->hasReturningInto)) {
+            if ($action == 'I') {
+                $sql = ':xx'.$fname.'xx, ';                
+            } else {
+                $sql = $fnameq.'=:xx'.$fname.'xx, ';
+            }
+            //add the variable to the returning clause array
+            //so the user can build this later in
+            //case they want to add more to it
+            $zthis->_returningArray[$fname] = ':xx'.$fname.'xx';
+        } else {
+            //this is to maintain compatibility
+            //with older adodb versions.
+            $sql = _adodb_column_sql($zthis, $action, $type, $fname, $fnameq, $arrFields, $magicq,false);
+        }            
+        break;
+        
+    default:
+        $sql = _adodb_column_sql($zthis, $action, $type, $fname, $fnameq,  $arrFields, $magicq,false);
+        break;
+    }
+    
+    return $sql;
+}    
+	
+function _adodb_column_sql(&$zthis, $action, $type, $fname, $fnameq, $arrFields, $magicq, $recurse=true) 
+{
+
+	if ($recurse) {
+		switch($zthis->dataProvider)  {
+		case 'postgres':
+			if ($type == 'L') $type = 'C';
+			break;
+		case 'oci8':
+			return _adodb_column_sql_oci8($zthis, $action, $type, $fname, $fnameq, $arrFields, $magicq);
+			
+		}
+	}
+		
+	switch($type) {
+		case "C":
+		case "X":
+		case 'B':
+			$val = $zthis->qstr($arrFields[$fname],$magicq);
+			break;
+
+		case "D":
+			$val = $zthis->DBDate($arrFields[$fname]);
+			break;
+
+		case "T":
+			$val = $zthis->DBTimeStamp($arrFields[$fname]);
+			break;
+
+		default:
+			$val = $arrFields[$fname];
+			if (empty($val)) $val = '0';
+			break;
+	}
+
+	if ($action == 'I') return $val . ", ";
+	
+	
+	return $fnameq . "=" . $val  . ", ";
+	
+}
+
+
+
+function _adodb_debug_execute(&$zthis, $sql, $inputarr)
+{
+	$ss = '';
+	if ($inputarr) {
+		foreach($inputarr as $kk=>$vv) {
+			if (is_string($vv) && strlen($vv)>64) $vv = substr($vv,0,64).'...';
+			$ss .= "($kk=>'$vv') ";
+		}
+		$ss = "[ $ss ]";
+	}
+	$sqlTxt = is_array($sql) ? $sql[0] : $sql;
+	/*str_replace(', ','##1#__^LF',is_array($sql) ? $sql[0] : $sql);
+	$sqlTxt = str_replace(',',', ',$sqlTxt);
+	$sqlTxt = str_replace('##1#__^LF', ', ' ,$sqlTxt);
+	*/
+	// check if running from browser or command-line
+	$inBrowser = isset($_SERVER['HTTP_USER_AGENT']);
+	
+	$dbt = $zthis->databaseType;
+	if (isset($zthis->dsnType)) $dbt .= '-'.$zthis->dsnType;
+	if ($inBrowser) {
+		if ($ss) {
+			$ss = '<code>'.htmlspecialchars($ss).'</code>';
+		}
+		if ($zthis->debug === -1)
+			ADOConnection::outp( "<br />\n($dbt): ".htmlspecialchars($sqlTxt)." &nbsp; $ss\n<br />\n",false);
+		else 
+			ADOConnection::outp( "<hr />\n($dbt): ".htmlspecialchars($sqlTxt)." &nbsp; $ss\n<hr />\n",false);
+	} else {
+		ADOConnection::outp("-----\n($dbt): ".$sqlTxt."\n-----\n",false);
+	}
+
+	$qID = $zthis->_query($sql,$inputarr);
+	
+	/* 
+		Alexios Fakios notes that ErrorMsg() must be called before ErrorNo() for mssql
+		because ErrorNo() calls Execute('SELECT @ERROR'), causing recursion
+	*/
+	if ($zthis->databaseType == 'mssql') { 
+	// ErrorNo is a slow function call in mssql, and not reliable in PHP 4.0.6
+		if($emsg = $zthis->ErrorMsg()) {
+			if ($err = $zthis->ErrorNo()) ADOConnection::outp($err.': '.$emsg);
+		}
+	} else if (!$qID) {
+		ADOConnection::outp($zthis->ErrorNo() .': '. $zthis->ErrorMsg());
+	}
+	
+	if ($zthis->debug === 99) _adodb_backtrace(true,9999,2);
+	return $qID;
+}
+
+# pretty print the debug_backtrace function
+function _adodb_backtrace($printOrArr=true,$levels=9999,$skippy=0)
+{
+	if (!function_exists('debug_backtrace')) return '';
+	 
+	$html =  (isset($_SERVER['HTTP_USER_AGENT']));
+	$fmt =  ($html) ? "</font><font color=#808080 size=-1> %% line %4d, file: <a href=\"file:/%s\">%s</a></font>" : "%% line %4d, file: %s";
+
+	$MAXSTRLEN = 128;
+
+	$s = ($html) ? '<pre align=left>' : '';
+	
+	if (is_array($printOrArr)) $traceArr = $printOrArr;
+	else $traceArr = debug_backtrace();
+	array_shift($traceArr);
+	array_shift($traceArr);
+	$tabs = sizeof($traceArr)-2;
+	
+	foreach ($traceArr as $arr) {
+		if ($skippy) {$skippy -= 1; continue;}
+		$levels -= 1;
+		if ($levels < 0) break;
+		
+		$args = array();
+		for ($i=0; $i < $tabs; $i++) $s .=  ($html) ? ' &nbsp; ' : "\t";
+		$tabs -= 1;
+		if ($html) $s .= '<font face="Courier New,Courier">';
+		if (isset($arr['class'])) $s .= $arr['class'].'.';
+		if (isset($arr['args']))
+		 foreach($arr['args'] as $v) {
+			if (is_null($v)) $args[] = 'null';
+			else if (is_array($v)) $args[] = 'Array['.sizeof($v).']';
+			else if (is_object($v)) $args[] = 'Object:'.get_class($v);
+			else if (is_bool($v)) $args[] = $v ? 'true' : 'false';
+			else {
+				$v = (string) @$v;
+				$str = htmlspecialchars(substr($v,0,$MAXSTRLEN));
+				if (strlen($v) > $MAXSTRLEN) $str .= '...';
+				$args[] = $str;
+			}
+		}
+		$s .= $arr['function'].'('.implode(', ',$args).')';
+		
+		
+		$s .= @sprintf($fmt, $arr['line'],$arr['file'],basename($arr['file']));
+			
+		$s .= "\n";
+	}	
+	if ($html) $s .= '</pre>';
+	if ($printOrArr) print $s;
+	
+	return $s;
+}
+/*
+function _adodb_find_from($sql) 
+{
+
+	$sql = str_replace(array("\n","\r"), ' ', $sql);
+	$charCount = strlen($sql);
+	
+	$inString = false;
+	$quote = '';
+	$parentheseCount = 0;
+	$prevChars = '';
+	$nextChars = '';
+	
+
+	for($i = 0; $i < $charCount; $i++) {
+
+    	$char = substr($sql,$i,1);
+	    $prevChars = substr($sql,0,$i);
+    	$nextChars = substr($sql,$i+1);
+
+		if((($char == "'" || $char == '"' || $char == '`') && substr($prevChars,-1,1) != '\\') && $inString === false) {
+			$quote = $char;
+			$inString = true;
+		}
+
+		elseif((($char == "'" || $char == '"' || $char == '`') && substr($prevChars,-1,1) != '\\') && $inString === true && $quote == $char) {
+			$quote = "";
+			$inString = false;
+		}
+
+		elseif($char == "(" && $inString === false)
+			$parentheseCount++;
+
+		elseif($char == ")" && $inString === false && $parentheseCount > 0)
+			$parentheseCount--;
+
+		elseif($parentheseCount <= 0 && $inString === false && $char == " " && strtoupper(substr($prevChars,-5,5)) == " FROM")
+			return $i;
+
+	}
+}
+*/
+
+?>
Index: /Dev/trunk/rdfapi/util/adodb/adodb-memcache.lib.inc.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/adodb-memcache.lib.inc.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/adodb-memcache.lib.inc.php	(revision 12)
@@ -0,0 +1,118 @@
+<?php
+
+// security - hide paths
+if (!defined('ADODB_DIR')) die();
+
+global $ADODB_INCLUDED_MEMCACHE;
+$ADODB_INCLUDED_MEMCACHE = 1;
+
+/* 
+
+  V4.90 8 June 2006  (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence. See License.txt. 
+  Set tabs to 4 for best viewing.
+  
+  Latest version is available at http://adodb.sourceforge.net
+  
+*/
+
+	function &getmemcache($key,&$err, $timeout=0, $host, $port)
+	{
+		$false = false;
+		$err = false;
+
+		if (!function_exists('memcache_pconnect')) {
+			$err = 'Memcache module PECL extension not found!';
+			return $false;
+		}
+
+		$memcache = new Memcache;
+		if (!@$memcache->pconnect($host, $port)) {
+			$err = 'Can\'t connect to memcache server on: '.$host.':'.$port;
+			return $false;
+		}
+
+		$rs = $memcache->get($key);
+		if (!$rs) {
+			$err = 'Item with such key doesn\'t exists on the memcached server.';
+			return $false;
+		}
+
+		$tdiff = intval($rs->timeCreated+$timeout - time());
+		if ($tdiff <= 2) {
+			switch($tdiff) {
+				case 2: 
+					if ((rand() & 15) == 0) {
+						$err = "Timeout 2";
+						return $false;
+					}
+					break;
+				case 1:
+					if ((rand() & 3) == 0) {
+						$err = "Timeout 1";
+						return $false;
+					}
+					break;
+				default: 
+					$err = "Timeout 0";
+					return $false;
+			}
+		}
+		return $rs;
+	}
+
+	function putmemcache($key, $rs, $host, $port, $compress, $debug=false)
+	{
+		$false = false;
+		$true = true;
+
+		if (!function_exists('memcache_pconnect')) {
+			if ($debug) ADOConnection::outp(" Memcache module PECL extension not found!<br>\n");
+			return $false;
+		}
+
+		$memcache = new Memcache;
+		if (!@$memcache->pconnect($host, $port)) {
+			if ($debug) ADOConnection::outp(" Can't connect to memcache server on: $host:$port<br>\n");
+			return $false;
+		}
+
+		$rs->timeCreated = time();
+		if (!$memcache->set($key, $rs, $compress, 0)) {
+			if ($debug) ADOConnection::outp(" Failed to save data at the memcached server!<br>\n");
+			return $false;
+		}
+		return $true;
+	}
+
+	function flushmemcache($key=false, $host, $port, $debug=false)
+	{
+		if (!function_exists('memcache_pconnect')) {
+			if ($debug) ADOConnection::outp(" Memcache module PECL extension not found!<br>\n");
+			return;
+		}
+
+		$memcache = new Memcache;
+		if (!@$memcache->pconnect($host, $port)) {
+			if ($debug) ADOConnection::outp(" Can't connect to memcache server on: $host:$port<br>\n");
+			return;
+		}
+
+		if ($key) {
+			if (!$memcache->delete($key)) {
+				if ($debug) ADOConnection::outp("CacheFlush: $key entery doesn't exist on memcached server!<br>\n");
+			} else {
+				if ($debug) ADOConnection::outp("CacheFlush: $key entery flushed from memcached server!<br>\n");
+			}
+		} else {
+			if (!$memcache->flush()) {
+				if ($debug) ADOConnection::outp("CacheFlush: Failure flushing all enteries from memcached server!<br>\n");
+			} else {
+				if ($debug) ADOConnection::outp("CacheFlush: All enteries flushed from memcached server!<br>\n");
+			}
+		}
+		return;
+	}
+?>
Index: /Dev/trunk/rdfapi/util/adodb/adodb-pager.inc.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/adodb-pager.inc.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/adodb-pager.inc.php	(revision 12)
@@ -0,0 +1,290 @@
+<?php
+
+/*
+	V4.94 23 Jan 2007  (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
+	  Released under both BSD license and Lesser GPL library license. 
+	  Whenever there is any discrepancy between the two licenses, 
+	  the BSD license will take precedence. 
+	  Set tabs to 4 for best viewing.
+
+  	This class provides recordset pagination with 
+	First/Prev/Next/Last links. 
+	
+	Feel free to modify this class for your own use as
+	it is very basic. To learn how to use it, see the 
+	example in adodb/tests/testpaging.php.
+	
+	"Pablo Costa" <pablo@cbsp.com.br> implemented Render_PageLinks().
+	
+	Please note, this class is entirely unsupported, 
+	and no free support requests except for bug reports
+	will be entertained by the author.
+
+*/
+class ADODB_Pager {
+	var $id; 	// unique id for pager (defaults to 'adodb')
+	var $db; 	// ADODB connection object
+	var $sql; 	// sql used
+	var $rs;	// recordset generated
+	var $curr_page;	// current page number before Render() called, calculated in constructor
+	var $rows;		// number of rows per page
+    var $linksPerPage=10; // number of links per page in navigation bar
+    var $showPageLinks; 
+
+	var $gridAttributes = 'width=100% border=1 bgcolor=white';
+	
+	// Localize text strings here
+	var $first = '<code>|&lt;</code>';
+	var $prev = '<code>&lt;&lt;</code>';
+	var $next = '<code>>></code>';
+	var $last = '<code>>|</code>';
+	var $moreLinks = '...';
+	var $startLinks = '...';
+	var $gridHeader = false;
+	var $htmlSpecialChars = true;
+	var $page = 'Page';
+	var $linkSelectedColor = 'red';
+	var $cache = 0;  #secs to cache with CachePageExecute()
+	
+	//----------------------------------------------
+	// constructor
+	//
+	// $db	adodb connection object
+	// $sql	sql statement
+	// $id	optional id to identify which pager, 
+	//		if you have multiple on 1 page. 
+	//		$id should be only be [a-z0-9]*
+	//
+	function ADODB_Pager(&$db,$sql,$id = 'adodb', $showPageLinks = false)
+	{
+	global $PHP_SELF;
+	
+		$curr_page = $id.'_curr_page';
+		if (empty($PHP_SELF)) $PHP_SELF = htmlspecialchars($_SERVER['PHP_SELF']); // htmlspecialchars() to prevent XSS attacks
+		
+		$this->sql = $sql;
+		$this->id = $id;
+		$this->db = $db;
+		$this->showPageLinks = $showPageLinks;
+		
+		$next_page = $id.'_next_page';	
+		
+		if (isset($_GET[$next_page])) {
+			$_SESSION[$curr_page] = (integer) $_GET[$next_page];
+		}
+		if (empty($_SESSION[$curr_page])) $_SESSION[$curr_page] = 1; ## at first page
+		
+		$this->curr_page = $_SESSION[$curr_page];
+		
+	}
+	
+	//---------------------------
+	// Display link to first page
+	function Render_First($anchor=true)
+	{
+	global $PHP_SELF;
+		if ($anchor) {
+	?>
+		<a href="<?php echo $PHP_SELF,'?',$this->id;?>_next_page=1"><?php echo $this->first;?></a> &nbsp; 
+	<?php
+		} else {
+			print "$this->first &nbsp; ";
+		}
+	}
+	
+	//--------------------------
+	// Display link to next page
+	function render_next($anchor=true)
+	{
+	global $PHP_SELF;
+	
+		if ($anchor) {
+		?>
+		<a href="<?php echo $PHP_SELF,'?',$this->id,'_next_page=',$this->rs->AbsolutePage() + 1 ?>"><?php echo $this->next;?></a> &nbsp; 
+		<?php
+		} else {
+			print "$this->next &nbsp; ";
+		}
+	}
+	
+	//------------------
+	// Link to last page
+	// 
+	// for better performance with large recordsets, you can set
+	// $this->db->pageExecuteCountRows = false, which disables
+	// last page counting.
+	function render_last($anchor=true)
+	{
+	global $PHP_SELF;
+	
+		if (!$this->db->pageExecuteCountRows) return;
+		
+		if ($anchor) {
+		?>
+			<a href="<?php echo $PHP_SELF,'?',$this->id,'_next_page=',$this->rs->LastPageNo() ?>"><?php echo $this->last;?></a> &nbsp; 
+		<?php
+		} else {
+			print "$this->last &nbsp; ";
+		}
+	}
+	
+	//---------------------------------------------------
+	// original code by "Pablo Costa" <pablo@cbsp.com.br> 
+        function render_pagelinks()
+        {
+        global $PHP_SELF;
+            $pages        = $this->rs->LastPageNo();
+            $linksperpage = $this->linksPerPage ? $this->linksPerPage : $pages;
+            for($i=1; $i <= $pages; $i+=$linksperpage)
+            {
+                if($this->rs->AbsolutePage() >= $i)
+                {
+                    $start = $i;
+                }
+            }
+			$numbers = '';
+            $end = $start+$linksperpage-1;
+			$link = $this->id . "_next_page";
+            if($end > $pages) $end = $pages;
+			
+			
+			if ($this->startLinks && $start > 1) {
+				$pos = $start - 1;
+				$numbers .= "<a href=$PHP_SELF?$link=$pos>$this->startLinks</a>  ";
+            } 
+			
+			for($i=$start; $i <= $end; $i++) {
+                if ($this->rs->AbsolutePage() == $i)
+                    $numbers .= "<font color=$this->linkSelectedColor><b>$i</b></font>  ";
+                else 
+                     $numbers .= "<a href=$PHP_SELF?$link=$i>$i</a>  ";
+            
+            }
+			if ($this->moreLinks && $end < $pages) 
+				$numbers .= "<a href=$PHP_SELF?$link=$i>$this->moreLinks</a>  ";
+            print $numbers . ' &nbsp; ';
+        }
+	// Link to previous page
+	function render_prev($anchor=true)
+	{
+	global $PHP_SELF;
+		if ($anchor) {
+	?>
+		<a href="<?php echo $PHP_SELF,'?',$this->id,'_next_page=',$this->rs->AbsolutePage() - 1 ?>"><?php echo $this->prev;?></a> &nbsp; 
+	<?php 
+		} else {
+			print "$this->prev &nbsp; ";
+		}
+	}
+	
+	//--------------------------------------------------------
+	// Simply rendering of grid. You should override this for
+	// better control over the format of the grid
+	//
+	// We use output buffering to keep code clean and readable.
+	function RenderGrid()
+	{
+	global $gSQLBlockRows; // used by rs2html to indicate how many rows to display
+		include_once(ADODB_DIR.'/tohtml.inc.php');
+		ob_start();
+		$gSQLBlockRows = $this->rows;
+		rs2html($this->rs,$this->gridAttributes,$this->gridHeader,$this->htmlSpecialChars);
+		$s = ob_get_contents();
+		ob_end_clean();
+		return $s;
+	}
+	
+	//-------------------------------------------------------
+	// Navigation bar
+	//
+	// we use output buffering to keep the code easy to read.
+	function RenderNav()
+	{
+		ob_start();
+		if (!$this->rs->AtFirstPage()) {
+			$this->Render_First();
+			$this->Render_Prev();
+		} else {
+			$this->Render_First(false);
+			$this->Render_Prev(false);
+		}
+        if ($this->showPageLinks){
+            $this->Render_PageLinks();
+        }
+		if (!$this->rs->AtLastPage()) {
+			$this->Render_Next();
+			$this->Render_Last();
+		} else {
+			$this->Render_Next(false);
+			$this->Render_Last(false);
+		}
+		$s = ob_get_contents();
+		ob_end_clean();
+		return $s;
+	}
+	
+	//-------------------
+	// This is the footer
+	function RenderPageCount()
+	{
+		if (!$this->db->pageExecuteCountRows) return '';
+		$lastPage = $this->rs->LastPageNo();
+		if ($lastPage == -1) $lastPage = 1; // check for empty rs.
+		if ($this->curr_page > $lastPage) $this->curr_page = 1;
+		return "<font size=-1>$this->page ".$this->curr_page."/".$lastPage."</font>";
+	}
+	
+	//-----------------------------------
+	// Call this class to draw everything.
+	function Render($rows=10)
+	{
+	global $ADODB_COUNTRECS;
+	
+		$this->rows = $rows;
+		
+		if ($this->db->dataProvider == 'informix') $this->db->cursorType = IFX_SCROLL;
+		
+		$savec = $ADODB_COUNTRECS;
+		if ($this->db->pageExecuteCountRows) $ADODB_COUNTRECS = true;
+		if ($this->cache)
+			$rs = &$this->db->CachePageExecute($this->cache,$this->sql,$rows,$this->curr_page);
+		else
+			$rs = &$this->db->PageExecute($this->sql,$rows,$this->curr_page);
+		$ADODB_COUNTRECS = $savec;
+		
+		$this->rs = &$rs;
+		if (!$rs) {
+			print "<h3>Query failed: $this->sql</h3>";
+			return;
+		}
+		
+		if (!$rs->EOF && (!$rs->AtFirstPage() || !$rs->AtLastPage())) 
+			$header = $this->RenderNav();
+		else
+			$header = "&nbsp;";
+		
+		$grid = $this->RenderGrid();
+		$footer = $this->RenderPageCount();
+		
+		$this->RenderLayout($header,$grid,$footer);
+		
+		$rs->Close();
+		$this->rs = false;
+	}
+	
+	//------------------------------------------------------
+	// override this to control overall layout and formating
+	function RenderLayout($header,$grid,$footer,$attributes='border=1 bgcolor=beige')
+	{
+		echo "<table ".$attributes."><tr><td>",
+				$header,
+			"</td></tr><tr><td>",
+				$grid,
+			"</td></tr><tr><td>",
+				$footer,
+			"</td></tr></table>";
+	}
+}
+
+
+?>
Index: /Dev/trunk/rdfapi/util/adodb/adodb-pear.inc.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/adodb-pear.inc.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/adodb-pear.inc.php	(revision 12)
@@ -0,0 +1,374 @@
+<?php
+/** 
+ * @version V4.94 23 Jan 2007 (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
+ * Released under both BSD license and Lesser GPL library license. 
+ * Whenever there is any discrepancy between the two licenses, 
+ * the BSD license will take precedence. 
+ *
+ * Set tabs to 4 for best viewing.
+ * 
+ * PEAR DB Emulation Layer for ADODB.
+ *
+ * The following code is modelled on PEAR DB code by Stig Bakken <ssb@fast.no>								   |
+ * and Tomas V.V.Cox <cox@idecnet.com>.	Portions (c)1997-2002 The PHP Group.
+ */
+
+ /*
+ We support:
+ 
+ DB_Common
+ ---------
+ 	query - returns PEAR_Error on error
+	limitQuery - return PEAR_Error on error
+	prepare - does not return PEAR_Error on error
+	execute - does not return PEAR_Error on error
+	setFetchMode - supports ASSOC and ORDERED
+	errorNative
+	quote
+	nextID
+	disconnect
+	
+	getOne
+	getAssoc
+	getRow
+	getCol
+	getAll
+	
+ DB_Result
+ ---------
+ 	numRows - returns -1 if not supported
+	numCols
+	fetchInto - does not support passing of fetchmode
+	fetchRows - does not support passing of fetchmode
+	free
+ */
+ 
+define('ADODB_PEAR',dirname(__FILE__));
+include_once "PEAR.php";
+include_once ADODB_PEAR."/adodb-errorpear.inc.php";
+include_once ADODB_PEAR."/adodb.inc.php";
+
+if (!defined('DB_OK')) {
+define("DB_OK",	1);
+define("DB_ERROR",-1);
+
+// autoExecute constants
+define('DB_AUTOQUERY_INSERT', 1);
+define('DB_AUTOQUERY_UPDATE', 2);
+
+/**
+ * This is a special constant that tells DB the user hasn't specified
+ * any particular get mode, so the default should be used.
+ */
+
+define('DB_FETCHMODE_DEFAULT', 0);
+
+/**
+ * Column data indexed by numbers, ordered from 0 and up
+ */
+
+define('DB_FETCHMODE_ORDERED', 1);
+
+/**
+ * Column data indexed by column names
+ */
+
+define('DB_FETCHMODE_ASSOC', 2);
+
+/* for compatibility */
+
+define('DB_GETMODE_ORDERED', DB_FETCHMODE_ORDERED);
+define('DB_GETMODE_ASSOC',   DB_FETCHMODE_ASSOC);
+
+/**
+ * these are constants for the tableInfo-function
+ * they are bitwised or'ed. so if there are more constants to be defined
+ * in the future, adjust DB_TABLEINFO_FULL accordingly
+ */
+
+define('DB_TABLEINFO_ORDER', 1);
+define('DB_TABLEINFO_ORDERTABLE', 2);
+define('DB_TABLEINFO_FULL', 3);
+}
+
+/**
+ * The main "DB" class is simply a container class with some static
+ * methods for creating DB objects as well as some utility functions
+ * common to all parts of DB.
+ *
+ */
+
+class DB
+{
+	/**
+	 * Create a new DB object for the specified database type
+	 *
+	 * @param $type string database type, for example "mysql"
+	 *
+	 * @return object a newly created DB object, or a DB error code on
+	 * error
+	 */
+
+	function &factory($type)
+	{
+		include_once(ADODB_DIR."/drivers/adodb-$type.inc.php");
+		$obj = &NewADOConnection($type);
+		if (!is_object($obj)) $obj =& new PEAR_Error('Unknown Database Driver: '.$dsninfo['phptype'],-1);
+		return $obj;
+	}
+
+	/**
+	 * Create a new DB object and connect to the specified database
+	 *
+	 * @param $dsn mixed "data source name", see the DB::parseDSN
+	 * method for a description of the dsn format.  Can also be
+	 * specified as an array of the format returned by DB::parseDSN.
+	 *
+	 * @param $options mixed if boolean (or scalar), tells whether
+	 * this connection should be persistent (for backends that support
+	 * this).  This parameter can also be an array of options, see
+	 * DB_common::setOption for more information on connection
+	 * options.
+	 *
+	 * @return object a newly created DB connection object, or a DB
+	 * error object on error
+	 *
+	 * @see DB::parseDSN
+	 * @see DB::isError
+	 */
+	function &connect($dsn, $options = false)
+	{
+		if (is_array($dsn)) {
+			$dsninfo = $dsn;
+		} else {
+			$dsninfo = DB::parseDSN($dsn);
+		}
+		switch ($dsninfo["phptype"]) {
+			case 'pgsql': 	$type = 'postgres7'; break;
+			case 'ifx':		$type = 'informix9'; break;
+			default: 		$type = $dsninfo["phptype"]; break;
+		}
+
+		if (is_array($options) && isset($options["debug"]) &&
+			$options["debug"] >= 2) {
+			// expose php errors with sufficient debug level
+			 @include_once("adodb-$type.inc.php");
+		} else {
+			 @include_once("adodb-$type.inc.php");
+		}
+
+		@$obj =& NewADOConnection($type);
+		if (!is_object($obj)) {
+			$obj =& new PEAR_Error('Unknown Database Driver: '.$dsninfo['phptype'],-1);
+			return $obj;
+		}
+		if (is_array($options)) {
+			foreach($options as $k => $v) {
+				switch(strtolower($k)) {
+				case 'persist':
+				case 'persistent': 	$persist = $v; break;
+				#ibase
+				case 'dialect': 	$obj->dialect = $v; break;
+				case 'charset':		$obj->charset = $v; break;
+				case 'buffers':		$obj->buffers = $v; break;
+				#ado
+				case 'charpage':	$obj->charPage = $v; break;
+				#mysql
+				case 'clientflags': $obj->clientFlags = $v; break;
+				}
+			}
+		} else {
+		   	$persist = false;
+		}
+
+		if (isset($dsninfo['socket'])) $dsninfo['hostspec'] .= ':'.$dsninfo['socket'];
+		else if (isset($dsninfo['port'])) $dsninfo['hostspec'] .= ':'.$dsninfo['port'];
+		
+		if($persist) $ok = $obj->PConnect($dsninfo['hostspec'], $dsninfo['username'],$dsninfo['password'],$dsninfo['database']);
+		else  $ok = $obj->Connect($dsninfo['hostspec'], $dsninfo['username'],$dsninfo['password'],$dsninfo['database']);
+		
+		if (!$ok) $obj = ADODB_PEAR_Error();
+		return $obj;
+	}
+
+	/**
+	 * Return the DB API version
+	 *
+	 * @return int the DB API version number
+	 */
+	function apiVersion()
+	{
+		return 2;
+	}
+
+	/**
+	 * Tell whether a result code from a DB method is an error
+	 *
+	 * @param $value int result code
+	 *
+	 * @return bool whether $value is an error
+	 */
+	function isError($value)
+	{
+		if (!is_object($value)) return false;
+		$class = get_class($value);
+		return $class == 'pear_error' || is_subclass_of($value, 'pear_error') || 
+				$class == 'db_error' || is_subclass_of($value, 'db_error');
+	}
+
+
+	/**
+	 * Tell whether a result code from a DB method is a warning.
+	 * Warnings differ from errors in that they are generated by DB,
+	 * and are not fatal.
+	 *
+	 * @param $value mixed result value
+	 *
+	 * @return bool whether $value is a warning
+	 */
+	function isWarning($value)
+	{
+		return false;
+		/*
+		return is_object($value) &&
+			(get_class( $value ) == "db_warning" ||
+			 is_subclass_of($value, "db_warning"));*/
+	}
+
+	/**
+	 * Parse a data source name
+	 *
+	 * @param $dsn string Data Source Name to be parsed
+	 *
+	 * @return array an associative array with the following keys:
+	 *
+	 *  phptype: Database backend used in PHP (mysql, odbc etc.)
+	 *  dbsyntax: Database used with regards to SQL syntax etc.
+	 *  protocol: Communication protocol to use (tcp, unix etc.)
+	 *  hostspec: Host specification (hostname[:port])
+	 *  database: Database to use on the DBMS server
+	 *  username: User name for login
+	 *  password: Password for login
+	 *
+	 * The format of the supplied DSN is in its fullest form:
+	 *
+	 *  phptype(dbsyntax)://username:password@protocol+hostspec/database
+	 *
+	 * Most variations are allowed:
+	 *
+	 *  phptype://username:password@protocol+hostspec:110//usr/db_file.db
+	 *  phptype://username:password@hostspec/database_name
+	 *  phptype://username:password@hostspec
+	 *  phptype://username@hostspec
+	 *  phptype://hostspec/database
+	 *  phptype://hostspec
+	 *  phptype(dbsyntax)
+	 *  phptype
+	 *
+	 * @author Tomas V.V.Cox <cox@idecnet.com>
+	 */
+	function parseDSN($dsn)
+	{
+		if (is_array($dsn)) {
+			return $dsn;
+		}
+
+		$parsed = array(
+			'phptype'  => false,
+			'dbsyntax' => false,
+			'protocol' => false,
+			'hostspec' => false,
+			'database' => false,
+			'username' => false,
+			'password' => false
+		);
+
+		// Find phptype and dbsyntax
+		if (($pos = strpos($dsn, '://')) !== false) {
+			$str = substr($dsn, 0, $pos);
+			$dsn = substr($dsn, $pos + 3);
+		} else {
+			$str = $dsn;
+			$dsn = NULL;
+		}
+
+		// Get phptype and dbsyntax
+		// $str => phptype(dbsyntax)
+		if (preg_match('|^(.+?)\((.*?)\)$|', $str, $arr)) {
+			$parsed['phptype'] = $arr[1];
+			$parsed['dbsyntax'] = (empty($arr[2])) ? $arr[1] : $arr[2];
+		} else {
+			$parsed['phptype'] = $str;
+			$parsed['dbsyntax'] = $str;
+		}
+
+		if (empty($dsn)) {
+			return $parsed;
+		}
+
+		// Get (if found): username and password
+		// $dsn => username:password@protocol+hostspec/database
+		if (($at = strpos($dsn,'@')) !== false) {
+			$str = substr($dsn, 0, $at);
+			$dsn = substr($dsn, $at + 1);
+			if (($pos = strpos($str, ':')) !== false) {
+				$parsed['username'] = urldecode(substr($str, 0, $pos));
+				$parsed['password'] = urldecode(substr($str, $pos + 1));
+			} else {
+				$parsed['username'] = urldecode($str);
+			}
+		}
+
+		// Find protocol and hostspec
+		// $dsn => protocol+hostspec/database
+		if (($pos=strpos($dsn, '/')) !== false) {
+			$str = substr($dsn, 0, $pos);
+			$dsn = substr($dsn, $pos + 1);
+		} else {
+			$str = $dsn;
+			$dsn = NULL;
+		}
+
+		// Get protocol + hostspec
+		// $str => protocol+hostspec
+		if (($pos=strpos($str, '+')) !== false) {
+			$parsed['protocol'] = substr($str, 0, $pos);
+			$parsed['hostspec'] = urldecode(substr($str, $pos + 1));
+		} else {
+			$parsed['hostspec'] = urldecode($str);
+		}
+
+		// Get dabase if any
+		// $dsn => database
+		if (!empty($dsn)) {
+			$parsed['database'] = $dsn;
+		}
+
+		return $parsed;
+	}
+
+	/**
+	 * Load a PHP database extension if it is not loaded already.
+	 *
+	 * @access public
+	 *
+	 * @param $name the base name of the extension (without the .so or
+	 * .dll suffix)
+	 *
+	 * @return bool true if the extension was already or successfully
+	 * loaded, false if it could not be loaded
+	 */
+	function assertExtension($name)
+	{
+		if (!extension_loaded($name)) {
+			$dlext = (strncmp(PHP_OS,'WIN',3) === 0) ? '.dll' : '.so';
+			@dl($name . $dlext);
+		}
+		if (!extension_loaded($name)) {
+			return false;
+		}
+		return true;
+	}
+}
+
+?>
Index: /Dev/trunk/rdfapi/util/adodb/adodb-perf.inc.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/adodb-perf.inc.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/adodb-perf.inc.php	(revision 12)
@@ -0,0 +1,1068 @@
+<?php
+/* 
+V4.94 23 Jan 2007  (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence. See License.txt. 
+  Set tabs to 4 for best viewing.
+  
+  Latest version is available at http://adodb.sourceforge.net
+  
+  Library for basic performance monitoring and tuning.
+  
+  My apologies if you see code mixed with presentation. The presentation suits
+  my needs. If you want to separate code from presentation, be my guest. Patches
+  are welcome.
+  
+*/
+
+if (!defined('ADODB_DIR')) include_once(dirname(__FILE__).'/adodb.inc.php');
+include_once(ADODB_DIR.'/tohtml.inc.php');
+
+define( 'ADODB_OPT_HIGH', 2);
+define( 'ADODB_OPT_LOW', 1);
+
+// returns in K the memory of current process, or 0 if not known
+function adodb_getmem()
+{
+	if (function_exists('memory_get_usage'))
+		return (integer) ((memory_get_usage()+512)/1024);
+	
+	$pid = getmypid();
+	
+	if ( strncmp(strtoupper(PHP_OS),'WIN',3)==0) {
+		$output = array();
+	
+		exec('tasklist /FI "PID eq ' . $pid. '" /FO LIST', $output); 
+		return substr($output[5], strpos($output[5], ':') + 1);
+	} 
+	
+	/* Hopefully UNIX */
+	exec("ps --pid $pid --no-headers -o%mem,size", $output);
+	if (sizeof($output) == 0) return 0;
+	
+	$memarr = explode(' ',$output[0]);
+	if (sizeof($memarr)>=2) return (integer) $memarr[1];
+	
+	return 0;
+}
+
+// avoids localization problems where , is used instead of .
+function adodb_round($n,$prec)
+{
+	return number_format($n, $prec, '.', '');
+}
+
+/* return microtime value as a float */
+function adodb_microtime()
+{
+	$t = microtime();
+	$t = explode(' ',$t);
+	return (float)$t[1]+ (float)$t[0];
+}
+
+/* sql code timing */
+function& adodb_log_sql(&$connx,$sql,$inputarr)
+{
+    $perf_table = adodb_perf::table();
+	$connx->fnExecute = false;
+	$t0 = microtime();
+	$rs =& $connx->Execute($sql,$inputarr);
+	$t1 = microtime();
+
+	if (!empty($connx->_logsql) && (empty($connx->_logsqlErrors) || !$rs)) {
+	global $ADODB_LOG_CONN;
+	
+		if (!empty($ADODB_LOG_CONN)) {
+			$conn = &$ADODB_LOG_CONN;
+			if ($conn->databaseType != $connx->databaseType)
+				$prefix = '/*dbx='.$connx->databaseType .'*/ ';
+			else
+				$prefix = '';
+		} else {
+			$conn =& $connx;
+			$prefix = '';
+		}
+		
+		$conn->_logsql = false; // disable logsql error simulation
+		$dbT = $conn->databaseType;
+		
+		$a0 = split(' ',$t0);
+		$a0 = (float)$a0[1]+(float)$a0[0];
+		
+		$a1 = split(' ',$t1);
+		$a1 = (float)$a1[1]+(float)$a1[0];
+		
+		$time = $a1 - $a0;
+	
+		if (!$rs) {
+			$errM = $connx->ErrorMsg();
+			$errN = $connx->ErrorNo();
+			$conn->lastInsID = 0;
+			$tracer = substr('ERROR: '.htmlspecialchars($errM),0,250);
+		} else {
+			$tracer = '';
+			$errM = '';
+			$errN = 0;
+			$dbg = $conn->debug;
+			$conn->debug = false;
+			if (!is_object($rs) || $rs->dataProvider == 'empty') 
+				$conn->_affected = $conn->affected_rows(true);
+			$conn->lastInsID = @$conn->Insert_ID();
+			$conn->debug = $dbg;
+		}
+		if (isset($_SERVER['HTTP_HOST'])) {
+			$tracer .= '<br>'.$_SERVER['HTTP_HOST'];
+			if (isset($_SERVER['PHP_SELF'])) $tracer .= $_SERVER['PHP_SELF'];
+		} else 
+			if (isset($_SERVER['PHP_SELF'])) $tracer .= '<br>'.$_SERVER['PHP_SELF'];
+		//$tracer .= (string) adodb_backtrace(false);
+		
+		$tracer = (string) substr($tracer,0,500);
+		
+		if (is_array($inputarr)) {
+			if (is_array(reset($inputarr))) $params = 'Array sizeof='.sizeof($inputarr);
+			else {
+				// Quote string parameters so we can see them in the
+				// performance stats. This helps spot disabled indexes.
+				$xar_params = $inputarr;
+				foreach ($xar_params as $xar_param_key => $xar_param) {
+					if (gettype($xar_param) == 'string')
+					$xar_params[$xar_param_key] = '"' . $xar_param . '"';
+				}
+				$params = implode(', ', $xar_params);
+				if (strlen($params) >= 3000) $params = substr($params, 0, 3000);
+			}
+		} else {
+			$params = '';
+		}
+		
+		if (is_array($sql)) $sql = $sql[0];
+		if ($prefix) $sql = $prefix.$sql;
+		$arr = array('b'=>strlen($sql).'.'.crc32($sql),
+					'c'=>substr($sql,0,3900), 'd'=>$params,'e'=>$tracer,'f'=>adodb_round($time,6));
+		//var_dump($arr);
+		$saved = $conn->debug;
+		$conn->debug = 0;
+		
+		$d = $conn->sysTimeStamp;
+		if (empty($d)) $d = date("'Y-m-d H:i:s'");
+		if ($conn->dataProvider == 'oci8' && $dbT != 'oci8po') {
+			$isql = "insert into $perf_table values($d,:b,:c,:d,:e,:f)";
+		} else if ($dbT == 'odbc_mssql' || $dbT == 'informix' || strncmp($dbT,'odbtp',4)==0) {
+			$timer = $arr['f'];
+			if ($dbT == 'informix') $sql2 = substr($sql2,0,230);
+
+			$sql1 = $conn->qstr($arr['b']);
+			$sql2 = $conn->qstr($arr['c']);
+			$params = $conn->qstr($arr['d']);
+			$tracer = $conn->qstr($arr['e']);
+			
+			$isql = "insert into $perf_table (created,sql0,sql1,params,tracer,timer) values($d,$sql1,$sql2,$params,$tracer,$timer)";
+			if ($dbT == 'informix') $isql = str_replace(chr(10),' ',$isql);
+			$arr = false;
+		} else {
+			if ($dbT == 'db2') $arr['f'] = (float) $arr['f'];
+			$isql = "insert into $perf_table (created,sql0,sql1,params,tracer,timer) values( $d,?,?,?,?,?)";
+		}
+		$ok = $conn->Execute($isql,$arr);
+		$conn->debug = $saved;
+		
+		if ($ok) {
+			$conn->_logsql = true; 
+		} else {
+			$err2 = $conn->ErrorMsg();
+			$conn->_logsql = true; // enable logsql error simulation
+			$perf =& NewPerfMonitor($conn);
+			if ($perf) {
+				if ($perf->CreateLogTable()) $ok = $conn->Execute($isql,$arr);
+			} else {
+				$ok = $conn->Execute("create table $perf_table (
+				created varchar(50),
+				sql0 varchar(250), 
+				sql1 varchar(4000),
+				params varchar(3000),
+				tracer varchar(500),
+				timer decimal(16,6))");
+			}
+			if (!$ok) {
+				ADOConnection::outp( "<p><b>LOGSQL Insert Failed</b>: $isql<br>$err2</p>");
+				$conn->_logsql = false;
+			}
+		}
+		$connx->_errorMsg = $errM;
+		$connx->_errorCode = $errN;
+	} 
+	$connx->fnExecute = 'adodb_log_sql';
+	return $rs;
+}
+
+	
+/*
+The settings data structure is an associative array that database parameter per element.
+
+Each database parameter element in the array is itself an array consisting of:
+
+0: category code, used to group related db parameters
+1: either
+	a. sql string to retrieve value, eg. "select value from v\$parameter where name='db_block_size'", 
+	b. array holding sql string and field to look for, e.g. array('show variables','table_cache'),
+	c. a string prefixed by =, then a PHP method of the class is invoked, 
+		e.g. to invoke $this->GetIndexValue(), set this array element to '=GetIndexValue',
+2: description of the database parameter
+*/
+
+class adodb_perf {
+	var $conn;
+	var $color = '#F0F0F0';
+	var $table = '<table border=1 bgcolor=white>';
+	var $titles = '<tr><td><b>Parameter</b></td><td><b>Value</b></td><td><b>Description</b></td></tr>';
+	var $warnRatio = 90;
+	var $tablesSQL = false;
+	var $cliFormat = "%32s => %s \r\n";
+	var $sql1 = 'sql1';  // used for casting sql1 to text for mssql
+	var $explain = true;
+	var $helpurl = "<a href=http://phplens.com/adodb/reference.functions.fnexecute.and.fncacheexecute.properties.html#logsql>LogSQL help</a>";
+	var $createTableSQL = false;
+	var $maxLength = 2000;
+	
+    // Sets the tablename to be used            
+    function table($newtable = false)
+    {
+        static $_table;
+
+        if (!empty($newtable))  $_table = $newtable;
+		if (empty($_table)) $_table = 'adodb_logsql';
+        return $_table;
+    }
+
+	// returns array with info to calculate CPU Load
+	function _CPULoad()
+	{
+/*
+
+cpu  524152 2662 2515228 336057010
+cpu0 264339 1408 1257951 168025827
+cpu1 259813 1254 1257277 168031181
+page 622307 25475680
+swap 24 1891
+intr 890153570 868093576 6 0 4 4 0 6 1 2 0 0 0 124 0 8098760 2 13961053 0 0 0 0 0 0 0 0 0 0 0 0 0 16 16 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
+disk_io: (3,0):(3144904,54369,610378,3090535,50936192) (3,1):(3630212,54097,633016,3576115,50951320)
+ctxt 66155838
+btime 1062315585
+processes 69293
+
+*/
+		// Algorithm is taken from
+		// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/wmisdk/wmi/example__obtaining_raw_performance_data.asp
+		if (strncmp(PHP_OS,'WIN',3)==0) {
+			if (PHP_VERSION == '5.0.0') return false;
+			if (PHP_VERSION == '5.0.1') return false;
+			if (PHP_VERSION == '5.0.2') return false;
+			if (PHP_VERSION == '5.0.3') return false;
+			if (PHP_VERSION == '4.3.10') return false; # see http://bugs.php.net/bug.php?id=31737
+			
+			@$c = new COM("WinMgmts:{impersonationLevel=impersonate}!Win32_PerfRawData_PerfOS_Processor.Name='_Total'");
+			if (!$c) return false;
+			
+			$info[0] = $c->PercentProcessorTime;
+			$info[1] = 0;
+			$info[2] = 0;
+			$info[3] = $c->TimeStamp_Sys100NS;
+			//print_r($info);
+			return $info;
+		}
+		
+		// Algorithm - Steve Blinch (BlitzAffe Online, http://www.blitzaffe.com)
+		$statfile = '/proc/stat';
+		if (!file_exists($statfile)) return false;
+		
+		$fd = fopen($statfile,"r");
+		if (!$fd) return false;
+		
+		$statinfo = explode("\n",fgets($fd, 1024));
+		fclose($fd);
+		foreach($statinfo as $line) {
+			$info = explode(" ",$line);
+			if($info[0]=="cpu") {
+				array_shift($info);  // pop off "cpu"
+				if(!$info[0]) array_shift($info); // pop off blank space (if any)
+				return $info;
+			}
+		}
+		
+		return false;
+		
+	}
+	
+	/* NOT IMPLEMENTED */
+	function MemInfo()
+	{
+		/*
+
+        total:    used:    free:  shared: buffers:  cached:
+Mem:  1055289344 917299200 137990144        0 165437440 599773184
+Swap: 2146775040 11055104 2135719936
+MemTotal:      1030556 kB
+MemFree:        134756 kB
+MemShared:           0 kB
+Buffers:        161560 kB
+Cached:         581384 kB
+SwapCached:       4332 kB
+Active:         494468 kB
+Inact_dirty:    322856 kB
+Inact_clean:     24256 kB
+Inact_target:   168316 kB
+HighTotal:      131064 kB
+HighFree:         1024 kB
+LowTotal:       899492 kB
+LowFree:        133732 kB
+SwapTotal:     2096460 kB
+SwapFree:      2085664 kB
+Committed_AS:   348732 kB
+		*/
+	}
+	
+	
+	/*
+		Remember that this is client load, not db server load!
+	*/
+	var $_lastLoad;
+	function CPULoad()
+	{
+		$info = $this->_CPULoad();
+		if (!$info) return false;
+			
+		if (empty($this->_lastLoad)) {
+			sleep(1);
+			$this->_lastLoad = $info;
+			$info = $this->_CPULoad();
+		}
+		
+		$last = $this->_lastLoad;
+		$this->_lastLoad = $info;
+		
+		$d_user = $info[0] - $last[0];
+		$d_nice = $info[1] - $last[1];
+		$d_system = $info[2] - $last[2];
+		$d_idle = $info[3] - $last[3];
+		
+		//printf("Delta - User: %f  Nice: %f  System: %f  Idle: %f<br>",$d_user,$d_nice,$d_system,$d_idle);
+
+		if (strncmp(PHP_OS,'WIN',3)==0) {
+			if ($d_idle < 1) $d_idle = 1;
+			return 100*(1-$d_user/$d_idle);
+		}else {
+			$total=$d_user+$d_nice+$d_system+$d_idle;
+			if ($total<1) $total=1;
+			return 100*($d_user+$d_nice+$d_system)/$total; 
+		}
+	}
+	
+	function Tracer($sql)
+	{
+        $perf_table = adodb_perf::table();
+		$saveE = $this->conn->fnExecute;
+		$this->conn->fnExecute = false;
+		
+		global $ADODB_FETCH_MODE;
+		$save = $ADODB_FETCH_MODE;
+		$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
+		if ($this->conn->fetchMode !== false) $savem = $this->conn->SetFetchMode(false);
+				
+		$sqlq = $this->conn->qstr($sql);
+		$arr = $this->conn->GetArray(
+"select count(*),tracer 
+	from $perf_table where sql1=$sqlq 
+	group by tracer
+	order by 1 desc");
+		$s = '';
+		if ($arr) {
+			$s .= '<h3>Scripts Affected</h3>';
+			foreach($arr as $k) {
+				$s .= sprintf("%4d",$k[0]).' &nbsp; '.strip_tags($k[1]).'<br>';
+			}
+		}
+		
+		if (isset($savem)) $this->conn->SetFetchMode($savem);
+		$ADODB_CACHE_MODE = $save;
+		$this->conn->fnExecute = $saveE;
+		return $s;
+	}
+
+	/* 
+		Explain Plan for $sql.
+		If only a snippet of the $sql is passed in, then $partial will hold the crc32 of the 
+			actual sql.
+	*/
+	function Explain($sql,$partial=false)
+	{	
+		return false;
+	}
+	
+	function InvalidSQL($numsql = 10)
+	{
+	
+		if (isset($_GET['sql'])) return;
+		$s = '<h3>Invalid SQL</h3>';
+		$saveE = $this->conn->fnExecute;
+		$this->conn->fnExecute = false;
+        $perf_table = adodb_perf::table();
+		$rs =& $this->conn->SelectLimit("select distinct count(*),sql1,tracer as error_msg from $perf_table where tracer like 'ERROR:%' group by sql1,tracer order by 1 desc",$numsql);//,$numsql);
+		$this->conn->fnExecute = $saveE;
+		if ($rs) {
+			$s .= rs2html($rs,false,false,false,false);
+		} else
+			return "<p>$this->helpurl. ".$this->conn->ErrorMsg()."</p>";
+		
+		return $s;
+	}
+
+	
+	/*
+		This script identifies the longest running SQL
+	*/	
+	function _SuspiciousSQL($numsql = 10)
+	{
+		global $ADODB_FETCH_MODE;
+		
+            $perf_table = adodb_perf::table();
+			$saveE = $this->conn->fnExecute;
+			$this->conn->fnExecute = false;
+			
+			if (isset($_GET['exps']) && isset($_GET['sql'])) {
+				$partial = !empty($_GET['part']);
+				echo "<a name=explain></a>".$this->Explain($_GET['sql'],$partial)."\n";
+			}
+			
+			if (isset($_GET['sql'])) return;
+			$sql1 = $this->sql1;
+			
+			$save = $ADODB_FETCH_MODE;
+			$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
+			if ($this->conn->fetchMode !== false) $savem = $this->conn->SetFetchMode(false);
+			//$this->conn->debug=1;
+			$rs =& $this->conn->SelectLimit(
+			"select avg(timer) as avg_timer,$sql1,count(*),max(timer) as max_timer,min(timer) as min_timer
+				from $perf_table
+				where {$this->conn->upperCase}({$this->conn->substr}(sql0,1,5)) not in ('DROP ','INSER','COMMI','CREAT')
+				and (tracer is null or tracer not like 'ERROR:%')
+				group by sql1
+				order by 1 desc",$numsql);
+			if (isset($savem)) $this->conn->SetFetchMode($savem);
+			$ADODB_FETCH_MODE = $save;
+			$this->conn->fnExecute = $saveE;
+			
+			if (!$rs) return "<p>$this->helpurl. ".$this->conn->ErrorMsg()."</p>";
+			$s = "<h3>Suspicious SQL</h3>
+<font size=1>The following SQL have high average execution times</font><br>
+<table border=1 bgcolor=white><tr><td><b>Avg Time</b><td><b>Count</b><td><b>SQL</b><td><b>Max</b><td><b>Min</b></tr>\n";
+			$max = $this->maxLength;
+			while (!$rs->EOF) {
+				$sql = $rs->fields[1];
+				$raw = urlencode($sql);
+				if (strlen($raw)>$max-100) {
+					$sql2 = substr($sql,0,$max-500);
+					$raw = urlencode($sql2).'&part='.crc32($sql);
+				}
+				$prefix = "<a target=sql".rand()." href=\"?hidem=1&exps=1&sql=".$raw."&x#explain\">";
+				$suffix = "</a>";
+				if ($this->explain == false || strlen($prefix)>$max) {
+					$suffix = ' ... <i>String too long for GET parameter: '.strlen($prefix).'</i>';
+					$prefix = '';
+				}
+				$s .= "<tr><td>".adodb_round($rs->fields[0],6)."<td align=right>".$rs->fields[2]."<td><font size=-1>".$prefix.htmlspecialchars($sql).$suffix."</font>".
+					"<td>".$rs->fields[3]."<td>".$rs->fields[4]."</tr>";
+				$rs->MoveNext();
+			}
+			return $s."</table>";
+		
+	}
+	
+	function CheckMemory()
+	{
+		return '';
+	}
+	
+	
+	function SuspiciousSQL($numsql=10)
+	{
+		return adodb_perf::_SuspiciousSQL($numsql);
+	}
+
+	function ExpensiveSQL($numsql=10)
+	{
+		return adodb_perf::_ExpensiveSQL($numsql);
+	}
+
+	
+	/*
+		This reports the percentage of load on the instance due to the most 
+		expensive few SQL statements. Tuning these statements can often 
+		make huge improvements in overall system performance. 
+	*/
+	function _ExpensiveSQL($numsql = 10)
+	{
+		global $ADODB_FETCH_MODE;
+		
+            $perf_table = adodb_perf::table();
+			$saveE = $this->conn->fnExecute;
+			$this->conn->fnExecute = false;
+			
+			if (isset($_GET['expe']) && isset($_GET['sql'])) {
+				$partial = !empty($_GET['part']);
+				echo "<a name=explain></a>".$this->Explain($_GET['sql'],$partial)."\n";
+			}
+			
+			if (isset($_GET['sql'])) return;
+			
+			$sql1 = $this->sql1;
+			$save = $ADODB_FETCH_MODE;
+			$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
+			if ($this->conn->fetchMode !== false) $savem = $this->conn->SetFetchMode(false);
+			
+			$rs =& $this->conn->SelectLimit(
+			"select sum(timer) as total,$sql1,count(*),max(timer) as max_timer,min(timer) as min_timer
+				from $perf_table
+				where {$this->conn->upperCase}({$this->conn->substr}(sql0,1,5))  not in ('DROP ','INSER','COMMI','CREAT')
+				and (tracer is null or tracer not like 'ERROR:%')
+				group by sql1
+				having count(*)>1
+				order by 1 desc",$numsql);
+			if (isset($savem)) $this->conn->SetFetchMode($savem);
+			$this->conn->fnExecute = $saveE;
+			$ADODB_FETCH_MODE = $save;
+			if (!$rs) return "<p>$this->helpurl. ".$this->conn->ErrorMsg()."</p>";
+			$s = "<h3>Expensive SQL</h3>
+<font size=1>Tuning the following SQL could reduce the server load substantially</font><br>
+<table border=1 bgcolor=white><tr><td><b>Load</b><td><b>Count</b><td><b>SQL</b><td><b>Max</b><td><b>Min</b></tr>\n";
+			$max = $this->maxLength;
+			while (!$rs->EOF) {
+				$sql = $rs->fields[1];
+				$raw = urlencode($sql);
+				if (strlen($raw)>$max-100) {
+					$sql2 = substr($sql,0,$max-500);
+					$raw = urlencode($sql2).'&part='.crc32($sql);
+				}
+				$prefix = "<a target=sqle".rand()." href=\"?hidem=1&expe=1&sql=".$raw."&x#explain\">";
+				$suffix = "</a>";
+				if($this->explain == false || strlen($prefix>$max)) {
+					$prefix = '';
+					$suffix = '';
+				}
+				$s .= "<tr><td>".adodb_round($rs->fields[0],6)."<td align=right>".$rs->fields[2]."<td><font size=-1>".$prefix.htmlspecialchars($sql).$suffix."</font>".
+					"<td>".$rs->fields[3]."<td>".$rs->fields[4]."</tr>";
+				$rs->MoveNext();
+			}
+			return $s."</table>";
+	}
+	
+	/*
+		Raw function to return parameter value from $settings.
+	*/
+	function DBParameter($param)
+	{
+		if (empty($this->settings[$param])) return false;
+		$sql = $this->settings[$param][1];
+		return $this->_DBParameter($sql);
+	}
+	
+	/*
+		Raw function returning array of poll paramters
+	*/
+	function &PollParameters()
+	{
+		$arr[0] = (float)$this->DBParameter('data cache hit ratio');
+		$arr[1] = (float)$this->DBParameter('data reads');
+		$arr[2] = (float)$this->DBParameter('data writes');
+		$arr[3] = (integer) $this->DBParameter('current connections');
+		return $arr;
+	}
+	
+	/*
+		Low-level Get Database Parameter
+	*/
+	function _DBParameter($sql)
+	{
+		$savelog = $this->conn->LogSQL(false);
+		if (is_array($sql)) {
+		global $ADODB_FETCH_MODE;
+		
+			$sql1 = $sql[0];
+			$key = $sql[1];
+			if (sizeof($sql)>2) $pos = $sql[2];
+			else $pos = 1;
+			if (sizeof($sql)>3) $coef = $sql[3];
+			else $coef = false;
+			$ret = false;
+			$save = $ADODB_FETCH_MODE;
+			$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
+			if ($this->conn->fetchMode !== false) $savem = $this->conn->SetFetchMode(false);
+			
+			$rs = $this->conn->Execute($sql1);
+			
+			if (isset($savem)) $this->conn->SetFetchMode($savem);
+			$ADODB_FETCH_MODE = $save;
+			if ($rs) {
+				while (!$rs->EOF) {
+					$keyf = reset($rs->fields);
+					if (trim($keyf) == $key) {
+						$ret = $rs->fields[$pos];
+						if ($coef) $ret *= $coef;
+						break;
+					}
+					$rs->MoveNext();
+				}
+				$rs->Close();
+			}
+			$this->conn->LogSQL($savelog);
+			return $ret;
+		} else {
+			if (strncmp($sql,'=',1) == 0) {
+				$fn = substr($sql,1);
+				return $this->$fn();
+			}
+			$sql = str_replace('$DATABASE',$this->conn->database,$sql);
+			$ret = $this->conn->GetOne($sql);
+			$this->conn->LogSQL($savelog);
+			
+			return $ret;
+		}
+	}
+	
+	/*
+		Warn if cache ratio falls below threshold. Displayed in "Description" column.
+	*/
+	function WarnCacheRatio($val)
+	{
+		if ($val < $this->warnRatio) 
+			 return '<font color=red><b>Cache ratio should be at least '.$this->warnRatio.'%</b></font>';
+		else return '';
+	}
+	
+	/***********************************************************************************************/
+	//                                    HIGH LEVEL UI FUNCTIONS
+	/***********************************************************************************************/
+
+	
+	function UI($pollsecs=5)
+	{
+	
+    $perf_table = adodb_perf::table();
+	$conn = $this->conn;
+	
+	$app = $conn->host;
+	if ($conn->host && $conn->database) $app .= ', db=';
+	$app .= $conn->database;
+	
+	if ($app) $app .= ', ';
+	$savelog = $this->conn->LogSQL(false);	
+	$info = $conn->ServerInfo();
+	if (isset($_GET['clearsql'])) {
+		$this->conn->Execute("delete from $perf_table");
+	}
+	$this->conn->LogSQL($savelog);
+	
+	// magic quotes
+	
+	if (isset($_GET['sql']) && get_magic_quotes_gpc()) {
+		$_GET['sql'] = $_GET['sql'] = str_replace(array("\\'",'\"'),array("'",'"'),$_GET['sql']);
+	}
+	
+	if (!isset($_SESSION['ADODB_PERF_SQL'])) $nsql = $_SESSION['ADODB_PERF_SQL'] = 10;
+	else  $nsql = $_SESSION['ADODB_PERF_SQL'];
+	
+	$app .= $info['description'];
+	
+	
+	if (isset($_GET['do'])) $do = $_GET['do'];
+	else if (isset($_POST['do'])) $do = $_POST['do'];
+	 else if (isset($_GET['sql'])) $do = 'viewsql';
+	 else $do = 'stats';
+	 
+	if (isset($_GET['nsql'])) {
+		if ($_GET['nsql'] > 0) $nsql = $_SESSION['ADODB_PERF_SQL'] = (integer) $_GET['nsql'];
+	}
+	echo "<title>ADOdb Performance Monitor on $app</title><body bgcolor=white>";
+	if ($do == 'viewsql') $form = "<td><form># SQL:<input type=hidden value=viewsql name=do> <input type=text size=4 name=nsql value=$nsql><input type=submit value=Go></td></form>";
+	else $form = "<td>&nbsp;</td>";
+	
+	$allowsql = !defined('ADODB_PERF_NO_RUN_SQL');
+	
+	if  (empty($_GET['hidem']))
+	echo "<table border=1 width=100% bgcolor=lightyellow><tr><td colspan=2>
+	<b><a href=http://adodb.sourceforge.net/?perf=1>ADOdb</a> Performance Monitor</b> <font size=1>for $app</font></tr><tr><td>
+	<a href=?do=stats><b>Performance Stats</b></a> &nbsp; <a href=?do=viewsql><b>View SQL</b></a>
+	 &nbsp; <a href=?do=tables><b>View Tables</b></a> &nbsp; <a href=?do=poll><b>Poll Stats</b></a>",
+	 $allowsql ? ' &nbsp; <a href=?do=dosql><b>Run SQL</b></a>' : '',
+	 "$form",
+	 "</tr></table>";
+
+	 
+	 	switch ($do) {
+		default:
+		case 'stats':
+			echo $this->HealthCheck();
+			//$this->conn->debug=1;
+			echo $this->CheckMemory();
+			break;
+		case 'poll':
+			echo "<iframe width=720 height=80% 
+				src=\"{$_SERVER['PHP_SELF']}?do=poll2&hidem=1\"></iframe>";
+			break;
+		case 'poll2':
+			echo "<pre>";
+			$this->Poll($pollsecs);
+			break;
+		
+		case 'dosql':
+			if (!$allowsql) break;
+			
+			$this->DoSQLForm();
+			break;
+		case 'viewsql':
+			if (empty($_GET['hidem']))
+				echo "&nbsp; <a href=\"?do=viewsql&clearsql=1\">Clear SQL Log</a><br>";
+			echo($this->SuspiciousSQL($nsql));
+			echo($this->ExpensiveSQL($nsql));
+			echo($this->InvalidSQL($nsql));
+			break;
+		case 'tables': 
+			echo $this->Tables(); break;
+		}
+		global $ADODB_vers;
+		echo "<p><div align=center><font size=1>$ADODB_vers Sponsored by <a href=http://phplens.com/>phpLens</a></font></div>";
+	}
+	
+	/*
+		Runs in infinite loop, returning real-time statistics
+	*/
+	function Poll($secs=5)
+	{
+		$this->conn->fnExecute = false;
+		//$this->conn->debug=1;
+		if ($secs <= 1) $secs = 1;
+		echo "Accumulating statistics, every $secs seconds...\n";flush();
+		$arro =& $this->PollParameters();
+		$cnt = 0;
+		set_time_limit(0);
+		sleep($secs);
+		while (1) {
+
+			$arr =& $this->PollParameters();
+			
+			$hits   = sprintf('%2.2f',$arr[0]);
+			$reads  = sprintf('%12.4f',($arr[1]-$arro[1])/$secs);
+			$writes = sprintf('%12.4f',($arr[2]-$arro[2])/$secs);
+			$sess = sprintf('%5d',$arr[3]);
+			
+			$load = $this->CPULoad();
+			if ($load !== false) {
+				$oslabel = 'WS-CPU%';
+				$osval = sprintf(" %2.1f  ",(float) $load);
+			}else {
+				$oslabel = '';
+				$osval = '';
+			}
+			if ($cnt % 10 == 0) echo " Time   ".$oslabel."   Hit%   Sess           Reads/s          Writes/s\n"; 
+			$cnt += 1;
+			echo date('H:i:s').'  '.$osval."$hits  $sess $reads $writes\n";
+			flush();
+			
+			if (connection_aborted()) return;
+			
+			sleep($secs);
+			$arro = $arr;
+		}
+	}
+	
+	/*
+		Returns basic health check in a command line interface
+	*/
+	function HealthCheckCLI()
+	{
+		return $this->HealthCheck(true);
+	}
+	
+		
+	/*
+		Returns basic health check as HTML
+	*/
+	function HealthCheck($cli=false)
+	{
+		$saveE = $this->conn->fnExecute;
+		$this->conn->fnExecute = false;	
+		if ($cli) $html = '';
+		else $html = $this->table.'<tr><td colspan=3><h3>'.$this->conn->databaseType.'</h3></td></tr>'.$this->titles;
+		
+		$oldc = false;
+		$bgc = '';
+		foreach($this->settings as $name => $arr) {
+			if ($arr === false) break;
+			
+			if (!is_string($name)) {
+				if ($cli) $html .= " -- $arr -- \n";
+				else $html .= "<tr bgcolor=$this->color><td colspan=3><i>$arr</i> &nbsp;</td></tr>";
+				continue;
+			}
+			
+			if (!is_array($arr)) break;
+			$category = $arr[0];
+			$how = $arr[1];
+			if (sizeof($arr)>2) $desc = $arr[2];
+			else $desc = ' &nbsp; ';
+			
+			
+			if ($category == 'HIDE') continue;
+			
+			$val = $this->_DBParameter($how);
+			
+			if ($desc && strncmp($desc,"=",1) === 0) {
+				$fn = substr($desc,1);
+				$desc = $this->$fn($val);
+			}
+			
+			if ($val === false) {
+				$m = $this->conn->ErrorMsg();
+				$val = "Error: $m"; 
+			} else {
+				if (is_numeric($val) && $val >= 256*1024) {
+					if ($val % (1024*1024) == 0) {
+						$val /= (1024*1024);
+						$val .= 'M';
+					} else if ($val % 1024 == 0) {
+						$val /= 1024;
+						$val .= 'K';
+					}
+					//$val = htmlspecialchars($val);
+				}
+			}
+			if ($category != $oldc) {
+				$oldc = $category;
+				//$bgc = ($bgc == ' bgcolor='.$this->color) ? ' bgcolor=white' : ' bgcolor='.$this->color;
+			}
+			if (strlen($desc)==0) $desc = '&nbsp;';
+			if (strlen($val)==0) $val = '&nbsp;';
+			if ($cli) {
+				$html  .= str_replace('&nbsp;','',sprintf($this->cliFormat,strip_tags($name),strip_tags($val),strip_tags($desc)));
+				
+			}else {
+				$html .= "<tr$bgc><td>".$name.'</td><td>'.$val.'</td><td>'.$desc."</td></tr>\n";
+			}
+		}
+		
+		if (!$cli) $html .= "</table>\n";
+		$this->conn->fnExecute = $saveE;
+			
+		return $html;	
+	}
+	
+	function Tables($orderby='1')
+	{
+		if (!$this->tablesSQL) return false;
+		
+		$savelog = $this->conn->LogSQL(false);
+		$rs = $this->conn->Execute($this->tablesSQL.' order by '.$orderby);
+		$this->conn->LogSQL($savelog);
+		$html = rs2html($rs,false,false,false,false);
+		return $html;
+	}
+	
+
+	function CreateLogTable()
+	{
+		if (!$this->createTableSQL) return false;
+		
+		$table = $this->table();
+		$sql = str_replace('adodb_logsql',$table,$this->createTableSQL);
+		$savelog = $this->conn->LogSQL(false);
+		$ok = $this->conn->Execute($sql);
+		$this->conn->LogSQL($savelog);
+		return ($ok) ? true : false;
+	}
+	
+	function DoSQLForm()
+	{
+	
+		
+		$PHP_SELF = $_SERVER['PHP_SELF'];
+		$sql = isset($_REQUEST['sql']) ? $_REQUEST['sql'] : '';
+
+		if (isset($_SESSION['phplens_sqlrows'])) $rows = $_SESSION['phplens_sqlrows'];
+		else $rows = 3;
+		
+		if (isset($_REQUEST['SMALLER'])) {
+			$rows /= 2;
+			if ($rows < 3) $rows = 3;
+			$_SESSION['phplens_sqlrows'] = $rows;
+		}
+		if (isset($_REQUEST['BIGGER'])) {
+			$rows *= 2;
+			$_SESSION['phplens_sqlrows'] = $rows;
+		}
+		
+?>
+
+<form method="POST" action="<?php echo $PHP_SELF ?>">
+<table><tr>
+<td> Form size: <input type="submit" value=" &lt; " name="SMALLER"><input type="submit" value=" &gt; &gt; " name="BIGGER">
+</td>
+<td align=right>
+<input type="submit" value=" Run SQL Below " name="RUN"><input type=hidden name=do value=dosql>
+</td></tr>
+  <tr>
+  <td colspan=2><textarea rows=<?php print $rows; ?> name="sql" cols="80"><?php print htmlspecialchars($sql) ?></textarea>
+  </td>
+  </tr>
+ </table>
+</form>
+
+<?php
+		if (!isset($_REQUEST['sql'])) return;
+		
+		$sql = $this->undomq(trim($sql));
+		if (substr($sql,strlen($sql)-1) === ';') {
+			$print = true;
+			$sqla = $this->SplitSQL($sql);
+		} else  {
+			$print = false;
+			$sqla = array($sql);
+		}
+		foreach($sqla as $sqls) {
+
+			if (!$sqls) continue;
+			
+			if ($print) {
+				print "<p>".htmlspecialchars($sqls)."</p>";
+				flush();
+			}
+			$savelog = $this->conn->LogSQL(false);
+			$rs = $this->conn->Execute($sqls);
+			$this->conn->LogSQL($savelog);
+			if ($rs && is_object($rs) && !$rs->EOF) {
+				rs2html($rs);
+				while ($rs->NextRecordSet()) {
+					print "<table width=98% bgcolor=#C0C0FF><tr><td>&nbsp;</td></tr></table>";
+					rs2html($rs);
+				}
+			} else {
+				$e1 = (integer) $this->conn->ErrorNo();
+				$e2 = $this->conn->ErrorMsg();
+				if (($e1) || ($e2)) {
+					if (empty($e1)) $e1 = '-1'; // postgresql fix
+					print ' &nbsp; '.$e1.': '.$e2;
+				} else {
+					print "<p>No Recordset returned<br></p>";
+				}
+			}
+		} // foreach
+	}
+	
+	function SplitSQL($sql)
+	{
+		$arr = explode(';',$sql);
+		return $arr;
+	}
+	
+	function undomq($m) 
+	{
+	if (get_magic_quotes_gpc()) {
+		// undo the damage
+		$m = str_replace('\\\\','\\',$m);
+		$m = str_replace('\"','"',$m);
+		$m = str_replace('\\\'','\'',$m);
+	}
+	return $m;
+}
+
+    
+   /************************************************************************/
+   
+    /** 
+     * Reorganise multiple table-indices/statistics/..
+     * OptimizeMode could be given by last Parameter
+     * 
+     * @example
+     *      <pre>
+     *          optimizeTables( 'tableA');
+     *      </pre>
+     *      <pre>
+     *          optimizeTables( 'tableA', 'tableB', 'tableC');
+     *      </pre>
+     *      <pre>
+     *          optimizeTables( 'tableA', 'tableB', ADODB_OPT_LOW);
+     *      </pre>
+     * 
+     * @param string table name of the table to optimize
+     * @param int mode optimization-mode
+     *      <code>ADODB_OPT_HIGH</code> for full optimization 
+     *      <code>ADODB_OPT_LOW</code> for CPU-less optimization
+     *      Default is LOW <code>ADODB_OPT_LOW</code> 
+     * @author Markus Staab
+     * @return Returns <code>true</code> on success and <code>false</code> on error
+     */
+    function OptimizeTables()
+    {
+        $args = func_get_args();
+        $numArgs = func_num_args();
+        
+        if ( $numArgs == 0) return false;
+        
+        $mode = ADODB_OPT_LOW; 
+        $lastArg = $args[ $numArgs - 1];
+        if ( !is_string($lastArg)) {
+            $mode = $lastArg;
+            unset( $args[ $numArgs - 1]);
+        }
+        
+        foreach( $args as $table) {
+            $this->optimizeTable( $table, $mode);
+        }
+	}
+
+    /** 
+     * Reorganise the table-indices/statistics/.. depending on the given mode.
+     * Default Implementation throws an error.
+     * 
+     * @param string table name of the table to optimize
+     * @param int mode optimization-mode
+     *      <code>ADODB_OPT_HIGH</code> for full optimization 
+     *      <code>ADODB_OPT_LOW</code> for CPU-less optimization
+     *      Default is LOW <code>ADODB_OPT_LOW</code> 
+     * @author Markus Staab
+     * @return Returns <code>true</code> on success and <code>false</code> on error
+     */
+    function OptimizeTable( $table, $mode = ADODB_OPT_LOW) 
+    {
+        ADOConnection::outp( sprintf( "<p>%s: '%s' not implemented for driver '%s'</p>", __CLASS__, __FUNCTION__, $this->conn->databaseType));
+        return false;
+    }
+    
+    /** 
+     * Reorganise current database.
+     * Default implementation loops over all <code>MetaTables()</code> and 
+     * optimize each using <code>optmizeTable()</code>
+     * 
+     * @author Markus Staab
+     * @return Returns <code>true</code> on success and <code>false</code> on error
+     */
+    function optimizeDatabase() 
+    {
+        $conn = $this->conn;
+        if ( !$conn) return false;
+        
+        $tables = $conn->MetaTables( 'TABLES');
+        if ( !$tables ) return false;
+
+        foreach( $tables as $table) {
+            if ( !$this->optimizeTable( $table)) {
+                return false;
+            }
+        }
+      
+        return true;
+    }
+    // end hack 
+}
+
+?>
Index: /Dev/trunk/rdfapi/util/adodb/adodb-php4.inc.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/adodb-php4.inc.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/adodb-php4.inc.php	(revision 12)
@@ -0,0 +1,16 @@
+<?php
+
+/*
+  V4.94 23 Jan 2007  (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence.
+  
+  Set tabs to 4.
+*/
+
+
+class ADODB_BASE_RS {
+}
+
+?>
Index: /Dev/trunk/rdfapi/util/adodb/adodb-time.inc.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/adodb-time.inc.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/adodb-time.inc.php	(revision 12)
@@ -0,0 +1,1337 @@
+<?php
+/**
+ADOdb Date Library, part of the ADOdb abstraction library
+Download: http://phplens.com/phpeverywhere/
+
+PHP native date functions use integer timestamps for computations.
+Because of this, dates are restricted to the years 1901-2038 on Unix 
+and 1970-2038 on Windows due to integer overflow for dates beyond 
+those years. This library overcomes these limitations by replacing the 
+native function's signed integers (normally 32-bits) with PHP floating 
+point numbers (normally 64-bits).
+
+Dates from 100 A.D. to 3000 A.D. and later
+have been tested. The minimum is 100 A.D. as <100 will invoke the
+2 => 4 digit year conversion. The maximum is billions of years in the 
+future, but this is a theoretical limit as the computation of that year 
+would take too long with the current implementation of adodb_mktime().
+
+This library replaces native functions as follows:
+
+<pre>	
+	getdate()  with  adodb_getdate()
+	date()     with  adodb_date() 
+	gmdate()   with  adodb_gmdate()
+	mktime()   with  adodb_mktime()
+	gmmktime() with  adodb_gmmktime()
+	strftime() with  adodb_strftime()
+	strftime() with  adodb_gmstrftime()
+</pre>
+	
+The parameters are identical, except that adodb_date() accepts a subset
+of date()'s field formats. Mktime() will convert from local time to GMT, 
+and date() will convert from GMT to local time, but daylight savings is 
+not handled currently.
+
+This library is independant of the rest of ADOdb, and can be used
+as standalone code.
+
+PERFORMANCE
+
+For high speed, this library uses the native date functions where
+possible, and only switches to PHP code when the dates fall outside 
+the 32-bit signed integer range.
+
+GREGORIAN CORRECTION
+
+Pope Gregory shortened October of A.D. 1582 by ten days. Thursday, 
+October 4, 1582 (Julian) was followed immediately by Friday, October 15, 
+1582 (Gregorian). 
+
+Since 0.06, we handle this correctly, so:
+
+adodb_mktime(0,0,0,10,15,1582) - adodb_mktime(0,0,0,10,4,1582) 
+	== 24 * 3600 (1 day)
+
+=============================================================================
+
+COPYRIGHT
+
+(c) 2003-2005 John Lim and released under BSD-style license except for code by 
+jackbbs, which includes adodb_mktime, adodb_get_gmt_diff, adodb_is_leap_year
+and originally found at http://www.php.net/manual/en/function.mktime.php
+
+=============================================================================
+
+BUG REPORTS
+
+These should be posted to the ADOdb forums at
+
+	http://phplens.com/lens/lensforum/topics.php?id=4
+
+=============================================================================
+
+FUNCTION DESCRIPTIONS
+
+
+** FUNCTION adodb_getdate($date=false)
+
+Returns an array containing date information, as getdate(), but supports
+dates greater than 1901 to 2038. The local date/time format is derived from a 
+heuristic the first time adodb_getdate is called. 
+	 
+	 
+** FUNCTION adodb_date($fmt, $timestamp = false)
+
+Convert a timestamp to a formatted local date. If $timestamp is not defined, the
+current timestamp is used. Unlike the function date(), it supports dates
+outside the 1901 to 2038 range.
+
+The format fields that adodb_date supports:
+
+<pre>
+	a - "am" or "pm" 
+	A - "AM" or "PM" 
+	d - day of the month, 2 digits with leading zeros; i.e. "01" to "31" 
+	D - day of the week, textual, 3 letters; e.g. "Fri" 
+	F - month, textual, long; e.g. "January" 
+	g - hour, 12-hour format without leading zeros; i.e. "1" to "12" 
+	G - hour, 24-hour format without leading zeros; i.e. "0" to "23" 
+	h - hour, 12-hour format; i.e. "01" to "12" 
+	H - hour, 24-hour format; i.e. "00" to "23" 
+	i - minutes; i.e. "00" to "59" 
+	j - day of the month without leading zeros; i.e. "1" to "31" 
+	l (lowercase 'L') - day of the week, textual, long; e.g. "Friday"  
+	L - boolean for whether it is a leap year; i.e. "0" or "1" 
+	m - month; i.e. "01" to "12" 
+	M - month, textual, 3 letters; e.g. "Jan" 
+	n - month without leading zeros; i.e. "1" to "12" 
+	O - Difference to Greenwich time in hours; e.g. "+0200" 
+	Q - Quarter, as in 1, 2, 3, 4 
+	r - RFC 2822 formatted date; e.g. "Thu, 21 Dec 2000 16:01:07 +0200" 
+	s - seconds; i.e. "00" to "59" 
+	S - English ordinal suffix for the day of the month, 2 characters; 
+	   			i.e. "st", "nd", "rd" or "th" 
+	t - number of days in the given month; i.e. "28" to "31"
+	T - Timezone setting of this machine; e.g. "EST" or "MDT" 
+	U - seconds since the Unix Epoch (January 1 1970 00:00:00 GMT)  
+	w - day of the week, numeric, i.e. "0" (Sunday) to "6" (Saturday) 
+	Y - year, 4 digits; e.g. "1999" 
+	y - year, 2 digits; e.g. "99" 
+	z - day of the year; i.e. "0" to "365" 
+	Z - timezone offset in seconds (i.e. "-43200" to "43200"). 
+	   			The offset for timezones west of UTC is always negative, 
+				and for those east of UTC is always positive. 
+</pre>
+
+Unsupported:
+<pre>
+	B - Swatch Internet time 
+	I (capital i) - "1" if Daylight Savings Time, "0" otherwise.
+	W - ISO-8601 week number of year, weeks starting on Monday 
+
+</pre>
+
+
+** FUNCTION adodb_date2($fmt, $isoDateString = false)
+Same as adodb_date, but 2nd parameter accepts iso date, eg.
+
+  adodb_date2('d-M-Y H:i','2003-12-25 13:01:34');
+
+  
+** FUNCTION adodb_gmdate($fmt, $timestamp = false)
+
+Convert a timestamp to a formatted GMT date. If $timestamp is not defined, the
+current timestamp is used. Unlike the function date(), it supports dates
+outside the 1901 to 2038 range.
+
+
+** FUNCTION adodb_mktime($hr, $min, $sec[, $month, $day, $year])
+
+Converts a local date to a unix timestamp.  Unlike the function mktime(), it supports
+dates outside the 1901 to 2038 range. All parameters are optional.
+
+
+** FUNCTION adodb_gmmktime($hr, $min, $sec [, $month, $day, $year])
+
+Converts a gmt date to a unix timestamp.  Unlike the function gmmktime(), it supports
+dates outside the 1901 to 2038 range. Differs from gmmktime() in that all parameters
+are currently compulsory.
+
+** FUNCTION adodb_gmstrftime($fmt, $timestamp = false)
+Convert a timestamp to a formatted GMT date.
+
+** FUNCTION adodb_strftime($fmt, $timestamp = false)
+
+Convert a timestamp to a formatted local date. Internally converts $fmt into 
+adodb_date format, then echo result.
+
+For best results, you can define the local date format yourself. Define a global
+variable $ADODB_DATE_LOCALE which is an array, 1st element is date format using
+adodb_date syntax, and 2nd element is the time format, also in adodb_date syntax.
+
+    eg. $ADODB_DATE_LOCALE = array('d/m/Y','H:i:s');
+	
+	Supported format codes:
+
+<pre>
+	%a - abbreviated weekday name according to the current locale 
+	%A - full weekday name according to the current locale 
+	%b - abbreviated month name according to the current locale 
+	%B - full month name according to the current locale 
+	%c - preferred date and time representation for the current locale 
+	%d - day of the month as a decimal number (range 01 to 31) 
+	%D - same as %m/%d/%y 
+	%e - day of the month as a decimal number, a single digit is preceded by a space (range ' 1' to '31') 
+	%h - same as %b
+	%H - hour as a decimal number using a 24-hour clock (range 00 to 23) 
+	%I - hour as a decimal number using a 12-hour clock (range 01 to 12) 
+	%m - month as a decimal number (range 01 to 12) 
+	%M - minute as a decimal number 
+	%n - newline character 
+	%p - either `am' or `pm' according to the given time value, or the corresponding strings for the current locale 
+	%r - time in a.m. and p.m. notation 
+	%R - time in 24 hour notation 
+	%S - second as a decimal number 
+	%t - tab character 
+	%T - current time, equal to %H:%M:%S 
+	%x - preferred date representation for the current locale without the time 
+	%X - preferred time representation for the current locale without the date 
+	%y - year as a decimal number without a century (range 00 to 99) 
+	%Y - year as a decimal number including the century 
+	%Z - time zone or name or abbreviation 
+	%% - a literal `%' character 
+</pre>	
+
+	Unsupported codes:
+<pre>
+	%C - century number (the year divided by 100 and truncated to an integer, range 00 to 99) 
+	%g - like %G, but without the century. 
+	%G - The 4-digit year corresponding to the ISO week number (see %V). 
+	     This has the same format and value as %Y, except that if the ISO week number belongs 
+		 to the previous or next year, that year is used instead. 
+	%j - day of the year as a decimal number (range 001 to 366) 
+	%u - weekday as a decimal number [1,7], with 1 representing Monday 
+	%U - week number of the current year as a decimal number, starting 
+	    with the first Sunday as the first day of the first week 
+	%V - The ISO 8601:1988 week number of the current year as a decimal number, 
+	     range 01 to 53, where week 1 is the first week that has at least 4 days in the 
+		 current year, and with Monday as the first day of the week. (Use %G or %g for 
+		 the year component that corresponds to the week number for the specified timestamp.) 
+	%w - day of the week as a decimal, Sunday being 0 
+	%W - week number of the current year as a decimal number, starting with the 
+	     first Monday as the first day of the first week 
+</pre>
+
+=============================================================================
+
+NOTES
+
+Useful url for generating test timestamps:
+	http://www.4webhelp.net/us/timestamp.php
+
+Possible future optimizations include 
+
+a. Using an algorithm similar to Plauger's in "The Standard C Library" 
+(page 428, xttotm.c _Ttotm() function). Plauger's algorithm will not 
+work outside 32-bit signed range, so i decided not to implement it.
+
+b. Implement daylight savings, which looks awfully complicated, see
+	http://webexhibits.org/daylightsaving/
+
+
+CHANGELOG
+- 19 March 2006 0.24
+Changed strftime() locale detection, because some locales prepend the day of week to the date when %c is used.
+
+- 10 Feb 2006 0.23
+PHP5 compat: when we detect PHP5, the RFC2822 format for gmt 0000hrs is changed from -0000 to +0000. 
+	In PHP4, we will still use -0000 for 100% compat with PHP4.
+
+- 08 Sept 2005 0.22
+In adodb_date2(), $is_gmt not supported properly. Fixed.
+
+- 18 July  2005 0.21
+In PHP 4.3.11, the 'r' format has changed. Leading 0 in day is added. Changed for compat.
+Added support for negative months in adodb_mktime().
+
+- 24 Feb 2005 0.20
+Added limited strftime/gmstrftime support. x10 improvement in performance of adodb_date().
+
+- 21 Dec 2004 0.17
+In adodb_getdate(), the timestamp was accidentally converted to gmt when $is_gmt is false. 
+Also adodb_mktime(0,0,0) did not work properly. Both fixed thx Mauro.
+
+- 17 Nov 2004 0.16
+Removed intval typecast in adodb_mktime() for secs, allowing:
+	 adodb_mktime(0,0,0 + 2236672153,1,1,1934);
+Suggested by Ryan.
+
+- 18 July 2004 0.15
+All params in adodb_mktime were formerly compulsory. Now only the hour, min, secs is compulsory. 
+This brings it more in line with mktime (still not identical).
+
+- 23 June 2004 0.14
+
+Allow you to define your own daylights savings function, adodb_daylight_sv.
+If the function is defined (somewhere in an include), then you can correct for daylights savings.
+
+In this example, we apply daylights savings in June or July, adding one hour. This is extremely
+unrealistic as it does not take into account time-zone, geographic location, current year.
+
+function adodb_daylight_sv(&$arr, $is_gmt)
+{
+	if ($is_gmt) return;
+	$m = $arr['mon'];
+	if ($m == 6 || $m == 7) $arr['hours'] += 1;
+}
+
+This is only called by adodb_date() and not by adodb_mktime(). 
+
+The format of $arr is
+Array ( 
+   [seconds] => 0 
+   [minutes] => 0 
+   [hours] => 0 
+   [mday] => 1      # day of month, eg 1st day of the month
+   [mon] => 2       # month (eg. Feb)
+   [year] => 2102 
+   [yday] => 31     # days in current year
+   [leap] =>        # true if leap year
+   [ndays] => 28    # no of days in current month
+   ) 
+   
+
+- 28 Apr 2004 0.13
+Fixed adodb_date to properly support $is_gmt. Thx to Dimitar Angelov.
+
+- 20 Mar 2004 0.12
+Fixed month calculation error in adodb_date. 2102-June-01 appeared as 2102-May-32.
+
+- 26 Oct 2003 0.11
+Because of daylight savings problems (some systems apply daylight savings to 
+January!!!), changed adodb_get_gmt_diff() to ignore daylight savings.
+
+- 9 Aug 2003 0.10
+Fixed bug with dates after 2038. 
+See http://phplens.com/lens/lensforum/msgs.php?id=6980
+
+- 1 July 2003 0.09
+Added support for Q (Quarter).
+Added adodb_date2(), which accepts ISO date in 2nd param
+
+- 3 March 2003 0.08
+Added support for 'S' adodb_date() format char. Added constant ADODB_ALLOW_NEGATIVE_TS
+if you want PHP to handle negative timestamps between 1901 to 1969.
+
+- 27 Feb 2003 0.07
+All negative numbers handled by adodb now because of RH 7.3+ problems.
+See http://bugs.php.net/bug.php?id=20048&edit=2
+
+- 4 Feb 2003 0.06
+Fixed a typo, 1852 changed to 1582! This means that pre-1852 dates
+are now correctly handled.
+
+- 29 Jan 2003 0.05
+
+Leap year checking differs under Julian calendar (pre 1582). Also
+leap year code optimized by checking for most common case first.
+
+We also handle month overflow correctly in mktime (eg month set to 13).
+
+Day overflow for less than one month's days is supported.
+
+- 28 Jan 2003 0.04
+
+Gregorian correction handled. In PHP5, we might throw an error if 
+mktime uses invalid dates around 5-14 Oct 1582. Released with ADOdb 3.10.
+Added limbo 5-14 Oct 1582 check, when we set to 15 Oct 1582.
+
+- 27 Jan 2003 0.03
+
+Fixed some more month problems due to gmt issues. Added constant ADODB_DATE_VERSION.
+Fixed calculation of days since start of year for <1970. 
+
+- 27 Jan 2003 0.02
+
+Changed _adodb_getdate() to inline leap year checking for better performance.
+Fixed problem with time-zones west of GMT +0000.
+
+- 24 Jan 2003 0.01
+
+First implementation.
+*/
+
+
+/* Initialization */
+
+/*
+	Version Number
+*/
+define('ADODB_DATE_VERSION',0.24);
+
+/*
+	This code was originally for windows. But apparently this problem happens 
+	also with Linux, RH 7.3 and later!
+	
+	glibc-2.2.5-34 and greater has been changed to return -1 for dates <
+	1970.  This used to work.  The problem exists with RedHat 7.3 and 8.0
+	echo (mktime(0, 0, 0, 1, 1, 1960));  // prints -1
+	
+	References:
+	 http://bugs.php.net/bug.php?id=20048&edit=2
+	 http://lists.debian.org/debian-glibc/2002/debian-glibc-200205/msg00010.html
+*/
+
+if (!defined('ADODB_ALLOW_NEGATIVE_TS')) define('ADODB_NO_NEGATIVE_TS',1);
+
+function adodb_date_test_date($y1,$m,$d=13)
+{
+	$t = adodb_mktime(0,0,0,$m,$d,$y1);
+	$rez = adodb_date('Y-n-j H:i:s',$t);
+	if ("$y1-$m-$d 00:00:00" != $rez) {
+		print "<b>$y1 error, expected=$y1-$m-$d 00:00:00, adodb=$rez</b><br>";
+		return false;
+	}
+	return true;
+}
+
+function adodb_date_test_strftime($fmt)
+{
+	$s1 = strftime($fmt);
+	$s2 = adodb_strftime($fmt);
+	
+	if ($s1 == $s2) return true;
+	
+	echo "error for $fmt,  strftime=$s1, $adodb=$s2<br>";
+	return false;
+}
+
+/**
+	 Test Suite
+*/
+function adodb_date_test()
+{
+	
+	error_reporting(E_ALL);
+	print "<h4>Testing adodb_date and adodb_mktime. version=".ADODB_DATE_VERSION.' PHP='.PHP_VERSION."</h4>";
+	@set_time_limit(0);
+	$fail = false;
+	
+	// This flag disables calling of PHP native functions, so we can properly test the code
+	if (!defined('ADODB_TEST_DATES')) define('ADODB_TEST_DATES',1);
+	
+	adodb_date_test_strftime('%Y %m %x %X');
+	adodb_date_test_strftime("%A %d %B %Y");
+	adodb_date_test_strftime("%H %M S");
+	
+	$t = adodb_mktime(0,0,0);
+	if (!(adodb_date('Y-m-d') == date('Y-m-d'))) print 'Error in '.adodb_mktime(0,0,0).'<br>';
+	
+	$t = adodb_mktime(0,0,0,6,1,2102);
+	if (!(adodb_date('Y-m-d',$t) == '2102-06-01')) print 'Error in '.adodb_date('Y-m-d',$t).'<br>';
+	
+	$t = adodb_mktime(0,0,0,2,1,2102);
+	if (!(adodb_date('Y-m-d',$t) == '2102-02-01')) print 'Error in '.adodb_date('Y-m-d',$t).'<br>';
+	
+	
+	print "<p>Testing gregorian <=> julian conversion<p>";
+	$t = adodb_mktime(0,0,0,10,11,1492);
+	//http://www.holidayorigins.com/html/columbus_day.html - Friday check
+	if (!(adodb_date('D Y-m-d',$t) == 'Fri 1492-10-11')) print 'Error in Columbus landing<br>';
+	
+	$t = adodb_mktime(0,0,0,2,29,1500);
+	if (!(adodb_date('Y-m-d',$t) == '1500-02-29')) print 'Error in julian leap years<br>';
+	
+	$t = adodb_mktime(0,0,0,2,29,1700);
+	if (!(adodb_date('Y-m-d',$t) == '1700-03-01')) print 'Error in gregorian leap years<br>';
+	
+	print  adodb_mktime(0,0,0,10,4,1582).' ';
+	print adodb_mktime(0,0,0,10,15,1582);
+	$diff = (adodb_mktime(0,0,0,10,15,1582) - adodb_mktime(0,0,0,10,4,1582));
+	if ($diff != 3600*24) print " <b>Error in gregorian correction = ".($diff/3600/24)." days </b><br>";
+		
+	print " 15 Oct 1582, Fri=".(adodb_dow(1582,10,15) == 5 ? 'Fri' : '<b>Error</b>')."<br>";
+	print " 4 Oct 1582, Thu=".(adodb_dow(1582,10,4) == 4 ? 'Thu' : '<b>Error</b>')."<br>";
+	
+	print "<p>Testing overflow<p>";
+	
+	$t = adodb_mktime(0,0,0,3,33,1965);
+	if (!(adodb_date('Y-m-d',$t) == '1965-04-02')) print 'Error in day overflow 1 <br>';
+	$t = adodb_mktime(0,0,0,4,33,1971);
+	if (!(adodb_date('Y-m-d',$t) == '1971-05-03')) print 'Error in day overflow 2 <br>';
+	$t = adodb_mktime(0,0,0,1,60,1965);
+	if (!(adodb_date('Y-m-d',$t) == '1965-03-01')) print 'Error in day overflow 3 '.adodb_date('Y-m-d',$t).' <br>';
+	$t = adodb_mktime(0,0,0,12,32,1965);
+	if (!(adodb_date('Y-m-d',$t) == '1966-01-01')) print 'Error in day overflow 4 '.adodb_date('Y-m-d',$t).' <br>';
+	$t = adodb_mktime(0,0,0,12,63,1965);
+	if (!(adodb_date('Y-m-d',$t) == '1966-02-01')) print 'Error in day overflow 5 '.adodb_date('Y-m-d',$t).' <br>';
+	$t = adodb_mktime(0,0,0,13,3,1965);
+	if (!(adodb_date('Y-m-d',$t) == '1966-01-03')) print 'Error in mth overflow 1 <br>';
+	
+	print "Testing 2-digit => 4-digit year conversion<p>";
+	if (adodb_year_digit_check(00) != 2000) print "Err 2-digit 2000<br>";
+	if (adodb_year_digit_check(10) != 2010) print "Err 2-digit 2010<br>";
+	if (adodb_year_digit_check(20) != 2020) print "Err 2-digit 2020<br>";
+	if (adodb_year_digit_check(30) != 2030) print "Err 2-digit 2030<br>";
+	if (adodb_year_digit_check(40) != 1940) print "Err 2-digit 1940<br>";
+	if (adodb_year_digit_check(50) != 1950) print "Err 2-digit 1950<br>";
+	if (adodb_year_digit_check(90) != 1990) print "Err 2-digit 1990<br>";
+	
+	// Test string formating
+	print "<p>Testing date formating</p>";
+	$fmt = '\d\a\t\e T Y-m-d H:i:s a A d D F g G h H i j l L m M n O \R\F\C2822 r s t U w y Y z Z 2003';
+	$s1 = date($fmt,0);
+	$s2 = adodb_date($fmt,0);
+	if ($s1 != $s2) {
+		print " date() 0 failed<br>$s1<br>$s2<br>";
+	}
+	flush();
+	for ($i=100; --$i > 0; ) {
+
+		$ts = 3600.0*((rand()%60000)+(rand()%60000))+(rand()%60000);
+		$s1 = date($fmt,$ts);
+		$s2 = adodb_date($fmt,$ts);
+		//print "$s1 <br>$s2 <p>";
+		$pos = strcmp($s1,$s2);
+
+		if (($s1) != ($s2)) {
+			for ($j=0,$k=strlen($s1); $j < $k; $j++) {
+				if ($s1[$j] != $s2[$j]) {
+					print substr($s1,$j).' ';
+					break;
+				}
+			}
+			print "<b>Error date(): $ts<br><pre> 
+&nbsp; \"$s1\" (date len=".strlen($s1).")
+&nbsp; \"$s2\" (adodb_date len=".strlen($s2).")</b></pre><br>";
+			$fail = true;
+		}
+		
+		$a1 = getdate($ts);
+		$a2 = adodb_getdate($ts);
+		$rez = array_diff($a1,$a2);
+		if (sizeof($rez)>0) {
+			print "<b>Error getdate() $ts</b><br>";
+				print_r($a1);
+			print "<br>";
+				print_r($a2);
+			print "<p>";
+			$fail = true;
+		}
+	}
+	
+	// Test generation of dates outside 1901-2038
+	print "<p>Testing random dates between 100 and 4000</p>";
+	adodb_date_test_date(100,1);
+	for ($i=100; --$i >= 0;) {
+		$y1 = 100+rand(0,1970-100);
+		$m = rand(1,12);
+		adodb_date_test_date($y1,$m);
+		
+		$y1 = 3000-rand(0,3000-1970);
+		adodb_date_test_date($y1,$m);
+	}
+	print '<p>';
+	$start = 1960+rand(0,10);
+	$yrs = 12;
+	$i = 365.25*86400*($start-1970);
+	$offset = 36000+rand(10000,60000);
+	$max = 365*$yrs*86400;
+	$lastyear = 0;
+	
+	// we generate a timestamp, convert it to a date, and convert it back to a timestamp
+	// and check if the roundtrip broke the original timestamp value.
+	print "Testing $start to ".($start+$yrs).", or $max seconds, offset=$offset: ";
+	$cnt = 0;
+	for ($max += $i; $i < $max; $i += $offset) {
+		$ret = adodb_date('m,d,Y,H,i,s',$i);
+		$arr = explode(',',$ret);
+		if ($lastyear != $arr[2]) {
+			$lastyear = $arr[2];
+			print " $lastyear ";
+			flush();
+		}
+		$newi = adodb_mktime($arr[3],$arr[4],$arr[5],$arr[0],$arr[1],$arr[2]);
+		if ($i != $newi) {
+			print "Error at $i, adodb_mktime returned $newi ($ret)";
+			$fail = true;
+			break;
+		}
+		$cnt += 1;
+	}
+	echo "Tested $cnt dates<br>";
+	if (!$fail) print "<p>Passed !</p>";
+	else print "<p><b>Failed</b> :-(</p>";
+}
+
+/**
+	Returns day of week, 0 = Sunday,... 6=Saturday. 
+	Algorithm from PEAR::Date_Calc
+*/
+function adodb_dow($year, $month, $day)
+{
+/*
+Pope Gregory removed 10 days - October 5 to October 14 - from the year 1582 and 
+proclaimed that from that time onwards 3 days would be dropped from the calendar 
+every 400 years.
+
+Thursday, October 4, 1582 (Julian) was followed immediately by Friday, October 15, 1582 (Gregorian). 
+*/
+	if ($year <= 1582) {
+		if ($year < 1582 || 
+			($year == 1582 && ($month < 10 || ($month == 10 && $day < 15)))) $greg_correction = 3;
+		 else
+			$greg_correction = 0;
+	} else
+		$greg_correction = 0;
+	
+	if($month > 2)
+	    $month -= 2;
+	else {
+	    $month += 10;
+	    $year--;
+	}
+	
+	$day =  floor((13 * $month - 1) / 5) +
+	        $day + ($year % 100) +
+	        floor(($year % 100) / 4) +
+	        floor(($year / 100) / 4) - 2 *
+	        floor($year / 100) + 77 + $greg_correction;
+	
+	return $day - 7 * floor($day / 7);
+}
+
+
+/**
+ Checks for leap year, returns true if it is. No 2-digit year check. Also 
+ handles julian calendar correctly.
+*/
+function _adodb_is_leap_year($year) 
+{
+	if ($year % 4 != 0) return false;
+	
+	if ($year % 400 == 0) {
+		return true;
+	// if gregorian calendar (>1582), century not-divisible by 400 is not leap
+	} else if ($year > 1582 && $year % 100 == 0 ) {
+		return false;
+	} 
+	
+	return true;
+}
+
+
+/**
+ checks for leap year, returns true if it is. Has 2-digit year check
+*/
+function adodb_is_leap_year($year) 
+{
+	return  _adodb_is_leap_year(adodb_year_digit_check($year));
+}
+
+/**
+	Fix 2-digit years. Works for any century.
+ 	Assumes that if 2-digit is more than 30 years in future, then previous century.
+*/
+function adodb_year_digit_check($y) 
+{
+	if ($y < 100) {
+	
+		$yr = (integer) date("Y");
+		$century = (integer) ($yr /100);
+		
+		if ($yr%100 > 50) {
+			$c1 = $century + 1;
+			$c0 = $century;
+		} else {
+			$c1 = $century;
+			$c0 = $century - 1;
+		}
+		$c1 *= 100;
+		// if 2-digit year is less than 30 years in future, set it to this century
+		// otherwise if more than 30 years in future, then we set 2-digit year to the prev century.
+		if (($y + $c1) < $yr+30) $y = $y + $c1;
+		else $y = $y + $c0*100;
+	}
+	return $y;
+}
+
+/**
+ get local time zone offset from GMT
+*/
+function adodb_get_gmt_diff() 
+{
+static $TZ;
+	if (isset($TZ)) return $TZ;
+	
+	$TZ = mktime(0,0,0,1,2,1970,0) - gmmktime(0,0,0,1,2,1970,0);
+	return $TZ;
+}
+
+/**
+	Returns an array with date info.
+*/
+function adodb_getdate($d=false,$fast=false)
+{
+	if ($d === false) return getdate();
+	if (!defined('ADODB_TEST_DATES')) {
+		if ((abs($d) <= 0x7FFFFFFF)) { // check if number in 32-bit signed range
+			if (!defined('ADODB_NO_NEGATIVE_TS') || $d >= 0) // if windows, must be +ve integer
+				return @getdate($d);
+		}
+	}
+	return _adodb_getdate($d);
+}
+
+/*
+// generate $YRS table for _adodb_getdate()
+function adodb_date_gentable($out=true)
+{
+
+	for ($i=1970; $i >= 1600; $i-=10) {
+		$s = adodb_gmmktime(0,0,0,1,1,$i);
+		echo "$i => $s,<br>";	
+	}
+}
+adodb_date_gentable();
+
+for ($i=1970; $i > 1500; $i--) {
+
+echo "<hr />$i ";
+	adodb_date_test_date($i,1,1);
+}
+
+*/
+
+
+$_month_table_normal = array("",31,28,31,30,31,30,31,31,30,31,30,31);
+$_month_table_leaf = array("",31,29,31,30,31,30,31,31,30,31,30,31);
+	
+function adodb_validdate($y,$m,$d)
+{
+global $_month_table_normal,$_month_table_leaf;
+
+	if (_adodb_is_leap_year($y)) $marr =& $_month_table_leaf;
+	else $marr =& $_month_table_normal;
+	
+	if ($m > 12 || $m < 1) return false;
+	
+	if ($d > 31 || $d < 1) return false;
+	
+	if ($marr[$m] < $d) return false;
+	
+	if ($y < 1000 && $y > 3000) return false;
+	
+	return true;
+}
+
+/**
+	Low-level function that returns the getdate() array. We have a special
+	$fast flag, which if set to true, will return fewer array values,
+	and is much faster as it does not calculate dow, etc.
+*/
+function _adodb_getdate($origd=false,$fast=false,$is_gmt=false)
+{
+static $YRS;
+global $_month_table_normal,$_month_table_leaf;
+
+	$d =  $origd - ($is_gmt ? 0 : adodb_get_gmt_diff());
+	
+	$_day_power = 86400;
+	$_hour_power = 3600;
+	$_min_power = 60;
+	
+	if ($d < -12219321600) $d -= 86400*10; // if 15 Oct 1582 or earlier, gregorian correction 
+	
+	$_month_table_normal = array("",31,28,31,30,31,30,31,31,30,31,30,31);
+	$_month_table_leaf = array("",31,29,31,30,31,30,31,31,30,31,30,31);
+	
+	$d366 = $_day_power * 366;
+	$d365 = $_day_power * 365;
+	
+	if ($d < 0) {
+		
+		if (empty($YRS)) $YRS = array(
+			1970 => 0,
+			1960 => -315619200,
+			1950 => -631152000,
+			1940 => -946771200,
+			1930 => -1262304000,
+			1920 => -1577923200,
+			1910 => -1893456000,
+			1900 => -2208988800,
+			1890 => -2524521600,
+			1880 => -2840140800,
+			1870 => -3155673600,
+			1860 => -3471292800,
+			1850 => -3786825600,
+			1840 => -4102444800,
+			1830 => -4417977600,
+			1820 => -4733596800,
+			1810 => -5049129600,
+			1800 => -5364662400,
+			1790 => -5680195200,
+			1780 => -5995814400,
+			1770 => -6311347200,
+			1760 => -6626966400,
+			1750 => -6942499200,
+			1740 => -7258118400,
+			1730 => -7573651200,
+			1720 => -7889270400,
+			1710 => -8204803200,
+			1700 => -8520336000,
+			1690 => -8835868800,
+			1680 => -9151488000,
+			1670 => -9467020800,
+			1660 => -9782640000,
+			1650 => -10098172800,
+			1640 => -10413792000,
+			1630 => -10729324800,
+			1620 => -11044944000,
+			1610 => -11360476800,
+			1600 => -11676096000);
+
+		if ($is_gmt) $origd = $d;
+		// The valid range of a 32bit signed timestamp is typically from 
+		// Fri, 13 Dec 1901 20:45:54 GMT to Tue, 19 Jan 2038 03:14:07 GMT
+		//
+		
+		# old algorithm iterates through all years. new algorithm does it in
+		# 10 year blocks
+		
+		/*
+		# old algo
+		for ($a = 1970 ; --$a >= 0;) {
+			$lastd = $d;
+			
+			if ($leaf = _adodb_is_leap_year($a)) $d += $d366;
+			else $d += $d365;
+			
+			if ($d >= 0) {
+				$year = $a;
+				break;
+			}
+		}
+		*/
+		
+		$lastsecs = 0;
+		$lastyear = 1970;
+		foreach($YRS as $year => $secs) {
+			if ($d >= $secs) {
+				$a = $lastyear;
+				break;
+			}
+			$lastsecs = $secs;
+			$lastyear = $year;
+		}
+		
+		$d -= $lastsecs;
+		if (!isset($a)) $a = $lastyear;
+		
+		//echo ' yr=',$a,' ', $d,'.';
+		
+		for (; --$a >= 0;) {
+			$lastd = $d;
+			
+			if ($leaf = _adodb_is_leap_year($a)) $d += $d366;
+			else $d += $d365;
+			
+			if ($d >= 0) {
+				$year = $a;
+				break;
+			}
+		}
+		/**/
+		
+		$secsInYear = 86400 * ($leaf ? 366 : 365) + $lastd;
+		
+		$d = $lastd;
+		$mtab = ($leaf) ? $_month_table_leaf : $_month_table_normal;
+		for ($a = 13 ; --$a > 0;) {
+			$lastd = $d;
+			$d += $mtab[$a] * $_day_power;
+			if ($d >= 0) {
+				$month = $a;
+				$ndays = $mtab[$a];
+				break;
+			}
+		}
+		
+		$d = $lastd;
+		$day = $ndays + ceil(($d+1) / ($_day_power));
+
+		$d += ($ndays - $day+1)* $_day_power;
+		$hour = floor($d/$_hour_power);
+	
+	} else {
+		for ($a = 1970 ;; $a++) {
+			$lastd = $d;
+			
+			if ($leaf = _adodb_is_leap_year($a)) $d -= $d366;
+			else $d -= $d365;
+			if ($d < 0) {
+				$year = $a;
+				break;
+			}
+		}
+		$secsInYear = $lastd;
+		$d = $lastd;
+		$mtab = ($leaf) ? $_month_table_leaf : $_month_table_normal;
+		for ($a = 1 ; $a <= 12; $a++) {
+			$lastd = $d;
+			$d -= $mtab[$a] * $_day_power;
+			if ($d < 0) {
+				$month = $a;
+				$ndays = $mtab[$a];
+				break;
+			}
+		}
+		$d = $lastd;
+		$day = ceil(($d+1) / $_day_power);
+		$d = $d - ($day-1) * $_day_power;
+		$hour = floor($d /$_hour_power);
+	}
+	
+	$d -= $hour * $_hour_power;
+	$min = floor($d/$_min_power);
+	$secs = $d - $min * $_min_power;
+	if ($fast) {
+		return array(
+		'seconds' => $secs,
+		'minutes' => $min,
+		'hours' => $hour,
+		'mday' => $day,
+		'mon' => $month,
+		'year' => $year,
+		'yday' => floor($secsInYear/$_day_power),
+		'leap' => $leaf,
+		'ndays' => $ndays
+		);
+	}
+	
+	
+	$dow = adodb_dow($year,$month,$day);
+
+	return array(
+		'seconds' => $secs,
+		'minutes' => $min,
+		'hours' => $hour,
+		'mday' => $day,
+		'wday' => $dow,
+		'mon' => $month,
+		'year' => $year,
+		'yday' => floor($secsInYear/$_day_power),
+		'weekday' => gmdate('l',$_day_power*(3+$dow)),
+		'month' => gmdate('F',mktime(0,0,0,$month,2,1971)),
+		0 => $origd
+	);
+}
+
+function adodb_gmdate($fmt,$d=false)
+{
+	return adodb_date($fmt,$d,true);
+}
+
+// accepts unix timestamp and iso date format in $d
+function adodb_date2($fmt, $d=false, $is_gmt=false)
+{
+	if ($d !== false) {
+		if (!preg_match( 
+			"|^([0-9]{4})[-/\.]?([0-9]{1,2})[-/\.]?([0-9]{1,2})[ -]?(([0-9]{1,2}):?([0-9]{1,2}):?([0-9\.]{1,4}))?|", 
+			($d), $rr)) return adodb_date($fmt,false,$is_gmt);
+
+		if ($rr[1] <= 100 && $rr[2]<= 1) return adodb_date($fmt,false,$is_gmt);
+	
+		// h-m-s-MM-DD-YY
+		if (!isset($rr[5])) $d = adodb_mktime(0,0,0,$rr[2],$rr[3],$rr[1],false,$is_gmt);
+		else $d = @adodb_mktime($rr[5],$rr[6],$rr[7],$rr[2],$rr[3],$rr[1],false,$is_gmt);
+	}
+	
+	return adodb_date($fmt,$d,$is_gmt);
+}
+
+
+/**
+	Return formatted date based on timestamp $d
+*/
+function adodb_date($fmt,$d=false,$is_gmt=false)
+{
+static $daylight;
+
+	if ($d === false) return ($is_gmt)? @gmdate($fmt): @date($fmt);
+	if (!defined('ADODB_TEST_DATES')) {
+		if ((abs($d) <= 0x7FFFFFFF)) { // check if number in 32-bit signed range
+			if (!defined('ADODB_NO_NEGATIVE_TS') || $d >= 0) // if windows, must be +ve integer
+				return ($is_gmt)? @gmdate($fmt,$d): @date($fmt,$d);
+
+		}
+	}
+	$_day_power = 86400;
+	
+	$arr = _adodb_getdate($d,true,$is_gmt);
+	
+	if (!isset($daylight)) $daylight = function_exists('adodb_daylight_sv');
+	if ($daylight) adodb_daylight_sv($arr, $is_gmt);
+	
+	$year = $arr['year'];
+	$month = $arr['mon'];
+	$day = $arr['mday'];
+	$hour = $arr['hours'];
+	$min = $arr['minutes'];
+	$secs = $arr['seconds'];
+	
+	$max = strlen($fmt);
+	$dates = '';
+	
+	$isphp5 = PHP_VERSION >= 5;
+	
+	/*
+		at this point, we have the following integer vars to manipulate:
+		$year, $month, $day, $hour, $min, $secs
+	*/
+	for ($i=0; $i < $max; $i++) {
+		switch($fmt[$i]) {
+		case 'T': $dates .= date('T');break;
+		// YEAR
+		case 'L': $dates .= $arr['leap'] ? '1' : '0'; break;
+		case 'r': // Thu, 21 Dec 2000 16:01:07 +0200
+		
+			// 4.3.11 uses '04 Jun 2004'
+			// 4.3.8 uses  ' 4 Jun 2004'
+			$dates .= gmdate('D',$_day_power*(3+adodb_dow($year,$month,$day))).', '		
+				. ($day<10?'0'.$day:$day) . ' '.date('M',mktime(0,0,0,$month,2,1971)).' '.$year.' ';
+			
+			if ($hour < 10) $dates .= '0'.$hour; else $dates .= $hour; 
+			
+			if ($min < 10) $dates .= ':0'.$min; else $dates .= ':'.$min;
+			
+			if ($secs < 10) $dates .= ':0'.$secs; else $dates .= ':'.$secs;
+			
+			$gmt = adodb_get_gmt_diff();
+			if ($isphp5) 
+				$dates .= sprintf(' %s%04d',($gmt<=0)?'+':'-',abs($gmt)/36); 
+			else
+				$dates .= sprintf(' %s%04d',($gmt<0)?'+':'-',abs($gmt)/36); 
+			break;
+				
+		case 'Y': $dates .= $year; break;
+		case 'y': $dates .= substr($year,strlen($year)-2,2); break;
+		// MONTH
+		case 'm': if ($month<10) $dates .= '0'.$month; else $dates .= $month; break;
+		case 'Q': $dates .= ($month+3)>>2; break;
+		case 'n': $dates .= $month; break;
+		case 'M': $dates .= date('M',mktime(0,0,0,$month,2,1971)); break;
+		case 'F': $dates .= date('F',mktime(0,0,0,$month,2,1971)); break;
+		// DAY
+		case 't': $dates .= $arr['ndays']; break;
+		case 'z': $dates .= $arr['yday']; break;
+		case 'w': $dates .= adodb_dow($year,$month,$day); break;
+		case 'l': $dates .= gmdate('l',$_day_power*(3+adodb_dow($year,$month,$day))); break;
+		case 'D': $dates .= gmdate('D',$_day_power*(3+adodb_dow($year,$month,$day))); break;
+		case 'j': $dates .= $day; break;
+		case 'd': if ($day<10) $dates .= '0'.$day; else $dates .= $day; break;
+		case 'S': 
+			$d10 = $day % 10;
+			if ($d10 == 1) $dates .= 'st';
+			else if ($d10 == 2 && $day != 12) $dates .= 'nd';
+			else if ($d10 == 3) $dates .= 'rd';
+			else $dates .= 'th';
+			break;
+			
+		// HOUR
+		case 'Z':
+			$dates .= ($is_gmt) ? 0 : -adodb_get_gmt_diff(); break;
+		case 'O': 
+			$gmt = ($is_gmt) ? 0 : adodb_get_gmt_diff();
+			
+			if ($isphp5)
+				$dates .= sprintf('%s%04d',($gmt<=0)?'+':'-',abs($gmt)/36); 
+			else
+				$dates .= sprintf('%s%04d',($gmt<0)?'+':'-',abs($gmt)/36); 
+			break;
+			
+		case 'H': 
+			if ($hour < 10) $dates .= '0'.$hour; 
+			else $dates .= $hour; 
+			break;
+		case 'h': 
+			if ($hour > 12) $hh = $hour - 12; 
+			else {
+				if ($hour == 0) $hh = '12'; 
+				else $hh = $hour;
+			}
+			
+			if ($hh < 10) $dates .= '0'.$hh;
+			else $dates .= $hh;
+			break;
+			
+		case 'G': 
+			$dates .= $hour;
+			break;
+			
+		case 'g':
+			if ($hour > 12) $hh = $hour - 12; 
+			else {
+				if ($hour == 0) $hh = '12'; 
+				else $hh = $hour; 
+			}
+			$dates .= $hh;
+			break;
+		// MINUTES
+		case 'i': if ($min < 10) $dates .= '0'.$min; else $dates .= $min; break;
+		// SECONDS
+		case 'U': $dates .= $d; break;
+		case 's': if ($secs < 10) $dates .= '0'.$secs; else $dates .= $secs; break;
+		// AM/PM
+		// Note 00:00 to 11:59 is AM, while 12:00 to 23:59 is PM
+		case 'a':
+			if ($hour>=12) $dates .= 'pm';
+			else $dates .= 'am';
+			break;
+		case 'A':
+			if ($hour>=12) $dates .= 'PM';
+			else $dates .= 'AM';
+			break;
+		default:
+			$dates .= $fmt[$i]; break;
+		// ESCAPE
+		case "\\": 
+			$i++;
+			if ($i < $max) $dates .= $fmt[$i];
+			break;
+		}
+	}
+	return $dates;
+}
+
+/**
+	Returns a timestamp given a GMT/UTC time. 
+	Note that $is_dst is not implemented and is ignored.
+*/
+function adodb_gmmktime($hr,$min,$sec,$mon=false,$day=false,$year=false,$is_dst=false)
+{
+	return adodb_mktime($hr,$min,$sec,$mon,$day,$year,$is_dst,true);
+}
+
+/**
+	Return a timestamp given a local time. Originally by jackbbs.
+	Note that $is_dst is not implemented and is ignored.
+	
+	Not a very fast algorithm - O(n) operation. Could be optimized to O(1).
+*/
+function adodb_mktime($hr,$min,$sec,$mon=false,$day=false,$year=false,$is_dst=false,$is_gmt=false) 
+{
+	if (!defined('ADODB_TEST_DATES')) {
+
+		if ($mon === false) {
+			return $is_gmt? @gmmktime($hr,$min,$sec): @mktime($hr,$min,$sec);
+		}
+		
+		// for windows, we don't check 1970 because with timezone differences, 
+		// 1 Jan 1970 could generate negative timestamp, which is illegal
+		if (1971 < $year && $year < 2038
+			|| !defined('ADODB_NO_NEGATIVE_TS') && (1901 < $year && $year < 2038)
+			) {
+				return $is_gmt ?
+					@gmmktime($hr,$min,$sec,$mon,$day,$year):
+					@mktime($hr,$min,$sec,$mon,$day,$year);
+			}
+	}
+	
+	$gmt_different = ($is_gmt) ? 0 : adodb_get_gmt_diff();
+
+	/*
+	# disabled because some people place large values in $sec.
+	# however we need it for $mon because we use an array...
+	$hr = intval($hr);
+	$min = intval($min);
+	$sec = intval($sec);
+	*/
+	$mon = intval($mon);
+	$day = intval($day);
+	$year = intval($year);
+	
+	
+	$year = adodb_year_digit_check($year);
+
+	if ($mon > 12) {
+		$y = floor($mon / 12);
+		$year += $y;
+		$mon -= $y*12;
+	} else if ($mon < 1) {
+		$y = ceil((1-$mon) / 12);
+		$year -= $y;
+		$mon += $y*12;
+	}
+	
+	$_day_power = 86400;
+	$_hour_power = 3600;
+	$_min_power = 60;
+	
+	$_month_table_normal = array("",31,28,31,30,31,30,31,31,30,31,30,31);
+	$_month_table_leaf = array("",31,29,31,30,31,30,31,31,30,31,30,31);
+	
+	$_total_date = 0;
+	if ($year >= 1970) {
+		for ($a = 1970 ; $a <= $year; $a++) {
+			$leaf = _adodb_is_leap_year($a);
+			if ($leaf == true) {
+				$loop_table = $_month_table_leaf;
+				$_add_date = 366;
+			} else {
+				$loop_table = $_month_table_normal;
+				$_add_date = 365;
+			}
+			if ($a < $year) { 
+				$_total_date += $_add_date;
+			} else {
+				for($b=1;$b<$mon;$b++) {
+					$_total_date += $loop_table[$b];
+				}
+			}
+		}
+		$_total_date +=$day-1;
+		$ret = $_total_date * $_day_power + $hr * $_hour_power + $min * $_min_power + $sec + $gmt_different;
+	
+	} else {
+		for ($a = 1969 ; $a >= $year; $a--) {
+			$leaf = _adodb_is_leap_year($a);
+			if ($leaf == true) {
+				$loop_table = $_month_table_leaf;
+				$_add_date = 366;
+			} else {
+				$loop_table = $_month_table_normal;
+				$_add_date = 365;
+			}
+			if ($a > $year) { $_total_date += $_add_date;
+			} else {
+				for($b=12;$b>$mon;$b--) {
+					$_total_date += $loop_table[$b];
+				}
+			}
+		}
+		$_total_date += $loop_table[$mon] - $day;
+		
+		$_day_time = $hr * $_hour_power + $min * $_min_power + $sec;
+		$_day_time = $_day_power - $_day_time;
+		$ret = -( $_total_date * $_day_power + $_day_time - $gmt_different);
+		if ($ret < -12220185600) $ret += 10*86400; // if earlier than 5 Oct 1582 - gregorian correction
+		else if ($ret < -12219321600) $ret = -12219321600; // if in limbo, reset to 15 Oct 1582.
+	} 
+	//print " dmy=$day/$mon/$year $hr:$min:$sec => " .$ret;
+	return $ret;
+}
+
+function adodb_gmstrftime($fmt, $ts=false)
+{
+	return adodb_strftime($fmt,$ts,true);
+}
+
+// hack - convert to adodb_date
+function adodb_strftime($fmt, $ts=false,$is_gmt=false)
+{
+global $ADODB_DATE_LOCALE;
+
+	if (!defined('ADODB_TEST_DATES')) {
+		if ((abs($ts) <= 0x7FFFFFFF)) { // check if number in 32-bit signed range
+			if (!defined('ADODB_NO_NEGATIVE_TS') || $ts >= 0) // if windows, must be +ve integer
+				return ($is_gmt)? @gmstrftime($fmt,$ts): @strftime($fmt,$ts);
+
+		}
+	}
+	
+	if (empty($ADODB_DATE_LOCALE)) {
+	/*
+		$tstr = strtoupper(gmstrftime('%c',31366800)); // 30 Dec 1970, 1 am
+		$sep = substr($tstr,2,1);
+		$hasAM = strrpos($tstr,'M') !== false;
+	*/
+		# see http://phplens.com/lens/lensforum/msgs.php?id=14865 for reasoning, and changelog for version 0.24
+		$dstr = gmstrftime('%x',31366800); // 30 Dec 1970, 1 am
+		$sep = substr($dstr,2,1);
+		$tstr = strtoupper(gmstrftime('%X',31366800)); // 30 Dec 1970, 1 am
+		$hasAM = strrpos($tstr,'M') !== false;
+		
+		$ADODB_DATE_LOCALE = array();
+		$ADODB_DATE_LOCALE[] =  strncmp($tstr,'30',2) == 0 ? 'd'.$sep.'m'.$sep.'y' : 'm'.$sep.'d'.$sep.'y';	
+		$ADODB_DATE_LOCALE[]  = ($hasAM) ? 'h:i:s a' : 'H:i:s';
+			
+	}
+	$inpct = false;
+	$fmtdate = '';
+	for ($i=0,$max = strlen($fmt); $i < $max; $i++) {
+		$ch = $fmt[$i];
+		if ($ch == '%') {
+			if ($inpct) {
+				$fmtdate .= '%';
+				$inpct = false;
+			} else
+				$inpct = true;
+		} else if ($inpct) {
+		
+			$inpct = false;
+			switch($ch) {
+			case '0':
+			case '1':
+			case '2':
+			case '3':
+			case '4':
+			case '5':
+			case '6':
+			case '7':
+			case '8':
+			case '9':
+			case 'E':
+			case 'O':
+				/* ignore format modifiers */
+				$inpct = true; 
+				break;
+				
+			case 'a': $fmtdate .= 'D'; break;
+			case 'A': $fmtdate .= 'l'; break;
+			case 'h':
+			case 'b': $fmtdate .= 'M'; break;
+			case 'B': $fmtdate .= 'F'; break;
+			case 'c': $fmtdate .= $ADODB_DATE_LOCALE[0].$ADODB_DATE_LOCALE[1]; break;
+			case 'C': $fmtdate .= '\C?'; break; // century
+			case 'd': $fmtdate .= 'd'; break;
+			case 'D': $fmtdate .= 'm/d/y'; break;
+			case 'e': $fmtdate .= 'j'; break;
+			case 'g': $fmtdate .= '\g?'; break; //?
+			case 'G': $fmtdate .= '\G?'; break; //?
+			case 'H': $fmtdate .= 'H'; break;
+			case 'I': $fmtdate .= 'h'; break;
+			case 'j': $fmtdate .= '?z'; $parsej = true; break; // wrong as j=1-based, z=0-basd
+			case 'm': $fmtdate .= 'm'; break;
+			case 'M': $fmtdate .= 'i'; break;
+			case 'n': $fmtdate .= "\n"; break;
+			case 'p': $fmtdate .= 'a'; break;
+			case 'r': $fmtdate .= 'h:i:s a'; break;
+			case 'R': $fmtdate .= 'H:i:s'; break;
+			case 'S': $fmtdate .= 's'; break;
+			case 't': $fmtdate .= "\t"; break;
+			case 'T': $fmtdate .= 'H:i:s'; break;
+			case 'u': $fmtdate .= '?u'; $parseu = true; break; // wrong strftime=1-based, date=0-based
+			case 'U': $fmtdate .= '?U'; $parseU = true; break;// wrong strftime=1-based, date=0-based
+			case 'x': $fmtdate .= $ADODB_DATE_LOCALE[0]; break;
+			case 'X': $fmtdate .= $ADODB_DATE_LOCALE[1]; break;
+			case 'w': $fmtdate .= '?w'; $parseu = true; break; // wrong strftime=1-based, date=0-based
+			case 'W': $fmtdate .= '?W'; $parseU = true; break;// wrong strftime=1-based, date=0-based
+			case 'y': $fmtdate .= 'y'; break;
+			case 'Y': $fmtdate .= 'Y'; break;
+			case 'Z': $fmtdate .= 'T'; break;
+			}
+		} else if (('A' <= ($ch) && ($ch) <= 'Z' ) || ('a' <= ($ch) && ($ch) <= 'z' ))
+			$fmtdate .= "\\".$ch;
+		else
+			$fmtdate .= $ch;
+	}
+	//echo "fmt=",$fmtdate,"<br>";
+	if ($ts === false) $ts = time();
+	$ret = adodb_date($fmtdate, $ts, $is_gmt);
+	return $ret;
+}
+
+
+?>
Index: /Dev/trunk/rdfapi/util/adodb/adodb-xmlschema.inc.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/adodb-xmlschema.inc.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/adodb-xmlschema.inc.php	(revision 12)
@@ -0,0 +1,2221 @@
+<?php
+// Copyright (c) 2004 ars Cognita Inc., all rights reserved
+/* ******************************************************************************
+    Released under both BSD license and Lesser GPL library license. 
+ 	Whenever there is any discrepancy between the two licenses, 
+ 	the BSD license will take precedence. 
+*******************************************************************************/
+/**
+ * xmlschema is a class that allows the user to quickly and easily
+ * build a database on any ADOdb-supported platform using a simple
+ * XML schema.
+ *
+ * Last Editor: $Author: cweiske $
+ * @author Richard Tango-Lowy & Dan Cech
+ * @version $Revision: 350 $
+ *
+ * @package axmls
+ * @tutorial getting_started.pkg
+ */
+ 
+function _file_get_contents($file) 
+{
+ 	if (function_exists('file_get_contents')) return file_get_contents($file);
+	
+	$f = fopen($file,'r');
+	if (!$f) return '';
+	$t = '';
+	
+	while ($s = fread($f,100000)) $t .= $s;
+	fclose($f);
+	return $t;
+}
+
+
+/**
+* Debug on or off
+*/
+if( !defined( 'XMLS_DEBUG' ) ) {
+	define( 'XMLS_DEBUG', FALSE );
+}
+
+/**
+* Default prefix key
+*/
+if( !defined( 'XMLS_PREFIX' ) ) {
+	define( 'XMLS_PREFIX', '%%P' );
+}
+
+/**
+* Maximum length allowed for object prefix
+*/
+if( !defined( 'XMLS_PREFIX_MAXLEN' ) ) {
+	define( 'XMLS_PREFIX_MAXLEN', 10 );
+}
+
+/**
+* Execute SQL inline as it is generated
+*/
+if( !defined( 'XMLS_EXECUTE_INLINE' ) ) {
+	define( 'XMLS_EXECUTE_INLINE', FALSE );
+}
+
+/**
+* Continue SQL Execution if an error occurs?
+*/
+if( !defined( 'XMLS_CONTINUE_ON_ERROR' ) ) {
+	define( 'XMLS_CONTINUE_ON_ERROR', FALSE );
+}
+
+/**
+* Current Schema Version
+*/
+if( !defined( 'XMLS_SCHEMA_VERSION' ) ) {
+	define( 'XMLS_SCHEMA_VERSION', '0.2' );
+}
+
+/**
+* Default Schema Version.  Used for Schemas without an explicit version set.
+*/
+if( !defined( 'XMLS_DEFAULT_SCHEMA_VERSION' ) ) {
+	define( 'XMLS_DEFAULT_SCHEMA_VERSION', '0.1' );
+}
+
+/**
+* Default Schema Version.  Used for Schemas without an explicit version set.
+*/
+if( !defined( 'XMLS_DEFAULT_UPGRADE_METHOD' ) ) {
+	define( 'XMLS_DEFAULT_UPGRADE_METHOD', 'ALTER' );
+}
+
+/**
+* Include the main ADODB library
+*/
+if( !defined( '_ADODB_LAYER' ) ) {
+	require( 'adodb.inc.php' );
+	require( 'adodb-datadict.inc.php' );
+}
+
+/**
+* Abstract DB Object. This class provides basic methods for database objects, such
+* as tables and indexes.
+*
+* @package axmls
+* @access private
+*/
+class dbObject {
+	
+	/**
+	* var object Parent
+	*/
+	var $parent;
+	
+	/**
+	* var string current element
+	*/
+	var $currentElement;
+	
+	/**
+	* NOP
+	*/
+	function dbObject( &$parent, $attributes = NULL ) {
+		$this->parent =& $parent;
+	}
+	
+	/**
+	* XML Callback to process start elements
+	*
+	* @access private
+	*/
+	function _tag_open( &$parser, $tag, $attributes ) {
+		
+	}
+	
+	/**
+	* XML Callback to process CDATA elements
+	*
+	* @access private
+	*/
+	function _tag_cdata( &$parser, $cdata ) {
+		
+	}
+	
+	/**
+	* XML Callback to process end elements
+	*
+	* @access private
+	*/
+	function _tag_close( &$parser, $tag ) {
+		
+	}
+	
+	function create() {
+		return array();
+	}
+	
+	/**
+	* Destroys the object
+	*/
+	function destroy() {
+		unset( $this );
+	}
+	
+	/**
+	* Checks whether the specified RDBMS is supported by the current
+	* database object or its ranking ancestor.
+	*
+	* @param string $platform RDBMS platform name (from ADODB platform list).
+	* @return boolean TRUE if RDBMS is supported; otherwise returns FALSE.
+	*/
+	function supportedPlatform( $platform = NULL ) {
+		return is_object( $this->parent ) ? $this->parent->supportedPlatform( $platform ) : TRUE;
+	}
+	
+	/**
+	* Returns the prefix set by the ranking ancestor of the database object.
+	*
+	* @param string $name Prefix string.
+	* @return string Prefix.
+	*/
+	function prefix( $name = '' ) {
+		return is_object( $this->parent ) ? $this->parent->prefix( $name ) : $name;
+	}
+	
+	/**
+	* Extracts a field ID from the specified field.
+	*
+	* @param string $field Field.
+	* @return string Field ID.
+	*/
+	function FieldID( $field ) {
+		return strtoupper( preg_replace( '/^`(.+)`$/', '$1', $field ) );
+	}
+}
+
+/**
+* Creates a table object in ADOdb's datadict format
+*
+* This class stores information about a database table. As charactaristics
+* of the table are loaded from the external source, methods and properties
+* of this class are used to build up the table description in ADOdb's
+* datadict format.
+*
+* @package axmls
+* @access private
+*/
+class dbTable extends dbObject {
+	
+	/**
+	* @var string Table name
+	*/
+	var $name;
+	
+	/**
+	* @var array Field specifier: Meta-information about each field
+	*/
+	var $fields = array();
+	
+	/**
+	* @var array List of table indexes.
+	*/
+	var $indexes = array();
+	
+	/**
+	* @var array Table options: Table-level options
+	*/
+	var $opts = array();
+	
+	/**
+	* @var string Field index: Keeps track of which field is currently being processed
+	*/
+	var $current_field;
+	
+	/**
+	* @var boolean Mark table for destruction
+	* @access private
+	*/
+	var $drop_table;
+	
+	/**
+	* @var boolean Mark field for destruction (not yet implemented)
+	* @access private
+	*/
+	var $drop_field = array();
+	
+	/**
+	* Iniitializes a new table object.
+	*
+	* @param string $prefix DB Object prefix
+	* @param array $attributes Array of table attributes.
+	*/
+	function dbTable( &$parent, $attributes = NULL ) {
+		$this->parent =& $parent;
+		$this->name = $this->prefix($attributes['NAME']);
+	}
+	
+	/**
+	* XML Callback to process start elements. Elements currently 
+	* processed are: INDEX, DROP, FIELD, KEY, NOTNULL, AUTOINCREMENT & DEFAULT. 
+	*
+	* @access private
+	*/
+	function _tag_open( &$parser, $tag, $attributes ) {
+		$this->currentElement = strtoupper( $tag );
+		
+		switch( $this->currentElement ) {
+			case 'INDEX':
+				if( !isset( $attributes['PLATFORM'] ) OR $this->supportedPlatform( $attributes['PLATFORM'] ) ) {
+					xml_set_object( $parser, $this->addIndex( $attributes ) );
+				}
+				break;
+			case 'DATA':
+				if( !isset( $attributes['PLATFORM'] ) OR $this->supportedPlatform( $attributes['PLATFORM'] ) ) {
+					xml_set_object( $parser, $this->addData( $attributes ) );
+				}
+				break;
+			case 'DROP':
+				$this->drop();
+				break;
+			case 'FIELD':
+				// Add a field
+				$fieldName = $attributes['NAME'];
+				$fieldType = $attributes['TYPE'];
+				$fieldSize = isset( $attributes['SIZE'] ) ? $attributes['SIZE'] : NULL;
+				$fieldOpts = isset( $attributes['OPTS'] ) ? $attributes['OPTS'] : NULL;
+				
+				$this->addField( $fieldName, $fieldType, $fieldSize, $fieldOpts );
+				break;
+			case 'KEY':
+			case 'NOTNULL':
+			case 'AUTOINCREMENT':
+				// Add a field option
+				$this->addFieldOpt( $this->current_field, $this->currentElement );
+				break;
+			case 'DEFAULT':
+				// Add a field option to the table object
+				
+				// Work around ADOdb datadict issue that misinterprets empty strings.
+				if( $attributes['VALUE'] == '' ) {
+					$attributes['VALUE'] = " '' ";
+				}
+				
+				$this->addFieldOpt( $this->current_field, $this->currentElement, $attributes['VALUE'] );
+				break;
+			case 'DEFDATE':
+			case 'DEFTIMESTAMP':
+				// Add a field option to the table object
+				$this->addFieldOpt( $this->current_field, $this->currentElement );
+				break;
+			default:
+				// print_r( array( $tag, $attributes ) );
+		}
+	}
+	
+	/**
+	* XML Callback to process CDATA elements
+	*
+	* @access private
+	*/
+	function _tag_cdata( &$parser, $cdata ) {
+		switch( $this->currentElement ) {
+			// Table constraint
+			case 'CONSTRAINT':
+				if( isset( $this->current_field ) ) {
+					$this->addFieldOpt( $this->current_field, $this->currentElement, $cdata );
+				} else {
+					$this->addTableOpt( $cdata );
+				}
+				break;
+			// Table option
+			case 'OPT':
+				$this->addTableOpt( $cdata );
+				break;
+			default:
+				
+		}
+	}
+	
+	/**
+	* XML Callback to process end elements
+	*
+	* @access private
+	*/
+	function _tag_close( &$parser, $tag ) {
+		$this->currentElement = '';
+		
+		switch( strtoupper( $tag ) ) {
+			case 'TABLE':
+				$this->parent->addSQL( $this->create( $this->parent ) );
+				xml_set_object( $parser, $this->parent );
+				$this->destroy();
+				break;
+			case 'FIELD':
+				unset($this->current_field);
+				break;
+
+		}
+	}
+	
+	/**
+	* Adds an index to a table object
+	*
+	* @param array $attributes Index attributes
+	* @return object dbIndex object
+	*/
+	function &addIndex( $attributes ) {
+		$name = strtoupper( $attributes['NAME'] );
+		$this->indexes[$name] =& new dbIndex( $this, $attributes );
+		return $this->indexes[$name];
+	}
+	
+	/**
+	* Adds data to a table object
+	*
+	* @param array $attributes Data attributes
+	* @return object dbData object
+	*/
+	function &addData( $attributes ) {
+		if( !isset( $this->data ) ) {
+			$this->data =& new dbData( $this, $attributes );
+		}
+		return $this->data;
+	}
+	
+	/**
+	* Adds a field to a table object
+	*
+	* $name is the name of the table to which the field should be added. 
+	* $type is an ADODB datadict field type. The following field types
+	* are supported as of ADODB 3.40:
+	* 	- C:  varchar
+	*	- X:  CLOB (character large object) or largest varchar size
+	*	   if CLOB is not supported
+	*	- C2: Multibyte varchar
+	*	- X2: Multibyte CLOB
+	*	- B:  BLOB (binary large object)
+	*	- D:  Date (some databases do not support this, and we return a datetime type)
+	*	- T:  Datetime or Timestamp
+	*	- L:  Integer field suitable for storing booleans (0 or 1)
+	*	- I:  Integer (mapped to I4)
+	*	- I1: 1-byte integer
+	*	- I2: 2-byte integer
+	*	- I4: 4-byte integer
+	*	- I8: 8-byte integer
+	*	- F:  Floating point number
+	*	- N:  Numeric or decimal number
+	*
+	* @param string $name Name of the table to which the field will be added.
+	* @param string $type	ADODB datadict field type.
+	* @param string $size	Field size
+	* @param array $opts	Field options array
+	* @return array Field specifier array
+	*/
+	function addField( $name, $type, $size = NULL, $opts = NULL ) {
+		$field_id = $this->FieldID( $name );
+		
+		// Set the field index so we know where we are
+		$this->current_field = $field_id;
+		
+		// Set the field name (required)
+		$this->fields[$field_id]['NAME'] = $name;
+		
+		// Set the field type (required)
+		$this->fields[$field_id]['TYPE'] = $type;
+		
+		// Set the field size (optional)
+		if( isset( $size ) ) {
+			$this->fields[$field_id]['SIZE'] = $size;
+		}
+		
+		// Set the field options
+		if( isset( $opts ) ) {
+			$this->fields[$field_id]['OPTS'][] = $opts;
+		}
+	}
+	
+	/**
+	* Adds a field option to the current field specifier
+	*
+	* This method adds a field option allowed by the ADOdb datadict 
+	* and appends it to the given field.
+	*
+	* @param string $field	Field name
+	* @param string $opt ADOdb field option
+	* @param mixed $value Field option value
+	* @return array Field specifier array
+	*/
+	function addFieldOpt( $field, $opt, $value = NULL ) {
+		if( !isset( $value ) ) {
+			$this->fields[$this->FieldID( $field )]['OPTS'][] = $opt;
+		// Add the option and value
+		} else {
+			$this->fields[$this->FieldID( $field )]['OPTS'][] = array( $opt => $value );
+		}
+	}
+	
+	/**
+	* Adds an option to the table
+	*
+	* This method takes a comma-separated list of table-level options
+	* and appends them to the table object.
+	*
+	* @param string $opt Table option
+	* @return array Options
+	*/
+	function addTableOpt( $opt ) {
+		$this->opts[] = $opt;
+		
+		return $this->opts;
+	}
+	
+	/**
+	* Generates the SQL that will create the table in the database
+	*
+	* @param object $xmls adoSchema object
+	* @return array Array containing table creation SQL
+	*/
+	function create( &$xmls ) {
+		$sql = array();
+		
+		// drop any existing indexes
+		if( is_array( $legacy_indexes = $xmls->dict->MetaIndexes( $this->name ) ) ) {
+			foreach( $legacy_indexes as $index => $index_details ) {
+				$sql[] = $xmls->dict->DropIndexSQL( $index, $this->name );
+			}
+		}
+		
+		// remove fields to be dropped from table object
+		foreach( $this->drop_field as $field ) {
+			unset( $this->fields[$field] );
+		}
+		
+		// if table exists
+		if( is_array( $legacy_fields = $xmls->dict->MetaColumns( $this->name ) ) ) {
+			// drop table
+			if( $this->drop_table ) {
+				$sql[] = $xmls->dict->DropTableSQL( $this->name );
+				
+				return $sql;
+			}
+			
+			// drop any existing fields not in schema
+			foreach( $legacy_fields as $field_id => $field ) {
+				if( !isset( $this->fields[$field_id] ) ) {
+					$sql[] = $xmls->dict->DropColumnSQL( $this->name, '`'.$field->name.'`' );
+				}
+			}
+		// if table doesn't exist
+		} else {
+			if( $this->drop_table ) {
+				return $sql;
+			}
+			
+			$legacy_fields = array();
+		}
+		
+		// Loop through the field specifier array, building the associative array for the field options
+		$fldarray = array();
+		
+		foreach( $this->fields as $field_id => $finfo ) {
+			// Set an empty size if it isn't supplied
+			if( !isset( $finfo['SIZE'] ) ) {
+				$finfo['SIZE'] = '';
+			}
+			
+			// Initialize the field array with the type and size
+			$fldarray[$field_id] = array(
+				'NAME' => $finfo['NAME'],
+				'TYPE' => $finfo['TYPE'],
+				'SIZE' => $finfo['SIZE']
+			);
+			
+			// Loop through the options array and add the field options. 
+			if( isset( $finfo['OPTS'] ) ) {
+				foreach( $finfo['OPTS'] as $opt ) {
+					// Option has an argument.
+					if( is_array( $opt ) ) {
+						$key = key( $opt );
+						$value = $opt[key( $opt )];
+						@$fldarray[$field_id][$key] .= $value;
+					// Option doesn't have arguments
+					} else {
+						$fldarray[$field_id][$opt] = $opt;
+					}
+				}
+			}
+		}
+		
+		if( empty( $legacy_fields ) ) {
+			// Create the new table
+			$sql[] = $xmls->dict->CreateTableSQL( $this->name, $fldarray, $this->opts );
+			logMsg( end( $sql ), 'Generated CreateTableSQL' );
+		} else {
+			// Upgrade an existing table
+			logMsg( "Upgrading {$this->name} using '{$xmls->upgrade}'" );
+			switch( $xmls->upgrade ) {
+				// Use ChangeTableSQL
+				case 'ALTER':
+					logMsg( 'Generated ChangeTableSQL (ALTERing table)' );
+					$sql[] = $xmls->dict->ChangeTableSQL( $this->name, $fldarray, $this->opts );
+					break;
+				case 'REPLACE':
+					logMsg( 'Doing upgrade REPLACE (testing)' );
+					$sql[] = $xmls->dict->DropTableSQL( $this->name );
+					$sql[] = $xmls->dict->CreateTableSQL( $this->name, $fldarray, $this->opts );
+					break;
+				// ignore table
+				default:
+					return array();
+			}
+		}
+		
+		foreach( $this->indexes as $index ) {
+			$sql[] = $index->create( $xmls );
+		}
+		
+		if( isset( $this->data ) ) {
+			$sql[] = $this->data->create( $xmls );
+		}
+		
+		return $sql;
+	}
+	
+	/**
+	* Marks a field or table for destruction
+	*/
+	function drop() {
+		if( isset( $this->current_field ) ) {
+			// Drop the current field
+			logMsg( "Dropping field '{$this->current_field}' from table '{$this->name}'" );
+			// $this->drop_field[$this->current_field] = $xmls->dict->DropColumnSQL( $this->name, $this->current_field );
+			$this->drop_field[$this->current_field] = $this->current_field;
+		} else {
+			// Drop the current table
+			logMsg( "Dropping table '{$this->name}'" );
+			// $this->drop_table = $xmls->dict->DropTableSQL( $this->name );
+			$this->drop_table = TRUE;
+		}
+	}
+}
+
+/**
+* Creates an index object in ADOdb's datadict format
+*
+* This class stores information about a database index. As charactaristics
+* of the index are loaded from the external source, methods and properties
+* of this class are used to build up the index description in ADOdb's
+* datadict format.
+*
+* @package axmls
+* @access private
+*/
+class dbIndex extends dbObject {
+	
+	/**
+	* @var string	Index name
+	*/
+	var $name;
+	
+	/**
+	* @var array	Index options: Index-level options
+	*/
+	var $opts = array();
+	
+	/**
+	* @var array	Indexed fields: Table columns included in this index
+	*/
+	var $columns = array();
+	
+	/**
+	* @var boolean Mark index for destruction
+	* @access private
+	*/
+	var $drop = FALSE;
+	
+	/**
+	* Initializes the new dbIndex object.
+	*
+	* @param object $parent Parent object
+	* @param array $attributes Attributes
+	*
+	* @internal
+	*/
+	function dbIndex( &$parent, $attributes = NULL ) {
+		$this->parent =& $parent;
+		
+		$this->name = $this->prefix ($attributes['NAME']);
+	}
+	
+	/**
+	* XML Callback to process start elements
+	*
+	* Processes XML opening tags. 
+	* Elements currently processed are: DROP, CLUSTERED, BITMAP, UNIQUE, FULLTEXT & HASH. 
+	*
+	* @access private
+	*/
+	function _tag_open( &$parser, $tag, $attributes ) {
+		$this->currentElement = strtoupper( $tag );
+		
+		switch( $this->currentElement ) {
+			case 'DROP':
+				$this->drop();
+				break;
+			case 'CLUSTERED':
+			case 'BITMAP':
+			case 'UNIQUE':
+			case 'FULLTEXT':
+			case 'HASH':
+				// Add index Option
+				$this->addIndexOpt( $this->currentElement );
+				break;
+			default:
+				// print_r( array( $tag, $attributes ) );
+		}
+	}
+	
+	/**
+	* XML Callback to process CDATA elements
+	*
+	* Processes XML cdata.
+	*
+	* @access private
+	*/
+	function _tag_cdata( &$parser, $cdata ) {
+		switch( $this->currentElement ) {
+			// Index field name
+			case 'COL':
+				$this->addField( $cdata );
+				break;
+			default:
+				
+		}
+	}
+	
+	/**
+	* XML Callback to process end elements
+	*
+	* @access private
+	*/
+	function _tag_close( &$parser, $tag ) {
+		$this->currentElement = '';
+		
+		switch( strtoupper( $tag ) ) {
+			case 'INDEX':
+				xml_set_object( $parser, $this->parent );
+				break;
+		}
+	}
+	
+	/**
+	* Adds a field to the index
+	*
+	* @param string $name Field name
+	* @return string Field list
+	*/
+	function addField( $name ) {
+		$this->columns[$this->FieldID( $name )] = $name;
+		
+		// Return the field list
+		return $this->columns;
+	}
+	
+	/**
+	* Adds options to the index
+	*
+	* @param string $opt Comma-separated list of index options.
+	* @return string Option list
+	*/
+	function addIndexOpt( $opt ) {
+		$this->opts[] = $opt;
+		
+		// Return the options list
+		return $this->opts;
+	}
+	
+	/**
+	* Generates the SQL that will create the index in the database
+	*
+	* @param object $xmls adoSchema object
+	* @return array Array containing index creation SQL
+	*/
+	function create( &$xmls ) {
+		if( $this->drop ) {
+			return NULL;
+		}
+		
+		// eliminate any columns that aren't in the table
+		foreach( $this->columns as $id => $col ) {
+			if( !isset( $this->parent->fields[$id] ) ) {
+				unset( $this->columns[$id] );
+			}
+		}
+		
+		return $xmls->dict->CreateIndexSQL( $this->name, $this->parent->name, $this->columns, $this->opts );
+	}
+	
+	/**
+	* Marks an index for destruction
+	*/
+	function drop() {
+		$this->drop = TRUE;
+	}
+}
+
+/**
+* Creates a data object in ADOdb's datadict format
+*
+* This class stores information about table data.
+*
+* @package axmls
+* @access private
+*/
+class dbData extends dbObject {
+	
+	var $data = array();
+	
+	var $row;
+	
+	/**
+	* Initializes the new dbIndex object.
+	*
+	* @param object $parent Parent object
+	* @param array $attributes Attributes
+	*
+	* @internal
+	*/
+	function dbData( &$parent, $attributes = NULL ) {
+		$this->parent =& $parent;
+	}
+	
+	/**
+	* XML Callback to process start elements
+	*
+	* Processes XML opening tags. 
+	* Elements currently processed are: DROP, CLUSTERED, BITMAP, UNIQUE, FULLTEXT & HASH. 
+	*
+	* @access private
+	*/
+	function _tag_open( &$parser, $tag, $attributes ) {
+		$this->currentElement = strtoupper( $tag );
+		
+		switch( $this->currentElement ) {
+			case 'ROW':
+				$this->row = count( $this->data );
+				$this->data[$this->row] = array();
+				break;
+			case 'F':
+				$this->addField($attributes);
+			default:
+				// print_r( array( $tag, $attributes ) );
+		}
+	}
+	
+	/**
+	* XML Callback to process CDATA elements
+	*
+	* Processes XML cdata.
+	*
+	* @access private
+	*/
+	function _tag_cdata( &$parser, $cdata ) {
+		switch( $this->currentElement ) {
+			// Index field name
+			case 'F':
+				$this->addData( $cdata );
+				break;
+			default:
+				
+		}
+	}
+	
+	/**
+	* XML Callback to process end elements
+	*
+	* @access private
+	*/
+	function _tag_close( &$parser, $tag ) {
+		$this->currentElement = '';
+		
+		switch( strtoupper( $tag ) ) {
+			case 'DATA':
+				xml_set_object( $parser, $this->parent );
+				break;
+		}
+	}
+	
+	/**
+	* Adds a field to the index
+	*
+	* @param string $name Field name
+	* @return string Field list
+	*/
+	function addField( $attributes ) {
+		if( isset( $attributes['NAME'] ) ) {
+			$name = $attributes['NAME'];
+		} else {
+			$name = count($this->data[$this->row]);
+		}
+		
+		// Set the field index so we know where we are
+		$this->current_field = $this->FieldID( $name );
+	}
+	
+	/**
+	* Adds options to the index
+	*
+	* @param string $opt Comma-separated list of index options.
+	* @return string Option list
+	*/
+	function addData( $cdata ) {
+		if( !isset( $this->data[$this->row] ) ) {
+			$this->data[$this->row] = array();
+		}
+		
+		if( !isset( $this->data[$this->row][$this->current_field] ) ) {
+			$this->data[$this->row][$this->current_field] = '';
+		}
+		
+		$this->data[$this->row][$this->current_field] .= $cdata;
+	}
+	
+	/**
+	* Generates the SQL that will create the index in the database
+	*
+	* @param object $xmls adoSchema object
+	* @return array Array containing index creation SQL
+	*/
+	function create( &$xmls ) {
+		$table = $xmls->dict->TableName($this->parent->name);
+		$table_field_count = count($this->parent->fields);
+		$sql = array();
+		
+		// eliminate any columns that aren't in the table
+		foreach( $this->data as $row ) {
+			$table_fields = $this->parent->fields;
+			$fields = array();
+			
+			foreach( $row as $field_id => $field_data ) {
+				if( !array_key_exists( $field_id, $table_fields ) ) {
+					if( is_numeric( $field_id ) ) {
+						$field_id = reset( array_keys( $table_fields ) );
+					} else {
+						continue;
+					}
+				}
+				
+				$name = $table_fields[$field_id]['NAME'];
+				
+				switch( $table_fields[$field_id]['TYPE'] ) {
+					case 'C':
+					case 'C2':
+					case 'X':
+					case 'X2':
+						$fields[$name] = $xmls->db->qstr( $field_data );
+						break;
+					case 'I':
+					case 'I1':
+					case 'I2':
+					case 'I4':
+					case 'I8':
+						$fields[$name] = intval($field_data);
+						break;
+					default:
+						$fields[$name] = $field_data;
+				}
+				
+				unset($table_fields[$field_id]);
+			}
+			
+			// check that at least 1 column is specified
+			if( empty( $fields ) ) {
+				continue;
+			}
+			
+			// check that no required columns are missing
+			if( count( $fields ) < $table_field_count ) {
+				foreach( $table_fields as $field ) {
+					if (isset( $field['OPTS'] ))
+						if( ( in_array( 'NOTNULL', $field['OPTS'] ) || in_array( 'KEY', $field['OPTS'] ) ) && !in_array( 'AUTOINCREMENT', $field['OPTS'] ) ) {
+							continue(2);
+						}
+				}
+			}
+			
+			$sql[] = 'INSERT INTO '. $table .' ('. implode( ',', array_keys( $fields ) ) .') VALUES ('. implode( ',', $fields ) .')';
+		}
+		
+		return $sql;
+	}
+}
+
+/**
+* Creates the SQL to execute a list of provided SQL queries
+*
+* @package axmls
+* @access private
+*/
+class dbQuerySet extends dbObject {
+	
+	/**
+	* @var array	List of SQL queries
+	*/
+	var $queries = array();
+	
+	/**
+	* @var string	String used to build of a query line by line
+	*/
+	var $query;
+	
+	/**
+	* @var string	Query prefix key
+	*/
+	var $prefixKey = '';
+	
+	/**
+	* @var boolean	Auto prefix enable (TRUE)
+	*/
+	var $prefixMethod = 'AUTO';
+	
+	/**
+	* Initializes the query set.
+	*
+	* @param object $parent Parent object
+	* @param array $attributes Attributes
+	*/
+	function dbQuerySet( &$parent, $attributes = NULL ) {
+		$this->parent =& $parent;
+			
+		// Overrides the manual prefix key
+		if( isset( $attributes['KEY'] ) ) {
+			$this->prefixKey = $attributes['KEY'];
+		}
+		
+		$prefixMethod = isset( $attributes['PREFIXMETHOD'] ) ? strtoupper( trim( $attributes['PREFIXMETHOD'] ) ) : '';
+		
+		// Enables or disables automatic prefix prepending
+		switch( $prefixMethod ) {
+			case 'AUTO':
+				$this->prefixMethod = 'AUTO';
+				break;
+			case 'MANUAL':
+				$this->prefixMethod = 'MANUAL';
+				break;
+			case 'NONE':
+				$this->prefixMethod = 'NONE';
+				break;
+		}
+	}
+	
+	/**
+	* XML Callback to process start elements. Elements currently 
+	* processed are: QUERY. 
+	*
+	* @access private
+	*/
+	function _tag_open( &$parser, $tag, $attributes ) {
+		$this->currentElement = strtoupper( $tag );
+		
+		switch( $this->currentElement ) {
+			case 'QUERY':
+				// Create a new query in a SQL queryset.
+				// Ignore this query set if a platform is specified and it's different than the 
+				// current connection platform.
+				if( !isset( $attributes['PLATFORM'] ) OR $this->supportedPlatform( $attributes['PLATFORM'] ) ) {
+					$this->newQuery();
+				} else {
+					$this->discardQuery();
+				}
+				break;
+			default:
+				// print_r( array( $tag, $attributes ) );
+		}
+	}
+	
+	/**
+	* XML Callback to process CDATA elements
+	*/
+	function _tag_cdata( &$parser, $cdata ) {
+		switch( $this->currentElement ) {
+			// Line of queryset SQL data
+			case 'QUERY':
+				$this->buildQuery( $cdata );
+				break;
+			default:
+				
+		}
+	}
+	
+	/**
+	* XML Callback to process end elements
+	*
+	* @access private
+	*/
+	function _tag_close( &$parser, $tag ) {
+		$this->currentElement = '';
+		
+		switch( strtoupper( $tag ) ) {
+			case 'QUERY':
+				// Add the finished query to the open query set.
+				$this->addQuery();
+				break;
+			case 'SQL':
+				$this->parent->addSQL( $this->create( $this->parent ) );
+				xml_set_object( $parser, $this->parent );
+				$this->destroy();
+				break;
+			default:
+				
+		}
+	}
+	
+	/**
+	* Re-initializes the query.
+	*
+	* @return boolean TRUE
+	*/
+	function newQuery() {
+		$this->query = '';
+		
+		return TRUE;
+	}
+	
+	/**
+	* Discards the existing query.
+	*
+	* @return boolean TRUE
+	*/
+	function discardQuery() {
+		unset( $this->query );
+		
+		return TRUE;
+	}
+	
+	/** 
+	* Appends a line to a query that is being built line by line
+	*
+	* @param string $data Line of SQL data or NULL to initialize a new query
+	* @return string SQL query string.
+	*/
+	function buildQuery( $sql = NULL ) {
+		if( !isset( $this->query ) OR empty( $sql ) ) {
+			return FALSE;
+		}
+		
+		$this->query .= $sql;
+		
+		return $this->query;
+	}
+	
+	/**
+	* Adds a completed query to the query list
+	*
+	* @return string	SQL of added query
+	*/
+	function addQuery() {
+		if( !isset( $this->query ) ) {
+			return FALSE;
+		}
+		
+		$this->queries[] = $return = trim($this->query);
+		
+		unset( $this->query );
+		
+		return $return;
+	}
+	
+	/**
+	* Creates and returns the current query set
+	*
+	* @param object $xmls adoSchema object
+	* @return array Query set
+	*/
+	function create( &$xmls ) {
+		foreach( $this->queries as $id => $query ) {
+			switch( $this->prefixMethod ) {
+				case 'AUTO':
+					// Enable auto prefix replacement
+					
+					// Process object prefix.
+					// Evaluate SQL statements to prepend prefix to objects
+					$query = $this->prefixQuery( '/^\s*((?is)INSERT\s+(INTO\s+)?)((\w+\s*,?\s*)+)(\s.*$)/', $query, $xmls->objectPrefix );
+					$query = $this->prefixQuery( '/^\s*((?is)UPDATE\s+(FROM\s+)?)((\w+\s*,?\s*)+)(\s.*$)/', $query, $xmls->objectPrefix );
+					$query = $this->prefixQuery( '/^\s*((?is)DELETE\s+(FROM\s+)?)((\w+\s*,?\s*)+)(\s.*$)/', $query, $xmls->objectPrefix );
+					
+					// SELECT statements aren't working yet
+					#$data = preg_replace( '/(?ias)(^\s*SELECT\s+.*\s+FROM)\s+(\W\s*,?\s*)+((?i)\s+WHERE.*$)/', "\1 $prefix\2 \3", $data );
+					
+				case 'MANUAL':
+					// If prefixKey is set and has a value then we use it to override the default constant XMLS_PREFIX.
+					// If prefixKey is not set, we use the default constant XMLS_PREFIX
+					if( isset( $this->prefixKey ) AND( $this->prefixKey !== '' ) ) {
+						// Enable prefix override
+						$query = str_replace( $this->prefixKey, $xmls->objectPrefix, $query );
+					} else {
+						// Use default replacement
+						$query = str_replace( XMLS_PREFIX , $xmls->objectPrefix, $query );
+					}
+			}
+			
+			$this->queries[$id] = trim( $query );
+		}
+		
+		// Return the query set array
+		return $this->queries;
+	}
+	
+	/**
+	* Rebuilds the query with the prefix attached to any objects
+	*
+	* @param string $regex Regex used to add prefix
+	* @param string $query SQL query string
+	* @param string $prefix Prefix to be appended to tables, indices, etc.
+	* @return string Prefixed SQL query string.
+	*/
+	function prefixQuery( $regex, $query, $prefix = NULL ) {
+		if( !isset( $prefix ) ) {
+			return $query;
+		}
+		
+		if( preg_match( $regex, $query, $match ) ) {
+			$preamble = $match[1];
+			$postamble = $match[5];
+			$objectList = explode( ',', $match[3] );
+			// $prefix = $prefix . '_';
+			
+			$prefixedList = '';
+			
+			foreach( $objectList as $object ) {
+				if( $prefixedList !== '' ) {
+					$prefixedList .= ', ';
+				}
+				
+				$prefixedList .= $prefix . trim( $object );
+			}
+			
+			$query = $preamble . ' ' . $prefixedList . ' ' . $postamble;
+		}
+		
+		return $query;
+	}
+}
+
+/**
+* Loads and parses an XML file, creating an array of "ready-to-run" SQL statements
+* 
+* This class is used to load and parse the XML file, to create an array of SQL statements
+* that can be used to build a database, and to build the database using the SQL array.
+*
+* @tutorial getting_started.pkg
+*
+* @author Richard Tango-Lowy & Dan Cech
+* @version $Revision: 350 $
+*
+* @package axmls
+*/
+class adoSchema {
+	
+	/**
+	* @var array	Array containing SQL queries to generate all objects
+	* @access private
+	*/
+	var $sqlArray;
+	
+	/**
+	* @var object	ADOdb connection object
+	* @access private
+	*/
+	var $db;
+	
+	/**
+	* @var object	ADOdb Data Dictionary
+	* @access private
+	*/
+	var $dict;
+	
+	/**
+	* @var string Current XML element
+	* @access private
+	*/
+	var $currentElement = '';
+	
+	/**
+	* @var string If set (to 'ALTER' or 'REPLACE'), upgrade an existing database
+	* @access private
+	*/
+	var $upgrade = '';
+	
+	/**
+	* @var string Optional object prefix
+	* @access private
+	*/
+	var $objectPrefix = '';
+	
+	/**
+	* @var long	Original Magic Quotes Runtime value
+	* @access private
+	*/
+	var $mgq;
+	
+	/**
+	* @var long	System debug
+	* @access private
+	*/
+	var $debug;
+	
+	/**
+	* @var string Regular expression to find schema version
+	* @access private
+	*/
+	var $versionRegex = '/<schema.*?( version="([^"]*)")?.*?>/';
+	
+	/**
+	* @var string Current schema version
+	* @access private
+	*/
+	var $schemaVersion;
+	
+	/**
+	* @var int	Success of last Schema execution
+	*/
+	var $success;
+	
+	/**
+	* @var bool	Execute SQL inline as it is generated
+	*/
+	var $executeInline;
+	
+	/**
+	* @var bool	Continue SQL execution if errors occur
+	*/
+	var $continueOnError;
+	
+	/**
+	* Creates an adoSchema object
+	*
+	* Creating an adoSchema object is the first step in processing an XML schema.
+	* The only parameter is an ADOdb database connection object, which must already
+	* have been created.
+	*
+	* @param object $db ADOdb database connection object.
+	*/
+	function adoSchema( &$db ) {
+		// Initialize the environment
+		$this->mgq = get_magic_quotes_runtime();
+		set_magic_quotes_runtime(0);
+		
+		$this->db =& $db;
+		$this->debug = $this->db->debug;
+		$this->dict = NewDataDictionary( $this->db );
+		$this->sqlArray = array();
+		$this->schemaVersion = XMLS_SCHEMA_VERSION;
+		$this->executeInline( XMLS_EXECUTE_INLINE );
+		$this->continueOnError( XMLS_CONTINUE_ON_ERROR );
+		$this->setUpgradeMethod();
+	}
+	
+	/**
+	* Sets the method to be used for upgrading an existing database
+	*
+	* Use this method to specify how existing database objects should be upgraded.
+	* The method option can be set to ALTER, REPLACE, BEST, or NONE. ALTER attempts to
+	* alter each database object directly, REPLACE attempts to rebuild each object
+	* from scratch, BEST attempts to determine the best upgrade method for each
+	* object, and NONE disables upgrading.
+	*
+	* This method is not yet used by AXMLS, but exists for backward compatibility.
+	* The ALTER method is automatically assumed when the adoSchema object is
+	* instantiated; other upgrade methods are not currently supported.
+	*
+	* @param string $method Upgrade method (ALTER|REPLACE|BEST|NONE)
+	* @returns string Upgrade method used
+	*/
+	function SetUpgradeMethod( $method = '' ) {
+		if( !is_string( $method ) ) {
+			return FALSE;
+		}
+		
+		$method = strtoupper( $method );
+		
+		// Handle the upgrade methods
+		switch( $method ) {
+			case 'ALTER':
+				$this->upgrade = $method;
+				break;
+			case 'REPLACE':
+				$this->upgrade = $method;
+				break;
+			case 'BEST':
+				$this->upgrade = 'ALTER';
+				break;
+			case 'NONE':
+				$this->upgrade = 'NONE';
+				break;
+			default:
+				// Use default if no legitimate method is passed.
+				$this->upgrade = XMLS_DEFAULT_UPGRADE_METHOD;
+		}
+		
+		return $this->upgrade;
+	}
+	
+	/**
+	* Enables/disables inline SQL execution.
+	*
+	* Call this method to enable or disable inline execution of the schema. If the mode is set to TRUE (inline execution),
+	* AXMLS applies the SQL to the database immediately as each schema entity is parsed. If the mode
+	* is set to FALSE (post execution), AXMLS parses the entire schema and you will need to call adoSchema::ExecuteSchema()
+	* to apply the schema to the database.
+	*
+	* @param bool $mode execute
+	* @return bool current execution mode
+	*
+	* @see ParseSchema(), ExecuteSchema()
+	*/
+	function ExecuteInline( $mode = NULL ) {
+		if( is_bool( $mode ) ) {
+			$this->executeInline = $mode;
+		}
+		
+		return $this->executeInline;
+	}
+	
+	/**
+	* Enables/disables SQL continue on error.
+	*
+	* Call this method to enable or disable continuation of SQL execution if an error occurs.
+	* If the mode is set to TRUE (continue), AXMLS will continue to apply SQL to the database, even if an error occurs.
+	* If the mode is set to FALSE (halt), AXMLS will halt execution of generated sql if an error occurs, though parsing
+	* of the schema will continue.
+	*
+	* @param bool $mode execute
+	* @return bool current continueOnError mode
+	*
+	* @see addSQL(), ExecuteSchema()
+	*/
+	function ContinueOnError( $mode = NULL ) {
+		if( is_bool( $mode ) ) {
+			$this->continueOnError = $mode;
+		}
+		
+		return $this->continueOnError;
+	}
+	
+	/**
+	* Loads an XML schema from a file and converts it to SQL.
+	*
+	* Call this method to load the specified schema (see the DTD for the proper format) from
+	* the filesystem and generate the SQL necessary to create the database described. 
+	* @see ParseSchemaString()
+	*
+	* @param string $file Name of XML schema file.
+	* @param bool $returnSchema Return schema rather than parsing.
+	* @return array Array of SQL queries, ready to execute
+	*/
+	function ParseSchema( $filename, $returnSchema = FALSE ) {
+		return $this->ParseSchemaString( $this->ConvertSchemaFile( $filename ), $returnSchema );
+	}
+	
+	/**
+	* Loads an XML schema from a file and converts it to SQL.
+	*
+	* Call this method to load the specified schema from a file (see the DTD for the proper format) 
+	* and generate the SQL necessary to create the database described by the schema.
+	*
+	* @param string $file Name of XML schema file.
+	* @param bool $returnSchema Return schema rather than parsing.
+	* @return array Array of SQL queries, ready to execute.
+	*
+	* @deprecated Replaced by adoSchema::ParseSchema() and adoSchema::ParseSchemaString()
+	* @see ParseSchema(), ParseSchemaString()
+	*/
+	function ParseSchemaFile( $filename, $returnSchema = FALSE ) {
+		// Open the file
+		if( !($fp = fopen( $filename, 'r' )) ) {
+			// die( 'Unable to open file' );
+			return FALSE;
+		}
+		
+		// do version detection here
+		if( $this->SchemaFileVersion( $filename ) != $this->schemaVersion ) {
+			return FALSE;
+		}
+		
+		if ( $returnSchema )
+		{
+			$xmlstring = '';
+			while( $data = fread( $fp, 100000 ) ) {
+				$xmlstring .= $data;
+			}
+			return $xmlstring;
+		}
+		
+		$this->success = 2;
+		
+		$xmlParser = $this->create_parser();
+		
+		// Process the file
+		while( $data = fread( $fp, 4096 ) ) {
+			if( !xml_parse( $xmlParser, $data, feof( $fp ) ) ) {
+				die( sprintf(
+					"XML error: %s at line %d",
+					xml_error_string( xml_get_error_code( $xmlParser) ),
+					xml_get_current_line_number( $xmlParser)
+				) );
+			}
+		}
+		
+		xml_parser_free( $xmlParser );
+		
+		return $this->sqlArray;
+	}
+	
+	/**
+	* Converts an XML schema string to SQL.
+	*
+	* Call this method to parse a string containing an XML schema (see the DTD for the proper format)
+	* and generate the SQL necessary to create the database described by the schema. 
+	* @see ParseSchema()
+	*
+	* @param string $xmlstring XML schema string.
+	* @param bool $returnSchema Return schema rather than parsing.
+	* @return array Array of SQL queries, ready to execute.
+	*/
+	function ParseSchemaString( $xmlstring, $returnSchema = FALSE ) {
+		if( !is_string( $xmlstring ) OR empty( $xmlstring ) ) {
+			return FALSE;
+		}
+		
+		// do version detection here
+		if( $this->SchemaStringVersion( $xmlstring ) != $this->schemaVersion ) {
+			return FALSE;
+		}
+		
+		if ( $returnSchema )
+		{
+			return $xmlstring;
+		}
+		
+		$this->success = 2;
+		
+		$xmlParser = $this->create_parser();
+		
+		if( !xml_parse( $xmlParser, $xmlstring, TRUE ) ) {
+			die( sprintf(
+				"XML error: %s at line %d",
+				xml_error_string( xml_get_error_code( $xmlParser) ),
+				xml_get_current_line_number( $xmlParser)
+			) );
+		}
+		
+		xml_parser_free( $xmlParser );
+		
+		return $this->sqlArray;
+	}
+	
+	/**
+	* Loads an XML schema from a file and converts it to uninstallation SQL.
+	*
+	* Call this method to load the specified schema (see the DTD for the proper format) from
+	* the filesystem and generate the SQL necessary to remove the database described.
+	* @see RemoveSchemaString()
+	*
+	* @param string $file Name of XML schema file.
+	* @param bool $returnSchema Return schema rather than parsing.
+	* @return array Array of SQL queries, ready to execute
+	*/
+	function RemoveSchema( $filename, $returnSchema = FALSE ) {
+		return $this->RemoveSchemaString( $this->ConvertSchemaFile( $filename ), $returnSchema );
+	}
+	
+	/**
+	* Converts an XML schema string to uninstallation SQL.
+	*
+	* Call this method to parse a string containing an XML schema (see the DTD for the proper format)
+	* and generate the SQL necessary to uninstall the database described by the schema. 
+	* @see RemoveSchema()
+	*
+	* @param string $schema XML schema string.
+	* @param bool $returnSchema Return schema rather than parsing.
+	* @return array Array of SQL queries, ready to execute.
+	*/
+	function RemoveSchemaString( $schema, $returnSchema = FALSE ) {
+		
+		// grab current version
+		if( !( $version = $this->SchemaStringVersion( $schema ) ) ) {
+			return FALSE;
+		}
+		
+		return $this->ParseSchemaString( $this->TransformSchema( $schema, 'remove-' . $version), $returnSchema );
+	}
+	
+	/**
+	* Applies the current XML schema to the database (post execution).
+	*
+	* Call this method to apply the current schema (generally created by calling 
+	* ParseSchema() or ParseSchemaString() ) to the database (creating the tables, indexes, 
+	* and executing other SQL specified in the schema) after parsing.
+	* @see ParseSchema(), ParseSchemaString(), ExecuteInline()
+	*
+	* @param array $sqlArray Array of SQL statements that will be applied rather than
+	*		the current schema.
+	* @param boolean $continueOnErr Continue to apply the schema even if an error occurs.
+	* @returns integer 0 if failure, 1 if errors, 2 if successful.
+	*/
+	function ExecuteSchema( $sqlArray = NULL, $continueOnErr =  NULL ) {
+		if( !is_bool( $continueOnErr ) ) {
+			$continueOnErr = $this->ContinueOnError();
+		}
+		
+		if( !isset( $sqlArray ) ) {
+			$sqlArray = $this->sqlArray;
+		}
+		
+		if( !is_array( $sqlArray ) ) {
+			$this->success = 0;
+		} else {
+			$this->success = $this->dict->ExecuteSQLArray( $sqlArray, $continueOnErr );
+		}
+		
+		return $this->success;
+	}
+	
+	/**
+	* Returns the current SQL array. 
+	*
+	* Call this method to fetch the array of SQL queries resulting from 
+	* ParseSchema() or ParseSchemaString(). 
+	*
+	* @param string $format Format: HTML, TEXT, or NONE (PHP array)
+	* @return array Array of SQL statements or FALSE if an error occurs
+	*/
+	function PrintSQL( $format = 'NONE' ) {
+		$sqlArray = null;
+		return $this->getSQL( $format, $sqlArray );
+	}
+	
+	/**
+	* Saves the current SQL array to the local filesystem as a list of SQL queries.
+	*
+	* Call this method to save the array of SQL queries (generally resulting from a
+	* parsed XML schema) to the filesystem.
+	*
+	* @param string $filename Path and name where the file should be saved.
+	* @return boolean TRUE if save is successful, else FALSE. 
+	*/
+	function SaveSQL( $filename = './schema.sql' ) {
+		
+		if( !isset( $sqlArray ) ) {
+			$sqlArray = $this->sqlArray;
+		}
+		if( !isset( $sqlArray ) ) {
+			return FALSE;
+		}
+		
+		$fp = fopen( $filename, "w" );
+		
+		foreach( $sqlArray as $key => $query ) {
+			fwrite( $fp, $query . ";\n" );
+		}
+		fclose( $fp );
+	}
+	
+	/**
+	* Create an xml parser
+	*
+	* @return object PHP XML parser object
+	*
+	* @access private
+	*/
+	function &create_parser() {
+		// Create the parser
+		$xmlParser = xml_parser_create();
+		xml_set_object( $xmlParser, $this );
+		
+		// Initialize the XML callback functions
+		xml_set_element_handler( $xmlParser, '_tag_open', '_tag_close' );
+		xml_set_character_data_handler( $xmlParser, '_tag_cdata' );
+		
+		return $xmlParser;
+	}
+	
+	/**
+	* XML Callback to process start elements
+	*
+	* @access private
+	*/
+	function _tag_open( &$parser, $tag, $attributes ) {
+		switch( strtoupper( $tag ) ) {
+			case 'TABLE':
+				$this->obj = new dbTable( $this, $attributes );
+				xml_set_object( $parser, $this->obj );
+				break;
+			case 'SQL':
+				if( !isset( $attributes['PLATFORM'] ) OR $this->supportedPlatform( $attributes['PLATFORM'] ) ) {
+					$this->obj = new dbQuerySet( $this, $attributes );
+					xml_set_object( $parser, $this->obj );
+				}
+				break;
+			default:
+				// print_r( array( $tag, $attributes ) );
+		}
+		
+	}
+	
+	/**
+	* XML Callback to process CDATA elements
+	*
+	* @access private
+	*/
+	function _tag_cdata( &$parser, $cdata ) {
+	}
+	
+	/**
+	* XML Callback to process end elements
+	*
+	* @access private
+	* @internal
+	*/
+	function _tag_close( &$parser, $tag ) {
+		
+	}
+	
+	/**
+	* Converts an XML schema string to the specified DTD version.
+	*
+	* Call this method to convert a string containing an XML schema to a different AXMLS
+	* DTD version. For instance, to convert a schema created for an pre-1.0 version for 
+	* AXMLS (DTD version 0.1) to a newer version of the DTD (e.g. 0.2). If no DTD version 
+	* parameter is specified, the schema will be converted to the current DTD version. 
+	* If the newFile parameter is provided, the converted schema will be written to the specified
+	* file.
+	* @see ConvertSchemaFile()
+	*
+	* @param string $schema String containing XML schema that will be converted.
+	* @param string $newVersion DTD version to convert to.
+	* @param string $newFile File name of (converted) output file.
+	* @return string Converted XML schema or FALSE if an error occurs.
+	*/
+	function ConvertSchemaString( $schema, $newVersion = NULL, $newFile = NULL ) {
+		
+		// grab current version
+		if( !( $version = $this->SchemaStringVersion( $schema ) ) ) {
+			return FALSE;
+		}
+		
+		if( !isset ($newVersion) ) {
+			$newVersion = $this->schemaVersion;
+		}
+		
+		if( $version == $newVersion ) {
+			$result = $schema;
+		} else {
+			$result = $this->TransformSchema( $schema, 'convert-' . $version . '-' . $newVersion);
+		}
+		
+		if( is_string( $result ) AND is_string( $newFile ) AND ( $fp = fopen( $newFile, 'w' ) ) ) {
+			fwrite( $fp, $result );
+			fclose( $fp );
+		}
+		
+		return $result;
+	}
+	
+	// compat for pre-4.3 - jlim
+	function _file_get_contents($path)
+	{
+		if (function_exists('file_get_contents')) return file_get_contents($path);
+		return join('',file($path));
+	}
+	
+	/**
+	* Converts an XML schema file to the specified DTD version.
+	*
+	* Call this method to convert the specified XML schema file to a different AXMLS
+	* DTD version. For instance, to convert a schema created for an pre-1.0 version for 
+	* AXMLS (DTD version 0.1) to a newer version of the DTD (e.g. 0.2). If no DTD version 
+	* parameter is specified, the schema will be converted to the current DTD version. 
+	* If the newFile parameter is provided, the converted schema will be written to the specified
+	* file.
+	* @see ConvertSchemaString()
+	*
+	* @param string $filename Name of XML schema file that will be converted.
+	* @param string $newVersion DTD version to convert to.
+	* @param string $newFile File name of (converted) output file.
+	* @return string Converted XML schema or FALSE if an error occurs.
+	*/
+	function ConvertSchemaFile( $filename, $newVersion = NULL, $newFile = NULL ) {
+		
+		// grab current version
+		if( !( $version = $this->SchemaFileVersion( $filename ) ) ) {
+			return FALSE;
+		}
+		
+		if( !isset ($newVersion) ) {
+			$newVersion = $this->schemaVersion;
+		}
+		
+		if( $version == $newVersion ) {
+			$result = _file_get_contents( $filename );
+			
+			// remove unicode BOM if present
+			if( substr( $result, 0, 3 ) == sprintf( '%c%c%c', 239, 187, 191 ) ) {
+				$result = substr( $result, 3 );
+			}
+		} else {
+			$result = $this->TransformSchema( $filename, 'convert-' . $version . '-' . $newVersion, 'file' );
+		}
+		
+		if( is_string( $result ) AND is_string( $newFile ) AND ( $fp = fopen( $newFile, 'w' ) ) ) {
+			fwrite( $fp, $result );
+			fclose( $fp );
+		}
+		
+		return $result;
+	}
+	
+	function TransformSchema( $schema, $xsl, $schematype='string' )
+	{
+		// Fail if XSLT extension is not available
+		if( ! function_exists( 'xslt_create' ) ) {
+			return FALSE;
+		}
+		
+		$xsl_file = dirname( __FILE__ ) . '/xsl/' . $xsl . '.xsl';
+		
+		// look for xsl
+		if( !is_readable( $xsl_file ) ) {
+			return FALSE;
+		}
+		
+		switch( $schematype )
+		{
+			case 'file':
+				if( !is_readable( $schema ) ) {
+					return FALSE;
+				}
+				
+				$schema = _file_get_contents( $schema );
+				break;
+			case 'string':
+			default:
+				if( !is_string( $schema ) ) {
+					return FALSE;
+				}
+		}
+		
+		$arguments = array (
+			'/_xml' => $schema,
+			'/_xsl' => _file_get_contents( $xsl_file )
+		);
+		
+		// create an XSLT processor
+		$xh = xslt_create ();
+		
+		// set error handler
+		xslt_set_error_handler ($xh, array (&$this, 'xslt_error_handler'));
+		
+		// process the schema
+		$result = xslt_process ($xh, 'arg:/_xml', 'arg:/_xsl', NULL, $arguments); 
+		
+		xslt_free ($xh);
+		
+		return $result;
+	}
+	
+	/**
+	* Processes XSLT transformation errors
+	*
+	* @param object $parser XML parser object
+	* @param integer $errno Error number
+	* @param integer $level Error level
+	* @param array $fields Error information fields
+	*
+	* @access private
+	*/
+	function xslt_error_handler( $parser, $errno, $level, $fields ) {
+		if( is_array( $fields ) ) {
+			$msg = array(
+				'Message Type' => ucfirst( $fields['msgtype'] ),
+				'Message Code' => $fields['code'],
+				'Message' => $fields['msg'],
+				'Error Number' => $errno,
+				'Level' => $level
+			);
+			
+			switch( $fields['URI'] ) {
+				case 'arg:/_xml':
+					$msg['Input'] = 'XML';
+					break;
+				case 'arg:/_xsl':
+					$msg['Input'] = 'XSL';
+					break;
+				default:
+					$msg['Input'] = $fields['URI'];
+			}
+			
+			$msg['Line'] = $fields['line'];
+		} else {
+			$msg = array(
+				'Message Type' => 'Error',
+				'Error Number' => $errno,
+				'Level' => $level,
+				'Fields' => var_export( $fields, TRUE )
+			);
+		}
+		
+		$error_details = $msg['Message Type'] . ' in XSLT Transformation' . "\n"
+					   . '<table>' . "\n";
+		
+		foreach( $msg as $label => $details ) {
+			$error_details .= '<tr><td><b>' . $label . ': </b></td><td>' . htmlentities( $details ) . '</td></tr>' . "\n";
+		}
+		
+		$error_details .= '</table>';
+		
+		trigger_error( $error_details, E_USER_ERROR );
+	}
+	
+	/**
+	* Returns the AXMLS Schema Version of the requested XML schema file.
+	*
+	* Call this method to obtain the AXMLS DTD version of the requested XML schema file.
+	* @see SchemaStringVersion()
+	*
+	* @param string $filename AXMLS schema file
+	* @return string Schema version number or FALSE on error
+	*/
+	function SchemaFileVersion( $filename ) {
+		// Open the file
+		if( !($fp = fopen( $filename, 'r' )) ) {
+			// die( 'Unable to open file' );
+			return FALSE;
+		}
+		
+		// Process the file
+		while( $data = fread( $fp, 4096 ) ) {
+			if( preg_match( $this->versionRegex, $data, $matches ) ) {
+				return !empty( $matches[2] ) ? $matches[2] : XMLS_DEFAULT_SCHEMA_VERSION;
+			}
+		}
+		
+		return FALSE;
+	}
+	
+	/**
+	* Returns the AXMLS Schema Version of the provided XML schema string.
+	*
+	* Call this method to obtain the AXMLS DTD version of the provided XML schema string.
+	* @see SchemaFileVersion()
+	*
+	* @param string $xmlstring XML schema string
+	* @return string Schema version number or FALSE on error
+	*/
+	function SchemaStringVersion( $xmlstring ) {
+		if( !is_string( $xmlstring ) OR empty( $xmlstring ) ) {
+			return FALSE;
+		}
+		
+		if( preg_match( $this->versionRegex, $xmlstring, $matches ) ) {
+			return !empty( $matches[2] ) ? $matches[2] : XMLS_DEFAULT_SCHEMA_VERSION;
+		}
+		
+		return FALSE;
+	}
+	
+	/**
+	* Extracts an XML schema from an existing database.
+	*
+	* Call this method to create an XML schema string from an existing database.
+	* If the data parameter is set to TRUE, AXMLS will include the data from the database
+	* in the schema. 
+	*
+	* @param boolean $data Include data in schema dump
+	* @return string Generated XML schema
+	*/
+	function ExtractSchema( $data = FALSE ) {
+		$old_mode = $this->db->SetFetchMode( ADODB_FETCH_NUM );
+		
+		$schema = '<?xml version="1.0"?>' . "\n"
+				. '<schema version="' . $this->schemaVersion . '">' . "\n";
+		
+		if( is_array( $tables = $this->db->MetaTables( 'TABLES' ) ) ) {
+			foreach( $tables as $table ) {
+				$schema .= '	<table name="' . $table . '">' . "\n";
+				
+				// grab details from database
+				$rs = $this->db->Execute( 'SELECT * FROM ' . $table . ' WHERE 1=1' );
+				$fields = $this->db->MetaColumns( $table );
+				$indexes = $this->db->MetaIndexes( $table );
+				
+				if( is_array( $fields ) ) {
+					foreach( $fields as $details ) {
+						$extra = '';
+						$content = array();
+						
+						if( $details->max_length > 0 ) {
+							$extra .= ' size="' . $details->max_length . '"';
+						}
+						
+						if( $details->primary_key ) {
+							$content[] = '<KEY/>';
+						} elseif( $details->not_null ) {
+							$content[] = '<NOTNULL/>';
+						}
+						
+						if( $details->has_default ) {
+							$content[] = '<DEFAULT value="' . $details->default_value . '"/>';
+						}
+						
+						if( $details->auto_increment ) {
+							$content[] = '<AUTOINCREMENT/>';
+						}
+						
+						// this stops the creation of 'R' columns,
+						// AUTOINCREMENT is used to create auto columns
+						$details->primary_key = 0;
+						$type = $rs->MetaType( $details );
+						
+						$schema .= '		<field name="' . $details->name . '" type="' . $type . '"' . $extra . '>';
+						
+						if( !empty( $content ) ) {
+							$schema .= "\n			" . implode( "\n			", $content ) . "\n		";
+						}
+						
+						$schema .= '</field>' . "\n";
+					}
+				}
+				
+				if( is_array( $indexes ) ) {
+					foreach( $indexes as $index => $details ) {
+						$schema .= '		<index name="' . $index . '">' . "\n";
+						
+						if( $details['unique'] ) {
+							$schema .= '			<UNIQUE/>' . "\n";
+						}
+						
+						foreach( $details['columns'] as $column ) {
+							$schema .= '			<col>' . $column . '</col>' . "\n";
+						}
+						
+						$schema .= '		</index>' . "\n";
+					}
+				}
+				
+				if( $data ) {
+					$rs = $this->db->Execute( 'SELECT * FROM ' . $table );
+					
+					if( is_object( $rs ) ) {
+						$schema .= '		<data>' . "\n";
+						
+						while( $row = $rs->FetchRow() ) {
+							foreach( $row as $key => $val ) {
+								$row[$key] = htmlentities($val);
+							}
+							
+							$schema .= '			<row><f>' . implode( '</f><f>', $row ) . '</f></row>' . "\n";
+						}
+						
+						$schema .= '		</data>' . "\n";
+					}
+				}
+				
+				$schema .= '	</table>' . "\n";
+			}
+		}
+		
+		$this->db->SetFetchMode( $old_mode );
+		
+		$schema .= '</schema>';
+		return $schema;
+	}
+	
+	/**
+	* Sets a prefix for database objects
+	*
+	* Call this method to set a standard prefix that will be prepended to all database tables 
+	* and indices when the schema is parsed. Calling setPrefix with no arguments clears the prefix.
+	*
+	* @param string $prefix Prefix that will be prepended.
+	* @param boolean $underscore If TRUE, automatically append an underscore character to the prefix.
+	* @return boolean TRUE if successful, else FALSE
+	*/
+	function SetPrefix( $prefix = '', $underscore = TRUE ) {
+		switch( TRUE ) {
+			// clear prefix
+			case empty( $prefix ):
+				logMsg( 'Cleared prefix' );
+				$this->objectPrefix = '';
+				return TRUE;
+			// prefix too long
+			case strlen( $prefix ) > XMLS_PREFIX_MAXLEN:
+			// prefix contains invalid characters
+			case !preg_match( '/^[a-z][a-z0-9_]+$/i', $prefix ):
+				logMsg( 'Invalid prefix: ' . $prefix );
+				return FALSE;
+		}
+		
+		if( $underscore AND substr( $prefix, -1 ) != '_' ) {
+			$prefix .= '_';
+		}
+		
+		// prefix valid
+		logMsg( 'Set prefix: ' . $prefix );
+		$this->objectPrefix = $prefix;
+		return TRUE;
+	}
+	
+	/**
+	* Returns an object name with the current prefix prepended.
+	*
+	* @param string	$name Name
+	* @return string	Prefixed name
+	*
+	* @access private
+	*/
+	function prefix( $name = '' ) {
+		// if prefix is set
+		if( !empty( $this->objectPrefix ) ) {
+			// Prepend the object prefix to the table name
+			// prepend after quote if used
+			return preg_replace( '/^(`?)(.+)$/', '$1' . $this->objectPrefix . '$2', $name );
+		}
+		
+		// No prefix set. Use name provided.
+		return $name;
+	}
+	
+	/**
+	* Checks if element references a specific platform
+	*
+	* @param string $platform Requested platform
+	* @returns boolean TRUE if platform check succeeds
+	*
+	* @access private
+	*/
+	function supportedPlatform( $platform = NULL ) {
+		$regex = '/^(\w*\|)*' . $this->db->databaseType . '(\|\w*)*$/';
+		
+		if( !isset( $platform ) OR preg_match( $regex, $platform ) ) {
+			logMsg( "Platform $platform is supported" );
+			return TRUE;
+		} else {
+			logMsg( "Platform $platform is NOT supported" );
+			return FALSE;
+		}
+	}
+	
+	/**
+	* Clears the array of generated SQL.
+	*
+	* @access private
+	*/
+	function clearSQL() {
+		$this->sqlArray = array();
+	}
+	
+	/**
+	* Adds SQL into the SQL array.
+	*
+	* @param mixed $sql SQL to Add
+	* @return boolean TRUE if successful, else FALSE.
+	*
+	* @access private
+	*/	
+	function addSQL( $sql = NULL ) {
+		if( is_array( $sql ) ) {
+			foreach( $sql as $line ) {
+				$this->addSQL( $line );
+			}
+			
+			return TRUE;
+		}
+		
+		if( is_string( $sql ) ) {
+			$this->sqlArray[] = $sql;
+			
+			// if executeInline is enabled, and either no errors have occurred or continueOnError is enabled, execute SQL.
+			if( $this->ExecuteInline() && ( $this->success == 2 || $this->ContinueOnError() ) ) {
+				$saved = $this->db->debug;
+				$this->db->debug = $this->debug;
+				$ok = $this->db->Execute( $sql );
+				$this->db->debug = $saved;
+				
+				if( !$ok ) {
+					if( $this->debug ) {
+						ADOConnection::outp( $this->db->ErrorMsg() );
+					}
+					
+					$this->success = 1;
+				}
+			}
+			
+			return TRUE;
+		}
+		
+		return FALSE;
+	}
+	
+	/**
+	* Gets the SQL array in the specified format.
+	*
+	* @param string $format Format
+	* @return mixed SQL
+	*	
+	* @access private
+	*/
+	function getSQL( $format = NULL, $sqlArray = NULL ) {
+		if( !is_array( $sqlArray ) ) {
+			$sqlArray = $this->sqlArray;
+		}
+		
+		if( !is_array( $sqlArray ) ) {
+			return FALSE;
+		}
+		
+		switch( strtolower( $format ) ) {
+			case 'string':
+			case 'text':
+				return !empty( $sqlArray ) ? implode( ";\n\n", $sqlArray ) . ';' : '';
+			case'html':
+				return !empty( $sqlArray ) ? nl2br( htmlentities( implode( ";\n\n", $sqlArray ) . ';' ) ) : '';
+		}
+		
+		return $this->sqlArray;
+	}
+	
+	/**
+	* Destroys an adoSchema object.
+	*
+	* Call this method to clean up after an adoSchema object that is no longer in use.
+	* @deprecated adoSchema now cleans up automatically.
+	*/
+	function Destroy() {
+		set_magic_quotes_runtime( $this->mgq );
+		unset( $this );
+	}
+}
+
+/**
+* Message logging function
+*
+* @access private
+*/
+function logMsg( $msg, $title = NULL, $force = FALSE ) {
+	if( XMLS_DEBUG or $force ) {
+		echo '<pre>';
+		
+		if( isset( $title ) ) {
+			echo '<h3>' . htmlentities( $title ) . '</h3>';
+		}
+		
+		if( is_object( $this ) ) {
+			echo '[' . get_class( $this ) . '] ';
+		}
+		
+		print_r( $msg );
+		
+		echo '</pre>';
+	}
+}
+?>
Index: /Dev/trunk/rdfapi/util/adodb/adodb-xmlschema03.inc.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/adodb-xmlschema03.inc.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/adodb-xmlschema03.inc.php	(revision 12)
@@ -0,0 +1,2403 @@
+<?php
+// Copyright (c) 2004-2005 ars Cognita Inc., all rights reserved
+/* ******************************************************************************
+    Released under both BSD license and Lesser GPL library license. 
+ 	Whenever there is any discrepancy between the two licenses, 
+ 	the BSD license will take precedence. 
+*******************************************************************************/
+/**
+ * xmlschema is a class that allows the user to quickly and easily
+ * build a database on any ADOdb-supported platform using a simple
+ * XML schema.
+ *
+ * Last Editor: $Author: cweiske $
+ * @author Richard Tango-Lowy & Dan Cech
+ * @version $Revision: 351 $
+ *
+ * @package axmls
+ * @tutorial getting_started.pkg
+ */
+ 
+function _file_get_contents($file) 
+{
+ 	if (function_exists('file_get_contents')) return file_get_contents($file);
+	
+	$f = fopen($file,'r');
+	if (!$f) return '';
+	$t = '';
+	
+	while ($s = fread($f,100000)) $t .= $s;
+	fclose($f);
+	return $t;
+}
+
+
+/**
+* Debug on or off
+*/
+if( !defined( 'XMLS_DEBUG' ) ) {
+	define( 'XMLS_DEBUG', FALSE );
+}
+
+/**
+* Default prefix key
+*/
+if( !defined( 'XMLS_PREFIX' ) ) {
+	define( 'XMLS_PREFIX', '%%P' );
+}
+
+/**
+* Maximum length allowed for object prefix
+*/
+if( !defined( 'XMLS_PREFIX_MAXLEN' ) ) {
+	define( 'XMLS_PREFIX_MAXLEN', 10 );
+}
+
+/**
+* Execute SQL inline as it is generated
+*/
+if( !defined( 'XMLS_EXECUTE_INLINE' ) ) {
+	define( 'XMLS_EXECUTE_INLINE', FALSE );
+}
+
+/**
+* Continue SQL Execution if an error occurs?
+*/
+if( !defined( 'XMLS_CONTINUE_ON_ERROR' ) ) {
+	define( 'XMLS_CONTINUE_ON_ERROR', FALSE );
+}
+
+/**
+* Current Schema Version
+*/
+if( !defined( 'XMLS_SCHEMA_VERSION' ) ) {
+	define( 'XMLS_SCHEMA_VERSION', '0.3' );
+}
+
+/**
+* Default Schema Version.  Used for Schemas without an explicit version set.
+*/
+if( !defined( 'XMLS_DEFAULT_SCHEMA_VERSION' ) ) {
+	define( 'XMLS_DEFAULT_SCHEMA_VERSION', '0.1' );
+}
+
+/**
+* How to handle data rows that already exist in a database during and upgrade.
+* Options are INSERT (attempts to insert duplicate rows), UPDATE (updates existing
+* rows) and IGNORE (ignores existing rows).
+*/
+if( !defined( 'XMLS_MODE_INSERT' ) ) {
+	define( 'XMLS_MODE_INSERT', 0 );
+}
+if( !defined( 'XMLS_MODE_UPDATE' ) ) {
+	define( 'XMLS_MODE_UPDATE', 1 );
+}
+if( !defined( 'XMLS_MODE_IGNORE' ) ) {
+	define( 'XMLS_MODE_IGNORE', 2 );
+}
+if( !defined( 'XMLS_EXISTING_DATA' ) ) {
+	define( 'XMLS_EXISTING_DATA', XMLS_MODE_INSERT );
+}
+
+/**
+* Default Schema Version.  Used for Schemas without an explicit version set.
+*/
+if( !defined( 'XMLS_DEFAULT_UPGRADE_METHOD' ) ) {
+	define( 'XMLS_DEFAULT_UPGRADE_METHOD', 'ALTER' );
+}
+
+/**
+* Include the main ADODB library
+*/
+if( !defined( '_ADODB_LAYER' ) ) {
+	require( 'adodb.inc.php' );
+	require( 'adodb-datadict.inc.php' );
+}
+
+/**
+* Abstract DB Object. This class provides basic methods for database objects, such
+* as tables and indexes.
+*
+* @package axmls
+* @access private
+*/
+class dbObject {
+	
+	/**
+	* var object Parent
+	*/
+	var $parent;
+	
+	/**
+	* var string current element
+	*/
+	var $currentElement;
+	
+	/**
+	* NOP
+	*/
+	function dbObject( &$parent, $attributes = NULL ) {
+		$this->parent =& $parent;
+	}
+	
+	/**
+	* XML Callback to process start elements
+	*
+	* @access private
+	*/
+	function _tag_open( &$parser, $tag, $attributes ) {
+		
+	}
+	
+	/**
+	* XML Callback to process CDATA elements
+	*
+	* @access private
+	*/
+	function _tag_cdata( &$parser, $cdata ) {
+		
+	}
+	
+	/**
+	* XML Callback to process end elements
+	*
+	* @access private
+	*/
+	function _tag_close( &$parser, $tag ) {
+		
+	}
+	
+	function create() {
+		return array();
+	}
+	
+	/**
+	* Destroys the object
+	*/
+	function destroy() {
+		unset( $this );
+	}
+	
+	/**
+	* Checks whether the specified RDBMS is supported by the current
+	* database object or its ranking ancestor.
+	*
+	* @param string $platform RDBMS platform name (from ADODB platform list).
+	* @return boolean TRUE if RDBMS is supported; otherwise returns FALSE.
+	*/
+	function supportedPlatform( $platform = NULL ) {
+		return is_object( $this->parent ) ? $this->parent->supportedPlatform( $platform ) : TRUE;
+	}
+	
+	/**
+	* Returns the prefix set by the ranking ancestor of the database object.
+	*
+	* @param string $name Prefix string.
+	* @return string Prefix.
+	*/
+	function prefix( $name = '' ) {
+		return is_object( $this->parent ) ? $this->parent->prefix( $name ) : $name;
+	}
+	
+	/**
+	* Extracts a field ID from the specified field.
+	*
+	* @param string $field Field.
+	* @return string Field ID.
+	*/
+	function FieldID( $field ) {
+		return strtoupper( preg_replace( '/^`(.+)`$/', '$1', $field ) );
+	}
+}
+
+/**
+* Creates a table object in ADOdb's datadict format
+*
+* This class stores information about a database table. As charactaristics
+* of the table are loaded from the external source, methods and properties
+* of this class are used to build up the table description in ADOdb's
+* datadict format.
+*
+* @package axmls
+* @access private
+*/
+class dbTable extends dbObject {
+	
+	/**
+	* @var string Table name
+	*/
+	var $name;
+	
+	/**
+	* @var array Field specifier: Meta-information about each field
+	*/
+	var $fields = array();
+	
+	/**
+	* @var array List of table indexes.
+	*/
+	var $indexes = array();
+	
+	/**
+	* @var array Table options: Table-level options
+	*/
+	var $opts = array();
+	
+	/**
+	* @var string Field index: Keeps track of which field is currently being processed
+	*/
+	var $current_field;
+	
+	/**
+	* @var boolean Mark table for destruction
+	* @access private
+	*/
+	var $drop_table;
+	
+	/**
+	* @var boolean Mark field for destruction (not yet implemented)
+	* @access private
+	*/
+	var $drop_field = array();
+	
+	/**
+	* @var array Platform-specific options
+	* @access private
+	*/
+	var $currentPlatform = true;
+	
+	
+	/**
+	* Iniitializes a new table object.
+	*
+	* @param string $prefix DB Object prefix
+	* @param array $attributes Array of table attributes.
+	*/
+	function dbTable( &$parent, $attributes = NULL ) {
+		$this->parent =& $parent;
+		$this->name = $this->prefix($attributes['NAME']);
+	}
+	
+	/**
+	* XML Callback to process start elements. Elements currently 
+	* processed are: INDEX, DROP, FIELD, KEY, NOTNULL, AUTOINCREMENT & DEFAULT. 
+	*
+	* @access private
+	*/
+	function _tag_open( &$parser, $tag, $attributes ) {
+		$this->currentElement = strtoupper( $tag );
+		
+		switch( $this->currentElement ) {
+			case 'INDEX':
+				if( !isset( $attributes['PLATFORM'] ) OR $this->supportedPlatform( $attributes['PLATFORM'] ) ) {
+					xml_set_object( $parser, $this->addIndex( $attributes ) );
+				}
+				break;
+			case 'DATA':
+				if( !isset( $attributes['PLATFORM'] ) OR $this->supportedPlatform( $attributes['PLATFORM'] ) ) {
+					xml_set_object( $parser, $this->addData( $attributes ) );
+				}
+				break;
+			case 'DROP':
+				$this->drop();
+				break;
+			case 'FIELD':
+				// Add a field
+				$fieldName = $attributes['NAME'];
+				$fieldType = $attributes['TYPE'];
+				$fieldSize = isset( $attributes['SIZE'] ) ? $attributes['SIZE'] : NULL;
+				$fieldOpts = !empty( $attributes['OPTS'] ) ? $attributes['OPTS'] : NULL;
+				
+				$this->addField( $fieldName, $fieldType, $fieldSize, $fieldOpts );
+				break;
+			case 'KEY':
+			case 'NOTNULL':
+			case 'AUTOINCREMENT':
+			case 'DEFDATE':
+			case 'DEFTIMESTAMP':
+			case 'UNSIGNED':
+				// Add a field option
+				$this->addFieldOpt( $this->current_field, $this->currentElement );
+				break;
+			case 'DEFAULT':
+				// Add a field option to the table object
+				
+				// Work around ADOdb datadict issue that misinterprets empty strings.
+				if( $attributes['VALUE'] == '' ) {
+					$attributes['VALUE'] = " '' ";
+				}
+				
+				$this->addFieldOpt( $this->current_field, $this->currentElement, $attributes['VALUE'] );
+				break;
+			case 'OPT':
+			case 'CONSTRAINT':
+				// Accept platform-specific options
+				$this->currentPlatform = ( !isset( $attributes['PLATFORM'] ) OR $this->supportedPlatform( $attributes['PLATFORM'] ) );
+				break;
+			default:
+				// print_r( array( $tag, $attributes ) );
+		}
+	}
+	
+	/**
+	* XML Callback to process CDATA elements
+	*
+	* @access private
+	*/
+	function _tag_cdata( &$parser, $cdata ) {
+		switch( $this->currentElement ) {
+			// Table/field constraint
+			case 'CONSTRAINT':
+				if( isset( $this->current_field ) ) {
+					$this->addFieldOpt( $this->current_field, $this->currentElement, $cdata );
+				} else {
+					$this->addTableOpt( $cdata );
+				}
+				break;
+			// Table/field option
+			case 'OPT':
+				if( isset( $this->current_field ) ) {
+					$this->addFieldOpt( $this->current_field, $cdata );
+				} else {
+				$this->addTableOpt( $cdata );
+				}
+				break;
+			default:
+				
+		}
+	}
+	
+	/**
+	* XML Callback to process end elements
+	*
+	* @access private
+	*/
+	function _tag_close( &$parser, $tag ) {
+		$this->currentElement = '';
+		
+		switch( strtoupper( $tag ) ) {
+			case 'TABLE':
+				$this->parent->addSQL( $this->create( $this->parent ) );
+				xml_set_object( $parser, $this->parent );
+				$this->destroy();
+				break;
+			case 'FIELD':
+				unset($this->current_field);
+				break;
+			case 'OPT':
+			case 'CONSTRAINT':
+				$this->currentPlatform = true;
+				break;
+			default:
+
+		}
+	}
+	
+	/**
+	* Adds an index to a table object
+	*
+	* @param array $attributes Index attributes
+	* @return object dbIndex object
+	*/
+	function &addIndex( $attributes ) {
+		$name = strtoupper( $attributes['NAME'] );
+		$this->indexes[$name] =& new dbIndex( $this, $attributes );
+		return $this->indexes[$name];
+	}
+	
+	/**
+	* Adds data to a table object
+	*
+	* @param array $attributes Data attributes
+	* @return object dbData object
+	*/
+	function &addData( $attributes ) {
+		if( !isset( $this->data ) ) {
+			$this->data =& new dbData( $this, $attributes );
+		}
+		return $this->data;
+	}
+	
+	/**
+	* Adds a field to a table object
+	*
+	* $name is the name of the table to which the field should be added. 
+	* $type is an ADODB datadict field type. The following field types
+	* are supported as of ADODB 3.40:
+	* 	- C:  varchar
+	*	- X:  CLOB (character large object) or largest varchar size
+	*	   if CLOB is not supported
+	*	- C2: Multibyte varchar
+	*	- X2: Multibyte CLOB
+	*	- B:  BLOB (binary large object)
+	*	- D:  Date (some databases do not support this, and we return a datetime type)
+	*	- T:  Datetime or Timestamp
+	*	- L:  Integer field suitable for storing booleans (0 or 1)
+	*	- I:  Integer (mapped to I4)
+	*	- I1: 1-byte integer
+	*	- I2: 2-byte integer
+	*	- I4: 4-byte integer
+	*	- I8: 8-byte integer
+	*	- F:  Floating point number
+	*	- N:  Numeric or decimal number
+	*
+	* @param string $name Name of the table to which the field will be added.
+	* @param string $type	ADODB datadict field type.
+	* @param string $size	Field size
+	* @param array $opts	Field options array
+	* @return array Field specifier array
+	*/
+	function addField( $name, $type, $size = NULL, $opts = NULL ) {
+		$field_id = $this->FieldID( $name );
+		
+		// Set the field index so we know where we are
+		$this->current_field = $field_id;
+		
+		// Set the field name (required)
+		$this->fields[$field_id]['NAME'] = $name;
+		
+		// Set the field type (required)
+		$this->fields[$field_id]['TYPE'] = $type;
+		
+		// Set the field size (optional)
+		if( isset( $size ) ) {
+			$this->fields[$field_id]['SIZE'] = $size;
+		}
+		
+		// Set the field options
+		if( isset( $opts ) ) {
+			$this->fields[$field_id]['OPTS'] = array($opts);
+		} else {
+			$this->fields[$field_id]['OPTS'] = array();
+		}
+	}
+	
+	/**
+	* Adds a field option to the current field specifier
+	*
+	* This method adds a field option allowed by the ADOdb datadict 
+	* and appends it to the given field.
+	*
+	* @param string $field	Field name
+	* @param string $opt ADOdb field option
+	* @param mixed $value Field option value
+	* @return array Field specifier array
+	*/
+	function addFieldOpt( $field, $opt, $value = NULL ) {
+		if( $this->currentPlatform ) {
+		if( !isset( $value ) ) {
+			$this->fields[$this->FieldID( $field )]['OPTS'][] = $opt;
+		// Add the option and value
+		} else {
+			$this->fields[$this->FieldID( $field )]['OPTS'][] = array( $opt => $value );
+		}
+	}
+	}
+	
+	/**
+	* Adds an option to the table
+	*
+	* This method takes a comma-separated list of table-level options
+	* and appends them to the table object.
+	*
+	* @param string $opt Table option
+	* @return array Options
+	*/
+	function addTableOpt( $opt ) {
+		if( $this->currentPlatform ) {
+		$this->opts[] = $opt;
+		}
+		return $this->opts;
+	}
+	
+	/**
+	* Generates the SQL that will create the table in the database
+	*
+	* @param object $xmls adoSchema object
+	* @return array Array containing table creation SQL
+	*/
+	function create( &$xmls ) {
+		$sql = array();
+		
+		// drop any existing indexes
+		if( is_array( $legacy_indexes = $xmls->dict->MetaIndexes( $this->name ) ) ) {
+			foreach( $legacy_indexes as $index => $index_details ) {
+				$sql[] = $xmls->dict->DropIndexSQL( $index, $this->name );
+			}
+		}
+		
+		// remove fields to be dropped from table object
+		foreach( $this->drop_field as $field ) {
+			unset( $this->fields[$field] );
+		}
+		
+		// if table exists
+		if( is_array( $legacy_fields = $xmls->dict->MetaColumns( $this->name ) ) ) {
+			// drop table
+			if( $this->drop_table ) {
+				$sql[] = $xmls->dict->DropTableSQL( $this->name );
+				
+				return $sql;
+			}
+			
+			// drop any existing fields not in schema
+			foreach( $legacy_fields as $field_id => $field ) {
+				if( !isset( $this->fields[$field_id] ) ) {
+					$sql[] = $xmls->dict->DropColumnSQL( $this->name, $field->name );
+				}
+			}
+		// if table doesn't exist
+		} else {
+			if( $this->drop_table ) {
+				return $sql;
+			}
+			
+			$legacy_fields = array();
+		}
+		
+		// Loop through the field specifier array, building the associative array for the field options
+		$fldarray = array();
+		
+		foreach( $this->fields as $field_id => $finfo ) {
+			// Set an empty size if it isn't supplied
+			if( !isset( $finfo['SIZE'] ) ) {
+				$finfo['SIZE'] = '';
+			}
+			
+			// Initialize the field array with the type and size
+			$fldarray[$field_id] = array(
+				'NAME' => $finfo['NAME'],
+				'TYPE' => $finfo['TYPE'],
+				'SIZE' => $finfo['SIZE']
+			);
+			
+			// Loop through the options array and add the field options. 
+			if( isset( $finfo['OPTS'] ) ) {
+				foreach( $finfo['OPTS'] as $opt ) {
+					// Option has an argument.
+					if( is_array( $opt ) ) {
+						$key = key( $opt );
+						$value = $opt[key( $opt )];
+						@$fldarray[$field_id][$key] .= $value;
+					// Option doesn't have arguments
+					} else {
+						$fldarray[$field_id][$opt] = $opt;
+					}
+				}
+			}
+		}
+		
+		if( empty( $legacy_fields ) ) {
+			// Create the new table
+			$sql[] = $xmls->dict->CreateTableSQL( $this->name, $fldarray, $this->opts );
+			logMsg( end( $sql ), 'Generated CreateTableSQL' );
+		} else {
+			// Upgrade an existing table
+			logMsg( "Upgrading {$this->name} using '{$xmls->upgrade}'" );
+			switch( $xmls->upgrade ) {
+				// Use ChangeTableSQL
+				case 'ALTER':
+					logMsg( 'Generated ChangeTableSQL (ALTERing table)' );
+					$sql[] = $xmls->dict->ChangeTableSQL( $this->name, $fldarray, $this->opts );
+					break;
+				case 'REPLACE':
+					logMsg( 'Doing upgrade REPLACE (testing)' );
+					$sql[] = $xmls->dict->DropTableSQL( $this->name );
+					$sql[] = $xmls->dict->CreateTableSQL( $this->name, $fldarray, $this->opts );
+					break;
+				// ignore table
+				default:
+					return array();
+			}
+		}
+		
+		foreach( $this->indexes as $index ) {
+			$sql[] = $index->create( $xmls );
+		}
+		
+		if( isset( $this->data ) ) {
+			$sql[] = $this->data->create( $xmls );
+		}
+		
+		return $sql;
+	}
+	
+	/**
+	* Marks a field or table for destruction
+	*/
+	function drop() {
+		if( isset( $this->current_field ) ) {
+			// Drop the current field
+			logMsg( "Dropping field '{$this->current_field}' from table '{$this->name}'" );
+			// $this->drop_field[$this->current_field] = $xmls->dict->DropColumnSQL( $this->name, $this->current_field );
+			$this->drop_field[$this->current_field] = $this->current_field;
+		} else {
+			// Drop the current table
+			logMsg( "Dropping table '{$this->name}'" );
+			// $this->drop_table = $xmls->dict->DropTableSQL( $this->name );
+			$this->drop_table = TRUE;
+		}
+	}
+}
+
+/**
+* Creates an index object in ADOdb's datadict format
+*
+* This class stores information about a database index. As charactaristics
+* of the index are loaded from the external source, methods and properties
+* of this class are used to build up the index description in ADOdb's
+* datadict format.
+*
+* @package axmls
+* @access private
+*/
+class dbIndex extends dbObject {
+	
+	/**
+	* @var string	Index name
+	*/
+	var $name;
+	
+	/**
+	* @var array	Index options: Index-level options
+	*/
+	var $opts = array();
+	
+	/**
+	* @var array	Indexed fields: Table columns included in this index
+	*/
+	var $columns = array();
+	
+	/**
+	* @var boolean Mark index for destruction
+	* @access private
+	*/
+	var $drop = FALSE;
+	
+	/**
+	* Initializes the new dbIndex object.
+	*
+	* @param object $parent Parent object
+	* @param array $attributes Attributes
+	*
+	* @internal
+	*/
+	function dbIndex( &$parent, $attributes = NULL ) {
+		$this->parent =& $parent;
+		
+		$this->name = $this->prefix ($attributes['NAME']);
+	}
+	
+	/**
+	* XML Callback to process start elements
+	*
+	* Processes XML opening tags. 
+	* Elements currently processed are: DROP, CLUSTERED, BITMAP, UNIQUE, FULLTEXT & HASH. 
+	*
+	* @access private
+	*/
+	function _tag_open( &$parser, $tag, $attributes ) {
+		$this->currentElement = strtoupper( $tag );
+		
+		switch( $this->currentElement ) {
+			case 'DROP':
+				$this->drop();
+				break;
+			case 'CLUSTERED':
+			case 'BITMAP':
+			case 'UNIQUE':
+			case 'FULLTEXT':
+			case 'HASH':
+				// Add index Option
+				$this->addIndexOpt( $this->currentElement );
+				break;
+			default:
+				// print_r( array( $tag, $attributes ) );
+		}
+	}
+	
+	/**
+	* XML Callback to process CDATA elements
+	*
+	* Processes XML cdata.
+	*
+	* @access private
+	*/
+	function _tag_cdata( &$parser, $cdata ) {
+		switch( $this->currentElement ) {
+			// Index field name
+			case 'COL':
+				$this->addField( $cdata );
+				break;
+			default:
+				
+		}
+	}
+	
+	/**
+	* XML Callback to process end elements
+	*
+	* @access private
+	*/
+	function _tag_close( &$parser, $tag ) {
+		$this->currentElement = '';
+		
+		switch( strtoupper( $tag ) ) {
+			case 'INDEX':
+				xml_set_object( $parser, $this->parent );
+				break;
+		}
+	}
+	
+	/**
+	* Adds a field to the index
+	*
+	* @param string $name Field name
+	* @return string Field list
+	*/
+	function addField( $name ) {
+		$this->columns[$this->FieldID( $name )] = $name;
+		
+		// Return the field list
+		return $this->columns;
+	}
+	
+	/**
+	* Adds options to the index
+	*
+	* @param string $opt Comma-separated list of index options.
+	* @return string Option list
+	*/
+	function addIndexOpt( $opt ) {
+		$this->opts[] = $opt;
+		
+		// Return the options list
+		return $this->opts;
+	}
+	
+	/**
+	* Generates the SQL that will create the index in the database
+	*
+	* @param object $xmls adoSchema object
+	* @return array Array containing index creation SQL
+	*/
+	function create( &$xmls ) {
+		if( $this->drop ) {
+			return NULL;
+		}
+		
+		// eliminate any columns that aren't in the table
+		foreach( $this->columns as $id => $col ) {
+			if( !isset( $this->parent->fields[$id] ) ) {
+				unset( $this->columns[$id] );
+			}
+		}
+		
+		return $xmls->dict->CreateIndexSQL( $this->name, $this->parent->name, $this->columns, $this->opts );
+	}
+	
+	/**
+	* Marks an index for destruction
+	*/
+	function drop() {
+		$this->drop = TRUE;
+	}
+}
+
+/**
+* Creates a data object in ADOdb's datadict format
+*
+* This class stores information about table data, and is called
+* when we need to load field data into a table.
+*
+* @package axmls
+* @access private
+*/
+class dbData extends dbObject {
+	
+	var $data = array();
+	
+	var $row;
+	
+	/**
+	* Initializes the new dbData object.
+	*
+	* @param object $parent Parent object
+	* @param array $attributes Attributes
+	*
+	* @internal
+	*/
+	function dbData( &$parent, $attributes = NULL ) {
+		$this->parent =& $parent;
+	}
+	
+	/**
+	* XML Callback to process start elements
+	*
+	* Processes XML opening tags. 
+	* Elements currently processed are: ROW and F (field). 
+	*
+	* @access private
+	*/
+	function _tag_open( &$parser, $tag, $attributes ) {
+		$this->currentElement = strtoupper( $tag );
+		
+		switch( $this->currentElement ) {
+			case 'ROW':
+				$this->row = count( $this->data );
+				$this->data[$this->row] = array();
+				break;
+			case 'F':
+				$this->addField($attributes);
+			default:
+				// print_r( array( $tag, $attributes ) );
+		}
+	}
+	
+	/**
+	* XML Callback to process CDATA elements
+	*
+	* Processes XML cdata.
+	*
+	* @access private
+	*/
+	function _tag_cdata( &$parser, $cdata ) {
+		switch( $this->currentElement ) {
+			// Index field name
+			case 'F':
+				$this->addData( $cdata );
+				break;
+			default:
+				
+		}
+	}
+	
+	/**
+	* XML Callback to process end elements
+	*
+	* @access private
+	*/
+	function _tag_close( &$parser, $tag ) {
+		$this->currentElement = '';
+		
+		switch( strtoupper( $tag ) ) {
+			case 'DATA':
+				xml_set_object( $parser, $this->parent );
+				break;
+		}
+	}
+	
+	/**
+	* Adds a field to the insert
+	*
+	* @param string $name Field name
+	* @return string Field list
+	*/
+	function addField( $attributes ) {
+		// check we're in a valid row
+		if( !isset( $this->row ) || !isset( $this->data[$this->row] ) ) {
+			return;
+		}
+		
+		// Set the field index so we know where we are
+		if( isset( $attributes['NAME'] ) ) {
+			$this->current_field = $this->FieldID( $attributes['NAME'] );
+		} else {
+			$this->current_field = count( $this->data[$this->row] );
+		}
+		
+		// initialise data
+		if( !isset( $this->data[$this->row][$this->current_field] ) ) {
+			$this->data[$this->row][$this->current_field] = '';
+		}
+	}
+	
+	/**
+	* Adds options to the index
+	*
+	* @param string $opt Comma-separated list of index options.
+	* @return string Option list
+	*/
+	function addData( $cdata ) {
+		// check we're in a valid field
+		if ( isset( $this->data[$this->row][$this->current_field] ) ) {
+			// add data to field
+			$this->data[$this->row][$this->current_field] .= $cdata;
+		}
+	}
+	
+	/**
+	* Generates the SQL that will add/update the data in the database
+	*
+	* @param object $xmls adoSchema object
+	* @return array Array containing index creation SQL
+	*/
+	function create( &$xmls ) {
+		$table = $xmls->dict->TableName($this->parent->name);
+		$table_field_count = count($this->parent->fields);
+		$tables = $xmls->db->MetaTables(); 
+		$sql = array();
+		
+		$ukeys = $xmls->db->MetaPrimaryKeys( $table );
+		if( !empty( $this->parent->indexes ) and !empty( $ukeys ) ) {
+			foreach( $this->parent->indexes as $indexObj ) {
+				if( !in_array( $indexObj->name, $ukeys ) ) $ukeys[] = $indexObj->name;
+			}
+		}
+		
+		// eliminate any columns that aren't in the table
+		foreach( $this->data as $row ) {
+			$table_fields = $this->parent->fields;
+			$fields = array();
+			$rawfields = array(); // Need to keep some of the unprocessed data on hand.
+			
+			foreach( $row as $field_id => $field_data ) {
+				if( !array_key_exists( $field_id, $table_fields ) ) {
+					if( is_numeric( $field_id ) ) {
+						$field_id = reset( array_keys( $table_fields ) );
+					} else {
+						continue;
+					}
+				}
+				
+				$name = $table_fields[$field_id]['NAME'];
+				
+				switch( $table_fields[$field_id]['TYPE'] ) {
+					case 'I':
+					case 'I1':
+					case 'I2':
+					case 'I4':
+					case 'I8':
+						$fields[$name] = intval($field_data);
+						break;
+					case 'C':
+					case 'C2':
+					case 'X':
+					case 'X2':
+					default:
+						$fields[$name] = $xmls->db->qstr( $field_data );
+						$rawfields[$name] = $field_data;
+				}
+				
+				unset($table_fields[$field_id]);
+				
+			}
+			
+			// check that at least 1 column is specified
+			if( empty( $fields ) ) {
+				continue;
+			}
+			
+			// check that no required columns are missing
+			if( count( $fields ) < $table_field_count ) {
+				foreach( $table_fields as $field ) {
+					if( isset( $field['OPTS'] ) and ( in_array( 'NOTNULL', $field['OPTS'] ) || in_array( 'KEY', $field['OPTS'] ) ) && !in_array( 'AUTOINCREMENT', $field['OPTS'] ) ) {
+							continue(2);
+						}
+				}
+			}
+			
+			// The rest of this method deals with updating existing data records.
+			
+			if( !in_array( $table, $tables ) or ( $mode = $xmls->existingData() ) == XMLS_MODE_INSERT ) {
+				// Table doesn't yet exist, so it's safe to insert.
+				logMsg( "$table doesn't exist, inserting or mode is INSERT" );
+			$sql[] = 'INSERT INTO '. $table .' ('. implode( ',', array_keys( $fields ) ) .') VALUES ('. implode( ',', $fields ) .')';
+				continue;
+		}
+		
+			// Prepare to test for potential violations. Get primary keys and unique indexes
+			$mfields = array_merge( $fields, $rawfields );
+			$keyFields = array_intersect( $ukeys, array_keys( $mfields ) );
+			
+			if( empty( $ukeys ) or count( $keyFields ) == 0 ) {
+				// No unique keys in schema, so safe to insert
+				logMsg( "Either schema or data has no unique keys, so safe to insert" );
+				$sql[] = 'INSERT INTO '. $table .' ('. implode( ',', array_keys( $fields ) ) .') VALUES ('. implode( ',', $fields ) .')';
+				continue;
+			}
+			
+			// Select record containing matching unique keys.
+			$where = '';
+			foreach( $ukeys as $key ) {
+				if( isset( $mfields[$key] ) and $mfields[$key] ) {
+					if( $where ) $where .= ' AND ';
+					$where .= $key . ' = ' . $xmls->db->qstr( $mfields[$key] );
+				}
+			}
+			$records = $xmls->db->Execute( 'SELECT * FROM ' . $table . ' WHERE ' . $where );
+			switch( $records->RecordCount() ) {
+				case 0:
+					// No matching record, so safe to insert.
+					logMsg( "No matching records. Inserting new row with unique data" );
+					$sql[] = $xmls->db->GetInsertSQL( $records, $mfields );
+					break;
+				case 1:
+					// Exactly one matching record, so we can update if the mode permits.
+					logMsg( "One matching record..." );
+					if( $mode == XMLS_MODE_UPDATE ) {
+						logMsg( "...Updating existing row from unique data" );
+						$sql[] = $xmls->db->GetUpdateSQL( $records, $mfields );
+					}
+					break;
+				default:
+					// More than one matching record; the result is ambiguous, so we must ignore the row.
+					logMsg( "More than one matching record. Ignoring row." );
+			}
+		}
+		return $sql;
+	}
+}
+
+/**
+* Creates the SQL to execute a list of provided SQL queries
+*
+* @package axmls
+* @access private
+*/
+class dbQuerySet extends dbObject {
+	
+	/**
+	* @var array	List of SQL queries
+	*/
+	var $queries = array();
+	
+	/**
+	* @var string	String used to build of a query line by line
+	*/
+	var $query;
+	
+	/**
+	* @var string	Query prefix key
+	*/
+	var $prefixKey = '';
+	
+	/**
+	* @var boolean	Auto prefix enable (TRUE)
+	*/
+	var $prefixMethod = 'AUTO';
+	
+	/**
+	* Initializes the query set.
+	*
+	* @param object $parent Parent object
+	* @param array $attributes Attributes
+	*/
+	function dbQuerySet( &$parent, $attributes = NULL ) {
+		$this->parent =& $parent;
+			
+		// Overrides the manual prefix key
+		if( isset( $attributes['KEY'] ) ) {
+			$this->prefixKey = $attributes['KEY'];
+		}
+		
+		$prefixMethod = isset( $attributes['PREFIXMETHOD'] ) ? strtoupper( trim( $attributes['PREFIXMETHOD'] ) ) : '';
+		
+		// Enables or disables automatic prefix prepending
+		switch( $prefixMethod ) {
+			case 'AUTO':
+				$this->prefixMethod = 'AUTO';
+				break;
+			case 'MANUAL':
+				$this->prefixMethod = 'MANUAL';
+				break;
+			case 'NONE':
+				$this->prefixMethod = 'NONE';
+				break;
+		}
+	}
+	
+	/**
+	* XML Callback to process start elements. Elements currently 
+	* processed are: QUERY. 
+	*
+	* @access private
+	*/
+	function _tag_open( &$parser, $tag, $attributes ) {
+		$this->currentElement = strtoupper( $tag );
+		
+		switch( $this->currentElement ) {
+			case 'QUERY':
+				// Create a new query in a SQL queryset.
+				// Ignore this query set if a platform is specified and it's different than the 
+				// current connection platform.
+				if( !isset( $attributes['PLATFORM'] ) OR $this->supportedPlatform( $attributes['PLATFORM'] ) ) {
+					$this->newQuery();
+				} else {
+					$this->discardQuery();
+				}
+				break;
+			default:
+				// print_r( array( $tag, $attributes ) );
+		}
+	}
+	
+	/**
+	* XML Callback to process CDATA elements
+	*/
+	function _tag_cdata( &$parser, $cdata ) {
+		switch( $this->currentElement ) {
+			// Line of queryset SQL data
+			case 'QUERY':
+				$this->buildQuery( $cdata );
+				break;
+			default:
+				
+		}
+	}
+	
+	/**
+	* XML Callback to process end elements
+	*
+	* @access private
+	*/
+	function _tag_close( &$parser, $tag ) {
+		$this->currentElement = '';
+		
+		switch( strtoupper( $tag ) ) {
+			case 'QUERY':
+				// Add the finished query to the open query set.
+				$this->addQuery();
+				break;
+			case 'SQL':
+				$this->parent->addSQL( $this->create( $this->parent ) );
+				xml_set_object( $parser, $this->parent );
+				$this->destroy();
+				break;
+			default:
+				
+		}
+	}
+	
+	/**
+	* Re-initializes the query.
+	*
+	* @return boolean TRUE
+	*/
+	function newQuery() {
+		$this->query = '';
+		
+		return TRUE;
+	}
+	
+	/**
+	* Discards the existing query.
+	*
+	* @return boolean TRUE
+	*/
+	function discardQuery() {
+		unset( $this->query );
+		
+		return TRUE;
+	}
+	
+	/** 
+	* Appends a line to a query that is being built line by line
+	*
+	* @param string $data Line of SQL data or NULL to initialize a new query
+	* @return string SQL query string.
+	*/
+	function buildQuery( $sql = NULL ) {
+		if( !isset( $this->query ) OR empty( $sql ) ) {
+			return FALSE;
+		}
+		
+		$this->query .= $sql;
+		
+		return $this->query;
+	}
+	
+	/**
+	* Adds a completed query to the query list
+	*
+	* @return string	SQL of added query
+	*/
+	function addQuery() {
+		if( !isset( $this->query ) ) {
+			return FALSE;
+		}
+		
+		$this->queries[] = $return = trim($this->query);
+		
+		unset( $this->query );
+		
+		return $return;
+	}
+	
+	/**
+	* Creates and returns the current query set
+	*
+	* @param object $xmls adoSchema object
+	* @return array Query set
+	*/
+	function create( &$xmls ) {
+		foreach( $this->queries as $id => $query ) {
+			switch( $this->prefixMethod ) {
+				case 'AUTO':
+					// Enable auto prefix replacement
+					
+					// Process object prefix.
+					// Evaluate SQL statements to prepend prefix to objects
+					$query = $this->prefixQuery( '/^\s*((?is)INSERT\s+(INTO\s+)?)((\w+\s*,?\s*)+)(\s.*$)/', $query, $xmls->objectPrefix );
+					$query = $this->prefixQuery( '/^\s*((?is)UPDATE\s+(FROM\s+)?)((\w+\s*,?\s*)+)(\s.*$)/', $query, $xmls->objectPrefix );
+					$query = $this->prefixQuery( '/^\s*((?is)DELETE\s+(FROM\s+)?)((\w+\s*,?\s*)+)(\s.*$)/', $query, $xmls->objectPrefix );
+					
+					// SELECT statements aren't working yet
+					#$data = preg_replace( '/(?ias)(^\s*SELECT\s+.*\s+FROM)\s+(\W\s*,?\s*)+((?i)\s+WHERE.*$)/', "\1 $prefix\2 \3", $data );
+					
+				case 'MANUAL':
+					// If prefixKey is set and has a value then we use it to override the default constant XMLS_PREFIX.
+					// If prefixKey is not set, we use the default constant XMLS_PREFIX
+					if( isset( $this->prefixKey ) AND( $this->prefixKey !== '' ) ) {
+						// Enable prefix override
+						$query = str_replace( $this->prefixKey, $xmls->objectPrefix, $query );
+					} else {
+						// Use default replacement
+						$query = str_replace( XMLS_PREFIX , $xmls->objectPrefix, $query );
+					}
+			}
+			
+			$this->queries[$id] = trim( $query );
+		}
+		
+		// Return the query set array
+		return $this->queries;
+	}
+	
+	/**
+	* Rebuilds the query with the prefix attached to any objects
+	*
+	* @param string $regex Regex used to add prefix
+	* @param string $query SQL query string
+	* @param string $prefix Prefix to be appended to tables, indices, etc.
+	* @return string Prefixed SQL query string.
+	*/
+	function prefixQuery( $regex, $query, $prefix = NULL ) {
+		if( !isset( $prefix ) ) {
+			return $query;
+		}
+		
+		if( preg_match( $regex, $query, $match ) ) {
+			$preamble = $match[1];
+			$postamble = $match[5];
+			$objectList = explode( ',', $match[3] );
+			// $prefix = $prefix . '_';
+			
+			$prefixedList = '';
+			
+			foreach( $objectList as $object ) {
+				if( $prefixedList !== '' ) {
+					$prefixedList .= ', ';
+				}
+				
+				$prefixedList .= $prefix . trim( $object );
+			}
+			
+			$query = $preamble . ' ' . $prefixedList . ' ' . $postamble;
+		}
+		
+		return $query;
+	}
+}
+
+/**
+* Loads and parses an XML file, creating an array of "ready-to-run" SQL statements
+* 
+* This class is used to load and parse the XML file, to create an array of SQL statements
+* that can be used to build a database, and to build the database using the SQL array.
+*
+* @tutorial getting_started.pkg
+*
+* @author Richard Tango-Lowy & Dan Cech
+* @version $Revision: 351 $
+*
+* @package axmls
+*/
+class adoSchema {
+	
+	/**
+	* @var array	Array containing SQL queries to generate all objects
+	* @access private
+	*/
+	var $sqlArray;
+	
+	/**
+	* @var object	ADOdb connection object
+	* @access private
+	*/
+	var $db;
+	
+	/**
+	* @var object	ADOdb Data Dictionary
+	* @access private
+	*/
+	var $dict;
+	
+	/**
+	* @var string Current XML element
+	* @access private
+	*/
+	var $currentElement = '';
+	
+	/**
+	* @var string If set (to 'ALTER' or 'REPLACE'), upgrade an existing database
+	* @access private
+	*/
+	var $upgrade = '';
+	
+	/**
+	* @var string Optional object prefix
+	* @access private
+	*/
+	var $objectPrefix = '';
+	
+	/**
+	* @var long	Original Magic Quotes Runtime value
+	* @access private
+	*/
+	var $mgq;
+	
+	/**
+	* @var long	System debug
+	* @access private
+	*/
+	var $debug;
+	
+	/**
+	* @var string Regular expression to find schema version
+	* @access private
+	*/
+	var $versionRegex = '/<schema.*?( version="([^"]*)")?.*?>/';
+	
+	/**
+	* @var string Current schema version
+	* @access private
+	*/
+	var $schemaVersion;
+	
+	/**
+	* @var int	Success of last Schema execution
+	*/
+	var $success;
+	
+	/**
+	* @var bool	Execute SQL inline as it is generated
+	*/
+	var $executeInline;
+	
+	/**
+	* @var bool	Continue SQL execution if errors occur
+	*/
+	var $continueOnError;
+	
+	/**
+	* @var int	How to handle existing data rows (insert, update, or ignore)
+	*/
+	var $existingData;
+	
+	/**
+	* Creates an adoSchema object
+	*
+	* Creating an adoSchema object is the first step in processing an XML schema.
+	* The only parameter is an ADOdb database connection object, which must already
+	* have been created.
+	*
+	* @param object $db ADOdb database connection object.
+	*/
+	function adoSchema( &$db ) {
+		// Initialize the environment
+		$this->mgq = get_magic_quotes_runtime();
+		set_magic_quotes_runtime(0);
+		
+		$this->db =& $db;
+		$this->debug = $this->db->debug;
+		$this->dict = NewDataDictionary( $this->db );
+		$this->sqlArray = array();
+		$this->schemaVersion = XMLS_SCHEMA_VERSION;
+		$this->executeInline( XMLS_EXECUTE_INLINE );
+		$this->continueOnError( XMLS_CONTINUE_ON_ERROR );
+		$this->existingData( XMLS_EXISTING_DATA );
+		$this->setUpgradeMethod();
+	}
+	
+	/**
+	* Sets the method to be used for upgrading an existing database
+	*
+	* Use this method to specify how existing database objects should be upgraded.
+	* The method option can be set to ALTER, REPLACE, BEST, or NONE. ALTER attempts to
+	* alter each database object directly, REPLACE attempts to rebuild each object
+	* from scratch, BEST attempts to determine the best upgrade method for each
+	* object, and NONE disables upgrading.
+	*
+	* This method is not yet used by AXMLS, but exists for backward compatibility.
+	* The ALTER method is automatically assumed when the adoSchema object is
+	* instantiated; other upgrade methods are not currently supported.
+	*
+	* @param string $method Upgrade method (ALTER|REPLACE|BEST|NONE)
+	* @returns string Upgrade method used
+	*/
+	function SetUpgradeMethod( $method = '' ) {
+		if( !is_string( $method ) ) {
+			return FALSE;
+		}
+		
+		$method = strtoupper( $method );
+		
+		// Handle the upgrade methods
+		switch( $method ) {
+			case 'ALTER':
+				$this->upgrade = $method;
+				break;
+			case 'REPLACE':
+				$this->upgrade = $method;
+				break;
+			case 'BEST':
+				$this->upgrade = 'ALTER';
+				break;
+			case 'NONE':
+				$this->upgrade = 'NONE';
+				break;
+			default:
+				// Use default if no legitimate method is passed.
+				$this->upgrade = XMLS_DEFAULT_UPGRADE_METHOD;
+		}
+		
+		return $this->upgrade;
+	}
+	
+	/**
+	* Specifies how to handle existing data row when there is a unique key conflict.
+	*
+	* The existingData setting specifies how the parser should handle existing rows
+	* when a unique key violation occurs during the insert. This can happen when inserting
+	* data into an existing table with one or more primary keys or unique indexes.
+	* The existingData method takes one of three options: XMLS_MODE_INSERT attempts
+	* to always insert the data as a new row. In the event of a unique key violation,
+	* the database will generate an error.  XMLS_MODE_UPDATE attempts to update the 
+	* any existing rows with the new data based upon primary or unique key fields in
+	* the schema. If the data row in the schema specifies no unique fields, the row
+	* data will be inserted as a new row. XMLS_MODE_IGNORE specifies that any data rows
+	* that would result in a unique key violation be ignored; no inserts or updates will
+	* take place. For backward compatibility, the default setting is XMLS_MODE_INSERT,
+	* but XMLS_MODE_UPDATE will generally be the most appropriate setting.
+	*
+	* @param int $mode XMLS_MODE_INSERT, XMLS_MODE_UPDATE, or XMLS_MODE_IGNORE
+	* @return int current mode
+	*/
+	function ExistingData( $mode = NULL ) {
+		if( is_int( $mode ) ) {
+			switch( $mode ) {
+				case XMLS_MODE_UPDATE:
+					$mode = XMLS_MODE_UPDATE;
+					break;
+				case XMLS_MODE_IGNORE:
+					$mode = XMLS_MODE_IGNORE;
+					break;
+				case XMLS_MODE_INSERT:
+					$mode = XMLS_MODE_INSERT;
+					break;
+				default:
+					$mode = XMLS_EXISITNG_DATA;
+					break;
+			}
+			$this->existingData = $mode;
+		}
+		
+		return $this->existingData;
+	}
+	
+	/**
+	* Enables/disables inline SQL execution.
+	*
+	* Call this method to enable or disable inline execution of the schema. If the mode is set to TRUE (inline execution),
+	* AXMLS applies the SQL to the database immediately as each schema entity is parsed. If the mode
+	* is set to FALSE (post execution), AXMLS parses the entire schema and you will need to call adoSchema::ExecuteSchema()
+	* to apply the schema to the database.
+	*
+	* @param bool $mode execute
+	* @return bool current execution mode
+	*
+	* @see ParseSchema(), ExecuteSchema()
+	*/
+	function ExecuteInline( $mode = NULL ) {
+		if( is_bool( $mode ) ) {
+			$this->executeInline = $mode;
+		}
+		
+		return $this->executeInline;
+	}
+	
+	/**
+	* Enables/disables SQL continue on error.
+	*
+	* Call this method to enable or disable continuation of SQL execution if an error occurs.
+	* If the mode is set to TRUE (continue), AXMLS will continue to apply SQL to the database, even if an error occurs.
+	* If the mode is set to FALSE (halt), AXMLS will halt execution of generated sql if an error occurs, though parsing
+	* of the schema will continue.
+	*
+	* @param bool $mode execute
+	* @return bool current continueOnError mode
+	*
+	* @see addSQL(), ExecuteSchema()
+	*/
+	function ContinueOnError( $mode = NULL ) {
+		if( is_bool( $mode ) ) {
+			$this->continueOnError = $mode;
+		}
+		
+		return $this->continueOnError;
+	}
+	
+	/**
+	* Loads an XML schema from a file and converts it to SQL.
+	*
+	* Call this method to load the specified schema (see the DTD for the proper format) from
+	* the filesystem and generate the SQL necessary to create the database
+	* described. This method automatically converts the schema to the latest
+	* axmls schema version.
+	* @see ParseSchemaString()
+	*
+	* @param string $file Name of XML schema file.
+	* @param bool $returnSchema Return schema rather than parsing.
+	* @return array Array of SQL queries, ready to execute
+	*/
+	function ParseSchema( $filename, $returnSchema = FALSE ) {
+		return $this->ParseSchemaString( $this->ConvertSchemaFile( $filename ), $returnSchema );
+	}
+	
+	/**
+	* Loads an XML schema from a file and converts it to SQL.
+	*
+	* Call this method to load the specified schema directly from a file (see
+	* the DTD for the proper format) and generate the SQL necessary to create
+	* the database described by the schema. Use this method when you are dealing
+	* with large schema files. Otherwise, ParseSchema() is faster.
+	* This method does not automatically convert the schema to the latest axmls
+	* schema version. You must convert the schema manually using either the
+	* ConvertSchemaFile() or ConvertSchemaString() method.
+	* @see ParseSchema()
+	* @see ConvertSchemaFile()
+	* @see ConvertSchemaString()
+	*
+	* @param string $file Name of XML schema file.
+	* @param bool $returnSchema Return schema rather than parsing.
+	* @return array Array of SQL queries, ready to execute.
+	*
+	* @deprecated Replaced by adoSchema::ParseSchema() and adoSchema::ParseSchemaString()
+	* @see ParseSchema(), ParseSchemaString()
+	*/
+	function ParseSchemaFile( $filename, $returnSchema = FALSE ) {
+		// Open the file
+		if( !($fp = fopen( $filename, 'r' )) ) {
+			logMsg( 'Unable to open file' );
+			return FALSE;
+		}
+		
+		// do version detection here
+		if( $this->SchemaFileVersion( $filename ) != $this->schemaVersion ) {
+			logMsg( 'Invalid Schema Version' );
+			return FALSE;
+		}
+		
+		if( $returnSchema ) {
+			$xmlstring = '';
+			while( $data = fread( $fp, 4096 ) ) {
+				$xmlstring .= $data . "\n";
+			}
+			return $xmlstring;
+		}
+		
+		$this->success = 2;
+		
+		$xmlParser = $this->create_parser();
+		
+		// Process the file
+		while( $data = fread( $fp, 4096 ) ) {
+			if( !xml_parse( $xmlParser, $data, feof( $fp ) ) ) {
+				die( sprintf(
+					"XML error: %s at line %d",
+					xml_error_string( xml_get_error_code( $xmlParser) ),
+					xml_get_current_line_number( $xmlParser)
+				) );
+			}
+		}
+		
+		xml_parser_free( $xmlParser );
+		
+		return $this->sqlArray;
+	}
+	
+	/**
+	* Converts an XML schema string to SQL.
+	*
+	* Call this method to parse a string containing an XML schema (see the DTD for the proper format)
+	* and generate the SQL necessary to create the database described by the schema. 
+	* @see ParseSchema()
+	*
+	* @param string $xmlstring XML schema string.
+	* @param bool $returnSchema Return schema rather than parsing.
+	* @return array Array of SQL queries, ready to execute.
+	*/
+	function ParseSchemaString( $xmlstring, $returnSchema = FALSE ) {
+		if( !is_string( $xmlstring ) OR empty( $xmlstring ) ) {
+			logMsg( 'Empty or Invalid Schema' );
+			return FALSE;
+		}
+		
+		// do version detection here
+		if( $this->SchemaStringVersion( $xmlstring ) != $this->schemaVersion ) {
+			logMsg( 'Invalid Schema Version' );
+			return FALSE;
+		}
+		
+		if( $returnSchema ) {
+			return $xmlstring;
+		}
+		
+		$this->success = 2;
+		
+		$xmlParser = $this->create_parser();
+		
+		if( !xml_parse( $xmlParser, $xmlstring, TRUE ) ) {
+			die( sprintf(
+				"XML error: %s at line %d",
+				xml_error_string( xml_get_error_code( $xmlParser) ),
+				xml_get_current_line_number( $xmlParser)
+			) );
+		}
+		
+		xml_parser_free( $xmlParser );
+		
+		return $this->sqlArray;
+	}
+	
+	/**
+	* Loads an XML schema from a file and converts it to uninstallation SQL.
+	*
+	* Call this method to load the specified schema (see the DTD for the proper format) from
+	* the filesystem and generate the SQL necessary to remove the database described.
+	* @see RemoveSchemaString()
+	*
+	* @param string $file Name of XML schema file.
+	* @param bool $returnSchema Return schema rather than parsing.
+	* @return array Array of SQL queries, ready to execute
+	*/
+	function RemoveSchema( $filename, $returnSchema = FALSE ) {
+		return $this->RemoveSchemaString( $this->ConvertSchemaFile( $filename ), $returnSchema );
+	}
+	
+	/**
+	* Converts an XML schema string to uninstallation SQL.
+	*
+	* Call this method to parse a string containing an XML schema (see the DTD for the proper format)
+	* and generate the SQL necessary to uninstall the database described by the schema. 
+	* @see RemoveSchema()
+	*
+	* @param string $schema XML schema string.
+	* @param bool $returnSchema Return schema rather than parsing.
+	* @return array Array of SQL queries, ready to execute.
+	*/
+	function RemoveSchemaString( $schema, $returnSchema = FALSE ) {
+		
+		// grab current version
+		if( !( $version = $this->SchemaStringVersion( $schema ) ) ) {
+			return FALSE;
+		}
+		
+		return $this->ParseSchemaString( $this->TransformSchema( $schema, 'remove-' . $version), $returnSchema );
+	}
+	
+	/**
+	* Applies the current XML schema to the database (post execution).
+	*
+	* Call this method to apply the current schema (generally created by calling 
+	* ParseSchema() or ParseSchemaString() ) to the database (creating the tables, indexes, 
+	* and executing other SQL specified in the schema) after parsing.
+	* @see ParseSchema(), ParseSchemaString(), ExecuteInline()
+	*
+	* @param array $sqlArray Array of SQL statements that will be applied rather than
+	*		the current schema.
+	* @param boolean $continueOnErr Continue to apply the schema even if an error occurs.
+	* @returns integer 0 if failure, 1 if errors, 2 if successful.
+	*/
+	function ExecuteSchema( $sqlArray = NULL, $continueOnErr =  NULL ) {
+		if( !is_bool( $continueOnErr ) ) {
+			$continueOnErr = $this->ContinueOnError();
+		}
+		
+		if( !isset( $sqlArray ) ) {
+			$sqlArray = $this->sqlArray;
+		}
+		
+		if( !is_array( $sqlArray ) ) {
+			$this->success = 0;
+		} else {
+			$this->success = $this->dict->ExecuteSQLArray( $sqlArray, $continueOnErr );
+		}
+		
+		return $this->success;
+	}
+	
+	/**
+	* Returns the current SQL array. 
+	*
+	* Call this method to fetch the array of SQL queries resulting from 
+	* ParseSchema() or ParseSchemaString(). 
+	*
+	* @param string $format Format: HTML, TEXT, or NONE (PHP array)
+	* @return array Array of SQL statements or FALSE if an error occurs
+	*/
+	function PrintSQL( $format = 'NONE' ) {
+		$sqlArray = null;
+		return $this->getSQL( $format, $sqlArray );
+	}
+	
+	/**
+	* Saves the current SQL array to the local filesystem as a list of SQL queries.
+	*
+	* Call this method to save the array of SQL queries (generally resulting from a
+	* parsed XML schema) to the filesystem.
+	*
+	* @param string $filename Path and name where the file should be saved.
+	* @return boolean TRUE if save is successful, else FALSE. 
+	*/
+	function SaveSQL( $filename = './schema.sql' ) {
+		
+		if( !isset( $sqlArray ) ) {
+			$sqlArray = $this->sqlArray;
+		}
+		if( !isset( $sqlArray ) ) {
+			return FALSE;
+		}
+		
+		$fp = fopen( $filename, "w" );
+		
+		foreach( $sqlArray as $key => $query ) {
+			fwrite( $fp, $query . ";\n" );
+		}
+		fclose( $fp );
+	}
+	
+	/**
+	* Create an xml parser
+	*
+	* @return object PHP XML parser object
+	*
+	* @access private
+	*/
+	function &create_parser() {
+		// Create the parser
+		$xmlParser = xml_parser_create();
+		xml_set_object( $xmlParser, $this );
+		
+		// Initialize the XML callback functions
+		xml_set_element_handler( $xmlParser, '_tag_open', '_tag_close' );
+		xml_set_character_data_handler( $xmlParser, '_tag_cdata' );
+		
+		return $xmlParser;
+	}
+	
+	/**
+	* XML Callback to process start elements
+	*
+	* @access private
+	*/
+	function _tag_open( &$parser, $tag, $attributes ) {
+		switch( strtoupper( $tag ) ) {
+			case 'TABLE':
+				if( !isset( $attributes['PLATFORM'] ) OR $this->supportedPlatform( $attributes['PLATFORM'] ) ) {
+				$this->obj = new dbTable( $this, $attributes );
+				xml_set_object( $parser, $this->obj );
+				}
+				break;
+			case 'SQL':
+				if( !isset( $attributes['PLATFORM'] ) OR $this->supportedPlatform( $attributes['PLATFORM'] ) ) {
+					$this->obj = new dbQuerySet( $this, $attributes );
+					xml_set_object( $parser, $this->obj );
+				}
+				break;
+			default:
+				// print_r( array( $tag, $attributes ) );
+		}
+		
+	}
+	
+	/**
+	* XML Callback to process CDATA elements
+	*
+	* @access private
+	*/
+	function _tag_cdata( &$parser, $cdata ) {
+	}
+	
+	/**
+	* XML Callback to process end elements
+	*
+	* @access private
+	* @internal
+	*/
+	function _tag_close( &$parser, $tag ) {
+		
+	}
+	
+	/**
+	* Converts an XML schema string to the specified DTD version.
+	*
+	* Call this method to convert a string containing an XML schema to a different AXMLS
+	* DTD version. For instance, to convert a schema created for an pre-1.0 version for 
+	* AXMLS (DTD version 0.1) to a newer version of the DTD (e.g. 0.2). If no DTD version 
+	* parameter is specified, the schema will be converted to the current DTD version. 
+	* If the newFile parameter is provided, the converted schema will be written to the specified
+	* file.
+	* @see ConvertSchemaFile()
+	*
+	* @param string $schema String containing XML schema that will be converted.
+	* @param string $newVersion DTD version to convert to.
+	* @param string $newFile File name of (converted) output file.
+	* @return string Converted XML schema or FALSE if an error occurs.
+	*/
+	function ConvertSchemaString( $schema, $newVersion = NULL, $newFile = NULL ) {
+		
+		// grab current version
+		if( !( $version = $this->SchemaStringVersion( $schema ) ) ) {
+			return FALSE;
+		}
+		
+		if( !isset ($newVersion) ) {
+			$newVersion = $this->schemaVersion;
+		}
+		
+		if( $version == $newVersion ) {
+			$result = $schema;
+		} else {
+			$result = $this->TransformSchema( $schema, 'convert-' . $version . '-' . $newVersion);
+		}
+		
+		if( is_string( $result ) AND is_string( $newFile ) AND ( $fp = fopen( $newFile, 'w' ) ) ) {
+			fwrite( $fp, $result );
+			fclose( $fp );
+		}
+		
+		return $result;
+	}
+
+	/*
+	// compat for pre-4.3 - jlim
+	function _file_get_contents($path)
+	{
+		if (function_exists('file_get_contents')) return file_get_contents($path);
+		return join('',file($path));
+	}*/
+	
+	/**
+	* Converts an XML schema file to the specified DTD version.
+	*
+	* Call this method to convert the specified XML schema file to a different AXMLS
+	* DTD version. For instance, to convert a schema created for an pre-1.0 version for 
+	* AXMLS (DTD version 0.1) to a newer version of the DTD (e.g. 0.2). If no DTD version 
+	* parameter is specified, the schema will be converted to the current DTD version. 
+	* If the newFile parameter is provided, the converted schema will be written to the specified
+	* file.
+	* @see ConvertSchemaString()
+	*
+	* @param string $filename Name of XML schema file that will be converted.
+	* @param string $newVersion DTD version to convert to.
+	* @param string $newFile File name of (converted) output file.
+	* @return string Converted XML schema or FALSE if an error occurs.
+	*/
+	function ConvertSchemaFile( $filename, $newVersion = NULL, $newFile = NULL ) {
+		
+		// grab current version
+		if( !( $version = $this->SchemaFileVersion( $filename ) ) ) {
+			return FALSE;
+		}
+		
+		if( !isset ($newVersion) ) {
+			$newVersion = $this->schemaVersion;
+		}
+		
+		if( $version == $newVersion ) {
+			$result = _file_get_contents( $filename );
+			
+			// remove unicode BOM if present
+			if( substr( $result, 0, 3 ) == sprintf( '%c%c%c', 239, 187, 191 ) ) {
+				$result = substr( $result, 3 );
+			}
+		} else {
+			$result = $this->TransformSchema( $filename, 'convert-' . $version . '-' . $newVersion, 'file' );
+		}
+		
+		if( is_string( $result ) AND is_string( $newFile ) AND ( $fp = fopen( $newFile, 'w' ) ) ) {
+			fwrite( $fp, $result );
+			fclose( $fp );
+		}
+		
+		return $result;
+	}
+	
+	function TransformSchema( $schema, $xsl, $schematype='string' )
+	{
+		// Fail if XSLT extension is not available
+		if( ! function_exists( 'xslt_create' ) ) {
+			return FALSE;
+		}
+		
+		$xsl_file = dirname( __FILE__ ) . '/xsl/' . $xsl . '.xsl';
+		
+		// look for xsl
+		if( !is_readable( $xsl_file ) ) {
+			return FALSE;
+		}
+		
+		switch( $schematype )
+		{
+			case 'file':
+				if( !is_readable( $schema ) ) {
+					return FALSE;
+				}
+				
+				$schema = _file_get_contents( $schema );
+				break;
+			case 'string':
+			default:
+				if( !is_string( $schema ) ) {
+					return FALSE;
+				}
+		}
+		
+		$arguments = array (
+			'/_xml' => $schema,
+			'/_xsl' => _file_get_contents( $xsl_file )
+		);
+		
+		// create an XSLT processor
+		$xh = xslt_create ();
+		
+		// set error handler
+		xslt_set_error_handler ($xh, array (&$this, 'xslt_error_handler'));
+		
+		// process the schema
+		$result = xslt_process ($xh, 'arg:/_xml', 'arg:/_xsl', NULL, $arguments); 
+		
+		xslt_free ($xh);
+		
+		return $result;
+	}
+	
+	/**
+	* Processes XSLT transformation errors
+	*
+	* @param object $parser XML parser object
+	* @param integer $errno Error number
+	* @param integer $level Error level
+	* @param array $fields Error information fields
+	*
+	* @access private
+	*/
+	function xslt_error_handler( $parser, $errno, $level, $fields ) {
+		if( is_array( $fields ) ) {
+			$msg = array(
+				'Message Type' => ucfirst( $fields['msgtype'] ),
+				'Message Code' => $fields['code'],
+				'Message' => $fields['msg'],
+				'Error Number' => $errno,
+				'Level' => $level
+			);
+			
+			switch( $fields['URI'] ) {
+				case 'arg:/_xml':
+					$msg['Input'] = 'XML';
+					break;
+				case 'arg:/_xsl':
+					$msg['Input'] = 'XSL';
+					break;
+				default:
+					$msg['Input'] = $fields['URI'];
+			}
+			
+			$msg['Line'] = $fields['line'];
+		} else {
+			$msg = array(
+				'Message Type' => 'Error',
+				'Error Number' => $errno,
+				'Level' => $level,
+				'Fields' => var_export( $fields, TRUE )
+			);
+		}
+		
+		$error_details = $msg['Message Type'] . ' in XSLT Transformation' . "\n"
+					   . '<table>' . "\n";
+		
+		foreach( $msg as $label => $details ) {
+			$error_details .= '<tr><td><b>' . $label . ': </b></td><td>' . htmlentities( $details ) . '</td></tr>' . "\n";
+		}
+		
+		$error_details .= '</table>';
+		
+		trigger_error( $error_details, E_USER_ERROR );
+	}
+	
+	/**
+	* Returns the AXMLS Schema Version of the requested XML schema file.
+	*
+	* Call this method to obtain the AXMLS DTD version of the requested XML schema file.
+	* @see SchemaStringVersion()
+	*
+	* @param string $filename AXMLS schema file
+	* @return string Schema version number or FALSE on error
+	*/
+	function SchemaFileVersion( $filename ) {
+		// Open the file
+		if( !($fp = fopen( $filename, 'r' )) ) {
+			// die( 'Unable to open file' );
+			return FALSE;
+		}
+		
+		// Process the file
+		while( $data = fread( $fp, 4096 ) ) {
+			if( preg_match( $this->versionRegex, $data, $matches ) ) {
+				return !empty( $matches[2] ) ? $matches[2] : XMLS_DEFAULT_SCHEMA_VERSION;
+			}
+		}
+		
+		return FALSE;
+	}
+	
+	/**
+	* Returns the AXMLS Schema Version of the provided XML schema string.
+	*
+	* Call this method to obtain the AXMLS DTD version of the provided XML schema string.
+	* @see SchemaFileVersion()
+	*
+	* @param string $xmlstring XML schema string
+	* @return string Schema version number or FALSE on error
+	*/
+	function SchemaStringVersion( $xmlstring ) {
+		if( !is_string( $xmlstring ) OR empty( $xmlstring ) ) {
+			return FALSE;
+		}
+		
+		if( preg_match( $this->versionRegex, $xmlstring, $matches ) ) {
+			return !empty( $matches[2] ) ? $matches[2] : XMLS_DEFAULT_SCHEMA_VERSION;
+		}
+		
+		return FALSE;
+	}
+	
+	/**
+	* Extracts an XML schema from an existing database.
+	*
+	* Call this method to create an XML schema string from an existing database.
+	* If the data parameter is set to TRUE, AXMLS will include the data from the database
+	* in the schema. 
+	*
+	* @param boolean $data Include data in schema dump
+	* @indent string indentation to use
+	* @prefix string extract only tables with given prefix
+	* @stripprefix strip prefix string when storing in XML schema
+	* @return string Generated XML schema
+	*/
+	function ExtractSchema( $data = FALSE, $indent = '  ', $prefix = '' , $stripprefix=false) {
+		$old_mode = $this->db->SetFetchMode( ADODB_FETCH_NUM );
+		
+		$schema = '<?xml version="1.0"?>' . "\n"
+				. '<schema version="' . $this->schemaVersion . '">' . "\n";
+		
+		if( is_array( $tables = $this->db->MetaTables( 'TABLES' , ($prefix) ? $prefix.'%' : '') ) ) {
+			foreach( $tables as $table ) {
+				if ($stripprefix) $table = str_replace(str_replace('\\_', '_', $pfx ), '', $table);
+				$schema .= $indent . '<table name="' . htmlentities( $table ) . '">' . "\n";
+				
+				// grab details from database
+				$rs = $this->db->Execute( 'SELECT * FROM ' . $table . ' WHERE -1' );
+				$fields = $this->db->MetaColumns( $table );
+				$indexes = $this->db->MetaIndexes( $table );
+				
+				if( is_array( $fields ) ) {
+					foreach( $fields as $details ) {
+						$extra = '';
+						$content = array();
+						
+						if( isset($details->max_length) && $details->max_length > 0 ) {
+							$extra .= ' size="' . $details->max_length . '"';
+						}
+						
+						if( isset($details->primary_key) && $details->primary_key ) {
+							$content[] = '<KEY/>';
+						} elseif( isset($details->not_null) && $details->not_null ) {
+							$content[] = '<NOTNULL/>';
+						}
+						
+						if( isset($details->has_default) && $details->has_default ) {
+							$content[] = '<DEFAULT value="' . htmlentities( $details->default_value ) . '"/>';
+						}
+						
+						if( isset($details->auto_increment) && $details->auto_increment ) {
+							$content[] = '<AUTOINCREMENT/>';
+						}
+						
+						if( isset($details->unsigned) && $details->unsigned ) {
+							$content[] = '<UNSIGNED/>';
+						}
+						
+						// this stops the creation of 'R' columns,
+						// AUTOINCREMENT is used to create auto columns
+						$details->primary_key = 0;
+						$type = $rs->MetaType( $details );
+						
+						$schema .= str_repeat( $indent, 2 ) . '<field name="' . htmlentities( $details->name ) . '" type="' . $type . '"' . $extra;
+						
+						if( !empty( $content ) ) {
+							$schema .= ">\n" . str_repeat( $indent, 3 )
+									 . implode( "\n" . str_repeat( $indent, 3 ), $content ) . "\n"
+									 . str_repeat( $indent, 2 ) . '</field>' . "\n";
+						} else {
+							$schema .= "/>\n";
+						}
+					}
+				}
+				
+				if( is_array( $indexes ) ) {
+					foreach( $indexes as $index => $details ) {
+						$schema .= str_repeat( $indent, 2 ) . '<index name="' . $index . '">' . "\n";
+						
+						if( $details['unique'] ) {
+							$schema .= str_repeat( $indent, 3 ) . '<UNIQUE/>' . "\n";
+						}
+						
+						foreach( $details['columns'] as $column ) {
+							$schema .= str_repeat( $indent, 3 ) . '<col>' . htmlentities( $column ) . '</col>' . "\n";
+						}
+						
+						$schema .= str_repeat( $indent, 2 ) . '</index>' . "\n";
+					}
+				}
+				
+				if( $data ) {
+					$rs = $this->db->Execute( 'SELECT * FROM ' . $table );
+					
+					if( is_object( $rs ) && !$rs->EOF ) {
+						$schema .= str_repeat( $indent, 2 ) . "<data>\n";
+						
+						while( $row = $rs->FetchRow() ) {
+							foreach( $row as $key => $val ) {
+								if ( $val != htmlentities( $val ) ) {
+									$row[$key] = '<![CDATA[' . $val . ']]>';
+								}
+							}
+							
+							$schema .= str_repeat( $indent, 3 ) . '<row><f>' . implode( '</f><f>', $row ) . "</f></row>\n";
+						}
+						
+						$schema .= str_repeat( $indent, 2 ) . "</data>\n";
+					}
+				}
+				
+				$schema .= $indent . "</table>\n";
+			}
+		}
+		
+		$this->db->SetFetchMode( $old_mode );
+		
+		$schema .= '</schema>';
+		return $schema;
+	}
+	
+	/**
+	* Sets a prefix for database objects
+	*
+	* Call this method to set a standard prefix that will be prepended to all database tables 
+	* and indices when the schema is parsed. Calling setPrefix with no arguments clears the prefix.
+	*
+	* @param string $prefix Prefix that will be prepended.
+	* @param boolean $underscore If TRUE, automatically append an underscore character to the prefix.
+	* @return boolean TRUE if successful, else FALSE
+	*/
+	function SetPrefix( $prefix = '', $underscore = TRUE ) {
+		switch( TRUE ) {
+			// clear prefix
+			case empty( $prefix ):
+				logMsg( 'Cleared prefix' );
+				$this->objectPrefix = '';
+				return TRUE;
+			// prefix too long
+			case strlen( $prefix ) > XMLS_PREFIX_MAXLEN:
+			// prefix contains invalid characters
+			case !preg_match( '/^[a-z][a-z0-9_]+$/i', $prefix ):
+				logMsg( 'Invalid prefix: ' . $prefix );
+				return FALSE;
+		}
+		
+		if( $underscore AND substr( $prefix, -1 ) != '_' ) {
+			$prefix .= '_';
+		}
+		
+		// prefix valid
+		logMsg( 'Set prefix: ' . $prefix );
+		$this->objectPrefix = $prefix;
+		return TRUE;
+	}
+	
+	/**
+	* Returns an object name with the current prefix prepended.
+	*
+	* @param string	$name Name
+	* @return string	Prefixed name
+	*
+	* @access private
+	*/
+	function prefix( $name = '' ) {
+		// if prefix is set
+		if( !empty( $this->objectPrefix ) ) {
+			// Prepend the object prefix to the table name
+			// prepend after quote if used
+			return preg_replace( '/^(`?)(.+)$/', '$1' . $this->objectPrefix . '$2', $name );
+		}
+		
+		// No prefix set. Use name provided.
+		return $name;
+	}
+	
+	/**
+	* Checks if element references a specific platform
+	*
+	* @param string $platform Requested platform
+	* @returns boolean TRUE if platform check succeeds
+	*
+	* @access private
+	*/
+	function supportedPlatform( $platform = NULL ) {
+		if( !empty( $platform ) ) {
+			$regex = '/(^|\|)' . $this->db->databaseType . '(\||$)/i';
+		
+			if( preg_match( '/^- /', $platform ) ) {
+				if (preg_match ( $regex, substr( $platform, 2 ) ) ) {
+					logMsg( 'Platform ' . $platform . ' is NOT supported' );
+					return FALSE;
+				}
+		} else {
+				if( !preg_match ( $regex, $platform ) ) {
+					logMsg( 'Platform ' . $platform . ' is NOT supported' );
+			return FALSE;
+		}
+	}
+		}
+		
+		logMsg( 'Platform ' . $platform . ' is supported' );
+		return TRUE;
+	}
+	
+	/**
+	* Clears the array of generated SQL.
+	*
+	* @access private
+	*/
+	function clearSQL() {
+		$this->sqlArray = array();
+	}
+	
+	/**
+	* Adds SQL into the SQL array.
+	*
+	* @param mixed $sql SQL to Add
+	* @return boolean TRUE if successful, else FALSE.
+	*
+	* @access private
+	*/	
+	function addSQL( $sql = NULL ) {
+		if( is_array( $sql ) ) {
+			foreach( $sql as $line ) {
+				$this->addSQL( $line );
+			}
+			
+			return TRUE;
+		}
+		
+		if( is_string( $sql ) ) {
+			$this->sqlArray[] = $sql;
+			
+			// if executeInline is enabled, and either no errors have occurred or continueOnError is enabled, execute SQL.
+			if( $this->ExecuteInline() && ( $this->success == 2 || $this->ContinueOnError() ) ) {
+				$saved = $this->db->debug;
+				$this->db->debug = $this->debug;
+				$ok = $this->db->Execute( $sql );
+				$this->db->debug = $saved;
+				
+				if( !$ok ) {
+					if( $this->debug ) {
+						ADOConnection::outp( $this->db->ErrorMsg() );
+					}
+					
+					$this->success = 1;
+				}
+			}
+			
+			return TRUE;
+		}
+		
+		return FALSE;
+	}
+	
+	/**
+	* Gets the SQL array in the specified format.
+	*
+	* @param string $format Format
+	* @return mixed SQL
+	*	
+	* @access private
+	*/
+	function getSQL( $format = NULL, $sqlArray = NULL ) {
+		if( !is_array( $sqlArray ) ) {
+			$sqlArray = $this->sqlArray;
+		}
+		
+		if( !is_array( $sqlArray ) ) {
+			return FALSE;
+		}
+		
+		switch( strtolower( $format ) ) {
+			case 'string':
+			case 'text':
+				return !empty( $sqlArray ) ? implode( ";\n\n", $sqlArray ) . ';' : '';
+			case'html':
+				return !empty( $sqlArray ) ? nl2br( htmlentities( implode( ";\n\n", $sqlArray ) . ';' ) ) : '';
+		}
+		
+		return $this->sqlArray;
+	}
+	
+	/**
+	* Destroys an adoSchema object.
+	*
+	* Call this method to clean up after an adoSchema object that is no longer in use.
+	* @deprecated adoSchema now cleans up automatically.
+	*/
+	function Destroy() {
+		set_magic_quotes_runtime( $this->mgq );
+		unset( $this );
+	}
+}
+
+/**
+* Message logging function
+*
+* @access private
+*/
+function logMsg( $msg, $title = NULL, $force = FALSE ) {
+	if( XMLS_DEBUG or $force ) {
+		echo '<pre>';
+		
+		if( isset( $title ) ) {
+			echo '<h3>' . htmlentities( $title ) . '</h3>';
+		}
+		
+		if( @is_object( $this ) ) {
+			echo '[' . get_class( $this ) . '] ';
+		}
+		
+		print_r( $msg );
+		
+		echo '</pre>';
+	}
+}
+?>
Index: /Dev/trunk/rdfapi/util/adodb/adodb.inc.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/adodb.inc.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/adodb.inc.php	(revision 12)
@@ -0,0 +1,4231 @@
+<?php 
+/*
+ * Set tabs to 4 for best viewing.
+ * 
+ * Latest version is available at http://adodb.sourceforge.net
+ * 
+ * This is the main include file for ADOdb.
+ * Database specific drivers are stored in the adodb/drivers/adodb-*.inc.php
+ *
+ * The ADOdb files are formatted so that doxygen can be used to generate documentation.
+ * Doxygen is a documentation generation tool and can be downloaded from http://doxygen.org/
+ */
+
+/**
+	\mainpage 	
+	
+	 @version V4.94 23 Jan 2007  (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
+
+	Released under both BSD license and Lesser GPL library license. You can choose which license
+	you prefer.
+	
+	PHP's database access functions are not standardised. This creates a need for a database 
+	class library to hide the differences between the different database API's (encapsulate 
+	the differences) so we can easily switch databases.
+
+	We currently support MySQL, Oracle, Microsoft SQL Server, Sybase, Sybase SQL Anywhere, DB2,
+	Informix, PostgreSQL, FrontBase, Interbase (Firebird and Borland variants), Foxpro, Access,
+	ADO, SAP DB, SQLite and ODBC. We have had successful reports of connecting to Progress and
+	other databases via ODBC.
+
+	Latest Download at http://adodb.sourceforge.net/
+	  
+ */
+ 
+ if (!defined('_ADODB_LAYER')) {
+ 	define('_ADODB_LAYER',1);
+	
+	//==============================================================================================	
+	// CONSTANT DEFINITIONS
+	//==============================================================================================	
+
+
+	/** 
+	 * Set ADODB_DIR to the directory where this file resides...
+	 * This constant was formerly called $ADODB_RootPath
+	 */
+	if (!defined('ADODB_DIR')) define('ADODB_DIR',dirname(__FILE__));
+	
+	//==============================================================================================	
+	// GLOBAL VARIABLES
+	//==============================================================================================	
+
+	GLOBAL 
+		$ADODB_vers, 		// database version
+		$ADODB_COUNTRECS,	// count number of records returned - slows down query
+		$ADODB_CACHE_DIR,	// directory to cache recordsets
+		$ADODB_EXTENSION,   // ADODB extension installed
+		$ADODB_COMPAT_FETCH, // If $ADODB_COUNTRECS and this is true, $rs->fields is available on EOF
+	 	$ADODB_FETCH_MODE,	// DEFAULT, NUM, ASSOC or BOTH. Default follows native driver default...
+		$ADODB_QUOTE_FIELDNAMES; // Allows you to force quotes (backticks) around field names in queries generated by getinsertsql and getupdatesql.	
+	
+	//==============================================================================================	
+	// GLOBAL SETUP
+	//==============================================================================================	
+	
+	$ADODB_EXTENSION = defined('ADODB_EXTENSION');
+	
+	//********************************************************//
+	/*
+	Controls $ADODB_FORCE_TYPE mode. Default is ADODB_FORCE_VALUE (3).
+	Used in GetUpdateSql and GetInsertSql functions. Thx to Niko, nuko#mbnet.fi
+
+ 		0 = ignore empty fields. All empty fields in array are ignored.
+		1 = force null. All empty, php null and string 'null' fields are changed to sql NULL values.
+		2 = force empty. All empty, php null and string 'null' fields are changed to sql empty '' or 0 values.
+		3 = force value. Value is left as it is. Php null and string 'null' are set to sql NULL values and empty fields '' are set to empty '' sql values.
+	*/
+        define('ADODB_FORCE_IGNORE',0);
+        define('ADODB_FORCE_NULL',1);
+        define('ADODB_FORCE_EMPTY',2);
+        define('ADODB_FORCE_VALUE',3);
+    //********************************************************//
+
+
+	if (!$ADODB_EXTENSION || ADODB_EXTENSION < 4.0) {
+		
+		define('ADODB_BAD_RS','<p>Bad $rs in %s. Connection or SQL invalid. Try using $connection->debug=true;</p>');
+	
+	// allow [ ] @ ` " and . in table names
+		define('ADODB_TABLE_REGEX','([]0-9a-z_\:\"\`\.\@\[-]*)');
+	
+	// prefetching used by oracle
+		if (!defined('ADODB_PREFETCH_ROWS')) define('ADODB_PREFETCH_ROWS',10);
+	
+	
+	/*
+	Controls ADODB_FETCH_ASSOC field-name case. Default is 2, use native case-names.
+	This currently works only with mssql, odbc, oci8po and ibase derived drivers.
+	
+ 		0 = assoc lowercase field names. $rs->fields['orderid']
+		1 = assoc uppercase field names. $rs->fields['ORDERID']
+		2 = use native-case field names. $rs->fields['OrderID']
+	*/
+	
+		define('ADODB_FETCH_DEFAULT',0);
+		define('ADODB_FETCH_NUM',1);
+		define('ADODB_FETCH_ASSOC',2);
+		define('ADODB_FETCH_BOTH',3);
+		
+		if (!defined('TIMESTAMP_FIRST_YEAR')) define('TIMESTAMP_FIRST_YEAR',100);
+	
+		// PHP's version scheme makes converting to numbers difficult - workaround
+		$_adodb_ver = (float) PHP_VERSION;
+		if ($_adodb_ver >= 5.2) {
+			define('ADODB_PHPVER',0x5200);
+		} else if ($_adodb_ver >= 5.0) {
+			define('ADODB_PHPVER',0x5000);
+		} else if ($_adodb_ver > 4.299999) { # 4.3
+			define('ADODB_PHPVER',0x4300);
+		} else if ($_adodb_ver > 4.199999) { # 4.2
+			define('ADODB_PHPVER',0x4200);
+		} else if (strnatcmp(PHP_VERSION,'4.0.5')>=0) {
+			define('ADODB_PHPVER',0x4050);
+		} else {
+			define('ADODB_PHPVER',0x4000);
+		}
+	}
+	
+	//if (!defined('ADODB_ASSOC_CASE')) define('ADODB_ASSOC_CASE',2);
+
+	
+	/**
+	 	Accepts $src and $dest arrays, replacing string $data
+	*/
+	function ADODB_str_replace($src, $dest, $data)
+	{
+		if (ADODB_PHPVER >= 0x4050) return str_replace($src,$dest,$data);
+		
+		$s = reset($src);
+		$d = reset($dest);
+		while ($s !== false) {
+			$data = str_replace($s,$d,$data);
+			$s = next($src);
+			$d = next($dest);
+		}
+		return $data;
+	}
+	
+	function ADODB_Setup()
+	{
+	GLOBAL 
+		$ADODB_vers, 		// database version
+		$ADODB_COUNTRECS,	// count number of records returned - slows down query
+		$ADODB_CACHE_DIR,	// directory to cache recordsets
+	 	$ADODB_FETCH_MODE,
+		$ADODB_FORCE_TYPE,
+		$ADODB_QUOTE_FIELDNAMES;
+		
+		$ADODB_FETCH_MODE = ADODB_FETCH_DEFAULT;
+		$ADODB_FORCE_TYPE = ADODB_FORCE_VALUE;
+
+
+		if (!isset($ADODB_CACHE_DIR)) {
+			$ADODB_CACHE_DIR = '/tmp'; //(isset($_ENV['TMP'])) ? $_ENV['TMP'] : '/tmp';
+		} else {
+			// do not accept url based paths, eg. http:/ or ftp:/
+			if (strpos($ADODB_CACHE_DIR,'://') !== false) 
+				die("Illegal path http:// or ftp://");
+		}
+		
+			
+		// Initialize random number generator for randomizing cache flushes
+		// -- note Since PHP 4.2.0, the seed  becomes optional and defaults to a random value if omitted.
+		 srand(((double)microtime())*1000000);
+		
+		/**
+		 * ADODB version as a string.
+		 */
+		$ADODB_vers = 'V4.94 23 Jan 2007 (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved. Released BSD & LGPL.';
+	
+		/**
+		 * Determines whether recordset->RecordCount() is used. 
+		 * Set to false for highest performance -- RecordCount() will always return -1 then
+		 * for databases that provide "virtual" recordcounts...
+		 */
+		if (!isset($ADODB_COUNTRECS)) $ADODB_COUNTRECS = true; 
+	}
+	
+	
+	//==============================================================================================	
+	// CHANGE NOTHING BELOW UNLESS YOU ARE DESIGNING ADODB
+	//==============================================================================================	
+	
+	ADODB_Setup();
+
+	//==============================================================================================	
+	// CLASS ADOFieldObject
+	//==============================================================================================	
+	/**
+	 * Helper class for FetchFields -- holds info on a column
+	 */
+	class ADOFieldObject { 
+		var $name = '';
+		var $max_length=0;
+		var $type="";
+/*
+		// additional fields by dannym... (danny_milo@yahoo.com)
+		var $not_null = false; 
+		// actually, this has already been built-in in the postgres, fbsql AND mysql module? ^-^
+		// so we can as well make not_null standard (leaving it at "false" does not harm anyways)
+
+		var $has_default = false; // this one I have done only in mysql and postgres for now ... 
+			// others to come (dannym)
+		var $default_value; // default, if any, and supported. Check has_default first.
+*/
+	}
+	
+
+	
+	function ADODB_TransMonitor($dbms, $fn, $errno, $errmsg, $p1, $p2, &$thisConnection)
+	{
+		//print "Errorno ($fn errno=$errno m=$errmsg) ";
+		$thisConnection->_transOK = false;
+		if ($thisConnection->_oldRaiseFn) {
+			$fn = $thisConnection->_oldRaiseFn;
+			$fn($dbms, $fn, $errno, $errmsg, $p1, $p2,$thisConnection);
+		}
+	}
+	
+	//==============================================================================================	
+	// CLASS ADOConnection
+	//==============================================================================================	
+	
+	/**
+	 * Connection object. For connecting to databases, and executing queries.
+	 */ 
+	class ADOConnection {
+	//
+	// PUBLIC VARS 
+	//
+	var $dataProvider = 'native';
+	var $databaseType = '';		/// RDBMS currently in use, eg. odbc, mysql, mssql					
+	var $database = '';			/// Name of database to be used.	
+	var $host = ''; 			/// The hostname of the database server	
+	var $user = ''; 			/// The username which is used to connect to the database server. 
+	var $password = ''; 		/// Password for the username. For security, we no longer store it.
+	var $debug = false; 		/// if set to true will output sql statements
+	var $maxblobsize = 262144; 	/// maximum size of blobs or large text fields (262144 = 256K)-- some db's die otherwise like foxpro
+	var $concat_operator = '+'; /// default concat operator -- change to || for Oracle/Interbase	
+	var $substr = 'substr';		/// substring operator
+	var $length = 'length';		/// string length ofperator
+	var $random = 'rand()';		/// random function
+	var $upperCase = 'upper';		/// uppercase function
+	var $fmtDate = "'Y-m-d'";	/// used by DBDate() as the default date format used by the database
+	var $fmtTimeStamp = "'Y-m-d, h:i:s A'"; /// used by DBTimeStamp as the default timestamp fmt.
+	var $true = '1'; 			/// string that represents TRUE for a database
+	var $false = '0'; 			/// string that represents FALSE for a database
+	var $replaceQuote = "\\'"; 	/// string to use to replace quotes
+	var $nameQuote = '"';		/// string to use to quote identifiers and names
+	var $charSet=false; 		/// character set to use - only for interbase, postgres and oci8
+	var $metaDatabasesSQL = '';
+	var $metaTablesSQL = '';
+	var $uniqueOrderBy = false; /// All order by columns have to be unique
+	var $emptyDate = '&nbsp;';
+	var $emptyTimeStamp = '&nbsp;';
+	var $lastInsID = false;
+	//--
+	var $hasInsertID = false; 		/// supports autoincrement ID?
+	var $hasAffectedRows = false; 	/// supports affected rows for update/delete?
+	var $hasTop = false;			/// support mssql/access SELECT TOP 10 * FROM TABLE
+	var $hasLimit = false;			/// support pgsql/mysql SELECT * FROM TABLE LIMIT 10
+	var $readOnly = false; 			/// this is a readonly database - used by phpLens
+	var $hasMoveFirst = false;  /// has ability to run MoveFirst(), scrolling backwards
+	var $hasGenID = false; 		/// can generate sequences using GenID();
+	var $hasTransactions = true; /// has transactions
+	//--
+	var $genID = 0; 			/// sequence id used by GenID();
+	var $raiseErrorFn = false; 	/// error function to call
+	var $isoDates = false; /// accepts dates in ISO format
+	var $cacheSecs = 3600; /// cache for 1 hour
+
+	// memcache
+	var $memCache = false; /// should we use memCache instead of caching in files
+	var $memCacheHost; /// memCache host
+	var $memCachePort = 11211; /// memCache port
+	var $memCacheCompress = false; /// Use 'true' to store the item compressed (uses zlib)
+
+	var $sysDate = false; /// name of function that returns the current date
+	var $sysTimeStamp = false; /// name of function that returns the current timestamp
+	var $arrayClass = 'ADORecordSet_array'; /// name of class used to generate array recordsets, which are pre-downloaded recordsets
+	
+	var $noNullStrings = false; /// oracle specific stuff - if true ensures that '' is converted to ' '
+	var $numCacheHits = 0; 
+	var $numCacheMisses = 0;
+	var $pageExecuteCountRows = true;
+	var $uniqueSort = false; /// indicates that all fields in order by must be unique
+	var $leftOuter = false; /// operator to use for left outer join in WHERE clause
+	var $rightOuter = false; /// operator to use for right outer join in WHERE clause
+	var $ansiOuter = false; /// whether ansi outer join syntax supported
+	var $autoRollback = false; // autoRollback on PConnect().
+	var $poorAffectedRows = false; // affectedRows not working or unreliable
+	
+	var $fnExecute = false;
+	var $fnCacheExecute = false;
+	var $blobEncodeType = false; // false=not required, 'I'=encode to integer, 'C'=encode to char
+	var $rsPrefix = "ADORecordSet_";
+	
+	var $autoCommit = true; 	/// do not modify this yourself - actually private
+	var $transOff = 0; 			/// temporarily disable transactions
+	var $transCnt = 0; 			/// count of nested transactions
+	
+	var $fetchMode=false;
+	
+	var $null2null = 'null'; // in autoexecute/getinsertsql/getupdatesql, this value will be converted to a null
+	 //
+	 // PRIVATE VARS
+	 //
+	var $_oldRaiseFn =  false;
+	var $_transOK = null;
+	var $_connectionID	= false;	/// The returned link identifier whenever a successful database connection is made.	
+	var $_errorMsg = false;		/// A variable which was used to keep the returned last error message.  The value will
+								/// then returned by the errorMsg() function	
+	var $_errorCode = false;	/// Last error code, not guaranteed to be used - only by oci8					
+	var $_queryID = false;		/// This variable keeps the last created result link identifier
+	
+	var $_isPersistentConnection = false;	/// A boolean variable to state whether its a persistent connection or normal connection.	*/
+	var $_bindInputArray = false; /// set to true if ADOConnection.Execute() permits binding of array parameters.
+	var $_evalAll = false;
+	var $_affected = false;
+	var $_logsql = false;
+	var $_transmode = ''; // transaction mode
+	
+
+	
+	/**
+	 * Constructor
+	 */
+	function ADOConnection()			
+	{
+		die('Virtual Class -- cannot instantiate');
+	}
+	
+	function Version()
+	{
+	global $ADODB_vers;
+	
+		return (float) substr($ADODB_vers,1);
+	}
+	
+	/**
+		Get server version info...
+		
+		@returns An array with 2 elements: $arr['string'] is the description string, 
+			and $arr[version] is the version (also a string).
+	*/
+	function ServerInfo()
+	{
+		return array('description' => '', 'version' => '');
+	}
+	
+	function IsConnected()
+	{
+    	return !empty($this->_connectionID);
+	}
+	
+	function _findvers($str)
+	{
+		if (preg_match('/([0-9]+\.([0-9\.])+)/',$str, $arr)) return $arr[1];
+		else return '';
+	}
+	
+	/**
+	* All error messages go through this bottleneck function.
+	* You can define your own handler by defining the function name in ADODB_OUTP.
+	*/
+	function outp($msg,$newline=true)
+	{
+	global $ADODB_FLUSH,$ADODB_OUTP;
+	
+		if (defined('ADODB_OUTP')) {
+			$fn = ADODB_OUTP;
+			$fn($msg,$newline);
+			return;
+		} else if (isset($ADODB_OUTP)) {
+			$fn = $ADODB_OUTP;
+			$fn($msg,$newline);
+			return;
+		}
+		
+		if ($newline) $msg .= "<br>\n";
+		
+		if (isset($_SERVER['HTTP_USER_AGENT']) || !$newline) echo $msg;
+		else echo strip_tags($msg);
+	
+		
+		if (!empty($ADODB_FLUSH) && ob_get_length() !== false) flush(); //  do not flush if output buffering enabled - useless - thx to Jesse Mullan 
+		
+	}
+	
+	function Time()
+	{
+		$rs =& $this->_Execute("select $this->sysTimeStamp");
+		if ($rs && !$rs->EOF) return $this->UnixTimeStamp(reset($rs->fields));
+		
+		return false;
+	}
+	
+	/**
+	 * Connect to database
+	 *
+	 * @param [argHostname]		Host to connect to
+	 * @param [argUsername]		Userid to login
+	 * @param [argPassword]		Associated password
+	 * @param [argDatabaseName]	database
+	 * @param [forceNew]		force new connection
+	 *
+	 * @return true or false
+	 */	  
+	function Connect($argHostname = "", $argUsername = "", $argPassword = "", $argDatabaseName = "", $forceNew = false) 
+	{
+		if ($argHostname != "") $this->host = $argHostname;
+		if ($argUsername != "") $this->user = $argUsername;
+		if ($argPassword != "") $this->password = $argPassword; // not stored for security reasons
+		if ($argDatabaseName != "") $this->database = $argDatabaseName;		
+		
+		$this->_isPersistentConnection = false;	
+		if ($forceNew) {
+			if ($rez=$this->_nconnect($this->host, $this->user, $this->password, $this->database)) return true;
+		} else {
+			 if ($rez=$this->_connect($this->host, $this->user, $this->password, $this->database)) return true;
+		}
+		if (isset($rez)) {
+			$err = $this->ErrorMsg();
+			if (empty($err)) $err = "Connection error to server '$argHostname' with user '$argUsername'";
+			$ret = false;
+		} else {
+			$err = "Missing extension for ".$this->dataProvider;
+			$ret = 0;
+		}
+		if ($fn = $this->raiseErrorFn) 
+			$fn($this->databaseType,'CONNECT',$this->ErrorNo(),$err,$this->host,$this->database,$this);
+		
+		
+		$this->_connectionID = false;
+		if ($this->debug) ADOConnection::outp( $this->host.': '.$err);
+		return $ret;
+	}	
+	
+	function _nconnect($argHostname, $argUsername, $argPassword, $argDatabaseName)
+	{
+		return $this->_connect($argHostname, $argUsername, $argPassword, $argDatabaseName);
+	}
+	
+	
+	/**
+	 * Always force a new connection to database - currently only works with oracle
+	 *
+	 * @param [argHostname]		Host to connect to
+	 * @param [argUsername]		Userid to login
+	 * @param [argPassword]		Associated password
+	 * @param [argDatabaseName]	database
+	 *
+	 * @return true or false
+	 */	  
+	function NConnect($argHostname = "", $argUsername = "", $argPassword = "", $argDatabaseName = "") 
+	{
+		return $this->Connect($argHostname, $argUsername, $argPassword, $argDatabaseName, true);
+	}
+	
+	/**
+	 * Establish persistent connect to database
+	 *
+	 * @param [argHostname]		Host to connect to
+	 * @param [argUsername]		Userid to login
+	 * @param [argPassword]		Associated password
+	 * @param [argDatabaseName]	database
+	 *
+	 * @return return true or false
+	 */	
+	function PConnect($argHostname = "", $argUsername = "", $argPassword = "", $argDatabaseName = "")
+	{
+		if (defined('ADODB_NEVER_PERSIST')) 
+			return $this->Connect($argHostname,$argUsername,$argPassword,$argDatabaseName);
+		
+		if ($argHostname != "") $this->host = $argHostname;
+		if ($argUsername != "") $this->user = $argUsername;
+		if ($argPassword != "") $this->password = $argPassword;
+		if ($argDatabaseName != "") $this->database = $argDatabaseName;		
+			
+		$this->_isPersistentConnection = true;	
+		if ($rez = $this->_pconnect($this->host, $this->user, $this->password, $this->database)) return true;
+		if (isset($rez)) {
+			$err = $this->ErrorMsg();
+			if (empty($err)) $err = "Connection error to server '$argHostname' with user '$argUsername'";
+			$ret = false;
+		} else {
+			$err = "Missing extension for ".$this->dataProvider;
+			$ret = 0;
+		}
+		if ($fn = $this->raiseErrorFn) {
+			$fn($this->databaseType,'PCONNECT',$this->ErrorNo(),$err,$this->host,$this->database,$this);
+		}
+		
+		$this->_connectionID = false;
+		if ($this->debug) ADOConnection::outp( $this->host.': '.$err);
+		return $ret;
+	}
+
+	// Format date column in sql string given an input format that understands Y M D
+	function SQLDate($fmt, $col=false)
+	{	
+		if (!$col) $col = $this->sysDate;
+		return $col; // child class implement
+	}
+	
+	/**
+	 * Should prepare the sql statement and return the stmt resource.
+	 * For databases that do not support this, we return the $sql. To ensure
+	 * compatibility with databases that do not support prepare:
+	 *
+	 *   $stmt = $db->Prepare("insert into table (id, name) values (?,?)");
+	 *   $db->Execute($stmt,array(1,'Jill')) or die('insert failed');
+	 *   $db->Execute($stmt,array(2,'Joe')) or die('insert failed');
+	 *
+	 * @param sql	SQL to send to database
+	 *
+	 * @return return FALSE, or the prepared statement, or the original sql if
+	 * 			if the database does not support prepare.
+	 *
+	 */	
+	function Prepare($sql)
+	{
+		return $sql;
+	}
+	
+	/**
+	 * Some databases, eg. mssql require a different function for preparing
+	 * stored procedures. So we cannot use Prepare().
+	 *
+	 * Should prepare the stored procedure  and return the stmt resource.
+	 * For databases that do not support this, we return the $sql. To ensure
+	 * compatibility with databases that do not support prepare:
+	 *
+	 * @param sql	SQL to send to database
+	 *
+	 * @return return FALSE, or the prepared statement, or the original sql if
+	 * 			if the database does not support prepare.
+	 *
+	 */	
+	function PrepareSP($sql,$param=true)
+	{
+		return $this->Prepare($sql,$param);
+	}
+	
+	/**
+	* PEAR DB Compat
+	*/
+	function Quote($s)
+	{
+		return $this->qstr($s,false);
+	}
+	
+	/**
+	 Requested by "Karsten Dambekalns" <k.dambekalns@fishfarm.de>
+	*/
+	function QMagic($s)
+	{
+		return $this->qstr($s,get_magic_quotes_gpc());
+	}
+
+	function q(&$s)
+	{
+		#if (!empty($this->qNull)) if ($s == 'null') return $s;
+		$s = $this->qstr($s,false);
+	}
+	
+	/**
+	* PEAR DB Compat - do not use internally. 
+	*/
+	function ErrorNative()
+	{
+		return $this->ErrorNo();
+	}
+
+	
+   /**
+	* PEAR DB Compat - do not use internally. 
+	*/
+	function nextId($seq_name)
+	{
+		return $this->GenID($seq_name);
+	}
+
+	/**
+	*	 Lock a row, will escalate and lock the table if row locking not supported
+	*	will normally free the lock at the end of the transaction
+	*
+	*  @param $table	name of table to lock
+	*  @param $where	where clause to use, eg: "WHERE row=12". If left empty, will escalate to table lock
+	*/
+	function RowLock($table,$where)
+	{
+		return false;
+	}
+	
+	function CommitLock($table)
+	{
+		return $this->CommitTrans();
+	}
+	
+	function RollbackLock($table)
+	{
+		return $this->RollbackTrans();
+	}
+	
+	/**
+	* PEAR DB Compat - do not use internally. 
+	*
+	* The fetch modes for NUMERIC and ASSOC for PEAR DB and ADODB are identical
+	* 	for easy porting :-)
+	*
+	* @param mode	The fetchmode ADODB_FETCH_ASSOC or ADODB_FETCH_NUM
+	* @returns		The previous fetch mode
+	*/
+	function SetFetchMode($mode)
+	{	
+		$old = $this->fetchMode;
+		$this->fetchMode = $mode;
+		
+		if ($old === false) {
+		global $ADODB_FETCH_MODE;
+			return $ADODB_FETCH_MODE;
+		}
+		return $old;
+	}
+	
+
+	/**
+	* PEAR DB Compat - do not use internally. 
+	*/
+	function &Query($sql, $inputarr=false)
+	{
+		$rs = &$this->Execute($sql, $inputarr);
+		if (!$rs && defined('ADODB_PEAR')) return ADODB_PEAR_Error();
+		return $rs;
+	}
+
+	
+	/**
+	* PEAR DB Compat - do not use internally
+	*/
+	function &LimitQuery($sql, $offset, $count, $params=false)
+	{
+		$rs = &$this->SelectLimit($sql, $count, $offset, $params); 
+		if (!$rs && defined('ADODB_PEAR')) return ADODB_PEAR_Error();
+		return $rs;
+	}
+
+	
+	/**
+	* PEAR DB Compat - do not use internally
+	*/
+	function Disconnect()
+	{
+		return $this->Close();
+	}
+	
+	/*
+		 Returns placeholder for parameter, eg.
+		 $DB->Param('a')
+		 
+		 will return ':a' for Oracle, and '?' for most other databases...
+		 
+		 For databases that require positioned params, eg $1, $2, $3 for postgresql,
+		 	pass in Param(false) before setting the first parameter.
+	*/
+	function Param($name,$type='C')
+	{
+		return '?';
+	}
+	
+	/*
+		InParameter and OutParameter are self-documenting versions of Parameter().
+	*/
+	function InParameter(&$stmt,&$var,$name,$maxLen=4000,$type=false)
+	{
+		return $this->Parameter($stmt,$var,$name,false,$maxLen,$type);
+	}
+	
+	/*
+	*/
+	function OutParameter(&$stmt,&$var,$name,$maxLen=4000,$type=false)
+	{
+		return $this->Parameter($stmt,$var,$name,true,$maxLen,$type);
+	
+	}
+
+	
+	/* 
+	Usage in oracle
+		$stmt = $db->Prepare('select * from table where id =:myid and group=:group');
+		$db->Parameter($stmt,$id,'myid');
+		$db->Parameter($stmt,$group,'group',64);
+		$db->Execute();
+		
+		@param $stmt Statement returned by Prepare() or PrepareSP().
+		@param $var PHP variable to bind to
+		@param $name Name of stored procedure variable name to bind to.
+		@param [$isOutput] Indicates direction of parameter 0/false=IN  1=OUT  2= IN/OUT. This is ignored in oci8.
+		@param [$maxLen] Holds an maximum length of the variable.
+		@param [$type] The data type of $var. Legal values depend on driver.
+
+	*/
+	function Parameter(&$stmt,&$var,$name,$isOutput=false,$maxLen=4000,$type=false)
+	{
+		return false;
+	}
+	
+	
+	function IgnoreErrors($saveErrs=false)
+	{
+		if (!$saveErrs) {
+			$saveErrs = array($this->raiseErrorFn,$this->_transOK);
+			$this->raiseErrorFn = false;
+			return $saveErrs;
+		} else {
+			$this->raiseErrorFn = $saveErrs[0];
+			$this->_transOK = $saveErrs[1];
+		}
+	}
+	
+	/**
+		Improved method of initiating a transaction. Used together with CompleteTrans().
+		Advantages include:
+		
+		a. StartTrans/CompleteTrans is nestable, unlike BeginTrans/CommitTrans/RollbackTrans.
+		   Only the outermost block is treated as a transaction.<br>
+		b. CompleteTrans auto-detects SQL errors, and will rollback on errors, commit otherwise.<br>
+		c. All BeginTrans/CommitTrans/RollbackTrans inside a StartTrans/CompleteTrans block
+		   are disabled, making it backward compatible.
+	*/
+	function StartTrans($errfn = 'ADODB_TransMonitor')
+	{
+		if ($this->transOff > 0) {
+			$this->transOff += 1;
+			return;
+		}
+		
+		$this->_oldRaiseFn = $this->raiseErrorFn;
+		$this->raiseErrorFn = $errfn;
+		$this->_transOK = true;
+		
+		if ($this->debug && $this->transCnt > 0) ADOConnection::outp("Bad Transaction: StartTrans called within BeginTrans");
+		$this->BeginTrans();
+		$this->transOff = 1;
+	}
+	
+	
+	/**
+		Used together with StartTrans() to end a transaction. Monitors connection
+		for sql errors, and will commit or rollback as appropriate.
+		
+		@autoComplete if true, monitor sql errors and commit and rollback as appropriate, 
+		and if set to false force rollback even if no SQL error detected.
+		@returns true on commit, false on rollback.
+	*/
+	function CompleteTrans($autoComplete = true)
+	{
+		if ($this->transOff > 1) {
+			$this->transOff -= 1;
+			return true;
+		}
+		$this->raiseErrorFn = $this->_oldRaiseFn;
+		
+		$this->transOff = 0;
+		if ($this->_transOK && $autoComplete) {
+			if (!$this->CommitTrans()) {
+				$this->_transOK = false;
+				if ($this->debug) ADOConnection::outp("Smart Commit failed");
+			} else
+				if ($this->debug) ADOConnection::outp("Smart Commit occurred");
+		} else {
+			$this->_transOK = false;
+			$this->RollbackTrans();
+			if ($this->debug) ADOCOnnection::outp("Smart Rollback occurred");
+		}
+		
+		return $this->_transOK;
+	}
+	
+	/*
+		At the end of a StartTrans/CompleteTrans block, perform a rollback.
+	*/
+	function FailTrans()
+	{
+		if ($this->debug) 
+			if ($this->transOff == 0) {
+				ADOConnection::outp("FailTrans outside StartTrans/CompleteTrans");
+			} else {
+				ADOConnection::outp("FailTrans was called");
+				adodb_backtrace();
+			}
+		$this->_transOK = false;
+	}
+	
+	/**
+		Check if transaction has failed, only for Smart Transactions.
+	*/
+	function HasFailedTrans()
+	{
+		if ($this->transOff > 0) return $this->_transOK == false;
+		return false;
+	}
+	
+	/**
+	 * Execute SQL 
+	 *
+	 * @param sql		SQL statement to execute, or possibly an array holding prepared statement ($sql[0] will hold sql text)
+	 * @param [inputarr]	holds the input data to bind to. Null elements will be set to null.
+	 * @return 		RecordSet or false
+	 */
+	function &Execute($sql,$inputarr=false) 
+	{
+		if ($this->fnExecute) {
+			$fn = $this->fnExecute;
+			$ret =& $fn($this,$sql,$inputarr);
+			if (isset($ret)) return $ret;
+		}
+		if ($inputarr) {
+			if (!is_array($inputarr)) $inputarr = array($inputarr);
+			
+			$element0 = reset($inputarr);
+			# is_object check because oci8 descriptors can be passed in
+			$array_2d = is_array($element0) && !is_object(reset($element0));
+			//remove extra memory copy of input -mikefedyk
+			unset($element0);
+			
+			if (!is_array($sql) && !$this->_bindInputArray) {
+				$sqlarr = explode('?',$sql);
+					
+				if (!$array_2d) $inputarr = array($inputarr);
+				foreach($inputarr as $arr) {
+					$sql = ''; $i = 0;
+					//Use each() instead of foreach to reduce memory usage -mikefedyk
+					while(list(, $v) = each($arr)) {
+						$sql .= $sqlarr[$i];
+						// from Ron Baldwin <ron.baldwin#sourceprose.com>
+						// Only quote string types	
+						$typ = gettype($v);
+						if ($typ == 'string')
+							//New memory copy of input created here -mikefedyk
+							$sql .= $this->qstr($v);
+						else if ($typ == 'double')
+							$sql .= str_replace(',','.',$v); // locales fix so 1.1 does not get converted to 1,1
+						else if ($typ == 'boolean')
+							$sql .= $v ? $this->true : $this->false;
+						else if ($typ == 'object') {
+							if (method_exists($v, '__toString')) $sql .= $this->qstr($v->__toString());
+							else $sql .= $this->qstr((string) $v);
+						} else if ($v === null)
+							$sql .= 'NULL';
+						else
+							$sql .= $v;
+						$i += 1;
+					}
+					if (isset($sqlarr[$i])) {
+						$sql .= $sqlarr[$i];
+						if ($i+1 != sizeof($sqlarr)) ADOConnection::outp( "Input Array does not match ?: ".htmlspecialchars($sql));
+					} else if ($i != sizeof($sqlarr))	
+						ADOConnection::outp( "Input array does not match ?: ".htmlspecialchars($sql));
+		
+					$ret =& $this->_Execute($sql);
+					if (!$ret) return $ret;
+				}	
+			} else {
+				if ($array_2d) {
+					if (is_string($sql))
+						$stmt = $this->Prepare($sql);
+					else
+						$stmt = $sql;
+						
+					foreach($inputarr as $arr) {
+						$ret =& $this->_Execute($stmt,$arr);
+						if (!$ret) return $ret;
+					}
+				} else {
+					$ret =& $this->_Execute($sql,$inputarr);
+				}
+			}
+		} else {
+			$ret =& $this->_Execute($sql,false);
+		}
+
+		return $ret;
+	}
+	
+	
+	function &_Execute($sql,$inputarr=false)
+	{
+		if ($this->debug) {
+			global $ADODB_INCLUDED_LIB;
+			if (empty($ADODB_INCLUDED_LIB)) include(ADODB_DIR.'/adodb-lib.inc.php');
+			$this->_queryID = _adodb_debug_execute($this, $sql,$inputarr);
+		} else {
+			$this->_queryID = @$this->_query($sql,$inputarr);
+		}
+		
+		/************************
+		// OK, query executed
+		*************************/
+
+		if ($this->_queryID === false) { // error handling if query fails
+			if ($this->debug == 99) adodb_backtrace(true,5);	
+			$fn = $this->raiseErrorFn;
+			if ($fn) {
+				$fn($this->databaseType,'EXECUTE',$this->ErrorNo(),$this->ErrorMsg(),$sql,$inputarr,$this);
+			} 
+			$false = false;
+			return $false;
+		} 
+		
+		if ($this->_queryID === true) { // return simplified recordset for inserts/updates/deletes with lower overhead
+			$rs = new ADORecordSet_empty();
+			return $rs;
+		}
+		
+		// return real recordset from select statement
+		$rsclass = $this->rsPrefix.$this->databaseType;
+		$rs = new $rsclass($this->_queryID,$this->fetchMode);
+		$rs->connection = &$this; // Pablo suggestion
+		$rs->Init();
+		if (is_array($sql)) $rs->sql = $sql[0];
+		else $rs->sql = $sql;
+		if ($rs->_numOfRows <= 0) {
+		global $ADODB_COUNTRECS;
+			if ($ADODB_COUNTRECS) {
+				if (!$rs->EOF) { 
+					$rs = &$this->_rs2rs($rs,-1,-1,!is_array($sql));
+					$rs->_queryID = $this->_queryID;
+				} else
+					$rs->_numOfRows = 0;
+			}
+		}
+		return $rs;
+	}
+
+	function CreateSequence($seqname='adodbseq',$startID=1)
+	{
+		if (empty($this->_genSeqSQL)) return false;
+		return $this->Execute(sprintf($this->_genSeqSQL,$seqname,$startID));
+	}
+
+	function DropSequence($seqname='adodbseq')
+	{
+		if (empty($this->_dropSeqSQL)) return false;
+		return $this->Execute(sprintf($this->_dropSeqSQL,$seqname));
+	}
+
+	/**
+	 * Generates a sequence id and stores it in $this->genID;
+	 * GenID is only available if $this->hasGenID = true;
+	 *
+	 * @param seqname		name of sequence to use
+	 * @param startID		if sequence does not exist, start at this ID
+	 * @return		0 if not supported, otherwise a sequence id
+	 */
+	function GenID($seqname='adodbseq',$startID=1)
+	{
+		if (!$this->hasGenID) {
+			return 0; // formerly returns false pre 1.60
+		}
+		
+		$getnext = sprintf($this->_genIDSQL,$seqname);
+		
+		$holdtransOK = $this->_transOK;
+		
+		$save_handler = $this->raiseErrorFn;
+		$this->raiseErrorFn = '';
+		@($rs = $this->Execute($getnext));
+		$this->raiseErrorFn = $save_handler;
+		
+		if (!$rs) {
+			$this->_transOK = $holdtransOK; //if the status was ok before reset
+			$createseq = $this->Execute(sprintf($this->_genSeqSQL,$seqname,$startID));
+			$rs = $this->Execute($getnext);
+		}
+		if ($rs && !$rs->EOF) $this->genID = reset($rs->fields);
+		else $this->genID = 0; // false
+	
+		if ($rs) $rs->Close();
+
+		return $this->genID;
+	}	
+
+	/**
+	 * @param $table string name of the table, not needed by all databases (eg. mysql), default ''
+	 * @param $column string name of the column, not needed by all databases (eg. mysql), default ''
+	 * @return  the last inserted ID. Not all databases support this.
+	 */ 
+	function Insert_ID($table='',$column='')
+	{
+		if ($this->_logsql && $this->lastInsID) return $this->lastInsID;
+		if ($this->hasInsertID) return $this->_insertid($table,$column);
+		if ($this->debug) {
+			ADOConnection::outp( '<p>Insert_ID error</p>');
+			adodb_backtrace();
+		}
+		return false;
+	}
+
+
+	/**
+	 * Portable Insert ID. Pablo Roca <pabloroca#mvps.org>
+	 *
+	 * @return  the last inserted ID. All databases support this. But aware possible
+	 * problems in multiuser environments. Heavy test this before deploying.
+	 */ 
+	function PO_Insert_ID($table="", $id="") 
+	{
+	   if ($this->hasInsertID){
+		   return $this->Insert_ID($table,$id);
+	   } else {
+		   return $this->GetOne("SELECT MAX($id) FROM $table");
+	   }
+	}
+
+	/**
+	* @return # rows affected by UPDATE/DELETE
+	*/ 
+	function Affected_Rows()
+	{
+		if ($this->hasAffectedRows) {
+			if ($this->fnExecute === 'adodb_log_sql') {
+				if ($this->_logsql && $this->_affected !== false) return $this->_affected;
+			}
+			$val = $this->_affectedrows();
+			return ($val < 0) ? false : $val;
+		}
+				  
+		if ($this->debug) ADOConnection::outp( '<p>Affected_Rows error</p>',false);
+		return false;
+	}
+	
+	
+	/**
+	 * @return  the last error message
+	 */
+	function ErrorMsg()
+	{
+		if ($this->_errorMsg) return '!! '.strtoupper($this->dataProvider.' '.$this->databaseType).': '.$this->_errorMsg;
+		else return '';
+	}
+	
+	
+	/**
+	 * @return the last error number. Normally 0 means no error.
+	 */
+	function ErrorNo() 
+	{
+		return ($this->_errorMsg) ? -1 : 0;
+	}
+	
+	function MetaError($err=false)
+	{
+		include_once(ADODB_DIR."/adodb-error.inc.php");
+		if ($err === false) $err = $this->ErrorNo();
+		return adodb_error($this->dataProvider,$this->databaseType,$err);
+	}
+	
+	function MetaErrorMsg($errno)
+	{
+		include_once(ADODB_DIR."/adodb-error.inc.php");
+		return adodb_errormsg($errno);
+	}
+	
+	/**
+	 * @returns an array with the primary key columns in it.
+	 */
+	function MetaPrimaryKeys($table, $owner=false)
+	{
+	// owner not used in base class - see oci8
+		$p = array();
+		$objs =& $this->MetaColumns($table);
+		if ($objs) {
+			foreach($objs as $v) {
+				if (!empty($v->primary_key))
+					$p[] = $v->name;
+			}
+		}
+		if (sizeof($p)) return $p;
+		if (function_exists('ADODB_VIEW_PRIMARYKEYS'))
+			return ADODB_VIEW_PRIMARYKEYS($this->databaseType, $this->database, $table, $owner);
+		return false;
+	}
+	
+	/**
+	 * @returns assoc array where keys are tables, and values are foreign keys
+	 */
+	function MetaForeignKeys($table, $owner=false, $upper=false)
+	{
+		return false;
+	}
+	/**
+	 * Choose a database to connect to. Many databases do not support this.
+	 *
+	 * @param dbName 	is the name of the database to select
+	 * @return 		true or false
+	 */
+	function SelectDB($dbName) 
+	{return false;}
+	
+	
+	/**
+	* Will select, getting rows from $offset (1-based), for $nrows. 
+	* This simulates the MySQL "select * from table limit $offset,$nrows" , and
+	* the PostgreSQL "select * from table limit $nrows offset $offset". Note that
+	* MySQL and PostgreSQL parameter ordering is the opposite of the other.
+	* eg. 
+	*  SelectLimit('select * from table',3); will return rows 1 to 3 (1-based)
+	*  SelectLimit('select * from table',3,2); will return rows 3 to 5 (1-based)
+	*
+	* Uses SELECT TOP for Microsoft databases (when $this->hasTop is set)
+	* BUG: Currently SelectLimit fails with $sql with LIMIT or TOP clause already set
+	*
+	* @param sql
+	* @param [offset]	is the row to start calculations from (1-based)
+	* @param [nrows]		is the number of rows to get
+	* @param [inputarr]	array of bind variables
+	* @param [secs2cache]		is a private parameter only used by jlim
+	* @return		the recordset ($rs->databaseType == 'array')
+ 	*/
+	function &SelectLimit($sql,$nrows=-1,$offset=-1, $inputarr=false,$secs2cache=0)
+	{
+		if ($this->hasTop && $nrows > 0) {
+		// suggested by Reinhard Balling. Access requires top after distinct 
+		 // Informix requires first before distinct - F Riosa
+			$ismssql = (strpos($this->databaseType,'mssql') !== false);
+			if ($ismssql) $isaccess = false;
+			else $isaccess = (strpos($this->databaseType,'access') !== false);
+			
+			if ($offset <= 	0) {
+				
+					// access includes ties in result
+					if ($isaccess) {
+						$sql = preg_replace(
+						'/(^\s*select\s+(distinctrow|distinct)?)/i','\\1 '.$this->hasTop.' '.((integer)$nrows).' ',$sql);
+
+						if ($secs2cache != 0) {
+							$ret =& $this->CacheExecute($secs2cache, $sql,$inputarr);
+						} else {
+							$ret =& $this->Execute($sql,$inputarr);
+						}
+						return $ret; // PHP5 fix
+					} else if ($ismssql){
+						$sql = preg_replace(
+						'/(^\s*select\s+(distinctrow|distinct)?)/i','\\1 '.$this->hasTop.' '.((integer)$nrows).' ',$sql);
+					} else {
+						$sql = preg_replace(
+						'/(^\s*select\s)/i','\\1 '.$this->hasTop.' '.((integer)$nrows).' ',$sql);
+					}
+			} else {
+				$nn = $nrows + $offset;
+				if ($isaccess || $ismssql) {
+					$sql = preg_replace(
+					'/(^\s*select\s+(distinctrow|distinct)?)/i','\\1 '.$this->hasTop.' '.$nn.' ',$sql);
+				} else {
+					$sql = preg_replace(
+					'/(^\s*select\s)/i','\\1 '.$this->hasTop.' '.$nn.' ',$sql);
+				}
+			}
+		}
+		
+		// if $offset>0, we want to skip rows, and $ADODB_COUNTRECS is set, we buffer  rows
+		// 0 to offset-1 which will be discarded anyway. So we disable $ADODB_COUNTRECS.
+		global $ADODB_COUNTRECS;
+		
+		$savec = $ADODB_COUNTRECS;
+		$ADODB_COUNTRECS = false;
+			
+		if ($offset>0){
+			if ($secs2cache != 0) $rs = &$this->CacheExecute($secs2cache,$sql,$inputarr);
+			else $rs = &$this->Execute($sql,$inputarr);
+		} else {
+			if ($secs2cache != 0) $rs = &$this->CacheExecute($secs2cache,$sql,$inputarr);
+			else $rs = &$this->Execute($sql,$inputarr);
+		}
+		$ADODB_COUNTRECS = $savec;
+		if ($rs && !$rs->EOF) {
+			$rs =& $this->_rs2rs($rs,$nrows,$offset);
+		}
+		//print_r($rs);
+		return $rs;
+	}
+	
+	/**
+	* Create serializable recordset. Breaks rs link to connection.
+	*
+	* @param rs			the recordset to serialize
+	*/
+	function &SerializableRS(&$rs)
+	{
+		$rs2 =& $this->_rs2rs($rs);
+		$ignore = false;
+		$rs2->connection =& $ignore;
+		
+		return $rs2;
+	}
+	
+	/**
+	* Convert database recordset to an array recordset
+	* input recordset's cursor should be at beginning, and
+	* old $rs will be closed.
+	*
+	* @param rs			the recordset to copy
+	* @param [nrows]  	number of rows to retrieve (optional)
+	* @param [offset] 	offset by number of rows (optional)
+	* @return 			the new recordset
+	*/
+	function &_rs2rs(&$rs,$nrows=-1,$offset=-1,$close=true)
+	{
+		if (! $rs) {
+			$false = false;
+			return $false;
+		}
+		$dbtype = $rs->databaseType;
+		if (!$dbtype) {
+			$rs = &$rs;  // required to prevent crashing in 4.2.1, but does not happen in 4.3.1 -- why ?
+			return $rs;
+		}
+		if (($dbtype == 'array' || $dbtype == 'csv') && $nrows == -1 && $offset == -1) {
+			$rs->MoveFirst();
+			$rs = &$rs; // required to prevent crashing in 4.2.1, but does not happen in 4.3.1-- why ?
+			return $rs;
+		}
+		$flds = array();
+		for ($i=0, $max=$rs->FieldCount(); $i < $max; $i++) {
+			$flds[] = $rs->FetchField($i);
+		}
+
+		$arr =& $rs->GetArrayLimit($nrows,$offset);
+		//print_r($arr);
+		if ($close) $rs->Close();
+		
+		$arrayClass = $this->arrayClass;
+		
+		$rs2 = new $arrayClass();
+		$rs2->connection = &$this;
+		$rs2->sql = $rs->sql;
+		$rs2->dataProvider = $this->dataProvider;
+		$rs2->InitArrayFields($arr,$flds);
+		$rs2->fetchMode = isset($rs->adodbFetchMode) ? $rs->adodbFetchMode : $rs->fetchMode;
+		return $rs2;
+	}
+	
+	/*
+	* Return all rows. Compat with PEAR DB
+	*/
+	function &GetAll($sql, $inputarr=false)
+	{
+		$arr =& $this->GetArray($sql,$inputarr);
+		return $arr;
+	}
+	
+	function &GetAssoc($sql, $inputarr=false,$force_array = false, $first2cols = false)
+	{
+		$rs =& $this->Execute($sql, $inputarr);
+		if (!$rs) {
+			$false = false;
+			return $false;
+		}
+		$arr =& $rs->GetAssoc($force_array,$first2cols);
+		return $arr;
+	}
+	
+	function &CacheGetAssoc($secs2cache, $sql=false, $inputarr=false,$force_array = false, $first2cols = false)
+	{
+		if (!is_numeric($secs2cache)) {
+			$first2cols = $force_array;
+			$force_array = $inputarr;
+		}
+		$rs =& $this->CacheExecute($secs2cache, $sql, $inputarr);
+		if (!$rs) {
+			$false = false;
+			return $false;
+		}
+		$arr =& $rs->GetAssoc($force_array,$first2cols);
+		return $arr;
+	}
+	
+	/**
+	* Return first element of first row of sql statement. Recordset is disposed
+	* for you.
+	*
+	* @param sql			SQL statement
+	* @param [inputarr]		input bind array
+	*/
+	function GetOne($sql,$inputarr=false)
+	{
+	global $ADODB_COUNTRECS;
+		$crecs = $ADODB_COUNTRECS;
+		$ADODB_COUNTRECS = false;
+		
+		$ret = false;
+		$rs = &$this->Execute($sql,$inputarr);
+		if ($rs) {	
+			if (!$rs->EOF) $ret = reset($rs->fields);
+			$rs->Close();
+		}
+		$ADODB_COUNTRECS = $crecs;
+		return $ret;
+	}
+	
+	function CacheGetOne($secs2cache,$sql=false,$inputarr=false)
+	{
+		$ret = false;
+		$rs = &$this->CacheExecute($secs2cache,$sql,$inputarr);
+		if ($rs) {		
+			if (!$rs->EOF) $ret = reset($rs->fields);
+			$rs->Close();
+		} 
+		
+		return $ret;
+	}
+	
+	function GetCol($sql, $inputarr = false, $trim = false)
+	{
+	  	$rv = false;
+	  	$rs = &$this->Execute($sql, $inputarr);
+	  	if ($rs) {
+			$rv = array();
+	   		if ($trim) {
+				while (!$rs->EOF) {
+					$rv[] = trim(reset($rs->fields));
+					$rs->MoveNext();
+		   		}
+			} else {
+				while (!$rs->EOF) {
+					$rv[] = reset($rs->fields);
+					$rs->MoveNext();
+		   		}
+			}
+	   		$rs->Close();
+	  	}
+	  	return $rv;
+	}
+	
+	function CacheGetCol($secs, $sql = false, $inputarr = false,$trim=false)
+	{
+	  	$rv = false;
+	  	$rs = &$this->CacheExecute($secs, $sql, $inputarr);
+	  	if ($rs) {
+			if ($trim) {
+				while (!$rs->EOF) {
+					$rv[] = trim(reset($rs->fields));
+					$rs->MoveNext();
+		   		}
+			} else {
+				while (!$rs->EOF) {
+					$rv[] = reset($rs->fields);
+					$rs->MoveNext();
+		   		}
+			}
+	   		$rs->Close();
+	  	}
+	  	return $rv;
+	}
+	
+	function &Transpose(&$rs,$addfieldnames=true)
+	{
+		$rs2 =& $this->_rs2rs($rs);
+		$false = false;
+		if (!$rs2) return $false;
+		
+		$rs2->_transpose($addfieldnames);
+		return $rs2;
+	}
+ 
+	/*
+		Calculate the offset of a date for a particular database and generate
+			appropriate SQL. Useful for calculating future/past dates and storing
+			in a database.
+			
+		If dayFraction=1.5 means 1.5 days from now, 1.0/24 for 1 hour.
+	*/
+	function OffsetDate($dayFraction,$date=false)
+	{		
+		if (!$date) $date = $this->sysDate;
+		return  '('.$date.'+'.$dayFraction.')';
+	}
+	
+	
+	/**
+	*
+	* @param sql			SQL statement
+	* @param [inputarr]		input bind array
+	*/
+	function &GetArray($sql,$inputarr=false)
+	{
+	global $ADODB_COUNTRECS;
+		
+		$savec = $ADODB_COUNTRECS;
+		$ADODB_COUNTRECS = false;
+		$rs =& $this->Execute($sql,$inputarr);
+		$ADODB_COUNTRECS = $savec;
+		if (!$rs) 
+			if (defined('ADODB_PEAR')) {
+				$cls = ADODB_PEAR_Error();
+				return $cls;
+			} else {
+				$false = false;
+				return $false;
+			}
+		$arr =& $rs->GetArray();
+		$rs->Close();
+		return $arr;
+	}
+	
+	function &CacheGetAll($secs2cache,$sql=false,$inputarr=false)
+	{
+		$arr =& $this->CacheGetArray($secs2cache,$sql,$inputarr);
+		return $arr;
+	}
+	
+	function &CacheGetArray($secs2cache,$sql=false,$inputarr=false)
+	{
+	global $ADODB_COUNTRECS;
+		
+		$savec = $ADODB_COUNTRECS;
+		$ADODB_COUNTRECS = false;
+		$rs =& $this->CacheExecute($secs2cache,$sql,$inputarr);
+		$ADODB_COUNTRECS = $savec;
+		
+		if (!$rs) 
+			if (defined('ADODB_PEAR')) {
+				$cls = ADODB_PEAR_Error();
+				return $cls;
+			} else {
+				$false = false;
+				return $false;
+			}
+		$arr =& $rs->GetArray();
+		$rs->Close();
+		return $arr;
+	}
+	
+	
+	
+	/**
+	* Return one row of sql statement. Recordset is disposed for you.
+	*
+	* @param sql			SQL statement
+	* @param [inputarr]		input bind array
+	*/
+	function &GetRow($sql,$inputarr=false)
+	{
+	global $ADODB_COUNTRECS;
+		$crecs = $ADODB_COUNTRECS;
+		$ADODB_COUNTRECS = false;
+		
+		$rs =& $this->Execute($sql,$inputarr);
+		
+		$ADODB_COUNTRECS = $crecs;
+		if ($rs) {
+			if (!$rs->EOF) $arr = $rs->fields;
+			else $arr = array();
+			$rs->Close();
+			return $arr;
+		}
+		
+		$false = false;
+		return $false;
+	}
+	
+	function &CacheGetRow($secs2cache,$sql=false,$inputarr=false)
+	{
+		$rs =& $this->CacheExecute($secs2cache,$sql,$inputarr);
+		if ($rs) {
+			$arr = false;
+			if (!$rs->EOF) $arr = $rs->fields;
+			$rs->Close();
+			return $arr;
+		}
+		$false = false;
+		return $false;
+	}
+	
+	/**
+	* Insert or replace a single record. Note: this is not the same as MySQL's replace. 
+	* ADOdb's Replace() uses update-insert semantics, not insert-delete-duplicates of MySQL.
+	* Also note that no table locking is done currently, so it is possible that the
+	* record be inserted twice by two programs...
+	*
+	* $this->Replace('products', array('prodname' =>"'Nails'","price" => 3.99), 'prodname');
+	*
+	* $table		table name
+	* $fieldArray	associative array of data (you must quote strings yourself).
+	* $keyCol		the primary key field name or if compound key, array of field names
+	* autoQuote		set to true to use a hueristic to quote strings. Works with nulls and numbers
+	*					but does not work with dates nor SQL functions.
+	* has_autoinc	the primary key is an auto-inc field, so skip in insert.
+	*
+	* Currently blob replace not supported
+	*
+	* returns 0 = fail, 1 = update, 2 = insert 
+	*/
+	
+	function Replace($table, $fieldArray, $keyCol, $autoQuote=false, $has_autoinc=false)
+	{
+		global $ADODB_INCLUDED_LIB;
+		if (empty($ADODB_INCLUDED_LIB)) include(ADODB_DIR.'/adodb-lib.inc.php');
+		
+		return _adodb_replace($this, $table, $fieldArray, $keyCol, $autoQuote, $has_autoinc);
+	}
+	
+	
+	/**
+	* Will select, getting rows from $offset (1-based), for $nrows. 
+	* This simulates the MySQL "select * from table limit $offset,$nrows" , and
+	* the PostgreSQL "select * from table limit $nrows offset $offset". Note that
+	* MySQL and PostgreSQL parameter ordering is the opposite of the other.
+	* eg. 
+	*  CacheSelectLimit(15,'select * from table',3); will return rows 1 to 3 (1-based)
+	*  CacheSelectLimit(15,'select * from table',3,2); will return rows 3 to 5 (1-based)
+	*
+	* BUG: Currently CacheSelectLimit fails with $sql with LIMIT or TOP clause already set
+	*
+	* @param [secs2cache]	seconds to cache data, set to 0 to force query. This is optional
+	* @param sql
+	* @param [offset]	is the row to start calculations from (1-based)
+	* @param [nrows]	is the number of rows to get
+	* @param [inputarr]	array of bind variables
+	* @return		the recordset ($rs->databaseType == 'array')
+ 	*/
+	function &CacheSelectLimit($secs2cache,$sql,$nrows=-1,$offset=-1,$inputarr=false)
+	{	
+		if (!is_numeric($secs2cache)) {
+			if ($sql === false) $sql = -1;
+			if ($offset == -1) $offset = false;
+									  // sql,	nrows, offset,inputarr
+			$rs =& $this->SelectLimit($secs2cache,$sql,$nrows,$offset,$this->cacheSecs);
+		} else {
+			if ($sql === false) ADOConnection::outp( "Warning: \$sql missing from CacheSelectLimit()");
+			$rs =& $this->SelectLimit($sql,$nrows,$offset,$inputarr,$secs2cache);
+		}
+		return $rs;
+	}
+	
+	
+	/**
+	* Flush cached recordsets that match a particular $sql statement. 
+	* If $sql == false, then we purge all files in the cache.
+ 	*/
+	
+	/**
+   * Flush cached recordsets that match a particular $sql statement. 
+   * If $sql == false, then we purge all files in the cache.
+    */
+	function CacheFlush($sql=false,$inputarr=false)
+	{
+	global $ADODB_CACHE_DIR;
+	
+		if ($this->memCache) {
+		global $ADODB_INCLUDED_MEMCACHE;
+		
+			$key = false;
+			if (empty($ADODB_INCLUDED_MEMCACHE)) include(ADODB_DIR.'/adodb-memcache.lib.inc.php');
+			if ($sql) $key = $this->_gencachename($sql.serialize($inputarr),false,true);
+			FlushMemCache($key, $this->memCacheHost, $this->memCachePort, $this->debug);
+			return;
+		}
+	
+		if (strlen($ADODB_CACHE_DIR) > 1 && !$sql) {
+         /*if (strncmp(PHP_OS,'WIN',3) === 0)
+            $dir = str_replace('/', '\\', $ADODB_CACHE_DIR);
+         else */
+            $dir = $ADODB_CACHE_DIR;
+            
+         if ($this->debug) {
+            ADOConnection::outp( "CacheFlush: $dir<br><pre>\n", $this->_dirFlush($dir),"</pre>");
+         } else {
+            $this->_dirFlush($dir);
+         }
+         return;
+      } 
+      
+      global $ADODB_INCLUDED_CSV;
+      if (empty($ADODB_INCLUDED_CSV)) include(ADODB_DIR.'/adodb-csvlib.inc.php');
+      
+      $f = $this->_gencachename($sql.serialize($inputarr),false);
+      adodb_write_file($f,''); // is adodb_write_file needed?
+      if (!@unlink($f)) {
+         if ($this->debug) ADOConnection::outp( "CacheFlush: failed for $f");
+      }
+   }
+   
+   /**
+   * Private function to erase all of the files and subdirectories in a directory.
+   *
+   * Just specify the directory, and tell it if you want to delete the directory or just clear it out.
+   * Note: $kill_top_level is used internally in the function to flush subdirectories.
+   */
+   function _dirFlush($dir, $kill_top_level = false) {
+      if(!$dh = @opendir($dir)) return;
+      
+      while (($obj = readdir($dh))) {
+         if($obj=='.' || $obj=='..')
+            continue;
+			
+         if (!@unlink($dir.'/'.$obj))
+			  $this->_dirFlush($dir.'/'.$obj, true);
+      }
+      if ($kill_top_level === true)
+         @rmdir($dir);
+      return true;
+   }
+   
+   
+	function xCacheFlush($sql=false,$inputarr=false)
+	{
+	global $ADODB_CACHE_DIR;
+	
+		if ($this->memCache) {
+			global $ADODB_INCLUDED_MEMCACHE;
+			$key = false;
+			if (empty($ADODB_INCLUDED_MEMCACHE)) include(ADODB_DIR.'/adodb-memcache.lib.inc.php');
+			if ($sql) $key = $this->_gencachename($sql.serialize($inputarr),false,true);
+			flushmemCache($key, $this->memCacheHost, $this->memCachePort, $this->debug);
+			return;
+		}
+
+		if (strlen($ADODB_CACHE_DIR) > 1 && !$sql) {
+			if (strncmp(PHP_OS,'WIN',3) === 0) {
+				$cmd = 'del /s '.str_replace('/','\\',$ADODB_CACHE_DIR).'\adodb_*.cache';
+			} else {
+				//$cmd = 'find "'.$ADODB_CACHE_DIR.'" -type f -maxdepth 1 -print0 | xargs -0 rm -f';
+				$cmd = 'rm -rf '.$ADODB_CACHE_DIR.'/[0-9a-f][0-9a-f]/'; 
+				// old version 'rm -f `find '.$ADODB_CACHE_DIR.' -name adodb_*.cache`';
+			}
+			if ($this->debug) {
+				ADOConnection::outp( "CacheFlush: $cmd<br><pre>\n", system($cmd),"</pre>");
+			} else {
+				exec($cmd);
+			}
+			return;
+		} 
+		
+		global $ADODB_INCLUDED_CSV;
+		if (empty($ADODB_INCLUDED_CSV)) include(ADODB_DIR.'/adodb-csvlib.inc.php');
+		
+		$f = $this->_gencachename($sql.serialize($inputarr),false);
+		adodb_write_file($f,''); // is adodb_write_file needed?
+		if (!@unlink($f)) {
+			if ($this->debug) ADOConnection::outp( "CacheFlush: failed for $f");
+		}
+	}
+	
+	/**
+	* Private function to generate filename for caching.
+	* Filename is generated based on:
+	*
+	*  - sql statement
+	*  - database type (oci8, ibase, ifx, etc)
+	*  - database name
+	*  - userid
+	*  - setFetchMode (adodb 4.23)
+	*
+	* When not in safe mode, we create 256 sub-directories in the cache directory ($ADODB_CACHE_DIR). 
+	* Assuming that we can have 50,000 files per directory with good performance, 
+	* then we can scale to 12.8 million unique cached recordsets. Wow!
+ 	*/
+	function _gencachename($sql,$createdir,$memcache=false)
+	{
+	global $ADODB_CACHE_DIR;
+	static $notSafeMode;
+		
+		if ($this->fetchMode === false) { 
+		global $ADODB_FETCH_MODE;
+			$mode = $ADODB_FETCH_MODE;
+		} else {
+			$mode = $this->fetchMode;
+		}
+		$m = md5($sql.$this->databaseType.$this->database.$this->user.$mode);
+		if ($memcache) return $m;
+		
+		if (!isset($notSafeMode)) $notSafeMode = !ini_get('safe_mode');
+		$dir = ($notSafeMode) ? $ADODB_CACHE_DIR.'/'.substr($m,0,2) : $ADODB_CACHE_DIR;
+			
+		if ($createdir && $notSafeMode && !file_exists($dir)) {
+			$oldu = umask(0);
+			if (!mkdir($dir,0771)) 
+				if ($this->debug) ADOConnection::outp( "Unable to mkdir $dir for $sql");
+			umask($oldu);
+		}
+		return $dir.'/adodb_'.$m.'.cache';
+	}
+	
+	
+	/**
+	 * Execute SQL, caching recordsets.
+	 *
+	 * @param [secs2cache]	seconds to cache data, set to 0 to force query. 
+	 *					  This is an optional parameter.
+	 * @param sql		SQL statement to execute
+	 * @param [inputarr]	holds the input data  to bind to
+	 * @return 		RecordSet or false
+	 */
+	function &CacheExecute($secs2cache,$sql=false,$inputarr=false)
+	{
+
+			
+		if (!is_numeric($secs2cache)) {
+			$inputarr = $sql;
+			$sql = $secs2cache;
+			$secs2cache = $this->cacheSecs;
+		}
+		
+		if (is_array($sql)) {
+			$sqlparam = $sql;
+			$sql = $sql[0];
+		} else
+			$sqlparam = $sql;
+			
+		if ($this->memCache) {
+			global $ADODB_INCLUDED_MEMCACHE;
+			if (empty($ADODB_INCLUDED_MEMCACHE)) include(ADODB_DIR.'/adodb-memcache.lib.inc.php');
+			$md5file = $this->_gencachename($sql.serialize($inputarr),false,true);
+		} else {
+		global $ADODB_INCLUDED_CSV;
+			if (empty($ADODB_INCLUDED_CSV)) include(ADODB_DIR.'/adodb-csvlib.inc.php');
+			$md5file = $this->_gencachename($sql.serialize($inputarr),true);
+		}
+
+		$err = '';
+		
+		if ($secs2cache > 0){
+			if ($this->memCache)
+				$rs = &getmemCache($md5file,$err,$secs2cache, $this->memCacheHost, $this->memCachePort);
+			else
+				$rs = &csv2rs($md5file,$err,$secs2cache,$this->arrayClass);
+			$this->numCacheHits += 1;
+		} else {
+			$err='Timeout 1';
+			$rs = false;
+			$this->numCacheMisses += 1;
+		}
+		if (!$rs) {
+		// no cached rs found
+			if ($this->debug) {
+				if (get_magic_quotes_runtime() && !$this->memCache) {
+					ADOConnection::outp("Please disable magic_quotes_runtime - it corrupts cache files :(");
+				}
+				if ($this->debug !== -1) ADOConnection::outp( " $md5file cache failure: $err (see sql below)");
+			}
+			
+			$rs = &$this->Execute($sqlparam,$inputarr);
+
+			if ($rs && $this->memCache) {
+				$rs = &$this->_rs2rs($rs); // read entire recordset into memory immediately
+				if(!putmemCache($md5file, $rs, $this->memCacheHost, $this->memCachePort, $this->memCacheCompress, $this->debug)) {
+					if ($fn = $this->raiseErrorFn)
+						$fn($this->databaseType,'CacheExecute',-32000,"Cache write error",$md5file,$sql,$this);
+					if ($this->debug) ADOConnection::outp( " Cache write error");
+				}
+			} else
+			if ($rs) {
+				$eof = $rs->EOF;
+				$rs = &$this->_rs2rs($rs); // read entire recordset into memory immediately
+				$txt = _rs2serialize($rs,false,$sql); // serialize
+		
+				if (!adodb_write_file($md5file,$txt,$this->debug)) {
+					if ($fn = $this->raiseErrorFn) {
+						$fn($this->databaseType,'CacheExecute',-32000,"Cache write error",$md5file,$sql,$this);
+					}
+					if ($this->debug) ADOConnection::outp( " Cache write error");
+				}
+				if ($rs->EOF && !$eof) {
+					$rs->MoveFirst();
+					//$rs = &csv2rs($md5file,$err);		
+					$rs->connection = &$this; // Pablo suggestion
+				}  
+				
+			} else
+			if (!$this->memCache)
+				@unlink($md5file);
+		} else {
+			$this->_errorMsg = '';
+			$this->_errorCode = 0;
+			
+			if ($this->fnCacheExecute) {
+				$fn = $this->fnCacheExecute;
+				$fn($this, $secs2cache, $sql, $inputarr);
+			}
+		// ok, set cached object found
+			$rs->connection = &$this; // Pablo suggestion
+			if ($this->debug){ 
+					
+				$inBrowser = isset($_SERVER['HTTP_USER_AGENT']);
+				$ttl = $rs->timeCreated + $secs2cache - time();
+				$s = is_array($sql) ? $sql[0] : $sql;
+				if ($inBrowser) $s = '<i>'.htmlspecialchars($s).'</i>';
+				
+				ADOConnection::outp( " $md5file reloaded, ttl=$ttl [ $s ]");
+			}
+		}
+		return $rs;
+	}
+	
+	
+	/* 
+		Similar to PEAR DB's autoExecute(), except that 
+		$mode can be 'INSERT' or 'UPDATE' or DB_AUTOQUERY_INSERT or DB_AUTOQUERY_UPDATE
+		If $mode == 'UPDATE', then $where is compulsory as a safety measure.
+		
+		$forceUpdate means that even if the data has not changed, perform update.
+	 */
+	function& AutoExecute($table, $fields_values, $mode = 'INSERT', $where = FALSE, $forceUpdate=true, $magicq=false) 
+	{
+		$false = false;
+		$sql = 'SELECT * FROM '.$table;  
+		if ($where!==FALSE) $sql .= ' WHERE '.$where;
+		else if ($mode == 'UPDATE' || $mode == 2 /* DB_AUTOQUERY_UPDATE */) {
+			ADOConnection::outp('AutoExecute: Illegal mode=UPDATE with empty WHERE clause');
+			return $false;
+		}
+
+		$rs =& $this->SelectLimit($sql,1);
+		if (!$rs) return $false; // table does not exist
+		$rs->tableName = $table;
+		
+		switch((string) $mode) {
+		case 'UPDATE':
+		case '2':
+			$sql = $this->GetUpdateSQL($rs, $fields_values, $forceUpdate, $magicq);
+			break;
+		case 'INSERT':
+		case '1':
+			$sql = $this->GetInsertSQL($rs, $fields_values, $magicq);
+			break;
+		default:
+			ADOConnection::outp("AutoExecute: Unknown mode=$mode");
+			return $false;
+		}
+		$ret = false;
+		if ($sql) $ret = $this->Execute($sql);
+		if ($ret) $ret = true;
+		return $ret;
+	}
+	
+	
+	/**
+	 * Generates an Update Query based on an existing recordset.
+	 * $arrFields is an associative array of fields with the value
+	 * that should be assigned.
+	 *
+	 * Note: This function should only be used on a recordset
+	 *	   that is run against a single table and sql should only 
+	 *		 be a simple select stmt with no groupby/orderby/limit
+	 *
+	 * "Jonathan Younger" <jyounger@unilab.com>
+  	 */
+	function GetUpdateSQL(&$rs, $arrFields,$forceUpdate=false,$magicq=false,$force=null)
+	{
+		global $ADODB_INCLUDED_LIB;
+
+        //********************************************************//
+        //This is here to maintain compatibility
+        //with older adodb versions. Sets force type to force nulls if $forcenulls is set.
+		if (!isset($force)) {
+				global $ADODB_FORCE_TYPE;
+			    $force = $ADODB_FORCE_TYPE;
+		}
+		//********************************************************//
+
+		if (empty($ADODB_INCLUDED_LIB)) include(ADODB_DIR.'/adodb-lib.inc.php');
+		return _adodb_getupdatesql($this,$rs,$arrFields,$forceUpdate,$magicq,$force);
+	}
+
+	/**
+	 * Generates an Insert Query based on an existing recordset.
+	 * $arrFields is an associative array of fields with the value
+	 * that should be assigned.
+	 *
+	 * Note: This function should only be used on a recordset
+	 *	   that is run against a single table.
+  	 */
+	function GetInsertSQL(&$rs, $arrFields,$magicq=false,$force=null)
+	{	
+		global $ADODB_INCLUDED_LIB;
+		if (!isset($force)) {
+			global $ADODB_FORCE_TYPE;
+			$force = $ADODB_FORCE_TYPE;
+			
+		}
+		if (empty($ADODB_INCLUDED_LIB)) include(ADODB_DIR.'/adodb-lib.inc.php');
+		return _adodb_getinsertsql($this,$rs,$arrFields,$magicq,$force);
+	}
+	
+
+	/**
+	* Update a blob column, given a where clause. There are more sophisticated
+	* blob handling functions that we could have implemented, but all require
+	* a very complex API. Instead we have chosen something that is extremely
+	* simple to understand and use. 
+	*
+	* Note: $blobtype supports 'BLOB' and 'CLOB', default is BLOB of course.
+	*
+	* Usage to update a $blobvalue which has a primary key blob_id=1 into a 
+	* field blobtable.blobcolumn:
+	*
+	*	UpdateBlob('blobtable', 'blobcolumn', $blobvalue, 'blob_id=1');
+	*
+	* Insert example:
+	*
+	*	$conn->Execute('INSERT INTO blobtable (id, blobcol) VALUES (1, null)');
+	*	$conn->UpdateBlob('blobtable','blobcol',$blob,'id=1');
+	*/
+	
+	function UpdateBlob($table,$column,$val,$where,$blobtype='BLOB')
+	{
+		return $this->Execute("UPDATE $table SET $column=? WHERE $where",array($val)) != false;
+	}
+
+	/**
+	* Usage:
+	*	UpdateBlob('TABLE', 'COLUMN', '/path/to/file', 'ID=1');
+	*	
+	*	$blobtype supports 'BLOB' and 'CLOB'
+	*
+	*	$conn->Execute('INSERT INTO blobtable (id, blobcol) VALUES (1, null)');
+	*	$conn->UpdateBlob('blobtable','blobcol',$blobpath,'id=1');
+	*/
+	function UpdateBlobFile($table,$column,$path,$where,$blobtype='BLOB')
+	{
+		$fd = fopen($path,'rb');
+		if ($fd === false) return false;
+		$val = fread($fd,filesize($path));
+		fclose($fd);
+		return $this->UpdateBlob($table,$column,$val,$where,$blobtype);
+	}
+	
+	function BlobDecode($blob)
+	{
+		return $blob;
+	}
+	
+	function BlobEncode($blob)
+	{
+		return $blob;
+	}
+	
+	function SetCharSet($charset)
+	{
+		return false;
+	}
+	
+	function IfNull( $field, $ifNull ) 
+	{
+		return " CASE WHEN $field is null THEN $ifNull ELSE $field END ";
+	}
+	
+	function LogSQL($enable=true)
+	{
+		include_once(ADODB_DIR.'/adodb-perf.inc.php');
+		
+		if ($enable) $this->fnExecute = 'adodb_log_sql';
+		else $this->fnExecute = false;
+		
+		$old = $this->_logsql;	
+		$this->_logsql = $enable;
+		if ($enable && !$old) $this->_affected = false;
+		return $old;
+	}
+	
+	function GetCharSet()
+	{
+		return false;
+	}
+	
+	/**
+	* Usage:
+	*	UpdateClob('TABLE', 'COLUMN', $var, 'ID=1', 'CLOB');
+	*
+	*	$conn->Execute('INSERT INTO clobtable (id, clobcol) VALUES (1, null)');
+	*	$conn->UpdateClob('clobtable','clobcol',$clob,'id=1');
+	*/
+	function UpdateClob($table,$column,$val,$where)
+	{
+		return $this->UpdateBlob($table,$column,$val,$where,'CLOB');
+	}
+	
+	// not the fastest implementation - quick and dirty - jlim
+	// for best performance, use the actual $rs->MetaType().
+	function MetaType($t,$len=-1,$fieldobj=false)
+	{
+		
+		if (empty($this->_metars)) {
+			$rsclass = $this->rsPrefix.$this->databaseType;
+			$this->_metars = new $rsclass(false,$this->fetchMode); 
+			$this->_metars->connection =& $this;
+		}
+		return $this->_metars->MetaType($t,$len,$fieldobj);
+	}
+	
+	
+	/**
+	*  Change the SQL connection locale to a specified locale.
+	*  This is used to get the date formats written depending on the client locale.
+	*/
+	function SetDateLocale($locale = 'En')
+	{
+		$this->locale = $locale;
+		switch (strtoupper($locale))
+		{
+			case 'EN':
+				$this->fmtDate="'Y-m-d'";
+				$this->fmtTimeStamp = "'Y-m-d H:i:s'";
+				break;
+				
+			case 'US':
+				$this->fmtDate = "'m-d-Y'";
+				$this->fmtTimeStamp = "'m-d-Y H:i:s'";
+				break;
+				
+			case 'PT_BR': 	
+			case 'NL':
+			case 'FR':
+			case 'RO':
+			case 'IT':
+				$this->fmtDate="'d-m-Y'";
+				$this->fmtTimeStamp = "'d-m-Y H:i:s'";
+				break;
+				
+			case 'GE':
+				$this->fmtDate="'d.m.Y'";
+				$this->fmtTimeStamp = "'d.m.Y H:i:s'";
+				break;
+				
+			default:
+				$this->fmtDate="'Y-m-d'";
+				$this->fmtTimeStamp = "'Y-m-d H:i:s'";
+				break;
+		}
+	}
+
+	function &GetActiveRecordsClass($class, $table,$whereOrderBy=false,$bindarr=false, $primkeyArr=false)
+	{
+	global $_ADODB_ACTIVE_DBS;
+	
+		$save = $this->SetFetchMode(ADODB_FETCH_NUM);
+		if (empty($whereOrderBy)) $whereOrderBy = '1=1';
+		$rows = $this->GetAll("select * from ".$table.' WHERE '.$whereOrderBy,$bindarr);
+		$this->SetFetchMode($save);
+		
+		$false = false;
+		
+		if ($rows === false) {	
+			return $false;
+		}
+		
+		
+		if (!isset($_ADODB_ACTIVE_DBS)) {
+			include(ADODB_DIR.'/adodb-active-record.inc.php');
+		}	
+		if (!class_exists($class)) {
+			ADOConnection::outp("Unknown class $class in GetActiveRcordsClass()");
+			return $false;
+		}
+		$arr = array();
+		foreach($rows as $row) {
+		
+			$obj = new $class($table,$primkeyArr,$this);
+			if ($obj->ErrorMsg()){
+				$this->_errorMsg = $obj->ErrorMsg();
+				return $false;
+			}
+			$obj->Set($row);
+			$arr[] = $obj;
+		}
+		return $arr;
+	}
+	
+	function &GetActiveRecords($table,$where=false,$bindarr=false,$primkeyArr=false)
+	{
+		$arr =& $this->GetActiveRecordsClass('ADODB_Active_Record', $table, $where, $bindarr, $primkeyArr);
+		return $arr;
+	}
+	
+	/**
+	 * Close Connection
+	 */
+	function Close()
+	{
+		$rez = $this->_close();
+		$this->_connectionID = false;
+		return $rez;
+	}
+	
+	/**
+	 * Begin a Transaction. Must be followed by CommitTrans() or RollbackTrans().
+	 *
+	 * @return true if succeeded or false if database does not support transactions
+	 */
+	function BeginTrans() 
+	{
+		if ($this->debug) ADOConnection::outp("BeginTrans: Transactions not supported for this driver");
+		return false;
+	}
+	
+	/* set transaction mode */
+	function SetTransactionMode( $transaction_mode ) 
+	{
+		$transaction_mode = $this->MetaTransaction($transaction_mode, $this->dataProvider);
+		$this->_transmode  = $transaction_mode;
+	}
+/*
+http://msdn2.microsoft.com/en-US/ms173763.aspx
+http://dev.mysql.com/doc/refman/5.0/en/innodb-transaction-isolation.html
+http://www.postgresql.org/docs/8.1/interactive/sql-set-transaction.html
+http://www.stanford.edu/dept/itss/docs/oracle/10g/server.101/b10759/statements_10005.htm
+*/
+	function MetaTransaction($mode,$db)
+	{
+		$mode = strtoupper($mode);
+		$mode = str_replace('ISOLATION LEVEL ','',$mode);
+		
+		switch($mode) {
+
+		case 'READ UNCOMMITTED':
+			switch($db) { 
+			case 'oci8':
+			case 'oracle':
+				return 'ISOLATION LEVEL READ COMMITTED';
+			default:
+				return 'ISOLATION LEVEL READ UNCOMMITTED';
+			}
+			break;
+					
+		case 'READ COMMITTED':
+				return 'ISOLATION LEVEL READ COMMITTED';
+			break;
+			
+		case 'REPEATABLE READ':
+			switch($db) {
+			case 'oci8':
+			case 'oracle':
+				return 'ISOLATION LEVEL SERIALIZABLE';
+			default:
+				return 'ISOLATION LEVEL REPEATABLE READ';
+			}
+			break;
+			
+		case 'SERIALIZABLE':
+				return 'ISOLATION LEVEL SERIALIZABLE';
+			break;
+			
+		default:
+			return $mode;
+		}
+	}
+	
+	/**
+	 * If database does not support transactions, always return true as data always commited
+	 *
+	 * @param $ok  set to false to rollback transaction, true to commit
+	 *
+	 * @return true/false.
+	 */
+	function CommitTrans($ok=true) 
+	{ return true;}
+	
+	
+	/**
+	 * If database does not support transactions, rollbacks always fail, so return false
+	 *
+	 * @return true/false.
+	 */
+	function RollbackTrans() 
+	{ return false;}
+
+
+	/**
+	 * return the databases that the driver can connect to. 
+	 * Some databases will return an empty array.
+	 *
+	 * @return an array of database names.
+	 */
+		function MetaDatabases() 
+		{
+		global $ADODB_FETCH_MODE;
+		
+			if ($this->metaDatabasesSQL) {
+				$save = $ADODB_FETCH_MODE; 
+				$ADODB_FETCH_MODE = ADODB_FETCH_NUM; 
+				
+				if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false);
+				
+				$arr = $this->GetCol($this->metaDatabasesSQL);
+				if (isset($savem)) $this->SetFetchMode($savem);
+				$ADODB_FETCH_MODE = $save; 
+			
+				return $arr;
+			}
+			
+			return false;
+		}
+	
+		
+	/**
+	 * @param ttype can either be 'VIEW' or 'TABLE' or false. 
+	 * 		If false, both views and tables are returned.
+	 *		"VIEW" returns only views
+	 *		"TABLE" returns only tables
+	 * @param showSchema returns the schema/user with the table name, eg. USER.TABLE
+	 * @param mask  is the input mask - only supported by oci8 and postgresql
+	 *
+	 * @return  array of tables for current database.
+	 */ 
+	function &MetaTables($ttype=false,$showSchema=false,$mask=false) 
+	{
+	global $ADODB_FETCH_MODE;
+	
+		
+		$false = false;
+		if ($mask) {
+			return $false;
+		}
+		if ($this->metaTablesSQL) {
+			$save = $ADODB_FETCH_MODE; 
+			$ADODB_FETCH_MODE = ADODB_FETCH_NUM; 
+			
+			if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false);
+			
+			$rs = $this->Execute($this->metaTablesSQL);
+			if (isset($savem)) $this->SetFetchMode($savem);
+			$ADODB_FETCH_MODE = $save; 
+			
+			if ($rs === false) return $false;
+			$arr =& $rs->GetArray();
+			$arr2 = array();
+			
+			if ($hast = ($ttype && isset($arr[0][1]))) { 
+				$showt = strncmp($ttype,'T',1);
+			}
+			
+			for ($i=0; $i < sizeof($arr); $i++) {
+				if ($hast) {
+					if ($showt == 0) {
+						if (strncmp($arr[$i][1],'T',1) == 0) $arr2[] = trim($arr[$i][0]);
+					} else {
+						if (strncmp($arr[$i][1],'V',1) == 0) $arr2[] = trim($arr[$i][0]);
+					}
+				} else
+					$arr2[] = trim($arr[$i][0]);
+			}
+			$rs->Close();
+			return $arr2;
+		}
+		return $false;
+	}
+	
+	
+	function _findschema(&$table,&$schema)
+	{
+		if (!$schema && ($at = strpos($table,'.')) !== false) {
+			$schema = substr($table,0,$at);
+			$table = substr($table,$at+1);
+		}
+	}
+	
+	/**
+	 * List columns in a database as an array of ADOFieldObjects. 
+	 * See top of file for definition of object.
+	 *
+	 * @param $table	table name to query
+	 * @param $normalize	makes table name case-insensitive (required by some databases)
+	 * @schema is optional database schema to use - not supported by all databases.
+	 *
+	 * @return  array of ADOFieldObjects for current table.
+	 */
+	function &MetaColumns($table,$normalize=true) 
+	{
+	global $ADODB_FETCH_MODE;
+		
+		$false = false;
+		
+		if (!empty($this->metaColumnsSQL)) {
+		
+			$schema = false;
+			$this->_findschema($table,$schema);
+		
+			$save = $ADODB_FETCH_MODE;
+			$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
+			if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false);
+			$rs = $this->Execute(sprintf($this->metaColumnsSQL,($normalize)?strtoupper($table):$table));
+			if (isset($savem)) $this->SetFetchMode($savem);
+			$ADODB_FETCH_MODE = $save;
+			if ($rs === false || $rs->EOF) return $false;
+
+			$retarr = array();
+			while (!$rs->EOF) { //print_r($rs->fields);
+				$fld = new ADOFieldObject();
+				$fld->name = $rs->fields[0];
+				$fld->type = $rs->fields[1];
+				if (isset($rs->fields[3]) && $rs->fields[3]) {
+					if ($rs->fields[3]>0) $fld->max_length = $rs->fields[3];
+					$fld->scale = $rs->fields[4];
+					if ($fld->scale>0) $fld->max_length += 1;
+				} else
+					$fld->max_length = $rs->fields[2];
+					
+				if ($ADODB_FETCH_MODE == ADODB_FETCH_NUM) $retarr[] = $fld;	
+				else $retarr[strtoupper($fld->name)] = $fld;
+				$rs->MoveNext();
+			}
+			$rs->Close();
+			return $retarr;	
+		}
+		return $false;
+	}
+	
+    /**
+      * List indexes on a table as an array.
+      * @param table  table name to query
+      * @param primary true to only show primary keys. Not actually used for most databases
+	  *
+      * @return array of indexes on current table. Each element represents an index, and is itself an associative array.
+	  
+		 Array (
+		    [name_of_index] => Array
+		      (
+	          [unique] => true or false
+	          [columns] => Array
+	          (
+	          	[0] => firstname
+		      	[1] => lastname
+	          )
+		)		
+      */
+     function &MetaIndexes($table, $primary = false, $owner = false)
+     {
+	 		$false = false;
+            return $false;
+     }
+
+	/**
+	 * List columns names in a table as an array. 
+	 * @param table	table name to query
+	 *
+	 * @return  array of column names for current table.
+	 */ 
+	function &MetaColumnNames($table, $numIndexes=false,$useattnum=false /* only for postgres */) 
+	{
+		$objarr =& $this->MetaColumns($table);
+		if (!is_array($objarr)) {
+			$false = false;
+			return $false;
+		}
+		$arr = array();
+		if ($numIndexes) {
+			$i = 0;
+			if ($useattnum) {
+				foreach($objarr as $v) 
+					$arr[$v->attnum] = $v->name;
+				
+			} else
+				foreach($objarr as $v) $arr[$i++] = $v->name;
+		} else
+			foreach($objarr as $v) $arr[strtoupper($v->name)] = $v->name;
+		
+		return $arr;
+	}
+			
+	/**
+	 * Different SQL databases used different methods to combine strings together.
+	 * This function provides a wrapper. 
+	 * 
+	 * param s	variable number of string parameters
+	 *
+	 * Usage: $db->Concat($str1,$str2);
+	 * 
+	 * @return concatenated string
+	 */ 	 
+	function Concat()
+	{	
+		$arr = func_get_args();
+		return implode($this->concat_operator, $arr);
+	}
+	
+	
+	/**
+	 * Converts a date "d" to a string that the database can understand.
+	 *
+	 * @param d	a date in Unix date time format.
+	 *
+	 * @return  date string in database date format
+	 */
+	function DBDate($d)
+	{
+		if (empty($d) && $d !== 0) return 'null';
+
+		if (is_string($d) && !is_numeric($d)) {
+			if ($d === 'null' || strncmp($d,"'",1) === 0) return $d;
+			if ($this->isoDates) return "'$d'";
+			$d = ADOConnection::UnixDate($d);
+		}
+
+		return adodb_date($this->fmtDate,$d);
+	}
+	
+	function BindDate($d)
+	{
+		$d = $this->DBDate($d);
+		if (strncmp($d,"'",1)) return $d;
+		
+		return substr($d,1,strlen($d)-2);
+	}
+	
+	function BindTimeStamp($d)
+	{
+		$d = $this->DBTimeStamp($d);
+		if (strncmp($d,"'",1)) return $d;
+		
+		return substr($d,1,strlen($d)-2);
+	}
+	
+	
+	/**
+	 * Converts a timestamp "ts" to a string that the database can understand.
+	 *
+	 * @param ts	a timestamp in Unix date time format.
+	 *
+	 * @return  timestamp string in database timestamp format
+	 */
+	function DBTimeStamp($ts)
+	{
+		if (empty($ts) && $ts !== 0) return 'null';
+
+		# strlen(14) allows YYYYMMDDHHMMSS format
+		if (!is_string($ts) || (is_numeric($ts) && strlen($ts)<14)) 
+			return adodb_date($this->fmtTimeStamp,$ts);
+		
+		if ($ts === 'null') return $ts;
+		if ($this->isoDates && strlen($ts) !== 14) return "'$ts'";
+		
+		$ts = ADOConnection::UnixTimeStamp($ts);
+		return adodb_date($this->fmtTimeStamp,$ts);
+	}
+	
+	/**
+	 * Also in ADORecordSet.
+	 * @param $v is a date string in YYYY-MM-DD format
+	 *
+	 * @return date in unix timestamp format, or 0 if before TIMESTAMP_FIRST_YEAR, or false if invalid date format
+	 */
+	function UnixDate($v)
+	{
+		if (is_object($v)) {
+		// odbtp support
+		//( [year] => 2004 [month] => 9 [day] => 4 [hour] => 12 [minute] => 44 [second] => 8 [fraction] => 0 )
+			return adodb_mktime($v->hour,$v->minute,$v->second,$v->month,$v->day, $v->year);
+		}
+	
+		if (is_numeric($v) && strlen($v) !== 8) return $v;
+		if (!preg_match( "|^([0-9]{4})[-/\.]?([0-9]{1,2})[-/\.]?([0-9]{1,2})|", 
+			($v), $rr)) return false;
+
+		if ($rr[1] <= TIMESTAMP_FIRST_YEAR) return 0;
+		// h-m-s-MM-DD-YY
+		return @adodb_mktime(0,0,0,$rr[2],$rr[3],$rr[1]);
+	}
+	
+
+	/**
+	 * Also in ADORecordSet.
+	 * @param $v is a timestamp string in YYYY-MM-DD HH-NN-SS format
+	 *
+	 * @return date in unix timestamp format, or 0 if before TIMESTAMP_FIRST_YEAR, or false if invalid date format
+	 */
+	function UnixTimeStamp($v)
+	{
+		if (is_object($v)) {
+		// odbtp support
+		//( [year] => 2004 [month] => 9 [day] => 4 [hour] => 12 [minute] => 44 [second] => 8 [fraction] => 0 )
+			return adodb_mktime($v->hour,$v->minute,$v->second,$v->month,$v->day, $v->year);
+		}
+		
+		if (!preg_match( 
+			"|^([0-9]{4})[-/\.]?([0-9]{1,2})[-/\.]?([0-9]{1,2})[ ,-]*(([0-9]{1,2}):?([0-9]{1,2}):?([0-9\.]{1,4}))?|", 
+			($v), $rr)) return false;
+			
+		if ($rr[1] <= TIMESTAMP_FIRST_YEAR && $rr[2]<= 1) return 0;
+	
+		// h-m-s-MM-DD-YY
+		if (!isset($rr[5])) return  adodb_mktime(0,0,0,$rr[2],$rr[3],$rr[1]);
+		return  @adodb_mktime($rr[5],$rr[6],$rr[7],$rr[2],$rr[3],$rr[1]);
+	}
+	
+	/**
+	 * Also in ADORecordSet.
+	 *
+	 * Format database date based on user defined format.
+	 *
+	 * @param v  	is the character date in YYYY-MM-DD format, returned by database
+	 * @param fmt 	is the format to apply to it, using date()
+	 *
+	 * @return a date formated as user desires
+	 */
+	 
+	function UserDate($v,$fmt='Y-m-d',$gmt=false)
+	{
+		$tt = $this->UnixDate($v);
+
+		// $tt == -1 if pre TIMESTAMP_FIRST_YEAR
+		if (($tt === false || $tt == -1) && $v != false) return $v;
+		else if ($tt == 0) return $this->emptyDate;
+		else if ($tt == -1) { // pre-TIMESTAMP_FIRST_YEAR
+		}
+		
+		return ($gmt) ? adodb_gmdate($fmt,$tt) : adodb_date($fmt,$tt);
+	
+	}
+	
+		/**
+	 *
+	 * @param v  	is the character timestamp in YYYY-MM-DD hh:mm:ss format
+	 * @param fmt 	is the format to apply to it, using date()
+	 *
+	 * @return a timestamp formated as user desires
+	 */
+	function UserTimeStamp($v,$fmt='Y-m-d H:i:s',$gmt=false)
+	{
+		if (!isset($v)) return $this->emptyTimeStamp;
+		# strlen(14) allows YYYYMMDDHHMMSS format
+		if (is_numeric($v) && strlen($v)<14) return ($gmt) ? adodb_gmdate($fmt,$v) : adodb_date($fmt,$v);
+		$tt = $this->UnixTimeStamp($v);
+		// $tt == -1 if pre TIMESTAMP_FIRST_YEAR
+		if (($tt === false || $tt == -1) && $v != false) return $v;
+		if ($tt == 0) return $this->emptyTimeStamp;
+		return ($gmt) ? adodb_gmdate($fmt,$tt) : adodb_date($fmt,$tt);
+	}
+	
+	function escape($s,$magic_quotes=false)
+	{
+		return $this->addq($s,$magic_quotes);
+	}
+	
+	/**
+	* Quotes a string, without prefixing nor appending quotes. 
+	*/
+	function addq($s,$magic_quotes=false)
+	{
+		if (!$magic_quotes) {
+		
+			if ($this->replaceQuote[0] == '\\'){
+				// only since php 4.0.5
+				$s = adodb_str_replace(array('\\',"\0"),array('\\\\',"\\\0"),$s);
+				//$s = str_replace("\0","\\\0", str_replace('\\','\\\\',$s));
+			}
+			return  str_replace("'",$this->replaceQuote,$s);
+		}
+		
+		// undo magic quotes for "
+		$s = str_replace('\\"','"',$s);
+		
+		if ($this->replaceQuote == "\\'")  // ' already quoted, no need to change anything
+			return $s;
+		else {// change \' to '' for sybase/mssql
+			$s = str_replace('\\\\','\\',$s);
+			return str_replace("\\'",$this->replaceQuote,$s);
+		}
+	}
+	
+	/**
+	 * Correctly quotes a string so that all strings are escaped. We prefix and append
+	 * to the string single-quotes.
+	 * An example is  $db->qstr("Don't bother",magic_quotes_runtime());
+	 * 
+	 * @param s			the string to quote
+	 * @param [magic_quotes]	if $s is GET/POST var, set to get_magic_quotes_gpc().
+	 *				This undoes the stupidity of magic quotes for GPC.
+	 *
+	 * @return  quoted string to be sent back to database
+	 */
+	function qstr($s,$magic_quotes=false)
+	{	
+		if (!$magic_quotes) {
+		
+			if ($this->replaceQuote[0] == '\\'){
+				// only since php 4.0.5
+				$s = adodb_str_replace(array('\\',"\0"),array('\\\\',"\\\0"),$s);
+				//$s = str_replace("\0","\\\0", str_replace('\\','\\\\',$s));
+			}
+			return  "'".str_replace("'",$this->replaceQuote,$s)."'";
+		}
+		
+		// undo magic quotes for "
+		$s = str_replace('\\"','"',$s);
+		
+		if ($this->replaceQuote == "\\'")  // ' already quoted, no need to change anything
+			return "'$s'";
+		else {// change \' to '' for sybase/mssql
+			$s = str_replace('\\\\','\\',$s);
+			return "'".str_replace("\\'",$this->replaceQuote,$s)."'";
+		}
+	}
+	
+	
+	/**
+	* Will select the supplied $page number from a recordset, given that it is paginated in pages of 
+	* $nrows rows per page. It also saves two boolean values saying if the given page is the first 
+	* and/or last one of the recordset. Added by Iván Oliva to provide recordset pagination.
+	*
+	* See readme.htm#ex8 for an example of usage.
+	*
+	* @param sql
+	* @param nrows		is the number of rows per page to get
+	* @param page		is the page number to get (1-based)
+	* @param [inputarr]	array of bind variables
+	* @param [secs2cache]		is a private parameter only used by jlim
+	* @return		the recordset ($rs->databaseType == 'array')
+	*
+	* NOTE: phpLens uses a different algorithm and does not use PageExecute().
+	*
+	*/
+	function &PageExecute($sql, $nrows, $page, $inputarr=false, $secs2cache=0) 
+	{
+		global $ADODB_INCLUDED_LIB;
+		if (empty($ADODB_INCLUDED_LIB)) include(ADODB_DIR.'/adodb-lib.inc.php');
+		if ($this->pageExecuteCountRows) $rs =& _adodb_pageexecute_all_rows($this, $sql, $nrows, $page, $inputarr, $secs2cache);
+		else $rs =& _adodb_pageexecute_no_last_page($this, $sql, $nrows, $page, $inputarr, $secs2cache);
+		return $rs;
+	}
+	
+		
+	/**
+	* Will select the supplied $page number from a recordset, given that it is paginated in pages of 
+	* $nrows rows per page. It also saves two boolean values saying if the given page is the first 
+	* and/or last one of the recordset. Added by Iván Oliva to provide recordset pagination.
+	*
+	* @param secs2cache	seconds to cache data, set to 0 to force query
+	* @param sql
+	* @param nrows		is the number of rows per page to get
+	* @param page		is the page number to get (1-based)
+	* @param [inputarr]	array of bind variables
+	* @return		the recordset ($rs->databaseType == 'array')
+	*/
+	function &CachePageExecute($secs2cache, $sql, $nrows, $page,$inputarr=false) 
+	{
+		/*switch($this->dataProvider) {
+		case 'postgres':
+		case 'mysql': 
+			break;
+		default: $secs2cache = 0; break;
+		}*/
+		$rs =& $this->PageExecute($sql,$nrows,$page,$inputarr,$secs2cache);
+		return $rs;
+	}
+
+} // end class ADOConnection
+	
+	
+	
+	//==============================================================================================	
+	// CLASS ADOFetchObj
+	//==============================================================================================	
+		
+	/**
+	* Internal placeholder for record objects. Used by ADORecordSet->FetchObj().
+	*/
+	class ADOFetchObj {
+	};
+	
+	//==============================================================================================	
+	// CLASS ADORecordSet_empty
+	//==============================================================================================	
+	
+	/**
+	* Lightweight recordset when there are no records to be returned
+	*/
+	class ADORecordSet_empty
+	{
+		var $dataProvider = 'empty';
+		var $databaseType = false;
+		var $EOF = true;
+		var $_numOfRows = 0;
+		var $fields = false;
+		var $connection = false;
+		function RowCount() {return 0;}
+		function RecordCount() {return 0;}
+		function PO_RecordCount(){return 0;}
+		function Close(){return true;}
+		function FetchRow() {return false;}
+		function FieldCount(){ return 0;}
+		function Init() {}
+	}
+	
+	//==============================================================================================	
+	// DATE AND TIME FUNCTIONS
+	//==============================================================================================	
+	if (!defined('ADODB_DATE_VERSION')) include(ADODB_DIR.'/adodb-time.inc.php');
+	
+	//==============================================================================================	
+	// CLASS ADORecordSet
+	//==============================================================================================	
+
+	if (PHP_VERSION < 5) include_once(ADODB_DIR.'/adodb-php4.inc.php');
+	else include_once(ADODB_DIR.'/adodb-iterator.inc.php');
+   /**
+	 * RecordSet class that represents the dataset returned by the database.
+	 * To keep memory overhead low, this class holds only the current row in memory.
+	 * No prefetching of data is done, so the RecordCount() can return -1 ( which
+	 * means recordcount not known).
+	 */
+	class ADORecordSet extends ADODB_BASE_RS {
+	/*
+	 * public variables	
+	 */
+	var $dataProvider = "native";
+	var $fields = false; 	/// holds the current row data
+	var $blobSize = 100; 	/// any varchar/char field this size or greater is treated as a blob
+							/// in other words, we use a text area for editing.
+	var $canSeek = false; 	/// indicates that seek is supported
+	var $sql; 				/// sql text
+	var $EOF = false;		/// Indicates that the current record position is after the last record in a Recordset object. 
+	
+	var $emptyTimeStamp = '&nbsp;'; /// what to display when $time==0
+	var $emptyDate = '&nbsp;'; /// what to display when $time==0
+	var $debug = false;
+	var $timeCreated=0; 	/// datetime in Unix format rs created -- for cached recordsets
+
+	var $bind = false; 		/// used by Fields() to hold array - should be private?
+	var $fetchMode;			/// default fetch mode
+	var $connection = false; /// the parent connection
+	/*
+	 *	private variables	
+	 */
+	var $_numOfRows = -1;	/** number of rows, or -1 */
+	var $_numOfFields = -1;	/** number of fields in recordset */
+	var $_queryID = -1;		/** This variable keeps the result link identifier.	*/
+	var $_currentRow = -1;	/** This variable keeps the current row in the Recordset.	*/
+	var $_closed = false; 	/** has recordset been closed */
+	var $_inited = false; 	/** Init() should only be called once */
+	var $_obj; 				/** Used by FetchObj */
+	var $_names;			/** Used by FetchObj */
+	
+	var $_currentPage = -1;	/** Added by Iván Oliva to implement recordset pagination */
+	var $_atFirstPage = false;	/** Added by Iván Oliva to implement recordset pagination */
+	var $_atLastPage = false;	/** Added by Iván Oliva to implement recordset pagination */
+	var $_lastPageNo = -1; 
+	var $_maxRecordCount = 0;
+	var $datetime = false;
+	
+	/**
+	 * Constructor
+	 *
+	 * @param queryID  	this is the queryID returned by ADOConnection->_query()
+	 *
+	 */
+	function ADORecordSet($queryID) 
+	{
+		$this->_queryID = $queryID;
+	}
+	
+	
+	
+	function Init()
+	{
+		if ($this->_inited) return;
+		$this->_inited = true;
+		if ($this->_queryID) @$this->_initrs();
+		else {
+			$this->_numOfRows = 0;
+			$this->_numOfFields = 0;
+		}
+		if ($this->_numOfRows != 0 && $this->_numOfFields && $this->_currentRow == -1) {
+			
+			$this->_currentRow = 0;
+			if ($this->EOF = ($this->_fetch() === false)) {
+				$this->_numOfRows = 0; // _numOfRows could be -1
+			}
+		} else {
+			$this->EOF = true;
+		}
+	}
+	
+	
+	/**
+	 * Generate a SELECT tag string from a recordset, and return the string.
+	 * If the recordset has 2 cols, we treat the 1st col as the containing 
+	 * the text to display to the user, and 2nd col as the return value. Default
+	 * strings are compared with the FIRST column.
+	 *
+	 * @param name  		name of SELECT tag
+	 * @param [defstr]		the value to hilite. Use an array for multiple hilites for listbox.
+	 * @param [blank1stItem]	true to leave the 1st item in list empty
+	 * @param [multiple]		true for listbox, false for popup
+	 * @param [size]		#rows to show for listbox. not used by popup
+	 * @param [selectAttr]		additional attributes to defined for SELECT tag.
+	 *				useful for holding javascript onChange='...' handlers.
+	 & @param [compareFields0]	when we have 2 cols in recordset, we compare the defstr with 
+	 *				column 0 (1st col) if this is true. This is not documented.
+	 *
+	 * @return HTML
+	 *
+	 * changes by glen.davies@cce.ac.nz to support multiple hilited items
+	 */
+	function GetMenu($name,$defstr='',$blank1stItem=true,$multiple=false,
+			$size=0, $selectAttr='',$compareFields0=true)
+	{
+		global $ADODB_INCLUDED_LIB;
+		if (empty($ADODB_INCLUDED_LIB)) include(ADODB_DIR.'/adodb-lib.inc.php');
+		return _adodb_getmenu($this, $name,$defstr,$blank1stItem,$multiple,
+			$size, $selectAttr,$compareFields0);
+	}
+	
+
+	
+	/**
+	 * Generate a SELECT tag string from a recordset, and return the string.
+	 * If the recordset has 2 cols, we treat the 1st col as the containing 
+	 * the text to display to the user, and 2nd col as the return value. Default
+	 * strings are compared with the SECOND column.
+	 *
+	 */
+	function GetMenu2($name,$defstr='',$blank1stItem=true,$multiple=false,$size=0, $selectAttr='')	
+	{
+		return $this->GetMenu($name,$defstr,$blank1stItem,$multiple,
+			$size, $selectAttr,false);
+	}
+	
+	/*
+		Grouped Menu
+	*/
+	function GetMenu3($name,$defstr='',$blank1stItem=true,$multiple=false,
+			$size=0, $selectAttr='')
+	{
+		global $ADODB_INCLUDED_LIB;
+		if (empty($ADODB_INCLUDED_LIB)) include(ADODB_DIR.'/adodb-lib.inc.php');
+		return _adodb_getmenu_gp($this, $name,$defstr,$blank1stItem,$multiple,
+			$size, $selectAttr,false);
+	}
+
+	/**
+	 * return recordset as a 2-dimensional array.
+	 *
+	 * @param [nRows]  is the number of rows to return. -1 means every row.
+	 *
+	 * @return an array indexed by the rows (0-based) from the recordset
+	 */
+	function &GetArray($nRows = -1) 
+	{
+	global $ADODB_EXTENSION; if ($ADODB_EXTENSION) {
+		$results = adodb_getall($this,$nRows);
+		return $results;
+	}
+		$results = array();
+		$cnt = 0;
+		while (!$this->EOF && $nRows != $cnt) {
+			$results[] = $this->fields;
+			$this->MoveNext();
+			$cnt++;
+		}
+		return $results;
+	}
+	
+	function &GetAll($nRows = -1)
+	{
+		$arr =& $this->GetArray($nRows);
+		return $arr;
+	}
+	
+	/*
+	* Some databases allow multiple recordsets to be returned. This function
+	* will return true if there is a next recordset, or false if no more.
+	*/
+	function NextRecordSet()
+	{
+		return false;
+	}
+	
+	/**
+	 * return recordset as a 2-dimensional array. 
+	 * Helper function for ADOConnection->SelectLimit()
+	 *
+	 * @param offset	is the row to start calculations from (1-based)
+	 * @param [nrows]	is the number of rows to return
+	 *
+	 * @return an array indexed by the rows (0-based) from the recordset
+	 */
+	function &GetArrayLimit($nrows,$offset=-1) 
+	{	
+		if ($offset <= 0) {
+			$arr =& $this->GetArray($nrows);
+			return $arr;
+		} 
+		
+		$this->Move($offset);
+		
+		$results = array();
+		$cnt = 0;
+		while (!$this->EOF && $nrows != $cnt) {
+			$results[$cnt++] = $this->fields;
+			$this->MoveNext();
+		}
+		
+		return $results;
+	}
+	
+	
+	/**
+	 * Synonym for GetArray() for compatibility with ADO.
+	 *
+	 * @param [nRows]  is the number of rows to return. -1 means every row.
+	 *
+	 * @return an array indexed by the rows (0-based) from the recordset
+	 */
+	function &GetRows($nRows = -1) 
+	{
+		$arr =& $this->GetArray($nRows);
+		return $arr;
+	}
+	
+	/**
+	 * return whole recordset as a 2-dimensional associative array if there are more than 2 columns. 
+	 * The first column is treated as the key and is not included in the array. 
+	 * If there is only 2 columns, it will return a 1 dimensional array of key-value pairs unless
+	 * $force_array == true.
+	 *
+	 * @param [force_array] has only meaning if we have 2 data columns. If false, a 1 dimensional
+	 * 	array is returned, otherwise a 2 dimensional array is returned. If this sounds confusing,
+	 * 	read the source.
+	 *
+	 * @param [first2cols] means if there are more than 2 cols, ignore the remaining cols and 
+	 * instead of returning array[col0] => array(remaining cols), return array[col0] => col1
+	 *
+	 * @return an associative array indexed by the first column of the array, 
+	 * 	or false if the  data has less than 2 cols.
+	 */
+	function &GetAssoc($force_array = false, $first2cols = false) 
+	{
+	global $ADODB_EXTENSION;
+	
+		$cols = $this->_numOfFields;
+		if ($cols < 2) {
+			$false = false;
+			return $false;
+		}
+		$numIndex = isset($this->fields[0]);
+		$results = array();
+		
+		if (!$first2cols && ($cols > 2 || $force_array)) {
+			if ($ADODB_EXTENSION) {
+				if ($numIndex) {
+					while (!$this->EOF) {
+						$results[trim($this->fields[0])] = array_slice($this->fields, 1);
+						adodb_movenext($this);
+					}
+				} else {
+					while (!$this->EOF) {
+					// Fix for array_slice re-numbering numeric associative keys
+						$keys = array_slice(array_keys($this->fields), 1);
+						$sliced_array = array();
+
+						foreach($keys as $key) {
+							$sliced_array[$key] = $this->fields[$key];
+						}
+						
+						$results[trim(reset($this->fields))] = $sliced_array;
+						adodb_movenext($this);
+					}
+				}
+			} else {
+				if ($numIndex) {
+					while (!$this->EOF) {
+						$results[trim($this->fields[0])] = array_slice($this->fields, 1);
+						$this->MoveNext();
+					}
+				} else {
+					while (!$this->EOF) {
+					// Fix for array_slice re-numbering numeric associative keys
+						$keys = array_slice(array_keys($this->fields), 1);
+						$sliced_array = array();
+
+						foreach($keys as $key) {
+							$sliced_array[$key] = $this->fields[$key];
+						}
+						
+						$results[trim(reset($this->fields))] = $sliced_array;
+						$this->MoveNext();
+					}
+				}
+			}
+		} else {
+			if ($ADODB_EXTENSION) {
+				// return scalar values
+				if ($numIndex) {
+					while (!$this->EOF) {
+					// some bug in mssql PHP 4.02 -- doesn't handle references properly so we FORCE creating a new string
+						$results[trim(($this->fields[0]))] = $this->fields[1];
+						adodb_movenext($this);
+					}
+				} else {
+					while (!$this->EOF) {
+					// some bug in mssql PHP 4.02 -- doesn't handle references properly so we FORCE creating a new string
+						$v1 = trim(reset($this->fields));
+						$v2 = ''.next($this->fields); 
+						$results[$v1] = $v2;
+						adodb_movenext($this);
+					}
+				}
+			} else {
+				if ($numIndex) {
+					while (!$this->EOF) {
+					// some bug in mssql PHP 4.02 -- doesn't handle references properly so we FORCE creating a new string
+						$results[trim(($this->fields[0]))] = $this->fields[1];
+						$this->MoveNext();
+					}
+				} else {
+					while (!$this->EOF) {
+					// some bug in mssql PHP 4.02 -- doesn't handle references properly so we FORCE creating a new string
+						$v1 = trim(reset($this->fields));
+						$v2 = ''.next($this->fields); 
+						$results[$v1] = $v2;
+						$this->MoveNext();
+					}
+				}
+			}
+		}
+		
+		$ref =& $results; # workaround accelerator incompat with PHP 4.4 :(
+		return $ref; 
+	}
+	
+	
+	/**
+	 *
+	 * @param v  	is the character timestamp in YYYY-MM-DD hh:mm:ss format
+	 * @param fmt 	is the format to apply to it, using date()
+	 *
+	 * @return a timestamp formated as user desires
+	 */
+	function UserTimeStamp($v,$fmt='Y-m-d H:i:s')
+	{
+		if (is_numeric($v) && strlen($v)<14) return adodb_date($fmt,$v);
+		$tt = $this->UnixTimeStamp($v);
+		// $tt == -1 if pre TIMESTAMP_FIRST_YEAR
+		if (($tt === false || $tt == -1) && $v != false) return $v;
+		if ($tt === 0) return $this->emptyTimeStamp;
+		return adodb_date($fmt,$tt);
+	}
+	
+	
+	/**
+	 * @param v  	is the character date in YYYY-MM-DD format, returned by database
+	 * @param fmt 	is the format to apply to it, using date()
+	 *
+	 * @return a date formated as user desires
+	 */
+	function UserDate($v,$fmt='Y-m-d')
+	{
+		$tt = $this->UnixDate($v);
+		// $tt == -1 if pre TIMESTAMP_FIRST_YEAR
+		if (($tt === false || $tt == -1) && $v != false) return $v;
+		else if ($tt == 0) return $this->emptyDate;
+		else if ($tt == -1) { // pre-TIMESTAMP_FIRST_YEAR
+		}
+		return adodb_date($fmt,$tt);
+	}
+	
+	
+	/**
+	 * @param $v is a date string in YYYY-MM-DD format
+	 *
+	 * @return date in unix timestamp format, or 0 if before TIMESTAMP_FIRST_YEAR, or false if invalid date format
+	 */
+	function UnixDate($v)
+	{
+		return ADOConnection::UnixDate($v);
+	}
+	
+
+	/**
+	 * @param $v is a timestamp string in YYYY-MM-DD HH-NN-SS format
+	 *
+	 * @return date in unix timestamp format, or 0 if before TIMESTAMP_FIRST_YEAR, or false if invalid date format
+	 */
+	function UnixTimeStamp($v)
+	{
+		return ADOConnection::UnixTimeStamp($v);
+	}
+	
+	
+	/**
+	* PEAR DB Compat - do not use internally
+	*/
+	function Free()
+	{
+		return $this->Close();
+	}
+	
+	
+	/**
+	* PEAR DB compat, number of rows
+	*/
+	function NumRows()
+	{
+		return $this->_numOfRows;
+	}
+	
+	
+	/**
+	* PEAR DB compat, number of cols
+	*/
+	function NumCols()
+	{
+		return $this->_numOfFields;
+	}
+	
+	/**
+	* Fetch a row, returning false if no more rows. 
+	* This is PEAR DB compat mode.
+	*
+	* @return false or array containing the current record
+	*/
+	function &FetchRow()
+	{
+		if ($this->EOF) {
+			$false = false;
+			return $false;
+		}
+		$arr = $this->fields;
+		$this->_currentRow++;
+		if (!$this->_fetch()) $this->EOF = true;
+		return $arr;
+	}
+	
+	
+	/**
+	* Fetch a row, returning PEAR_Error if no more rows. 
+	* This is PEAR DB compat mode.
+	*
+	* @return DB_OK or error object
+	*/
+	function FetchInto(&$arr)
+	{
+		if ($this->EOF) return (defined('PEAR_ERROR_RETURN')) ? new PEAR_Error('EOF',-1): false;
+		$arr = $this->fields;
+		$this->MoveNext();
+		return 1; // DB_OK
+	}
+	
+	
+	/**
+	 * Move to the first row in the recordset. Many databases do NOT support this.
+	 *
+	 * @return true or false
+	 */
+	function MoveFirst() 
+	{
+		if ($this->_currentRow == 0) return true;
+		return $this->Move(0);			
+	}			
+
+	
+	/**
+	 * Move to the last row in the recordset. 
+	 *
+	 * @return true or false
+	 */
+	function MoveLast() 
+	{
+		if ($this->_numOfRows >= 0) return $this->Move($this->_numOfRows-1);
+		if ($this->EOF) return false;
+		while (!$this->EOF) {
+			$f = $this->fields;
+			$this->MoveNext();
+		}
+		$this->fields = $f;
+		$this->EOF = false;
+		return true;
+	}
+	
+	
+	/**
+	 * Move to next record in the recordset.
+	 *
+	 * @return true if there still rows available, or false if there are no more rows (EOF).
+	 */
+	function MoveNext() 
+	{
+		if (!$this->EOF) {
+			$this->_currentRow++;
+			if ($this->_fetch()) return true;
+		}
+		$this->EOF = true;
+		/* -- tested error handling when scrolling cursor -- seems useless.
+		$conn = $this->connection;
+		if ($conn && $conn->raiseErrorFn && ($errno = $conn->ErrorNo())) {
+			$fn = $conn->raiseErrorFn;
+			$fn($conn->databaseType,'MOVENEXT',$errno,$conn->ErrorMsg().' ('.$this->sql.')',$conn->host,$conn->database);
+		}
+		*/
+		return false;
+	}
+	
+	
+	/**
+	 * Random access to a specific row in the recordset. Some databases do not support
+	 * access to previous rows in the databases (no scrolling backwards).
+	 *
+	 * @param rowNumber is the row to move to (0-based)
+	 *
+	 * @return true if there still rows available, or false if there are no more rows (EOF).
+	 */
+	function Move($rowNumber = 0) 
+	{
+		$this->EOF = false;
+		if ($rowNumber == $this->_currentRow) return true;
+		if ($rowNumber >= $this->_numOfRows)
+	   		if ($this->_numOfRows != -1) $rowNumber = $this->_numOfRows-2;
+  				
+		if ($this->canSeek) { 
+	
+			if ($this->_seek($rowNumber)) {
+				$this->_currentRow = $rowNumber;
+				if ($this->_fetch()) {
+					return true;
+				}
+			} else {
+				$this->EOF = true;
+				return false;
+			}
+		} else {
+			if ($rowNumber < $this->_currentRow) return false;
+			global $ADODB_EXTENSION;
+			if ($ADODB_EXTENSION) {
+				while (!$this->EOF && $this->_currentRow < $rowNumber) {
+					adodb_movenext($this);
+				}
+			} else {
+			
+				while (! $this->EOF && $this->_currentRow < $rowNumber) {
+					$this->_currentRow++;
+					
+					if (!$this->_fetch()) $this->EOF = true;
+				}
+			}
+			return !($this->EOF);
+		}
+		
+		$this->fields = false;	
+		$this->EOF = true;
+		return false;
+	}
+	
+		
+	/**
+	 * Get the value of a field in the current row by column name.
+	 * Will not work if ADODB_FETCH_MODE is set to ADODB_FETCH_NUM.
+	 * 
+	 * @param colname  is the field to access
+	 *
+	 * @return the value of $colname column
+	 */
+	function Fields($colname)
+	{
+		return $this->fields[$colname];
+	}
+	
+	function GetAssocKeys($upper=true)
+	{
+		$this->bind = array();
+		for ($i=0; $i < $this->_numOfFields; $i++) {
+			$o = $this->FetchField($i);
+			if ($upper === 2) $this->bind[$o->name] = $i;
+			else $this->bind[($upper) ? strtoupper($o->name) : strtolower($o->name)] = $i;
+		}
+	}
+	
+  /**
+   * Use associative array to get fields array for databases that do not support
+   * associative arrays. Submitted by Paolo S. Asioli paolo.asioli#libero.it
+   *
+   * If you don't want uppercase cols, set $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC
+   * before you execute your SQL statement, and access $rs->fields['col'] directly.
+   *
+   * $upper  0 = lowercase, 1 = uppercase, 2 = whatever is returned by FetchField
+   */
+	function &GetRowAssoc($upper=1)
+	{
+		$record = array();
+	 //	if (!$this->fields) return $record;
+		
+	   	if (!$this->bind) {
+			$this->GetAssocKeys($upper);
+		}
+		
+		foreach($this->bind as $k => $v) {
+			$record[$k] = $this->fields[$v];
+		}
+
+		return $record;
+	}
+	
+	
+	/**
+	 * Clean up recordset
+	 *
+	 * @return true or false
+	 */
+	function Close() 
+	{
+		// free connection object - this seems to globally free the object
+		// and not merely the reference, so don't do this...
+		// $this->connection = false; 
+		if (!$this->_closed) {
+			$this->_closed = true;
+			return $this->_close();		
+		} else
+			return true;
+	}
+	
+	/**
+	 * synonyms RecordCount and RowCount	
+	 *
+	 * @return the number of rows or -1 if this is not supported
+	 */
+	function RecordCount() {return $this->_numOfRows;}
+	
+	
+	/*
+	* If we are using PageExecute(), this will return the maximum possible rows
+	* that can be returned when paging a recordset.
+	*/
+	function MaxRecordCount()
+	{
+		return ($this->_maxRecordCount) ? $this->_maxRecordCount : $this->RecordCount();
+	}
+	
+	/**
+	 * synonyms RecordCount and RowCount	
+	 *
+	 * @return the number of rows or -1 if this is not supported
+	 */
+	function RowCount() {return $this->_numOfRows;} 
+	
+
+	 /**
+	 * Portable RecordCount. Pablo Roca <pabloroca@mvps.org>
+	 *
+	 * @return  the number of records from a previous SELECT. All databases support this.
+	 *
+	 * But aware possible problems in multiuser environments. For better speed the table
+	 * must be indexed by the condition. Heavy test this before deploying.
+	 */ 
+	function PO_RecordCount($table="", $condition="") {
+		
+		$lnumrows = $this->_numOfRows;
+		// the database doesn't support native recordcount, so we do a workaround
+		if ($lnumrows == -1 && $this->connection) {
+			IF ($table) {
+				if ($condition) $condition = " WHERE " . $condition; 
+				$resultrows = &$this->connection->Execute("SELECT COUNT(*) FROM $table $condition");
+				if ($resultrows) $lnumrows = reset($resultrows->fields);
+			}
+		}
+		return $lnumrows;
+	}
+	
+	
+	/**
+	 * @return the current row in the recordset. If at EOF, will return the last row. 0-based.
+	 */
+	function CurrentRow() {return $this->_currentRow;}
+	
+	/**
+	 * synonym for CurrentRow -- for ADO compat
+	 *
+	 * @return the current row in the recordset. If at EOF, will return the last row. 0-based.
+	 */
+	function AbsolutePosition() {return $this->_currentRow;}
+	
+	/**
+	 * @return the number of columns in the recordset. Some databases will set this to 0
+	 * if no records are returned, others will return the number of columns in the query.
+	 */
+	function FieldCount() {return $this->_numOfFields;}   
+
+
+	/**
+	 * Get the ADOFieldObject of a specific column.
+	 *
+	 * @param fieldoffset	is the column position to access(0-based).
+	 *
+	 * @return the ADOFieldObject for that column, or false.
+	 */
+	function &FetchField($fieldoffset = -1) 
+	{
+		// must be defined by child class
+		
+		$false = false;
+		return $false;
+	}	
+	
+	/**
+	 * Get the ADOFieldObjects of all columns in an array.
+	 *
+	 */
+	function& FieldTypesArray()
+	{
+		$arr = array();
+		for ($i=0, $max=$this->_numOfFields; $i < $max; $i++) 
+			$arr[] = $this->FetchField($i);
+		return $arr;
+	}
+	
+	/**
+	* Return the fields array of the current row as an object for convenience.
+	* The default case is lowercase field names.
+	*
+	* @return the object with the properties set to the fields of the current row
+	*/
+	function &FetchObj()
+	{
+		$o =& $this->FetchObject(false);
+		return $o;
+	}
+	
+	/**
+	* Return the fields array of the current row as an object for convenience.
+	* The default case is uppercase.
+	* 
+	* @param $isupper to set the object property names to uppercase
+	*
+	* @return the object with the properties set to the fields of the current row
+	*/
+	function &FetchObject($isupper=true)
+	{
+		if (empty($this->_obj)) {
+			$this->_obj = new ADOFetchObj();
+			$this->_names = array();
+			for ($i=0; $i <$this->_numOfFields; $i++) {
+				$f = $this->FetchField($i);
+				$this->_names[] = $f->name;
+			}
+		}
+		$i = 0;
+		if (PHP_VERSION >= 5) $o = clone($this->_obj);
+		else $o = $this->_obj;
+	
+		for ($i=0; $i <$this->_numOfFields; $i++) {
+			$name = $this->_names[$i];
+			if ($isupper) $n = strtoupper($name);
+			else $n = $name;
+			
+			$o->$n = $this->Fields($name);
+		}
+		return $o;
+	}
+	
+	/**
+	* Return the fields array of the current row as an object for convenience.
+	* The default is lower-case field names.
+	* 
+	* @return the object with the properties set to the fields of the current row,
+	* 	or false if EOF
+	*
+	* Fixed bug reported by tim@orotech.net
+	*/
+	function &FetchNextObj()
+	{
+		$o =& $this->FetchNextObject(false);
+		return $o;
+	}
+	
+	
+	/**
+	* Return the fields array of the current row as an object for convenience. 
+	* The default is upper case field names.
+	* 
+	* @param $isupper to set the object property names to uppercase
+	*
+	* @return the object with the properties set to the fields of the current row,
+	* 	or false if EOF
+	*
+	* Fixed bug reported by tim@orotech.net
+	*/
+	function &FetchNextObject($isupper=true)
+	{
+		$o = false;
+		if ($this->_numOfRows != 0 && !$this->EOF) {
+			$o = $this->FetchObject($isupper);	
+			$this->_currentRow++;
+			if ($this->_fetch()) return $o;
+		}
+		$this->EOF = true;
+		return $o;
+	}
+	
+	/**
+	 * Get the metatype of the column. This is used for formatting. This is because
+	 * many databases use different names for the same type, so we transform the original
+	 * type to our standardised version which uses 1 character codes:
+	 *
+	 * @param t  is the type passed in. Normally is ADOFieldObject->type.
+	 * @param len is the maximum length of that field. This is because we treat character
+	 * 	fields bigger than a certain size as a 'B' (blob).
+	 * @param fieldobj is the field object returned by the database driver. Can hold
+	 *	additional info (eg. primary_key for mysql).
+	 * 
+	 * @return the general type of the data: 
+	 *	C for character < 250 chars
+	 *	X for teXt (>= 250 chars)
+	 *	B for Binary
+	 * 	N for numeric or floating point
+	 *	D for date
+	 *	T for timestamp
+	 * 	L for logical/Boolean
+	 *	I for integer
+	 *	R for autoincrement counter/integer
+	 * 
+	 *
+	*/
+	function MetaType($t,$len=-1,$fieldobj=false)
+	{
+		if (is_object($t)) {
+			$fieldobj = $t;
+			$t = $fieldobj->type;
+			$len = $fieldobj->max_length;
+		}
+	// changed in 2.32 to hashing instead of switch stmt for speed...
+	static $typeMap = array(
+		'VARCHAR' => 'C',
+		'VARCHAR2' => 'C',
+		'CHAR' => 'C',
+		'C' => 'C',
+		'STRING' => 'C',
+		'NCHAR' => 'C',
+		'NVARCHAR' => 'C',
+		'VARYING' => 'C',
+		'BPCHAR' => 'C',
+		'CHARACTER' => 'C',
+		'INTERVAL' => 'C',  # Postgres
+		'MACADDR' => 'C', # postgres
+		##
+		'LONGCHAR' => 'X',
+		'TEXT' => 'X',
+		'NTEXT' => 'X',
+		'M' => 'X',
+		'X' => 'X',
+		'CLOB' => 'X',
+		'NCLOB' => 'X',
+		'LVARCHAR' => 'X',
+		##
+		'BLOB' => 'B',
+		'IMAGE' => 'B',
+		'BINARY' => 'B',
+		'VARBINARY' => 'B',
+		'LONGBINARY' => 'B',
+		'B' => 'B',
+		##
+		'YEAR' => 'D', // mysql
+		'DATE' => 'D',
+		'D' => 'D',
+		##
+		'UNIQUEIDENTIFIER' => 'C', # MS SQL Server
+		##
+		'TIME' => 'T',
+		'TIMESTAMP' => 'T',
+		'DATETIME' => 'T',
+		'TIMESTAMPTZ' => 'T',
+		'T' => 'T',
+		'TIMESTAMP WITHOUT TIME ZONE' => 'T', // postgresql
+		##
+		'BOOL' => 'L',
+		'BOOLEAN' => 'L', 
+		'BIT' => 'L',
+		'L' => 'L',
+		##
+		'COUNTER' => 'R',
+		'R' => 'R',
+		'SERIAL' => 'R', // ifx
+		'INT IDENTITY' => 'R',
+		##
+		'INT' => 'I',
+		'INT2' => 'I',
+		'INT4' => 'I',
+		'INT8' => 'I',
+		'INTEGER' => 'I',
+		'INTEGER UNSIGNED' => 'I',
+		'SHORT' => 'I',
+		'TINYINT' => 'I',
+		'SMALLINT' => 'I',
+		'I' => 'I',
+		##
+		'LONG' => 'N', // interbase is numeric, oci8 is blob
+		'BIGINT' => 'N', // this is bigger than PHP 32-bit integers
+		'DECIMAL' => 'N',
+		'DEC' => 'N',
+		'REAL' => 'N',
+		'DOUBLE' => 'N',
+		'DOUBLE PRECISION' => 'N',
+		'SMALLFLOAT' => 'N',
+		'FLOAT' => 'N',
+		'NUMBER' => 'N',
+		'NUM' => 'N',
+		'NUMERIC' => 'N',
+		'MONEY' => 'N',
+		
+		## informix 9.2
+		'SQLINT' => 'I', 
+		'SQLSERIAL' => 'I', 
+		'SQLSMINT' => 'I', 
+		'SQLSMFLOAT' => 'N', 
+		'SQLFLOAT' => 'N', 
+		'SQLMONEY' => 'N', 
+		'SQLDECIMAL' => 'N', 
+		'SQLDATE' => 'D', 
+		'SQLVCHAR' => 'C', 
+		'SQLCHAR' => 'C', 
+		'SQLDTIME' => 'T', 
+		'SQLINTERVAL' => 'N', 
+		'SQLBYTES' => 'B', 
+		'SQLTEXT' => 'X',
+		 ## informix 10
+		"SQLINT8" => 'I8',
+		"SQLSERIAL8" => 'I8',
+		"SQLNCHAR" => 'C',
+		"SQLNVCHAR" => 'C',
+		"SQLLVARCHAR" => 'X',
+		"SQLBOOL" => 'L'
+		);
+		
+		$tmap = false;
+		$t = strtoupper($t);
+		$tmap = (isset($typeMap[$t])) ? $typeMap[$t] : 'N';
+		switch ($tmap) {
+		case 'C':
+		
+			// is the char field is too long, return as text field... 
+			if ($this->blobSize >= 0) {
+				if ($len > $this->blobSize) return 'X';
+			} else if ($len > 250) {
+				return 'X';
+			}
+			return 'C';
+			
+		case 'I':
+			if (!empty($fieldobj->primary_key)) return 'R';
+			return 'I';
+		
+		case false:
+			return 'N';
+			
+		case 'B':
+			 if (isset($fieldobj->binary)) 
+				 return ($fieldobj->binary) ? 'B' : 'X';
+			return 'B';
+		
+		case 'D':
+			if (!empty($this->connection) && !empty($this->connection->datetime)) return 'T';
+			return 'D';
+			
+		default: 
+			if ($t == 'LONG' && $this->dataProvider == 'oci8') return 'B';
+			return $tmap;
+		}
+	}
+	
+	
+	function _close() {}
+	
+	/**
+	 * set/returns the current recordset page when paginating
+	 */
+	function AbsolutePage($page=-1)
+	{
+		if ($page != -1) $this->_currentPage = $page;
+		return $this->_currentPage;
+	}
+	
+	/**
+	 * set/returns the status of the atFirstPage flag when paginating
+	 */
+	function AtFirstPage($status=false)
+	{
+		if ($status != false) $this->_atFirstPage = $status;
+		return $this->_atFirstPage;
+	}
+	
+	function LastPageNo($page = false)
+	{
+		if ($page != false) $this->_lastPageNo = $page;
+		return $this->_lastPageNo;
+	}
+	
+	/**
+	 * set/returns the status of the atLastPage flag when paginating
+	 */
+	function AtLastPage($status=false)
+	{
+		if ($status != false) $this->_atLastPage = $status;
+		return $this->_atLastPage;
+	}
+	
+} // end class ADORecordSet
+	
+	//==============================================================================================	
+	// CLASS ADORecordSet_array
+	//==============================================================================================	
+	
+	/**
+	 * This class encapsulates the concept of a recordset created in memory
+	 * as an array. This is useful for the creation of cached recordsets.
+	 * 
+	 * Note that the constructor is different from the standard ADORecordSet
+	 */
+	
+	class ADORecordSet_array extends ADORecordSet
+	{
+		var $databaseType = 'array';
+
+		var $_array; 	// holds the 2-dimensional data array
+		var $_types;	// the array of types of each column (C B I L M)
+		var $_colnames;	// names of each column in array
+		var $_skiprow1;	// skip 1st row because it holds column names
+		var $_fieldobjects; // holds array of field objects
+		var $canSeek = true;
+		var $affectedrows = false;
+		var $insertid = false;
+		var $sql = '';
+		var $compat = false;
+		/**
+		 * Constructor
+		 *
+		 */
+		function ADORecordSet_array($fakeid=1)
+		{
+		global $ADODB_FETCH_MODE,$ADODB_COMPAT_FETCH;
+		
+			// fetch() on EOF does not delete $this->fields
+			$this->compat = !empty($ADODB_COMPAT_FETCH);
+			$this->ADORecordSet($fakeid); // fake queryID		
+			$this->fetchMode = $ADODB_FETCH_MODE;
+		}
+		
+		function _transpose($addfieldnames=true)
+		{
+		global $ADODB_INCLUDED_LIB;
+			
+			if (empty($ADODB_INCLUDED_LIB)) include(ADODB_DIR.'/adodb-lib.inc.php');
+			$hdr = true;
+			
+			$fobjs = $addfieldnames ? $this->_fieldobjects : false;
+			adodb_transpose($this->_array, $newarr, $hdr, $fobjs);
+			//adodb_pr($newarr);
+			
+			$this->_skiprow1 = false;
+			$this->_array =& $newarr;
+			$this->_colnames = $hdr;
+			
+			adodb_probetypes($newarr,$this->_types);
+		
+			$this->_fieldobjects = array();
+			
+			foreach($hdr as $k => $name) {
+				$f = new ADOFieldObject();
+				$f->name = $name;
+				$f->type = $this->_types[$k];
+				$f->max_length = -1;
+				$this->_fieldobjects[] = $f;
+			}
+			$this->fields = reset($this->_array);
+			
+			$this->_initrs();
+			
+		}
+		
+		/**
+		 * Setup the array.
+		 *
+		 * @param array		is a 2-dimensional array holding the data.
+		 *			The first row should hold the column names 
+		 *			unless paramter $colnames is used.
+		 * @param typearr	holds an array of types. These are the same types 
+		 *			used in MetaTypes (C,B,L,I,N).
+		 * @param [colnames]	array of column names. If set, then the first row of
+		 *			$array should not hold the column names.
+		 */
+		function InitArray($array,$typearr,$colnames=false)
+		{
+			$this->_array = $array;
+			$this->_types = $typearr;	
+			if ($colnames) {
+				$this->_skiprow1 = false;
+				$this->_colnames = $colnames;
+			} else  {
+				$this->_skiprow1 = true;
+				$this->_colnames = $array[0];
+			}
+			$this->Init();
+		}
+		/**
+		 * Setup the Array and datatype file objects
+		 *
+		 * @param array		is a 2-dimensional array holding the data.
+		 *			The first row should hold the column names 
+		 *			unless paramter $colnames is used.
+		 * @param fieldarr	holds an array of ADOFieldObject's.
+		 */
+		function InitArrayFields(&$array,&$fieldarr)
+		{
+			$this->_array =& $array;
+			$this->_skiprow1= false;
+			if ($fieldarr) {
+				$this->_fieldobjects =& $fieldarr;
+			} 
+			$this->Init();
+		}
+		
+		function &GetArray($nRows=-1)
+		{
+			if ($nRows == -1 && $this->_currentRow <= 0 && !$this->_skiprow1) {
+				return $this->_array;
+			} else {
+				$arr =& ADORecordSet::GetArray($nRows);
+				return $arr;
+			}
+		}
+		
+		function _initrs()
+		{
+			$this->_numOfRows =  sizeof($this->_array);
+			if ($this->_skiprow1) $this->_numOfRows -= 1;
+		
+			$this->_numOfFields =(isset($this->_fieldobjects)) ?
+				 sizeof($this->_fieldobjects):sizeof($this->_types);
+		}
+		
+		/* Use associative array to get fields array */
+		function Fields($colname)
+		{
+			$mode = isset($this->adodbFetchMode) ? $this->adodbFetchMode : $this->fetchMode;
+			
+			if ($mode & ADODB_FETCH_ASSOC) {
+				if (!isset($this->fields[$colname])) $colname = strtolower($colname);
+				return $this->fields[$colname];
+			}
+			if (!$this->bind) {
+				$this->bind = array();
+				for ($i=0; $i < $this->_numOfFields; $i++) {
+					$o = $this->FetchField($i);
+					$this->bind[strtoupper($o->name)] = $i;
+				}
+			}
+			return $this->fields[$this->bind[strtoupper($colname)]];
+		}
+		
+		function &FetchField($fieldOffset = -1) 
+		{
+			if (isset($this->_fieldobjects)) {
+				return $this->_fieldobjects[$fieldOffset];
+			}
+			$o =  new ADOFieldObject();
+			$o->name = $this->_colnames[$fieldOffset];
+			$o->type =  $this->_types[$fieldOffset];
+			$o->max_length = -1; // length not known
+			
+			return $o;
+		}
+			
+		function _seek($row)
+		{
+			if (sizeof($this->_array) && 0 <= $row && $row < $this->_numOfRows) {
+				$this->_currentRow = $row;
+				if ($this->_skiprow1) $row += 1;
+				$this->fields = $this->_array[$row];
+				return true;
+			}
+			return false;
+		}
+		
+		function MoveNext() 
+		{
+			if (!$this->EOF) {		
+				$this->_currentRow++;
+				
+				$pos = $this->_currentRow;
+				
+				if ($this->_numOfRows <= $pos) {
+					if (!$this->compat) $this->fields = false;
+				} else {
+					if ($this->_skiprow1) $pos += 1;
+					$this->fields = $this->_array[$pos];
+					return true;
+				}		
+				$this->EOF = true;
+			}
+			
+			return false;
+		}	
+	
+		function _fetch()
+		{
+			$pos = $this->_currentRow;
+			
+			if ($this->_numOfRows <= $pos) {
+				if (!$this->compat) $this->fields = false;
+				return false;
+			}
+			if ($this->_skiprow1) $pos += 1;
+			$this->fields = $this->_array[$pos];
+			return true;
+		}
+		
+		function _close() 
+		{
+			return true;	
+		}
+	
+	} // ADORecordSet_array
+
+	//==============================================================================================	
+	// HELPER FUNCTIONS
+	//==============================================================================================			
+	
+	/**
+	 * Synonym for ADOLoadCode. Private function. Do not use.
+	 *
+	 * @deprecated
+	 */
+	function ADOLoadDB($dbType) 
+	{ 
+		return ADOLoadCode($dbType);
+	}
+		
+	/**
+	 * Load the code for a specific database driver. Private function. Do not use.
+	 */
+	function ADOLoadCode($dbType) 
+	{
+	global $ADODB_LASTDB;
+	
+		if (!$dbType) return false;
+		$db = strtolower($dbType);
+		switch ($db) {
+			case 'ado': 
+				if (PHP_VERSION >= 5) $db = 'ado5';
+				$class = 'ado'; 
+				break;
+			case 'ifx':
+			case 'maxsql': $class = $db = 'mysqlt'; break;
+			case 'postgres':
+			case 'postgres8':
+			case 'pgsql': $class = $db = 'postgres7'; break;
+			default:
+				$class = $db; break;
+		}
+		
+		$file = ADODB_DIR."/drivers/adodb-".$db.".inc.php";
+		@include_once($file);
+		$ADODB_LASTDB = $class;
+		if (class_exists("ADODB_" . $class)) return $class;
+		
+		//ADOConnection::outp(adodb_pr(get_declared_classes(),true));
+		if (!file_exists($file)) ADOConnection::outp("Missing file: $file");
+		else ADOConnection::outp("Syntax error in file: $file");
+		return false;
+	}
+
+	/**
+	 * synonym for ADONewConnection for people like me who cannot remember the correct name
+	 */
+	function &NewADOConnection($db='')
+	{
+		$tmp =& ADONewConnection($db);
+		return $tmp;
+	}
+	
+	/**
+	 * Instantiate a new Connection class for a specific database driver.
+	 *
+	 * @param [db]  is the database Connection object to create. If undefined,
+	 * 	use the last database driver that was loaded by ADOLoadCode().
+	 *
+	 * @return the freshly created instance of the Connection class.
+	 */
+	function &ADONewConnection($db='')
+	{
+	GLOBAL $ADODB_NEWCONNECTION, $ADODB_LASTDB;
+		
+		if (!defined('ADODB_ASSOC_CASE')) define('ADODB_ASSOC_CASE',2);
+		$errorfn = (defined('ADODB_ERROR_HANDLER')) ? ADODB_ERROR_HANDLER : false;
+		$false = false;
+		if ($at = strpos($db,'://')) {
+			$origdsn = $db;
+			if (PHP_VERSION < 5) $dsna = @parse_url($db);
+			else {
+				$fakedsn = 'fake'.substr($db,$at);
+				$dsna = @parse_url($fakedsn);
+				$dsna['scheme'] = substr($db,0,$at);
+			
+				if (strncmp($db,'pdo',3) == 0) {
+					$sch = explode('_',$dsna['scheme']);
+					if (sizeof($sch)>1) {
+						$dsna['host'] = isset($dsna['host']) ? rawurldecode($dsna['host']) : '';
+						$dsna['host'] = rawurlencode($sch[1].':host='.rawurldecode($dsna['host']));
+						$dsna['scheme'] = 'pdo';
+					}
+				}
+			}
+			
+			if (!$dsna) {
+				// special handling of oracle, which might not have host
+				$db = str_replace('@/','@adodb-fakehost/',$db);
+				$dsna = parse_url($db);
+				if (!$dsna) return $false;
+				$dsna['host'] = '';
+			}
+			$db = @$dsna['scheme'];
+			if (!$db) return $false;
+			$dsna['host'] = isset($dsna['host']) ? rawurldecode($dsna['host']) : '';
+			$dsna['user'] = isset($dsna['user']) ? rawurldecode($dsna['user']) : '';
+			$dsna['pass'] = isset($dsna['pass']) ? rawurldecode($dsna['pass']) : '';
+			$dsna['path'] = isset($dsna['path']) ? rawurldecode(substr($dsna['path'],1)) : ''; # strip off initial /
+			
+			if (isset($dsna['query'])) {
+				$opt1 = explode('&',$dsna['query']);
+				foreach($opt1 as $k => $v) {
+					$arr = explode('=',$v);
+					$opt[$arr[0]] = isset($arr[1]) ? rawurldecode($arr[1]) : 1;
+				}
+			} else $opt = array();
+		}
+	/*
+	 *  phptype: Database backend used in PHP (mysql, odbc etc.)
+	 *  dbsyntax: Database used with regards to SQL syntax etc.
+	 *  protocol: Communication protocol to use (tcp, unix etc.)
+	 *  hostspec: Host specification (hostname[:port])
+	 *  database: Database to use on the DBMS server
+	 *  username: User name for login
+	 *  password: Password for login
+	 */
+		if (!empty($ADODB_NEWCONNECTION)) {
+			$obj = $ADODB_NEWCONNECTION($db);
+
+		} else {
+		
+			if (!isset($ADODB_LASTDB)) $ADODB_LASTDB = '';
+			if (empty($db)) $db = $ADODB_LASTDB;
+			
+			if ($db != $ADODB_LASTDB) $db = ADOLoadCode($db);
+			
+			if (!$db) {
+				if (isset($origdsn)) $db = $origdsn;
+				if ($errorfn) {
+					// raise an error
+					$ignore = false;
+					$errorfn('ADONewConnection', 'ADONewConnection', -998,
+							 "could not load the database driver for '$db'",
+							 $db,false,$ignore);
+				} else
+					 ADOConnection::outp( "<p>ADONewConnection: Unable to load database driver '$db'</p>",false);
+					
+				return $false;
+			}
+			
+			$cls = 'ADODB_'.$db;
+			if (!class_exists($cls)) {
+				adodb_backtrace();
+				return $false;
+			}
+			
+			$obj = new $cls();
+		}
+		
+		# constructor should not fail
+		if ($obj) {
+			if ($errorfn)  $obj->raiseErrorFn = $errorfn;
+			if (isset($dsna)) {
+				if (isset($dsna['port'])) $obj->port = $dsna['port'];
+				foreach($opt as $k => $v) {
+					switch(strtolower($k)) {
+					case 'new':
+										$nconnect = true; $persist = true; break;
+					case 'persist':
+					case 'persistent': 	$persist = $v; break;
+					case 'debug':		$obj->debug = (integer) $v; break;
+					#ibase
+					case 'role':		$obj->role = $v; break;
+					case 'dialect': 	$obj->dialect = (integer) $v; break;
+					case 'charset':		$obj->charset = $v; $obj->charSet=$v; break;
+					case 'buffers':		$obj->buffers = $v; break;
+					case 'fetchmode':   $obj->SetFetchMode($v); break;
+					#ado
+					case 'charpage':	$obj->charPage = $v; break;
+					#mysql, mysqli
+					case 'clientflags': $obj->clientFlags = $v; break;
+					#mysql, mysqli, postgres
+					case 'port': $obj->port = $v; break;
+					#mysqli
+					case 'socket': $obj->socket = $v; break;
+					#oci8
+					case 'nls_date_format': $obj->NLS_DATE_FORMAT = $v; break;
+					}
+				}
+				if (empty($persist))
+					$ok = $obj->Connect($dsna['host'], $dsna['user'], $dsna['pass'], $dsna['path']);
+				else if (empty($nconnect))
+					$ok = $obj->PConnect($dsna['host'], $dsna['user'], $dsna['pass'], $dsna['path']);
+				else
+					$ok = $obj->NConnect($dsna['host'], $dsna['user'], $dsna['pass'], $dsna['path']);
+					
+				if (!$ok) return $false;
+			}
+		}
+		return $obj;
+	}
+	
+	
+	
+	// $perf == true means called by NewPerfMonitor(), otherwise for data dictionary
+	function _adodb_getdriver($provider,$drivername,$perf=false)
+	{
+		switch ($provider) {
+		case 'odbtp':   if (strncmp('odbtp_',$drivername,6)==0) return substr($drivername,6); 
+		case 'odbc' :   if (strncmp('odbc_',$drivername,5)==0) return substr($drivername,5); 
+		case 'ado'  :   if (strncmp('ado_',$drivername,4)==0) return substr($drivername,4);
+		case 'native':  break;
+		default:
+			return $provider;
+		}
+		
+		switch($drivername) {
+		case 'mysqlt':
+		case 'mysqli': 
+				$drivername='mysql'; 
+				break;
+		case 'postgres7':
+		case 'postgres8':
+				$drivername = 'postgres'; 
+				break;	
+		case 'firebird15': $drivername = 'firebird'; break;
+		case 'oracle': $drivername = 'oci8'; break;
+		case 'access': if ($perf) $drivername = ''; break;
+		case 'db2'   : break;
+		case 'sapdb' : break;
+		default:
+			$drivername = 'generic';
+			break;
+		}
+		return $drivername;
+	}
+	
+	function &NewPerfMonitor(&$conn)
+	{
+		$false = false;
+		$drivername = _adodb_getdriver($conn->dataProvider,$conn->databaseType,true);
+		if (!$drivername || $drivername == 'generic') return $false;
+		include_once(ADODB_DIR.'/adodb-perf.inc.php');
+		@include_once(ADODB_DIR."/perf/perf-$drivername.inc.php");
+		$class = "Perf_$drivername";
+		if (!class_exists($class)) return $false;
+		$perf = new $class($conn);
+		
+		return $perf;
+	}
+	
+	function &NewDataDictionary(&$conn,$drivername=false)
+	{
+		$false = false;
+		if (!$drivername) $drivername = _adodb_getdriver($conn->dataProvider,$conn->databaseType);
+
+		include_once(ADODB_DIR.'/adodb-lib.inc.php');
+		include_once(ADODB_DIR.'/adodb-datadict.inc.php');
+		$path = ADODB_DIR."/datadict/datadict-$drivername.inc.php";
+
+		if (!file_exists($path)) {
+			ADOConnection::outp("Dictionary driver '$path' not available");
+			return $false;
+		}
+		include_once($path);
+		$class = "ADODB2_$drivername";
+		$dict = new $class();
+		$dict->dataProvider = $conn->dataProvider;
+		$dict->connection = &$conn;
+		$dict->upperName = strtoupper($drivername);
+		$dict->quote = $conn->nameQuote;
+		if (!empty($conn->_connectionID))
+			$dict->serverInfo = $conn->ServerInfo();
+		
+		return $dict;
+	}
+
+
+	
+	/*
+		Perform a print_r, with pre tags for better formatting.
+	*/
+	function adodb_pr($var,$as_string=false)
+	{
+		if ($as_string) ob_start();
+		
+		if (isset($_SERVER['HTTP_USER_AGENT'])) { 
+			echo " <pre>\n";print_r($var);echo "</pre>\n";
+		} else
+			print_r($var);
+			
+		if ($as_string) {
+			$s = ob_get_contents();
+			ob_end_clean();
+			return $s;
+		}
+	}
+	
+	/*
+		Perform a stack-crawl and pretty print it.
+		
+		@param printOrArr  Pass in a boolean to indicate print, or an $exception->trace array (assumes that print is true then).
+		@param levels Number of levels to display
+	*/
+	function adodb_backtrace($printOrArr=true,$levels=9999)
+	{
+		global $ADODB_INCLUDED_LIB;
+		if (empty($ADODB_INCLUDED_LIB)) include(ADODB_DIR.'/adodb-lib.inc.php');
+		return _adodb_backtrace($printOrArr,$levels);
+	}
+
+
+}
+?>
Index: /Dev/trunk/rdfapi/util/adodb/contrib/toxmlrpc.inc.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/contrib/toxmlrpc.inc.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/contrib/toxmlrpc.inc.php	(revision 12)
@@ -0,0 +1,183 @@
+<?php
+    /**
+    * Helper functions to convert between ADODB recordset objects and XMLRPC values.
+    * Uses John Lim's AdoDB and Edd Dumbill's phpxmlrpc libs
+    * 
+    * @author Daniele Baroncelli
+    * @author Gaetano Giunta
+    * @copyright (c) 2003-2004 Giunta/Baroncelli. All rights reserved.
+    * 
+    * @todo some more error checking here and there
+    * @todo document the xmlrpc-struct used to encode recordset info
+    * @todo verify if using xmlrpc_encode($rs->GetArray()) would work with:
+    *       - ADODB_FETCH_BOTH
+    *       - null values
+    */
+
+    /**
+    * Include the main libraries
+    */    
+    require_once('xmlrpc.inc');
+    if (!defined('ADODB_DIR')) require_once('adodb.inc.php');
+            
+    /**
+    * Builds an xmlrpc struct value out of an AdoDB recordset
+    */
+    function rs2xmlrpcval(&$adodbrs) {
+
+        $header =& rs2xmlrpcval_header($adodbrs);
+        $body =& rs2xmlrpcval_body($adodbrs);
+
+        // put it all together and build final xmlrpc struct
+        $xmlrpcrs =& new xmlrpcval ( array(
+                "header" => $header,
+                "body" => $body,
+                ), "struct");
+
+        return $xmlrpcrs;
+
+    }
+
+    /**
+    * Builds an xmlrpc struct value describing an AdoDB recordset
+    */
+    function rs2xmlrpcval_header($adodbrs)
+    {
+        $numfields = $adodbrs->FieldCount();
+        $numrecords = $adodbrs->RecordCount();
+
+        // build structure holding recordset information
+        $fieldstruct = array();
+        for ($i = 0; $i < $numfields; $i++) {
+            $fld = $adodbrs->FetchField($i);
+            $fieldarray = array();
+            if (isset($fld->name))
+                $fieldarray["name"] =& new xmlrpcval ($fld->name);
+            if (isset($fld->type))
+                $fieldarray["type"] =& new xmlrpcval ($fld->type);
+            if (isset($fld->max_length))
+                $fieldarray["max_length"] =& new xmlrpcval ($fld->max_length, "int");
+            if (isset($fld->not_null))
+                $fieldarray["not_null"] =& new xmlrpcval ($fld->not_null, "boolean");
+            if (isset($fld->has_default))
+                $fieldarray["has_default"] =& new xmlrpcval ($fld->has_default, "boolean");
+            if (isset($fld->default_value))
+                $fieldarray["default_value"] =& new xmlrpcval ($fld->default_value);
+            $fieldstruct[$i] =& new xmlrpcval ($fieldarray, "struct");
+        }
+        $fieldcount =& new xmlrpcval ($numfields, "int");
+        $recordcount =& new xmlrpcval ($numrecords, "int");
+        $sql =& new xmlrpcval ($adodbrs->sql);
+        $fieldinfo =& new xmlrpcval ($fieldstruct, "array");
+
+        $header =& new xmlrpcval ( array(
+                "fieldcount" => $fieldcount,
+                "recordcount" => $recordcount,
+                "sql" => $sql,
+                "fieldinfo" => $fieldinfo
+                ), "struct");
+
+        return $header;
+    }
+
+    /**
+    * Builds an xmlrpc struct value out of an AdoDB recordset
+    * (data values only, no data definition)
+    */
+    function rs2xmlrpcval_body($adodbrs)
+    {
+        $numfields = $adodbrs->FieldCount();
+
+        // build structure containing recordset data
+        $adodbrs->MoveFirst();
+        $rows = array();
+        while (!$adodbrs->EOF) {
+            $columns = array();
+            // This should work on all cases of fetch mode: assoc, num, both or default
+            if ($adodbrs->fetchMode == 'ADODB_FETCH_BOTH' || count($adodbrs->fields) == 2 * $adodbrs->FieldCount())
+                for ($i = 0; $i < $numfields; $i++)
+                    if ($adodbrs->fields[$i] === null)
+                        $columns[$i] =& new xmlrpcval ('');
+                    else
+                        $columns[$i] =& xmlrpc_encode ($adodbrs->fields[$i]);
+            else
+                foreach ($adodbrs->fields as $val)
+                    if ($val === null)
+                        $columns[] =& new xmlrpcval ('');
+                    else
+                        $columns[] =& xmlrpc_encode ($val);
+
+            $rows[] =& new xmlrpcval ($columns, "array");
+
+            $adodbrs->MoveNext();
+        }
+        $body =& new xmlrpcval ($rows, "array");
+
+        return $body;    
+    }
+    
+    /**
+    * Returns an xmlrpc struct value as string out of an AdoDB recordset
+    */    
+    function rs2xmlrpcstring (&$adodbrs) {
+        $xmlrpc = rs2xmlrpcval ($adodbrs);
+        if ($xmlrpc)
+          return $xmlrpc->serialize();
+        else
+          return null;
+    }
+
+    /**
+    * Given a well-formed xmlrpc struct object returns an AdoDB object
+    * 
+    * @todo add some error checking on the input value
+    */
+    function xmlrpcval2rs (&$xmlrpcval) {
+
+        $fields_array = array();
+        $data_array = array();
+ 
+        // rebuild column information  
+        $header =& $xmlrpcval->structmem('header');
+        
+        $numfields = $header->structmem('fieldcount');
+        $numfields = $numfields->scalarval();
+        $numrecords = $header->structmem('recordcount');
+        $numrecords = $numrecords->scalarval();
+        $sqlstring = $header->structmem('sql');
+        $sqlstring = $sqlstring->scalarval();
+        
+        $fieldinfo =& $header->structmem('fieldinfo');
+        for ($i = 0; $i < $numfields; $i++) {
+            $temp =& $fieldinfo->arraymem($i);
+            $fld =& new ADOFieldObject();
+            while (list($key,$value) = $temp->structeach()) {
+                if ($key == "name") $fld->name = $value->scalarval();
+                if ($key == "type") $fld->type = $value->scalarval();
+                if ($key == "max_length") $fld->max_length = $value->scalarval();
+                if ($key == "not_null") $fld->not_null = $value->scalarval();
+                if ($key == "has_default") $fld->has_default = $value->scalarval();
+                if ($key == "default_value") $fld->default_value = $value->scalarval();
+            } // while
+            $fields_array[] = $fld;
+        } // for
+
+        // fetch recordset information into php array
+        $body =& $xmlrpcval->structmem('body');
+        for ($i = 0; $i < $numrecords; $i++) {
+            $data_array[$i]= array();
+            $xmlrpcrs_row =& $body->arraymem($i);
+            for ($j = 0; $j < $numfields; $j++) {
+                $temp =& $xmlrpcrs_row->arraymem($j);
+                $data_array[$i][$j] = $temp->scalarval();
+            } // for j
+        } // for i
+
+        // finally build in-memory recordset object and return it
+        $rs =& new ADORecordSet_array();
+        $rs->InitArrayFields($data_array,$fields_array);
+        return $rs;
+
+    }
+
+?>
Index: /Dev/trunk/rdfapi/util/adodb/datadict/datadict-access.inc.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/datadict/datadict-access.inc.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/datadict/datadict-access.inc.php	(revision 12)
@@ -0,0 +1,95 @@
+<?php
+
+/**
+  V4.94 23 Jan 2007  (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence.
+	
+  Set tabs to 4 for best viewing.
+ 
+*/
+
+// security - hide paths
+if (!defined('ADODB_DIR')) die();
+
+class ADODB2_access extends ADODB_DataDict {
+	
+	var $databaseType = 'access';
+	var $seqField = false;
+	
+ 	
+ 	function ActualType($meta)
+	{
+		switch($meta) {
+		case 'C': return 'TEXT';
+		case 'XL':
+		case 'X': return 'MEMO'; 
+		
+		case 'C2': return 'TEXT'; // up to 32K
+		case 'X2': return 'MEMO';
+		
+		case 'B': return 'BINARY';
+			
+		case 'D': return 'DATETIME';
+		case 'T': return 'DATETIME';
+		
+		case 'L': return 'BYTE';
+		case 'I': return 'INTEGER';
+		case 'I1': return 'BYTE';
+		case 'I2': return 'SMALLINT';
+		case 'I4': return 'INTEGER';
+		case 'I8': return 'INTEGER';
+		
+		case 'F': return 'DOUBLE';
+		case 'N': return 'NUMERIC';
+		default:
+			return $meta;
+		}
+	}
+	
+	// return string must begin with space
+	function _CreateSuffix($fname, &$ftype, $fnotnull,$fdefault,$fautoinc,$fconstraint)
+	{
+		if ($fautoinc) {
+			$ftype = 'COUNTER';
+			return '';
+		}
+		if (substr($ftype,0,7) == 'DECIMAL') $ftype = 'DECIMAL';
+		$suffix = '';
+		if (strlen($fdefault)) {
+			//$suffix .= " DEFAULT $fdefault";
+			if ($this->debug) ADOConnection::outp("Warning: Access does not supported DEFAULT values (field $fname)");
+		}
+		if ($fnotnull) $suffix .= ' NOT NULL';
+		if ($fconstraint) $suffix .= ' '.$fconstraint;
+		return $suffix;
+	}
+	
+	function CreateDatabase($dbname,$options=false)
+	{
+		return array();
+	}
+	
+	
+	function SetSchema($schema)
+	{
+	}
+
+	function AlterColumnSQL($tabname, $flds)
+	{
+		if ($this->debug) ADOConnection::outp("AlterColumnSQL not supported");
+		return array();
+	}
+	
+	
+	function DropColumnSQL($tabname, $flds)
+	{
+		if ($this->debug) ADOConnection::outp("DropColumnSQL not supported");
+		return array();
+	}
+	
+}
+
+
+?>
Index: /Dev/trunk/rdfapi/util/adodb/datadict/datadict-db2.inc.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/datadict/datadict-db2.inc.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/datadict/datadict-db2.inc.php	(revision 12)
@@ -0,0 +1,143 @@
+<?php
+
+/**
+  V4.94 23 Jan 2007  (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence.
+	
+  Set tabs to 4 for best viewing.
+ 
+*/
+// security - hide paths
+if (!defined('ADODB_DIR')) die();
+
+class ADODB2_db2 extends ADODB_DataDict {
+	
+	var $databaseType = 'db2';
+	var $seqField = false;
+	
+ 	function ActualType($meta)
+	{
+		switch($meta) {
+		case 'C': return 'VARCHAR';
+		case 'XL': return 'CLOB';
+		case 'X': return 'VARCHAR(3600)'; 
+
+		case 'C2': return 'VARCHAR'; // up to 32K
+		case 'X2': return 'VARCHAR(3600)'; // up to 32000, but default page size too small
+
+		case 'B': return 'BLOB';
+
+		case 'D': return 'DATE';
+		case 'T': return 'TIMESTAMP';
+
+		case 'L': return 'SMALLINT';
+		case 'I': return 'INTEGER';
+		case 'I1': return 'SMALLINT';
+		case 'I2': return 'SMALLINT';
+		case 'I4': return 'INTEGER';
+		case 'I8': return 'BIGINT';
+
+		case 'F': return 'DOUBLE';
+		case 'N': return 'DECIMAL';
+		default:
+			return $meta;
+		}
+	}
+	
+	// return string must begin with space
+	function _CreateSuffix($fname,$ftype,$fnotnull,$fdefault,$fautoinc,$fconstraint)
+	{	
+		$suffix = '';
+		if ($fautoinc) return ' GENERATED ALWAYS AS IDENTITY'; # as identity start with 
+		if (strlen($fdefault)) $suffix .= " DEFAULT $fdefault";
+		if ($fnotnull) $suffix .= ' NOT NULL';
+		if ($fconstraint) $suffix .= ' '.$fconstraint;
+		return $suffix;
+	}
+
+	function AlterColumnSQL($tabname, $flds)
+	{
+		if ($this->debug) ADOConnection::outp("AlterColumnSQL not supported");
+		return array();
+	}
+	
+	
+	function DropColumnSQL($tabname, $flds)
+	{
+		if ($this->debug) ADOConnection::outp("DropColumnSQL not supported");
+		return array();
+	}
+	
+	
+	function ChangeTableSQL($tablename, $flds, $tableoptions = false)
+	{
+		
+		/**
+		  Allow basic table changes to DB2 databases
+		  DB2 will fatally reject changes to non character columns 
+
+		*/
+		
+		$validTypes = array("CHAR","VARC");
+		$invalidTypes = array("BIGI","BLOB","CLOB","DATE", "DECI","DOUB", "INTE", "REAL","SMAL", "TIME");
+		// check table exists
+		$cols = &$this->MetaColumns($tablename);
+		if ( empty($cols)) { 
+			return $this->CreateTableSQL($tablename, $flds, $tableoptions);
+		}
+		
+		// already exists, alter table instead
+		list($lines,$pkey) = $this->_GenFields($flds);
+		$alter = 'ALTER TABLE ' . $this->TableName($tablename);
+		$sql = array();
+		
+		foreach ( $lines as $id => $v ) {
+			if ( isset($cols[$id]) && is_object($cols[$id]) ) {
+				/**
+				  If the first field of $v is the fieldname, and
+				  the second is the field type/size, we assume its an
+				  attempt to modify the column size, so check that it is allowed
+				  $v can have an indeterminate number of blanks between the
+				  fields, so account for that too
+				 */
+				$vargs = explode(' ' , $v);
+				// assume that $vargs[0] is the field name.
+				$i=0;
+				// Find the next non-blank value;
+				for ($i=1;$i<sizeof($vargs);$i++)
+					if ($vargs[$i] != '')
+						break;
+				
+				// if $vargs[$i] is one of the following, we are trying to change the
+				// size of the field, if not allowed, simply ignore the request.
+				if (in_array(substr($vargs[$i],0,4),$invalidTypes)) 
+					continue;
+				// insert the appropriate DB2 syntax
+				if (in_array(substr($vargs[$i],0,4),$validTypes)) {
+					array_splice($vargs,$i,0,array('SET','DATA','TYPE'));
+				}
+
+				// Now Look for the NOT NULL statement as this is not allowed in
+				// the ALTER table statement. If it is in there, remove it
+				if (in_array('NOT',$vargs) && in_array('NULL',$vargs)) {
+					for ($i=1;$i<sizeof($vargs);$i++)
+					if ($vargs[$i] == 'NOT')
+						break;
+					array_splice($vargs,$i,2,'');
+				}
+				$v = implode(' ',$vargs);	
+				$sql[] = $alter . $this->alterCol . ' ' . $v;
+			} else {
+				$sql[] = $alter . $this->addCol . ' ' . $v;
+			}
+		}
+		
+		return $sql;
+	}
+	
+}
+
+
+?>
Index: /Dev/trunk/rdfapi/util/adodb/datadict/datadict-firebird.inc.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/datadict/datadict-firebird.inc.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/datadict/datadict-firebird.inc.php	(revision 12)
@@ -0,0 +1,151 @@
+<?php
+
+/**
+  V4.94 23 Jan 2007  (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence.
+	
+  Set tabs to 4 for best viewing.
+ 
+*/
+
+class ADODB2_firebird extends ADODB_DataDict {
+	
+	var $databaseType = 'firebird';
+	var $seqField = false;
+	var $seqPrefix = 'gen_';
+	var $blobSize = 40000;	
+ 	
+ 	function ActualType($meta)
+	{
+		switch($meta) {
+		case 'C': return 'VARCHAR';
+		case 'XL': return 'VARCHAR(32000)'; 
+		case 'X': return 'VARCHAR(4000)'; 
+		
+		case 'C2': return 'VARCHAR'; // up to 32K
+		case 'X2': return 'VARCHAR(4000)';
+		
+		case 'B': return 'BLOB';
+			
+		case 'D': return 'DATE';
+		case 'T': return 'TIMESTAMP';
+		
+		case 'L': return 'SMALLINT';
+		case 'I': return 'INTEGER';
+		case 'I1': return 'SMALLINT';
+		case 'I2': return 'SMALLINT';
+		case 'I4': return 'INTEGER';
+		case 'I8': return 'INTEGER';
+		
+		case 'F': return 'DOUBLE PRECISION';
+		case 'N': return 'DECIMAL';
+		default:
+			return $meta;
+		}
+	}
+	
+	function NameQuote($name = NULL)
+	{
+		if (!is_string($name)) {
+			return FALSE;
+		}
+		
+		$name = trim($name);
+		
+		if ( !is_object($this->connection) ) {
+			return $name;
+		}
+		
+		$quote = $this->connection->nameQuote;
+		
+		// if name is of the form `name`, quote it
+		if ( preg_match('/^`(.+)`$/', $name, $matches) ) {
+			return $quote . $matches[1] . $quote;
+		}
+		
+		// if name contains special characters, quote it
+		if ( !preg_match('/^[' . $this->nameRegex . ']+$/', $name) ) {
+			return $quote . $name . $quote;
+		}
+		
+		return $quote . $name . $quote;
+	}
+
+	function CreateDatabase($dbname, $options=false)
+	{
+		$options = $this->_Options($options);
+		$sql = array();
+		
+		$sql[] = "DECLARE EXTERNAL FUNCTION LOWER CSTRING(80) RETURNS CSTRING(80) FREE_IT ENTRY_POINT 'IB_UDF_lower' MODULE_NAME 'ib_udf'";
+		
+		return $sql;
+	}
+	
+	function _DropAutoIncrement($t)
+	{
+		if (strpos($t,'.') !== false) {
+			$tarr = explode('.',$t);
+			return 'DROP GENERATOR '.$tarr[0].'."gen_'.$tarr[1].'"';
+		}
+		return 'DROP GENERATOR "GEN_'.$t;
+	}
+	
+
+	function _CreateSuffix($fname,$ftype,$fnotnull,$fdefault,$fautoinc,$fconstraint,$funsigned)
+	{
+		$suffix = '';
+		
+		if (strlen($fdefault)) $suffix .= " DEFAULT $fdefault";
+		if ($fnotnull) $suffix .= ' NOT NULL';
+		if ($fautoinc) $this->seqField = $fname;
+		if ($fconstraint) $suffix .= ' '.$fconstraint;
+		
+		return $suffix;
+	}
+	
+/*
+CREATE or replace TRIGGER jaddress_insert
+before insert on jaddress
+for each row
+begin
+IF ( NEW."seqField" IS NULL OR NEW."seqField" = 0 ) THEN
+  NEW."seqField" = GEN_ID("GEN_tabname", 1);
+end;
+*/
+	function _Triggers($tabname,$tableoptions)
+	{	
+		if (!$this->seqField) return array();
+		
+		$tab1 = preg_replace( '/"/', '', $tabname );
+		if ($this->schema) {
+			$t = strpos($tab1,'.');
+			if ($t !== false) $tab = substr($tab1,$t+1);
+			else $tab = $tab1;
+			$seqField = $this->seqField;
+			$seqname = $this->schema.'.'.$this->seqPrefix.$tab;
+			$trigname = $this->schema.'.trig_'.$this->seqPrefix.$tab;
+		} else {
+			$seqField = $this->seqField;
+			$seqname = $this->seqPrefix.$tab1;
+			$trigname = 'trig_'.$seqname;
+		}
+		if (isset($tableoptions['REPLACE']))
+		{ $sql[] = "DROP GENERATOR \"$seqname\"";
+		  $sql[] = "CREATE GENERATOR \"$seqname\"";
+		  $sql[] = "ALTER TRIGGER \"$trigname\" BEFORE INSERT OR UPDATE AS BEGIN IF ( NEW.$seqField IS NULL OR NEW.$seqField = 0 ) THEN NEW.$seqField = GEN_ID(\"$seqname\", 1); END";
+		}
+		else
+		{ $sql[] = "CREATE GENERATOR \"$seqname\"";
+		  $sql[] = "CREATE TRIGGER \"$trigname\" FOR $tabname BEFORE INSERT OR UPDATE AS BEGIN IF ( NEW.$seqField IS NULL OR NEW.$seqField = 0 ) THEN NEW.$seqField = GEN_ID(\"$seqname\", 1); END";
+		}
+		
+		$this->seqField = false;
+		return $sql;
+	}
+
+}
+
+
+?>
Index: /Dev/trunk/rdfapi/util/adodb/datadict/datadict-generic.inc.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/datadict/datadict-generic.inc.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/datadict/datadict-generic.inc.php	(revision 12)
@@ -0,0 +1,125 @@
+<?php
+
+/**
+  V4.94 23 Jan 2007  (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence.
+	
+  Set tabs to 4 for best viewing.
+ 
+*/
+
+// security - hide paths
+if (!defined('ADODB_DIR')) die();
+
+class ADODB2_generic extends ADODB_DataDict {
+	
+	var $databaseType = 'generic';
+	var $seqField = false;
+	
+ 	
+ 	function ActualType($meta)
+	{
+		switch($meta) {
+		case 'C': return 'VARCHAR';
+		case 'XL':
+		case 'X': return 'VARCHAR(250)';
+		
+		case 'C2': return 'VARCHAR';
+		case 'X2': return 'VARCHAR(250)';
+		
+		case 'B': return 'VARCHAR';
+			
+		case 'D': return 'DATE';
+		case 'T': return 'DATE';
+		
+		case 'L': return 'DECIMAL(1)';
+		case 'I': return 'DECIMAL(10)';
+		case 'I1': return 'DECIMAL(3)';
+		case 'I2': return 'DECIMAL(5)';
+		case 'I4': return 'DECIMAL(10)';
+		case 'I8': return 'DECIMAL(20)';
+		
+		case 'F': return 'DECIMAL(32,8)';
+		case 'N': return 'DECIMAL';
+		default:
+			return $meta;
+		}
+	}
+
+	function AlterColumnSQL($tabname, $flds)
+	{
+		if ($this->debug) ADOConnection::outp("AlterColumnSQL not supported");
+		return array();
+	}
+	
+	
+	function DropColumnSQL($tabname, $flds)
+	{
+		if ($this->debug) ADOConnection::outp("DropColumnSQL not supported");
+		return array();
+	}
+	
+}
+
+/*
+//db2
+ 	function ActualType($meta)
+	{
+		switch($meta) {
+		case 'C': return 'VARCHAR';
+		case 'X': return 'VARCHAR'; 
+		
+		case 'C2': return 'VARCHAR'; // up to 32K
+		case 'X2': return 'VARCHAR';
+		
+		case 'B': return 'BLOB';
+			
+		case 'D': return 'DATE';
+		case 'T': return 'TIMESTAMP';
+		
+		case 'L': return 'SMALLINT';
+		case 'I': return 'INTEGER';
+		case 'I1': return 'SMALLINT';
+		case 'I2': return 'SMALLINT';
+		case 'I4': return 'INTEGER';
+		case 'I8': return 'BIGINT';
+		
+		case 'F': return 'DOUBLE';
+		case 'N': return 'DECIMAL';
+		default:
+			return $meta;
+		}
+	}
+	
+// ifx
+function ActualType($meta)
+	{
+		switch($meta) {
+		case 'C': return 'VARCHAR';// 255
+		case 'X': return 'TEXT'; 
+		
+		case 'C2': return 'NVARCHAR';
+		case 'X2': return 'TEXT';
+		
+		case 'B': return 'BLOB';
+			
+		case 'D': return 'DATE';
+		case 'T': return 'DATETIME';
+		
+		case 'L': return 'SMALLINT';
+		case 'I': return 'INTEGER';
+		case 'I1': return 'SMALLINT';
+		case 'I2': return 'SMALLINT';
+		case 'I4': return 'INTEGER';
+		case 'I8': return 'DECIMAL(20)';
+		
+		case 'F': return 'FLOAT';
+		case 'N': return 'DECIMAL';
+		default:
+			return $meta;
+		}
+	}
+*/
+?>
Index: /Dev/trunk/rdfapi/util/adodb/datadict/datadict-ibase.inc.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/datadict/datadict-ibase.inc.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/datadict/datadict-ibase.inc.php	(revision 12)
@@ -0,0 +1,67 @@
+<?php
+
+/**
+  V4.94 23 Jan 2007  (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence.
+	
+  Set tabs to 4 for best viewing.
+ 
+*/
+
+// security - hide paths
+if (!defined('ADODB_DIR')) die();
+
+class ADODB2_ibase extends ADODB_DataDict {
+	
+	var $databaseType = 'ibase';
+	var $seqField = false;
+	
+ 	
+ 	function ActualType($meta)
+	{
+		switch($meta) {
+		case 'C': return 'VARCHAR';
+		case 'XL':
+		case 'X': return 'VARCHAR(4000)'; 
+		
+		case 'C2': return 'VARCHAR'; // up to 32K
+		case 'X2': return 'VARCHAR(4000)';
+		
+		case 'B': return 'BLOB';
+			
+		case 'D': return 'DATE';
+		case 'T': return 'TIMESTAMP';
+		
+		case 'L': return 'SMALLINT';
+		case 'I': return 'INTEGER';
+		case 'I1': return 'SMALLINT';
+		case 'I2': return 'SMALLINT';
+		case 'I4': return 'INTEGER';
+		case 'I8': return 'INTEGER';
+		
+		case 'F': return 'DOUBLE PRECISION';
+		case 'N': return 'DECIMAL';
+		default:
+			return $meta;
+		}
+	}
+
+	function AlterColumnSQL($tabname, $flds)
+	{
+		if ($this->debug) ADOConnection::outp("AlterColumnSQL not supported");
+		return array();
+	}
+	
+	
+	function DropColumnSQL($tabname, $flds)
+	{
+		if ($this->debug) ADOConnection::outp("DropColumnSQL not supported");
+		return array();
+	}
+	
+}
+
+
+?>
Index: /Dev/trunk/rdfapi/util/adodb/datadict/datadict-informix.inc.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/datadict/datadict-informix.inc.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/datadict/datadict-informix.inc.php	(revision 12)
@@ -0,0 +1,80 @@
+<?php
+
+/**
+  V4.94 23 Jan 2007  (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence.
+	
+  Set tabs to 4 for best viewing.
+ 
+*/
+
+// security - hide paths
+if (!defined('ADODB_DIR')) die();
+
+class ADODB2_informix extends ADODB_DataDict {
+	
+	var $databaseType = 'informix';
+	var $seqField = false;
+	
+ 	
+	function ActualType($meta)
+	{
+		switch($meta) {
+		case 'C': return 'VARCHAR';// 255
+		case 'XL':
+		case 'X': return 'TEXT'; 
+		
+		case 'C2': return 'NVARCHAR';
+		case 'X2': return 'TEXT';
+		
+		case 'B': return 'BLOB';
+			
+		case 'D': return 'DATE';
+		case 'T': return 'DATETIME YEAR TO SECOND';
+		
+		case 'L': return 'SMALLINT';
+		case 'I': return 'INTEGER';
+		case 'I1': return 'SMALLINT';
+		case 'I2': return 'SMALLINT';
+		case 'I4': return 'INTEGER';
+		case 'I8': return 'DECIMAL(20)';
+		
+		case 'F': return 'FLOAT';
+		case 'N': return 'DECIMAL';
+		default:
+			return $meta;
+		}
+	}
+
+	function AlterColumnSQL($tabname, $flds)
+	{
+		if ($this->debug) ADOConnection::outp("AlterColumnSQL not supported");
+		return array();
+	}
+	
+	
+	function DropColumnSQL($tabname, $flds)
+	{
+		if ($this->debug) ADOConnection::outp("DropColumnSQL not supported");
+		return array();
+	}
+	
+	// return string must begin with space
+	function _CreateSuffix($fname, &$ftype, $fnotnull,$fdefault,$fautoinc,$fconstraint)
+	{
+		if ($fautoinc) {
+			$ftype = 'SERIAL';
+			return '';
+		}
+		$suffix = '';
+		if (strlen($fdefault)) $suffix .= " DEFAULT $fdefault";
+		if ($fnotnull) $suffix .= ' NOT NULL';
+		if ($fconstraint) $suffix .= ' '.$fconstraint;
+		return $suffix;
+	}
+	
+}
+
+?>
Index: /Dev/trunk/rdfapi/util/adodb/datadict/datadict-mssql.inc.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/datadict/datadict-mssql.inc.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/datadict/datadict-mssql.inc.php	(revision 12)
@@ -0,0 +1,282 @@
+<?php
+
+/**
+  V4.94 23 Jan 2007  (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence.
+	
+  Set tabs to 4 for best viewing.
+ 
+*/
+
+/*
+In ADOdb, named quotes for MS SQL Server use ". From the MSSQL Docs:
+
+	Note Delimiters are for identifiers only. Delimiters cannot be used for keywords, 
+	whether or not they are marked as reserved in SQL Server.
+	
+	Quoted identifiers are delimited by double quotation marks ("):
+	SELECT * FROM "Blanks in Table Name"
+	
+	Bracketed identifiers are delimited by brackets ([ ]):
+	SELECT * FROM [Blanks In Table Name]
+	
+	Quoted identifiers are valid only when the QUOTED_IDENTIFIER option is set to ON. By default, 
+	the Microsoft OLE DB Provider for SQL Server and SQL Server ODBC driver set QUOTED_IDENTIFIER ON 
+	when they connect. 
+	
+	In Transact-SQL, the option can be set at various levels using SET QUOTED_IDENTIFIER, 
+	the quoted identifier option of sp_dboption, or the user options option of sp_configure.
+	
+	When SET ANSI_DEFAULTS is ON, SET QUOTED_IDENTIFIER is enabled.
+	
+	Syntax
+	
+		SET QUOTED_IDENTIFIER { ON | OFF }
+
+
+*/
+
+// security - hide paths
+if (!defined('ADODB_DIR')) die();
+
+class ADODB2_mssql extends ADODB_DataDict {
+	var $databaseType = 'mssql';
+	var $dropIndex = 'DROP INDEX %2$s.%1$s';
+	var $renameTable = "EXEC sp_rename '%s','%s'";
+	var $renameColumn = "EXEC sp_rename '%s.%s','%s'";
+
+	var $typeX = 'TEXT';  ## Alternatively, set it to VARCHAR(4000)
+	var $typeXL = 'TEXT';
+	
+	//var $alterCol = ' ALTER COLUMN ';
+	
+	function MetaType($t,$len=-1,$fieldobj=false)
+	{
+		if (is_object($t)) {
+			$fieldobj = $t;
+			$t = $fieldobj->type;
+			$len = $fieldobj->max_length;
+		}
+		
+		$len = -1; // mysql max_length is not accurate
+		switch (strtoupper($t)) {
+		case 'R':
+		case 'INT': 
+		case 'INTEGER': return  'I';
+		case 'BIT':
+		case 'TINYINT': return  'I1';
+		case 'SMALLINT': return 'I2';
+		case 'BIGINT':  return  'I8';
+		
+		case 'REAL':
+		case 'FLOAT': return 'F';
+		default: return parent::MetaType($t,$len,$fieldobj);
+		}
+	}
+	
+	function ActualType($meta)
+	{
+		switch(strtoupper($meta)) {
+
+		case 'C': return 'VARCHAR';
+		case 'XL': return (isset($this)) ? $this->typeXL : 'TEXT';
+		case 'X': return (isset($this)) ? $this->typeX : 'TEXT'; ## could be varchar(8000), but we want compat with oracle
+		case 'C2': return 'NVARCHAR';
+		case 'X2': return 'NTEXT';
+		
+		case 'B': return 'IMAGE';
+			
+		case 'D': return 'DATETIME';
+		case 'T': return 'DATETIME';
+		case 'L': return 'BIT';
+		
+		case 'R':		
+		case 'I': return 'INT'; 
+		case 'I1': return 'TINYINT';
+		case 'I2': return 'SMALLINT';
+		case 'I4': return 'INT';
+		case 'I8': return 'BIGINT';
+		
+		case 'F': return 'REAL';
+		case 'N': return 'NUMERIC';
+		default:
+			return $meta;
+		}
+	}
+	
+	
+	function AddColumnSQL($tabname, $flds)
+	{
+		$tabname = $this->TableName ($tabname);
+		$f = array();
+		list($lines,$pkey) = $this->_GenFields($flds);
+		$s = "ALTER TABLE $tabname $this->addCol";
+		foreach($lines as $v) {
+			$f[] = "\n $v";
+		}
+		$s .= implode(', ',$f);
+		$sql[] = $s;
+		return $sql;
+	}
+	
+	/*
+	function AlterColumnSQL($tabname, $flds)
+	{
+		$tabname = $this->TableName ($tabname);
+		$sql = array();
+		list($lines,$pkey) = $this->_GenFields($flds);
+		foreach($lines as $v) {
+			$sql[] = "ALTER TABLE $tabname $this->alterCol $v";
+		}
+
+		return $sql;
+	}
+	*/
+	
+	function DropColumnSQL($tabname, $flds)
+	{
+		$tabname = $this->TableName ($tabname);
+		if (!is_array($flds))
+			$flds = explode(',',$flds);
+		$f = array();
+		$s = 'ALTER TABLE ' . $tabname;
+		foreach($flds as $v) {
+			$f[] = "\n$this->dropCol ".$this->NameQuote($v);
+		}
+		$s .= implode(', ',$f);
+		$sql[] = $s;
+		return $sql;
+	}
+	
+	// return string must begin with space
+	function _CreateSuffix($fname,$ftype,$fnotnull,$fdefault,$fautoinc,$fconstraint)
+	{	
+		$suffix = '';
+		if (strlen($fdefault)) $suffix .= " DEFAULT $fdefault";
+		if ($fautoinc) $suffix .= ' IDENTITY(1,1)';
+		if ($fnotnull) $suffix .= ' NOT NULL';
+		else if ($suffix == '') $suffix .= ' NULL';
+		if ($fconstraint) $suffix .= ' '.$fconstraint;
+		return $suffix;
+	}
+	
+	/*
+CREATE TABLE 
+    [ database_name.[ owner ] . | owner. ] table_name 
+    ( { < column_definition > 
+        | column_name AS computed_column_expression 
+        | < table_constraint > ::= [ CONSTRAINT constraint_name ] }
+
+            | [ { PRIMARY KEY | UNIQUE } [ ,...n ] 
+    ) 
+
+[ ON { filegroup | DEFAULT } ] 
+[ TEXTIMAGE_ON { filegroup | DEFAULT } ] 
+
+< column_definition > ::= { column_name data_type } 
+    [ COLLATE < collation_name > ] 
+    [ [ DEFAULT constant_expression ] 
+        | [ IDENTITY [ ( seed , increment ) [ NOT FOR REPLICATION ] ] ]
+    ] 
+    [ ROWGUIDCOL] 
+    [ < column_constraint > ] [ ...n ] 
+
+< column_constraint > ::= [ CONSTRAINT constraint_name ] 
+    { [ NULL | NOT NULL ] 
+        | [ { PRIMARY KEY | UNIQUE } 
+            [ CLUSTERED | NONCLUSTERED ] 
+            [ WITH FILLFACTOR = fillfactor ] 
+            [ON {filegroup | DEFAULT} ] ] 
+        ] 
+        | [ [ FOREIGN KEY ] 
+            REFERENCES ref_table [ ( ref_column ) ] 
+            [ ON DELETE { CASCADE | NO ACTION } ] 
+            [ ON UPDATE { CASCADE | NO ACTION } ] 
+            [ NOT FOR REPLICATION ] 
+        ] 
+        | CHECK [ NOT FOR REPLICATION ] 
+        ( logical_expression ) 
+    } 
+
+< table_constraint > ::= [ CONSTRAINT constraint_name ] 
+    { [ { PRIMARY KEY | UNIQUE } 
+        [ CLUSTERED | NONCLUSTERED ] 
+        { ( column [ ASC | DESC ] [ ,...n ] ) } 
+        [ WITH FILLFACTOR = fillfactor ] 
+        [ ON { filegroup | DEFAULT } ] 
+    ] 
+    | FOREIGN KEY 
+        [ ( column [ ,...n ] ) ] 
+        REFERENCES ref_table [ ( ref_column [ ,...n ] ) ] 
+        [ ON DELETE { CASCADE | NO ACTION } ] 
+        [ ON UPDATE { CASCADE | NO ACTION } ] 
+        [ NOT FOR REPLICATION ] 
+    | CHECK [ NOT FOR REPLICATION ] 
+        ( search_conditions ) 
+    } 
+
+
+	*/
+	
+	/*
+	CREATE [ UNIQUE ] [ CLUSTERED | NONCLUSTERED ] INDEX index_name 
+    ON { table | view } ( column [ ASC | DESC ] [ ,...n ] ) 
+		[ WITH < index_option > [ ,...n] ] 
+		[ ON filegroup ]
+		< index_option > :: = 
+		    { PAD_INDEX | 
+		        FILLFACTOR = fillfactor | 
+		        IGNORE_DUP_KEY | 
+		        DROP_EXISTING | 
+		    STATISTICS_NORECOMPUTE | 
+		    SORT_IN_TEMPDB  
+		}
+*/
+	function _IndexSQL($idxname, $tabname, $flds, $idxoptions)
+	{
+		$sql = array();
+		
+		if ( isset($idxoptions['REPLACE']) || isset($idxoptions['DROP']) ) {
+			$sql[] = sprintf ($this->dropIndex, $idxname, $tabname);
+			if ( isset($idxoptions['DROP']) )
+				return $sql;
+		}
+		
+		if ( empty ($flds) ) {
+			return $sql;
+		}
+		
+		$unique = isset($idxoptions['UNIQUE']) ? ' UNIQUE' : '';
+		$clustered = isset($idxoptions['CLUSTERED']) ? ' CLUSTERED' : '';
+		
+		if ( is_array($flds) )
+			$flds = implode(', ',$flds);
+		$s = 'CREATE' . $unique . $clustered . ' INDEX ' . $idxname . ' ON ' . $tabname . ' (' . $flds . ')';
+		
+		if ( isset($idxoptions[$this->upperName]) )
+			$s .= $idxoptions[$this->upperName];
+		
+
+		$sql[] = $s;
+		
+		return $sql;
+	}
+	
+	
+	function _GetSize($ftype, $ty, $fsize, $fprec)
+	{
+		switch ($ftype) {
+		case 'INT':
+		case 'SMALLINT':
+		case 'TINYINT':
+		case 'BIGINT':
+			return $ftype;
+		}
+    	if ($ty == 'T') return $ftype;
+    	return parent::_GetSize($ftype, $ty, $fsize, $fprec);    
+
+	}
+}
+?>
Index: /Dev/trunk/rdfapi/util/adodb/datadict/datadict-mysql.inc.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/datadict/datadict-mysql.inc.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/datadict/datadict-mysql.inc.php	(revision 12)
@@ -0,0 +1,181 @@
+<?php
+
+/**
+  V4.94 23 Jan 2007  (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence.
+	
+  Set tabs to 4 for best viewing.
+ 
+*/
+
+// security - hide paths
+if (!defined('ADODB_DIR')) die();
+
+class ADODB2_mysql extends ADODB_DataDict {
+	var $databaseType = 'mysql';
+	var $alterCol = ' MODIFY COLUMN';
+	var $alterTableAddIndex = true;
+	var $dropTable = 'DROP TABLE IF EXISTS %s'; // requires mysql 3.22 or later
+	
+	var $dropIndex = 'DROP INDEX %s ON %s';
+	var $renameColumn = 'ALTER TABLE %s CHANGE COLUMN %s %s %s';	// needs column-definition!
+	
+	function MetaType($t,$len=-1,$fieldobj=false)
+	{
+		if (is_object($t)) {
+			$fieldobj = $t;
+			$t = $fieldobj->type;
+			$len = $fieldobj->max_length;
+		}
+		$is_serial = is_object($fieldobj) && $fieldobj->primary_key && $fieldobj->auto_increment;
+		
+		$len = -1; // mysql max_length is not accurate
+		switch (strtoupper($t)) {
+		case 'STRING': 
+		case 'CHAR':
+		case 'VARCHAR': 
+		case 'TINYBLOB': 
+		case 'TINYTEXT': 
+		case 'ENUM': 
+		case 'SET':
+			if ($len <= $this->blobSize) return 'C';
+			
+		case 'TEXT':
+		case 'LONGTEXT': 
+		case 'MEDIUMTEXT':
+			return 'X';
+			
+		// php_mysql extension always returns 'blob' even if 'text'
+		// so we have to check whether binary...
+		case 'IMAGE':
+		case 'LONGBLOB': 
+		case 'BLOB':
+		case 'MEDIUMBLOB':
+			return !empty($fieldobj->binary) ? 'B' : 'X';
+			
+		case 'YEAR':
+		case 'DATE': return 'D';
+		
+		case 'TIME':
+		case 'DATETIME':
+		case 'TIMESTAMP': return 'T';
+		
+		case 'FLOAT':
+		case 'DOUBLE':
+			return 'F';
+			
+		case 'INT': 
+		case 'INTEGER': return $is_serial ? 'R' : 'I';
+		case 'TINYINT': return $is_serial ? 'R' : 'I1';
+		case 'SMALLINT': return $is_serial ? 'R' : 'I2';
+		case 'MEDIUMINT': return $is_serial ? 'R' : 'I4';
+		case 'BIGINT':  return $is_serial ? 'R' : 'I8';
+		default: return 'N';
+		}
+	}
+
+	function ActualType($meta)
+	{
+		switch(strtoupper($meta)) {
+		case 'C': return 'VARCHAR';
+		case 'XL':return 'LONGTEXT';
+		case 'X': return 'TEXT';
+		
+		case 'C2': return 'VARCHAR';
+		case 'X2': return 'LONGTEXT';
+		
+		case 'B': return 'LONGBLOB';
+			
+		case 'D': return 'DATE';
+		case 'T': return 'DATETIME';
+		case 'L': return 'TINYINT';
+		
+		case 'R':
+		case 'I4':
+		case 'I': return 'INTEGER';
+		case 'I1': return 'TINYINT';
+		case 'I2': return 'SMALLINT';
+		case 'I8': return 'BIGINT';
+		
+		case 'F': return 'DOUBLE';
+		case 'N': return 'NUMERIC';
+		default:
+			return $meta;
+		}
+	}
+	
+	// return string must begin with space
+	function _CreateSuffix($fname,$ftype,$fnotnull,$fdefault,$fautoinc,$fconstraint,$funsigned)
+	{	
+		$suffix = '';
+		if ($funsigned) $suffix .= ' UNSIGNED';
+		if ($fnotnull) $suffix .= ' NOT NULL';
+		if (strlen($fdefault)) $suffix .= " DEFAULT $fdefault";
+		if ($fautoinc) $suffix .= ' AUTO_INCREMENT';
+		if ($fconstraint) $suffix .= ' '.$fconstraint;
+		return $suffix;
+	}
+	
+	/*
+	CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name [(create_definition,...)]
+		[table_options] [select_statement]
+		create_definition:
+		col_name type [NOT NULL | NULL] [DEFAULT default_value] [AUTO_INCREMENT]
+		[PRIMARY KEY] [reference_definition]
+		or PRIMARY KEY (index_col_name,...)
+		or KEY [index_name] (index_col_name,...)
+		or INDEX [index_name] (index_col_name,...)
+		or UNIQUE [INDEX] [index_name] (index_col_name,...)
+		or FULLTEXT [INDEX] [index_name] (index_col_name,...)
+		or [CONSTRAINT symbol] FOREIGN KEY [index_name] (index_col_name,...)
+		[reference_definition]
+		or CHECK (expr)
+	*/
+	
+	/*
+	CREATE [UNIQUE|FULLTEXT] INDEX index_name
+		ON tbl_name (col_name[(length)],... )
+	*/
+	
+	function _IndexSQL($idxname, $tabname, $flds, $idxoptions)
+	{
+		$sql = array();
+		
+		if ( isset($idxoptions['REPLACE']) || isset($idxoptions['DROP']) ) {
+			if ($this->alterTableAddIndex) $sql[] = "ALTER TABLE $tabname DROP INDEX $idxname";
+			else $sql[] = sprintf($this->dropIndex, $idxname, $tabname);
+
+			if ( isset($idxoptions['DROP']) )
+				return $sql;
+		}
+		
+		if ( empty ($flds) ) {
+			return $sql;
+		}
+		
+		if (isset($idxoptions['FULLTEXT'])) {
+			$unique = ' FULLTEXT';
+		} elseif (isset($idxoptions['UNIQUE'])) {
+			$unique = ' UNIQUE';
+		} else {
+			$unique = '';
+		}
+		
+		if ( is_array($flds) ) $flds = implode(', ',$flds);
+		
+		if ($this->alterTableAddIndex) $s = "ALTER TABLE $tabname ADD $unique INDEX $idxname ";
+		else $s = 'CREATE' . $unique . ' INDEX ' . $idxname . ' ON ' . $tabname;
+		
+		$s .= ' (' . $flds . ')';
+		
+		if ( isset($idxoptions[$this->upperName]) )
+			$s .= $idxoptions[$this->upperName];
+		
+		$sql[] = $s;
+		
+		return $sql;
+	}
+}
+?>
Index: /Dev/trunk/rdfapi/util/adodb/datadict/datadict-oci8.inc.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/datadict/datadict-oci8.inc.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/datadict/datadict-oci8.inc.php	(revision 12)
@@ -0,0 +1,290 @@
+<?php
+
+/**
+  V4.94 23 Jan 2007  (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence.
+	
+  Set tabs to 4 for best viewing.
+ 
+*/
+
+// security - hide paths
+if (!defined('ADODB_DIR')) die();
+
+class ADODB2_oci8 extends ADODB_DataDict {
+	
+	var $databaseType = 'oci8';
+	var $seqField = false;
+	var $seqPrefix = 'SEQ_';
+	var $dropTable = "DROP TABLE %s CASCADE CONSTRAINTS";
+	var $trigPrefix = 'TRIG_';
+	var $alterCol = ' MODIFY ';
+	var $typeX = 'VARCHAR(4000)';
+	var $typeXL = 'CLOB';
+	
+	function MetaType($t,$len=-1)
+	{
+		if (is_object($t)) {
+			$fieldobj = $t;
+			$t = $fieldobj->type;
+			$len = $fieldobj->max_length;
+		}
+		switch (strtoupper($t)) {
+	 	case 'VARCHAR':
+	 	case 'VARCHAR2':
+		case 'CHAR':
+		case 'VARBINARY':
+		case 'BINARY':
+			if (isset($this) && $len <= $this->blobSize) return 'C';
+			return 'X';
+		
+		case 'NCHAR':
+		case 'NVARCHAR2':
+		case 'NVARCHAR':
+			if (isset($this) && $len <= $this->blobSize) return 'C2';
+			return 'X2';
+			
+		case 'NCLOB':
+		case 'CLOB':
+			return 'XL';
+		
+		case 'LONG RAW':
+		case 'LONG VARBINARY':
+		case 'BLOB':
+			return 'B';
+		
+		case 'DATE': 
+			return 'T';
+		
+		case 'INT': 
+		case 'SMALLINT':
+		case 'INTEGER': 
+			return 'I';
+			
+		default:
+			return 'N';
+		}
+	}
+	
+ 	function ActualType($meta)
+	{
+		switch($meta) {
+		case 'C': return 'VARCHAR';
+		case 'X': return $this->typeX;
+		case 'XL': return $this->typeXL;
+		
+		case 'C2': return 'NVARCHAR2';
+		case 'X2': return 'NVARCHAR2(4000)';
+		
+		case 'B': return 'BLOB';
+			
+		case 'D': 
+		case 'T': return 'DATE';
+		case 'L': return 'DECIMAL(1)';
+		case 'I1': return 'DECIMAL(3)';
+		case 'I2': return 'DECIMAL(5)';
+		case 'I':
+		case 'I4': return 'DECIMAL(10)';
+		
+		case 'I8': return 'DECIMAL(20)';
+		case 'F': return 'DECIMAL';
+		case 'N': return 'DECIMAL';
+		default:
+			return $meta;
+		}	
+	}
+	
+	function CreateDatabase($dbname, $options=false)
+	{
+		$options = $this->_Options($options);
+		$password = isset($options['PASSWORD']) ? $options['PASSWORD'] : 'tiger';
+		$tablespace = isset($options["TABLESPACE"]) ? " DEFAULT TABLESPACE ".$options["TABLESPACE"] : '';
+		$sql[] = "CREATE USER ".$dbname." IDENTIFIED BY ".$password.$tablespace;
+		$sql[] = "GRANT CREATE SESSION, CREATE TABLE,UNLIMITED TABLESPACE,CREATE SEQUENCE TO $dbname";
+		
+		return $sql;
+	}
+	
+	function AddColumnSQL($tabname, $flds)
+	{
+		$f = array();
+		list($lines,$pkey) = $this->_GenFields($flds);
+		$s = "ALTER TABLE $tabname ADD (";
+		foreach($lines as $v) {
+			$f[] = "\n $v";
+		}
+		
+		$s .= implode(', ',$f).')';
+		$sql[] = $s;
+		return $sql;
+	}
+	
+	function AlterColumnSQL($tabname, $flds)
+	{
+		$f = array();
+		list($lines,$pkey) = $this->_GenFields($flds);
+		$s = "ALTER TABLE $tabname MODIFY(";
+		foreach($lines as $v) {
+			$f[] = "\n $v";
+		}
+		$s .= implode(', ',$f).')';
+		$sql[] = $s;
+		return $sql;
+	}
+	
+	function DropColumnSQL($tabname, $flds)
+	{
+		if (!is_array($flds)) $flds = explode(',',$flds);
+		foreach ($flds as $k => $v) $flds[$k] = $this->NameQuote($v);
+		
+		$sql = array();
+		$s = "ALTER TABLE $tabname DROP(";
+		$s .= implode(', ',$flds).') CASCADE CONSTRAINTS';
+		$sql[] = $s;
+		return $sql;
+	}
+	
+	function _DropAutoIncrement($t)
+	{
+		if (strpos($t,'.') !== false) {
+			$tarr = explode('.',$t);
+			return "drop sequence ".$tarr[0].".seq_".$tarr[1];
+		}
+		return "drop sequence seq_".$t;
+	}
+	
+	// return string must begin with space
+	function _CreateSuffix($fname,$ftype,$fnotnull,$fdefault,$fautoinc,$fconstraint,$funsigned)
+	{
+		$suffix = '';
+		
+		if ($fdefault == "''" && $fnotnull) {// this is null in oracle
+			$fnotnull = false;
+			if ($this->debug) ADOConnection::outp("NOT NULL and DEFAULT='' illegal in Oracle");
+		}
+		
+		if (strlen($fdefault)) $suffix .= " DEFAULT $fdefault";
+		if ($fnotnull) $suffix .= ' NOT NULL';
+		
+		if ($fautoinc) $this->seqField = $fname;
+		if ($fconstraint) $suffix .= ' '.$fconstraint;
+		
+		return $suffix;
+	}
+	
+/*
+CREATE or replace TRIGGER jaddress_insert
+before insert on jaddress
+for each row
+begin
+select seqaddress.nextval into :new.A_ID from dual;
+end;
+*/
+	function _Triggers($tabname,$tableoptions)
+	{
+		if (!$this->seqField) return array();
+		
+		if ($this->schema) {
+			$t = strpos($tabname,'.');
+			if ($t !== false) $tab = substr($tabname,$t+1);
+			else $tab = $tabname;
+			$seqname = $this->schema.'.'.$this->seqPrefix.$tab;
+			$trigname = $this->schema.'.'.$this->trigPrefix.$this->seqPrefix.$tab;
+		} else {
+			$seqname = $this->seqPrefix.$tabname;
+			$trigname = $this->trigPrefix.$seqname;
+		}
+		
+		if (strlen($seqname) > 30) {
+			$seqname = $this->seqPrefix.uniqid('');
+		} // end if
+		if (strlen($trigname) > 30) {
+			$trigname = $this->trigPrefix.uniqid('');
+		} // end if
+
+		if (isset($tableoptions['REPLACE'])) $sql[] = "DROP SEQUENCE $seqname";
+		$seqCache = '';
+		if (isset($tableoptions['SEQUENCE_CACHE'])){$seqCache = $tableoptions['SEQUENCE_CACHE'];}
+		$seqIncr = '';
+		if (isset($tableoptions['SEQUENCE_INCREMENT'])){$seqIncr = ' INCREMENT BY '.$tableoptions['SEQUENCE_INCREMENT'];}
+		$seqStart = '';
+		if (isset($tableoptions['SEQUENCE_START'])){$seqIncr = ' START WITH '.$tableoptions['SEQUENCE_START'];}
+		$sql[] = "CREATE SEQUENCE $seqname $seqStart $seqIncr $seqCache";
+		$sql[] = "CREATE OR REPLACE TRIGGER $trigname BEFORE insert ON $tabname FOR EACH ROW WHEN (NEW.$this->seqField IS NULL OR NEW.$this->seqField = 0) BEGIN select $seqname.nextval into :new.$this->seqField from dual; END;";
+		
+		$this->seqField = false;
+		return $sql;
+	}
+	
+	/*
+	CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name [(create_definition,...)]
+		[table_options] [select_statement]
+		create_definition:
+		col_name type [NOT NULL | NULL] [DEFAULT default_value] [AUTO_INCREMENT]
+		[PRIMARY KEY] [reference_definition]
+		or PRIMARY KEY (index_col_name,...)
+		or KEY [index_name] (index_col_name,...)
+		or INDEX [index_name] (index_col_name,...)
+		or UNIQUE [INDEX] [index_name] (index_col_name,...)
+		or FULLTEXT [INDEX] [index_name] (index_col_name,...)
+		or [CONSTRAINT symbol] FOREIGN KEY [index_name] (index_col_name,...)
+		[reference_definition]
+		or CHECK (expr)
+	*/
+	
+
+	
+	function _IndexSQL($idxname, $tabname, $flds,$idxoptions)
+	{
+		$sql = array();
+		
+		if ( isset($idxoptions['REPLACE']) || isset($idxoptions['DROP']) ) {
+			$sql[] = sprintf ($this->dropIndex, $idxname, $tabname);
+			if ( isset($idxoptions['DROP']) )
+				return $sql;
+		}
+		
+		if ( empty ($flds) ) {
+			return $sql;
+		}
+		
+		if (isset($idxoptions['BITMAP'])) {
+			$unique = ' BITMAP'; 
+		} elseif (isset($idxoptions['UNIQUE'])) {
+			$unique = ' UNIQUE';
+		} else {
+			$unique = '';
+		}
+		
+		if ( is_array($flds) )
+			$flds = implode(', ',$flds);
+		$s = 'CREATE' . $unique . ' INDEX ' . $idxname . ' ON ' . $tabname . ' (' . $flds . ')';
+		
+		if ( isset($idxoptions[$this->upperName]) )
+			$s .= $idxoptions[$this->upperName];
+		
+		if (isset($idxoptions['oci8']))
+			$s .= $idxoptions['oci8'];
+		
+
+		$sql[] = $s;
+		
+		return $sql;
+	}
+	
+	function GetCommentSQL($table,$col)
+	{
+		$table = $this->connection->qstr($table);
+		$col = $this->connection->qstr($col);	
+		return "select comments from USER_COL_COMMENTS where TABLE_NAME=$table and COLUMN_NAME=$col";
+	}
+	
+	function SetCommentSQL($table,$col,$cmt)
+	{
+		$cmt = $this->connection->qstr($cmt);
+		return  "COMMENT ON COLUMN $table.$col IS $cmt";
+	}
+}
+?>
Index: /Dev/trunk/rdfapi/util/adodb/datadict/datadict-postgres.inc.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/datadict/datadict-postgres.inc.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/datadict/datadict-postgres.inc.php	(revision 12)
@@ -0,0 +1,371 @@
+<?php
+
+/**
+  V4.94 23 Jan 2007  (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence.
+	
+  Set tabs to 4 for best viewing.
+ 
+*/
+
+// security - hide paths
+if (!defined('ADODB_DIR')) die();
+
+class ADODB2_postgres extends ADODB_DataDict {
+	
+	var $databaseType = 'postgres';
+	var $seqField = false;
+	var $seqPrefix = 'SEQ_';
+	var $addCol = ' ADD COLUMN';
+	var $quote = '"';
+	var $renameTable = 'ALTER TABLE %s RENAME TO %s'; // at least since 7.1
+	var $dropTable = 'DROP TABLE %s CASCADE';
+	
+	function MetaType($t,$len=-1,$fieldobj=false)
+	{
+		if (is_object($t)) {
+			$fieldobj = $t;
+			$t = $fieldobj->type;
+			$len = $fieldobj->max_length;
+		}
+		$is_serial = is_object($fieldobj) && $fieldobj->primary_key && $fieldobj->unique && 
+			$fieldobj->has_default && substr($fieldobj->default_value,0,8) == 'nextval(';
+		
+		switch (strtoupper($t)) {
+			case 'INTERVAL':
+			case 'CHAR':
+			case 'CHARACTER':
+			case 'VARCHAR':
+			case 'NAME':
+	   		case 'BPCHAR':
+				if ($len <= $this->blobSize) return 'C';
+			
+			case 'TEXT':
+				return 'X';
+	
+			case 'IMAGE': // user defined type
+			case 'BLOB': // user defined type
+			case 'BIT':	// This is a bit string, not a single bit, so don't return 'L'
+			case 'VARBIT':
+			case 'BYTEA':
+				return 'B';
+			
+			case 'BOOL':
+			case 'BOOLEAN':
+				return 'L';
+			
+			case 'DATE':
+				return 'D';
+			
+			case 'TIME':
+			case 'DATETIME':
+			case 'TIMESTAMP':
+			case 'TIMESTAMPTZ':
+				return 'T';
+			
+			case 'INTEGER': return !$is_serial ? 'I' : 'R';
+			case 'SMALLINT': 
+			case 'INT2': return !$is_serial ? 'I2' : 'R';
+			case 'INT4': return !$is_serial ? 'I4' : 'R';
+			case 'BIGINT': 
+			case 'INT8': return !$is_serial ? 'I8' : 'R';
+				
+			case 'OID':
+			case 'SERIAL':
+				return 'R';
+			
+			case 'FLOAT4':
+			case 'FLOAT8':
+			case 'DOUBLE PRECISION':
+			case 'REAL':
+				return 'F';
+				
+			 default:
+			 	return 'N';
+		}
+	}
+ 	
+ 	function ActualType($meta)
+	{
+		switch($meta) {
+		case 'C': return 'VARCHAR';
+		case 'XL':
+		case 'X': return 'TEXT';
+		
+		case 'C2': return 'VARCHAR';
+		case 'X2': return 'TEXT';
+		
+		case 'B': return 'BYTEA';
+			
+		case 'D': return 'DATE';
+		case 'T': return 'TIMESTAMP';
+		
+		case 'L': return 'BOOLEAN';
+		case 'I': return 'INTEGER';
+		case 'I1': return 'SMALLINT';
+		case 'I2': return 'INT2';
+		case 'I4': return 'INT4';
+		case 'I8': return 'INT8';
+		
+		case 'F': return 'FLOAT8';
+		case 'N': return 'NUMERIC';
+		default:
+			return $meta;
+		}
+	}
+	
+	/**
+	 * Adding a new Column 
+	 *
+	 * reimplementation of the default function as postgres does NOT allow to set the default in the same statement
+	 *
+	 * @param string $tabname table-name
+	 * @param string $flds column-names and types for the changed columns
+	 * @return array with SQL strings
+	 */
+	function AddColumnSQL($tabname, $flds)
+	{
+		$tabname = $this->TableName ($tabname);
+		$sql = array();
+		list($lines,$pkey) = $this->_GenFields($flds);
+		$alter = 'ALTER TABLE ' . $tabname . $this->addCol . ' ';
+		foreach($lines as $v) {
+			if (($not_null = preg_match('/NOT NULL/i',$v))) {
+				$v = preg_replace('/NOT NULL/i','',$v);
+			}
+			if (preg_match('/^([^ ]+) .*DEFAULT ([^ ]+)/',$v,$matches)) {
+				list(,$colname,$default) = $matches;
+				$sql[] = $alter . str_replace('DEFAULT '.$default,'',$v);
+				$sql[] = 'UPDATE '.$tabname.' SET '.$colname.'='.$default;
+				$sql[] = 'ALTER TABLE '.$tabname.' ALTER COLUMN '.$colname.' SET DEFAULT ' . $default;
+			} else {				
+				$sql[] = $alter . $v;
+			}
+			if ($not_null) {
+				list($colname) = explode(' ',$v);
+				$sql[] = 'ALTER TABLE '.$tabname.' ALTER COLUMN '.$colname.' SET NOT NULL';
+			}
+		}
+		return $sql;
+	}
+	
+	/**
+	 * Change the definition of one column
+	 *
+	 * Postgres can't do that on it's own, you need to supply the complete defintion of the new table,
+	 * to allow, recreating the table and copying the content over to the new table
+	 * @param string $tabname table-name
+	 * @param string $flds column-name and type for the changed column
+	 * @param string $tableflds complete defintion of the new table, eg. for postgres, default ''
+	 * @param array/ $tableoptions options for the new table see CreateTableSQL, default ''
+	 * @return array with SQL strings
+	 */
+	function AlterColumnSQL($tabname, $flds, $tableflds='',$tableoptions='')
+	{
+		if (!$tableflds) {
+			if ($this->debug) ADOConnection::outp("AlterColumnSQL needs a complete table-definiton for PostgreSQL");
+			return array();
+		}
+		return $this->_recreate_copy_table($tabname,False,$tableflds,$tableoptions);
+	}
+	
+	/**
+	 * Drop one column
+	 *
+	 * Postgres < 7.3 can't do that on it's own, you need to supply the complete defintion of the new table,
+	 * to allow, recreating the table and copying the content over to the new table
+	 * @param string $tabname table-name
+	 * @param string $flds column-name and type for the changed column
+	 * @param string $tableflds complete defintion of the new table, eg. for postgres, default ''
+	 * @param array/ $tableoptions options for the new table see CreateTableSQL, default ''
+	 * @return array with SQL strings
+	 */
+	function DropColumnSQL($tabname, $flds, $tableflds='',$tableoptions='')
+	{
+		$has_drop_column = 7.3 <= (float) @$this->serverInfo['version'];
+		if (!$has_drop_column && !$tableflds) {
+			if ($this->debug) ADOConnection::outp("DropColumnSQL needs complete table-definiton for PostgreSQL < 7.3");
+		return array();
+	}
+		if ($has_drop_column) {
+			return ADODB_DataDict::DropColumnSQL($tabname, $flds);
+		}
+		return $this->_recreate_copy_table($tabname,$flds,$tableflds,$tableoptions);
+	}
+	
+	/**
+	 * Save the content into a temp. table, drop and recreate the original table and copy the content back in
+	 *
+	 * We also take care to set the values of the sequenz and recreate the indexes.
+	 * All this is done in a transaction, to not loose the content of the table, if something went wrong!
+	 * @internal
+	 * @param string $tabname table-name
+	 * @param string $dropflds column-names to drop
+	 * @param string $tableflds complete defintion of the new table, eg. for postgres
+	 * @param array/string $tableoptions options for the new table see CreateTableSQL, default ''
+	 * @return array with SQL strings
+	 */
+	function _recreate_copy_table($tabname,$dropflds,$tableflds,$tableoptions='')
+	{
+		if ($dropflds && !is_array($dropflds)) $dropflds = explode(',',$dropflds);
+		$copyflds = array();
+		foreach($this->MetaColumns($tabname) as $fld) {
+			if (!$dropflds || !in_array($fld->name,$dropflds)) {
+				// we need to explicit convert varchar to a number to be able to do an AlterColumn of a char column to a nummeric one
+				if (preg_match('/'.$fld->name.' (I|I2|I4|I8|N|F)/i',$tableflds,$matches) && 
+					in_array($fld->type,array('varchar','char','text','bytea'))) {
+					$copyflds[] = "to_number($fld->name,'S9999999999999D99')";
+				} else {
+					$copyflds[] = $fld->name;
+				}
+				// identify the sequence name and the fld its on
+				if ($fld->primary_key && $fld->has_default && 
+					preg_match("/nextval\('([^']+)'::text\)/",$fld->default_value,$matches)) {
+					$seq_name = $matches[1];
+					$seq_fld = $fld->name;
+				}
+			}
+		}
+		$copyflds = implode(', ',$copyflds);
+		
+		$tempname = $tabname.'_tmp';
+		$aSql[] = 'BEGIN';		// we use a transaction, to make sure not to loose the content of the table
+		$aSql[] = "SELECT * INTO TEMPORARY TABLE $tempname FROM $tabname";
+		$aSql = array_merge($aSql,$this->DropTableSQL($tabname));
+		$aSql = array_merge($aSql,$this->CreateTableSQL($tabname,$tableflds,$tableoptions));
+		$aSql[] = "INSERT INTO $tabname SELECT $copyflds FROM $tempname";
+		if ($seq_name && $seq_fld) {	// if we have a sequence we need to set it again
+			$seq_name = $tabname.'_'.$seq_fld.'_seq';	// has to be the name of the new implicit sequence
+			$aSql[] = "SELECT setval('$seq_name',MAX($seq_fld)) FROM $tabname";
+		}
+		$aSql[] = "DROP TABLE $tempname";
+		// recreate the indexes, if they not contain one of the droped columns
+		foreach($this->MetaIndexes($tabname) as $idx_name => $idx_data)
+		{
+			if (substr($idx_name,-5) != '_pkey' && (!$dropflds || !count(array_intersect($dropflds,$idx_data['columns'])))) {
+				$aSql = array_merge($aSql,$this->CreateIndexSQL($idx_name,$tabname,$idx_data['columns'],
+					$idx_data['unique'] ? array('UNIQUE') : False));
+			}
+		}
+		$aSql[] = 'COMMIT';
+		return $aSql;
+	}
+	
+	function DropTableSQL($tabname)
+	{
+		$sql = ADODB_DataDict::DropTableSQL($tabname);
+		
+		$drop_seq = $this->_DropAutoIncrement($tabname);
+		if ($drop_seq) $sql[] = $drop_seq;
+		
+		return $sql;
+	}
+
+	// return string must begin with space
+	function _CreateSuffix($fname, &$ftype, $fnotnull,$fdefault,$fautoinc,$fconstraint)
+	{
+		if ($fautoinc) {
+			$ftype = 'SERIAL';
+			return '';
+		}
+		$suffix = '';
+		if (strlen($fdefault)) $suffix .= " DEFAULT $fdefault";
+		if ($fnotnull) $suffix .= ' NOT NULL';
+		if ($fconstraint) $suffix .= ' '.$fconstraint;
+		return $suffix;
+	}
+	
+	// search for a sequece for the given table (asumes the seqence-name contains the table-name!)
+	// if yes return sql to drop it
+	// this is still necessary if postgres < 7.3 or the SERIAL was created on an earlier version!!!
+	function _DropAutoIncrement($tabname)
+	{
+		$tabname = $this->connection->quote('%'.$tabname.'%');
+
+		$seq = $this->connection->GetOne("SELECT relname FROM pg_class WHERE NOT relname ~ 'pg_.*' AND relname LIKE $tabname AND relkind='S'");
+
+		// check if a tables depends on the sequenz and it therefor cant and dont need to be droped separatly
+		if (!$seq || $this->connection->GetOne("SELECT relname FROM pg_class JOIN pg_depend ON pg_class.relfilenode=pg_depend.objid WHERE relname='$seq' AND relkind='S' AND deptype='i'")) {
+			return False;
+		}
+		return "DROP SEQUENCE ".$seq;
+	}
+	
+	/*
+	CREATE [ [ LOCAL ] { TEMPORARY | TEMP } ] TABLE table_name (
+	{ column_name data_type [ DEFAULT default_expr ] [ column_constraint [, ... ] ]
+	| table_constraint } [, ... ]
+	)
+	[ INHERITS ( parent_table [, ... ] ) ]
+	[ WITH OIDS | WITHOUT OIDS ]
+	where column_constraint is:
+	[ CONSTRAINT constraint_name ]
+	{ NOT NULL | NULL | UNIQUE | PRIMARY KEY |
+	CHECK (expression) |
+	REFERENCES reftable [ ( refcolumn ) ] [ MATCH FULL | MATCH PARTIAL ]
+	[ ON DELETE action ] [ ON UPDATE action ] }
+	[ DEFERRABLE | NOT DEFERRABLE ] [ INITIALLY DEFERRED | INITIALLY IMMEDIATE ]
+	and table_constraint is:
+	[ CONSTRAINT constraint_name ]
+	{ UNIQUE ( column_name [, ... ] ) |
+	PRIMARY KEY ( column_name [, ... ] ) |
+	CHECK ( expression ) |
+	FOREIGN KEY ( column_name [, ... ] ) REFERENCES reftable [ ( refcolumn [, ... ] ) ]
+	[ MATCH FULL | MATCH PARTIAL ] [ ON DELETE action ] [ ON UPDATE action ] }
+	[ DEFERRABLE | NOT DEFERRABLE ] [ INITIALLY DEFERRED | INITIALLY IMMEDIATE ]
+	*/
+	
+	
+	/*
+	CREATE [ UNIQUE ] INDEX index_name ON table
+[ USING acc_method ] ( column [ ops_name ] [, ...] )
+[ WHERE predicate ]
+CREATE [ UNIQUE ] INDEX index_name ON table
+[ USING acc_method ] ( func_name( column [, ... ]) [ ops_name ] )
+[ WHERE predicate ]
+	*/
+	function _IndexSQL($idxname, $tabname, $flds, $idxoptions)
+	{
+		$sql = array();
+		
+		if ( isset($idxoptions['REPLACE']) || isset($idxoptions['DROP']) ) {
+			$sql[] = sprintf ($this->dropIndex, $idxname, $tabname);
+			if ( isset($idxoptions['DROP']) )
+				return $sql;
+		}
+		
+		if ( empty ($flds) ) {
+			return $sql;
+		}
+		
+		$unique = isset($idxoptions['UNIQUE']) ? ' UNIQUE' : '';
+		
+		$s = 'CREATE' . $unique . ' INDEX ' . $idxname . ' ON ' . $tabname . ' ';
+		
+		if (isset($idxoptions['HASH']))
+			$s .= 'USING HASH ';
+		
+		if ( isset($idxoptions[$this->upperName]) )
+			$s .= $idxoptions[$this->upperName];
+		
+		if ( is_array($flds) )
+			$flds = implode(', ',$flds);
+		$s .= '(' . $flds . ')';
+		$sql[] = $s;
+		
+		return $sql;
+	}
+	
+	function _GetSize($ftype, $ty, $fsize, $fprec)
+	{
+		if (strlen($fsize) && $ty != 'X' && $ty != 'B' && $ty  != 'I' && strpos($ftype,'(') === false) {
+			$ftype .= "(".$fsize;
+			if (strlen($fprec)) $ftype .= ",".$fprec;
+			$ftype .= ')';
+		}
+		return $ftype;
+	}
+}
+?>
Index: /Dev/trunk/rdfapi/util/adodb/datadict/datadict-sapdb.inc.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/datadict/datadict-sapdb.inc.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/datadict/datadict-sapdb.inc.php	(revision 12)
@@ -0,0 +1,121 @@
+<?php
+
+/**
+  V4.50 6 July 2004  (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence.
+	
+  Set tabs to 4 for best viewing.
+  
+  Modified from datadict-generic.inc.php for sapdb by RalfBecker-AT-outdoor-training.de
+*/
+
+// security - hide paths
+if (!defined('ADODB_DIR')) die();
+
+class ADODB2_sapdb extends ADODB_DataDict {
+	
+	var $databaseType = 'sapdb';
+	var $seqField = false;	
+	var $renameColumn = 'RENAME COLUMN %s.%s TO %s';
+ 	
+ 	function ActualType($meta)
+	{
+		switch($meta) {
+		case 'C': return 'VARCHAR';
+		case 'XL':
+		case 'X': return 'LONG';
+		
+		case 'C2': return 'VARCHAR UNICODE';
+		case 'X2': return 'LONG UNICODE';
+		
+		case 'B': return 'LONG';
+			
+		case 'D': return 'DATE';
+		case 'T': return 'TIMESTAMP';
+		
+		case 'L': return 'BOOLEAN';
+		case 'I': return 'INTEGER';
+		case 'I1': return 'FIXED(3)';
+		case 'I2': return 'SMALLINT';
+		case 'I4': return 'INTEGER';
+		case 'I8': return 'FIXED(20)';
+		
+		case 'F': return 'FLOAT(38)';
+		case 'N': return 'FIXED';
+		default:
+			return $meta;
+		}
+	}
+	
+	function MetaType($t,$len=-1,$fieldobj=false)
+	{
+		if (is_object($t)) {
+			$fieldobj = $t;
+			$t = $fieldobj->type;
+			$len = $fieldobj->max_length;
+		}
+		static $maxdb_type2adodb = array(
+			'VARCHAR'	=> 'C',
+			'CHARACTER'	=> 'C',
+			'LONG'		=> 'X',		// no way to differ between 'X' and 'B' :-(
+			'DATE'		=> 'D',
+			'TIMESTAMP'	=> 'T',
+			'BOOLEAN'	=> 'L',
+			'INTEGER'	=> 'I4',
+			'SMALLINT'	=> 'I2',
+			'FLOAT'		=> 'F',
+			'FIXED'		=> 'N',
+		);
+		$type = isset($maxdb_type2adodb[$t]) ? $maxdb_type2adodb[$t] : 'C';
+
+		// convert integer-types simulated with fixed back to integer
+		if ($t == 'FIXED' && !$fieldobj->scale && ($len == 20 || $len == 3)) {
+			$type = $len == 20 ? 'I8' : 'I1';
+		}
+		if ($fieldobj->auto_increment) $type = 'R';
+
+		return $type;
+	}
+	
+	// return string must begin with space
+	function _CreateSuffix($fname,$ftype,$fnotnull,$fdefault,$fautoinc,$fconstraint,$funsigned)
+	{	
+		$suffix = '';
+		if ($funsigned) $suffix .= ' UNSIGNED';
+		if ($fnotnull) $suffix .= ' NOT NULL';
+		if ($fautoinc) $suffix .= ' DEFAULT SERIAL';
+		elseif (strlen($fdefault)) $suffix .= " DEFAULT $fdefault";
+		if ($fconstraint) $suffix .= ' '.$fconstraint;
+		return $suffix;
+	}
+
+	function AddColumnSQL($tabname, $flds)
+	{
+		$tabname = $this->TableName ($tabname);
+		$sql = array();
+		list($lines,$pkey) = $this->_GenFields($flds);
+		return array( 'ALTER TABLE ' . $tabname . ' ADD (' . implode(', ',$lines) . ')' );
+	}
+	
+	function AlterColumnSQL($tabname, $flds)
+	{
+		$tabname = $this->TableName ($tabname);
+		$sql = array();
+		list($lines,$pkey) = $this->_GenFields($flds);
+		return array( 'ALTER TABLE ' . $tabname . ' MODIFY (' . implode(', ',$lines) . ')' );
+	}
+
+	function DropColumnSQL($tabname, $flds)
+	{
+		$tabname = $this->TableName ($tabname);
+		if (!is_array($flds)) $flds = explode(',',$flds);
+		foreach($flds as $k => $v) {
+			$flds[$k] = $this->NameQuote($v);
+		}
+		return array( 'ALTER TABLE ' . $tabname . ' DROP (' . implode(', ',$flds) . ')' );
+	}	
+}
+
+?>
Index: /Dev/trunk/rdfapi/util/adodb/datadict/datadict-sybase.inc.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/datadict/datadict-sybase.inc.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/datadict/datadict-sybase.inc.php	(revision 12)
@@ -0,0 +1,228 @@
+<?php
+
+/**
+  V4.94 23 Jan 2007  (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence.
+	
+  Set tabs to 4 for best viewing.
+ 
+*/
+
+// security - hide paths
+if (!defined('ADODB_DIR')) die();
+
+class ADODB2_sybase extends ADODB_DataDict {
+	var $databaseType = 'sybase';
+	
+	var $dropIndex = 'DROP INDEX %2$s.%1$s';
+	
+	function MetaType($t,$len=-1,$fieldobj=false)
+	{
+		if (is_object($t)) {
+			$fieldobj = $t;
+			$t = $fieldobj->type;
+			$len = $fieldobj->max_length;
+		}
+		
+		$len = -1; // mysql max_length is not accurate
+		switch (strtoupper($t)) {
+
+		case 'INT': 
+		case 'INTEGER': return  'I';
+		case 'BIT':
+		case 'TINYINT': return  'I1';
+		case 'SMALLINT': return 'I2';
+		case 'BIGINT':  return  'I8';
+		
+		case 'REAL':
+		case 'FLOAT': return 'F';
+		default: return parent::MetaType($t,$len,$fieldobj);
+		}
+	}
+	
+	function ActualType($meta)
+	{
+		switch(strtoupper($meta)) {
+		case 'C': return 'VARCHAR';
+		case 'XL':
+		case 'X': return 'TEXT';
+		
+		case 'C2': return 'NVARCHAR';
+		case 'X2': return 'NTEXT';
+		
+		case 'B': return 'IMAGE';
+			
+		case 'D': return 'DATETIME';
+		case 'T': return 'DATETIME';
+		case 'L': return 'BIT';
+		
+		case 'I': return 'INT'; 
+		case 'I1': return 'TINYINT';
+		case 'I2': return 'SMALLINT';
+		case 'I4': return 'INT';
+		case 'I8': return 'BIGINT';
+		
+		case 'F': return 'REAL';
+		case 'N': return 'NUMERIC';
+		default:
+			return $meta;
+		}
+	}
+	
+	
+	function AddColumnSQL($tabname, $flds)
+	{
+		$tabname = $this->TableName ($tabname);
+		$f = array();
+		list($lines,$pkey) = $this->_GenFields($flds);
+		$s = "ALTER TABLE $tabname $this->addCol";
+		foreach($lines as $v) {
+			$f[] = "\n $v";
+		}
+		$s .= implode(', ',$f);
+		$sql[] = $s;
+		return $sql;
+	}
+	
+	function AlterColumnSQL($tabname, $flds)
+	{
+		$tabname = $this->TableName ($tabname);
+		$sql = array();
+		list($lines,$pkey) = $this->_GenFields($flds);
+		foreach($lines as $v) {
+			$sql[] = "ALTER TABLE $tabname $this->alterCol $v";
+		}
+
+		return $sql;
+	}
+	
+	function DropColumnSQL($tabname, $flds)
+	{
+		$tabname = $this->TableName($tabname);
+		if (!is_array($flds)) $flds = explode(',',$flds);
+		$f = array();
+		$s = "ALTER TABLE $tabname";
+		foreach($flds as $v) {
+			$f[] = "\n$this->dropCol ".$this->NameQuote($v);
+		}
+		$s .= implode(', ',$f);
+		$sql[] = $s;
+		return $sql;
+	}
+	
+	// return string must begin with space
+	function _CreateSuffix($fname,$ftype,$fnotnull,$fdefault,$fautoinc,$fconstraint)
+	{	
+		$suffix = '';
+		if (strlen($fdefault)) $suffix .= " DEFAULT $fdefault";
+		if ($fautoinc) $suffix .= ' DEFAULT AUTOINCREMENT';
+		if ($fnotnull) $suffix .= ' NOT NULL';
+		else if ($suffix == '') $suffix .= ' NULL';
+		if ($fconstraint) $suffix .= ' '.$fconstraint;
+		return $suffix;
+	}
+	
+	/*
+CREATE TABLE 
+    [ database_name.[ owner ] . | owner. ] table_name 
+    ( { < column_definition > 
+        | column_name AS computed_column_expression 
+        | < table_constraint > ::= [ CONSTRAINT constraint_name ] }
+
+            | [ { PRIMARY KEY | UNIQUE } [ ,...n ] 
+    ) 
+
+[ ON { filegroup | DEFAULT } ] 
+[ TEXTIMAGE_ON { filegroup | DEFAULT } ] 
+
+< column_definition > ::= { column_name data_type } 
+    [ COLLATE < collation_name > ] 
+    [ [ DEFAULT constant_expression ] 
+        | [ IDENTITY [ ( seed , increment ) [ NOT FOR REPLICATION ] ] ]
+    ] 
+    [ ROWGUIDCOL] 
+    [ < column_constraint > ] [ ...n ] 
+
+< column_constraint > ::= [ CONSTRAINT constraint_name ] 
+    { [ NULL | NOT NULL ] 
+        | [ { PRIMARY KEY | UNIQUE } 
+            [ CLUSTERED | NONCLUSTERED ] 
+            [ WITH FILLFACTOR = fillfactor ] 
+            [ON {filegroup | DEFAULT} ] ] 
+        ] 
+        | [ [ FOREIGN KEY ] 
+            REFERENCES ref_table [ ( ref_column ) ] 
+            [ ON DELETE { CASCADE | NO ACTION } ] 
+            [ ON UPDATE { CASCADE | NO ACTION } ] 
+            [ NOT FOR REPLICATION ] 
+        ] 
+        | CHECK [ NOT FOR REPLICATION ] 
+        ( logical_expression ) 
+    } 
+
+< table_constraint > ::= [ CONSTRAINT constraint_name ] 
+    { [ { PRIMARY KEY | UNIQUE } 
+        [ CLUSTERED | NONCLUSTERED ] 
+        { ( column [ ASC | DESC ] [ ,...n ] ) } 
+        [ WITH FILLFACTOR = fillfactor ] 
+        [ ON { filegroup | DEFAULT } ] 
+    ] 
+    | FOREIGN KEY 
+        [ ( column [ ,...n ] ) ] 
+        REFERENCES ref_table [ ( ref_column [ ,...n ] ) ] 
+        [ ON DELETE { CASCADE | NO ACTION } ] 
+        [ ON UPDATE { CASCADE | NO ACTION } ] 
+        [ NOT FOR REPLICATION ] 
+    | CHECK [ NOT FOR REPLICATION ] 
+        ( search_conditions ) 
+    } 
+
+
+	*/
+	
+	/*
+	CREATE [ UNIQUE ] [ CLUSTERED | NONCLUSTERED ] INDEX index_name 
+    ON { table | view } ( column [ ASC | DESC ] [ ,...n ] ) 
+		[ WITH < index_option > [ ,...n] ] 
+		[ ON filegroup ]
+		< index_option > :: = 
+		    { PAD_INDEX | 
+		        FILLFACTOR = fillfactor | 
+		        IGNORE_DUP_KEY | 
+		        DROP_EXISTING | 
+		    STATISTICS_NORECOMPUTE | 
+		    SORT_IN_TEMPDB  
+		}
+*/
+	function _IndexSQL($idxname, $tabname, $flds, $idxoptions)
+	{
+		$sql = array();
+		
+		if ( isset($idxoptions['REPLACE']) || isset($idxoptions['DROP']) ) {
+			$sql[] = sprintf ($this->dropIndex, $idxname, $tabname);
+			if ( isset($idxoptions['DROP']) )
+				return $sql;
+		}
+		
+		if ( empty ($flds) ) {
+			return $sql;
+		}
+		
+		$unique = isset($idxoptions['UNIQUE']) ? ' UNIQUE' : '';
+		$clustered = isset($idxoptions['CLUSTERED']) ? ' CLUSTERED' : '';
+		
+		if ( is_array($flds) )
+			$flds = implode(', ',$flds);
+		$s = 'CREATE' . $unique . $clustered . ' INDEX ' . $idxname . ' ON ' . $tabname . ' (' . $flds . ')';
+		
+		if ( isset($idxoptions[$this->upperName]) )
+			$s .= $idxoptions[$this->upperName];
+
+		$sql[] = $s;
+		
+		return $sql;
+	}
+}
+?>
Index: /Dev/trunk/rdfapi/util/adodb/docs/docs-active-record.htm
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/docs/docs-active-record.htm	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/docs/docs-active-record.htm	(revision 12)
@@ -0,0 +1,541 @@
+<html>
+<style>
+pre {
+  background-color: #eee;
+  padding: 0.75em 1.5em;
+  font-size: 12px;
+  border: 1px solid #ddd;
+}
+
+li,p {
+font-family: Arial, Helvetica, sans-serif ;
+}
+</style>
+<title>ADOdb Active Record</title>
+<body>
+<h1>ADOdb Active Record</h1>
+<p> (c) 2000-2007 John Lim (jlim#natsoft.com)</p>
+<p><font size="1">This software is dual licensed using BSD-Style and LGPL. This 
+  means you can use it in compiled proprietary and commercial products.</font></p>
+<p><hr>
+<ol>
+
+<h3><li>Introduction</h3>
+<p>
+ADOdb_Active_Record is an Object Relation Mapping (ORM) implementation using PHP. In an ORM system, the tables and rows of the database are abstracted into native PHP objects. This allows the programmer to focus more on manipulating the data and less on writing SQL queries.
+<p>
+This implementation differs from Zend Framework's implementation in the following ways:
+<ul>
+<li>Works with PHP4 and PHP5 and provides equivalent functionality in both versions of PHP.<p>
+<li>ADOdb_Active_Record works when you are connected to multiple databases. Zend's only works when connected to a default database.<p>
+<li>Support for $ADODB_ASSOC_CASE. The field names are upper-cased, lower-cased or left in natural case depending on this setting.<p>
+<li>No field name conversion to camel-caps style, unlike Zend's implementation which will convert field names such as 'first_name' to 'firstName'.<p>
+<li>NewADOConnection::GetActiveRecords() and ADOConnection::GetActiveRecordsClass() functions in adodb.inc.php.<p>
+<li>Caching of table metadata so it is only queried once per table, no matter how many Active Records are created.<p>
+<li>The additional functionality is described <a href=#additional>below</a>. 
+</ul>
+<P>
+ADOdb_Active_Record is designed upon the principles of the "ActiveRecord" design pattern, which was first described by Martin Fowler. The ActiveRecord pattern has been implemented in many forms across the spectrum of programming languages. ADOdb_Active_Record attempts to represent the database as closely to native PHP objects as possible.
+<p>
+ADOdb_Active_Record maps a database table to a PHP class, and each instance of that class represents a table row. Relations between tables can also be defined, allowing the ADOdb_Active_Record objects to be nested.
+<p>
+
+<h3><li>Setting the Database Connection</h3>
+<p>
+The first step to using  ADOdb_Active_Record is to set the default connection that an ADOdb_Active_Record objects will use to connect to a database. 
+
+<pre>
+require_once('adodb/adodb-active-record.inc.php');
+
+$db = NewADOConnection('mysql://root:pwd@localhost/dbname');
+ADOdb_Active_Record::SetDatabaseAdapter($db);
+</pre>        
+
+<h3><li>Table Rows as Objects</h3>
+<p>
+First, let's create a temporary table in our MySQL database that we can use for demonstrative purposes throughout the rest of this tutorial. We can do this by sending a CREATE query:
+
+<pre>
+$db->Execute("CREATE TEMPORARY TABLE `persons` (
+                `id` int(10) unsigned NOT NULL auto_increment,
+                `name_first` varchar(100) NOT NULL default '',
+                `name_last` varchar(100) NOT NULL default '',
+                `favorite_color` varchar(100) NOT NULL default '',
+                PRIMARY KEY  (`id`)
+            ) ENGINE=MyISAM;
+           ");
+ </pre>   
+<p>
+ADOdb_Active_Record's are object representations of table rows. Each table in the database is represented by a class in PHP. To begin working with a table as a ADOdb_Active_Record, a class that extends ADOdb_Active_Records needs to be created for it.
+
+<pre>
+class Person extends ADOdb_Active_Record{}
+$person = new Person();
+</pre>   
+
+<p>
+In the above example, a new ADOdb_Active_Record object $person was created to access the "persons" table. Zend_Db_DataObject takes the name of the class, pluralizes it (according to American English rules), and assumes that this is the name of the table in the database.
+<p>
+This kind of behavior is typical of ADOdb_Active_Record. It will assume as much as possible by convention rather than explicit configuration. In situations where it isn't possible to use the conventions that ADOdb_Active_Record expects, options can be overridden as we'll see later.
+
+<h3><li>Table Columns as Object Properties</h3>
+<p>
+When the $person object was instantiated, ADOdb_Active_Record read the table metadata from the database itself, and then exposed the table's columns (fields) as object properties.
+<p>
+Our "persons" table has three fields: "name_first", "name_last", and "favorite_color". Each of these fields is now a property of the $person object. To see all these properties, use the ADOdb_Active_Record::getAttributeNames() method:
+<pre>
+var_dump($person->getAttributeNames());
+
+/**
+ * Outputs the following:
+ * array(4) {
+ *    [0]=>
+ *    string(2) "id"
+ *    [1]=>
+ *    string(9) "name_first"
+ *    [2]=>
+ *    string(8) "name_last"
+ *    [3]=>
+ *    string(13) "favorite_color"
+ *  }
+ */
+    </pre>   
+<p>
+One big difference between ADOdb and Zend's implementation is we do not automatically convert to camelCaps style.
+<p>
+<h3><li>Inserting and Updating a Record</h3><p>
+
+An ADOdb_Active_Record object is a representation of a single table row. However, when our $person object is instantiated, it does not reference any particular row. It is a blank record that does not yet exist in the database. An ADOdb_Active_Record object is considered blank when its primary key is NULL. The primary key in our persons table is "id".
+<p>
+To insert a new record into the database, change the object's properties and then call the ADOdb_Active_Record::save() method:
+<pre>
+$person = new Person();
+$person->nameFirst = 'Andi';
+$person->nameLast  = 'Gutmans';
+$person->save();
+ </pre>   
+<p>
+Oh, no! The above code snippet does not insert a new record into the database. Instead, outputs an error:
+<pre>
+1048: Column 'name_first' cannot be null
+ </pre>   
+<p>
+This error occurred because MySQL rejected the INSERT query that was generated by ADOdb_Active_Record. If exceptions are enabled in ADOdb and you are using PHP5, an error will be thrown. In the definition of our table, we specified all of the fields as NOT NULL; i.e., they must contain a value.
+<p>
+ADOdb_Active_Records are bound by the same contraints as the database tables they represent. If the field in the database cannot be NULL, the corresponding property in the ADOdb_Active_Record also cannot be NULL. In the example above, we failed to set the property $person->favoriteColor, which caused the INSERT to be rejected by MySQL.
+<p>
+To insert a new ADOdb_Active_Record in the database, populate all of ADOdb_Active_Record's properties so that they satisfy the constraints of the database table, and then call the save() method:
+<pre>
+/**
+ * Calling the save() method will successfully INSERT
+ * this $person into the database table.
+ */
+$person = new Person();
+$person->name_first     = 'Andi';
+$person->name_last      = 'Gutmans';
+$person->favorite_color = 'blue';
+$person->save();
+</pre>
+<p>
+Once this $person has been INSERTed into the database by calling save(), the primary key can now be read as a property. Since this is the first row inserted into our temporary table, its "id" will be 1:
+<pre>
+var_dump($person->id);
+
+/**
+ * Outputs the following:
+ * string(1)
+ */
+ </pre>       
+<p>
+From this point on, updating it is simply a matter of changing the object's properties and calling the save() method again:
+
+<pre>
+$person->favorite_color = 'red';
+$person->save();
+   </pre>
+<p>
+The code snippet above will change the favorite color to red, and then UPDATE the record in the database.
+
+<a name=additional>
+<h2>ADOdb Specific Functionality</h2>
+<h3><li>Setting the Table Name</h3>
+<p>The default behaviour on creating an ADOdb_Active_Record is to "pluralize" the class name and
+ use that as the table name. Often, this is not the case. For example, the Person class could be reading 
+ from the "People" table. 
+<p>We provide two ways to define your own table:
+<p>1. Use a constructor parameter to override the default table naming behaviour.
+<pre>
+	class Person extends ADOdb_Active_Record{}
+	$person = new Person('People');
+</pre>
+<p>2. Define it in a class declaration:
+<pre>
+	class Person extends ADOdb_Active_Record
+	{
+	var $_table = 'People';
+	}
+	$person = new Person();
+</pre>
+
+<h3><li>$ADODB_ASSOC_CASE</h3>
+<p>This allows you to control the case of field names and properties. For example, all field names in Oracle are upper-case by default. So you 
+can force field names to be lowercase using $ADODB_ASSOC_CASE. Legal values are as follows:
+<pre>
+ 0: lower-case
+ 1: upper-case
+ 2: native-case
+</pre>
+<p>So to force all Oracle field names to lower-case, use
+<pre>
+$ADODB_ASSOC_CASE = 0;
+$person = new Person('People');
+$person->name = 'Lily';
+$ADODB_ASSOC_CASE = 2;
+$person2 = new Person('People');
+$person2->NAME = 'Lily'; 
+</pre>
+
+<p>Also see <a href=http://phplens.com/adodb/reference.constants.adodb_assoc_case.html>$ADODB_ASSOC_CASE</a>.
+
+<h3><li>ADOdb_Active_Record::Save()</h3>
+<p>
+Saves a record by executing an INSERT or UPDATE SQL statement as appropriate. 
+<p>Returns false on  unsuccessful INSERT, true if successsful INSERT.
+<p>Returns 0 on failed UPDATE, and 1 on UPDATE if data has changed, and -1 if no data was changed, so no UPDATE statement was executed.
+
+<h3><li>ADOdb_Active_Record::Replace()</h3>
+<p>
+ADOdb supports replace functionality, whereby the record is inserted if it does not exists, or updated otherwise.
+<pre>
+$rec = new ADOdb_Active_Record("product");
+$rec->name = 'John';
+$rec->tel_no = '34111145';
+$ok = $rec->replace(); // 0=failure, 1=update, 2=insert
+</pre>
+
+
+<h3><li>ADOdb_Active_Record::Load($where)</h3>
+<p>Sometimes, we want to load a single record into an Active Record. We can do so using:
+<pre>
+$person->load("id=3");
+
+// or using bind parameters
+
+$person->load("id=?", array(3));
+</pre>
+<p>Returns false if an error occurs.
+
+<h3><li>ADOdb_Active_Record::Find($whereOrderBy, $bindarr=false, $pkeyArr=false)</h3>
+<p>We want to retrieve an array of active records based on some search criteria. For example:
+<pre>
+class Person extends ADOdb_Active_Record {
+var $_table = 'people';
+}
+
+$person = new Person();
+$peopleArray =& $person->Find("name like ? order by age", array('Sm%'));
+</pre>
+
+<h3><li>Error Handling and Debugging</h3>
+<p>
+In PHP5, if adodb-exceptions.inc.php is included, then errors are thrown. Otherwise errors are handled by returning a value. False by default means an error has occurred. You can get the last error message using the ErrorMsg() function. 
+<p>
+To check for errors in ADOdb_Active_Record, do not poll ErrorMsg() as the last error message will always be returned, even if it occurred several operations ago. Do this instead:
+<pre>
+# right!
+$ok = $rec->Save();
+if (!$ok) $err = $rec->ErrorMsg();
+
+# wrong :(
+$rec->Save();
+if ($rec->ErrorMsg()) echo "Wrong way to detect error";
+</pre>
+<p>The ADOConnection::Debug property is obeyed. So
+if $db->debug is enabled, then ADOdb_Active_Record errors are also outputted to standard output and written to the browser.
+
+<h3><li>ADOdb_Active_Record::Set()</h3>
+<p>You can convert an array to an ADOdb_Active_Record using Set(). The array must be numerically indexed, and have all fields of the table defined in the array. The elements of the array must be in the table's natural order too.
+<pre>
+$row = $db->GetRow("select * from tablex where id=$id");
+
+# PHP4 or PHP5 without enabling exceptions
+$obj =& new ADOdb_Active_Record('Products');
+if ($obj->ErrorMsg()){
+	echo $obj->ErrorMsg();
+} else {
+	$obj->Set($row);
+}
+
+# in PHP5, with exceptions enabled:
+
+include('adodb-exceptions.inc.php');
+try {
+	$obj =& new ADOdb_Active_Record('Products');
+	$obj->Set($row);
+} catch(exceptions $e) {
+	echo $e->getMessage();
+}
+</pre>
+<p>
+<h3><li>Primary Keys</h3>
+<p>
+ADOdb_Active_Record does not require the table to have a primary key. You can insert records for such a table, but you will not be able to update nor delete. 
+<p>Sometimes you are retrieving data from a view or table that has no primary key, but has a unique index. You can dynamically set the primary key of a table through the constructor, or using ADOdb_Active_Record::SetPrimaryKeys():
+<pre>
+	$pkeys = array('category','prodcode');
+	
+	// set primary key using constructor
+	$rec = new ADOdb_Active_Record('Products', $pkeys);
+	
+	 // or use method
+	$rec->SetPrimaryKeys($pkeys);
+</pre>
+
+
+<h3><li>Retrieval of Auto-incrementing ID</h3>
+When creating a new record, the retrieval of the last auto-incrementing ID is not reliable for databases that do not support the Insert_ID() function call (check $connection->hasInsertID). In this case we perform a <b>SELECT MAX($primarykey) FROM $table</b>, which will not work reliably in a multi-user environment. You can override the ADOdb_Active_Record::LastInsertID() function in this case.
+
+<h3><li>Dealing with Multiple Databases</h3>
+<p>
+Sometimes we want to load  data from one database and insert it into another using ActiveRecords. This can be done using the optional parameter of the ADOdb_Active_Record constructor. In the following example, we read data from db.table1 and store it in db2.table2:
+<pre>
+$db = NewADOConnection(...);
+$db2 = NewADOConnection(...);
+
+ADOdb_Active_Record::SetDatabaseAdapter($db2);
+
+$activeRecs = $db->GetActiveRecords('table1');
+
+foreach($activeRecs as $rec) {
+	$rec2 = new ADOdb_Active_Record('table2',$db2);
+	$rec2->id = $rec->id;
+	$rec2->name = $rec->name;
+	
+	$rec2->Save();
+}
+</pre>
+<p>
+If you have to pass in a primary key called "id" and the 2nd db connection in the constructor, you can do so too:
+<pre>
+$rec = new ADOdb_Active_Record("table1",array("id"),$db2);
+</pre>
+
+<h3><li>$ADODB_ACTIVE_CACHESECS</h3>
+<p>You can cache the table metadata (field names, types, and other info such primary keys) in $ADODB_CACHE_DIR (which defaults to /tmp) by setting
+the global variable $ADODB_ACTIVE_CACHESECS to a value greater than 0. This will be the number of seconds to cache.
+ You should set this to a value of 30 seconds or greater for optimal performance.
+
+<h3><li>Active Record Considered Bad?</h3>
+<p>Although the Active Record concept is useful, you have to be aware of some pitfalls when using Active Record. The level of granularity of Active Record is individual records. It encourages code like the following, used to increase the price of all furniture products by 10%:
+<pre>
+ $recs = $db->GetActiveRecords("Products","category='Furniture'");
+ foreach($recs as $rec) {
+    $rec->price *= 1.1; // increase price by 10% for all Furniture products
+    $rec->save();
+ }
+</pre>
+Of course a SELECT statement is superior because it's simpler and much more efficient (probably by a factor of x10 or more):
+<pre>
+   $db->Execute("update Products set price = price * 1.1 where category='Furniture'");
+</pre>
+<p>Another issue is performance. For performance sensitive code, using direct SQL will always be faster than using Active Records due to overhead and the fact that all fields in a row are retrieved (rather than only the subset you need) whenever an Active Record is loaded.
+
+<h3><li>Transactions</h3>
+<p>
+The default transaction mode in ADOdb is autocommit. So that is the default with active record too. 
+The general rules for managing transactions still apply. Active Record to the database is a set of insert/update/delete statements, and the db has no knowledge of active records.
+<p>
+Smart transactions, that does an auto-rollback if an error occurs, is still the best method to multiple activities (inserts/updates/deletes) that need to be treated as a single transaction:
+<pre>
+$conn->StartTrans();
+$parent->save();
+$child->save();
+$conn->CompleteTrans();
+</pre>
+
+<h2>ADOConnection Supplement</h2>
+
+<h3><li>ADOConnection::GetActiveRecords()</h3>
+<p>
+This allows you to retrieve an array of ADOdb_Active_Records. Returns false if an error occurs.
+<pre>
+$table = 'products';
+$whereOrderBy = "name LIKE 'A%' ORDER BY Name";
+$activeRecArr = $db->GetActiveRecords($table, $whereOrderBy);
+foreach($activeRecArr as $rec) {
+	$rec->id = rand();
+	$rec->save();
+}
+</pre>
+<p>
+And to retrieve all records ordered by specific fields:
+<pre>
+$whereOrderBy = "1=1 ORDER BY Name";
+$activeRecArr = $db->ADOdb_Active_Records($table);
+</pre>
+<p>
+To use bind variables (assuming ? is the place-holder for your database):
+<pre>
+$activeRecArr = $db->GetActiveRecords($tableName, 'name LIKE ?',
+						array('A%'));
+</pre>
+<p>You can also define the primary keys of the table by passing an array of field names:
+<pre>
+$activeRecArr = $db->GetActiveRecords($tableName, 'name LIKE ?',
+						array('A%'), array('id'));
+</pre>
+
+<h3><li>ADOConnection::GetActiveRecordsClass()</h3>
+<p>
+This allows you to retrieve an array of objects derived from ADOdb_Active_Records. Returns false if an error occurs.
+<pre>
+class Product extends ADOdb_Active_Records{};
+$table = 'products';
+$whereOrderBy = "name LIKE 'A%' ORDER BY Name";
+$activeRecArr = $db->GetActiveRecordsClass('Product',$table, $whereOrderBy);
+
+# the objects in $activeRecArr are of class 'Product'
+foreach($activeRecArr as $rec) {
+	$rec->id = rand();
+	$rec->save();
+}
+</pre>
+<p>
+To use bind variables (assuming ? is the place-holder for your database):
+<pre>
+$activeRecArr = $db->GetActiveRecordsClass($className,$tableName, 'name LIKE ?',
+						array('A%'));
+</pre>
+<p>You can also define the primary keys of the table by passing an array of field names:
+<pre>
+$activeRecArr = $db->GetActiveRecordsClass($className,$tableName, 'name LIKE ?',
+						array('A%'), array('id'));
+</pre>
+
+</ol>
+
+<h3><li>ADOConnection::ErrorMsg()</h3>
+<p>Returns last error message.
+<h3><li>ADOConnection::ErrorNo()</h3>
+<p>Returns last error number.
+<h2>Code Sample</h2>
+<p>The following works with PHP4 and PHP5
+<pre>
+include('../adodb.inc.php');
+include('../adodb-active-record.inc.php');
+
+// uncomment the following if you want to test exceptions
+#if (PHP_VERSION >= 5) include('../adodb-exceptions.inc.php');
+
+$db = NewADOConnection('mysql://root@localhost/northwind');
+$db->debug=1;
+ADOdb_Active_Record::SetDatabaseAdapter($db);
+
+$db->Execute("CREATE TEMPORARY TABLE `persons` (
+                `id` int(10) unsigned NOT NULL auto_increment,
+                `name_first` varchar(100) NOT NULL default '',
+                `name_last` varchar(100) NOT NULL default '',
+                `favorite_color` varchar(100) NOT NULL default '',
+                PRIMARY KEY  (`id`)
+            ) ENGINE=MyISAM;
+           ");
+		   
+class Person extends ADOdb_Active_Record{}
+$person = new Person();
+
+echo "&lt;p>Output of getAttributeNames: ";
+var_dump($person->getAttributeNames());
+
+/**
+ * Outputs the following:
+ * array(4) {
+ *    [0]=>
+ *    string(2) "id"
+ *    [1]=>
+ *    string(9) "name_first"
+ *    [2]=>
+ *    string(8) "name_last"
+ *    [3]=>
+ *    string(13) "favorite_color"
+ *  }
+ */
+
+$person = new Person();
+$person->nameFirst = 'Andi';
+$person->nameLast  = 'Gutmans';
+$person->save(); // this save() will fail on INSERT as favorite_color is a must fill...
+
+
+$person = new Person();
+$person->name_first     = 'Andi';
+$person->name_last      = 'Gutmans';
+$person->favorite_color = 'blue';
+$person->save(); // this save will perform an INSERT successfully
+
+echo "&lt;p>The Insert ID generated:"; print_r($person->id);
+
+$person->favorite_color = 'red';
+$person->save(); // this save() will perform an UPDATE
+
+$person = new Person();
+$person->name_first     = 'John';
+$person->name_last      = 'Lim';
+$person->favorite_color = 'lavender';
+$person->save(); // this save will perform an INSERT successfully
+
+// load record where id=2 into a new ADOdb_Active_Record
+$person2 = new Person();
+$person2->Load('id=2');
+var_dump($person2);
+
+// retrieve an array of records
+$activeArr = $db->GetActiveRecordsClass($class = "Person",$table = "persons","id=".$db->Param(0),array(2));
+$person2 =& $activeArr[0];
+echo "&lt;p>Name first (should be John): ",$person->name_first, "&lt;br>Class = ",get_class($person2);	
+</pre>
+
+ <h3>Todo (Code Contributions welcome)</h3>
+ <p>Check _original and current field values before update, only update changes. Also if the primary key value is changed, then on update, we should save and use the original primary key values in the WHERE clause!
+ <p>Handle 1-to-many relationships.
+ <p>PHP5 specific:  Make GetActiveRecords*() return an Iterator.
+ <p>PHP5 specific: Change PHP5 implementation of Active Record to use __get() and __set() for better performance.
+
+<h3> Change Log</h3>
+<p>0.07
+<p>$ADODB_ASSOC_CASE=2 did not work properly. Fixed.
+<p>Added === check in ADODB_SetDatabaseAdapter for $db, adodb-active-record.inc.php. Thx Christian Affolter.
+
+<p>0.06
+<p>Added ErrorNo().
+<p>Fixed php 5.2.0 compat issues.
+ 
+<p>0.05
+<p>If inserting a record and the value of a primary key field is null, then we do not insert that field in as
+we assume it is an auto-increment field. Needed by mssql.
+
+<p>0.04 5 June 2006 <br>
+<p>Added support for declaring table name in $_table in class declaration. Thx Bill Dueber for idea.
+<p>Added find($where,$bindarr=false) method to retrieve an array of active record objects.
+
+<p>0.03 <br>
+- Now we only update fields that have changed, using $this->_original.<br>
+- We do not include auto_increment fields in replace(). Thx Travis Cline<br>
+- Added ADODB_ACTIVE_CACHESECS.<br>
+
+<p>0.02 <br>
+- Much better error handling. ErrorMsg() implemented. Throw implemented if adodb-exceptions.inc.php detected.<br>
+- You can now define the primary keys of the view or table you are accessing manually.<br>
+- The Active Record allows you to create an object which does not have a primary key. You can INSERT but not UPDATE in this case.
+- Set() documented.<br>
+- Fixed _pluralize bug with y suffix.
+
+<p>
+ 0.01 6 Mar 2006<br>
+- Fixed handling of nulls when saving (it didn't save nulls, saved them as '').<br>
+- Better error handling messages.<br>
+- Factored out a new method GetPrimaryKeys().<br>
+ <p>
+ 0.00 5 Mar 2006<br>
+ 1st release
+</body>
+</html>
Index: /Dev/trunk/rdfapi/util/adodb/docs/docs-adodb.htm
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/docs/docs-adodb.htm	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/docs/docs-adodb.htm	(revision 12)
@@ -0,0 +1,3568 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
+<html><head><title>ADODB Manual</title>
+
+<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
+
+	
+<style>
+pre {
+  background-color: #eee;
+  padding: 0.75em 1.5em;
+  font-size: 12px;
+  border: 1px solid #ddd;
+}
+</style></head>
+<body bgcolor="#ffffff" text="black">
+
+<h2>ADOdb Library for PHP</h2>
+<p>V4.94 23 Jan 2007 (c) 2000-2007 John Lim (jlim#natsoft.com)</p>
+<p><font size="1">This software is dual licensed using BSD-Style and LGPL. This 
+  means you can use it in compiled proprietary and commercial products.</font></p>
+  
+
+	<p>Useful ADOdb links:  <a href="http://adodb.sourceforge.net/#download">Download</a> &nbsp; <a href="http://adodb.sourceforge.net/#docs">Other Docs</a>
+
+</p><p><a href="#intro"><b>Introduction</b></a><b><br>
+	<a href="#features">Unique Features</a><br>
+	<a href="#users">How People are using ADOdb</a><br>
+	<a href="#bugs">Feature Requests and Bug Reports</a><br>
+	</b><b><a href="#install">Installation</a><br>
+	<a href="#mininstall">Minimum Install</a><br>
+	<a href="#coding">Initializing Code and Connectioning to Databases</a><br>
+	</b><font size="2"> &nbsp; <a href="#dsnsupport">Data Source Name (DSN) Support</a></font>  &nbsp;  <a href="#connect_ex">Connection Examples</a> <br>
+	<b><a href="#speed">High Speed ADOdb - tuning tips</a></b><br>
+	<b><a href="#hack">Hacking and Modifying ADOdb Safely</a><br>
+	<a href="#php5">PHP5 Features</a></b><br>
+	<font size="2"><a href="#php5iterators">foreach iterators</a> <a href="#php5exceptions">exceptions</a></font><br>
+	<b> <a href="#drivers">Supported Databases</a></b><br>
+	<b> <a href="#quickstart">Tutorials</a></b><br>
+	<a href="#ex1">Example 1: Select</a><br>
+	<a href="#ex2">Example 2: Advanced Select</a><br>
+	<a href="#ex3">Example 3: Insert</a><br>
+	<a href="#ex4">Example 4: Debugging</a> &nbsp;<a href="#exrs2html">rs2html 
+	example</a><br>
+	<a href="#ex5">Example 5: MySQL and Menus</a><br>
+	<a href="#ex6">Example 6: Connecting to Multiple Databases at once</a> <br>
+	<a href="#ex7">Example 7: Generating Update and Insert SQL</a> <br>
+	<a href="#ex8">Example 8: Implementing Scrolling with Next and Previous</a><br>
+	<a href="#ex9">Example 9: Exporting in CSV or Tab-Delimited Format</a> <br>
+	<a href="#ex10">Example 10: Custom filters</a><br>
+	<a href="#ex11">Example 11: Smart Transactions</a><br>
+	<br>
+	<b> <a href="#errorhandling">Using Custom Error Handlers and PEAR_Error</a><br>
+	<a href="#DSN">Data Source Names</a><br>
+	<a href="#caching">Caching</a><br>
+	<a href="#pivot">Pivot Tables</a></b> 
+</p><p><a href="#ref"><b>REFERENCE</b></a>
+</p><p> <font size="2">Variables: <a href="#adodb_countrecs">$ADODB_COUNTRECS</a> 
+<a href="#adodb_ansi_padding_off">$ADODB_ANSI_PADDING_OFF</a>
+  <a href="#adodb_cache_dir">$ADODB_CACHE_DIR</a> <br>
+  &nbsp; &nbsp; &nbsp; &nbsp;  <a href="#force_type">$ADODB_FORCE_TYPE</a> 
+  <a href="#adodb_fetch_mode">$ADODB_FETCH_MODE</a> 
+  <a href="#adodb_lang">$ADODB_LANG</a> <a href=#adodb_auto_quote>ADODB_QUOTE_FIELDNAMES</a> <br>
+  Constants: </font><font size="2"><a href="#adodb_assoc_case">ADODB_ASSOC_CASE</a> 
+  </font><br>
+  <a href="#ADOConnection"><b> ADOConnection</b></a><br>
+  <font size="2">Connections: <a href="#connect">Connect</a> <a href="#pconnect">PConnect</a> 
+  <a href="#nconnect">NConnect</a> <a href="#isconnected">IsConnected</a><br>
+  Executing SQL: <a href="#execute">Execute</a> <a href="#cacheexecute"><i>CacheExecute</i></a> 
+  <a href="#selectlimit">SelectLimit</a> <a href="#cacheSelectLimit"><i>CacheSelectLimit</i></a> 
+  <a href="#param">Param</a> <a href="#prepare">Prepare</a> <a href="#preparesp">PrepareSP</a> 
+  <a href="#inparameter">InParameter</a> <a href="#outparameter">OutParameter</a> <a href="#autoexecute">AutoExecute</a>
+  <br>
+  &nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <a href="#getone">GetOne</a> 
+  <a href="#cachegetone"><i>CacheGetOne</i></a> <a href="#getrow">GetRow</a> <a href="#cachegetrow"><i>CacheGetRow</i></a> 
+  <a href="#getall">GetAll</a> <a href="#cachegetall"><i>CacheGetAll</i></a> <a href="#getcol">GetCol</a> 
+  <a href="#cachegetcol"><i>CacheGetCol</i></a> <a href="#getassoc1">GetAssoc</a> <a href="#cachegetassoc"><i>CacheGetAssoc</i></a> <a href="#replace">Replace</a> 
+  <br>
+  &nbsp; &nbsp; &nbsp; &nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <a href="#executecursor">ExecuteCursor</a> 
+  (oci8 only)<br>
+  Generates SQL strings: <a href="#getupdatesql">GetUpdateSQL</a> <a href="#getinsertsql">GetInsertSQL</a> 
+  <a href="#concat">Concat</a> <a href="#ifnull">IfNull</a> <a href="#length">length</a> <a href="#random">random</a> <a href="#substr">substr</a> 
+  <a href="#qstr">qstr</a> <a href="#param">Param</a>  <a href="#OffsetDate">OffsetDate</a> <a href="#sqldate">SQLDate</a> 
+  <a href="#dbdate">DBDate</a>  <a href="#dbtimestamp">DBTimeStamp</a>
+  <a href="#binddate">BindDate</a>  <a href="#bindtimestamp">BindTimeStamp</a>
+  <br>
+  Blobs: <a href="#updateblob">UpdateBlob</a> <a href="#updateclob">UpdateClob</a> 
+  <a href="#updateblobfile">UpdateBlobFile</a> <a href="#blobencode">BlobEncode</a> 
+  <a href="#blobdecode">BlobDecode</a><br>
+  Paging/Scrolling: <a href="#pageexecute">PageExecute</a> <a href="#cachepageexecute">CachePageExecute</a><br>
+  Cleanup: <a href="#cacheflush">CacheFlush</a> <a href="#Close">Close</a><br>
+  Transactions: <a href="#starttrans">StartTrans</a> <a href="#completetrans">CompleteTrans</a> 
+  <a href="#failtrans">FailTrans</a> <a href="#hasfailedtrans">HasFailedTrans</a> 
+  <a href="#begintrans">BeginTrans</a> <a href="#committrans">CommitTrans</a> 
+  <a href="#rollbacktrans">RollbackTrans</a> <a href=#SetTransactionMode>SetTransactionMode</a><br>
+  Fetching Data: </font> <font size="2"><a href="#setfetchmode">SetFetchMode</a><br>
+  Strings: <a href="#concat">concat</a> <a href="#length">length</a>  <a href="#qstr">qstr</a> <a href="#quote">quote</a> <a href="#substr">substr</a><br>
+  Dates: <a href="#dbdate">DBDate</a> <a href="#dbtimestamp">DBTimeStamp</a> <a href="#unixdate">UnixDate</a> 
+  <a href="#binddate">BindDate</a>  <a href="#bindtimestamp">BindTimeStamp</a>
+  <a href="#unixtimestamp">UnixTimeStamp</a> <a href="#OffsetDate">OffsetDate</a> 
+  <a href="#SQLDate">SQLDate</a> <br>
+  Row Management: <a href="#affected_rows">Affected_Rows</a> <a href="#inserted_id">Insert_ID</a>  <a href="#rowlock">RowLock</a>
+  <a href="#genid">GenID</a> <a href="#createseq">CreateSequence</a> <a href="#dropseq">DropSequence</a> 
+  <br>
+  Error Handling: <a href="#errormsg">ErrorMsg</a> <a href="#errorno">ErrorNo</a> 
+  <a href="#metaerror">MetaError</a> <a href="#metaerrormsg">MetaErrorMsg</a> <a href="#ignoreerrors">IgnoreErrors</a><br>
+  Data Dictionary (metadata): <a href="#metadatabases">MetaDatabases</a> <a href="#metatables">MetaTables</a> 
+  <a href="#metacolumns">MetaColumns</a> <a href="#metacolumnames">MetaColumnNames</a> 
+  <a href="#metaprimarykeys">MetaPrimaryKeys</a> <a href="#metaforeignkeys">MetaForeignKeys</a> 
+  <a href="#serverinfo">ServerInfo</a> <br>
+  Statistics and Query-Rewriting: <a href="#logsql">LogSQL</a> <a href="#fnexecute">fnExecute 
+  and fnCacheExecute</a><br>
+  </font><font size="2">Deprecated: <a href="#bind">Bind</a> <a href="#blankrecordset">BlankRecordSet</a>
+  <a href="#parameter">Parameter</a></font>
+  <a href="#adorecordSet"><b><br>
+  ADORecordSet</b></a><br>
+  <font size="2">
+  Returns one field: <a href="#fields">Fields</a><br>
+ Returns one row:<a href="#fetchrow">FetchRow</a> <a href="#fetchinto">FetchInto</a> 
+  <a href="#fetchobject">FetchObject</a> <a href="#fetchnextobject">FetchNextObject</a> 
+  <a href="#fetchobj">FetchObj</a> <a href="#fetchnextobj">FetchNextObj</a>
+ <a href="#getrowassoc">GetRowAssoc</a> <br>
+  Returns all rows:<a href="#getarray">GetArray</a> <a href="#getrows">GetRows</a> 
+  <a href="#getassoc">GetAssoc</a><br>
+  Scrolling:<a href="#move">Move</a> <a href="#movenext">MoveNext</a> <a href="#movefirst">MoveFirst</a> 
+  <a href="#movelast">MoveLast</a> <a href="#abspos">AbsolutePosition</a> <a href="#currentrow">CurrentRow</a> 
+  <a href="#atfirstpage">AtFirstPage</a> <a href="#atlastpage">AtLastPage</a> 
+  <a href="#absolutepage">AbsolutePage</a> </font> <font size="2"><br>
+  Menu generation:<a href="#getmenu">GetMenu</a> <a href="#getmenu2">GetMenu2</a><br>
+  Dates:<a href="#userdate">UserDate</a> <a href="#usertimestamp">UserTimeStamp</a> 
+  <a href="#unixdate">UnixDate</a> <a href="#unixtimestamp">UnixTimeStamp<br>
+  </a>Recordset Info:<a href="#recordcount">RecordCount</a> <a href="#po_recordcount">PO_RecordCount</a> 
+  <a href="#nextrecordset">NextRecordSet</a><br>
+  Field Info:<a href="#fieldcount">FieldCount</a> <a href="#fetchfield">FetchField</a> 
+  <a href="#metatype">MetaType</a><br>
+  Cleanup: <a href="#rsclose">Close</a></font>  
+</p>
+<p><font size="2"><a href="#rs2html"><b>rs2html</b></a>&nbsp; <a href="#exrs2html">example</a></font><br>
+  <a href="#adodiff">Differences between ADOdb and ADO</a><br>
+  <a href="#driverguide"><b>Database Driver Guide<br>
+  </b></a><b><a href="#changes">Change Log</a></b><br>
+</p>
+<h2>Introduction<a name="intro"></a></h2>
+<p>PHP's database access functions are not standardised. This creates a need for 
+  a database class library to hide the differences between the different database 
+  API's (encapsulate the differences) so we can easily switch databases. PHP 4.0.5 or later
+  is now required (because we use array-based str_replace).</p>
+<p>We currently support MySQL, Oracle, Microsoft SQL Server, Sybase, Sybase SQL Anywhere, Informix, 
+  PostgreSQL, FrontBase,  SQLite, Interbase (Firebird and Borland variants), Foxpro, Access, ADO, DB2, SAP DB and ODBC. 
+  We have had successful reports of connecting to Progress and CacheLite via ODBC. We hope more people 
+  will contribute drivers to support other databases.</p>
+<p>PHP4 supports session variables. You can store your session information using 
+  ADOdb for true portability and scalability. See adodb-session.php for more information.</p>
+<p>Also read <a href="http://phplens.com/lens/adodb/tips_portable_sql.htm">tips_portable_sql.htm</a> 
+ for tips on writing 
+  portable SQL.</p>
+<h2>Unique Features of ADOdb<a name="features"></a></h2>
+<ul>
+  <li><b>Easy for Windows programmers</b> to adapt to because many of the conventions 
+	are similar to Microsoft's ADO.</li>
+  <li>Unlike other PHP database classes which focus only on select statements, 
+	<b>we provide support code to handle inserts and updates which can be adapted 
+	to multiple databases quickly.</b> Methods are provided for date handling, 
+	string concatenation and string quoting characters for differing databases.</li>
+  <li>A<b> metatype system </b>is built in so that we can figure out that types 
+	such as CHAR, TEXT and STRING are equivalent in different databases.</li>
+  <li><b>Easy to port</b> because all the database dependant code are stored in 
+	stub functions. You do not need to port the core logic of the classes.</li>
+  <li><b>Portable table and index creation</b> with the <a href="docs-datadict.htm">datadict</a> classes.
+  </li><li><b>Database performance monitoring and SQL tuning</b> with the <a href="docs-perf.htm">performance monitoring</a> classes.
+  </li><li><b>Database-backed sessions</b> with the <a href="docs-session.htm">session management</a> classes. Supports session expiry notification.
+<li><b>Object-Relational Mapping</b> using <a href="docs-active-record.htm">ADOdb_Active_Record</a> classes.
+</li></ul>
+<h2>How People are using ADOdb<a name="users"></a></h2>
+Here are some examples of how people are using ADOdb (for a much longer list, 
+visit <a href="http://phplens.com/phpeverywhere/adodb-cool-apps">adodb-cool-apps</a>): 
+<ul>
+<li><a href="http://phplens.com/">PhpLens</a> is a commercial data grid
+component that allows both cool Web designers and serious unshaved
+programmers to develop and maintain databases on the Web easily.
+Developed by the author of ADOdb.<p>
+
+</p></li><li><a href="http://www.interakt.ro/phakt/">PHAkt: PHP Extension for DreamWeaver Ultradev</a> allows you to script PHP in the popular Web page editor. Database handling provided by ADOdb.<p>
+
+</p></li><li><a href="http://www.andrew.cmu.edu/%7Erdanyliw/snort/snortacid.html">Analysis Console for Intrusion Databases</a>
+(ACID): PHP-based analysis engine to search and process a database of
+security incidents generated by security-related software such as IDSes
+and firewalls (e.g. Snort, ipchains). By Roman Danyliw.<p>
+
+</p></li><li><a href="http://www.postnuke.com/">PostNuke</a> is a very
+popular free content management system and weblog system. It offers
+full CSS support, HTML 4.01 transitional compliance throughout, an
+advanced blocks system, and is fully multi-lingual enabled. <p>
+
+</p></li><li><a href="http://www.auto-net.no/easypublish.php?page=index&amp;lang_id=2">EasyPublish CMS</a>
+is another free content management system for managing information and
+integrated modules on your internet, intranet- and extranet-sites. From
+Norway.<p>
+
+</p></li><li><a href="http://nola.noguska.com/">NOLA</a> is a full featured accounting, inventory, and job tracking application. It is licensed under the GPL, and developed by Noguska.
+</li></ul><p>
+
+</p><h2>Feature Requests and Bug Reports<a name="bugs"></a></h2>
+<p>Feature requests and bug reports can be emailed to <a href="mailto:jlim#natsoft.com.my">jlim#natsoft.com.my</a> 
+  or posted to the ADOdb Help forums at <a href="http://phplens.com/lens/lensforum/topics.php?id=4">http://phplens.com/lens/lensforum/topics.php?id=4</a>.</p>
+<h2>Installation Guide<a name="install"></a></h2>
+<p>Make sure you are running PHP 4.0.5 or later. 
+  Unpack all the files into a directory accessible by your webserver.</p>
+<p>To test, try modifying some of the tutorial examples. Make sure you customize 
+  the connection settings correctly. You can debug using <i>$db-&gt;debug = true</i> as shown below:</p>
+<pre>&lt;?php<br>	include('adodb/adodb.inc.php');<br>	$db = <a href="#adonewconnection">ADONewConnection</a>($dbdriver); # eg 'mysql' or 'postgres'<br>	$db-&gt;debug = true;<br>	$db-&gt;<a href="#connect">Connect</a>($server, $user, $password, $database);<br>	$rs = $db-&gt;<a href="#execute">Execute</a>('select * from some_small_table');<br>	print "&lt;pre&gt;";<br>	print_r($rs-&gt;<a href="#getrows">GetRows</a>());<br>	print "&lt;/pre&gt;";<br>?&gt;</pre>
+
+ <h3>Minimum Install<a name="mininstall"></a></h3>
+<p>For developers who want to release a minimal install of ADOdb, you will need:
+</p><ul>
+<li>adodb.inc.php
+</li><li>adodb-lib.inc.php
+</li><li>adodb-time.inc.php
+</li><li>drivers/adodb-$database.inc.php
+</li><li>license.txt (for legal reasons)
+</li><li>adodb-php4.inc.php 
+</li><li>adodb-iterator.inc.php  (php5 functionality)
+</li></ul>
+Optional:
+<ul>
+<li>adodb-error.inc.php and lang/adodb-$lang.inc.php (if you use MetaError())
+</li><li>adodb-csvlib.inc.php (if you use cached recordsets - CacheExecute(), etc)
+</li><li>adodb-exceptions.inc.php and adodb-errorhandler.inc.php (if you use adodb error handler or php5 exceptions).
+<li>adodb-active-record.inc.php if you use <a href=docs-active-record.htm>Active Records</a>.
+</li></ul>
+
+<h3>Code Initialization Examples<a name="coding"></a></h3>
+<p>When running ADOdb, at least two files are loaded. First is adodb/adodb.inc.php, 
+ which contains all functions used by all database classes. The code specific 
+ to a particular database is in the adodb/driver/adodb-????.inc.php file.</p>
+ <a name="adonewconnection"></a>
+<p>For example, to connect to a mysql database:</p>
+<pre>include('/path/to/set/here/adodb.inc.php');<br>$conn = &amp;ADONewConnection('mysql');<br></pre>
+<p>Whenever you need to connect to a database, you create a Connection object 
+  using the <b>ADONewConnection</b>($driver) function. 
+  <b>NewADOConnection</b>($driver) is an alternative name for the same function.</p>
+
+<p>At this point, you are not connected to the database (no longer true if you pass in a <a href="#dsnsupport">dsn</a>). You will first need to decide
+whether to use <i>persistent</i> or <i>non-persistent</i> connections. The advantage of <i>persistent</i>
+connections is that they are faster, as the database connection is never closed (even 
+when you call Close()). <i>Non-persistent </i>connections take up much fewer resources though,
+reducing the risk of your database and your web-server becoming overloaded. 
+</p><p>For persistent connections,
+use $conn-&gt;<a href="#pconnect">PConnect()</a>,
+ or $conn-&gt;<a href="#connect">Connect()</a> for non-persistent connections.
+Some database drivers also support <a href="#nconnect">NConnect()</a>, which forces 
+the creation of a new connection. 
+
+<a name="connection_gotcha"></a>
+</p><p><b>Connection Gotcha</b>:  If you create two connections, but both use the same userid and password,
+PHP will share the same connection. This can cause problems if the connections are meant to 
+different databases. The solution is to always use different userid's for different databases,
+ or use NConnect().
+
+ <a name="dsnsupport"></a>
+ </p><h3>Data Source Name (DSN) Support</h3>
+ <p> Since ADOdb 4.51, you can connect to a database by passing a dsn to NewADOConnection() (or ADONewConnection, which is
+ the same function). The dsn format is:
+</p><pre>	$driver://$username:$password@hostname/$database?options[=value]<br></pre><p>
+NewADOConnection() calls Connect() or PConnect() internally for you. If the connection fails, false is returned.
+</p><pre>	<font color="#008000"># non-persistent connection</font>
+	$dsn = 'mysql://root:pwd@localhost/mydb'; 
+	$db = NewADOConnection($dsn);
+	if (!$db) die("Connection failed");   
+	
+	<font color="#008000"># no need to call connect/pconnect!</font>
+	$arr = $db-&gt;GetArray("select * from table");
+	
+	<font color="#008000"># persistent connection</font>
+	$dsn2 = 'mysql://root:pwd@localhost/mydb?persist'; 
+</pre>
+<p>
+If you have special characters such as /:?_ in your dsn, then you need to rawurlencode them first:
+</p><pre>	$pwd = rawurlencode($pwd);<br>	$dsn = "mysql://root:$pwd@localhost/mydb";
+	$dsn2=rawurlencode("sybase_ase")."://user:pass@host/path?query";<br></pre>
+<p>
+Legal options are:
+</p><p>
+<table align="center" border="1"><tbody><tr><td>For all drivers</td><td>
+	'persist', 'persistent', 'debug', 'fetchmode', 'new'
+	</td></tr><tr><td>Interbase/Firebird
+	</td><td>
+					 'dialect','charset','buffers','role'
+	</td></tr><tr><td>M'soft ADO</td><td>
+					 'charpage'
+					
+		</td></tr><tr><td>MySQL</td><td>
+					'clientflags'
+</td></tr><tr><td>MySQLi</td><td>
+	'port', 'socket', 'clientflags'
+</td></tr><tr><td>Oci8</td><td>
+ 'nls_date_format','charset'
+</td></tr></tbody></table>
+</p><p>
+For all drivers, when the options <i>persist</i> or <i>persistent</i> are set,  a persistent connection is forced; similarly, when <i>new</i> is set, then
+a new connection will be created using NConnect if the underlying driver supports it. 
+The <i>debug</i> option enables debugging. The <i>fetchmode</i> calls <a href="#setfetchmode">SetFetchMode()</a>.
+If no value is defined for an option, then the value is set to 1.
+</p><p>
+ADOdb DSN's are compatible with version 1.0 of PEAR DB's DSN format.
+<a name="connect_ex">
+</a></p><h3><a name="connect_ex">Examples of Connecting to Databases</a></h3>
+<h4><a name="connect_ex">MySQL and Most Other Database Drivers</a></h4>
+<p><a name="connect_ex">MySQL connections are very straightforward, and the parameters are identical 
+  to mysql_connect:</a></p>
+<pre><a name="connect_ex">	$conn = &amp;ADONewConnection('mysql'); <br>	$conn-&gt;PConnect('localhost','userid','password','database');<br>	<br>	<font color="#008000"># or dsn </font>
+	$dsn = 'mysql://user:pwd@localhost/mydb'; 
+	$conn = ADONewConnection($dsn);  # no need for Connect()
+	
+	<font color="#008000"># or persistent dsn</font>
+	$dsn = 'mysql://user:pwd@localhost/mydb?persist'; 
+	$conn = ADONewConnection($dsn);  # no need for PConnect()
+	
+	<font color="#008000"># a more complex example:</font>
+	$pwd = urlencode($pwd);
+	$flags =  MYSQL_CLIENT_COMPRESS;
+	$dsn = "mysql://user:$pwd@localhost/mydb?persist&amp;clientflags=$flags";
+	$conn = ADONewConnection($dsn);  # no need for PConnect()
+ </a></pre>
+<p><a name="connect_ex"> For most drivers, you can use the standard function: Connect($server, $user, $password, $database), or
+a </a><a href="dsnsupport">DSN</a> since ADOdb 4.51. Exceptions to this are listed below.
+</p>
+<a name=pdo>
+<h4>PDO</h4>
+<p>PDO, which only works with PHP5, accepts a driver specific connection string:
+<pre>
+	$conn =& NewADConnection('pdo');
+	$conn->Connect('mysql:host=localhost',$user,$pwd,$mydb);
+	$conn->Connect('mysql:host=localhost;dbname=mydb',$user,$pwd);
+	$conn->Connect("mysql:host=localhost;dbname=mydb;username=$user;password=$pwd");
+</pre>
+<p>The DSN mechanism is also supported:
+<pre>
+	$conn =& NewADConnection("pdo_mysql://user:pwd@localhost/mydb?persist"); # persist is optional
+</pre>
+<h4>PostgreSQL</h4>
+<p>PostgreSQL 7 and 8 accepts connections using: </p>
+<p>a. the standard connection string:</p>
+<pre>	$conn = &amp;ADONewConnection('postgres');  <br>	$conn-&gt;PConnect('host=localhost port=5432 dbname=mary');</pre>
+<p> b. the classical 4 parameters:</p>
+ <pre>	$conn-&gt;PConnect('localhost','userid','password','database');<br> </pre>
+<p>c. dsn:
+</p><pre>	$dsn = 'postgres://user:pwd@localhost/mydb?persist';  # persist is optional
+	$conn = ADONewConnection($dsn);  # no need for Connect/PConnect<br></pre>
+<a name="ldap"></a>
+
+ <h4>LDAP</h4>
+  <p>Here is an example of querying a LDAP server. Thanks to Josh Eldridge for the driver and this example:
+</p><pre>
+require('/path/to/adodb.inc.php');
+
+/* Make sure to set this BEFORE calling Connect() */
+$LDAP_CONNECT_OPTIONS = Array(
+	Array ("OPTION_NAME"=>LDAP_OPT_DEREF, "OPTION_VALUE"=>2),
+	Array ("OPTION_NAME"=>LDAP_OPT_SIZELIMIT,"OPTION_VALUE"=>100),
+	Array ("OPTION_NAME"=>LDAP_OPT_TIMELIMIT,"OPTION_VALUE"=>30),
+	Array ("OPTION_NAME"=>LDAP_OPT_PROTOCOL_VERSION,"OPTION_VALUE"=>3),
+	Array ("OPTION_NAME"=>LDAP_OPT_ERROR_NUMBER,"OPTION_VALUE"=>13),
+	Array ("OPTION_NAME"=>LDAP_OPT_REFERRALS,"OPTION_VALUE"=>FALSE),
+	Array ("OPTION_NAME"=>LDAP_OPT_RESTART,"OPTION_VALUE"=>FALSE)
+);
+$host = 'ldap.baylor.edu';
+$ldapbase = 'ou=People,o=Baylor University,c=US';
+
+$ldap = NewADOConnection( 'ldap' );
+$ldap->Connect( $host, $user_name='', $password='', $ldapbase );
+
+echo "&lt;pre>";
+
+print_r( $ldap->ServerInfo() );
+$ldap->SetFetchMode(ADODB_FETCH_ASSOC);
+$userName = 'eldridge';
+$filter="(|(CN=$userName*)(sn=$userName*)(givenname=$userName*)(uid=$userName*))";
+
+$rs = $ldap->Execute( $filter );
+if ($rs)
+	while ($arr = $rs->FetchRow()) {
+	     print_r($arr);	
+	}
+
+$rs = $ldap->Execute( $filter );
+if ($rs) 
+	while (!$rs->EOF) {
+ 		print_r($rs->fields);	
+		$rs->MoveNext();
+	} 
+	
+print_r( $ldap->GetArray( $filter ) );
+print_r( $ldap->GetRow( $filter ) );
+
+$ldap->Close();
+echo "&lt;/pre>";
+</pre>
+<p>Using DSN:
+<pre>
+$dsn = "ldap://ldap.baylor.edu/ou=People,o=Baylor University,c=US";
+$db = NewADOConnection($dsn);
+</pre>
+<h4>Interbase/Firebird</h4>
+You define the database in the $host parameter:
+<pre>	$conn = &amp;ADONewConnection('ibase'); <br>	$conn-&gt;PConnect('localhost:c:\ibase\employee.gdb','sysdba','masterkey');<br></pre>
+<p>Or dsn:
+</p><pre>	$dsn = 'firebird://user:pwd@localhost/mydb?persist&amp;dialect=3';  # persist is optional<br>	$conn = ADONewConnection($dsn);  # no need for Connect/PConnect<br></pre>
+<h4>SQLite</h4>
+Sqlite will create the database file if it does not exist.
+<pre>	$conn = &amp;ADONewConnection('sqlite');
+	$conn-&gt;PConnect('c:\path\to\sqlite.db'); # sqlite will create if does not exist<br></pre>
+<p>Or dsn:
+</p><pre>	$path = urlencode('c:\path\to\sqlite.db');
+	$dsn = "sqlite://$path/?persist";  # persist is optional
+	$conn = ADONewConnection($dsn);  # no need for Connect/PConnect<br></pre>
+<h4>Oracle (oci8)</h4>
+<p>With oci8, you can connect in multiple ways. Note that oci8 works fine with 
+newer versions of the Oracle, eg. 9i and 10g.</p>
+<p>a. PHP and Oracle reside on the same machine, use default SID.</p>
+<pre>	$conn-&gt;Connect(false, 'scott', 'tiger');</pre>
+<p>b. TNS Name defined in tnsnames.ora (or ONAMES or HOSTNAMES), eg. 'myTNS'</p>
+<pre>	$conn-&gt;PConnect(false, 'scott', 'tiger', 'myTNS');</pre>
+<p>or</p>
+<pre> 	$conn-&gt;PConnect('myTNS', 'scott', 'tiger');</pre>
+<p>c. Host Address and SID</p>
+<pre>
+	$conn->connectSID = true;
+	$conn-&gt;Connect('192.168.0.1', 'scott', 'tiger', 'SID');</pre>
+<p>d. Host Address and Service Name</p>
+<pre>	$conn-&gt;Connect('192.168.0.1', 'scott', 'tiger', 'servicename');</pre>
+<p>e. Oracle connection string:
+</p><pre>	$cstr = "(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=$host)(PORT=$port))<br>			(CONNECT_DATA=(SID=$sid)))";<br>	$conn-&gt;Connect($cstr, 'scott', 'tiger');<br></pre>
+<p>f. ADOdb dsn:
+</p><pre>	$dsn = 'oci8://user:pwd@tnsname/?persist';  # persist is optional<br>	$conn = ADONewConnection($dsn);  # no need for Connect/PConnect<br>	<br>	$dsn = 'oci8://user:pwd@host/sid';<br>	$conn = ADONewConnection($dsn);<br>	<br>	$dsn = 'oci8://user:pwd@/';   # oracle on local machine<br>	$conn = ADONewConnection($dsn);<br></pre>
+<p>You can also set the charSet for Oracle 9.2 and later, supported since PHP 4.3.2, ADOdb 4.54:
+</p><pre>	$conn-&gt;charSet = 'we8iso8859p1';<br>	$conn-&gt;Connect(...);<br>	<br>	# or<br>	$dsn = 'oci8://user:pwd@tnsname/?charset=WE8MSWIN1252';<br>	$db = ADONewConnection($dsn);<br></pre>
+<a name="dsnless"></a>
+<h4>DSN-less ODBC ( Access, MSSQL and DB2 examples)</h4>
+<p>ODBC DSN's can be created in the ODBC control panel, or you can use a DSN-less 
+  connection.To use DSN-less connections with ODBC you need PHP 4.3 or later. 
+</p>
+<p>For Microsoft Access:</p>
+<pre>	$db =&amp; ADONewConnection('access');<br>	$dsn = <strong>"Driver={Microsoft Access Driver (*.mdb)};Dbq=d:\\northwind.mdb;Uid=Admin;Pwd=;";</strong>
+	$db-&gt;Connect($dsn);
+</pre>
+For Microsoft SQL Server: 
+<pre>	$db =&amp; ADONewConnection('odbc_mssql');<br>	$dsn = <strong>"Driver={SQL Server};Server=localhost;Database=northwind;"</strong>;<br>	$db-&gt;Connect($dsn,'userid','password');<br></pre>
+or if you prefer to use the mssql extension (which is limited to mssql 6.5 functionality):
+<pre>	$db =&amp; ADONewConnection('mssql');<br>	$db-&gt;Execute('localhost', 'userid', 'password', 'northwind');<br></pre>
+For DB2:
+<pre>
+	$dbms = 'db2'; # or 'odbc_db2' if db2 extension not available
+	$db =&amp; ADONewConnection($dbms);
+	$dsn = "driver={IBM db2 odbc DRIVER};Database=sample;hostname=localhost;port=50000;protocol=TCPIP;".
+				"uid=root; pwd=secret";<br>	$db-&gt;Connect($dsn);
+</pre>
+<b>DSN-less Connections with ADO</b><br>
+If you are using versions of PHP earlier than PHP 4.3.0, DSN-less connections 
+only work with Microsoft's ADO, which is Microsoft's COM based API. An example 
+using the ADOdb library and Microsoft's ADO: 
+<pre>&lt;?php<br>	include('adodb.inc.php'); <br>	$db = &amp;ADONewConnection("ado_mssql");<br>	print "&lt;h1&gt;Connecting DSN-less $db-&gt;databaseType...&lt;/h1&gt;";<br>		<br>	<b>$myDSN="PROVIDER=MSDASQL;DRIVER={SQL Server};"<br>		. "SERVER=flipper;DATABASE=ai;UID=sa;PWD=;"  ;</b>
+	$db-&gt;Connect($myDSN);
+	
+	$rs = $db-&gt;Execute("select * from table");
+	$arr = $rs-&gt;GetArray();
+	print_r($arr);
+?&gt;
+</pre><a name="speed"></a>
+<h2>High Speed ADOdb - tuning tips</h2>
+<p>ADOdb is a big class library, yet it <a href="http://phplens.com/lens/adodb/">consistently beats</a> all other PHP class 
+  libraries in performance. This is because it is designed in a layered fashion, 
+  like an onion, with the fastest functions in the innermost layer. Stick to the 
+  following functions for best performance:</p>
+<table align="center" border="1" width="40%">
+  <tbody><tr>
+    <td><div align="center"><b>Innermost Layer</b></div></td>
+  </tr>
+  <tr> 
+    <td><p align="center">Connect, PConnect, NConnect<br>
+        Execute, CacheExecute<br>
+        SelectLimit, CacheSelectLimit<br>
+        MoveNext, Close <br>
+		qstr, Affected_Rows, Insert_ID</p></td>
+  </tr>
+</tbody></table>
+<p>The fastest way to access the field data is by accessing the array $recordset-&gt;fields 
+  directly. Also set the global variables <a href="#adodb_fetch_mode">$ADODB_FETCH_MODE</a> 
+  = ADODB_FETCH_NUM, and (for oci8, ibase/firebird and odbc) <a href="#adodb_countrecs">$ADODB_COUNTRECS</a> = false 
+  before you connect to your database.</p>
+<p>Consider using bind parameters if your database supports it, as it improves 
+  query plan reuse. Use ADOdb's performance tuning system to identify bottlenecks 
+  quickly. At the time of writing (Dec 2003), this means oci8 and odbc drivers.</p>
+ <p>Lastly make sure you have a PHP accelerator cache installed such as APC, Turck 
+  MMCache, Zend Accelerator or ionCube.</p>
+ <p>Some examples:</p>
+ <table align="center" border="1"><tbody><tr><td><b>Fastest data retrieval using PHP</b></td><td><b>Fastest data retrieval using ADOdb extension</b></td></tr>
+<tr><td>
+<pre>$rs =&amp; $rs-&gt;Execute($sql);<br>while (!$rs-&gt;EOF) {<br>	var_dump($rs-&gt;fields);<br>	$rs-&gt;MoveNext();<br>}</pre></td><td>
+<pre>$rs =&amp; $rs-&gt;Execute($sql);<br>$array = adodb_getall($rs);<br>var_dump($array);<br><br><br></pre></td></tr></tbody></table>
+ <p><b>Advanced Tips</b>
+ </p><p>If you have the <a href="http://adodb.sourceforge.net/#extension">ADOdb C extension</a> installed, 
+ you can replace your calls to $rs-&gt;MoveNext() with adodb_movenext($rs). 
+ This doubles the speed of this operation. For retrieving entire recordsets at once,
+use GetArray(), which uses the high speed extension function adodb_getall($rs) internally.
+ </p><p>Execute() is the default way to run queries. You can use the low-level functions _Execute() and _query()
+to reduce query overhead.  Both these functions share the same parameters as Execute().
+</p><p>If you do not have any bind parameters or your database supports
+binding (without emulation),
+then you can call _Execute() directly. Calling this function bypasses
+bind emulation. Debugging is still supported in _Execute().
+</p><p>If you do not require debugging facilities nor emulated
+binding, and do not require a recordset to be returned, then you can
+call _query. This is great for inserts, updates and deletes. Calling
+this function
+bypasses emulated binding, debugging, and recordset handling. Either
+the resultid, true or false are returned by _query(). </p><p>For Informix, you can disable scrollable cursors with $db-&gt;cursorType = 0.
+</p><p><a name="hack"></a> </p>
+<h2>Hacking ADOdb Safely</h2>
+<p>You might want to modify ADOdb for your own purposes. Luckily you can
+still maintain backward compatibility by sub-classing ADOdb and using the $ADODB_NEWCONNECTION
+variable. $ADODB_NEWCONNECTION allows you to override the behaviour of ADONewConnection().
+ADOConnection() checks for this variable and will call
+the function-name stored in this variable if it is defined.
+</p><p>In the following example, new functionality for the connection object 
+is placed in the <i>hack_mysql</i> and <i>hack_postgres7</i> classes. The recordset class naming convention
+can be controlled using $rsPrefix. Here we set it to 'hack_rs_', which will make ADOdb use
+<i>hack_rs_mysql</i> and <i>hack_rs_postgres7</i> as the recordset classes.
+
+
+</p><pre>class hack_mysql extends adodb_mysql {<br>var $rsPrefix = 'hack_rs_';<br>  /* Your mods here */<br>}<br><br>class hack_rs_mysql extends ADORecordSet_mysql {<br>	 /* Your mods here */<br>}<br><br>class hack_postgres7 extends adodb_postgres7 {<br>var $rsPrefix = 'hack_rs_';<br>  /* Your mods here */<br>}<br><br>class hack_rs_postgres7 extends ADORecordSet_postgres7 {<br> /* Your mods here */<br>}<br><br>$ADODB_NEWCONNECTION = 'hack_factory';<br><br>function&amp; hack_factory($driver)<br>{<br>	if ($driver !== 'mysql' &amp;&amp; $driver !== 'postgres7') return false;<br>	<br>	$driver = 'hack_'.$driver;<br>	$obj = new $driver();<br>	return $obj;<br>}<br><br>include_once('adodb.inc.php');<br></pre>
+<p></p><p>Don't forget to call the constructor of the parent class in
+your constructor. If you want to use the default ADOdb drivers return
+false in the above hack_factory() function.
+<a name="php5"></a>
+</p><h2>PHP5 Features</h2>
+ ADOdb 4.02 or later will transparently determine which version of PHP you are using.
+If PHP5 is detected, the following features become available:
+<ul>
+
+<li><b>PDO</b>: PDO drivers are available. See the <a href=#pdo>connection examples</a>. Currently PDO drivers are
+ not as powerful as native drivers, and should be treated as experimental.<br><br>
+<a name="php5iterators"></a>
+<li><b>Foreach iterators</b>: This is a very natural way of going through a recordset:
+<pre>	$ADODB_FETCH_MODE = ADODB_FETCH_NUM;<br>	$rs = $db-&gt;Execute($sql);<br>	foreach($rs as $k =&gt; $row) {<br>		echo "r1=".$row[0]." r2=".$row[1]."&lt;br&gt;";<br>	}<br></pre>
+<p>
+<a name="php5exceptions"></a>
+</p></li><li><b>Exceptions</b>: Just include <i>adodb-exceptions.inc.php</i> and you can now 
+catch exceptions on errors as they occur.
+<pre>	<b>include("../adodb-exceptions.inc.php");</b> <br>	include("../adodb.inc.php");	 <br>	try { <br>		$db = NewADOConnection("oci8"); <br>		$db-&gt;Connect('','scott','bad-password'); <br>	} catch (exception $e) { <br>		var_dump($e); <br>		adodb_backtrace($e-&gt;gettrace());<br>	} <br></pre>
+<p>Note that reaching EOF is <b>not</b> considered an error nor an exception.
+</p></li></ul> 
+<h3><a name="drivers"></a>Databases Supported</h3>
+The <i>name</i> below is the value you pass to NewADOConnection($name) to create a  connection object for that database.
+<p>
+</p><p> 
+</p><table border="1" width="100%">
+  <tbody><tr valign="top"> 
+    <td><b>Name</b></td>
+    <td><b>Tested</b></td>
+    <td><b>Database</b></td>
+    <td><b><font size="2">RecordCount() usable</font></b></td>
+    <td><b>Prerequisites</b></td>
+    <td><b>Operating Systems</b></td>
+  </tr>
+  <tr valign="top"> 
+    <td><b><font size="2">access</font></b></td>
+    <td><font size="2">B</font></td>
+    <td><font size="2">Microsoft Access/Jet. You need to create an ODBC DSN.</font></td>
+    <td><font size="2">Y/N</font></td>
+    <td><font size="2">ODBC </font></td>
+    <td><font size="2">Windows only</font></td>
+  </tr>
+  <tr valign="top"> 
+    <td><b><font size="2">ado</font></b></td>
+    <td><font size="2">B</font></td>
+    <td><p><font size="2">Generic ADO, not tuned for specific databases. Allows 
+        DSN-less connections. For best performance, use an OLEDB provider. This 
+        is the base class for all ado drivers.</font></p>
+      <p><font size="2">You can set $db-&gt;codePage before connecting.</font></p></td>
+    <td><font size="2">? depends on database</font></td>
+    <td><font size="2">ADO or OLEDB provider</font></td>
+    <td><font size="2">Windows only</font></td>
+  </tr>
+  <tr valign="top"> 
+    <td><b><font size="2">ado_access</font></b></td>
+    <td><font size="2">B</font></td>
+    <td><font size="2">Microsoft Access/Jet using ADO. Allows DSN-less connections. 
+      For best performance, use an OLEDB provider.</font></td>
+    <td><font size="2">Y/N</font></td>
+    <td><font size="2">ADO or OLEDB provider</font></td>
+    <td><font size="2">Windows only</font></td>
+  </tr>
+  <tr valign="top"> 
+    <td><b><font size="2">ado_mssql</font></b></td>
+    <td><font size="2">B</font></td>
+    <td><font size="2">Microsoft SQL Server using ADO. Allows DSN-less connections. 
+      For best performance, use an OLEDB provider.</font></td>
+    <td><font size="2">Y/N</font></td>
+    <td><font size="2">ADO or OLEDB provider</font></td>
+    <td><font size="2">Windows only</font></td>
+  </tr>
+    <tr valign="top"> 
+    <td height="54"><b><font size="2">db2</font></b></td>
+    <td height="54"><font size="2">C</font></td>
+    <td height="54"><font size="2">Uses PHP's db2-specific extension for better performance.</font></td>
+    <td height="54"><font size="2">Y/N</font></td>
+    <td height="54"><font size="2">DB2 CLI/ODBC interface</font></td>
+    <td height="54"> <p><font size="2">Unix and Windows. Requires IBM DB2 Universal Database client.</font></p></td>
+  </tr>
+  <tr valign="top"> 
+    <td height="54"><b><font size="2">odbc_db2</font></b></td>
+    <td height="54"><font size="2">C</font></td>
+    <td height="54"><font size="2">Connects to DB2 using generic ODBC extension.</font></td>
+    <td height="54"><font size="2">Y/N</font></td>
+    <td height="54"><font size="2">DB2 CLI/ODBC interface</font></td>
+    <td height="54"> <p><font size="2">Unix and Windows. <a href="http://www.faqts.com/knowledge_base/view.phtml/aid/6283/fid/14">Unix 
+        install hints</a>. I have had reports that the $host and $database params have to be reversed in Connect() when using the CLI interface.</font></p></td>
+  </tr>
+  <tr valign="top"> 
+    <td><b><font size="2">vfp</font></b></td>
+    <td><font size="2">A</font></td>
+    <td><font size="2">Microsoft Visual FoxPro. You need to create an ODBC DSN.</font></td>
+    <td><font size="2">Y/N</font></td>
+    <td><font size="2">ODBC</font></td>
+    <td><font size="2">Windows only</font></td>
+  </tr>
+  <tr valign="top"> 
+    <td><b><font size="2">fbsql</font></b></td>
+    <td><font size="2">C</font></td>
+    <td><font size="2">FrontBase. </font></td>
+    <td><font size="2">Y</font></td>
+    <td><font size="2">?</font></td>
+    <td> <p><font size="2">Unix and Windows</font></p></td>
+  </tr>
+  <tr valign="top"> 
+    <td><b><font size="2">ibase</font></b></td>
+    <td><font size="2">B</font></td>
+    <td><font size="2">Interbase 6 or earlier. Some users report you might need 
+      to use this<br>
+      $db-&gt;PConnect('localhost:c:/ibase/employee.gdb', "sysdba", "masterkey") 
+      to connect. Lacks Affected_Rows currently.<br>
+      <br>
+      You can set $db-&gt;role, $db-&gt;dialect, $db-&gt;buffers and $db-&gt;charSet before connecting.</font></td>
+    <td><font size="2">Y/N</font></td>
+    <td><font size="2">Interbase client</font></td>
+    <td><font size="2">Unix and Windows</font></td>
+  </tr>
+  <tr valign="top"> 
+    <td><b><i><font size="2">firebird</font></i></b></td>
+    <td><font size="2">C</font></td>
+    <td><font size="2">Firebird version of interbase.</font></td>
+    <td><font size="2">Y/N</font></td>
+    <td><font size="2">Interbase client</font></td>
+    <td><font size="2">Unix and Windows</font></td>
+  </tr>
+  <tr valign="top"> 
+    <td><b><i><font size="2">borland_ibase</font></i></b></td>
+    <td><font size="2">C</font></td>
+    <td><font size="2">Borland version of Interbase 6.5 or later. Very sad that 
+      the forks differ.</font></td>
+    <td><font size="2">Y/N</font></td>
+    <td><font size="2">Interbase client</font></td>
+    <td><font size="2">Unix and Windows</font></td>
+  </tr>
+
+  <tr valign="top"> 
+    <td><b><font size="2">informix</font></b></td>
+    <td><font size="2">C</font></td>
+    <td><font size="2">Generic informix driver. Use this if you are using Informix 7.3 or later.</font></td>
+    <td><font size="2">Y/N</font></td>
+    <td><font size="2">Informix client</font></td>
+    <td><font size="2">Unix and Windows</font></td>
+  </tr>
+  <tr valign="top"> 
+    <td><b><font size="2">informix72</font></b></td>
+    <td><font size="2">C</font></td>
+    <td><font size="2"> Informix databases before Informix 7.3 that do no support 
+      SELECT FIRST.</font></td>
+    <td><font size="2">Y/N</font></td>
+    <td><font size="2">Informix client</font></td>
+    <td><font size="2">Unix and Windows</font></td>
+  </tr>
+  <tr valign="top"> 
+    <td><b><font size="2">ldap</font></b></td>
+    <td><font size="2">C</font></td>
+    <td><font size="2">LDAP driver. See this example for usage information.</font></td>
+    <td>&nbsp;</td>
+    <td><font size="2">LDAP extension</font></td>
+    <td><font size="2">?</font></td>
+  </tr>
+  <tr valign="top"> 
+    <td height="73"><b><font size="2">mssql</font></b></td>
+    <td height="73"><font size="2">A</font></td>
+    <td height="73"> <p><font size="2">Microsoft SQL Server 7 and later. Works 
+        with Microsoft SQL Server 2000 also. Note that date formating is problematic 
+        with this driver. For example, the PHP mssql extension does not return 
+        the seconds for datetime!</font></p></td>
+    <td height="73"><font size="2">Y/N</font></td>
+    <td height="73"><font size="2">Mssql client</font></td>
+    <td height="73"> <p><font size="2">Unix and Windows. <br>
+        <a href="http://phpbuilder.com/columns/alberto20000919.php3">Unix install 
+        howto</a> and <a href="http://linuxjournal.com/article.php?sid=6636&amp;mode=thread&amp;order=0">another 
+        one</a>. </font></p></td>
+  </tr>
+  <tr valign="top"> 
+    <td height="73"><b><font size="2">mssqlpo</font></b></td>
+    <td height="73"><font size="2">A</font></td>
+    <td height="73"> <p><font size="2">Portable mssql driver. Identical to above 
+        mssql driver, except that '||', the concatenation operator, is converted 
+        to '+'. Useful for porting scripts from most other sql variants that use 
+        ||.</font></p></td>
+    <td height="73"><font size="2">Y/N</font></td>
+    <td height="73"><font size="2">Mssql client</font></td>
+    <td height="73"> <p><font size="2">Unix and Windows. <a href="http://phpbuilder.com/columns/alberto20000919.php3"><br>
+        Unix install howto</a>.</font></p></td>
+  </tr>
+  <tr valign="top"> 
+    <td><b><font size="2">mysql</font></b></td>
+    <td><font size="2">A</font></td>
+    <td><font size="2">MySQL without transaction support. You can also set $db-&gt;clientFlags 
+      before connecting.</font></td>
+    <td><font size="2">Y</font></td>
+    <td><font size="2">MySQL client</font></td>
+    <td><font size="2">Unix and Windows</font></td>
+  </tr>
+  <tr valign="top"> 
+    <td><font size="2"><b>mysqlt</b> or <b>maxsql</b></font></td>
+    <td><font size="2">A</font></td>
+    <td> <p><font size="2">MySQL with transaction support. We recommend using 
+        || as the concat operator for best portability. This can be done by running 
+        MySQL using: <br>
+        <i>mysqld --ansi</i> or <i>mysqld --sql-mode=PIPES_AS_CONCAT</i></font></p></td>
+    <td><font size="2">Y/N</font></td>
+    <td><font size="2">MySQL client</font></td>
+    <td><font size="2">Unix and Windows</font></td>
+  </tr>
+  <tr valign="top"> 
+    <td><b><font size="2">oci8</font></b></td>
+    <td><font size="2">A</font></td>
+    <td><font size="2">Oracle 8/9. Has more functionality than <i>oracle</i> driver 
+      (eg. Affected_Rows). You might have to putenv('ORACLE_HOME=...') before 
+      Connect/PConnect. </font> <p><font size="2"> There are 2 ways of connecting 
+        - with server IP and service name: <br>
+        <i>PConnect('serverip:1521','scott','tiger','service'</i>)<br>
+        or using an entry in TNSNAMES.ORA or ONAMES or HOSTNAMES: <br>
+        <i>PConnect(false, 'scott', 'tiger', $oraname)</i>. </font> 
+      </p><p><font size="2">Since 2.31, we support Oracle REF cursor variables directly 
+        (see <a href="#executecursor">ExecuteCursor</a>).</font> </p></td>
+    <td><font size="2">Y/N</font></td>
+    <td><font size="2">Oracle client</font></td>
+    <td><font size="2">Unix and Windows</font></td>
+  </tr>
+  <tr valign="top"> 
+    <td><b><font size="2">oci805</font></b></td>
+    <td><font size="2">C</font></td>
+    <td><font size="2">Supports reduced Oracle functionality for Oracle 8.0.5. 
+      SelectLimit is not as efficient as in the oci8 or oci8po drivers.</font></td>
+    <td><font size="2">Y/N</font></td>
+    <td><font size="2">Oracle client</font></td>
+    <td><font size="2">Unix and Windows</font></td>
+  </tr>
+  <tr valign="top"> 
+    <td><b><font size="2">oci8po</font></b></td>
+    <td><font size="2">A</font></td>
+    <td><font size="2">Oracle 8/9 portable driver. This is nearly identical with 
+      the oci8 driver except (a) bind variables in Prepare() use the ? convention, 
+      instead of :bindvar, (b) field names use the more common PHP convention 
+      of lowercase names. </font> <p><font size="2">Use this driver if porting 
+        from other databases is important. Otherwise the oci8 driver offers better 
+        performance. </font> </p></td>
+    <td><font size="2">Y/N</font></td>
+    <td><font size="2">Oracle client</font></td>
+    <td><font size="2">Unix and Windows</font></td>
+  </tr>
+  <tr valign="top"> 
+    <td><b><font size="2">odbc</font></b></td>
+    <td><font size="2">A</font></td>
+    <td><font size="2">Generic ODBC, not tuned for specific databases. To connect, 
+      use <br>
+      PConnect('DSN','user','pwd'). This is the base class for all odbc derived 
+      drivers.</font></td>
+    <td><font size="2">? depends on database</font></td>
+    <td><font size="2">ODBC</font></td>
+    <td><font size="2">Unix and Windows. <a href="http://phpbuilder.com/columns/alberto20000919.php3?page=4">Unix 
+      hints.</a></font></td>
+  </tr>
+  <tr valign="top"> 
+    <td><b><font size="2">odbc_mssql</font></b></td>
+    <td><font size="2">C</font></td>
+    <td><font size="2">Uses ODBC to connect to MSSQL</font></td>
+    <td><font size="2">Y/N</font></td>
+    <td><font size="2">ODBC</font></td>
+    <td><font size="2">Unix and Windows. </font></td>
+  </tr>
+  <tr valign="top"> 
+    <td><b><font size="2">odbc_oracle</font></b></td>
+    <td><font size="2">C</font></td>
+    <td><font size="2">Uses ODBC to connect to Oracle</font></td>
+    <td><font size="2">Y/N</font></td>
+    <td><font size="2">ODBC</font></td>
+    <td><font size="2">Unix and Windows. </font></td>
+  </tr>
+    
+  <tr valign="top"> 
+    <td><b><font size="2">odbtp</font></b></td>
+    <td><font size="2">C</font></td>
+    <td><font size="2">Generic odbtp driver. <a href="http://odbtp.sourceforge.net/">Odbtp</a> is a software for
+	accessing Windows ODBC data sources from other operating systems.</font></td>
+    <td><font size="2">Y/N</font></td>
+    <td><font size="2">odbtp</font></td>
+    <td><font size="2">Unix and Windows</font></td>
+  </tr>
+  <tr valign="top"> 
+    <td><b><font size="2">odbtp_unicode</font></b></td>
+    <td><font size="2">C</font></td>
+    <td><font size="2">Odtbp with unicode support</font></td>
+    <td><font size="2">Y/N</font></td>
+    <td><font size="2">odbtp</font></td>
+    <td><font size="2">Unix and Windows</font></td>
+  </tr>
+  <tr valign="top"> 
+    <td height="34"><b><font size="2">oracle</font></b></td>
+    <td height="34"><font size="2">C</font></td>
+    <td height="34"><font size="2">Implements old Oracle 7 client API. Use oci8 
+      driver if possible for better performance.</font></td>
+    <td height="34"><font size="2">Y/N</font></td>
+    <td height="34"><font size="2">Oracle client</font></td>
+    <td height="34"><font size="2">Unix and Windows</font></td>
+  </tr>
+  <tr valign="top"> 
+    <td height="34"><b><font size="2">netezza</font></b></td>
+    <td height="34"><font size="2">C</font></td>
+    <td height="34"><font size="2">Netezza driver. Netezza is based on postgres code-base.</font></td>
+    <td height="34"><font size="2">Y</font></td>
+    <td height="34"><font size="2">?</font></td>
+    <td height="34"><font size="2">?</font></td>
+  </tr>
+     <tr valign="top"> 
+    <td><b><font size="2">pdo</font></b></td>
+    <td><font size="2">C</font></td>
+    <td><font size="2">Generic PDO driver for PHP5. </font></td>
+    <td><font size="2">Y</font></td>
+    <td><font size="2">PDO extension and database specific drivers</font></td>
+    <td><font size="2">Unix and Windows. </font></td>
+  </tr>
+  <tr valign="top"> 
+    <td><b><font size="2">postgres</font></b></td>
+    <td><font size="2">A</font></td>
+    <td><font size="2">Generic PostgreSQL driver. Currently identical to postgres7 
+      driver.</font></td>
+    <td><font size="2">Y</font></td>
+    <td><font size="2">PostgreSQL client</font></td>
+    <td><font size="2">Unix and Windows. </font></td>
+  </tr>
+  <tr valign="top"> 
+    <td><b><font size="2">postgres64</font></b></td>
+    <td><font size="2">A</font></td>
+    <td><font size="2">For PostgreSQL 6.4 and earlier which does not support LIMIT 
+      internally.</font></td>
+    <td><font size="2">Y</font></td>
+    <td><font size="2">PostgreSQL client</font></td>
+    <td><font size="2">Unix and Windows. </font></td>
+  </tr>
+  <tr valign="top"> 
+    <td><b><font size="2">postgres7</font></b></td>
+    <td><font size="2">A</font></td>
+    <td><font size="2">PostgreSQL which supports LIMIT and other version 7 functionality.</font></td>
+    <td><font size="2">Y</font></td>
+    <td><font size="2">PostgreSQL client</font></td>
+    <td><font size="2">Unix and Windows. </font></td>
+  </tr>
+    <tr valign="top"> 
+    <td><b><font size="2">postgres8</font></b></td>
+    <td><font size="2">A</font></td>
+    <td><font size="2">PostgreSQL which supports version 8 functionality.</font></td>
+    <td><font size="2">Y</font></td>
+    <td><font size="2">PostgreSQL client</font></td>
+    <td><font size="2">Unix and Windows. </font></td>
+  </tr>
+  <tr valign="top"> 
+    <td><b><font size="2">sapdb</font></b></td>
+    <td><font size="2">C</font></td>
+    <td><font size="2">SAP DB. Should work reliably as based on ODBC driver.</font></td>
+    <td><font size="2">Y/N</font></td>
+    <td><font size="2">SAP ODBC client</font></td>
+    <td> <p><font size="2">?</font></p></td>
+  </tr>
+  <tr valign="top"> 
+    <td><b><font size="2">sqlanywhere</font></b></td>
+    <td><font size="2">C</font></td>
+    <td><font size="2">Sybase SQL Anywhere. Should work reliably as based on ODBC 
+      driver.</font></td>
+    <td><font size="2">Y/N</font></td>
+    <td><font size="2">SQL Anywhere ODBC client</font></td>
+    <td> <p><font size="2">?</font></p></td>
+  </tr>
+  <tr valign="top"> 
+    <td height="54"><b><font size="2">sqlite</font></b></td>
+    <td height="54"><font size="2">B</font></td>
+    <td height="54"><font size="2">SQLite.</font></td>
+    <td height="54"><font size="2">Y</font></td>
+    <td height="54"><font size="2">-</font></td>
+    <td height="54"> <p><font size="2">Unix and Windows.</font></p></td>
+  </tr>
+    <tr valign="top"> 
+    <td height="54"><b><font size="2">sqlitepo</font></b></td>
+    <td height="54"><font size="2">B</font></td>
+    <td height="54"><font size="2">Portable SQLite driver.  This is because assoc mode does not work like other drivers in sqlite.
+   Namely, when selecting (joining) multiple tables, the table
+   	  names are included in the assoc keys in the "sqlite" driver.</font><p>
+<font size="2">	  In "sqlitepo" driver, the table names are stripped from the returned column names. 
+	  When this results in a conflict,  the first field get preference.
+	  </font></p></td>
+    <td height="54"><font size="2">Y</font></td>
+    <td height="54"><font size="2">-</font></td>
+    <td height="54"> <p><font size="2">Unix and Windows.</font></p></td>
+  </tr>
+ 
+	  
+  <tr valign="top"> 
+    <td><b><font size="2">sybase</font></b></td>
+    <td><font size="2">C</font></td>
+    <td><font size="2">Sybase. </font></td>
+    <td><font size="2">Y/N</font></td>
+    <td><font size="2">Sybase client</font></td>
+    <td> <p><font size="2">Unix and Windows.</font></p></td>
+  </tr>
+  
+    <tr valign="top"> 
+    <td><b><font size="2">sybase_ase</font></b></td>
+    <td><font size="2">C</font></td>
+    <td><font size="2">Sybase ASE. </font></td>
+    <td><font size="2">Y/N</font></td>
+    <td><font size="2">Sybase client</font></td>
+    <td> <p><font size="2">Unix and Windows.</font></p></td>
+  </tr>
+  </tbody></table>
+
+<p></p><p>The "Tested" column indicates how extensively the code has been tested 
+  and used. <br>
+  A = well tested and used by many people<br>
+  B = tested and usable, but some features might not be implemented<br>
+  C = user contributed or experimental driver. Might not fully support all of 
+  the latest features of ADOdb. </p>
+<p>The column "RecordCount() usable" indicates whether RecordCount() 
+  return the number of rows, or returns -1 when a SELECT statement is executed. 
+  If this column displays Y/N then the RecordCount() is emulated when the global 
+  variable $ADODB_COUNTRECS=true (this is the default). Note that for large recordsets, 
+  it might be better to disable RecordCount() emulation because substantial amounts 
+  of memory are required to cache the recordset for counting. Also there is a 
+  speed penalty of 40-50% if emulation is required. This is emulated in most databases 
+  except for PostgreSQL and MySQL. This variable is checked every time a query 
+  is executed, so you can selectively choose which recordsets to count.</p>
+<p> 
+</p><hr />
+<h1>Tutorials<a name="quickstart"></a></h1>
+<h3>Example 1: Select Statement<a name="ex1"></a></h3>
+<p>Task: Connect to the Access Northwind DSN, display the first 2 columns of each 
+  row.</p>
+<p>In this example, we create a ADOConnection object, which represents the connection 
+  to the database. The connection is initiated with <a href="#pconnect"><font face="Courier New, Courier, mono">PConnect</font></a>, 
+  which is a persistent connection. Whenever we want to query the database, we 
+  call the <font face="Courier New, Courier, mono">ADOConnection.<a href="#execute">Execute</a>()</font> 
+  function. This returns an ADORecordSet object which is actually a cursor that 
+  holds the current row in the array <font face="Courier New, Courier, mono">fields[]</font>. 
+  We use <font face="Courier New, Courier, mono"><a href="#movenext">MoveNext</a>()</font> 
+  to move from row to row.</p>
+<p>NB: A useful function that is not used in this example is <font face="Courier New, Courier, mono"><a href="#selectlimit">SelectLimit</a></font>, 
+  which allows us to limit the number of rows shown. 
+</p><pre>&lt;?<br><font face="Courier New, Courier, mono"><b>include</b>('adodb.inc.php');	   # load code common to ADOdb<br>$<font color="#660000">conn</font> = &amp;ADONewConnection('access');	# create a connection<br>$<font color="#660000">conn</font>-&gt;PConnect('northwind');   # connect to MS-Access, northwind DSN<br>$<font color="#660000">recordSet</font> = &amp;$<font color="#660000">conn</font>-&gt;Execute('select * from products');<br>if (!$<font color="#660000">recordSet</font>) <br>	print $<font color="#660000">conn</font>-&gt;ErrorMsg();<br>else<br><b>while</b> (!$<font color="#660000">recordSet</font>-&gt;EOF) {<br>	<b>print</b> $<font color="#660000">recordSet</font>-&gt;fields[0].' '.$<font color="#660000">recordSet</font>-&gt;fields[1].'&lt;BR&gt;';<br>	$<font color="#660000">recordSet</font>-&gt;MoveNext();<br>}</font><font face="Courier New, Courier, mono">
+
+$<font color="#660000">recordSet</font>-&gt;Close(); # optional<br>$<font color="#660000">conn</font>-&gt;Close(); # optional<br></font>
+?&gt;
+</pre>
+<p>The $<font face="Courier New, Courier, mono">recordSet</font> returned stores 
+  the current row in the <font face="Courier New, Courier, mono">$recordSet-&gt;fields</font> 
+  array, indexed by column number (starting from zero). We use the <font face="Courier New, Courier, mono"><a href="#movenext">MoveNext</a>()</font> 
+  function to move to the next row. The <font face="Courier New, Courier, mono">EOF</font> 
+  property is set to true when end-of-file is reached. If an error occurs in Execute(), 
+  we return false instead of a recordset.</p>
+<p>The <code>$recordSet-&gt;fields[]</code> array is generated by the PHP database 
+  extension. Some database extensions only index by number and do not index the 
+  array by field name. To force indexing by name - that is associative arrays 
+  - use the SetFetchMode function. Each recordset saves and uses whatever fetch 
+  mode was set when the recordset was created in Execute() or SelectLimit(). 
+</p><pre>	$db-&gt;SetFetchMode(ADODB_FETCH_NUM);<br>	$rs1 = $db-&gt;Execute('select * from table');<br>	$db-&gt;SetFetchMode(ADODB_FETCH_ASSOC);<br>	$rs2 = $db-&gt;Execute('select * from table');<br>	print_r($rs1-&gt;fields); # shows <i>array([0]=&gt;'v0',[1] =&gt;'v1')</i>
+	print_r($rs2-&gt;fields); # shows <i>array(['col1']=&gt;'v0',['col2'] =&gt;'v1')</i>
+</pre>
+<p> </p>
+<p>To get the number of rows in the select statement, you can use <font face="Courier New, Courier, mono">$recordSet-&gt;<a href="#recordcount">RecordCount</a>()</font>. 
+  Note that it can return -1 if the number of rows returned cannot be determined.</p>
+<h3>Example 2: Advanced Select with Field Objects<a name="ex2"></a></h3>
+<p>Select a table, display the first two columns. If the second column is a date 
+  or timestamp, reformat the date to US format.</p>
+<pre>&lt;?<br><font face="Courier New, Courier, mono"><b>include</b>('adodb.inc.php');	   # load code common to ADOdb<br>$<font color="#660000">conn</font> = &amp;ADONewConnection('access');	# create a connection<br>$<font color="#660000">conn</font>-&gt;PConnect('northwind');   # connect to MS-Access, northwind dsn<br>$<font color="#660000">recordSet</font> = &amp;$<font color="#660000">conn</font>-&gt;Execute('select CustomerID,OrderDate from Orders');<br>if (!$<font color="#660000">recordSet</font>) <br>	print $<font color="#660000">conn</font>-&gt;ErrorMsg();<br>else<br><b>while</b> (!$<font color="#660000">recordSet</font>-&gt;EOF) {<br>	$<font color="#660000">fld</font> = <font color="#336600"><b>$</b><font color="#660000">recordSet</font><b>-&gt;FetchField</b></font><font color="#006600">(</font>1<font color="#006600">);</font>
+	$<font color="#660000">type</font> = <font color="#336600"><b>$</b><font color="#660000">recordSet</font><b>-&gt;MetaType</b></font>($fld-&gt;type);<br><br>	<b>if</b> ( $<font color="#660000">type</font> == 'D' || $<font color="#660000">type</font> == 'T') <br>		<b>print</b> $<font color="#660000">recordSet</font>-&gt;fields[0].' '.<br>			<b><font color="#336600">$</font></b><font color="#660000">recordSet</font><b><font color="#336600">-&gt;UserDate</font></b>($<font color="#660000">recordSet</font>-&gt;fields[1],'<b>m/d/Y</b>').'&lt;BR&gt;';<br>	<b>else </b>
+		<b>print</b> $<font color="#660000">recordSet</font>-&gt;fields[0].' '.$<font color="#660000">recordSet</font>-&gt;fields[1].'&lt;BR&gt;';<br><br>	$<font color="#660000">recordSet</font>-&gt;MoveNext();<br>}</font><font face="Courier New, Courier, mono">
+$<font color="#660000">recordSet</font>-&gt;Close(); # optional<br>$<font color="#660000">conn</font>-&gt;Close(); # optional<br></font>
+?&gt;
+</pre>
+<p>In this example, we check the field type of the second column using <font face="Courier New, Courier, mono"><a href="#fetchfield">FetchField</a>().</font> 
+  This returns an object with at least 3 fields.</p>
+<ul>
+  <li><b>name</b>: name of column</li>
+  <li> <b>type</b>: native field type of column</li>
+  <li> <b>max_length</b>: maximum length of field. Some databases such as MySQL 
+    do not return the maximum length of the field correctly. In these cases max_length 
+    will be set to -1.</li>
+</ul>
+<p>We then use <font face="Courier New, Courier, mono"><a href="#metatype">MetaType</a>()</font> 
+  to translate the native type to a <i>generic</i> type. Currently the following 
+  <i>generic</i> types are defined:</p>
+<ul>
+  <li><b>C</b>: character fields that should be shown in a &lt;input type="text"&gt; 
+    tag.</li>
+  <li><b>X</b>: TeXt, large text fields that should be shown in a &lt;textarea&gt;</li>
+  <li><b>B</b>: Blobs, or Binary Large Objects. Typically images. 
+  </li><li><b>D</b>: Date field</li>
+  <li><b>T</b>: Timestamp field</li>
+  <li><b>L</b>: Logical field (boolean or bit-field)</li>
+  <li><b>I</b>:&nbsp; Integer field</li>
+  <li><b>N</b>: Numeric field. Includes autoincrement, numeric, floating point, 
+    real and integer. </li>
+  <li><b>R</b>: Serial field. Includes serial, autoincrement integers. This works 
+    for selected databases. </li>
+</ul>
+<p>If the metatype is of type date or timestamp, then we print it using the user 
+  defined date format with <font face="Courier New, Courier, mono"><a href="#userdate">UserDate</a>(),</font> 
+  which converts the PHP SQL date string format to a user defined one. Another 
+  use for <font face="Courier New, Courier, mono"><a href="#metatype">MetaType</a>()</font> 
+  is data validation before doing an SQL insert or update.</p>
+<h3>Example 3: Inserting<a name="ex3"></a></h3>
+<p>Insert a row to the Orders table containing dates and strings that need to 
+  be quoted before they can be accepted by the database, eg: the single-quote 
+  in the word <i>John's</i>.</p>
+<pre>&lt;?<br><b>include</b>('adodb.inc.php');	   # load code common to ADOdb<br>$<font color="#660000">conn</font> = &amp;ADONewConnection('access');	# create a connection<br><br>$<font color="#660000">conn</font>-&gt;PConnect('northwind');   # connect to MS-Access, northwind dsn<br>$<font color="#660000">shipto</font> = <font color="#006600"><b>$conn-&gt;qstr</b></font>("<i>John's Old Shoppe</i>");<br><br>$<font color="#660000">sql</font> = "insert into orders (customerID,EmployeeID,OrderDate,ShipName) ";<br>$<font color="#660000">sql</font> .= "values ('ANATR',2,".<b><font color="#006600">$conn-&gt;DBDate(</font>time()<font color="#006600">)</font></b><font color="#006600">.</font>",$<font color="#660000">shipto</font>)";<br><br><b>if</b> ($<font color="#660000">conn</font>-&gt;Execute($<font color="#660000">sql</font>) <font color="#336600"><b>=== false</b></font>) {<br>	<b>print</b> 'error inserting: '.<font color="#336600"><b>$conn-&gt;ErrorMsg()</b></font>.'&lt;BR&gt;';<br>}<br>?&gt;<br></pre>
+<p>In this example, we see the advanced date and quote handling facilities of 
+  ADOdb. The unix timestamp (which is a long integer) is appropriately formated 
+  for Access with <font face="Courier New, Courier, mono"><a href="#dbdate">DBDate</a>()</font>, 
+  and the right escape character is used for quoting the <i>John's Old Shoppe</i>, 
+  which is<b> </b><i>John'<b>'</b>s Old Shoppe</i> and not PHP's default <i>John<b>'</b>s 
+  Old Shoppe</i> with <font face="Courier New, Courier, mono"><a href="#qstr">qstr</a>()</font>. 
+</p>
+<p>Observe the error-handling of the Execute statement. False is returned by<font face="Courier New, Courier, mono"> 
+  <a href="#execute">Execute</a>() </font>if an error occured. The error message 
+  for the last error that occurred is displayed in <font face="Courier New, Courier, mono"><a href="#errormsg">ErrorMsg</a>()</font>. 
+  Note: <i>php_track_errors</i> might have to be enabled for error messages to 
+  be saved.</p>
+<h3> Example 4: Debugging<a name="ex4"></a></h3>
+<pre>&lt;?<br><b>include</b>('adodb.inc.php');	   # load code common to ADOdb<br>$<font color="#663300">conn</font> = &amp;ADONewConnection('access');	# create a connection<br>$<font color="#663300">conn</font>-&gt;PConnect('northwind');   # connect to MS-Access, northwind dsn<br><font>$<font color="#663300">shipto</font> = <b>$conn-&gt;qstr</b>("John's Old Shoppe");<br>$<font color="#663300">sql</font> = "insert into orders (customerID,EmployeeID,OrderDate,ShipName) ";<br>$<font color="#663300">sql</font> .= "values ('ANATR',2,".$<font color="#663300">conn</font>-&gt;FormatDate(time()).",$shipto)";<br><b><font color="#336600">$<font color="#663300">conn</font>-&gt;debug = true;</font></b>
+<b>if</b> ($<font color="#663300">conn</font>-&gt;Execute($sql) <b>=== false</b>) <b>print</b> 'error inserting';</font>
+?&gt;
+</pre>
+<p>In the above example, we have turned on debugging by setting <b>debug = true</b>. 
+  This will display the SQL statement before execution, and also show any error 
+  messages. There is no need to call <font face="Courier New, Courier, mono"><a href="#errormsg">ErrorMsg</a>()</font> 
+  in this case. For displaying the recordset, see the <font face="Courier New, Courier, mono"><a href="#exrs2html">rs2html</a>() 
+  </font>example.</p>
+<p>Also see the section on <a href="#errorhandling">Custom Error Handlers</a>.</p>
+<h3>Example 5: MySQL and Menus<a name="ex5"></a></h3>
+<p>Connect to MySQL database <i>agora</i>, and generate a &lt;select&gt; menu 
+  from an SQL statement where the &lt;option&gt; captions are in the 1st column, 
+  and the value to send back to the server is in the 2nd column.</p>
+<pre>&lt;?<br><b>include</b>('adodb.inc.php'); # load code common to ADOdb<br>$<font color="#663300">conn</font> = &amp;ADONewConnection('mysql');  # create a connection<br>$<font color="#663300">conn</font>-&gt;PConnect('localhost','userid','','agora');# connect to MySQL, agora db<br><font>$<font color="#663300">sql</font> = 'select CustomerName, CustomerID from customers';<br>$<font color="#663300">rs</font> = $<font color="#663300">conn</font>-&gt;Execute($sql);<br><b>print</b> <b><font color="#336600">$<font color="#663300">rs</font>-&gt;GetMenu('GetCust','Mary Rosli');<br>?&gt;</font></b></font></pre>
+<p>Here we define a menu named GetCust, with the menu option 'Mary Rosli' selected. 
+  See <a href="#getmenu"><font face="Courier New, Courier, mono">GetMenu</font></a><font face="Courier New, Courier, mono">()</font>. 
+  We also have functions that return the recordset as an array: <font face="Courier New, Courier, mono"><a href="#getarray">GetArray</a>()</font>, 
+  and as an associative array with the key being the first column: <a href="#getassoc1">GetAssoc</a>().</p>
+<h3>Example 6: Connecting to 2 Databases At Once<a name="ex6"></a></h3>
+<pre>&lt;?<br><b>include</b>('adodb.inc.php');	 # load code common to ADOdb<br>$<font color="#663300">conn1</font> = &amp;ADONewConnection('mysql');  # create a mysql connection<br>$<font color="#663300">conn2</font> = &amp;ADONewConnection('oracle');  # create a oracle connection<br><br>$conn1-&gt;PConnect($server, $userid, $password, $database);<br>$conn2-&gt;PConnect(false, $ora_userid, $ora_pwd, $oraname);<br><br>$conn1-&gt;Execute('insert ...');<br>$conn2-&gt;Execute('update ...');<br>?&gt;</pre>
+<p> 
+</p><h3>Example 7: Generating Update and Insert SQL<a name="ex7"></a></h3>
+<p>Since ADOdb 4.56, we support <a href="reference.functions.getupdatesql.html#autoexecute">AutoExecute()</a>, 
+which simplifies things by providing an advanced wrapper for GetInsertSQL() and GetUpdateSQL(). For example,
+an INSERT can be carried out with:
+
+<pre>
+    $record["firstname"] = "Bob"; 
+    $record["lastname"] = "Smith"; 
+    $record["created"] = time(); 
+    $insertSQL = $conn->AutoExecute($rs, $record, 'INSERT'); 
+</pre>
+
+and an UPDATE with:
+<pre>
+    $record["firstname"] = "Caroline"; 
+    $record["lastname"] = "Smith"; # Update Caroline's lastname from Miranda to Smith 
+    $insertSQL = $conn->AutoExecute($rs, $record, 'UPDATE', 'id = 1'); 
+</pre>
+<p>
+The rest of this section is out-of-date:
+<p>ADOdb 1.31 and later supports two new recordset functions: GetUpdateSQL( ) and 
+GetInsertSQL( ). This allow you to perform a "SELECT * FROM table query WHERE...", 
+make a copy of the $rs-&gt;fields, modify the fields, and then generate the SQL to 
+update or insert into the table automatically. 
+<p> We show how the functions can be used when accessing a table with the following 
+  fields: (ID, FirstName, LastName, Created). 
+</p><p> Before these functions can be called, you need to initialize the recordset 
+  by performing a select on the table. Idea and code by Jonathan Younger jyounger#unilab.com. 
+ Since ADOdb 2.42, you can pass a  table name instead of a recordset into 
+GetInsertSQL (in $rs), and it will generate an insert statement for that table.
+</p><p> 
+</p><pre>&lt;?<br>#==============================================<br># SAMPLE GetUpdateSQL() and GetInsertSQL() code<br>#==============================================<br>include('adodb.inc.php');<br>include('tohtml.inc.php');<br><br>#==========================<br># This code tests an insert<br><br>$sql = "SELECT * FROM ADOXYZ WHERE id = -1"; <br># Select an empty record from the database<br><br>$conn = &amp;ADONewConnection("mysql");  # create a connection<br>$conn-&gt;debug=1;<br>$conn-&gt;PConnect("localhost", "admin", "", "test"); # connect to MySQL, testdb<br>$rs = $conn-&gt;Execute($sql); # Execute the query and get the empty recordset<br><br>$record = array(); # Initialize an array to hold the record data to insert<br><br># Set the values for the fields in the record<br># Note that field names are case-insensitive<br>$record["firstname"] = "Bob";<br>$record["lastNamE"] = "Smith";<br>$record["creaTed"] = time();<br><br># Pass the empty recordset and the array containing the data to insert<br># into the GetInsertSQL function. The function will process the data and return<br># a fully formatted insert sql statement.<br>$insertSQL = $conn-&gt;GetInsertSQL($rs, $record);<br><br>$conn-&gt;Execute($insertSQL); # Insert the record into the database<br><br>#==========================<br># This code tests an update<br><br>$sql = "SELECT * FROM ADOXYZ WHERE id = 1"; <br># Select a record to update<br><br>$rs = $conn-&gt;Execute($sql); # Execute the query and get the existing record to update<br><br>$record = array(); # Initialize an array to hold the record data to update<br><br># Set the values for the fields in the record<br># Note that field names are case-insensitive<br>$record["firstname"] = "Caroline";<br>$record["LasTnAme"] = "Smith"; # Update Caroline's lastname from Miranda to Smith<br><br># Pass the single record recordset and the array containing the data to update<br># into the GetUpdateSQL function. The function will process the data and return<br># a fully formatted update sql statement with the correct WHERE clause.<br># If the data has not changed, no recordset is returned<br>$updateSQL = $conn-&gt;GetUpdateSQL($rs, $record);<br><br>$conn-&gt;Execute($updateSQL); # Update the record in the database<br>$conn-&gt;Close();<br>?&gt;<br></pre>
+<a name="ADODB_FORCE_TYPE"></a>
+<b>$ADODB_FORCE_TYPE</b><p>
+The behaviour of AutoExecute(), GetUpdateSQL() and GetInsertSQL()  
+when converting empty or null PHP variables to SQL is controlled by the
+ global $ADODB_FORCE_TYPE variable. Set it to one of the values below. Default
+  is ADODB_FORCE_VALUE (3):
+</p><pre>0 = ignore empty fields. All empty fields in array are ignored.<br>1 = force null. All empty, php null and string 'null' fields are changed to sql NULL values.<br>2 = force empty. All empty, php null and string 'null' fields are changed to sql empty '' or 0 values.<br>3 = force value. Value is left as it is. Php null and string 'null' are set to sql NULL values and <br>    empty fields '' are set to empty '' sql values.<br><br>define('ADODB_FORCE_IGNORE',0);<br>define('ADODB_FORCE_NULL',1);<br>define('ADODB_FORCE_EMPTY',2);<br>define('ADODB_FORCE_VALUE',3);<br></pre>
+<p>
+Thanks to Niko (nuko#mbnet.fi) for the $ADODB_FORCE_TYPE code.
+</p><p>
+Note: the constant ADODB_FORCE_NULLS is obsolete since 4.52 and is ignored. Set $ADODB_FORCE_TYPE = ADODB_FORCE_NULL
+for equivalent behaviour.
+<p>Since 4.62, the table name to be used can be overridden by setting $rs->tableName before AutoExecute(), GetInsertSQL() or GetUpdateSQL() is called.
+</p><h3>Example 8: Implementing Scrolling with Next and Previous<a name="ex8"></a></h3>
+<p> The following code creates a very simple recordset pager, where you can scroll 
+  from page to page of a recordset.</p>
+<pre>include_once('../adodb.inc.php');<br>include_once('../adodb-pager.inc.php');<br>session_start();<br><br>$db = NewADOConnection('mysql');<br><br>$db-&gt;Connect('localhost','root','','xphplens');<br><br>$sql = "select * from adoxyz ";<br><br>$pager = new ADODB_Pager($db,$sql);<br>$pager-&gt;Render($rows_per_page=5);</pre>
+<p>This will create a basic record pager that looks like this: <a name="scr"></a> 
+</p><p> 
+<table bgcolor="beige" border="1">
+  <tbody><tr> 
+    <td> <a href="#scr"><code>|&lt;</code></a> &nbsp; <a href="#scr"><code>&lt;&lt;</code></a> 
+      &nbsp; <a href="#scr"><code>&gt;&gt;</code></a> &nbsp; <a href="#scr"><code>&gt;|</code></a> 
+      &nbsp; </td>
+  </tr>
+  <tr>
+    <td><table bgcolor="white" border="1" cols="4" width="100%">
+        <tbody><tr><th>ID</th>
+        <th>First Name</th>
+        <th>Last Name</th>
+        <th>Date Created</th>
+        </tr><tr> 
+          <td align="right">36&nbsp;</td>
+          <td>Alan&nbsp;</td>
+          <td>Turing&nbsp;</td>
+          <td>Sat 06, Oct 2001&nbsp;</td>
+        </tr>
+        <tr> 
+          <td align="right">37&nbsp;</td>
+          <td>Serena&nbsp;</td>
+          <td>Williams&nbsp;</td>
+          <td>Sat 06, Oct 2001&nbsp;</td>
+        </tr>
+        <tr> 
+          <td align="right">38&nbsp;</td>
+          <td>Yat Sun&nbsp;</td>
+          <td>Sun&nbsp;</td>
+          <td>Sat 06, Oct 2001&nbsp;</td>
+        </tr>
+        <tr> 
+          <td align="right">39&nbsp;</td>
+          <td>Wai Hun&nbsp;</td>
+          <td>See&nbsp;</td>
+          <td>Sat 06, Oct 2001&nbsp;</td>
+        </tr>
+        <tr> 
+          <td align="right">40&nbsp;</td>
+          <td>Steven&nbsp;</td>
+          <td>Oey&nbsp;</td>
+          <td>Sat 06, Oct 2001&nbsp;</td>
+        </tr>
+      </tbody></table></td>
+  </tr>
+  <tr>
+    <td><font size="-1">Page 8/10</font></td>
+  </tr>
+</tbody></table>
+</p><p>The number of rows to display at one time is controled by the Render($rows) 
+  method. If you do not pass any value to Render(), ADODB_Pager will default to 
+  10 records per page. 
+</p><p>You can control the column titles by modifying your SQL (supported by most 
+  databases): 
+</p><pre>$sql = 'select id as "ID", firstname as "First Name", <br>		  lastname as "Last Name", created as "Date Created" <br>		from adoxyz';</pre>
+<p>The above code can be found in the <i>adodb/tests/testpaging.php</i> example 
+  included with this release, and the class ADODB_Pager in <i>adodb/adodb-pager.inc.php</i>. 
+  The ADODB_Pager code can be adapted by a programmer so that the text links can 
+  be replaced by images, and the dull white background be replaced with more interesting 
+  colors. 
+</p><p>You can also allow display of html by setting $pager-&gt;htmlSpecialChars = false. 
+</p><p>Some of the code used here was contributed by Iv&aacute;n Oliva and Cornel 
+  G. </p>
+<h3><a name="ex9"></a>Example 9: Exporting in CSV or Tab-Delimited Format</h3>
+<p>We provide some helper functions to export in comma-separated-value (CSV) and 
+  tab-delimited formats:</p>
+<pre><b>include_once('/path/to/adodb/toexport.inc.php');</b><br>include_once('/path/to/adodb/adodb.inc.php');<br>
+$db = &amp;NewADOConnection('mysql');<br>$db-&gt;Connect($server, $userid, $password, $database);<br><br>$rs = $db-&gt;Execute('select fname as "First Name", surname as "Surname" from table');<br><br>print "&lt;pre&gt;";<br>print <b>rs2csv</b>($rs); # return a string, CSV format<p>print '&lt;hr&gt;';<br><br>$rs-&gt;MoveFirst(); # note, some databases do not support MoveFirst<br>print <b>rs2tab</b>($rs,<i>false</i>); # return a string, tab-delimited<br>						 # false == suppress field names in first line</p>print '&lt;hr&gt;';<br>$rs-&gt;MoveFirst();<br><b>rs2tabout</b>($rs); # send to stdout directly (there is also an rs2csvout function)<br>print "&lt;/pre&gt;";<br><br>$rs-&gt;MoveFirst();<br>$fp = fopen($path, "w");<br>if ($fp) {<br>  <b>rs2csvfile</b>($rs, $fp); # write to file (there is also an rs2tabfile function)<br>  fclose($fp);<br>}<br></pre>
+<p> Carriage-returns or newlines are converted to spaces. Field names are returned 
+  in the first line of text. Strings containing the delimiter character are quoted 
+  with double-quotes. Double-quotes are double-quoted again. This conforms to 
+  Excel import and export guide-lines. 
+</p><p>All the above functions take as an optional last parameter, $addtitles which 
+  defaults to <i>true</i>. When set to <i>false</i> field names in the first line 
+  are suppressed. <br>
+</p><h3>Example 10: Recordset Filters<a name="ex10"></a></h3>
+<p>Sometimes we want to pre-process all rows in a recordset before we use it. 
+  For example, we want to ucwords all text in recordset. 
+</p><pre>include_once('adodb/rsfilter.inc.php');<br>include_once('adodb/adodb.inc.php');<br><br>// ucwords() every element in the recordset<br>function do_ucwords(&amp;$arr,$rs)<br>{<br>	foreach($arr as $k =&gt; $v) {<br>		$arr[$k] = ucwords($v);<br>	}<br>}<br><br>$db = NewADOConnection('mysql');<br>$db-&gt;PConnect('server','user','pwd','db');<br><br>$rs = $db-&gt;Execute('select ... from table');<br>$rs = <b>RSFilter</b>($rs,'do_ucwords');<br></pre>
+<p>The <i>RSFilter</i> function takes 2 parameters, the recordset, and the name 
+  of the <i>filter</i> function. It returns the processed recordset scrolled to 
+  the first record. The <i>filter</i> function takes two parameters, the current 
+  row as an array, and the recordset object. For future compatibility, you should 
+  not use the original recordset object. </p>
+<h3>Example 11:<a name="ex11"></a> Smart Transactions</h3>
+The old way of doing transactions required you to use 
+<pre>$conn-&gt;<b>BeginTrans</b>();<br>$ok = $conn-&gt;Execute($sql);<br>if ($ok) $ok = $conn-&gt;Execute($sql2);<br>if (!$ok) $conn-&gt;<b>RollbackTrans</b>();<br>else $conn-&gt;<b>CommitTrans</b>();<br></pre>
+This is very complicated for large projects because you have to track the error 
+status. Smart Transactions is much simpler. You start a smart transaction by calling 
+StartTrans(): 
+<pre>$conn-&gt;<b>StartTrans</b>();<br>$conn-&gt;Execute($sql);<br>$conn-&gt;Execute($Sql2);<br>$conn-&gt;<b>CompleteTrans</b>();<br></pre>
+CompleteTrans() detects when an SQL error occurs, and will Rollback/Commit as 
+appropriate. To specificly force a rollback even if no error occured, use FailTrans(). 
+Note that the rollback is done in CompleteTrans(), and not in FailTrans(). 
+<pre>$conn-&gt;<b>StartTrans</b>();<br>$conn-&gt;Execute($sql);<br>if (!CheckRecords()) $conn-&gt;<strong>FailTrans</strong>();<br>$conn-&gt;Execute($Sql2);<br>$conn-&gt;<b>CompleteTrans</b>();<br></pre>
+<p>You can also check if a transaction has failed, using HasFailedTrans(), which 
+  returns true if FailTrans() was called, or there was an error in the SQL execution. 
+  Make sure you call HasFailedTrans() before you call CompleteTrans(), as it is 
+  only works between StartTrans/CompleteTrans.
+</p><p>Lastly, StartTrans/CompleteTrans is nestable, and only the outermost block 
+  is executed. In contrast, BeginTrans/CommitTrans/RollbackTrans is NOT nestable. 
+</p><pre>$conn-&gt;<strong>StartTrans</strong>();<br>$conn-&gt;Execute($sql);<br>  $conn-&gt;<strong>StartTrans</strong>();    <font color="#006600"># ignored</font>
+  if (!CheckRecords()) $conn-&gt;FailTrans();
+  $conn-&gt;<strong>CompleteTrans</strong>(); <font color="#006600"># ignored</font>
+$conn-&gt;Execute($Sql2);
+$conn-&gt;<strong>CompleteTrans</strong>();<br></pre>
+<p>Note: Savepoints are currently not supported. 
+</p><h2><a name="errorhandling"></a>Using Custom Error Handlers and PEAR_Error</h2>
+<p>ADOdb supports PHP5 exceptions.  Just include <i>adodb-exceptions.inc.php</i> and you can now 
+catch exceptions on errors as they occur.
+</p><pre>	<b>include("../adodb-exceptions.inc.php");</b> <br>	include("../adodb.inc.php");	 <br>	try { <br>		$db = NewADOConnection("oci8://scott:bad-password@mytns/"); <br>	} catch (exception $e) { <br>		var_dump($e); <br>		adodb_backtrace($e-&gt;gettrace());<br>	} <br></pre>
+<p> ADOdb also provides two custom handlers which you can modify for your needs. The 
+  first one is in the <b>adodb-errorhandler.inc.php</b> file. This makes use of 
+  the standard PHP functions <a href="http://php.net/error_reporting">error_reporting</a> 
+  to control what error messages types to display, and <a href="http://php.net/trigger_error">trigger_error</a> 
+  which invokes the default PHP error handler. 
+</p><p> Including the above file will cause <i>trigger_error($errorstring,E_USER_ERROR)</i> 
+  to be called when<br>
+  (a) Connect() or PConnect() fails, or <br>
+  (b) a function that executes SQL statements such as Execute() or SelectLimit() 
+  has an error.<br>
+  (c) GenID() appears to go into an infinite loop. 
+</p><p> The $errorstring is generated by ADOdb and will contain useful debugging information 
+  similar to the error.log data generated below. This file adodb-errorhandler.inc.php 
+  should be included before you create any ADOConnection objects. 
+</p><p> If you define error_reporting(0), no errors will be passed to the error handler. 
+  If you set error_reporting(E_ALL), all errors will be passed to the error handler. 
+  You still need to use <b>ini_set("display_errors", "0" or "1")</b> to control 
+  the display of errors. 
+</p><pre>&lt;?php<br><b>error_reporting(E_ALL); # pass any error messages triggered to error handler<br>include('adodb-errorhandler.inc.php');</b>
+include('adodb.inc.php');
+include('tohtml.inc.php');
+$c = NewADOConnection('mysql');
+$c-&gt;PConnect('localhost','root','','northwind');
+$rs=$c-&gt;Execute('select * from productsz'); #invalid table productsz');
+if ($rs) rs2html($rs);
+?&gt;
+</pre>
+<p> If you want to log the error message, you can do so by defining the following 
+  optional constants ADODB_ERROR_LOG_TYPE and ADODB_ERROR_LOG_DEST. ADODB_ERROR_LOG_TYPE 
+  is the error log message type (see <a href="http://php.net/error_log">error_log</a> 
+  in the PHP manual). In this case we set it to 3, which means log to the file 
+  defined by the constant ADODB_ERROR_LOG_DEST. 
+</p><pre>&lt;?php<br><b>error_reporting(E_ALL); # report all errors<br>ini_set("display_errors", "0"); # but do not echo the errors<br>define('ADODB_ERROR_LOG_TYPE',3);<br>define('ADODB_ERROR_LOG_DEST','C:/errors.log');<br>include('adodb-errorhandler.inc.php');</b>
+include('adodb.inc.php');
+include('tohtml.inc.php');
+
+$c = NewADOConnection('mysql');
+$c-&gt;PConnect('localhost','root','','northwind');
+$rs=$c-&gt;Execute('select * from productsz'); ## invalid table productsz
+if ($rs) rs2html($rs);
+?&gt;
+</pre>
+The following message will be logged in the error.log file: 
+<pre>(2001-10-28 14:20:38) mysql error: [1146: Table 'northwind.productsz' doesn't exist] in<br> EXECUTE("select * from productsz")<br></pre>
+<h3>PEAR_ERROR</h3>
+The second error handler is <b>adodb-errorpear.inc.php</b>. This will create a 
+PEAR_Error derived object whenever an error occurs. The last PEAR_Error object 
+created can be retrieved using ADODB_Pear_Error(). 
+<pre>&lt;?php<br><b>include('adodb-errorpear.inc.php');</b>
+include('adodb.inc.php');
+include('tohtml.inc.php');
+$c = NewADOConnection('mysql');
+$c-&gt;PConnect('localhost','root','','northwind');
+$rs=$c-&gt;Execute('select * from productsz'); #invalid table productsz');
+if ($rs) rs2html($rs);
+else {
+	<b>$e = ADODB_Pear_Error();<br>	echo '&lt;p&gt;',$e-&gt;message,'&lt;/p&gt;';</b>
+}
+?&gt;
+</pre>
+<p> You can use a PEAR_Error derived class by defining the constant ADODB_PEAR_ERROR_CLASS 
+  before the adodb-errorpear.inc.php file is included. For easy debugging, you 
+  can set the default error handler in the beginning of the PHP script to PEAR_ERROR_DIE, 
+  which will cause an error message to be printed, then halt script execution: 
+</p><pre>include('PEAR.php');<br>PEAR::setErrorHandling('PEAR_ERROR_DIE');<br></pre>
+<p> Note that we do not explicitly return a PEAR_Error object to you when an error 
+  occurs. We return false instead. You have to call ADODB_Pear_Error() to get 
+  the last error or use the PEAR_ERROR_DIE technique. 
+</p>
+<h3>MetaError and MetaErrMsg</h3>
+ <p>If you need error messages that work across multiple databases, then use <a href="#metaerror">MetaError()</a>, which returns a virtualized error number, based on PEAR DB's error number system, and <a href=<a href="#metaerrmsg">MetaErrMsg()</a>.
+
+<h4>Error Messages</h4>
+<p>Error messages are outputted using the static method ADOConnnection::outp($msg,$newline=true). 
+  By default, it sends the messages to the client. You can override this to perform 
+  error-logging. 
+</p><h2><a name="dsn"></a> Data Source Names</h2>
+<p>We now support connecting using PEAR style DSN's. A DSN is a connection string 
+  of the form:</p>
+<p>$dsn = <i>"$driver://$username:$password@$hostname/$databasename"</i>;</p>
+<p>An example:</p>
+<pre>   $username = 'root';<br>   $password = '';<br>   $hostname = 'localhost';<br>   $databasename = 'xphplens';<br>   $driver = 'mysql';<br>   $dsn = "$driver://$username:$password@$hostname/$databasename"<br>   $db = NewADOConnection(); <br>   # DB::Connect($dsn) also works if you include 'adodb/adodb-pear.inc.php' at the top<br>   $rs = $db-&gt;query('select firstname,lastname from adoxyz');<br>   $cnt = 0;<br>   while ($arr = $rs-&gt;fetchRow()) {<br>		print_r($arr); print "&lt;br&gt;";<br>   }</pre>
+   <p></p>
+<p>   <a href="#dsnsupport">More info and connection examples</a> on the DSN format.
+
+</p><h2><a name="pear"></a>PEAR Compatibility</h2>
+  We support DSN's (see above), and the following functions:
+ <pre><b> DB_Common</b>
+ 	query - returns PEAR_Error on error
+	limitQuery - return PEAR_Error on error
+	prepare - does not return PEAR_Error on error
+	execute - does not return PEAR_Error on error
+	setFetchMode - supports ASSOC and ORDERED
+	errorNative
+	quote
+	nextID
+	disconnect
+	
+	getOne
+	getAssoc
+	getRow
+	getCol
+	
+<b> DB_Result</b>
+ 	numRows - returns -1 if not supported
+	numCols
+	fetchInto - does not support passing of fetchmode
+	fetchRows - does not support passing of fetchmode
+	free
+</pre>
+<h2><a name="caching"></a>Caching of Recordsets</h2>
+<p>ADOdb now supports caching of recordsets using the CacheExecute( ), CachePageExecute( 
+  ) and CacheSelectLimit( ) functions. There are similar to the non-cache functions, 
+  except that they take a new first parameter, $secs2cache. 
+</p><p> An example: 
+</p><pre><b>include</b>('adodb.inc.php'); # load code common to ADOdb<br>$ADODB_CACHE_DIR = '/usr/ADODB_cache';<br>$<font color="#663300">conn</font> = &amp;ADONewConnection('mysql');  # create a connection<br>$<font color="#663300">conn</font>-&gt;PConnect('localhost','userid','','agora');# connect to MySQL, agora db<br><font>$<font color="#663300">sql</font> = 'select CustomerName, CustomerID from customers';<br>$<font color="#663300">rs</font> = $<font color="#663300">conn</font>-&gt;CacheExecute(15,$sql);</font></pre>
+<p><font> The first parameter is the number of seconds to cache 
+  the query. Subsequent calls to that query will used the cached version stored 
+  in $ADODB_CACHE_DIR. To force a query to execute and flush the cache, call CacheExecute() 
+  with the first parameter set to zero. Alternatively, use the CacheFlush($sql) 
+  call. </font></p>
+<p><font>For the sake of security, we recommend you set <i>register_globals=off</i> 
+  in php.ini if you are using $ADODB_CACHE_DIR.</font></p>
+<p>In ADOdb 1.80 onwards, the secs2cache parameter is optional in CacheSelectLimit() 
+  and CacheExecute(). If you leave it out, it will use the $connection-&gt;cacheSecs 
+  parameter, which defaults to 60 minutes. 
+</p><pre>	$conn-&gt;Connect(...);<br>	$conn-&gt;cacheSecs = 3600*24; # cache 24 hours<br>	$rs = $conn-&gt;CacheExecute('select * from table');<br></pre>
+<p>Please note that magic_quotes_runtime should be turned off. <a href="http://phplens.com/lens/lensforum/msgs.php?LeNs#LensBM_forummsg">More 
+  info</a>, and do not change $ADODB_FETCH_MODE (or SetFetchMode) 
+  as the cached recordset will use the $ADODB_FETCH_MODE set when the query was executed. <font> 
+<h2><a name="pivot"></a>Pivot Tables</h2>
+</font> </p><p><font>Since ADOdb 2.30, we support the generation of 
+SQL to create pivot tables, also known as cross-tabulations. For further explanation 
+read this DevShed <a href="http://www.devshed.com/Server_Side/MySQL/MySQLWiz/">Cross-Tabulation 
+tutorial</a>. We assume that your database supports the SQL case-when expression. </font></p> 
+<font> 
+<p>In this example, we will use the Northwind database from Microsoft. In the 
+  database, we have a products table, and we want to analyze this table by <i>suppliers 
+  versus product categories</i>. We will place the suppliers on each row, and 
+  pivot on categories. So from the table on the left, we generate the pivot-table 
+  on the right:</p>
+</font> 
+<table align="center" border="0" cellpadding="2" cellspacing="2">
+  <tbody><tr>
+	<td>
+	  <table align="center" border="1" cellpadding="2" cellspacing="2" width="142">
+		<tbody><tr> 
+		  <td><i>Supplier</i></td>
+		  <td><i>Category</i></td>
+		</tr>
+		<tr> 
+		  <td>supplier1</td>
+		  <td>category1</td>
+		</tr>
+		<tr> 
+		  <td>supplier2</td>
+		  			<td>category1</td>
+		</tr>
+		<tr> 
+		  			<td>supplier2</td>
+		  <td>category2</td>
+		</tr>
+	  </tbody></table>
+	</td>
+	<td> <font face="Courier New, Courier, mono">--&gt;</font></td>
+	<td>
+	  <table align="center" border="1" cellpadding="2" cellspacing="2">
+		<tbody><tr> 
+		  <td>&nbsp;</td>
+		  <td><i>category1</i></td>
+		  <td><i>category2</i></td>
+		  <td><i>total</i></td>
+		</tr>
+		<tr> 
+		  <td><i>supplier1</i></td>
+		  <td align="right">1</td>
+		  <td align="right">0</td>
+		  <td align="right">1</td>
+		</tr>
+		<tr> 
+		  <td><i>supplier2</i></td>
+		  <td align="right">1</td>
+		  <td align="right">1</td>
+		  <td align="right">2</td>
+		</tr>
+	  </tbody></table>
+	</td>
+  </tr>
+</tbody></table>
+<font> 
+</font><p><font>The following code will generate the SQL for a cross-tabulation: 
+</font></p><pre><font># Query the main "product" table<br># Set the rows to SupplierName<br># and the columns to the values of Categories<br># and define the joins to link to lookup tables <br># "categories" and "suppliers"<br>#<br> include "adodb/pivottable.inc.php";<br> $sql = PivotTableSQL(<br> 	$gDB,                                      # adodb connection<br> 	'products p ,categories c ,suppliers s',   # tables<br>	'SupplierName',                             # rows (multiple fields allowed)<br>	'CategoryName',                            # column to pivot on <br>	'p.CategoryID = c.CategoryID and s.SupplierID= p.SupplierID' # joins/where<br>);<br></font></pre>
+ 
+<p><font> This will generate the following SQL:</font></p>
+<p><code><font size="2">SELECT SupplierName, <br>
+  SUM(CASE WHEN CategoryName='Beverages' THEN 1 ELSE 0 END) AS "Beverages", 
+  <br>
+  SUM(CASE WHEN CategoryName='Condiments' THEN 1 ELSE 0 END) AS "Condiments", 
+  <br>
+  SUM(CASE WHEN CategoryName='Confections' THEN 1 ELSE 0 END) AS "Confections", 
+  <br>
+  SUM(CASE WHEN CategoryName='Dairy Products' THEN 1 ELSE 0 END) AS "Dairy 
+  Products", <br>
+  SUM(CASE WHEN CategoryName='Grains/Cereals' THEN 1 ELSE 0 END) AS "Grains/Cereals", 
+  <br>
+  SUM(CASE WHEN CategoryName='Meat/Poultry' THEN 1 ELSE 0 END) AS "Meat/Poultry", 
+  <br>
+  SUM(CASE WHEN CategoryName='Produce' THEN 1 ELSE 0 END) AS "Produce", 
+  <br>
+  SUM(CASE WHEN CategoryName='Seafood' THEN 1 ELSE 0 END) AS "Seafood", 
+  <br>
+  SUM(1) as Total <br>
+  FROM products p ,categories c ,suppliers s WHERE p.CategoryID = c.CategoryID 
+  and s.SupplierID= p.SupplierID <br>
+  GROUP BY SupplierName</font></code></p>
+<p> You can also pivot on <i>numerical columns</i> and <i>generate totals</i> 
+	by using ranges. <font>This code was revised in ADODB 2.41 
+	and is not backward compatible.</font> The second example shows this:</p>
+<pre> $sql = PivotTableSQL(<br> 	$gDB,                                       # adodb connection<br> 	'products p ,categories c ,suppliers s',    # tables<br>	'SupplierName',                              #<font> rows (multiple fields allowed)</font>
+   array(                                       # column ranges
+	' 0 '      =&gt; 'UnitsInStock &lt;= 0',
+	"1 to 5"   =&gt; '0 &lt; UnitsInStock and UnitsInStock &lt;= 5',
+	"6 to 10"  =&gt; '5 &lt; UnitsInStock and UnitsInStock &lt;= 10',
+	"11 to 15" =&gt; '10 &lt; UnitsInStock and UnitsInStock &lt;= 15',
+	"16+"      =&gt; '15 &lt; UnitsInStock'
+	),
+	' p.CategoryID = c.CategoryID and s.SupplierID= p.SupplierID', # joins/where
+	'UnitsInStock',                             # sum this field
+	'Sum '                                      # sum label prefix
+);
+</pre> 
+<p>Which generates: </p>
+<p> <code> <font size="2">SELECT SupplierName, <br>
+	SUM(CASE WHEN UnitsInStock &lt;= 0 THEN UnitsInStock ELSE 0 END) AS "Sum 
+	0 ", <br>
+	SUM(CASE WHEN 0 &lt; UnitsInStock and UnitsInStock &lt;= 5 THEN UnitsInStock 
+	ELSE 0 END) AS "Sum 1 to 5",<br>
+	SUM(CASE WHEN 5 &lt; UnitsInStock and UnitsInStock &lt;= 10 THEN UnitsInStock 
+	ELSE 0 END) AS "Sum 6 to 10",<br>
+	SUM(CASE WHEN 10 &lt; UnitsInStock and UnitsInStock &lt;= 15 THEN UnitsInStock 
+	ELSE 0 END) AS "Sum 11 to 15", <br>
+	SUM(CASE WHEN 15 &lt; UnitsInStock THEN UnitsInStock ELSE 0 END) AS "Sum 
+	16+", <br>
+	SUM(UnitsInStock) AS "Sum UnitsInStock", <br>
+	SUM(1) as Total,<br>
+	FROM products p ,categories c ,suppliers s WHERE p.CategoryID = c.CategoryID 
+	and s.SupplierID= p.SupplierID <br>
+	GROUP BY SupplierName</font></code><font size="2"><br>
+	</font> </p>
+<font><hr />
+<h1>Class Reference<a name="ref"></a></h1>
+<p>Function parameters with [ ] around them are optional.</p>
+</font> 
+<h2>Global Variables</h2>
+<h3><font><a name="adodb_countrecs"></a></font>$ADODB_COUNTRECS</h3>
+<p>If the database driver API does not support counting the number of records 
+	returned in a SELECT statement, the function RecordCount() is emulated when 
+	the global variable $ADODB_COUNTRECS is set to true, which is the default. 
+	We emulate this by buffering the records, which can take up large amounts 
+	of memory for big recordsets. Set this variable to false for the best performance. 
+	This variable is checked every time a query is executed, so you can selectively 
+	choose which recordsets to count.</p>
+<h3><font><a name="adodb_cache_dir"></a>$ADODB_CACHE_DIR</font></h3>
+<font> 
+<p>If you are using recordset caching, this is the directory to save your recordsets 
+  in. Define this before you call any caching functions such as CacheExecute( 
+  ). We recommend setting <i>register_globals=off</i> in php.ini if you use this 
+  feature for security reasons.</p>
+<p>If you are using Unix and apache, you might need to set your cache directory 
+  permissions to something similar to the following:</p>
+</font> 
+<p>chown -R apache /path/to/adodb/cache<br>
+  chgrp -R apache /path/to/adodb/cache </p>
+<h3><font><a name="adodb_ansi_padding_off"></a>$ADODB_ANSI_PADDING_OFF</font></h3>
+<p><font>Determines whether to right trim CHAR fields (and also VARCHAR for ibase/firebird).
+Set to true to trim. Default is false. Currently works for oci8po, ibase and firebird 
+drivers. Added in ADOdb 4.01.
+</font></p><h3><font><a name="adodb_lang"></a>$ADODB_LANG</font></h3>
+<p><font>Determines the language used in MetaErrorMsg(). The default is 'en', for English. 
+To find out what languages are supported, see the files 
+in adodb/lang/adodb-$lang.inc.php, where $lang is the supported langauge.
+</font></p><h3><font><a name="adodb_fetch_mode"></a>$ADODB_FETCH_MODE</font></h3>
+<p><font>This is a global variable that determines how arrays are retrieved by recordsets. 
+  The recordset saves this value on creation (eg. in Execute( ) or SelectLimit( 
+  )), and any subsequent changes to $ADODB_FETCH_MODE have no affect on existing 
+  recordsets, only on recordsets created in the future.</font></p>
+ <p><font>The following constants are defined:</font></p>
+ <p><font>define('ADODB_FETCH_DEFAULT',0);<br>
+  define('ADODB_FETCH_NUM',1);<br>
+  define('ADODB_FETCH_ASSOC',2);<br>
+  define('ADODB_FETCH_BOTH',3); </font></p>
+<font> 
+</font><p><font> An example: 
+</font></p><pre><font>	$ADODB_<b>FETCH_MODE</b> = ADODB_FETCH_NUM;<br>	$rs1 = $db-&gt;Execute('select * from table');<br>	$ADODB_<b>FETCH_MODE</b> = ADODB_FETCH_ASSOC;<br>	$rs2 = $db-&gt;Execute('select * from table');<br>	print_r($rs1-&gt;fields); # shows <i>array([0]=&gt;'v0',[1] =&gt;'v1')</i>
+	print_r($rs2-&gt;fields); # shows <i>array(['col1']=&gt;'v0',['col2'] =&gt;'v1')</i>
+</font></pre>
+<p><font> As you can see in the above example, both recordsets store and use different 
+	fetch modes based on the $ADODB_FETCH_MODE setting when the recordset was 
+	created by Execute().</font></p>
+<p><font>If no fetch mode is predefined, the fetch mode defaults to ADODB_FETCH_DEFAULT. 
+	The behaviour of this default mode varies from driver to driver, so do not 
+	rely on ADODB_FETCH_DEFAULT. For portability, we recommend sticking to ADODB_FETCH_NUM 
+	or ADODB_FETCH_ASSOC. Many drivers do not support ADODB_FETCH_BOTH.</font></p>
+<p><font><strong>SetFetchMode Function</strong></font></p>
+<p><font>If you have multiple connection objects, and want to have different fetch modes for each 
+connection, then use <a href="#setfetchmode">SetFetchMode</a>. 
+	Once this function is called for a connection object, that connection object 
+	will ignore the global variable $ADODB_FETCH_MODE and will use the internal 
+	fetchMode property exclusively.</font></p>
+<pre><font>	$db-&gt;SetFetchMode(ADODB_FETCH_NUM);<br>	$rs1 = $db-&gt;Execute('select * from table');<br>	$db-&gt;SetFetchMode(ADODB_FETCH_ASSOC);<br>	$rs2 = $db-&gt;Execute('select * from table');<br>	print_r($rs1-&gt;fields); # shows <i>array([0]=&gt;'v0',[1] =&gt;'v1')</i>
+	print_r($rs2-&gt;fields); # shows <i>array(['col1']=&gt;'v0',['col2'] =&gt;'v1')</i></font></pre>
+<p><font>To retrieve the previous fetch mode, you can use check the $db-&gt;fetchMode 
+	property, or use the return value of SetFetchMode( ). 
+</font></p><p><font><strong><a name="adodb_assoc_case"></a>ADODB_ASSOC_CASE</strong></font></p>
+<p><font>You can control the associative fetch case for certain drivers which behave 
+	differently. For the sybase, oci8po, mssql, odbc and ibase drivers and all 
+	drivers derived from them, ADODB_ASSOC_CASE will by default generate recordsets 
+	where the field name keys are lower-cased. Use the constant ADODB_ASSOC_CASE 
+	to change the case of the keys. There are 3 possible values:</font></p>
+<p><font>0 = assoc lowercase field names. $rs-&gt;fields['orderid']<br>
+	1 = assoc uppercase field names. $rs-&gt;fields['ORDERID']<br>
+	2 = use native-case field names. $rs-&gt;fields['OrderID'] -- this is the 
+	default since ADOdb 2.90</font></p>
+<p><font>To use it, declare it before you incldue adodb.inc.php.</font></p>
+<p><font>define('ADODB_ASSOC_CASE', 2); # use native-case for ADODB_FETCH_ASSOC<br>
+	include('adodb.inc.php'); </font></p>
+<h3><font><a name="force_type"></a>$ADODB_FORCE_TYPE</font></h3>
+<p><font>See the <a href="#ADODB_FORCE_TYPE">GetUpdateSQL tutorial</a>.
+</font></p>
+<h3><font><a name="adodb_auto_quote"></a>$ADODB_QUOTE_FIELDNAMES</font></h3>
+<p><font>Auto-quotes field names when using AutoExecute() when set to true. </font>
+<p>&nbsp;</p>
+<hr />
+<h2><font>ADOConnection<a name="adoconnection"></a></font></h2>
+<p><font>Object that performs the connection to the database, executes SQL statements 
+	and has a set of utility functions for standardising the format of SQL statements 
+	for issues such as concatenation and date formats.</font></p>
+<h3><font>ADOConnection Fields</font></h3>
+<p><font><b>databaseType</b>: Name of the database system we are connecting to. Eg. 
+	<b>odbc</b> or <b>mssql</b> or <b>mysql</b>.</font></p>
+<p><font><b>dataProvider</b>: The underlying mechanism used to connect to the database. 
+	Normally set to <b>native</b>, unless using <b>odbc</b> or <b>ado</b>.</font></p>
+<p><font><b>host: </b>Name of server or data source name (DSN) to connect to.</font></p>
+<p><font><b>database</b>: Name of the database or to connect to. If ado is used, it 
+	will hold the ado data provider.</font></p>
+<p><font><b>user</b>: Login id to connect to database. Password is not saved for security 
+	reasons.</font></p>
+<p><font><b>raiseErrorFn</b>: Allows you to define an error handling function. See adodb-errorhandler.inc.php 
+	for an example.</font></p>
+<p><font><b>debug</b>: Set to <i>true</i> to make debug statements to appear.</font></p>
+<p><font><b>concat_operator</b>: Set to '+' or '||' normally. The operator used to concatenate 
+	strings in SQL. Used by the <b><a href="#concat">Concat</a></b> function.</font></p>
+<p><font><b>fmtDate</b>: The format used by the <b><a href="#dbdate">DBDate</a></b> 
+	function to send dates to the database. is '#Y-m-d#' for Microsoft Access, 
+	and ''Y-m-d'' for MySQL.</font></p>
+<p><font><b>fmtTimeStamp: </b>The format used by the <b><a href="#dbtimestamp">DBTimeStamp</a></b> 
+	function to send timestamps to the database. </font></p>
+<p><font><b>true</b>: The value used to represent true.Eg. '.T.'. for Foxpro, '1' for 
+	Microsoft SQL.</font></p>
+<p><font><b>false: </b> The value used to represent false. Eg. '.F.'. for Foxpro, '0' 
+	for Microsoft SQL.</font></p>
+<p><font><b>replaceQuote</b>: The string used to escape quotes. Eg. double single-quotes 
+	for Microsoft SQL, and backslash-quote for MySQL. Used by <a href="#qstr">qstr</a>.</font></p>
+<p><font><b>autoCommit</b>: indicates whether automatic commit is enabled. Default is 
+	true.</font></p>
+<p><font><b>charSet</b>: set the default charset to use. Currently only interbase/firebird supports 
+	this.</font></p>
+<p><font><b>dialect</b>: set the default sql dialect to use. Currently only interbase/firebird 
+	supports this.</font></p>
+	<p><font><b>role</b>: set the role. Currently only interbase/firebird 
+	supports this.</font></p>
+<p><font><b>metaTablesSQL</b>: SQL statement to return a list of available tables. Eg. 
+	<i>SHOW TABLES</i> in MySQL.</font></p>
+<p><font><b>genID</b>: The latest id generated by GenID() if supported by the database.</font></p>
+<p><font><b>cacheSecs</b>: The number of seconds to cache recordsets if CacheExecute() 
+	or CacheSelectLimit() omit the $secs2cache parameter. Defaults to 60 minutes.</font></p>
+<p><font><b>sysDate</b>: String that holds the name of the database function to call 
+	to get the current date. Useful for inserts and updates.</font></p>
+<p><font><b>sysTimeStamp</b>: String that holds the name of the database function to 
+	call to get the current timestamp/datetime value.</font></p>
+<p><font><b>leftOuter</b>: String that holds operator for left outer join, if known. 
+	Otherwise set to false.</font></p>
+<p><font><b>rightOuter</b>: String that holds operator for left outer join, if known. 
+	Otherwise set to false.</font></p>
+<p><font><b>ansiOuter</b>: Boolean that if true indicates that ANSI style outer joins 
+	are permitted. Eg. <i>select * from table1 left join table2 on p1=p2.</i></font></p>
+<p><font><b>connectSID</b>: Boolean that indicates whether to treat the $database parameter 
+	in connects as the SID for the oci8 driver. Defaults to false. Useful for 
+	Oracle 8.0.5 and earlier.</font></p>
+<p><font><b>autoRollback</b>: Persistent connections are auto-rollbacked in PConnect( 
+	) if this is set to true. Default is false.</font></p>
+<hr />
+<h3><font>ADOConnection Main Functions</font></h3>
+<p><font><b>ADOConnection( )</b></font></p>
+<p><font>Constructor function. Do not call this directly. Use ADONewConnection( ) instead.</font></p>
+<p><font><b>Connect<a name="connect"></a>($host,[$user],[$password],[$database])</b></font></p>
+<p><font>Non-persistent connect to data source or server $<b>host</b>, using userid 
+	$<b>user </b>and password $<b>password</b>. If the server supports multiple 
+	databases, connect to database $<b>database</b>. </font></p>
+<p><font>Returns true/false depending on connection success. Since 4.23, null is returned if the extension is not loaded.</font></p>
+<p><font>ADO Note: If you are using a Microsoft ADO and not OLEDB, you can set the $database 
+	parameter to the OLEDB data provider you are using.</font></p>
+<p><font>PostgreSQL: An alternative way of connecting to the database is to pass the 
+	standard PostgreSQL connection string in the first parameter $host, and the 
+	other parameters will be ignored.</font></p>
+<p><font>For Oracle and Oci8, there are two ways to connect. First is to use the TNS 
+	name defined in your local tnsnames.ora (or ONAMES or HOSTNAMES). Place the 
+	name in the $database field, and set the $host field to false. Alternatively, 
+	set $host to the server, and $database to the database SID, this bypassed 
+	tnsnames.ora. 
+</font></p><p><font>Examples: 
+</font></p><pre><font> # $oraname in tnsnames.ora/ONAMES/HOSTNAMES<br> $conn-&gt;Connect(false, 'scott', 'tiger', $oraname); <br> $conn-&gt;Connect('server:1521', 'scott', 'tiger', 'ServiceName'); # bypass tnsnames.ora</font></pre>
+<p><font>There are many examples of connecting to a database.
+See  <a href="#connect_ex">Connection Examples</a> for many examples.
+
+</font></p><p><font><b>PConnect<a name="pconnect"></a>($host,[$user],[$password],[$database])</b></font></p>
+<p><font>Persistent connect to data source or server $<b>host</b>, using userid $<b>user</b> 
+	and password $<b>password</b>. If the server supports multiple databases, 
+	connect to database $<b>database</b>.</font></p>
+<p><font>We now perform a rollback on persistent connection for selected databases since 
+	2.21, as advised in the PHP manual. See change log or source code for which 
+	databases are affected. 
+</font></p><p><font>Returns true/false depending on connection. Since 4.23, 0 is returned if the extension is not loaded.
+See Connect( ) above for more info.</font></p>
+<p><font>Since ADOdb 2.21, we also support autoRollback. If you set:</font></p>
+ 
+<pre> $conn = &amp;NewADOConnection('mysql');<br> $conn-&gt;autoRollback = true; # default is false<br> $conn-&gt;PConnect(...); # rollback here</pre>
+<p> Then when doing a persistent connection with PConnect( ), ADOdb will 
+  perform a rollback first. This is because it is documented that PHP is 
+  not guaranteed to rollback existing failed transactions when 
+  persistent connections are used. This is implemented in Oracle, 
+  MySQL, PgSQL, MSSQL, ODBC currently. 
+</p><p>Since ADOdb 3.11, you can force non-persistent 
+connections even if PConnect is called by defining the constant 
+ADODB_NEVER_PERSIST  before you call PConnect.
+</p><p>
+Since 4.23, null is returned if the extension is not loaded.
+</p><p><b>NConnect<a name="nconnect"></a>($host,[$user],[$password],[$database])</b></p>
+<p>Always force a new connection. In contrast, PHP sometimes reuses connections 
+	when you use Connect() or PConnect(). Currently works only on mysql (PHP 4.3.0 
+	or later), postgresql and oci8-derived drivers. For other drivers, NConnect() works like 
+	Connect().</p>
+<p><font><b>IsConnected( )<a name="isconnected"></a></b></font></p>
+<p>
+<font>Returns true if connected to database. Added in 4.53.
+
+</font></p><p><font><b>Execute<a name="execute"></a>($sql,$inputarr=false)</b></font></p>
+<p><font>Execute SQL statement $<b>sql</b> and return derived class of ADORecordSet 
+	if successful. Note that a record set is always returned on success, even 
+	if we are executing an insert or update statement. You can also pass in $sql a statement prepared 
+	in <a href="#prepare">Prepare()</a>.</font></p>
+<p><font>Returns derived class of ADORecordSet. Eg. if connecting via mysql, then ADORecordSet_mysql 
+	would be returned. False is returned if there was an error in executing the 
+	sql.</font></p>
+<p><font>The $inputarr parameter can be used for binding variables to parameters. Below 
+	is an Oracle example:</font></p>
+<pre><font> $conn-&gt;Execute("SELECT * FROM TABLE WHERE COND=:val", array('val'=&gt; $val));<br> </font></pre>
+<p><font>Another example, using ODBC,which uses the ? convention:</font></p>
+<pre><font>  $conn-&gt;Execute("SELECT * FROM TABLE WHERE COND=?", array($val));<br></font></pre>
+<font><a name="binding"></a>
+<i>Binding variables</i></font><p>
+<font>Variable binding speeds the compilation and caching of SQL statements, leading 
+to higher performance. Currently Oracle, Interbase and ODBC supports variable binding. 
+Interbase/ODBC style ? binding is emulated in databases that do not support binding. 
+Note that you do not have to quote strings if you use binding.
+</font></p><p><font> Variable binding in the odbc, interbase and oci8po drivers. 
+</font></p><pre><font>$rs = $db-&gt;Execute('select * from table where val=?', array('10'));<br></font></pre>
+<font>Variable binding in the oci8 driver: 
+</font><pre><font>$rs = $db-&gt;Execute('select name from table where val=:key', <br>  array('key' =&gt; 10));<br></font></pre>
+<font><a name="bulkbind"></a>
+<i>Bulk binding</i>
+</font><p><font>Since ADOdb 3.80, we support bulk binding in Execute(), in which you pass in a 2-dimensional array to
+be bound to an INSERT/UPDATE or DELETE statement.
+</font></p><pre><font>$arr = array(<br>	array('Ahmad',32),<br>	array('Zulkifli', 24),<br>	array('Rosnah', 21)<br>	);<br>$ok = $db-&gt;Execute('insert into table (name,age) values (?,?)',$arr);<br></font></pre>
+<p><font>This provides very high performance as the SQL statement is prepared first. 
+The prepared statement is executed repeatedly for each array row until all rows are completed, 
+or until the first error. Very useful for importing data.
+
+</font></p><p><font><b>CacheExecute<a name="cacheexecute"></a>([$secs2cache,]$sql,$inputarr=false)</b></font></p>
+<p><font>Similar to Execute, except that the recordset is cached for $secs2cache seconds 
+	in the $ADODB_CACHE_DIR directory, and $inputarr only accepts 1-dimensional arrays. 
+	If CacheExecute() is called again with the same $sql, $inputarr, 
+	and also the same database, same userid, and the cached recordset 
+	has not expired, the cached recordset is returned. 
+</font></p><pre><font>  include('adodb.inc.php'); <br>  include('tohtml.inc.php');<br>  $ADODB_<b>CACHE_DIR</b> = '/usr/local/ADOdbcache';<br>  $conn = &amp;ADONewConnection('mysql'); <br>  $conn-&gt;PConnect('localhost','userid','password','database');<br>  $rs = $conn-&gt;<b>CacheExecute</b>(15, 'select * from table'); # cache 15 secs<br>  rs2html($rs); /* recordset to html table */  <br></font></pre>
+<p><font> Alternatively, since ADOdb 1.80, the $secs2cache parameter is optional:</font></p>
+<pre><font>	$conn-&gt;Connect(...);<br>   	$conn-&gt;cacheSecs = 3600*24; // cache 24 hours<br>	$rs = $conn-&gt;CacheExecute('select * from table');<br></font></pre>
+<font>If $secs2cache is omitted, we use the value 
+in $connection-&gt;cacheSecs (default is 3600 seconds, or 1 hour). Use CacheExecute() 
+only with SELECT statements. 
+</font><p><font>Performance note: I have done some benchmarks and found that they vary so greatly 
+	that it's better to talk about when caching is of benefit. When your database 
+	server is <i>much slower </i>than your Web server or the database is <i>very 
+	overloaded </i>then ADOdb's caching is good because it reduces the load on 
+	your database server. If your database server is lightly loaded or much faster 
+	than your Web server, then caching could actually reduce performance. </font></p>
+<p><font><b>ExecuteCursor<a name="executecursor"></a>($sql,$cursorName='rs',$parameters=false)</b></font></p>
+<p><font>Execute an Oracle stored procedure, and returns an Oracle REF cursor variable as 
+	a regular ADOdb recordset. Does not work with any other database except oci8. 
+	Thanks to Robert Tuttle for the design.
+</font></p><pre><font>    $db = ADONewConnection("oci8"); <br>    $db-&gt;Connect("foo.com:1521", "uid", "pwd", "FOO"); <br>    $rs = $db-&gt;ExecuteCursor("begin :cursorvar := getdata(:param1); end;", <br>					'cursorvar',<br>					array('param1'=&gt;10)); <br>    # $rs is now just like any other ADOdb recordset object<br>    rs2html($rs);</font></pre>
+<p><font>ExecuteCursor() is a helper function that does the following internally: 
+</font></p><pre><font>	$stmt = $db-&gt;Prepare("begin :cursorvar := getdata(:param1); end;", true); <br>	$db-&gt;Parameter($stmt, $cur, 'cursorvar', false, -1, OCI_B_CURSOR);<br>	$rs = $db-&gt;Execute($stmt,$bindarr);<br></font></pre>
+<p><font>ExecuteCursor only accepts 1 out parameter. So if you have 2 out parameters, use:
+</font></p><pre><font>	$vv = 'A%';<br>	$stmt = $db-&gt;PrepareSP("BEGIN list_tabs(:crsr,:tt); END;");<br>	$db-&gt;OutParameter($stmt, $cur, 'crsr', -1, OCI_B_CURSOR);<br>	$db-&gt;OutParameter($stmt, $vv, 'tt', 32); # return varchar(32)<br>	$arr = $db-&gt;GetArray($stmt);<br>	print_r($arr);<br>	echo " val = $vv"; ## outputs 'TEST'<br></font></pre>
+<font>for the following PL/SQL:
+</font><pre><font>	TYPE TabType IS REF CURSOR RETURN TAB%ROWTYPE;<br><br>	PROCEDURE list_tabs(tabcursor IN OUT TabType,tablenames IN OUT VARCHAR) IS<br>	BEGIN<br>		OPEN tabcursor FOR SELECT * FROM TAB WHERE tname LIKE tablenames;<br>		tablenames := 'TEST';<br>	END list_tabs;<br></font></pre>
+<p><font><b>SelectLimit<a name="selectlimit"></a>($sql,$numrows=-1,$offset=-1,$inputarr=false)</b></font></p>
+<p><font>Returns a recordset if successful. Returns false otherwise. Performs a select 
+	statement, simulating PostgreSQL's SELECT statement, LIMIT $numrows OFFSET 
+	$offset clause.</font></p>
+<p><font>In PostgreSQL, SELECT * FROM TABLE LIMIT 3 will return the first 3 records 
+	only. The equivalent is <code>$connection-&gt;SelectLimit('SELECT * FROM TABLE',3)</code>. 
+	This functionality is simulated for databases that do not possess this feature.</font></p>
+<p><font>And SELECT * FROM TABLE LIMIT 3 OFFSET 2 will return records 3, 4 and 5 (eg. 
+	after record 2, return 3 rows). The equivalent in ADOdb is <code>$connection-&gt;SelectLimit('SELECT 
+	* FROM TABLE',3,2)</code>.</font></p>
+<p><font>Note that this is the <i>opposite</i> of MySQL's LIMIT clause. You can also 
+	set <code>$connection-&gt;SelectLimit('SELECT * FROM TABLE',-1,10)</code> to 
+	get rows 11 to the last row.</font></p>
+<p><font>The last parameter $inputarr is for databases that support variable binding 
+	such as Oracle oci8. This substantially reduces SQL compilation overhead. 
+	Below is an Oracle example:</font></p>
+<pre><font> $conn-&gt;SelectLimit("SELECT * FROM TABLE WHERE COND=:val", 100,-1,array('val'=&gt; $val));<br> </font></pre>
+<p><font>The oci8po driver (oracle portable driver) uses the more standard bind variable 
+	of ?: 
+</font></p><pre><font> $conn-&gt;SelectLimit("SELECT * FROM TABLE WHERE COND=?", 100,-1,array('val'=&gt; $val));<br></font></pre>
+<p><font> 
+</font></p><p><font>Ron Wilson reports that SelectLimit does not work with UNIONs. 
+</font></p><p><font><b>CacheSelectLimit<a name="cacheselectlimit"></a>([$secs2cache,] $sql, $numrows=-1,$offset=-1,$inputarr=false)</b></font></p>
+<p><font>Similar to SelectLimit, except that the recordset returned is cached for $secs2cache 
+	seconds in the $ADODB_CACHE_DIR directory. </font></p>
+<p><font>Since 1.80, $secs2cache has been optional, and you can define the caching time 
+	in $connection-&gt;cacheSecs.</font></p>
+ 
+<pre><font>	$conn-&gt;Connect(...);<br>   $conn-&gt;cacheSecs = 3600*24; // cache 24 hours<br>	$rs = $conn-&gt;CacheSelectLimit('select * from table',10);</font></pre>
+<font> 
+</font><p><font><b>CacheFlush<a name="cacheflush"></a>($sql=false,$inputarr=false)</b></font></p>
+<p><font>Flush (delete) any cached recordsets for the SQL statement $sql in $ADODB_CACHE_DIR. 
+</font></p><p><font>If no parameter is passed in, then all adodb_*.cache files are deleted. 
+</font></p>
+  <p>CacheSelectLimit() rewrites the SQL query, so you won't be able to pass the SQL to CacheFlush. In this case,
+   to flush the cached SQL recordset returned by CacheSelectLimit(), set $secs2cache to -1:
+<pre>
+	$db->CacheSelectLimit(-1, $sql, $nrows);
+</pre>
+<p><font> If you want to flush all cached recordsets manually, execute the following 
+	PHP code (works only under Unix): <br>
+	<code> &nbsp; system("rm -f `find ".$ADODB_CACHE_DIR." -name 
+	adodb_*.cache`");</code></font></p>
+<p><font>For general cleanup of all expired files, you should use <a href="http://www.superscripts.com/tutorial/crontab.html">crontab</a> 
+	on Unix, or at.exe on Windows, and a shell script similar to the following:<font face="Courier New, Courier, mono"><br>
+	#------------------------------------------------------ <br>
+	# This particular example deletes files in the TMPPATH <br>
+	# directory with the string ".cache" in their name that <br>
+	# are more than 7 days old. <br>
+	#------------------------------------------------------ <br>
+	AGED=7 <br>
+	find ${TMPPATH} -mtime +$AGED | grep "\.cache" | xargs rm -f <br>
+	</font> </font></p>
+<p><font><b>MetaError<a name="metaerror"></a>($errno=false)</b></font></p>
+<p><font>Returns a virtualized error number, based on PEAR DB's error number system. You might
+need to include adodb-error.inc.php before you call this function. The parameter $errno
+is the native error number you want to convert. If you do not pass any parameter, MetaError
+will call ErrorNo() for you and convert it. If the error number cannot be virtualized, MetaError 
+will return -1 (DB_ERROR).</font></p>
+
+<p><font><b>MetaErrorMsg<a name="metaerrormsg"></a>($errno)</b></font></p>
+<p><font>Pass the error number returned by MetaError() for the equivalent textual error message.</font></p>
+<p><font><b>ErrorMsg<a name="errormsg"></a>()</b></font></p>
+<p><font>Returns the last status or error message. The error message is reset after every 
+call to Execute(). 
+</font></p><p>
+<font>This can return a string even if 
+	no error occurs. In general you do not need to call this function unless an 
+	ADOdb function returns false on an error. </font></p>
+<p><font>Note: If <b>debug</b> is enabled, the SQL error message is always displayed 
+	when the <b>Execute</b> function is called.</font></p>
+<p><font><b>ErrorNo<a name="errorno"></a>()</b></font></p>
+<p><font>Returns the last error number. The error number is reset after every call to Execute(). 
+If 0 is returned, no error occurred.
+</font></p><p>
+<font>Note that old versions of PHP (pre 4.0.6) do 
+	not support error number for ODBC. In general you do not need to call this 
+	function unless an ADOdb function returns false on an error.</font></p>
+<p><font><b>IgnoreErrors<a name="ignoreerrors"></a>($saveErrHandlers)</b></font></p>
+<p>Allows you to ignore errors so that StartTrans()/CompleteTrans() is not affected, nor is the default error handler called if an error occurs.
+Useful when you want to check if a field or table exists in a database without invoking an error if it does not exist.
+<p>Usage:
+<pre>
+$saveErrHandlers = $conn->IgnoreErrors();
+$rs = $conn->Execute("select field from some_table_that_might_not_exist");
+$conn->IgnoreErrors($saveErrHandlers);
+</pre>
+<p>Warning: do not call StartTrans()/CompleteTrans() inside a code block that is using IgnoreErrors().
+<p><font><b>SetFetchMode<a name="setfetchmode"></a>($mode)</b></font></p>
+<p><font>Sets the current fetch mode for the connection and stores 
+	it in $db-&gt;fetchMode. Legal modes are ADODB_FETCH_ASSOC and ADODB_FETCH_NUM. 
+	For more info, see <a href="#adodb_fetch_mode">$ADODB_FETCH_MODE</a>.</font></p>
+<p><font>Returns the previous fetch mode, which could be false 
+	if SetFetchMode( ) has not been called before.</font></p>
+<font> 
+</font><p><font><b>CreateSequence<a name="createseq"></a>($seqName = 'adodbseq',$startID=1)</b></font></p>
+<p><font>Create a sequence. The next time GenID( ) is called, the value returned will 
+	be $startID. Added in 2.60. 
+</font></p><p><font><b>DropSequence<a name="dropseq"></a>($seqName = 'adodbseq')</b></font></p>
+<p><font>Delete a sequence. Added in 2.60. 
+</font></p><p><font><b>GenID<a name="genid"></a>($seqName = 'adodbseq',$startID=1)</b></font></p>
+<p><font>Generate a sequence number . Works for interbase, 
+	mysql, postgresql, oci8, oci8po, mssql, ODBC based (access,vfp,db2,etc) drivers 
+	currently. Uses $seqName as the name of the sequence. GenID() will automatically 
+	create the sequence for you if it does not exist (provided the userid has 
+	permission to do so). Otherwise you will have to create the sequence yourself. 
+</font></p><p><font> If your database driver emulates sequences, the name of the table is the sequence 
+	name. The table has one column, "id" which should be of type integer, or if 
+	you need something larger - numeric(16). 
+</font></p><p><font> For ODBC and databases that do not support sequences natively (eg mssql, mysql), 
+	we create a table for each sequence. If the sequence has not been defined 
+	earlier, it is created with the starting value set in $startID.</font></p>
+<p><font>Note that the mssql driver's GenID() before 1.90 used to generate 16 byte GUID's.</font></p>
+<p><font><b>UpdateBlob<a name="updateblob"></a>($table,$column,$val,$where)</b></font></p>
+<font>Allows you to store a blob (in $val) into $table into $column in a row at $where. 
+</font><p><font> Usage: 
+</font></p><p><font> 
+</font></p><pre><font>	# for oracle<br>	$conn-&gt;Execute('INSERT INTO blobtable (id, blobcol) VALUES (1, empty_blob())');<br>	$conn-&gt;UpdateBlob('blobtable','blobcol',$blobvalue,'id=1');<br>	<br>	# non oracle databases<br>	$conn-&gt;Execute('INSERT INTO blobtable (id, blobcol) VALUES (1, null)');<br>	$conn-&gt;UpdateBlob('blobtable','blobcol',$blobvalue,'id=1');<br></font></pre>
+<p><font> Returns true if succesful, false otherwise. Supported by MySQL, PostgreSQL, 
+	Oci8, Oci8po and Interbase drivers. Other drivers might work, depending on 
+	the state of development.</font></p>
+<p><font>Note that when an Interbase blob is retrieved using SELECT, it still needs 
+	to be decoded using $connection-&gt;DecodeBlob($blob); to derive the original 
+	value in versions of PHP before 4.1.0. 
+</font></p><p><font>For PostgreSQL, you can store your blob using blob oid's or as a bytea field. 
+	You can use bytea fields but not blob oid's currently with UpdateBlob( ). 
+	Conversely UpdateBlobFile( ) supports oid's, but not bytea data.<br>
+	<br>
+	If you do not pass in an oid, then UpdateBlob() assumes that you are storing 
+	in bytea fields.
+	<p>If you do not have any blob fields, you can improve you can improve general SQL query performance by disabling blob handling with $connection->disableBlobs = true.
+</p></font><p><font><b>UpdateClob<a name="updateclob"></a>($table,$column,$val,$where)</b></font></p>
+<font>Allows you to store a clob (in $val) into $table into $column in a row at $where. 
+Similar to UpdateBlob (see above), but for Character Large OBjects. 
+</font><p><font> Usage:
+</font></p><pre><font>	# for oracle<br>	$conn-&gt;Execute('INSERT INTO clobtable (id, clobcol) VALUES (1, empty_clob())');<br>	$conn-&gt;UpdateBlob('clobtable','clobcol',$clobvalue,'id=1');<br>	<br>	# non oracle databases<br>	$conn-&gt;Execute('INSERT INTO clobtable (id, clobcol) VALUES (1, null)');<br>	$conn-&gt;UpdateBlob('clobtable','clobcol',$clobvalue,'id=1');<br></font></pre>
+<p><font><b>UpdateBlobFile<a name="updateblobfile"></a>($table,$column,$path,$where,$blobtype='BLOB')</b></font></p>
+<p><font>Similar to UpdateBlob, except that we pass in a file path to where the blob 
+	resides.
+</font></p><p><font>For PostgreSQL, if you are using blob oid's, use this interface. This interface 
+	does not support bytea fields.
+</font></p><p><font>Returns true if successful, false otherwise. 
+</font></p><p><font><b>BlobEncode<a name="blobencode" id="blobencode"></a>($blob)</b> 
+</font></p><p><font>Some databases require blob's to be encoded manually before upload. Note if 
+	you use UpdateBlob( ) or UpdateBlobFile( ) the conversion is done automatically 
+	for you and you do not have to call this function. For PostgreSQL, currently, 
+	BlobEncode() can only be used for bytea fields.
+</font></p><p><font>Returns the encoded blob value.
+</font></p><p><font>Note that there is a connection property called <em>blobEncodeType</em> which 
+	has 3 legal values: 
+</font></p><p><font>false - no need to perform encoding or decoding.<br>
+	'I' - blob encoding required, and returned encoded blob is a numeric value 
+	(no need to quote).<br>
+	'C' - blob encoding required, and returned encoded blob is a character value 
+	(requires quoting).
+</font></p><p><font>This is purely for documentation purposes, so that programs that accept multiple 
+	database drivers know what is the right thing to do when processing blobs.
+</font></p><p><font><strong>BlobDecode<a name="blobdecode"></a>($blob, $maxblobsize = false)</strong> 
+</font></p><p><font>Some databases require blob's to be decoded manually after doing a select statement. 
+	If the database does not require decoding, then this function will return 
+	the blob unchanged. Currently BlobDecode is only required for one database, 
+	PostgreSQL, and only if you are using blob oid's (if you are using bytea fields, 
+	we auto-decode for you).</font> The default maxblobsize is set in $connection-&gt;maxblobsize, which 
+	is set to 256K in adodb 4.54. </p><p>
+	In ADOdb 4.54 and later, the blob is the return value. In earlier versions, the blob data is sent to stdout.</p><font>
+</font><p></p><pre><font>$rs = $db-&gt;Execute("select bloboid from postgres_table where id=$key");<br>$blob = $db-&gt;BlobDecode( reset($rs-&gt;fields) );</font></pre>
+<p><font><b>Replace<a name="replace"></a>($table, $arrFields, $keyCols,$autoQuote=false)</b></font></p>
+<p><font>Try to update a record, and if the record is not found, an insert statement 
+	is generated and executed. Returns 0 on failure, 1 if update statement worked, 
+	2 if no record was found and the insert was executed successfully. This differs 
+	from MySQL's replace which deletes the record and inserts a new record. This 
+	also means you cannot update the primary key. The only exception to this is 
+	Interbase and its derivitives, which uses delete and insert because of some 
+	Interbase API limitations. 
+</font></p><p><font>The parameters are $table which is the table name, the $arrFields which is an 
+	associative array where the keys are the field names, and $keyCols is the name 
+	of the primary key, or an array of field names if it is a compound key. If 
+	$autoQuote is set to true, then Replace() will quote all values that are non-numeric; 
+	auto-quoting will not quote nulls. Note that auto-quoting will not work if 
+	you use SQL functions or operators. 
+</font></p><p><font>Examples: 
+</font></p><pre><font># single field primary key<br>$ret = $db-&gt;Replace('atable', <br>	array('id'=&gt;1000,'firstname'=&gt;'Harun','lastname'=&gt;'Al-Rashid'),<br>	'id',$autoquote = true);	<br># generates UPDATE atable SET firstname='Harun',lastname='Al-Rashid' WHERE id=1000<br># or INSERT INTO atable (id,firstname,lastname) VALUES (1000,'Harun','Al-Rashid')<br><br># compound key<br>$ret = $db-&gt;Replace('atable2', <br>	array('firstname'=&gt;'Harun','lastname'=&gt;'Al-Rashid', 'age' =&gt; 33, 'birthday' =&gt; 'null'),<br>	array('lastname','firstname'),<br>	$autoquote = true);<br><br># no auto-quoting<br>$ret = $db-&gt;Replace('atable2', <br>	array('firstname'=&gt;"'Harun'",'lastname'=&gt;"'Al-Rashid'", 'age' =&gt; 'null'),<br>	array('lastname','firstname'));	<br></font></pre>
+<p><font><b>AutoExecute<a name="autoexecute"></a>($table, $arrFields, $mode, $where=false, $forceUpdate=true,$magicq=false)</b></font></p>
+<p>Since ADOdb 4.56, you can automatically generate and execute INSERTs and UPDATEs on a given table with this
+function, which is a wrapper for GetInsertSQL() and GetUpdateSQL().
+<p>AutoExecute() inserts or updates $table given an array of $arrFields, where the keys are the field names and the array values are the 
+field values to store. Note that there is some overhead because the table is first queried to extract key information 
+before the SQL is generated. We generate an INSERT or UPDATE based on $mode (see below).
+<p>
+Legal values for $mode are 
+<ul>
+<li>'INSERT' or 1 or DB_AUTOQUERY_INSERT
+<li>'UPDATE' or 2 or DB_AUTOQUERY_UPDATE
+</ul>
+<p>You have to define the constants DB_AUTOQUERY_UPDATE and DB_AUTOQUERY_INSERT yourself or include adodb-pear.inc.php.
+<p>The $where clause is required if $mode == 'UPDATE'. If $forceUpdate=false then we will query the 
+database first and check if the field value returned by the query matches the current field value; only if they differ do we update that field.
+<p>Returns true on success, false on error.
+<p>An example of its use is:
+<pre>
+$record["firstName"] = "Carol";
+$record["lasTname"] = "Smith"; 
+$conn->AutoExecute($table,$record,'INSERT');
+# executes <i>"INSERT INTO $table (firstName,lasTname) values ('Carol',Smith')"</i>;
+
+$record["firstName"] = "Carol";
+$record["lasTname"] = "Jones"; 
+$conn->AutoExecute($table,$record,'UPDATE', "lastname like 'Sm%'");
+# executes <i>"UPDATE $table SET firstName='Carol',lasTname='Jones' WHERE lastname like 'Sm%'"</i>;
+</pre>
+<p>Note: One of the strengths of ADOdb's AutoExecute() is that only valid field names for $table are updated. If $arrFields
+contains keys that are invalid field names for $table, they are ignored. There is some overhead in doing this as we have to 
+query the database to get the field names, but given that you are not directly coding the SQL yourself, you probably aren't interested in
+speed at all, but convenience.
+<p>Since 4.62, the table name to be used can be overridden by setting $rs->tableName before AutoExecute(), GetInsertSQL() or GetUpdateSQL() is called.
+<p>Since 4.94, setting the global variable $ADODB_QUOTE_FIELDNAMES to true will force field names to be auto-quoted in AutoExecute(), GetInsertSQL() and GetUpdateSQL(). </p>
+<p><font><b>GetUpdateSQL<a name="getupdatesql"></a>(&amp;$rs, $arrFields, $forceUpdate=false,$magicq=false, $force=null)</b></font></p>
+<p><font>Generate SQL to update a table given a recordset $rs, and the modified fields 
+	of the array $arrFields (which must be an associative array holding the column 
+	names and the new values) are compared with the current recordset. If $forceUpdate 
+	is true, then we also generate the SQL even if $arrFields is identical to 
+	$rs-&gt;fields. Requires the recordset to be associative. $magicq is used 
+	to indicate whether magic quotes are enabled (see qstr()). The field names in the array 
+	are case-insensitive.</font></p>
+<font>	</font><p><font>Since 4.52, we allow you to pass the $force type parameter, and this overrides the <a href="#ADODB_FORCE_TYPE">$ADODB_FORCE_TYPE</a>
+	global variable.
+<p>Since 4.62, the table name to be used can be overridden by setting $rs->tableName before AutoExecute(), GetInsertSQL() or GetUpdateSQL() is called.
+</p></font><p><font><b>GetInsertSQL<a name="getinsertsql"></a>(&amp;$rs, $arrFields,$magicq=false,$force_type=false)</b></font></p>
+<p><font>Generate SQL to insert into a table given a recordset $rs. Requires the query 
+	to be associative. $magicq is used to indicate whether magic quotes are enabled 
+	(for qstr()). The field names in the array are case-insensitive.</font></p>
+<p>
+<font>  Since 2.42, you can pass a  table name instead of a recordset into 
+GetInsertSQL (in $rs), and it will generate an insert statement for that table.
+</font></p><p><font>Since 4.52, we allow you to pass the $force_type parameter, and this overrides the <a href="#ADODB_FORCE_TYPE">$ADODB_FORCE_TYPE</a>
+	global variable.
+<p>Since 4.62, the table name to be used can be overridden by setting $rs->tableName before AutoExecute(), GetInsertSQL() or GetUpdateSQL() is called.
+</p></font><p><font><b>PageExecute<a name="pageexecute"></a>($sql, $nrows, $page, $inputarr=false)</b> 
+</font></p><p><font>Used for pagination of recordset. $page is 1-based. See <a href="#ex8">Example 
+  8</a>.</font></p>
+ 
+<p><font><b>CachePageExecute<a name="cachepageexecute"></a>($secs2cache, 
+  $sql, $nrows, $page, $inputarr=false)</b> </font></p>
+<p><font>Used for pagination of recordset. $page is 1-based. See 
+  <a href="#ex8">Example 8</a>. Caching version of PageExecute.</font></p>
+<font> 
+</font><p></p>
+<p><font><b>Close<a name="close"></a>( )</b></font></p>
+<p><font>Close the database connection. PHP4 proudly states that we no longer have to 
+  clean up at the end of the connection because the reference counting mechanism 
+  of PHP4 will automatically clean up for us.</font></p>
+<font>  </font><p><font><b>StartTrans<a name="starttrans"></a>( )</b></font></p>
+<font>  </font><p><font>Start a monitored transaction. As SQL statements are executed, ADOdb will monitor
+  for SQL errors, and if any are detected, when CompleteTrans() is called, we auto-rollback.
+  </font></p><p>
+<font>  </font></p><p><font> To understand why StartTrans() is superior to BeginTrans(), 
+  let us examine a few ways of using BeginTrans().
+  The following is the wrong way to use transactions: 
+</font></p><pre><font>$DB-&gt;BeginTrans();<br>$DB-&gt;Execute("update table1 set val=$val1 where id=$id");<br>$DB-&gt;Execute("update table2 set val=$val2 where id=$id");<br>$DB-&gt;CommitTrans();<br></font></pre>
+<p><font>because you perform no error checking. It is possible to update table1 and 
+  for the update on table2 to fail. Here is a better way: 
+</font></p><pre><font>$DB-&gt;BeginTrans();<br>$ok = $DB-&gt;Execute("update table1 set val=$val1 where id=$id");<br>if ($ok) $ok = $DB-&gt;Execute("update table2 set val=$val2 where id=$id");<br>if ($ok) $DB-&gt;CommitTrans();<br>else $DB-&gt;RollbackTrans();<br></font></pre>
+<p><font>Another way is (since ADOdb 2.0): 
+</font></p><pre><font>$DB-&gt;BeginTrans();<br>$ok = $DB-&gt;Execute("update table1 set val=$val1 where id=$id");<br>if ($ok) $ok = $DB-&gt;Execute("update table2 set val=$val2 where id=$id");<br>$DB-&gt;CommitTrans($ok);<br></font></pre>
+<p><font> Now it is a headache monitoring $ok all over the place. StartTrans() is an
+improvement because it monitors all SQL errors for you. This is particularly
+useful if you are calling black-box functions in which SQL queries might be executed.
+ Also all BeginTrans, CommitTrans and RollbackTrans calls inside a StartTrans block 
+  will be disabled, so even if the black box function does a commit, it will be ignored.
+</font></p><pre><font>$DB-&gt;StartTrans();<br>CallBlackBox();<br>$DB-&gt;Execute("update table1 set val=$val1 where id=$id");<br>$DB-&gt;Execute("update table2 set val=$val2 where id=$id");<br>$DB-&gt;CompleteTrans();<br></font></pre>
+<p><font>Note that a StartTrans blocks are nestable, the inner blocks are ignored.
+ </font></p><p><font><b>CompleteTrans<a name="completetrans"></a>($autoComplete=true)</b></font></p>
+<font>  </font><p><font>Complete a transaction called with StartTrans(). This function monitors
+  for SQL errors, and will commit if no errors have occured, otherwise it will rollback. 
+  Returns true on commit, false on rollback. If the parameter $autoComplete is true
+  monitor sql errors and commit and rollback as appropriate. Set $autoComplete to false 
+  to force rollback even if no SQL error detected.
+  </font></p><p><font><b>FailTrans<a name="failtrans"></a>( )</b></font></p>
+<font>  </font><p><font>Fail a transaction started with StartTrans(). The rollback will only occur when
+  CompleteTrans() is called.
+    </font></p><p><font><b>HasFailedTrans<a name="hasfailedtrans"></a>( )</b></font></p>
+<font>	</font><p><font>Check whether smart transaction has failed, 
+	eg. returns true if there was an error in SQL execution or FailTrans() was called.
+	If not within smart transaction, returns false.
+</font></p><p><font><b>BeginTrans<a name="begintrans"></a>( )</b></font></p>
+<p><font>Begin a transaction. Turns off autoCommit. Returns true if successful. Some 
+  databases will always return false if transaction support is not available. 
+   Any open transactions will be rolled back when the connection is closed. Among the
+   databases that support transactions are Oracle, PostgreSQL, Interbase, MSSQL, certain
+    versions of MySQL, DB2, Informix, Sybase, etc.</font></p>
+<font> </font><p><font>Note that <a href="#starttrans">StartTrans()</a> and CompleteTrans() is a superior method of 
+ handling transactions, available since ADOdb 3.40. For a explanation, see the <a href="#starttrans">StartTrans()</a> documentation.
+
+</font></p><p><font>You can also use the ADOdb <a href="#errorhandling">error handler</a> to die 
+  and rollback your transactions for you transparently. Some buggy database extensions 
+  are known to commit all outstanding tranasactions, so you might want to explicitly 
+  do a $DB-&gt;RollbackTrans() in your error handler for safety. 
+ </font></p><h4><font>Detecting Transactions</font></h4>
+<font> </font><p><font>Since ADOdb 2.50, you are able to detect when you are inside a transaction. Check
+ that $connection-&gt;transCnt &gt; 0. This variable is incremented whenever BeginTrans() is called,
+ and decremented whenever RollbackTrans() or CommitTrans() is called.
+</font></p><p><font><b>CommitTrans<a name="committrans"></a>($ok=true)</b></font></p>
+<p><font>End a transaction successfully. Returns true if successful. If the database 
+  does not support transactions, will return true also as data is always committed. 
+</font></p>
+<p><font>If you pass the parameter $ok=false, the data is rolled back. See example in 
+  BeginTrans().</font></p>
+<p><font><b>RollbackTrans<a name="rollbacktrans"></a>( )</b></font></p>
+<p><font>End a transaction, rollback all changes. Returns true if successful. If the 
+  database does not support transactions, will return false as data is never rollbacked. 
+</font></p>
+ 
+<p><font><b>SetTransactionMode<a name="SetTransactionMode"></a>($mode )</b></font></p>
+<p>SetTransactionMode allows you to pass in the transaction mode to use for all subsequent transactions. 
+Note: if you have persistent connections and using mssql or mysql, you might have to explicitly reset your transaction mode at the beginning of each page request. 
+This is only supported in postgresql, mssql, mysql with InnoDB and oci8 currently. For example:
+<pre>
+$db->SetTransactionMode("SERIALIZABLE");
+$db->BeginTrans();
+$db->Execute(...); $db->Execute(...);
+$db->CommiTrans();
+
+$db->SetTransactionMode(""); // restore to default
+$db->StartTrans();
+$db->Execute(...); $db->Execute(...);
+$db->CompleteTrans();
+</pre>
+
+<p>Supported values to pass in:
+<ul>
+<li>READ UNCOMMITTED (allows dirty reads, but fastest)
+<li>READ COMMITTED (default postgres, mssql and oci8)
+<li>REPEATABLE READ (default mysql)
+<li>SERIALIZABLE (slowest and most restrictive)
+</ul>
+<p>You can also pass in database specific values such as 'SNAPSHOT' for mssql or 'READ ONLY' for oci8/postgres.
+<p>See transaction levels for <a href=http://www.postgresql.org/docs/8.1/interactive/sql-set-transaction.html>PostgreSQL</a>,
+<a href=http://www.stanford.edu/dept/itss/docs/oracle/10g/server.101/b10759/statements_10005.htm>Oracle</a>,
+<a href=http://dev.mysql.com/doc/refman/5.0/en/set-transaction.html>MySQL</a>, and
+<a href=http://msdn2.microsoft.com/en-US/ms173763.aspx>MS SQL Server</a>.
+<p><font><b>GetAssoc<a name="getassoc1"></a>($sql,$inputarr=false,$force_array=false,$first2cols=false)</b></font></p>
+<p><font>Returns an associative array for the given query $sql with optional bind parameters 
+  in $inputarr. If the number of columns returned is greater to two, a 2-dimensional 
+  array is returned, with the first column of the recordset becomes the keys 
+  to the rest of the rows. If the columns is equal to two, a 1-dimensional array 
+  is created, where the the keys directly map to the values (unless $force_array 
+  is set to true, when an array is created for each value).
+</font></p><p><font> Examples:<a name="getassocex"></a></font></p>
+
+<p><font>We have the following data in a recordset:</font></p>
+<p><font>row1: Apple, Fruit, Edible<br>
+  row2: Cactus, Plant, Inedible<br>
+  row3: Rose, Flower, Edible</font></p>
+<p><font>GetAssoc will generate the following 2-dimensional associative 
+  array:</font></p>
+<p><font>Apple =&gt; array[Fruit, Edible]<br>
+  Cactus =&gt; array[Plant, Inedible]<br>
+  Rose =&gt; array[Flower,Edible]</font></p>
+<p><font>If the dataset is:</font></p>
+<p><font>row1: Apple, Fruit<br>
+row2: Cactus, Plant<br>
+row3: Rose, Flower </font></p>
+<p><font>GetAssoc will generate the following 1-dimensional associative
+  array (with $force_array==false):</font></p>
+<p><font>Apple =&gt; Fruit</font><br>
+  Cactus=&gt;Plant<br>
+  Rose=&gt;Flower </p>
+<p><font>The function returns:</font></p>
+<p><font>The associative array, or false if an error occurs.</font></p>
+<font>
+<p><b>CacheGetAssoc<a name="cachegetassoc"></a>([$secs2cache,] $sql,$inputarr=false,$force_array=false,$first2cols=false)</b></p>
+</font>
+<p><font>Caching version of <a href="#getassoc1">GetAssoc</a> function above.
+</font></p><p><font><b>GetOne<a name="getone"></a>($sql,$inputarr=false)</b></font></p>
+<p><font>Executes the SQL and returns the first field of the first row. The recordset 
+  and remaining rows are discarded for you automatically. If an error occur, false 
+  is returned.</font></p>
+<p><font><b>GetRow<a name="getrow"></a>($sql,$inputarr=false)</b></font></p>
+<p><font>Executes the SQL and returns the first row as an array. The recordset and remaining 
+  rows are discarded for you automatically. If an error occurs, false is returned.</font></p>
+<p><font><b>GetAll<a name="getall"></a>($sql,$inputarr=false)</b></font></p>
+
+<p>Executes the SQL and returns the all the rows as a 2-dimensional 
+  array. The recordset is discarded for you automatically. If an error occurs, 
+  false is returned. <i>GetArray</i> is a synonym for <i>GetAll</i>.</p>
+ <p><b>GetCol<a name="getcol"></a>($sql,$inputarr=false,$trim=false)</b></p>
+
+<p><font>Executes the SQL and returns all elements of the first column as a 
+1-dimensional array. The recordset is discarded for you automatically. If an error occurs, 
+  false is returned.</font></p>
+<p><font><b>CacheGetOne<a name="cachegetone"></a>([$secs2cache,] 
+  $sql,$inputarr=false), CacheGetRow<a name="cachegetrow"></a>([$secs2cache,] $sql,$inputarr=false), CacheGetAll<a name="cachegetall"></a>([$secs2cache,] 
+  $sql,$inputarr=false), CacheGetCol<a name="cachegetcol"></a>([$secs2cache,] 
+  $sql,$inputarr=false,$trim=false)</b></font></p>
+<font> 
+</font><p><font>Similar to above Get* functions, except that the recordset is serialized and 
+  cached in the $ADODB_CACHE_DIR directory for $secs2cache seconds. Good for speeding 
+  up queries on rarely changing data. Note that the $secs2cache parameter is optional. 
+  If omitted, we use the value in $connection-&gt;cacheSecs (default is 3600 seconds, 
+  or 1 hour).</font></p>
+<p><font><b>Prepare<a name="prepare"></a>($sql )</b></font></p>
+ 
+<p><font>Prepares (compiles) an SQL query for repeated execution. Bind parameters
+are denoted by ?, except for the oci8 driver, which uses the traditional Oracle :varname
+convention. 
+  </font></p>
+<p><font>Returns an array containing the original sql statement 
+  in the first array element; the remaining elements of the array are driver dependent. 
+  If there is an error, or we are emulating Prepare( ), we return the original 
+  $sql string. This is because all error-handling has been centralized in Execute( 
+  ).</font></p>
+<p><font>Prepare( ) cannot be used with functions that use SQL 
+  query rewriting techniques, e.g. PageExecute( ) and SelectLimit( ).</font></p>
+<p>Example:</p>
+<pre><font>$stmt = $DB-&gt;Prepare('insert into table (col1,col2) values (?,?)');<br>for ($i=0; $i &lt; $max; $i++)<br></font>	$DB-&gt;<font>Execute($stmt,array((string) rand(), $i));<br></font></pre>
+<font> 
+</font><p><font>Also see InParameter(), OutParameter() and PrepareSP() below. Only supported internally by interbase, 
+  oci8 and selected ODBC-based drivers, otherwise it is emulated. There is no 
+  performance advantage to using Prepare() with emulation. 
+</font></p><p><font> Important: Due to limitations or bugs in PHP, if you are getting errors when 
+  you using prepared queries, try setting $ADODB_COUNTRECS = false before preparing. 
+  This behaviour has been observed with ODBC. 
+</font></p><p><font><b>IfNull<a name="ifnull"></a>($field, $nullReplacementValue)</b></font></p>
+<p><font>Portable IFNULL function (NVL in Oracle). Returns a string that represents 
+  the function that checks whether a $field is null for the given database, and 
+  if null, change the value returned to $nullReplacementValue. Eg.</font></p>
+<pre><font>$sql = <font color="#993300">'SELECT '</font>.$db-&gt;IfNull('name', <font color="#993300">"'- unknown -'"</font>).<font color="#993300"> ' FROM table'</font>;</font></pre>
+
+<p><font><b>length<a name="length"></a></b></font></p>
+<p><font>This is not a function, but a property. Some databases have "length" and others "len"
+as the function to measure the length of a string. To use this property:
+</font></p><pre><font>  $sql = <font color="#993300">"SELECT "</font>.$db-&gt;length.<font color="#993300">"(field) from table"</font>;<br>  $rs = $db-&gt;Execute($sql);<br></font></pre>
+
+<p><font><b>random<a name="random"></a></b></font></p>
+<p><font>This is not a function, but a property. This is a string that holds the sql to
+generate a random number between 0.0 and 1.0 inclusive.
+
+</font></p><p><font><b>substr<a name="substr"></a></b></font></p>
+<p><font>This is not a function, but a property. Some databases have "substr" and others "substring"
+as the function to retrieve a sub-string. To use this property:
+</font></p><pre><font>  $sql = <font color="#993300">"SELECT "</font>.$db-&gt;substr.<font color="#993300">"(field, $offset, $length) from table"</font>;<br>  $rs = $db-&gt;Execute($sql);<br></font></pre>
+<p><font>For all databases, the 1st parameter of <i>substr</i> is the field, the 2nd is the
+offset (1-based) to the beginning of the sub-string, and the 3rd is the length of the sub-string.
+
+
+</font></p><p><font><b>Param<a name="param"></a>($name)</b></font></p>
+<p><font>Generates a bind placeholder portably. For most databases, the bind placeholder 
+  is "?". However some databases use named bind parameters such as Oracle, eg 
+  ":somevar". This allows us to portably define an SQL statement with bind parameters: 
+</font></p><pre><font>$sql = <font color="#993300">'insert into table (col1,col2) values ('</font>.$DB-&gt;Param('a').<font color="#993300">','</font>.$DB-&gt;Param('b').<font color="#993300">')'</font>;<br><font color="#006600"># generates 'insert into table (col1,col2) values (?,?)'<br># or        'insert into table (col1,col2) values (:a,:b)</font>'<br>$stmt = $DB-&gt;Prepare($sql);<br>$stmt = $DB-&gt;Execute($stmt,array('one','two'));<br></font></pre>
+<font> </font>
+<p></p>
+<p><font><b>PrepareSP</b><b><a name="preparesp"></a></b><b>($sql,
+$cursor=false )</b></font></p>
+<p><font>When calling stored procedures in mssql and oci8 (oracle),
+    and you might want to directly bind to parameters that return values, or
+for special LOB handling. PrepareSP() allows you to do so. </font></p>
+<p><font>Returns the same array or $sql string as Prepare( )
+    above. If you do not need to bind to return values, you should use Prepare(
+  ) instead.</font></p>
+<p><font>The 2nd parameter, $cursor is not used except with oci8.
+    Setting it to true will force OCINewCursor to be called; this is to support
+output REF CURSORs. </font></p>
+<p><font>For examples of usage of PrepareSP( ), see InParameter(
+) below. </font></p>
+<p><font>Note: in the mssql driver, preparing stored procedures
+    requires a special function call, mssql_init( ), which is called by this
+    function. PrepareSP( ) is available in all other drivers, and is emulated
+  by calling Prepare( ). </font></p>
+<p><font><b> InParameter<a name="inparameter"></a>($stmt, $var,
+  $name, $maxLen = 4000, $type = false )</b></font></p>
+<font>Binds a PHP variable as input to a stored procedure variable.
+The parameter <i>$stmt</i> is the value returned by PrepareSP(), <i>$var</i> is
+the PHP variable you want to bind, $name is the name of the stored procedure
+variable. Optional is <i>$maxLen</i>, the maximum length of the data to bind,
+and $type which is database dependant. Consult <a href="http://php.net/mssql_bind">mssql_bind</a> and <a href="http://php.net/ocibindbyname">ocibindbyname</a> docs
+at php.net for more info on legal values for $type. </font>
+<p>
+<font>InParameter() is a wrapper function that calls Parameter()
+with $isOutput=false. The advantage of this function is that it is self-documenting,
+because the $isOutput parameter is no longer needed. Only for mssql and oci8
+currently. </font></p>
+<p><font>Here is an example using oci8: </font></p>
+<pre><font><font color="green"># For oracle, Prepare and PrepareSP are identical</font>
+$stmt = $db-&gt;PrepareSP(
+	<font color="#993300">"declare RETVAL integer; <br>	begin<br>	:RETVAL := </font><font color="#993300">SP_RUNSOMETHING</font><font color="#993300">(:myid,:group);<br>	end;"</font>);<br>$db-&gt;InParameter($stmt,$id,'myid');<br>$db-&gt;InParameter($stmt,$group,'group',64);<br>$db-&gt;OutParameter($stmt,$ret,'RETVAL');<br>$db-&gt;Execute($stmt);<br></font></pre>
+<p><font> The same example using mssql:</font></p>
+<font> 
+</font><pre><font><font color="green"># @RETVAL = SP_RUNSOMETHING @myid,@group</font>
+$stmt = $db-&gt;PrepareSP(<font color="#993333">'<font color="#993300">SP_RUNSOMETHING</font>'</font>); <br><font color="green"># note that the parameter name does not have @ in front!</font>
+$db-&gt;InParameter($stmt,$id,'myid');
+$db-&gt;InParameter($stmt,$group,'group',64);
+<font color="green"># return value in mssql - RETVAL is hard-coded name</font> <br>$db-&gt;OutParameter($stmt,$ret,'RETVAL');<br>$db-&gt;Execute($stmt); </font></pre>
+
+<p><font>Note that the only difference between the oci8 and mssql implementations is $sql.</font></p>
+<p>
+<font> If $type parameter is set to false, in mssql, $type will be dynamicly determined 
+based on the type of the PHP variable passed <font face="Courier New, Courier, mono">(string 
+=&gt; SQLCHAR, boolean =&gt;SQLINT1, integer =&gt;SQLINT4 or float/double=&gt;SQLFLT8)</font>.
+</font></p><p><font> 
+In oci8, $type can be set to OCI_B_FILE (Binary-File), OCI_B_CFILE (Character-File), 
+OCI_B_CLOB (Character-LOB), OCI_B_BLOB (Binary-LOB) and OCI_B_ROWID (ROWID). To 
+pass in a null, use<font face="Courier New, Courier, mono"> $db-&gt;Parameter($stmt, 
+$null=null, 'param')</font>. 
+  </font></p><p><font><b> OutParameter<a name="outparameter"></a>($stmt, $var, $name, 
+  $maxLen = 4000, $type = false )</b></font></p>
+<font>  Binds a PHP variable as output from a stored procedure variable. The parameter <i>$stmt</i>
+ is the value returned by PrepareSP(), <i>$var</i> is the PHP variable you want to bind, <i>$name</i>
+ is the name of the stored procedure variable. Optional is <i>$maxLen</i>, the maximum length of the
+ data to bind, and <i>$type</i> which is database dependant. 
+</font><p>
+<font>  OutParameter() is a wrapper function that calls Parameter() with $isOutput=true. 
+  The advantage of this function is that it is self-documenting, because
+the $isOutput parameter is no longer needed.  Only for mssql 
+  and oci8 currently.
+</font></p><p>
+<font>For an example, see <a href="#inparameter">InParameter</a>.
+
+</font></p><p><font><b> Parameter<a name="parameter"></a>($stmt, $var, $name, $isOutput=false, 
+  $maxLen = 4000, $type = false )</b></font></p>
+<p><font>Note: This function is deprecated, because of the new InParameter() and OutParameter() functions.
+These are superior because they are self-documenting, unlike Parameter().
+</font></p><p><font>Adds a bind parameter suitable for return values or special data handling (eg. 
+  LOBs) after a statement has been prepared using PrepareSP(). Only for mssql 
+  and oci8 currently. The parameters are:<br>
+  <br>
+  $<i><b>stmt</b></i> Statement returned by Prepare() or PrepareSP().<br>
+  $<i><b>var</b></i> PHP variable to bind to. Make sure you pre-initialize it!<br>
+  $<i><b>name</b></i> Name of stored procedure variable name to bind to.<br>
+  [$<i><b>isOutput</b></i>] Indicates direction of parameter 0/false=IN 1=OUT 
+  2= IN/OUT. This is ignored in oci8 as this driver auto-detects the direction.<br>
+  [$<b>maxLen</b>] Maximum length of the parameter variable.<br>
+  [$<b>type</b>] Consult <a href="http://php.net/mssql_bind">mssql_bind</a> and 
+  <a href="http://php.net/ocibindbyname">ocibindbyname</a> docs at php.net for 
+  more info on legal values for type.</font></p>
+<p><font>Lastly, in oci8, bind parameters can be reused without calling PrepareSP( ) 
+  or Parameters again. This is not possible with mssql. An oci8 example:</font></p>
+<pre><font>$id = 0; $i = 0;<br>$stmt = $db-&gt;PrepareSP( <font color="#993300">"update table set val=:i where id=:id"</font>);<br>$db-&gt;Parameter($stmt,$id,'id');<br>$db-&gt;Parameter($stmt,$i, 'i');<br>for ($cnt=0; $cnt &lt; 1000; $cnt++) {<br>	$id = $cnt; <br>	$i = $cnt * $cnt; <font color="green"># works with oci8!</font>
+	$db-&gt;Execute($stmt); <br>}</font></pre>
+<p><font><b>Bind<a name="bind"></a>($stmt, $var, $size=4001, $type=false, $name=false)</b></font></p>
+ 
+<p><font>This is a low-level function supported only by the oci8 
+  driver. <b>Avoid using</b> unless you only want to support Oracle. The Parameter( 
+  ) function is the recommended way to go with bind variables.</font></p>
+<p><font>Bind( ) allows you to use bind variables in your sql 
+  statement. This binds a PHP variable to a name defined in an Oracle sql statement 
+  that was previously prepared using Prepare(). Oracle named variables begin with 
+  a colon, and ADOdb requires the named variables be called :0, :1, :2, :3, etc. 
+  The first invocation of Bind() will match :0, the second invocation will match 
+  :1, etc. Binding can provide 100% speedups for insert, select and update statements. 
+  </font></p>
+<p>The other variables, $size sets the buffer size for data storage, $type is 
+  the optional descriptor type OCI_B_FILE (Binary-File), OCI_B_CFILE (Character-File), 
+  OCI_B_CLOB (Character-LOB), OCI_B_BLOB (Binary-LOB) and OCI_B_ROWID (ROWID). 
+  Lastly, instead of using the default :0, :1, etc names, you can define your 
+  own bind-name using $name. 
+</p><p><font>The following example shows 3 bind variables being used: 
+  p1, p2 and p3. These variables are bound to :0, :1 and :2.</font></p>
+<pre>$stmt = $DB-&gt;Prepare("insert into table (col0, col1, col2) values (:0, :1, :2)");<br>$DB-&gt;Bind($stmt, $p1);<br>$DB-&gt;Bind($stmt, $p2);<br>$DB-&gt;Bind($stmt, $p3);<br>for ($i = 0; $i &lt; $max; $i++) { <br>   $p1 = ?; $p2 = ?; $p3 = ?;<br>   $DB-&gt;Execute($stmt);<br>}</pre>
+<p>You can also use named variables:</p>
+<pre>$stmt = $DB-&gt;Prepare("insert into table (col0, col1, col2) values (:name0, :name1, :name2)");<br>$DB-&gt;Bind($stmt, $p1, "name0");<br>$DB-&gt;Bind($stmt, $p2, "name1");<br>$DB-&gt;Bind($stmt, $p3, "name2");<br>for ($i = 0; $i &lt; $max; $i++) { <br>   $p1 = ?; $p2 = ?; $p3 = ?;<br>   $DB-&gt;Execute($stmt);<br>}</pre>
+<p><b>LogSQL($enable=true)<a name="logsql"></a></b></p>
+Call this method to install a SQL logging and timing function (using fnExecute). 
+Then all SQL statements are logged into an adodb_logsql table in a database. If 
+the adodb_logsql table does not exist, ADOdb will create the table if you have 
+the appropriate permissions. Returns the previous logging value (true for enabled, 
+false for disabled). Here are samples of the DDL for selected databases: 
+<p> 
+</p><pre>		<b>mysql:</b>
+		CREATE TABLE adodb_logsql (
+		  created datetime NOT NULL,
+		  sql0 varchar(250) NOT NULL,
+		  sql1 text NOT NULL,
+		  params text NOT NULL,
+		  tracer text NOT NULL,
+		  timer decimal(16,6) NOT NULL
+		)
+		
+		<b>postgres:</b>
+		CREATE TABLE adodb_logsql (
+		  created timestamp NOT NULL,
+		  sql0 varchar(250) NOT NULL,
+		  sql1 text NOT NULL,
+		  params text NOT NULL,
+		  tracer text NOT NULL,
+		  timer decimal(16,6) NOT NULL
+		)
+		
+		<b>mssql:</b>
+		CREATE TABLE adodb_logsql (
+		  created datetime NOT NULL,
+		  sql0 varchar(250) NOT NULL,
+		  sql1 varchar(4000) NOT NULL,
+		  params varchar(3000) NOT NULL,
+		  tracer varchar(500) NOT NULL,
+		  timer decimal(16,6) NOT NULL
+		)
+		
+		<b>oci8:</b>
+		CREATE TABLE adodb_logsql (
+		  created date NOT NULL,
+		  sql0 varchar(250) NOT NULL,
+		  sql1 varchar(4000) NOT NULL,
+		  params varchar(4000),
+		  tracer varchar(4000),
+		  timer decimal(16,6) NOT NULL
+		)
+</pre>
+Usage: 
+<pre>	$conn-&gt;LogSQL(); // turn on logging<br>	  :<br>	$conn-&gt;Execute(...);<br>	  :<br>	$conn-&gt;LogSQL(false); // turn off logging<br>	<br>	# output summary of SQL logging results<br>	$perf = NewPerfMonitor($conn);<br>	echo $perf-&gt;SuspiciousSQL();<br>	echo $perf-&gt;ExpensiveSQL();<br></pre>
+<p>One limitation of logging is that rollback also prevents SQL from being logged.
+</p><p>
+If you prefer to use another name for the table used to store the SQL, you can override it by calling 
+adodb_perf::table($tablename), where $tablename is the new table name (you will still need to manually
+create the table yourself). An example:
+</p><pre>	include('adodb.inc.php');<br>	include('adodb-perf.inc.php');<br>	adodb_perf::table('my_logsql_table');<br></pre>
+Also see <a href="docs-perf.htm">Performance Monitor</a>. 
+<p><font><b>fnExecute and fnCacheExecute properties<a name="fnexecute" id="fnexecute"></a></b></font></p>
+<p>These two properties allow you to define bottleneck functions for all sql statements 
+  processed by ADOdb. This allows you to perform statistical analysis and query-rewriting 
+  of your sql. 
+</p><p><b>Examples of fnExecute</b></p>
+<p>Here is an example of using fnExecute, to count all cached queries and non-cached 
+  queries, you can do this:</p>
+<pre><font color="#006600"># $db is the connection object</font>
+function &CountExecs($db, $sql, $inputarray)
+{
+global $EXECS;
+
+	if (!is_array(inputarray)) $EXECS++;
+	<font color="#006600"># handle 2-dimensional input arrays</font>
+	else if (is_array(reset($inputarray))) $EXECS += sizeof($inputarray);
+	else $EXECS++;
+	
+	<font color="#006600"># in PHP4.4 and PHP5, we need to return a value by reference</font>
+	$null = null;
+	return $null;
+}
+
+<font color="#006600"># $db is the connection object</font>
+function CountCachedExecs($db, $secs2cache, $sql, $inputarray)
+{<br>global $CACHED; $CACHED++;<br>}<br><br>$db = NewADOConnection('mysql');<br>$db-&gt;Connect(...);<br>$db-&gt;<strong>fnExecute</strong> = 'CountExecs';<br>$db-&gt;<strong>fnCacheExecute</strong> = 'CountCachedExecs';<br> :<br> :<br><font color="#006600"># After many sql statements:</font>`<br>printf("&lt;p&gt;Total queries=%d; total cached=%d&lt;/p&gt;",$EXECS+$CACHED, $CACHED);<br></pre>
+<p>The fnExecute function is called before the sql is parsed and executed, so 
+  you can perform a query rewrite. If you are passing in a prepared statement, 
+  then $sql is an array (see <a href="#prepare">Prepare</a>). The fnCacheExecute 
+  function is only called if the recordset returned was cached.<font> 
+  The function parameters match the Execute and CacheExecute functions respectively, 
+  except that $this (the connection object) is passed as the first parameter.</font></p>
+<p>Since ADOdb 3.91, the behaviour of fnExecute varies depending on whether the 
+  defined function returns a value. If it does not return a value, then the $sql 
+  is executed as before. This is useful for query rewriting or counting sql queries. 
+</p><p> On the other hand, you might want to replace the Execute function with one 
+  of your own design. If this is the case, then have your function return a value. 
+  If a value is returned, that value is returned immediately, without any further 
+  processing. This is used internally by ADOdb to implement LogSQL() functionality. 
+</p>
+<p>
+</p><hr />
+<h3><font>ADOConnection Utility Functions</font></h3>
+<p><font><b>BlankRecordSet<a name="blankrecordset"></a>([$queryid])</b></font></p>
+<p><font>No longer available - removed since 1.99.</font></p>
+<p><font><b>Concat<a name="concat"></a>($s1,$s2,....)</b></font></p>
+<p><font>Generates the sql string used to concatenate $s1, $s2, etc together. Uses the 
+  string in the concat_operator field to generate the concatenation. Override 
+  this function if a concatenation operator is not used, eg. MySQL.</font></p>
+<p><font>Returns the concatenated string.</font></p>
+<p><font><b>DBDate<a name="dbdate"></a>($date)</b></font></p>
+<p><font>Format the $<b>date</b> in the format the database accepts. This is used in 
+  INSERT/UPDATE statements; for SELECT statements, use <a href="#sqldate">SQLDate</a>. 
+  The $<b>date</b> parameter can be a Unix integer timestamp or an ISO format 
+  Y-m-d. Uses the fmtDate field, which holds the format to use. If null or false 
+  or '' is passed in, it will be converted to an SQL null.</font></p>
+<p><font>Returns the date as a quoted string.</font></p>
+<pre>
+	$sql = "select * from atable where created > ".$db->DBDate("$year-$month-$day");
+	$db->Execute($sql);
+</pre>
+<p><font><b>BindDate<a name="binddate"></a>($date)</b></font></p>
+<p><font>Format the $<b>date</b> in the bind format the database accepts. Normally
+ this means that the date string is not quoted, unlike DBDate, which quotes the string.
+<pre>
+	$sql = "select * from atable where created > ".$db->Param('0');
+	// or
+	$sql = "select * from atable where created > ?";
+	$db->Execute($sql,array($db->BindDate("$year-$month-$day"));
+</pre>
+<p><font><b>DBTimeStamp<a name="dbtimestamp"></a>($ts)</b></font></p>
+<p><font>Format the timestamp $<b>ts</b> in the format the database accepts; this can 
+  be a Unix integer timestamp or an ISO format Y-m-d H:i:s. Uses the fmtTimeStamp 
+  field, which holds the format to use. If null or false or '' is passed in, it 
+  will be converted to an SQL null.</font></p>
+<p><font>Returns the timestamp as a quoted string.</font></p>
+<pre>
+	$sql = "select * from atable where created > ".$db->DBTimeStamp("$year-$month-$day $hr:$min:$secs");
+	$db->Execute($sql);
+</pre>
+<p><font><b>BindTimeStamp<a name="bindtimestamp"></a>($ts)</b></font></p>
+<p><font>Format the timestamp $<b>ts</b> in the bind format the database accepts. Normally
+ this means that the timestamp string is not quoted, unlike DBTimeStamp, which quotes the string.
+<pre>
+	$sql = "select * from atable where created > ".$db->Param('0');
+	// or
+	$sql = "select * from atable where created > ?";
+	$db->Execute($sql,array($db->BindTimeStamp("$year-$month-$day $hr:$min:$secs"));
+</pre>
+<p><font><b>qstr<a name="qstr"></a>($s,[$magic_quotes_enabled</b>=false]<b>)</b></font></p>
+<p><font>Quotes a string to be sent to the database. The $<b>magic_quotes_enabled</b> 
+  parameter may look funny, but the idea is if you are quoting a string extracted 
+  from a POST/GET variable, then pass get_magic_quotes_gpc() as the second parameter. 
+  This will ensure that the variable is not quoted twice, once by <i>qstr</i> 
+  and once by the <i>magic_quotes_gpc</i>.</font></p>
+<p><font>Eg.<font face="Courier New, Courier, mono"> $s = $db-&gt;qstr(HTTP_GET_VARS['name'],get_magic_quotes_gpc());</font></font></p>
+<p><font>Returns the quoted string.</font></p>
+<p><font><b>Quote<a name="quote"></a>($s)</b></font></p>
+<p><font>Quotes the string $s, escaping the database specific quote character as appropriate. 
+  Formerly checked magic quotes setting, but this was disabled since 3.31 for 
+  compatibility with PEAR DB. 
+</font></p><p><font><b>Affected_Rows<a name="affected_rows"></a>( )</b></font></p>
+<p><font>Returns the number of rows affected by a update or delete statement. Returns 
+  false if function not supported.</font></p>
+<p><font>Not supported by interbase/firebird currently. </font></p>
+<p><font><b>Insert_ID<a name="inserted_id"></a>( )</b></font></p>
+<p><font>Returns the last autonumbering ID inserted. Returns false if function not supported. 
+</font></p>
+<p><font>Only supported by databases that support auto-increment or object id's, such 
+  as PostgreSQL, MySQL and MS SQL Server currently. PostgreSQL returns the OID, which 
+  can change on a database reload.</font></p>
+<p><font><b>RowLock<a name="rowlock"></a>($table,$where)</b></font></p>
+<p><font>Lock a table row for the duration of a transaction. For example to lock record $id in table1:
+</font></p><pre><font>	$DB-&gt;StartTrans();<br>	$DB-&gt;RowLock("table1","rowid=$id");<br>	$DB-&gt;Execute($sql1);<br>	$DB-&gt;Execute($sql2);<br>	$DB-&gt;CompleteTrans();<br></font></pre>
+<p><font>Supported in db2, interbase, informix, mssql, oci8, postgres, sybase.
+</font></p><p><font><b>MetaDatabases<a name="metadatabases"></a>()</b></font></p>
+<p><font>Returns a list of databases available on the server as an array. You have to 
+  connect to the server first. Only available for ODBC, MySQL and ADO.</font></p>
+<p><font><b>MetaTables<a name="metatables"></a>($ttype = false, $showSchema = false, 
+  $mask=false)</b></font></p>
+<p><font>Returns an array of tables and views for the current database as an array. 
+  The array should exclude system catalog tables if possible. To only show tables, 
+  use $db-&gt;MetaTables('TABLES'). To show only views, use $db-&gt;MetaTables('VIEWS'). 
+  The $showSchema parameter currently works only for DB2, and when set to true, 
+  will add the schema name to the table, eg. "SCHEMA.TABLE". </font></p>
+<p><font>You can define a mask for matching. For example, setting $mask = 'TMP%' will 
+  match all tables that begin with 'TMP'. Currently only mssql, oci8, odbc_mssql 
+  and postgres* support $mask. 
+</font></p><p><font><b>MetaColumns<a name="metacolumns"></a>($table,$notcasesensitive=true)</b></font></p>
+<p><font>Returns an array of ADOFieldObject's, one field object for every column of 
+  $table. A field object is a class instance with (name, type, max_length) defined.
+  Currently Sybase does not recognise date types, and ADO cannot identify 
+  the correct data type (so we default to varchar).   
+ </font></p><p><font> The $notcasesensitive parameter determines whether we uppercase or lowercase the table name to normalize it
+ (required for some databases). Does not work with MySQL ISAM tables.
+ </font></p><p><font>For schema support, pass in the $table parameter, "$schema.$tablename". This is only
+ supported for selected databases.
+</font></p><p><font><b>MetaColumnNames<a name="metacolumnames"></a>($table,$numericIndex=false)</b></font></p>
+<p><font>Returns an array of column names for $table. Since ADOdb 4.22, this is an associative array, with the
+keys in uppercase. Set $numericIndex=true if you want the old behaviour of numeric indexes (since 4.23).
+</font></p><p>
+<font>e.g. array('FIELD1' =&gt; 'Field1', 'FIELD2'=&gt;'Field2')
+</font></p><p>
+</p><p><font><b>MetaPrimaryKeys<a name="metaprimarykeys"></a>($table,
+      $owner=false)</b></font> 
+</p>
+<p><font>Returns an array containing column names that are the 
+  primary keys of $table. Supported by mysql, odbc (including db2, odbc_mssql, 
+etc), mssql, postgres, interbase/firebird, oci8 currently. </font></p>
+<p><font>Views (and some tables) have primary keys, but sometimes this information is not available from the
+database. You can define a function  ADODB_View_PrimaryKeys($databaseType, $database, $view, $owner) that
+should return an array containing the fields that make up the primary key. If that function exists,
+it will be called when MetaPrimaryKeys() cannot find a primary key for a table or view.
+</font></p><pre><font>// In this example: dbtype = 'oci8', $db = 'mydb', $view = 'dataView', $owner = false <br>function ADODB_View_PrimaryKeys($dbtype,$db,$view,$owner)<br>{<br>	switch(strtoupper($view)) {<br>	case 'DATAVIEW': return array('DATAID');<br>	default: return false;<br>	}<br>}<br><br>$db = NewADOConnection('oci8');<br>$db-&gt;Connect('localhost','root','','mydb'); <br>$db-&gt;MetaPrimaryKeys('dataView');<br></font></pre>
+<p><font><b>ServerInfo<a name="serverinfo" id="serverinfo"></a>()</b></font> 
+</p>
+<p><font>Returns an array of containing two elements 'description' 
+  and 'version'. The 'description' element contains the string description of 
+  the database. The 'version' naturally holds the version number (which is also 
+a string).</font></p>
+<p><font><b>MetaForeignKeys<a name="metaforeignkeys"></a>($table, $owner=false, $upper=false)</b> 
+</font></p><p><font>Returns an associate array of foreign keys, or false if not supported. For 
+  example, if table employee has a foreign key where employee.deptkey points to 
+  dept_table.deptid, and employee.posn=posn_table.postionid and employee.poscategory=posn_table.category, 
+  then $conn-&gt;MetaForeignKeys('employee') will return 
+</font></p><pre><font>	array(<br>		'dept_table' =&gt; array('deptkey=deptid'),<br>		'posn_table' =&gt; array('posn=positionid','poscategory=category')<br>	)<br></font></pre>
+<p><font>The optional schema or owner can be defined in $owner. If $upper is true, then 
+  the table names (array keys) are upper-cased. 
+</font></p><hr />
+<h2><font>ADORecordSet<a name="adorecordset"></a></font></h2>
+<p><font>When an SQL statement successfully is executed by <font face="Courier New, Courier, mono">ADOConnection-&gt;Execute($sql),</font>an 
+  ADORecordSet object is returned. This object contains a virtual cursor so we 
+  can move from row to row, functions to obtain information about the columns 
+  and column types, and helper functions to deal with formating the results to 
+  show to the user.</font></p>
+<h3><font>ADORecordSet Fields</font></h3>
+<p><font><b>fields: </b>Array containing the current row. This is not associative, but 
+  is an indexed array from 0 to columns-1. See also the function <b><a href="#fields">Fields</a></b>, 
+  which behaves like an associative array.</font></p>
+<p><font><b>dataProvider</b>: The underlying mechanism used to connect to the database. 
+  Normally set to <b>native</b>, unless using <b>odbc</b> or <b>ado</b>.</font></p>
+<p><font><b>blobSize</b>: Maximum size of a char, string or varchar object before it 
+  is treated as a Blob (Blob's should be shown with textarea's). See the <a href="#metatype">MetaType</a> 
+  function.</font></p>
+<p><font><b>sql</b>: Holds the sql statement used to generate this record set.</font></p>
+<p><font><b>canSeek</b>: Set to true if Move( ) function works.</font></p>
+<p><font><b>EOF</b>: True if we have scrolled the cursor past the last record.</font></p>
+<h3><font>ADORecordSet Functions</font></h3>
+<p><font><b>ADORecordSet( )</b></font></p>
+<p><font>Constructer. Normally you never call this function yourself.</font></p>
+<p><font><b>GetAssoc<a name="getassoc"></a>([$force_array])</b></font></p>
+<p><font>Generates an associative array from the recordset. Note that is this function 
+  is also <a href="#getassoc1">available</a> in the connection object. More details 
+  can be found there.</font></p>
+<font> </font>
+<p><font><b>GetArray<a name="getarray"></a>([$number_of_rows])</b></font></p>
+<p><font>Generate a 2-dimensional array of records from the current
+    cursor position, indexed from 0 to $number_of_rows - 1. If $number_of_rows
+  is undefined, till EOF.</font></p>
+<p><font><b>GetRows<a name="getrows"></a>([$number_of_rows])</b></font></p>
+<font>Generate a 2-dimensional array of records from the current
+cursor position. Synonym for GetArray() for compatibility with Microsoft ADO. </font>
+<p><font> <b>GetMenu<a name="getmenu"></a>($name, [$default_str=''],
+  [$blank1stItem=true], [$multiple_select=false], [$size=0], [$moreAttr=''])</b></font></p>
+<p><font>Generate a HTML menu (&lt;select&gt;&lt;option&gt;&lt;option&gt;&lt;/select&gt;).
+    The first column of the recordset (fields[0]) will hold the string to display
+    in the option tags. If the recordset has more than 1 column, the second column
+    (fields[1]) is the value to send back to the web server.. The menu will be
+given the name $<i>name</i>. </font></p>
+<p><font> If $<i>default_str</i> is defined, then if $<i>default_str</i> ==
+    fields[0], that field is selected. If $<i>blank1stItem</i> is true, the first
+    option is empty. You can also set the first option strings by setting $blank1stItem
+  = "$value:$text".</font></p>
+<p><font>$<i>Default_str</i> can be array for a multiple select
+listbox.</font></p>
+<p><font>To get a listbox, set the $<i>size</i> to a non-zero
+    value (or pass $default_str as an array). If $<i>multiple_select</i> is true
+    then a listbox will be generated with $<i>size</i> items (or if $size==0,
+    then 5 items) visible, and we will return an array to a server. Lastly use
+  $<i>moreAttr </i> to add additional attributes such as javascript or styles. </font></p>
+<p><font>Menu Example 1: <code>GetMenu('menu1','A',true)</code> will
+    generate a menu:
+    <select name="menu1"><option> </option><option value="1" selected="selected">A </option><option value="2">B </option><option value="3">C </option></select>
+for the data (A,1), (B,2), (C,3). Also see <a href="#ex5">example 5</a>.</font></p>
+<p><font>Menu Example 2: For the same data, <code>GetMenu('menu1',array('A','B'),false)</code> will
+    generate a menu with both A and B selected: <br>
+    <select name="menu1" multiple="multiple" size="3"><option value="1" selected="selected">A </option><option value="2" selected="selected">B </option><option value="3">C </option></select>
+</font></p>
+<p><font> <b>GetMenu2<a name="getmenu2"></a>($name, [$default_str=''],
+  [$blank1stItem=true], [$multiple_select=false], [$size=0], [$moreAttr=''])</b></font></p>
+<p><font>This is nearly identical to GetMenu, except that the
+  $<i>default_str</i> is matched to fields[1] (the option values).</font></p>
+<p><font>Menu Example 3: Given the data in menu example 2, <code>GetMenu2('menu1',array('1','2'),false)</code> will
+    generate a menu with both A and B selected in menu example 2, but this time
+    the selection is based on the 2nd column, which holds the values to return
+to the Web server. </font></p>
+<p><font><b>UserDate<a name="userdate"></a>($str, [$fmt])</b></font></p>
+<p><font>Converts the date string $<i>str</i> to another format.
+    The date format is Y-m-d, or Unix timestamp format. The default $<i>fmt</i> is
+Y-m-d.</font></p>
+<p><font><b>UserTimeStamp<a name="usertimestamp"></a>($str, [$fmt])</b></font></p>
+<p><font>Converts the timestamp string $<b>str</b> to another
+    format. The timestamp format is Y-m-d H:i:s, as in '2002-02-28 23:00:12',
+    or Unix timestamp format. UserTimeStamp calls UnixTimeStamp to parse $<i>str</i>,
+and $<i>fmt</i> defaults to Y-m-d H:i:s if not defined. </font></p>
+<p><font><b>UnixDate<a name="unixdate"></a>($str)</b></font></p>
+<p><font>Parses the date string $<b>str</b> and returns it in
+    unix mktime format (eg. a number indicating the seconds after January 1st,
+    1970). Expects the date to be in Y-m-d H:i:s format, except for Sybase and
+    Microsoft SQL Server, where M d Y is also accepted (the 3 letter month strings
+  are controlled by a global array, which might need localisation).</font></p>
+<p><font>This function is available in both ADORecordSet and
+ADOConnection since 1.91.</font></p>
+<p><font><b>UnixTimeStamp<a name="unixtimestamp"></a>($str)</b></font></p>
+<p><font>Parses the timestamp string $<b>str</b> and returns
+    it in unix mktime format (eg. a number indicating the seconds after January
+    1st, 1970). Expects the date to be in "Y-m-d, H:i:s" (1970-12-24, 00:00:00)
+    or "Y-m-d H:i:s" (1970-12-24 00:00:00) or "YmdHis" (19701225000000) format,
+    except for Sybase and Microsoft SQL Server, where "M d Y h:i:sA" (Dec 25
+    1970 00:00:00AM) is also accepted (the 3 letter month strings are controlled
+by a global array, which might need localisation).</font></p>
+<font> 
+</font><p><font>This function is available in both ADORecordSet
+    and ADOConnection since 1.91. </font></p>
+<p><font><b>OffsetDate<a name="OffsetDate"></a>($dayFraction,
+  $basedate=false)</b></font></p>
+<p><font>Returns a string with the native SQL functions to calculate
+    future and past dates based on $basedate in a portable fashion. If $basedate
+    is not defined, then the current date (at 12 midnight) is used. Returns the
+  SQL string that performs the calculation when passed to Execute(). </font></p>
+<p><font>For example, in Oracle, to find the date and time that
+  is 2.5 days from today, you can use:</font></p>
+<pre><font># get date one week from now<br>$fld = $conn-&gt;OffsetDate(7); // returns "(trunc(sysdate)+7")</font></pre>
+<pre><font># get date and time that is 60 hours from current date and time<br>$fld = $conn-&gt;OffsetDate(2.5, $conn-&gt;sysTimeStamp);	// returns "(sysdate+2.5)"<br><br>$conn-&gt;Execute("UPDATE TABLE SET dodate=$fld WHERE ID=$id");</font></pre>
+<p><font> This function is available for mysql, mssql, oracle, oci8 and postgresql drivers 
+  since 2.13. It might work with other drivers provided they allow performing
+  numeric day arithmetic on dates.</font></p>
+<font> </font>
+<p><font><b>SQLDate<a name="sqldate"></a>($dateFormat, $basedate=false)</b></font></p>
+<font>Returns a string which contains the native SQL functions
+to format a date or date column $basedate. This is used in SELECT statements.
+For INSERT/UPDATE statements, use <a href="#dbdate">DBDate</a>. It uses a case-sensitive
+$dateFormat, which supports: </font>
+<pre><font> 
+  Y: 4-digit Year
+  Q: Quarter (1-4)
+  M: Month (Jan-Dec)
+  m: Month (01-12)
+  d: Day (01-31)
+  H: Hour (00-23)
+  h: Hour (1-12)
+  i: Minute (00-59)
+  s: Second (00-60)
+  A: AM/PM indicator
+  w: day of week (0-6 or 1-7 depending on DB)
+  l: day of week (as string - lowercase L)
+  W: week in year (0..53 for MySQL, 1..53 for PostgreSQL and Oracle)
+  </font></pre>
+<p><font>All other characters are treated as strings. You can
+    also use \ to escape characters. Available on selected databases, including
+mysql, postgresql, mssql, oci8 and DB2. </font></p>
+<p><font>This is useful in writing portable sql statements that
+    GROUP BY on dates. For example to display total cost of goods sold broken
+by quarter (dates are stored in a field called postdate): </font></p>
+<pre><font> $sqlfn = $db-&gt;SQLDate('Y-\QQ','postdate'); # get sql that formats postdate to output 2002-Q1<br> $sql = "SELECT $sqlfn,SUM(cogs) FROM table GROUP BY $sqlfn ORDER BY 1 desc";<br> </font></pre>
+<p><font><b>MoveNext<a name="movenext"></a>( )</b></font></p>
+<p><font>Move the internal cursor to the next row. The <i>$this-&gt;fields</i> array
+    is automatically updated. Returns false if unable to do so (normally because
+EOF has been reached), otherwise true. </font></p>
+<p><font> If EOF is reached, then the $this-&gt;fields array
+    is set to false (this was only implemented consistently in ADOdb 3.30). For
+    the pre-3.30 behaviour of $this-&gt;fields (at EOF), set the global variable
+  $ADODB_COMPAT_FETCH = true.</font></p>
+<p><font>Example:</font></p>
+<pre><font>$rs = $db-&gt;Execute($sql);<br>if ($rs) <br>	while (!$rs-&gt;EOF) {<br> 		ProcessArray($rs-&gt;fields);	<br>		$rs-&gt;MoveNext();<br>	} </font></pre>
+<p><font><b>Move<a name="move"></a>($to)</b></font></p>
+<p><font>Moves the internal cursor to a specific row $<b>to</b>.
+    Rows are zero-based eg. 0 is the first row. The <b>fields</b> array is automatically
+    updated. For databases that do not support scrolling internally, ADOdb will
+    simulate forward scrolling. Some databases do not support backward scrolling.
+    If the $<b>to</b> position is after the EOF, $<b>to</b> will move to the
+    end of the RecordSet for most databases. Some obscure databases using odbc
+  might not behave this way.</font></p>
+<p><font>Note: This function uses <i>absolute positioning</i>,
+unlike Microsoft's ADO.</font></p>
+<p><font>Returns true or false. If false, the internal cursor
+    is not moved in most implementations, so AbsolutePosition( ) will return
+  the last cursor position before the Move( ). </font></p>
+<p><font><b>MoveFirst<a name="movefirst"></a>()</b></font></p>
+<p><font>Internally calls Move(0). Note that some databases do
+not support this function.</font></p>
+<p><font><b>MoveLast<a name="movelast"></a>()</b></font></p>
+<p><font>Internally calls Move(RecordCount()-1). Note that some
+  databases do not support this function.</font></p>
+<p><font><b>GetRowAssoc</b><a name="getrowassoc"></a>($toUpper=true)</font></p>
+<p><font>Returns an associative array containing the current
+    row. The keys to the array are the column names. The column names are upper-cased
+  for easy access. To get the next row, you will still need to call MoveNext(). </font></p>
+<p><font>For example:<br>
+Array ( [ID] =&gt; 1 [FIRSTNAME] =&gt; Caroline [LASTNAME] =&gt; Miranda [CREATED]
+=&gt; 2001-07-05 ) </font></p>
+<p><font>Note: do not use GetRowAssoc() with $ADODB_FETCH_MODE
+    = ADODB_FETCH_ASSOC. Because they have the same functionality, they will
+  interfere with each other.</font></p>
+<font> 
+</font><p><font><b>AbsolutePage<a name="absolutepage"></a>($page=-1) </b></font></p>
+<p><font>Returns the current page. Requires PageExecute()/CachePageExecute() to be called. 
+  See <a href="#ex8">Example 8</a>.</font></p>
+<font>
+<p><b>AtFirstPage<a name="atfirstpage">($status='')</a></b></p>
+<p>Returns true if at first page (1-based). Requires PageExecute()/CachePageExecute()
+  to be called. See <a href="#ex8">Example 8</a>.</p>
+<p><b>AtLastPage<a name="atlastpage">($status='')</a></b></p>
+<p>Returns true if at last page (1-based). Requires PageExecute()/CachePageExecute()
+  to be called. See <a href="#ex8">Example 8</a>.</p>
+<p><b>Fields</b><a name="fields"></a>(<b>$colname</b>)</p>
+<p>Returns the value of the associated column $<b>colname</b> for the current
+  row. The column name is case-insensitive.</p>
+<p>This is a convenience function. For higher performance, use <a href="#adodb_fetch_mode">$ADODB_FETCH_MODE</a>. </p>
+<p><b>FetchRow</b><a name="fetchrow"></a>()</p> 
+</font><p><font>Returns array containing current row, or false
+    if EOF. FetchRow( ) internally moves to the next record after returning the
+    current row. </font></p>
+<p><font>Warning: Do not mix using FetchRow() with MoveNext().</font></p>
+<p><font>Usage:</font></p>
+<pre><font>$rs = $db-&gt;Execute($sql);<br>if ($rs)<br>	while ($arr = $rs-&gt;FetchRow()) {<br>	   &nbsp;&nbsp;# process $arr	<br>	}</font></pre>
+<p><font><b>FetchInto</b><a name="fetchinto"></a>(<b>&amp;$array</b>)</font></p>
+<p><font> Sets $array to the current row. Returns PEAR_Error
+    object if EOF, 1 if ok (DB_OK constant). If PEAR is undefined, false is returned
+    when EOF. FetchInto( ) internally moves to the next record after returning
+  the current row. </font></p>
+<p><font> FetchRow() is easier to use. See above.</font></p>
+<font> </font>
+<p><font><b>FetchField<a name="fetchfield"></a>($column_number)</b></font></p>
+<p><font>Returns an object containing the <b>name</b>, <b>type</b> and <b>max_length</b> of
+    the associated field. If the max_length cannot be determined reliably, it
+    will be set to -1. The column numbers are zero-based. See <a href="#ex2">example
+  2.</a></font></p>
+<p><font><b>FieldCount<a name="fieldcount"></a>( )</b></font></p>
+<p><font>Returns the number of fields (columns) in the record
+set.</font></p>
+<p><font><b>RecordCount<a name="recordcount"></a>( )</b></font></p>
+<p><font>Returns the number of rows in the record set. If the
+    number of records returned cannot be determined from the database driver
+    API, we will buffer all rows and return a count of the rows after all the
+    records have been retrieved. This buffering can be disabled (for performance
+    reasons) by setting the global variable $ADODB_COUNTRECS = false. When disabled,
+    RecordCount( ) will return -1 for certain databases. See the supported databases
+  list above for more details. </font></p>
+<p><font> RowCount is a synonym for RecordCount.</font></p>
+<p><font><b>PO_RecordCount<a name="po_recordcount"></a>($table,
+$where)</b></font></p>
+<p><font>Returns the number of rows in the record set. If the
+    database does not support this, it will perform a SELECT COUNT(*) on the
+    table $table, with the given $where condition to return an estimate of the
+  recordset size.</font></p>
+<p><font>$numrows = $rs-&gt;PO_RecordCount("articles_table", "group=$group");</font></p>
+<font><b> NextRecordSet<a name="nextrecordset" id="nextrecordset"></a>()</b> </font>
+<p><font>For databases that allow multiple recordsets to be returned
+    in one query, this function allows you to switch to the next recordset. Currently
+  only supported by mssql driver.</font></p>
+<pre><font>$rs = $db-&gt;Execute('execute return_multiple_rs');<br>$arr1 = $rs-&gt;GetArray();<br>$rs-&gt;NextRecordSet();<br>$arr2 = $rs-&gt;GetArray();</font></pre>
+<p><font><b>FetchObject<a name="fetchobject"></a>($toupper=true)</b></font></p>
+<p><font>Returns the current row as an object. If you set $toupper
+    to true, then the object fields are set to upper-case. Note: The newer FetchNextObject()
+  is the recommended way of accessing rows as objects. See below.</font></p>
+<p><font><b>FetchNextObject<a name="fetchnextobject"></a>($toupper=true)</b></font></p>
+<p><font>Gets the current row as an object and moves to the next
+    row automatically. Returns false if at end-of-file. If you set $toupper to
+  true, then the object fields are set to upper-case. Note that for some drivers such as mssql, you need to SetFetchMode(ADODB_FETCH_ASSOC) or SetFetchMode(ADODB_FETCH_BOTH).</font></p>
+<pre><font>$rs = $db-&gt;Execute('select firstname,lastname from table');<br>if ($rs) {<br>	while ($o = $rs-&gt;FetchNextObject()) {<br>		print "$o-&gt;FIRSTNAME, $o-&gt;LASTNAME&lt;BR&gt;";<br>	}<br>}<br></font></pre>
+<p><font>There is some trade-off in speed in using FetchNextObject().
+If performance is important, you should access rows with the <code>fields[]</code> array. <b>FetchObj<a name="fetchobj" id="fetchobj"></a>()</b> </font></p>
+<p><font>Returns the current record as an object. Fields are
+    not upper-cased, unlike FetchObject.  
+</font></p>
+<p><font><b>FetchNextObj<a name="fetchnextobj" id="fetchnextobj"></a>()</b> </font></p>
+<p><font>Returns the current record as an object and moves to
+    the next record. If EOF, false is returned. Fields are not upper-cased, unlike
+  FetctNextObject. </font></p>
+<font>
+<p><b>CurrentRow<a name="currentrow"></a>( )</b></p>
+<p>Returns the current row of the record set. 0 is the first row.</p>
+<p><b>AbsolutePosition<a name="abspos"></a>( )</b></p>
+<p>Synonym for <b>CurrentRow</b> for compatibility with ADO. Returns the current
+  row of the record set. 0 is the first row.</p>
+<p><b>MetaType<a name="metatype"></a>($nativeDBType[,$field_max_length],[$fieldobj])</b></p>
+<p>Determine what <i>generic</i> meta type a database field type is given its
+  native type $<b>nativeDBType</b> as a string and the length of the field $<b>field_max_length</b>.
+  Note that field_max_length can be -1 if it is not known. The field object returned
+  by FetchField() can be passed in $<b>fieldobj</b> or as the 1st parameter <b>$nativeDBType</b>.
+  This is useful for databases such as <i>mysql</i> which has additional properties
+  in the field object such as <i>primary_key</i>. </p>
+<p>Uses the field <b>blobSize</b> and compares it with $<b>field_max_length</b> to
+  determine whether the character field is actually a blob.</p>
+For example, $db-&gt;MetaType('char') will return 'C'.
+<p>Returns:</p>
+<ul>
+  <li><b>C</b>: Character fields that should be shown in a &lt;input type="text"&gt; tag. </li>
+  <li><b>X</b>: Clob (character large objects), or large text fields that should
+    be shown in a &lt;textarea&gt;</li>
+  <li><b>D</b>: Date field</li>
+  <li><b>T</b>: Timestamp field</li>
+  <li><b>L</b>: Logical field (boolean or bit-field)</li>
+  <li><b>N</b>: Numeric field. Includes decimal, numeric, floating point, and
+    real. </li>
+  <li><b>I</b>:&nbsp; Integer field. </li>
+  <li><b>R</b>: Counter or Autoincrement field. Must be numeric.</li>
+  <li><b>B</b>: Blob, or binary large objects. </li>
+</ul> 
+</font><p><font> Since ADOdb 3.0, MetaType accepts $fieldobj
+    as the first parameter, instead of $nativeDBType. </font></p>
+<font> </font>
+<p><font><b>Close( )<a name="rsclose"></a></b></font></p>
+<p><font>Closes the recordset, cleaning all memory and resources
+associated with the recordset. </font></p>
+<p>
+<font>If memory management is not an issue, you do not need to
+call this function as recordsets are closed for you by PHP at the end of the
+script. SQL statements such as INSERT/UPDATE/DELETE do not really return a recordset,
+so you do not have to call Close() for such SQL statements.</font></p>
+<hr />
+<h3><font>function rs2html<a name="rs2html"></a>($adorecordset,[$tableheader_attributes],
+  [$col_titles])</font></h3>
+<p><font>This is a standalone function (rs2html = recordset to
+    html) that is similar to PHP's <i>odbc_result_all</i> function, it prints
+    a ADORecordSet, $<b>adorecordset</b> as a HTML table. $<b>tableheader_attributes</b> allow
+    you to control the table <i>cellpadding</i>, <i>cellspacing</i> and <i>border</i> attributes.
+    Lastly you can replace the database column names with your own column titles
+    with the array $<b>col_titles</b>. This is designed more as a quick debugging
+  mechanism, not a production table recordset viewer.</font></p>
+<p><font>You will need to include the file <i>tohtml.inc.php</i>.</font></p>
+<p><font>Example of rs2html:<b><font color="#336600"><a name="exrs2html"></a></font></b></font></p>
+<pre><font><b><font color="#336600">&lt;?<br>include('tohtml.inc.php')</font></b>; # load code common to ADOdb <br><b>include</b>('adodb.inc.php'); # load code common to ADOdb <br>$<font color="#663300">conn</font> = &amp;ADONewConnection('mysql');   # create a connection <br>$<font color="#663300">conn</font>-&gt;PConnect('localhost','userid','','agora');# connect to MySQL, agora db<br>$<font color="#663300">sql</font> = 'select CustomerName, CustomerID from customers'; <br>$<font color="#663300">rs</font>   = $<font color="#663300">conn</font>-&gt;Execute($sql); <br><font color="#336600"><b>rs2html</b></font><b>($<font color="#663300">rs</font>,'<i>border=2 cellpadding=3</i>',array('<i>Customer Name','Customer ID</i>'));<br>?&gt;</b></font></pre>
+<hr />
+<h3><font>Differences between this ADOdb library and Microsoft
+ADO<a name="adodiff"></a></font></h3>
+<ol>
+<font>
+<li>ADOdb only supports recordsets created by a connection object. Recordsets
+  cannot be created independently.</li>
+<li>ADO properties are implemented as functions in ADOdb. This makes it easier
+  to implement any enhanced ADO functionality in the future.</li>
+<li>ADOdb's <font face="Courier New, Courier, mono">ADORecordSet-&gt;Move()</font> uses
+  absolute positioning, not relative. Bookmarks are not supported.</li>
+<li><font face="Courier New, Courier, mono">ADORecordSet-&gt;AbsolutePosition() </font>cannot
+  be used to move the record cursor.</li>
+<li>ADO Parameter objects are not supported. Instead we have the ADOConnection::<a href="#parameter">Parameter</a>(
+  ) function, which provides a simpler interface for calling preparing parameters
+  and calling stored procedures.</li>
+<li>Recordset properties for paging records are available, but implemented as
+  in <a href="#ex8">Example 8</a>.</li>
+</font></ol>
+<hr />
+<h1><font>Database Driver Guide<a name="driverguide"></a></font></h1>
+<p><font>This describes how to create a class to connect to a
+    new database. To ensure there is no duplication of work, kindly email me
+  at jlim#natsoft.com.my if you decide to create such a class.</font></p>
+<p><font>First decide on a name in lower case to call the database
+  type. Let's say we call it xbase. </font></p>
+<p><font>Then we need to create two classes ADODB_xbase and ADORecordSet_xbase
+  in the file adodb-xbase.inc.php.</font></p>
+<p><font>The simplest form of database driver is an adaptation
+    of an existing ODBC driver. Then we just need to create the class <i>ADODB_xbase
+    extends ADODB_odbc</i> to support the new <b>date</b> and <b>timestamp</b> formats,
+    the <b>concatenation</b> operator used, <b>true</b> and <b>false</b>. For
+    the<i> ADORecordSet_xbase extends ADORecordSet_odbc </i>we need to change
+  the <b>MetaType</b> function. See<b> adodb-vfp.inc.php</b> as an example.</font></p>
+<p><font>More complicated is a totally new database driver that
+    connects to a new PHP extension. Then you will need to implement several
+    functions. Fortunately, you do not have to modify most of the complex code.
+    You only need to override a few stub functions. See <b>adodb-mysql.inc.php</b> for
+  example.</font></p>
+<p><font>The default date format of ADOdb internally is YYYY-MM-DD
+    (Ansi-92). All dates should be converted to that format when passing to an
+    ADOdb date function. See Oracle for an example how we use ALTER SESSION to
+  change the default date format in _pconnect _connect.</font></p>
+<p><font><b>ADOConnection Functions to Override</b></font></p>
+<p><font>Defining a constructor for your ADOConnection derived
+  function is optional. There is no need to call the base class constructor.</font></p>
+<p><font>_<b>connect</b>: Low level implementation of Connect.
+  Returns true or false. Should set the _<b>connectionID</b>.</font></p>
+<p><font>_<b>pconnect:</b> Low level implemention of PConnect.
+  Returns true or false. Should set the _<b>connectionID</b>.</font></p>
+<p><font>_<b>query</b>: Execute a query. Returns the queryID,
+or false.</font></p>
+<p><font>_<b>close: </b>Close the connection -- PHP should clean
+up all recordsets. </font></p>
+<p><font><b>ErrorMsg</b>: Stores the error message in the private
+variable _errorMsg. </font></p>
+<p><font><b>ADOConnection Fields to Set</b></font></p>
+<p><font>_<b>bindInputArray</b>: Set to true if binding of parameters
+  for SQL inserts and updates is allowed using ?, eg. as with ODBC.</font></p>
+<p><font><b>fmtDate</b></font></p>
+<p><font><b>fmtTimeStamp</b></font></p>
+<p><font><b>true</b></font></p>
+<p><font><b>false</b></font></p>
+<p><font><b>concat_operator</b></font></p>
+<p><font><b>replaceQuote</b></font></p>
+<p><font><b>hasLimit</b> support SELECT * FROM TABLE LIMIT 10
+of MySQL.</font></p>
+<p><font><b>hasTop</b> support Microsoft style SELECT TOP 10
+* FROM TABLE.</font></p>
+<p><font><b>ADORecordSet Functions to Override</b></font></p>
+<p><font>You will need to define a constructor for your ADORecordSet
+  derived class that calls the parent class constructor.</font></p>
+<p><font><b>FetchField: </b> as documented above in ADORecordSet</font></p>
+<p><font>_<b>initrs</b>: low level initialization of the recordset:
+    setup the _<b>numOfRows</b> and _<b>numOfFields</b> fields -- called by the
+  constructor.</font></p>
+<p><font>_<b>seek</b>: seek to a particular row. Do not load
+    the data into the fields array. This is done by _fetch. Returns true or false.
+    Note that some implementations such as Interbase do not support seek. Set
+  canSeek to false.</font></p>
+<p><font>_<b>fetch</b>: fetch a row using the database extension
+    function and then move to the next row. Sets the <b>fields</b> array. If
+    the parameter $ignore_fields is true then there is no need to populate the <b>fields</b> array,
+  just move to the next row. then Returns true or false.</font></p>
+<p><font>_<b>close</b>: close the recordset</font></p>
+<p><font><b>Fields</b>: If the array row returned by the PHP
+    extension is not an associative one, you will have to override this. See
+    adodb-odbc.inc.php for an example. For databases such as MySQL and MSSQL
+    where an associative array is returned, there is no need to override this
+  function.</font></p>
+<p><font><b>ADOConnection Fields to Set</b></font></p>
+<p><font>canSeek: Set to true if the _seek function works.</font></p>
+<h2><font>Optimizing PHP</font></h2>
+    For info on tuning PHP, read this article on <a href="http://phplens.com/lens/php-book/optimizing-debugging-php.php">Optimizing
+  PHP</a>. </font></p>
+
+<h2><font>Change Log<a name="Changes"></a><a name="changes"></a><a name="changelog"></a></font></h2>
+
+<p><a name="4.94"></a><b>4.94 23 Jan 2007</b>
+<p>Active Record: $ADODB_ASSOC_CASE=2 did not work properly. Fixed. Thx gmane#auxbuss.com.
+<p>mysqli had bugs in BeginTrans() and EndTrans(). Fixed.</p>
+<p>Improved error handling when no database is connected for oci8. Thx Andy Hassall.</p>
+<p>Names longer than 30 chars in oci8 datadict will be changed to random name. Thx Eugenio. http://phplens.com/lens/lensforum/msgs.php?id=16182
+<p>Added var $upperCase = 'ucase' to access and ado_access drivers. Thx Renato De Giovanni renato#cria.org.br</p>
+<p>Postgres64 driver, if preparing plan failed in _query, did not handle error properly. Fixed. See http://phplens.com/lens/lensforum/msgs.php?id=16131.
+<p>Fixed  GetActiveRecordsClass() reference bug. See http://phplens.com/lens/lensforum/msgs.php?id=16120
+<p>
+
+Added handling of nulls in adodb-ado_mssql.inc.php for qstr(). Thx to Felix Rabinovich.
+<p>
+
+Adodb-dict contributions by Gaetano:
+<br>
++ Support for INDEX in data-dict. Example:
+idx_ev1. The ability to define indexes using the INDEX keyword was added in ADOdb 4.94. The following example features mutiple indexes, including a compound index idx_ev1. 
+<pre>
+  event_id I(11) NOTNULL AUTOINCREMENT PRIMARY,
+  event_type I(4) NOTNULL  <b>INDEX idx_evt</b>,
+  event_start_date T DEFAULT NULL <b>INDEX id_esd</b>,
+  event_end_date T DEFAULT '0000-00-00 00:00:00' <b>INDEX id_eted</b>,
+  event_parent I(11) UNSIGNED NOTNULL DEFAULT 0 <b>INDEX id_evp</b>,
+  event_owner I(11) DEFAULT 0 <b>INDEX idx_ev1</b>,
+  event_project I(11) DEFAULT 0 <b>INDEX idx_ev1</b>,
+  event_times_recuring I(11) UNSIGNED NOTNULL DEFAULT 0,
+  event_icon C(20) DEFAULT 'obj/event',
+  event_description X
+</pre>
+<br>
++ Prevents the generated SQL from including double drop-sequence statements for REPLACE case of tables with autoincrement columns (on those dbs that emulate it via sequences)
+<br>
++ makes any date defined as DEFAULT value for D and T columns work cross-database, not just the "sysdate" value (as long as it is specified using adodb standard format). See above example.
+<p>Fixed pdo's GetInsertID() support. Thx Ricky Su.
+<p>oci8 Prepare() now sets error messages if an error occurs.
+<p>Added 'PT_BR' to SetDateLocale() -- brazilian portugese.
+<p>charset in oci8 was not set correctly on *Connect()
+<p>ADOConnection::Transpose() now appends as first column the field names.
+<p>Added $ADODB_QUOTE_FIELDNAMES. If set to true, will autoquote field names in AutoExecute(),GetInsertSQL(), GetUpdateSQL().
+<p>Transpose now adds the field names as the first column after transposition.
+<p>Added === check in ADODB_SetDatabaseAdapter for $db, adodb-active-record.inc.php. Thx Christian Affolter.
+<p>Added ErrorNo() to adodb-active-record.inc.php. Thx ante#novisplet.com.
+
+
+
+<p><a name="4.93"></a><b>4.93 10 Oct 2006</b>
+<p>Added support for multiple database connections in performance monitoring code (adodb-perf.inc.php). Now all sql in multiple database connections can be saved into one database ($ADODB_LOG_CONN).
+<p>Added MetaIndexes() to odbc_mssql.
+<p>Added connection property $db->null2null = 'null'. In autoexecute/getinsertsql/getupdatesql, this value will be converted to a null. Set this to a funny invalid value if you do not want null conversion. See http://phplens.com/lens/lensforum/msgs.php?id=15902.
+<p>Path disclosure problem in mysqli fixed. Thx Andy.
+<p>Fixed typo in session_schema2.xml.
+<p>Changed INT in oci8 to return correct precision in $fld->max_length, MetaColumns(). Thx Eloy Lafuente Plaza.
+<p>Patched postgres64 _connect to handle serverinfo(). see http://phplens.com/lens/lensforum/msgs.php?id=15887.
+<p>Added pdo fix for null columns. See http://phplens.com/lens/lensforum/msgs.php?id=15889
+<p>For stored procedures, missing connection id now passed into mssql_query(). Thx Ecsy (ecsy#freemail.hu).
+
+<p><a name="4.92a"></a><b>4.92a 30 Aug 2006</b>
+<p>Syntax error in postgres7 driver. Thx Eloy Lafuente Plaza. 
+<p>Minor bug fixes - adodb informix 10 types added to adodb.inc.php. Thx Fernando Ortiz.
+
+<p><a name="4.92"></a><b>4.92 29 Aug 2006</b>
+
+<p>Better odbtp date support.
+<P>Added IgnoreErrors() to bypass default error handling.
+<p>The _adodb_getcount() function in adodb-lib.inc.php, some ORDER BY bug fixes.
+<p>For ibase and firebird, set  $sysTimeStamp = "CURRENT_TIMESTAMP".
+<p>Fixed postgres connection bug: http://phplens.com/lens/lensforum/msgs.php?id=11057.
+<p>Changed CacheSelectLimit() to flush cache when $secs2cache==-1 due to complaints from other users. 
+<p>Added support for using memcached with CacheExecute/CacheSelectLimit. Requires memcache module PECL extension. Usage:
+<pre>
+$db = NewADOConnection($driver);
+$db->memCache = true; /// should we use memCache instead of caching in files
+$db->memCacheHost = 126.0.1.1; /// memCache host
+$db->memCachePort = 11211; /// this is default memCache port
+$db->memCacheCompress = false; /// Use 'true' to store the item compressed (uses zlib)
+
+$db->Connect(...);
+$db->CacheExecute($sql);
+</pre>
+<p>Implemented Transpose() for recordsets. Recordset must be retrieved using ADODB_FETCH_NUM. First column becomes the 
+column name.
+<pre>
+$DB = NewADOConnection('mysql');
+$DB->Connect(...);
+$DB->SetFetchMode(ADODB_FETCH_NUM);
+$rs = $DB->Execute('select productname,productid,unitprice from products limit 10');
+$rs2 = $DB->Transpose($rs);
+rs2html($rs2);
+</pre>
+<p><a name="4.91"></a><b>4.91 2 Aug 2006</b>
+<p>Major session code rewrite .... See session docs.
+<p>PDO bindinputarray was not set properly for MySQL (changed from true to false).
+<p>Changed CacheSelectLimit() to re-cache when $secs2cache==0. This is one way to flush the cache when SelectLimit is called.
+<p>Added to quotes to mysql  and mysqli: "SHOW COLUMNS FROM `%s`";
+<p>Removed accidental optgroup handling in GetMenu().
+<a>Fixed ibase _BlobDecode for php5 compat, and also mem alloc issues for small blobs, thx salvatori#interia.pl
+<p>Mysql driver OffsetDate() speedup, useful for adodb-sessions.
+<p>Fix for GetAssoc() PHP5 compat. See http://phplens.com/lens/lensforum/msgs.php?id=15425
+<p>Active Record - If inserting a record and the value of a primary key field is null, then we do not insert that field in as we assume it is an auto-increment field. Needed by mssql.
+<p>Changed postgres7 MetaForeignKeys() see http://phplens.com/lens/lensforum/msgs.php?id=15531
+<p>DB2 will now return db2_conn_errormsg() when it is a connection error. 
+<p><a name="4.90"></a><b>4.90 8 June 2006</b>
+<p>Changed adodb_countrec() in adodb-lib.inc.php to allow LIMIT to be used as a speedup to reduce no of records counted.
+<p>Added support for transaction modes for postgres and oci8 with SetTransactionMode(). 
+These transaction modes affect all subsequent transactions of that connection.
+<p>Thanks to Halmai Csongor for suggestion.
+<p>Removed $off = $fieldOffset - 1 line in db2 driver, FetchField(). Tx Larry Menard.
+<p>Added support for PHP5 objects as Execute() bind parameters using __toString (eg. Simple-XML). Thx Carl-Christian Salvesen.
+<p>Rounding in tohtml.inc.php did not work properly. Fixed.
+<p>MetaIndexes in postgres fails when fields are deleted then added in again because the attnum has gaps in it. 
+See http://sourceforge.net/tracker/index.php?func=detail&aid=1451245&group_id=42718&atid=433976. Fixed.
+<p>MetaForeignkeys in mysql and mysqli did not work when fetchMode==ADODB_FETCH_ASSOC used. Fixed.
+<p>Reference error in AutoExecute() fixed.
+<p>Added macaddr postgres type to MetaType. Maps to 'C'.
+<p>Added to _connect() in adodb-ado5.inc.php support for $database and $dataProvider parameters.  Thx Larry Menard.
+<p>Added support for sequences in adodb-ado_mssql.inc.php. Thx Larry Menard.
+<p>Added ADODB_SESSION_READONLY.
+<p>Added session expiryref support to crc32 mode, and in LOB code.
+<p>Clear _errorMsg in postgres7 driver, so that ErrorMsg() displays properly when no error occurs.
+<p>Added BindDate and BindTimeStamp
+<p><a name="4.81"></a><b>4.81 3 May 2006</b>
+<p>Fixed variable ref errors in adodb-ado5.inc.php in _query().
+<p>Mysqli setcharset fix using method_exists().
+<p>The adodb-perf.inc.php CreateLogTable() code now works for user-defined table names.
+<p>Error in ibase_blob_open() fixed. See http://phplens.com/lens/lensforum/msgs.php?id=14997
+<p><a name="4.80"></a><b>4.80 8 Mar 2006</b>
+<p>Added activerecord support.
+<p>Added mysql $conn->compat323 = true if you want MySQL 3.23 compat enabled. Fixes GetOne() Select-Limit problems.
+<p>Added adodb-xmlschema03.inc.php to support XML Schema version 3 and updated adodb-datadict.htm docs.
+<p>Better memory management in Execute. Thx Mike Fedyk.
+<p><a name="4.72"></a><b>4.72 21 Feb 2006</b>
+<p>Added 'new' DSN parameter for NConnect().
+<p>Pager now sanitizes $PHP_SELF to protect against XSS. Thx to James Bercegay and others.
+<p>ADOConnection::MetaType changed to setup $rs->connection correctly. 
+<p>New native DB2 driver contributed by Larry Menard, Dan Scott, Andy Staudacher, Bharat Mediratta.
+<p>The mssql CreateSequence() did not BEGIN TRANSACTION correctly. Fixed. Thx Sean Lee.
+<p>The _adodb_countrecs() function in adodb-lib.inc.php has been revised to handle more ORDER BY variations.
+<p><a name="4.71"></a><b>4.71 24 Jan 2006</b>
+<p>Fixes postgresql security issue related to binary strings. Thx to Andy Staudacher.
+<p>Several DSN bugs found:
+<p>1. Fix bugs in DSN connections introduced in 4.70 when underscores are found in the DSN. 
+<p>2. DSN with _ did not work properly in PHP5 (fine in PHP4). Fixed.
+<p>3. Added support for PDO DSN connections in NewADOConnection(), and database parameter in PDO::Connect().
+<p>The oci8 datetime flag not correctly implemented in ADORecordSet_array. Fixed.
+<p>Added BlobDelete() to postgres, as a counterpoint to UpdateBlobFile().
+<p>Fixed GetInsertSQL() to support oci8po.
+<p>Fixed qstr() issue with postgresql with \0 in strings.
+<p>Fixed some datadict driver loading issues in _adodb_getdriver(). 
+<p>Added register shutdown function session_write_close in adodb-session.inc.php for PHP 5 compat. See http://phplens.com/lens/lensforum/msgs.php?id=14200.
+<p><a name="4.70"></a><b>4.70 6 Jan 2006</b>
+<p>Many fixes from Danila Ulyanov  to ibase, oci8, postgres, mssql, odbc_oracle, odbtp, etc drivers.
+<p>Changed usage of binary hint in adodb-session.inc.php for mysql. See 
+http://phplens.com/lens/lensforum/msgs.php?id=14160
+<p>Fixed invalid variable reference problem in undomq(), adodb-perf.inc.php.
+<p>Fixed http://phplens.com/lens/lensforum/msgs.php?id=14254 in adodb-perf.inc.php, _DBParameter() settings of fetchmode was wrong.
+<p>Fixed security issues in server.php and tmssql.php discussed by Andreas Sandblad in a Secunia security advisory. Added $ACCEPTIP = 127.0.0.1
+and changed suggested root password to something more secure.
+<p>Changed pager to close recordset after RenderLayout().
+<p><a name="4.68"></a><b>4.68 25 Nov  2005</b>
+<p>PHP 5 compat for mysqli. MetaForeignKeys repeated twice and MYSQLI_BINARY_FLAG missing.
+<p>PHP 5.1 support for postgresql bind parameters using ? did not work if >= 10 parameters. Fixed. Thx to Stanislav Shramko.
+<p>Lots of PDO improvements.
+<p>Spelling error fixed in mysql MetaForeignKeys, $associative parameter.
+<p><a name="4.67"></a><b>4.67 16 Nov  2005</b>
+<p>Postgresql not_null flag not set to false correctly. Thx Cristian MARIN.
+<p>We now check in Replace() if key is in fieldArray. Thx Sébastien Vanvelthem.
+<p>_file_get_contents() function was missing in xmlschema. fixed.
+<p>Added week in year support to SQLDate(), using 'W' flag. Thx Spider.
+<p>In sqlite metacolumns was repeated twice, causing PHP 5 problems. Fixed.
+<p>Made debug output XHTML compliant. 
+<p><a name="4.66"></a><b>4.66 28 Sept  2005</b>
+<p>ExecuteCursor() in oci8 did not clean up properly on failure. Fixed.
+<p>Updated xmlschema.dtd, by "Alec Smecher" asmecher#smecher.bc.ca
+<p>Hardened SelectLimit, typecasting nrows and offset to integer.
+<p>Fixed misc bugs in AutoExecute() and GetInsertSQL().
+<p>Added $conn->database as the property holding the database name. The older $conn->databaseName is retained for backward
+compat.
+<p>Changed _adodb_backtrace() compat check to use function_exists().
+<p>Bug in postgresql MetaIndexes fixed. Thx Kevin Jamieson. 
+<p>Improved OffsetDate for MySQL, reducing rounding error.
+<p>Metacolumns added to sqlite. Thx Mark Newnham.
+<p>PHP 4.4 compat fixes for GetAssoc().
+<p>Added postgresql bind support for php 5.1. Thx Cristiano da Cunha Duarte
+<p>OffsetDate() fixes for postgresql, typecasting strings to date or timestamp.
+<p>DBTimeStamp formats for mssql, odbc_mssql and postgresql made to conform with other db's.
+<p>Changed PDO constants from PDO_ to PDO:: to support latest spec.
+<p><a name="4.65"></a><b>4.65 22 July  2005</b>
+<p>Reverted 'X' in mssql datadict to 'TEXT' to be compat with mssql driver. However now you can 
+set $datadict->typeX = 'varchar(4000)' or 'TEXT' or 'CLOB' for mssql and oci8 drivers. 
+<p>Added charset support when using DSN for Oracle.
+<p>_adodb_getmenu did not use fieldcount() to get number of fields. Fixed.
+<p>MetaForeignKeys() for mysql/mysqli contributed by Juan Carlos Gonzalez.
+<p>MetaDatabases() now correctly returns an array for mysqli driver. Thx Cristian MARIN.
+<p>CompleteTrans(false) did not return false. Fixed. Thx to JMF.
+<p>AutoExecute() did not work with Oracle. Fixed. Thx José Moreira.
+<p>MetaType() added to connection object.
+<p>More PHP 4.4 reference return fixes. Thx Ryan C Bonham and others.
+
+<p><a name="4.64"></a><b>4.64 20 June 2005</b>
+<p>In datadict, if the default field value is set to '', then it is not applied when the field is created. Fixed by Eugenio.
+<p>MetaPrimaryKeys for postgres did not work because of true/false change in 4.63. Fixed.
+<p>Tested ocifetchstatement in oci8. Rejected at the end.
+<p>Added port to dsn handling. Supported in postgres, mysql, mysqli,ldap.
+<p>Added  'w' and 'l' to mysqli SQLDate().
+<p>Fixed error handling in ldap _connect() to be more consistent. Also added ErrorMsg() handling to ldap.
+<p>Added support for union in _adodb_getcount, adodb-lib.inc.php for postgres and oci8.
+<p>rs2html() did not work with null dates properly.
+<p>PHP 4.4 reference return fixes.
+
+<p><a name="4.63"></a><b>4.63  18 May 2005</b>
+<p>Added $nrows<0 check to mysqli's SelectLimit().
+<p>Added OptimizeTable() and OptimizeTables() in adodb-perf.inc.php. By Markus Staab.
+<p>PostgreSQL inconsistencies fixed. true and false set to TRUE and FALSE, and boolean type in datadict-postgres.inc.php set
+to 'L' => 'BOOLEAN'. Thx Kevin Jamieson.
+<p>New adodb_session_create_table() function in adodb-session.inc.php. By Markus Staab.
+<p>Added null check to UserTimeStamp().
+<p>Fixed typo in mysqlt driver in adorecordset. Thx to Andy Staudacher.
+<p>GenID() had a bug in the raiseErrorFn handling. Fixed. Thx Marcos Pont.
+<p>Datadict name quoting now handles ( ) in index fields correctly - they aren't part of the index field.
+<p>Performance monitoring: (1) oci8 Ixora checks moved down; (2) expensive sql changed so that only those sql with 
+count(*)>1 are shown; (3) changed sql1 field to a length+crc32 checksum - this breaks backward compat.
+<p>We remap firebird15 to firebird in data dictionary.
+
+<p><a name="4.62"></a><b>4.62  2 Apr 2005</b>
+<p>Added 'w' (dow as 0-6 or 1-7) and 'l' (dow as string) for SQLDate for oci8, postgres and mysql.
+<p>Rolled back MetaType() changes for mysqli done in prev version.
+<p>Datadict change by chris, cblin#tennaxia.com data mappings from:
+<pre>
+oci8:  X->varchar(4000) XL->CLOB
+mssql: X->XL->TEXT
+mysql: X->XL->LONGTEXT
+fbird: X->XL->varchar(4000)
+</pre>
+<p>to:
+<pre>
+oci8:  X->varchar(4000) XL->CLOB
+mssql: X->VARCHAR(4000) XL->TEXT
+mysql: X->TEXT          XL->LONGTEXT
+fbird: X->VARCHAR(4000) XL->VARCHAR(32000)
+</pre>
+<p>Added $connection->disableBlobs to postgresql to improve performance when no bytea is used (2-5% improvement).
+<p>Removed all HTTP_* vars.
+<p>Added $rs->tableName to be set before calling AutoExecute().
+<p>Alex Rootoff rootoff#pisem.net contributed ukrainian language file.
+<p>Added new mysql_option() support using $conn->optionFlags array.
+<p>Added support for ldap_set_option() using the $LDAP_CONNECT_OPTIONS global variable. Contributed by Josh Eldridge.
+<p>Added LDAP_* constant definitions to ldap.
+<p>Added support for boolean bind variables. We use $conn->false and $conn->true to hold values to set false/true to.
+<p>We now do not close the session connection in adodb-session.inc.php as other objects could be using this connection.
+<p>We now strip off \0 at end of Ixora SQL strings in $perf->tohtml() for oci8.
+<p><a name="4.61"></a><b>4.61 23 Feb 2005</b>
+<p>MySQLi added support for mysqli_connect_errno() and mysqli_connect_error().
+<p>Massive improvements to alpha PDO driver.
+<p>Quote string bind parameters logged by performance monitor for easy type checking. Thx Jason Judge.
+<p>Added support for $role when connecting with Interbase/firebird.
+<p>Added support for enum recognition in MetaColumns() mysql and mysqli. Thx Amedeo Petrella.
+<p>The sybase_ase driver contributed by Interakt Online. Thx Cristian Marin cristic#interaktonline.com.
+<p>Removed not_null, has_default, and default_value from ADOFieldObject.
+<p>Sessions code, fixed quoting of keys when handling LOBs in session write() function.
+<p>Sessions code, added adodb_session_regenerate_id(), to reduce risk of session hijacking by changing session cookie dynamically. Thx Joe Li.
+<p>Perf monitor, polling for CPU did not work for PHP 4.3.10 and 5.0.0-5.0.3 due to PHP bugs, so we special case these versions.
+<p>Postgresql, UpdateBlob() added code to handle type==CLOB.
+<p><a name="4.60"></a><b>4.60 24 Jan 2005</b>
+<p>Implemented PEAR DB's autoExecute(). Simplified design because I don't like using constants when
+strings work fine.
+<p>_rs2serialize will now update $rs->sql and $rs->oldProvider.
+<p>Added autoExecute().
+<p>Added support for postgres8 driver. Currently just remapped to postgres7 driver.
+<p>Changed oci8 _query(), so that OCIBindByName() sets the length to -1 if element size is > 4000. This provides better support
+for LONGs.
+<p>Added SetDateLocale() support for netherlands (Nl).
+<p>Spelling error in pivot code ($iff should be $iif).
+</p><p>mysql insert_id() did not work with mysql 3.x. Fixed.
+</p><p>"\r\n" not converted to spaces correctly in exporting data. Fixed.
+</p><p>_nconnect() in mysqli did not return value correctly. Fixed.
+</p><p>Arne Eckmann contributed danish language file.
+</p><p>Added clone() support to FetchObject() for PHP5.<br>
+</p>
+<p>Removed SQL_CUR_USE_ODBC from odbc_mssql.<br>
+</p>
+<p><a name="4.55"></a><b>4.55 5 Jan 2005</b>
+</p><p>Found bug in Execute() with bind params for db's that do not support binding natively.
+</p><p>DropSequence() now correctly uses default parameter.
+</p><p>Now Execute() ignores locale for floats, so 1.23 is NEVER converted to 1,23.
+</p><p>SetFetchMode() not properly saved in adodb-perf, suspicious sql and expensive sql. Fixed.
+</p><p>Added INET to postgresql metatypes. Thx motzel.
+</p><p>Allow oracle hints to work when counting with _adodb_getcount in adodb-lib.inc.php. Thx Chris Wrye.
+</p><p>Changed mysql insert_id() to use SELECT LAST_INSERT_ID().
+</p><p>If alter col in datadict does not modify col type/size of actual
+col, then it is removed from alter col code. By Mark Newham. Not
+perfect as MetaType() !== ActualType().
+</p><p>Added handling of view fields in metacolumns() for postgresql. Thx Renato De Giovanni.
+</p><p>Added to informix MetaPrimaryKeys and MetaColumns fixes for null bit. Thx to Cecilio Albero.
+</p><p>Removed obsolete connection_timeout() from perf code.
+</p><p>Added support for arrayClass in adodb-csv.inc.php.
+</p><p>RSFilter now accepts methods of the form $array($obj, 'methodname'). Thx to blake#near-time.com.
+</p><p>Changed CacheFlush to $cmd = 'rm -rf '.$ADODB_CACHE_DIR.'/[0-9a-f][0-9a-f]/'; 
+</p><p>For better cursor concurrency, added code to free ref cursors in
+oci8 when $rs-&gt;Close() is called. Note that CLose() is called
+internally by the Get* functions too.
+</p><p>Added IIF support for access when pivoting.  Thx Volodia Krupach.
+</p><p>Added mssql datadict support for timestamp. Thx Alexios.
+</p><p>Informix pager fix. By Mario Ramirez.
+</p><p>ADODB_TABLE_REGEX now includes ':'. By Mario Ramirez.
+</p><p>Mark Newnham contributed MetaIndexes for oci8 and db2.
+</p><p><a name="4.54"></a><b>4.54 5 Nov 2004</b>
+</p><p>
+Now you can set $db-&gt;charSet = ?? before doing a Connect() in oci8.
+</p><p>
+Added adodbFetchMode to sqlite.
+</p><p>
+Perf code, added a string typecast to substr in adodb_log_sql().
+</p><p>
+Postgres: Changed BlobDecode() to use po_loread, added new $maxblobsize parameter, and now it returns the blob instead
+of sending it to stdout - make sure to mention that as a compat warning.
+Also added $db-&gt;IsOID($oid) function; uses a heuristic, not guaranteed to work 100%.
+</p><p>
+Contributed arabic language file by "El-Shamaa, Khaled" k.el-shamaa#cgiar.org
+</p><p>
+PHP5 exceptions did not handle @ protocol properly. Fixed.
+</p><p>
+Added ifnull handling for postgresql (using coalesce).
+</p><p>
+Added  metatables() support for Postgresql 8.0 (no longer uses pg_% dictionary tables).
+</p><p>
+Improved Sybase ErrorMsg() function. By Gaetano Giunta.
+</p><p>
+Improved oci8 SelectLimit() to use Prepare(). By Cristiano Duarte.
+</p><p>
+Type-cast $row parameter in ifx_fetch_row() to int. Thx stefan bodgan.
+</p><p>Ralf becker contributed improvements in postgresql, sapdb, mysql data dictionary handling:<br>
+- MySql and Postgres MetaType was reporting every int column which was 
+part of a primary key and unique as serial<br>
+- Postgres was not reporting the scale of decimal types<br>
+- MaxDB was padding the defaults of none-string types with spaces<br>
+- MySql now correctly converts enum columns to varchar
+</p><p>
+Ralf also changed Postgresql datadict:<br>
+- you cant add NOT NULL columns in postgres in one go, they need to be 
+added as NULL and then altered to NOT NULL<br>
+- AlterColumnSQL could not change a varchar column with numbers into an 
+integer column, postgres need an explicit conversation<br>
+- a re-created sequence was not set to the correct value, if the name 
+was the old name (no implicit sequence), now always the new name of the 
+implicit sequence is used<br>
+</p><p>Sergio Strampelli added extra $intoken check to Lens_ParseArgs() in datadict code.
+</p><p><a name="4.53"></a><b>4.53 28 Sept 2004</b>
+</p><p>FetchMode cached in recordset is sometimes mapped to native db fetchMode. Normally this does not matter,
+but when using cached recordsets, we need to switch back to using adodb fetchmode.  So we cache this
+in $rs-&gt;adodbFetchMode if it differs from the db's fetchMode.
+</p><p>For informix we now set canSeek = false driver because stefan bodgan tells me that seeking doesn't work. 
+</p><p>SetDateLocale() never worked till now ;-) Thx david#tomato.it
+</p><p>Set $_bindInputArray = true in sapdb driver. Required for clob support.
+</p><p>Fixed some PEAR::DB emulation issues with isError() and isWarning. Thx to Gert-Rainer Bitterlich.
+</p><p>Empty() used in getupdatesql without strlen() check. Fixed.</p>
+<p>Added unsigned detection to mysql and mysqli drivers. Thx to dan cech.
+</p><p>Added hungarian language file. Thx to Hal&aacute;szv&aacute;ri G&aacute;bor.
+</p><p>Improved fieldname-type formatting of datadict SQL generated (adding $widespacing parameter to _GenField).
+</p><p>Datadict oci8 DROP CONSTRAINTS misspelt. Fixed. Thx Mark Newnham.
+</p><p>Changed odbtp to dynamically change databaseType based on connection, eg. from 'odbtp' to 'odbtp_mssql' when connecting
+to mssql database.
+</p><p>In datadict, MySQL I4 was wrongly mapped to MEDIUMINT, which is actually I3. Fixed.
+</p><p>Fixed mysqli MetaType() recognition. Mysqli returns numeric types unlike mysql extension. Thx Francesco Riosa.
+</p><p>VFP odbc driver curmode set wrongly, causing problems with memo fields. Fixed.
+</p><p>Odbc driver did not recognize odbc version 2 driver date types properly. Fixed. Thx Bostjan.
+</p><p>ChangeTableSQL() fixes to datadict-db2.inc.php by Mark Newnham.
+</p><p>Perf monitoring with odbc improved. Now we try in perf code to manually set the sysTimeStamp using date() if sysTimeStamp
+is empty.
+</p><p>All ADO errors are thrown as exceptions in PHP5. 
+So we added exception handling to ado in PHP5 by creating new adodb-ado5.inc.php driver.
+</p><p>Added IsConnected(). Returns true if connection object connected. By Luca.Gioppo.
+</p><p>"Ralf Becker"
+RalfBecker#digitalROCK.de contributed new sapdb data-dictionary driver
+and a large patch that implements field and table renaming for oracle,
+mssql, postgresql, mysql and sapdb. See the new RenameTableSQL() and
+RenameColumnSQL() functions.
+</p><p>We now check ExecuteCursor to see if PrepareSP was initially called.
+</p><p>Changed oci8 datadict to use MODIFY for $dd-&gt;alterCol. Thx Mark Newnham.
+</p><p><a name="4.52"></a><b>4.52  10 Aug 2004</b>
+</p><p>Bug found in Replace() when performance logging enabled, introduced in ADOdb 4.50. Fixed.
+</p><p>Replace() checks update stmt. If update stmt fails, we now return immediately. Thx to alex.
+</p><p>Added support for $ADODB_FORCE_TYPE in GetUpdateSQL/GetInsertSQL. Thx to niko.
+</p><p>Added ADODB_ASSOC_CASE support to postgres/postgres7 driver.
+</p><p>Support for DECLARE stmt in oci8. Thx Lochbrunner.
+</p><p><a name="4.51"></a><b>4.51  29 July  2004</b>
+</p><p>Added adodb-xmlschema 1.0.2. Thx dan and richard.
+</p><p>Added new adorecordset_ext_* classes. If ADOdb extension installed for mysql, mysqlt and oci8 
+(but not oci8po),  we use the superfast ADOdb extension code for movenext.
+</p><p>Added schema support to mssql and odbc_mssql MetaPrimaryKeys().
+</p><p>Patched MSSQL driver to support PHP NULL and Boolean values 
+while binding the input array parameters in the _query() function. By Stephen Farmer.
+</p><p>Added support for clob's for mssql,  UpdateBlob(). Thx to gfran#directa.com.br
+</p><p>Added normalize support for postgresql (true=lowercase table name, or false=case-sensitive table names) 
+to MetaColumns($table, $normalize=true).
+</p><p>PHP5 variant dates in ADO not working. Fixed in adodb-ado.inc.php.
+</p><p>Constant ADODB_FORCE_NULLS was not working properly for many releases (for GetUpdateSQL). Fixed. 
+Also GetUpdateSQL strips off ORDER BY now - thx Elieser Le&atilde;o.
+</p><p>Perf Monitor for oci8 now dynamically highlights optimizer_* params if too high/low.
+</p><p>Added dsn support to NewADOConnection/ADONewConnection.
+</p><p>Fixed out of page bounds bug in _adodb_pageexecute_all_rows() Thx to "Sergio Strampelli" sergio#rir.it
+</p><p>Speedup of movenext for mysql and oci8 drivers.
+</p><p>Moved debugging code _adodb_debug_execute() to adodb-lib.inc.php.
+</p><p>Fixed postgresql bytea detection bug. See http://phplens.com/lens/lensforum/msgs.php?id=9849.
+</p><p>Fixed ibase datetimestamp typo in PHP5. Thx stefan.
+</p><p>Removed whitespace at end of odbtp drivers.
+</p><p>Added db2 metaprimarykeys fix.
+</p><p>Optimizations to MoveNext() for mysql and oci8. Misc speedups to Get* functions.
+</p><p><a name="4.50"></a><b>4.50  6 July  2004</b>
+</p><p>Bumped it to 4.50 to avoid confusion with PHP 4.3.x series.
+</p><p>Added db2 metatables and metacolumns extensions.
+</p><p>Added alpha PDO driver. Very buggy, only works with odbc.
+</p><p>Tested mysqli. Set poorAffectedRows = true. Cleaned up movenext() and _fetch().
+</p><p>PageExecute does not work properly with php5 (return val not a variable). Reported Dmytro Sychevsky sych#php.com.ua.  Fixed.
+</p><p>MetaTables() for mysql, $showschema parameter was not backward compatible with older versions of adodb. Fixed.
+</p><p>Changed mysql GetOne() to work with mysql 3.23 when using with non-select stmts (e.g. SHOW TABLES).
+</p><p>Changed TRIG_ prefix to a variable in datadict-oci8.inc.php. Thx to Luca.Gioppo#csi.it.
+</p><p>New to adodb-time code. We allow you to define your own daylights savings function, 
+adodb_daylight_sv for pre-1970 dates. If the function is defined 
+(somewhere in an include), then you can correct 
+for daylights savings. See http://phplens.com/phpeverywhere/node/view/16#daylightsavings
+for more info.
+</p><p>New sqlitepo driver. This is because assoc mode does not work like other drivers in sqlite.
+   Namely, when selecting (joining) multiple tables, in assoc mode the table
+   	  names are included in the assoc keys in the "sqlite" driver.
+	  In "sqlitepo" driver, the table names are stripped from the returned column names. 
+	  When this results in a conflict,  the first field get preference.
+	Contributed by Herman Kuiper  herman#ozuzo.net  
+</p><p>Added $forcenull parameter to GetInsertSQL/GetUpdateSQL. Idea by Marco Aurelio Silva.
+</p><p>More XHTML changes for GetMenu. By Jeremy Evans.
+</p><p>Fixes some ibase date issues. Thx to stefan bogdan.
+</p><p>Improvements to mysqli driver to support $ADODB_COUNTRECS.
+</p><p>Fixed adodb-csvlib.inc.php problem when reading stream from socket. We need to poll stream continiously.
+</p><p><a name="4.23"></a><b>4.23  16 June   2004</b>
+</p><p>
+New interbase/firebird fixes thx to Lester Caine.
+Driver fixes a problem with getting field names in the result array, and 
+corrects a couple of data conversions. Also we default to dialect3 for firebird.
+Also ibase sysDate property was wrong. Changed to cast as timestamp.
+</p><p>
+The datadict driver is set up to give quoted tables and fields as this 
+was the only way round reserved words being used as field names in 
+TikiWiki. TikiPro is tidying that up, and I hope to be able to produce a 
+build of THAT which uses what I consider proper UPPERCASE field and 
+table names. The conversion of TikiWiki to ADOdb helped in that, but 
+until the database is completely tidied up in TikiPro ...
+</p><p>Modified _gencachename() to include fetchmode in name hash.
+This means you should clear your cache directory after installing this release as the 
+cache name algorithm has changed.
+</p><p>Now Cache* functions work in safe
+mode, because we do not create sub-directories in the $ADODB_CACHE_DIR
+in safe mode. In non-safe mode we still create sub-directories. Done by
+modifying _gencachename().
+</p><p>Added $gmt parameter (true/false)
+to UserDate and UserTimeStamp in connection class, to force conversion
+of input (in local time) to be converted to UTC/GMT.
+</p><p>Mssql datadict did not support INT types properly (no size param allowed). 
+Added _GetSize() to datadict-mssql.inc.php.
+</p><p>For borland_ibase, BeginTrans(), changed:<br>
+</p><pre>   $this-&gt;_transactionID = $this-&gt;_connectionID;</pre>
+to<br>
+<pre>   $this-&gt;_transactionID = ibase_trans($this-&gt;ibasetrans, $this-&gt;_connectionID);</pre>
+		
+<p>Fixed typo in mysqi_field_seek(). Thx to Sh4dow (sh4dow#php.pl).
+</p><p>LogSQL did not work with Firebird/Interbase. Fixed.
+</p><p>Postgres: made errorno() handling more consistent. Thx to Michael Jahn, Michael.Jahn#mailbox.tu-dresden.de.
+</p><p>Added informix patch to better support metatables, metacolumns by "Cecilio Albero" c-albero#eos-i.com
+</p><p>Cyril Malevanov contributed patch to oci8 to support passing of LOB parameters:
+</p><pre>	$text = 'test test test';<br>	$sql = "declare rs clob; begin :rs := lobinout(:sa0); end;";<br>	$stmt = $conn -&gt; PrepareSP($sql);<br>	$conn -&gt; InParameter($stmt,$text,'sa0', -1, OCI_B_CLOB);<br>	$rs = '';<br>	$conn -&gt; OutParameter($stmt,$rs,'rs', -1, OCI_B_CLOB);<br>	$conn -&gt; Execute($stmt);<br>	echo "return = ".$rs."&lt;br&gt;";<br></pre>
+As he says, the LOBs limitations are:
+<pre> - use OCINewDescriptor before binding<br> - if Param is IN, uses save() before each execute. This is done automatically for you.<br> - if Param is OUT, uses load() after each execute. This is done automatically for you.<br> - when we bind $var as LOB, we create new descriptor and return it as a<br>   Bind Result, so if we want to use OUT parameters, we have to store<br>   somewhere &amp;$var to load() data from LOB to it.<br> - IN OUT params are not working now (should not be a big problem to fix it)<br> - now mass binding not working too (I've wrote about it before)<br></pre>
+<p>Simplified Connect() and PConnect() error handling.
+</p><p>When extension not loaded, Connect() and PConnect() will return null. On connect error, the fns will return false.
+</p><p>CacheGetArray() added to code.
+</p><p>Added Init() to adorecordset_empty().
+</p><p>Changed postgres64 driver, MetaColumns() to not strip off quotes in default value if :: detected (type-casting of default).
+</p><p>Added test: if (!defined('ADODB_DIR')) die(). Useful to prevent hackers from detecting file paths.
+</p><p>Changed metaTablesSQL to ignore Postgres 7.4 information schemas (sql_*).
+</p><p>New polish language file by  Grzegorz Pacan
+</p><p>Added support for UNION in _adodb_getcount().
+</p><p>Added security check for ADODB_DIR to limit path disclosure issues. Requested by postnuke team.
+</p><p>Added better error message support to oracle driver. Thx to Gaetano Giunta.
+</p><p>Added showSchema support to mysql.
+</p><p>Bind in oci8 did not handle $name=false properly. Fixed.
+</p><p>If extension not loaded, Connect(), PConnect(), NConnect() will return null.
+</p><p><b>4.22  15 Apr   2004</b>
+</p><p>Moved docs to own adodb/docs folder.
+</p><p>Fixed session bug when quoting compressed/encrypted data in Replace().
+</p><p>Netezza Driver and LDAP drivers contributed by Josh Eldridge.
+</p><p>GetMenu now uses rtrim() on values instead of trim().
+</p><p>Changed MetaColumnNames to return an associative array, keys being the field names in uppercase.
+</p><p>Suggested fix to adodb-ado.inc.php affected_rows to support PHP5 variants. Thx to Alexios Fakos.
+</p><p>Contributed bulgarian language file by Valentin Sheiretsky valio#valio.eu.org.
+</p><p>Contributed romanian language file by stefan bogdan.
+</p><p>GetInsertSQL now checks for table name (string) in $rs, and will create a recordset for that
+table automatically. Contributed by Walt Boring. Also added OCI_B_BLOB in bind on Walt's request - hope
+it doesn't break anything :-)
+</p><p>Some minor postgres speedups in _initrs().
+</p><p> ChangeTableSQL checks now if MetaColumns returns empty. Thx Jason Judge.
+</p><p>Added ADOConnection::Time(), returns current database time in unix timestamp format, or false.
+</p><p><b>4.21 20 Mar 2004</b>
+</p><p>We no longer in SelectLimit for VFP driver add SELECT TOP X unless an ORDER BY exists.
+</p><p>Pim Koeman contributed dutch language file adodb-nl.inc.php.
+</p><p>Rick Hickerson added CLOB support to db2 datadict.
+</p><p>Added odbtp driver. Thx to "stefan bogdan" sbogdan#rsb.ro.
+</p><p>Changed PrepareSP() 2nd parameter, $cursor, to default to true (formerly false). Fixes oci8 backward
+compat problems with OUT params.
+</p><p>Fixed month calculation error in adodb-time.inc.php. 2102-June-01 appeared as 2102-May-32.
+</p><p>Updated PHP5 RC1 iterator support. API changed, hasMore() renamed to valid().
+</p><p>Changed internal format of serialized cache recordsets. As we store a version number, this should be
+backward compatible.
+</p><p>Error handling when driver file not found was flawed in ADOLoadCode(). Fixed.
+</p><p><b>4.20 27 Feb 2004</b>
+</p><p>Updated to AXMLS 1.01.
+</p><p>MetaForeignKeys for postgres7 modified by Edward Jaramilla, works on pg 7.4.
+</p><p>Now numbers accepts function calls or sequences for GetInsertSQL/GetUpdateSQL numeric fields.
+</p><p>Changed quotes of 'delete from $perf_table' to "". Thx Kehui (webmaster#kehui.net)
+</p><p>Added ServerInfo() for ifx, and putenv trim fix. Thx Fernando Ortiz.
+</p><p>Added addq(), which is analogous to addslashes().
+</p><p>Tested with php5b4. Fix some php5 compat problems with exceptions and sybase.
+</p><p>Carl-Christian Salvesen added patch to mssql _query to support binds greater than 4000 chars.
+</p><p>Mike suggested patch to PHP5 exception handler. $errno must be numeric.
+</p><p>Added double quotes (") to ADODB_TABLE_REGEX.
+</p><p>For oci8, Prepare(...,$cursor),
+$cursor's meaning was accidentally inverted in 4.11. This causes
+problems with ExecuteCursor() too, which calls Prepare() internally.
+Thx to William Lovaton.
+</p><p>Now dateHasTime property in connection object renamed to datetime for consistency. This could break bc.
+</p><p>Csongor Halmai reports that db2 SelectLimit with input array is not working. Fixed..
+</p><p><b>4.11 27 Jan 2004</b>
+</p><p>Csongor Halmai reports db2 binding not working. Reverted back to emulated binding.
+</p><p>Dan Cech modifies datadict code. Adds support for DropIndex. Minor cleanups.
+</p><p>Table misspelt in perf-oci8.inc.php. Changed v$conn_cache_advice to v$db_cache_advice. Reported by Steve W.
+</p><p>UserTimeStamp and DBTimeStamp did not handle YYYYMMDDHHMMSS format properly. Reported by Mike Muir. Fixed.
+</p><p>Changed oci8 Prepare(). Does not auto-allocate OCINewCursor automatically, unless 2nd param is set to true.
+This will break backward compat, if Prepare/Execute is used instead of ExecuteCursor. Reported by Chris Jones.
+</p><p>Added InParameter() and OutParameter(). Wrapper functions to Parameter(), but nicer because they
+are self-documenting.
+</p><p>Added 'R' handling in ActualType() to datadict-mysql.inc.php
+</p><p>Added ADOConnection::SerializableRS($rs). Returns a recordset that can be serialized in a session.
+</p><p>Added "Run SQL" to performance UI().
+</p><p>Misc spelling corrections in adodb-mysqli.inc.php, adodb-oci8.inc.php and datadict-oci8.inc.php, from Heinz Hombergs.
+</p><p>MetaIndexes() for ibase contributed by Heinz Hombergs.
+</p><p><b>4.10 12 Jan 2004</b>
+</p><p>Dan Cech contributed extensive changes to data dictionary to support name quoting (with `), and drop table/index.
+</p><p>Informix added cursorType property. Default remains IFX_SCROLL, but you can change to 0 (non-scrollable cursor) for performance.
+</p><p>Added ADODB_View_PrimaryKeys() for returning view primary keys to MetaPrimaryKeys().
+</p><p>Simplified chinese file, adodb-cn.inc.php from cysoft.
+</p><p>Added check for ctype_alnum in adodb-datadict.inc.php. Thx to Jason Judge.
+</p><p>Added connection parameter to ibase Prepare(). Fix by Daniel Hassan.
+</p><p>Added nameQuote for quoting identifiers and names to connection obj. Requested by Jason Judge. Also the
+data dictionary parser now detects `field name` and generates column names with spaces correctly.
+</p><p>BOOL type not recognised correctly as L. Fixed.
+</p><p>Fixed paths in ADODB_DIR for session files, and back-ported it to 4.05 (15 Dec 2003)
+</p><p>Added Schema to postgresql MetaTables. Thx to col#gear.hu
+</p><p>Empty postgresql recordsets that had blob fields did not set EOF properly. Fixed.
+</p><p>CacheSelectLimit internal parameters to SelectLimit were wrong. Thx to Nio.
+</p><p>Modified adodb_pr() and adodb_backtrace() to support command-line usage (eg. no html).
+</p><p>Fixed some fr and it lang errors. Thx to Gaetano G.
+</p><p>Added contrib directory, with adodb rs to xmlrpc convertor by Gaetano G.
+</p><p>Fixed array recordset bugs when _skiprow1 is true. Thx to Gaetano G.
+</p><p>Fixed pivot table code when count is false.
+</p><p>
+
+</p><p><b>4.05 13 Dec 2003 </b>
+</p><p>Added MetaIndexes to data-dict code - thx to Dan Cech.
+</p><p>Rewritten session code by Ross Smith. Moved code to adodb/session directory.
+</p><p>Added function exists check on connecting to most drivers, so we don't crash with the unknown function error.
+</p><p>Smart Transactions failed with GenID() when it no seq table has been created because the sql
+	statement fails. Fix by Mark Newnham.
+</p><p>Added $db-&gt;length, which holds name of function that returns strlen.
+</p><p>Fixed error handling for bad driver in ADONewConnection - passed too few params to error-handler.
+</p><p>Datadict did not handle types like 16.0 properly in _GetSize. Fixed.
+</p><p>Oci8 driver SelectLimit() bug &amp;= instead of =&amp; used. Thx to Swen Th&uuml;mmler.
+</p><p>Jesse Mullan suggested not flushing outp when output buffering enabled. Due to Apache 2.0 bug. Added.
+</p><p>MetaTables/MetaColumns return ref bug with PHP5 fixed in adodb-datadict.inc.php.
+</p><p>New mysqli driver contributed by Arjen de Rijke. Based on adodb 3.40 driver.
+Then jlim added BeginTrans, CommitTrans, RollbackTrans, IfNull, SQLDate. Also fixed return ref bug.
+</p><p>$ADODB_FLUSH added, if true then force flush in debugging outp. Default is false.  In earlier
+versions, outp defaulted to flush, which is not compat with apache 2.0.
+</p><p>Mysql driver's GenID() function did not work when when sql logging is on. Fixed.
+</p><p>$ADODB_SESSION_TBL not declared as global var. Not available if adodb-session.inc.php included in function. Fixed.
+</p><p>The input array not passed to Execute() in _adodb_getcount(). Fixed.
+</p><p><b>4.04 13 Nov 2003 </b>
+</p><p>Switched back to foreach - faster than list-each.
+</p><p>Fixed bug in ado driver - wiping out $this-&gt;fields with date fields.
+</p><p>Performance Monitor, View SQL, Explain Plan did not work if strlen($SQL)&gt;max($_GET length). Fixed.
+</p><p>Performance monitor, oci8 driver added memory sort ratio.
+</p><p>Added random property, returns SQL to generate a floating point number between 0 and 1;
+</p><p><b>4.03 6 Nov 2003 </b>
+</p><p>The path to adodb-php4.inc.php and adodb-iterators.inc.php was not setup properly.
+</p><p>Patched SQLDate in interbase to support hours/mins/secs. Thx to ari kuorikoski.
+</p><p>Force autorollback for pgsql persistent connections - 
+apparently pgsql did not autorollback properly before 4.3.4. See http://bugs.php.net/bug.php?id=25404
+</p><p><b>4.02 5 Nov 2003 </b>
+</p><p>Some errors in adodb_error_pg() fixed. Thx to Styve.
+</p><p>Spurious Insert_ID() error was generated by LogSQL(). Fixed.
+</p><p>Insert_ID was interfering with Affected_Rows() and Replace()  when LogSQL() enabled. Fixed.
+</p><p>More foreach loops optimized with list/each.
+</p><p>Null dates not handled properly in ADO driver (it becomes 31 Dec 1969!).
+</p><p>Heinz Hombergs contributed patches for mysql MetaColumns - adding scale, made
+interbase MetaColumns work with firebird/interbase, and added lang/adodb-de.inc.php.
+</p><p>Added INFORMIXSERVER environment variable.
+</p><p>Added $ADODB_ANSI_PADDING_OFF for interbase/firebird.
+</p><p>PHP 5 beta 2 compat check. Foreach (Iterator) support. Exceptions support.
+</p><p><b>4.01 23 Oct 2003 </b>
+</p><p>Fixed bug in rs2html(), tohtml.inc.php, that generated blank table cells.
+</p><p>Fixed insert_id() incorrectly generated when logsql() enabled.
+</p><p>Modified PostgreSQL _fixblobs to use list/each instead of foreach.
+</p><p>Informix ErrorNo() implemented correctly.
+</p><p>Modified several places to use list/each, including GetRowAssoc().
+</p><p>Added UserTimeStamp() to connection class.
+</p><p>Added $ADODB_ANSI_PADDING_OFF for oci8po.
+</p><p><b>4.00 20 Oct 2003 </b>
+</p><p>Upgraded adodb-xmlschema to 1 Oct 2003 snapshot.
+</p><p>Fix to rs2html warning message. Thx to Filo.
+</p><p>Fix for odbc_mssql/mssql SQLDate(), hours was wrong.
+</p><p>Added MetaColumns and MetaPrimaryKeys for sybase. Thx to Chris Phillipson.
+</p><p>Added autoquoting to datadict for MySQL and PostgreSQL. Suggestion by Karsten Dambekalns  
+</p><p><b>3.94 11 Oct 2003 </b>
+</p><p>Create trigger in datadict-oci8.inc.php did not work, because all cr/lf's must be removed. 
+</p><p>ErrorMsg()/ErrorNo() did not work for many databases when logging enabled. Fixed.
+</p><p>Removed global variable $ADODB_LOGSQL as it does not work properly with multiple connections.
+</p><p>Added SQLDate support for sybase. Thx to Chris Phillipson
+</p><p>Postgresql checking of pgsql resultset resource was incorrect. Fix by Bharat Mediratta bharat#menalto.com.
+Same patch applied to  _insertid and _affectedrows for adodb-postgres64.inc.php.
+</p><p>Added support for NConnect for postgresql.
+</p><p>Added Sybase data dict support. Thx to Chris Phillipson  
+</p><p>Extensive improvements in $perf-&gt;UI(), eg. Explain now opens in new window, we show scripts
+which call sql, etc.
+</p><p>Perf Monitor UI works with magic quotes enabled.
+</p><p>rsPrefix was declared twice. Removed.
+</p><p>Oci8 stored procedure support, eg. "begin func(); end;" was incorrect in _query. Fixed.
+</p><p>Tiraboschi Massimiliano contributed italian language file.
+</p><p>Fernando Ortiz, fortiz#lacorona.com.mx, contributed informix performance monitor.
+</p><p>Added _varchar (varchar arrays) support for postgresql. Reported by PREVOT St&eacute;phane.<hr />
+<p><strong>0.10 Sept 9 2000</strong> First release 
+</p><h3><strong>Old change log history moved to <a href="old-changelog.htm">old-changelog.htm</a>. 
+  </strong></h3>
+<p>&nbsp;</p>
+<p>  
+</p></body></html>
Index: /Dev/trunk/rdfapi/util/adodb/docs/docs-datadict.htm
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/docs/docs-datadict.htm	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/docs/docs-datadict.htm	(revision 12)
@@ -0,0 +1,328 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
+<html>
+<head>
+  <title>ADOdb Data Dictionary Manual</title>
+  <meta http-equiv="Content-Type"
+ content="text/html; charset=iso-8859-1">
+  <style type="text/css">
+      body, td {
+        /*font-family: Arial, Helvetica, sans-serif;*/
+        font-size: 11pt;
+      }
+      pre {
+        font-size: 9pt;
+         background-color: #EEEEEE; padding: .5em; margin: 0px; 
+      }
+      .toplink {
+        font-size: 8pt;
+      }
+    </style>
+</head>
+<body style="background-color: rgb(255, 255, 255);">
+<h2>ADOdb Data Dictionary Library for PHP</h2>
+<p>V4.94 23 Jan 2007 (c) 2000-2007 John Lim (<a
+ href="mailto:jlim#natsoft.com.my">jlim#natsoft.com.my</a>).<br>
+AXMLS (c) 2004 ars Cognita, Inc</p>
+<p><font size="1">This software is dual licensed using BSD-Style and
+LGPL. This means you can use it in compiled proprietary and commercial
+products.</font></p>
+
+<p>Useful ADOdb links: <a href="http://adodb.sourceforge.net/#download">Download</a>
+&nbsp; <a href="http://adodb.sourceforge.net/#docs">Other Docs</a>
+</p>
+<p>This documentation describes a PHP class library to automate the
+creation of tables, indexes and foreign key constraints portably for
+multiple databases. Richard Tango-Lowy and Dan Cech have been kind
+enough to contribute <a href="#xmlschema">AXMLS</a>, an XML schema
+system for defining databases. You can contact them at
+dcech#phpwerx.net and richtl#arscognita.com.</p>
+<p>Currently the following databases are supported:</p>
+<p> <b>Well-tested:</b> PostgreSQL, MySQL, Oracle, MSSQL.<br>
+<b>Beta-quality:</b> DB2, Informix, Sybase, Interbase, Firebird.<br>
+<b>Alpha-quality:</b> MS Access (does not support DEFAULT values) and
+generic ODBC.
+</p>
+<h3>Example Usage</h3>
+<pre>  include_once('adodb.inc.php');<br>  <font color="#006600"># First create a normal connection</font><br>  $db = NewADOConnection('mysql');<br>  $db-&gt;Connect(...);<br><br>  <font
+ color="#006600"># Then create a data dictionary object, using this connection</font><br>  $dict = <strong>NewDataDictionary</strong>($db);<br><br>  <font
+ color="#006600"># We have a portable declarative data dictionary format in ADOdb, similar to SQL.<br>  # Field types use 1 character codes, and fields are separated by commas.<br>  # The following example creates three fields: "col1", "col2" and "col3":</font><br>  $flds = " <br>  <font
+ color="#663300"><strong> col1 C(32) NOTNULL DEFAULT 'abc',<br>   col2 I  DEFAULT 0,<br>   col3 N(12.2)</strong></font><br>  ";<br><br>  <font
+ color="#006600"># We demonstrate creating tables and indexes</font><br>  $sqlarray = $dict-&gt;<strong>CreateTableSQL</strong>($tabname, $flds, $taboptarray);<br>  $dict-&gt;<strong>ExecuteSQLArray</strong>($sqlarray);<br><br>  $idxflds = 'co11, col2';<br>  $sqlarray = $dict-&gt;<strong>CreateIndexSQL</strong>($idxname, $tabname, $idxflds);<br>  $dict-&gt;<strong>ExecuteSQLArray</strong>($sqlarray);<br></pre>
+<h3>More Complex Table Sample</h3>
+<p>
+The following string will create a table with a primary key event_id and multiple indexes, including one compound index idx_ev1. The ability to define indexes using the INDEX keyword was added in ADOdb 4.94 by Gaetano Giunta.
+<pre>
+$flds = "
+  event_id I(11) NOTNULL AUTOINCREMENT PRIMARY,
+  event_type I(4) NOTNULL  <b>INDEX idx_evt</b>,
+  event_start_date T DEFAULT NULL <b>INDEX id_esd</b>,
+  event_end_date T DEFAULT '0000-00-00 00:00:00' <b>INDEX id_eted</b>,
+  event_parent I(11) UNSIGNED NOTNULL DEFAULT 0 <b>INDEX id_evp</b>,
+  event_owner I(11) DEFAULT 0 <b>INDEX idx_ev1</b>,
+  event_project I(11) DEFAULT 0 <b>INDEX idx_ev1</b>,
+  event_times_recuring I(11) UNSIGNED NOTNULL DEFAULT 0,
+  event_icon C(20) DEFAULT 'obj/event',
+  event_description X
+";
+$sqlarray = $db-><b>CreateTableSQL</b>($tablename, $flds);
+$dict-><b>ExecuteSQLArray</b>($sqlarray);
+</pre>
+<h3>Class Factory</h3>
+<h4>NewDataDictionary($connection, $drivername=false)</h4>
+<p>Creates a new data dictionary object. You pass a database connection object in $connection. The $connection does not have to be actually connected to the database. Some database connection objects are generic (eg. odbtp and odbc). Since 4.53, you can tell ADOdb  the actual database with $drivername. E.g.</p>
+<pre>
+$db =& NewADOConnection('odbtp');
+$datadict = NewDataDictionary($db, 'mssql'); # force mssql
+</pre>
+<h3>Class Functions</h3>
+<h4>function CreateDatabase($dbname, $optionsarray=false)</h4>
+<p>Create a database with the name $dbname;</p>
+<h4>function CreateTableSQL($tabname, $fldarray, $taboptarray=false)</h4>
+<pre>  RETURNS:      an array of strings, the sql to be executed, or false<br>  $tabname:     name of table<br>  $fldarray:    string (or array) containing field info<br>  $taboptarray: array containing table options<br></pre>
+<p>The new format of $fldarray uses a free text format, where each
+field is comma-delimited.
+The first token for each field is the field name, followed by the type
+and optional
+field size. Then optional keywords in $otheroptions:</p>
+<pre>  "$fieldname $type $colsize $otheroptions"</pre>
+<p>The older (and still supported) format of $fldarray is a
+2-dimensional array, where each row in the 1st dimension represents one
+field. Each row has this format:</p>
+<pre>  array($fieldname, $type, [,$colsize] [,$otheroptions]*)</pre>
+<p>The first 2 fields must be the field name and the field type. The
+field type can be a portable type codes or the actual type for that
+database.</p>
+<p>Legal portable type codes include:</p>
+<pre>  C:  Varchar, capped to 255 characters.<br>  X:  Larger varchar, capped to 4000 characters (to be compatible with Oracle). <br>  XL: For Oracle, returns CLOB, otherwise the largest varchar size.<br><br>  C2: Multibyte varchar<br>  X2: Multibyte varchar (largest size)<br><br>  B:  BLOB (binary large object)<br><br>  D:  Date (some databases do not support this, and we return a datetime type)<br>  T:  Datetime or Timestamp<br>  L:  Integer field suitable for storing booleans (0 or 1)<br>  I:  Integer (mapped to I4)<br>  I1: 1-byte integer<br>  I2: 2-byte integer<br>  I4: 4-byte integer<br>  I8: 8-byte integer<br>  F:  Floating point number<br>  N:  Numeric or decimal number<br></pre>
+<p>The $colsize field represents the size of the field. If a decimal
+number is used, then it is assumed that the number following the dot is
+the precision, so 6.2 means a number of size 6 digits and 2 decimal
+places. It is recommended that the default for number types be
+represented as a string to avoid any rounding errors.</p>
+<p>The $otheroptions include the following keywords (case-insensitive):</p>
+<pre>  AUTO            For autoincrement number. Emulated with triggers if not available.<br>                  Sets NOTNULL also.<br>  AUTOINCREMENT   Same as auto.<br>  KEY             Primary key field. Sets NOTNULL also. Compound keys are supported.<br>  PRIMARY         Same as KEY.<br>  DEF             Synonym for DEFAULT for lazy typists.<br>  DEFAULT         The default value. Character strings are auto-quoted unless<br>                  the string begins and ends with spaces, eg ' SYSDATE '.<br>  NOTNULL         If field is not null.<br>  DEFDATE         Set default value to call function to get today's date.<br>  DEFTIMESTAMP    Set default to call function to get today's datetime.<br>  NOQUOTE         Prevents autoquoting of default string values.<br>  CONSTRAINTS     Additional constraints defined at the end of the field<br>                  definition.<br></pre>
+<p>The Data Dictonary accepts two formats, the older array
+specification:</p>
+<pre>  $flds = array(<br>    array('COLNAME',   'DECIMAL', '8.4', 'DEFAULT' =&gt; 0, 'NOTNULL'),<br>    array('id',        'I'      , 'AUTO'),<br>    array('`MY DATE`', 'D'      , 'DEFDATE'),<br>    array('NAME',      'C'      , '32', 'CONSTRAINTS' =&gt; 'FOREIGN KEY REFERENCES reftable')<br>  );<br></pre>
+<p>Or the simpler declarative format:</p>
+<pre>  $flds = "<font color="#660000"><strong><br>    COLNAME DECIMAL(8.4) DEFAULT 0 NOTNULL,<br>    id I AUTO,<br>    `MY DATE` D DEFDATE,<br>    NAME C(32) CONSTRAINTS 'FOREIGN KEY REFERENCES reftable'</strong></font><br>  ";<br></pre>
+<p>Note that if you have special characters in the field name (e.g. My
+Date), you should enclose it in back-quotes. Normally field names are
+not case-sensitive, but if you enclose it in back-quotes, some
+databases will treat the names as case-sensitive (eg. Oracle) , and
+others won't. So be careful.</p>
+<p>The $taboptarray is the 3rd parameter of the CreateTableSQL
+function. This contains table specific settings. Legal keywords include:</p>
+<ul>
+  <li><b>REPLACE</b><br>
+Indicates that the previous table definition should be removed
+(dropped)together with ALL data. See first example below. </li>
+  <li><b>DROP</b><br>
+Drop table. Useful for removing unused tables. </li>
+  <li><b>CONSTRAINTS</b><br>
+Define this as the key, with the constraint as the value. See the
+postgresql <a href="#foreignkey">example</a> below. Additional constraints defined for the whole
+table. You will probably need to prefix this with a comma. </li>
+</ul>
+<p>Database specific table options can be defined also using the name
+of the database type as the array key. In the following example, <em>create
+the table as ISAM with MySQL, and store the table in the "users"
+tablespace if using Oracle</em>. And because we specified REPLACE, drop
+the table first.</p>
+<pre>  $taboptarray = array('mysql' =&gt; 'TYPE=ISAM', 'oci8' =&gt; 'tablespace users', 'REPLACE');</pre>
+<p><a name=foreignkey></a>You can also define foreign key constraints. The following is syntax
+for postgresql:
+</p>
+<pre>  $taboptarray = array('constraints' =&gt; ', FOREIGN KEY (col1) REFERENCES reftable (refcol)');</pre>
+<h4>function DropTableSQL($tabname)</h4>
+<p>Returns the SQL to drop the specified table.</p>
+<h4>function ChangeTableSQL($tabname, $flds)</h4>
+<p>Checks to see if table exists, if table does not exist, behaves like
+CreateTableSQL. If table exists, generates appropriate ALTER TABLE
+MODIFY COLUMN commands if field already exists, or ALTER TABLE ADD
+$column if field does not exist.</p>
+<p>The class must be connected to the database for ChangeTableSQL to
+detect the existence of the table. Idea and code contributed by Florian
+Buzin.</p>
+<h4>function RenameTableSQL($tabname,$newname)</h4>
+<p>Rename a table.  Returns the an array of strings, which is the SQL required to rename a table. Since ADOdb 4.53. Contributed by Ralf Becker.</p>
+<h4> function RenameColumnSQL($tabname,$oldcolumn,$newcolumn,$flds='')</h4>
+<p>Rename a table field. Returns the an array of strings, which is the SQL required to rename a column. The optional $flds is a complete column-defintion-string like for AddColumnSQL, only used by mysql at the moment. Since ADOdb 4.53. Contributed by Ralf Becker.</p>
+<h4>function CreateIndexSQL($idxname, $tabname, $flds,
+$idxoptarray=false)</h4>
+<pre>  RETURNS:      an array of strings, the sql to be executed, or false<br>  $idxname:     name of index<br>  $tabname:     name of table<br>  $flds:        list of fields as a comma delimited string or an array of strings<br>  $idxoptarray: array of index creation options<br></pre>
+<p>$idxoptarray is similar to $taboptarray in that index specific
+information can be embedded in the array. Other options include:</p>
+<pre>  CLUSTERED     Create clustered index (only mssql)<br>  BITMAP        Create bitmap index (only oci8)<br>  UNIQUE        Make unique index<br>  FULLTEXT      Make fulltext index (only mysql)<br>  HASH          Create hash index (only postgres)<br>  DROP          Drop legacy index<br></pre>
+<h4>function DropIndexSQL ($idxname, $tabname = NULL)</h4>
+<p>Returns the SQL to drop the specified index.</p>
+<h4>function AddColumnSQL($tabname, $flds)</h4>
+<p>Add one or more columns. Not guaranteed to work under all situations.</p>
+<h4>function AlterColumnSQL($tabname, $flds)</h4>
+<p>Warning, not all databases support this feature.</p>
+<h4>function DropColumnSQL($tabname, $flds)</h4>
+<p>Drop 1 or more columns.</p>
+<h4>function SetSchema($schema)</h4>
+<p>Set the schema.</p>
+<h4>function &amp;MetaTables()</h4>
+<h4>function &amp;MetaColumns($tab, $upper=true, $schema=false)</h4>
+<h4>function &amp;MetaPrimaryKeys($tab,$owner=false,$intkey=false)</h4>
+<h4>function &amp;MetaIndexes($table, $primary = false, $owner = false)</h4>
+<p>These functions are wrappers for the corresponding functions in the
+connection object. However, the table names will be autoquoted by the
+TableName function (see below) before being passed to the connection
+object.</p>
+<h4>function NameQuote($name = NULL)</h4>
+<p>If the provided name is quoted with backquotes (`) or contains
+special characters, returns the name quoted with the appropriate quote
+character, otherwise the name is returned unchanged.</p>
+<h4>function TableName($name)</h4>
+<p>The same as NameQuote, but will prepend the current schema if
+specified</p>
+<h4>function MetaType($t,$len=-1,$fieldobj=false)</h4>
+<h4>function ActualType($meta)</h4>
+<p>Convert between database-independent 'Meta' and database-specific
+'Actual' type codes.</p>
+<h4>function ExecuteSQLArray($sqlarray, $contOnError = true)</h4>
+<pre>  RETURNS:      0 if failed, 1 if executed all but with errors, 2 if executed successfully<br>  $sqlarray:    an array of strings with sql code (no semicolon at the end of string)<br>  $contOnError: if true, then continue executing even if error occurs<br></pre>
+<p>Executes an array of SQL strings returned by CreateTableSQL or
+CreateIndexSQL.</p>
+<hr />
+<a name="xmlschema"></a>
+<h2>ADOdb XML Schema (AXMLS)</h2>
+<p>This is a class contributed by Richard Tango-Lowy and Dan Cech that
+allows the user to quickly
+and easily build a database using the excellent ADODB database library
+and a simple XML formatted file.
+You can <a href="http://sourceforge.net/projects/adodb-xmlschema/">download
+the latest version of AXMLS here</a>.</p>
+<h3>Quick Start</h3>
+<p>Adodb-xmlschema, or AXMLS, is a set of classes that allow the user
+to quickly and easily build or upgrade a database on almost any RDBMS
+using the excellent ADOdb database library and a simple XML formatted
+schema file. Our goal is to give developers a tool that's simple to
+use, but that will allow them to create a single file that can build,
+upgrade, and manipulate databases on most RDBMS platforms.</p>
+<span style="font-weight: bold;"> Installing axmls</span>
+<p>The easiest way to install AXMLS to download and install any recent
+version of the ADOdb database abstraction library. To install AXMLS
+manually, simply copy the adodb-xmlschema.inc.php file and the xsl
+directory into your adodb directory.</p>
+<span style="font-weight: bold;"> Using AXMLS in Your Application</span>
+<p>There are two steps involved in using AXMLS in your application:
+first, you must create a schema, or XML representation of your
+database, and second, you must create the PHP code that will parse and
+execute the schema.</p>
+<p>Let's begin with a schema that describes a typical, if simplistic
+user management table for an application.</p>
+<pre class="listing"><pre>&lt;?xml version="1.0"?&gt;<br>&lt;schema version="0.2"&gt;<br><br>  &lt;table name="users"&gt;<br>    &lt;desc&gt;A typical users table for our application.&lt;/desc&gt;<br>    &lt;field name="userId" type="I"&gt;<br>      &lt;descr&gt;A unique ID assigned to each user.&lt;/descr&gt;<br><br>      &lt;KEY/&gt;<br>      &lt;AUTOINCREMENT/&gt;<br>    &lt;/field&gt;<br>    <br>    &lt;field name="userName" type="C" size="16"&gt;&lt;NOTNULL/&gt;&lt;/field&gt;<br><br>    <br>    &lt;index name="userName"&gt;<br>      &lt;descr&gt;Put a unique index on the user name&lt;/descr&gt;<br>      &lt;col&gt;userName&lt;/col&gt;<br>      &lt;UNIQUE/&gt;<br><br>    &lt;/index&gt;<br>  &lt;/table&gt;<br>  <br>  &lt;sql&gt;<br>    &lt;descr&gt;Insert some data into the users table.&lt;/descr&gt;<br>    &lt;query&gt;insert into users (userName) values ( 'admin' )&lt;/query&gt;<br><br>    &lt;query&gt;insert into users (userName) values ( 'Joe' )&lt;/query&gt;<br>  &lt;/sql&gt;<br>&lt;/schema&gt;			<br></pre></pre>
+<p>Let's take a detailed look at this schema.</p>
+<p>The opening &lt;?xml version="1.0"?&gt; tag is required by XML. The
+&lt;schema&gt; tag tells the parser that the enclosed markup defines an
+XML schema. The version="0.2" attribute sets <em>the version of the
+AXMLS DTD used by the XML schema.</em> </p>
+<p>All versions of AXMLS prior to version 1.0 have a schema version of
+"0.1". The current schema version is "0.2".</p>
+<pre class="listing"><pre>&lt;?xml version="1.0"?&gt;<br>&lt;schema version="0.2"&gt;<br>  ...<br>&lt;/schema&gt;<br></pre></pre>
+<p>Next we define one or more tables. A table consists of a fields (and
+other objects) enclosed by &lt;table&gt; tags. The name="" attribute
+specifies the name of the table that will be created in the database.</p>
+<pre class="listing"><pre>&lt;table name="users"&gt;<br><br>    &lt;desc&gt;A typical users table for our application.&lt;/desc&gt;<br>    &lt;field name="userId" type="I"&gt;<br><br>      &lt;descr&gt;A unique ID assigned to each user.&lt;/descr&gt;<br>      &lt;KEY/&gt;<br>      &lt;AUTOINCREMENT/&gt;<br>    &lt;/field&gt;<br>    <br>    &lt;field name="userName" type="C" size="16"&gt;&lt;NOTNULL/&gt;&lt;/field&gt;<br><br>    <br>&lt;/table&gt;<br></pre></pre>
+<p>This table is called "users" and has a description and two fields.
+The description is optional, and is currently only for your own
+information; it is not applied to the database.</p>
+<p>The first &lt;field&gt; tag will create a field named "userId" of
+type "I", or integer. (See the ADOdb Data Dictionary documentation for
+a list of valid types.) This &lt;field&gt; tag encloses two special
+field options: &lt;KEY/&gt;, which specifies this field as a primary
+key, and &lt;AUTOINCREMENT/&gt;, which specifies that the database
+engine should automatically fill this field with the next available
+value when a new row is inserted.</p>
+<p>The second &lt;field&gt; tag will create a field named "userName" of
+type "C", or character, and of length 16 characters. The
+&lt;NOTNULL/&gt; option specifies that this field does not allow NULLs.</p>
+<p>There are two ways to add indexes to a table. The simplest is to
+mark a field with the &lt;KEY/&gt; option as described above; a primary
+key is a unique index. The second and more powerful method uses the
+&lt;index&gt; tags.</p>
+<pre class="listing"><pre>&lt;table name="users"&gt;<br>  ...<br>    <br>  &lt;index name="userName"&gt;<br>    &lt;descr&gt;Put a unique index on the user name&lt;/descr&gt;<br>    &lt;col&gt;userName&lt;/col&gt;<br><br>    &lt;UNIQUE/&gt;<br>  &lt;/index&gt;<br>    <br>&lt;/table&gt;<br></pre></pre>
+<p>The &lt;index&gt; tag specifies that an index should be created on
+the enclosing table. The name="" attribute provides the name of the
+index that will be created in the database. The description, as above,
+is for your information only. The &lt;col&gt; tags list each column
+that will be included in the index. Finally, the &lt;UNIQUE/&gt; tag
+specifies that this will be created as a unique index.</p>
+<p>Finally, AXMLS allows you to include arbitrary SQL that will be
+applied to the database when the schema is executed.</p>
+<pre class="listing"><pre>&lt;sql&gt;<br>  &lt;descr&gt;Insert some data into the users table.&lt;/descr&gt;<br>  &lt;query&gt;insert into users (userName) values ( 'admin' )&lt;/query&gt;<br><br>  &lt;query&gt;insert into users (userName) values ( 'Joe' )&lt;/query&gt;<br>&lt;/sql&gt;<br></pre></pre>
+<p>The &lt;sql&gt; tag encloses any number of SQL queries that you
+define for your own use.</p>
+<p>Now that we've defined an XML schema, you need to know how to apply
+it to your database. Here's a simple PHP script that shows how to load
+the schema.</p>
+<pre class="listing"><pre>&lt;?PHP<br>/* You must tell the script where to find the ADOdb and<br> * the AXMLS libraries.<br> */
+require( "path_to_adodb/adodb.inc.php");
+require( "path_to_adodb/adodb-xmlschema.inc.php" ); # or adodb-xmlschema03.inc.php
+
+/* Configuration information. Define the schema filename,<br> * RDBMS platform (see the ADODB documentation for valid<br> * platform names), and database connection information here.<br> */<br>$schemaFile = 'example.xml';<br>$platform = 'mysql';<br>$dbHost = 'localhost';<br>$dbName = 'database';<br>$dbUser = 'username';<br>$dbPassword = 'password';<br><br>/* Start by creating a normal ADODB connection.<br> */<br>$db = ADONewConnection( $platform );<br>$db-&gt;Connect( $dbHost, $dbUser, $dbPassword, $dbName );<br><br>/* Use the database connection to create a new adoSchema object.<br> */<br>$schema = new adoSchema( $db );<br><br>/* Call ParseSchema() to build SQL from the XML schema file.<br> * Then call ExecuteSchema() to apply the resulting SQL to <br> * the database.<br> */<br>$sql = $schema-&gt;ParseSchema( $schemaFile );<br>$result = $schema-&gt;ExecuteSchema();<br>?&gt;<br></pre></pre>
+<p>Let's look at each part of the example in turn. After you manually
+create the database, there are three steps required to load (or
+upgrade) your schema.</p>
+<p>First, create a normal ADOdb connection. The variables and values
+here should be those required to connect to your database.</p>
+<pre class="listing"><pre>$db = ADONewConnection( 'mysql' );<br>$db-&gt;Connect( 'host', 'user', 'password', 'database' );<br></pre></pre>
+<p>Second, create the adoSchema object that load and manipulate your
+schema. You must pass an ADOdb database connection object in order to
+create the adoSchema object.</p>
+<pre class="listing">$schema = new adoSchema( $db );<br></pre>
+<p>Third, call ParseSchema() to parse the schema and then
+ExecuteSchema() to apply it to the database. You must pass
+ParseSchema() the path and filename of your schema file.</p>
+<pre class="listing">$schema-&gt;ParseSchema( $schemaFile ); <br>$schema-&gt;ExecuteSchema();</pre>
+<p>Execute the above code and then log into your database. If you've
+done all this right, you should see your tables, indexes, and SQL.</p>
+<p>You can find the source files for this tutorial in the examples
+directory as tutorial_shema.xml and tutorial.php. See the class
+documentation for a more detailed description of the adoSchema methods,
+including methods and schema elements that are not described in this
+tutorial.</p>
+<h3>XML Schema Version 3</h3>
+<p>In March 2006, we added adodb-xmlschema03.inc.php to the release, which supports version 3 of XML Schema. 
+The adodb-xmlschema.inc.php remains the same as previous releases, and supports version 2 of XML Schema. 
+Version 3 provides some enhancements:
+
+<ul>
+     <li> Support for updating table data during an upgrade.
+     <li> Support for platform-specific table options and platform negation.
+     <li> Support for unsigned fields.
+     <li> Fixed opt and constraint support
+     <li> Many other fixes such as OPT tag, which allows you to set optional platform settings:
+</ul>
+
+<p>Example usage:
+<pre>&lt;?xml version="1.0"?>
+<b>&lt;schema version="0.3"></b>
+ &lt;table name="ats_kb">
+  &lt;descr>ATS KnowledgeBase&lt;/descr>
+  &lt;opt platform="mysql">TYPE=INNODB&lt;/opt>
+  &lt;field name="recid" type="I"/>
+  &lt;field name="organization_code" type="I4"/> 
+  &lt;field name="sub_code" type="C" size="20"/>
+  etc...
+</pre>
+<p>To use it, change your code to include adodb-xmlschema03.inc.php.
+
+<h3>Upgrading</h3>
+<p>
+If your schema version is older, than XSLT is used to transform the
+schema to the newest version. This means that if you are using an older
+XML schema format, you need to have the XSLT extension installed.
+If you do not want to require your users to have the XSLT extension
+installed, make sure you modify your XML schema to conform to the
+latest version.
+<hr />
+<address>If you have any questions or comments, please email them to
+Richard at richtl#arscognita.com.
+</address>
+</body>
+</html>
Index: /Dev/trunk/rdfapi/util/adodb/docs/docs-oracle.htm
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/docs/docs-oracle.htm	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/docs/docs-oracle.htm	(revision 12)
@@ -0,0 +1,542 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
+<html>
+<head>
+<style>
+pre {
+  background-color: #eee;
+  padding: 0.75em 1.5em;
+  font-size: 12px;
+  border: 1px solid #ddd;
+}
+.greybg {
+  background-color: #eee;
+  padding: 0.75em 1.5em;
+  font-size: 12px;
+  border: 1px solid #ddd;
+}
+.style1 {color: #660000}
+</style>
+<title>ADOdb with PHP and Oracle</title>
+<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
+</style>
+</head>
+
+<body>
+<table width=100%><tr><td>
+<h2>Using ADOdb with PHP and Oracle: an advanced tutorial</h2>
+</td><td><div align="right"><img src=cute_icons_for_site/adodb.gif width="88" height="31"></div></tr></table>
+<p><font size="1">(c)2004-2005 John Lim. All rights reserved.</font></p>
+<h3>1. Introduction</h3>
+<p>Oracle is the most popular commercial database used with PHP. There are many ways of accessing Oracle databases in PHP. These include:</p>
+<ul>
+  <li>The oracle extension</li>
+  <li>The oci8 extension</li>
+  <li>PEAR DB library</li>
+  <li>ADOdb library</li>
+</ul>
+<p>The wide range of choices is confusing to someone just starting with Oracle and PHP. I will briefly summarize the differences, and  show you the advantages of using <a href="http://adodb.sourceforge.net/">ADOdb</a>. </p>
+<p>First we have the C extensions which provide low-level access to Oracle functionality. These C extensions are precompiled into PHP, or linked in dynamically when the web server starts up. Just in case you need it, here's a <a href=http://www.oracle.com/technology/tech/opensource/php/apache/inst_php_apache_linux.html>guide to installing Oracle and PHP on Linux</a>.</p>
+<table width="75%" border="1" align="center">
+  <tr valign="top">
+    <td nowrap><b>Oracle extension</b></td>
+    <td>Designed for Oracle 7 or earlier. This is obsolete.</td>
+  </tr>
+  <tr valign="top">
+    <td nowrap><b>Oci8 extension</b></td>
+    <td> Despite it's name, which implies it is only for Oracle 8i, this is the standard method for accessing databases running Oracle 8i, 9i or 10g (and later).</td>
+  </tr>
+</table>
+<p>Here is an example of using the oci8 extension to query the <i>emp</i> table of the <i>scott</i> schema with bind parameters:
+<pre>
+$conn = OCILogon("scott","tiger", $tnsName); 
+
+$stmt = OCIParse($conn,"select * from emp where empno > :emp order by empno"); 
+$emp = 7900;
+OCIBindByName($stmt, ':emp', $emp);
+$ok = OCIExecute($stmt);
+while (OCIFetchInto($stmt,$arr)) {
+	print_r($arr);
+	echo "&lt;hr>";	
+} 
+</pre>
+<p>This generates the following output:
+<div class=greybg>
+Array ( [0] => 7902 [1] => FORD [2] => ANALYST [3] => 7566 [4] => 03/DEC/81 [5] => 3000 [7] => 20 ) 
+<hr />
+  Array ( [0] => 7934 [1] => MILLER [2] => CLERK [3] => 7782 [4] => 23/JAN/82 [5] => 1300 [7] => 10 )
+</div>
+<p>We also have  many higher level PHP libraries that allow you to simplify the above code. The most popular are <a href="http://pear.php.net/">PEAR DB</a> and <a href="http://adodb.sourceforge.net/">ADOdb</a>.  Here are some of the differences between these libraries:</p>
+<table width="75%" border="1" align="center">
+  <tr>
+    <td><b>Feature</b></td>
+    <td><b>PEAR DB 1.6</b></td>
+    <td><b>ADOdb 4.52</b></td>
+  </tr>
+  <tr valign="top">
+    <td>General Style</td>
+    <td>Simple, easy to use. Lacks Oracle specific functionality.</td>
+    <td>Has multi-tier design. Simple high-level design for beginners, and also lower-level advanced Oracle functionality.</td>
+  </tr>
+  <tr valign="top">
+    <td>Support for Prepare</td>
+    <td>Yes, but only on one statement, as the last prepare overwrites previous prepares.</td>
+    <td>Yes (multiple simultaneous prepare's allowed)</td>
+  </tr>
+  <tr valign="top">
+    <td>Support for LOBs</td>
+    <td>No</td>
+    <td>Yes, using update semantics</td>
+  </tr>
+  <tr valign="top">
+    <td>Support for REF Cursors</td>
+    <td>No</td>
+    <td>Yes</td>
+  </tr>
+  <tr valign="top">
+    <td>Support for IN Parameters</td>
+    <td>Yes</td>
+    <td>Yes</td>
+  </tr>
+  <tr valign="top">
+    <td>Support for OUT Parameters</td>
+    <td>No</td>
+    <td>Yes</td>
+  </tr>
+  <tr valign="top">
+    <td>Schema creation using XML</td>
+    <td>No</td>
+    <td>Yes, including ability to define tablespaces and constraints</td>
+  </tr>
+  <tr valign="top">
+    <td>Provides database portability features</td>
+    <td>No</td>
+    <td>Yes, has some ability to abstract features that differ between databases such as dates, bind parameters, and data types.</td>
+  </tr>
+  <tr valign="top">
+    <td>Performance monitoring and tracing</td>
+    <td>No</td>
+    <td>Yes. SQL can be traced and linked to web page it was executed on. Explain plan support included.</td>
+  </tr>
+  <tr valign="top">
+    <td>Recordset caching for frequently used queries</td>
+    <td>No</td>
+    <td>Yes. Provides great speedups for SQL involving complex <i>where, group-by </i>and <i>order-by</i> clauses.</td>
+  </tr>
+  <tr valign="top">
+    <td>Popularity</td>
+    <td>Yes, part of PEAR release</td>
+    <td>Yes, many open source projects are using this software, including PostNuke, Xaraya, Mambo, Tiki Wiki.</td>
+  </tr>
+  <tr valign="top">
+    <td>Speed</td>
+    <td>Medium speed.</td>
+    <td>Very high speed. Fastest database abstraction library available for PHP. <a href="http://phplens.com/lens/adodb/">Benchmarks are available</a>.</td>
+  </tr>
+  <tr valign="top">
+    <td>High Speed Extension available</td>
+    <td>No</td>
+    <td>Yes. You can install the optional ADOdb extension, which reimplements the most frequently used parts of ADOdb as fast C code. Note that the source code version of ADOdb runs just fine without this extension, and only makes use of the extension if detected.</td>
+  </tr>
+</table>
+<p> PEAR DB is good enough for simple web apps. But if you need more power, you can see ADOdb offers more sophisticated functionality. The rest of this article will concentrate on using ADOdb with Oracle. You can find out more about <a href="#connecting">connecting to Oracle</a> later in this guide.</p>
+<h4>ADOdb Example</h4>
+<p>In ADOdb, the above oci8 example querying the <i>emp</i> table could be written as:</p>
+<pre>
+include "/path/to/adodb.inc.php";
+$db = NewADOConnection("oci8");
+$db->Connect($tnsName, "scott", "tiger");
+
+$rs = $db->Execute("select * from emp where empno>:emp order by empno", 
+                    array('emp' => 7900));
+while ($arr = $rs->FetchRow()) {
+    print_r($arr);
+	echo "&lt;hr>";
+}
+</pre>
+<p>The Execute( ) function returns a recordset object, and you can retrieve the rows returned using $recordset-&gt;FetchRow( ). </p>
+<p>If we ignore the initial connection preamble, we can see the ADOdb version is much easier and simpler:</p>
+<table width="100%" border="1">
+  <tr valign="top" bgcolor="#FFFFFF">
+    <td width="50%" bgcolor="#e0e0e0"><b>Oci8</b></td>
+    <td bgcolor="#e0e0e0"><b>ADOdb</b></td>
+  </tr>
+  <tr valign="top" bgcolor="#CCCCCC">
+    <td><pre><font size="1">$stmt = <b>OCIParse</b>($conn,
+       "select * from emp where empno > :emp"); 
+$emp = 7900;
+<b>OCIBindByName</b>($stmt, ':emp', $emp);
+$ok = <b>OCIExecute</b>($stmt);
+
+while (<b>OCIFetchInto</b>($stmt,$arr)) {
+	print_r($arr);
+	echo "&lt;hr>";	
+} </font></pre></td>
+    <td><pre><font size="1">$recordset = $db-><b>Execute</b>("select * from emp where empno>:emp", 
+                           array('emp' => 7900));
+
+while ($arr = $recordset-><b>FetchRow</b>()) {
+	print_r($arr);
+	echo "&lt;hr>";
+}</font></pre></td>
+  </tr>
+</table>
+<p>&nbsp;</p>
+<h3>2. ADOdb Query Semantics</h3>
+<p>You can also query the database using the standard Microsoft ADO MoveNext( ) metaphor. The data array for the current row is stored in the <i>fields</i> property of the recordset object, $rs.
+MoveNext( ) offers the highest performance among all the techniques for iterating through a recordset:
+<pre>
+$rs = $db->Execute("select * from emp where empno>:emp", array('emp' => 7900));
+while (!$rs->EOF) {
+	print_r($rs->fields);
+	$rs->MoveNext();
+}
+</pre>
+<p>And if you are interested in having the data returned in a 2-dimensional array, you can use:
+<pre>
+$arr = $db->GetArray("select * from emp where empno>:emp", array('emp' => 7900));
+</pre>
+<p>Now to obtain only the first row as an array:
+<pre>
+$arr = $db->GetRow("select * from emp where empno=:emp", array('emp' => 7900));
+</pre>
+<p>Or to retrieve only the first field of the first row:
+<pre>
+$arr = $db->GetOne("select ename from emp where empno=:emp", array('emp' => 7900));
+</pre>
+<p>For easy pagination support, we provide the SelectLimit function. The following will perform a select query, limiting it to 100 rows, starting from row 201 (row 1 being the 1st row):
+<pre>
+$offset = 200; $limitrows = 100;
+$rs = $db->SelectLimit('select * from table', $limitrows, $offset);
+</pre>
+<p>The $offset parameter is optional.
+<h4>Array Fetch Mode</h4>
+<p>When data is being returned in an array, you can choose the type of array the data is returned in. 
+<ol>
+  <li> Numeric indexes - use <font size="2" face="Courier New, Courier, mono">$connection-&gt;SetFetchMode(ADODB_FETCH_NUM).</font></li>
+  <li>Associative indexes - the keys of the array are the names of the fields (in upper-case). Use <font size="2" face="Courier New, Courier, mono">$connection-&gt;SetFetchMode(ADODB_FETCH_ASSOC)</font><font face="Courier New, Courier, mono">.</font></li>
+  <li>Both numeric and associative indexes - use <font size="2" face="Courier New, Courier, mono">$connection-&gt;SetFetchMode(ADODB_FETCH_BOTH).</font></li>
+</ol>
+<p>The default is ADODB_FETCH_BOTH for Oracle.</p>
+<h4><b>Caching</b></h4>
+<p>You can define a database cache directory using $ADODB_CACHE_DIR, and cache the results of frequently used queries that rarely change. This is particularly useful for SQL with complex where clauses and group-by's and order-by's. It is also good for relieving heavily-loaded database servers.</p>
+<p>This example will cache the following select statement for 3600 seconds (1 hour):</p>
+<pre>
+$ADODB_CACHE_DIR = '/var/adodb/tmp';
+$rs = $db->CacheExecute(3600, "select names from allcountries order by 1");
+</pre>
+There are analogous CacheGetArray(
+), CacheGetRow( ),  CacheGetOne( ) and CacheSelectLimit( )  functions. The first parameter is the number of seconds to cache. You can also pass a bind array as a 3rd parameter (not shown above).
+<p>There is an alternative syntax for the caching functions. The first parameter is omitted, and you set the cacheSecs
+ property of the connection object:
+<pre>
+$ADODB_CACHE_DIR = '/var/adodb/tmp';
+$connection->cacheSecs = 3600;
+$rs = $connection->CacheExecute($sql, array('id' => 1));
+</pre>
+<h3>&nbsp;</h3>
+<h3>3. Using Prepare( ) For Frequently Used Statements</h3>
+<p>Prepare( ) is  for compiling frequently used  SQL statement for reuse. For example, suppose we have a large array which needs to be inserted into an Oracle database. The following will result in a massive speedup in query execution (at least 20-40%), as the SQL statement only needs to be compiled once:</p>
+<pre>
+$stmt = $db->Prepare('insert into table (field1, field2) values (:f1, :f2)');
+foreach ($arrayToInsert as $key => $value) {
+	$db->Execute($stmt, array('f1' => $key, 'f2' => $val);
+}
+</pre>
+<p>&nbsp;</p>
+<h3>4. Working With LOBs</h3>
+<p>Oracle treats data which is more than 4000 bytes in length specially. These are called Large Objects, or LOBs for short. Binary LOBs are BLOBs, and character LOBs are CLOBs. In most Oracle libraries, you need to do a lot of work to process LOBs, probably because Oracle designed it to work in systems with little memory. ADOdb tries to make things easy by assuming the LOB can fit into main memory. </p>
+<p>ADOdb will transparently handle LOBs  in <i>select</i> statements. The LOBs are automatically converted to PHP variables without any special coding.</p>
+<p>For updating records with LOBs, the functions UpdateBlob( ) and UpdateClob( ) are provided. Here's a BLOB example. The parameters should be self-explanatory:
+<pre>
+$ok = $db->Execute("insert into aTable (id, name, ablob) 
+                                values (aSequence.nextVal, 'Name', null)");
+if (!$ok) return LogError($db-&gt;ErrorMsg());
+<font color="#006600"># params: $tableName, $blobFieldName, $blobValue, $whereClause</font>
+$db->UpdateBlob('aTable', 'ablob', $blobValue, 'id=aSequence.currVal');
+</pre>
+<p>and the analogous CLOB example:
+<pre>
+$ok = $db->Execute("insert into aTable (id, name, aclob) 
+                                values (aSequence.nextVal, 'Name', null)");
+if (!$ok) return LogError($db-&gt;ErrorMsg());
+$db->UpdateClob('aTable', 'aclob', $clobValue, 'id=aSequence.currVal');
+</pre>
+<p>Note that LogError( ) is a user-defined function, and not part of ADOdb.
+<p>Inserting LOBs is more complicated. Since ADOdb 4.55, we allow you to do this
+  (assuming that the <em>photo</em> field is a BLOB, and we want to store $blob_data into
+  this field, and the primary key is the <em>id</em> field):
+<pre>
+	$sql = <span class="style1">"INSERT INTO photos ( ID, photo) ".
+			"VALUES ( :id, empty_blob() )".
+			" RETURNING photo INTO :xx"</span>;
+
+ 		$stmt = $db->PrepareSP($sql);
+		$db->InParameter($stmt, $<strong>id</strong>, <span class="style1">'id'</span>);
+		$blob = $db->InParameter($stmt, $<strong>blob_data</strong>, <span class="style1">'xx'</span>,-1, OCI_B_BLOB);
+		$db->StartTrans();
+		$ok = $db->Execute($stmt);
+		$db->CompleteTrans();
+</pre> 
+<p>
+<h3>5. REF CURSORs</h3>
+<p>Oracle recordsets can be passed around as variables called REF Cursors. For example, in PL/SQL, we could define a function <i>open_tab</i> that returns a REF CURSOR in the first parameter:</p>
+<pre>
+TYPE TabType IS REF CURSOR RETURN TAB%ROWTYPE;
+
+PROCEDURE open_tab (tabcursor IN OUT TabType,tablenames IN VARCHAR) IS
+	BEGIN
+		OPEN tabcursor FOR SELECT * FROM TAB WHERE tname LIKE tablenames;
+	END open_tab;
+</pre>
+<p>In ADOdb, we could access this REF Cursor using the ExecuteCursor() function. The following will find
+ all table names that begin with 'A' in the current schema:
+<pre>
+$rs = $db->ExecuteCursor("BEGIN open_tab(:refc,'A%'); END;",'refc');
+while ($arr = $rs->FetchRow()) print_r($arr);
+</pre>
+<p>The first parameter is the PL/SQL statement, and the second parameter is the name of the REF Cursor.
+</p>
+<p>&nbsp;</p>
+<h3>6. In and Out Parameters</h3>
+<p>The following PL/SQL
+stored procedure  requires an input  variable, and returns a result into an output variable:
+<pre>
+PROCEDURE data_out(input IN VARCHAR, output OUT VARCHAR) IS
+	BEGIN
+		output := 'I love '||input;
+	END;
+</pre>
+<p>The following ADOdb code allows you to call the stored procedure:</p>
+<pre>
+$stmt = $db->PrepareSP("BEGIN adodb.data_out(:a1, :a2); END;");
+$input = 'Sophia Loren';
+$db->InParameter($stmt,$input,'a1');
+$db->OutParameter($stmt,$output,'a2');
+$ok = $db->Execute($stmt);
+if ($ok) echo ($output == 'I love Sophia Loren') ? 'OK' : 'Failed';
+</pre>
+<p>PrepareSP( ) is a special function that knows about bind parameters.
+The main limitation currently is that IN OUT parameters do not work.
+<h4>Bind Parameters and REF CURSORs</h4>
+<p>We could also rewrite the REF CURSOR example to use InParameter (requires ADOdb 4.53 or later):
+<pre>
+$stmt = $db->PrepareSP("BEGIN adodb.open_tab(:refc,:tabname); END;");
+$input = 'A%';
+$db->InParameter($stmt,$input,'tabname');
+$rs = $db->ExecuteCursor($stmt,'refc');
+while ($arr = $rs->FetchRow()) print_r($arr);
+</pre>
+<h4>Bind Parameters and LOBs</h4>
+<p>You can also operate on LOBs. In this example, we have IN and OUT parameters using CLOBs. 
+<pre>
+	$text = 'test test test';
+	$sql = "declare rs clob; begin :rs := lobinout(:sa0); end;";
+	$stmt = $conn -> PrepareSP($sql);
+	$conn -> InParameter($stmt,$text,'sa0', -1, OCI_B_CLOB); # -1 means variable length
+	$rs = '';
+	$conn -> OutParameter($stmt,$rs,'rs', -1, OCI_B_CLOB);
+	$conn -> Execute($stmt);
+	echo "return = ".$rs."&lt;br>";
+</pre>
+<p>Similarly, you can use the constant OCI_B_BLOB to indicate that you are using BLOBs.
+<h4>Reusing Bind Parameters with CURSOR_SHARING=FORCE</h4>
+<p>Many web programmers do not care to use bind parameters, and prefer to enter the SQL directly. So instead of:</p>
+<pre>
+$arr = $db->GetArray("select * from emp where empno>:emp", array('emp' => 7900));
+</pre>
+<p>They prefer  entering the values inside the SQL:
+<pre>
+$arr = $db->GetArray("select * from emp where empno>7900");
+</pre>
+<p>This reduces Oracle performance because Oracle will reuse compiled SQL which is identical to previously compiled SQL. The above example with the values inside the SQL
+is unlikely to be reused. As an optimization, from Oracle 8.1 onwards, you can set the following session parameter after you login:
+<pre>
+ALTER SESSION SET CURSOR_SHARING=FORCE
+</pre>
+<p>This will force Oracle to convert all such variables (eg. the 7900 value) into constant bind parameters, improving SQL reuse.</p>
+<p>More <a href="http://phplens.com/adodb/code.initialization.html#speed">speedup tips</a>.</p>
+<p>&nbsp;</p>
+<h3>7. Dates and Datetime in ADOdb</h3>
+<p>There are two things you need to know about dates in ADOdb. </p>
+<p>First, to ensure cross-database compability, ADOdb assumes that dates are returned in ISO format (YYYY-MM-DD H24:MI:SS).</p>
+<p>Secondly, since Oracle treats dates and datetime as the same data type, we decided not to display the time in the default date format. So on login, ADOdb will set the NLS_DATE_FORMAT to 'YYYY-MM-DD'. If you prefer to show the date and time by default, do this:</p>
+<pre>
+$db = NewADOConnection('oci8');
+$db->NLS_DATE_FORMAT =  'RRRR-MM-DD HH24:MI:SS';
+$db->Connect($tns, $user, $pwd);
+</pre>
+<p>Or execute:</p>
+<pre>$sql = &quot;ALTER SESSION SET NLS_DATE_FORMAT = 'RRRR-MM-DD HH24:MI:SS'&quot;;
+$db-&gt;Execute($sql);
+</pre>
+<p>If you are not concerned about date portability and do not use ADOdb's portability layer, you can use your preferred date format instead.
+<p>
+<h3>8. Database Portability Layer</h3>
+<p>ADOdb provides the following functions for portably generating SQL functions 
+  as strings to be merged into your SQL statements:</p>
+<table width="75%" border="1" align=center>
+  <tr> 
+    <td width=30%><b>Function</b></td>
+    <td><b>Description</b></td>
+  </tr>
+  <tr> 
+    <td>DBDate($date)</td>
+    <td>Pass in a UNIX timestamp or ISO date and it will convert it to a date 
+      string formatted for INSERT/UPDATE</td>
+  </tr>
+  <tr> 
+    <td>DBTimeStamp($date)</td>
+    <td>Pass in a UNIX timestamp or ISO date and it will convert it to a timestamp 
+      string formatted for INSERT/UPDATE</td>
+  </tr>
+  <tr> 
+    <td>SQLDate($date, $fmt)</td>
+    <td>Portably generate a date formatted using $fmt mask, for use in SELECT 
+      statements.</td>
+  </tr>
+  <tr> 
+    <td>OffsetDate($date, $ndays)</td>
+    <td>Portably generate a $date offset by $ndays.</td>
+  </tr>
+  <tr> 
+    <td>Concat($s1, $s2, ...)</td>
+    <td>Portably concatenate strings. Alternatively, for mssql use mssqlpo driver, 
+      which allows || operator.</td>
+  </tr>
+  <tr> 
+    <td>IfNull($fld, $replaceNull)</td>
+    <td>Returns a string that is the equivalent of MySQL IFNULL or Oracle NVL.</td>
+  </tr>
+  <tr>
+    <td>Param($name)</td>
+    <td>Generates bind placeholders, using ? or named conventions as appropriate.</td>
+  </tr>
+  <tr><td>$db->sysDate</td><td>Property that holds the SQL function that returns today's date</td>
+</tr>
+<tr><td>$db->sysTimeStamp</td><td>Property that holds the SQL function that returns the current
+timestamp (date+time).
+</td>
+</tr>
+<tr>
+<td>$db->concat_operator</td><td>Property that holds the concatenation operator
+</td>
+</tr>
+<tr><td>$db->length</td><td>Property that holds the name of the SQL strlen function.
+</td></tr>
+
+<tr><td>$db->upperCase</td><td>Property that holds the name of the SQL strtoupper function.
+</td></tr>
+<tr><td>$db->random</td><td>Property that holds the SQL to generate a random number between 0.00 and 1.00.
+</td>
+</tr>
+<tr><td>$db->substr</td><td>Property that holds the name of the SQL substring function.
+</td></tr>
+</table>
+<p>ADOdb also provides multiple oracle oci8 drivers for different scenarios:</p>
+<table width="75%" border="1" align="center">
+  <tr>
+    <td nowrap><b>Driver Name</b></td>
+    <td><b>Description</b></td>
+  </tr>
+  <tr>
+    <td>oci805 </td>
+    <td>Specifically for Oracle 8.0.5. This driver has a slower SelectLimit( ).</td>
+  </tr>
+  <tr>
+    <td>oci8</td>
+    <td>The default high performance driver. The keys of associative arrays returned in a recordset are upper-case.</td>
+  </tr>
+  <tr>
+    <td>oci8po</td>
+    <td> The portable Oracle driver. Slightly slower than oci8. This driver uses ? instead of :<i>bindvar</i> for binding variables, which is the standard for  other databases. Also the keys of associative arrays are in lower-case like other databases.</td>
+  </tr>
+</table>
+<p>Here's an example of calling the <i>oci8po</i> driver. Note that the bind variables use question-mark:</p>
+<pre>$db = NewADOConnection('oci8po');
+$db-&gt;Connect($tns, $user, $pwd);
+$db-&gt;Execute(&quot;insert into atable (f1, f2) values (?,?)&quot;, array(12, 'abc'));</pre>
+<p>&nbsp;<a name=connecting></a>
+<h3>9. Connecting to Oracle</h3>
+<p>Before you can use ADOdb, you need to have the Oracle client installed and setup the oci8 extension. This extension comes pre-compiled for Windows (but you still need to enable it in the php.ini file). For information on compiling the oci8 extension for PHP and Apache on Unix, there is an excellent guide at <a href="http://www.oracle.com/technology/tech/opensource/php/apache/inst_php_apache_linux.html">oracle.com</a>. </p>
+<h4>Should You Use Persistent Connections</h4>
+<p>One question that is frequently asked is should you use persistent connections to Oracle. Persistent connections allow PHP to recycle existing connections, reusing them after the previous web pages have completed. Non-persistent connections close automatically after the web page has completed. Persistent connections are faster because the cost of reconnecting is expensive, but there is additional resource overhead. As an alternative, Oracle allows you to pool and reuse server processes; this is called  <a href="http://www.cise.ufl.edu/help/database/oracle-docs/server.920/a96521/manproc.htm#13132">Shared Server</a> (also known as MTS).</p>
+<p>The author's benchmarks suggest that using non-persistent connections and the  Shared Server configuration offer the best performance. If Shared Server is not an option, only then consider using persistent connections.</p>
+<h4>Connection Examples</h4>
+<p>Just in case you are having problems connecting to Oracle, here are some examples:</p>
+<p>a. PHP and Oracle reside on the same machine, use default SID, with non-persistent connections:</p>
+<pre>	$conn = NewADOConnection('oci8');
+	$conn-&gt;Connect(false, 'scott', 'tiger');</pre>
+<p>b. TNS Name defined in tnsnames.ora (or ONAMES or HOSTNAMES), eg. 'myTNS', using persistent connections:</p>
+<pre>	$conn = NewADOConnection('oci8');
+	$conn-&gt;PConnect(false, 'scott', 'tiger', 'myTNS');</pre>
+<p>or</p>
+<pre> 	$conn-&gt;PConnect('myTNS', 'scott', 'tiger');</pre>
+<p>c. Host Address and SID</p>
+<pre>
+	$conn->connectSID = true;	
+	$conn-&gt;Connect('192.168.0.1', 'scott', 'tiger', 'SID');</pre>
+<p>d. Host Address and Service Name</p>
+<pre>	$conn-&gt;Connect('192.168.0.1', 'scott', 'tiger', 'servicename');</pre>
+<p>e. Oracle connection string:
+<pre>	$cstr = "(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=$host)(PORT=$port))
+			(CONNECT_DATA=(SID=$sid)))";
+	$conn-&gt;Connect($cstr, 'scott', 'tiger');
+</pre>
+<p>f. ADOdb data source names (dsn):
+<pre>
+	$dsn = 'oci8://user:pwd@tnsname/?persist';  # persist is optional
+	$conn = ADONewConnection($dsn);  # no need for Connect/PConnect
+	
+	$dsn = 'oci8://user:pwd@host/sid';
+	$conn = ADONewConnection($dsn);
+	
+	$dsn = 'oci8://user:pwd@/';   # oracle on local machine
+	$conn = ADONewConnection($dsn);</pre>
+<p>With ADOdb data source names,
+you don't have to call Connect( ) or PConnect( ).
+</p>
+<p>&nbsp;</p>
+<h3>10. Error Checking</h3>
+<p>The examples in this article are easy to read but a bit simplistic because we ignore error-handling. Execute( ) and Connect( ) will return false on error. So a more realistic way to call Connect( ) and Execute( ) is:
+<pre>function InvokeErrorHandler()
+{<br>global $db; ## assume global
+    MyLogFunction($db-&gt;ErrorNo(), $db-&gt;ErrorMsg());
+}
+if (!$db-&gt;Connect($tns, $usr, $pwd)) InvokeErrorHandler();
+
+$rs = $db->Execute("select * from emp where empno>:emp order by empno", 
+                    array('emp' => 7900));
+if (!$rs) return InvokeErrorHandler();
+while ($arr = $rs->FetchRow()) {
+    print_r($arr);
+	echo "&lt;hr>";
+}
+</pre>
+<p>You can retrieve the  error message and error number of the last SQL statement executed from ErrorMsg( ) and ErrorNo( ). You can also <a href=http://phplens.com/adodb/using.custom.error.handlers.and.pear_error.html>define a custom error handler function</a>.
+ADOdb also supports throwing exceptions in PHP5.
+<p>&nbsp;</p>
+<h3>Handling Large Recordsets (added 27 May 2005)</h3>
+The oci8 driver does not support counting the number of records returned in a SELECT statement, so the function RecordCount() 
+is emulated when the global variable $ADODB_COUNTRECS is set to true, which is the default. 
+We emulate this by buffering all the records. This can take up large amounts of memory for big recordsets.
+ Set $ADODB_COUNTRECS to false for the best performance. 
+ <p>
+This variable is checked every time a query is executed, so you can selectively choose which recordsets to count.
+<p>&nbsp;</p>
+<h3>11. Other ADOdb Features</h3>
+<p><a href="http://phplens.com/lens/adodb/docs-datadict.htm">Schema generation</a>. This allows you to define a schema using XML and import it into different RDBMS systems portably.</p>
+<p><a href="http://phplens.com/lens/adodb/docs-perf.htm">Performance monitoring and tracing</a>. Highlights of performance monitoring include identification of poor and suspicious SQL, with explain plan support, and identifying which web pages the SQL ran on.</p>
+<p>&nbsp;</p>
+<h3>12. Download</h3>
+<p>You can <a href="http://adodb.sourceforge.net/#download">download ADOdb from sourceforge</a>. ADOdb uses a BSD style license. That means that it is free for commercial use, and redistribution without source code is allowed.</p>
+<p>&nbsp;</p>
+<h3>13. Resources</h3>
+<ul>
+  <li>Oracle's <a href="http://www.oracle.com/technology/pub/articles/php_experts/index.html">Hitchhiker Guide to PHP</a></li>
+  <li>OTN article on <a href=http://www.oracle.com/technology/pub/articles/deployphp/lim_deployphp.html>Optimizing PHP and Oracle</a> by this author.
+  <li>Oracle has an excellent <a href="http://www.oracle.com/technology/tech/opensource/php/php_troubleshooting_faq.html">FAQ on PHP</a></li>
+  <li>PHP <a href="http://php.net/oci8">oci8</a> manual pages</li>
+  <li><a href=http://phplens.com/lens/lensforum/topics.php?id=4>ADOdb forums</a>.
+</ul>
+</body>
+</html>
Index: /Dev/trunk/rdfapi/util/adodb/docs/docs-perf.htm
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/docs/docs-perf.htm	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/docs/docs-perf.htm	(revision 12)
@@ -0,0 +1,962 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
+<html>
+<head>
+  <title>ADOdb Performance Monitoring Library</title>
+  <style type="text/css">
+body, td {
+/*font-family: Arial, Helvetica, sans-serif;*/
+font-size: 11pt;
+}
+pre {
+font-size: 9pt;
+background-color: #EEEEEE; padding: .5em; margin: 0px;
+}
+.toplink {
+font-size: 8pt;
+}
+  </style>
+</head>
+<body>
+<h3>The ADOdb Performance Monitoring Library</h3>
+<p>V4.94 23 Jan 2007 (c) 2000-2007 John Lim (jlim#natsoft.com.my)</p>
+<p><font size="1">This software is dual licensed using BSD-Style and
+LGPL. This means you can use it in compiled proprietary and commercial
+products.</font></p>
+<p>Useful ADOdb links: <a href="http://adodb.sourceforge.net/#download">Download</a>
+&nbsp; <a href="http://adodb.sourceforge.net/#docs">Other Docs</a>
+</p>
+<h3>Introduction</h3>
+<p>This module, part of the ADOdb package, provides both CLI and HTML
+interfaces for viewing key performance indicators of your database.
+This is very useful because web apps such as the popular phpMyAdmin
+currently do not provide effective database health monitoring tools.
+The module provides the following: </p>
+<ul>
+  <li>A quick health check of your database server using <code>$perf-&gt;HealthCheck()</code>
+or <code>$perf-&gt;HealthCheckCLI()</code>. </li>
+  <li>User interface for performance monitoring, <code>$perf-&gt;UI()</code>.
+This UI displays:
+    <ul>
+      <li>the health check, </li>
+      <li>all SQL logged and their query plans, </li>
+      <li>a list of all tables in the current database</li>
+      <li>an interface to continiously poll the server for key
+performance indicators such as CPU, Hit Ratio, Disk I/O</li>
+      <li>a form where you can enter and run SQL interactively.</li>
+    </ul>
+  </li>
+  <li>Gives you an API to build database monitoring tools for a server
+farm, for example calling <code>$perf-&gt;DBParameter('data cache hit
+ratio')</code> returns this very important statistic in a database
+independant manner. </li>
+</ul>
+<p>ADOdb also has the ability to log all SQL executed, using <a
+ href="docs-adodb.htm#logsql">LogSQL</a>. All SQL logged can be
+analyzed through the performance monitor <a href="#ui">UI</a>. In the <i>View
+SQL</i> mode, we categorize the SQL into 3 types:
+</p>
+<ul>
+  <li><b>Suspicious SQL</b>: queries with high average execution times,
+and are potential candidates for rewriting</li>
+  <li><b>Expensive SQL</b>: queries with high total execution times
+(#executions * avg execution time). Optimizing these queries will
+reduce your database server load.</li>
+  <li><b>Invalid SQL</b>: queries that generate errors.</li>
+</ul>
+<p>Each query is hyperlinked to a description of the query plan, and
+every PHP script that executed that query is also shown.</p>
+<p>Please note that the information presented is a very basic database
+health check, and does not provide a complete overview of database
+performance. Although some attempt has been made to make it work across
+multiple databases in the same way, it is impossible to do so. For the
+health check, we do try to display the following key database
+parameters for all drivers:</p>
+<ul>
+  <li><b>data cache size</b> - The amount of memory allocated to the
+cache.</li>
+  <li><b>data cache hit ratio</b> - A measure of how effective the
+cache is, as a percentage. The higher, the better.</li>
+  <li><b>current connections</b> - The number of sessions currently
+connected to the database. </li>
+</ul>
+<p>You will need to connect to the database as an administrator to view
+most of the parameters. </p>
+<p>Code improvements as very welcome, particularly adding new database
+parameters and automated tuning hints.</p>
+<a name="usage"></a>
+<h3>Usage</h3>
+<p>Currently, the following drivers: <em>mysql</em>, <em>postgres</em>,
+<em>oci8</em>, <em>mssql</em>, <i>informix</i> and <em>db2</em> are
+supported. To create a new performance monitor, call NewPerfMonitor( )
+as demonstrated below: </p>
+<pre>&lt;?php<br>include_once('adodb.inc.php');<br>session_start(); <font
+ color="#006600"># session variables required for monitoring</font><br>$conn = ADONewConnection($driver);<br>$conn-&gt;Connect($server,$user,$pwd,$db);<br>$perf =&amp; NewPerfMonitor($conn);<br>$perf-&gt;UI($pollsecs=5);<br>?&gt;<br></pre>
+<p>It is also possible to retrieve a single database parameter:</p>
+<pre>$size = $perf-&gt;DBParameter('data cache size');<br></pre>
+<p>
+Thx to Fernando Ortiz for the informix module. </p>
+<h3>Methods</h3>
+<a name="ui"></a>
+<p><font face="Courier New, Courier, mono">function <b>UI($pollsecs=5)</b></font></p>
+<p>Creates a web-based user interface for performance monitoring. When
+you click on Poll, server statistics will be displayed every $pollsecs
+seconds. See <a href="#usage">Usage</a> above. </p>
+<p>Since 4.11, we allow users to enter and run SQL interactively via
+the "Run SQL" link. To disable this for security reasons, set this
+constant before calling $perf-&gt;UI(). </p>
+<p> </p>
+<pre>define('ADODB_PERF_NO_RUN_SQL',1);</pre>
+<p>Sample output follows below:</p>
+<table bgcolor="lightyellow" border="1" width="100%">
+  <tbody>
+    <tr>
+      <td> <b><a href="http://php.weblogs.com/adodb?perf=1">ADOdb</a>
+Performance Monitor</b> for localhost, db=test<br>
+      <font size="-1">PostgreSQL 7.3.2 on i686-pc-cygwin, compiled by
+GCC gcc (GCC) 3.2 20020927 (prerelease)</font></td>
+    </tr>
+    <tr>
+      <td> <a href="#">Performance Stats</a> &nbsp; <a href="#">View
+SQL</a> &nbsp; <a href="#">View Tables</a> &nbsp; <a href="#">Poll
+Stats</a></td>
+    </tr>
+  </tbody>
+</table>
+<table bgcolor="white" border="1">
+  <tbody>
+    <tr>
+      <td colspan="3">
+      <h3>postgres7</h3>
+      </td>
+    </tr>
+    <tr>
+      <td><b>Parameter</b></td>
+      <td><b>Value</b></td>
+      <td><b>Description</b></td>
+    </tr>
+    <tr bgcolor="#f0f0f0">
+      <td colspan="3"><i>Ratios</i> &nbsp;</td>
+    </tr>
+    <tr>
+      <td>statistics collector</td>
+      <td>TRUE</td>
+      <td>Value must be TRUE to enable hit ratio statistics (<i>stats_start_collector</i>,<i>stats_row_level</i>
+and <i>stats_block_level</i> must be set to true in postgresql.conf)</td>
+    </tr>
+    <tr>
+      <td>data cache hit ratio</td>
+      <td>99.7967555299239</td>
+      <td>&nbsp;</td>
+    </tr>
+    <tr bgcolor="#f0f0f0">
+      <td colspan="3"><i>IO</i> &nbsp;</td>
+    </tr>
+    <tr>
+      <td>data reads</td>
+      <td>125</td>
+      <td>&nbsp; </td>
+    </tr>
+    <tr>
+      <td>data writes</td>
+      <td>21.78125000000000000</td>
+      <td>Count of inserts/updates/deletes * coef</td>
+    </tr>
+    <tr bgcolor="#f0f0f0">
+      <td colspan="3"><i>Data Cache</i> &nbsp;</td>
+    </tr>
+    <tr>
+      <td>data cache buffers</td>
+      <td>640</td>
+      <td>Number of cache buffers. <a
+ href="http://www.varlena.com/GeneralBits/Tidbits/perf.html#basic">Tuning</a></td>
+    </tr>
+    <tr>
+      <td>cache blocksize</td>
+      <td>8192</td>
+      <td>(estimate)</td>
+    </tr>
+    <tr>
+      <td>data cache size</td>
+      <td>5M</td>
+      <td>&nbsp;</td>
+    </tr>
+    <tr>
+      <td>operating system cache size</td>
+      <td>80M</td>
+      <td>(effective cache size)</td>
+    </tr>
+    <tr bgcolor="#f0f0f0">
+      <td colspan="3"><i>Memory Usage</i> &nbsp;</td>
+    </tr>
+    <tr>
+      <td>sort buffer size</td>
+      <td>1M</td>
+      <td>Size of sort buffer (per query)</td>
+    </tr>
+    <tr bgcolor="#f0f0f0">
+      <td colspan="3"><i>Connections</i> &nbsp;</td>
+    </tr>
+    <tr>
+      <td>current connections</td>
+      <td>0</td>
+      <td>&nbsp;</td>
+    </tr>
+    <tr>
+      <td>max connections</td>
+      <td>32</td>
+      <td>&nbsp;</td>
+    </tr>
+    <tr bgcolor="#f0f0f0">
+      <td colspan="3"><i>Parameters</i> &nbsp;</td>
+    </tr>
+    <tr>
+      <td>rollback buffers</td>
+      <td>8</td>
+      <td>WAL buffers</td>
+    </tr>
+    <tr>
+      <td>random page cost</td>
+      <td>4</td>
+      <td>Cost of doing a seek (default=4). See <a
+ href="http://www.varlena.com/GeneralBits/Tidbits/perf.html#less">random_page_cost</a></td>
+    </tr>
+  </tbody>
+</table>
+<p><font face="Courier New, Courier, mono">function <b>HealthCheck</b>()</font></p>
+<p>Returns database health check parameters as a HTML table. You will
+need to echo or print the output of this function,</p>
+<p><font face="Courier New, Courier, mono">function <b>HealthCheckCLI</b>()</font></p>
+<p>Returns database health check parameters formatted for a command
+line interface. You will need to echo or print the output of this
+function. Sample output for mysql:</p>
+<pre>-- Ratios -- <br>          MyISAM cache hit ratio =&gt; 56.5635738832 <br>          InnoDB cache hit ratio =&gt; 0 <br>             sql cache hit ratio =&gt; 0 <br> -- IO -- <br>                      data reads =&gt; 2622 <br>                     data writes =&gt; 2415.5 <br> -- Data Cache -- <br>          MyISAM data cache size =&gt; 512K <br>             BDB data cache size =&gt; 8388600<br>          InnoDB data cache size =&gt; 8M<br> -- Memory Pools -- <br>                read buffer size =&gt; 131072 <br>                sort buffer size =&gt; 65528 <br>                     table cache =&gt; 4 <br> -- Connections -- <br>             current connections =&gt; 3<br>                 max connections =&gt; 100</pre>
+<p><font face="Courier New, Courier, mono">function <b>Poll</b>($pollSecs=5)
+</font> </p>
+<p> Run in infinite loop, displaying the following information every
+$pollSecs. This will not work properly if output buffering is enabled.
+In the example below, $pollSecs=3:
+</p>
+<pre>Accumulating statistics...<br> Time   WS-CPU%   Hit%   Sess        Reads/s          Writes/s<br>11:08:30    0.7  56.56      1         0.0000            0.0000<br>11:08:33    1.8  56.56      2         0.0000            0.0000<br>11:08:36   11.1  56.55      3         2.5000            0.0000<br>11:08:39    9.8  56.55      2         3.1121            0.0000<br>11:08:42    2.8  56.55      1         0.0000            0.0000<br>11:08:45    7.4  56.55      2         0.0000            1.5000<br></pre>
+<p><b>WS-CPU%</b> is the Web Server CPU load of the server that PHP is
+running from (eg. the database client), and not the database. The <b>Hit%</b>
+is the data cache hit ratio. <b>Sess</b> is the current number of
+sessions connected to the database. If you are using persistent
+connections, this should not change much. The <b>Reads/s</b> and <b>Writes/s</b>
+are synthetic values to give the viewer a rough guide to I/O, and are
+not to be taken literally. </p>
+<p><font face="Courier New, Courier, mono">function <b>SuspiciousSQL</b>($numsql=10)</font></p>
+<p>Returns SQL which have high average execution times as a HTML table.
+Each sql statement
+is hyperlinked to a new window which details the execution plan and the
+scripts that execute this SQL.
+</p>
+<p> The number of statements returned is determined by $numsql. Data is
+taken from the adodb_logsql table, where the sql statements are logged
+when
+$connection-&gt;LogSQL(true) is enabled. The adodb_logsql table is
+populated using <a href="docs-adodb.htm#logsql">$conn-&gt;LogSQL</a>.
+</p>
+<p>For Oracle, Ixora Suspicious SQL returns a list of SQL statements
+that are most cache intensive as a HTML table. These are data intensive
+SQL statements that could benefit most from tuning. </p>
+<p><font face="Courier New, Courier, mono">function <b>ExpensiveSQL</b>($numsql=10)</font></p>
+<p>Returns SQL whose total execution time (avg time * #executions) is
+high as a HTML table. Each sql statement
+is hyperlinked to a new window which details the execution plan and the
+scripts that execute this SQL.
+</p>
+<p> The number of statements returned is determined by $numsql. Data is
+taken from the adodb_logsql table, where the sql statements are logged
+when
+$connection-&gt;LogSQL(true) is enabled. The adodb_logsql table is
+populated using <a href="docs-adodb.htm#logsql">$conn-&gt;LogSQL</a>.
+</p>
+<p>For Oracle, Ixora Expensive SQL returns a list of SQL statements
+that are taking the most CPU load when run.
+</p>
+<p><font face="Courier New, Courier, mono">function <b>InvalidSQL</b>($numsql=10)</font></p>
+<p>Returns a list of invalid SQL as an HTML table.
+</p>
+<p>Data is taken from the adodb_logsql table, where the sql statements
+are logged when
+$connection-&gt;LogSQL(true) is enabled.
+</p>
+<p><font face="Courier New, Courier, mono">function <b>Tables</b>($orderby=1)</font></p>
+<p>Returns information on all tables in a database, with the first two
+fields containing the table name and table size, the remaining fields
+depend on the database driver. If $orderby is set to 1, it will sort by
+name. If $orderby is set to 2, then it will sort by table size. Some
+database drivers (mssql and mysql) will ignore the $orderby clause. For
+postgresql, the information is up-to-date since the last <i>vacuum</i>.
+Not supported currently for db2.</p>
+<h3>Raw Functions</h3>
+<p>Raw functions return values without any formatting.</p>
+<p><font face="Courier New, Courier, mono">function <b>DBParameter</b>($paramname)</font></p>
+<p>Returns the value of a database parameter, such as
+$this-&gt;DBParameter("data cache size").</p>
+<p><font face="Courier New, Courier, mono">function <b>CPULoad</b>()</font></p>
+<p>Returns the CPU load of the database client (NOT THE SERVER) as a
+percentage. Only works for Linux and Windows. For Windows, WMI must be
+available.</p>
+<h3>Format of $settings Property</h3>
+<p> To create new database parameters, you need to understand
+$settings. The $settings data structure is an associative array. Each
+element of the array defines a database parameter. The key is the name
+of the database parameter. If no key is defined, then it is assumed to
+be a section break, and the value is the name of the section break. If
+this is too confusing, looking at the source code will help a lot!</p>
+<p> Each database parameter is itself an array consisting of the
+following elements:</p>
+<ol start="0">
+  <li> Category code, used to group related db parameters. If the
+category code is 'HIDE', then
+the database parameter is not shown when HTML() is called. <br>
+  </li>
+  <li> either
+    <ol type="a">
+      <li>sql string to retrieve value, eg. "select value from
+v\$parameter where name='db_block_size'", </li>
+      <li>array holding sql string and field to look for, e.g.
+array('show variables','table_cache'); optional 3rd parameter is the
+$rs-&gt;fields[$index] to use (otherwise $index=1), and optional 4th
+parameter is a constant to multiply the result with (typically 100 for
+percentage calculations),</li>
+      <li>a string prefixed by =, then a PHP method of the class is
+invoked, e.g. to invoke $this-&gt;GetIndexValue(), set this array
+element to '=GetIndexValue', <br>
+      </li>
+    </ol>
+  </li>
+  <li> Description of database parameter. If description begins with an
+=, then it is interpreted as a method call, just as in (1c) above,
+taking one parameter, the current value. E.g. '=GetIndexDescription'
+will invoke $this-&gt;GetIndexDescription($val). This is useful for
+generating tuning suggestions. For an example, see WarnCacheRatio().</li>
+</ol>
+<p>Example from MySQL, table_cache database parameter:</p>
+<pre>'table cache' =&gt; array('CACHE',            # category code<br>   array("show variables", 'table_cache'), # array (type 1b)<br>   'Number of tables to keep open'),       # description</pre>
+<h3>Example Health Check Output</h3>
+<p><a href="#db2">db2</a> <a href="#informix">informix</a> <a
+ href="#mysql">mysql</a> <a href="#mssql">mssql</a> <a href="#oci8">oci8</a>
+<a href="#postgres">postgres</a></p>
+<p><a name="db2"></a></p>
+<table bgcolor="white" border="1">
+  <tbody>
+    <tr>
+      <td colspan="3">
+      <h3>db2</h3>
+      </td>
+    </tr>
+    <tr>
+      <td><b>Parameter</b></td>
+      <td><b>Value</b></td>
+      <td><b>Description</b></td>
+    </tr>
+    <tr bgcolor="#f0f0f0">
+      <td colspan="3"><i>Ratios</i> &nbsp;</td>
+    </tr>
+    <tr bgcolor="#ffffff">
+      <td>data cache hit ratio</td>
+      <td>0 &nbsp; </td>
+      <td>&nbsp;</td>
+    </tr>
+    <tr bgcolor="#f0f0f0">
+      <td colspan="3"><i>Data Cache</i></td>
+    </tr>
+    <tr bgcolor="#ffffff">
+      <td>data cache buffers</td>
+      <td>250 &nbsp; </td>
+      <td>See <a
+ href="http://www7b.boulder.ibm.com/dmdd/library/techarticle/anshum/0107anshum.html#bufferpoolsize">tuning
+reference</a>.</td>
+    </tr>
+    <tr bgcolor="#ffffff">
+      <td>cache blocksize</td>
+      <td>4096 &nbsp; </td>
+      <td>&nbsp;</td>
+    </tr>
+    <tr bgcolor="#ffffff">
+      <td>data cache size</td>
+      <td>1000K &nbsp; </td>
+      <td>&nbsp;</td>
+    </tr>
+    <tr bgcolor="#f0f0f0">
+      <td colspan="3"><i>Connections</i></td>
+    </tr>
+    <tr bgcolor="#ffffff">
+      <td>current connections</td>
+      <td>2 &nbsp; </td>
+      <td>&nbsp;</td>
+    </tr>
+  </tbody>
+</table>
+<p>&nbsp;</p>
+<p><a name="informix"></a>
+<table bgcolor="white" border="1">
+  <tbody>
+    <tr>
+      <td colspan="3">
+      <h3>informix</h3>
+      </td>
+    </tr>
+    <tr>
+      <td><b>Parameter</b></td>
+      <td><b>Val
+ue</b></td>
+      <td><b>Description</b></td>
+    </tr>
+    <tr bgcolor="#f0f0f0">
+      <td colspan="3"><i>Ratios</i> &nbsp;</td>
+    </tr>
+    <tr>
+      <td>data cache hit
+ratio</td>
+      <td>95.89</td>
+      <td>&nbsp;</td>
+    </tr>
+    <tr bgcolor="#f0f0f0">
+      <td colspan="3"><i>IO</i> &nbsp;</td>
+    </tr>
+    <tr>
+      <td>data
+reads</td>
+      <td>1883884</td>
+      <td>Page reads</td>
+    </tr>
+    <tr>
+      <td>data writes</td>
+      <td>1716724</td>
+      <td>Page writes</td>
+    </tr>
+    <tr bgcolor="#f0f0f0">
+      <td colspan="3"><i>Connections</i>
+&nbsp;</td>
+    </tr>
+    <tr>
+      <td>current connections</td>
+      <td>263.0</td>
+      <td>Number of
+sessions</td>
+    </tr>
+  </tbody>
+</table>
+</p>
+<p>&nbsp;</p>
+<p><a name="mysql" id="mysql"></a></p>
+<table bgcolor="white" border="1">
+  <tbody>
+    <tr>
+      <td colspan="3">
+      <h3>mysql</h3>
+      </td>
+    </tr>
+    <tr>
+      <td><b>Parameter</b></td>
+      <td><b>Value</b></td>
+      <td><b>Description</b></td>
+    </tr>
+    <tr bgcolor="#f0f0f0">
+      <td colspan="3"><i>Ratios</i> &nbsp;</td>
+    </tr>
+    <tr>
+      <td>MyISAM cache hit ratio</td>
+      <td>56.5658301822</td>
+      <td><font color="red"><b>Cache ratio should be at least 90%</b></font></td>
+    </tr>
+    <tr>
+      <td>InnoDB cache hit ratio</td>
+      <td>0</td>
+      <td><font color="red"><b>Cache ratio should be at least 90%</b></font></td>
+    </tr>
+    <tr>
+      <td>sql cache hit ratio</td>
+      <td>0</td>
+      <td>&nbsp;</td>
+    </tr>
+    <tr bgcolor="#f0f0f0">
+      <td colspan="3"><i>IO</i> &nbsp;</td>
+    </tr>
+    <tr>
+      <td>data reads</td>
+      <td>2622</td>
+      <td>Number of selects (Key_reads is not accurate)</td>
+    </tr>
+    <tr>
+      <td>data writes</td>
+      <td>2415.5</td>
+      <td>Number of inserts/updates/deletes * coef (Key_writes is not
+accurate)</td>
+    </tr>
+    <tr bgcolor="#f0f0f0">
+      <td colspan="3"><i>Data Cache</i> &nbsp;</td>
+    </tr>
+    <tr>
+      <td>MyISAM data cache size</td>
+      <td>512K</td>
+      <td>&nbsp;</td>
+    </tr>
+    <tr>
+      <td>BDB data cache size</td>
+      <td>8388600</td>
+      <td>&nbsp;</td>
+    </tr>
+    <tr>
+      <td>InnoDB data cache size</td>
+      <td>8M</td>
+      <td>&nbsp;</td>
+    </tr>
+    <tr bgcolor="#f0f0f0">
+      <td colspan="3"><i>Memory Pools</i> &nbsp;</td>
+    </tr>
+    <tr>
+      <td>read buffer size</td>
+      <td>131072</td>
+      <td>(per session)</td>
+    </tr>
+    <tr>
+      <td>sort buffer size</td>
+      <td>65528</td>
+      <td>Size of sort buffer (per session)</td>
+    </tr>
+    <tr>
+      <td>table cache</td>
+      <td>4</td>
+      <td>Number of tables to keep open</td>
+    </tr>
+    <tr bgcolor="#f0f0f0">
+      <td colspan="3"><i>Connections</i> &nbsp;</td>
+    </tr>
+    <tr>
+      <td>current connections</td>
+      <td>3</td>
+      <td>&nbsp;</td>
+    </tr>
+    <tr>
+      <td>max connections</td>
+      <td>100</td>
+      <td>&nbsp;</td>
+    </tr>
+  </tbody>
+</table>
+<p>&nbsp;</p>
+<p><a name="mssql" id="mssql"></a></p>
+<table bgcolor="white" border="1">
+  <tbody>
+    <tr>
+      <td colspan="3">
+      <h3>mssql</h3>
+      </td>
+    </tr>
+    <tr>
+      <td><b>Parameter</b></td>
+      <td><b>Value</b></td>
+      <td><b>Description</b></td>
+    </tr>
+    <tr bgcolor="#f0f0f0">
+      <td colspan="3"><i>Ratios</i> &nbsp;</td>
+    </tr>
+    <tr>
+      <td>data cache hit ratio</td>
+      <td>99.9999694824</td>
+      <td>&nbsp;</td>
+    </tr>
+    <tr>
+      <td>prepared sql hit ratio</td>
+      <td>99.7738579828</td>
+      <td>&nbsp;</td>
+    </tr>
+    <tr>
+      <td>adhoc sql hit ratio</td>
+      <td>98.4540169133</td>
+      <td>&nbsp;</td>
+    </tr>
+    <tr bgcolor="#f0f0f0">
+      <td colspan="3"><i>IO</i> &nbsp;</td>
+    </tr>
+    <tr>
+      <td>data reads</td>
+      <td>2858</td>
+      <td>&nbsp; </td>
+    </tr>
+    <tr>
+      <td>data writes</td>
+      <td>1438</td>
+      <td>&nbsp; </td>
+    </tr>
+    <tr bgcolor="#f0f0f0">
+      <td colspan="3"><i>Data Cache</i> &nbsp;</td>
+    </tr>
+    <tr>
+      <td>data cache size</td>
+      <td>4362</td>
+      <td>in K</td>
+    </tr>
+    <tr bgcolor="#f0f0f0">
+      <td colspan="3"><i>Connections</i> &nbsp;</td>
+    </tr>
+    <tr>
+      <td>current connections</td>
+      <td>14</td>
+      <td>&nbsp;</td>
+    </tr>
+    <tr>
+      <td>max connections</td>
+      <td>32767</td>
+      <td>&nbsp;</td>
+    </tr>
+  </tbody>
+</table>
+<p>&nbsp;</p>
+<p><a name="oci8" id="oci8"></a></p>
+<table bgcolor="white" border="1">
+  <tbody>
+    <tr>
+      <td colspan="3">
+      <h3>oci8</h3>
+      </td>
+    </tr>
+    <tr>
+      <td><b>Parameter</b></td>
+      <td><b>Value</b></td>
+      <td><b>Description</b></td>
+    </tr>
+    <tr bgcolor="#f0f0f0">
+      <td colspan="3"><i>Ratios</i> &nbsp;</td>
+    </tr>
+    <tr>
+      <td>data cache hit ratio</td>
+      <td>96.98</td>
+      <td>&nbsp;</td>
+    </tr>
+    <tr>
+      <td>sql cache hit ratio</td>
+      <td>99.96</td>
+      <td>&nbsp;</td>
+    </tr>
+    <tr bgcolor="#f0f0f0">
+      <td colspan="3"><i>IO</i> &nbsp;</td>
+    </tr>
+    <tr>
+      <td>data reads</td>
+      <td>842938</td>
+      <td>&nbsp; </td>
+    </tr>
+    <tr>
+      <td>data writes</td>
+      <td>16852</td>
+      <td>&nbsp; </td>
+    </tr>
+    <tr bgcolor="#f0f0f0">
+      <td colspan="3"><i>Data Cache</i> &nbsp;</td>
+    </tr>
+    <tr>
+      <td>data cache buffers</td>
+      <td>3072</td>
+      <td>Number of cache buffers</td>
+    </tr>
+    <tr>
+      <td>data cache blocksize</td>
+      <td>8192</td>
+      <td>&nbsp;</td>
+    </tr>
+    <tr>
+      <td>data cache size</td>
+      <td>48M</td>
+      <td>shared_pool_size</td>
+    </tr>
+    <tr bgcolor="#f0f0f0">
+      <td colspan="3"><i>Memory Pools</i> &nbsp;</td>
+    </tr>
+    <tr>
+      <td>java pool size</td>
+      <td>0</td>
+      <td>java_pool_size</td>
+    </tr>
+    <tr>
+      <td>sort buffer size</td>
+      <td>512K</td>
+      <td>sort_area_size (per query)</td>
+    </tr>
+    <tr>
+      <td>user session buffer size</td>
+      <td>8M</td>
+      <td>large_pool_size</td>
+    </tr>
+    <tr bgcolor="#f0f0f0">
+      <td colspan="3"><i>Connections</i> &nbsp;</td>
+    </tr>
+    <tr>
+      <td>current connections</td>
+      <td>1</td>
+      <td>&nbsp;</td>
+    </tr>
+    <tr>
+      <td>max connections</td>
+      <td>170</td>
+      <td>&nbsp;</td>
+    </tr>
+    <tr>
+      <td>data cache utilization ratio</td>
+      <td>88.46</td>
+      <td>Percentage of data cache actually in use</td>
+    </tr>
+    <tr>
+      <td>user cache utilization ratio</td>
+      <td>91.76</td>
+      <td>Percentage of user cache (large_pool) actually in use</td>
+    </tr>
+    <tr>
+      <td>rollback segments</td>
+      <td>11</td>
+      <td>&nbsp;</td>
+    </tr>
+    <tr bgcolor="#f0f0f0">
+      <td colspan="3"><i>Transactions</i> &nbsp;</td>
+    </tr>
+    <tr>
+      <td>peak transactions</td>
+      <td>24</td>
+      <td>Taken from high-water-mark</td>
+    </tr>
+    <tr>
+      <td>max transactions</td>
+      <td>187</td>
+      <td>max transactions / rollback segments &lt; 3.5 (or
+transactions_per_rollback_segment)</td>
+    </tr>
+    <tr bgcolor="#f0f0f0">
+      <td colspan="3"><i>Parameters</i> &nbsp;</td>
+    </tr>
+    <tr>
+      <td>cursor sharing</td>
+      <td>EXACT</td>
+      <td>Cursor reuse strategy. Recommended is FORCE (8i+) or SIMILAR
+(9i+). See <a
+ href="http://www.praetoriate.com/oracle_tips_cursor_sharing.htm">cursor_sharing</a>.</td>
+    </tr>
+    <tr>
+      <td>index cache cost</td>
+      <td>0</td>
+      <td>% of indexed data blocks expected in the cache. Recommended
+is 20-80. Default is 0. See <a
+ href="http://www.dba-oracle.com/oracle_tips_cbo_part1.htm">optimizer_index_caching</a>.</td>
+    </tr>
+    <tr>
+      <td>random page cost</td>
+      <td>100</td>
+      <td>Recommended is 10-50 for TP, and 50 for data warehouses.
+Default is 100. See <a
+ href="http://www.dba-oracle.com/oracle_tips_cost_adj.htm">optimizer_index_cost_adj</a>.
+      </td>
+    </tr>
+  </tbody>
+</table>
+<h3>Suspicious SQL</h3>
+<table bgcolor="white" border="1">
+  <tbody>
+    <tr>
+      <td><b>LOAD</b></td>
+      <td><b>EXECUTES</b></td>
+      <td><b>SQL_TEXT</b></td>
+    </tr>
+    <tr>
+      <td align="right"> .73%</td>
+      <td align="right">89</td>
+      <td>select u.name, o.name, t.spare1, t.pctfree$ from sys.obj$ o,
+sys.user$ u, sys.tab$ t where (bitand(t.trigflag, 1048576) = 1048576)
+and o.obj#=t.obj# and o.owner# = u.user# select i.obj#, i.flags,
+u.name, o.name from sys.obj$ o, sys.user$ u, sys.ind$ i where
+(bitand(i.flags, 256) = 256 or bitand(i.flags, 512) = 512) and
+(not((i.type# = 9) and bitand(i.flags,8) = 8)) and o.obj#=i.obj# and
+o.owner# = u.user# </td>
+    </tr>
+    <tr>
+      <td align="right"> .84%</td>
+      <td align="right">3</td>
+      <td>select /*+ RULE */ distinct tabs.table_name, tabs.owner ,
+partitioned, iot_type , TEMPORARY, table_type, table_type_owner from
+DBA_ALL_TABLES tabs where tabs.owner = :own </td>
+    </tr>
+    <tr>
+      <td align="right"> 3.95%</td>
+      <td align="right">6</td>
+      <td>SELECT round(count(1)*avg(buf.block_size)/1048576) FROM
+DBA_OBJECTS obj, V$BH bh, dba_segments seg, v$buffer_pool buf WHERE
+obj.object_id = bh.objd AND obj.owner != 'SYS' and obj.owner =
+seg.owner and obj.object_name = seg.segment_name and obj.object_type =
+seg.segment_type and seg.buffer_pool = buf.name and buf.name =
+'DEFAULT' </td>
+    </tr>
+    <tr>
+      <td align="right"> 4.50%</td>
+      <td align="right">6</td>
+      <td>SELECT round(count(1)*avg(tsp.block_size)/1048576) FROM
+DBA_OBJECTS obj, V$BH bh, dba_segments seg, dba_tablespaces tsp WHERE
+obj.object_id = bh.objd AND obj.owner != 'SYS' and obj.owner =
+seg.owner and obj.object_name = seg.segment_name and obj.object_type =
+seg.segment_type and seg.tablespace_name = tsp.tablespace_name </td>
+    </tr>
+    <tr>
+      <td align="right">57.34%</td>
+      <td align="right">9267</td>
+      <td>select t.schema, t.name, t.flags, q.name from
+system.aq$_queue_tables t, sys.aq$_queue_table_affinities aft,
+system.aq$_queues q where aft.table_objno = t.objno and
+aft.owner_instance = :1 and q.table_objno = t.objno and q.usage = 0 and
+bitand(t.flags, 4+16+32+64+128+256) = 0 for update of t.name,
+aft.table_objno skip locked </td>
+    </tr>
+  </tbody>
+</table>
+<h3>Expensive SQL</h3>
+<table bgcolor="white" border="1">
+  <tbody>
+    <tr>
+      <td><b>LOAD</b></td>
+      <td><b>EXECUTES</b></td>
+      <td><b>SQL_TEXT</b></td>
+    </tr>
+    <tr>
+      <td align="right"> 5.24%</td>
+      <td align="right">1</td>
+      <td>select round(sum(bytes)/1048576) from dba_segments </td>
+    </tr>
+    <tr>
+      <td align="right"> 6.89%</td>
+      <td align="right">6</td>
+      <td>SELECT round(count(1)*avg(buf.block_size)/1048576) FROM
+DBA_OBJECTS obj, V$BH bh, dba_segments seg, v$buffer_pool buf WHERE
+obj.object_id = bh.objd AND obj.owner != 'SYS' and obj.owner =
+seg.owner and obj.object_name = seg.segment_name and obj.object_type =
+seg.segment_type and seg.buffer_pool = buf.name and buf.name =
+'DEFAULT' </td>
+    </tr>
+    <tr>
+      <td align="right"> 7.85%</td>
+      <td align="right">6</td>
+      <td>SELECT round(count(1)*avg(tsp.block_size)/1048576) FROM
+DBA_OBJECTS obj, V$BH bh, dba_segments seg, dba_tablespaces tsp WHERE
+obj.object_id = bh.objd AND obj.owner != 'SYS' and obj.owner =
+seg.owner and obj.object_name = seg.segment_name and obj.object_type =
+seg.segment_type and seg.tablespace_name = tsp.tablespace_name </td>
+    </tr>
+    <tr>
+      <td align="right">33.69%</td>
+      <td align="right">89</td>
+      <td>select u.name, o.name, t.spare1, t.pctfree$ from sys.obj$ o,
+sys.user$ u, sys.tab$ t where (bitand(t.trigflag, 1048576) = 1048576)
+and o.obj#=t.obj# and o.owner# = u.user# </td>
+    </tr>
+    <tr>
+      <td align="right">36.44%</td>
+      <td align="right">89</td>
+      <td>select i.obj#, i.flags, u.name, o.name from sys.obj$ o,
+sys.user$ u, sys.ind$ i where (bitand(i.flags, 256) = 256 or
+bitand(i.flags, 512) = 512) and (not((i.type# = 9) and
+bitand(i.flags,8) = 8)) and o.obj#=i.obj# and o.owner# = u.user# </td>
+    </tr>
+  </tbody>
+</table>
+<p><a name="postgres" id="postgres"></a></p>
+<table bgcolor="white" border="1">
+  <tbody>
+    <tr>
+      <td colspan="3">
+      <h3>postgres7</h3>
+      </td>
+    </tr>
+    <tr>
+      <td><b>Parameter</b></td>
+      <td><b>Value</b></td>
+      <td><b>Description</b></td>
+    </tr>
+    <tr bgcolor="#f0f0f0">
+      <td colspan="3"><i>Ratios</i> &nbsp;</td>
+    </tr>
+    <tr>
+      <td>statistics collector</td>
+      <td>FALSE</td>
+      <td>Must be set to TRUE to enable hit ratio statistics (<i>stats_start_collector</i>,<i>stats_row_level</i>
+and <i>stats_block_level</i> must be set to true in postgresql.conf)</td>
+    </tr>
+    <tr>
+      <td>data cache hit ratio</td>
+      <td>99.9666031916603</td>
+      <td>&nbsp;</td>
+    </tr>
+    <tr bgcolor="#f0f0f0">
+      <td colspan="3"><i>IO</i> &nbsp;</td>
+    </tr>
+    <tr>
+      <td>data reads</td>
+      <td>15</td>
+      <td>&nbsp; </td>
+    </tr>
+    <tr>
+      <td>data writes</td>
+      <td>0.000000000000000000</td>
+      <td>Count of inserts/updates/deletes * coef</td>
+    </tr>
+    <tr bgcolor="#f0f0f0">
+      <td colspan="3"><i>Data Cache</i> &nbsp;</td>
+    </tr>
+    <tr>
+      <td>data cache buffers</td>
+      <td>1280</td>
+      <td>Number of cache buffers. <a
+ href="http://www.varlena.com/GeneralBits/Tidbits/perf.html#basic">Tuning</a></td>
+    </tr>
+    <tr>
+      <td>cache blocksize</td>
+      <td>8192</td>
+      <td>(estimate)</td>
+    </tr>
+    <tr>
+      <td>data cache size</td>
+      <td>10M</td>
+      <td>&nbsp;</td>
+    </tr>
+    <tr>
+      <td>operating system cache size</td>
+      <td>80000K</td>
+      <td>(effective cache size)</td>
+    </tr>
+    <tr bgcolor="#f0f0f0">
+      <td colspan="3"><i>Memory Pools</i> &nbsp;</td>
+    </tr>
+    <tr>
+      <td>sort buffer size</td>
+      <td>1M</td>
+      <td>Size of sort buffer (per query)</td>
+    </tr>
+    <tr bgcolor="#f0f0f0">
+      <td colspan="3"><i>Connections</i> &nbsp;</td>
+    </tr>
+    <tr>
+      <td>current connections</td>
+      <td>13</td>
+      <td>&nbsp;</td>
+    </tr>
+    <tr>
+      <td>max connections</td>
+      <td>32</td>
+      <td>&nbsp;</td>
+    </tr>
+    <tr bgcolor="#f0f0f0">
+      <td colspan="3"><i>Parameters</i> &nbsp;</td>
+    </tr>
+    <tr>
+      <td>rollback buffers</td>
+      <td>8</td>
+      <td>WAL buffers</td>
+    </tr>
+    <tr>
+      <td>random page cost</td>
+      <td>4</td>
+      <td>Cost of doing a seek (default=4). See <a
+ href="http://www.varlena.com/GeneralBits/Tidbits/perf.html#less">random_page_cost</a></td>
+    </tr>
+  </tbody>
+</table>
+</body>
+</html>
Index: /Dev/trunk/rdfapi/util/adodb/docs/docs-session.htm
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/docs/docs-session.htm	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/docs/docs-session.htm	(revision 12)
@@ -0,0 +1,336 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
+<html>
+<head>
+  <title>ADODB Session Management Manual</title>
+  <meta http-equiv="Content-Type"
+ content="text/html; charset=iso-8859-1">
+  <style type="text/css">
+body, td {
+/*font-family: Arial, Helvetica, sans-serif;*/
+font-size: 11pt;
+}
+pre {
+font-size: 9pt;
+background-color: #EEEEEE; padding: .5em; margin: 0px;
+}
+.toplink {
+font-size: 8pt;
+}
+  </style>
+</head>
+<body style="background-color: rgb(255, 255, 255);">
+<h1>ADODB Session 2 Management Manual</h1>
+<p>
+V4.94 23 Jan 2007 (c) 2000-2007 John Lim (jlim#natsoft.com.my)
+</p>
+<p> <font size="1">This software is dual licensed using BSD-Style and
+LGPL. This means you can use it in compiled proprietary and commercial
+products. </font>
+<p>Useful ADOdb links: <a href="http://adodb.sourceforge.net/#download">Download</a>
+&nbsp; <a href="http://adodb.sourceforge.net/#docs">Other Docs</a>
+</p>
+<h2>Introduction</h2>
+<p> This document discusses the newer session handler adodb-session2.php. If
+  you have used the older adodb-session.php, then be forewarned that you will
+  need to alter your session table format. Otherwise everything is <a href="#compat">backward
+  compatible</a>.
+  Here are the <a href="docs-session.old.htm">older
+    docs</a> for
+  adodb-session.php.</p>
+<h2>Why Session Variables in a Database? </h2>
+<p>We store state information specific to a user or web
+    client in session variables. These session variables persist throughout a
+session, as the user moves from page to page. </p>
+<p>To use session variables, call session_start() at the beginning of
+your web page, before your HTTP headers are sent. Then for every
+variable you want to keep alive for the duration of the session, call
+session_register($variable_name). By default, the session handler will
+keep track of the session by using a cookie. You can save objects or
+arrays in session variables also.
+</p>
+<p>The default method of storing sessions is to store it in a file.
+However if you have special needs such as you:
+</p>
+<ul>
+  <li>Have multiple web servers that need to share session info</li>
+  <li>Need to do special processing of each session</li>
+  <li>Require notification when a session expires</li>
+</ul>
+<p>The ADOdb session handler provides you with the above
+additional capabilities by storing the session information as records
+in a database table that can be shared across multiple servers. </p>
+<p>These records will be garbage collected based on the php.ini [session] timeout settings. 
+You can register a notification function to notify you when the record has expired and 
+is about to be freed by the garbage collector.</p>
+<p>An alternative to using a database backed session handler is to use <a href="http://www.danga.com/memcached/">memcached</a>.
+  This is a distributed memory based caching system suitable for storing session
+  information.
+  </p>
+<h2> The Improved Session Handler</h2>
+<p>In ADOdb 4.91, we added a new session handler, in adodb-session2.php.
+It features the following improvements:
+<ul>
+<li>Fully supports server farms using a new database table format. The
+  previous version used the web server time for timestamps, which can cause problems
+  on a system with multiple web servers with possibly inconsistent
+  times. The new version uses the database server time instead for all timestamps.
+<li>The older database table format is obsolete. The database table must be modified
+  to support storage of the database server time mentioned above. Also the field
+  named DATA has been changed to SESSDATA. In some databases, DATA is a reserved
+  word.
+<li>The functions dataFieldName() and syncSeconds() is obsolete.
+</ul>
+
+<p>Usage is 
+
+<pre>
+include_once("adodb/session/adodb-session2.php");
+ADOdb_Session::config($driver, $host, $user, $password, $database,$options=false);
+session_start();
+
+<font
+ color="#004040">#<br># Test session vars, the following should increment on refresh<br>#<br>$_SESSION['AVAR'] += 1;<br>print "&lt;p&gt;\$_SESSION['AVAR']={$_SESSION['AVAR']}&lt;/p&gt;";</font>
+</pre>
+
+<p>When the session is created in session_start( ), the global variable $<b>ADODB_SESS_CONN</b> holds
+the connection object.
+<p>The default name of the table is sessions2. If you want to override it:
+  
+<pre>
+include_once("adodb/session/adodb-session2.php");
+$options['table'] = 'mytablename';
+ADOdb_Session::config($driver, $host, $user, $password, $database,$options);
+session_start();
+</pre>
+
+
+<h3>ADOdb Session Handler Features</h3>
+<ul>
+  <li>Ability to define a notification function that is called when a
+session expires. Typically
+used to detect session logout and release global resources. </li>
+  <li>Optimization of database writes. We crc32 the session data and
+only perform an update
+to the session data if there is a data change. </li>
+  <li>Support for large amounts of session data with CLOBs (see
+adodb-session-clob2.php). Useful
+for Oracle. </li>
+  <li>Support for encrypted session data, see
+adodb-cryptsession2.php. Enabling encryption is simply a matter of
+including adodb-cryptsession2.php instead of adodb-session2.php. </li>
+</ul>
+<h3>Session Handler Files </h3>
+<p>There are 3 session management files that you can use:
+</p>
+<pre>adodb-session2.php        : The default<br>adodb-cryptsession2.php   : Use this if you want to store encrypted session data in the database<br>adodb-session-clob2.php   : Use this if you are storing DATA in clobs and you are NOT using oci8 driver</pre>
+<h2><strong>Usage Examples</strong></h2>
+<p>To force non-persistent connections, call <font color="#004040"><b>Persist</b></font>() first before session_start():
+
+ 
+<pre>
+ <font color="#004040">
+include_once("adodb/session/adodb-session2.php");
+$driver = 'mysql'; $host = 'localhost'; $user = 'auser'; $pwd = 'secret'; $database = 'sessiondb';
+ADOdb_Session::config($driver, $host, $user, $password, $database,$options=false);<b><br>ADOdb_session::Persist($connectMode=false);</b>
+session_start();<br> </font>
+</pre>
+<p> The parameter to the Persist( ) method sets the connection mode. You can
+  pass the following:</p>
+<table width="50%" border="1">
+  <tr>
+    <td><b>$connectMode</b></td>
+    <td><b>Connection Method</b></td>
+  </tr>
+  <tr>
+    <td>true</td>
+    <td><p>PConnect( )</p></td>
+  </tr>
+  <tr>
+    <td>false</td>
+    <td>Connect( )</td>
+  </tr>
+  <tr>
+    <td>'N'</td>
+    <td>NConnect( )</td>
+  </tr>
+  <tr>
+    <td>'P'</td>
+    <td>PConnect( )</td>
+  </tr>
+  <tr>
+    <td>'C'</td>
+    <td>Connect( )</td>
+  </tr>
+</table>
+<p>To use a encrypted sessions, simply replace the file adodb-session2.php:</p>
+ <pre> <font
+ color="#004040"><b><br>include('adodb/session/adodb-cryptsession2.php');</b><br>$driver = 'mysql'; $host = 'localhost'; $user = 'auser'; $pwd = 'secret'; $database = 'sessiondb';
+ADOdb_Session::config($driver, $host, $user, $password, $database,$options=false);<b><br>adodb_sess_open(false,false,$connectMode=false);</b>
+session_start();<br></font></pre>
+ <p>And the same technique for adodb-session-clob2.php:</p>
+ <pre>  <font
+ color="#004040"><br><b>include('adodb/session/adodb-session2-clob2.php');</b><br>$driver = 'oci8'; $host = 'localhost'; $user = 'auser'; $pwd = 'secret'; $database = 'sessiondb';
+ADOdb_Session::config($driver, $host, $user, $password, $database,$options=false);<b><br>adodb_sess_open(false,false,$connectMode=false);</b>
+session_start();</font></pre>
+ <h2>Installation</h2>
+<p>1. Create this table in your database. Here is the MySQL version:
+<pre> <a
+ name="sessiontab"></a> <font color="#004040">
+CREATE TABLE sessions2(
+	  sesskey VARCHAR( 64 ) NOT NULL DEFAULT '',
+  	  expiry DATETIME NOT NULL ,
+	  expireref VARCHAR( 250 ) DEFAULT '',
+	  created DATETIME NOT NULL ,
+	  modified DATETIME NOT NULL ,
+	  sessdata LONGTEXT DEFAULT '',
+	  PRIMARY KEY ( sesskey ) ,
+	  INDEX sess2_expiry( expiry ),
+	  INDEX sess2_expireref( expireref )
+)</font></pre>
+
+ <p> For PostgreSQL, use:
+ <pre>CREATE TABLE sessions2(
+ sesskey VARCHAR( 64 ) NOT NULL DEFAULT '',
+ expiry TIMESTAMP NOT NULL ,
+ expireref VARCHAR( 250 ) DEFAULT '',
+ created TIMESTAMP NOT NULL ,
+ modified TIMESTAMP NOT NULL ,
+ sessdata TEXT DEFAULT '',
+ PRIMARY KEY ( sesskey )
+ );
+</pre>
+ <pre>create INDEX sess2_expiry on sessions2( expiry );
+create INDEX sess2_expireref on sessions2 ( expireref );</pre>
+ <p>Here is the Oracle definition, which uses a CLOB for the SESSDATA field:
+ <pre>
+  <font
+ color="#004040">CREATE TABLE SESSIONS2<br>(<br>   SESSKEY    VARCHAR2(48 BYTE)                  NOT NULL,<br>   EXPIRY     DATE                               NOT NULL,<br>   EXPIREREF  VARCHAR2(200 BYTE),<br>   CREATED    DATE                               NOT NULL,<br>   MODIFIED   DATE                               NOT NULL,<br>   SESSDATA   CLOB,<br>  PRIMARY KEY(SESSKEY)<br>);
+<br>CREATE INDEX SESS2_EXPIRY ON SESSIONS2(EXPIRY);
+CREATE INDEX SESS2_EXPIREREF ON SESSIONS2(EXPIREREF);</font></pre>
+<p> We need to use a CLOB here because for text greater than 4000 bytes long,
+  Oracle requires you to use the CLOB data type. If you are using the oci8 driver,
+  ADOdb will automatically enable CLOB handling. So you can use either adodb-session2.php
+  or adodb-session-clob2.php - in this case it doesn't matter. <br>    
+<h2>Notifications</h2>
+<p>You can receive notification when your session is cleaned up by the session garbage collector or
+when you call session_destroy().
+<p>PHP's session extension will automatically run a special garbage collection function based on
+your php.ini session.cookie_lifetime and session.gc_probability settings. This will in turn call
+adodb's garbage collection function, which can be setup to do notification.
+<p>
+<pre>
+	PHP Session --> ADOdb Session  --> Find all recs  --> Send          --> Delete queued
+	GC Function     GC Function        to be deleted      notification      records
+	executed at     called by                             for all recs
+	random time     Session Extension                     queued for deletion
+</pre>
+<p>When a session is created, we need to store a value in the session record (in the EXPIREREF field), typically 
+the userid of the session. Later when the session has expired,  just before the record is deleted,
+we reload the EXPIREREF field and call the notification function with the value of EXPIREREF, which 
+is the userid of the person being logged off.
+<p>ADOdb uses a global variable $ADODB_SESSION_EXPIRE_NOTIFY that you must predefine before session
+start to store the notification configuration. 
+$ADODB_SESSION_EXPIRE_NOTIFY is an array with 2 elements, the
+first being the name of the session variable you would like to store in
+the EXPIREREF field, and the 2nd is the notification function's name. </p>
+<p>For example, suppose we want to be notified when a user's session has expired,
+based on the userid. When the user logs in, we store the id in the global session variable
+$USERID. The function name is 'NotifyFn'. 
+<p>
+So we define (before session_start() is called): </p>
+<pre> <font color="#004040">
+	$ADODB_SESSION_EXPIRE_NOTIFY = array('USERID','NotifyFn');
+</font></pre>
+And when the NotifyFn is called (when the session expires), the
+$USERID is passed in as the first parameter, eg. NotifyFn($userid, $sesskey). The
+session key (which is the primary key of the record in the sessions
+table) is the 2nd parameter.
+<p> Here is an example of a Notification function that deletes some
+records in the database and temporary files: </p>
+<pre><font color="#004040">
+	function NotifyFn($expireref, $sesskey)
+	{
+		global $ADODB_SESS_CONN; # the session connection object
+		$user = $ADODB_SESS_CONN-&gt;qstr($expireref);
+		
+		$ADODB_SESS_CONN-&gt;Execute("delete from shopping_cart where user=$user");          
+		system("rm /work/tmpfiles/$expireref/*");
+	}</font>  
+			  </pre>
+<p> NOTE 1: If you have register_globals disabled in php.ini, then you
+will have to manually set the EXPIREREF. E.g. </p>
+<pre> <font color="#004040">
+$GLOBALS['USERID'] = GetUserID();
+$ADODB_SESSION_EXPIRE_NOTIFY = array('USERID','NotifyFn');</font>
+</pre>
+<p> NOTE 2: If you want to change the EXPIREREF after the session
+record has been created, you will need to modify any session variable
+to force a database record update.
+</p>
+<h3>Neat Notification Tricks</h3>
+<p><i>ExpireRef</i> normally holds the user id of the current session.
+</p>
+<p>1. You can then write a session monitor, scanning expireref to see
+who is currently logged on.
+</p>
+<p>2. If you delete the sessions record for a specific user, eg.
+</p>
+<pre>delete from sessions where expireref = '$USER'<br></pre>
+then the user is logged out. Useful for ejecting someone from a
+site.
+<p>3. You can scan the sessions table to ensure no user
+can be logged in twice. Useful for security reasons.
+</p>
+<h2>Compression/Encryption Schemes</h2>
+Since ADOdb 4.05, thanks to Ross Smith, multiple encryption and
+compression schemes are supported. Currently, supported are:
+<p>
+<pre>  MD5Crypt (crypt.inc.php)<br>  MCrypt<br>  Secure (Horde's emulation of MCrypt, if MCrypt module is not available.)<br>  GZip<br>  BZip2<br></pre>
+<p>These are stackable. E.g.
+<pre>ADODB_Session::filter(new ADODB_Compress_Bzip2());<br>ADODB_Session::filter(new ADODB_Encrypt_MD5());<br></pre>
+will compress and then encrypt the record in the database.
+<h2>Session Cookie Regeneration: adodb_session_regenerate_id()</h2>
+<p>Dynamically change the current session id with a newly generated one and update
+  database. Currently only works with cookies. Useful to improve security by
+  reducing the risk of session-hijacking. See this article on <a href=http://shiflett.org/articles/security-corner-feb2004>Session
+  Fixation</a> for more info 
+on the theory behind this feature. Usage:<pre>
+	include('path/to/adodb/session/adodb-session2.php');
+	
+	session_start();
+	# Approximately every 10 page loads, reset cookie for safety.
+	# This is extremely simplistic example, better 
+	# to regenerate only when the user logs in or changes
+	# user privilege levels.
+	if ((rand()%10) == 0) adodb_session_regenerate_id(); 
+</pre>
+<p>This function calls session_regenerate_id() internally or simulates it if the function does not exist.
+<h2>Vacuum/Optimize Database</h2>
+<p>During session garbage collection, if postgresql is detected,
+  ADOdb can be set to run VACUUM. If mysql is detected, then optimize database
+  could be called.You can turn this on or off using:</p>
+<pre>$turnOn = true; # or false
+ADODB_Session::optimize($turnOn);
+</pre>
+<p>The default  is optimization is disabled.</p>
+<h2><a name=compat></a>Backwards Compatability </h2>
+<p>The older method of connecting to ADOdb using global variables is still supported:</p>
+<pre> $ADODB_SESSION_DRIVER='mysql';
+ $ADODB_SESSION_CONNECT='localhost';
+ $ADODB_SESSION_USER ='root';
+ $ADODB_SESSION_PWD ='abc';
+ $ADODB_SESSION_DB ='phplens';
+ 
+ include('path/to/adodb/session/adodb-<strong>session2</strong>.php'); </pre>
+<p>In the above example, the only things you need to change in your code to upgrade
+  is </p>
+<ul>
+  <li>your session table format to the new one.</li>
+  <li>the include file from adodb-session.php to adodb-session2.php. </li>
+</ul>
+<h2>More Info</h2>
+<p>Also see the <a href="docs-adodb.htm">core ADOdb documentation</a>. And if
+  you are interested in the obsolete adodb-session.php, see <a href="docs-session.old.htm">old
+    session documentation</a>. </p>
+</body>
+</html>
Index: /Dev/trunk/rdfapi/util/adodb/docs/docs-session.old.htm
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/docs/docs-session.old.htm	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/docs/docs-session.old.htm	(revision 12)
@@ -0,0 +1,313 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
+<html>
+<head>
+  <title>ADODB Old Session Management Manual</title>
+  <meta http-equiv="Content-Type"
+ content="text/html; charset=iso-8859-1">
+  <style type="text/css">
+body, td {
+/*font-family: Arial, Helvetica, sans-serif;*/
+font-size: 11pt;
+}
+pre {
+font-size: 9pt;
+background-color: #EEEEEE; padding: .5em; margin: 0px;
+}
+.toplink {
+font-size: 8pt;
+}
+  </style>
+</head>
+<body style="background-color: rgb(255, 255, 255);">
+<h3>ADODB Session Management Manual</h3>
+<p>
+V4.94 23 Jan 2007 (c) 2000-2007 John Lim (jlim#natsoft.com.my)
+</p>
+<p> <font size="1">This software is dual licensed using BSD-Style and
+LGPL. This means you can use it in compiled proprietary and commercial
+products. </font>
+<p>Useful ADOdb links: <a href="http://adodb.sourceforge.net/#download">Download</a>
+&nbsp; <a href="http://adodb.sourceforge.net/#docs">Other Docs</a>
+</p>
+<h3>Introduction</h3>
+<p>This documentation discusses the old adodb-session.php. 
+Here is the <a href=docs-session.htm>new documentation</a> on the newer adodb-session2.php.
+<p> We store state information specific to a user or web client in
+session variables. These session variables persist throughout a
+session, as the user moves from page to page. </p>
+<p>To use session variables, call session_start() at the beginning of
+your web page, before your HTTP headers are sent. Then for every
+variable you want to keep alive for the duration of the session, call
+session_register($variable_name). By default, the session handler will
+keep track of the session by using a cookie. You can save objects or
+arrays in session variables also.
+</p>
+<p>The default method of storing sessions is to store it in a file.
+However if you have special needs such as you:
+</p>
+<ul>
+  <li>Have multiple web servers that need to share session info</li>
+  <li>Need to do special processing of each session</li>
+  <li>Require notification when a session expires</li>
+</ul>
+<p>The ADOdb session handler provides you with the above
+additional capabilities by storing the session information as records
+in a database table that can be shared across multiple servers. </p>
+<p>These records will be garbage collected based on the php.ini [session] timeout settings. 
+You can register a notification function to notify you when the record has expired and 
+is about to be freed by the garbage collector.</p>
+<p><b>Important Upgrade Notice:</b> Since ADOdb 4.05, the session files
+have been moved to its own folder, adodb/session. This is a rewrite
+of the session code by Ross Smith. The old session code is in
+adodb/session/old. </p>
+<h4>ADOdb Session Handler Features</h4>
+<ul>
+  <li>Ability to define a notification function that is called when a
+session expires. Typically
+used to detect session logout and release global resources. </li>
+  <li>Optimization of database writes. We crc32 the session data and
+only perform an update
+to the session data if there is a data change. </li>
+  <li>Support for large amounts of session data with CLOBs (see
+adodb-session-clob.php). Useful
+for Oracle. </li>
+  <li>Support for encrypted session data, see
+adodb-cryptsession.php. Enabling encryption is simply a matter of
+including adodb-cryptsession.php instead of adodb-session.php. </li>
+</ul>
+<h3>Setup</h3>
+<p>There are 3 session management files that you can use:
+</p>
+<pre>adodb-session.php        : The default<br>adodb-session-clob.php   : Use this if you are storing DATA in clobs<br>adodb-cryptsession.php   : Use this if you want to store encrypted session data in the database<br><br>
+</pre>
+<p><strong>Examples</strong>
+<p><pre>
+ <font
+ color="#004040">    include('adodb/adodb.inc.php');<br>    <br><b>    $ADODB_SESSION_DRIVER='mysql';<br>    $ADODB_SESSION_CONNECT='localhost';<br>    $ADODB_SESSION_USER ='scott';<br>    $ADODB_SESSION_PWD ='tiger';<br>    $ADODB_SESSION_DB ='sessiondb';</b><br>    <br>    <b>include('adodb/session/adodb-session.php');</b><br>    session_start();<br>    <br>    #<br>    # Test session vars, the following should increment on refresh<br>    #<br>    $_SESSION['AVAR'] += 1;<br>    print "&lt;p&gt;\$_SESSION['AVAR']={$_SESSION['AVAR']}&lt;/p&gt;";<br></font></pre>
+ 
+<p>To force non-persistent connections, call adodb_session_open() first before session_start():
+<p>
+ <pre>
+ <font color="#004040"><br>    include('adodb/adodb.inc.php');<br>    <br><b>    $ADODB_SESSION_DRIVER='mysql';<br>    $ADODB_SESSION_CONNECT='localhost';<br>    $ADODB_SESSION_USER ='scott';<br>    $ADODB_SESSION_PWD ='tiger';<br>    $ADODB_SESSION_DB ='sessiondb';</b><br>    <br>    <b>include('adodb/session/adodb-session.php');<br>    adodb_sess_open(false,false,false);</b><br>    session_start();<br> </font>
+ </pre>
+<p> The 3rd parameter to adodb_sess_open($path, $sessname, $connectMode)  sets the connection method. You can pass in the following:</p>
+<table width="50%" border="1">
+  <tr>
+    <td><b>$connectMode</b></td>
+    <td><b>Connection Method</b></td>
+  </tr>
+  <tr>
+    <td>true</td>
+    <td><p>PConnect( )</p></td>
+  </tr>
+  <tr>
+    <td>false</td>
+    <td>Connect( )</td>
+  </tr>
+  <tr>
+    <td>'N'</td>
+    <td>NConnect( )</td>
+  </tr>
+  <tr>
+    <td>'P'</td>
+    <td>PConnect( )</td>
+  </tr>
+  <tr>
+    <td>'C'</td>
+    <td>Connect( )</td>
+  </tr>
+</table>
+<p>To use a encrypted sessions, simply replace the file adodb-session.php:</p>
+ <pre> <font
+ color="#004040"><br>    include('adodb/adodb.inc.php');<br>    <br><b>    $ADODB_SESSION_DRIVER='mysql';<br>    $ADODB_SESSION_CONNECT='localhost';<br>    $ADODB_SESSION_USER ='scott';<br>    $ADODB_SESSION_PWD ='tiger';<br>    $ADODB_SESSION_DB ='sessiondb';<br>    <br>    include('adodb/session/adodb-cryptsession.php');</b><br>    session_start();</font><br>
+ </pre>
+ <p>And the same technique for adodb-session-clob.php:</p>
+ <pre>  <font
+ color="#004040"><br>    include('adodb/adodb.inc.php');<br>    <br><b>    $ADODB_SESSION_DRIVER='mysql';<br>    $ADODB_SESSION_CONNECT='localhost';<br>    $ADODB_SESSION_USER ='scott';<br>    $ADODB_SESSION_PWD ='tiger';<br>    $ADODB_SESSION_DB ='sessiondb';<br>    <br>    include('adodb/session/adodb-session-clob.php');</b><br>    session_start();</font>
+ </pre>
+ <p>An alternative way to set persistant or non-persistent connections is to call the following function before session_start() is called.
+ <pre>
+ 	ADODB_Session::persist('P'); # 'C' for non-persistent connections
+ </pre>
+ <h4>Installation</h4>
+<p>1. Create this table in your database (MySQL syntax):
+<p><pre> <a
+ name="sessiontab"></a> <font color="#004040">
+   create table sessions (
+       SESSKEY char(32) not null,
+       EXPIRY int(11) unsigned not null,
+       EXPIREREF varchar(64),
+	   DATA text not null,
+	   primary key (sesskey)
+	   );</font>
+ </pre>
+
+ <p>You may want to rename the 'data' field to 'session_data' as
+	'data' appears to be a reserved word for one or more of the following:
+	<ul>
+	<li>	ANSI SQL
+	<li>	IBM DB2
+	<li>	MS SQL Server
+	<li>	Postgres
+	<li>	SAP
+		</ul>
+<p>
+	If you do, then execute:
+<pre>
+		ADODB_Session::dataFieldName('session_data');
+</pre>
+ <p> For the adodb-session-clob.php version, create this:
+<p>  <pre>
+    <font
+ color="#004040"><br>    create table sessions (<br>       SESSKEY char(32) not null,<br>       EXPIRY int(11) unsigned not null,<br>       EXPIREREF varchar(64),<br>       DATA CLOB,<br>      primary key (sesskey)<br>  );</font>
+ </pre>
+ <p>2. Then define the following parameters. You can either modify this file, or define them before this file is included:
+ <pre>      <font
+ color="#004040"><br>    $ADODB_SESSION_DRIVER='database driver, eg. mysql or ibase';<br>    $ADODB_SESSION_CONNECT='server to connect to';<br>    $ADODB_SESSION_USER ='user';<br>    $ADODB_SESSION_PWD ='password';<br>    $ADODB_SESSION_DB ='database';<br>    $ADODB_SESSION_TBL = 'sessions'; # setting this is optional<br>	</font>
+ </pre><p>
+     When the session is created, $<b>ADODB_SESS_CONN</b> holds the connection object.<br>    <br>  3. Recommended is PHP 4.0.6 or later. There are documented session bugs in earlier versions of PHP.
+<h3>Notifications</h3>
+<p>You can receive notification when your session is cleaned up by the session garbage collector or
+when you call session_destroy().
+<p>PHP's session extension will automatically run a special garbage collection function based on
+your php.ini session.cookie_lifetime and session.gc_probability settings. This will in turn call
+adodb's garbage collection function, which can be setup to do notification.
+<p>
+<pre>
+	PHP Session --> ADOdb Session  --> Find all recs  --> Send          --> Delete queued
+	GC Function     GC Function        to be deleted      notification      records
+	executed at     called by                             for all recs
+	random time     Session Extension                     queued for deletion
+</pre>
+<p>When a session is created, we need to store a value in the session record (in the EXPIREREF field), typically 
+the userid of the session. Later when the session has expired,  just before the record is deleted,
+we reload the EXPIREREF field and call the notification function with the value of EXPIREREF, which 
+is the userid of the person being logged off.
+<p>ADOdb uses a global variable $ADODB_SESSION_EXPIRE_NOTIFY that you must predefine before session
+start to store the notification configuration. 
+$ADODB_SESSION_EXPIRE_NOTIFY is an array with 2 elements, the
+first being the name of the session variable you would like to store in
+the EXPIREREF field, and the 2nd is the notification function's name. </p>
+<p>For example, suppose we want to be notified when a user's session has expired,
+based on the userid. When the user logs in, we store the id in the global session variable
+$USERID. The function name is 'NotifyFn'. 
+<p>
+So we define (before session_start() is called): </p>
+<pre> <font color="#004040">
+	$ADODB_SESSION_EXPIRE_NOTIFY = array('USERID','NotifyFn');
+</font></pre>
+And when the NotifyFn is called (when the session expires), the
+$USERID is passed in as the first parameter, eg. NotifyFn($userid, $sesskey). The
+session key (which is the primary key of the record in the sessions
+table) is the 2nd parameter.
+<p> Here is an example of a Notification function that deletes some
+records in the database and temporary files: </p>
+<pre><font color="#004040">
+	function NotifyFn($expireref, $sesskey)
+	{
+		global $ADODB_SESS_CONN; # the session connection object
+		$user = $ADODB_SESS_CONN-&gt;qstr($expireref);
+		
+		$ADODB_SESS_CONN-&gt;Execute("delete from shopping_cart where user=$user");          
+		system("rm /work/tmpfiles/$expireref/*");
+	}</font>  
+			  </pre>
+<p> NOTE 1: If you have register_globals disabled in php.ini, then you
+will have to manually set the EXPIREREF. E.g. </p>
+<pre> <font color="#004040">
+$GLOBALS['USERID'] = GetUserID();
+$ADODB_SESSION_EXPIRE_NOTIFY = array('USERID','NotifyFn');</font>
+</pre>
+<p> NOTE 2: If you want to change the EXPIREREF after the session
+record has been created, you will need to modify any session variable
+to force a database record update.
+</p>
+<h4>Neat Notification Tricks</h4>
+<p><i>ExpireRef</i> normally holds the user id of the current session.
+</p>
+<p>1. You can then write a session monitor, scanning expireref to see
+who is currently logged on.
+</p>
+<p>2. If you delete the sessions record for a specific user, eg.
+</p>
+<pre>delete from sessions where expireref = '$USER'<br></pre>
+then the user is logged out. Useful for ejecting someone from a
+site.
+<p>3. You can scan the sessions table to ensure no user
+can be logged in twice. Useful for security reasons.
+</p>
+<h3>Using Oracle CLOBs</h3>
+<p>Suppose you are storing the DATA field in a CLOB:
+ <pre><font color="#004040">
+   CREATE TABLE sessions (
+       SESSKEY VARCHAR(32) NOT NULL,
+       EXPIRY NUMBER(16)  NOT NULL,
+       EXPIREREF VARCHAR(64),
+       DATA CLOB,
+      PRIMARY KEY (sesskey)
+  );</font>
+ </pre> 
+ <p>Then your PHP code could look like this:
+	 <pre>
+	ADODB_SESSION_DRIVER='oci8';
+	$ADODB_SESSION_CONNECT=$tnsname;
+	$ADODB_SESSION_USER ='scott';
+	$ADODB_SESSION_PWD = 'tiger';
+	$ADODB_SESSION_DB ='';
+	
+	$ADODB_SESSION_USE_LOBS = 'clob';
+	$ADODB_SESSION_TBL = 'sessions';
+	
+	$ADODB_SESS_DEBUG=0;
+	
+	include(ADODB_DIR.'/session/adodb-session.php');
+	
+	ADODB_Session::persist('P'); # use 'C' for non-persistent connects
+	
+	session_start();
+ </pre>
+ <p>Note that you can set persistance using ADODB_Session::persist('P').
+ 
+<h3>Compression/Encryption Schemes</h3>
+Since ADOdb 4.05, thanks to Ross Smith, multiple encryption and
+compression schemes are supported. Currently, supported are:
+<p>
+<pre>  MD5Crypt (crypt.inc.php)<br>  MCrypt<br>  Secure (Horde's emulation of MCrypt, if MCrypt module is not available.)<br>  GZip<br>  BZip2<br></pre>
+<p>These are stackable. E.g.
+<p><pre>ADODB_Session::filter(new ADODB_Compress_Bzip2());<br>ADODB_Session::filter(new ADODB_Encrypt_MD5());<br></pre>
+will compress and then encrypt the record in the database.
+<h3>adodb_session_regenerate_id()</h3>
+<p>Dynamically change the current session id with a newly generated one and update database. Currently only
+works with cookies. Useful to improve security by reducing the risk of session-hijacking.
+See this article on <a href=http://shiflett.org/articles/security-corner-feb2004>Session Fixation</a> for more info 
+on the theory behind this feature. Usage:
+<pre>
+	$ADODB_SESSION_DRIVER='mysql';
+	$ADODB_SESSION_CONNECT='localhost';
+	$ADODB_SESSION_USER ='root';
+	$ADODB_SESSION_PWD ='abc';
+	$ADODB_SESSION_DB ='phplens';
+	
+	include('path/to/adodb/session/adodb-session.php');
+	
+	session_start();
+	# Every 10 page loads, reset cookie for safety.
+	# This is extremely simplistic example, better 
+	# to regenerate only when the user logs in or changes
+	# user privilege levels.
+	if ((rand()%10) == 0) adodb_session_regenerate_id(); 
+</pre>
+<p>This function calls session_regenerate_id() internally or simulates it if the function does not exist.
+<h3>Vacuum/Optimize Database</h3>
+<p>During session garbage collection, if postgresql is detected,
+  ADOdb can be set to run VACUUM. If mysql is detected, then optimize database
+  could be called.You can turn this on or off using:</p>
+<pre>$turnOn = true; # or false
+ADODB_Session::optimize($turnOn);
+</pre>
+<p>The default for optimization is it is disabled.</p>
+<h2>More Info</h2>
+<p>Also see the <a href="docs-adodb.htm">core ADOdb documentation</a>.
+</p>
+</body>
+</html>
Index: /Dev/trunk/rdfapi/util/adodb/docs/old-changelog.htm
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/docs/old-changelog.htm	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/docs/old-changelog.htm	(revision 12)
@@ -0,0 +1,822 @@
+<html><title>Old Changelog: ADOdb</title><body>
+<h3>Old Changelog</h3>
+
+</p><p><b>3.92 22 Sept 2003</b> 
+</p><p>Added GetAssoc and CacheGetAssoc to connection object.
+</p><p>Removed TextMax and CharMax functions from adodb.inc.php. 
+</p><p>HasFailedTrans() returned false when trans failed. Fixed. 
+</p><p>Moved perf driver classes into adodb/perf/*.php. 
+</p><p>Misc improvements to performance monitoring, including UI(). 
+</p><p>RETVAL in mssql Parameter(), we do not append @ now. 
+</p><p>Added Param($name) to connection class, returns '?' or ":$name", for defining 
+  bind parameters portably. 
+</p><p>LogSQL traps affected_rows() and saves its value properly now. Also fixed oci8 
+  _stmt and _affectedrows() bugs. 
+</p><p>Session code timestamp check for oci8 works now. Formerly default NLS_DATE_FORMAT 
+  stripped off time portion. Thx to Tony Blair (tonanbarbarian#hotmail.com). Also 
+  added new $conn-&gt;datetime field to oci8, controls whether MetaType() returns 
+  'D' ($this-&gt;datetime==false) or 'T' ($this-&gt;datetime == true) for DATE type. 
+</p><p>Fixed bugs in adodb-cryptsession.inc.php and adodb-session-clob.inc.php. 
+</p><p>Fixed misc bugs in adodb_key_exists, GetInsertSQL() and GetUpdateSQL(). 
+</p><p>Tuned include_once handling to reduce file-system checking overhead. 
+</p><p><b>3.91 9 Sept 2003</b> 
+</p><p>Only released to InterAkt 
+</p><p>Added LogSQL() for sql logging and $ADODB_NEWCONNECTION to override factory 
+  for driver instantiation. 
+</p><p>Added IfNull($field,$ifNull) function, thx to johnwilk#juno.com 
+</p><p>Added portable substr support. 
+</p><p>Now rs2html() has new parameter, $echo. Set to false to return $html instead 
+  of echoing it. 
+</p><p><b>3.90 5 Sept 2003</b> 
+</p><p>First beta of performance monitoring released. 
+</p><p>MySQL supports MetaTable() masking. 
+</p><p>Fixed key_exists() bug in adodb-lib.inc.php 
+</p><p>Added sp_executesql Prepare() support to mssql. 
+</p><p>Added bind support to db2. 
+</p><p>Added swedish language file - Christian Tiberg" christian#commsoft.nu 
+</p><p>Bug in drop index for mssql data dict fixed. Thx to Gert-Rainer Bitterlich. 
+</p><p>Left join setting for oci8 was wrong. Thx to johnwilk#juno.com 
+</p><p><b>3.80 27 Aug 2003</b> 
+</p><p>Patch for PHP 4.3.3 cached recordset csv2rs() fread loop incompatibility. 
+</p><p>Added matching mask for MetaTables. Only for oci8, mssql and postgres currently. 
+</p><p>Rewrite of "oracle" driver connection code, merging with "oci8", by Gaetano. 
+</p><p>Added better debugging for Smart Transactions. 
+</p><p>Postgres DBTimeStamp() was wrongly using TO_DATE. Changed to TO_TIMESTAMP. 
+</p><p>ADODB_FETCH_CASE check pushed to ADONewConnection to allow people to define 
+  it after including adodb.inc.php. 
+</p><p>Added portugese (brazilian) to languages. Thx to "Levi Fukumori". 
+</p><p>Removed arg3 parameter from Execute/SelectLimit/Cache* functions. 
+</p><p>Execute() now accepts 2-d array as $inputarray. Also changed docs of fnExecute() 
+  to note change in sql query counting with 2-d arrays. 
+</p><p>Added MONEY to MetaType in PostgreSQL. 
+</p><p>Added more debugging output to CacheFlush(). 
+</p><p><b>3.72 9 Aug 2003</b> 
+</p><p>Added qmagic($str), which is a qstr($str) that auto-checks for magic quotes 
+  and does the right thing... 
+</p><p>Fixed CacheFlush() bug - Thx to martin#gmx.de 
+</p><p>Walt Boring contributed MetaForeignKeys for postgres7. 
+</p><p>_fetch() called _BlobDecode() wrongly in interbase. Fixed. 
+</p><p>adodb_time bug fixed with dates after 2038 fixed by Jason Pell. http://phplens.com/lens/lensforum/msgs.php?id=6980 
+</p><p><b>3.71 4 Aug 2003</b> 
+</p><p>The oci8 driver, MetaPrimaryKeys() did not check the owner correctly when $owner 
+  == false. 
+</p><p>Russian language file contributed by "Cyrill Malevanov" cyrill#malevanov.spb.ru. 
+</p><p>Spanish language file contributed by "Horacio Degiorgi" horaciod#codigophp.com. 
+</p><p>Error handling in oci8 bugfix - if there was an error in Execute(), then when 
+  calling ErrorNo() and/or ErrorMsg(), the 1st call would return the error, but 
+  the 2nd call would return no error. 
+</p><p>Error handling in odbc bugfix. ODBC would always return the last error, even 
+  if it happened 5 queries ago. Now we reset the errormsg to '' and errorno to 
+  0 everytime before CacheExecute() and Execute(). 
+</p><p><b>3.70 29 July 2003</b> 
+</p><p>Added new SQLite driver. Tested on PHP 4.3 and PHP 5. 
+</p><p>Added limited "sapdb" driver support - mainly date support. 
+</p><p>The oci8 driver did not identify NUMBER with no defined precision correctly. 
+</p><p>Added ADODB_FORCE_NULLS, if set, then PHP nulls are converted to SQL nulls 
+  in GetInsertSQL/GetUpdateSQL. 
+</p><p>DBDate() and DBTimeStamp() format for postgresql had problems. Fixed. 
+</p><p>Added tableoptions to ChangeTableSQL(). Thx to Mike Benoit. 
+</p><p>Added charset support to postgresql. Thx to Julian Tarkhanov. 
+</p><p>Changed OS check for MS-Windows to prevent confusion with darWIN (MacOS) 
+</p><p>Timestamp format for db2 was wrong. Changed to yyyy-mm-dd-hh.mm.ss.nnnnnn. 
+</p><p>adodb-cryptsession.php includes wrong. Fixed. 
+</p><p>Added MetaForeignKeys(). Supported by mssql, odbc_mssql and oci8. 
+</p><p>Fixed some oci8 MetaColumns/MetaPrimaryKeys bugs. Thx to Walt Boring. 
+</p><p>adodb_getcount() did not init qryRecs to 0. Missing "WHERE" clause checking 
+  in GetUpdateSQL fixed. Thx to Sebastiaan van Stijn. 
+</p><p>Added support for only 'VIEWS' and "TABLES" in MetaTables. From Walt Boring. 
+</p><p>Upgraded to adodb-xmlschema.inc.php 0.0.2. 
+</p><p>NConnect for mysql now returns value. Thx to Dennis Verspuij. 
+</p><p>ADODB_FETCH_BOTH support added to interbase/firebird. 
+</p><p>Czech language file contributed by Kamil Jakubovic jake#host.sk. 
+</p><p>PostgreSQL BlobDecode did not use _connectionID properly. Thx to Juraj Chlebec. 
+</p><p>Added some new initialization stuff for Informix. Thx to "Andrea Pinnisi" pinnisi#sysnet.it 
+</p><p>ADODB_ASSOC_CASE constant wrong in sybase _fetch(). Fixed. 
+</p><p><b>3.60 16 June 2003</b> 
+</p><p>We now SET CONCAT_NULL_YIELDS_NULL OFF for odbc_mssql driver to be compat with 
+  mssql driver. 
+</p><p>The property $emptyDate missing from connection class. Also changed 1903 to 
+  constant (TIMESTAMP_FIRST_YEAR=100). Thx to Sebastiaan van Stijn. 
+</p><p>ADOdb speedup optimization - we now return all arrays by reference. 
+</p><p>Now DBDate() and DBTimeStamp() now accepts the string 'null' as a parameter. 
+  Suggested by vincent. 
+</p><p>Added GetArray() to connection class. 
+</p><p>Added not_null check in informix metacolumns(). 
+</p><p>Connection parameters for postgresql did not work correctly when port was defined. 
+</p><p>DB2 is now a tested driver, making adodb 100% compatible. Extensive changes 
+  to odbc driver for DB2, including implementing serverinfo() and SQLDate(), switching 
+  to SQL_CUR_USE_ODBC as the cursor mode, and lastAffectedRows and SelectLimit() 
+  fixes. 
+</p><p>The odbc driver's FetchField() field names did not obey ADODB_ASSOC_CASE. Fixed. 
+</p><p>Some bugs in adodb_backtrace() fixed. 
+</p><p>Added "INT IDENTITY" type to adorecordset::MetaType() to support odbc_mssql 
+  properly. 
+</p><p>MetaColumns() for oci8, mssql, odbc revised to support scale. Also minor revisions 
+  to odbc MetaColumns() for vfp and db2 compat. 
+</p><p>Added unsigned support to mysql datadict class. Thx to iamsure. 
+</p><p>Infinite loop in mssql MoveNext() fixed when ADODB_FETCH_ASSOC used. Thx to 
+  Josh R, Night_Wulfe#hotmail.com. 
+</p><p>ChangeTableSQL contributed by Florian Buzin. 
+</p><p>The odbc_mssql driver now sets CONCAT_NULL_YIELDS_NULL OFF for compat with 
+  mssql driver. 
+</p>
+
+<p><b>3.50 19 May 2003</b></p>
+<p>Fixed mssql compat with FreeTDS. FreeTDS does not implement mssql_fetch_assoc(). 
+<p>Merged back connection and recordset code into adodb.inc.php. 
+<p>ADOdb sessions using oracle clobs contributed by achim.gosse#ddd.de. See adodb-session-clob.php. 
+<p>Added /s modifier to preg_match everywhere, which ensures that regex does not 
+  stop at /n. Thx Pao-Hsi Huang. 
+<p>Fixed error in metacolumns() for mssql. 
+<p>Added time format support for SQLDate. 
+<p>Image => B added to metatype. 
+<p>MetaType now checks empty($this->blobSize) instead of empty($this). 
+<p>Datadict has beta support for informix, sybase (mapped to mssql), db2 and generic 
+  (which is a fudge). 
+<p>BlobEncode for postgresql uses pg_escape_bytea, if available. Needed for compat 
+  with 7.3. 
+<p>Added $ADODB_LANG, to support multiple languages in MetaErrorMsg(). 
+<p>Datadict can now parse table definition as declarative text. 
+<p>For DataDict, oci8 autoincrement trigger missing semi-colon. Fixed. 
+<p>For DataDict, when REPLACE flag enabled, drop sequence in datadict for autoincrement 
+  field in postgres and oci8.s 
+<p>Postgresql defaults to template1 database if no database defined in connect/pconnect. 
+<p>We now clear _resultid in postgresql if query fails. 
+<p><b>3.40 19 May 2003</b></p>
+<p>Added insert_id for odbc_mssql. 
+<p>Modified postgresql UpdateBlobFile() because it did not work in safe mode. 
+<p>Now connection object is passed to raiseErrorFn as last parameter. Needed by 
+  StartTrans(). 
+<p>Added StartTrans() and CompleteTrans(). It is recommended that you do not modify 
+  transOff, but use the above functions. 
+<p>oci8po now obeys ADODB_ASSOC_CASE settings. 
+<p>Added virtualized error codes, using PEAR DB equivalents. Requires you to manually 
+  include adodb-error.inc.php yourself, with MetaError() and MetaErrorMsg($errno). 
+<p>GetRowAssoc for mysql and pgsql were flawed. Fix by Ross Smith. 
+<p>Added to datadict types I1, I2, I4 and I8. Changed datadict type 'T' to map 
+  to timestamp instead of datetime for postgresql. 
+<p>Error handling in ExecuteSQLArray(), adodb-datadict.inc.php did not work. 
+<p>We now auto-quote postgresql connection parameters when building connection 
+  string. 
+<p>Added session expiry notification. 
+<p>We now test with odbc mysql - made some changes to odbc recordset constructor. 
+<p>MetaColumns now special cases access and other databases for odbc. 
+<p><b>3.31 17 March 2003</b></p>
+<p>Added row checking for _fetch in postgres. 
+<p>Added Interval type to MetaType for postgres. 
+<p>Remapped postgres driver to call postgres7 driver internally. 
+<p>Adorecordset_array::getarray() did not return array when nRows >= 0. 
+<p>Postgresql: at times, no error message returned by pg_result_error() but error 
+  message returned in pg_last_error(). Recoded again. 
+<p>Interbase blob's now use chunking for updateblob. 
+<p>Move() did not set EOF correctly. Reported by Jorma T. 
+<p>We properly support mysql timestamp fields when we are creating mysql tables 
+  using the data-dict interface. 
+<p>Table regex includes backticks character now. 
+<p><b>3.30 3 March 2003</b></p>
+<p>Added $ADODB_EXTENSION and $ADODB_COMPAT_FETCH constant. 
+<p>Made blank1stItem configurable using syntax "value:text" in GetMenu/GetMenu2. 
+  Thx to Gabriel Birke. 
+<p>Previously ADOdb differed from the Microsoft standard because it did not define 
+  what to set $this->fields when EOF was reached. Now at EOF, ADOdb sets $this->fields 
+  to false for all databases, which is consist with Microsoft's implementation. 
+  Postgresql and mysql have always worked this way (in 3.11 and earlier). If you 
+  are experiencing compatibility problems (and you are not using postgresql nor 
+  mysql) on upgrading to 3.30, try setting the global variables $ADODB_COUNTRECS 
+  = true (which is the default) and $ADODB_FETCH_COMPAT = true (this is a new 
+  global variable). 
+<p>We now check both pg_result_error and pg_last_error as sometimes pg_result_error 
+  does not display anything. Iman Mayes 
+<p> We no longer check for magic quotes gpc in Quote(). 
+<p> Misc fixes for table creation in adodb-datadict.inc.php. Thx to iamsure. 
+<p> Time calculations use adodb_time library for all negative timestamps due to 
+  problems in Red Hat 7.3 or later. Formerly, only did this for Windows. 
+<p> In mssqlpo, we now check if $sql in _query is a string before we change || 
+  to +. This is to support prepared stmts. 
+<p> Move() and MoveLast() internals changed to support to support EOF and $this->fields 
+  change. 
+<p> Added ADODB_FETCH_BOTH support to mssql. Thx to Angel Fradejas afradejas#mediafusion.es 
+<p> We now check if link resource exists before we run mysql_escape_string in 
+  qstr(). 
+<p> Before we flock in csv code, we check that it is not a http url. 
+<p><b>3.20 17 Feb 2003</b></p>
+<p>Added new Data Dictionary classes for creating tables and indexes. Warning 
+  - this is very much alpha quality code. The API can still change. See adodb/tests/test-datadict.php 
+  for more info. 
+<p>We now ignore $ADODB_COUNTRECS for mysql, because PHP truncates incomplete 
+  recordsets when mysql_unbuffered_query() is called a second time. 
+<p>Now postgresql works correctly when $ADODB_COUNTRECS = false. 
+<p>Changed _adodb_getcount to properly support SELECT DISTINCT. 
+<p>Discovered that $ADODB_COUNTRECS=true has some problems with prepared queries 
+  - suspect PHP bug. 
+<p>Now GetOne and GetRow run in $ADODB_COUNTRECS=false mode for better performance. 
+<p>Added support for mysql_real_escape_string() and pg_escape_string() in qstr(). 
+<p>Added an intermediate variable for mysql _fetch() and MoveNext() to store fields, 
+  to prevent overwriting field array with boolean when mysql_fetch_array() returns 
+  false. 
+<p>Made arrays for getinsertsql and getupdatesql case-insensitive. Suggested by 
+  Tim Uckun" tim#diligence.com 
+<p><b>3.11 11 Feb 2003</b></p>
+<p>Added check for ADODB_NEVER_PERSIST constant in PConnect(). If defined, then 
+  PConnect() will actually call non-persistent Connect(). 
+<p>Modified interbase to properly work with Prepare(). 
+<p>Added $this->ibase_timefmt to allow you to change the date and time format. 
+<p>Added support for $input_array parameter in CacheFlush(). 
+<p>Added experimental support for dbx, which was then removed when i found that 
+  it was slower than using native calls. 
+<p>Added MetaPrimaryKeys for mssql and ibase/firebird. 
+<p>Added new $trim parameter to GetCol and CacheGetCol 
+<p>Uses updated adodb-time.inc.php 0.06. 
+<p><b>3.10 27 Jan 2003</b> 
+<p>Added adodb_date(), adodb_getdate(), adodb_mktime() and adodb-time.inc.php. 
+<p>For interbase, added code to handle unlimited number of bind parameters. From 
+  Daniel Hasan daniel#hasan.cl. 
+<p>Added BlobDecode and UpdateBlob for informix. Thx to Fernando Ortiz. 
+<p>Added constant ADODB_WINDOWS. If defined, means that running on Windows. 
+<p>Added constant ADODB_PHPVER which stores php version as a hex num. Removed 
+  $ADODB_PHPVER variable. 
+<p>Felho Bacsi reported a minor white-space regular expression problem in GetInsertSQL. 
+<p>Modified ADO to use variant to store _affectedRows 
+<p>Changed ibase to use base class Replace(). Modified base class Replace() to 
+  support ibase. 
+<p>Changed odbc to auto-detect when 0 records returned is wrong due to bad odbc 
+  drivers. 
+<p>Changed mssql to use datetimeconvert ini setting only when 4.30 or later (does 
+  not work in 4.23). 
+<p>ExecuteCursor($stmt, $cursorname, $params) now accepts a new $params array 
+  of additional bind parameters -- William Lovaton walovaton#yahoo.com.mx. 
+<p>Added support for sybase_unbuffered_query if ADODB_COUNTRECS == false. Thx 
+  to chuck may. 
+<p>Fixed FetchNextObj() bug. Thx to Jorma Tuomainen. 
+<p>We now use SCOPE_IDENTITY() instead of @@IDENTITY for mssql - thx to marchesini#eside.it 
+<p>Changed postgresql movenext logic to prevent illegal row number from being 
+  passed to pg_fetch_array(). 
+<p>Postgresql initrs bug found by "Bogdan RIPA" bripa#interakt.ro $f1 accidentally 
+  named $f 
+<p><b>3.00 6 Jan 2003</b> 
+<p>Fixed adodb-pear.inc.php syntax error. 
+<p>Improved _adodb_getcount() to use SELECT COUNT(*) FROM ($sql) for languages 
+  that accept it. 
+<p>Fixed _adodb_getcount() caching error. 
+<p>Added sql to retrive table and column info for odbc_mssql. 
+<p><strong>2.91 3 Jan 2003</strong> 
+<p>Revised PHP version checking to use $ADODB_PHPVER with legal values 0x4000, 
+  0x4050, 0x4200, 0x4300. 
+<p>Added support for bytea fields and oid blobs in postgres by allowing BlobDecode() 
+  to detect and convert non-oid fields. Also added BlobEncode to postgres when 
+  you want to encode oid blobs. 
+<p>Added blobEncodeType property for connections to inform phpLens what encoding 
+  method to use for blobs. 
+<p>Added BlobDecode() and BlobEncode() to base ADOConnection class. 
+<p>Added umask() to _gencachename() when creating directories. 
+<p>Added charPage for ado drivers, so you can set the code page. 
+<pre>
+$conn->charPage = CP_UTF8;
+$conn->Connect($dsn);
+</pre>
+<p>Modified _seek in mysql to check for num rows=0. 
+<p>Added to metatypes new informix types for IDS 9.30. Thx Fernando Ortiz. 
+<p>_maxrecordcount returned in CachePageExecute $rsreturn 
+<p>Fixed sybase cacheselectlimit( ) problems 
+<p>MetaColumns() max_length should use precision for types X and C for ms access. 
+  Fixed. 
+<p>Speedup of odbc non-SELECT sql statements. 
+<p>Added support in MetaColumns for Wide Char types for ODBC. We halve max_length 
+  if unicode/wide char. 
+<p>Added 'B' to types handled by GetUpdateSQL/GetInsertSQL. 
+<p>Fixed warning message in oci8 driver with $persist variable when using PConnect. 
+<p><b>2.90 11 Dec 2002</b> 
+<p>Mssql and mssqlpo and oci8po now support ADODB_ASSOC_CASE. 
+<p>Now MetaType() can accept a field object as the first parameter. 
+<p>New $arr = $db-&gt;ServerInfo( ) function. Returns $arr['description'] which 
+  is the string description, and $arr['version']. 
+<p>PostgreSQL and MSSQL speedups for insert/updates. 
+<p> Implemented new SetFetchMode() that removes the need to use $ADODB_FETCH_MODE. 
+  Each connection has independant fetchMode. 
+<p>ADODB_ASSOC_CASE now defaults to 2, use native defaults. This is because we 
+  would break backward compat for too many applications otherwise. 
+<p>Patched encrypted sessions to use replace() 
+<p>The qstr function supports quoting of nulls when escape character is \ 
+<p>Rewrote bits and pieces of session code to check for time synch and improve 
+  reliability. 
+<p>Added property ADOConnection::hasTransactions = true/false; 
+<p>Added CreateSequence and DropSequence functions 
+<p>Found misplaced MoveNext() in adodb-postgres.inc.php. Fixed. 
+<p>Sybase SelectLimit not reliable because 'set rowcount' not cached - fixed. 
+<p>Moved ADOConnection to adodb-connection.inc.php and ADORecordSet to adodb-recordset.inc.php. 
+  This allows us to use doxygen to generate documentation. Doxygen doesn't like 
+  the classes in the main adodb.inc.php file for some mysterious reason. 
+<p><b>2.50, 14 Nov 2002</b> 
+<p>Added transOff and transCnt properties for disabling (transOff = true) and 
+  tracking transaction status (transCnt>0). 
+<p>Added inputarray handling into _adodb_pageexecute_all_rows - "Ross Smith" RossSmith#bnw.com. 
+<p>Fixed postgresql inconsistencies in date handling. 
+<p>Added support for mssql_fetch_assoc. 
+<p>Fixed $ADODB_FETCH_MODE bug in odbc MetaTables() and MetaPrimaryKeys(). 
+<p>Accidentally declared UnixDate() twice, making adodb incompatible with php 
+  4.3.0. Fixed. 
+<p>Fixed pager problems with some databases that returned -1 for _currentRow on 
+  MoveLast() by switching to MoveNext() in adodb-lib.inc.php. 
+<p>Also fixed uninited $discard in adodb-lib.inc.php. 
+<p><b>2.43, 25 Oct 2002</b></p>
+Added ADODB_ASSOC_CASE constant to better support ibase and odbc field names. 
+<p>Added support for NConnect() for oracle OCINLogin. 
+<p>Fixed NumCols() bug. 
+<p>Changed session handler to use Replace() on write. 
+<p>Fixed oci8 SelectLimit aggregate function bug again. 
+<p>Rewrote pivoting code. 
+<p><b>2.42, 4 Oct 2002</b></p>
+<p>Fixed ibase_fetch() problem with nulls. Also interbase now does automatic blob 
+  decoding, and is backward compatible. Suggested by Heinz Hombergs heinz#hhombergs.de. 
+<p>Fixed postgresql MoveNext() problems when called repeatedly after EOF. Also 
+  suggested by Heinz Hombergs. 
+<p>PageExecute() does not rewrite queries if SELECT DISTINCT is used. Requested 
+  by hans#velum.net 
+<p>Added additional fixes to oci8 SelectLimit handling with aggregate functions 
+  - thx to Christian Bugge for reporting the problem. 
+<p><b>2.41, 2 Oct 2002</b></p>
+<p>Fixed ADODB_COUNTRECS bug in odbc. Thx to Joshua Zoshi jzoshi#hotmail.com. 
+<p>Increased buffers for adodb-csvlib.inc.php for extremely long sql from 8192 
+  to 32000. 
+<p>Revised pivottable.inc.php code. Added better support for aggregate fields. 
+<p>Fixed mysql text/blob types problem in MetaTypes base class - thx to horacio 
+  degiorgi. 
+<p>Added SQLDate($fmt,$date) function, which allows an sql date format string 
+  to be generated - useful for group by's. 
+<p>Fixed bug in oci8 SelectLimit when offset>100. 
+<p><b>2.40 4 Sept 2002</b></p>
+<p>Added new NLS_DATE_FORMAT property to oci8. Suggested by Laurent NAVARRO ln#altidev.com 
+<p>Now use bind parameters in oci8 selectlimit for better performance. 
+<p>Fixed interbase replaceQuote for dialect != 1. Thx to "BEGUIN Pierre-Henri 
+  - INFOCOB" phb#infocob.com. 
+<p>Added white-space check to QA. 
+<p>Changed unixtimestamp to support fractional seconds (we always round down/floor 
+  the seconds). Thanks to beezly#beezly.org.uk. 
+<p>Now you can set the trigger_error type your own user-defined type in adodb-errorhandler.inc.php. 
+  Suggested by Claudio Bustos clbustos#entelchile.net. 
+<p>Added recordset filters with rsfilter.inc.php. 
+<p>$conn->_rs2rs does not create a new recordset when it detects it is of type 
+  array. Some trickery there as there seems to be a bug in Zend Engine 
+<p>Added render_pagelinks to adodb-pager.inc.php. Code by "Pablo Costa" pablo#cbsp.com.br. 
+<p>MetaType() speedup in adodb.inc.php by using hashing instead of switch. Best 
+  performance if constant arrays are supported, as they are in PHP5. 
+<p>adodb-session.php now updates only the expiry date if the crc32 check indicates 
+  that the data has not been modified. 
+<p><b>2.31 20 Aug 2002</b></p>
+<p>Made changes to pivottable.inc.php due to daniel lucuzaeu's suggestions (we sum the pivottable column if desired).
+<p>Fixed ErrorNo() in postgres so it does not depend on _errorMsg property.
+<p>Robert Tuttle added support for oracle cursors. See ExecuteCursor().
+<p>Fixed Replace() so it works with mysql when updating record where data has not changed. Reported by
+Cal Evans (cal#calevans.com).
+<p><b>2.30 1 Aug 2002</b></p>
+<p>Added pivottable.inc.php. Thanks to daniel.lucazeau#ajornet.com for the original 
+  concept.
+<p>Added ADOConnection::outp($msg,$newline) to output error and debugging messages. Now 
+you can override this using the ADODB_OUTP constant and use your own output handler.
+<p>Changed == to === for 'null' comparison. Reported by ericquil#yahoo.com 
+<p>Fixed mssql SelectLimit( ) bug when distinct used.
+<p><b>2.30 1 Aug 2002</b></p>
+<p>New GetCol() and CacheGetCol() from ross#bnw.com that returns the first field as a 1 dim array.
+<p>We have an empty recordset, but RecordCount() could return -1. Fixed. Reported by  "Jonathan Polansky" jonathan#polansky.com.
+<p>We now check for session variable changes using strlen($sessval).crc32($sessval). 
+Formerly we only used crc32().
+<p>Informix SelectLimit() problem with $ADODB_COUNTRECS fixed.
+<p>Fixed informix SELECT FIRST x DISTINCT, and not SELECT DISTINCT FIRST x - reported by F Riosa
+<p>Now default adodb error handlers ignores error if @ used.
+<p>If you set $conn->autoRollback=true, we auto-rollback persistent connections for odbc, mysql, oci8, mssql. 
+Default for autoRollback is false. No need to do so for postgres. 
+As interbase requires a transaction id (what a flawed api), we don't do it for interbase.
+<p>Changed PageExecute() to use non-greedy preg_match when searching for "FROM" keyword.
+<p><b>2.20 9 July 2002</b></p>
+<p>Added CacheGetOne($secs2cache,$sql), CacheGetRow($secs2cache,$sql), CacheGetAll($secs2cache,$sql).
+<p>Added $conn->OffsetDate($dayFraction,$date=false) to generate sql that calcs 
+  date offsets. Useful for scheduling appointments.
+<p>Added connection properties: leftOuter, rightOuter that hold left and right 
+  outer join operators.
+<p>Added connection property: ansiOuter to indicate whether ansi outer joins supported.
+<p>New driver <i>mssqlpo</i>, the portable mssql driver, which converts string 
+  concat operator from || to +.
+<p>Fixed ms access bug - SelectLimit() did not support ties - fixed.
+<p>Karsten Kraus (Karsten.Kraus#web.de), contributed error-handling code to ADONewConnection. 
+  Unfortunately due to backward compat problems, had to rollback most of the changes.
+<p>Added new parameter to GetAssoc() to allow returning an array of key-value pairs, 
+ignoring any additional columns in the recordset. Off by default.
+<p>Corrected mssql $conn->sysDate to return only date using convert().
+<p>CacheExecute() improved debugging output.
+<p>Changed rs2html() so newlines are converted to BR tags. Also optimized rs2html() based
+on feedback by "Jerry Workman" jerry#mtncad.com.
+<p>Added support for Replace() with Interbase, using DELETE and INSERT.
+<p>Some minor optimizations (mostly removing & references when passing arrays).
+<p>Changed  GenID() to allows id's larger than the size of an integer.
+<p>Added force_session property to oci8 for better updateblob() support.
+<p>Fixed PageExecute() which did not work properly with sql containing GROUP BY.
+<p><b>2.12 12 June 2002</b></p>
+<p>Added toexport.inc.php to export recordsets in CSV and tab-delimited format.
+<p>CachePageExecute() does not work - fixed - thx John Huong.
+<p>Interbase aliases not set properly in FetchField() - fixed. Thx Stefan Goethals.
+<p>Added cache property to adodb pager class. The number of secs to cache recordsets.
+<p>SQL rewriting bug in pageexecute() due to skipping of newlines due to missing /s modifier. Fixed.
+<p>Max size of cached recordset due to a bug was 256000 bytes. Fixed.
+<p>Speedup of 1st invocation of CacheExecute() by tuning code.
+<p>We compare $rewritesql with $sql in pageexecute code in case of rewrite failure.
+<p><b>2.11 7 June 2002</b></p>
+<p>Fixed PageExecute() rewrite sql problem - COUNT(*) and ORDER BY don't go together with
+	mssql, access and postgres. Thx to Alexander Zhukov alex#unipack.ru
+<p>DB2 support for CHARACTER type added - thx John Huong huongch#bigfoot.com
+<p>For ado, $argProvider not properly checked. Fixed - kalimero#ngi.it
+<p>Added $conn->Replace() function for update with automatic insert if the record does not exist. 
+	Supported by all databases except interbase.
+<p><b>2.10 4 June 2002</b></p>
+<p>Added uniqueSort property to indicate mssql ORDER BY cols must be unique.
+<p>Optimized session handler by crc32 the data. We only write if session data has changed.
+<p>adodb_sess_read in adodb-session.php now returns ''correctly - thanks to Jorma Tuomainen, webmaster#wizactive.com
+<p>Mssql driver did not throw EXECUTE errors correctly because ErrorMsg() and ErrorNo() called in wrong order. 
+Pointed out by Alexios Fakos. Fixed.
+<p>Changed ado to use client cursors. This fixes BeginTran() problems with ado.
+<p>Added handling of timestamp type in ado.
+<p>Added to ado_mssql support for insert_id() and affected_rows().
+<p>Added support for mssql.datetimeconvert=0, available since php 4.2.0.
+<p>Made UnixDate() less strict, so that the time is ignored if present.
+<p>Changed quote() so that it checks for magic_quotes_gpc.
+<p>Changed maxblobsize for odbc to default to 64000.
+<p><b>2.00 13 May 2002</b></p>
+<p>Added drivers <i>informix72</i> for pre-7.3 versions, and <i>oci805</i> for 
+  oracle 8.0.5, and postgres64 for postgresql 6.4 and earlier. The postgres and postgres7 drivers
+  are now identical.
+<p>Interbase now partially supports ADODB_FETCH_BOTH, by defaulting to ASSOC mode.
+<p>Proper support for blobs in mssql. Also revised blob support code 
+is base class. Now UpdateBlobFile() calls UpdateBlob() for consistency.
+<p>Added support for changed odbc_fetch_into api in php 4.2.0 
+with $conn-&gt;_has_stupid_odbc_fetch_api_change.
+<p>Fixed spelling of tablock locking hint in GenID( ) for mssql. 
+<p>Added RowLock( ) to several databases, including oci8, informix, sybase, etc. 
+  Fixed where error in mssql RowLock().
+<p>Added sysDate and sysTimeStamp properties to most database drivers. These are the sql
+functions/constants for that database that return the current date and current timestamp, and 
+are useful for portable inserts and updates.
+<p>Support for RecordCount() caused date handling in sybase and mssql to break. 
+Fixed, thanks to Toni Tunkkari, by creating derived classes for ADORecordSet_array for
+both databases. Generalized using arrayClass property. Also to support RecordCount(), 
+changed metatype handling for ado drivers. Now the type returned in FetchField 
+  is no longer a number, but the 1-char data type returned by MetaType.
+  At the same time, fixed a lot of date handling. Now mssql support dmy and mdy date formats. 
+Also speedups in sybase and mssql with preg_match and ^ in date/timestamp handling.
+Added support in sybase and mssql for 24 hour clock in timestamps (no AM/PM).
+<p>Extensive revisions to informix driver - thanks to Samuel CARRIERE samuel_carriere#hotmail.com 
+<p>Added $ok parameter to CommitTrans($ok) for easy rollbacks.
+<p>Fixed odbc MetaColumns and MetaTables to save and restore $ADODB_FETCH_MODE.
+<p>Some odbc drivers did not call the base connection class constructor. Fixed.
+<p>Fixed regex for GetUpdateSQL() and GetInsertSQL() to support more legal character combinations.
+
+<p><b>1.99 21 April 2002</b></p>
+<p>Added emulated RecordCount() to all database drivers if $ADODB_COUNTRECS = true 
+  (which it is by default). Inspired by Cristiano Duarte (cunha17#uol.com.br). 
+<p>Unified stored procedure support for mssql and oci8. Parameter() and PrepareSP() 
+  functions implemented. 
+<p>Added support for SELECT FIRST in informix, modified hasTop property to support 
+  this. 
+<p>Changed csv driver to handle updates/deletes/inserts properly (when Execute() returns true).
+Bind params also work now, and raiseErrorFn with csv driver. Added csv driver to QA process. 
+<p>Better error checking in oci8 UpdateBlob() and UpdateBlobFile().
+<p>Added TIME type to MySQL - patch by Manfred h9125297#zechine.wu-wien.ac.at
+<p>Prepare/Execute implemented for Interbase/Firebird 
+<p>Changed some regular expressions to be anchored by /^ $/ for speed.
+<p>Added UnixTimeStamp() and UnixDate() to ADOConnection(). Now these functions 
+  are in both ADOConnection and ADORecordSet classes.
+<p>Empty recordsets were not cached - fixed.
+<p>Thanks to Gaetano Giunta (g.giunta#libero.it) for the oci8 code review. We 
+  didn't agree on everything, but i hoped we agreed to disagree! 
+<p><b>1.90 6 April 2002</b></p>
+<p>Now all database drivers support fetch modes ADODB_FETCH_NUM and ADODB_FETCH_ASSOC, though
+	still not fully tested. Eg. Frontbase, Sybase, Informix.
+<p>NextRecordSet() support for mssql. Contributed by "Sven Axelsson" sven.axelsson#bokochwebb.se
+<p>Added blob support for SQL Anywhere. Contributed by Wade Johnson wade#wadejohnson.de
+<p>Fixed some security loopholes in server.php. Server.php also supports fetch mode.
+<p>Generalized GenID() to support odbc and mssql drivers. Mssql no longer generates GUID's.
+<p>Experimental RowLock($table,$where) for mssql.
+<p>Properly implemented Prepare() in oci8 and ODBC.
+<p>Added Bind() support to oci8 to support Prepare().
+<p>Improved error handler. Catches CacheExecute() and GenID() errors now.
+<p>Now if you are running php from the command line, debugging messages do not output html formating.
+Not 100% complete, but getting there.
+<p><b>1.81 22 March 2002</b></p>
+<p>Restored default $ADODB_FETCH_MODE = ADODB_FETCH_DEFAULT for backward compatibility.
+<p>SelectLimit for oci8 improved - Our FIRST_ROWS optimization now does not overwrite existing hint.
+<p>New Sybase SQL Anywhere driver. Contributed by Wade Johnson wade#wadejohnson.de
+<p><b>1.80 15 March 2002</b></p>
+<p>Redesigned directory structure of ADOdb files. Added new driver directory where
+all database drivers reside.
+<p>Changed caching algorithm to create subdirectories. Now we scale better.
+<p>Informix driver now supports insert_id(). Contribution by "Andrea Pinnisi" pinnisi#sysnet.it
+<p>Added experimental ISO date and FetchField support for informix.
+<p>Fixed a quoting bug in Execute() with bind parameters, causing problems with blobs.
+<p>Mssql driver speedup by 10-15%.
+<p>Now in CacheExecute($secs2cache,$sql,...), $secs2cache is optional. If missing, it will
+take the value defined in $connection->cacheSecs (default is 3600 seconds). Note that
+CacheSelectLimit(), the secs2cache is still compulsory - sigh.
+<p>Sybase SQL Anywhere driver (using ODBC) contributed by Wade Johnson wade#wadejohnson.de
+<p><b>1.72 8 March 2002</b></p>
+<p>Added @ when returning Fields() to prevent spurious error - "Michael William Miller" mille562#pilot.msu.edu
+<p>MetaDatabases() for postgres contributed by Phil pamelant#nerim.net
+ <p>Mitchell T. Young (mitch#youngfamily.org) contributed informix driver.
+ <p>Fixed rs2html() problem. I cannot reproduce, so probably a problem with pre PHP 4.1.0 versions,
+  when supporting new ADODB_FETCH_MODEs.
+ <p>Mattia Rossi (mattia#technologist.com) contributed BlobDecode() and UpdateBlobFile() for postgresql
+ using the postgres specific pg_lo_import()/pg_lo_open() - i don't use them but hopefully others will
+ find this useful. See <a href="http://phplens.com/lens/lensforum/msgs.php?id=1262">this posting</a>
+ for an example of usage.
+ <p>Added UpdateBlobFile() for uploading files to a database.
+ <p>Made UpdateBlob() compatible with oci8po driver.
+ <p>Added noNullStrings support to oci8 driver. Oracle changes all ' ' strings to nulls,
+  so you need to set strings to ' ' to prevent the nullifying of strings. $conn->noNullStrings = true;
+  will do this for you automatically. This is useful when you define a char column as NOT NULL.
+  <p>Fixed UnixTimeStamp() bug - wasn't setting minutes and seconds properly. Patch from Agusti Fita i Borrell agusti#anglatecnic.com.
+  <p>Toni Tunkkari added patch for sybase dates. Problem with spaces in day part of date fixed.
+ <p><b>1.71 18 Jan 2002</b></p>
+ <p>Sequence start id support. Now $conn->Gen_ID('seqname', 50) to start sequence from 50.
+ <p>CSV driver fix for selectlimit, from Andreas - akaiser#vocote.de.
+<P>Gam3r spotted that a global variable was undefined in the session handler. 
+<p>Mssql date regex had error. Fixed - reported by Minh Hoang vb_user#yahoo.com.
+<p>DBTimeStamp() and DBDate() now accept iso dates and unix timestamps. This means
+that the PostgreSQL handling of dates in GetInsertSQL() and GetUpdateSQL() can
+be removed. Also if these functions are passed '' or null or false, we return a SQL null.
+<p>GetInsertSQL() and GetUpdateSQL() now accept a new parameter, $magicq to 
+indicate whether quotes should be inserted based on magic quote settings - suggested by
+dj#4ict.com.
+<p>Reformated docs slightly based on suggestions by Chris Small.
+ <p><b>1.65 28 Dec 2001</b></p>
+ <p>Fixed borland_ibase class naming bug.
+ <p>Now instead of using $rs->fields[0] internally, we use reset($rs->fields) so 
+ that we are compatible with ADODB_FETCH_ASSOC mode. Reported by Nico S.
+ <p>Changed recordset constructor and _initrs() for oci8 so that it returns the field definitions even
+ if no rows in the recordset. Reported by Rick Hickerson (rhickers#mv.mv.com).
+ <p>Improved support for postgresql in GetInsertSQL and GetUpdateSQL by
+  "mike" mike#partner2partner.com  and "Ryan Bailey" rebel#windriders.com
+ <p><b>1.64 20 Dec 2001</b></p>
+<p>Danny Milosavljevic &lt;danny.milo#gmx.net> added some patches for MySQL error handling
+and displaying default values.
+<p>Fixed some ADODB_FETCH_BOTH inconsistencies in odbc and interbase.
+<p>Added more tests to test suite to cover ADODB_FETCH_* and ADODB_ERROR_HANDLER.
+<p>Added firebird (ibase) driver
+<p>Added borland_ibase driver for interbase 6.5
+<p><b>1.63 13 Dec 2001</b></p>
+Absolute to the adodb-lib.inc.php file not set properly. Fixed.<p>
+
+<p><b>1.62 11 Dec 2001</b></p>
+<p>Major speedup of ADOdb for low-end web sites by reducing the php code loading and compiling
+cycle. We conditionally compile not so common functions. 
+Moved csv code to adodb-csvlib.inc.php to reduce adodb.inc.php parsing. This file
+is loaded only when the csv/proxy driver is used, or CacheExecute() is run.
+Also moved PageExecute(), GetSelectSQL() and GetUpdateSQL() core code to adodb-lib.inc.php.
+This reduced the 70K main adodb.inc.php file to 55K, and since at least 20K of the file
+is comments, we have reduced 50K of code in adodb.inc.php to 35K. There
+ should be 35% reduction in memory and thus 35% speedup in compiling the php code for the
+main adodb.inc.php file.
+<p>Highly tuned SelectLimit() for oci8 for massive speed improvements on large files. 
+Selecting 20 rows starting from the 20,000th row of a table is now 7 times faster. 
+Thx to Tomas V V Cox.
+<p>Allow . and # in table definitions in GetInsertSQL and GetUpdateSQL.
+ See ADODB_TABLE_REGEX constant. Thx to Ari Kuorikoski.
+<p>Added ADODB_PREFETCH_ROWS constant, defaulting to 10. This determines the number
+of records to prefetch in a SELECT statement. Only used by oci8.</p>
+<p>Added high portability Oracle class called oci8po. This uses ? for bind variables, and 
+lower cases column names.</p>
+<p>Now all database drivers support $ADODB_FETCH_MODE, including interbase, ado, and odbc:
+ADODB_FETCH_NUM and ADODB_FETCH_ASSOC. ADODB_FETCH_BOTH is not fully implemented for all 
+database drivers.
+<p><b>1.61 Nov 2001</b></p>
+<p>Added PO_RecordCount() and PO_Insert_ID(). PO stands for portable. Pablo Roca 
+  [pabloroca#mvps.org]</p>
+<p>GenID now returns 0 if not available. Safer is that you should check $conn->hasGenID 
+  for availability.</p>
+<p>M'soft ADO we now correctly close recordset in _close() peterd#telephonetics.co.uk</p>
+<p>MSSQL now supports GenID(). It generates a 16-byte GUID from mssql newid() 
+  function.</p>
+<p>Changed ereg_replace to preg_replace in SelectLimit. This is a fix for mssql. 
+  Ereg doesn't support t or n! Reported by marino Carlos xaplo#postnuke-espanol.org</p>
+<p>Added $recordset->connection. This is the ADOConnection object for the recordset. 
+Works with cached and normal recordsets. Surprisingly, this had no affect on performance!</p>
+<p><b>1.54 15 Nov 2001</b></p>
+Fixed some more bugs in PageExecute().  I am getting sick of bug in this and will have to 
+reconsider my QA here. The main issue is that I don't use PageExecute() and 
+to check whether it is working requires a visual inspection of the html generated currently.
+It is possible to write a test script but it would be quite complicated :(
+<p> More speedups of SelectLimit() for DB2, Oci8, access, vfp, mssql.
+<p>
+
+<p><b>1.53 7 Nov 2001</b></p>
+Added support for ADODB_FETCH_ASSOC for ado and odbc drivers.<p>
+Tuned GetRowAssoc(false) in postgresql and mysql.<p>
+Stephen Van Dyke contributed ADOdb icon, accepted with some minor mods.<p>
+Enabled Affected_Rows() for postgresql<p>
+Speedup for Concat() using implode() - Benjamin Curtis ben_curtis#yahoo.com<p>
+Fixed some more bugs in PageExecute() to prevent infinite loops<p>
+<p><b>1.52 5 Nov 2001</b></p>
+Spelling error in CacheExecute() caused it to fail. $ql should be $sql in line 625!<p>
+Added fixes for parsing [ and ] in GetUpdateSQL().
+<p><b>1.51 5 Nov 2001</b></p>
+<p>Oci8 SelectLimit() speedup by using OCIFetch().
+<p>Oci8 was mistakenly reporting errors when $db->debug = true.
+<p>If a connection failed with ODBC, it was not correctly reported - fixed.
+<p>_connectionID was inited to -1, changed to false.
+<p>Added $rs->FetchRow(), to simplify API, ala PEAR DB
+<p>Added PEAR DB compat mode, which is still faster than PEAR! See adodb-pear.inc.php.
+<p>Removed postgres pconnect debugging statement.
+<p><b>1.50 31 Oct 2001</b></p>
+<p>ADOdbConnection renamed to ADOConnection, and ADOdbFieldObject to ADOFieldObject.
+<p>PageExecute() now checks for empty $rs correctly, and the errors in the docs on this subject have been fixed.
+<p>odbc_error() does not return 6 digit error correctly at times. Implemented workaround.
+<p>Added ADORecordSet_empty class. This will speedup INSERTS/DELETES/UPDATES because the return
+object created is much smaller.
+<p>Added Prepare() to odbc, and oci8 (but doesn't work properly for oci8 still).
+<p>Made pgsql a synonym for postgre7, and changed SELECT LIMIT to use OFFSET for compat with 
+postgres 7.2.
+<p>Revised adodb-cryptsession.php thanks to Ari.
+<p>Set resources to false on _close, to force freeing of resources.
+<p>Added adodb-errorhandler.inc.php, adodb-errorpear.inc.php and raiseErrorFn on Freek's urging.
+<p>GetRowAssoc($toUpper=true): $toUpper added as default.
+<p>Errors when connecting to a database were not captured formerly. Now we do it correctly.
+<p><b>1.40 19 September 2001</b></p>
+<p>PageExecute() to implement page scrolling added. Code and idea by Iv&aacute;n Oliva.</p>
+<p>Some minor postgresql fixes.</p>
+<p>Added sequence support using GenID() for postgresql, oci8, mysql, interbase.</p>
+<p>Added UpdateBlob support for interbase (untested).</p>
+<p>Added encrypted sessions (see adodb-cryptsession.php). By Ari Kuorikoski &lt;kuoriari#finebyte.com></p>
+<p><b>1.31 21 August 2001</b></p>
+<p>Many bug fixes thanks to "GaM3R (Cameron)" &lt;gamr#outworld.cx>. Some session changes due to Gam3r.
+<p>Fixed qstr() to quote  also.
+<p>rs2html() now pretty printed.
+<p>Jonathan Younger jyounger#unilab.com contributed the great idea GetUpdateSQL() and GetInsertSQL() which
+generates SQL to update and insert into a table from a recordset. Modify the recordset fields
+array, then can this function to generate the SQL (the SQL is not executed).
+<p>"Nicola Fankhauser" &lt;nicola.fankhauser#couniq.com> found some bugs in date handling for mssql.</p>
+<p>Added minimal Oracle support for LOBs. Still under development.</p>
+Added $ADODB_FETCH_MODE so you can control whether recordsets return arrays which are
+numeric, associative or both. This is a global variable you set. Currently only MySQL, Oci8, Postgres
+drivers support this.
+<p>PostgreSQL properly closes recordsets now. Reported by several people.
+<p>
+Added UpdateBlob() for Oracle. A hack to make it easier to save blobs.
+<p>
+Oracle timestamps did not display properly. Fixed.
+<p><b>1.20 6 June 2001</b></p>
+<p>Now Oracle can connect using tnsnames.ora or server and service name</p>
+<p>Extensive Oci8 speed optimizations. 
+Oci8 code revised to support variable binding, and /*+ FIRST_ROWS */ hint.</p>
+<p>Worked around some 4.0.6 bugs in odbc_fetch_into().</p>
+<p>Paolo S. Asioli paolo.asioli#libero.it suggested GetRowAssoc().</p>
+<p>Escape quotes for oracle wrongly set to '. Now '' is used.</p>
+<p>Variable binding now works in ODBC also.</p>
+<p>Jumped to version 1.20 because I don't like 13 :-)</p>
+<p><b>1.12 6 June 2001</b></p>
+<p>Changed $ADODB_DIR to ADODB_DIR constant to plug a security loophole.</p>
+<p>Changed _close() to close persistent connections also. Prevents connection leaks.</p>
+<p>Major revision of oracle and oci8 drivers. 
+Added OCI_RETURN_NULLS and OCI_RETURN_LOBS to OCIFetchInto(). BLOB, CLOB and VARCHAR2 recognition
+in MetaType() improved. MetaColumns() returns columns in correct sort order.</p>
+<p>Interbase timestamp input format was wrong. Fixed.</p>
+<p><b>1.11 20 May 2001</b></p>
+<p>Improved file locking for Windows.</p>
+<p>Probabilistic flushing of cache to avoid avalanche updates when cache timeouts.</p>
+<p>Cached recordset timestamp not saved in some scenarios. Fixed.</p>
+<p><b>1.10 19 May 2001</b></p>
+<p>Added caching. CacheExecute() and CacheSelectLimit().
+<p>Added csv driver. See <a href="http://php.weblogs.com/adodb_csv">http://php.weblogs.com/ADODB_csv</a>. 
+<p>Fixed SelectLimit(), SELECT TOP not working under certain circumstances.
+<p>Added better Frontbase support of MetaTypes() by Frank M. Kromann.
+<p><b>1.01 24 April 2001</b></p>
+<p>Fixed SelectLimit bug.  not quoted properly.
+<p>SelectLimit: SELECT TOP -1 * FROM TABLE not support by Microsoft. Fixed.</p>
+<p>GetMenu improved by glen.davies#cce.ac.nz to support multiple hilited items<p>
+<p>FetchNextObject() did not work with only 1 record returned. Fixed bug reported by $tim#orotech.net</p>
+<p>Fixed mysql field max_length problem. Fix suggested by Jim Nicholson (jnich#att.com)</p>
+<p><b>1.00 16 April 2001</b></p>
+<p>Given some brilliant suggestions on how to simplify ADOdb by akul. You no longer need to
+setup $ADODB_DIR yourself, and ADOLoadCode() is automatically called by ADONewConnection(), 
+simplifying the startup code.</p>
+<p>FetchNextObject() added. Suggested by Jakub Marecek. This makes FetchObject() obsolete, as
+this is more flexible and powerful.</p>
+<p>Misc fixes to SelectLimit() to support Access (top must follow distinct) and Fields() 
+in the array recordset. From Reinhard Balling.</p>
+<p><b>0.96 27 Mar 2001</b></p>
+<p>ADOConnection Close() did not return a value correctly. Thanks to akul#otamedia.com.</p>
+<p>When the horrible magic_quotes is enabled, back-slash () is changed to double-backslash (\).
+This doesn't make sense for Microsoft/Sybase databases. We fix this in qstr().</p>
+<p>Fixed Sybase date problem in UnixDate() thanks to Toni Tunkkari. Also fixed MSSQL problem
+in UnixDate() - thanks to milhouse31#hotmail.com.</p>
+<p>MoveNext() moved to leaf classes for speed in MySQL/PostgreSQL. 10-15% speedup.</p>
+<p>Added null handling in bindInputArray in Execute() -- Ron Baldwin suggestion.</p>
+<p>Fixed some option tags. Thanks to john#jrmstudios.com.</p>
+<p><b>0.95 13 Mar 2001</b></p>
+<p>Added postgres7 database driver which supports LIMIT and other version 7 stuff in the future.</p>
+<p>Added SelectLimit to ADOConnection to simulate PostgreSQL's "select * from table limit 10 offset 3".
+Added helper function GetArrayLimit() to ADORecordSet.</p>
+<p>Fixed mysql metacolumns bug. Thanks to Freek Dijkstra (phpeverywhere#macfreek.com).</p>
+<p>Also many PostgreSQL changes by Freek. He almost rewrote the whole PostgreSQL driver!</p>
+<p>Added fix to input parameters in Execute for non-strings by Ron Baldwin.</p>
+<p>Added new metatype, X for TeXt. Formerly, metatype B for Blob also included
+text fields. Now 'B' is for binary/image data. 'X' for textual data.</p>
+<p>Fixed $this->GetArray() in GetRows().</p>
+<p>Oracle and OCI8: 1st parameter is always blank -- now warns if it is filled.</p>
+<p>Now <i>hasLimit</i> and <i>hasTop</i> added to indicate whether 
+SELECT * FROM TABLE LIMIT 10 or SELECT TOP 10 * FROM TABLE are supported.</p>
+<p><b>0.94 04 Feb 2001</b></p>
+<p>Added ADORecordSet::GetRows() for compatibility with Microsoft ADO. Synonym for GetArray().</p>
+<p>Added new metatype 'R' to represent autoincrement numbers.</p>
+<p>Added ADORecordSet.FetchObject() to return a row as an object.</p>
+<p>Finally got a Linux box to test PostgreSql. Many fixes.</p>
+<p>Fixed copyright misspellings in 0.93.</p>
+<p>Fixed mssql MetaColumns type bug.</p>
+<p>Worked around odbc bug in PHP4 for sessions.</p>
+<p>Fixed many documentation bugs (affected_rows, metadatabases, qstr).</p>
+<p>Fixed MySQL timestamp format (removed comma).</p>
+<p>Interbase driver did not call ibase_pconnect(). Fixed.</p>
+<p><b>0.93 18 Jan 2002</b></p>
+<p>Fixed GetMenu bug.</p>
+<p>Simplified Interbase commit and rollback.</p>
+<p>Default behaviour on closing a connection is now to rollback all active transactions.</p>
+<p>Added field object handling for array recordset for future XML compatibility.</p>
+<p>Added arr2html() to convert array to html table.</p>
+<p><b>0.92 2 Jan 2002</b></p>
+<p>Interbase Commit and Rollback should be working again.</p>
+<p>Changed initialisation of ADORecordSet. This is internal and should not affect users. We
+are doing this to support cached recordsets in the future.</p>
+
+<p>Implemented ADORecordSet_array class. This allows you to simulate a database recordset
+with an array.</p>
+<p>Added UnixDate() and UnixTimeStamp() to ADORecordSet.</p>
+<p><b>0.91 21 Dec 2000</b></p>
+<p>Fixed ODBC so ErrorMsg() is working.</p>
+<p>Worked around ADO unrecognised null (0x1) value problem in COM.</p>
+<p>Added Sybase support for FetchField() type</p>
+<p>Removed debugging code and unneeded html from various files</p>
+<p>Changed to javadoc style comments to adodb.inc.php.</p>
+<p>Added maxsql as synonym for mysqlt</p>
+<p>Now ODBC downloads first 8K of blob by default
+<p><b>0.90 15 Nov 2000</b></p>
+<p>Lots of testing of Microsoft ADO. Should be more stable now.</p>
+<p>Added $ADODB_COUNTREC. Set to false for high speed selects.</p>
+<p>Added Sybase support. Contributed by Toni Tunkkari (toni.tunkkari#finebyte.com). Bug in Sybase 
+  API: GetFields is unable to determine date types.</p>
+<p>Changed behaviour of RecordSet.GetMenu() to support size parameter (listbox) properly.</p>
+<p>Added emptyDate and emptyTimeStamp to RecordSet class that defines how to represent 
+  empty dates.</p>
+<p>Added MetaColumns($table) that returns an array of ADOFieldObject's listing 
+  the columns of a table.</p>
+<p>Added transaction support for PostgresSQL -- thanks to "Eric G. Werk" egw#netguide.dk.</p>
+<p>Added adodb-session.php for session support.</p>
+<p><b>0.80 30 Nov 2000</b></p>
+<p>Added support for charSet for interbase. Implemented MetaTables for most databases. 
+  PostgreSQL more extensively tested.</p>
+<p><b>0.71 22 Nov 2000</b></p>
+<p>Switched from using require_once to include/include_once for backward compatability with PHP 4.02 and earlier.</p>
+<p><b>0.70 15 Nov 2000</b></p>
+<p>Calls by reference have been removed (call_time_pass_reference=Off) to ensure compatibility with future versions of PHP, 
+except in Oracle 7 driver due to a bug in php_oracle.dll.</p>
+<p>PostgreSQL database driver contributed by Alberto Cerezal (acerezalp#dbnet.es). 
+</p>
+<p>Oci8 driver for Oracle 8 contributed by George Fourlanos (fou#infomap.gr).</p>
+<p>Added <i>mysqlt</i> database driver to support MySQL 3.23 which has transaction 
+ support. </p>
+<p>Oracle default date format (DD-MON-YY) did not match ADOdb default date format (which is YYYY-MM-DD). Use ALTER SESSION to force the default date.</p>
+<p>Error message checking is now included in test suite.</p>
+<p>MoveNext() did not check EOF properly -- fixed.</p>
+<p><b>0.60 Nov 8 2000</b></p>
+<p>Fixed some constructor bugs in ODBC and ADO. Added ErrorNo function to ADOConnection 
+ class. </p>
+<p><b>0.51 Oct 18 2000</b></p>
+<p>Fixed some interbase bugs.</p>
+<p><b>0.50 Oct 16 2000</b></p>
+<p>Interbase commit/rollback changed to be compatible with PHP 4.03. </p>
+<p>CommitTrans( ) will now return true if transactions not supported. </p>
+<p>Conversely RollbackTrans( ) will return false if transactions not supported. 
+</p>
+<p><b>0.46 Oct 12</b></p>
+Many Oracle compatibility issues fixed. 
+<p><b>0.40 Sept 26</b></p>
+<p>Many bug fixes</p>
+<p>Now Code for BeginTrans, CommitTrans and RollbackTrans is working. So is the Affected_Rows
+and Insert_ID. Added above functions to test.php.</p>
+<p>ADO type handling was busted in 0.30. Fixed.</p>
+<p>Generalised Move( ) so it works will all databases, including ODBC.</p>
+<p><b>0.30 Sept 18</b></p>
+<p>Renamed ADOLoadDB to ADOLoadCode. This is clearer.</p>
+<p>Added BeginTrans, CommitTrans and RollbackTrans functions.</p>
+<p>Added Affected_Rows() and Insert_ID(), _affectedrows() and _insertID(), ListTables(), 
+ ListDatabases(), ListColumns().</p>
+<p>Need to add New_ID() and hasInsertID and hasAffectedRows, autoCommit </p>
+<p><b>0.20 Sept 12</b></p>
+<p>Added support for Microsoft's ADO.</p>
+<p>Added new field to ADORecordSet -- canSeek</p>
+<p>Added new parameter to _fetch($ignore_fields = false). Setting to true will 
+ not update fields array for faster performance.</p>
+<p>Added new field to ADORecordSet/ADOConnection -- dataProvider to indicate whether 
+ a class is derived from odbc or ado.</p>
+<p>Changed class ODBCFieldObject to ADOFieldObject -- not documented currently.</p>
+<p>Added benchmark.php and testdatabases.inc.php to the test suite.</p>
+<p>Added to ADORecordSet FastForward( ) for future high speed scrolling. Not documented.</p>
+<p>Realised that ADO's Move( ) uses relative positioning. ADOdb uses absolute. 
+</p>
+<p><b>0.10 Sept 9 2000</b></p>
+<p>First release</p>
+</body></html>
Index: /Dev/trunk/rdfapi/util/adodb/docs/readme.htm
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/docs/readme.htm	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/docs/readme.htm	(revision 12)
@@ -0,0 +1,68 @@
+<html>
+<head>
+<title>ADODB Manual</title>
+<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
+<XSTYLE
+	body,td {font-family:Arial,Helvetica,sans-serif;font-size:11pt}
+	pre {font-size:9pt}
+	.toplink {font-size:8pt}
+	/>
+</head>	
+<body bgcolor="#FFFFFF">
+
+<h3>ADOdb Library for PHP</h3>
+<p>ADOdb is a suite of database libraries that allow you to connect to multiple 
+	databases in a portable manner. Download from <a href=http://adodb.sourceforge.net/>http://adodb.sourceforge.net/</a>.
+<ul><li>The ADOdb documentation has moved to <a href=docs-adodb.htm>docs-adodb.htm</a> 
+	This allows you to query, update and insert records using a portable API.
+<p><li>The ADOdb data dictionary docs are at <a href=docs-datadict.htm>docs-datadict.htm</a>. 
+	This allows you to create database tables and indexes in a portable manner.
+<p><li>The ADOdb database performance monitoring docs are at <a href=docs-perf.htm>docs-perf.htm</a>. 
+	This allows you to perform health checks, tune and monitor your database.
+<p><li>The ADOdb database-backed session docs are at <a href=docs-session.htm>docs-session.htm</a>. 
+</ul>
+<p>
+<h3>Installation</h3>
+Make sure you are running PHP4.0.4 or later. Unpack all the files into a directory accessible by your webserver.
+<p>
+To test, try modifying some of the tutorial examples. Make sure you customize the connection settings correctly. You can debug using:
+<pre>
+&lt;?php
+include('adodb/adodb.inc.php');
+
+$db = <b>ADONewConnection</b>($driver); # eg. 'mysql' or 'oci8' 
+$db->debug = true;
+$db-><b>Connect</b>($server, $user, $password, $database);
+$rs = $db-><b>Execute</b>('select * from some_small_table');
+print "&lt;pre>";
+print_r($rs-><b>GetRows</b>());
+print "&lt;/pre>";
+?>
+</pre>
+<h3>How are people using ADOdb</h3>
+Here are some examples of how people are using ADOdb: 
+<ul>
+	<li> <strong>PhpLens</strong> is a commercial data grid component that allows 
+		both cool Web designers and serious unshaved programmers to develop and 
+		maintain databases on the Web easily. Developed by the author of ADOdb. 
+	</li>
+	<li> <strong>PHAkt</strong>: PHP Extension for DreamWeaver Ultradev allows 
+		you to script PHP in the popular Web page editor. Database handling provided 
+		by ADOdb. </li>
+	<li> <strong>Analysis Console for Intrusion Databases (ACID)</strong>: PHP-based 
+		analysis engine to search and process a database of security incidents 
+		generated by security-related software such as IDSes and firewalls (e.g. 
+		Snort, ipchains). By Roman Danyliw. </li>
+	<li> <strong>PostNuke</strong> is a very popular free content management system 
+		and weblog system. It offers full CSS support, HTML 4.01 transitional 
+		compliance throughout, an advanced blocks system, and is fully multi-lingual 
+		enabled. </li>
+	<li><strong> EasyPublish CMS</strong> is another free content management system 
+		for managing information and integrated modules on your internet, intranet- 
+		and extranet-sites. From Norway. </li>
+	<li> <strong>NOLA</strong> is a full featured accounting, inventory, and job 
+		tracking application. It is licensed under the GPL, and developed by Noguska. 
+	</li>
+</ul>
+</body>
+</html>
Index: /Dev/trunk/rdfapi/util/adodb/docs/tips_portable_sql.htm
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/docs/tips_portable_sql.htm	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/docs/tips_portable_sql.htm	(revision 12)
@@ -0,0 +1,367 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
+
+<html>
+<head>
+	<title>Tips on Writing Portable SQL for Multiple Databases for PHP</title>
+</head>
+
+<body bgcolor=white>
+<table width=100% border=0><tr><td><h2>Tips on Writing Portable SQL &nbsp;</h2></td><td>
+ <div align=right><img src="cute_icons_for_site/adodb.gif"></div></td></tr></table>
+  <p>Updated 6 Oct 2006. Added OffsetDate example.
+  <p>Updated 18 Sep 2003. Added Portable Native SQL section.
+<p>
+
+ If you are writing an application that is used in multiple environments and 
+  operating systems, you need to plan to support multiple databases. This article 
+  is based on my experiences with multiple database systems, stretching from 4th 
+  Dimension in my Mac days, to the databases I currently use, which are: Oracle, 
+  FoxPro, Access, MS SQL Server and MySQL. Although most of the advice here applies 
+  to using SQL with Perl, Python and other programming languages, I will focus on PHP and how 
+  the <a href="http://adodb.sourceforge.net/">ADOdb</a> database abstraction library 
+  offers some solutions.<p></p>
+<p>Most database vendors practice product lock-in. The best or fastest way to 
+  do things is often implemented using proprietary extensions to SQL. This makes 
+  it extremely hard to write portable SQL code that performs well under all conditions. 
+  When the first ANSI committee got together in 1984 to standardize SQL, the database 
+  vendors had such different implementations that they could only agree on the 
+  core functionality of SQL. Many important application specific requirements 
+  were not standardized, and after so many years since the ANSI effort began, 
+  it looks as if much useful database functionality will never be standardized. 
+  Even though ANSI-92 SQL has codified much more, we still have to implement portability 
+  at the application level.</p>
+<h3><b>Selects</b></h3>
+<p>The SELECT statement has been standardized to a great degree. Nearly every 
+  database supports the following:</p>
+<p>SELECT [cols] FROM [tables]<br>
+  &nbsp;&nbsp;[WHERE conditions]<br>
+  &nbsp; [GROUP BY cols]<br>
+  &nbsp; [HAVING conditions] <br>
+  &nbsp; [ORDER BY cols]</p>
+<p>But so many useful techniques can only be implemented by using proprietary 
+  extensions. For example, when writing SQL to retrieve the first 10 rows for 
+  paging, you could write...</p>
+<table width="80%" border="1" cellspacing="0" cellpadding="0" align="center">
+  <tr> 
+	<td><b>Database</b></td>
+	<td><b>SQL Syntax</b></td>
+  </tr>
+  <tr> 
+	<td>DB2</td>
+	<td>select * from table fetch first 10 rows only</td>
+  </tr>
+  <tr> 
+	<td>Informix</td>
+	<td>select first 10 * from table</td>
+  </tr>
+  <tr> 
+	<td>Microsoft SQL Server and Access</td>
+	<td>select top 10 * from table</td>
+  </tr>
+  <tr> 
+	<td>MySQL and PostgreSQL</td>
+	<td>select * from table limit 10</td>
+  </tr>
+  <tr> 
+	<td>Oracle 8i</td>
+	<td>select * from (select * from table) where rownum &lt;= 10</td>
+  </tr>
+</table>
+<p>This feature of getting a subset of data is so useful that in the PHP class 
+  library ADOdb, we have a SelectLimit( ) function that allows you to hide the 
+  implementation details within a function that will rewrite your SQL for you:</p>
+<pre>$connection-&gt;SelectLimit('select * from table', 10);
+</pre>
+<p><b>Selects: Fetch Modes</b></p>
+<p>PHP allows you to retrieve database records as arrays. You can choose to have 
+  the arrays indexed by field name or number. However different low-level PHP 
+  database drivers are inconsistent in their indexing efforts. ADOdb allows you 
+  to determine your prefered mode. You set this by setting the variable $ADODB_FETCH_MODE 
+  to either of the constants ADODB_FETCH_NUM (for numeric indexes) or ADODB_FETCH_ASSOC 
+  (using field names as an associative index).</p>
+<p>The default behaviour of ADOdb varies depending on the database you are using. 
+  For consistency, set the fetch mode to either ADODB_FETCH_NUM (for speed) or 
+  ADODB_FETCH_ASSOC (for convenience) at the beginning of your code. </p>
+<p><b>Selects: Counting Records</b></p>
+<p>Another problem with SELECTs is that some databases do not return the number 
+  of rows retrieved from a select statement. This is because the highest performance 
+  databases will return records to you even before the last record has been found. 
+</p>
+<p>In ADOdb, RecordCount( ) returns the number of rows returned, or will emulate 
+  it by buffering the rows and returning the count after all rows have been returned. 
+  This can be disabled for performance reasons when retrieving large recordsets 
+  by setting the global variable $ADODB_COUNTRECS = false. This variable is checked 
+  every time a query is executed, so you can selectively choose which recordsets 
+  to count.</p>
+<p>If you prefer to set $ADODB_COUNTRECS = false, ADOdb still has the PO_RecordCount( 
+  ) function. This will return the number of rows, or if it is not found, it will 
+  return an estimate using SELECT COUNT(*):</p>
+<pre>$rs = $db-&gt;Execute(&quot;select * from table where state=$state&quot;);
+$numrows = $rs-&gt;PO_RecordCount('table', &quot;state=$state&quot;);</pre>
+<p><b>Selects: Locking</b> </p>
+<p>SELECT statements are commonly used to implement row-level locking of tables. 
+  Other databases such as Oracle, Interbase, PostgreSQL and MySQL with InnoDB 
+  do not require row-level locking because they use versioning to display data 
+  consistent with a specific point in time.</p>
+<p>Currently, I recommend encapsulating the row-level locking in a separate function, 
+  such as RowLock($table, $where):</p>
+<pre>$connection-&gt;BeginTrans( );
+$connection-&gt;RowLock($table, $where); </pre>
+<pre><font color=green># some operation</font></pre>
+<pre>if ($ok) $connection-&gt;CommitTrans( );
+else $connection-&gt;RollbackTrans( );
+</pre>
+<p><b>Selects: Outer Joins</b></p>
+<p>Not all databases support outer joins. Furthermore the syntax for outer joins 
+  differs dramatically between database vendors. One portable (and possibly slower) 
+  method of implementing outer joins is using UNION.</p>
+<p>For example, an ANSI-92 left outer join between two tables t1 and t2 could 
+  look like:</p>
+<pre>SELECT t1.col1, t1.col2, t2.cola <br>  FROM t1 <i>LEFT JOIN</i> t2 ON t1.col = t2.col</pre>
+<p>This can be emulated using:</p>
+<pre>SELECT t1.col1, t1.col2, t2.cola FROM t1, t2 <br>	   WHERE t1.col = t2.col 
+   UNION ALL
+SELECT col1, col2, null FROM t1 <br>	   WHERE t1.col not in (select distinct col from t2)
+</pre>
+<p>Since ADOdb 2.13, we provide some hints in the connection object as to legal 
+  join variations. This is still incomplete and sometimes depends on the database 
+  version you are using, but is useful as a general guideline:</p>
+<p><font face="Courier New, Courier, mono">$conn-&gt;leftOuter</font>: holds the 
+  operator used for left outer joins (eg. '*='), or false if not known or not 
+  available.<br>
+  <font face="Courier New, Courier, mono">$conn-&gt;rightOuter</font>: holds the 
+  operator used for right outer joins (eg '=*'), or false if not known or not 
+  available.<br>
+  <font face="Courier New, Courier, mono">$conn-&gt;ansiOuter</font>: boolean 
+  that if true means that ANSI-92 style outer joins are supported, or false if 
+  not known.</p>
+<h3><b>Inserts</b> </h3>
+<p>When you create records, you need to generate unique id's for each record. 
+  There are two common techniques: (1) auto-incrementing columns and (2) sequences. 
+</p>
+<p>Auto-incrementing columns are supported by MySQL, Sybase and Microsoft Access 
+  and SQL Server. However most other databases do not support this feature. So 
+  for portability, you have little choice but to use sequences. Sequences are 
+  special functions that return a unique incrementing number every time you call 
+  it, suitable to be used as database keys. In ADOdb, we use the GenID( ) function. 
+  It has takes a parameter, the sequence name. Different tables can have different 
+  sequences. </p>
+<pre>$id = $connection-&gt;GenID('sequence_name');<br>$connection-&gt;Execute(&quot;insert into table (id, firstname, lastname) <br>			   values ($id, $firstname, $lastname)&quot;);</pre>
+<p>For databases that do not support sequences natively, ADOdb emulates sequences 
+  by creating a table for every sequence.</p>
+<h3><b>Binding</b></h3>
+<p>Binding variables in an SQL statement is another tricky feature. Binding is 
+  useful because it allows pre-compilation of SQL. When inserting multiple records 
+  into a database in a loop, binding can offer a 50% (or greater) speedup. However 
+  many databases such as Access and MySQL do not support binding natively and 
+  there is some overhead in emulating binding. Furthermore, different databases 
+  (specificly Oracle!) implement binding differently. My recommendation is to 
+  use binding if your database queries are too slow, but make sure you are using 
+  a database that supports it like Oracle. </p>
+<p>ADOdb supports portable Prepare/Execute with:</p>
+<pre>$stmt = $db-&gt;Prepare('select * from customers where custid=? and state=?');
+$rs = $db-&gt;Execute($stmt, array($id,'New York'));</pre>
+<p>Oracle uses named bind placeholders, not "?", so to support portable binding, we have Param() that generates 
+the correct placeholder (available since ADOdb 3.92):
+<pre><font color="#000000">$sql = <font color="#993300">'insert into table (col1,col2) values ('</font>.$DB-&gt;Param('a').<font color="#993300">','</font>.$DB-&gt;Param('b').<font color="#993300">')'</font>;
+<font color="#006600"># generates 'insert into table (col1,col2) values (?,?)'
+# or        'insert into table (col1,col2) values (:a,:b)</font>'
+$stmt = $DB-&gt;Prepare($sql);
+$stmt = $DB-&gt;Execute($stmt,array('one','two'));
+</font></pre>
+<a name="native"></a>
+<h2>Portable Native SQL</h2>
+<p>ADOdb provides the following functions for portably generating SQL functions 
+  as strings to be merged into your SQL statements (some are only available since 
+  ADOdb 3.92): </p>
+<table width="75%" border="1" align=center>
+  <tr> 
+    <td width=30%><b>Function</b></td>
+    <td><b>Description</b></td>
+  </tr>
+  <tr> 
+    <td>DBDate($date)</td>
+    <td>Pass in a UNIX timestamp or ISO date and it will convert it to a date 
+      string formatted for INSERT/UPDATE</td>
+  </tr>
+  <tr> 
+    <td>DBTimeStamp($date)</td>
+    <td>Pass in a UNIX timestamp or ISO date and it will convert it to a timestamp 
+      string formatted for INSERT/UPDATE</td>
+  </tr>
+  <tr> 
+    <td>SQLDate($date, $fmt)</td>
+    <td>Portably generate a date formatted using $fmt mask, for use in SELECT 
+      statements.</td>
+  </tr>
+  <tr> 
+    <td>OffsetDate($date, $ndays)</td>
+    <td>Portably generate a $date offset by $ndays.</td>
+  </tr>
+  <tr> 
+    <td>Concat($s1, $s2, ...)</td>
+    <td>Portably concatenate strings. Alternatively, for mssql use mssqlpo driver, 
+      which allows || operator.</td>
+  </tr>
+  <tr> 
+    <td>IfNull($fld, $replaceNull)</td>
+    <td>Returns a string that is the equivalent of MySQL IFNULL or Oracle NVL.</td>
+  </tr>
+  <tr>
+    <td>Param($name)</td>
+    <td>Generates bind placeholders, using ? or named conventions as appropriate.</td>
+  </tr>
+  <tr><td>$db->sysDate</td><td>Property that holds the SQL function that returns today's date</td>
+</tr>
+<tr><td>$db->sysTimeStamp</td><td>Property that holds the SQL function that returns the current
+timestamp (date+time).
+</td>
+</tr>
+<tr>
+<td>$db->concat_operator</td><td>Property that holds the concatenation operator
+</td>
+</tr>
+<tr><td>$db->length</td><td>Property that holds the name of the SQL strlen function.
+</td></tr>
+
+<tr><td>$db->upperCase</td><td>Property that holds the name of the SQL strtoupper function.
+</td></tr>
+<tr><td>$db->random</td><td>Property that holds the SQL to generate a random number between 0.00 and 1.00.
+</td>
+</tr>
+<tr><td>$db->substr</td><td>Property that holds the name of the SQL substring function.
+</td></tr>
+</table>
+<p>&nbsp; </p>
+<h2>DDL and Tuning</h2>
+There are database design tools such as ERWin or Dezign that allow you to generate data definition language commands such as ALTER TABLE or CREATE INDEX from Entity-Relationship diagrams. 
+<p>
+However if you prefer to use a PHP-based table creation scheme, adodb provides you with this feature. Here is the code to generate the SQL to create a table with: 
+<ol>
+	<li> Auto-increment primary key 'ID', </li>
+	<li>The person's 'NAME' VARCHAR(32) NOT NULL and defaults to '', </li>
+	<li>The date and time of record creation 'CREATED', </li>
+	<li> The person's 'AGE', defaulting to 0, type NUMERIC(16). </li>
+</ol>
+<p>
+Also create a compound index consisting of 'NAME' and 'AGE': 
+<pre>
+$datadict = <strong>NewDataDictionary</strong>($connection);
+$flds = " 
+<font color="#660000">  ID I AUTOINCREMENT PRIMARY,
+  NAME C(32) DEFAULT '' NOTNULL,
+  CREATED T DEFTIMESTAMP,
+  AGE N(16) DEFAULT 0</font>
+";
+$sql1 = $datadict-><strong>CreateTableSQL</strong>('tabname', $flds);
+$sql2 = $datadict-><strong>CreateIndexSQL</strong>('idx_name_age', 'tabname', 'NAME,AGE');
+</pre>
+
+<h3>Data Types</h3>
+<p>Stick to a few data types that are available in most databases. Char, varchar 
+  and numeric/number are supported by most databases. Most other data types (including 
+  integer, boolean and float) cannot be relied on being available. I recommend 
+  using char(1) or number(1) to hold booleans. </p>
+<p>Different databases have different ways of representing dates and timestamps/datetime. 
+  ADOdb attempts to display all dates in ISO (YYYY-MM-DD) format. ADOdb also provides 
+  DBDate( ) and DBTimeStamp( ) to convert dates to formats that are acceptable 
+  to that database. Both functions accept Unix integer timestamps and date strings 
+  in ISO format.</p>
+<pre>$date1 = $connection-&gt;DBDate(time( ));<br>$date2 = $connection-&gt;DBTimeStamp('2002-02-23 13:03:33');</pre>
+<p>We also provide functions to convert database dates to Unix timestamps:</p>
+<pre>$unixts = $recordset-&gt;UnixDate('#2002-02-30#'); <font color="green"># MS Access date =&gt; unix timestamp</font></pre>
+<p>For date calculations, we have OffsetDate which allows you to calculate dates such as <i>yesterday</i> and <i>next week</i> in a RDBMS independant fashion. For example, if we want to set a field to 6 hour from now, use:
+<pre>
+$sql = 'update table set dtimefld='.$db-&gt;OffsetDate($db-&gtsysTimeStamp, 6/24).' where ...';
+</pre>
+<p>The maximum length of a char/varchar field is also database specific. You can 
+  only assume that field lengths of up to 250 characters are supported. This is 
+  normally impractical for web based forum or content management systems. You 
+  will need to be familiar with how databases handle large objects (LOBs). ADOdb 
+  implements two functions, UpdateBlob( ) and UpdateClob( ) that allow you to 
+  update fields holding Binary Large Objects (eg. pictures) and Character Large 
+  Objects (eg. HTML articles):</p>
+<pre><font color=green># for oracle </font>
+$conn->Execute('INSERT INTO blobtable (id, blobcol) VALUES (1,empty_blob())'); 
+$conn->UpdateBlob('blobtable','blobcol',$blobvalue,'id=1'); 
+   
+<font color=green># non-oracle databases</font>
+$conn->Execute('INSERT INTO blobtable (id, blobcol) VALUES (1, null)'); 
+$conn->UpdateBlob('blobtable','blobcol',$blobvalue,'id=1');
+</pre>
+<p>Null handling is another area where differences can occur. This is a mine-field, 
+  because 3-value logic is tricky.
+<p>In general, I avoid using nulls except for dates and default all my numeric 
+  and character fields to 0 or the empty string. This maintains consistency with 
+  PHP, where empty strings and zero are treated as equivalent, and avoids SQL 
+  ambiguities when you use the ANY and EXISTS operators. However if your database 
+  has significant amounts of missing or unknown data, using nulls might be a good 
+  idea. 
+  <p>
+  ADOdb also supports a portable <a href=http://phplens.com/adodb/reference.functions.concat.html#ifnull>IfNull</a> function, so you can define what to display
+  if the field contains a null.
+<h3><b>Stored Procedures</b></h3>
+<p>Stored procedures are another problem area. Some databases allow recordsets 
+  to be returned in a stored procedure (Microsoft SQL Server and Sybase), and 
+  others only allow output parameters to be returned. Stored procedures sometimes 
+  need to be wrapped in special syntax. For example, Oracle requires such code 
+  to be wrapped in an anonymous block with BEGIN and END. Also internal sql operators 
+  and functions such as +, ||, TRIM( ), SUBSTR( ) or INSTR( ) vary between vendors. 
+</p>
+<p>An example of how to call a stored procedure with 2 parameters and 1 return 
+  value follows:</p>
+<pre>	switch ($db->databaseType) {
+	case '<font color="#993300">mssql</font>':
+	  $sql = <font color="#000000"><font color="#993333">'<font color="#993300">SP_RUNSOMETHING</font>'</font></font>; break;
+	case '<font color="#993300">oci8</font>':
+	  $sql = 
+<font color="#993300">	  </font><font color="#000000"><font color="#993300">&quot;declare RETVAL integer;begin :RETVAL := </font><font color="#000000"><font color="#993333"><font color="#993300">SP_RUNSOMETHING</font></font></font><font color="#993300">(:myid,:group);end;&quot;;
+</font>	  break;</font>
+	default:
+	  die('<font color="#993300">Unsupported feature</font>');
+	}
+<font color="#000000"><font color="green">	# @RETVAL = SP_RUNSOMETHING @myid,@group</font>
+	$stmt = $db-&gt;PrepareSP($sql);	<br>	$db-&gt;Parameter($stmt,$id,'<font color="#993300">myid</font>'); 
+	$db-&gt;Parameter($stmt,$group,'<font color="#993300">group</font>');
+	<font color="green"># true indicates output parameter<br>	</font>$db-&gt;Parameter($stmt,$ret,'<font color="#993300">RETVAL</font>',true); 
+	$db-&gt;Execute($stmt); </font></pre>
+<p>As you can see, the ADOdb API is the same for both databases. But the stored 
+  procedure SQL syntax is quite different between databases and is not portable, 
+  so be forewarned! However sometimes you have little choice as some systems only 
+  allow data to be accessed via stored procedures. This is when the ultimate portability 
+  solution might be the only solution: <i>treating portable SQL as a localization 
+  exercise...</i></p>
+<h3><b>SQL as a Localization Exercise</b></h3>
+<p> In general to provide real portability, you will have to treat SQL coding 
+  as a localization exercise. In PHP, it has become common to define separate 
+  language files for English, Russian, Korean, etc. Similarly, I would suggest 
+  you have separate Sybase, Intebase, MySQL, etc files, and conditionally include 
+  the SQL based on the database. For example, each MySQL SQL statement would be 
+  stored in a separate variable, in a file called 'mysql-lang.inc.php'.</p>
+<pre>$sqlGetPassword = '<font color="#993300">select password from users where userid=%s</font>';
+$sqlSearchKeyword = &quot;<font color="#993300">SELECT * FROM articles WHERE match (title,body) against (%s</font>)&quot;;</pre>
+<p>In our main PHP file:</p>
+<pre><font color=green># define which database to load...</font>
+<b>$database = '<font color="#993300">mysql</font>';
+include_once(&quot;<font color="#993300">$database-lang.inc.php</font>&quot;);</b>
+
+$db = &amp;NewADOConnection($database);
+$db->PConnect(...) or die('<font color="#993300">Failed to connect to database</font>');
+
+<font color=green># search for a keyword $word</font>
+$rs = $db-&gt;Execute(sprintf($sqlSearchKeyWord,$db-&gt;qstr($word)));</pre>
+<p>Note that we quote the $word variable using the qstr( ) function. This is because 
+  each database quotes strings using different conventions.</p>
+<p>
+<h3>Final Thoughts</h3>
+<p>The best way to ensure that you have portable SQL is to have your data tables designed using 
+sound principles. Learn the theory of normalization and entity-relationship diagrams and model 
+your data carefully. Understand how joins and indexes work and how they are used to tune performance.
+<p> Visit the following page for more references on database theory and vendors: 
+  <a href="http://php.weblogs.com/sql_tutorial">http://php.weblogs.com/sql_tutorial</a>. 
+  Also read this article on <a href=http://phplens.com/lens/php-book/optimizing-debugging-php.php>Optimizing PHP</a>.
+<p>
+<font size=1>(c) 2002-2003 John Lim.</font>
+
+</body>
+</html>
Index: /Dev/trunk/rdfapi/util/adodb/docs/tute.htm
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/docs/tute.htm	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/docs/tute.htm	(revision 12)
@@ -0,0 +1,290 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
+
+<html>
+<head>
+	<title>Tutorial: Moving from MySQL to ADODB</title>
+</head>
+
+<body bgcolor=white>
+<h1>Tutorial: Moving from MySQL to ADODB</h1>
+
+<pre>		You say eether and I say eyether, 
+		You say neether and I say nyther; 
+		Eether, eyether, neether, nyther - 
+		Let's call the whole thing off ! 
+<br>
+		You like potato and I like po-tah-to, 
+		You like tomato and I like to-mah-to; 
+		Potato, po-tah-to, tomato, to-mah-to - 
+		Let's call the whole thing off ! 
+</pre>
+<p>I love this song, especially the version with Louis Armstrong and Ella singing 
+  duet. It is all about how hard it is for two people in love to be compatible 
+  with each other. It's about compromise and finding a common ground, and that's 
+  what this article is all about. 
+<p>PHP is all about creating dynamic web-sites with the least fuss and the most 
+  fun. To create these websites we need to use databases to retrieve login information, 
+  to splash dynamic news onto the web page and store forum postings. So let's 
+  say we were using the popular MySQL database for this. Your company has done 
+  such a fantastic job that the Web site is more popular than your wildest dreams. 
+  You find that MySQL cannot scale to handle the workload; time to switch databases. 
+<p> Unfortunately in PHP every database is accessed slightly differently. To connect 
+  to MySQL, you would use <i>mysql_connect()</i>; when you decide to upgrade to 
+  Oracle or Microsoft SQL Server, you would use <i>ocilogon() </i>or <i>mssql_connect()</i> 
+  respectively. What is worse is that the parameters you use for the different 
+  connect functions are different also.. One database says po-tato, the other 
+  database says pota-to. Oh-oh. 
+<h3>Let's NOT call the whole thing off</h3>
+<p>A database wrapper library such as ADODB comes in handy when you need to ensure portability. It provides 
+  you with a common API to communicate with any supported database so you don't have to call things off. <p>
+
+<p>ADODB stands for Active Data Objects DataBase (sorry computer guys are sometimes 
+  not very original). ADODB currently supports MySQL, PostgreSQL, Oracle, Interbase, 
+  Microsoft SQL Server, Access, FoxPro, Sybase, ODBC and ADO. You can download 
+  ADODB from <a href=http://php.weblogs.com/adodb></a><a href="http://php.weblogs.com/adodb">http://php.weblogs.com/adodb</a>.
+<h3>MySQL Example</h3>
+<p>The most common database used with PHP is MySQL, so I guess you should be familiar 
+  with the following code. It connects to a MySQL server at <i>localhost</i>, 
+  database <i>mydb</i>, and executes an SQL select statement. The results are 
+  printed, one line per row. 
+<pre><font color="#666600">$db = <b>mysql_connect</b>(&quot;localhost&quot;, &quot;root&quot;, &quot;password&quot;);
+<b>mysql_select_db</b>(&quot;mydb&quot;,$db);</font>
+<font color="#660000">$result = <b>mysql_query</b>(&quot;SELECT * FROM employees&quot;,$db)</font><code><font color="#663300">;
+if ($result === false) die(&quot;failed&quot;);</font></code> 
+<font color="#006666"><b>while</b> ($fields =<b> mysql_fetch_row</b>($result)) &#123;
+ <b>for</b> ($i=0, $max=sizeof($fields); $i &lt; $max; $i++) &#123;
+		<b>print</b> $fields[$i].' ';
+ &#125;
+ <b>print</b> &quot;&lt;br&gt;\n&quot;;
+&#125;</font> 
+</pre>
+<p>The above code has been color-coded by section. The first section is the connection 
+  phase. The second is the execution of the SQL, and the last section is displaying 
+  the fields. The <i>while</i> loop scans the rows of the result, while the <i>for</i> 
+  loop scans the fields in one row.</p>
+<p>Here is the equivalent code in ADODB</p>
+<pre><b><font color="#666600"> include(&quot;adodb.inc.php&quot;);</font></b><font color="#666600">
+ $db = <b>NewADOConnection</b>('mysql');
+ $db-&gt;<b>Connect</b>(&quot;localhost&quot;, &quot;root&quot;, &quot;password&quot;, &quot;mydb&quot;);</font>
+ <font color="#663300">$result = $db-&gt;<b>Execute</b>(&quot;SELECT * FROM employees&quot;);
+ </font><font color="#663300"></font><code><font color="#663300">if ($result === false) die(&quot;failed&quot;)</font></code><code><font color="#663300">;</font></code>  
+ <font color="#006666"><b>while</b> (!$result-&gt;EOF) &#123;
+	<b>for</b> ($i=0, $max=$result-&gt;<b>FieldCount</b>(); $i &lt; $max; $i++)
+		   <b>print</b> $result-&gt;fields[$i].' ';
+	$result-&gt;<b>MoveNext</b>();
+	<b>print</b> &quot;&lt;br&gt;\n&quot;;
+ &#125;</font> </pre>
+<p></p>
+<p>Now porting to Oracle is as simple as changing the second line to <code>NewADOConnection('oracle')</code>. 
+  Let's walk through the code...</p>
+<h3>Connecting to the Database</h3>
+<p></p>
+<pre><b><font color="#666600">include(&quot;adodb.inc.php&quot;);</font></b><font color="#666600">
+$db = <b>NewADOConnection</b>('mysql');
+$db-&gt;<b>Connect</b>(&quot;localhost&quot;, &quot;root&quot;, &quot;password&quot;, &quot;mydb&quot;);</font></pre>
+<p>The connection code is a bit more sophisticated than MySQL's because our needs 
+  are more sophisticated. In ADODB, we use an object-oriented approach to managing 
+  the complexity of handling multiple databases. We have different classes to 
+  handle different databases. If you aren't familiar with object-oriented programing, 
+  don't worry -- the complexity is all hidden away in the<code> NewADOConnection()</code> 
+  function.</p>
+<p>To conserve memory, we only load the PHP code specific to the database you 
+  are connecting to. We do this by calling <code>NewADOConnection(databasedriver)</code>. 
+  Legal database drivers include <i>mysql, mssql, oracle, oci8, postgres, sybase, 
+  vfp, access, ibase </i>and many others.</p>
+<p>Then we create a new instance of the connection class by calling <code>NewADOConnection()</code>. 
+  Finally we connect to the database using <code>$db-&gt;Connect(). </code></p>
+<h3>Executing the SQL</h3>
+<p><code><font color="#663300">$result = $db-&gt;<b>Execute</b>(&quot;SELECT * 
+  FROM employees&quot;);<br>
+  if ($result === false) die(&quot;failed&quot;)</font></code><code><font color="#663300">;</font></code> 
+  <br>
+</p>
+<p>Sending the SQL statement to the server is straight forward. Execute() will 
+  return a recordset object on successful execution. You should check $result 
+  as we do above.
+<p>An issue that confuses beginners is the fact that we have two types of objects 
+  in ADODB, the connection object and the recordset object. When do we use each?
+<p>The connection object ($db) is responsible for connecting to the database, 
+  formatting your SQL and querying the database server. The recordset object ($result) 
+  is responsible for retrieving the results and formatting the reply as text or 
+  as an array.
+<p>The only thing I need to add is that ADODB provides several helper functions 
+  for making INSERT and UPDATE statements easier, which we will cover in the Advanced 
+  section. 
+<h3>Retrieving the Data<br>
+</h3>
+<pre><font color="#006666"><b>while</b> (!$result-&gt;EOF) &#123;
+   <b>for</b> ($i=0, $max=$result-&gt;<b>FieldCount</b>(); $i &lt; $max; $i++)
+	   <b>print</b> $result-&gt;fields[$i].' ';
+   $result-&gt;<b>MoveNext</b>();
+   <b>print</b> &quot;&lt;br&gt;\n&quot;;
+&#125;</font></pre>
+<p>The paradigm for getting the data is that it's like reading a file. For every 
+  line, we check first whether we have reached the end-of-file (EOF). While not 
+  end-of-file, loop through each field in the row. Then move to the next line 
+  (MoveNext) and repeat. 
+<p>The <code>$result-&gt;fields[]</code> array is generated by the PHP database 
+  extension. Some database extensions do not index the array by field name. 
+  To force indexing by name - that is associative arrays - 
+  use the $ADODB_FETCH_MODE global variable. 
+<pre>
+	$<b>ADODB_FETCH_MODE</b> = ADODB_FETCH_NUM;
+	$rs1 = $db->Execute('select * from table');
+	$<b>ADODB_FETCH_MODE</b> = ADODB_FETCH_ASSOC;
+	$rs2 = $db->Execute('select * from table');
+	print_r($rs1->fields); // shows <i>array([0]=>'v0',[1] =>'v1')</i>
+	print_r($rs2->fields); // shows <i>array(['col1']=>'v0',['col2'] =>'v1')</i>
+</pre>
+<p>
+As you can see in the above example, both recordsets store and use different fetch modes
+based on the $ADODB_FETCH_MODE setting when the recordset was created by Execute().</p>
+<h2>ADOConnection<a name="ADOConnection"></a></h2>
+<p>Object that performs the connection to the database, executes SQL statements 
+  and has a set of utility functions for standardising the format of SQL statements 
+  for issues such as concatenation and date formats.</p>
+  
+<h3>Other Useful Functions</h3>
+<p><code>$recordset-&gt;Move($pos)</code> scrolls to that particular row. ADODB supports forward 
+  scrolling for all databases. Some databases will not support backwards scrolling. 
+  This is normally not a problem as you can always cache records to simulate backwards 
+  scrolling. 
+<p><code>$recordset-&gt;RecordCount()</code> returns the number of records accessed by the 
+  SQL statement. Some databases will return -1 because it is not supported. 
+<p><code>$recordset-&gt;GetArray()</code> returns the result as an array. 
+<p><code>rs2html($recordset)</code> is a function that is generates a HTML table based on the 
+  $recordset passed to it. An example with the relevant lines in bold:
+<pre>   include('adodb.inc.php'); 
+   <b>include('tohtml.inc.php');</b> /* includes the rs2html function */
+   $conn = &amp;ADONewConnection('mysql'); 
+   $conn-&gt;PConnect('localhost','userid','password','database');
+   $rs = $conn-&gt;Execute('select * from table');
+  <b> rs2html($rs)</b>; /* recordset to html table */ </pre>
+<p>There are many other helper functions that are listed in the documentation available at <a href="http://php.weblogs.com/adodb_manual"></a><a href="http://php.weblogs.com/adodb_manual">http://php.weblogs.com/adodb_manual</a>. 
+<h2>Advanced Material</h2>
+<h3>Inserts and Updates </h3>
+<p>Let's say you want to insert the following data into a database. 
+<p><b>ID</b> = 3<br>
+  <b>TheDate</b>=mktime(0,0,0,8,31,2001) /* 31st August 2001 */<br>
+  <b>Note</b>= sugar why don't we call it off 
+<p>When you move to another database, your insert might no longer work.</p>
+<p>The first problem is that each database has a different default date format. 
+  MySQL expects YYYY-MM-DD format, while other databases have different defaults. 
+  ADODB has a function called DBDate() that addresses this issue by converting 
+  converting the date to the correct format.</p>
+<p>The next problem is that the <b>don't</b> in the Note needs to be quoted. In 
+  MySQL, we use <b>don\'t</b> but in some other databases (Sybase, Access, Microsoft 
+  SQL Server) we use <b>don''t. </b>The qstr() function addresses this issue.</p>
+<p>So how do we use the functions? Like this:</p>
+<pre>$sql = &quot;INSERT INTO table (id, thedate,note) values (&quot; 
+   . $<b>ID</b> . ','
+   . $db-&gt;DBDate($<b>TheDate</b>) .','
+   . $db-&gt;qstr($<b>Note</b>).&quot;)&quot;;
+$db-&gt;Execute($sql);</pre>
+<p>ADODB also supports <code>$connection-&gt;Affected_Rows()</code> (returns the 
+  number of rows affected by last update or delete) and <code>$recordset-&gt;Insert_ID()</code> 
+  (returns last autoincrement number generated by an insert statement). Be forewarned 
+  that not all databases support the two functions.<br>
+</p>
+<h3>MetaTypes</h3>
+<p>You can find out more information about each of the fields (I use the words 
+  fields and columns interchangebly) you are selecting by calling the recordset 
+  method <code>FetchField($fieldoffset)</code>. This will return an object with 
+  3 properties: name, type and max_length. 
+<pre>For example:</pre>
+<pre>$recordset = $conn-&gt;Execute(&quot;select adate from table&quot;);<br>$f0 = $recordset-&gt;FetchField(0);
+</pre>
+<p>Then <code>$f0-&gt;name</code> will hold <i>'adata'</i>, <code>$f0-&gt;type</code> 
+  will be set to '<i>date'</i>. If the max_length is unknown, it will be set to 
+  -1. 
+<p>One problem with handling different databases is that each database often calls 
+  the same type by a different name. For example a <i>timestamp</i> type is called 
+  <i>datetime</i> in one database and <i>time</i> in another. So ADODB has a special 
+  <code>MetaType($type, $max_length)</code> function that standardises the types 
+  to the following: 
+<p>C: character and varchar types<br>
+  X: text or long character (eg. more than 255 bytes wide).<br>
+  B: blob or binary image<br>
+  D: date<br>
+  T: timestamp<br>
+  L: logical (boolean)<br>
+  I: integer<br>
+  N: numeric (float, double, money) 
+<p>In the above date example, 
+<p><code>$recordset = $conn-&gt;Execute(&quot;select adate from table&quot;);<br>
+  $f0 = $recordset-&gt;FetchField(0);<br>
+  $type = $recordset-&gt;MetaType($f0-&gt;type, $f0-&gt;max_length);<br>
+  print $type; /* should print 'D'</code> */
+<p> 
+<p><b>Select Limit and Top Support</b> 
+<p>ADODB has a function called $connection->SelectLimit($sql,$nrows,$offset) that allows
+you to retrieve a subset of the recordset. This will take advantage of native
+SELECT TOP on Microsoft products and SELECT ... LIMIT with PostgreSQL and MySQL, and
+emulated if the database does not support it.
+<p><b>Caching Support</b> 
+<p>ADODB allows you to cache recordsets in your file system, and only requery the database
+server after a certain timeout period with $connection->CacheExecute($secs2cache,$sql) and 
+$connection->CacheSelectLimit($secs2cache,$sql,$nrows,$offset).
+<p><b>PHP4 Session Handler Support</b> 
+<p>ADODB also supports PHP4 session handlers. You can store your session variables 
+  in a database for true scalability using ADODB. For further information, visit 
+  <a href="http://php.weblogs.com/adodb-sessions"></a><a href="http://php.weblogs.com/adodb-sessions">http://php.weblogs.com/adodb-sessions</a>
+<h3>Commercial Use Encouraged</h3>
+<p>If you plan to write commercial PHP applications that you want to resell, you should consider ADODB. It has been released using the lesser GPL, which means you can legally include it in commercial applications, while keeping your code proprietary. Commercial use of ADODB is strongly encouraged! We are using it internally for this reason.<p>
+
+<h2>Conclusion</h2>
+<p>As a thank you for finishing this article, here are the complete lyrics for 
+  <i>let's call the whole thing off</i>.<br>
+  <br>
+<pre>
+   Refrain 
+<br>
+		You say eether and I say eyether, 
+		You say neether and I say nyther; 
+		Eether, eyether, neether, nyther - 
+		Let's call the whole thing off ! 
+<br>
+		You like potato and I like po-tah-to, 
+		You like tomato and I like to-mah-to; 
+		Potato, po-tah-to, tomato, to-mah-to - 
+		Let's call the whole thing off ! 
+<br>
+But oh, if we call the whole thing off, then we must part. 
+And oh, if we ever part, then that might break my heart. 
+<br>
+		So, if you like pajamas and I like pa-jah-mas, 
+		I'll wear pajamas and give up pa-jah-mas. 
+		For we know we 
+		Need each other, so we 
+		Better call the calling off off. 
+		Let's call the whole thing off ! 
+<br>
+   Second Refrain 
+<br>
+		You say laughter and I say lawfter, 
+		You say after and I say awfter; 
+		Laughter, lawfter, after, awfter - 
+		Let's call the whole thing off ! 
+<br>
+		You like vanilla and I like vanella, 
+		You, sa's'parilla and I sa's'parella; 
+		Vanilla, vanella, choc'late, strawb'ry - 
+		Let's call the whole thing off ! 
+<br>
+But oh, if we call the whole thing off, then we must part. 
+And oh, if we ever part, then that might break my heart. 
+<br>
+		So, if you go for oysters and I go for ersters, 
+		I'll order oysters and cancel the ersters. 
+		For we know we 
+		Need each other, so we 
+		Better call the calling off off. 
+		Let's call the whole thing off ! 
+  </pre>
+<p><font size=2>Song and lyrics by George and Ira Gershwin, introduced by Fred Astaire and Ginger Rogers
+in the film "Shall We Dance?"  </font><p>
+<p>
+(c)2001-2002 John Lim.
+
+</body>
+</html>
Index: /Dev/trunk/rdfapi/util/adodb/drivers/adodb-access.inc.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/drivers/adodb-access.inc.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/drivers/adodb-access.inc.php	(revision 12)
@@ -0,0 +1,87 @@
+<?php
+/* 
+V4.94 23 Jan 2007  (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence. See License.txt. 
+  Set tabs to 4 for best viewing.
+  
+  Latest version is available at http://adodb.sourceforge.net
+  
+  Microsoft Access data driver. Requires ODBC. Works only on MS Windows.
+*/
+if (!defined('_ADODB_ODBC_LAYER')) {
+	if (!defined('ADODB_DIR')) die();
+	
+	include(ADODB_DIR."/drivers/adodb-odbc.inc.php");
+}
+ if (!defined('_ADODB_ACCESS')) {
+ 	define('_ADODB_ACCESS',1);
+
+class  ADODB_access extends ADODB_odbc {	
+	var $databaseType = 'access';
+	var $hasTop = 'top';		// support mssql SELECT TOP 10 * FROM TABLE
+	var $fmtDate = "#Y-m-d#";
+	var $fmtTimeStamp = "#Y-m-d h:i:sA#"; // note not comma
+	var $_bindInputArray = false; // strangely enough, setting to true does not work reliably
+	var $sysDate = "FORMAT(NOW,'yyyy-mm-dd')";
+	var $sysTimeStamp = 'NOW';
+	var $hasTransactions = false;
+	var $upperCase = 'ucase';
+	
+	function ADODB_access()
+	{
+	global $ADODB_EXTENSION;
+	
+		$ADODB_EXTENSION = false;
+		$this->ADODB_odbc();
+	}
+	
+	function Time()
+	{
+		return time();
+	}
+	
+	function BeginTrans() { return false;}
+	
+	function IfNull( $field, $ifNull ) 
+	{
+		return " IIF(IsNull($field), $ifNull, $field) "; // if Access
+	}
+/*
+	function &MetaTables()
+	{
+	global $ADODB_FETCH_MODE;
+	
+		$savem = $ADODB_FETCH_MODE;
+		$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
+		$qid = odbc_tables($this->_connectionID);
+		$rs = new ADORecordSet_odbc($qid);
+		$ADODB_FETCH_MODE = $savem;
+		if (!$rs) return false;
+		
+		$rs->_has_stupid_odbc_fetch_api_change = $this->_has_stupid_odbc_fetch_api_change;
+		
+		$arr = &$rs->GetArray();
+		//print_pre($arr);
+		$arr2 = array();
+		for ($i=0; $i < sizeof($arr); $i++) {
+			if ($arr[$i][2] && $arr[$i][3] != 'SYSTEM TABLE')
+				$arr2[] = $arr[$i][2];
+		}
+		return $arr2;
+	}*/
+}
+
+ 
+class  ADORecordSet_access extends ADORecordSet_odbc {	
+	
+	var $databaseType = "access";		
+	
+	function ADORecordSet_access($id,$mode=false)
+	{
+		return $this->ADORecordSet_odbc($id,$mode);
+	}
+}// class
+} 
+?>
Index: /Dev/trunk/rdfapi/util/adodb/drivers/adodb-ado.inc.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/drivers/adodb-ado.inc.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/drivers/adodb-ado.inc.php	(revision 12)
@@ -0,0 +1,634 @@
+<?php
+/* 
+V4.94 23 Jan 2007  (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence. 
+Set tabs to 4 for best viewing.
+  
+  Latest version is available at http://adodb.sourceforge.net
+  
+	Microsoft ADO data driver. Requires ADO. Works only on MS Windows.
+*/
+
+// security - hide paths
+if (!defined('ADODB_DIR')) die();
+	
+define("_ADODB_ADO_LAYER", 1 );
+/*--------------------------------------------------------------------------------------
+--------------------------------------------------------------------------------------*/
+
+	
+class ADODB_ado extends ADOConnection {
+	var $databaseType = "ado";	
+	var $_bindInputArray = false;
+	var $fmtDate = "'Y-m-d'";
+	var $fmtTimeStamp = "'Y-m-d, h:i:sA'";
+	var $replaceQuote = "''"; // string to use to replace quotes
+	var $dataProvider = "ado";	
+	var $hasAffectedRows = true;
+	var $adoParameterType = 201; // 201 = long varchar, 203=long wide varchar, 205 = long varbinary
+	var $_affectedRows = false;
+	var $_thisTransactions;
+	var $_cursor_type = 3; // 3=adOpenStatic,0=adOpenForwardOnly,1=adOpenKeyset,2=adOpenDynamic
+	var $_cursor_location = 3; // 2=adUseServer, 3 = adUseClient;
+	var $_lock_type = -1;
+	var $_execute_option = -1;
+	var $poorAffectedRows = true; 
+	var $charPage;
+		
+	function ADODB_ado() 
+	{ 	
+		$this->_affectedRows = new VARIANT;
+	}
+
+	function ServerInfo()
+	{
+		if (!empty($this->_connectionID)) $desc = $this->_connectionID->provider;
+		return array('description' => $desc, 'version' => '');
+	}
+	
+	function _affectedrows()
+	{
+		if (PHP_VERSION >= 5) return $this->_affectedRows;
+		
+		return $this->_affectedRows->value;
+	}
+	
+	// you can also pass a connection string like this:
+	//
+	// $DB->Connect('USER ID=sa;PASSWORD=pwd;SERVER=mangrove;DATABASE=ai',false,false,'SQLOLEDB');
+	function _connect($argHostname, $argUsername, $argPassword, $argProvider= 'MSDASQL')
+	{
+		$u = 'UID';
+		$p = 'PWD';
+	
+		if (!empty($this->charPage))
+			$dbc = new COM('ADODB.Connection',null,$this->charPage);
+		else
+			$dbc = new COM('ADODB.Connection');
+			
+		if (! $dbc) return false;
+
+		/* special support if provider is mssql or access */
+		if ($argProvider=='mssql') {
+			$u = 'User Id';  //User parameter name for OLEDB
+			$p = 'Password'; 
+			$argProvider = "SQLOLEDB"; // SQL Server Provider
+			
+			// not yet
+			//if ($argDatabasename) $argHostname .= ";Initial Catalog=$argDatabasename";
+			
+			//use trusted conection for SQL if username not specified
+			if (!$argUsername) $argHostname .= ";Trusted_Connection=Yes";
+		} else if ($argProvider=='access')
+			$argProvider = "Microsoft.Jet.OLEDB.4.0"; // Microsoft Jet Provider
+		
+		if ($argProvider) $dbc->Provider = $argProvider;	
+		
+		if ($argUsername) $argHostname .= ";$u=$argUsername";
+		if ($argPassword)$argHostname .= ";$p=$argPassword";
+		
+		if ($this->debug) ADOConnection::outp( "Host=".$argHostname."<BR>\n version=$dbc->version");
+		// @ added below for php 4.0.1 and earlier
+		@$dbc->Open((string) $argHostname);
+		
+		$this->_connectionID = $dbc;
+		
+		$dbc->CursorLocation = $this->_cursor_location;
+		return  $dbc->State > 0;
+	}
+	
+	// returns true or false
+	function _pconnect($argHostname, $argUsername, $argPassword, $argProvider='MSDASQL')
+	{
+		return $this->_connect($argHostname,$argUsername,$argPassword,$argProvider);
+	}	
+	
+/*
+	adSchemaCatalogs	= 1,
+	adSchemaCharacterSets	= 2,
+	adSchemaCollations	= 3,
+	adSchemaColumns	= 4,
+	adSchemaCheckConstraints	= 5,
+	adSchemaConstraintColumnUsage	= 6,
+	adSchemaConstraintTableUsage	= 7,
+	adSchemaKeyColumnUsage	= 8,
+	adSchemaReferentialContraints	= 9,
+	adSchemaTableConstraints	= 10,
+	adSchemaColumnsDomainUsage	= 11,
+	adSchemaIndexes	= 12,
+	adSchemaColumnPrivileges	= 13,
+	adSchemaTablePrivileges	= 14,
+	adSchemaUsagePrivileges	= 15,
+	adSchemaProcedures	= 16,
+	adSchemaSchemata	= 17,
+	adSchemaSQLLanguages	= 18,
+	adSchemaStatistics	= 19,
+	adSchemaTables	= 20,
+	adSchemaTranslations	= 21,
+	adSchemaProviderTypes	= 22,
+	adSchemaViews	= 23,
+	adSchemaViewColumnUsage	= 24,
+	adSchemaViewTableUsage	= 25,
+	adSchemaProcedureParameters	= 26,
+	adSchemaForeignKeys	= 27,
+	adSchemaPrimaryKeys	= 28,
+	adSchemaProcedureColumns	= 29,
+	adSchemaDBInfoKeywords	= 30,
+	adSchemaDBInfoLiterals	= 31,
+	adSchemaCubes	= 32,
+	adSchemaDimensions	= 33,
+	adSchemaHierarchies	= 34,
+	adSchemaLevels	= 35,
+	adSchemaMeasures	= 36,
+	adSchemaProperties	= 37,
+	adSchemaMembers	= 38
+
+*/
+	
+	function &MetaTables()
+	{
+		$arr= array();
+		$dbc = $this->_connectionID;
+		
+		$adors=@$dbc->OpenSchema(20);//tables
+		if ($adors){
+			$f = $adors->Fields(2);//table/view name
+			$t = $adors->Fields(3);//table type
+			while (!$adors->EOF){
+				$tt=substr($t->value,0,6);
+				if ($tt!='SYSTEM' && $tt !='ACCESS')
+					$arr[]=$f->value;
+				//print $f->value . ' ' . $t->value.'<br>';
+				$adors->MoveNext();
+			}
+			$adors->Close();
+		}
+		
+		return $arr;
+	}
+	
+	function &MetaColumns($table)
+	{
+		$table = strtoupper($table);
+		$arr = array();
+		$dbc = $this->_connectionID;
+		
+		$adors=@$dbc->OpenSchema(4);//tables
+	
+		if ($adors){
+			$t = $adors->Fields(2);//table/view name
+			while (!$adors->EOF){
+				
+				
+				if (strtoupper($t->Value) == $table) {
+				
+					$fld = new ADOFieldObject();
+					$c = $adors->Fields(3);
+					$fld->name = $c->Value;
+					$fld->type = 'CHAR'; // cannot discover type in ADO!
+					$fld->max_length = -1;
+					$arr[strtoupper($fld->name)]=$fld;
+				}
+		
+				$adors->MoveNext();
+			}
+			$adors->Close();
+		}
+		$false = false;
+		return empty($arr) ? $false : $arr;
+	}
+	
+
+
+	
+	/* returns queryID or false */
+	function &_query($sql,$inputarr=false) 
+	{
+		
+		$dbc = $this->_connectionID;
+		$false = false;
+		
+	//	return rs	
+		if ($inputarr) {
+			
+			if (!empty($this->charPage))
+				$oCmd = new COM('ADODB.Command',null,$this->charPage);
+			else
+				$oCmd = new COM('ADODB.Command');
+			$oCmd->ActiveConnection = $dbc;
+			$oCmd->CommandText = $sql;
+			$oCmd->CommandType = 1;
+
+			foreach($inputarr as $val) {
+				// name, type, direction 1 = input, len,
+				$this->adoParameterType = 130;
+				$p = $oCmd->CreateParameter('name',$this->adoParameterType,1,strlen($val),$val);
+				//print $p->Type.' '.$p->value;
+				$oCmd->Parameters->Append($p);
+			}
+			$p = false;
+			$rs = $oCmd->Execute();
+			$e = $dbc->Errors;
+			if ($dbc->Errors->Count > 0) return $false;
+			return $rs;
+		}
+		
+		$rs = @$dbc->Execute($sql,$this->_affectedRows, $this->_execute_option);
+
+		if ($dbc->Errors->Count > 0) return $false;
+		if (! $rs) return $false;
+		
+		if ($rs->State == 0) {
+			$true = true;
+			return $true; // 0 = adStateClosed means no records returned
+		}
+		return $rs;
+	}
+
+	
+	function BeginTrans() 
+	{ 
+		if ($this->transOff) return true;
+		
+		if (isset($this->_thisTransactions))
+			if (!$this->_thisTransactions) return false;
+		else {
+			$o = $this->_connectionID->Properties("Transaction DDL");
+			$this->_thisTransactions = $o ? true : false;
+			if (!$o) return false;
+		}
+		@$this->_connectionID->BeginTrans();
+		$this->transCnt += 1;
+		return true;
+	}
+	
+	function CommitTrans($ok=true) 
+	{ 
+		if (!$ok) return $this->RollbackTrans();
+		if ($this->transOff) return true;
+		
+		@$this->_connectionID->CommitTrans();
+		if ($this->transCnt) @$this->transCnt -= 1;
+		return true;
+	}
+	function RollbackTrans() {
+		if ($this->transOff) return true;
+		@$this->_connectionID->RollbackTrans();
+		if ($this->transCnt) @$this->transCnt -= 1;
+		return true;
+	}
+	
+	/*	Returns: the last error message from previous database operation	*/	
+
+	function ErrorMsg() 
+	{
+		if (!$this->_connectionID) return "No connection established";
+		$errc = $this->_connectionID->Errors;
+		if (!$errc) return "No Errors object found";
+		if ($errc->Count == 0) return '';
+		$err = $errc->Item($errc->Count-1);
+		return $err->Description;
+	}
+	
+	function ErrorNo() 
+	{
+		$errc = $this->_connectionID->Errors;
+		if ($errc->Count == 0) return 0;
+		$err = $errc->Item($errc->Count-1);
+		return $err->NativeError;
+	}
+
+	// returns true or false
+	function _close()
+	{
+		if ($this->_connectionID) $this->_connectionID->Close();
+		$this->_connectionID = false;
+		return true;
+	}
+	
+	
+}
+	
+/*--------------------------------------------------------------------------------------
+	 Class Name: Recordset
+--------------------------------------------------------------------------------------*/
+
+class ADORecordSet_ado extends ADORecordSet {	
+	
+	var $bind = false;
+	var $databaseType = "ado";	
+	var $dataProvider = "ado";	
+	var $_tarr = false; // caches the types
+	var $_flds; // and field objects
+	var $canSeek = true;
+  	var $hideErrors = true;
+		  
+	function ADORecordSet_ado($id,$mode=false)
+	{
+		if ($mode === false) { 
+			global $ADODB_FETCH_MODE;
+			$mode = $ADODB_FETCH_MODE;
+		}
+		$this->fetchMode = $mode;
+		return $this->ADORecordSet($id,$mode);
+	}
+
+
+	// returns the field object
+	function &FetchField($fieldOffset = -1) {
+		$off=$fieldOffset+1; // offsets begin at 1
+		
+		$o= new ADOFieldObject();
+		$rs = $this->_queryID;
+		$f = $rs->Fields($fieldOffset);
+		$o->name = $f->Name;
+		$t = $f->Type;
+		$o->type = $this->MetaType($t);
+		$o->max_length = $f->DefinedSize;
+		$o->ado_type = $t;	
+
+		//print "off=$off name=$o->name type=$o->type len=$o->max_length<br>";
+		return $o;
+	}
+	
+	/* Use associative array to get fields array */
+	function Fields($colname)
+	{
+		if ($this->fetchMode & ADODB_FETCH_ASSOC) return $this->fields[$colname];
+		if (!$this->bind) {
+			$this->bind = array();
+			for ($i=0; $i < $this->_numOfFields; $i++) {
+				$o = $this->FetchField($i);
+				$this->bind[strtoupper($o->name)] = $i;
+			}
+		}
+		
+		 return $this->fields[$this->bind[strtoupper($colname)]];
+	}
+
+		
+	function _initrs()
+	{
+		$rs = $this->_queryID;
+		$this->_numOfRows = $rs->RecordCount;
+		
+		$f = $rs->Fields;
+		$this->_numOfFields = $f->Count;
+	}
+	
+	
+	 // should only be used to move forward as we normally use forward-only cursors
+	function _seek($row)
+	{
+	   $rs = $this->_queryID; 
+		// absoluteposition doesn't work -- my maths is wrong ?
+		//	$rs->AbsolutePosition->$row-2;
+		//	return true;
+		if ($this->_currentRow > $row) return false;
+		@$rs->Move((integer)$row - $this->_currentRow-1); //adBookmarkFirst
+		return true;
+	}
+	
+/*
+	OLEDB types
+	
+	 enum DBTYPEENUM
+	{	DBTYPE_EMPTY	= 0,
+	DBTYPE_NULL	= 1,
+	DBTYPE_I2	= 2,
+	DBTYPE_I4	= 3,
+	DBTYPE_R4	= 4,
+	DBTYPE_R8	= 5,
+	DBTYPE_CY	= 6,
+	DBTYPE_DATE	= 7,
+	DBTYPE_BSTR	= 8,
+	DBTYPE_IDISPATCH	= 9,
+	DBTYPE_ERROR	= 10,
+	DBTYPE_BOOL	= 11,
+	DBTYPE_VARIANT	= 12,
+	DBTYPE_IUNKNOWN	= 13,
+	DBTYPE_DECIMAL	= 14,
+	DBTYPE_UI1	= 17,
+	DBTYPE_ARRAY	= 0x2000,
+	DBTYPE_BYREF	= 0x4000,
+	DBTYPE_I1	= 16,
+	DBTYPE_UI2	= 18,
+	DBTYPE_UI4	= 19,
+	DBTYPE_I8	= 20,
+	DBTYPE_UI8	= 21,
+	DBTYPE_GUID	= 72,
+	DBTYPE_VECTOR	= 0x1000,
+	DBTYPE_RESERVED	= 0x8000,
+	DBTYPE_BYTES	= 128,
+	DBTYPE_STR	= 129,
+	DBTYPE_WSTR	= 130,
+	DBTYPE_NUMERIC	= 131,
+	DBTYPE_UDT	= 132,
+	DBTYPE_DBDATE	= 133,
+	DBTYPE_DBTIME	= 134,
+	DBTYPE_DBTIMESTAMP	= 135
+	
+	ADO Types
+	
+   	adEmpty	= 0,
+	adTinyInt	= 16,
+	adSmallInt	= 2,
+	adInteger	= 3,
+	adBigInt	= 20,
+	adUnsignedTinyInt	= 17,
+	adUnsignedSmallInt	= 18,
+	adUnsignedInt	= 19,
+	adUnsignedBigInt	= 21,
+	adSingle	= 4,
+	adDouble	= 5,
+	adCurrency	= 6,
+	adDecimal	= 14,
+	adNumeric	= 131,
+	adBoolean	= 11,
+	adError	= 10,
+	adUserDefined	= 132,
+	adVariant	= 12,
+	adIDispatch	= 9,
+	adIUnknown	= 13,	
+	adGUID	= 72,
+	adDate	= 7,
+	adDBDate	= 133,
+	adDBTime	= 134,
+	adDBTimeStamp	= 135,
+	adBSTR	= 8,
+	adChar	= 129,
+	adVarChar	= 200,
+	adLongVarChar	= 201,
+	adWChar	= 130,
+	adVarWChar	= 202,
+	adLongVarWChar	= 203,
+	adBinary	= 128,
+	adVarBinary	= 204,
+	adLongVarBinary	= 205,
+	adChapter	= 136,
+	adFileTime	= 64,
+	adDBFileTime	= 137,
+	adPropVariant	= 138,
+	adVarNumeric	= 139
+*/
+	function MetaType($t,$len=-1,$fieldobj=false)
+	{
+		if (is_object($t)) {
+			$fieldobj = $t;
+			$t = $fieldobj->type;
+			$len = $fieldobj->max_length;
+		}
+		
+		if (!is_numeric($t)) return $t;
+		
+		switch ($t) {
+		case 0:
+		case 12: // variant
+		case 8: // bstr
+		case 129: //char
+		case 130: //wc
+		case 200: // varc
+		case 202:// varWC
+		case 128: // bin
+		case 204: // varBin
+		case 72: // guid
+			if ($len <= $this->blobSize) return 'C';
+		
+		case 201:
+		case 203:
+			return 'X';
+		case 128:
+		case 204:
+		case 205:
+			 return 'B';
+		case 7:
+		case 133: return 'D';
+		
+		case 134:
+		case 135: return 'T';
+		
+		case 11: return 'L';
+		
+		case 16://	adTinyInt	= 16,
+		case 2://adSmallInt	= 2,
+		case 3://adInteger	= 3,
+		case 4://adBigInt	= 20,
+		case 17://adUnsignedTinyInt	= 17,
+		case 18://adUnsignedSmallInt	= 18,
+		case 19://adUnsignedInt	= 19,
+		case 20://adUnsignedBigInt	= 21,
+			return 'I';
+		default: return 'N';
+		}
+	}
+	
+	// time stamp not supported yet
+	function _fetch()
+	{	
+		$rs = $this->_queryID;
+		if (!$rs or $rs->EOF) {
+			$this->fields = false;
+			return false;
+		}
+		$this->fields = array();
+	
+		if (!$this->_tarr) {
+			$tarr = array();
+			$flds = array();
+			for ($i=0,$max = $this->_numOfFields; $i < $max; $i++) {
+				$f = $rs->Fields($i);
+				$flds[] = $f;
+				$tarr[] = $f->Type;
+			}
+			// bind types and flds only once
+			$this->_tarr = $tarr; 
+			$this->_flds = $flds;
+		}
+		$t = reset($this->_tarr);
+		$f = reset($this->_flds);
+		
+		if ($this->hideErrors)  $olde = error_reporting(E_ERROR|E_CORE_ERROR);// sometimes $f->value be null
+		for ($i=0,$max = $this->_numOfFields; $i < $max; $i++) {
+			//echo "<p>",$t,' ';var_dump($f->value); echo '</p>';
+			switch($t) {
+			case 135: // timestamp
+				if (!strlen((string)$f->value)) $this->fields[] = false;
+				else {
+					if (!is_numeric($f->value)) # $val = variant_date_to_timestamp($f->value);
+						// VT_DATE stores dates as (float) fractional days since 1899/12/30 00:00:00
+						$val=(float) variant_cast($f->value,VT_R8)*3600*24-2209161600;
+					else 
+						$val = $f->value;
+					$this->fields[] = adodb_date('Y-m-d H:i:s',$val);
+				}
+				break;			
+			case 133:// A date value (yyyymmdd) 
+				if ($val = $f->value) {
+					$this->fields[] = substr($val,0,4).'-'.substr($val,4,2).'-'.substr($val,6,2);
+				} else
+					$this->fields[] = false;
+				break;
+			case 7: // adDate
+				if (!strlen((string)$f->value)) $this->fields[] = false;
+				else {
+					if (!is_numeric($f->value)) $val = variant_date_to_timestamp($f->value);
+					else $val = $f->value;
+					
+					if (($val % 86400) == 0) $this->fields[] = adodb_date('Y-m-d',$val);
+					else $this->fields[] = adodb_date('Y-m-d H:i:s',$val);
+				}
+				break;
+			case 1: // null
+				$this->fields[] = false;
+				break;
+			case 6: // currency is not supported properly;
+				ADOConnection::outp( '<b>'.$f->Name.': currency type not supported by PHP</b>');
+				$this->fields[] = (float) $f->value;
+				break;
+			default:
+				$this->fields[] = $f->value; 
+				break;
+			}
+			//print " $f->value $t, ";
+			$f = next($this->_flds);
+			$t = next($this->_tarr);
+		} // for
+		if ($this->hideErrors) error_reporting($olde);
+		@$rs->MoveNext(); // @ needed for some versions of PHP!
+		
+		if ($this->fetchMode & ADODB_FETCH_ASSOC) {
+			$this->fields = &$this->GetRowAssoc(ADODB_ASSOC_CASE);
+		}
+		return true;
+	}
+	
+		function NextRecordSet()
+		{
+			$rs = $this->_queryID;
+			$this->_queryID = $rs->NextRecordSet();
+			//$this->_queryID = $this->_QueryId->NextRecordSet();
+			if ($this->_queryID == null) return false;
+			
+			$this->_currentRow = -1;
+			$this->_currentPage = -1;
+			$this->bind = false;
+			$this->fields = false;
+			$this->_flds = false;
+			$this->_tarr = false;
+			
+			$this->_inited = false;
+			$this->Init();
+			return true;
+		}
+
+	function _close() {
+		$this->_flds = false;
+		@$this->_queryID->Close();// by Pete Dishman (peterd@telephonetics.co.uk)
+		$this->_queryID = false;	
+	}
+
+}
+
+?>
Index: /Dev/trunk/rdfapi/util/adodb/drivers/adodb-ado5.inc.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/drivers/adodb-ado5.inc.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/drivers/adodb-ado5.inc.php	(revision 12)
@@ -0,0 +1,668 @@
+<?php
+/* 
+V4.94 23 Jan 2007  (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence. 
+Set tabs to 4 for best viewing.
+  
+  Latest version is available at http://adodb.sourceforge.net
+  
+	Microsoft ADO data driver. Requires ADO. Works only on MS Windows. PHP5 compat version.
+*/
+
+// security - hide paths
+if (!defined('ADODB_DIR')) die();
+	
+define("_ADODB_ADO_LAYER", 1 );
+/*--------------------------------------------------------------------------------------
+--------------------------------------------------------------------------------------*/
+
+	
+class ADODB_ado extends ADOConnection {
+	var $databaseType = "ado";	
+	var $_bindInputArray = false;
+	var $fmtDate = "'Y-m-d'";
+	var $fmtTimeStamp = "'Y-m-d, h:i:sA'";
+	var $replaceQuote = "''"; // string to use to replace quotes
+	var $dataProvider = "ado";	
+	var $hasAffectedRows = true;
+	var $adoParameterType = 201; // 201 = long varchar, 203=long wide varchar, 205 = long varbinary
+	var $_affectedRows = false;
+	var $_thisTransactions;
+	var $_cursor_type = 3; // 3=adOpenStatic,0=adOpenForwardOnly,1=adOpenKeyset,2=adOpenDynamic
+	var $_cursor_location = 3; // 2=adUseServer, 3 = adUseClient;
+	var $_lock_type = -1;
+	var $_execute_option = -1;
+	var $poorAffectedRows = true; 
+	var $charPage;
+		
+	function ADODB_ado() 
+	{ 	
+		$this->_affectedRows = new VARIANT;
+	}
+
+	function ServerInfo()
+	{
+		if (!empty($this->_connectionID)) $desc = $this->_connectionID->provider;
+		return array('description' => $desc, 'version' => '');
+	}
+	
+	function _affectedrows()
+	{
+		if (PHP_VERSION >= 5) return $this->_affectedRows;
+		
+		return $this->_affectedRows->value;
+	}
+	
+	// you can also pass a connection string like this:
+	//
+	// $DB->Connect('USER ID=sa;PASSWORD=pwd;SERVER=mangrove;DATABASE=ai',false,false,'SQLOLEDB');
+	function _connect($argHostname, $argUsername, $argPassword,$argDBorProvider, $argProvider= '')
+	{
+	// two modes
+	//	-	if $argProvider is empty, we assume that $argDBorProvider holds provider -- this is for backward compat
+	//	- 	if $argProvider is not empty, then $argDBorProvider holds db
+	
+		
+		 if ($argProvider) {
+		 	$argDatabasename = $argDBorProvider;
+		 } else {
+		 	$argDatabasename = '';
+		 	if ($argDBorProvider) $argProvider = $argDBorProvider;
+			else $argProvider = 'MSDASQL';
+		}
+		
+		
+		try {
+		$u = 'UID';
+		$p = 'PWD';
+	
+		if (!empty($this->charPage))
+			$dbc = new COM('ADODB.Connection',null,$this->charPage);
+		else
+			$dbc = new COM('ADODB.Connection');
+			
+		if (! $dbc) return false;
+
+		/* special support if provider is mssql or access */
+		if ($argProvider=='mssql') {
+			$u = 'User Id';  //User parameter name for OLEDB
+			$p = 'Password'; 
+			$argProvider = "SQLOLEDB"; // SQL Server Provider
+			
+			// not yet
+			//if ($argDatabasename) $argHostname .= ";Initial Catalog=$argDatabasename";
+			
+			//use trusted conection for SQL if username not specified
+			if (!$argUsername) $argHostname .= ";Trusted_Connection=Yes";
+		} else if ($argProvider=='access')
+			$argProvider = "Microsoft.Jet.OLEDB.4.0"; // Microsoft Jet Provider
+		
+		if ($argProvider) $dbc->Provider = $argProvider;	
+
+		if ($argProvider) $argHostname = "PROVIDER=$argProvider;DRIVER={SQL Server};SERVER=$argHostname";	
+		
+
+		if ($argDatabasename) $argHostname .= ";DATABASE=$argDatabasename";		
+		if ($argUsername) $argHostname .= ";$u=$argUsername";
+		if ($argPassword)$argHostname .= ";$p=$argPassword";
+		
+		if ($this->debug) ADOConnection::outp( "Host=".$argHostname."<BR>\n version=$dbc->version");
+		// @ added below for php 4.0.1 and earlier
+		@$dbc->Open((string) $argHostname);
+		
+		$this->_connectionID = $dbc;
+		
+		$dbc->CursorLocation = $this->_cursor_location;
+		return  $dbc->State > 0;
+		} catch (exception $e) {
+		}
+		
+		return false;
+	}
+	
+	// returns true or false
+	function _pconnect($argHostname, $argUsername, $argPassword, $argProvider='MSDASQL')
+	{
+		return $this->_connect($argHostname,$argUsername,$argPassword,$argProvider);
+	}	
+	
+/*
+	adSchemaCatalogs	= 1,
+	adSchemaCharacterSets	= 2,
+	adSchemaCollations	= 3,
+	adSchemaColumns	= 4,
+	adSchemaCheckConstraints	= 5,
+	adSchemaConstraintColumnUsage	= 6,
+	adSchemaConstraintTableUsage	= 7,
+	adSchemaKeyColumnUsage	= 8,
+	adSchemaReferentialContraints	= 9,
+	adSchemaTableConstraints	= 10,
+	adSchemaColumnsDomainUsage	= 11,
+	adSchemaIndexes	= 12,
+	adSchemaColumnPrivileges	= 13,
+	adSchemaTablePrivileges	= 14,
+	adSchemaUsagePrivileges	= 15,
+	adSchemaProcedures	= 16,
+	adSchemaSchemata	= 17,
+	adSchemaSQLLanguages	= 18,
+	adSchemaStatistics	= 19,
+	adSchemaTables	= 20,
+	adSchemaTranslations	= 21,
+	adSchemaProviderTypes	= 22,
+	adSchemaViews	= 23,
+	adSchemaViewColumnUsage	= 24,
+	adSchemaViewTableUsage	= 25,
+	adSchemaProcedureParameters	= 26,
+	adSchemaForeignKeys	= 27,
+	adSchemaPrimaryKeys	= 28,
+	adSchemaProcedureColumns	= 29,
+	adSchemaDBInfoKeywords	= 30,
+	adSchemaDBInfoLiterals	= 31,
+	adSchemaCubes	= 32,
+	adSchemaDimensions	= 33,
+	adSchemaHierarchies	= 34,
+	adSchemaLevels	= 35,
+	adSchemaMeasures	= 36,
+	adSchemaProperties	= 37,
+	adSchemaMembers	= 38
+
+*/
+	
+	function &MetaTables()
+	{
+		$arr= array();
+		$dbc = $this->_connectionID;
+		
+		$adors=@$dbc->OpenSchema(20);//tables
+		if ($adors){
+			$f = $adors->Fields(2);//table/view name
+			$t = $adors->Fields(3);//table type
+			while (!$adors->EOF){
+				$tt=substr($t->value,0,6);
+				if ($tt!='SYSTEM' && $tt !='ACCESS')
+					$arr[]=$f->value;
+				//print $f->value . ' ' . $t->value.'<br>';
+				$adors->MoveNext();
+			}
+			$adors->Close();
+		}
+		
+		return $arr;
+	}
+	
+	function &MetaColumns($table)
+	{
+		$table = strtoupper($table);
+		$arr= array();
+		$dbc = $this->_connectionID;
+		
+		$adors=@$dbc->OpenSchema(4);//tables
+	
+		if ($adors){
+			$t = $adors->Fields(2);//table/view name
+			while (!$adors->EOF){
+				
+				
+				if (strtoupper($t->Value) == $table) {
+				
+					$fld = new ADOFieldObject();
+					$c = $adors->Fields(3);
+					$fld->name = $c->Value;
+					$fld->type = 'CHAR'; // cannot discover type in ADO!
+					$fld->max_length = -1;
+					$arr[strtoupper($fld->name)]=$fld;
+				}
+		
+				$adors->MoveNext();
+			}
+			$adors->Close();
+		}
+		
+		return $arr;
+	}
+	
+	/* returns queryID or false */
+	function &_query($sql,$inputarr=false) 
+	{
+		try { // In PHP5, all COM errors are exceptions, so to maintain old behaviour...
+		
+		$dbc = $this->_connectionID;
+		
+	//	return rs	
+	
+		$false = false;
+		
+		if ($inputarr) {
+			
+			if (!empty($this->charPage))
+				$oCmd = new COM('ADODB.Command',null,$this->charPage);
+			else
+				$oCmd = new COM('ADODB.Command');
+			$oCmd->ActiveConnection = $dbc;
+			$oCmd->CommandText = $sql;
+			$oCmd->CommandType = 1;
+
+			foreach($inputarr as $val) {
+				// name, type, direction 1 = input, len,
+				$this->adoParameterType = 130;
+				$p = $oCmd->CreateParameter('name',$this->adoParameterType,1,strlen($val),$val);
+				//print $p->Type.' '.$p->value;
+				$oCmd->Parameters->Append($p);
+			}
+			$p = false;
+			$rs = $oCmd->Execute();
+			$e = $dbc->Errors;
+			if ($dbc->Errors->Count > 0) return $false;
+			return $rs;
+		}
+		
+		$rs = @$dbc->Execute($sql,$this->_affectedRows, $this->_execute_option);
+			
+		if ($dbc->Errors->Count > 0) return $false;
+		if (! $rs) return $false;
+		
+		if ($rs->State == 0) {
+			$true = true;
+			return $true; // 0 = adStateClosed means no records returned
+		}
+		return $rs;
+		
+		} catch (exception $e) {
+			
+		}
+		return $false;
+	}
+
+	
+	function BeginTrans() 
+	{ 
+		if ($this->transOff) return true;
+		
+		if (isset($this->_thisTransactions))
+			if (!$this->_thisTransactions) return false;
+		else {
+			$o = $this->_connectionID->Properties("Transaction DDL");
+			$this->_thisTransactions = $o ? true : false;
+			if (!$o) return false;
+		}
+		@$this->_connectionID->BeginTrans();
+		$this->transCnt += 1;
+		return true;
+	}
+	function CommitTrans($ok=true) 
+	{ 
+		if (!$ok) return $this->RollbackTrans();
+		if ($this->transOff) return true;
+		
+		@$this->_connectionID->CommitTrans();
+		if ($this->transCnt) @$this->transCnt -= 1;
+		return true;
+	}
+	function RollbackTrans() {
+		if ($this->transOff) return true;
+		@$this->_connectionID->RollbackTrans();
+		if ($this->transCnt) @$this->transCnt -= 1;
+		return true;
+	}
+	
+	/*	Returns: the last error message from previous database operation	*/	
+
+	function ErrorMsg() 
+	{
+		if (!$this->_connectionID) return "No connection established";
+		$errmsg = '';
+		
+		try {
+			$errc = $this->_connectionID->Errors;
+			if (!$errc) return "No Errors object found";
+			if ($errc->Count == 0) return '';
+			$err = $errc->Item($errc->Count-1);
+			$errmsg = $err->Description;
+		}catch(exception $e) {
+		}
+		return $errmsg;
+	}
+	
+	function ErrorNo() 
+	{
+		$errc = $this->_connectionID->Errors;
+		if ($errc->Count == 0) return 0;
+		$err = $errc->Item($errc->Count-1);
+		return $err->NativeError;
+	}
+
+	// returns true or false
+	function _close()
+	{
+		if ($this->_connectionID) $this->_connectionID->Close();
+		$this->_connectionID = false;
+		return true;
+	}
+	
+	
+}
+	
+/*--------------------------------------------------------------------------------------
+	 Class Name: Recordset
+--------------------------------------------------------------------------------------*/
+
+class ADORecordSet_ado extends ADORecordSet {	
+	
+	var $bind = false;
+	var $databaseType = "ado";	
+	var $dataProvider = "ado";	
+	var $_tarr = false; // caches the types
+	var $_flds; // and field objects
+	var $canSeek = true;
+  	var $hideErrors = true;
+		  
+	function ADORecordSet_ado($id,$mode=false)
+	{
+		if ($mode === false) { 
+			global $ADODB_FETCH_MODE;
+			$mode = $ADODB_FETCH_MODE;
+		}
+		$this->fetchMode = $mode;
+		return $this->ADORecordSet($id,$mode);
+	}
+
+
+	// returns the field object
+	function &FetchField($fieldOffset = -1) {
+		$off=$fieldOffset+1; // offsets begin at 1
+		
+		$o= new ADOFieldObject();
+		$rs = $this->_queryID;
+		$f = $rs->Fields($fieldOffset);
+		$o->name = $f->Name;
+		$t = $f->Type;
+		$o->type = $this->MetaType($t);
+		$o->max_length = $f->DefinedSize;
+		$o->ado_type = $t;
+		
+
+		//print "off=$off name=$o->name type=$o->type len=$o->max_length<br>";
+		return $o;
+	}
+	
+	/* Use associative array to get fields array */
+	function Fields($colname)
+	{
+		if ($this->fetchMode & ADODB_FETCH_ASSOC) return $this->fields[$colname];
+		if (!$this->bind) {
+			$this->bind = array();
+			for ($i=0; $i < $this->_numOfFields; $i++) {
+				$o = $this->FetchField($i);
+				$this->bind[strtoupper($o->name)] = $i;
+			}
+		}
+		
+		 return $this->fields[$this->bind[strtoupper($colname)]];
+	}
+
+		
+	function _initrs()
+	{
+		$rs = $this->_queryID;
+		$this->_numOfRows = $rs->RecordCount;
+		
+		$f = $rs->Fields;
+		$this->_numOfFields = $f->Count;
+	}
+	
+	
+	 // should only be used to move forward as we normally use forward-only cursors
+	function _seek($row)
+	{
+	   $rs = $this->_queryID; 
+		// absoluteposition doesn't work -- my maths is wrong ?
+		//	$rs->AbsolutePosition->$row-2;
+		//	return true;
+		if ($this->_currentRow > $row) return false;
+		@$rs->Move((integer)$row - $this->_currentRow-1); //adBookmarkFirst
+		return true;
+	}
+	
+/*
+	OLEDB types
+	
+	 enum DBTYPEENUM
+	{	DBTYPE_EMPTY	= 0,
+	DBTYPE_NULL	= 1,
+	DBTYPE_I2	= 2,
+	DBTYPE_I4	= 3,
+	DBTYPE_R4	= 4,
+	DBTYPE_R8	= 5,
+	DBTYPE_CY	= 6,
+	DBTYPE_DATE	= 7,
+	DBTYPE_BSTR	= 8,
+	DBTYPE_IDISPATCH	= 9,
+	DBTYPE_ERROR	= 10,
+	DBTYPE_BOOL	= 11,
+	DBTYPE_VARIANT	= 12,
+	DBTYPE_IUNKNOWN	= 13,
+	DBTYPE_DECIMAL	= 14,
+	DBTYPE_UI1	= 17,
+	DBTYPE_ARRAY	= 0x2000,
+	DBTYPE_BYREF	= 0x4000,
+	DBTYPE_I1	= 16,
+	DBTYPE_UI2	= 18,
+	DBTYPE_UI4	= 19,
+	DBTYPE_I8	= 20,
+	DBTYPE_UI8	= 21,
+	DBTYPE_GUID	= 72,
+	DBTYPE_VECTOR	= 0x1000,
+	DBTYPE_RESERVED	= 0x8000,
+	DBTYPE_BYTES	= 128,
+	DBTYPE_STR	= 129,
+	DBTYPE_WSTR	= 130,
+	DBTYPE_NUMERIC	= 131,
+	DBTYPE_UDT	= 132,
+	DBTYPE_DBDATE	= 133,
+	DBTYPE_DBTIME	= 134,
+	DBTYPE_DBTIMESTAMP	= 135
+	
+	ADO Types
+	
+   	adEmpty	= 0,
+	adTinyInt	= 16,
+	adSmallInt	= 2,
+	adInteger	= 3,
+	adBigInt	= 20,
+	adUnsignedTinyInt	= 17,
+	adUnsignedSmallInt	= 18,
+	adUnsignedInt	= 19,
+	adUnsignedBigInt	= 21,
+	adSingle	= 4,
+	adDouble	= 5,
+	adCurrency	= 6,
+	adDecimal	= 14,
+	adNumeric	= 131,
+	adBoolean	= 11,
+	adError	= 10,
+	adUserDefined	= 132,
+	adVariant	= 12,
+	adIDispatch	= 9,
+	adIUnknown	= 13,	
+	adGUID	= 72,
+	adDate	= 7,
+	adDBDate	= 133,
+	adDBTime	= 134,
+	adDBTimeStamp	= 135,
+	adBSTR	= 8,
+	adChar	= 129,
+	adVarChar	= 200,
+	adLongVarChar	= 201,
+	adWChar	= 130,
+	adVarWChar	= 202,
+	adLongVarWChar	= 203,
+	adBinary	= 128,
+	adVarBinary	= 204,
+	adLongVarBinary	= 205,
+	adChapter	= 136,
+	adFileTime	= 64,
+	adDBFileTime	= 137,
+	adPropVariant	= 138,
+	adVarNumeric	= 139
+*/
+	function MetaType($t,$len=-1,$fieldobj=false)
+	{
+		if (is_object($t)) {
+			$fieldobj = $t;
+			$t = $fieldobj->type;
+			$len = $fieldobj->max_length;
+		}
+		
+		if (!is_numeric($t)) return $t;
+		
+		switch ($t) {
+		case 0:
+		case 12: // variant
+		case 8: // bstr
+		case 129: //char
+		case 130: //wc
+		case 200: // varc
+		case 202:// varWC
+		case 128: // bin
+		case 204: // varBin
+		case 72: // guid
+			if ($len <= $this->blobSize) return 'C';
+		
+		case 201:
+		case 203:
+			return 'X';
+		case 128:
+		case 204:
+		case 205:
+			 return 'B';
+		case 7:
+		case 133: return 'D';
+		
+		case 134:
+		case 135: return 'T';
+		
+		case 11: return 'L';
+		
+		case 16://	adTinyInt	= 16,
+		case 2://adSmallInt	= 2,
+		case 3://adInteger	= 3,
+		case 4://adBigInt	= 20,
+		case 17://adUnsignedTinyInt	= 17,
+		case 18://adUnsignedSmallInt	= 18,
+		case 19://adUnsignedInt	= 19,
+		case 20://adUnsignedBigInt	= 21,
+			return 'I';
+		default: return 'N';
+		}
+	}
+	
+	// time stamp not supported yet
+	function _fetch()
+	{	
+		$rs = $this->_queryID;
+		if (!$rs or $rs->EOF) {
+			$this->fields = false;
+			return false;
+		}
+		$this->fields = array();
+	
+		if (!$this->_tarr) {
+			$tarr = array();
+			$flds = array();
+			for ($i=0,$max = $this->_numOfFields; $i < $max; $i++) {
+				$f = $rs->Fields($i);
+				$flds[] = $f;
+				$tarr[] = $f->Type;
+			}
+			// bind types and flds only once
+			$this->_tarr = $tarr; 
+			$this->_flds = $flds;
+		}
+		$t = reset($this->_tarr);
+		$f = reset($this->_flds);
+		
+		if ($this->hideErrors)  $olde = error_reporting(E_ERROR|E_CORE_ERROR);// sometimes $f->value be null
+		for ($i=0,$max = $this->_numOfFields; $i < $max; $i++) {
+			//echo "<p>",$t,' ';var_dump($f->value); echo '</p>';
+			switch($t) {
+			case 135: // timestamp
+				if (!strlen((string)$f->value)) $this->fields[] = false;
+				else {
+					if (!is_numeric($f->value)) # $val = variant_date_to_timestamp($f->value);
+						// VT_DATE stores dates as (float) fractional days since 1899/12/30 00:00:00
+						$val= (float) variant_cast($f->value,VT_R8)*3600*24-2209161600;
+					else 
+						$val = $f->value;
+					$this->fields[] = adodb_date('Y-m-d H:i:s',$val);
+				}
+				break;			
+			case 133:// A date value (yyyymmdd) 
+				if ($val = $f->value) {
+					$this->fields[] = substr($val,0,4).'-'.substr($val,4,2).'-'.substr($val,6,2);
+				} else
+					$this->fields[] = false;
+				break;
+			case 7: // adDate
+				if (!strlen((string)$f->value)) $this->fields[] = false;
+				else {
+					if (!is_numeric($f->value)) $val = variant_date_to_timestamp($f->value);
+					else $val = $f->value;
+					
+					if (($val % 86400) == 0) $this->fields[] = adodb_date('Y-m-d',$val);
+					else $this->fields[] = adodb_date('Y-m-d H:i:s',$val);
+				}
+				break;
+			case 1: // null
+				$this->fields[] = false;
+				break;
+			case 6: // currency is not supported properly;
+				ADOConnection::outp( '<b>'.$f->Name.': currency type not supported by PHP</b>');
+				$this->fields[] = (float) $f->value;
+				break;
+			default:
+				$this->fields[] = $f->value; 
+				break;
+			}
+			//print " $f->value $t, ";
+			$f = next($this->_flds);
+			$t = next($this->_tarr);
+		} // for
+		if ($this->hideErrors) error_reporting($olde);
+		@$rs->MoveNext(); // @ needed for some versions of PHP!
+		
+		if ($this->fetchMode & ADODB_FETCH_ASSOC) {
+			$this->fields = &$this->GetRowAssoc(ADODB_ASSOC_CASE);
+		}
+		return true;
+	}
+	
+		function NextRecordSet()
+		{
+			$rs = $this->_queryID;
+			$this->_queryID = $rs->NextRecordSet();
+			//$this->_queryID = $this->_QueryId->NextRecordSet();
+			if ($this->_queryID == null) return false;
+			
+			$this->_currentRow = -1;
+			$this->_currentPage = -1;
+			$this->bind = false;
+			$this->fields = false;
+			$this->_flds = false;
+			$this->_tarr = false;
+			
+			$this->_inited = false;
+			$this->Init();
+			return true;
+		}
+
+	function _close() {
+		$this->_flds = false;
+		@$this->_queryID->Close();// by Pete Dishman (peterd@telephonetics.co.uk)
+		$this->_queryID = false;	
+	}
+
+}
+
+?>
Index: /Dev/trunk/rdfapi/util/adodb/drivers/adodb-ado_access.inc.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/drivers/adodb-ado_access.inc.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/drivers/adodb-ado_access.inc.php	(revision 12)
@@ -0,0 +1,55 @@
+<?php
+/* 
+V4.94 23 Jan 2007  (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
+Released under both BSD license and Lesser GPL library license. 
+Whenever there is any discrepancy between the two licenses, 
+the BSD license will take precedence. See License.txt. 
+Set tabs to 4 for best viewing.
+  
+  Latest version is available at http://adodb.sourceforge.net
+  
+	Microsoft Access ADO data driver. Requires ADO and ODBC. Works only on MS Windows.
+*/
+
+// security - hide paths
+if (!defined('ADODB_DIR')) die();
+
+if (!defined('_ADODB_ADO_LAYER')) {
+	if (PHP_VERSION >= 5) include(ADODB_DIR."/drivers/adodb-ado5.inc.php");
+	else include(ADODB_DIR."/drivers/adodb-ado.inc.php");
+}
+
+class  ADODB_ado_access extends ADODB_ado {	
+	var $databaseType = 'ado_access';
+	var $hasTop = 'top';		// support mssql SELECT TOP 10 * FROM TABLE
+	var $fmtDate = "#Y-m-d#";
+	var $fmtTimeStamp = "#Y-m-d h:i:sA#";// note no comma
+	var $sysDate = "FORMAT(NOW,'yyyy-mm-dd')";
+	var $sysTimeStamp = 'NOW';
+	var $hasTransactions = false;
+	var $upperCase = 'ucase';
+	
+	function ADODB_ado_access()
+	{
+		$this->ADODB_ado();
+	}
+	
+	function BeginTrans() { return false;}
+	
+	function CommitTrans() { return false;}
+	
+	function RollbackTrans() { return false;}
+
+}
+
+ 
+class  ADORecordSet_ado_access extends ADORecordSet_ado {	
+	
+	var $databaseType = "ado_access";		
+	
+	function ADORecordSet_ado_access($id,$mode=false)
+	{
+		return $this->ADORecordSet_ado($id,$mode);
+	}
+}
+?>
Index: /Dev/trunk/rdfapi/util/adodb/drivers/adodb-ado_mssql.inc.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/drivers/adodb-ado_mssql.inc.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/drivers/adodb-ado_mssql.inc.php	(revision 12)
@@ -0,0 +1,154 @@
+<?php
+/* 
+V4.94 23 Jan 2007  (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence. 
+Set tabs to 4 for best viewing.
+  
+  Latest version is available at http://adodb.sourceforge.net
+  
+  Microsoft SQL Server ADO data driver. Requires ADO and MSSQL client. 
+  Works only on MS Windows.
+  
+  Warning: Some versions of PHP (esp PHP4) leak memory when ADO/COM is used. 
+  Please check http://bugs.php.net/ for more info.
+*/
+
+// security - hide paths
+if (!defined('ADODB_DIR')) die();
+
+if (!defined('_ADODB_ADO_LAYER')) {
+	if (PHP_VERSION >= 5) include(ADODB_DIR."/drivers/adodb-ado5.inc.php");
+	else include(ADODB_DIR."/drivers/adodb-ado.inc.php");
+}
+
+
+class  ADODB_ado_mssql extends ADODB_ado {        
+	var $databaseType = 'ado_mssql';
+	var $hasTop = 'top';
+	var $hasInsertID = true;
+	var $sysDate = 'convert(datetime,convert(char,GetDate(),102),102)';
+	var $sysTimeStamp = 'GetDate()';
+	var $leftOuter = '*=';
+	var $rightOuter = '=*';
+	var $ansiOuter = true; // for mssql7 or later
+	var $substr = "substring";
+	var $length = 'len';
+	var $_dropSeqSQL = "drop table %s";
+	
+	//var $_inTransaction = 1; // always open recordsets, so no transaction problems.
+	
+	function ADODB_ado_mssql()
+	{
+	        $this->ADODB_ado();
+	}
+	
+	function _insertid()
+	{
+	        return $this->GetOne('select @@identity');
+	}
+	
+	function _affectedrows()
+	{
+	        return $this->GetOne('select @@rowcount');
+	}
+	
+	function SetTransactionMode( $transaction_mode ) 
+	{
+		$this->_transmode  = $transaction_mode;
+		if (empty($transaction_mode)) {
+			$this->Execute('SET TRANSACTION ISOLATION LEVEL READ COMMITTED');
+			return;
+		}
+		if (!stristr($transaction_mode,'isolation')) $transaction_mode = 'ISOLATION LEVEL '.$transaction_mode;
+		$this->Execute("SET TRANSACTION ".$transaction_mode);
+	}
+	
+	function qstr($s,$magic_quotes=false)
+	{
+		$s = ADOConnection::qstr($s, $magic_quotes);
+		return str_replace("\0", "\\\\000", $s);
+	}
+	
+	function MetaColumns($table)
+	{
+        $table = strtoupper($table);
+        $arr= array();
+        $dbc = $this->_connectionID;
+        
+        $osoptions = array();
+        $osoptions[0] = null;
+        $osoptions[1] = null;
+        $osoptions[2] = $table;
+        $osoptions[3] = null;
+        
+        $adors=@$dbc->OpenSchema(4, $osoptions);//tables
+
+        if ($adors){
+                while (!$adors->EOF){
+                        $fld = new ADOFieldObject();
+                        $c = $adors->Fields(3);
+                        $fld->name = $c->Value;
+                        $fld->type = 'CHAR'; // cannot discover type in ADO!
+                        $fld->max_length = -1;
+                        $arr[strtoupper($fld->name)]=$fld;
+        
+                        $adors->MoveNext();
+                }
+                $adors->Close();
+        }
+        $false = false;
+		return empty($arr) ? $false : $arr;
+	}
+	
+	function CreateSequence($seq='adodbseq',$start=1)
+	{
+		
+		$this->Execute('BEGIN TRANSACTION adodbseq');
+		$start -= 1;
+		$this->Execute("create table $seq (id float(53))");
+		$ok = $this->Execute("insert into $seq with (tablock,holdlock) values($start)");
+		if (!$ok) {
+				$this->Execute('ROLLBACK TRANSACTION adodbseq');
+				return false;
+		}
+		$this->Execute('COMMIT TRANSACTION adodbseq'); 
+		return true;
+	}
+
+	function GenID($seq='adodbseq',$start=1)
+	{
+		//$this->debug=1;
+		$this->Execute('BEGIN TRANSACTION adodbseq');
+		$ok = $this->Execute("update $seq with (tablock,holdlock) set id = id + 1");
+		if (!$ok) {
+			$this->Execute("create table $seq (id float(53))");
+			$ok = $this->Execute("insert into $seq with (tablock,holdlock) values($start)");
+			if (!$ok) {
+				$this->Execute('ROLLBACK TRANSACTION adodbseq');
+				return false;
+			}
+			$this->Execute('COMMIT TRANSACTION adodbseq'); 
+			return $start;
+		}
+		$num = $this->GetOne("select id from $seq");
+		$this->Execute('COMMIT TRANSACTION adodbseq'); 
+		return $num;
+		
+		// in old implementation, pre 1.90, we returned GUID...
+		//return $this->GetOne("SELECT CONVERT(varchar(255), NEWID()) AS 'Char'");
+	}
+	
+	} // end class 
+	
+	class  ADORecordSet_ado_mssql extends ADORecordSet_ado {        
+	
+	var $databaseType = 'ado_mssql';
+	
+	function ADORecordSet_ado_mssql($id,$mode=false)
+	{
+	        return $this->ADORecordSet_ado($id,$mode);
+	}
+}
+?>
Index: /Dev/trunk/rdfapi/util/adodb/drivers/adodb-borland_ibase.inc.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/drivers/adodb-borland_ibase.inc.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/drivers/adodb-borland_ibase.inc.php	(revision 12)
@@ -0,0 +1,92 @@
+<?php
+/* 
+V4.94 23 Jan 2007  (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence. 
+Set tabs to 4 for best viewing.
+  
+  Latest version is available at http://adodb.sourceforge.net
+  
+  Support Borland Interbase 6.5 and later
+
+*/
+
+// security - hide paths
+if (!defined('ADODB_DIR')) die();
+
+include_once(ADODB_DIR."/drivers/adodb-ibase.inc.php");
+
+class ADODB_borland_ibase extends ADODB_ibase {
+	var $databaseType = "borland_ibase";	
+	
+	
+	function ADODB_borland_ibase()
+	{
+		$this->ADODB_ibase();
+	}
+	
+	function BeginTrans()
+	{	 
+		if ($this->transOff) return true;
+		$this->transCnt += 1;
+		$this->autoCommit = false;
+	 	$this->_transactionID = ibase_trans($this->ibasetrans, $this->_connectionID);
+		return $this->_transactionID;
+	}
+	
+	function ServerInfo()
+	{
+		$arr['dialect'] = $this->dialect;
+		switch($arr['dialect']) {
+		case '': 
+		case '1': $s = 'Interbase 6.5, Dialect 1'; break;
+		case '2': $s = 'Interbase 6.5, Dialect 2'; break;
+		default:
+		case '3': $s = 'Interbase 6.5, Dialect 3'; break;
+		}
+		$arr['version'] = '6.5';
+		$arr['description'] = $s;
+		return $arr;
+	}
+	
+	// Note that Interbase 6.5 uses ROWS instead - don't you love forking wars!
+	// 		SELECT col1, col2 FROM table ROWS 5 -- get 5 rows 
+	//		SELECT col1, col2 FROM TABLE ORDER BY col1 ROWS 3 TO 7 -- first 5 skip 2
+	// Firebird uses
+	//		SELECT FIRST 5 SKIP 2 col1, col2 FROM TABLE
+	function &SelectLimit($sql,$nrows=-1,$offset=-1,$inputarr=false,$secs2cache=0)
+	{
+		if ($nrows > 0) {
+			if ($offset <= 0) $str = " ROWS $nrows "; 
+			else {
+				$a = $offset+1;
+				$b = $offset+$nrows;
+				$str = " ROWS $a TO $b";
+			}
+		} else {
+			// ok, skip 
+			$a = $offset + 1;
+			$str = " ROWS $a TO 999999999"; // 999 million
+		}
+		$sql .= $str;
+		
+		return ($secs2cache) ? 
+				$this->CacheExecute($secs2cache,$sql,$inputarr)
+			:
+				$this->Execute($sql,$inputarr);
+	}
+	
+};
+ 
+
+class  ADORecordSet_borland_ibase extends ADORecordSet_ibase {	
+	
+	var $databaseType = "borland_ibase";		
+	
+	function ADORecordSet_borland_ibase($id,$mode=false)
+	{
+		$this->ADORecordSet_ibase($id,$mode);
+	}
+}
+?>
Index: /Dev/trunk/rdfapi/util/adodb/drivers/adodb-csv.inc.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/drivers/adodb-csv.inc.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/drivers/adodb-csv.inc.php	(revision 12)
@@ -0,0 +1,207 @@
+<?php
+/*
+V4.94 23 Jan 2007  (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence.
+  Set tabs to 4.
+  
+  Currently unsupported: MetaDatabases, MetaTables and MetaColumns, and also inputarr in Execute.
+  Native types have been converted to MetaTypes.
+  Transactions not supported yet.
+  
+  Limitation of url length. For IIS, see MaxClientRequestBuffer registry value.
+  
+	  http://support.microsoft.com/default.aspx?scid=kb;en-us;260694
+*/ 
+
+// security - hide paths
+if (!defined('ADODB_DIR')) die();
+
+if (! defined("_ADODB_CSV_LAYER")) {
+ define("_ADODB_CSV_LAYER", 1 );
+
+include_once(ADODB_DIR.'/adodb-csvlib.inc.php');
+ 
+class ADODB_csv extends ADOConnection {
+	var $databaseType = 'csv';
+	var $databaseProvider = 'csv';
+	var $hasInsertID = true;
+	var $hasAffectedRows = true;	
+	var $fmtTimeStamp = "'Y-m-d H:i:s'";
+	var $_affectedrows=0;
+	var $_insertid=0;
+	var $_url;
+	var $replaceQuote = "''"; // string to use to replace quotes
+	var $hasTransactions = false;
+	var $_errorNo = false;
+	
+	function ADODB_csv() 
+	{		
+	}
+	
+	function _insertid()
+	{
+			return $this->_insertid;
+	}
+	
+	function _affectedrows()
+	{
+			return $this->_affectedrows;
+	}
+  
+  	function &MetaDatabases()
+	{
+		return false;
+	}
+
+	
+	// returns true or false
+	function _connect($argHostname, $argUsername, $argPassword, $argDatabasename)
+	{
+		if (strtolower(substr($argHostname,0,7)) !== 'http://') return false;
+		$this->_url = $argHostname;
+		return true;	
+	}
+	
+	// returns true or false
+	function _pconnect($argHostname, $argUsername, $argPassword, $argDatabasename)
+	{
+		if (strtolower(substr($argHostname,0,7)) !== 'http://') return false;
+		$this->_url = $argHostname;
+		return true;
+	}
+	
+ 	function &MetaColumns($table) 
+	{
+		return false;
+	}
+		
+		
+	// parameters use PostgreSQL convention, not MySQL
+	function &SelectLimit($sql,$nrows=-1,$offset=-1)
+	{
+	global $ADODB_FETCH_MODE;
+	
+		$url = $this->_url.'?sql='.urlencode($sql)."&nrows=$nrows&fetch=".
+			(($this->fetchMode !== false)?$this->fetchMode : $ADODB_FETCH_MODE).
+			"&offset=$offset";
+		$err = false;
+		$rs = csv2rs($url,$err,false);
+		
+		if ($this->debug) print "$url<br><i>$err</i><br>";
+
+		$at = strpos($err,'::::');
+		if ($at === false) {
+			$this->_errorMsg = $err;
+			$this->_errorNo = (integer)$err;
+		} else {
+			$this->_errorMsg = substr($err,$at+4,1024);
+			$this->_errorNo = -9999;
+		}
+		if ($this->_errorNo) 
+			if ($fn = $this->raiseErrorFn) {
+				$fn($this->databaseType,'EXECUTE',$this->ErrorNo(),$this->ErrorMsg(),$sql,'');
+			}
+			
+		if (is_object($rs)) {	
+		
+			$rs->databaseType='csv';		
+			$rs->fetchMode = ($this->fetchMode !== false) ?  $this->fetchMode : $ADODB_FETCH_MODE;
+			$rs->connection = &$this;
+		}
+		return $rs;
+	}
+	
+	// returns queryID or false
+	function &_Execute($sql,$inputarr=false)
+	{
+	global $ADODB_FETCH_MODE;
+	
+		if (!$this->_bindInputArray && $inputarr) {
+			$sqlarr = explode('?',$sql);
+			$sql = '';
+			$i = 0;
+			foreach($inputarr as $v) {
+
+				$sql .= $sqlarr[$i];
+				if (gettype($v) == 'string')
+					$sql .= $this->qstr($v);
+				else if ($v === null)
+					$sql .= 'NULL';
+				else
+					$sql .= $v;
+				$i += 1;
+	
+			}
+			$sql .= $sqlarr[$i];
+			if ($i+1 != sizeof($sqlarr))	
+				print "Input Array does not match ?: ".htmlspecialchars($sql);
+			$inputarr = false;
+		}
+		
+		$url =  $this->_url.'?sql='.urlencode($sql)."&fetch=".
+			(($this->fetchMode !== false)?$this->fetchMode : $ADODB_FETCH_MODE);
+		$err = false;
+		
+		
+		$rs = csv2rs($url,$err,false);
+		if ($this->debug) print urldecode($url)."<br><i>$err</i><br>";
+		$at = strpos($err,'::::');
+		if ($at === false) {		
+			$this->_errorMsg = $err;
+			$this->_errorNo = (integer)$err;
+		} else {
+			$this->_errorMsg = substr($err,$at+4,1024);
+			$this->_errorNo = -9999;
+		}
+		
+		if ($this->_errorNo) 
+			if ($fn = $this->raiseErrorFn) {
+				$fn($this->databaseType,'EXECUTE',$this->ErrorNo(),$this->ErrorMsg(),$sql,$inputarr);
+			}
+		if (is_object($rs)) {
+			$rs->fetchMode = ($this->fetchMode !== false) ?  $this->fetchMode : $ADODB_FETCH_MODE;
+			
+			$this->_affectedrows = $rs->affectedrows;
+			$this->_insertid = $rs->insertid;
+			$rs->databaseType='csv';
+			$rs->connection = &$this;
+		}
+		return $rs;
+	}
+
+	/*	Returns: the last error message from previous database operation	*/	
+	function ErrorMsg() 
+	{
+			return $this->_errorMsg;
+	}
+	
+	/*	Returns: the last error number from previous database operation	*/	
+	function ErrorNo() 
+	{
+		return $this->_errorNo;
+	}
+	
+	// returns true or false
+	function _close()
+	{
+		return true;
+	}
+} // class
+
+class ADORecordset_csv extends ADORecordset {
+	function ADORecordset_csv($id,$mode=false)
+	{
+		$this->ADORecordset($id,$mode);
+	}
+	
+	function _close()
+	{
+		return true;
+	}
+}
+
+} // define
+	
+?>
Index: /Dev/trunk/rdfapi/util/adodb/drivers/adodb-db2.inc.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/drivers/adodb-db2.inc.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/drivers/adodb-db2.inc.php	(revision 12)
@@ -0,0 +1,828 @@
+<?php
+/* 
+  V4.94 23 Jan 2007  (c) 2006 John Lim (jlim#natsoft.com.my). All rights reserved.
+
+  This is a version of the ADODB driver for DB2.  It uses the 'ibm_db2' PECL extension
+  for PHP (http://pecl.php.net/package/ibm_db2), which in turn requires DB2 V8.2.2 or
+  higher.
+
+  Originally tested with PHP 5.1.1 and Apache 2.0.55 on Windows XP SP2.
+  More recently tested with PHP 5.1.2 and Apache 2.0.55 on Windows XP SP2.
+
+  This file was ported from "adodb-odbc.inc.php" by Larry Menard, "larry.menard#rogers.com".
+  I ripped out what I believed to be a lot of redundant or obsolete code, but there are
+  probably still some remnants of the ODBC support in this file; I'm relying on reviewers
+  of this code to point out any other things that can be removed.
+*/
+
+// security - hide paths
+if (!defined('ADODB_DIR')) die();
+
+  define("_ADODB_DB2_LAYER", 2 );
+	 
+/*--------------------------------------------------------------------------------------
+--------------------------------------------------------------------------------------*/
+
+
+class ADODB_db2 extends ADOConnection {
+	var $databaseType = "db2";	
+	var $fmtDate = "'Y-m-d'";
+	var $concat_operator = '||';
+	
+	var $sysTime = 'CURRENT TIME';
+	var $sysDate = 'CURRENT DATE';
+	var $sysTimeStamp = 'CURRENT TIMESTAMP';
+	
+	var $fmtTimeStamp = "'Y-m-d-H.i.s'";
+	var $replaceQuote = "''"; // string to use to replace quotes
+	var $dataProvider = "db2";
+	var $hasAffectedRows = true;
+
+	var $binmode = DB2_BINARY;
+
+	var $useFetchArray = false; // setting this to true will make array elements in FETCH_ASSOC mode case-sensitive
+								// breaking backward-compat
+	var $_bindInputArray = false;	
+	var $_genIDSQL = "VALUES NEXTVAL FOR %s";
+	var $_genSeqSQL = "CREATE SEQUENCE %s START WITH 1 NO MAXVALUE NO CYCLE";
+	var $_dropSeqSQL = "DROP SEQUENCE %s";
+	var $_autocommit = true;
+	var $_haserrorfunctions = true;
+	var $_lastAffectedRows = 0;
+	var $uCaseTables = true; // for meta* functions, uppercase table names
+	var $hasInsertID = true;
+	
+    function _insertid()
+    {
+        return ADOConnection::GetOne('VALUES IDENTITY_VAL_LOCAL()');
+    }
+	
+	function ADODB_db2() 
+	{ 	
+		$this->_haserrorfunctions = ADODB_PHPVER >= 0x4050;
+	}
+	
+		// returns true or false
+	function _connect($argDSN, $argUsername, $argPassword, $argDatabasename)
+	{
+		global $php_errormsg;
+		
+		if (!function_exists('db2_connect')) {
+			ADOConnection::outp("Warning: The old ODBC based DB2 driver has been renamed 'odbc_db2'. This ADOdb driver calls PHP's native db2 extension.");
+			return null;
+		}
+		// This needs to be set before the connect().
+		// Replaces the odbc_binmode() call that was in Execute()
+		ini_set('ibm_db2.binmode', $this->binmode);
+
+		if ($argDatabasename) {
+			$this->_connectionID = db2_connect($argDatabasename,$argUsername,$argPassword);
+		} else {
+			$this->_connectionID = db2_connect($argDSN,$argUsername,$argPassword);
+		}
+		if (isset($php_errormsg)) $php_errormsg = '';
+
+		// For db2_connect(), there is an optional 4th arg.  If present, it must be
+		// an array of valid options.  So far, we don't use them.
+
+		$this->_errorMsg = @db2_conn_errormsg();
+ 
+		if (isset($this->connectStmt)) $this->Execute($this->connectStmt);
+		
+		return $this->_connectionID != false;
+	}
+	
+	// returns true or false
+	function _pconnect($argDSN, $argUsername, $argPassword, $argDatabasename)
+	{
+		global $php_errormsg;
+	
+		if (!function_exists('db2_connect')) return null;
+		
+		// This needs to be set before the connect().
+		// Replaces the odbc_binmode() call that was in Execute()
+		ini_set('ibm_db2.binmode', $this->binmode);
+
+		if (isset($php_errormsg)) $php_errormsg = '';
+		$this->_errorMsg = isset($php_errormsg) ? $php_errormsg : '';
+		
+		if ($argDatabasename) {
+			$this->_connectionID = db2_pconnect($argDatabasename,$argUsername,$argPassword);
+		} else {
+			$this->_connectionID = db2_pconnect($argDSN,$argUsername,$argPassword);
+		}
+		if (isset($php_errormsg)) $php_errormsg = '';
+
+		$this->_errorMsg = @db2_conn_errormsg();
+		if ($this->_connectionID && $this->autoRollback) @db2_rollback($this->_connectionID);
+		if (isset($this->connectStmt)) $this->Execute($this->connectStmt);
+		
+		return $this->_connectionID != false;
+	}
+
+	// format and return date string in database timestamp format
+	function DBTimeStamp($ts)
+	{
+		if (empty($ts) && $ts !== 0) return 'null';
+		if (is_string($ts)) $ts = ADORecordSet::UnixTimeStamp($ts);
+		return 'TO_DATE('.adodb_date($this->fmtTimeStamp,$ts).",'YYYY-MM-DD HH24:MI:SS')";
+	}
+	
+	// Format date column in sql string given an input format that understands Y M D
+	function SQLDate($fmt, $col=false)
+	{	
+	// use right() and replace() ?
+		if (!$col) $col = $this->sysDate;
+
+		/* use TO_CHAR() if $fmt is TO_CHAR() allowed fmt */
+		if ($fmt== 'Y-m-d H:i:s')
+			return 'TO_CHAR('.$col.", 'YYYY-MM-DD HH24:MI:SS')";
+
+		$s = '';
+		
+		$len = strlen($fmt);
+		for ($i=0; $i < $len; $i++) {
+			if ($s) $s .= $this->concat_operator;
+			$ch = $fmt[$i];
+			switch($ch) {
+			case 'Y':
+			case 'y':
+				if ($len==1) return "year($col)";
+				$s .= "char(year($col))";
+				break;
+			case 'M':
+				if ($len==1) return "monthname($col)";
+				$s .= "substr(monthname($col),1,3)";
+				break;
+			case 'm':
+				if ($len==1) return "month($col)";
+				$s .= "right(digits(month($col)),2)";
+				break;
+			case 'D':
+			case 'd':
+				if ($len==1) return "day($col)";
+				$s .= "right(digits(day($col)),2)";
+				break;
+			case 'H':
+			case 'h':
+				if ($len==1) return "hour($col)";
+				if ($col != $this->sysDate) $s .= "right(digits(hour($col)),2)";	
+				else $s .= "''";
+				break;
+			case 'i':
+			case 'I':
+				if ($len==1) return "minute($col)";
+				if ($col != $this->sysDate)
+					$s .= "right(digits(minute($col)),2)";
+					else $s .= "''";
+				break;
+			case 'S':
+			case 's':
+				if ($len==1) return "second($col)";
+				if ($col != $this->sysDate)
+					$s .= "right(digits(second($col)),2)";
+				else $s .= "''";
+				break;
+			default:
+				if ($ch == '\\') {
+					$i++;
+					$ch = substr($fmt,$i,1);
+				}
+				$s .= $this->qstr($ch);
+			}
+		}
+		return $s;
+	} 
+ 
+	
+	function ServerInfo()
+	{
+	
+		if (!empty($this->host) && ADODB_PHPVER >= 0x4300) {
+			$dsn = strtoupper($this->host);
+			$first = true;
+			$found = false;
+			
+			if (!function_exists('db2_data_source')) return false;
+			
+			while(true) {
+				
+				$rez = @db2_data_source($this->_connectionID,
+					$first ? SQL_FETCH_FIRST : SQL_FETCH_NEXT);
+				$first = false;
+				if (!is_array($rez)) break;
+				if (strtoupper($rez['server']) == $dsn) {
+					$found = true;
+					break;
+				}
+			} 
+			if (!$found) return ADOConnection::ServerInfo();
+			if (!isset($rez['version'])) $rez['version'] = '';
+			return $rez;
+		} else {
+			return ADOConnection::ServerInfo();
+		}
+	}
+
+	
+	function CreateSequence($seqname='adodbseq',$start=1)
+	{
+		if (empty($this->_genSeqSQL)) return false;
+		$ok = $this->Execute(sprintf($this->_genSeqSQL,$seqname));
+		if (!$ok) return false;
+		return true;
+	}
+	
+	function DropSequence($seqname)
+	{
+		if (empty($this->_dropSeqSQL)) return false;
+		return $this->Execute(sprintf($this->_dropSeqSQL,$seqname));
+	}
+	
+	/*
+		This algorithm is not very efficient, but works even if table locking
+		is not available.
+		
+		Will return false if unable to generate an ID after $MAXLOOPS attempts.
+	*/
+	function GenID($seq='adodbseq',$start=1)
+	{	
+		// if you have to modify the parameter below, your database is overloaded,
+		// or you need to implement generation of id's yourself!
+		$num = $this->GetOne("VALUES NEXTVAL FOR $seq");
+				return $num;
+			}
+
+
+	function ErrorMsg()
+	{
+		if ($this->_haserrorfunctions) {
+			if ($this->_errorMsg !== false) return $this->_errorMsg;
+			if (empty($this->_connectionID)) return @db2_conn_errormsg();
+			return @db2_conn_errormsg($this->_connectionID);
+		} else return ADOConnection::ErrorMsg();
+	}
+	
+	function ErrorNo()
+	{
+		
+		if ($this->_haserrorfunctions) {
+			if ($this->_errorCode !== false) {
+				// bug in 4.0.6, error number can be corrupted string (should be 6 digits)
+				return (strlen($this->_errorCode)<=2) ? 0 : $this->_errorCode;
+			}
+
+			if (empty($this->_connectionID)) $e = @db2_conn_error(); 
+			else $e = @db2_conn_error($this->_connectionID);
+			
+			 // bug in 4.0.6, error number can be corrupted string (should be 6 digits)
+			 // so we check and patch
+			if (strlen($e)<=2) return 0;
+			return $e;
+		} else return ADOConnection::ErrorNo();
+	}
+	
+	
+
+	function BeginTrans()
+	{	
+		if (!$this->hasTransactions) return false;
+		if ($this->transOff) return true; 
+		$this->transCnt += 1;
+		$this->_autocommit = false;
+		return db2_autocommit($this->_connectionID,false);
+	}
+	
+	function CommitTrans($ok=true) 
+	{ 
+		if ($this->transOff) return true; 
+		if (!$ok) return $this->RollbackTrans();
+		if ($this->transCnt) $this->transCnt -= 1;
+		$this->_autocommit = true;
+		$ret = db2_commit($this->_connectionID);
+		db2_autocommit($this->_connectionID,true);
+		return $ret;
+	}
+	
+	function RollbackTrans()
+	{
+		if ($this->transOff) return true; 
+		if ($this->transCnt) $this->transCnt -= 1;
+		$this->_autocommit = true;
+		$ret = db2_rollback($this->_connectionID);
+		db2_autocommit($this->_connectionID,true);
+		return $ret;
+	}
+	
+	function MetaPrimaryKeys($table)
+	{
+	global $ADODB_FETCH_MODE;
+	
+		if ($this->uCaseTables) $table = strtoupper($table);
+		$schema = '';
+		$this->_findschema($table,$schema);
+
+		$savem = $ADODB_FETCH_MODE;
+		$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
+		$qid = @db2_primarykeys($this->_connectionID,'',$schema,$table);
+		
+		if (!$qid) {
+			$ADODB_FETCH_MODE = $savem;
+			return false;
+		}
+		$rs = new ADORecordSet_db2($qid);
+		$ADODB_FETCH_MODE = $savem;
+		
+		if (!$rs) return false;
+		
+		$arr =& $rs->GetArray();
+		$rs->Close();
+		$arr2 = array();
+		for ($i=0; $i < sizeof($arr); $i++) {
+			if ($arr[$i][3]) $arr2[] = $arr[$i][3];
+		}
+		return $arr2;
+	}
+	
+	function MetaForeignKeys($table, $owner = FALSE, $upper = FALSE, $asociative = FALSE )
+	{
+	global $ADODB_FETCH_MODE;
+	
+		if ($this->uCaseTables) $table = strtoupper($table);
+		$schema = '';
+		$this->_findschema($table,$schema);
+
+		$savem = $ADODB_FETCH_MODE;
+		$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
+		$qid = @db2_foreign_keys($this->_connectionID,'',$schema,$table);
+		if (!$qid) {
+			$ADODB_FETCH_MODE = $savem;
+			return false;
+		}
+		$rs = new ADORecordSet_db2($qid);
+
+		$ADODB_FETCH_MODE = $savem;
+		/*
+		$rs->fields indices
+		0 PKTABLE_CAT
+		1 PKTABLE_SCHEM
+		2 PKTABLE_NAME
+		3 PKCOLUMN_NAME
+		4 FKTABLE_CAT
+		5 FKTABLE_SCHEM
+		6 FKTABLE_NAME
+		7 FKCOLUMN_NAME
+		*/	
+		if (!$rs) return false;
+
+		$foreign_keys = array();	 	 
+		while (!$rs->EOF) {
+			if (strtoupper(trim($rs->fields[2])) == $table && (!$schema || strtoupper($rs->fields[1]) == $schema)) {
+				if (!is_array($foreign_keys[$rs->fields[5].'.'.$rs->fields[6]])) 
+					$foreign_keys[$rs->fields[5].'.'.$rs->fields[6]] = array();
+				$foreign_keys[$rs->fields[5].'.'.$rs->fields[6]][$rs->fields[7]] = $rs->fields[3];	 		
+			}
+			$rs->MoveNext();
+		}
+
+		$rs->Close();
+		return $foreign_key;
+	}
+	
+	
+	function &MetaTables($ttype=false,$schema=false)
+	{
+	global $ADODB_FETCH_MODE;
+	
+		$savem = $ADODB_FETCH_MODE;
+		$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
+		$qid = db2_tables($this->_connectionID);
+		
+		$rs = new ADORecordSet_db2($qid);
+		
+		$ADODB_FETCH_MODE = $savem;
+		if (!$rs) {
+			$false = false;
+			return $false;
+		}
+		
+		$arr =& $rs->GetArray();
+		
+		$rs->Close();
+		$arr2 = array();
+		
+		if ($ttype) {
+			$isview = strncmp($ttype,'V',1) === 0;
+		}
+		for ($i=0; $i < sizeof($arr); $i++) {
+			if (!$arr[$i][2]) continue;
+			$type = $arr[$i][3];
+			$schemaval = ($schema) ? $arr[$i][1].'.' : '';
+			if ($ttype) { 
+				if ($isview) {
+					if (strncmp($type,'V',1) === 0) $arr2[] = $schemaval.$arr[$i][2];
+				} else if (strncmp($type,'SYS',3) !== 0) $arr2[] = $schemaval.$arr[$i][2];
+			} else if (strncmp($type,'SYS',3) !== 0) $arr2[] = $schemaval.$arr[$i][2];
+		}
+		return $arr2;
+	}
+	
+/*
+See http://msdn.microsoft.com/library/default.asp?url=/library/en-us/db2/htm/db2datetime_data_type_changes.asp
+/ SQL data type codes /
+#define	SQL_UNKNOWN_TYPE	0
+#define SQL_CHAR			1
+#define SQL_NUMERIC		 2
+#define SQL_DECIMAL		 3
+#define SQL_INTEGER		 4
+#define SQL_SMALLINT		5
+#define SQL_FLOAT		   6
+#define SQL_REAL			7
+#define SQL_DOUBLE		  8
+#if (DB2VER >= 0x0300)
+#define SQL_DATETIME		9
+#endif
+#define SQL_VARCHAR		12
+
+
+/ One-parameter shortcuts for date/time data types /
+#if (DB2VER >= 0x0300)
+#define SQL_TYPE_DATE	  91
+#define SQL_TYPE_TIME	  92
+#define SQL_TYPE_TIMESTAMP 93
+
+#define SQL_UNICODE                             (-95)
+#define SQL_UNICODE_VARCHAR                     (-96)
+#define SQL_UNICODE_LONGVARCHAR                 (-97)
+*/
+	function DB2Types($t)
+	{
+		switch ((integer)$t) {
+		case 1:	
+		case 12:
+		case 0:
+		case -95:
+		case -96:
+			return 'C';
+		case -97:
+		case -1: //text
+			return 'X';
+		case -4: //image
+			return 'B';
+				
+		case 9:	
+		case 91:
+			return 'D';
+		
+		case 10:
+		case 11:
+		case 92:
+		case 93:
+			return 'T';
+			
+		case 4:
+		case 5:
+		case -6:
+			return 'I';
+			
+		case -11: // uniqidentifier
+			return 'R';
+		case -7: //bit
+			return 'L';
+		
+		default:
+			return 'N';
+		}
+	}
+	
+	function &MetaColumns($table)
+	{
+	global $ADODB_FETCH_MODE;
+	
+		$false = false;
+		if ($this->uCaseTables) $table = strtoupper($table);
+		$schema = '';
+		$this->_findschema($table,$schema);
+		
+		$savem = $ADODB_FETCH_MODE;
+		$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
+	
+        	$colname = "%";
+	        $qid = db2_columns($this->_connectionID, "", $schema, $table, $colname);
+		if (empty($qid)) return $false;
+		
+		$rs =& new ADORecordSet_db2($qid);
+		$ADODB_FETCH_MODE = $savem;
+		
+		if (!$rs) return $false;
+		$rs->_fetch();
+		
+		$retarr = array();
+		
+		/*
+		$rs->fields indices
+		0 TABLE_QUALIFIER
+		1 TABLE_SCHEM
+		2 TABLE_NAME
+		3 COLUMN_NAME
+		4 DATA_TYPE
+		5 TYPE_NAME
+		6 PRECISION
+		7 LENGTH
+		8 SCALE
+		9 RADIX
+		10 NULLABLE
+		11 REMARKS
+		*/
+		while (!$rs->EOF) {
+			if (strtoupper(trim($rs->fields[2])) == $table && (!$schema || strtoupper($rs->fields[1]) == $schema)) {
+				$fld = new ADOFieldObject();
+				$fld->name = $rs->fields[3];
+				$fld->type = $this->DB2Types($rs->fields[4]);
+				
+				// ref: http://msdn.microsoft.com/library/default.asp?url=/archive/en-us/dnaraccgen/html/msdn_odk.asp
+				// access uses precision to store length for char/varchar
+				if ($fld->type == 'C' or $fld->type == 'X') {
+					if ($rs->fields[4] <= -95) // UNICODE
+						$fld->max_length = $rs->fields[7]/2;
+					else
+						$fld->max_length = $rs->fields[7];
+				} else 
+					$fld->max_length = $rs->fields[7];
+				$fld->not_null = !empty($rs->fields[10]);
+				$fld->scale = $rs->fields[8];
+				$fld->primary_key = false;
+				$retarr[strtoupper($fld->name)] = $fld;	
+			} else if (sizeof($retarr)>0)
+				break;
+			$rs->MoveNext();
+		}
+		$rs->Close(); 
+		if (empty($retarr)) $retarr = false;
+
+	      $qid = db2_primary_keys($this->_connectionID, "", $schema, $table);
+		if (empty($qid)) return $false;
+		
+		$rs =& new ADORecordSet_db2($qid);
+		$ADODB_FETCH_MODE = $savem;
+		
+		if (!$rs) return $retarr;
+		$rs->_fetch();
+		
+		/*
+		$rs->fields indices
+		0 TABLE_CAT
+		1 TABLE_SCHEM
+		2 TABLE_NAME
+		3 COLUMN_NAME
+		4 KEY_SEQ
+		5 PK_NAME
+		*/
+		while (!$rs->EOF) {
+			if (strtoupper(trim($rs->fields[2])) == $table && (!$schema || strtoupper($rs->fields[1]) == $schema)) {
+				$retarr[strtoupper($rs->fields[3])]->primary_key = true;
+			} else if (sizeof($retarr)>0)
+				break;
+			$rs->MoveNext();
+		}
+		$rs->Close(); 
+		
+		if (empty($retarr)) $retarr = false;
+		return $retarr;
+	}
+	
+	function Prepare($sql)
+	{
+		if (! $this->_bindInputArray) return $sql; // no binding
+		$stmt = db2_prepare($this->_connectionID,$sql);
+		if (!$stmt) {
+			// we don't know whether db2 driver is parsing prepared stmts, so just return sql
+			return $sql;
+		}
+		return array($sql,$stmt,false);
+	}
+
+	/* returns queryID or false */
+	function _query($sql,$inputarr=false) 
+	{
+	GLOBAL $php_errormsg;
+		if (isset($php_errormsg)) $php_errormsg = '';
+		$this->_error = '';
+		
+		if ($inputarr) {
+			if (is_array($sql)) {
+				$stmtid = $sql[1];
+			} else {
+				$stmtid = db2_prepare($this->_connectionID,$sql);
+	
+				if ($stmtid == false) {
+					$this->_errorMsg = isset($php_errormsg) ? $php_errormsg : '';
+					return false;
+				}
+			}
+			
+			if (! db2_execute($stmtid,$inputarr)) {
+				if ($this->_haserrorfunctions) {
+					$this->_errorMsg = db2_stmt_errormsg();
+					$this->_errorCode = db2_stmt_error();
+				}
+				return false;
+			}
+		
+		} else if (is_array($sql)) {
+			$stmtid = $sql[1];
+			if (!db2_execute($stmtid)) {
+				if ($this->_haserrorfunctions) {
+					$this->_errorMsg = db2_stmt_errormsg();
+					$this->_errorCode = db2_stmt_error();
+				}
+				return false;
+			}
+		} else
+			$stmtid = @db2_exec($this->_connectionID,$sql);
+		
+		$this->_lastAffectedRows = 0;
+		if ($stmtid) {
+			if (@db2_num_fields($stmtid) == 0) {
+				$this->_lastAffectedRows = db2_num_rows($stmtid);
+				$stmtid = true;
+			} else {
+				$this->_lastAffectedRows = 0;
+			}
+			
+			if ($this->_haserrorfunctions) {
+				$this->_errorMsg = '';
+				$this->_errorCode = 0;
+			} else
+				$this->_errorMsg = isset($php_errormsg) ? $php_errormsg : '';
+		} else {
+			if ($this->_haserrorfunctions) {
+				$this->_errorMsg = db2_stmt_errormsg();
+				$this->_errorCode = db2_stmt_error();
+			} else
+				$this->_errorMsg = isset($php_errormsg) ? $php_errormsg : '';
+
+		}
+		return $stmtid;
+	}
+
+	/*
+		Insert a null into the blob field of the table first.
+		Then use UpdateBlob to store the blob.
+		
+		Usage:
+		 
+		$conn->Execute('INSERT INTO blobtable (id, blobcol) VALUES (1, null)');
+		$conn->UpdateBlob('blobtable','blobcol',$blob,'id=1');
+	*/
+	function UpdateBlob($table,$column,$val,$where,$blobtype='BLOB')
+	{
+		return $this->Execute("UPDATE $table SET $column=? WHERE $where",array($val)) != false;
+	}
+	
+	// returns true or false
+	function _close()
+	{
+		$ret = @db2_close($this->_connectionID);
+		$this->_connectionID = false;
+		return $ret;
+	}
+
+	function _affectedrows()
+	{
+		return $this->_lastAffectedRows;
+	}
+	
+}
+	
+/*--------------------------------------------------------------------------------------
+	 Class Name: Recordset
+--------------------------------------------------------------------------------------*/
+
+class ADORecordSet_db2 extends ADORecordSet {	
+	
+	var $bind = false;
+	var $databaseType = "db2";		
+	var $dataProvider = "db2";
+	var $useFetchArray;
+	
+	function ADORecordSet_db2($id,$mode=false)
+	{
+		if ($mode === false) {  
+			global $ADODB_FETCH_MODE;
+			$mode = $ADODB_FETCH_MODE;
+		}
+		$this->fetchMode = $mode;
+		
+		$this->_queryID = $id;
+	}
+
+
+	// returns the field object
+	function &FetchField($offset = -1) 
+	{
+		$o= new ADOFieldObject();
+		$o->name = @db2_field_name($this->_queryID,$offset);
+		$o->type = @db2_field_type($this->_queryID,$offset);
+		$o->max_length = db2_field_width($this->_queryID,$offset);
+		if (ADODB_ASSOC_CASE == 0) $o->name = strtolower($o->name);
+		else if (ADODB_ASSOC_CASE == 1) $o->name = strtoupper($o->name);
+		return $o;
+	}
+	
+	/* Use associative array to get fields array */
+	function Fields($colname)
+	{
+		if ($this->fetchMode & ADODB_FETCH_ASSOC) return $this->fields[$colname];
+		if (!$this->bind) {
+			$this->bind = array();
+			for ($i=0; $i < $this->_numOfFields; $i++) {
+				$o = $this->FetchField($i);
+				$this->bind[strtoupper($o->name)] = $i;
+			}
+		}
+
+		 return $this->fields[$this->bind[strtoupper($colname)]];
+	}
+	
+		
+	function _initrs()
+	{
+	global $ADODB_COUNTRECS;
+		$this->_numOfRows = ($ADODB_COUNTRECS) ? @db2_num_rows($this->_queryID) : -1;
+		$this->_numOfFields = @db2_num_fields($this->_queryID);
+		// some silly drivers such as db2 as/400 and intersystems cache return _numOfRows = 0
+		if ($this->_numOfRows == 0) $this->_numOfRows = -1;
+	}	
+	
+	function _seek($row)
+	{
+		return false;
+	}
+	
+	// speed up SelectLimit() by switching to ADODB_FETCH_NUM as ADODB_FETCH_ASSOC is emulated
+	function &GetArrayLimit($nrows,$offset=-1) 
+	{
+		if ($offset <= 0) {
+			$rs =& $this->GetArray($nrows);
+			return $rs;
+		}
+		$savem = $this->fetchMode;
+		$this->fetchMode = ADODB_FETCH_NUM;
+		$this->Move($offset);
+		$this->fetchMode = $savem;
+		
+		if ($this->fetchMode & ADODB_FETCH_ASSOC) {
+			$this->fields =& $this->GetRowAssoc(ADODB_ASSOC_CASE);
+		}
+		
+		$results = array();
+		$cnt = 0;
+		while (!$this->EOF && $nrows != $cnt) {
+			$results[$cnt++] = $this->fields;
+			$this->MoveNext();
+		}
+		
+		return $results;
+	}
+	
+	
+	function MoveNext() 
+	{
+		if ($this->_numOfRows != 0 && !$this->EOF) {		
+			$this->_currentRow++;
+			
+			$this->fields = @db2_fetch_array($this->_queryID);
+			if ($this->fields) {
+				if ($this->fetchMode & ADODB_FETCH_ASSOC) {
+					$this->fields =& $this->GetRowAssoc(ADODB_ASSOC_CASE);
+				}
+				return true;
+			}
+		}
+		$this->fields = false;
+		$this->EOF = true;
+		return false;
+	}	
+	
+	function _fetch()
+	{
+
+		$this->fields = db2_fetch_array($this->_queryID);
+		if ($this->fields) {
+			if ($this->fetchMode & ADODB_FETCH_ASSOC) {
+				$this->fields =& $this->GetRowAssoc(ADODB_ASSOC_CASE);
+			}
+			return true;
+		}
+		$this->fields = false;
+		return false;
+	}
+	
+	function _close() 
+	{
+		return @db2_free_result($this->_queryID);		
+	}
+
+}
+?>
Index: /Dev/trunk/rdfapi/util/adodb/drivers/adodb-fbsql.inc.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/drivers/adodb-fbsql.inc.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/drivers/adodb-fbsql.inc.php	(revision 12)
@@ -0,0 +1,266 @@
+<?php
+/*
+ @version V4.94 23 Jan 2007 (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
+ Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence. 
+ Contribution by Frank M. Kromann <frank@frontbase.com>. 
+  Set tabs to 8.
+*/ 
+
+// security - hide paths
+if (!defined('ADODB_DIR')) die();
+
+if (! defined("_ADODB_FBSQL_LAYER")) {
+ define("_ADODB_FBSQL_LAYER", 1 );
+
+class ADODB_fbsql extends ADOConnection {
+	var $databaseType = 'fbsql';
+	var $hasInsertID = true;
+	var $hasAffectedRows = true;	
+	var $metaTablesSQL = "SHOW TABLES";	
+	var $metaColumnsSQL = "SHOW COLUMNS FROM %s";
+	var $fmtTimeStamp = "'Y-m-d H:i:s'";
+	var $hasLimit = false;
+	
+	function ADODB_fbsql() 
+	{			
+	}
+	
+	function _insertid()
+	{
+			return fbsql_insert_id($this->_connectionID);
+	}
+	
+	function _affectedrows()
+	{
+			return fbsql_affected_rows($this->_connectionID);
+	}
+  
+  	function &MetaDatabases()
+	{
+		$qid = fbsql_list_dbs($this->_connectionID);
+		$arr = array();
+		$i = 0;
+		$max = fbsql_num_rows($qid);
+		while ($i < $max) {
+			$arr[] = fbsql_tablename($qid,$i);
+			$i += 1;
+		}
+		return $arr;
+	}
+
+	// returns concatenated string
+	function Concat()
+	{
+		$s = "";
+		$arr = func_get_args();
+		$first = true;
+
+		$s = implode(',',$arr);
+		if (sizeof($arr) > 0) return "CONCAT($s)";
+		else return '';
+	}
+	
+	// returns true or false
+	function _connect($argHostname, $argUsername, $argPassword, $argDatabasename)
+	{
+		$this->_connectionID = fbsql_connect($argHostname,$argUsername,$argPassword);
+		if ($this->_connectionID === false) return false;
+		if ($argDatabasename) return $this->SelectDB($argDatabasename);
+		return true;	
+	}
+	
+	// returns true or false
+	function _pconnect($argHostname, $argUsername, $argPassword, $argDatabasename)
+	{
+		$this->_connectionID = fbsql_pconnect($argHostname,$argUsername,$argPassword);
+		if ($this->_connectionID === false) return false;
+		if ($argDatabasename) return $this->SelectDB($argDatabasename);
+		return true;	
+	}
+	
+ 	function &MetaColumns($table) 
+	{
+		if ($this->metaColumnsSQL) {
+			
+			$rs = $this->Execute(sprintf($this->metaColumnsSQL,$table));
+			
+			if ($rs === false) return false;
+			
+			$retarr = array();
+			while (!$rs->EOF){
+				$fld = new ADOFieldObject();
+				$fld->name = $rs->fields[0];
+				$fld->type = $rs->fields[1];
+					
+				// split type into type(length):
+				if (preg_match("/^(.+)\((\d+)\)$/", $fld->type, $query_array)) {
+					$fld->type = $query_array[1];
+					$fld->max_length = $query_array[2];
+				} else {
+					$fld->max_length = -1;
+				}
+				$fld->not_null = ($rs->fields[2] != 'YES');
+				$fld->primary_key = ($rs->fields[3] == 'PRI');
+				$fld->auto_increment = (strpos($rs->fields[5], 'auto_increment') !== false);
+				$fld->binary = (strpos($fld->type,'blob') !== false);
+				
+				$retarr[strtoupper($fld->name)] = $fld;	
+				$rs->MoveNext();
+			}
+			$rs->Close();
+			return $retarr;	
+		}
+		return false;
+	}
+		
+	// returns true or false
+	function SelectDB($dbName) 
+	{
+		$this->database = $dbName;
+		if ($this->_connectionID) {
+			return @fbsql_select_db($dbName,$this->_connectionID);		
+		}
+		else return false;	
+	}
+	
+	
+	// returns queryID or false
+	function _query($sql,$inputarr)
+	{
+		return fbsql_query("$sql;",$this->_connectionID);
+	}
+
+	/*	Returns: the last error message from previous database operation	*/	
+	function ErrorMsg() 
+	{
+		$this->_errorMsg = @fbsql_error($this->_connectionID);
+			return $this->_errorMsg;
+	}
+	
+	/*	Returns: the last error number from previous database operation	*/	
+	function ErrorNo() 
+	{
+		return @fbsql_errno($this->_connectionID);
+	}
+	
+	// returns true or false
+	function _close()
+	{
+		return @fbsql_close($this->_connectionID);
+	}
+		
+}
+	
+/*--------------------------------------------------------------------------------------
+	 Class Name: Recordset
+--------------------------------------------------------------------------------------*/
+
+class ADORecordSet_fbsql extends ADORecordSet{	
+	
+	var $databaseType = "fbsql";
+	var $canSeek = true;
+	
+	function ADORecordSet_fbsql($queryID,$mode=false) 
+	{
+		if (!$mode) { 
+			global $ADODB_FETCH_MODE;
+			$mode = $ADODB_FETCH_MODE;
+		}
+		switch ($mode) {
+		case ADODB_FETCH_NUM: $this->fetchMode = FBSQL_NUM; break;
+		case ADODB_FETCH_ASSOC: $this->fetchMode = FBSQL_ASSOC; break;
+		case ADODB_FETCH_BOTH: 
+		default:
+		$this->fetchMode = FBSQL_BOTH; break;
+		}
+		return $this->ADORecordSet($queryID);
+	}
+	
+	function _initrs()
+	{
+	GLOBAL $ADODB_COUNTRECS;
+		$this->_numOfRows = ($ADODB_COUNTRECS) ? @fbsql_num_rows($this->_queryID):-1;
+		$this->_numOfFields = @fbsql_num_fields($this->_queryID);
+	}
+	
+
+
+	function &FetchField($fieldOffset = -1) {
+		if ($fieldOffset != -1) {
+			$o =  @fbsql_fetch_field($this->_queryID, $fieldOffset);
+			//$o->max_length = -1; // fbsql returns the max length less spaces -- so it is unrealiable
+			$f = @fbsql_field_flags($this->_queryID,$fieldOffset);
+			$o->binary = (strpos($f,'binary')!== false);
+		}
+		else if ($fieldOffset == -1) {	/*	The $fieldOffset argument is not provided thus its -1 	*/
+			$o = @fbsql_fetch_field($this->_queryID);// fbsql returns the max length less spaces -- so it is unrealiable
+			//$o->max_length = -1;
+		}
+		
+		return $o;
+	}
+		
+	function _seek($row)
+	{
+		return @fbsql_data_seek($this->_queryID,$row);
+	}
+	
+	function _fetch($ignore_fields=false)
+	{
+		$this->fields = @fbsql_fetch_array($this->_queryID,$this->fetchMode);
+		return ($this->fields == true);
+	}
+	
+	function _close() {
+		return @fbsql_free_result($this->_queryID);		
+	}
+	
+	function MetaType($t,$len=-1,$fieldobj=false)
+	{
+		if (is_object($t)) {
+			$fieldobj = $t;
+			$t = $fieldobj->type;
+			$len = $fieldobj->max_length;
+		}
+		$len = -1; // fbsql max_length is not accurate
+		switch (strtoupper($t)) {
+		case 'CHARACTER':
+		case 'CHARACTER VARYING': 
+		case 'BLOB': 
+		case 'CLOB': 
+		case 'BIT': 
+		case 'BIT VARYING': 
+			if ($len <= $this->blobSize) return 'C';
+			
+		// so we have to check whether binary...
+		case 'IMAGE':
+		case 'LONGBLOB': 
+		case 'BLOB':
+		case 'MEDIUMBLOB':
+			return !empty($fieldobj->binary) ? 'B' : 'X';
+			
+		case 'DATE': return 'D';
+		
+		case 'TIME':
+		case 'TIME WITH TIME ZONE':
+		case 'TIMESTAMP': 
+		case 'TIMESTAMP WITH TIME ZONE': return 'T';
+		
+		case 'PRIMARY_KEY':
+			return 'R';
+		case 'INTEGER':
+		case 'SMALLINT': 
+		case 'BOOLEAN':
+			
+			if (!empty($fieldobj->primary_key)) return 'R';
+			else return 'I';
+		
+		default: return 'N';
+		}
+	}
+
+} //class
+} // defined
+?>
Index: /Dev/trunk/rdfapi/util/adodb/drivers/adodb-firebird.inc.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/drivers/adodb-firebird.inc.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/drivers/adodb-firebird.inc.php	(revision 12)
@@ -0,0 +1,77 @@
+<?php
+/* 
+V4.94 23 Jan 2007  (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence. 
+Set tabs to 4 for best viewing.
+  
+  Latest version is available at http://adodb.sourceforge.net
+
+*/
+
+// security - hide paths
+if (!defined('ADODB_DIR')) die();
+
+include_once(ADODB_DIR."/drivers/adodb-ibase.inc.php");
+
+class ADODB_firebird extends ADODB_ibase {
+	var $databaseType = "firebird";	
+	var $dialect = 3;
+	
+	var $sysTimeStamp = "CURRENT_TIMESTAMP"; //"cast('NOW' as timestamp)";
+	
+	function ADODB_firebird()
+	{	
+		$this->ADODB_ibase();
+	}
+	
+	function ServerInfo()
+	{
+		$arr['dialect'] = $this->dialect;
+		switch($arr['dialect']) {
+		case '': 
+		case '1': $s = 'Firebird Dialect 1'; break;
+		case '2': $s = 'Firebird Dialect 2'; break;
+		default:
+		case '3': $s = 'Firebird Dialect 3'; break;
+		}
+		$arr['version'] = ADOConnection::_findvers($s);
+		$arr['description'] = $s;
+		return $arr;
+	}
+	
+	// Note that Interbase 6.5 uses this ROWS instead - don't you love forking wars!
+	// 		SELECT col1, col2 FROM table ROWS 5 -- get 5 rows 
+	//		SELECT col1, col2 FROM TABLE ORDER BY col1 ROWS 3 TO 7 -- first 5 skip 2
+	function &SelectLimit($sql,$nrows=-1,$offset=-1,$inputarr=false, $secs=0)
+	{
+		$nrows = (integer) $nrows;
+		$offset = (integer) $offset;
+		$str = 'SELECT ';
+		if ($nrows >= 0) $str .= "FIRST $nrows "; 
+		$str .=($offset>=0) ? "SKIP $offset " : '';
+		
+		$sql = preg_replace('/^[ \t]*select/i',$str,$sql); 
+		if ($secs)
+			$rs =& $this->CacheExecute($secs,$sql,$inputarr);
+		else
+			$rs =& $this->Execute($sql,$inputarr);
+			
+		return $rs;
+	}
+	
+	
+};
+ 
+
+class  ADORecordSet_firebird extends ADORecordSet_ibase {	
+	
+	var $databaseType = "firebird";		
+	
+	function ADORecordSet_firebird($id,$mode=false)
+	{
+		$this->ADORecordSet_ibase($id,$mode);
+	}
+}
+?>
Index: /Dev/trunk/rdfapi/util/adodb/drivers/adodb-ibase.inc.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/drivers/adodb-ibase.inc.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/drivers/adodb-ibase.inc.php	(revision 12)
@@ -0,0 +1,887 @@
+<?php
+/*
+V4.94 23 Jan 2007  (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.  
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence.
+
+  Latest version is available at http://adodb.sourceforge.net
+  
+  Interbase data driver. Requires interbase client. Works on Windows and Unix.
+
+  3 Jan 2002 -- suggestions by Hans-Peter Oeri <kampfcaspar75@oeri.ch>
+  	changed transaction handling and added experimental blob stuff
+  
+  Docs to interbase at the website
+   http://www.synectics.co.za/php3/tutorial/IB_PHP3_API.html
+   
+  To use gen_id(), see
+   http://www.volny.cz/iprenosil/interbase/ip_ib_code.htm#_code_creategen
+   
+   $rs = $conn->Execute('select gen_id(adodb,1) from rdb$database');
+   $id = $rs->fields[0];
+   $conn->Execute("insert into table (id, col1,...) values ($id, $val1,...)");
+*/
+
+// security - hide paths
+if (!defined('ADODB_DIR')) die();
+
+class ADODB_ibase extends ADOConnection {
+	var $databaseType = "ibase";
+	var $dataProvider = "ibase";
+	var $replaceQuote = "''"; // string to use to replace quotes
+	var $ibase_datefmt = '%Y-%m-%d'; // For hours,mins,secs change to '%Y-%m-%d %H:%M:%S';
+	var $fmtDate = "'Y-m-d'";
+	var $ibase_timestampfmt = "%Y-%m-%d %H:%M:%S";
+	var $ibase_timefmt = "%H:%M:%S";
+	var $fmtTimeStamp = "'Y-m-d, H:i:s'";
+	var $concat_operator='||';
+	var $_transactionID;
+	var $metaTablesSQL = "select rdb\$relation_name from rdb\$relations where rdb\$relation_name not like 'RDB\$%'";
+	//OPN STUFF start
+	var $metaColumnsSQL = "select a.rdb\$field_name, a.rdb\$null_flag, a.rdb\$default_source, b.rdb\$field_length, b.rdb\$field_scale, b.rdb\$field_sub_type, b.rdb\$field_precision, b.rdb\$field_type from rdb\$relation_fields a, rdb\$fields b where a.rdb\$field_source = b.rdb\$field_name and a.rdb\$relation_name = '%s' order by a.rdb\$field_position asc";
+	//OPN STUFF end
+	var $ibasetrans;
+	var $hasGenID = true;
+	var $_bindInputArray = true;
+	var $buffers = 0;
+	var $dialect = 1;
+	var $sysDate = "cast('TODAY' as timestamp)";
+	var $sysTimeStamp = "CURRENT_TIMESTAMP"; //"cast('NOW' as timestamp)";
+	var $ansiOuter = true;
+	var $hasAffectedRows = false;
+	var $poorAffectedRows = true;
+	var $blobEncodeType = 'C';
+	var $role = false;
+	
+	function ADODB_ibase() 
+	{
+		 if (defined('IBASE_DEFAULT')) $this->ibasetrans = IBASE_DEFAULT;
+  	}
+	
+	
+	   // returns true or false
+	function _connect($argHostname, $argUsername, $argPassword, $argDatabasename,$persist=false)
+	{  
+		if (!function_exists('ibase_pconnect')) return null;
+		if ($argDatabasename) $argHostname .= ':'.$argDatabasename;
+		$fn = ($persist) ? 'ibase_pconnect':'ibase_connect';
+		if ($this->role)
+			$this->_connectionID = $fn($argHostname,$argUsername,$argPassword,
+					$this->charSet,$this->buffers,$this->dialect,$this->role);
+		else	
+			$this->_connectionID = $fn($argHostname,$argUsername,$argPassword,
+					$this->charSet,$this->buffers,$this->dialect);
+		
+		if ($this->dialect != 1) { // http://www.ibphoenix.com/ibp_60_del_id_ds.html
+			$this->replaceQuote = "''";
+		}
+		if ($this->_connectionID === false) {
+			$this->_handleerror();
+			return false;
+		}
+		
+		// PHP5 change.
+		if (function_exists('ibase_timefmt')) {
+			ibase_timefmt($this->ibase_datefmt,IBASE_DATE );
+			if ($this->dialect == 1) ibase_timefmt($this->ibase_datefmt,IBASE_TIMESTAMP );
+			else ibase_timefmt($this->ibase_timestampfmt,IBASE_TIMESTAMP );
+			ibase_timefmt($this->ibase_timefmt,IBASE_TIME );
+			
+		} else {
+			ini_set("ibase.timestampformat", $this->ibase_timestampfmt);
+			ini_set("ibase.dateformat", $this->ibase_datefmt);
+			ini_set("ibase.timeformat", $this->ibase_timefmt);
+		}
+		return true;
+	}
+	   // returns true or false
+	function _pconnect($argHostname, $argUsername, $argPassword, $argDatabasename)
+	{
+		return $this->_connect($argHostname, $argUsername, $argPassword, $argDatabasename,true);
+	}	
+	
+	
+	function MetaPrimaryKeys($table,$owner_notused=false,$internalKey=false)
+	{	
+		if ($internalKey) return array('RDB$DB_KEY');
+		
+		$table = strtoupper($table);
+		
+		$sql = 'SELECT S.RDB$FIELD_NAME AFIELDNAME
+	FROM RDB$INDICES I JOIN RDB$INDEX_SEGMENTS S ON I.RDB$INDEX_NAME=S.RDB$INDEX_NAME  
+	WHERE I.RDB$RELATION_NAME=\''.$table.'\' and I.RDB$INDEX_NAME like \'RDB$PRIMARY%\'
+	ORDER BY I.RDB$INDEX_NAME,S.RDB$FIELD_POSITION';
+
+		$a = $this->GetCol($sql,false,true);
+		if ($a && sizeof($a)>0) return $a;
+		return false;	  
+	}
+	
+	function ServerInfo()
+	{
+		$arr['dialect'] = $this->dialect;
+		switch($arr['dialect']) {
+		case '': 
+		case '1': $s = 'Interbase 5.5 or earlier'; break;
+		case '2': $s = 'Interbase 5.6'; break;
+		default:
+		case '3': $s = 'Interbase 6.0'; break;
+		}
+		$arr['version'] = ADOConnection::_findvers($s);
+		$arr['description'] = $s;
+		return $arr;
+	}
+
+	function BeginTrans()
+	{	 
+		if ($this->transOff) return true;
+		$this->transCnt += 1;
+		$this->autoCommit = false;
+	 	$this->_transactionID = $this->_connectionID;//ibase_trans($this->ibasetrans, $this->_connectionID);
+		return $this->_transactionID;
+	}
+	
+	function CommitTrans($ok=true) 
+	{ 
+		if (!$ok) return $this->RollbackTrans();
+		if ($this->transOff) return true;
+		if ($this->transCnt) $this->transCnt -= 1;
+		$ret = false;
+		$this->autoCommit = true;
+		if ($this->_transactionID) {
+			   		//print ' commit ';
+			$ret = ibase_commit($this->_transactionID);
+		}
+		$this->_transactionID = false;
+		return $ret;
+	}
+	
+	// there are some compat problems with ADODB_COUNTRECS=false and $this->_logsql currently.
+	// it appears that ibase extension cannot support multiple concurrent queryid's
+	function &_Execute($sql,$inputarr=false) 
+	{
+	global $ADODB_COUNTRECS;
+	
+		if ($this->_logsql) {
+			$savecrecs = $ADODB_COUNTRECS;
+			$ADODB_COUNTRECS = true; // force countrecs
+			$ret =& ADOConnection::_Execute($sql,$inputarr);
+			$ADODB_COUNTRECS = $savecrecs;
+		} else {
+			$ret =& ADOConnection::_Execute($sql,$inputarr);
+		}
+		return $ret;
+	}
+	
+	function RollbackTrans()
+	{
+		if ($this->transOff) return true;
+		if ($this->transCnt) $this->transCnt -= 1;
+		$ret = false;
+		$this->autoCommit = true;
+		if ($this->_transactionID) 
+				  $ret = ibase_rollback($this->_transactionID);
+		$this->_transactionID = false;   
+		
+		return $ret;
+	}
+	
+	function &MetaIndexes ($table, $primary = FALSE, $owner=false)
+	{
+        // save old fetch mode
+        global $ADODB_FETCH_MODE;
+        $false = false;
+        $save = $ADODB_FETCH_MODE;
+        $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
+        if ($this->fetchMode !== FALSE) {
+               $savem = $this->SetFetchMode(FALSE);
+        }
+        $table = strtoupper($table);
+        $sql = "SELECT * FROM RDB\$INDICES WHERE RDB\$RELATION_NAME = '".$table."'";
+        if (!$primary) {
+        	$sql .= " AND RDB\$INDEX_NAME NOT LIKE 'RDB\$%'";
+        } else {
+        	$sql .= " AND RDB\$INDEX_NAME NOT LIKE 'RDB\$FOREIGN%'";
+        }
+        // get index details
+        $rs = $this->Execute($sql);
+        if (!is_object($rs)) {
+	        // restore fetchmode
+	        if (isset($savem)) {
+	            $this->SetFetchMode($savem);
+	        }
+	        $ADODB_FETCH_MODE = $save;
+            return $false;
+        }
+        
+        $indexes = array();
+		while ($row = $rs->FetchRow()) {
+			$index = $row[0];
+             if (!isset($indexes[$index])) {
+             		if (is_null($row[3])) {$row[3] = 0;}
+                     $indexes[$index] = array(
+                             'unique' => ($row[3] == 1),
+                             'columns' => array()
+                     );
+             }
+			$sql = "SELECT * FROM RDB\$INDEX_SEGMENTS WHERE RDB\$INDEX_NAME = '".$index."' ORDER BY RDB\$FIELD_POSITION ASC";
+			$rs1 = $this->Execute($sql);
+            while ($row1 = $rs1->FetchRow()) {
+             	$indexes[$index]['columns'][$row1[2]] = $row1[1];
+        	}
+		}
+        // restore fetchmode
+        if (isset($savem)) {
+            $this->SetFetchMode($savem);
+        }
+        $ADODB_FETCH_MODE = $save;
+        
+        return $indexes;
+	}
+
+	
+	// See http://community.borland.com/article/0,1410,25844,00.html
+	function RowLock($tables,$where,$col)
+	{
+		if ($this->autoCommit) $this->BeginTrans();
+		$this->Execute("UPDATE $table SET $col=$col WHERE $where "); // is this correct - jlim?
+		return 1;
+	}
+	
+	
+	function CreateSequence($seqname,$startID=1)
+	{
+		$ok = $this->Execute(("INSERT INTO RDB\$GENERATORS (RDB\$GENERATOR_NAME) VALUES (UPPER('$seqname'))" ));
+		if (!$ok) return false;
+		return $this->Execute("SET GENERATOR $seqname TO ".($startID-1).';');
+	}
+	
+	function DropSequence($seqname)
+	{
+		$seqname = strtoupper($seqname);
+		$this->Execute("delete from RDB\$GENERATORS where RDB\$GENERATOR_NAME='$seqname'");
+	}
+	
+	function GenID($seqname='adodbseq',$startID=1)
+	{
+		$getnext = ("SELECT Gen_ID($seqname,1) FROM RDB\$DATABASE");
+		$rs = @$this->Execute($getnext);
+		if (!$rs) {
+			$this->Execute(("INSERT INTO RDB\$GENERATORS (RDB\$GENERATOR_NAME) VALUES (UPPER('$seqname'))" ));
+			$this->Execute("SET GENERATOR $seqname TO ".($startID-1).';');
+			$rs = $this->Execute($getnext);
+		}
+		if ($rs && !$rs->EOF) $this->genID = (integer) reset($rs->fields);
+		else $this->genID = 0; // false
+		
+		if ($rs) $rs->Close();
+		
+		return $this->genID;
+	}
+
+	function SelectDB($dbName) 
+	{
+		   return false;
+	}
+
+	function _handleerror()
+	{
+		$this->_errorMsg = ibase_errmsg();
+	}
+
+	function ErrorNo() 
+	{
+		if (preg_match('/error code = ([\-0-9]*)/i', $this->_errorMsg,$arr)) return (integer) $arr[1];
+		else return 0;
+	}
+
+	function ErrorMsg() 
+	{
+			return $this->_errorMsg;
+	}
+
+	function Prepare($sql)
+	{
+		$stmt = ibase_prepare($this->_connectionID,$sql);
+		if (!$stmt) return false;
+		return array($sql,$stmt);
+	}
+
+	   // returns query ID if successful, otherwise false
+	   // there have been reports of problems with nested queries - the code is probably not re-entrant?
+	function _query($sql,$iarr=false)
+	{ 
+
+		if (!$this->autoCommit && $this->_transactionID) {
+			$conn = $this->_transactionID;
+			$docommit = false;
+		} else {
+			$conn = $this->_connectionID;
+			$docommit = true;
+		}
+		if (is_array($sql)) {
+			$fn = 'ibase_execute';
+			$sql = $sql[1];
+			if (is_array($iarr)) {
+				if  (ADODB_PHPVER >= 0x4050) { // actually 4.0.4
+					if ( !isset($iarr[0]) ) $iarr[0] = ''; // PHP5 compat hack
+					$fnarr =& array_merge( array($sql) , $iarr);
+					$ret = call_user_func_array($fn,$fnarr);
+				} else {
+					switch(sizeof($iarr)) {
+					case 1: $ret = $fn($sql,$iarr[0]); break;
+					case 2: $ret = $fn($sql,$iarr[0],$iarr[1]); break;
+					case 3: $ret = $fn($sql,$iarr[0],$iarr[1],$iarr[2]); break;
+					case 4: $ret = $fn($sql,$iarr[0],$iarr[1],$iarr[2],$iarr[3]); break;
+					case 5: $ret = $fn($sql,$iarr[0],$iarr[1],$iarr[2],$iarr[3],$iarr[4]); break;
+					case 6: $ret = $fn($sql,$iarr[0],$iarr[1],$iarr[2],$iarr[3],$iarr[4],$iarr[5]); break;
+					case 7: $ret = $fn($sql,$iarr[0],$iarr[1],$iarr[2],$iarr[3],$iarr[4],$iarr[5],$iarr[6]); break;
+					default: ADOConnection::outp( "Too many parameters to ibase query $sql");
+					case 8: $ret = $fn($sql,$iarr[0],$iarr[1],$iarr[2],$iarr[3],$iarr[4],$iarr[5],$iarr[6],$iarr[7]); break;
+					}
+				}
+			} else $ret = $fn($sql); 
+		} else {
+			$fn = 'ibase_query';
+		
+			if (is_array($iarr)) {	
+				if (ADODB_PHPVER >= 0x4050) { // actually 4.0.4
+					if (sizeof($iarr) == 0) $iarr[0] = ''; // PHP5 compat hack
+					$fnarr =& array_merge( array($conn,$sql) , $iarr);
+					$ret = call_user_func_array($fn,$fnarr);
+				} else {
+					switch(sizeof($iarr)) {
+					case 1: $ret = $fn($conn,$sql,$iarr[0]); break;
+					case 2: $ret = $fn($conn,$sql,$iarr[0],$iarr[1]); break;
+					case 3: $ret = $fn($conn,$sql,$iarr[0],$iarr[1],$iarr[2]); break;
+					case 4: $ret = $fn($conn,$sql,$iarr[0],$iarr[1],$iarr[2],$iarr[3]); break;
+					case 5: $ret = $fn($conn,$sql,$iarr[0],$iarr[1],$iarr[2],$iarr[3],$iarr[4]); break;
+					case 6: $ret = $fn($conn,$sql,$iarr[0],$iarr[1],$iarr[2],$iarr[3],$iarr[4],$iarr[5]); break;
+					case 7: $ret = $fn($conn,$sql,$iarr[0],$iarr[1],$iarr[2],$iarr[3],$iarr[4],$iarr[5],$iarr[6]); break;
+					default: ADOConnection::outp( "Too many parameters to ibase query $sql");
+					case 8: $ret = $fn($conn,$sql,$iarr[0],$iarr[1],$iarr[2],$iarr[3],$iarr[4],$iarr[5],$iarr[6],$iarr[7]); break;
+					}
+				}
+			} else $ret = $fn($conn,$sql); 
+		}
+		if ($docommit && $ret === true) ibase_commit($this->_connectionID);
+
+		$this->_handleerror();
+		return $ret;
+	}
+
+	 // returns true or false
+	 function _close()
+	 {	   
+		if (!$this->autoCommit) @ibase_rollback($this->_connectionID);
+		return @ibase_close($this->_connectionID);
+	 }
+	
+	//OPN STUFF start
+	function _ConvertFieldType(&$fld, $ftype, $flen, $fscale, $fsubtype, $fprecision, $dialect3)
+	{
+		$fscale = abs($fscale);
+		$fld->max_length = $flen;
+		$fld->scale = null;
+		switch($ftype){
+			case 7: 
+			case 8:
+				if ($dialect3) {
+				    switch($fsubtype){
+				    	case 0: 
+				    		$fld->type = ($ftype == 7 ? 'smallint' : 'integer');
+				    		break;
+				    	case 1: 
+				    		$fld->type = 'numeric';
+							$fld->max_length = $fprecision;
+							$fld->scale = $fscale;
+				    		break;
+				    	case 2:
+				    		$fld->type = 'decimal';
+							$fld->max_length = $fprecision;
+							$fld->scale = $fscale;
+				    		break;
+				    } // switch
+				} else {
+					if ($fscale !=0) {
+					    $fld->type = 'decimal';
+						$fld->scale = $fscale;
+						$fld->max_length = ($ftype == 7 ? 4 : 9);
+					} else {
+						$fld->type = ($ftype == 7 ? 'smallint' : 'integer');
+					}
+				}
+				break;
+			case 16: 
+				if ($dialect3) {
+				    switch($fsubtype){
+				    	case 0: 
+				    		$fld->type = 'decimal';
+							$fld->max_length = 18;
+							$fld->scale = 0;
+				    		break;
+				    	case 1: 
+				    		$fld->type = 'numeric';
+							$fld->max_length = $fprecision;
+							$fld->scale = $fscale;
+				    		break;
+				    	case 2:
+				    		$fld->type = 'decimal';
+							$fld->max_length = $fprecision;
+							$fld->scale = $fscale;
+				    		break;
+				    } // switch
+				}
+				break;
+			case 10:
+				$fld->type = 'float';
+				break;
+			case 14:
+				$fld->type = 'char';
+				break;
+			case 27:
+				if ($fscale !=0) {
+				    $fld->type = 'decimal';
+					$fld->max_length = 15;
+					$fld->scale = 5;
+				} else {
+					$fld->type = 'double';
+				}
+				break;
+			case 35:
+				if ($dialect3) {
+				    $fld->type = 'timestamp';
+				} else {
+					$fld->type = 'date';
+				}
+				break;
+			case 12:
+				$fld->type = 'date';
+				break;
+			case 13:
+				$fld->type = 'time';
+				break;
+			case 37:
+				$fld->type = 'varchar';
+				break;
+			case 40:
+				$fld->type = 'cstring';
+				break;
+			case 261:
+				$fld->type = 'blob';
+				$fld->max_length = -1;
+				break;
+		} // switch
+	}
+	//OPN STUFF end
+		// returns array of ADOFieldObjects for current table
+	function &MetaColumns($table) 
+	{
+	global $ADODB_FETCH_MODE;
+		
+		$save = $ADODB_FETCH_MODE;
+		$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
+	
+		$rs = $this->Execute(sprintf($this->metaColumnsSQL,strtoupper($table)));
+	
+		$ADODB_FETCH_MODE = $save;
+		$false = false;
+		if ($rs === false) {
+			return $false;
+		}
+		
+		$retarr = array();
+		//OPN STUFF start
+		$dialect3 = ($this->dialect==3 ? true : false);
+		//OPN STUFF end
+		while (!$rs->EOF) { //print_r($rs->fields);
+			$fld = new ADOFieldObject();
+			$fld->name = trim($rs->fields[0]);
+			//OPN STUFF start
+			$this->_ConvertFieldType($fld, $rs->fields[7], $rs->fields[3], $rs->fields[4], $rs->fields[5], $rs->fields[6], $dialect3);
+			if (isset($rs->fields[1]) && $rs->fields[1]) {
+				$fld->not_null = true;
+			}				
+			if (isset($rs->fields[2])) {
+				
+				$fld->has_default = true;
+				$d = substr($rs->fields[2],strlen('default '));
+				switch ($fld->type)
+				{
+				case 'smallint':
+				case 'integer': $fld->default_value = (int) $d; break;
+				case 'char': 
+				case 'blob':
+				case 'text':
+				case 'varchar': $fld->default_value = (string) substr($d,1,strlen($d)-2); break;
+				case 'double':
+				case 'float': $fld->default_value = (float) $d; break;
+				default: $fld->default_value = $d; break;
+				}
+		//	case 35:$tt = 'TIMESTAMP'; break;
+			}
+			if ((isset($rs->fields[5])) && ($fld->type == 'blob')) {
+				$fld->sub_type = $rs->fields[5];
+			} else {
+				$fld->sub_type = null;
+			}
+			//OPN STUFF end
+			if ($ADODB_FETCH_MODE == ADODB_FETCH_NUM) $retarr[] = $fld;	
+			else $retarr[strtoupper($fld->name)] = $fld;
+			
+			$rs->MoveNext();
+		}
+		$rs->Close();
+		if ( empty($retarr)) return $false;
+		else return $retarr;	
+	}
+	
+	function BlobEncode( $blob ) 
+	{
+		$blobid = ibase_blob_create( $this->_connectionID);
+		ibase_blob_add( $blobid, $blob );
+		return ibase_blob_close( $blobid );
+	}
+	
+	// since we auto-decode all blob's since 2.42, 
+	// BlobDecode should not do any transforms
+	function BlobDecode($blob)
+	{
+		return $blob; 
+	}
+	
+	
+	
+	
+	// old blobdecode function
+	// still used to auto-decode all blob's
+	function _BlobDecode_old( $blob ) 
+	{
+		$blobid = ibase_blob_open($this->_connectionID, $blob );
+		$realblob = ibase_blob_get( $blobid,$this->maxblobsize); // 2nd param is max size of blob -- Kevin Boillet <kevinboillet@yahoo.fr>
+		while($string = ibase_blob_get($blobid, 8192)){ 
+			$realblob .= $string; 
+		}
+		ibase_blob_close( $blobid );
+
+		return( $realblob );
+	} 
+	
+	function _BlobDecode( $blob ) 
+    {
+        if  (ADODB_PHPVER >= 0x5000) {
+            $blob_data = ibase_blob_info($this->_connectionID, $blob );
+            $blobid = ibase_blob_open($this->_connectionID, $blob );
+        } else {
+
+            $blob_data = ibase_blob_info( $blob );
+            $blobid = ibase_blob_open( $blob );
+        }
+
+        if( $blob_data[0] > $this->maxblobsize ) {
+
+            $realblob = ibase_blob_get($blobid, $this->maxblobsize);
+
+            while($string = ibase_blob_get($blobid, 8192)){
+                $realblob .= $string; 
+            }
+        } else {
+            $realblob = ibase_blob_get($blobid, $blob_data[0]);
+        }
+
+        ibase_blob_close( $blobid );
+        return( $realblob );
+	}
+	
+	function UpdateBlobFile($table,$column,$path,$where,$blobtype='BLOB') 
+	{ 
+		$fd = fopen($path,'rb'); 
+		if ($fd === false) return false; 
+		$blob_id = ibase_blob_create($this->_connectionID); 
+		
+		/* fill with data */ 
+		
+		while ($val = fread($fd,32768)){ 
+			ibase_blob_add($blob_id, $val); 
+		} 
+		
+		/* close and get $blob_id_str for inserting into table */ 
+		$blob_id_str = ibase_blob_close($blob_id); 
+		
+		fclose($fd); 
+		return $this->Execute("UPDATE $table SET $column=(?) WHERE $where",array($blob_id_str)) != false; 
+	} 
+	
+	/*
+		Insert a null into the blob field of the table first.
+		Then use UpdateBlob to store the blob.
+		
+		Usage:
+		 
+		$conn->Execute('INSERT INTO blobtable (id, blobcol) VALUES (1, null)');
+		$conn->UpdateBlob('blobtable','blobcol',$blob,'id=1');
+	*/
+	function UpdateBlob($table,$column,$val,$where,$blobtype='BLOB') 
+	{ 
+	$blob_id = ibase_blob_create($this->_connectionID); 
+	
+	// ibase_blob_add($blob_id, $val); 
+	
+	// replacement that solves the problem by which only the first modulus 64K / 
+	// of $val are stored at the blob field //////////////////////////////////// 
+	// Thx Abel Berenstein  aberenstein#afip.gov.ar
+	$len = strlen($val); 
+	$chunk_size = 32768; 
+	$tail_size = $len % $chunk_size; 
+	$n_chunks = ($len - $tail_size) / $chunk_size; 
+	
+	for ($n = 0; $n < $n_chunks; $n++) { 
+		$start = $n * $chunk_size; 
+		$data = substr($val, $start, $chunk_size); 
+		ibase_blob_add($blob_id, $data); 
+	} 
+	
+	if ($tail_size) {
+		$start = $n_chunks * $chunk_size; 
+		$data = substr($val, $start, $tail_size); 
+		ibase_blob_add($blob_id, $data); 
+	}
+	// end replacement ///////////////////////////////////////////////////////// 
+	
+	$blob_id_str = ibase_blob_close($blob_id); 
+	
+	return $this->Execute("UPDATE $table SET $column=(?) WHERE $where",array($blob_id_str)) != false; 
+	
+	} 
+	
+	
+	function OldUpdateBlob($table,$column,$val,$where,$blobtype='BLOB')
+	{
+		$blob_id = ibase_blob_create($this->_connectionID);
+		ibase_blob_add($blob_id, $val);
+		$blob_id_str = ibase_blob_close($blob_id);
+		return $this->Execute("UPDATE $table SET $column=(?) WHERE $where",array($blob_id_str)) != false;
+	}
+	
+	// Format date column in sql string given an input format that understands Y M D
+	// Only since Interbase 6.0 - uses EXTRACT
+	// problem - does not zero-fill the day and month yet
+	function SQLDate($fmt, $col=false)
+	{	
+		if (!$col) $col = $this->sysDate;
+		$s = '';
+		
+		$len = strlen($fmt);
+		for ($i=0; $i < $len; $i++) {
+			if ($s) $s .= '||';
+			$ch = $fmt[$i];
+			switch($ch) {
+			case 'Y':
+			case 'y':
+				$s .= "extract(year from $col)";
+				break;
+			case 'M':
+			case 'm':
+				$s .= "extract(month from $col)";
+				break;
+			case 'Q':
+			case 'q':
+				$s .= "cast(((extract(month from $col)+2) / 3) as integer)";
+				break;
+			case 'D':
+			case 'd':
+				$s .= "(extract(day from $col))";
+				break;
+			case 'H':
+			case 'h':
+			  $s .= "(extract(hour from $col))";
+			  break;                        
+			case 'I':
+			case 'i':
+			  $s .= "(extract(minute from $col))";
+			  break;                
+			case 'S':
+			case 's':
+			  $s .= "CAST((extract(second from $col)) AS INTEGER)";
+			  break;        
+
+			default:
+				if ($ch == '\\') {
+					$i++;
+					$ch = substr($fmt,$i,1);
+				}
+				$s .= $this->qstr($ch);
+				break;
+			}
+		}
+		return $s;
+	}
+}
+
+/*--------------------------------------------------------------------------------------
+		 Class Name: Recordset
+--------------------------------------------------------------------------------------*/
+
+class ADORecordset_ibase extends ADORecordSet
+{
+
+	var $databaseType = "ibase";
+	var $bind=false;
+	var $_cacheType;
+	
+	function ADORecordset_ibase($id,$mode=false)
+	{
+	global $ADODB_FETCH_MODE;
+	
+			$this->fetchMode = ($mode === false) ? $ADODB_FETCH_MODE : $mode;
+			$this->ADORecordSet($id);
+	}
+
+	/*		Returns: an object containing field information.
+			Get column information in the Recordset object. fetchField() can be used in order to obtain information about
+			fields in a certain query result. If the field offset isn't specified, the next field that wasn't yet retrieved by
+			fetchField() is retrieved.		*/
+
+	function &FetchField($fieldOffset = -1)
+	{
+			 $fld = new ADOFieldObject;
+			 $ibf = ibase_field_info($this->_queryID,$fieldOffset);
+			 switch (ADODB_ASSOC_CASE) {
+			 case 2: // the default
+			 	$fld->name = ($ibf['alias']);
+				 if (empty($fld->name)) $fld->name = ($ibf['name']);
+				 break;
+			 case 0: 
+				 $fld->name = strtoupper($ibf['alias']);
+				 if (empty($fld->name)) $fld->name = strtoupper($ibf['name']);
+				 break;
+			 case 1: 
+			 	$fld->name = strtolower($ibf['alias']);
+				 if (empty($fld->name)) $fld->name = strtolower($ibf['name']);
+				 break;
+			 }
+			 
+			 $fld->type = $ibf['type'];
+			 $fld->max_length = $ibf['length'];
+			 
+			 /*       This needs to be populated from the metadata */ 
+			 $fld->not_null = false;
+			 $fld->has_default = false;
+			 $fld->default_value = 'null';
+			 return $fld;
+	}
+
+	function _initrs()
+	{
+		$this->_numOfRows = -1;
+		$this->_numOfFields = @ibase_num_fields($this->_queryID);
+
+		// cache types for blob decode check
+		for ($i=0, $max = $this->_numOfFields; $i < $max; $i++) { 
+			$f1 = $this->FetchField($i); 
+			$this->_cacheType[] = $f1->type;
+		}				
+	}
+
+	function _seek($row)
+	{
+		return false;
+	}
+	
+	function _fetch() 
+	{
+		$f = @ibase_fetch_row($this->_queryID); 
+		if ($f === false) {
+			$this->fields = false;
+			return false;
+		}
+		// OPN stuff start - optimized
+		// fix missing nulls and decode blobs automatically
+	
+		global $ADODB_ANSI_PADDING_OFF;
+		//$ADODB_ANSI_PADDING_OFF=1;
+		$rtrim = !empty($ADODB_ANSI_PADDING_OFF);
+		
+		for ($i=0, $max = $this->_numOfFields; $i < $max; $i++) { 
+			if ($this->_cacheType[$i]=="BLOB") {
+				if (isset($f[$i])) { 
+					$f[$i] = $this->connection->_BlobDecode($f[$i]); 
+				} else { 
+					$f[$i] = null; 
+				} 
+			} else { 
+				if (!isset($f[$i])) { 
+					$f[$i] = null; 
+				} else if ($rtrim && is_string($f[$i])) {
+					$f[$i] = rtrim($f[$i]);
+				}
+			} 
+		} 
+		// OPN stuff end 
+		
+		$this->fields = $f;
+		if ($this->fetchMode == ADODB_FETCH_ASSOC) {
+			$this->fields = &$this->GetRowAssoc(ADODB_ASSOC_CASE);
+		} else if ($this->fetchMode == ADODB_FETCH_BOTH) {
+			$this->fields =& array_merge($this->fields,$this->GetRowAssoc(ADODB_ASSOC_CASE));
+		}
+		return true;
+	}
+
+	/* Use associative array to get fields array */
+	function Fields($colname)
+	{
+		if ($this->fetchMode & ADODB_FETCH_ASSOC) return $this->fields[$colname];
+		if (!$this->bind) {
+			$this->bind = array();
+			for ($i=0; $i < $this->_numOfFields; $i++) {
+				$o = $this->FetchField($i);
+				$this->bind[strtoupper($o->name)] = $i;
+			}
+		}
+		
+		return $this->fields[$this->bind[strtoupper($colname)]];
+		
+	}
+	
+
+	function _close() 
+	{
+			return @ibase_free_result($this->_queryID);
+	}
+
+	function MetaType($t,$len=-1,$fieldobj=false)
+	{
+		if (is_object($t)) {
+			$fieldobj = $t;
+			$t = $fieldobj->type;
+			$len = $fieldobj->max_length;
+		}
+		switch (strtoupper($t)) {
+		case 'CHAR':
+			return 'C';
+			
+		case 'TEXT':
+		case 'VARCHAR':
+		case 'VARYING':
+		if ($len <= $this->blobSize) return 'C';
+			return 'X';
+		case 'BLOB':
+			return 'B';
+			   
+		case 'TIMESTAMP':
+		case 'DATE': return 'D';
+		case 'TIME': return 'T';
+				//case 'T': return 'T';
+
+				//case 'L': return 'L';
+		case 'INT': 
+		case 'SHORT':
+		case 'INTEGER': return 'I';
+		default: return 'N';
+		}
+	}
+
+}
+?>
Index: /Dev/trunk/rdfapi/util/adodb/drivers/adodb-informix.inc.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/drivers/adodb-informix.inc.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/drivers/adodb-informix.inc.php	(revision 12)
@@ -0,0 +1,40 @@
+<?php
+/**
+* @version V4.94 23 Jan 2007 (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
+* Released under both BSD license and Lesser GPL library license.
+* Whenever there is any discrepancy between the two licenses,
+* the BSD license will take precedence.
+*
+* Set tabs to 4 for best viewing.
+*
+* Latest version is available at http://php.weblogs.com
+*
+* Informix 9 driver that supports SELECT FIRST
+*
+*/
+
+// security - hide paths
+if (!defined('ADODB_DIR')) die();
+
+include_once(ADODB_DIR.'/drivers/adodb-informix72.inc.php');
+
+class ADODB_informix extends ADODB_informix72 {
+	var $databaseType = "informix";
+	var $hasTop = 'FIRST';
+	var $ansiOuter = true;
+	
+	function IfNull( $field, $ifNull )
+	{
+		return " NVL($field, $ifNull) "; // if Informix 9.X or 10.X
+	}
+}
+
+class ADORecordset_informix extends ADORecordset_informix72 {
+	var $databaseType = "informix";
+	
+	function ADORecordset_informix($id,$mode=false)
+	{
+		$this->ADORecordset_informix72($id,$mode);
+	}
+}
+?>
Index: /Dev/trunk/rdfapi/util/adodb/drivers/adodb-informix72.inc.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/drivers/adodb-informix72.inc.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/drivers/adodb-informix72.inc.php	(revision 12)
@@ -0,0 +1,475 @@
+<?php
+/*
+V4.94 23 Jan 2007  (c) 2000-2007 John Lim. All rights reserved.
+  Released under both BSD license and Lesser GPL library license.
+  Whenever there is any discrepancy between the two licenses,
+  the BSD license will take precedence.
+  Set tabs to 4 for best viewing.
+
+  Latest version is available at http://adodb.sourceforge.net
+
+  Informix port by Mitchell T. Young (mitch@youngfamily.org)
+
+  Further mods by "Samuel CARRIERE" <samuel_carriere@hotmail.com>
+
+*/
+
+// security - hide paths
+if (!defined('ADODB_DIR')) die();
+
+if (!defined('IFX_SCROLL')) define('IFX_SCROLL',1);
+
+class ADODB_informix72 extends ADOConnection {
+	var $databaseType = "informix72";
+	var $dataProvider = "informix";
+	var $replaceQuote = "''"; // string to use to replace quotes
+	var $fmtDate = "'Y-m-d'";
+	var $fmtTimeStamp = "'Y-m-d H:i:s'";
+	var $hasInsertID = true;
+	var $hasAffectedRows = true;
+    var $substr = 'substr';
+	var $metaTablesSQL="select tabname,tabtype from systables where tabtype in ('T','V') and owner!='informix'"; //Don't get informix tables and pseudo-tables
+
+
+	var $metaColumnsSQL = 
+		"select c.colname, c.coltype, c.collength, d.default,c.colno
+		from syscolumns c, systables t,outer sysdefaults d
+		where c.tabid=t.tabid and d.tabid=t.tabid and d.colno=c.colno
+		and tabname='%s' order by c.colno";
+
+	var $metaPrimaryKeySQL =
+		"select part1,part2,part3,part4,part5,part6,part7,part8 from
+		systables t,sysconstraints s,sysindexes i where t.tabname='%s'
+		and s.tabid=t.tabid and s.constrtype='P'
+		and i.idxname=s.idxname";
+
+	var $concat_operator = '||';
+
+	var $lastQuery = false;
+	var $has_insertid = true;
+
+	var $_autocommit = true;
+	var $_bindInputArray = true;  // set to true if ADOConnection.Execute() permits binding of array parameters.
+	var $sysDate = 'TODAY';
+	var $sysTimeStamp = 'CURRENT';
+	var $cursorType = IFX_SCROLL; // IFX_SCROLL or IFX_HOLD or 0
+   
+	function ADODB_informix72()
+	{
+		// alternatively, use older method:
+		//putenv("DBDATE=Y4MD-");
+		
+		// force ISO date format
+		putenv('GL_DATE=%Y-%m-%d');
+		
+		if (function_exists('ifx_byteasvarchar')) {
+			ifx_byteasvarchar(1); // Mode "0" will return a blob id, and mode "1" will return a varchar with text content. 
+        	ifx_textasvarchar(1); // Mode "0" will return a blob id, and mode "1" will return a varchar with text content. 
+        	ifx_blobinfile_mode(0); // Mode "0" means save Byte-Blobs in memory, and mode "1" means save Byte-Blobs in a file.
+		}
+	}
+	
+	function ServerInfo()
+	{
+	    if (isset($this->version)) return $this->version;
+	
+	    $arr['description'] = $this->GetOne("select DBINFO('version','full') from systables where tabid = 1");
+	    $arr['version'] = $this->GetOne("select DBINFO('version','major') || DBINFO('version','minor') from systables where tabid = 1");
+	    $this->version = $arr;
+	    return $arr;
+	}
+
+
+
+	function _insertid()
+	{
+		$sqlca =ifx_getsqlca($this->lastQuery);
+		return @$sqlca["sqlerrd1"];
+	}
+
+	function _affectedrows()
+	{
+		if ($this->lastQuery) {
+		   return @ifx_affected_rows ($this->lastQuery);
+		}
+		return 0;
+	}
+
+	function BeginTrans()
+	{
+		if ($this->transOff) return true;
+		$this->transCnt += 1;
+		$this->Execute('BEGIN');
+		$this->_autocommit = false;
+		return true;
+	}
+
+	function CommitTrans($ok=true) 
+	{ 
+		if (!$ok) return $this->RollbackTrans();
+		if ($this->transOff) return true;
+		if ($this->transCnt) $this->transCnt -= 1;
+		$this->Execute('COMMIT');
+		$this->_autocommit = true;
+		return true;
+	}
+
+	function RollbackTrans()
+	{
+		if ($this->transOff) return true;
+		if ($this->transCnt) $this->transCnt -= 1;
+		$this->Execute('ROLLBACK');
+		$this->_autocommit = true;
+		return true;
+	}
+
+	function RowLock($tables,$where,$flds='1 as ignore')
+	{
+		if ($this->_autocommit) $this->BeginTrans();
+		return $this->GetOne("select $flds from $tables where $where for update");
+	}
+
+	/*	Returns: the last error message from previous database operation
+		Note: This function is NOT available for Microsoft SQL Server.	*/
+
+	function ErrorMsg() 
+	{
+		if (!empty($this->_logsql)) return $this->_errorMsg;
+		$this->_errorMsg = ifx_errormsg();
+		return $this->_errorMsg;
+	}
+
+	function ErrorNo()
+	{
+		preg_match("/.*SQLCODE=([^\]]*)/",ifx_error(),$parse);
+		if (is_array($parse) && isset($parse[1])) return (int)$parse[1]; 
+		return 0;
+	}
+
+   
+    function &MetaColumns($table)
+	{
+	global $ADODB_FETCH_MODE;
+	
+		$false = false;
+		if (!empty($this->metaColumnsSQL)) {
+			$save = $ADODB_FETCH_MODE;
+			$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
+			if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false);
+          		$rs = $this->Execute(sprintf($this->metaColumnsSQL,$table));
+			if (isset($savem)) $this->SetFetchMode($savem);
+			$ADODB_FETCH_MODE = $save;
+			if ($rs === false) return $false;
+			$rspkey = $this->Execute(sprintf($this->metaPrimaryKeySQL,$table)); //Added to get primary key colno items
+
+			$retarr = array();
+			while (!$rs->EOF) { //print_r($rs->fields);
+				$fld = new ADOFieldObject();
+				$fld->name = $rs->fields[0];
+/*  //!eos.
+						$rs->fields[1] is not the correct adodb type
+						$rs->fields[2] is not correct max_length, because can include not-null bit
+
+				$fld->type = $rs->fields[1];
+				$fld->primary_key=$rspkey->fields && array_search($rs->fields[4],$rspkey->fields); //Added to set primary key flag
+				$fld->max_length = $rs->fields[2];*/
+				$pr=ifx_props($rs->fields[1],$rs->fields[2]); //!eos
+				$fld->type = $pr[0] ;//!eos
+				$fld->primary_key=$rspkey->fields && array_search($rs->fields[4],$rspkey->fields);
+				$fld->max_length = $pr[1]; //!eos
+				$fld->precision = $pr[2] ;//!eos
+				$fld->not_null = $pr[3]=="N"; //!eos
+
+				if (trim($rs->fields[3]) != "AAAAAA 0") {
+	                    		$fld->has_default = 1;
+	                    		$fld->default_value = $rs->fields[3];
+				} else {
+					$fld->has_default = 0;
+				}
+
+                $retarr[strtolower($fld->name)] = $fld;	
+				$rs->MoveNext();
+			}
+
+			$rs->Close();
+			$rspkey->Close(); //!eos
+			return $retarr;	
+		}
+
+		return $false;
+	}
+	
+   function &xMetaColumns($table)
+   {
+		return ADOConnection::MetaColumns($table,false);
+   }
+
+	 function MetaForeignKeys($table, $owner=false, $upper=false) //!Eos
+	{
+		$sql = "
+			select tr.tabname,updrule,delrule,
+			i.part1 o1,i2.part1 d1,i.part2 o2,i2.part2 d2,i.part3 o3,i2.part3 d3,i.part4 o4,i2.part4 d4,
+			i.part5 o5,i2.part5 d5,i.part6 o6,i2.part6 d6,i.part7 o7,i2.part7 d7,i.part8 o8,i2.part8 d8
+			from systables t,sysconstraints s,sysindexes i,
+			sysreferences r,systables tr,sysconstraints s2,sysindexes i2
+			where t.tabname='$table'
+			and s.tabid=t.tabid and s.constrtype='R' and r.constrid=s.constrid
+			and i.idxname=s.idxname and tr.tabid=r.ptabid
+			and s2.constrid=r.primary and i2.idxname=s2.idxname";
+
+		$rs = $this->Execute($sql);
+		if (!$rs || $rs->EOF)  return false;
+		$arr =& $rs->GetArray();
+		$a = array();
+		foreach($arr as $v) {
+			$coldest=$this->metaColumnNames($v["tabname"]);
+			$colorig=$this->metaColumnNames($table);
+			$colnames=array();
+			for($i=1;$i<=8 && $v["o$i"] ;$i++) {
+				$colnames[]=$coldest[$v["d$i"]-1]."=".$colorig[$v["o$i"]-1];
+			}
+			if($upper)
+				$a[strtoupper($v["tabname"])] =  $colnames;
+			else
+				$a[$v["tabname"]] =  $colnames;
+		}
+		return $a;
+	 }
+
+   function UpdateBlob($table, $column, $val, $where, $blobtype = 'BLOB')
+   {
+   		$type = ($blobtype == 'TEXT') ? 1 : 0;
+		$blobid = ifx_create_blob($type,0,$val);
+		return $this->Execute("UPDATE $table SET $column=(?) WHERE $where",array($blobid));
+   }
+
+   function BlobDecode($blobid)
+   {
+   		return function_exists('ifx_byteasvarchar') ? $blobid : @ifx_get_blob($blobid);
+   }
+   
+	// returns true or false
+   function _connect($argHostname, $argUsername, $argPassword, $argDatabasename)
+	{
+		if (!function_exists('ifx_connect')) return null;
+		
+		$dbs = $argDatabasename . "@" . $argHostname;
+		if ($argHostname) putenv("INFORMIXSERVER=$argHostname"); 
+		putenv("INFORMIXSERVER=".trim($argHostname)); 
+		$this->_connectionID = ifx_connect($dbs,$argUsername,$argPassword);
+		if ($this->_connectionID === false) return false;
+		#if ($argDatabasename) return $this->SelectDB($argDatabasename);
+		return true;
+	}
+
+	// returns true or false
+   function _pconnect($argHostname, $argUsername, $argPassword, $argDatabasename)
+	{
+		if (!function_exists('ifx_connect')) return null;
+		
+		$dbs = $argDatabasename . "@" . $argHostname;
+		putenv("INFORMIXSERVER=".trim($argHostname)); 
+		$this->_connectionID = ifx_pconnect($dbs,$argUsername,$argPassword);
+		if ($this->_connectionID === false) return false;
+		#if ($argDatabasename) return $this->SelectDB($argDatabasename);
+		return true;
+	}
+/*
+	// ifx_do does not accept bind parameters - weird ???
+	function Prepare($sql)
+	{
+		$stmt = ifx_prepare($sql);
+		if (!$stmt) return $sql;
+		else return array($sql,$stmt);
+	}
+*/
+	// returns query ID if successful, otherwise false
+	function _query($sql,$inputarr)
+	{
+	global $ADODB_COUNTRECS;
+	
+	  // String parameters have to be converted using ifx_create_char
+	  if ($inputarr) {
+		 foreach($inputarr as $v) {
+			if (gettype($v) == 'string') {
+			   $tab[] = ifx_create_char($v);
+			}
+			else {
+			   $tab[] = $v;
+			}
+		 }
+	  }
+
+	  // In case of select statement, we use a scroll cursor in order
+	  // to be able to call "move", or "movefirst" statements
+	  if (!$ADODB_COUNTRECS && preg_match("/^\s*select/is", $sql)) {
+		 if ($inputarr) {
+			$this->lastQuery = ifx_query($sql,$this->_connectionID, $this->cursorType, $tab);
+		 }
+		 else {
+			$this->lastQuery = ifx_query($sql,$this->_connectionID, $this->cursorType);
+		 }
+	  }
+	  else {
+		 if ($inputarr) {
+			$this->lastQuery = ifx_query($sql,$this->_connectionID, $tab);
+		 }
+		 else {
+			$this->lastQuery = ifx_query($sql,$this->_connectionID);
+		 }
+	  }
+
+	  // Following line have been commented because autocommit mode is
+	  // not supported by informix SE 7.2
+
+	  //if ($this->_autocommit) ifx_query('COMMIT',$this->_connectionID);
+
+		return $this->lastQuery;
+	}
+
+	// returns true or false
+	function _close()
+	{
+		$this->lastQuery = false;
+		return ifx_close($this->_connectionID);
+	}
+}
+
+
+/*--------------------------------------------------------------------------------------
+	 Class Name: Recordset
+--------------------------------------------------------------------------------------*/
+
+class ADORecordset_informix72 extends ADORecordSet {
+
+	var $databaseType = "informix72";
+	var $canSeek = true;
+	var $_fieldprops = false;
+
+	function ADORecordset_informix72($id,$mode=false)
+	{
+		if ($mode === false) { 
+			global $ADODB_FETCH_MODE;
+			$mode = $ADODB_FETCH_MODE;
+		}
+		$this->fetchMode = $mode;
+		return $this->ADORecordSet($id);
+	}
+
+
+
+	/*	Returns: an object containing field information.
+		Get column information in the Recordset object. fetchField() can be used in order to obtain information about
+		fields in a certain query result. If the field offset isn't specified, the next field that wasn't yet retrieved by
+		fetchField() is retrieved.	*/
+	function &FetchField($fieldOffset = -1)
+	{
+		if (empty($this->_fieldprops)) {
+			$fp = ifx_fieldproperties($this->_queryID);
+			foreach($fp as $k => $v) {
+				$o = new ADOFieldObject;
+				$o->name = $k;
+				$arr = split(';',$v); //"SQLTYPE;length;precision;scale;ISNULLABLE"
+				$o->type = $arr[0];
+				$o->max_length = $arr[1];
+				$this->_fieldprops[] = $o;
+				$o->not_null = $arr[4]=="N";
+			}
+		}
+		$ret = $this->_fieldprops[$fieldOffset];
+		return $ret;
+	}
+
+	function _initrs()
+	{
+		$this->_numOfRows = -1; // ifx_affected_rows not reliable, only returns estimate -- ($ADODB_COUNTRECS)? ifx_affected_rows($this->_queryID):-1;
+		$this->_numOfFields = ifx_num_fields($this->_queryID);
+	}
+
+	function _seek($row)
+	{
+		return @ifx_fetch_row($this->_queryID, (int) $row);
+	}
+
+   function MoveLast()
+   {
+	  $this->fields = @ifx_fetch_row($this->_queryID, "LAST");
+	  if ($this->fields) $this->EOF = false;
+	  $this->_currentRow = -1;
+
+	  if ($this->fetchMode == ADODB_FETCH_NUM) {
+		 foreach($this->fields as $v) {
+			$arr[] = $v;
+		 }
+		 $this->fields = $arr;
+	  }
+
+	  return true;
+   }
+
+   function MoveFirst()
+	{
+	  $this->fields = @ifx_fetch_row($this->_queryID, "FIRST");
+	  if ($this->fields) $this->EOF = false;
+	  $this->_currentRow = 0;
+
+	  if ($this->fetchMode == ADODB_FETCH_NUM) {
+		 foreach($this->fields as $v) {
+			$arr[] = $v;
+		 }
+		 $this->fields = $arr;
+	  }
+
+	  return true;
+   }
+
+   function _fetch($ignore_fields=false)
+   {
+
+		$this->fields = @ifx_fetch_row($this->_queryID);
+
+		if (!is_array($this->fields)) return false;
+
+		if ($this->fetchMode == ADODB_FETCH_NUM) {
+			foreach($this->fields as $v) {
+				$arr[] = $v;
+			}
+			$this->fields = $arr;
+		}
+		return true;
+	}
+
+	/*	close() only needs to be called if you are worried about using too much memory while your script
+		is running. All associated result memory for the specified result identifier will automatically be freed.	*/
+	function _close()
+	{
+		return ifx_free_result($this->_queryID);
+	}
+
+}
+/** !Eos
+* Auxiliar function to Parse coltype,collength. Used by Metacolumns
+* return: array ($mtype,$length,$precision,$nullable) (similar to ifx_fieldpropierties)
+*/
+function ifx_props($coltype,$collength){
+	$itype=fmod($coltype+1,256);
+	$nullable=floor(($coltype+1) /256) ?"N":"Y";
+	$mtype=substr(" CIIFFNNDN TBXCC     ",$itype,1);
+	switch ($itype){
+		case 2:
+			$length=4;
+		case 6:
+		case 9:
+		case 14:
+			$length=floor($collength/256);
+			$precision=fmod($collength,256);
+			break;
+		default:
+			$precision=0;
+			$length=$collength;
+	}
+	return array($mtype,$length,$precision,$nullable);
+}
+
+
+?>
Index: /Dev/trunk/rdfapi/util/adodb/drivers/adodb-ldap.inc.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/drivers/adodb-ldap.inc.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/drivers/adodb-ldap.inc.php	(revision 12)
@@ -0,0 +1,406 @@
+<?php
+/*
+  V4.94 23 Jan 2007  (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
+   Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence.
+  Set tabs to 8.
+  
+  Revision 1: (02/25/2005) Updated codebase to include the _inject_bind_options function. This allows
+  users to access the options in the ldap_set_option function appropriately. Most importantly
+  LDAP Version 3 is now supported. See the examples for more information. Also fixed some minor
+  bugs that surfaced when PHP error levels were set high.
+  
+  Joshua Eldridge (joshuae74#hotmail.com)
+*/ 
+
+// security - hide paths
+if (!defined('ADODB_DIR')) die();
+
+if (!defined('LDAP_ASSOC')) {
+	 define('LDAP_ASSOC',ADODB_FETCH_ASSOC);
+	 define('LDAP_NUM',ADODB_FETCH_NUM);
+	 define('LDAP_BOTH',ADODB_FETCH_BOTH);
+}
+
+class ADODB_ldap extends ADOConnection {
+    var $databaseType = 'ldap';
+	var $dataProvider = 'ldap';
+	
+	# Connection information
+    var $username = false;
+    var $password = false;
+    
+    # Used during searches
+    var $filter;
+    var $dn;
+	var $version;
+	var $port = 389;
+
+	# Options configuration information
+	var $LDAP_CONNECT_OPTIONS;
+
+	function ADODB_ldap() 
+	{		
+	}
+  		
+	// returns true or false
+	
+	function _connect( $host, $username, $password, $ldapbase)
+	{
+	global $LDAP_CONNECT_OPTIONS;
+		
+		if ( !function_exists( 'ldap_connect' ) ) return null;
+		
+		$conn_info = array( $host,$this->port);
+		
+		if ( strstr( $host, ':' ) ) {
+		    $conn_info = split( ':', $host );
+		} 
+		
+		$this->_connectionID = ldap_connect( $conn_info[0], $conn_info[1] );
+		if (!$this->_connectionID) {
+			$e = 'Could not connect to ' . $conn_info[0];
+			$this->_errorMsg = $e;
+			if ($this->debug) ADOConnection::outp($e);
+			return false;
+		}
+		if( count( $LDAP_CONNECT_OPTIONS ) > 0 ) {
+			$this->_inject_bind_options( $LDAP_CONNECT_OPTIONS );
+		}
+		
+		if ($username) {
+		    $bind = ldap_bind( $this->_connectionID, $username, $password );
+		} else {
+			$username = 'anonymous';
+		    $bind = ldap_bind( $this->_connectionID );		
+		}
+		
+		if (!$bind) {
+			$e = 'Could not bind to ' . $conn_info[0] . " as ".$username;
+			$this->_errorMsg = $e;
+			if ($this->debug) ADOConnection::outp($e);
+			return false;
+		}
+		$this->_errorMsg = '';
+		$this->database = $ldapbase;
+		return $this->_connectionID;
+	}
+    
+/*
+	Valid Domain Values for LDAP Options:
+
+	LDAP_OPT_DEREF (integer)
+	LDAP_OPT_SIZELIMIT (integer)
+	LDAP_OPT_TIMELIMIT (integer)
+	LDAP_OPT_PROTOCOL_VERSION (integer)
+	LDAP_OPT_ERROR_NUMBER (integer)
+	LDAP_OPT_REFERRALS (boolean)
+	LDAP_OPT_RESTART (boolean)
+	LDAP_OPT_HOST_NAME (string)
+	LDAP_OPT_ERROR_STRING (string)
+	LDAP_OPT_MATCHED_DN (string)
+	LDAP_OPT_SERVER_CONTROLS (array)
+	LDAP_OPT_CLIENT_CONTROLS (array)
+
+	Make sure to set this BEFORE calling Connect()
+
+	Example:
+
+	$LDAP_CONNECT_OPTIONS = Array(
+		Array (
+			"OPTION_NAME"=>LDAP_OPT_DEREF,
+			"OPTION_VALUE"=>2
+		),
+		Array (
+			"OPTION_NAME"=>LDAP_OPT_SIZELIMIT,
+			"OPTION_VALUE"=>100
+		),
+		Array (
+			"OPTION_NAME"=>LDAP_OPT_TIMELIMIT,
+			"OPTION_VALUE"=>30
+		),
+		Array (
+			"OPTION_NAME"=>LDAP_OPT_PROTOCOL_VERSION,
+			"OPTION_VALUE"=>3
+		),
+		Array (
+			"OPTION_NAME"=>LDAP_OPT_ERROR_NUMBER,
+			"OPTION_VALUE"=>13
+		),
+		Array (
+			"OPTION_NAME"=>LDAP_OPT_REFERRALS,
+			"OPTION_VALUE"=>FALSE
+		),
+		Array (
+			"OPTION_NAME"=>LDAP_OPT_RESTART,
+			"OPTION_VALUE"=>FALSE
+		)
+	);
+*/
+
+	function _inject_bind_options( $options ) {
+		foreach( $options as $option ) {
+			ldap_set_option( $this->_connectionID, $option["OPTION_NAME"], $option["OPTION_VALUE"] )
+				or die( "Unable to set server option: " . $option["OPTION_NAME"] );
+		}
+	}
+	
+	/* returns _queryID or false */
+	function _query($sql,$inputarr)
+	{
+		$rs = ldap_search( $this->_connectionID, $this->database, $sql );
+		$this->_errorMsg = ($rs) ? '' : 'Search error on '.$sql;
+		return $rs; 
+	}
+
+    /* closes the LDAP connection */
+	function _close()
+	{
+		@ldap_close( $this->_connectionID );
+		$this->_connectionID = false;
+	}
+    
+	function SelectDB($db) {
+		$this->database = $db;
+		return true;
+	} // SelectDB
+
+    function ServerInfo()
+    {
+        if( !empty( $this->version ) ) return $this->version;
+        $version = array();
+        /*
+        Determines how aliases are handled during search. 
+        LDAP_DEREF_NEVER (0x00)
+        LDAP_DEREF_SEARCHING (0x01)
+        LDAP_DEREF_FINDING (0x02)
+        LDAP_DEREF_ALWAYS (0x03)
+        The LDAP_DEREF_SEARCHING value means aliases are dereferenced during the search but 
+        not when locating the base object of the search. The LDAP_DEREF_FINDING value means 
+        aliases are dereferenced when locating the base object but not during the search.  
+        Default: LDAP_DEREF_NEVER
+        */
+        ldap_get_option( $this->_connectionID, LDAP_OPT_DEREF, $version['LDAP_OPT_DEREF'] ) ;
+        switch ( $version['LDAP_OPT_DEREF'] ) {
+          case 0:
+            $version['LDAP_OPT_DEREF'] = 'LDAP_DEREF_NEVER';
+          case 1:
+            $version['LDAP_OPT_DEREF'] = 'LDAP_DEREF_SEARCHING';
+          case 2:
+            $version['LDAP_OPT_DEREF'] = 'LDAP_DEREF_FINDING';
+          case 3:
+            $version['LDAP_OPT_DEREF'] = 'LDAP_DEREF_ALWAYS';
+        }
+        
+        /* 
+        A limit on the number of entries to return from a search. 
+        LDAP_NO_LIMIT (0) means no limit.
+        Default: LDAP_NO_LIMIT
+        */
+        ldap_get_option( $this->_connectionID, LDAP_OPT_SIZELIMIT, $version['LDAP_OPT_SIZELIMIT'] );
+        if ( $version['LDAP_OPT_SIZELIMIT'] == 0 ) {
+           $version['LDAP_OPT_SIZELIMIT'] = 'LDAP_NO_LIMIT';
+        }
+        
+        /*
+        A limit on the number of seconds to spend on a search. 
+        LDAP_NO_LIMIT (0) means no limit.
+        Default: LDAP_NO_LIMIT
+        */
+        ldap_get_option( $this->_connectionID, LDAP_OPT_TIMELIMIT, $version['LDAP_OPT_TIMELIMIT'] );
+        if ( $version['LDAP_OPT_TIMELIMIT'] == 0 ) {
+           $version['LDAP_OPT_TIMELIMIT'] = 'LDAP_NO_LIMIT';
+        }
+        
+        /*
+        Determines whether the LDAP library automatically follows referrals returned by LDAP servers or not. 
+        LDAP_OPT_ON
+        LDAP_OPT_OFF
+        Default: ON
+        */
+        ldap_get_option( $this->_connectionID, LDAP_OPT_REFERRALS, $version['LDAP_OPT_REFERRALS'] );
+        if ( $version['LDAP_OPT_REFERRALS'] == 0 ) {
+           $version['LDAP_OPT_REFERRALS'] = 'LDAP_OPT_OFF';
+        } else {
+           $version['LDAP_OPT_REFERRALS'] = 'LDAP_OPT_ON';
+        
+        }
+        /*
+        Determines whether LDAP I/O operations are automatically restarted if they abort prematurely. 
+        LDAP_OPT_ON
+        LDAP_OPT_OFF
+        Default: OFF
+        */
+        ldap_get_option( $this->_connectionID, LDAP_OPT_RESTART, $version['LDAP_OPT_RESTART'] );
+        if ( $version['LDAP_OPT_RESTART'] == 0 ) {
+           $version['LDAP_OPT_RESTART'] = 'LDAP_OPT_OFF';
+        } else {
+           $version['LDAP_OPT_RESTART'] = 'LDAP_OPT_ON';
+        
+        }
+        /*
+        This option indicates the version of the LDAP protocol used when communicating with the primary LDAP server.
+        LDAP_VERSION2 (2)
+        LDAP_VERSION3 (3)
+        Default: LDAP_VERSION2 (2)
+        */
+        ldap_get_option( $this->_connectionID, LDAP_OPT_PROTOCOL_VERSION, $version['LDAP_OPT_PROTOCOL_VERSION'] );
+        if ( $version['LDAP_OPT_PROTOCOL_VERSION'] == 2 ) {
+           $version['LDAP_OPT_PROTOCOL_VERSION'] = 'LDAP_VERSION2';
+        } else {
+           $version['LDAP_OPT_PROTOCOL_VERSION'] = 'LDAP_VERSION3';
+        
+        }
+        /* The host name (or list of hosts) for the primary LDAP server. */
+        ldap_get_option( $this->_connectionID, LDAP_OPT_HOST_NAME, $version['LDAP_OPT_HOST_NAME'] ); 
+        ldap_get_option( $this->_connectionID, LDAP_OPT_ERROR_NUMBER, $version['LDAP_OPT_ERROR_NUMBER'] ); 
+        ldap_get_option( $this->_connectionID, LDAP_OPT_ERROR_STRING, $version['LDAP_OPT_ERROR_STRING'] ); 
+        ldap_get_option( $this->_connectionID, LDAP_OPT_MATCHED_DN, $version['LDAP_OPT_MATCHED_DN'] ); 
+        
+        return $this->version = $version;
+    
+    }
+}
+	
+/*--------------------------------------------------------------------------------------
+	 Class Name: Recordset
+--------------------------------------------------------------------------------------*/
+
+class ADORecordSet_ldap extends ADORecordSet{	
+	
+	var $databaseType = "ldap";
+	var $canSeek = false;
+	var $_entryID; /* keeps track of the entry resource identifier */
+	
+	function ADORecordSet_ldap($queryID,$mode=false) 
+	{
+		if ($mode === false) { 
+			global $ADODB_FETCH_MODE;
+			$mode = $ADODB_FETCH_MODE;
+		}
+		switch ($mode)
+		{
+		case ADODB_FETCH_NUM: 
+		  $this->fetchMode = LDAP_NUM; 
+		break;
+		case ADODB_FETCH_ASSOC: 
+		  $this->fetchMode = LDAP_ASSOC; 
+		break;
+		case ADODB_FETCH_DEFAULT:
+		case ADODB_FETCH_BOTH: 
+		default:
+		  $this->fetchMode = LDAP_BOTH; 
+		break;
+		}
+	
+		$this->ADORecordSet($queryID);	
+	}
+	
+	function _initrs()
+	{
+	   /* 
+	   This could be teaked to respect the $COUNTRECS directive from ADODB
+	   It's currently being used in the _fetch() function and the
+	   GetAssoc() function
+       */
+	    $this->_numOfRows = ldap_count_entries( $this->connection->_connectionID, $this->_queryID );
+
+	}
+
+    /*
+    Return whole recordset as a multi-dimensional associative array
+	*/
+	function &GetAssoc($force_array = false, $first2cols = false) 
+	{
+		$records = $this->_numOfRows;
+        $results = array();
+            for ( $i=0; $i < $records; $i++ ) {
+                foreach ( $this->fields as $k=>$v ) {
+                    if ( is_array( $v ) ) {
+                        if ( $v['count'] == 1 ) {
+                            $results[$i][$k] = $v[0];
+                        } else {
+                            array_shift( $v );
+                            $results[$i][$k] = $v;
+                        } 
+                    }
+                }
+            }
+        
+		return $results; 
+	}
+    
+    function &GetRowAssoc()
+	{
+        $results = array();
+        foreach ( $this->fields as $k=>$v ) {
+            if ( is_array( $v ) ) {
+                if ( $v['count'] == 1 ) {
+                    $results[$k] = $v[0];
+                } else {
+                    array_shift( $v );
+                    $results[$k] = $v;
+                } 
+            }
+        }
+ 
+		return $results; 
+	}
+		
+    function GetRowNums()
+    {
+        $results = array();
+        foreach ( $this->fields as $k=>$v ) {
+        static $i = 0;
+            if (is_array( $v )) {
+                if ( $v['count'] == 1 ) {
+                    $results[$i] = $v[0];
+                } else {
+                    array_shift( $v );
+                    $results[$i] = $v;
+                } 
+            $i++;
+            }
+        }
+        return $results;
+    }
+	
+	function _fetch()
+	{		
+		if ( $this->_currentRow >= $this->_numOfRows && $this->_numOfRows >= 0 )
+        	return false;
+        	
+        if ( $this->_currentRow == 0 ) {
+		  $this->_entryID = ldap_first_entry( $this->connection->_connectionID, $this->_queryID );
+        } else {
+          $this->_entryID = ldap_next_entry( $this->connection->_connectionID, $this->_entryID );
+        }
+	    
+	    $this->fields = ldap_get_attributes( $this->connection->_connectionID, $this->_entryID );
+	    $this->_numOfFields = $this->fields['count'];	
+	    switch ( $this->fetchMode ) {
+            
+            case LDAP_ASSOC:
+            $this->fields = $this->GetRowAssoc();
+            break;
+            
+            case LDAP_NUM:
+			$this->fields = array_merge($this->GetRowNums(),$this->GetRowAssoc());
+            break;
+            
+            case LDAP_BOTH:
+            default:
+			$this->fields = $this->GetRowNums();
+            break;
+        }
+        return ( is_array( $this->fields ) );        
+	}
+	
+	function _close() {
+		@ldap_free_result( $this->_queryID );	
+		$this->_queryID = false;
+	}
+	
+}
+?>
Index: /Dev/trunk/rdfapi/util/adodb/drivers/adodb-mssql.inc.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/drivers/adodb-mssql.inc.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/drivers/adodb-mssql.inc.php	(revision 12)
@@ -0,0 +1,1037 @@
+<?php
+/* 
+V4.94 23 Jan 2007  (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence. 
+Set tabs to 4 for best viewing.
+  
+  Latest version is available at http://adodb.sourceforge.net
+  
+  Native mssql driver. Requires mssql client. Works on Windows. 
+  To configure for Unix, see 
+   	http://phpbuilder.com/columns/alberto20000919.php3
+	
+*/
+
+// security - hide paths
+if (!defined('ADODB_DIR')) die();
+
+//----------------------------------------------------------------
+// MSSQL returns dates with the format Oct 13 2002 or 13 Oct 2002
+// and this causes tons of problems because localized versions of 
+// MSSQL will return the dates in dmy or  mdy order; and also the 
+// month strings depends on what language has been configured. The 
+// following two variables allow you to control the localization
+// settings - Ugh.
+//
+// MORE LOCALIZATION INFO
+// ----------------------
+// To configure datetime, look for and modify sqlcommn.loc, 
+//  	typically found in c:\mssql\install
+// Also read :
+//	 http://support.microsoft.com/default.aspx?scid=kb;EN-US;q220918
+// Alternatively use:
+// 	   CONVERT(char(12),datecol,120)
+//----------------------------------------------------------------
+
+
+// has datetime converstion to YYYY-MM-DD format, and also mssql_fetch_assoc
+if (ADODB_PHPVER >= 0x4300) {
+// docs say 4.2.0, but testing shows only since 4.3.0 does it work!
+	ini_set('mssql.datetimeconvert',0); 
+} else {
+global $ADODB_mssql_mths;		// array, months must be upper-case
+
+
+	$ADODB_mssql_date_order = 'mdy'; 
+	$ADODB_mssql_mths = array(
+		'JAN'=>1,'FEB'=>2,'MAR'=>3,'APR'=>4,'MAY'=>5,'JUN'=>6,
+		'JUL'=>7,'AUG'=>8,'SEP'=>9,'OCT'=>10,'NOV'=>11,'DEC'=>12);
+}
+
+//---------------------------------------------------------------------------
+// Call this to autoset $ADODB_mssql_date_order at the beginning of your code,
+// just after you connect to the database. Supports mdy and dmy only.
+// Not required for PHP 4.2.0 and above.
+function AutoDetect_MSSQL_Date_Order($conn)
+{
+global $ADODB_mssql_date_order;
+	$adate = $conn->GetOne('select getdate()');
+	if ($adate) {
+		$anum = (int) $adate;
+		if ($anum > 0) {
+			if ($anum > 31) {
+				//ADOConnection::outp( "MSSQL: YYYY-MM-DD date format not supported currently");
+			} else
+				$ADODB_mssql_date_order = 'dmy';
+		} else
+			$ADODB_mssql_date_order = 'mdy';
+	}
+}
+
+class ADODB_mssql extends ADOConnection {
+	var $databaseType = "mssql";	
+	var $dataProvider = "mssql";
+	var $replaceQuote = "''"; // string to use to replace quotes
+	var $fmtDate = "'Y-m-d'";
+	var $fmtTimeStamp = "'Y-m-d H:i:s'";
+	var $hasInsertID = true;
+	var $substr = "substring";
+	var $length = 'len';
+	var $hasAffectedRows = true;
+	var $metaDatabasesSQL = "select name from sysdatabases where name <> 'master'";
+	var $metaTablesSQL="select name,case when type='U' then 'T' else 'V' end from sysobjects where (type='U' or type='V') and (name not in ('sysallocations','syscolumns','syscomments','sysdepends','sysfilegroups','sysfiles','sysfiles1','sysforeignkeys','sysfulltextcatalogs','sysindexes','sysindexkeys','sysmembers','sysobjects','syspermissions','sysprotects','sysreferences','systypes','sysusers','sysalternates','sysconstraints','syssegments','REFERENTIAL_CONSTRAINTS','CHECK_CONSTRAINTS','CONSTRAINT_TABLE_USAGE','CONSTRAINT_COLUMN_USAGE','VIEWS','VIEW_TABLE_USAGE','VIEW_COLUMN_USAGE','SCHEMATA','TABLES','TABLE_CONSTRAINTS','TABLE_PRIVILEGES','COLUMNS','COLUMN_DOMAIN_USAGE','COLUMN_PRIVILEGES','DOMAINS','DOMAIN_CONSTRAINTS','KEY_COLUMN_USAGE','dtproperties'))";
+	var $metaColumnsSQL = # xtype==61 is datetime
+"select c.name,t.name,c.length,
+	(case when c.xusertype=61 then 0 else c.xprec end),
+	(case when c.xusertype=61 then 0 else c.xscale end) 
+	from syscolumns c join systypes t on t.xusertype=c.xusertype join sysobjects o on o.id=c.id where o.name='%s'";
+	var $hasTop = 'top';		// support mssql SELECT TOP 10 * FROM TABLE
+	var $hasGenID = true;
+	var $sysDate = 'convert(datetime,convert(char,GetDate(),102),102)';
+	var $sysTimeStamp = 'GetDate()';
+	var $_has_mssql_init;
+	var $maxParameterLen = 4000;
+	var $arrayClass = 'ADORecordSet_array_mssql';
+	var $uniqueSort = true;
+	var $leftOuter = '*=';
+	var $rightOuter = '=*';
+	var $ansiOuter = true; // for mssql7 or later
+	var $poorAffectedRows = true;
+	var $identitySQL = 'select @@IDENTITY'; // 'select SCOPE_IDENTITY'; # for mssql 2000
+	var $uniqueOrderBy = true;
+	var $_bindInputArray = true;
+	
+	function ADODB_mssql() 
+	{		
+		$this->_has_mssql_init = (strnatcmp(PHP_VERSION,'4.1.0')>=0);
+	}
+
+	function ServerInfo()
+	{
+	global $ADODB_FETCH_MODE;
+	
+	
+		if ($this->fetchMode === false) {
+			$savem = $ADODB_FETCH_MODE;
+			$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
+		} else 
+			$savem = $this->SetFetchMode(ADODB_FETCH_NUM);
+				
+		if (0) {
+			$stmt = $this->PrepareSP('sp_server_info');
+			$val = 2;
+			$this->Parameter($stmt,$val,'attribute_id');
+			$row = $this->GetRow($stmt);
+		}
+		
+		$row = $this->GetRow("execute sp_server_info 2");
+		
+		
+		if ($this->fetchMode === false) {
+			$ADODB_FETCH_MODE = $savem;
+		} else
+			$this->SetFetchMode($savem);
+		
+		$arr['description'] = $row[2];
+		$arr['version'] = ADOConnection::_findvers($arr['description']);
+		return $arr;
+	}
+	
+	function IfNull( $field, $ifNull ) 
+	{
+		return " ISNULL($field, $ifNull) "; // if MS SQL Server
+	}
+	
+	function _insertid()
+	{
+	// SCOPE_IDENTITY()
+	// Returns the last IDENTITY value inserted into an IDENTITY column in 
+	// the same scope. A scope is a module -- a stored procedure, trigger, 
+	// function, or batch. Thus, two statements are in the same scope if 
+	// they are in the same stored procedure, function, or batch.
+			return $this->GetOne($this->identitySQL);
+	}
+
+	function _affectedrows()
+	{
+		return $this->GetOne('select @@rowcount');
+	}
+
+	var $_dropSeqSQL = "drop table %s";
+	
+	function CreateSequence($seq='adodbseq',$start=1)
+	{
+		
+		$this->Execute('BEGIN TRANSACTION adodbseq');
+		$start -= 1;
+		$this->Execute("create table $seq (id float(53))");
+		$ok = $this->Execute("insert into $seq with (tablock,holdlock) values($start)");
+		if (!$ok) {
+				$this->Execute('ROLLBACK TRANSACTION adodbseq');
+				return false;
+		}
+		$this->Execute('COMMIT TRANSACTION adodbseq'); 
+		return true;
+	}
+
+	function GenID($seq='adodbseq',$start=1)
+	{
+		//$this->debug=1;
+		$this->Execute('BEGIN TRANSACTION adodbseq');
+		$ok = $this->Execute("update $seq with (tablock,holdlock) set id = id + 1");
+		if (!$ok) {
+			$this->Execute("create table $seq (id float(53))");
+			$ok = $this->Execute("insert into $seq with (tablock,holdlock) values($start)");
+			if (!$ok) {
+				$this->Execute('ROLLBACK TRANSACTION adodbseq');
+				return false;
+			}
+			$this->Execute('COMMIT TRANSACTION adodbseq'); 
+			return $start;
+		}
+		$num = $this->GetOne("select id from $seq");
+		$this->Execute('COMMIT TRANSACTION adodbseq'); 
+		return $num;
+		
+		// in old implementation, pre 1.90, we returned GUID...
+		//return $this->GetOne("SELECT CONVERT(varchar(255), NEWID()) AS 'Char'");
+	}
+	
+
+	function &SelectLimit($sql,$nrows=-1,$offset=-1, $inputarr=false,$secs2cache=0)
+	{
+		if ($nrows > 0 && $offset <= 0) {
+			$sql = preg_replace(
+				'/(^\s*select\s+(distinctrow|distinct)?)/i','\\1 '.$this->hasTop." $nrows ",$sql);
+			$rs =& $this->Execute($sql,$inputarr);
+		} else
+			$rs =& ADOConnection::SelectLimit($sql,$nrows,$offset,$inputarr,$secs2cache);
+	
+		return $rs;
+	}
+	
+	
+	// Format date column in sql string given an input format that understands Y M D
+	function SQLDate($fmt, $col=false)
+	{	
+		if (!$col) $col = $this->sysTimeStamp;
+		$s = '';
+		
+		$len = strlen($fmt);
+		for ($i=0; $i < $len; $i++) {
+			if ($s) $s .= '+';
+			$ch = $fmt[$i];
+			switch($ch) {
+			case 'Y':
+			case 'y':
+				$s .= "datename(yyyy,$col)";
+				break;
+			case 'M':
+				$s .= "convert(char(3),$col,0)";
+				break;
+			case 'm':
+				$s .= "replace(str(month($col),2),' ','0')";
+				break;
+			case 'Q':
+			case 'q':
+				$s .= "datename(quarter,$col)";
+				break;
+			case 'D':
+			case 'd':
+				$s .= "replace(str(day($col),2),' ','0')";
+				break;
+			case 'h':
+				$s .= "substring(convert(char(14),$col,0),13,2)";
+				break;
+			
+			case 'H':
+				$s .= "replace(str(datepart(hh,$col),2),' ','0')";
+				break;
+				
+			case 'i':
+				$s .= "replace(str(datepart(mi,$col),2),' ','0')";
+				break;
+			case 's':
+				$s .= "replace(str(datepart(ss,$col),2),' ','0')";
+				break;
+			case 'a':
+			case 'A':
+				$s .= "substring(convert(char(19),$col,0),18,2)";
+				break;
+				
+			default:
+				if ($ch == '\\') {
+					$i++;
+					$ch = substr($fmt,$i,1);
+				}
+				$s .= $this->qstr($ch);
+				break;
+			}
+		}
+		return $s;
+	}
+
+	
+	function BeginTrans()
+	{
+		if ($this->transOff) return true; 
+		$this->transCnt += 1;
+	   	$this->Execute('BEGIN TRAN');
+	   	return true;
+	}
+		
+	function CommitTrans($ok=true) 
+	{ 
+		if ($this->transOff) return true; 
+		if (!$ok) return $this->RollbackTrans();
+		if ($this->transCnt) $this->transCnt -= 1;
+		$this->Execute('COMMIT TRAN');
+		return true;
+	}
+	function RollbackTrans()
+	{
+		if ($this->transOff) return true; 
+		if ($this->transCnt) $this->transCnt -= 1;
+		$this->Execute('ROLLBACK TRAN');
+		return true;
+	}
+	
+	function SetTransactionMode( $transaction_mode ) 
+	{
+		$this->_transmode  = $transaction_mode;
+		if (empty($transaction_mode)) {
+			$this->Execute('SET TRANSACTION ISOLATION LEVEL READ COMMITTED');
+			return;
+		}
+		if (!stristr($transaction_mode,'isolation')) $transaction_mode = 'ISOLATION LEVEL '.$transaction_mode;
+		$this->Execute("SET TRANSACTION ".$transaction_mode);
+	}
+	
+	/*
+		Usage:
+		
+		$this->BeginTrans();
+		$this->RowLock('table1,table2','table1.id=33 and table2.id=table1.id'); # lock row 33 for both tables
+		
+		# some operation on both tables table1 and table2
+		
+		$this->CommitTrans();
+		
+		See http://www.swynk.com/friends/achigrik/SQL70Locks.asp
+	*/
+	function RowLock($tables,$where,$flds='top 1 null as ignore') 
+	{
+		if (!$this->transCnt) $this->BeginTrans();
+		return $this->GetOne("select $flds from $tables with (ROWLOCK,HOLDLOCK) where $where");
+	}
+	
+	
+	function &MetaIndexes($table,$primary=false)
+	{
+		$table = $this->qstr($table);
+
+		$sql = "SELECT i.name AS ind_name, C.name AS col_name, USER_NAME(O.uid) AS Owner, c.colid, k.Keyno, 
+			CASE WHEN I.indid BETWEEN 1 AND 254 AND (I.status & 2048 = 2048 OR I.Status = 16402 AND O.XType = 'V') THEN 1 ELSE 0 END AS IsPK,
+			CASE WHEN I.status & 2 = 2 THEN 1 ELSE 0 END AS IsUnique
+			FROM dbo.sysobjects o INNER JOIN dbo.sysindexes I ON o.id = i.id 
+			INNER JOIN dbo.sysindexkeys K ON I.id = K.id AND I.Indid = K.Indid 
+			INNER JOIN dbo.syscolumns c ON K.id = C.id AND K.colid = C.Colid
+			WHERE LEFT(i.name, 8) <> '_WA_Sys_' AND o.status >= 0 AND O.Name LIKE $table
+			ORDER BY O.name, I.Name, K.keyno";
+
+		global $ADODB_FETCH_MODE;
+		$save = $ADODB_FETCH_MODE;
+        $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
+        if ($this->fetchMode !== FALSE) {
+        	$savem = $this->SetFetchMode(FALSE);
+        }
+        
+        $rs = $this->Execute($sql);
+        if (isset($savem)) {
+        	$this->SetFetchMode($savem);
+        }
+        $ADODB_FETCH_MODE = $save;
+
+        if (!is_object($rs)) {
+        	return FALSE;
+        }
+
+		$indexes = array();
+		while ($row = $rs->FetchRow()) {
+			if (!$primary && $row[5]) continue;
+			
+            $indexes[$row[0]]['unique'] = $row[6];
+            $indexes[$row[0]]['columns'][] = $row[1];
+    	}
+        return $indexes;
+	}
+	
+	function MetaForeignKeys($table, $owner=false, $upper=false)
+	{
+	global $ADODB_FETCH_MODE;
+	
+		$save = $ADODB_FETCH_MODE;
+		$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
+		$table = $this->qstr(strtoupper($table));
+		
+		$sql = 
+"select object_name(constid) as constraint_name,
+	col_name(fkeyid, fkey) as column_name,
+	object_name(rkeyid) as referenced_table_name,
+   	col_name(rkeyid, rkey) as referenced_column_name
+from sysforeignkeys
+where upper(object_name(fkeyid)) = $table
+order by constraint_name, referenced_table_name, keyno";
+		
+		$constraints =& $this->GetArray($sql);
+		
+		$ADODB_FETCH_MODE = $save;
+		
+		$arr = false;
+		foreach($constraints as $constr) {
+			//print_r($constr);
+			$arr[$constr[0]][$constr[2]][] = $constr[1].'='.$constr[3]; 
+		}
+		if (!$arr) return false;
+		
+		$arr2 = false;
+		
+		foreach($arr as $k => $v) {
+			foreach($v as $a => $b) {
+				if ($upper) $a = strtoupper($a);
+				$arr2[$a] = $b;
+			}
+		}
+		return $arr2;
+	}
+
+	//From: Fernando Moreira <FMoreira@imediata.pt>
+	function MetaDatabases() 
+	{ 
+		if(@mssql_select_db("master")) { 
+				 $qry=$this->metaDatabasesSQL; 
+				 if($rs=@mssql_query($qry,$this->_connectionID)){ 
+						 $tmpAr=$ar=array(); 
+						 while($tmpAr=@mssql_fetch_row($rs)) 
+								 $ar[]=$tmpAr[0]; 
+						@mssql_select_db($this->database); 
+						 if(sizeof($ar)) 
+								 return($ar); 
+						 else 
+								 return(false); 
+				 } else { 
+						 @mssql_select_db($this->database); 
+						 return(false); 
+				 } 
+		 } 
+		 return(false); 
+	} 
+
+	// "Stein-Aksel Basma" <basma@accelero.no>
+	// tested with MSSQL 2000
+	function &MetaPrimaryKeys($table)
+	{
+	global $ADODB_FETCH_MODE;
+	
+		$schema = '';
+		$this->_findschema($table,$schema);
+		if (!$schema) $schema = $this->database;
+		if ($schema) $schema = "and k.table_catalog like '$schema%'"; 
+
+		$sql = "select distinct k.column_name,ordinal_position from information_schema.key_column_usage k,
+		information_schema.table_constraints tc 
+		where tc.constraint_name = k.constraint_name and tc.constraint_type =
+		'PRIMARY KEY' and k.table_name = '$table' $schema order by ordinal_position ";
+		
+		$savem = $ADODB_FETCH_MODE;
+		$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
+		$a = $this->GetCol($sql);
+		$ADODB_FETCH_MODE = $savem;
+		
+		if ($a && sizeof($a)>0) return $a;
+		$false = false;
+		return $false;	  
+	}
+
+	
+	function &MetaTables($ttype=false,$showSchema=false,$mask=false) 
+	{
+		if ($mask) {
+			$save = $this->metaTablesSQL;
+			$mask = $this->qstr(($mask));
+			$this->metaTablesSQL .= " AND name like $mask";
+		}
+		$ret =& ADOConnection::MetaTables($ttype,$showSchema);
+		
+		if ($mask) {
+			$this->metaTablesSQL = $save;
+		}
+		return $ret;
+	}
+ 
+	function SelectDB($dbName) 
+	{
+		$this->database = $dbName;
+		$this->databaseName = $dbName; # obsolete, retained for compat with older adodb versions
+		if ($this->_connectionID) {
+			return @mssql_select_db($dbName);		
+		}
+		else return false;	
+	}
+	
+	function ErrorMsg() 
+	{
+		if (empty($this->_errorMsg)){
+			$this->_errorMsg = mssql_get_last_message();
+		}
+		return $this->_errorMsg;
+	}
+	
+	function ErrorNo() 
+	{
+		if ($this->_logsql && $this->_errorCode !== false) return $this->_errorCode;
+		if (empty($this->_errorMsg)) {
+			$this->_errorMsg = mssql_get_last_message();
+		}
+		$id = @mssql_query("select @@ERROR",$this->_connectionID);
+		if (!$id) return false;
+		$arr = mssql_fetch_array($id);
+		@mssql_free_result($id);
+		if (is_array($arr)) return $arr[0];
+	   else return -1;
+	}
+	
+	// returns true or false
+	function _connect($argHostname, $argUsername, $argPassword, $argDatabasename)
+	{
+		if (!function_exists('mssql_pconnect')) return null;
+		$this->_connectionID = mssql_connect($argHostname,$argUsername,$argPassword);
+		if ($this->_connectionID === false) return false;
+		if ($argDatabasename) return $this->SelectDB($argDatabasename);
+		return true;	
+	}
+	
+	
+	// returns true or false
+	function _pconnect($argHostname, $argUsername, $argPassword, $argDatabasename)
+	{
+		if (!function_exists('mssql_pconnect')) return null;
+		$this->_connectionID = mssql_pconnect($argHostname,$argUsername,$argPassword);
+		if ($this->_connectionID === false) return false;
+		
+		// persistent connections can forget to rollback on crash, so we do it here.
+		if ($this->autoRollback) {
+			$cnt = $this->GetOne('select @@TRANCOUNT');
+			while (--$cnt >= 0) $this->Execute('ROLLBACK TRAN'); 
+		}
+		if ($argDatabasename) return $this->SelectDB($argDatabasename);
+		return true;	
+	}
+	
+	function Prepare($sql)
+	{
+		$sqlarr = explode('?',$sql);
+		if (sizeof($sqlarr) <= 1) return $sql;
+		$sql2 = $sqlarr[0];
+		for ($i = 1, $max = sizeof($sqlarr); $i < $max; $i++) {
+			$sql2 .=  '@P'.($i-1) . $sqlarr[$i];
+		} 
+		return array($sql,$this->qstr($sql2),$max);
+	}
+	
+	function PrepareSP($sql)
+	{
+		if (!$this->_has_mssql_init) {
+			ADOConnection::outp( "PrepareSP: mssql_init only available since PHP 4.1.0");
+			return $sql;
+		}
+		$stmt = mssql_init($sql,$this->_connectionID);
+		if (!$stmt)  return $sql;
+		return array($sql,$stmt);
+	}
+	
+	// returns concatenated string
+    // MSSQL requires integers to be cast as strings
+    // automatically cast every datatype to VARCHAR(255)
+    // @author David Rogers (introspectshun)
+    function Concat()
+    {
+            $s = "";
+            $arr = func_get_args();
+
+            // Split single record on commas, if possible
+            if (sizeof($arr) == 1) {
+                foreach ($arr as $arg) {
+                    $args = explode(',', $arg);
+                }
+                $arr = $args;
+            }
+
+            array_walk($arr, create_function('&$v', '$v = "CAST(" . $v . " AS VARCHAR(255))";'));
+            $s = implode('+',$arr);
+            if (sizeof($arr) > 0) return "$s";
+            
+			return '';
+    }
+	
+	/* 
+	Usage:
+		$stmt = $db->PrepareSP('SP_RUNSOMETHING'); -- takes 2 params, @myid and @group
+		
+		# note that the parameter does not have @ in front!
+		$db->Parameter($stmt,$id,'myid');
+		$db->Parameter($stmt,$group,'group',false,64);
+		$db->Execute($stmt);
+		
+		@param $stmt Statement returned by Prepare() or PrepareSP().
+		@param $var PHP variable to bind to. Can set to null (for isNull support).
+		@param $name Name of stored procedure variable name to bind to.
+		@param [$isOutput] Indicates direction of parameter 0/false=IN  1=OUT  2= IN/OUT. This is ignored in oci8.
+		@param [$maxLen] Holds an maximum length of the variable.
+		@param [$type] The data type of $var. Legal values depend on driver.
+		
+		See mssql_bind documentation at php.net.
+	*/
+	function Parameter(&$stmt, &$var, $name, $isOutput=false, $maxLen=4000, $type=false)
+	{
+		if (!$this->_has_mssql_init) {
+			ADOConnection::outp( "Parameter: mssql_bind only available since PHP 4.1.0");
+			return false;
+		}
+
+		$isNull = is_null($var); // php 4.0.4 and above...
+			
+		if ($type === false) 
+			switch(gettype($var)) {
+			default:
+			case 'string': $type = SQLCHAR; break;
+			case 'double': $type = SQLFLT8; break;
+			case 'integer': $type = SQLINT4; break;
+			case 'boolean': $type = SQLINT1; break; # SQLBIT not supported in 4.1.0
+			}
+		
+		if  ($this->debug) {
+			$prefix = ($isOutput) ? 'Out' : 'In';
+			$ztype = (empty($type)) ? 'false' : $type;
+			ADOConnection::outp( "{$prefix}Parameter(\$stmt, \$php_var='$var', \$name='$name', \$maxLen=$maxLen, \$type=$ztype);");
+		}
+		/*
+			See http://phplens.com/lens/lensforum/msgs.php?id=7231
+			
+			RETVAL is HARD CODED into php_mssql extension:
+			The return value (a long integer value) is treated like a special OUTPUT parameter, 
+			called "RETVAL" (without the @). See the example at mssql_execute to 
+			see how it works. - type: one of this new supported PHP constants. 
+				SQLTEXT, SQLVARCHAR,SQLCHAR, SQLINT1,SQLINT2, SQLINT4, SQLBIT,SQLFLT8 
+		*/
+		if ($name !== 'RETVAL') $name = '@'.$name;
+		return mssql_bind($stmt[1], $name, $var, $type, $isOutput, $isNull, $maxLen);
+	}
+	
+	/* 
+		Unfortunately, it appears that mssql cannot handle varbinary > 255 chars
+		So all your blobs must be of type "image".
+		
+		Remember to set in php.ini the following...
+		
+		; Valid range 0 - 2147483647. Default = 4096. 
+		mssql.textlimit = 0 ; zero to pass through 
+
+		; Valid range 0 - 2147483647. Default = 4096. 
+		mssql.textsize = 0 ; zero to pass through 
+	*/
+	function UpdateBlob($table,$column,$val,$where,$blobtype='BLOB')
+	{
+	
+		if (strtoupper($blobtype) == 'CLOB') {
+			$sql = "UPDATE $table SET $column='" . $val . "' WHERE $where";
+			return $this->Execute($sql) != false;
+		}
+		$sql = "UPDATE $table SET $column=0x".bin2hex($val)." WHERE $where";
+		return $this->Execute($sql) != false;
+	}
+	
+	// returns query ID if successful, otherwise false
+	function _query($sql,$inputarr)
+	{
+		$this->_errorMsg = false;
+		if (is_array($inputarr)) {
+			
+			# bind input params with sp_executesql: 
+			# see http://www.quest-pipelines.com/newsletter-v3/0402_F.htm
+			# works only with sql server 7 and newer
+			if (!is_array($sql)) $sql = $this->Prepare($sql);
+			$params = '';
+			$decl = '';
+			$i = 0;
+			foreach($inputarr as $v) {
+				if ($decl) {
+					$decl .= ', ';
+					$params .= ', ';
+				}	
+				if (is_string($v)) {
+					$len = strlen($v);
+					if ($len == 0) $len = 1;
+					
+					if ($len > 4000 ) {
+						// NVARCHAR is max 4000 chars. Let's use NTEXT
+						$decl .= "@P$i NTEXT";
+					} else {
+						$decl .= "@P$i NVARCHAR($len)";
+					}
+
+					$params .= "@P$i=N". (strncmp($v,"'",1)==0? $v : $this->qstr($v));
+				} else if (is_integer($v)) {
+					$decl .= "@P$i INT";
+					$params .= "@P$i=".$v;
+				} else if (is_float($v)) {
+					$decl .= "@P$i FLOAT";
+					$params .= "@P$i=".$v;
+				} else if (is_bool($v)) {
+					$decl .= "@P$i INT"; # Used INT just in case BIT in not supported on the user's MSSQL version. It will cast appropriately.
+					$params .= "@P$i=".(($v)?'1':'0'); # True == 1 in MSSQL BIT fields and acceptable for storing logical true in an int field
+				} else {
+					$decl .= "@P$i CHAR"; # Used char because a type is required even when the value is to be NULL.
+					$params .= "@P$i=NULL";
+					}
+				$i += 1;
+			}
+			$decl = $this->qstr($decl);
+			if ($this->debug) ADOConnection::outp("<font size=-1>sp_executesql N{$sql[1]},N$decl,$params</font>");
+			$rez = mssql_query("sp_executesql N{$sql[1]},N$decl,$params", $this->_connectionID);
+			
+		} else if (is_array($sql)) {
+			# PrepareSP()
+			$rez = mssql_execute($sql[1]);
+			
+		} else {
+			$rez = mssql_query($sql,$this->_connectionID);
+		}
+		return $rez;
+	}
+	
+	// returns true or false
+	function _close()
+	{ 
+		if ($this->transCnt) $this->RollbackTrans();
+		$rez = @mssql_close($this->_connectionID);
+		$this->_connectionID = false;
+		return $rez;
+	}
+	
+	// mssql uses a default date like Dec 30 2000 12:00AM
+	function UnixDate($v)
+	{
+		return ADORecordSet_array_mssql::UnixDate($v);
+	}
+	
+	function UnixTimeStamp($v)
+	{
+		return ADORecordSet_array_mssql::UnixTimeStamp($v);
+	}	
+}
+	
+/*--------------------------------------------------------------------------------------
+	 Class Name: Recordset
+--------------------------------------------------------------------------------------*/
+
+class ADORecordset_mssql extends ADORecordSet {	
+
+	var $databaseType = "mssql";
+	var $canSeek = true;
+	var $hasFetchAssoc; // see http://phplens.com/lens/lensforum/msgs.php?id=6083
+	// _mths works only in non-localised system
+	
+	function ADORecordset_mssql($id,$mode=false)
+	{
+		// freedts check...
+		$this->hasFetchAssoc = function_exists('mssql_fetch_assoc');
+
+		if ($mode === false) { 
+			global $ADODB_FETCH_MODE;
+			$mode = $ADODB_FETCH_MODE;
+
+		}
+		$this->fetchMode = $mode;
+		return $this->ADORecordSet($id,$mode);
+	}
+	
+	
+	function _initrs()
+	{
+	GLOBAL $ADODB_COUNTRECS;	
+		$this->_numOfRows = ($ADODB_COUNTRECS)? @mssql_num_rows($this->_queryID):-1;
+		$this->_numOfFields = @mssql_num_fields($this->_queryID);
+	}
+	
+
+	//Contributed by "Sven Axelsson" <sven.axelsson@bokochwebb.se>
+	// get next resultset - requires PHP 4.0.5 or later
+	function NextRecordSet()
+	{
+		if (!mssql_next_result($this->_queryID)) return false;
+		$this->_inited = false;
+		$this->bind = false;
+		$this->_currentRow = -1;
+		$this->Init();
+		return true;
+	}
+
+	/* Use associative array to get fields array */
+	function Fields($colname)
+	{
+		if ($this->fetchMode != ADODB_FETCH_NUM) return $this->fields[$colname];
+		if (!$this->bind) {
+			$this->bind = array();
+			for ($i=0; $i < $this->_numOfFields; $i++) {
+				$o = $this->FetchField($i);
+				$this->bind[strtoupper($o->name)] = $i;
+			}
+		}
+		
+		 return $this->fields[$this->bind[strtoupper($colname)]];
+	}
+	
+	/*	Returns: an object containing field information. 
+		Get column information in the Recordset object. fetchField() can be used in order to obtain information about
+		fields in a certain query result. If the field offset isn't specified, the next field that wasn't yet retrieved by
+		fetchField() is retrieved.	*/
+
+	function &FetchField($fieldOffset = -1) 
+	{
+		if ($fieldOffset != -1) {
+			$f = @mssql_fetch_field($this->_queryID, $fieldOffset);
+		}
+		else if ($fieldOffset == -1) {	/*	The $fieldOffset argument is not provided thus its -1 	*/
+			$f = @mssql_fetch_field($this->_queryID);
+		}
+		$false = false;
+		if (empty($f)) return $false;
+		return $f;
+	}
+	
+	function _seek($row) 
+	{
+		return @mssql_data_seek($this->_queryID, $row);
+	}
+
+	// speedup
+	function MoveNext() 
+	{
+		if ($this->EOF) return false;
+		
+		$this->_currentRow++;
+		
+		if ($this->fetchMode & ADODB_FETCH_ASSOC) {
+			if ($this->fetchMode & ADODB_FETCH_NUM) {
+				//ADODB_FETCH_BOTH mode
+				$this->fields = @mssql_fetch_array($this->_queryID);
+			}
+			else {
+				if ($this->hasFetchAssoc) {// only for PHP 4.2.0 or later
+					 $this->fields = @mssql_fetch_assoc($this->_queryID);
+				} else {
+					$flds = @mssql_fetch_array($this->_queryID);
+					if (is_array($flds)) {
+						$fassoc = array();
+						foreach($flds as $k => $v) {
+							if (is_numeric($k)) continue;
+							$fassoc[$k] = $v;
+						}
+						$this->fields = $fassoc;
+					} else
+						$this->fields = false;
+				}
+			}
+			
+			if (is_array($this->fields)) {
+				if (ADODB_ASSOC_CASE == 0) {
+					foreach($this->fields as $k=>$v) {
+						$this->fields[strtolower($k)] = $v;
+					}
+				} else if (ADODB_ASSOC_CASE == 1) {
+					foreach($this->fields as $k=>$v) {
+						$this->fields[strtoupper($k)] = $v;
+					}
+				}
+			}
+		} else {
+			$this->fields = @mssql_fetch_row($this->_queryID);
+		}
+		if ($this->fields) return true;
+		$this->EOF = true;
+		
+		return false;
+	}
+
+	
+	// INSERT UPDATE DELETE returns false even if no error occurs in 4.0.4
+	// also the date format has been changed from YYYY-mm-dd to dd MMM YYYY in 4.0.4. Idiot!
+	function _fetch($ignore_fields=false) 
+	{
+		if ($this->fetchMode & ADODB_FETCH_ASSOC) {
+			if ($this->fetchMode & ADODB_FETCH_NUM) {
+				//ADODB_FETCH_BOTH mode
+				$this->fields = @mssql_fetch_array($this->_queryID);
+			} else {
+				if ($this->hasFetchAssoc) // only for PHP 4.2.0 or later
+					$this->fields = @mssql_fetch_assoc($this->_queryID);
+				else {
+					$this->fields = @mssql_fetch_array($this->_queryID);
+					if (@is_array($$this->fields)) {
+						$fassoc = array();
+						foreach($$this->fields as $k => $v) {
+							if (is_integer($k)) continue;
+							$fassoc[$k] = $v;
+						}
+						$this->fields = $fassoc;
+					}
+				}
+			}
+			
+			if (!$this->fields) {
+			} else if (ADODB_ASSOC_CASE == 0) {
+				foreach($this->fields as $k=>$v) {
+					$this->fields[strtolower($k)] = $v;
+				}
+			} else if (ADODB_ASSOC_CASE == 1) {
+				foreach($this->fields as $k=>$v) {
+					$this->fields[strtoupper($k)] = $v;
+				}
+			}
+		} else {
+			$this->fields = @mssql_fetch_row($this->_queryID);
+		}
+		return $this->fields;
+	}
+	
+	/*	close() only needs to be called if you are worried about using too much memory while your script
+		is running. All associated result memory for the specified result identifier will automatically be freed.	*/
+
+	function _close() 
+	{
+		$rez = mssql_free_result($this->_queryID);	
+		$this->_queryID = false;
+		return $rez;
+	}
+	// mssql uses a default date like Dec 30 2000 12:00AM
+	function UnixDate($v)
+	{
+		return ADORecordSet_array_mssql::UnixDate($v);
+	}
+	
+	function UnixTimeStamp($v)
+	{
+		return ADORecordSet_array_mssql::UnixTimeStamp($v);
+	}
+	
+}
+
+
+class ADORecordSet_array_mssql extends ADORecordSet_array {
+	function ADORecordSet_array_mssql($id=-1,$mode=false) 
+	{
+		$this->ADORecordSet_array($id,$mode);
+	}
+	
+		// mssql uses a default date like Dec 30 2000 12:00AM
+	function UnixDate($v)
+	{
+	
+		if (is_numeric(substr($v,0,1)) && ADODB_PHPVER >= 0x4200) return parent::UnixDate($v);
+		
+	global $ADODB_mssql_mths,$ADODB_mssql_date_order;
+	
+		//Dec 30 2000 12:00AM 
+		if ($ADODB_mssql_date_order == 'dmy') {
+			if (!preg_match( "|^([0-9]{1,2})[-/\. ]+([A-Za-z]{3})[-/\. ]+([0-9]{4})|" ,$v, $rr)) {
+				return parent::UnixDate($v);
+			}
+			if ($rr[3] <= TIMESTAMP_FIRST_YEAR) return 0;
+			
+			$theday = $rr[1];
+			$themth =  substr(strtoupper($rr[2]),0,3);
+		} else {
+			if (!preg_match( "|^([A-Za-z]{3})[-/\. ]+([0-9]{1,2})[-/\. ]+([0-9]{4})|" ,$v, $rr)) {
+				return parent::UnixDate($v);
+			}
+			if ($rr[3] <= TIMESTAMP_FIRST_YEAR) return 0;
+			
+			$theday = $rr[2];
+			$themth = substr(strtoupper($rr[1]),0,3);
+		}
+		$themth = $ADODB_mssql_mths[$themth];
+		if ($themth <= 0) return false;
+		// h-m-s-MM-DD-YY
+		return  mktime(0,0,0,$themth,$theday,$rr[3]);
+	}
+	
+	function UnixTimeStamp($v)
+	{
+	
+		if (is_numeric(substr($v,0,1)) && ADODB_PHPVER >= 0x4200) return parent::UnixTimeStamp($v);
+		
+	global $ADODB_mssql_mths,$ADODB_mssql_date_order;
+	
+		//Dec 30 2000 12:00AM
+		 if ($ADODB_mssql_date_order == 'dmy') {
+			 if (!preg_match( "|^([0-9]{1,2})[-/\. ]+([A-Za-z]{3})[-/\. ]+([0-9]{4}) +([0-9]{1,2}):([0-9]{1,2}) *([apAP]{0,1})|"
+			,$v, $rr)) return parent::UnixTimeStamp($v);
+			if ($rr[3] <= TIMESTAMP_FIRST_YEAR) return 0;
+		
+			$theday = $rr[1];
+			$themth =  substr(strtoupper($rr[2]),0,3);
+		} else {
+			if (!preg_match( "|^([A-Za-z]{3})[-/\. ]+([0-9]{1,2})[-/\. ]+([0-9]{4}) +([0-9]{1,2}):([0-9]{1,2}) *([apAP]{0,1})|"
+			,$v, $rr)) return parent::UnixTimeStamp($v);
+			if ($rr[3] <= TIMESTAMP_FIRST_YEAR) return 0;
+		
+			$theday = $rr[2];
+			$themth = substr(strtoupper($rr[1]),0,3);
+		}
+		
+		$themth = $ADODB_mssql_mths[$themth];
+		if ($themth <= 0) return false;
+		
+		switch (strtoupper($rr[6])) {
+		case 'P':
+			if ($rr[4]<12) $rr[4] += 12;
+			break;
+		case 'A':
+			if ($rr[4]==12) $rr[4] = 0;
+			break;
+		default:
+			break;
+		}
+		// h-m-s-MM-DD-YY
+		return  mktime($rr[4],$rr[5],0,$themth,$theday,$rr[3]);
+	}
+}
+
+/*
+Code Example 1:
+
+select 	object_name(constid) as constraint_name,
+       	object_name(fkeyid) as table_name, 
+        col_name(fkeyid, fkey) as column_name,
+	object_name(rkeyid) as referenced_table_name,
+   	col_name(rkeyid, rkey) as referenced_column_name
+from sysforeignkeys
+where object_name(fkeyid) = x
+order by constraint_name, table_name, referenced_table_name,  keyno
+
+Code Example 2:
+select 	constraint_name,
+	column_name,
+	ordinal_position
+from information_schema.key_column_usage
+where constraint_catalog = db_name()
+and table_name = x
+order by constraint_name, ordinal_position
+
+http://www.databasejournal.com/scripts/article.php/1440551
+*/
+
+?>
Index: /Dev/trunk/rdfapi/util/adodb/drivers/adodb-mssql_n.inc.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/drivers/adodb-mssql_n.inc.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/drivers/adodb-mssql_n.inc.php	(revision 12)
@@ -0,0 +1,166 @@
+<?php  
+
+/// $Id $
+
+///////////////////////////////////////////////////////////////////////////
+//                                                                       //
+// NOTICE OF COPYRIGHT                                                   //
+//                                                                       //
+// ADOdb  - Database Abstraction Library for PHP                         //
+//          http://adodb.sourceforge.net/                                //
+//                                                                       //
+// Copyright (C) 2000-2007 John Lim (jlim\@natsoft.com.my)               //
+//          All rights reserved.                                         //
+//          Released under both BSD license and LGPL library license.    //
+//          Whenever there is any discrepancy between the two licenses,  //
+//          the BSD license will take precedence                         //
+//                                                                       //
+// Moodle - Modular Object-Oriented Dynamic Learning Environment         //
+//          http://moodle.com                                            //
+//                                                                       //
+// Copyright (C) 2001-3001 Martin Dougiamas        http://dougiamas.com  //
+//           (C) 2001-3001 Eloy Lafuente (stronk7) http://contiento.com  //
+//                                                                       //
+// This program is free software; you can redistribute it and/or modify  //
+// it under the terms of the GNU General Public License as published by  //
+// the Free Software Foundation; either version 2 of the License, or     //
+// (at your option) any later version.                                   //
+//                                                                       //
+// This program is distributed in the hope that it will be useful,       //
+// but WITHOUT ANY WARRANTY; without even the implied warranty of        //
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         //
+// GNU General Public License for more details:                          //
+//                                                                       //
+//          http://www.gnu.org/copyleft/gpl.html                         //
+//                                                                       //
+///////////////////////////////////////////////////////////////////////////
+
+/**
+*  MSSQL Driver with auto-prepended "N" for correct unicode storage
+*  of SQL literal strings. Intended to be used with MSSQL drivers that
+*  are sending UCS-2 data to MSSQL (FreeTDS and ODBTP) in order to get
+*  true cross-db compatibility from the application point of view.
+*/
+
+// security - hide paths
+if (!defined('ADODB_DIR')) die();
+
+// one useful constant
+if (!defined('SINGLEQUOTE')) define('SINGLEQUOTE', "'");
+
+include_once(ADODB_DIR.'/drivers/adodb-mssql.inc.php');
+
+class ADODB_mssql_n extends ADODB_mssql {
+	var $databaseType = "mssql_n";
+	
+	function ADODB_mssqlpo()
+	{
+		ADODB_mssql::ADODB_mssql();
+	}
+
+	function _query($sql,$inputarr)
+	{
+        $sql = $this->_appendN($sql);
+		return ADODB_mssql::_query($sql,$inputarr);
+	}
+
+    /**
+     * This function will intercept all the literals used in the SQL, prepending the "N" char to them
+     * in order to allow mssql to store properly data sent in the correct UCS-2 encoding (by freeTDS
+     * and ODBTP) keeping SQL compatibility at ADOdb level (instead of hacking every project to add
+     * the "N" notation when working against MSSQL.
+     *
+     * Note that this hack only must be used if ALL the char-based columns in your DB are of type nchar,
+     * nvarchar and ntext 
+     */
+    function _appendN($sql) {
+
+        $result = $sql;
+
+    /// Check we have some single quote in the query. Exit ok.
+        if (strpos($sql, SINGLEQUOTE) === false) {
+            return $sql;
+        }
+
+    /// Check we haven't an odd number of single quotes (this can cause problems below
+    /// and should be considered one wrong SQL). Exit with debug info.
+        if ((substr_count($sql, SINGLEQUOTE) & 1)) {
+            if ($this->debug) {
+                ADOConnection::outp("{$this->databaseType} internal transformation: not converted. Wrong number of quotes (odd)");
+            }
+            return $sql;
+        }
+
+    /// Check we haven't any backslash + single quote combination. It should mean wrong
+    /// backslashes use (bad magic_quotes_sybase?). Exit with debug info.
+        $regexp = '/(\\\\' . SINGLEQUOTE . '[^' . SINGLEQUOTE . '])/';
+        if (preg_match($regexp, $sql)) {
+            if ($this->debug) {
+                ADOConnection::outp("{$this->databaseType} internal transformation: not converted. Found bad use of backslash + single quote");
+            }
+            return $sql;
+        }
+
+    /// Remove pairs of single-quotes
+        $pairs = array();
+        $regexp = '/(' . SINGLEQUOTE . SINGLEQUOTE . ')/';
+        preg_match_all($regexp, $result, $list_of_pairs);
+        if ($list_of_pairs) {
+            foreach (array_unique($list_of_pairs[0]) as $key=>$value) {
+                $pairs['<@#@#@PAIR-'.$key.'@#@#@>'] = $value;
+            }
+            if (!empty($pairs)) {
+                $result = str_replace($pairs, array_keys($pairs), $result);
+            }
+        }
+
+    /// Remove the rest of literals present in the query
+        $literals = array();
+        $regexp = '/(N?' . SINGLEQUOTE . '.*?' . SINGLEQUOTE . ')/is';
+        preg_match_all($regexp, $result, $list_of_literals);
+        if ($list_of_literals) {
+            foreach (array_unique($list_of_literals[0]) as $key=>$value) {
+                $literals['<#@#@#LITERAL-'.$key.'#@#@#>'] = $value;
+            }
+            if (!empty($literals)) {
+                $result = str_replace($literals, array_keys($literals), $result);
+            }
+        }
+
+    /// Analyse literals to prepend the N char to them if their contents aren't numeric
+        if (!empty($literals)) {
+            foreach ($literals as $key=>$value) {
+                if (!is_numeric(trim($value, SINGLEQUOTE))) {
+                /// Non numeric string, prepend our dear N
+                    $literals[$key] = 'N' . trim($value, 'N'); //Trimming potentially existing previous "N"
+                }
+            }
+        }
+
+    /// Re-apply literals to the text
+        if (!empty($literals)) {
+            $result = str_replace(array_keys($literals), $literals, $result);
+        }
+
+    /// Re-apply pairs of single-quotes to the text
+        if (!empty($pairs)) {
+            $result = str_replace(array_keys($pairs), $pairs, $result);
+        }
+
+    /// Print transformation if debug = on
+        if ($result != $sql && $this->debug) {
+            ADOConnection::outp("{$this->databaseType} internal transformation:<br>{$sql}<br>to<br>{$result}");
+        }
+
+        return $result;
+    }
+}
+
+class ADORecordset_mssql_n extends ADORecordset_mssql {
+	var $databaseType = "mssql_n";
+	function ADORecordset_mssql_n($id,$mode=false)
+	{
+		$this->ADORecordset_mssql($id,$mode);
+	}
+}
+?>
Index: /Dev/trunk/rdfapi/util/adodb/drivers/adodb-mssqlpo.inc.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/drivers/adodb-mssqlpo.inc.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/drivers/adodb-mssqlpo.inc.php	(revision 12)
@@ -0,0 +1,62 @@
+<?php
+/**
+* @version V4.94 23 Jan 2007 (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
+* Released under both BSD license and Lesser GPL library license.
+* Whenever there is any discrepancy between the two licenses,
+* the BSD license will take precedence.
+*
+* Set tabs to 4 for best viewing.
+*
+* Latest version is available at http://php.weblogs.com
+*
+*  Portable MSSQL Driver that supports || instead of +
+*
+*/
+
+// security - hide paths
+if (!defined('ADODB_DIR')) die();
+
+
+/*
+	The big difference between mssqlpo and it's parent mssql is that mssqlpo supports
+	the more standard || string concatenation operator.
+*/
+	
+include_once(ADODB_DIR.'/drivers/adodb-mssql.inc.php');
+
+class ADODB_mssqlpo extends ADODB_mssql {
+	var $databaseType = "mssqlpo";
+	var $concat_operator = '||'; 
+	
+	function ADODB_mssqlpo()
+	{
+		ADODB_mssql::ADODB_mssql();
+	}
+
+	function PrepareSP($sql)
+	{
+		if (!$this->_has_mssql_init) {
+			ADOConnection::outp( "PrepareSP: mssql_init only available since PHP 4.1.0");
+			return $sql;
+		}
+		if (is_string($sql)) $sql = str_replace('||','+',$sql);
+		$stmt = mssql_init($sql,$this->_connectionID);
+		if (!$stmt)  return $sql;
+		return array($sql,$stmt);
+	}
+	
+	function _query($sql,$inputarr)
+	{
+		if (is_string($sql)) $sql = str_replace('||','+',$sql);
+		return ADODB_mssql::_query($sql,$inputarr);
+	}
+}
+
+class ADORecordset_mssqlpo extends ADORecordset_mssql {
+	var $databaseType = "mssqlpo";
+	function ADORecordset_mssqlpo($id,$mode=false)
+	{
+		$this->ADORecordset_mssql($id,$mode);
+	}
+}
+?>
Index: /Dev/trunk/rdfapi/util/adodb/drivers/adodb-mysql.inc.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/drivers/adodb-mysql.inc.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/drivers/adodb-mysql.inc.php	(revision 12)
@@ -0,0 +1,782 @@
+<?php
+/*
+V4.94 23 Jan 2007  (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence.
+  Set tabs to 8.
+  
+  MySQL code that does not support transactions. Use mysqlt if you need transactions.
+  Requires mysql client. Works on Windows and Unix.
+  
+ 28 Feb 2001: MetaColumns bug fix - suggested by  Freek Dijkstra (phpeverywhere@macfreek.com)
+*/ 
+
+// security - hide paths
+if (!defined('ADODB_DIR')) die();
+
+if (! defined("_ADODB_MYSQL_LAYER")) {
+ define("_ADODB_MYSQL_LAYER", 1 );
+
+class ADODB_mysql extends ADOConnection {
+	var $databaseType = 'mysql';
+	var $dataProvider = 'mysql';
+	var $hasInsertID = true;
+	var $hasAffectedRows = true;	
+	var $metaTablesSQL = "SHOW TABLES";	
+	var $metaColumnsSQL = "SHOW COLUMNS FROM `%s`";
+	var $fmtTimeStamp = "'Y-m-d H:i:s'";
+	var $hasLimit = true;
+	var $hasMoveFirst = true;
+	var $hasGenID = true;
+	var $isoDates = true; // accepts dates in ISO format
+	var $sysDate = 'CURDATE()';
+	var $sysTimeStamp = 'NOW()';
+	var $hasTransactions = false;
+	var $forceNewConnect = false;
+	var $poorAffectedRows = true;
+	var $clientFlags = 0;
+	var $substr = "substring";
+	var $nameQuote = '`';		/// string to use to quote identifiers and names
+	var $compat323 = false; 		// true if compat with mysql 3.23
+	
+	function ADODB_mysql() 
+	{			
+		if (defined('ADODB_EXTENSION')) $this->rsPrefix .= 'ext_';
+	}
+	
+	function ServerInfo()
+	{
+		$arr['description'] = ADOConnection::GetOne("select version()");
+		$arr['version'] = ADOConnection::_findvers($arr['description']);
+		return $arr;
+	}
+	
+	function IfNull( $field, $ifNull ) 
+	{
+		return " IFNULL($field, $ifNull) "; // if MySQL
+	}
+	
+	
+	function &MetaTables($ttype=false,$showSchema=false,$mask=false) 
+	{	
+		$save = $this->metaTablesSQL;
+		if ($showSchema && is_string($showSchema)) {
+			$this->metaTablesSQL .= " from $showSchema";
+		}
+		
+		if ($mask) {
+			$mask = $this->qstr($mask);
+			$this->metaTablesSQL .= " like $mask";
+		}
+		$ret =& ADOConnection::MetaTables($ttype,$showSchema);
+		
+		$this->metaTablesSQL = $save;
+		return $ret;
+	}
+	
+	
+	function &MetaIndexes ($table, $primary = FALSE, $owner=false)
+	{
+        // save old fetch mode
+        global $ADODB_FETCH_MODE;
+        
+		$false = false;
+        $save = $ADODB_FETCH_MODE;
+        $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
+        if ($this->fetchMode !== FALSE) {
+               $savem = $this->SetFetchMode(FALSE);
+        }
+        
+        // get index details
+        $rs = $this->Execute(sprintf('SHOW INDEX FROM %s',$table));
+        
+        // restore fetchmode
+        if (isset($savem)) {
+                $this->SetFetchMode($savem);
+        }
+        $ADODB_FETCH_MODE = $save;
+        
+        if (!is_object($rs)) {
+                return $false;
+        }
+        
+        $indexes = array ();
+        
+        // parse index data into array
+        while ($row = $rs->FetchRow()) {
+                if ($primary == FALSE AND $row[2] == 'PRIMARY') {
+                        continue;
+                }
+                
+                if (!isset($indexes[$row[2]])) {
+                        $indexes[$row[2]] = array(
+                                'unique' => ($row[1] == 0),
+                                'columns' => array()
+                        );
+                }
+                
+                $indexes[$row[2]]['columns'][$row[3] - 1] = $row[4];
+        }
+        
+        // sort columns by order in the index
+        foreach ( array_keys ($indexes) as $index )
+        {
+                ksort ($indexes[$index]['columns']);
+        }
+        
+        return $indexes;
+	}
+
+	
+	// if magic quotes disabled, use mysql_real_escape_string()
+	function qstr($s,$magic_quotes=false)
+	{
+		if (!$magic_quotes) {
+		
+			if (ADODB_PHPVER >= 0x4300) {
+				if (is_resource($this->_connectionID))
+					return "'".mysql_real_escape_string($s,$this->_connectionID)."'";
+			}
+			if ($this->replaceQuote[0] == '\\'){
+				$s = adodb_str_replace(array('\\',"\0"),array('\\\\',"\\\0"),$s);
+			}
+			return  "'".str_replace("'",$this->replaceQuote,$s)."'"; 
+		}
+		
+		// undo magic quotes for "
+		$s = str_replace('\\"','"',$s);
+		return "'$s'";
+	}
+	
+	function _insertid()
+	{
+		return ADOConnection::GetOne('SELECT LAST_INSERT_ID()');
+		//return mysql_insert_id($this->_connectionID);
+	}
+	
+	function GetOne($sql,$inputarr=false)
+	{
+		if ($this->compat323 == false && strncasecmp($sql,'sele',4) == 0) {
+			$rs =& $this->SelectLimit($sql,1,-1,$inputarr);
+			if ($rs) {
+				$rs->Close();
+				if ($rs->EOF) return false;
+				return reset($rs->fields);
+			}
+		} else {
+			return ADOConnection::GetOne($sql,$inputarr);
+		}
+		return false;
+	}
+	
+	function BeginTrans()
+	{
+		if ($this->debug) ADOConnection::outp("Transactions not supported in 'mysql' driver. Use 'mysqlt' or 'mysqli' driver");
+	}
+	
+	function _affectedrows()
+	{
+			return mysql_affected_rows($this->_connectionID);
+	}
+  
+ 	// See http://www.mysql.com/doc/M/i/Miscellaneous_functions.html
+	// Reference on Last_Insert_ID on the recommended way to simulate sequences
+ 	var $_genIDSQL = "update %s set id=LAST_INSERT_ID(id+1);";
+	var $_genSeqSQL = "create table %s (id int not null)";
+	var $_genSeq2SQL = "insert into %s values (%s)";
+	var $_dropSeqSQL = "drop table %s";
+	
+	function CreateSequence($seqname='adodbseq',$startID=1)
+	{
+		if (empty($this->_genSeqSQL)) return false;
+		$u = strtoupper($seqname);
+		
+		$ok = $this->Execute(sprintf($this->_genSeqSQL,$seqname));
+		if (!$ok) return false;
+		return $this->Execute(sprintf($this->_genSeq2SQL,$seqname,$startID-1));
+	}
+	
+
+	function GenID($seqname='adodbseq',$startID=1)
+	{
+		// post-nuke sets hasGenID to false
+		if (!$this->hasGenID) return false;
+		
+		$savelog = $this->_logsql;
+		$this->_logsql = false;
+		$getnext = sprintf($this->_genIDSQL,$seqname);
+		$holdtransOK = $this->_transOK; // save the current status
+		$rs = @$this->Execute($getnext);
+		if (!$rs) {
+			if ($holdtransOK) $this->_transOK = true; //if the status was ok before reset
+			$u = strtoupper($seqname);
+			$this->Execute(sprintf($this->_genSeqSQL,$seqname));
+			$this->Execute(sprintf($this->_genSeq2SQL,$seqname,$startID-1));
+			$rs = $this->Execute($getnext);
+		}
+		$this->genID = mysql_insert_id($this->_connectionID);
+		
+		if ($rs) $rs->Close();
+		
+		$this->_logsql = $savelog;
+		return $this->genID;
+	}
+	
+  	function &MetaDatabases()
+	{
+		$qid = mysql_list_dbs($this->_connectionID);
+		$arr = array();
+		$i = 0;
+		$max = mysql_num_rows($qid);
+		while ($i < $max) {
+			$db = mysql_tablename($qid,$i);
+			if ($db != 'mysql') $arr[] = $db;
+			$i += 1;
+		}
+		return $arr;
+	}
+	
+		
+	// Format date column in sql string given an input format that understands Y M D
+	function SQLDate($fmt, $col=false)
+	{	
+		if (!$col) $col = $this->sysTimeStamp;
+		$s = 'DATE_FORMAT('.$col.",'";
+		$concat = false;
+		$len = strlen($fmt);
+		for ($i=0; $i < $len; $i++) {
+			$ch = $fmt[$i];
+			switch($ch) {
+				
+			default:
+				if ($ch == '\\') {
+					$i++;
+					$ch = substr($fmt,$i,1);
+				}
+				/** FALL THROUGH */
+			case '-':
+			case '/':
+				$s .= $ch;
+				break;
+				
+			case 'Y':
+			case 'y':
+				$s .= '%Y';
+				break;
+			case 'M':
+				$s .= '%b';
+				break;
+				
+			case 'm':
+				$s .= '%m';
+				break;
+			case 'D':
+			case 'd':
+				$s .= '%d';
+				break;
+			
+			case 'Q':
+			case 'q':
+				$s .= "'),Quarter($col)";
+				
+				if ($len > $i+1) $s .= ",DATE_FORMAT($col,'";
+				else $s .= ",('";
+				$concat = true;
+				break;
+			
+			case 'H': 
+				$s .= '%H';
+				break;
+				
+			case 'h':
+				$s .= '%I';
+				break;
+				
+			case 'i':
+				$s .= '%i';
+				break;
+				
+			case 's':
+				$s .= '%s';
+				break;
+				
+			case 'a':
+			case 'A':
+				$s .= '%p';
+				break;
+				
+			case 'w':
+				$s .= '%w';
+				break;
+				
+			 case 'W':
+				$s .= '%U';
+				break;
+				
+			case 'l':
+				$s .= '%W';
+				break;
+			}
+		}
+		$s.="')";
+		if ($concat) $s = "CONCAT($s)";
+		return $s;
+	}
+	
+
+	// returns concatenated string
+	// much easier to run "mysqld --ansi" or "mysqld --sql-mode=PIPES_AS_CONCAT" and use || operator
+	function Concat()
+	{
+		$s = "";
+		$arr = func_get_args();
+		
+		// suggestion by andrew005@mnogo.ru
+		$s = implode(',',$arr); 
+		if (strlen($s) > 0) return "CONCAT($s)";
+		else return '';
+	}
+	
+	function OffsetDate($dayFraction,$date=false)
+	{		
+		if (!$date) $date = $this->sysDate;
+		
+		$fraction = $dayFraction * 24 * 3600;
+		return $date . ' + INTERVAL ' .	 $fraction.' SECOND';
+		
+//		return "from_unixtime(unix_timestamp($date)+$fraction)";
+	}
+	
+	// returns true or false
+	function _connect($argHostname, $argUsername, $argPassword, $argDatabasename)
+	{
+		if (!empty($this->port)) $argHostname .= ":".$this->port;
+		
+		if (ADODB_PHPVER >= 0x4300)
+			$this->_connectionID = mysql_connect($argHostname,$argUsername,$argPassword,
+												$this->forceNewConnect,$this->clientFlags);
+		else if (ADODB_PHPVER >= 0x4200)
+			$this->_connectionID = mysql_connect($argHostname,$argUsername,$argPassword,
+												$this->forceNewConnect);
+		else
+			$this->_connectionID = mysql_connect($argHostname,$argUsername,$argPassword);
+	
+		if ($this->_connectionID === false) return false;
+		if ($argDatabasename) return $this->SelectDB($argDatabasename);
+		return true;	
+	}
+	
+	// returns true or false
+	function _pconnect($argHostname, $argUsername, $argPassword, $argDatabasename)
+	{
+		if (!empty($this->port)) $argHostname .= ":".$this->port;
+		
+		if (ADODB_PHPVER >= 0x4300)
+			$this->_connectionID = mysql_pconnect($argHostname,$argUsername,$argPassword,$this->clientFlags);
+		else
+			$this->_connectionID = mysql_pconnect($argHostname,$argUsername,$argPassword);
+		if ($this->_connectionID === false) return false;
+		if ($this->autoRollback) $this->RollbackTrans();
+		if ($argDatabasename) return $this->SelectDB($argDatabasename);
+		return true;	
+	}
+	
+	function _nconnect($argHostname, $argUsername, $argPassword, $argDatabasename)
+	{
+		$this->forceNewConnect = true;
+		return $this->_connect($argHostname, $argUsername, $argPassword, $argDatabasename);
+	}
+	
+ 	function &MetaColumns($table) 
+	{
+		$this->_findschema($table,$schema);
+		if ($schema) {
+			$dbName = $this->database;
+			$this->SelectDB($schema);
+		}
+		global $ADODB_FETCH_MODE;
+		$save = $ADODB_FETCH_MODE;
+		$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
+		
+		if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false);
+		$rs = $this->Execute(sprintf($this->metaColumnsSQL,$table));
+		
+		if ($schema) {
+			$this->SelectDB($dbName);
+		}
+		
+		if (isset($savem)) $this->SetFetchMode($savem);
+		$ADODB_FETCH_MODE = $save;
+		if (!is_object($rs)) {
+			$false = false;
+			return $false;
+		}
+			
+		$retarr = array();
+		while (!$rs->EOF){
+			$fld = new ADOFieldObject();
+			$fld->name = $rs->fields[0];
+			$type = $rs->fields[1];
+			
+			// split type into type(length):
+			$fld->scale = null;
+			if (preg_match("/^(.+)\((\d+),(\d+)/", $type, $query_array)) {
+				$fld->type = $query_array[1];
+				$fld->max_length = is_numeric($query_array[2]) ? $query_array[2] : -1;
+				$fld->scale = is_numeric($query_array[3]) ? $query_array[3] : -1;
+			} elseif (preg_match("/^(.+)\((\d+)/", $type, $query_array)) {
+				$fld->type = $query_array[1];
+				$fld->max_length = is_numeric($query_array[2]) ? $query_array[2] : -1;
+			} elseif (preg_match("/^(enum)\((.*)\)$/i", $type, $query_array)) {
+				$fld->type = $query_array[1];
+				$arr = explode(",",$query_array[2]);
+				$fld->enums = $arr;
+				$zlen = max(array_map("strlen",$arr)) - 2; // PHP >= 4.0.6
+				$fld->max_length = ($zlen > 0) ? $zlen : 1;
+			} else {
+				$fld->type = $type;
+				$fld->max_length = -1;
+			}
+			$fld->not_null = ($rs->fields[2] != 'YES');
+			$fld->primary_key = ($rs->fields[3] == 'PRI');
+			$fld->auto_increment = (strpos($rs->fields[5], 'auto_increment') !== false);
+			$fld->binary = (strpos($type,'blob') !== false);
+			$fld->unsigned = (strpos($type,'unsigned') !== false);
+				
+			if (!$fld->binary) {
+				$d = $rs->fields[4];
+				if ($d != '' && $d != 'NULL') {
+					$fld->has_default = true;
+					$fld->default_value = $d;
+				} else {
+					$fld->has_default = false;
+				}
+			}
+			
+			if ($save == ADODB_FETCH_NUM) {
+				$retarr[] = $fld;
+			} else {
+				$retarr[strtoupper($fld->name)] = $fld;
+			}
+				$rs->MoveNext();
+			}
+		
+			$rs->Close();
+			return $retarr;	
+	}
+		
+	// returns true or false
+	function SelectDB($dbName) 
+	{
+		$this->database = $dbName;
+		$this->databaseName = $dbName; # obsolete, retained for compat with older adodb versions
+		if ($this->_connectionID) {
+			return @mysql_select_db($dbName,$this->_connectionID);		
+		}
+		else return false;	
+	}
+	
+	// parameters use PostgreSQL convention, not MySQL
+	function &SelectLimit($sql,$nrows=-1,$offset=-1,$inputarr=false,$secs=0)
+	{
+		$offsetStr =($offset>=0) ? ((integer)$offset)."," : '';
+		// jason judge, see http://phplens.com/lens/lensforum/msgs.php?id=9220
+		if ($nrows < 0) $nrows = '18446744073709551615'; 
+		
+		if ($secs)
+			$rs =& $this->CacheExecute($secs,$sql." LIMIT $offsetStr".((integer)$nrows),$inputarr);
+		else
+			$rs =& $this->Execute($sql." LIMIT $offsetStr".((integer)$nrows),$inputarr);
+		return $rs;
+	}
+	
+	// returns queryID or false
+	function _query($sql,$inputarr)
+	{
+	//global $ADODB_COUNTRECS;
+		//if($ADODB_COUNTRECS) 
+		return mysql_query($sql,$this->_connectionID);
+		//else return @mysql_unbuffered_query($sql,$this->_connectionID); // requires PHP >= 4.0.6
+	}
+
+	/*	Returns: the last error message from previous database operation	*/	
+	function ErrorMsg() 
+	{
+	
+		if ($this->_logsql) return $this->_errorMsg;
+		if (empty($this->_connectionID)) $this->_errorMsg = @mysql_error();
+		else $this->_errorMsg = @mysql_error($this->_connectionID);
+		return $this->_errorMsg;
+	}
+	
+	/*	Returns: the last error number from previous database operation	*/	
+	function ErrorNo() 
+	{
+		if ($this->_logsql) return $this->_errorCode;
+		if (empty($this->_connectionID))  return @mysql_errno();
+		else return @mysql_errno($this->_connectionID);
+	}
+	
+	// returns true or false
+	function _close()
+	{
+		@mysql_close($this->_connectionID);
+		$this->_connectionID = false;
+	}
+
+	
+	/*
+	* Maximum size of C field
+	*/
+	function CharMax()
+	{
+		return 255; 
+	}
+	
+	/*
+	* Maximum size of X field
+	*/
+	function TextMax()
+	{
+		return 4294967295; 
+	}
+	
+	// "Innox - Juan Carlos Gonzalez" <jgonzalez#innox.com.mx>
+	function MetaForeignKeys( $table, $owner = FALSE, $upper = FALSE, $associative = FALSE )
+     {
+	 global $ADODB_FETCH_MODE;
+		if ($ADODB_FETCH_MODE == ADODB_FETCH_ASSOC || $this->fetchMode == ADODB_FETCH_ASSOC) $associative = true;
+
+         if ( !empty($owner) ) {
+            $table = "$owner.$table";
+         }
+         $a_create_table = $this->getRow(sprintf('SHOW CREATE TABLE %s', $table));
+		 if ($associative) $create_sql = $a_create_table["Create Table"];
+         else $create_sql  = $a_create_table[1];
+
+         $matches = array();
+
+         if (!preg_match_all("/FOREIGN KEY \(`(.*?)`\) REFERENCES `(.*?)` \(`(.*?)`\)/", $create_sql, $matches)) return false;
+	     $foreign_keys = array();	 	 
+         $num_keys = count($matches[0]);
+         for ( $i = 0;  $i < $num_keys;  $i ++ ) {
+             $my_field  = explode('`, `', $matches[1][$i]);
+             $ref_table = $matches[2][$i];
+             $ref_field = explode('`, `', $matches[3][$i]);
+
+             if ( $upper ) {
+                 $ref_table = strtoupper($ref_table);
+             }
+
+             $foreign_keys[$ref_table] = array();
+             $num_fields = count($my_field);
+             for ( $j = 0;  $j < $num_fields;  $j ++ ) {
+                 if ( $associative ) {
+                     $foreign_keys[$ref_table][$ref_field[$j]] = $my_field[$j];
+                 } else {
+                     $foreign_keys[$ref_table][] = "{$my_field[$j]}={$ref_field[$j]}";
+                 }
+             }
+         }
+         
+         return  $foreign_keys;
+     }
+	 
+	
+}
+	
+/*--------------------------------------------------------------------------------------
+	 Class Name: Recordset
+--------------------------------------------------------------------------------------*/
+
+
+class ADORecordSet_mysql extends ADORecordSet{	
+	
+	var $databaseType = "mysql";
+	var $canSeek = true;
+	
+	function ADORecordSet_mysql($queryID,$mode=false) 
+	{
+		if ($mode === false) { 
+			global $ADODB_FETCH_MODE;
+			$mode = $ADODB_FETCH_MODE;
+		}
+		switch ($mode)
+		{
+		case ADODB_FETCH_NUM: $this->fetchMode = MYSQL_NUM; break;
+		case ADODB_FETCH_ASSOC:$this->fetchMode = MYSQL_ASSOC; break;
+		case ADODB_FETCH_DEFAULT:
+		case ADODB_FETCH_BOTH:
+		default:
+			$this->fetchMode = MYSQL_BOTH; break;
+		}
+		$this->adodbFetchMode = $mode;
+		$this->ADORecordSet($queryID);	
+	}
+	
+	function _initrs()
+	{
+	//GLOBAL $ADODB_COUNTRECS;
+	//	$this->_numOfRows = ($ADODB_COUNTRECS) ? @mysql_num_rows($this->_queryID):-1;
+		$this->_numOfRows = @mysql_num_rows($this->_queryID);
+		$this->_numOfFields = @mysql_num_fields($this->_queryID);
+	}
+	
+	function &FetchField($fieldOffset = -1) 
+	{	
+		if ($fieldOffset != -1) {
+			$o = @mysql_fetch_field($this->_queryID, $fieldOffset);
+			$f = @mysql_field_flags($this->_queryID,$fieldOffset);
+			$o->max_length = @mysql_field_len($this->_queryID,$fieldOffset); // suggested by: Jim Nicholson (jnich#att.com)
+			//$o->max_length = -1; // mysql returns the max length less spaces -- so it is unrealiable
+			$o->binary = (strpos($f,'binary')!== false);
+		}
+		else if ($fieldOffset == -1) {	/*	The $fieldOffset argument is not provided thus its -1 	*/
+			$o = @mysql_fetch_field($this->_queryID);
+		$o->max_length = @mysql_field_len($this->_queryID); // suggested by: Jim Nicholson (jnich#att.com)
+		//$o->max_length = -1; // mysql returns the max length less spaces -- so it is unrealiable
+		}
+			
+		return $o;
+	}
+
+	function &GetRowAssoc($upper=true)
+	{
+		if ($this->fetchMode == MYSQL_ASSOC && !$upper) $row = $this->fields;
+		else $row =& ADORecordSet::GetRowAssoc($upper);
+		return $row;
+	}
+	
+	/* Use associative array to get fields array */
+	function Fields($colname)
+	{	
+		// added @ by "Michael William Miller" <mille562@pilot.msu.edu>
+		if ($this->fetchMode != MYSQL_NUM) return @$this->fields[$colname];
+		
+		if (!$this->bind) {
+			$this->bind = array();
+			for ($i=0; $i < $this->_numOfFields; $i++) {
+				$o = $this->FetchField($i);
+				$this->bind[strtoupper($o->name)] = $i;
+			}
+		}
+		 return $this->fields[$this->bind[strtoupper($colname)]];
+	}
+	
+	function _seek($row)
+	{
+		if ($this->_numOfRows == 0) return false;
+		return @mysql_data_seek($this->_queryID,$row);
+	}
+	
+	function MoveNext()
+	{
+		//return adodb_movenext($this);
+		//if (defined('ADODB_EXTENSION')) return adodb_movenext($this);
+		if (@$this->fields = mysql_fetch_array($this->_queryID,$this->fetchMode)) {
+			$this->_currentRow += 1;
+			return true;
+		}
+		if (!$this->EOF) {
+			$this->_currentRow += 1;
+			$this->EOF = true;
+		}
+		return false;
+	}
+	
+	function _fetch()
+	{
+		$this->fields =  @mysql_fetch_array($this->_queryID,$this->fetchMode);
+		return is_array($this->fields);
+	}
+	
+	function _close() {
+		@mysql_free_result($this->_queryID);	
+		$this->_queryID = false;	
+	}
+	
+	function MetaType($t,$len=-1,$fieldobj=false)
+	{
+		if (is_object($t)) {
+			$fieldobj = $t;
+			$t = $fieldobj->type;
+			$len = $fieldobj->max_length;
+		}
+		
+		$len = -1; // mysql max_length is not accurate
+		switch (strtoupper($t)) {
+		case 'STRING': 
+		case 'CHAR':
+		case 'VARCHAR': 
+		case 'TINYBLOB': 
+		case 'TINYTEXT': 
+		case 'ENUM': 
+		case 'SET': 
+			if ($len <= $this->blobSize) return 'C';
+			
+		case 'TEXT':
+		case 'LONGTEXT': 
+		case 'MEDIUMTEXT':
+			return 'X';
+			
+		// php_mysql extension always returns 'blob' even if 'text'
+		// so we have to check whether binary...
+		case 'IMAGE':
+		case 'LONGBLOB': 
+		case 'BLOB':
+		case 'MEDIUMBLOB':
+			return !empty($fieldobj->binary) ? 'B' : 'X';
+			
+		case 'YEAR':
+		case 'DATE': return 'D';
+		
+		case 'TIME':
+		case 'DATETIME':
+		case 'TIMESTAMP': return 'T';
+		
+		case 'INT': 
+		case 'INTEGER':
+		case 'BIGINT':
+		case 'TINYINT':
+		case 'MEDIUMINT':
+		case 'SMALLINT': 
+			
+			if (!empty($fieldobj->primary_key)) return 'R';
+			else return 'I';
+		
+		default: return 'N';
+		}
+	}
+
+}
+
+class ADORecordSet_ext_mysql extends ADORecordSet_mysql {	
+	function ADORecordSet_ext_mysql($queryID,$mode=false) 
+	{
+		if ($mode === false) { 
+			global $ADODB_FETCH_MODE;
+			$mode = $ADODB_FETCH_MODE;
+		}
+		switch ($mode)
+		{
+		case ADODB_FETCH_NUM: $this->fetchMode = MYSQL_NUM; break;
+		case ADODB_FETCH_ASSOC:$this->fetchMode = MYSQL_ASSOC; break;
+		case ADODB_FETCH_DEFAULT:
+		case ADODB_FETCH_BOTH:
+		default:
+		$this->fetchMode = MYSQL_BOTH; break;
+		}
+		$this->adodbFetchMode = $mode;
+		$this->ADORecordSet($queryID);
+	}
+	
+	function MoveNext()
+	{
+		return @adodb_movenext($this);
+	}
+}
+
+
+}
+?>
Index: /Dev/trunk/rdfapi/util/adodb/drivers/adodb-mysqli.inc.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/drivers/adodb-mysqli.inc.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/drivers/adodb-mysqli.inc.php	(revision 12)
@@ -0,0 +1,1020 @@
+<?php
+/*
+V4.94 23 Jan 2007  (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
+  Released under both BSD license and Lesser GPL library license.
+  Whenever there is any discrepancy between the two licenses,
+  the BSD license will take precedence.
+  Set tabs to 8.
+
+  MySQL code that does not support transactions. Use mysqlt if you need transactions.
+  Requires mysql client. Works on Windows and Unix.
+
+21 October 2003: MySQLi extension implementation by Arjen de Rijke (a.de.rijke@xs4all.nl)
+Based on adodb 3.40
+*/
+
+// security - hide paths
+if (!defined('ADODB_DIR')) die();
+
+if (! defined("_ADODB_MYSQLI_LAYER")) {
+ define("_ADODB_MYSQLI_LAYER", 1 );
+
+ // PHP5 compat...
+ if (! defined("MYSQLI_BINARY_FLAG"))  define("MYSQLI_BINARY_FLAG", 128);
+ if (!defined('MYSQLI_READ_DEFAULT_GROUP')) define('MYSQLI_READ_DEFAULT_GROUP',1);
+
+ // disable adodb extension - currently incompatible.
+ global $ADODB_EXTENSION; $ADODB_EXTENSION = false;
+
+class ADODB_mysqli extends ADOConnection {
+	var $databaseType = 'mysqli';
+	var $dataProvider = 'native';
+	var $hasInsertID = true;
+	var $hasAffectedRows = true;
+	var $metaTablesSQL = "SHOW TABLES";
+	var $metaColumnsSQL = "SHOW COLUMNS FROM `%s`";
+	var $fmtTimeStamp = "'Y-m-d H:i:s'";
+	var $hasLimit = true;
+	var $hasMoveFirst = true;
+	var $hasGenID = true;
+	var $isoDates = true; // accepts dates in ISO format
+	var $sysDate = 'CURDATE()';
+	var $sysTimeStamp = 'NOW()';
+	var $hasTransactions = true;
+	var $forceNewConnect = false;
+	var $poorAffectedRows = true;
+	var $clientFlags = 0;
+	var $substr = "substring";
+	var $port = false;
+	var $socket = false;
+	var $_bindInputArray = false;
+	var $nameQuote = '`';		/// string to use to quote identifiers and names
+	var $optionFlags = array(array(MYSQLI_READ_DEFAULT_GROUP,0));
+
+	function ADODB_mysqli()
+	{
+	 // if(!extension_loaded("mysqli"))
+	      ;//trigger_error("You must have the mysqli extension installed.", E_USER_ERROR);
+
+	}
+
+	function SetTransactionMode( $transaction_mode )
+	{
+		$this->_transmode  = $transaction_mode;
+		if (empty($transaction_mode)) {
+			$this->Execute('SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ');
+			return;
+		}
+		if (!stristr($transaction_mode,'isolation')) $transaction_mode = 'ISOLATION LEVEL '.$transaction_mode;
+		$this->Execute("SET SESSION TRANSACTION ".$transaction_mode);
+	}
+
+	// returns true or false
+	// To add: parameter int $port,
+	//         parameter string $socket
+	function _connect($argHostname = NULL,
+			  $argUsername = NULL,
+			  $argPassword = NULL,
+			  $argDatabasename = NULL, $persist=false)
+	  {
+	  	 if(!extension_loaded("mysqli")) {
+			return null;
+		 }
+	    $this->_connectionID = @mysqli_init();
+
+	    if (is_null($this->_connectionID)) {
+	      // mysqli_init only fails if insufficient memory
+	      if ($this->debug)
+				ADOConnection::outp("mysqli_init() failed : "  . $this->ErrorMsg());
+	      return false;
+	    }
+		/*
+		I suggest a simple fix which would enable adodb and mysqli driver to
+		read connection options from the standard mysql configuration file
+		/etc/my.cnf - "Bastien Duclaux" <bduclaux#yahoo.com>
+		*/
+		foreach($this->optionFlags as $arr) {
+			mysqli_options($this->_connectionID,$arr[0],$arr[1]);
+		}
+
+		#if (!empty($this->port)) $argHostname .= ":".$this->port;
+		$ok = mysqli_real_connect($this->_connectionID,
+ 				    $argHostname,
+ 				    $argUsername,
+ 				    $argPassword,
+ 				    $argDatabasename,
+					$this->port,
+					$this->socket,
+					$this->clientFlags);
+
+		if ($ok) {
+	 		if ($argDatabasename)  return $this->SelectDB($argDatabasename);
+ 			return true;
+ 	   } else {
+			if ($this->debug)
+		  		ADOConnection::outp("Could't connect : "  . $this->ErrorMsg());
+			return false;
+	   }
+	}
+
+	// returns true or false
+	// How to force a persistent connection
+	function _pconnect($argHostname, $argUsername, $argPassword, $argDatabasename)
+	{
+		return $this->_connect($argHostname, $argUsername, $argPassword, $argDatabasename, true);
+
+	}
+
+	// When is this used? Close old connection first?
+	// In _connect(), check $this->forceNewConnect?
+	function _nconnect($argHostname, $argUsername, $argPassword, $argDatabasename)
+	  {
+	    $this->forceNewConnect = true;
+	    return $this->_connect($argHostname, $argUsername, $argPassword, $argDatabasename);
+	  }
+
+	function IfNull( $field, $ifNull )
+	{
+		return " IFNULL($field, $ifNull) "; // if MySQL
+	}
+
+	// do not use $ADODB_COUNTRECS
+	function GetOne($sql,$inputarr=false)
+	{
+		$ret = false;
+		$rs = &$this->Execute($sql,$inputarr);
+		if ($rs) {
+			if (!$rs->EOF) $ret = reset($rs->fields);
+			$rs->Close();
+		}
+		return $ret;
+	}
+
+	function ServerInfo()
+	{
+		$arr['description'] = $this->GetOne("select version()");
+		$arr['version'] = ADOConnection::_findvers($arr['description']);
+		return $arr;
+	}
+
+
+	function BeginTrans()
+	{
+		if ($this->transOff) return true;
+		$this->transCnt += 1;
+
+		//$this->Execute('SET AUTOCOMMIT=0');
+		mysqli_autocommit($this->_connectionID, false);
+		$this->Execute('BEGIN');
+		return true;
+	}
+
+	function CommitTrans($ok=true)
+	{
+		if ($this->transOff) return true;
+		if (!$ok) return $this->RollbackTrans();
+
+		if ($this->transCnt) $this->transCnt -= 1;
+		$this->Execute('COMMIT');
+
+		//$this->Execute('SET AUTOCOMMIT=1');
+		mysqli_autocommit($this->_connectionID, true);
+		return true;
+	}
+
+	function RollbackTrans()
+	{
+		if ($this->transOff) return true;
+		if ($this->transCnt) $this->transCnt -= 1;
+		$this->Execute('ROLLBACK');
+		//$this->Execute('SET AUTOCOMMIT=1');
+		mysqli_autocommit($this->_connectionID, true);
+		return true;
+	}
+
+	function RowLock($tables,$where='',$flds='1 as adodb_ignore')
+	{
+		if ($this->transCnt==0) $this->BeginTrans();
+		if ($where) $where = ' where '.$where;
+		$rs =& $this->Execute("select $flds from $tables $where for update");
+		return !empty($rs);
+	}
+
+	// if magic quotes disabled, use mysql_real_escape_string()
+	// From readme.htm:
+	// Quotes a string to be sent to the database. The $magic_quotes_enabled
+	// parameter may look funny, but the idea is if you are quoting a
+	// string extracted from a POST/GET variable, then
+	// pass get_magic_quotes_gpc() as the second parameter. This will
+	// ensure that the variable is not quoted twice, once by qstr and once
+	// by the magic_quotes_gpc.
+	//
+	//Eg. $s = $db->qstr(_GET['name'],get_magic_quotes_gpc());
+	function qstr($s, $magic_quotes = false)
+	{
+		if (!$magic_quotes) {
+	    	if (PHP_VERSION >= 5)
+	      		return "'" . mysqli_real_escape_string($this->_connectionID, $s) . "'";
+
+		if ($this->replaceQuote[0] == '\\')
+			$s = adodb_str_replace(array('\\',"\0"),array('\\\\',"\\\0"),$s);
+	    return  "'".str_replace("'",$this->replaceQuote,$s)."'";
+	  }
+	  // undo magic quotes for "
+	  $s = str_replace('\\"','"',$s);
+	  return "'$s'";
+	}
+
+	function _insertid()
+	{
+	  $result = @mysqli_insert_id($this->_connectionID);
+	  if ($result == -1){
+	      if ($this->debug) ADOConnection::outp("mysqli_insert_id() failed : "  . $this->ErrorMsg());
+	  }
+	  return $result;
+	}
+
+	// Only works for INSERT, UPDATE and DELETE query's
+	function _affectedrows()
+	{
+	  $result =  @mysqli_affected_rows($this->_connectionID);
+	  if ($result == -1) {
+	      if ($this->debug) ADOConnection::outp("mysqli_affected_rows() failed : "  . $this->ErrorMsg());
+	  }
+	  return $result;
+	}
+
+ 	// See http://www.mysql.com/doc/M/i/Miscellaneous_functions.html
+	// Reference on Last_Insert_ID on the recommended way to simulate sequences
+ 	var $_genIDSQL = "update %s set id=LAST_INSERT_ID(id+1);";
+	var $_genSeqSQL = "create table %s (id int not null)";
+	var $_genSeq2SQL = "insert into %s values (%s)";
+	var $_dropSeqSQL = "drop table %s";
+
+	function CreateSequence($seqname='adodbseq',$startID=1)
+	{
+		if (empty($this->_genSeqSQL)) return false;
+		$u = strtoupper($seqname);
+
+		$ok = $this->Execute(sprintf($this->_genSeqSQL,$seqname));
+		if (!$ok) return false;
+		return $this->Execute(sprintf($this->_genSeq2SQL,$seqname,$startID-1));
+	}
+
+	function GenID($seqname='adodbseq',$startID=1)
+	{
+		// post-nuke sets hasGenID to false
+		if (!$this->hasGenID) return false;
+
+		$getnext = sprintf($this->_genIDSQL,$seqname);
+		$holdtransOK = $this->_transOK; // save the current status
+		$rs = @$this->Execute($getnext);
+		if (!$rs) {
+			if ($holdtransOK) $this->_transOK = true; //if the status was ok before reset
+			$u = strtoupper($seqname);
+			$this->Execute(sprintf($this->_genSeqSQL,$seqname));
+			$this->Execute(sprintf($this->_genSeq2SQL,$seqname,$startID-1));
+			$rs = $this->Execute($getnext);
+		}
+		$this->genID = mysqli_insert_id($this->_connectionID);
+
+		if ($rs) $rs->Close();
+
+		return $this->genID;
+	}
+
+  	function &MetaDatabases()
+	{
+		$query = "SHOW DATABASES";
+		$ret =& $this->Execute($query);
+		if ($ret && is_object($ret)){
+		   $arr = array();
+			while (!$ret->EOF){
+				$db = $ret->Fields('Database');
+				if ($db != 'mysql') $arr[] = $db;
+				$ret->MoveNext();
+			}
+   		   return $arr;
+		}
+        return $ret;
+	}
+
+
+	function &MetaIndexes ($table, $primary = FALSE)
+	{
+		// save old fetch mode
+		global $ADODB_FETCH_MODE;
+
+		$false = false;
+		$save = $ADODB_FETCH_MODE;
+		$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
+		if ($this->fetchMode !== FALSE) {
+		       $savem = $this->SetFetchMode(FALSE);
+		}
+
+		// get index details
+		$rs = $this->Execute(sprintf('SHOW INDEXES FROM %s',$table));
+
+		// restore fetchmode
+		if (isset($savem)) {
+		        $this->SetFetchMode($savem);
+		}
+		$ADODB_FETCH_MODE = $save;
+
+		if (!is_object($rs)) {
+		        return $false;
+		}
+
+		$indexes = array ();
+
+		// parse index data into array
+		while ($row = $rs->FetchRow()) {
+		        if ($primary == FALSE AND $row[2] == 'PRIMARY') {
+		                continue;
+		        }
+
+		        if (!isset($indexes[$row[2]])) {
+		                $indexes[$row[2]] = array(
+		                        'unique' => ($row[1] == 0),
+		                        'columns' => array()
+		                );
+		        }
+
+		        $indexes[$row[2]]['columns'][$row[3] - 1] = $row[4];
+		}
+
+		// sort columns by order in the index
+		foreach ( array_keys ($indexes) as $index )
+		{
+		        ksort ($indexes[$index]['columns']);
+		}
+
+		return $indexes;
+	}
+
+
+	// Format date column in sql string given an input format that understands Y M D
+	function SQLDate($fmt, $col=false)
+	{
+		if (!$col) $col = $this->sysTimeStamp;
+		$s = 'DATE_FORMAT('.$col.",'";
+		$concat = false;
+		$len = strlen($fmt);
+		for ($i=0; $i < $len; $i++) {
+			$ch = $fmt[$i];
+			switch($ch) {
+			case 'Y':
+			case 'y':
+				$s .= '%Y';
+				break;
+			case 'Q':
+			case 'q':
+				$s .= "'),Quarter($col)";
+
+				if ($len > $i+1) $s .= ",DATE_FORMAT($col,'";
+				else $s .= ",('";
+				$concat = true;
+				break;
+			case 'M':
+				$s .= '%b';
+				break;
+
+			case 'm':
+				$s .= '%m';
+				break;
+			case 'D':
+			case 'd':
+				$s .= '%d';
+				break;
+
+			case 'H':
+				$s .= '%H';
+				break;
+
+			case 'h':
+				$s .= '%I';
+				break;
+
+			case 'i':
+				$s .= '%i';
+				break;
+
+			case 's':
+				$s .= '%s';
+				break;
+
+			case 'a':
+			case 'A':
+				$s .= '%p';
+				break;
+
+			case 'w':
+				$s .= '%w';
+				break;
+
+			case 'l':
+				$s .= '%W';
+				break;
+
+			default:
+
+				if ($ch == '\\') {
+					$i++;
+					$ch = substr($fmt,$i,1);
+				}
+				$s .= $ch;
+				break;
+			}
+		}
+		$s.="')";
+		if ($concat) $s = "CONCAT($s)";
+		return $s;
+	}
+
+	// returns concatenated string
+	// much easier to run "mysqld --ansi" or "mysqld --sql-mode=PIPES_AS_CONCAT" and use || operator
+	function Concat()
+	{
+		$s = "";
+		$arr = func_get_args();
+
+		// suggestion by andrew005@mnogo.ru
+		$s = implode(',',$arr);
+		if (strlen($s) > 0) return "CONCAT($s)";
+		else return '';
+	}
+
+	// dayFraction is a day in floating point
+	function OffsetDate($dayFraction,$date=false)
+	{
+		if (!$date) $date = $this->sysDate;
+
+		$fraction = $dayFraction * 24 * 3600;
+		return $date . ' + INTERVAL ' .	 $fraction.' SECOND';
+
+//		return "from_unixtime(unix_timestamp($date)+$fraction)";
+	}
+
+	function &MetaTables($ttype=false,$showSchema=false,$mask=false)
+	{
+		$save = $this->metaTablesSQL;
+		if ($showSchema && is_string($showSchema)) {
+			$this->metaTablesSQL .= " from $showSchema";
+		}
+
+		if ($mask) {
+			$mask = $this->qstr($mask);
+			$this->metaTablesSQL .= " like $mask";
+		}
+		$ret =& ADOConnection::MetaTables($ttype,$showSchema);
+
+		$this->metaTablesSQL = $save;
+		return $ret;
+	}
+
+	// "Innox - Juan Carlos Gonzalez" <jgonzalez#innox.com.mx>
+	function MetaForeignKeys( $table, $owner = FALSE, $upper = FALSE, $associative = FALSE )
+	{
+	 global $ADODB_FETCH_MODE;
+
+		if ($ADODB_FETCH_MODE == ADODB_FETCH_ASSOC || $this->fetchMode == ADODB_FETCH_ASSOC) $associative = true;
+
+	    if ( !empty($owner) ) {
+	       $table = "$owner.$table";
+	    }
+	    $a_create_table = $this->getRow(sprintf('SHOW CREATE TABLE %s', $table));
+		if ($associative) $create_sql = $a_create_table["Create Table"];
+	    else $create_sql  = $a_create_table[1];
+
+	    $matches = array();
+
+	    if (!preg_match_all("/FOREIGN KEY \(`(.*?)`\) REFERENCES `(.*?)` \(`(.*?)`\)/", $create_sql, $matches)) return false;
+	 	$foreign_keys = array();
+	    $num_keys = count($matches[0]);
+	    for ( $i = 0;  $i < $num_keys;  $i ++ ) {
+	        $my_field  = explode('`, `', $matches[1][$i]);
+	        $ref_table = $matches[2][$i];
+	        $ref_field = explode('`, `', $matches[3][$i]);
+
+	        if ( $upper ) {
+	            $ref_table = strtoupper($ref_table);
+	        }
+
+	        $foreign_keys[$ref_table] = array();
+	        $num_fields               = count($my_field);
+	        for ( $j = 0;  $j < $num_fields;  $j ++ ) {
+	            if ( $associative ) {
+	                $foreign_keys[$ref_table][$ref_field[$j]] = $my_field[$j];
+	            } else {
+	                $foreign_keys[$ref_table][] = "{$my_field[$j]}={$ref_field[$j]}";
+	            }
+	        }
+	    }
+
+	    return  $foreign_keys;
+	}
+
+ 	function &MetaColumns($table)
+	{
+		$false = false;
+		if (!$this->metaColumnsSQL)
+			return $false;
+
+		global $ADODB_FETCH_MODE;
+		$save = $ADODB_FETCH_MODE;
+		$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
+		if ($this->fetchMode !== false)
+			$savem = $this->SetFetchMode(false);
+		$rs = $this->Execute(sprintf($this->metaColumnsSQL,$table));
+		if (isset($savem)) $this->SetFetchMode($savem);
+		$ADODB_FETCH_MODE = $save;
+		if (!is_object($rs))
+			return $false;
+
+		$retarr = array();
+		while (!$rs->EOF) {
+			$fld = new ADOFieldObject();
+			$fld->name = $rs->fields[0];
+			$type = $rs->fields[1];
+
+			// split type into type(length):
+			$fld->scale = null;
+			if (preg_match("/^(.+)\((\d+),(\d+)/", $type, $query_array)) {
+				$fld->type = $query_array[1];
+				$fld->max_length = is_numeric($query_array[2]) ? $query_array[2] : -1;
+				$fld->scale = is_numeric($query_array[3]) ? $query_array[3] : -1;
+			} elseif (preg_match("/^(.+)\((\d+)/", $type, $query_array)) {
+				$fld->type = $query_array[1];
+				$fld->max_length = is_numeric($query_array[2]) ? $query_array[2] : -1;
+			} elseif (preg_match("/^(enum)\((.*)\)$/i", $type, $query_array)) {
+				$fld->type = $query_array[1];
+				$fld->max_length = max(array_map("strlen",explode(",",$query_array[2]))) - 2; // PHP >= 4.0.6
+				$fld->max_length = ($fld->max_length == 0 ? 1 : $fld->max_length);
+			} else {
+				$fld->type = $type;
+				$fld->max_length = -1;
+			}
+			$fld->not_null = ($rs->fields[2] != 'YES');
+			$fld->primary_key = ($rs->fields[3] == 'PRI');
+			$fld->auto_increment = (strpos($rs->fields[5], 'auto_increment') !== false);
+			$fld->binary = (strpos($type,'blob') !== false);
+			$fld->unsigned = (strpos($type,'unsigned') !== false);
+
+			if (!$fld->binary) {
+				$d = $rs->fields[4];
+				if ($d != '' && $d != 'NULL') {
+					$fld->has_default = true;
+					$fld->default_value = $d;
+				} else {
+					$fld->has_default = false;
+				}
+			}
+
+			if ($save == ADODB_FETCH_NUM) {
+				$retarr[] = $fld;
+			} else {
+				$retarr[strtoupper($fld->name)] = $fld;
+			}
+			$rs->MoveNext();
+		}
+
+		$rs->Close();
+		return $retarr;
+	}
+
+	// returns true or false
+	function SelectDB($dbName)
+	{
+//	    $this->_connectionID = $this->mysqli_resolve_link($this->_connectionID);
+	    $this->database = $dbName;
+		$this->databaseName = $dbName; # obsolete, retained for compat with older adodb versions
+
+	    if ($this->_connectionID) {
+        	$result = @mysqli_select_db($this->_connectionID, $dbName);
+			if (!$result) {
+		    	ADOConnection::outp("Select of database " . $dbName . " failed. " . $this->ErrorMsg());
+			}
+			return $result;
+		}
+	    return false;
+	}
+
+	// parameters use PostgreSQL convention, not MySQL
+	function &SelectLimit($sql,
+			      $nrows = -1,
+			      $offset = -1,
+			      $inputarr = false,
+			      $arg3 = false,
+			      $secs = 0)
+	{
+		$offsetStr = ($offset >= 0) ? "$offset," : '';
+		if ($nrows < 0) $nrows = '18446744073709551615';
+
+		if ($secs)
+			$rs =& $this->CacheExecute($secs, $sql . " LIMIT $offsetStr$nrows" , $inputarr , $arg3);
+		else
+			$rs =& $this->Execute($sql . " LIMIT $offsetStr$nrows" , $inputarr , $arg3);
+
+		return $rs;
+	}
+
+
+	function Prepare($sql)
+	{
+		return $sql;
+
+		$stmt = $this->_connectionID->prepare($sql);
+		if (!$stmt) {
+			echo $this->ErrorMsg();
+			return $sql;
+		}
+		return array($sql,$stmt);
+	}
+
+
+	// returns queryID or false
+	function _query($sql, $inputarr)
+	{
+	global $ADODB_COUNTRECS;
+
+		if (is_array($sql)) {
+			$stmt = $sql[1];
+			$a = '';
+			foreach($inputarr as $k => $v) {
+				if (is_string($v)) $a .= 's';
+				else if (is_integer($v)) $a .= 'i';
+				else $a .= 'd';
+			}
+
+			$fnarr = array_merge( array($stmt,$a) , $inputarr);
+			$ret = call_user_func_array('mysqli_stmt_bind_param',$fnarr);
+
+			$ret = mysqli_stmt_execute($stmt);
+			return $ret;
+		}
+		if (!$mysql_res =  mysqli_query($this->_connectionID, $sql, ($ADODB_COUNTRECS) ? MYSQLI_STORE_RESULT : MYSQLI_USE_RESULT)) {
+		    if ($this->debug) ADOConnection::outp("Query: " . $sql . " failed. " . $this->ErrorMsg());
+		    return false;
+		}
+
+		return $mysql_res;
+	}
+
+	/*	Returns: the last error message from previous database operation	*/
+	function ErrorMsg()
+	  {
+	    if (empty($this->_connectionID))
+	      $this->_errorMsg = @mysqli_connect_error();
+	    else
+	      $this->_errorMsg = @mysqli_error($this->_connectionID);
+	    return $this->_errorMsg;
+	  }
+
+	/*	Returns: the last error number from previous database operation	*/
+	function ErrorNo()
+	  {
+	    if (empty($this->_connectionID))
+	      return @mysqli_connect_errno();
+	    else
+	      return @mysqli_errno($this->_connectionID);
+	  }
+
+	// returns true or false
+	function _close()
+	  {
+	    @mysqli_close($this->_connectionID);
+	    $this->_connectionID = false;
+	  }
+
+	/*
+	* Maximum size of C field
+	*/
+	function CharMax()
+	{
+		return 255;
+	}
+
+	/*
+	* Maximum size of X field
+	*/
+	function TextMax()
+	{
+	  return 4294967295;
+	}
+
+
+
+	// this is a set of functions for managing client encoding - very important if the encodings
+	// of your database and your output target (i.e. HTML) don't match
+	// for instance, you may have UTF8 database and server it on-site as latin1 etc.
+	// GetCharSet - get the name of the character set the client is using now
+	// Under Windows, the functions should work with MySQL 4.1.11 and above, the set of charsets supported
+	// depends on compile flags of mysql distribution
+
+  function GetCharSet()
+  {
+    //we will use ADO's builtin property charSet
+    if (!method_exists($this->_connectionID,'character_set_name'))
+    	return false;
+
+    $this->charSet = @$this->_connectionID->character_set_name();
+    if (!$this->charSet) {
+      return false;
+    } else {
+      return $this->charSet;
+    }
+  }
+
+  // SetCharSet - switch the client encoding
+  function SetCharSet($charset_name)
+  {
+    if (!method_exists($this->_connectionID,'set_charset'))
+    	return false;
+
+    if ($this->charSet !== $charset_name) {
+      $if = @$this->_connectionID->set_charset($charset_name);
+      if ($if == "0" & $this->GetCharSet() == $charset_name) {
+        return true;
+      } else return false;
+    } else return true;
+  }
+
+
+
+
+}
+
+/*--------------------------------------------------------------------------------------
+	 Class Name: Recordset
+--------------------------------------------------------------------------------------*/
+
+class ADORecordSet_mysqli extends ADORecordSet{
+
+	var $databaseType = "mysqli";
+	var $canSeek = true;
+
+	function ADORecordSet_mysqli($queryID, $mode = false)
+	{
+	  if ($mode === false)
+	   {
+	      global $ADODB_FETCH_MODE;
+	      $mode = $ADODB_FETCH_MODE;
+	   }
+
+	  switch ($mode)
+	    {
+	    case ADODB_FETCH_NUM:
+	      $this->fetchMode = MYSQLI_NUM;
+	      break;
+	    case ADODB_FETCH_ASSOC:
+	      $this->fetchMode = MYSQLI_ASSOC;
+	      break;
+	    case ADODB_FETCH_DEFAULT:
+	    case ADODB_FETCH_BOTH:
+	    default:
+	      $this->fetchMode = MYSQLI_BOTH;
+	      break;
+	    }
+	  $this->adodbFetchMode = $mode;
+	  $this->ADORecordSet($queryID);
+	}
+
+	function _initrs()
+	{
+	global $ADODB_COUNTRECS;
+
+		$this->_numOfRows = $ADODB_COUNTRECS ? @mysqli_num_rows($this->_queryID) : -1;
+		$this->_numOfFields = @mysqli_num_fields($this->_queryID);
+	}
+
+/*
+1      = MYSQLI_NOT_NULL_FLAG
+2      = MYSQLI_PRI_KEY_FLAG
+4      = MYSQLI_UNIQUE_KEY_FLAG
+8      = MYSQLI_MULTIPLE_KEY_FLAG
+16     = MYSQLI_BLOB_FLAG
+32     = MYSQLI_UNSIGNED_FLAG
+64     = MYSQLI_ZEROFILL_FLAG
+128    = MYSQLI_BINARY_FLAG
+256    = MYSQLI_ENUM_FLAG
+512    = MYSQLI_AUTO_INCREMENT_FLAG
+1024   = MYSQLI_TIMESTAMP_FLAG
+2048   = MYSQLI_SET_FLAG
+32768  = MYSQLI_NUM_FLAG
+16384  = MYSQLI_PART_KEY_FLAG
+32768  = MYSQLI_GROUP_FLAG
+65536  = MYSQLI_UNIQUE_FLAG
+131072 = MYSQLI_BINCMP_FLAG
+*/
+
+	function &FetchField($fieldOffset = -1)
+	{
+		$fieldnr = $fieldOffset;
+		if ($fieldOffset != -1) {
+		  $fieldOffset = mysqli_field_seek($this->_queryID, $fieldnr);
+		}
+		$o = mysqli_fetch_field($this->_queryID);
+		/* Properties of an ADOFieldObject as set by MetaColumns */
+		$o->primary_key = $o->flags & MYSQLI_PRI_KEY_FLAG;
+		$o->not_null = $o->flags & MYSQLI_NOT_NULL_FLAG;
+		$o->auto_increment = $o->flags & MYSQLI_AUTO_INCREMENT_FLAG;
+		$o->binary = $o->flags & MYSQLI_BINARY_FLAG;
+		// $o->blob = $o->flags & MYSQLI_BLOB_FLAG; /* not returned by MetaColumns */
+		$o->unsigned = $o->flags & MYSQLI_UNSIGNED_FLAG;
+
+		return $o;
+	}
+
+	function &GetRowAssoc($upper = true)
+	{
+		if ($this->fetchMode == MYSQLI_ASSOC && !$upper)
+		  return $this->fields;
+		$row =& ADORecordSet::GetRowAssoc($upper);
+		return $row;
+	}
+
+	/* Use associative array to get fields array */
+	function Fields($colname)
+	{
+	  if ($this->fetchMode != MYSQLI_NUM)
+	    return @$this->fields[$colname];
+
+	  if (!$this->bind) {
+	    $this->bind = array();
+	    for ($i = 0; $i < $this->_numOfFields; $i++) {
+	      $o = $this->FetchField($i);
+	      $this->bind[strtoupper($o->name)] = $i;
+	    }
+	  }
+	  return $this->fields[$this->bind[strtoupper($colname)]];
+	}
+
+	function _seek($row)
+	{
+	  if ($this->_numOfRows == 0)
+	    return false;
+
+	  if ($row < 0)
+	    return false;
+
+	  mysqli_data_seek($this->_queryID, $row);
+	  $this->EOF = false;
+	  return true;
+	}
+
+	// 10% speedup to move MoveNext to child class
+	// This is the only implementation that works now (23-10-2003).
+	// Other functions return no or the wrong results.
+	function MoveNext()
+	{
+		if ($this->EOF) return false;
+		$this->_currentRow++;
+		$this->fields = @mysqli_fetch_array($this->_queryID,$this->fetchMode);
+
+		if (is_array($this->fields)) return true;
+		$this->EOF = true;
+		return false;
+	}
+
+	function _fetch()
+	{
+		$this->fields = mysqli_fetch_array($this->_queryID,$this->fetchMode);
+	  	return is_array($this->fields);
+	}
+
+	function _close()
+	{
+		mysqli_free_result($this->_queryID);
+	  	$this->_queryID = false;
+	}
+
+/*
+
+0 = MYSQLI_TYPE_DECIMAL
+1 = MYSQLI_TYPE_CHAR
+1 = MYSQLI_TYPE_TINY
+2 = MYSQLI_TYPE_SHORT
+3 = MYSQLI_TYPE_LONG
+4 = MYSQLI_TYPE_FLOAT
+5 = MYSQLI_TYPE_DOUBLE
+6 = MYSQLI_TYPE_NULL
+7 = MYSQLI_TYPE_TIMESTAMP
+8 = MYSQLI_TYPE_LONGLONG
+9 = MYSQLI_TYPE_INT24
+10 = MYSQLI_TYPE_DATE
+11 = MYSQLI_TYPE_TIME
+12 = MYSQLI_TYPE_DATETIME
+13 = MYSQLI_TYPE_YEAR
+14 = MYSQLI_TYPE_NEWDATE
+247 = MYSQLI_TYPE_ENUM
+248 = MYSQLI_TYPE_SET
+249 = MYSQLI_TYPE_TINY_BLOB
+250 = MYSQLI_TYPE_MEDIUM_BLOB
+251 = MYSQLI_TYPE_LONG_BLOB
+252 = MYSQLI_TYPE_BLOB
+253 = MYSQLI_TYPE_VAR_STRING
+254 = MYSQLI_TYPE_STRING
+255 = MYSQLI_TYPE_GEOMETRY
+*/
+
+	function MetaType($t, $len = -1, $fieldobj = false)
+	{
+		if (is_object($t)) {
+		    $fieldobj = $t;
+		    $t = $fieldobj->type;
+		    $len = $fieldobj->max_length;
+		}
+
+
+		 $len = -1; // mysql max_length is not accurate
+		 switch (strtoupper($t)) {
+		 case 'STRING':
+		 case 'CHAR':
+		 case 'VARCHAR':
+		 case 'TINYBLOB':
+		 case 'TINYTEXT':
+		 case 'ENUM':
+		 case 'SET':
+
+		case MYSQLI_TYPE_TINY_BLOB :
+		case MYSQLI_TYPE_CHAR :
+		case MYSQLI_TYPE_STRING :
+		case MYSQLI_TYPE_ENUM :
+		case MYSQLI_TYPE_SET :
+		case 253 :
+		   if ($len <= $this->blobSize) return 'C';
+
+		case 'TEXT':
+		case 'LONGTEXT':
+		case 'MEDIUMTEXT':
+		   return 'X';
+
+
+		   // php_mysql extension always returns 'blob' even if 'text'
+		   // so we have to check whether binary...
+		case 'IMAGE':
+		case 'LONGBLOB':
+		case 'BLOB':
+		case 'MEDIUMBLOB':
+
+		case MYSQLI_TYPE_BLOB :
+		case MYSQLI_TYPE_LONG_BLOB :
+		case MYSQLI_TYPE_MEDIUM_BLOB :
+
+		   return !empty($fieldobj->binary) ? 'B' : 'X';
+		case 'YEAR':
+		case 'DATE':
+		case MYSQLI_TYPE_DATE :
+		case MYSQLI_TYPE_YEAR :
+
+		   return 'D';
+
+		case 'TIME':
+		case 'DATETIME':
+		case 'TIMESTAMP':
+
+		case MYSQLI_TYPE_DATETIME :
+		case MYSQLI_TYPE_NEWDATE :
+		case MYSQLI_TYPE_TIME :
+		case MYSQLI_TYPE_TIMESTAMP :
+
+			return 'T';
+
+		case 'INT':
+		case 'INTEGER':
+		case 'BIGINT':
+		case 'TINYINT':
+		case 'MEDIUMINT':
+		case 'SMALLINT':
+
+		case MYSQLI_TYPE_INT24 :
+		case MYSQLI_TYPE_LONG :
+		case MYSQLI_TYPE_LONGLONG :
+		case MYSQLI_TYPE_SHORT :
+		case MYSQLI_TYPE_TINY :
+
+		   if (!empty($fieldobj->primary_key)) return 'R';
+
+		   return 'I';
+
+
+		   // Added floating-point types
+		   // Maybe not necessery.
+		 case 'FLOAT':
+		 case 'DOUBLE':
+		   //		case 'DOUBLE PRECISION':
+		 case 'DECIMAL':
+		 case 'DEC':
+		 case 'FIXED':
+		 default:
+		 	//if (!is_numeric($t)) echo "<p>--- Error in type matching $t -----</p>";
+		 	return 'N';
+		}
+	} // function
+
+
+} // rs class
+
+}
+
+?>
Index: /Dev/trunk/rdfapi/util/adodb/drivers/adodb-mysqlt.inc.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/drivers/adodb-mysqlt.inc.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/drivers/adodb-mysqlt.inc.php	(revision 12)
@@ -0,0 +1,155 @@
+<?php
+
+/*
+V4.94 23 Jan 2007  (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence.
+  Set tabs to 8.
+  
+  MySQL code that supports transactions. For MySQL 3.23 or later.
+  Code from James Poon <jpoon88@yahoo.com>
+  
+  Requires mysql client. Works on Windows and Unix.
+*/
+
+// security - hide paths
+if (!defined('ADODB_DIR')) die();
+
+include_once(ADODB_DIR."/drivers/adodb-mysql.inc.php");
+
+
+class ADODB_mysqlt extends ADODB_mysql {
+	var $databaseType = 'mysqlt';
+	var $ansiOuter = true; // for Version 3.23.17 or later
+	var $hasTransactions = true;
+	var $autoRollback = true; // apparently mysql does not autorollback properly 
+	
+	function ADODB_mysqlt() 
+	{			
+	global $ADODB_EXTENSION; if ($ADODB_EXTENSION) $this->rsPrefix .= 'ext_';
+	}
+	
+	/* set transaction mode
+	
+	SET [GLOBAL | SESSION] TRANSACTION ISOLATION LEVEL
+{ READ UNCOMMITTED | READ COMMITTED | REPEATABLE READ | SERIALIZABLE }
+
+	*/
+	function SetTransactionMode( $transaction_mode ) 
+	{
+		$this->_transmode  = $transaction_mode;
+		if (empty($transaction_mode)) {
+			$this->Execute('SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ');
+			return;
+		}
+		if (!stristr($transaction_mode,'isolation')) $transaction_mode = 'ISOLATION LEVEL '.$transaction_mode;
+		$this->Execute("SET SESSION TRANSACTION ".$transaction_mode);
+	}
+	
+	function BeginTrans()
+	{	  
+		if ($this->transOff) return true;
+		$this->transCnt += 1;
+		$this->Execute('SET AUTOCOMMIT=0');
+		$this->Execute('BEGIN');
+		return true;
+	}
+	
+	function CommitTrans($ok=true) 
+	{
+		if ($this->transOff) return true; 
+		if (!$ok) return $this->RollbackTrans();
+		
+		if ($this->transCnt) $this->transCnt -= 1;
+		$this->Execute('COMMIT');
+		$this->Execute('SET AUTOCOMMIT=1');
+		return true;
+	}
+	
+	function RollbackTrans()
+	{
+		if ($this->transOff) return true;
+		if ($this->transCnt) $this->transCnt -= 1;
+		$this->Execute('ROLLBACK');
+		$this->Execute('SET AUTOCOMMIT=1');
+		return true;
+	}
+	
+	function RowLock($tables,$where='',$flds='1 as adodb_ignore') 
+	{
+		if ($this->transCnt==0) $this->BeginTrans();
+		if ($where) $where = ' where '.$where;
+		$rs =& $this->Execute("select $flds from $tables $where for update");
+		return !empty($rs); 
+	}
+	
+}
+
+class ADORecordSet_mysqlt extends ADORecordSet_mysql{	
+	var $databaseType = "mysqlt";
+	
+	function ADORecordSet_mysqlt($queryID,$mode=false) 
+	{
+		if ($mode === false) { 
+			global $ADODB_FETCH_MODE;
+			$mode = $ADODB_FETCH_MODE;
+		}
+		
+		switch ($mode)
+		{
+		case ADODB_FETCH_NUM: $this->fetchMode = MYSQL_NUM; break;
+		case ADODB_FETCH_ASSOC:$this->fetchMode = MYSQL_ASSOC; break;
+		
+		case ADODB_FETCH_DEFAULT:
+		case ADODB_FETCH_BOTH:
+		default: $this->fetchMode = MYSQL_BOTH; break;
+		}
+	
+		$this->adodbFetchMode = $mode;
+		$this->ADORecordSet($queryID);	
+	}
+	
+	function MoveNext()
+	{
+		if (@$this->fields = mysql_fetch_array($this->_queryID,$this->fetchMode)) {
+			$this->_currentRow += 1;
+			return true;
+		}
+		if (!$this->EOF) {
+			$this->_currentRow += 1;
+			$this->EOF = true;
+		}
+		return false;
+	}
+}
+
+class ADORecordSet_ext_mysqlt extends ADORecordSet_mysqlt {	
+
+	function ADORecordSet_ext_mysqlt($queryID,$mode=false) 
+	{
+		if ($mode === false) { 
+			global $ADODB_FETCH_MODE;
+			$mode = $ADODB_FETCH_MODE;
+		}
+		switch ($mode)
+		{
+		case ADODB_FETCH_NUM: $this->fetchMode = MYSQL_NUM; break;
+		case ADODB_FETCH_ASSOC:$this->fetchMode = MYSQL_ASSOC; break;
+		
+		case ADODB_FETCH_DEFAULT:
+		case ADODB_FETCH_BOTH:
+		default: 
+			$this->fetchMode = MYSQL_BOTH; break;
+		}
+		$this->adodbFetchMode = $mode;
+		$this->ADORecordSet($queryID);	
+	}
+	
+	function MoveNext()
+	{
+		return adodb_movenext($this);
+	}
+}
+
+?>
Index: /Dev/trunk/rdfapi/util/adodb/drivers/adodb-netezza.inc.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/drivers/adodb-netezza.inc.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/drivers/adodb-netezza.inc.php	(revision 12)
@@ -0,0 +1,170 @@
+<?php
+/*
+  V4.94 23 Jan 2007  (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
+ 
+  First cut at the Netezza Driver by Josh Eldridge joshuae74#hotmail.com
+ Based on the previous postgres drivers.
+ http://www.netezza.com/
+ Major Additions/Changes:
+    MetaDatabasesSQL, MetaTablesSQL, MetaColumnsSQL
+    Note: You have to have admin privileges to access the system tables
+    Removed non-working keys code (Netezza has no concept of keys)
+    Fixed the way data types and lengths are returned in MetaColumns()
+    as well as added the default lengths for certain types
+    Updated public variables for Netezza
+    Still need to remove blob functions, as Netezza doesn't suppport blob
+*/
+// security - hide paths
+if (!defined('ADODB_DIR')) die();
+
+include_once(ADODB_DIR.'/drivers/adodb-postgres64.inc.php');
+
+class ADODB_netezza extends ADODB_postgres64 {
+    var $databaseType = 'netezza';	
+	var $dataProvider = 'netezza';
+	var $hasInsertID = false;
+	var $_resultid = false;
+  	var $concat_operator='||';
+  	var $random = 'random';
+	var $metaDatabasesSQL = "select objname from _v_object_data where objtype='database' order by 1";
+    var $metaTablesSQL = "select objname from _v_object_data where objtype='table' order by 1";
+	var $isoDates = true; // accepts dates in ISO format
+	var $sysDate = "CURRENT_DATE";
+	var $sysTimeStamp = "CURRENT_TIMESTAMP";
+	var $blobEncodeType = 'C';
+	var $metaColumnsSQL = "SELECT attname, atttype FROM _v_relation_column_def WHERE name = '%s' AND attnum > 0 ORDER BY attnum";
+	var $metaColumnsSQL1 = "SELECT attname, atttype FROM _v_relation_column_def WHERE name = '%s' AND attnum > 0 ORDER BY attnum";
+	// netezza doesn't have keys. it does have distributions, so maybe this is 
+	// something that can be pulled from the system tables
+	var $metaKeySQL = "";
+	var $hasAffectedRows = true;
+	var $hasLimit = true;	
+	var $true = 't';		// string that represents TRUE for a database
+	var $false = 'f';		// string that represents FALSE for a database
+	var $fmtDate = "'Y-m-d'";	// used by DBDate() as the default date format used by the database
+	var $fmtTimeStamp = "'Y-m-d G:i:s'"; // used by DBTimeStamp as the default timestamp fmt.
+	var $ansiOuter = true;
+	var $autoRollback = true; // apparently pgsql does not autorollback properly before 4.3.4
+							// http://bugs.php.net/bug.php?id=25404
+
+							
+	function ADODB_netezza() 
+	{
+	
+	}
+	
+	function &MetaColumns($table,$upper=true) 
+	{
+	
+	// Changed this function to support Netezza which has no concept of keys
+	// could posisbly work on other things from the system table later.
+	
+	global $ADODB_FETCH_MODE;
+	
+		$table = strtolower($table);
+
+		$save = $ADODB_FETCH_MODE;
+		$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
+		if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false);
+		
+		$rs =& $this->Execute(sprintf($this->metaColumnsSQL,$table,$table));
+		if (isset($savem)) $this->SetFetchMode($savem);
+		$ADODB_FETCH_MODE = $save;
+		
+		if ($rs === false) return false;
+
+		$retarr = array();
+		while (!$rs->EOF) { 	
+			$fld = new ADOFieldObject();
+			$fld->name = $rs->fields[0];
+			
+			// since we're returning type and length as one string, 
+			// split them out here.
+			
+			if ($first = strstr($rs->fields[1], "(")) {
+			 $fld->max_length = trim($first, "()");
+			} else {
+			 $fld->max_length = -1;
+			}
+		
+			if ($first = strpos($rs->fields[1], "(")) {
+			 $fld->type = substr($rs->fields[1], 0, $first);
+			} else {
+			 $fld->type = $rs->fields[1];
+			}
+			
+			switch ($fld->type) {
+			 case "byteint":
+			 case "boolean":
+			 $fld->max_length = 1;
+			 break;
+			 case "smallint":
+			 $fld->max_length = 2;
+			 break;
+			 case "integer":
+			 case "numeric":
+			 case "date":
+			 $fld->max_length = 4;
+			 break;
+			 case "bigint":
+			 case "time":
+			 case "timestamp":
+			 $fld->max_length = 8;
+			 break;
+			 case "timetz":
+			 case "time with time zone":
+			 $fld->max_length = 12;
+			 break;
+			}
+			
+			if ($ADODB_FETCH_MODE == ADODB_FETCH_NUM) $retarr[] = $fld;	
+			else $retarr[($upper) ? strtoupper($fld->name) : $fld->name] = $fld;
+			
+			$rs->MoveNext();
+		}
+		$rs->Close();
+		return $retarr;	
+		
+	}
+
+		
+}
+	
+/*--------------------------------------------------------------------------------------
+	 Class Name: Recordset
+--------------------------------------------------------------------------------------*/
+
+class ADORecordSet_netezza extends ADORecordSet_postgres64
+{
+	var $databaseType = "netezza";
+	var $canSeek = true;
+	
+	function ADORecordSet_netezza($queryID,$mode=false) 
+	{
+		if ($mode === false) { 
+			global $ADODB_FETCH_MODE;
+			$mode = $ADODB_FETCH_MODE;
+		}
+		switch ($mode)
+		{
+		case ADODB_FETCH_NUM: $this->fetchMode = PGSQL_NUM; break;
+		case ADODB_FETCH_ASSOC:$this->fetchMode = PGSQL_ASSOC; break;
+		
+		case ADODB_FETCH_DEFAULT:
+		case ADODB_FETCH_BOTH:
+		default: $this->fetchMode = PGSQL_BOTH; break;
+		}
+		$this->adodbFetchMode = $mode;
+		$this->ADORecordSet($queryID);
+	}
+	
+	// _initrs modified to disable blob handling
+	function _initrs()
+	{
+	global $ADODB_COUNTRECS;
+		$this->_numOfRows = ($ADODB_COUNTRECS)? @pg_numrows($this->_queryID):-1;
+		$this->_numOfFields = @pg_numfields($this->_queryID);
+	}
+
+}
+?>
Index: /Dev/trunk/rdfapi/util/adodb/drivers/adodb-oci8.inc.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/drivers/adodb-oci8.inc.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/drivers/adodb-oci8.inc.php	(revision 12)
@@ -0,0 +1,1512 @@
+<?php
+/*
+
+  version V4.94 23 Jan 2007 (c) 2000-2007 John Lim. All rights reserved.
+
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence.
+
+  Latest version is available at http://adodb.sourceforge.net
+  
+  Code contributed by George Fourlanos <fou@infomap.gr>
+  
+  13 Nov 2000 jlim - removed all ora_* references.
+*/
+
+// security - hide paths
+if (!defined('ADODB_DIR')) die();
+
+/*
+NLS_Date_Format
+Allows you to use a date format other than the Oracle Lite default. When a literal
+character string appears where a date value is expected, the Oracle Lite database
+tests the string to see if it matches the formats of Oracle, SQL-92, or the value
+specified for this parameter in the POLITE.INI file. Setting this parameter also
+defines the default format used in the TO_CHAR or TO_DATE functions when no
+other format string is supplied.
+
+For Oracle the default is dd-mon-yy or dd-mon-yyyy, and for SQL-92 the default is
+yy-mm-dd or yyyy-mm-dd.
+
+Using 'RR' in the format forces two-digit years less than or equal to 49 to be
+interpreted as years in the 21st century (20002049), and years over 50 as years in
+the 20th century (19501999). Setting the RR format as the default for all two-digit
+year entries allows you to become year-2000 compliant. For example:
+NLS_DATE_FORMAT='RR-MM-DD'
+
+You can also modify the date format using the ALTER SESSION command. 
+*/
+
+# define the LOB descriptor type for the given type
+# returns false if no LOB descriptor
+function oci_lob_desc($type) {
+	switch ($type) {
+		case OCI_B_BFILE: $result = OCI_D_FILE; break;
+		case OCI_B_CFILEE: $result = OCI_D_FILE; break;
+		case OCI_B_CLOB: $result = OCI_D_LOB; break;
+		case OCI_B_BLOB: $result = OCI_D_LOB; break;
+		case OCI_B_ROWID: $result = OCI_D_ROWID; break;
+		default: $result = false; break;
+	}
+	return $result;
+}
+
+class ADODB_oci8 extends ADOConnection {
+	var $databaseType = 'oci8';
+	var $dataProvider = 'oci8';
+	var $replaceQuote = "''"; // string to use to replace quotes
+	var $concat_operator='||';
+	var $sysDate = "TRUNC(SYSDATE)";
+	var $sysTimeStamp = 'SYSDATE';
+	var $metaDatabasesSQL = "SELECT USERNAME FROM ALL_USERS WHERE USERNAME NOT IN ('SYS','SYSTEM','DBSNMP','OUTLN') ORDER BY 1";
+	var $_stmt;
+	var $_commit = OCI_COMMIT_ON_SUCCESS;
+	var $_initdate = true; // init date to YYYY-MM-DD
+	var $metaTablesSQL = "select table_name,table_type from cat where table_type in ('TABLE','VIEW') and table_name not like 'BIN\$%'"; // bin$ tables are recycle bin tables
+	var $metaColumnsSQL = "select cname,coltype,width, SCALE, PRECISION, NULLS, DEFAULTVAL from col where tname='%s' order by colno"; //changed by smondino@users.sourceforge. net
+	var $_bindInputArray = true;
+	var $hasGenID = true;
+	var $_genIDSQL = "SELECT (%s.nextval) FROM DUAL";
+	var $_genSeqSQL = "CREATE SEQUENCE %s START WITH %s";
+	var $_dropSeqSQL = "DROP SEQUENCE %s";
+	var $hasAffectedRows = true;
+	var $random = "abs(mod(DBMS_RANDOM.RANDOM,10000001)/10000000)";
+	var $noNullStrings = false;
+	var $connectSID = false;
+	var $_bind = false;
+	var $_nestedSQL = true;
+	var $_hasOCIFetchStatement = false;
+	var $_getarray = false; // currently not working
+	var $leftOuter = '';  // oracle wierdness, $col = $value (+) for LEFT OUTER, $col (+)= $value for RIGHT OUTER
+	var $session_sharing_force_blob = false; // alter session on updateblob if set to true 
+	var $firstrows = true; // enable first rows optimization on SelectLimit()
+	var $selectOffsetAlg1 = 100; // when to use 1st algorithm of selectlimit.
+	var $NLS_DATE_FORMAT = 'YYYY-MM-DD';  // To include time, use 'RRRR-MM-DD HH24:MI:SS'
+ 	var $useDBDateFormatForTextInput=false;
+	var $datetime = false; // MetaType('DATE') returns 'D' (datetime==false) or 'T' (datetime == true)
+	var $_refLOBs = array();
+	
+	// var $ansiOuter = true; // if oracle9
+    
+	function ADODB_oci8() 
+	{
+		$this->_hasOCIFetchStatement = ADODB_PHPVER >= 0x4200;
+		if (defined('ADODB_EXTENSION')) $this->rsPrefix .= 'ext_';
+	}
+	
+	/*  Function &MetaColumns($table) added by smondino@users.sourceforge.net*/
+	function &MetaColumns($table) 
+	{
+	global $ADODB_FETCH_MODE;
+	
+		$false = false;
+		$save = $ADODB_FETCH_MODE;
+		$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
+		if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false);
+		
+		$rs = $this->Execute(sprintf($this->metaColumnsSQL,strtoupper($table)));
+		
+		if (isset($savem)) $this->SetFetchMode($savem);
+		$ADODB_FETCH_MODE = $save;
+		if (!$rs) {
+			return $false;
+		}
+		$retarr = array();
+		while (!$rs->EOF) { //print_r($rs->fields);
+			$fld = new ADOFieldObject();
+	   		$fld->name = $rs->fields[0];
+	   		$fld->type = $rs->fields[1];
+	   		$fld->max_length = $rs->fields[2];
+			$fld->scale = $rs->fields[3];
+			if ($rs->fields[1] == 'NUMBER') {
+				if ($rs->fields[3] == 0) $fld->type = 'INT';
+	     		$fld->max_length = $rs->fields[4];
+	    	}	
+		   	$fld->not_null = (strncmp($rs->fields[5], 'NOT',3) === 0);
+			$fld->binary = (strpos($fld->type,'BLOB') !== false);
+			$fld->default_value = $rs->fields[6];
+			
+			if ($ADODB_FETCH_MODE == ADODB_FETCH_NUM) $retarr[] = $fld;	
+			else $retarr[strtoupper($fld->name)] = $fld;
+			$rs->MoveNext();
+		}
+		$rs->Close();
+		if (empty($retarr))
+			return  $false;
+		else 
+			return $retarr;
+	}
+	
+	function Time()
+	{
+		$rs =& $this->Execute("select TO_CHAR($this->sysTimeStamp,'YYYY-MM-DD HH24:MI:SS') from dual");
+		if ($rs && !$rs->EOF) return $this->UnixTimeStamp(reset($rs->fields));
+		
+		return false;
+	}
+ 
+/*
+
+  Multiple modes of connection are supported:
+  
+  a. Local Database
+    $conn->Connect(false,'scott','tiger');
+  
+  b. From tnsnames.ora
+    $conn->Connect(false,'scott','tiger',$tnsname); 
+    $conn->Connect($tnsname,'scott','tiger'); 
+  
+  c. Server + service name
+    $conn->Connect($serveraddress,'scott,'tiger',$service_name);
+  
+  d. Server + SID
+  	$conn->connectSID = true;
+	$conn->Connect($serveraddress,'scott,'tiger',$SID);
+
+
+Example TNSName:
+---------------
+NATSOFT.DOMAIN =
+  (DESCRIPTION =
+	(ADDRESS_LIST =
+	  (ADDRESS = (PROTOCOL = TCP)(HOST = kermit)(PORT = 1523))
+	)
+	(CONNECT_DATA =
+	  (SERVICE_NAME = natsoft.domain)
+	)
+  )
+  
+  There are 3 connection modes, 0 = non-persistent, 1 = persistent, 2 = force new connection
+	
+*/
+	function _connect($argHostname, $argUsername, $argPassword, $argDatabasename,$mode=0)
+	{
+		if (!function_exists('OCIPLogon')) return null;
+		
+		
+        $this->_errorMsg = false;
+		$this->_errorCode = false;
+		
+		if($argHostname) { // added by Jorma Tuomainen <jorma.tuomainen@ppoy.fi>
+			if (empty($argDatabasename)) $argDatabasename = $argHostname;
+			else {
+				if(strpos($argHostname,":")) {
+					$argHostinfo=explode(":",$argHostname);
+				   	$argHostname=$argHostinfo[0];
+					$argHostport=$argHostinfo[1];
+			 	} else {
+					$argHostport = empty($this->port)?  "1521" : $this->port;
+	   			}
+				
+				if ($this->connectSID) {
+					$argDatabasename="(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=".$argHostname
+					.")(PORT=$argHostport))(CONNECT_DATA=(SID=$argDatabasename)))";
+				} else
+					$argDatabasename="(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=".$argHostname
+					.")(PORT=$argHostport))(CONNECT_DATA=(SERVICE_NAME=$argDatabasename)))";
+			}
+		}
+				
+ 		//if ($argHostname) print "<p>Connect: 1st argument should be left blank for $this->databaseType</p>";
+		if ($mode==1) {
+			$this->_connectionID = ($this->charSet) ? 
+				OCIPLogon($argUsername,$argPassword, $argDatabasename,$this->charSet)
+				:
+				OCIPLogon($argUsername,$argPassword, $argDatabasename)
+				;
+			if ($this->_connectionID && $this->autoRollback)  OCIrollback($this->_connectionID);
+		} else if ($mode==2) {
+			$this->_connectionID = ($this->charSet) ? 
+				OCINLogon($argUsername,$argPassword, $argDatabasename,$this->charSet)
+				:
+				OCINLogon($argUsername,$argPassword, $argDatabasename);
+				
+		} else {
+			$this->_connectionID = ($this->charSet) ? 
+				OCILogon($argUsername,$argPassword, $argDatabasename,$this->charSet)
+				:
+				OCILogon($argUsername,$argPassword, $argDatabasename);
+		}
+		if (!$this->_connectionID) return false;
+		if ($this->_initdate) {
+			$this->Execute("ALTER SESSION SET NLS_DATE_FORMAT='".$this->NLS_DATE_FORMAT."'");
+		}
+		
+		// looks like: 
+		// Oracle8i Enterprise Edition Release 8.1.7.0.0 - Production With the Partitioning option JServer Release 8.1.7.0.0 - Production
+		// $vers = OCIServerVersion($this->_connectionID);
+		// if (strpos($vers,'8i') !== false) $this->ansiOuter = true;
+		return true;
+   	}
+	
+	function ServerInfo()
+	{
+		$arr['compat'] = $this->GetOne('select value from sys.database_compatible_level');
+		$arr['description'] = @OCIServerVersion($this->_connectionID);
+		$arr['version'] = ADOConnection::_findvers($arr['description']);
+		return $arr;
+	}
+		// returns true or false
+	function _pconnect($argHostname, $argUsername, $argPassword, $argDatabasename)
+	{
+		return $this->_connect($argHostname, $argUsername, $argPassword, $argDatabasename,1);
+	}
+	
+	// returns true or false
+	function _nconnect($argHostname, $argUsername, $argPassword, $argDatabasename)
+	{
+		return $this->_connect($argHostname, $argUsername, $argPassword, $argDatabasename,2);
+	}
+	
+	function _affectedrows()
+	{
+		if (is_resource($this->_stmt)) return @OCIRowCount($this->_stmt);
+		return 0;
+	}
+	
+	function IfNull( $field, $ifNull ) 
+	{
+		return " NVL($field, $ifNull) "; // if Oracle
+	}
+	
+	// format and return date string in database date format
+	function DBDate($d)
+	{
+		if (empty($d) && $d !== 0) return 'null';
+		
+		if (is_string($d)) $d = ADORecordSet::UnixDate($d);
+		return "TO_DATE(".adodb_date($this->fmtDate,$d).",'".$this->NLS_DATE_FORMAT."')";
+	}
+
+	function BindDate($d)
+	{
+		$d = ADOConnection::DBDate($d);
+		if (strncmp($d,"'",1)) return $d;
+		
+		return substr($d,1,strlen($d)-2);
+	}
+	
+	function BindTimeStamp($d)
+	{
+		$d = ADOConnection::DBTimeStamp($d);
+		if (strncmp($d,"'",1)) return $d;
+		
+		return substr($d,1,strlen($d)-2);
+	}
+	
+	// format and return date string in database timestamp format
+	function DBTimeStamp($ts)
+	{
+		if (empty($ts) && $ts !== 0) return 'null';
+		if (is_string($ts)) $ts = ADORecordSet::UnixTimeStamp($ts);
+		return 'TO_DATE('.adodb_date($this->fmtTimeStamp,$ts).",'RRRR-MM-DD, HH:MI:SS AM')";
+	}
+	
+	function RowLock($tables,$where,$flds='1 as ignore') 
+	{
+		if ($this->autoCommit) $this->BeginTrans();
+		return $this->GetOne("select $flds from $tables where $where for update");
+	}
+	
+	function &MetaTables($ttype=false,$showSchema=false,$mask=false) 
+	{
+		if ($mask) {
+			$save = $this->metaTablesSQL;
+			$mask = $this->qstr(strtoupper($mask));
+			$this->metaTablesSQL .= " AND upper(table_name) like $mask";
+		}
+		$ret =& ADOConnection::MetaTables($ttype,$showSchema);
+		
+		if ($mask) {
+			$this->metaTablesSQL = $save;
+		}
+		return $ret;
+	}
+	
+	// Mark Newnham 
+	function &MetaIndexes ($table, $primary = FALSE, $owner=false)
+	{
+        // save old fetch mode
+        global $ADODB_FETCH_MODE;
+
+        $save = $ADODB_FETCH_MODE;
+        $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
+
+        if ($this->fetchMode !== FALSE) {
+               $savem = $this->SetFetchMode(FALSE);
+        }
+
+		// get index details
+		$table = strtoupper($table);
+
+		// get Primary index
+		$primary_key = '';
+
+		$false = false;
+		$rs = $this->Execute(sprintf("SELECT * FROM ALL_CONSTRAINTS WHERE UPPER(TABLE_NAME)='%s' AND CONSTRAINT_TYPE='P'",$table));
+		if ($row = $rs->FetchRow())
+		   $primary_key = $row[1]; //constraint_name
+
+		if ($primary==TRUE && $primary_key=='') {
+			 if (isset($savem)) 
+                $this->SetFetchMode($savem);
+			$ADODB_FETCH_MODE = $save;
+			return $false; //There is no primary key
+		}
+
+        $rs = $this->Execute(sprintf("SELECT ALL_INDEXES.INDEX_NAME, ALL_INDEXES.UNIQUENESS, ALL_IND_COLUMNS.COLUMN_POSITION, ALL_IND_COLUMNS.COLUMN_NAME FROM ALL_INDEXES,ALL_IND_COLUMNS WHERE UPPER(ALL_INDEXES.TABLE_NAME)='%s' AND ALL_IND_COLUMNS.INDEX_NAME=ALL_INDEXES.INDEX_NAME",$table));
+
+		
+        if (!is_object($rs)) {
+			if (isset($savem)) 
+				$this->SetFetchMode($savem);
+			$ADODB_FETCH_MODE = $save;
+            return $false;
+        }
+
+		$indexes = array ();
+        // parse index data into array
+
+        while ($row = $rs->FetchRow()) {
+			if ($primary && $row[0] != $primary_key) continue;
+            if (!isset($indexes[$row[0]])) {
+				$indexes[$row[0]] = array(
+				   'unique' => ($row[1] == 'UNIQUE'),
+				   'columns' => array()
+				);
+            }
+            $indexes[$row[0]]['columns'][$row[2] - 1] = $row[3];
+        }
+
+        // sort columns by order in the index
+        foreach ( array_keys ($indexes) as $index ) {
+            ksort ($indexes[$index]['columns']);
+        }
+
+		if (isset($savem)) { 
+            $this->SetFetchMode($savem);
+			$ADODB_FETCH_MODE = $save;
+		}
+        return $indexes;
+	}
+	
+	function BeginTrans()
+	{	
+		if ($this->transOff) return true;
+		$this->transCnt += 1;
+		$this->autoCommit = false;
+		$this->_commit = OCI_DEFAULT;
+		
+		if ($this->_transmode) $this->Execute("SET TRANSACTION ".$this->_transmode);
+		return true;
+	}
+	
+	function CommitTrans($ok=true) 
+	{ 
+		if ($this->transOff) return true;
+		if (!$ok) return $this->RollbackTrans();
+		
+		if ($this->transCnt) $this->transCnt -= 1;
+		$ret = OCIcommit($this->_connectionID);
+		$this->_commit = OCI_COMMIT_ON_SUCCESS;
+		$this->autoCommit = true;
+		return $ret;
+	}
+	
+	function RollbackTrans()
+	{
+		if ($this->transOff) return true;
+		if ($this->transCnt) $this->transCnt -= 1;
+		$ret = OCIrollback($this->_connectionID);
+		$this->_commit = OCI_COMMIT_ON_SUCCESS;
+		$this->autoCommit = true;
+		return $ret;
+	}
+	
+	
+	function SelectDB($dbName) 
+	{
+		return false;
+	}
+
+	function ErrorMsg() 
+	{
+		if ($this->_errorMsg !== false) return $this->_errorMsg;
+
+		if (is_resource($this->_stmt)) $arr = @OCIError($this->_stmt);
+		if (empty($arr)) {
+			if (is_resource($this->_connectionID)) $arr = @OCIError($this->_connectionID);
+			else $arr = @OCIError();
+			if ($arr === false) return '';
+		}
+		$this->_errorMsg = $arr['message'];
+		$this->_errorCode = $arr['code'];
+		return $this->_errorMsg;
+	}
+
+	function ErrorNo() 
+	{
+		if ($this->_errorCode !== false) return $this->_errorCode;
+		
+		if (is_resource($this->_stmt)) $arr = @OCIError($this->_stmt);
+		if (empty($arr)) {
+			$arr = @OCIError($this->_connectionID);
+			if ($arr == false) $arr = @OCIError();
+			if ($arr == false) return '';
+		}
+		
+		$this->_errorMsg = $arr['message'];
+		$this->_errorCode = $arr['code'];
+		
+		return $arr['code'];
+	}
+	
+	// Format date column in sql string given an input format that understands Y M D
+	function SQLDate($fmt, $col=false)
+	{	
+		if (!$col) $col = $this->sysTimeStamp;
+		$s = 'TO_CHAR('.$col.",'";
+		
+		$len = strlen($fmt);
+		for ($i=0; $i < $len; $i++) {
+			$ch = $fmt[$i];
+			switch($ch) {
+			case 'Y':
+			case 'y':
+				$s .= 'YYYY';
+				break;
+			case 'Q':
+			case 'q':
+				$s .= 'Q';
+				break;
+				
+			case 'M':
+				$s .= 'Mon';
+				break;
+				
+			case 'm':
+				$s .= 'MM';
+				break;
+			case 'D':
+			case 'd':
+				$s .= 'DD';
+				break;
+			
+			case 'H':
+				$s.= 'HH24';
+				break;
+				
+			case 'h':
+				$s .= 'HH';
+				break;
+				
+			case 'i':
+				$s .= 'MI';
+				break;
+			
+			case 's':
+				$s .= 'SS';
+				break;
+			
+			case 'a':
+			case 'A':
+				$s .= 'AM';
+				break;
+				
+			case 'w':
+				$s .= 'D';
+				break;
+				
+			case 'l':
+				$s .= 'DAY';
+				break;
+				
+			 case 'W':
+				$s .= 'WW';
+				break;
+				
+			default:
+			// handle escape characters...
+				if ($ch == '\\') {
+					$i++;
+					$ch = substr($fmt,$i,1);
+				}
+				if (strpos('-/.:;, ',$ch) !== false) $s .= $ch;
+				else $s .= '"'.$ch.'"';
+				
+			}
+		}
+		return $s. "')";
+	}
+	
+	
+	/*
+	This algorithm makes use of
+	
+	a. FIRST_ROWS hint
+	The FIRST_ROWS hint explicitly chooses the approach to optimize response time, 
+	that is, minimum resource usage to return the first row. Results will be returned 
+	as soon as they are identified. 
+
+	b. Uses rownum tricks to obtain only the required rows from a given offset.
+	 As this uses complicated sql statements, we only use this if the $offset >= 100. 
+	 This idea by Tomas V V Cox.
+	 
+	 This implementation does not appear to work with oracle 8.0.5 or earlier. Comment
+	 out this function then, and the slower SelectLimit() in the base class will be used.
+	*/
+	function &SelectLimit($sql,$nrows=-1,$offset=-1, $inputarr=false,$secs2cache=0)
+	{
+		// seems that oracle only supports 1 hint comment in 8i
+		if ($this->firstrows) {
+			if (strpos($sql,'/*+') !== false)
+				$sql = str_replace('/*+ ','/*+FIRST_ROWS ',$sql);
+			else
+				$sql = preg_replace('/^[ \t\n]*select/i','SELECT /*+FIRST_ROWS*/',$sql);
+		}
+		
+		if ($offset < $this->selectOffsetAlg1) {
+			if ($nrows > 0) {	
+				if ($offset > 0) $nrows += $offset;
+				//$inputarr['adodb_rownum'] = $nrows;
+				if ($this->databaseType == 'oci8po') {
+					$sql = "select * from (".$sql.") where rownum <= ?";
+				} else {
+					$sql = "select * from (".$sql.") where rownum <= :adodb_offset";
+				} 
+				$inputarr['adodb_offset'] = $nrows;
+				$nrows = -1;
+			}
+			// note that $nrows = 0 still has to work ==> no rows returned
+
+			$rs =& ADOConnection::SelectLimit($sql,$nrows,$offset,$inputarr,$secs2cache);
+			return $rs;
+			
+		} else {
+			 // Algorithm by Tomas V V Cox, from PEAR DB oci8.php
+			
+			 // Let Oracle return the name of the columns
+			$q_fields = "SELECT * FROM (".$sql.") WHERE NULL = NULL";
+			 
+			$false = false;
+			if (! $stmt_arr = $this->Prepare($q_fields)) {
+				return $false;
+			}
+			$stmt = $stmt_arr[1];
+			 
+			 if (is_array($inputarr)) {
+			 	foreach($inputarr as $k => $v) {
+					if (is_array($v)) {
+						if (sizeof($v) == 2) // suggested by g.giunta@libero.
+							OCIBindByName($stmt,":$k",$inputarr[$k][0],$v[1]);
+						else
+							OCIBindByName($stmt,":$k",$inputarr[$k][0],$v[1],$v[2]);
+					} else {
+						$len = -1;
+						if ($v === ' ') $len = 1;
+						if (isset($bindarr)) {	// is prepared sql, so no need to ocibindbyname again
+							$bindarr[$k] = $v;
+						} else { 				// dynamic sql, so rebind every time
+							OCIBindByName($stmt,":$k",$inputarr[$k],$len);
+						}
+					}
+				}
+			}
+			
+			 if (!OCIExecute($stmt, OCI_DEFAULT)) {
+				 OCIFreeStatement($stmt); 
+				 return $false;
+			 }
+			 
+			 $ncols = OCINumCols($stmt);
+			 for ( $i = 1; $i <= $ncols; $i++ ) {
+				 $cols[] = '"'.OCIColumnName($stmt, $i).'"';
+			 }
+			 $result = false;
+			
+			 OCIFreeStatement($stmt); 
+			 $fields = implode(',', $cols);
+			 $nrows += $offset;
+			 $offset += 1; // in Oracle rownum starts at 1
+			
+			if ($this->databaseType == 'oci8po') {
+					 $sql = "SELECT $fields FROM".
+					  "(SELECT rownum as adodb_rownum, $fields FROM".
+					  " ($sql) WHERE rownum <= ?".
+					  ") WHERE adodb_rownum >= ?";
+				} else {
+					 $sql = "SELECT $fields FROM".
+					  "(SELECT rownum as adodb_rownum, $fields FROM".
+					  " ($sql) WHERE rownum <= :adodb_nrows".
+					  ") WHERE adodb_rownum >= :adodb_offset";
+				} 
+				$inputarr['adodb_nrows'] = $nrows;
+				$inputarr['adodb_offset'] = $offset;
+				
+			if ($secs2cache>0) $rs =& $this->CacheExecute($secs2cache, $sql,$inputarr);
+			else $rs =& $this->Execute($sql,$inputarr);
+			return $rs;
+		}
+	
+	}
+	
+	/**
+	* Usage:
+	* Store BLOBs and CLOBs
+	*
+	* Example: to store $var in a blob
+	*
+	*	$conn->Execute('insert into TABLE (id,ablob) values(12,empty_blob())');
+	*	$conn->UpdateBlob('TABLE', 'ablob', $varHoldingBlob, 'ID=12', 'BLOB');
+	*	
+	*	$blobtype supports 'BLOB' and 'CLOB', but you need to change to 'empty_clob()'.
+	*
+	*  to get length of LOB:
+	*  	select DBMS_LOB.GETLENGTH(ablob) from TABLE
+	*
+	* If you are using CURSOR_SHARING = force, it appears this will case a segfault
+	* under oracle 8.1.7.0. Run:
+	*	 $db->Execute('ALTER SESSION SET CURSOR_SHARING=EXACT');
+	* before UpdateBlob() then...
+	*/
+
+	function UpdateBlob($table,$column,$val,$where,$blobtype='BLOB')
+	{
+		
+		//if (strlen($val) < 4000) return $this->Execute("UPDATE $table SET $column=:blob WHERE $where",array('blob'=>$val)) != false;
+		
+		switch(strtoupper($blobtype)) {
+		default: ADOConnection::outp("<b>UpdateBlob</b>: Unknown blobtype=$blobtype"); return false;
+		case 'BLOB': $type = OCI_B_BLOB; break;
+		case 'CLOB': $type = OCI_B_CLOB; break;
+		}
+		
+		if ($this->databaseType == 'oci8po') 
+			$sql = "UPDATE $table set $column=EMPTY_{$blobtype}() WHERE $where RETURNING $column INTO ?";
+		else 
+			$sql = "UPDATE $table set $column=EMPTY_{$blobtype}() WHERE $where RETURNING $column INTO :blob";
+		
+		$desc = OCINewDescriptor($this->_connectionID, OCI_D_LOB);
+		$arr['blob'] = array($desc,-1,$type);
+		if ($this->session_sharing_force_blob) $this->Execute('ALTER SESSION SET CURSOR_SHARING=EXACT');
+		$commit = $this->autoCommit;
+		if ($commit) $this->BeginTrans();
+		$rs = $this->_Execute($sql,$arr);
+		if ($rez = !empty($rs)) $desc->save($val);
+		$desc->free();
+		if ($commit) $this->CommitTrans();
+		if ($this->session_sharing_force_blob) $this->Execute('ALTER SESSION SET CURSOR_SHARING=FORCE');
+		
+		if ($rez) $rs->Close();
+		return $rez;
+	}
+	
+	/**
+	* Usage:  store file pointed to by $var in a blob
+	*/
+	function UpdateBlobFile($table,$column,$val,$where,$blobtype='BLOB')
+	{
+		switch(strtoupper($blobtype)) {
+		default: ADOConnection::outp( "<b>UpdateBlob</b>: Unknown blobtype=$blobtype"); return false;
+		case 'BLOB': $type = OCI_B_BLOB; break;
+		case 'CLOB': $type = OCI_B_CLOB; break;
+		}
+		
+		if ($this->databaseType == 'oci8po') 
+			$sql = "UPDATE $table set $column=EMPTY_{$blobtype}() WHERE $where RETURNING $column INTO ?";
+		else 
+			$sql = "UPDATE $table set $column=EMPTY_{$blobtype}() WHERE $where RETURNING $column INTO :blob";
+		
+		$desc = OCINewDescriptor($this->_connectionID, OCI_D_LOB);
+		$arr['blob'] = array($desc,-1,$type);
+		
+		$this->BeginTrans();
+		$rs = ADODB_oci8::Execute($sql,$arr);
+		if ($rez = !empty($rs)) $desc->savefile($val);
+		$desc->free();
+		$this->CommitTrans();
+		
+		if ($rez) $rs->Close();
+		return $rez;
+	}
+
+		/**
+	 * Execute SQL 
+	 *
+	 * @param sql		SQL statement to execute, or possibly an array holding prepared statement ($sql[0] will hold sql text)
+	 * @param [inputarr]	holds the input data to bind to. Null elements will be set to null.
+	 * @return 		RecordSet or false
+	 */
+	function &Execute($sql,$inputarr=false) 
+	{
+		if ($this->fnExecute) {
+			$fn = $this->fnExecute;
+			$ret =& $fn($this,$sql,$inputarr);
+			if (isset($ret)) return $ret;
+		}
+		if ($inputarr) {
+			#if (!is_array($inputarr)) $inputarr = array($inputarr);
+			
+			$element0 = reset($inputarr);
+			
+			# is_object check because oci8 descriptors can be passed in
+			if (is_array($element0) && !is_object(reset($element0))) {
+				if (is_string($sql))
+					$stmt = $this->Prepare($sql);
+				else
+					$stmt = $sql;
+					
+				foreach($inputarr as $arr) {
+					$ret =& $this->_Execute($stmt,$arr);
+					if (!$ret) return $ret;
+				}
+			} else {
+				$ret =& $this->_Execute($sql,$inputarr);
+			}
+			
+		} else {
+			$ret =& $this->_Execute($sql,false);
+		}
+
+		return $ret;
+	}
+	
+	/*
+		Example of usage:
+		
+		$stmt = $this->Prepare('insert into emp (empno, ename) values (:empno, :ename)');
+	*/
+	function Prepare($sql,$cursor=false)
+	{
+	static $BINDNUM = 0;
+	
+		$stmt = OCIParse($this->_connectionID,$sql);
+
+		if (!$stmt) {
+			$this->_errorMsg = false;
+			$this->_errorCode = false;
+			$arr = @OCIError($this->_connectionID);
+			if ($arr === false) return false;
+		
+			$this->_errorMsg = $arr['message'];
+			$this->_errorCode = $arr['code'];
+			return false;
+		}
+		
+		$BINDNUM += 1;
+		
+		$sttype = @OCIStatementType($stmt);
+		if ($sttype == 'BEGIN' || $sttype == 'DECLARE') {
+			return array($sql,$stmt,0,$BINDNUM, ($cursor) ? OCINewCursor($this->_connectionID) : false);
+		}
+		return array($sql,$stmt,0,$BINDNUM);
+	}
+	
+	/*
+		Call an oracle stored procedure and returns a cursor variable as a recordset. 
+		Concept by Robert Tuttle robert@ud.com
+		
+		Example:
+			Note: we return a cursor variable in :RS2
+			$rs = $db->ExecuteCursor("BEGIN adodb.open_tab(:RS2); END;",'RS2');
+			
+			$rs = $db->ExecuteCursor(
+				"BEGIN :RS2 = adodb.getdata(:VAR1); END;", 
+				'RS2',
+				array('VAR1' => 'Mr Bean'));
+			
+	*/
+	function &ExecuteCursor($sql,$cursorName='rs',$params=false)
+	{
+		if (is_array($sql)) $stmt = $sql;
+		else $stmt = ADODB_oci8::Prepare($sql,true); # true to allocate OCINewCursor
+	
+		if (is_array($stmt) && sizeof($stmt) >= 5) {
+			$hasref = true;
+			$ignoreCur = false;
+			$this->Parameter($stmt, $ignoreCur, $cursorName, false, -1, OCI_B_CURSOR);
+			if ($params) {
+				foreach($params as $k => $v) {
+					$this->Parameter($stmt,$params[$k], $k);
+				}
+			}
+		} else
+			$hasref = false;
+			
+		$rs =& $this->Execute($stmt);
+		if ($rs) {
+			if ($rs->databaseType == 'array') OCIFreeCursor($stmt[4]);
+			else if ($hasref) $rs->_refcursor = $stmt[4];
+		}
+		return $rs;
+	}
+	
+	/*
+		Bind a variable -- very, very fast for executing repeated statements in oracle. 
+		Better than using
+			for ($i = 0; $i < $max; $i++) {	
+				$p1 = ?; $p2 = ?; $p3 = ?;
+				$this->Execute("insert into table (col0, col1, col2) values (:0, :1, :2)", 
+					array($p1,$p2,$p3));
+			}
+		
+		Usage:
+			$stmt = $DB->Prepare("insert into table (col0, col1, col2) values (:0, :1, :2)");
+			$DB->Bind($stmt, $p1);
+			$DB->Bind($stmt, $p2);
+			$DB->Bind($stmt, $p3);
+			for ($i = 0; $i < $max; $i++) {	
+				$p1 = ?; $p2 = ?; $p3 = ?;
+				$DB->Execute($stmt);
+			}
+			
+		Some timings:		
+			** Test table has 3 cols, and 1 index. Test to insert 1000 records
+			Time 0.6081s (1644.60 inserts/sec) with direct OCIParse/OCIExecute
+			Time 0.6341s (1577.16 inserts/sec) with ADOdb Prepare/Bind/Execute
+			Time 1.5533s ( 643.77 inserts/sec) with pure SQL using Execute
+			
+		Now if PHP only had batch/bulk updating like Java or PL/SQL...
+	
+		Note that the order of parameters differs from OCIBindByName,
+		because we default the names to :0, :1, :2
+	*/
+	function Bind(&$stmt,&$var,$size=4000,$type=false,$name=false,$isOutput=false)
+	{
+		
+		if (!is_array($stmt)) return false;
+        
+        if (($type == OCI_B_CURSOR) && sizeof($stmt) >= 5) { 
+            return OCIBindByName($stmt[1],":".$name,$stmt[4],$size,$type);
+        }
+        
+		if ($name == false) {
+			if ($type !== false) $rez = OCIBindByName($stmt[1],":".$stmt[2],$var,$size,$type);
+			else $rez = OCIBindByName($stmt[1],":".$stmt[2],$var,$size); // +1 byte for null terminator
+			$stmt[2] += 1;
+		} else if (oci_lob_desc($type)) {
+			if ($this->debug) {
+				ADOConnection::outp("<b>Bind</b>: name = $name");
+			}
+            //we have to create a new Descriptor here
+			$numlob = count($this->_refLOBs);
+        	$this->_refLOBs[$numlob]['LOB'] = OCINewDescriptor($this->_connectionID, oci_lob_desc($type));
+			$this->_refLOBs[$numlob]['TYPE'] = $isOutput;
+			
+			$tmp = &$this->_refLOBs[$numlob]['LOB'];
+	        $rez = OCIBindByName($stmt[1], ":".$name, $tmp, -1, $type);
+			if ($this->debug) {
+				ADOConnection::outp("<b>Bind</b>: descriptor has been allocated, var (".$name.") binded");
+			}
+			
+			// if type is input then write data to lob now
+			if ($isOutput == false) {
+				$var = $this->BlobEncode($var);
+				$tmp->WriteTemporary($var);
+				$this->_refLOBs[$numlob]['VAR'] = &$var;
+				if ($this->debug) {
+					ADOConnection::outp("<b>Bind</b>: LOB has been written to temp");
+				}
+			} else {
+				$this->_refLOBs[$numlob]['VAR'] = &$var;
+			}
+			$rez = $tmp;
+		} else {
+			if ($this->debug) 
+				ADOConnection::outp("<b>Bind</b>: name = $name");
+			
+			if ($type !== false) $rez = OCIBindByName($stmt[1],":".$name,$var,$size,$type);
+			else $rez = OCIBindByName($stmt[1],":".$name,$var,$size); // +1 byte for null terminator
+		}
+		
+		return $rez;
+	}
+	
+	function Param($name,$type=false)
+	{
+		return ':'.$name;
+	}
+	
+	/* 
+	Usage:
+		$stmt = $db->Prepare('select * from table where id =:myid and group=:group');
+		$db->Parameter($stmt,$id,'myid');
+		$db->Parameter($stmt,$group,'group');
+		$db->Execute($stmt);
+		
+		@param $stmt Statement returned by Prepare() or PrepareSP().
+		@param $var PHP variable to bind to
+		@param $name Name of stored procedure variable name to bind to.
+		@param [$isOutput] Indicates direction of parameter 0/false=IN  1=OUT  2= IN/OUT. This is ignored in oci8.
+		@param [$maxLen] Holds an maximum length of the variable.
+		@param [$type] The data type of $var. Legal values depend on driver.
+		
+		See OCIBindByName documentation at php.net.
+	*/
+	function Parameter(&$stmt,&$var,$name,$isOutput=false,$maxLen=4000,$type=false)
+	{
+			if  ($this->debug) {
+				$prefix = ($isOutput) ? 'Out' : 'In';
+				$ztype = (empty($type)) ? 'false' : $type;
+				ADOConnection::outp( "{$prefix}Parameter(\$stmt, \$php_var='$var', \$name='$name', \$maxLen=$maxLen, \$type=$ztype);");
+			}
+			return $this->Bind($stmt,$var,$maxLen,$type,$name,$isOutput);
+	}
+	
+	/*
+	returns query ID if successful, otherwise false
+	this version supports:
+	
+	   1. $db->execute('select * from table');
+	   
+	   2. $db->prepare('insert into table (a,b,c) values (:0,:1,:2)');
+		  $db->execute($prepared_statement, array(1,2,3));
+		  
+	   3. $db->execute('insert into table (a,b,c) values (:a,:b,:c)',array('a'=>1,'b'=>2,'c'=>3));
+	   
+	   4. $db->prepare('insert into table (a,b,c) values (:0,:1,:2)');
+		  $db->bind($stmt,1); $db->bind($stmt,2); $db->bind($stmt,3); 
+		  $db->execute($stmt);
+	*/ 
+	function _query($sql,$inputarr)
+	{
+		if (is_array($sql)) { // is prepared sql
+			$stmt = $sql[1];
+			
+			// we try to bind to permanent array, so that OCIBindByName is persistent
+			// and carried out once only - note that max array element size is 4000 chars
+			if (is_array($inputarr)) {
+				$bindpos = $sql[3];
+				if (isset($this->_bind[$bindpos])) {
+				// all tied up already
+					$bindarr = &$this->_bind[$bindpos];
+				} else {
+				// one statement to bind them all
+					$bindarr = array();
+					foreach($inputarr as $k => $v) {
+						$bindarr[$k] = $v;
+						OCIBindByName($stmt,":$k",$bindarr[$k],is_string($v) && strlen($v)>4000 ? -1 : 4000);
+					}
+					$this->_bind[$bindpos] = &$bindarr;
+				}
+			}
+		} else {
+			$stmt=OCIParse($this->_connectionID,$sql);
+		}
+			
+		$this->_stmt = $stmt;
+		if (!$stmt) return false;
+	
+		if (defined('ADODB_PREFETCH_ROWS')) @OCISetPrefetch($stmt,ADODB_PREFETCH_ROWS);
+			
+		if (is_array($inputarr)) {
+			foreach($inputarr as $k => $v) {
+				if (is_array($v)) {
+					if (sizeof($v) == 2) // suggested by g.giunta@libero.
+						OCIBindByName($stmt,":$k",$inputarr[$k][0],$v[1]);
+					else
+						OCIBindByName($stmt,":$k",$inputarr[$k][0],$v[1],$v[2]);
+					
+					if ($this->debug==99) echo "name=:$k",' var='.$inputarr[$k][0],' len='.$v[1],' type='.$v[2],'<br>';
+				} else {
+					$len = -1;
+					if ($v === ' ') $len = 1;
+					if (isset($bindarr)) {	// is prepared sql, so no need to ocibindbyname again
+						$bindarr[$k] = $v;
+					} else { 				// dynamic sql, so rebind every time
+						OCIBindByName($stmt,":$k",$inputarr[$k],$len);
+					}
+				}
+			}
+		}
+		
+        $this->_errorMsg = false;
+		$this->_errorCode = false;
+		if (OCIExecute($stmt,$this->_commit)) {
+//OCIInternalDebug(1);			
+			if (count($this -> _refLOBs) > 0) {
+		
+				foreach ($this -> _refLOBs as $key => $value) {
+					if ($this -> _refLOBs[$key]['TYPE'] == true) {
+						$tmp = $this -> _refLOBs[$key]['LOB'] -> load();
+						if ($this -> debug) {
+							ADOConnection::outp("<b>OUT LOB</b>: LOB has been loaded. <br>");
+						}
+						//$_GLOBALS[$this -> _refLOBs[$key]['VAR']] = $tmp;
+						$this -> _refLOBs[$key]['VAR'] = $tmp;
+					} else {
+                        $this->_refLOBs[$key]['LOB']->save($this->_refLOBs[$key]['VAR']);
+						$this -> _refLOBs[$key]['LOB']->free();
+						unset($this -> _refLOBs[$key]);
+                        if ($this->debug) {
+							ADOConnection::outp("<b>IN LOB</b>: LOB has been saved. <br>");
+						}
+                    }					
+				}
+			}
+		
+            switch (@OCIStatementType($stmt)) {
+                case "SELECT":
+					return $stmt;
+				
+				case 'DECLARE':
+                case "BEGIN":
+                    if (is_array($sql) && !empty($sql[4])) {
+						$cursor = $sql[4];
+						if (is_resource($cursor)) {
+							$ok = OCIExecute($cursor);	
+	                        return $cursor;
+						}
+						return $stmt;
+                    } else {
+						if (is_resource($stmt)) {
+							OCIFreeStatement($stmt);
+							return true;
+						}
+                        return $stmt;
+                    }
+                    break;
+                default :
+					// ociclose -- no because it could be used in a LOB?
+                    return true;
+            }
+		}
+		return false;
+	}
+	
+	// returns true or false
+	function _close()
+	{
+		if (!$this->_connectionID) return;
+		
+		if (!$this->autoCommit) OCIRollback($this->_connectionID);
+		if (count($this->_refLOBs) > 0) {
+			foreach ($this ->_refLOBs as $key => $value) {
+				$this->_refLOBs[$key]['LOB']->free();
+				unset($this->_refLOBs[$key]);
+			}
+		}
+		OCILogoff($this->_connectionID);
+		
+		$this->_stmt = false;
+		$this->_connectionID = false;
+	}
+	
+	function MetaPrimaryKeys($table, $owner=false,$internalKey=false)
+	{
+		if ($internalKey) return array('ROWID');
+		
+	// tested with oracle 8.1.7
+		$table = strtoupper($table);
+		if ($owner) {
+			$owner_clause = "AND ((a.OWNER = b.OWNER) AND (a.OWNER = UPPER('$owner')))";
+			$ptab = 'ALL_';
+		} else {
+			$owner_clause = '';
+			$ptab = 'USER_';
+		}
+		$sql = "
+SELECT /*+ RULE */ distinct b.column_name
+   FROM {$ptab}CONSTRAINTS a
+	  , {$ptab}CONS_COLUMNS b
+  WHERE ( UPPER(b.table_name) = ('$table'))
+	AND (UPPER(a.table_name) = ('$table') and a.constraint_type = 'P')
+	$owner_clause
+	AND (a.constraint_name = b.constraint_name)";
+
+ 		$rs = $this->Execute($sql);
+		if ($rs && !$rs->EOF) {
+			$arr =& $rs->GetArray();
+			$a = array();
+			foreach($arr as $v) {
+				$a[] = reset($v);
+			}
+			return $a;
+		}
+		else return false;
+	}
+	
+	// http://gis.mit.edu/classes/11.521/sqlnotes/referential_integrity.html
+	function MetaForeignKeys($table, $owner=false)
+	{
+	global $ADODB_FETCH_MODE;
+	
+		$save = $ADODB_FETCH_MODE;
+		$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
+		$table = $this->qstr(strtoupper($table));
+		if (!$owner) {
+			$owner = $this->user;
+			$tabp = 'user_';
+		} else
+			$tabp = 'all_';
+			
+		$owner = ' and owner='.$this->qstr(strtoupper($owner));
+		
+		$sql = 
+"select constraint_name,r_owner,r_constraint_name 
+	from {$tabp}constraints
+	where constraint_type = 'R' and table_name = $table $owner";
+		
+		$constraints =& $this->GetArray($sql);
+		$arr = false;
+		foreach($constraints as $constr) {
+			$cons = $this->qstr($constr[0]);
+			$rowner = $this->qstr($constr[1]);
+			$rcons = $this->qstr($constr[2]);
+			$cols = $this->GetArray("select column_name from {$tabp}cons_columns where constraint_name=$cons $owner order by position");
+			$tabcol = $this->GetArray("select table_name,column_name from {$tabp}cons_columns where owner=$rowner and constraint_name=$rcons order by position");
+			
+			if ($cols && $tabcol) 
+				for ($i=0, $max=sizeof($cols); $i < $max; $i++) {
+					$arr[$tabcol[$i][0]] = $cols[$i][0].'='.$tabcol[$i][1];
+				}
+		}
+		$ADODB_FETCH_MODE = $save;
+		
+		return $arr;
+	}
+
+	
+	function CharMax()
+	{
+		return 4000;
+	}
+	
+	function TextMax()
+	{
+		return 4000;
+	}
+	
+	/**
+	 * Quotes a string.
+	 * An example is  $db->qstr("Don't bother",magic_quotes_runtime());
+	 * 
+	 * @param s			the string to quote
+	 * @param [magic_quotes]	if $s is GET/POST var, set to get_magic_quotes_gpc().
+	 *				This undoes the stupidity of magic quotes for GPC.
+	 *
+	 * @return  quoted string to be sent back to database
+	 */
+	function qstr($s,$magic_quotes=false)
+	{	
+		//$nofixquotes=false;
+	
+		if ($this->noNullStrings && strlen($s)==0)$s = ' ';
+		if (!$magic_quotes) {	
+			if ($this->replaceQuote[0] == '\\'){
+				$s = str_replace('\\','\\\\',$s);
+			}
+			return  "'".str_replace("'",$this->replaceQuote,$s)."'";
+		}
+		
+		// undo magic quotes for "
+		$s = str_replace('\\"','"',$s);
+		
+		$s = str_replace('\\\\','\\',$s);
+		return "'".str_replace("\\'",$this->replaceQuote,$s)."'";
+		
+	}
+	
+}
+
+/*--------------------------------------------------------------------------------------
+		 Class Name: Recordset
+--------------------------------------------------------------------------------------*/
+
+class ADORecordset_oci8 extends ADORecordSet {
+
+	var $databaseType = 'oci8';
+	var $bind=false;
+	var $_fieldobjs;
+	
+	//var $_arr = false;
+		
+	function ADORecordset_oci8($queryID,$mode=false)
+	{
+		if ($mode === false) { 
+			global $ADODB_FETCH_MODE;
+			$mode = $ADODB_FETCH_MODE;
+		}
+		switch ($mode)
+		{
+		case ADODB_FETCH_ASSOC:$this->fetchMode = OCI_ASSOC+OCI_RETURN_NULLS+OCI_RETURN_LOBS; break;
+		case ADODB_FETCH_DEFAULT:
+		case ADODB_FETCH_BOTH:$this->fetchMode = OCI_NUM+OCI_ASSOC+OCI_RETURN_NULLS+OCI_RETURN_LOBS; break;
+		case ADODB_FETCH_NUM: 
+		default:
+		$this->fetchMode = OCI_NUM+OCI_RETURN_NULLS+OCI_RETURN_LOBS; break;
+		}
+		
+		$this->adodbFetchMode = $mode;
+		$this->_queryID = $queryID;
+	}
+
+
+	function Init()
+	{
+		if ($this->_inited) return;
+		
+		$this->_inited = true;
+		if ($this->_queryID) {
+			
+			$this->_currentRow = 0;
+			@$this->_initrs();
+			$this->EOF = !$this->_fetch();
+			
+			/*
+			// based on idea by Gaetano Giunta to detect unusual oracle errors
+			// see http://phplens.com/lens/lensforum/msgs.php?id=6771
+			$err = OCIError($this->_queryID);
+			if ($err && $this->connection->debug) ADOConnection::outp($err);
+			*/
+			
+			if (!is_array($this->fields)) {
+				$this->_numOfRows = 0;
+				$this->fields = array();
+			}
+		} else {
+			$this->fields = array();
+			$this->_numOfRows = 0;
+			$this->_numOfFields = 0;
+			$this->EOF = true;
+		}
+	}
+	
+	function _initrs()
+	{
+		$this->_numOfRows = -1;
+		$this->_numOfFields = OCInumcols($this->_queryID);
+		if ($this->_numOfFields>0) {
+			$this->_fieldobjs = array();
+			$max = $this->_numOfFields;
+			for ($i=0;$i<$max; $i++) $this->_fieldobjs[] = $this->_FetchField($i);
+		}
+	}
+
+	  /*		Returns: an object containing field information.
+			  Get column information in the Recordset object. fetchField() can be used in order to obtain information about
+			  fields in a certain query result. If the field offset isn't specified, the next field that wasn't yet retrieved by
+			  fetchField() is retrieved.		*/
+
+	function &_FetchField($fieldOffset = -1)
+	{
+		$fld = new ADOFieldObject;
+		$fieldOffset += 1;
+		$fld->name =OCIcolumnname($this->_queryID, $fieldOffset);
+		$fld->type = OCIcolumntype($this->_queryID, $fieldOffset);
+		$fld->max_length = OCIcolumnsize($this->_queryID, $fieldOffset);
+	 	if ($fld->type == 'NUMBER') {
+	 		$p = OCIColumnPrecision($this->_queryID, $fieldOffset);
+			$sc = OCIColumnScale($this->_queryID, $fieldOffset);
+			if ($p != 0 && $sc == 0) $fld->type = 'INT';
+			//echo " $this->name ($p.$sc) ";
+	 	}
+		return $fld;
+	}
+	
+	/* For some reason, OCIcolumnname fails when called after _initrs() so we cache it */
+	function &FetchField($fieldOffset = -1)
+	{
+		return $this->_fieldobjs[$fieldOffset];
+	}
+	
+	
+	/*
+	// 10% speedup to move MoveNext to child class
+	function _MoveNext() 
+	{
+	//global $ADODB_EXTENSION;if ($ADODB_EXTENSION) return @adodb_movenext($this);
+		
+		if ($this->EOF) return false;
+		
+		$this->_currentRow++;
+		if(@OCIfetchinto($this->_queryID,$this->fields,$this->fetchMode))
+			return true;
+		$this->EOF = true;
+		
+		return false;
+	}	*/
+	
+	
+	function MoveNext()
+	{
+		if (@OCIfetchinto($this->_queryID,$this->fields,$this->fetchMode)) {
+			$this->_currentRow += 1;
+			return true;
+		}
+		if (!$this->EOF) {
+			$this->_currentRow += 1;
+			$this->EOF = true;
+		}
+		return false;
+	}
+	
+	/*
+	# does not work as first record is retrieved in _initrs(), so is not included in GetArray()
+	function &GetArray($nRows = -1) 
+	{
+	global $ADODB_OCI8_GETARRAY;
+	
+		if (true ||  !empty($ADODB_OCI8_GETARRAY)) {
+			# does not support $ADODB_ANSI_PADDING_OFF
+	
+			//OCI_RETURN_NULLS and OCI_RETURN_LOBS is set by OCIfetchstatement
+			switch($this->adodbFetchMode) {
+			case ADODB_FETCH_NUM:
+			
+				$ncols = @OCIfetchstatement($this->_queryID, $results, 0, $nRows, OCI_FETCHSTATEMENT_BY_ROW+OCI_NUM);
+				$results = array_merge(array($this->fields),$results);
+				return $results;
+				
+			case ADODB_FETCH_ASSOC: 
+				if (ADODB_ASSOC_CASE != 2 || $this->databaseType != 'oci8') break;
+				
+				$ncols = @OCIfetchstatement($this->_queryID, $assoc, 0, $nRows, OCI_FETCHSTATEMENT_BY_ROW);
+				$results =& array_merge(array($this->fields),$assoc);
+				return $results;
+			
+			default:
+				break;
+			}
+		}
+			
+		$results =& ADORecordSet::GetArray($nRows);
+		return $results;
+		
+	} */
+	
+	/* Optimize SelectLimit() by using OCIFetch() instead of OCIFetchInto() */
+	function &GetArrayLimit($nrows,$offset=-1) 
+	{
+		if ($offset <= 0) {
+			$arr =& $this->GetArray($nrows);
+			return $arr;
+		}
+		$arr = array();
+		for ($i=1; $i < $offset; $i++) 
+			if (!@OCIFetch($this->_queryID)) return $arr;
+			
+		if (!@OCIfetchinto($this->_queryID,$this->fields,$this->fetchMode)) return $arr;;
+		$results = array();
+		$cnt = 0;
+		while (!$this->EOF && $nrows != $cnt) {
+			$results[$cnt++] = $this->fields;
+			$this->MoveNext();
+		}
+		
+		return $results;
+	}
+
+	
+	/* Use associative array to get fields array */
+	function Fields($colname)
+	{
+		if (!$this->bind) {
+			$this->bind = array();
+			for ($i=0; $i < $this->_numOfFields; $i++) {
+				$o = $this->FetchField($i);
+				$this->bind[strtoupper($o->name)] = $i;
+			}
+		}
+		
+		 return $this->fields[$this->bind[strtoupper($colname)]];
+	}
+	
+
+
+	function _seek($row)
+	{
+		return false;
+	}
+
+	function _fetch() 
+	{
+		return @OCIfetchinto($this->_queryID,$this->fields,$this->fetchMode);
+	}
+
+	/*		close() only needs to be called if you are worried about using too much memory while your script
+			is running. All associated result memory for the specified result identifier will automatically be freed.		*/
+
+	function _close() 
+	{
+		if ($this->connection->_stmt === $this->_queryID) $this->connection->_stmt = false;
+		if (!empty($this->_refcursor)) {
+			OCIFreeCursor($this->_refcursor);
+			$this->_refcursor = false;
+		}
+		@OCIFreeStatement($this->_queryID);
+ 		$this->_queryID = false;
+		
+	}
+
+	function MetaType($t,$len=-1)
+	{
+		if (is_object($t)) {
+			$fieldobj = $t;
+			$t = $fieldobj->type;
+			$len = $fieldobj->max_length;
+		}
+		switch (strtoupper($t)) {
+	 	case 'VARCHAR':
+	 	case 'VARCHAR2':
+		case 'CHAR':
+		case 'VARBINARY':
+		case 'BINARY':
+		case 'NCHAR':
+		case 'NVARCHAR':
+		case 'NVARCHAR2':
+				 if (isset($this) && $len <= $this->blobSize) return 'C';
+		
+		case 'NCLOB':
+		case 'LONG':
+		case 'LONG VARCHAR':
+		case 'CLOB':
+		return 'X';
+		
+		case 'LONG RAW':
+		case 'LONG VARBINARY':
+		case 'BLOB':
+			return 'B';
+		
+		case 'DATE': 
+			return  ($this->connection->datetime) ? 'T' : 'D';
+		
+		
+		case 'TIMESTAMP': return 'T';
+		
+		case 'INT': 
+		case 'SMALLINT':
+		case 'INTEGER': 
+			return 'I';
+			
+		default: return 'N';
+		}
+	}
+}
+
+class ADORecordSet_ext_oci8 extends ADORecordSet_oci8 {	
+	function ADORecordSet_ext_oci8($queryID,$mode=false) 
+	{
+		if ($mode === false) { 
+			global $ADODB_FETCH_MODE;
+			$mode = $ADODB_FETCH_MODE;
+		}
+		switch ($mode)
+		{
+		case ADODB_FETCH_ASSOC:$this->fetchMode = OCI_ASSOC+OCI_RETURN_NULLS+OCI_RETURN_LOBS; break;
+		case ADODB_FETCH_DEFAULT:
+		case ADODB_FETCH_BOTH:$this->fetchMode = OCI_NUM+OCI_ASSOC+OCI_RETURN_NULLS+OCI_RETURN_LOBS; break;
+		case ADODB_FETCH_NUM: 
+		default: $this->fetchMode = OCI_NUM+OCI_RETURN_NULLS+OCI_RETURN_LOBS; break;
+		}
+		$this->adodbFetchMode = $mode;
+		$this->_queryID = $queryID;
+	}
+	
+	function MoveNext()
+	{
+		return adodb_movenext($this);
+	}
+}
+?>
Index: /Dev/trunk/rdfapi/util/adodb/drivers/adodb-oci805.inc.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/drivers/adodb-oci805.inc.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/drivers/adodb-oci805.inc.php	(revision 12)
@@ -0,0 +1,59 @@
+<?php
+/** 
+ * @version V4.94 23 Jan 2007 (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
+ * Released under both BSD license and Lesser GPL library license. 
+ * Whenever there is any discrepancy between the two licenses, 
+ * the BSD license will take precedence. 
+ *
+ * Set tabs to 4 for best viewing.
+ * 
+ * Latest version is available at http://php.weblogs.com
+ *
+ * Oracle 8.0.5 driver
+*/
+
+// security - hide paths
+if (!defined('ADODB_DIR')) die();
+
+include_once(ADODB_DIR.'/drivers/adodb-oci8.inc.php');
+
+class ADODB_oci805 extends ADODB_oci8 {
+	var $databaseType = "oci805";	
+	var $connectSID = true;
+	
+	function ADODB_oci805() 
+	{
+		$this->ADODB_oci8();
+	}
+	
+	function &SelectLimit($sql,$nrows=-1,$offset=-1, $inputarr=false,$secs2cache=0)
+	{
+		// seems that oracle only supports 1 hint comment in 8i
+		if (strpos($sql,'/*+') !== false)
+			$sql = str_replace('/*+ ','/*+FIRST_ROWS ',$sql);
+		else
+			$sql = preg_replace('/^[ \t\n]*select/i','SELECT /*+FIRST_ROWS*/',$sql);
+		
+		/* 
+			The following is only available from 8.1.5 because order by in inline views not 
+			available before then...
+			http://www.jlcomp.demon.co.uk/faq/top_sql.html
+		if ($nrows > 0) {	
+			if ($offset > 0) $nrows += $offset;
+			$sql = "select * from ($sql) where rownum <= $nrows";
+			$nrows = -1;
+		}
+		*/
+
+		return ADOConnection::SelectLimit($sql,$nrows,$offset,$inputarr,$secs2cache);
+	}
+}
+
+class ADORecordset_oci805 extends ADORecordset_oci8 {	
+	var $databaseType = "oci805";
+	function ADORecordset_oci805($id,$mode=false)
+	{
+		$this->ADORecordset_oci8($id,$mode);
+	}
+}
+?>
Index: /Dev/trunk/rdfapi/util/adodb/drivers/adodb-oci8po.inc.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/drivers/adodb-oci8po.inc.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/drivers/adodb-oci8po.inc.php	(revision 12)
@@ -0,0 +1,217 @@
+<?php
+/*
+V4.94 23 Jan 2007  (c) 2000-2007 John Lim. All rights reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence.
+
+  Latest version is available at http://adodb.sourceforge.net
+  
+  Portable version of oci8 driver, to make it more similar to other database drivers.
+  The main differences are
+
+   1. that the OCI_ASSOC names are in lowercase instead of uppercase.
+   2. bind variables are mapped using ? instead of :<bindvar>
+
+   Should some emulation of RecordCount() be implemented?
+  
+*/
+
+// security - hide paths
+if (!defined('ADODB_DIR')) die();
+
+include_once(ADODB_DIR.'/drivers/adodb-oci8.inc.php');
+
+class ADODB_oci8po extends ADODB_oci8 {
+	var $databaseType = 'oci8po';
+	var $dataProvider = 'oci8';
+	var $metaColumnsSQL = "select lower(cname),coltype,width, SCALE, PRECISION, NULLS, DEFAULTVAL from col where tname='%s' order by colno"; //changed by smondino@users.sourceforge. net
+	var $metaTablesSQL = "select lower(table_name),table_type from cat where table_type in ('TABLE','VIEW')";
+	
+	function ADODB_oci8po()
+	{
+		$this->_hasOCIFetchStatement = ADODB_PHPVER >= 0x4200;
+		# oci8po does not support adodb extension: adodb_movenext()
+	}
+	
+	function Param($name)
+	{
+		return '?';
+	}
+	
+	function Prepare($sql,$cursor=false)
+	{
+		$sqlarr = explode('?',$sql);
+		$sql = $sqlarr[0];
+		for ($i = 1, $max = sizeof($sqlarr); $i < $max; $i++) {
+			$sql .=  ':'.($i-1) . $sqlarr[$i];
+		} 
+		return ADODB_oci8::Prepare($sql,$cursor);
+	}
+	
+	// emulate handling of parameters ? ?, replacing with :bind0 :bind1
+	function _query($sql,$inputarr)
+	{
+		if (is_array($inputarr)) {
+			$i = 0;
+			if (is_array($sql)) {
+				foreach($inputarr as $v) {
+					$arr['bind'.$i++] = $v;
+				} 
+			} else {
+				$sqlarr = explode('?',$sql);
+				$sql = $sqlarr[0];
+				foreach($inputarr as $k => $v) {
+					$sql .=  ":$k" . $sqlarr[++$i];
+				}
+			}
+		}
+		return ADODB_oci8::_query($sql,$inputarr);
+	}
+}
+
+/*--------------------------------------------------------------------------------------
+		 Class Name: Recordset
+--------------------------------------------------------------------------------------*/
+
+class ADORecordset_oci8po extends ADORecordset_oci8 {
+
+	var $databaseType = 'oci8po';
+	
+	function ADORecordset_oci8po($queryID,$mode=false)
+	{
+		$this->ADORecordset_oci8($queryID,$mode);
+	}
+
+	function Fields($colname)
+	{
+		if ($this->fetchMode & OCI_ASSOC) return $this->fields[$colname];
+		
+		if (!$this->bind) {
+			$this->bind = array();
+			for ($i=0; $i < $this->_numOfFields; $i++) {
+				$o = $this->FetchField($i);
+				$this->bind[strtoupper($o->name)] = $i;
+			}
+		}
+		 return $this->fields[$this->bind[strtoupper($colname)]];
+	}
+	
+	// lowercase field names...
+	function &_FetchField($fieldOffset = -1)
+	{
+		 $fld = new ADOFieldObject;
+ 		 $fieldOffset += 1;
+		 $fld->name = strtolower(OCIcolumnname($this->_queryID, $fieldOffset));
+		 $fld->type = OCIcolumntype($this->_queryID, $fieldOffset);
+		 $fld->max_length = OCIcolumnsize($this->_queryID, $fieldOffset);
+		 if ($fld->type == 'NUMBER') {
+		 	//$p = OCIColumnPrecision($this->_queryID, $fieldOffset);
+			$sc = OCIColumnScale($this->_queryID, $fieldOffset);
+			if ($sc == 0) $fld->type = 'INT';
+		 }
+		 return $fld;
+	}
+	/*
+	function MoveNext()
+	{
+		if (@OCIfetchinto($this->_queryID,$this->fields,$this->fetchMode)) {
+			$this->_currentRow += 1;
+			return true;
+		}
+		if (!$this->EOF) {
+			$this->_currentRow += 1;
+			$this->EOF = true;
+		}
+		return false;
+	}*/
+
+	// 10% speedup to move MoveNext to child class
+	function MoveNext() 
+	{
+		if(@OCIfetchinto($this->_queryID,$this->fields,$this->fetchMode)) {
+		global $ADODB_ANSI_PADDING_OFF;
+			$this->_currentRow++;
+			
+			if ($this->fetchMode & OCI_ASSOC) $this->_updatefields();
+			if (!empty($ADODB_ANSI_PADDING_OFF)) {
+				foreach($this->fields as $k => $v) {
+					if (is_string($v)) $this->fields[$k] = rtrim($v);
+				}
+			}
+			return true;
+		}
+		if (!$this->EOF) {
+			$this->EOF = true;
+			$this->_currentRow++;
+		}
+		return false;
+	}	
+	
+	/* Optimize SelectLimit() by using OCIFetch() instead of OCIFetchInto() */
+	function &GetArrayLimit($nrows,$offset=-1) 
+	{
+		if ($offset <= 0) {
+			$arr = $this->GetArray($nrows);
+			return $arr;
+		}
+		for ($i=1; $i < $offset; $i++) 
+			if (!@OCIFetch($this->_queryID)) {
+				$arr = array();
+				return $arr;
+			}
+		if (!@OCIfetchinto($this->_queryID,$this->fields,$this->fetchMode)) {
+			$arr = array();
+			return $arr;
+		}
+		if ($this->fetchMode & OCI_ASSOC) $this->_updatefields();
+		$results = array();
+		$cnt = 0;
+		while (!$this->EOF && $nrows != $cnt) {
+			$results[$cnt++] = $this->fields;
+			$this->MoveNext();
+		}
+		
+		return $results;
+	}
+
+	// Create associative array
+	function _updatefields()
+	{
+		if (ADODB_ASSOC_CASE == 2) return; // native
+	
+		$arr = array();
+		$lowercase = (ADODB_ASSOC_CASE == 0);
+		
+		foreach($this->fields as $k => $v) {
+			if (is_integer($k)) $arr[$k] = $v;
+			else {
+				if ($lowercase)
+					$arr[strtolower($k)] = $v;
+				else
+					$arr[strtoupper($k)] = $v;
+			}
+		}
+		$this->fields = $arr;
+	}
+	
+	function _fetch() 
+	{
+		$ret = @OCIfetchinto($this->_queryID,$this->fields,$this->fetchMode);
+		if ($ret) {
+		global $ADODB_ANSI_PADDING_OFF;
+	
+				if ($this->fetchMode & OCI_ASSOC) $this->_updatefields();
+				if (!empty($ADODB_ANSI_PADDING_OFF)) {
+					foreach($this->fields as $k => $v) {
+						if (is_string($v)) $this->fields[$k] = rtrim($v);
+					}
+				}
+		}
+		return $ret;
+	}
+	
+}
+
+
+?>
Index: /Dev/trunk/rdfapi/util/adodb/drivers/adodb-odbc.inc.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/drivers/adodb-odbc.inc.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/drivers/adodb-odbc.inc.php	(revision 12)
@@ -0,0 +1,738 @@
+<?php
+/* 
+V4.94 23 Jan 2007  (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence. 
+Set tabs to 4 for best viewing.
+  
+  Latest version is available at http://adodb.sourceforge.net
+  
+  Requires ODBC. Works on Windows and Unix.
+*/
+// security - hide paths
+if (!defined('ADODB_DIR')) die();
+
+  define("_ADODB_ODBC_LAYER", 2 );
+	 
+/*--------------------------------------------------------------------------------------
+--------------------------------------------------------------------------------------*/
+
+
+class ADODB_odbc extends ADOConnection {
+	var $databaseType = "odbc";	
+	var $fmtDate = "'Y-m-d'";
+	var $fmtTimeStamp = "'Y-m-d, h:i:sA'";
+	var $replaceQuote = "''"; // string to use to replace quotes
+	var $dataProvider = "odbc";
+	var $hasAffectedRows = true;
+	var $binmode = ODBC_BINMODE_RETURN;
+	var $useFetchArray = false; // setting this to true will make array elements in FETCH_ASSOC mode case-sensitive
+								// breaking backward-compat
+	//var $longreadlen = 8000; // default number of chars to return for a Blob/Long field
+	var $_bindInputArray = false;	
+	var $curmode = SQL_CUR_USE_DRIVER; // See sqlext.h, SQL_CUR_DEFAULT == SQL_CUR_USE_DRIVER == 2L
+	var $_genSeqSQL = "create table %s (id integer)";
+	var $_autocommit = true;
+	var $_haserrorfunctions = true;
+	var $_has_stupid_odbc_fetch_api_change = true;
+	var $_lastAffectedRows = 0;
+	var $uCaseTables = true; // for meta* functions, uppercase table names
+	
+	function ADODB_odbc() 
+	{ 	
+		$this->_haserrorfunctions = ADODB_PHPVER >= 0x4050;
+		$this->_has_stupid_odbc_fetch_api_change = ADODB_PHPVER >= 0x4200;
+	}
+	
+		// returns true or false
+	function _connect($argDSN, $argUsername, $argPassword, $argDatabasename)
+	{
+	global $php_errormsg;
+		
+		if (!function_exists('odbc_connect')) return null;
+		
+		if ($this->debug && $argDatabasename && $this->databaseType != 'vfp') {
+			ADOConnection::outp("For odbc Connect(), $argDatabasename is not used. Place dsn in 1st parameter.");
+		}
+		if (isset($php_errormsg)) $php_errormsg = '';
+		if ($this->curmode === false) $this->_connectionID = odbc_connect($argDSN,$argUsername,$argPassword);
+		else $this->_connectionID = odbc_connect($argDSN,$argUsername,$argPassword,$this->curmode);
+		$this->_errorMsg = isset($php_errormsg) ? $php_errormsg : '';
+		if (isset($this->connectStmt)) $this->Execute($this->connectStmt);
+		
+		return $this->_connectionID != false;
+	}
+	
+	// returns true or false
+	function _pconnect($argDSN, $argUsername, $argPassword, $argDatabasename)
+	{
+	global $php_errormsg;
+	
+		if (!function_exists('odbc_connect')) return null;
+		
+		if (isset($php_errormsg)) $php_errormsg = '';
+		$this->_errorMsg = isset($php_errormsg) ? $php_errormsg : '';
+		if ($this->debug && $argDatabasename) {
+			ADOConnection::outp("For odbc PConnect(), $argDatabasename is not used. Place dsn in 1st parameter.");
+		}
+	//	print "dsn=$argDSN u=$argUsername p=$argPassword<br>"; flush();
+		if ($this->curmode === false) $this->_connectionID = odbc_connect($argDSN,$argUsername,$argPassword);
+		else $this->_connectionID = odbc_pconnect($argDSN,$argUsername,$argPassword,$this->curmode);
+		
+		$this->_errorMsg = isset($php_errormsg) ? $php_errormsg : '';
+		if ($this->_connectionID && $this->autoRollback) @odbc_rollback($this->_connectionID);
+		if (isset($this->connectStmt)) $this->Execute($this->connectStmt);
+		
+		return $this->_connectionID != false;
+	}
+
+	
+	function ServerInfo()
+	{
+	
+		if (!empty($this->host) && ADODB_PHPVER >= 0x4300) {
+			$dsn = strtoupper($this->host);
+			$first = true;
+			$found = false;
+			
+			if (!function_exists('odbc_data_source')) return false;
+			
+			while(true) {
+				
+				$rez = @odbc_data_source($this->_connectionID,
+					$first ? SQL_FETCH_FIRST : SQL_FETCH_NEXT);
+				$first = false;
+				if (!is_array($rez)) break;
+				if (strtoupper($rez['server']) == $dsn) {
+					$found = true;
+					break;
+				}
+			} 
+			if (!$found) return ADOConnection::ServerInfo();
+			if (!isset($rez['version'])) $rez['version'] = '';
+			return $rez;
+		} else {
+			return ADOConnection::ServerInfo();
+		}
+	}
+
+	
+	function CreateSequence($seqname='adodbseq',$start=1)
+	{
+		if (empty($this->_genSeqSQL)) return false;
+		$ok = $this->Execute(sprintf($this->_genSeqSQL,$seqname));
+		if (!$ok) return false;
+		$start -= 1;
+		return $this->Execute("insert into $seqname values($start)");
+	}
+	
+	var $_dropSeqSQL = 'drop table %s';
+	function DropSequence($seqname)
+	{
+		if (empty($this->_dropSeqSQL)) return false;
+		return $this->Execute(sprintf($this->_dropSeqSQL,$seqname));
+	}
+	
+	/*
+		This algorithm is not very efficient, but works even if table locking
+		is not available.
+		
+		Will return false if unable to generate an ID after $MAXLOOPS attempts.
+	*/
+	function GenID($seq='adodbseq',$start=1)
+	{	
+		// if you have to modify the parameter below, your database is overloaded,
+		// or you need to implement generation of id's yourself!
+		$MAXLOOPS = 100;
+		//$this->debug=1;
+		while (--$MAXLOOPS>=0) {
+			$num = $this->GetOne("select id from $seq");
+			if ($num === false) {
+				$this->Execute(sprintf($this->_genSeqSQL ,$seq));	
+				$start -= 1;
+				$num = '0';
+				$ok = $this->Execute("insert into $seq values($start)");
+				if (!$ok) return false;
+			} 
+			$this->Execute("update $seq set id=id+1 where id=$num");
+			
+			if ($this->affected_rows() > 0) {
+				$num += 1;
+				$this->genID = $num;
+				return $num;
+			}
+		}
+		if ($fn = $this->raiseErrorFn) {
+			$fn($this->databaseType,'GENID',-32000,"Unable to generate unique id after $MAXLOOPS attempts",$seq,$num);
+		}
+		return false;
+	}
+
+
+	function ErrorMsg()
+	{
+		if ($this->_haserrorfunctions) {
+			if ($this->_errorMsg !== false) return $this->_errorMsg;
+			if (empty($this->_connectionID)) return @odbc_errormsg();
+			return @odbc_errormsg($this->_connectionID);
+		} else return ADOConnection::ErrorMsg();
+	}
+	
+	function ErrorNo()
+	{
+		
+		if ($this->_haserrorfunctions) {
+			if ($this->_errorCode !== false) {
+				// bug in 4.0.6, error number can be corrupted string (should be 6 digits)
+				return (strlen($this->_errorCode)<=2) ? 0 : $this->_errorCode;
+			}
+
+			if (empty($this->_connectionID)) $e = @odbc_error(); 
+			else $e = @odbc_error($this->_connectionID);
+			
+			 // bug in 4.0.6, error number can be corrupted string (should be 6 digits)
+			 // so we check and patch
+			if (strlen($e)<=2) return 0;
+			return $e;
+		} else return ADOConnection::ErrorNo();
+	}
+	
+	
+
+	function BeginTrans()
+	{	
+		if (!$this->hasTransactions) return false;
+		if ($this->transOff) return true; 
+		$this->transCnt += 1;
+		$this->_autocommit = false;
+		return odbc_autocommit($this->_connectionID,false);
+	}
+	
+	function CommitTrans($ok=true) 
+	{ 
+		if ($this->transOff) return true; 
+		if (!$ok) return $this->RollbackTrans();
+		if ($this->transCnt) $this->transCnt -= 1;
+		$this->_autocommit = true;
+		$ret = odbc_commit($this->_connectionID);
+		odbc_autocommit($this->_connectionID,true);
+		return $ret;
+	}
+	
+	function RollbackTrans()
+	{
+		if ($this->transOff) return true; 
+		if ($this->transCnt) $this->transCnt -= 1;
+		$this->_autocommit = true;
+		$ret = odbc_rollback($this->_connectionID);
+		odbc_autocommit($this->_connectionID,true);
+		return $ret;
+	}
+	
+	function MetaPrimaryKeys($table)
+	{
+	global $ADODB_FETCH_MODE;
+	
+		if ($this->uCaseTables) $table = strtoupper($table);
+		$schema = '';
+		$this->_findschema($table,$schema);
+
+		$savem = $ADODB_FETCH_MODE;
+		$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
+		$qid = @odbc_primarykeys($this->_connectionID,'',$schema,$table);
+		
+		if (!$qid) {
+			$ADODB_FETCH_MODE = $savem;
+			return false;
+		}
+		$rs = new ADORecordSet_odbc($qid);
+		$ADODB_FETCH_MODE = $savem;
+		
+		if (!$rs) return false;
+		$rs->_has_stupid_odbc_fetch_api_change = $this->_has_stupid_odbc_fetch_api_change;
+		
+		$arr =& $rs->GetArray();
+		$rs->Close();
+		//print_r($arr);
+		$arr2 = array();
+		for ($i=0; $i < sizeof($arr); $i++) {
+			if ($arr[$i][3]) $arr2[] = $arr[$i][3];
+		}
+		return $arr2;
+	}
+	
+	
+	
+	function &MetaTables($ttype=false)
+	{
+	global $ADODB_FETCH_MODE;
+	
+		$savem = $ADODB_FETCH_MODE;
+		$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
+		$qid = odbc_tables($this->_connectionID);
+		
+		$rs = new ADORecordSet_odbc($qid);
+		
+		$ADODB_FETCH_MODE = $savem;
+		if (!$rs) {
+			$false = false;
+			return $false;
+		}
+		$rs->_has_stupid_odbc_fetch_api_change = $this->_has_stupid_odbc_fetch_api_change;
+		
+		$arr =& $rs->GetArray();
+		//print_r($arr);
+		
+		$rs->Close();
+		$arr2 = array();
+		
+		if ($ttype) {
+			$isview = strncmp($ttype,'V',1) === 0;
+		}
+		for ($i=0; $i < sizeof($arr); $i++) {
+			if (!$arr[$i][2]) continue;
+			$type = $arr[$i][3];
+			if ($ttype) { 
+				if ($isview) {
+					if (strncmp($type,'V',1) === 0) $arr2[] = $arr[$i][2];
+				} else if (strncmp($type,'SYS',3) !== 0) $arr2[] = $arr[$i][2];
+			} else if (strncmp($type,'SYS',3) !== 0) $arr2[] = $arr[$i][2];
+		}
+		return $arr2;
+	}
+	
+/*
+See http://msdn.microsoft.com/library/default.asp?url=/library/en-us/odbc/htm/odbcdatetime_data_type_changes.asp
+/ SQL data type codes /
+#define	SQL_UNKNOWN_TYPE	0
+#define SQL_CHAR			1
+#define SQL_NUMERIC		 2
+#define SQL_DECIMAL		 3
+#define SQL_INTEGER		 4
+#define SQL_SMALLINT		5
+#define SQL_FLOAT		   6
+#define SQL_REAL			7
+#define SQL_DOUBLE		  8
+#if (ODBCVER >= 0x0300)
+#define SQL_DATETIME		9
+#endif
+#define SQL_VARCHAR		12
+
+
+/ One-parameter shortcuts for date/time data types /
+#if (ODBCVER >= 0x0300)
+#define SQL_TYPE_DATE	  91
+#define SQL_TYPE_TIME	  92
+#define SQL_TYPE_TIMESTAMP 93
+
+#define SQL_UNICODE                             (-95)
+#define SQL_UNICODE_VARCHAR                     (-96)
+#define SQL_UNICODE_LONGVARCHAR                 (-97)
+*/
+	function ODBCTypes($t)
+	{
+		switch ((integer)$t) {
+		case 1:	
+		case 12:
+		case 0:
+		case -95:
+		case -96:
+			return 'C';
+		case -97:
+		case -1: //text
+			return 'X';
+		case -4: //image
+			return 'B';
+				
+		case 9:	
+		case 91:
+			return 'D';
+		
+		case 10:
+		case 11:
+		case 92:
+		case 93:
+			return 'T';
+			
+		case 4:
+		case 5:
+		case -6:
+			return 'I';
+			
+		case -11: // uniqidentifier
+			return 'R';
+		case -7: //bit
+			return 'L';
+		
+		default:
+			return 'N';
+		}
+	}
+	
+	function &MetaColumns($table)
+	{
+	global $ADODB_FETCH_MODE;
+	
+		$false = false;
+		if ($this->uCaseTables) $table = strtoupper($table);
+		$schema = '';
+		$this->_findschema($table,$schema);
+		
+		$savem = $ADODB_FETCH_MODE;
+		$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
+	
+		/*if (false) { // after testing, confirmed that the following does not work becoz of a bug
+			$qid2 = odbc_tables($this->_connectionID);
+			$rs = new ADORecordSet_odbc($qid2);		
+			$ADODB_FETCH_MODE = $savem;
+			if (!$rs) return false;
+			$rs->_has_stupid_odbc_fetch_api_change = $this->_has_stupid_odbc_fetch_api_change;
+			$rs->_fetch();
+			
+			while (!$rs->EOF) {
+				if ($table == strtoupper($rs->fields[2])) {
+					$q = $rs->fields[0];
+					$o = $rs->fields[1];
+					break;
+				}
+				$rs->MoveNext();
+			}
+			$rs->Close();
+			
+			$qid = odbc_columns($this->_connectionID,$q,$o,strtoupper($table),'%');
+		} */
+		
+		switch ($this->databaseType) {
+		case 'access':
+		case 'vfp':
+			$qid = odbc_columns($this->_connectionID);#,'%','',strtoupper($table),'%');
+			break;
+		
+		
+		case 'db2':
+            $colname = "%";
+            $qid = odbc_columns($this->_connectionID, "", $schema, $table, $colname);
+            break;
+			
+		default:
+			$qid = @odbc_columns($this->_connectionID,'%','%',strtoupper($table),'%');
+			if (empty($qid)) $qid = odbc_columns($this->_connectionID);
+			break;
+		}
+		if (empty($qid)) return $false;
+		
+		$rs =& new ADORecordSet_odbc($qid);
+		$ADODB_FETCH_MODE = $savem;
+		
+		if (!$rs) return $false;
+		$rs->_has_stupid_odbc_fetch_api_change = $this->_has_stupid_odbc_fetch_api_change;
+		$rs->_fetch();
+		
+		$retarr = array();
+		
+		/*
+		$rs->fields indices
+		0 TABLE_QUALIFIER
+		1 TABLE_SCHEM
+		2 TABLE_NAME
+		3 COLUMN_NAME
+		4 DATA_TYPE
+		5 TYPE_NAME
+		6 PRECISION
+		7 LENGTH
+		8 SCALE
+		9 RADIX
+		10 NULLABLE
+		11 REMARKS
+		*/
+		while (!$rs->EOF) {
+		//	adodb_pr($rs->fields);
+			if (strtoupper(trim($rs->fields[2])) == $table && (!$schema || strtoupper($rs->fields[1]) == $schema)) {
+				$fld = new ADOFieldObject();
+				$fld->name = $rs->fields[3];
+				$fld->type = $this->ODBCTypes($rs->fields[4]);
+				
+				// ref: http://msdn.microsoft.com/library/default.asp?url=/archive/en-us/dnaraccgen/html/msdn_odk.asp
+				// access uses precision to store length for char/varchar
+				if ($fld->type == 'C' or $fld->type == 'X') {
+					if ($this->databaseType == 'access') 
+						$fld->max_length = $rs->fields[6];
+					else if ($rs->fields[4] <= -95) // UNICODE
+						$fld->max_length = $rs->fields[7]/2;
+					else
+						$fld->max_length = $rs->fields[7];
+				} else 
+					$fld->max_length = $rs->fields[7];
+				$fld->not_null = !empty($rs->fields[10]);
+				$fld->scale = $rs->fields[8];
+				$retarr[strtoupper($fld->name)] = $fld;	
+			} else if (sizeof($retarr)>0)
+				break;
+			$rs->MoveNext();
+		}
+		$rs->Close(); //-- crashes 4.03pl1 -- why?
+		
+		if (empty($retarr)) $retarr = false;
+		return $retarr;
+	}
+	
+	function Prepare($sql)
+	{
+		if (! $this->_bindInputArray) return $sql; // no binding
+		$stmt = odbc_prepare($this->_connectionID,$sql);
+		if (!$stmt) {
+			// we don't know whether odbc driver is parsing prepared stmts, so just return sql
+			return $sql;
+		}
+		return array($sql,$stmt,false);
+	}
+
+	/* returns queryID or false */
+	function _query($sql,$inputarr=false) 
+	{
+	GLOBAL $php_errormsg;
+		if (isset($php_errormsg)) $php_errormsg = '';
+		$this->_error = '';
+		
+		if ($inputarr) {
+			if (is_array($sql)) {
+				$stmtid = $sql[1];
+			} else {
+				$stmtid = odbc_prepare($this->_connectionID,$sql);
+	
+				if ($stmtid == false) {
+					$this->_errorMsg = isset($php_errormsg) ? $php_errormsg : '';
+					return false;
+				}
+			}
+			
+			if (! odbc_execute($stmtid,$inputarr)) {
+				//@odbc_free_result($stmtid);
+				if ($this->_haserrorfunctions) {
+					$this->_errorMsg = odbc_errormsg();
+					$this->_errorCode = odbc_error();
+				}
+				return false;
+			}
+		
+		} else if (is_array($sql)) {
+			$stmtid = $sql[1];
+			if (!odbc_execute($stmtid)) {
+				//@odbc_free_result($stmtid);
+				if ($this->_haserrorfunctions) {
+					$this->_errorMsg = odbc_errormsg();
+					$this->_errorCode = odbc_error();
+				}
+				return false;
+			}
+		} else
+			$stmtid = odbc_exec($this->_connectionID,$sql);
+		
+		$this->_lastAffectedRows = 0;
+		if ($stmtid) {
+			if (@odbc_num_fields($stmtid) == 0) {
+				$this->_lastAffectedRows = odbc_num_rows($stmtid);
+				$stmtid = true;
+			} else {
+				$this->_lastAffectedRows = 0;
+				odbc_binmode($stmtid,$this->binmode);
+				odbc_longreadlen($stmtid,$this->maxblobsize);
+			}
+			
+			if ($this->_haserrorfunctions) {
+				$this->_errorMsg = '';
+				$this->_errorCode = 0;
+			} else
+				$this->_errorMsg = isset($php_errormsg) ? $php_errormsg : '';
+		} else {
+			if ($this->_haserrorfunctions) {
+				$this->_errorMsg = odbc_errormsg();
+				$this->_errorCode = odbc_error();
+			} else
+				$this->_errorMsg = isset($php_errormsg) ? $php_errormsg : '';
+		}
+		return $stmtid;
+	}
+
+	/*
+		Insert a null into the blob field of the table first.
+		Then use UpdateBlob to store the blob.
+		
+		Usage:
+		 
+		$conn->Execute('INSERT INTO blobtable (id, blobcol) VALUES (1, null)');
+		$conn->UpdateBlob('blobtable','blobcol',$blob,'id=1');
+	*/
+	function UpdateBlob($table,$column,$val,$where,$blobtype='BLOB')
+	{
+		return $this->Execute("UPDATE $table SET $column=? WHERE $where",array($val)) != false;
+	}
+	
+	// returns true or false
+	function _close()
+	{
+		$ret = @odbc_close($this->_connectionID);
+		$this->_connectionID = false;
+		return $ret;
+	}
+
+	function _affectedrows()
+	{
+		return $this->_lastAffectedRows;
+	}
+	
+}
+	
+/*--------------------------------------------------------------------------------------
+	 Class Name: Recordset
+--------------------------------------------------------------------------------------*/
+
+class ADORecordSet_odbc extends ADORecordSet {	
+	
+	var $bind = false;
+	var $databaseType = "odbc";		
+	var $dataProvider = "odbc";
+	var $useFetchArray;
+	var $_has_stupid_odbc_fetch_api_change;
+	
+	function ADORecordSet_odbc($id,$mode=false)
+	{
+		if ($mode === false) {  
+			global $ADODB_FETCH_MODE;
+			$mode = $ADODB_FETCH_MODE;
+		}
+		$this->fetchMode = $mode;
+		
+		$this->_queryID = $id;
+		
+		// the following is required for mysql odbc driver in 4.3.1 -- why?
+		$this->EOF = false;
+		$this->_currentRow = -1;
+		//$this->ADORecordSet($id);
+	}
+
+
+	// returns the field object
+	function &FetchField($fieldOffset = -1) 
+	{
+		
+		$off=$fieldOffset+1; // offsets begin at 1
+		
+		$o= new ADOFieldObject();
+		$o->name = @odbc_field_name($this->_queryID,$off);
+		$o->type = @odbc_field_type($this->_queryID,$off);
+		$o->max_length = @odbc_field_len($this->_queryID,$off);
+		if (ADODB_ASSOC_CASE == 0) $o->name = strtolower($o->name);
+		else if (ADODB_ASSOC_CASE == 1) $o->name = strtoupper($o->name);
+		return $o;
+	}
+	
+	/* Use associative array to get fields array */
+	function Fields($colname)
+	{
+		if ($this->fetchMode & ADODB_FETCH_ASSOC) return $this->fields[$colname];
+		if (!$this->bind) {
+			$this->bind = array();
+			for ($i=0; $i < $this->_numOfFields; $i++) {
+				$o = $this->FetchField($i);
+				$this->bind[strtoupper($o->name)] = $i;
+			}
+		}
+
+		 return $this->fields[$this->bind[strtoupper($colname)]];
+	}
+	
+		
+	function _initrs()
+	{
+	global $ADODB_COUNTRECS;
+		$this->_numOfRows = ($ADODB_COUNTRECS) ? @odbc_num_rows($this->_queryID) : -1;
+		$this->_numOfFields = @odbc_num_fields($this->_queryID);
+		// some silly drivers such as db2 as/400 and intersystems cache return _numOfRows = 0
+		if ($this->_numOfRows == 0) $this->_numOfRows = -1;
+		//$this->useFetchArray = $this->connection->useFetchArray;
+		$this->_has_stupid_odbc_fetch_api_change = ADODB_PHPVER >= 0x4200;
+	}	
+	
+	function _seek($row)
+	{
+		return false;
+	}
+	
+	// speed up SelectLimit() by switching to ADODB_FETCH_NUM as ADODB_FETCH_ASSOC is emulated
+	function &GetArrayLimit($nrows,$offset=-1) 
+	{
+		if ($offset <= 0) {
+			$rs =& $this->GetArray($nrows);
+			return $rs;
+		}
+		$savem = $this->fetchMode;
+		$this->fetchMode = ADODB_FETCH_NUM;
+		$this->Move($offset);
+		$this->fetchMode = $savem;
+		
+		if ($this->fetchMode & ADODB_FETCH_ASSOC) {
+			$this->fields =& $this->GetRowAssoc(ADODB_ASSOC_CASE);
+		}
+		
+		$results = array();
+		$cnt = 0;
+		while (!$this->EOF && $nrows != $cnt) {
+			$results[$cnt++] = $this->fields;
+			$this->MoveNext();
+		}
+		
+		return $results;
+	}
+	
+	
+	function MoveNext() 
+	{
+		if ($this->_numOfRows != 0 && !$this->EOF) {		
+			$this->_currentRow++;
+			
+			if ($this->_has_stupid_odbc_fetch_api_change)
+				$rez = @odbc_fetch_into($this->_queryID,$this->fields);
+			else {
+				$row = 0;
+				$rez = @odbc_fetch_into($this->_queryID,$row,$this->fields);
+			}
+			if ($rez) {
+				if ($this->fetchMode & ADODB_FETCH_ASSOC) {
+					$this->fields =& $this->GetRowAssoc(ADODB_ASSOC_CASE);
+				}
+				return true;
+			}
+		}
+		$this->fields = false;
+		$this->EOF = true;
+		return false;
+	}	
+	
+	function _fetch()
+	{
+
+		if ($this->_has_stupid_odbc_fetch_api_change)
+			$rez = @odbc_fetch_into($this->_queryID,$this->fields);
+		else {
+			$row = 0;
+			$rez = @odbc_fetch_into($this->_queryID,$row,$this->fields);
+		}
+		if ($rez) {
+			if ($this->fetchMode & ADODB_FETCH_ASSOC) {
+				$this->fields =& $this->GetRowAssoc(ADODB_ASSOC_CASE);
+			}
+			return true;
+		}
+		$this->fields = false;
+		return false;
+	}
+	
+	function _close() 
+	{
+		return @odbc_free_result($this->_queryID);		
+	}
+
+}
+?>
Index: /Dev/trunk/rdfapi/util/adodb/drivers/adodb-odbc_db2.inc.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/drivers/adodb-odbc_db2.inc.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/drivers/adodb-odbc_db2.inc.php	(revision 12)
@@ -0,0 +1,368 @@
+<?php
+/* 
+V4.94 23 Jan 2007  (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence. 
+Set tabs to 4 for best viewing.
+  
+  Latest version is available at http://adodb.sourceforge.net
+  
+  DB2 data driver. Requires ODBC.
+ 
+From phpdb list:
+
+Hi Andrew,
+
+thanks a lot for your help. Today we discovered what
+our real problem was:
+
+After "playing" a little bit with the php-scripts that try
+to connect to the IBM DB2, we set the optional parameter
+Cursortype when calling odbc_pconnect(....).
+
+And the exciting thing: When we set the cursor type
+to SQL_CUR_USE_ODBC Cursor Type, then
+the whole query speed up from 1 till 10 seconds
+to 0.2 till 0.3 seconds for 100 records. Amazing!!!
+
+Therfore, PHP is just almost fast as calling the DB2
+from Servlets using JDBC (don't take too much care
+about the speed at whole: the database was on a
+completely other location, so the whole connection
+was made over a slow network connection).
+
+I hope this helps when other encounter the same
+problem when trying to connect to DB2 from
+PHP.
+
+Kind regards,
+Christian Szardenings
+
+2 Oct 2001
+Mark Newnham has discovered that the SQL_CUR_USE_ODBC is not supported by 
+IBM's DB2 ODBC driver, so this must be a 3rd party ODBC driver.
+
+From the IBM CLI Reference:
+
+SQL_ATTR_ODBC_CURSORS (DB2 CLI v5) 
+This connection attribute is defined by ODBC, but is not supported by DB2
+CLI. Any attempt to set or get this attribute will result in an SQLSTATE of
+HYC00 (Driver not capable). 
+
+A 32-bit option specifying how the Driver Manager uses the ODBC cursor
+library. 
+
+So I guess this means the message [above] was related to using a 3rd party
+odbc driver.
+
+Setting SQL_CUR_USE_ODBC
+========================
+To set SQL_CUR_USE_ODBC for drivers that require it, do this:
+
+$db = NewADOConnection('odbc_db2');
+$db->curMode = SQL_CUR_USE_ODBC;
+$db->Connect($dsn, $userid, $pwd);
+
+
+
+USING CLI INTERFACE
+===================
+
+I have had reports that the $host and $database params have to be reversed in 
+Connect() when using the CLI interface. From Halmai Csongor csongor.halmai#nexum.hu:
+
+> The symptom is that if I change the database engine from postgres or any other to DB2 then the following
+> connection command becomes wrong despite being described this version to be correct in the docs. 
+>
+> $connection_object->Connect( $DATABASE_HOST, $DATABASE_AUTH_USER_NAME, $DATABASE_AUTH_PASSWORD, $DATABASE_NAME )
+>
+> In case of DB2 I had to swap the first and last arguments in order to connect properly. 
+
+
+System Error 5
+==============
+IF you get a System Error 5 when trying to Connect/Load, it could be a permission problem. Give the user connecting
+to DB2 full rights to the DB2 SQLLIB directory, and place the user in the DBUSERS group.
+*/
+
+// security - hide paths
+if (!defined('ADODB_DIR')) die();
+
+if (!defined('_ADODB_ODBC_LAYER')) {
+	include(ADODB_DIR."/drivers/adodb-odbc.inc.php");
+}
+if (!defined('ADODB_ODBC_DB2')){
+define('ADODB_ODBC_DB2',1);
+
+class ADODB_ODBC_DB2 extends ADODB_odbc {
+	var $databaseType = "db2";	
+	var $concat_operator = '||';
+	var $sysTime = 'CURRENT TIME';
+	var $sysDate = 'CURRENT DATE';
+	var $sysTimeStamp = 'CURRENT TIMESTAMP';
+	// The complete string representation of a timestamp has the form 
+	// yyyy-mm-dd-hh.mm.ss.nnnnnn.
+	var $fmtTimeStamp = "'Y-m-d-H.i.s'";
+	var $ansiOuter = true;
+	var $identitySQL = 'values IDENTITY_VAL_LOCAL()';
+	var $_bindInputArray = true;
+	 var $hasInsertID = true;
+	var $rsPrefix = 'ADORecordset_odbc_';
+	
+	function ADODB_DB2()
+	{
+		if (strncmp(PHP_OS,'WIN',3) === 0) $this->curmode = SQL_CUR_USE_ODBC;
+		$this->ADODB_odbc();
+	}
+	
+	function IfNull( $field, $ifNull ) 
+	{
+		return " COALESCE($field, $ifNull) "; // if DB2 UDB
+	}
+	
+	function ServerInfo()
+	{
+		//odbc_setoption($this->_connectionID,1,101 /*SQL_ATTR_ACCESS_MODE*/, 1 /*SQL_MODE_READ_ONLY*/);
+		$vers = $this->GetOne('select versionnumber from sysibm.sysversions');
+		//odbc_setoption($this->_connectionID,1,101, 0 /*SQL_MODE_READ_WRITE*/);
+		return array('description'=>'DB2 ODBC driver', 'version'=>$vers);
+	}
+	
+	function _insertid()
+	{
+		return $this->GetOne($this->identitySQL);
+	}
+	
+	function RowLock($tables,$where,$flds='1 as ignore')
+	{
+		if ($this->_autocommit) $this->BeginTrans();
+		return $this->GetOne("select $flds from $tables where $where for update");
+	}
+	
+	function &MetaTables($ttype=false,$showSchema=false, $qtable="%", $qschema="%")
+	{
+	global $ADODB_FETCH_MODE;
+	
+		$savem = $ADODB_FETCH_MODE;
+		$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
+		$qid = odbc_tables($this->_connectionID, "", $qschema, $qtable, "");
+		
+		$rs = new ADORecordSet_odbc($qid);
+		
+		$ADODB_FETCH_MODE = $savem;
+		if (!$rs) {
+			$false = false;
+			return $false;
+		}
+		$rs->_has_stupid_odbc_fetch_api_change = $this->_has_stupid_odbc_fetch_api_change;
+		
+		$arr =& $rs->GetArray();
+		//print_r($arr);
+		
+		$rs->Close();
+		$arr2 = array();
+		
+		if ($ttype) {
+			$isview = strncmp($ttype,'V',1) === 0;
+		}
+		for ($i=0; $i < sizeof($arr); $i++) {
+		
+			if (!$arr[$i][2]) continue;
+			if (strncmp($arr[$i][1],'SYS',3) === 0) continue;
+			
+			$type = $arr[$i][3];
+			
+			if ($showSchema) $arr[$i][2] = $arr[$i][1].'.'.$arr[$i][2];
+			
+			if ($ttype) { 
+				if ($isview) {
+					if (strncmp($type,'V',1) === 0) $arr2[] = $arr[$i][2];
+				} else if (strncmp($type,'T',1) === 0) $arr2[] = $arr[$i][2];
+			} else if (strncmp($type,'S',1) !== 0) $arr2[] = $arr[$i][2];
+		}
+		return $arr2;
+	}
+
+	function &MetaIndexes ($table, $primary = FALSE, $owner=false)
+	{
+        // save old fetch mode
+        global $ADODB_FETCH_MODE;
+        $save = $ADODB_FETCH_MODE;
+        $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
+        if ($this->fetchMode !== FALSE) {
+               $savem = $this->SetFetchMode(FALSE);
+        }
+		$false = false;
+		// get index details
+		$table = strtoupper($table);
+		$SQL="SELECT NAME, UNIQUERULE, COLNAMES FROM SYSIBM.SYSINDEXES WHERE TBNAME='$table'";
+        if ($primary) 
+			$SQL.= " AND UNIQUERULE='P'";
+		$rs = $this->Execute($SQL);
+        if (!is_object($rs)) {
+			if (isset($savem)) 
+				$this->SetFetchMode($savem);
+			$ADODB_FETCH_MODE = $save;
+            return $false;
+        }
+		$indexes = array ();
+        // parse index data into array
+        while ($row = $rs->FetchRow()) {
+			$indexes[$row[0]] = array(
+			   'unique' => ($row[1] == 'U' || $row[1] == 'P'),
+			   'columns' => array()
+			);
+			$cols = ltrim($row[2],'+');
+			$indexes[$row[0]]['columns'] = explode('+', $cols);
+        }
+		if (isset($savem)) { 
+            $this->SetFetchMode($savem);
+			$ADODB_FETCH_MODE = $save;
+		}
+        return $indexes;
+	}
+	
+	// Format date column in sql string given an input format that understands Y M D
+	function SQLDate($fmt, $col=false)
+	{	
+	// use right() and replace() ?
+		if (!$col) $col = $this->sysDate;
+		$s = '';
+		
+		$len = strlen($fmt);
+		for ($i=0; $i < $len; $i++) {
+			if ($s) $s .= '||';
+			$ch = $fmt[$i];
+			switch($ch) {
+			case 'Y':
+			case 'y':
+				$s .= "char(year($col))";
+				break;
+			case 'M':
+				$s .= "substr(monthname($col),1,3)";
+				break;
+			case 'm':
+				$s .= "right(digits(month($col)),2)";
+				break;
+			case 'D':
+			case 'd':
+				$s .= "right(digits(day($col)),2)";
+				break;
+			case 'H':
+			case 'h':
+				if ($col != $this->sysDate) $s .= "right(digits(hour($col)),2)";	
+				else $s .= "''";
+				break;
+			case 'i':
+			case 'I':
+				if ($col != $this->sysDate)
+					$s .= "right(digits(minute($col)),2)";
+					else $s .= "''";
+				break;
+			case 'S':
+			case 's':
+				if ($col != $this->sysDate)
+					$s .= "right(digits(second($col)),2)";
+				else $s .= "''";
+				break;
+			default:
+				if ($ch == '\\') {
+					$i++;
+					$ch = substr($fmt,$i,1);
+				}
+				$s .= $this->qstr($ch);
+			}
+		}
+		return $s;
+	} 
+ 
+	
+	function &SelectLimit($sql,$nrows=-1,$offset=-1,$inputArr=false)
+	{
+		$nrows = (integer) $nrows;
+		if ($offset <= 0) {
+		// could also use " OPTIMIZE FOR $nrows ROWS "
+			if ($nrows >= 0) $sql .=  " FETCH FIRST $nrows ROWS ONLY ";
+			$rs =& $this->Execute($sql,$inputArr);
+		} else {
+			if ($offset > 0 && $nrows < 0);
+			else {
+				$nrows += $offset;
+				$sql .=  " FETCH FIRST $nrows ROWS ONLY ";
+			}
+			$rs =& ADOConnection::SelectLimit($sql,-1,$offset,$inputArr);
+		}
+		
+		return $rs;
+	}
+	
+};
+ 
+
+class  ADORecordSet_odbc_db2 extends ADORecordSet_odbc {	
+	
+	var $databaseType = "db2";		
+	
+	function ADORecordSet_db2($id,$mode=false)
+	{
+		$this->ADORecordSet_odbc($id,$mode);
+	}
+
+	function MetaType($t,$len=-1,$fieldobj=false)
+	{
+		if (is_object($t)) {
+			$fieldobj = $t;
+			$t = $fieldobj->type;
+			$len = $fieldobj->max_length;
+		}
+		
+		switch (strtoupper($t)) {
+		case 'VARCHAR':
+		case 'CHAR':
+		case 'CHARACTER':
+		case 'C':
+			if ($len <= $this->blobSize) return 'C';
+		
+		case 'LONGCHAR':
+		case 'TEXT':
+		case 'CLOB':
+		case 'DBCLOB': // double-byte
+		case 'X':
+			return 'X';
+		
+		case 'BLOB':
+		case 'GRAPHIC':
+		case 'VARGRAPHIC':
+			return 'B';
+			
+		case 'DATE':
+		case 'D':
+			return 'D';
+		
+		case 'TIME':
+		case 'TIMESTAMP':
+		case 'T':
+			return 'T';
+		
+		//case 'BOOLEAN': 
+		//case 'BIT':
+		//	return 'L';
+			
+		//case 'COUNTER':
+		//	return 'R';
+			
+		case 'INT':
+		case 'INTEGER':
+		case 'BIGINT':
+		case 'SMALLINT':
+		case 'I':
+			return 'I';
+			
+		default: return 'N';
+		}
+	}
+}
+
+} //define
+?>
Index: /Dev/trunk/rdfapi/util/adodb/drivers/adodb-odbc_mssql.inc.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/drivers/adodb-odbc_mssql.inc.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/drivers/adodb-odbc_mssql.inc.php	(revision 12)
@@ -0,0 +1,306 @@
+<?php
+/* 
+V4.94 23 Jan 2007  (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence. 
+Set tabs to 4 for best viewing.
+  
+  Latest version is available at http://adodb.sourceforge.net
+  
+  MSSQL support via ODBC. Requires ODBC. Works on Windows and Unix. 
+  For Unix configuration, see http://phpbuilder.com/columns/alberto20000919.php3
+*/
+
+// security - hide paths
+if (!defined('ADODB_DIR')) die();
+
+if (!defined('_ADODB_ODBC_LAYER')) {
+	include(ADODB_DIR."/drivers/adodb-odbc.inc.php");
+}
+
+ 
+class  ADODB_odbc_mssql extends ADODB_odbc {	
+	var $databaseType = 'odbc_mssql';
+	var $fmtDate = "'Y-m-d'";
+	var $fmtTimeStamp = "'Y-m-d H:i:s'";
+	var $_bindInputArray = true;
+	var $metaTablesSQL="select name,case when type='U' then 'T' else 'V' end from sysobjects where (type='U' or type='V') and (name not in ('sysallocations','syscolumns','syscomments','sysdepends','sysfilegroups','sysfiles','sysfiles1','sysforeignkeys','sysfulltextcatalogs','sysindexes','sysindexkeys','sysmembers','sysobjects','syspermissions','sysprotects','sysreferences','systypes','sysusers','sysalternates','sysconstraints','syssegments','REFERENTIAL_CONSTRAINTS','CHECK_CONSTRAINTS','CONSTRAINT_TABLE_USAGE','CONSTRAINT_COLUMN_USAGE','VIEWS','VIEW_TABLE_USAGE','VIEW_COLUMN_USAGE','SCHEMATA','TABLES','TABLE_CONSTRAINTS','TABLE_PRIVILEGES','COLUMNS','COLUMN_DOMAIN_USAGE','COLUMN_PRIVILEGES','DOMAINS','DOMAIN_CONSTRAINTS','KEY_COLUMN_USAGE'))";
+	var $metaColumnsSQL = "select c.name,t.name,c.length from syscolumns c join systypes t on t.xusertype=c.xusertype join sysobjects o on o.id=c.id where o.name='%s'";
+	var $hasTop = 'top';		// support mssql/interbase SELECT TOP 10 * FROM TABLE
+	var $sysDate = 'GetDate()';
+	var $sysTimeStamp = 'GetDate()';
+	var $leftOuter = '*=';
+	var $rightOuter = '=*';
+	var $substr = 'substring';
+	var $length = 'len';
+	var $ansiOuter = true; // for mssql7 or later
+	var $identitySQL = 'select @@IDENTITY'; // 'select SCOPE_IDENTITY'; # for mssql 2000
+	var $hasInsertID = true;
+	var $connectStmt = 'SET CONCAT_NULL_YIELDS_NULL OFF'; # When SET CONCAT_NULL_YIELDS_NULL is ON, 
+														  # concatenating a null value with a string yields a NULL result
+	
+	function ADODB_odbc_mssql()
+	{
+		$this->ADODB_odbc();
+		//$this->curmode = SQL_CUR_USE_ODBC;	
+	}
+
+	// crashes php...
+	function ServerInfo()
+	{
+	global $ADODB_FETCH_MODE;
+		$save = $ADODB_FETCH_MODE;
+		$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
+		$row = $this->GetRow("execute sp_server_info 2");
+		$ADODB_FETCH_MODE = $save;
+		if (!is_array($row)) return false;
+		$arr['description'] = $row[2];
+		$arr['version'] = ADOConnection::_findvers($arr['description']);
+		return $arr;
+	}
+
+	function IfNull( $field, $ifNull ) 
+	{
+		return " ISNULL($field, $ifNull) "; // if MS SQL Server
+	}
+	
+	function _insertid()
+	{
+	// SCOPE_IDENTITY()
+	// Returns the last IDENTITY value inserted into an IDENTITY column in 
+	// the same scope. A scope is a module -- a stored procedure, trigger, 
+	// function, or batch. Thus, two statements are in the same scope if 
+	// they are in the same stored procedure, function, or batch.
+			return $this->GetOne($this->identitySQL);
+	}
+	
+	
+	function MetaForeignKeys($table, $owner=false, $upper=false)
+	{
+	global $ADODB_FETCH_MODE;
+	
+		$save = $ADODB_FETCH_MODE;
+		$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
+		$table = $this->qstr(strtoupper($table));
+		
+		$sql = 
+"select object_name(constid) as constraint_name,
+	col_name(fkeyid, fkey) as column_name,
+	object_name(rkeyid) as referenced_table_name,
+   	col_name(rkeyid, rkey) as referenced_column_name
+from sysforeignkeys
+where upper(object_name(fkeyid)) = $table
+order by constraint_name, referenced_table_name, keyno";
+		
+		$constraints =& $this->GetArray($sql);
+		
+		$ADODB_FETCH_MODE = $save;
+		
+		$arr = false;
+		foreach($constraints as $constr) {
+			//print_r($constr);
+			$arr[$constr[0]][$constr[2]][] = $constr[1].'='.$constr[3]; 
+		}
+		if (!$arr) return false;
+		
+		$arr2 = false;
+		
+		foreach($arr as $k => $v) {
+			foreach($v as $a => $b) {
+				if ($upper) $a = strtoupper($a);
+				$arr2[$a] = $b;
+			}
+		}
+		return $arr2;
+	}
+	
+	function &MetaTables($ttype=false,$showSchema=false,$mask=false) 
+	{
+		if ($mask) {$this->debug=1;
+			$save = $this->metaTablesSQL;
+			$mask = $this->qstr($mask);
+			$this->metaTablesSQL .= " AND name like $mask";
+		}
+		$ret =& ADOConnection::MetaTables($ttype,$showSchema);
+		
+		if ($mask) {
+			$this->metaTablesSQL = $save;
+		}
+		return $ret;
+	}
+	
+	function &MetaColumns($table)
+	{
+		$arr = ADOConnection::MetaColumns($table);
+		return $arr;
+	}
+	
+	
+	function &MetaIndexes($table,$primary=false)
+	{
+		$table = $this->qstr($table);
+
+		$sql = "SELECT i.name AS ind_name, C.name AS col_name, USER_NAME(O.uid) AS Owner, c.colid, k.Keyno, 
+			CASE WHEN I.indid BETWEEN 1 AND 254 AND (I.status & 2048 = 2048 OR I.Status = 16402 AND O.XType = 'V') THEN 1 ELSE 0 END AS IsPK,
+			CASE WHEN I.status & 2 = 2 THEN 1 ELSE 0 END AS IsUnique
+			FROM dbo.sysobjects o INNER JOIN dbo.sysindexes I ON o.id = i.id 
+			INNER JOIN dbo.sysindexkeys K ON I.id = K.id AND I.Indid = K.Indid 
+			INNER JOIN dbo.syscolumns c ON K.id = C.id AND K.colid = C.Colid
+			WHERE LEFT(i.name, 8) <> '_WA_Sys_' AND o.status >= 0 AND O.Name LIKE $table
+			ORDER BY O.name, I.Name, K.keyno";
+
+		global $ADODB_FETCH_MODE;
+		$save = $ADODB_FETCH_MODE;
+        $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
+        if ($this->fetchMode !== FALSE) {
+        	$savem = $this->SetFetchMode(FALSE);
+        }
+        
+        $rs = $this->Execute($sql);
+        if (isset($savem)) {
+        	$this->SetFetchMode($savem);
+        }
+        $ADODB_FETCH_MODE = $save;
+
+        if (!is_object($rs)) {
+        	return FALSE;
+        }
+
+		$indexes = array();
+		while ($row = $rs->FetchRow()) {
+			if (!$primary && $row[5]) continue;
+			
+            $indexes[$row[0]]['unique'] = $row[6];
+            $indexes[$row[0]]['columns'][] = $row[1];
+    	}
+        return $indexes;
+	}
+	
+	function _query($sql,$inputarr)
+	{
+		if (is_string($sql)) $sql = str_replace('||','+',$sql);
+		return ADODB_odbc::_query($sql,$inputarr);
+	}
+	
+	function SetTransactionMode( $transaction_mode ) 
+	{
+		$this->_transmode  = $transaction_mode;
+		if (empty($transaction_mode)) {
+			$this->Execute('SET TRANSACTION ISOLATION LEVEL READ COMMITTED');
+			return;
+		}
+		if (!stristr($transaction_mode,'isolation')) $transaction_mode = 'ISOLATION LEVEL '.$transaction_mode;
+		$this->Execute("SET TRANSACTION ".$transaction_mode);
+	}
+	
+	// "Stein-Aksel Basma" <basma@accelero.no>
+	// tested with MSSQL 2000
+	function &MetaPrimaryKeys($table)
+	{
+	global $ADODB_FETCH_MODE;
+	
+		$schema = '';
+		$this->_findschema($table,$schema);
+		//if (!$schema) $schema = $this->database;
+		if ($schema) $schema = "and k.table_catalog like '$schema%'"; 
+	
+		$sql = "select distinct k.column_name,ordinal_position from information_schema.key_column_usage k,
+		information_schema.table_constraints tc 
+		where tc.constraint_name = k.constraint_name and tc.constraint_type =
+		'PRIMARY KEY' and k.table_name = '$table' $schema order by ordinal_position ";
+		
+		$savem = $ADODB_FETCH_MODE;
+		$ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
+		$a = $this->GetCol($sql);
+		$ADODB_FETCH_MODE = $savem;
+		
+		if ($a && sizeof($a)>0) return $a;
+		$false = false;
+		return $false;	  
+	}
+	
+	function &SelectLimit($sql,$nrows=-1,$offset=-1, $inputarr=false,$secs2cache=0)
+	{
+		if ($nrows > 0 && $offset <= 0) {
+			$sql = preg_replace(
+				'/(^\s*select\s+(distinctrow|distinct)?)/i','\\1 '.$this->hasTop." $nrows ",$sql);
+			$rs =& $this->Execute($sql,$inputarr);
+		} else
+			$rs =& ADOConnection::SelectLimit($sql,$nrows,$offset,$inputarr,$secs2cache);
+			
+		return $rs;
+	}
+	
+	// Format date column in sql string given an input format that understands Y M D
+	function SQLDate($fmt, $col=false)
+	{	
+		if (!$col) $col = $this->sysTimeStamp;
+		$s = '';
+		
+		$len = strlen($fmt);
+		for ($i=0; $i < $len; $i++) {
+			if ($s) $s .= '+';
+			$ch = $fmt[$i];
+			switch($ch) {
+			case 'Y':
+			case 'y':
+				$s .= "datename(yyyy,$col)";
+				break;
+			case 'M':
+				$s .= "convert(char(3),$col,0)";
+				break;
+			case 'm':
+				$s .= "replace(str(month($col),2),' ','0')";
+				break;
+			case 'Q':
+			case 'q':
+				$s .= "datename(quarter,$col)";
+				break;
+			case 'D':
+			case 'd':
+				$s .= "replace(str(day($col),2),' ','0')";
+				break;
+			case 'h':
+				$s .= "substring(convert(char(14),$col,0),13,2)";
+				break;
+			
+			case 'H':
+				$s .= "replace(str(datepart(hh,$col),2),' ','0')";
+				break;
+				
+			case 'i':
+				$s .= "replace(str(datepart(mi,$col),2),' ','0')";
+				break;
+			case 's':
+				$s .= "replace(str(datepart(ss,$col),2),' ','0')";
+				break;
+			case 'a':
+			case 'A':
+				$s .= "substring(convert(char(19),$col,0),18,2)";
+				break;
+				
+			default:
+				if ($ch == '\\') {
+					$i++;
+					$ch = substr($fmt,$i,1);
+				}
+				$s .= $this->qstr($ch);
+				break;
+			}
+		}
+		return $s;
+	}
+
+} 
+ 
+class  ADORecordSet_odbc_mssql extends ADORecordSet_odbc {	
+	
+	var $databaseType = 'odbc_mssql';
+	
+	function ADORecordSet_odbc_mssql($id,$mode=false)
+	{
+		return $this->ADORecordSet_odbc($id,$mode);
+	}	
+}
+?>
Index: /Dev/trunk/rdfapi/util/adodb/drivers/adodb-odbc_oracle.inc.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/drivers/adodb-odbc_oracle.inc.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/drivers/adodb-odbc_oracle.inc.php	(revision 12)
@@ -0,0 +1,115 @@
+<?php
+/* 
+V4.94 23 Jan 2007  (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence. 
+Set tabs to 4 for best viewing.
+  
+  Latest version is available at http://adodb.sourceforge.net
+  
+  Oracle support via ODBC. Requires ODBC. Works on Windows. 
+*/
+// security - hide paths
+if (!defined('ADODB_DIR')) die();
+
+if (!defined('_ADODB_ODBC_LAYER')) {
+	include(ADODB_DIR."/drivers/adodb-odbc.inc.php");
+}
+
+ 
+class  ADODB_odbc_oracle extends ADODB_odbc {	
+	var $databaseType = 'odbc_oracle';
+ 	var $replaceQuote = "''"; // string to use to replace quotes
+	var $concat_operator='||';
+	var $fmtDate = "'Y-m-d 00:00:00'"; 
+	var $fmtTimeStamp = "'Y-m-d h:i:sA'";
+	var $metaTablesSQL = 'select table_name from cat';
+	var $metaColumnsSQL = "select cname,coltype,width from col where tname='%s' order by colno";
+	var $sysDate = "TRUNC(SYSDATE)";
+	var $sysTimeStamp = 'SYSDATE';
+	
+	//var $_bindInputArray = false;
+	
+	function ADODB_odbc_oracle()
+	{
+		$this->ADODB_odbc();
+	}
+		
+	function &MetaTables() 
+	{
+		$false = false;
+		$rs = $this->Execute($this->metaTablesSQL);
+		if ($rs === false) return $false;
+		$arr = $rs->GetArray();
+		$arr2 = array();
+		for ($i=0; $i < sizeof($arr); $i++) {
+			$arr2[] = $arr[$i][0];
+		}
+		$rs->Close();
+		return $arr2;
+	}
+	
+	function &MetaColumns($table) 
+	{
+	global $ADODB_FETCH_MODE;
+	
+		$rs = $this->Execute(sprintf($this->metaColumnsSQL,strtoupper($table)));
+		if ($rs === false) {	
+			$false = false;
+			return $false;
+		}
+		$retarr = array();
+		while (!$rs->EOF) { //print_r($rs->fields);
+			$fld = new ADOFieldObject();
+			$fld->name = $rs->fields[0];
+			$fld->type = $rs->fields[1];
+			$fld->max_length = $rs->fields[2];
+			
+			
+			if ($ADODB_FETCH_MODE == ADODB_FETCH_NUM) $retarr[] = $fld;	
+			else $retarr[strtoupper($fld->name)] = $fld;
+			
+			$rs->MoveNext();
+		}
+		$rs->Close();
+		return $retarr;	
+	}
+
+	// returns true or false
+	function _connect($argDSN, $argUsername, $argPassword, $argDatabasename)
+	{
+	global $php_errormsg;
+	
+		$php_errormsg = '';
+		$this->_connectionID = odbc_connect($argDSN,$argUsername,$argPassword,SQL_CUR_USE_ODBC );
+		$this->_errorMsg = $php_errormsg;
+		
+		$this->Execute("ALTER SESSION SET NLS_DATE_FORMAT='YYYY-MM-DD HH24:MI:SS'");
+		//if ($this->_connectionID) odbc_autocommit($this->_connectionID,true);
+		return $this->_connectionID != false;
+	}
+	// returns true or false
+	function _pconnect($argDSN, $argUsername, $argPassword, $argDatabasename)
+	{
+	global $php_errormsg;
+		$php_errormsg = '';
+		$this->_connectionID = odbc_pconnect($argDSN,$argUsername,$argPassword,SQL_CUR_USE_ODBC );
+		$this->_errorMsg = $php_errormsg;
+		
+		$this->Execute("ALTER SESSION SET NLS_DATE_FORMAT='YYYY-MM-DD HH24:MI:SS'");
+		//if ($this->_connectionID) odbc_autocommit($this->_connectionID,true);
+		return $this->_connectionID != false;
+	}
+} 
+ 
+class  ADORecordSet_odbc_oracle extends ADORecordSet_odbc {	
+	
+	var $databaseType = 'odbc_oracle';
+	
+	function ADORecordSet_odbc_oracle($id,$mode=false)
+	{
+		return $this->ADORecordSet_odbc($id,$mode);
+	}
+}
+?>
Index: /Dev/trunk/rdfapi/util/adodb/drivers/adodb-odbtp.inc.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/drivers/adodb-odbtp.inc.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/drivers/adodb-odbtp.inc.php	(revision 12)
@@ -0,0 +1,743 @@
+<?php
+/*
+  V4.94 23 Jan 2007  (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
+  Released under both BSD license and Lesser GPL library license.
+  Whenever there is any discrepancy between the two licenses,
+  the BSD license will take precedence. See License.txt.
+  Set tabs to 4 for best viewing.
+  Latest version is available at http://adodb.sourceforge.net
+*/
+// Code contributed by "stefan bogdan" <sbogdan#rsb.ro>
+
+// security - hide paths
+if (!defined('ADODB_DIR')) die();
+
+define("_ADODB_ODBTP_LAYER", 2 );
+
+class ADODB_odbtp extends ADOConnection{
+	var $databaseType = "odbtp";
+	var $dataProvider = "odbtp";
+	var $fmtDate = "'Y-m-d'";
+	var $fmtTimeStamp = "'Y-m-d, h:i:sA'";
+	var $replaceQuote = "''"; // string to use to replace quotes
+	var $odbc_driver = 0;
+	var $hasAffectedRows = true;
+	var $hasInsertID = false;
+	var $hasGenID = true;
+	var $hasMoveFirst = true;
+
+	var $_genSeqSQL = "create table %s (seq_name char(30) not null unique , seq_value integer not null)";
+	var $_dropSeqSQL = "delete from adodb_seq where seq_name = '%s'";
+	var $_bindInputArray = false;
+	var $_useUnicodeSQL = false;
+	var $_canPrepareSP = false;
+	var $_dontPoolDBC = true;
+
+	function ADODB_odbtp()
+	{
+	}
+
+	function ServerInfo()
+	{
+		return array('description' => @odbtp_get_attr( ODB_ATTR_DBMSNAME, $this->_connectionID),
+		             'version' => @odbtp_get_attr( ODB_ATTR_DBMSVER, $this->_connectionID));
+	}
+
+	function ErrorMsg()
+	{
+		if (empty($this->_connectionID)) return @odbtp_last_error();
+		return @odbtp_last_error($this->_connectionID);
+	}
+
+	function ErrorNo()
+	{
+		if (empty($this->_connectionID)) return @odbtp_last_error_state();
+			return @odbtp_last_error_state($this->_connectionID);
+	}
+
+	function _insertid()
+	{
+	// SCOPE_IDENTITY()
+	// Returns the last IDENTITY value inserted into an IDENTITY column in
+	// the same scope. A scope is a module -- a stored procedure, trigger,
+	// function, or batch. Thus, two statements are in the same scope if
+	// they are in the same stored procedure, function, or batch.
+			return $this->GetOne($this->identitySQL);
+	}
+
+	function _affectedrows()
+	{
+		if ($this->_queryID) {
+			return @odbtp_affected_rows ($this->_queryID);
+	   } else
+		return 0;
+	}
+
+	function CreateSequence($seqname='adodbseq',$start=1)
+	{
+		//verify existence
+		$num = $this->GetOne("select seq_value from adodb_seq");
+		$seqtab='adodb_seq';
+		if( $this->odbc_driver == ODB_DRIVER_FOXPRO ) {
+			$path = @odbtp_get_attr( ODB_ATTR_DATABASENAME, $this->_connectionID );
+			//if using vfp dbc file
+			if( !strcasecmp(strrchr($path, '.'), '.dbc') )
+                $path = substr($path,0,strrpos($path,'\/'));
+           	$seqtab = $path . '/' . $seqtab;
+        }
+		if($num == false) {
+			if (empty($this->_genSeqSQL)) return false;
+			$ok = $this->Execute(sprintf($this->_genSeqSQL ,$seqtab));
+		}
+		$num = $this->GetOne("select seq_value from adodb_seq where seq_name='$seqname'");
+		if ($num) {
+			return false;
+		}
+		$start -= 1;
+		return $this->Execute("insert into adodb_seq values('$seqname',$start)");
+	}
+
+	function DropSequence($seqname)
+	{
+		if (empty($this->_dropSeqSQL)) return false;
+		return $this->Execute(sprintf($this->_dropSeqSQL,$seqname));
+	}
+
+	function GenID($seq='adodbseq',$start=1)
+	{
+		$seqtab='adodb_seq';
+		if( $this->odbc_driver == ODB_DRIVER_FOXPRO) {
+			$path = @odbtp_get_attr( ODB_ATTR_DATABASENAME, $this->_connectionID );
+			//if using vfp dbc file
+			if( !strcasecmp(strrchr($path, '.'), '.dbc') )
+                $path = substr($path,0,strrpos($path,'\/'));
+           	$seqtab = $path . '/' . $seqtab;
+        }
+		$MAXLOOPS = 100;
+		while (--$MAXLOOPS>=0) {
+			$num = $this->GetOne("select seq_value from adodb_seq where seq_name='$seq'");
+			if ($num === false) {
+				//verify if abodb_seq table exist
+				$ok = $this->GetOne("select seq_value from adodb_seq ");
+				if(!$ok) {
+					//creating the sequence table adodb_seq
+					$this->Execute(sprintf($this->_genSeqSQL ,$seqtab));
+				}
+				$start -= 1;
+				$num = '0';
+				$ok = $this->Execute("insert into adodb_seq values('$seq',$start)");
+				if (!$ok) return false;
+			}
+			$ok = $this->Execute("update adodb_seq set seq_value=seq_value+1 where seq_name='$seq'");
+			if($ok) {
+				$num += 1;
+				$this->genID = $num;
+				return $num;
+			}
+		}
+	if ($fn = $this->raiseErrorFn) {
+		$fn($this->databaseType,'GENID',-32000,"Unable to generate unique id after $MAXLOOPS attempts",$seq,$num);
+	}
+		return false;
+	}
+
+	//example for $UserOrDSN
+	//for visual fox : DRIVER={Microsoft Visual FoxPro Driver};SOURCETYPE=DBF;SOURCEDB=c:\YourDbfFileDir;EXCLUSIVE=NO;
+	//for visual fox dbc: DRIVER={Microsoft Visual FoxPro Driver};SOURCETYPE=DBC;SOURCEDB=c:\YourDbcFileDir\mydb.dbc;EXCLUSIVE=NO;
+	//for access : DRIVER={Microsoft Access Driver (*.mdb)};DBQ=c:\path_to_access_db\base_test.mdb;UID=root;PWD=;
+	//for mssql : DRIVER={SQL Server};SERVER=myserver;UID=myuid;PWD=mypwd;DATABASE=OdbtpTest;
+	//if uid & pwd can be separate
+    function _connect($HostOrInterface, $UserOrDSN='', $argPassword='', $argDatabase='')
+	{
+		$this->_connectionID = odbtp_connect($HostOrInterface,$UserOrDSN,$argPassword,$argDatabase);
+		if ($this->_connectionID === false) {
+			$this->_errorMsg = $this->ErrorMsg() ;
+			return false;
+		}
+		
+		odbtp_convert_datetime($this->_connectionID,true);
+		
+		if ($this->_dontPoolDBC) {
+			if (function_exists('odbtp_dont_pool_dbc'))
+				@odbtp_dont_pool_dbc($this->_connectionID);
+		}
+		else {
+			$this->_dontPoolDBC = true;
+		}
+		$this->odbc_driver = @odbtp_get_attr(ODB_ATTR_DRIVER, $this->_connectionID);
+		$dbms = strtolower(@odbtp_get_attr(ODB_ATTR_DBMSNAME, $this->_connectionID));
+		$this->odbc_name = $dbms;
+		
+		// Account for inconsistent DBMS names
+		if( $this->odbc_driver == ODB_DRIVER_ORACLE )
+			$dbms = 'oracle';
+		else if( $this->odbc_driver == ODB_DRIVER_SYBASE )
+			$dbms = 'sybase';
+
+		// Set DBMS specific attributes
+		switch( $dbms ) {
+			case 'microsoft sql server':
+				$this->databaseType = 'odbtp_mssql';
+				$this->fmtDate = "'Y-m-d'";
+				$this->fmtTimeStamp = "'Y-m-d h:i:sA'";
+				$this->sysDate = 'convert(datetime,convert(char,GetDate(),102),102)';
+				$this->sysTimeStamp = 'GetDate()';
+				$this->ansiOuter = true;
+				$this->leftOuter = '*=';
+				$this->rightOuter = '=*';
+                $this->hasTop = 'top';
+				$this->hasInsertID = true;
+				$this->hasTransactions = true;
+				$this->_bindInputArray = true;
+				$this->_canSelectDb = true;
+				$this->substr = "substring";
+				$this->length = 'len';
+				$this->identitySQL = 'select @@IDENTITY';
+				$this->metaDatabasesSQL = "select name from master..sysdatabases where name <> 'master'";
+				$this->_canPrepareSP = true;
+				break;
+			case 'access':
+				$this->databaseType = 'odbtp_access';
+				$this->fmtDate = "#Y-m-d#";
+				$this->fmtTimeStamp = "#Y-m-d h:i:sA#";
+				$this->sysDate = "FORMAT(NOW,'yyyy-mm-dd')";
+				$this->sysTimeStamp = 'NOW';
+                $this->hasTop = 'top';
+				$this->hasTransactions = false;
+				$this->_canPrepareSP = true;  // For MS Access only.
+				break;
+			case 'visual foxpro':
+				$this->databaseType = 'odbtp_vfp';
+				$this->fmtDate = "{^Y-m-d}";
+				$this->fmtTimeStamp = "{^Y-m-d, h:i:sA}";
+				$this->sysDate = 'date()';
+				$this->sysTimeStamp = 'datetime()';
+				$this->ansiOuter = true;
+                $this->hasTop = 'top';
+				$this->hasTransactions = false;
+				$this->replaceQuote = "'+chr(39)+'";
+				$this->true = '.T.';
+				$this->false = '.F.';
+
+				break;
+			case 'oracle':
+				$this->databaseType = 'odbtp_oci8';
+				$this->fmtDate = "'Y-m-d 00:00:00'";
+				$this->fmtTimeStamp = "'Y-m-d h:i:sA'";
+				$this->sysDate = 'TRUNC(SYSDATE)';
+				$this->sysTimeStamp = 'SYSDATE';
+				$this->hasTransactions = true;
+				$this->_bindInputArray = true;
+				$this->concat_operator = '||';
+				break;
+			case 'sybase':
+				$this->databaseType = 'odbtp_sybase';
+				$this->fmtDate = "'Y-m-d'";
+				$this->fmtTimeStamp = "'Y-m-d H:i:s'";
+				$this->sysDate = 'GetDate()';
+				$this->sysTimeStamp = 'GetDate()';
+				$this->leftOuter = '*=';
+				$this->rightOuter = '=*';
+				$this->hasInsertID = true;
+				$this->hasTransactions = true;
+				$this->identitySQL = 'select @@IDENTITY';
+				break;
+			default:
+				$this->databaseType = 'odbtp';
+				if( @odbtp_get_attr(ODB_ATTR_TXNCAPABLE, $this->_connectionID) )
+					$this->hasTransactions = true;
+				else
+					$this->hasTransactions = false;
+		}
+        @odbtp_set_attr(ODB_ATTR_FULLCOLINFO, TRUE, $this->_connectionID );
+
+		if ($this->_useUnicodeSQL )
+			@odbtp_set_attr(ODB_ATTR_UNICODESQL, TRUE, $this->_connectionID);
+
+        return true;
+	}
+
+	function _pconnect($HostOrInterface, $UserOrDSN='', $argPassword='', $argDatabase='')
+	{
+		$this->_dontPoolDBC = false;
+  		return $this->_connect($HostOrInterface, $UserOrDSN, $argPassword, $argDatabase);
+	}
+
+	function SelectDB($dbName)
+	{
+		if (!@odbtp_select_db($dbName, $this->_connectionID)) {
+			return false;
+		}
+		$this->database = $dbName;
+		$this->databaseName = $dbName; # obsolete, retained for compat with older adodb versions
+		return true;
+	}
+	
+	function &MetaTables($ttype='',$showSchema=false,$mask=false)
+	{
+	global $ADODB_FETCH_MODE;
+
+		$savem = $ADODB_FETCH_MODE;
+		$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
+		if ($this->fetchMode !== false) $savefm = $this->SetFetchMode(false);
+		
+		$arr =& $this->GetArray("||SQLTables||||$ttype");
+		
+		if (isset($savefm)) $this->SetFetchMode($savefm);
+		$ADODB_FETCH_MODE = $savem;
+
+		$arr2 = array();
+		for ($i=0; $i < sizeof($arr); $i++) {
+			if ($arr[$i][3] == 'SYSTEM TABLE' )	continue;
+			if ($arr[$i][2])
+				$arr2[] = $showSchema && $arr[$i][1]? $arr[$i][1].'.'.$arr[$i][2] : $arr[$i][2];
+		}
+		return $arr2;
+	}
+	
+	function &MetaColumns($table,$upper=true)
+	{
+	global $ADODB_FETCH_MODE;
+
+		$schema = false;
+		$this->_findschema($table,$schema);
+		if ($upper) $table = strtoupper($table);
+
+		$savem = $ADODB_FETCH_MODE;
+		$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
+		if ($this->fetchMode !== false) $savefm = $this->SetFetchMode(false);
+		
+		$rs = $this->Execute( "||SQLColumns||$schema|$table" );
+		
+		if (isset($savefm)) $this->SetFetchMode($savefm);
+		$ADODB_FETCH_MODE = $savem;
+
+		if (!$rs || $rs->EOF) {
+			$false = false;
+			return $false;
+		}
+		$retarr = array();
+		while (!$rs->EOF) {
+			//print_r($rs->fields);
+			if (strtoupper($rs->fields[2]) == $table) {
+				$fld = new ADOFieldObject();
+				$fld->name = $rs->fields[3];
+				$fld->type = $rs->fields[5];
+				$fld->max_length = $rs->fields[6];
+    			$fld->not_null = !empty($rs->fields[9]);
+ 				$fld->scale = $rs->fields[7];
+				if (isset($rs->fields[12])) // vfp does not have field 12
+	 				if (!is_null($rs->fields[12])) {
+	 					$fld->has_default = true;
+	 					$fld->default_value = $rs->fields[12];
+					}
+				$retarr[strtoupper($fld->name)] = $fld;
+			} else if (!empty($retarr))
+				break;
+			$rs->MoveNext();
+		}
+		$rs->Close();
+
+		return $retarr;
+	}
+
+	function &MetaPrimaryKeys($table, $owner='')
+	{
+	global $ADODB_FETCH_MODE;
+
+		$savem = $ADODB_FETCH_MODE;
+		$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
+		$arr =& $this->GetArray("||SQLPrimaryKeys||$owner|$table");
+		$ADODB_FETCH_MODE = $savem;
+
+		//print_r($arr);
+		$arr2 = array();
+		for ($i=0; $i < sizeof($arr); $i++) {
+			if ($arr[$i][3]) $arr2[] = $arr[$i][3];
+		}
+		return $arr2;
+	}
+
+	function &MetaForeignKeys($table, $owner='', $upper=false)
+	{
+	global $ADODB_FETCH_MODE;
+
+		$savem = $ADODB_FETCH_MODE;
+		$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
+		$constraints =& $this->GetArray("||SQLForeignKeys|||||$owner|$table");
+		$ADODB_FETCH_MODE = $savem;
+
+		$arr = false;
+		foreach($constraints as $constr) {
+			//print_r($constr);
+			$arr[$constr[11]][$constr[2]][] = $constr[7].'='.$constr[3];
+		}
+		if (!$arr) {
+			$false = false;
+			return $false;
+		}
+		
+		$arr2 = array();
+
+		foreach($arr as $k => $v) {
+			foreach($v as $a => $b) {
+				if ($upper) $a = strtoupper($a);
+				$arr2[$a] = $b;
+			}
+		}
+		return $arr2;
+	}
+
+	function BeginTrans()
+	{
+		if (!$this->hasTransactions) return false;
+		if ($this->transOff) return true;
+		$this->transCnt += 1;
+		$this->autoCommit = false;
+		if (defined('ODB_TXN_DEFAULT'))
+			$txn = ODB_TXN_DEFAULT;
+		else
+			$txn = ODB_TXN_READUNCOMMITTED;
+		$rs = @odbtp_set_attr(ODB_ATTR_TRANSACTIONS,$txn,$this->_connectionID);
+		if(!$rs) return false;
+		return true;
+	}
+
+	function CommitTrans($ok=true)
+	{
+		if ($this->transOff) return true;
+		if (!$ok) return $this->RollbackTrans();
+		if ($this->transCnt) $this->transCnt -= 1;
+		$this->autoCommit = true;
+		if( ($ret = @odbtp_commit($this->_connectionID)) )
+			$ret = @odbtp_set_attr(ODB_ATTR_TRANSACTIONS, ODB_TXN_NONE, $this->_connectionID);//set transaction off
+		return $ret;
+	}
+
+	function RollbackTrans()
+	{
+		if ($this->transOff) return true;
+		if ($this->transCnt) $this->transCnt -= 1;
+		$this->autoCommit = true;
+		if( ($ret = @odbtp_rollback($this->_connectionID)) )
+			$ret = @odbtp_set_attr(ODB_ATTR_TRANSACTIONS, ODB_TXN_NONE, $this->_connectionID);//set transaction off
+		return $ret;
+	}
+
+	function &SelectLimit($sql,$nrows=-1,$offset=-1, $inputarr=false,$secs2cache=0)
+	{
+		// TOP requires ORDER BY for Visual FoxPro
+		if( $this->odbc_driver == ODB_DRIVER_FOXPRO ) {
+			if (!preg_match('/ORDER[ \t\r\n]+BY/is',$sql)) $sql .= ' ORDER BY 1';
+		}
+		$ret =& ADOConnection::SelectLimit($sql,$nrows,$offset,$inputarr,$secs2cache);
+		return $ret;
+	}
+
+	function Prepare($sql)
+	{
+		if (! $this->_bindInputArray) return $sql; // no binding
+		$stmt = @odbtp_prepare($sql,$this->_connectionID);
+		if (!$stmt) {
+		//	print "Prepare Error for ($sql) ".$this->ErrorMsg()."<br>";
+			return $sql;
+		}
+		return array($sql,$stmt,false);
+	}
+
+	function PrepareSP($sql)
+	{
+		if (!$this->_canPrepareSP) return $sql; // Can't prepare procedures
+
+		$stmt = @odbtp_prepare_proc($sql,$this->_connectionID);
+		if (!$stmt) return false;
+		return array($sql,$stmt);
+	}
+
+	/*
+	Usage:
+		$stmt = $db->PrepareSP('SP_RUNSOMETHING'); -- takes 2 params, @myid and @group
+
+		# note that the parameter does not have @ in front!
+		$db->Parameter($stmt,$id,'myid');
+		$db->Parameter($stmt,$group,'group',false,64);
+		$db->Parameter($stmt,$group,'photo',false,100000,ODB_BINARY);
+		$db->Execute($stmt);
+
+		@param $stmt Statement returned by Prepare() or PrepareSP().
+		@param $var PHP variable to bind to. Can set to null (for isNull support).
+		@param $name Name of stored procedure variable name to bind to.
+		@param [$isOutput] Indicates direction of parameter 0/false=IN  1=OUT  2= IN/OUT. This is ignored in odbtp.
+		@param [$maxLen] Holds an maximum length of the variable.
+		@param [$type] The data type of $var. Legal values depend on driver.
+
+		See odbtp_attach_param documentation at http://odbtp.sourceforge.net.
+	*/
+	function Parameter(&$stmt, &$var, $name, $isOutput=false, $maxLen=0, $type=0)
+	{
+		if ( $this->odbc_driver == ODB_DRIVER_JET ) {
+			$name = '['.$name.']';
+			if( !$type && $this->_useUnicodeSQL
+				&& @odbtp_param_bindtype($stmt[1], $name) == ODB_CHAR )
+			{
+				$type = ODB_WCHAR;
+			}
+		}
+		else {
+			$name = '@'.$name;
+		}
+		return @odbtp_attach_param($stmt[1], $name, $var, $type, $maxLen);
+	}
+
+	/*
+		Insert a null into the blob field of the table first.
+		Then use UpdateBlob to store the blob.
+
+		Usage:
+
+		$conn->Execute('INSERT INTO blobtable (id, blobcol) VALUES (1, null)');
+		$conn->UpdateBlob('blobtable','blobcol',$blob,'id=1');
+	*/
+
+	function UpdateBlob($table,$column,$val,$where,$blobtype='image')
+	{
+		$sql = "UPDATE $table SET $column = ? WHERE $where";
+		if( !($stmt = @odbtp_prepare($sql, $this->_connectionID)) )
+			return false;
+		if( !@odbtp_input( $stmt, 1, ODB_BINARY, 1000000, $blobtype ) )
+			return false;
+		if( !@odbtp_set( $stmt, 1, $val ) )
+			return false;
+		return @odbtp_execute( $stmt ) != false;
+	}
+
+	function IfNull( $field, $ifNull )
+	{
+		switch( $this->odbc_driver ) {
+			case ODB_DRIVER_MSSQL:
+				return " ISNULL($field, $ifNull) ";
+			case ODB_DRIVER_JET:
+				return " IIF(IsNull($field), $ifNull, $field) ";
+		}
+		return " CASE WHEN $field is null THEN $ifNull ELSE $field END ";
+	}
+
+	function _query($sql,$inputarr=false)
+	{
+	global $php_errormsg;
+	
+ 		if ($inputarr) {
+			if (is_array($sql)) {
+				$stmtid = $sql[1];
+			} else {
+				$stmtid = @odbtp_prepare($sql,$this->_connectionID);
+				if ($stmtid == false) {
+					$this->_errorMsg = $php_errormsg;
+					return false;
+				}
+			}
+			$num_params = @odbtp_num_params( $stmtid );
+			for( $param = 1; $param <= $num_params; $param++ ) {
+				@odbtp_input( $stmtid, $param );
+				@odbtp_set( $stmtid, $param, $inputarr[$param-1] );
+			}
+			if (!@odbtp_execute($stmtid) ) {
+				return false;
+			}
+		} else if (is_array($sql)) {
+			$stmtid = $sql[1];
+			if (!@odbtp_execute($stmtid)) {
+				return false;
+			}
+		} else {
+			$stmtid = odbtp_query($sql,$this->_connectionID);
+   		}
+		$this->_lastAffectedRows = 0;
+		if ($stmtid) {
+				$this->_lastAffectedRows = @odbtp_affected_rows($stmtid);
+		}
+        return $stmtid;
+	}
+
+	function _close()
+	{
+		$ret = @odbtp_close($this->_connectionID);
+		$this->_connectionID = false;
+		return $ret;
+	}
+}
+
+class ADORecordSet_odbtp extends ADORecordSet {
+
+	var $databaseType = 'odbtp';
+	var $canSeek = true;
+
+	function ADORecordSet_odbtp($queryID,$mode=false)
+	{
+		if ($mode === false) {
+			global $ADODB_FETCH_MODE;
+			$mode = $ADODB_FETCH_MODE;
+		}
+		$this->fetchMode = $mode;
+		$this->ADORecordSet($queryID);
+	}
+
+	function _initrs()
+	{
+		$this->_numOfFields = @odbtp_num_fields($this->_queryID);
+		if (!($this->_numOfRows = @odbtp_num_rows($this->_queryID)))
+			$this->_numOfRows = -1;
+
+		if (!$this->connection->_useUnicodeSQL) return;
+
+		if ($this->connection->odbc_driver == ODB_DRIVER_JET) {
+			if (!@odbtp_get_attr(ODB_ATTR_MAPCHARTOWCHAR,
+			                     $this->connection->_connectionID))
+			{
+				for ($f = 0; $f < $this->_numOfFields; $f++) {
+					if (@odbtp_field_bindtype($this->_queryID, $f) == ODB_CHAR)
+						@odbtp_bind_field($this->_queryID, $f, ODB_WCHAR);
+				}
+			}
+		}
+	}
+
+	function &FetchField($fieldOffset = 0)
+	{
+		$off=$fieldOffset; // offsets begin at 0
+		$o= new ADOFieldObject();
+		$o->name = @odbtp_field_name($this->_queryID,$off);
+		$o->type = @odbtp_field_type($this->_queryID,$off);
+        $o->max_length = @odbtp_field_length($this->_queryID,$off);
+		if (ADODB_ASSOC_CASE == 0) $o->name = strtolower($o->name);
+		else if (ADODB_ASSOC_CASE == 1) $o->name = strtoupper($o->name);
+		return $o;
+	}
+
+	function _seek($row)
+	{
+		return @odbtp_data_seek($this->_queryID, $row);
+	}
+
+	function fields($colname)
+	{
+		if ($this->fetchMode & ADODB_FETCH_ASSOC) return $this->fields[$colname];
+
+		if (!$this->bind) {
+			$this->bind = array();
+			for ($i=0; $i < $this->_numOfFields; $i++) {
+				$name = @odbtp_field_name( $this->_queryID, $i );
+				$this->bind[strtoupper($name)] = $i;
+			}
+		}
+		return $this->fields[$this->bind[strtoupper($colname)]];
+	}
+
+	function _fetch_odbtp($type=0)
+	{
+		switch ($this->fetchMode) {
+			case ADODB_FETCH_NUM:
+				$this->fields = @odbtp_fetch_row($this->_queryID, $type);
+				break;
+			case ADODB_FETCH_ASSOC:
+				$this->fields = @odbtp_fetch_assoc($this->_queryID, $type);
+				break;
+            default:
+				$this->fields = @odbtp_fetch_array($this->_queryID, $type);
+		}
+		if ($this->databaseType = 'odbtp_vfp') {
+			if ($this->fields)
+			foreach($this->fields as $k => $v) {
+				if (strncmp($v,'1899-12-30',10) == 0) $this->fields[$k] = '';
+			}
+		}
+		return is_array($this->fields);
+	}
+
+	function _fetch()
+	{
+		return $this->_fetch_odbtp();
+	}
+
+	function MoveFirst()
+	{
+		if (!$this->_fetch_odbtp(ODB_FETCH_FIRST)) return false;
+		$this->EOF = false;
+		$this->_currentRow = 0;
+		return true;
+    }
+
+	function MoveLast()
+	{
+		if (!$this->_fetch_odbtp(ODB_FETCH_LAST)) return false;
+		$this->EOF = false;
+		$this->_currentRow = $this->_numOfRows - 1;
+		return true;
+	}
+
+	function NextRecordSet()
+	{
+		if (!@odbtp_next_result($this->_queryID)) return false;
+		$this->_inited = false;
+		$this->bind = false;
+		$this->_currentRow = -1;
+		$this->Init();
+		return true;
+	}
+
+	function _close()
+	{
+		return @odbtp_free_query($this->_queryID);
+	}
+}
+
+class ADORecordSet_odbtp_mssql extends ADORecordSet_odbtp {
+
+	var $databaseType = 'odbtp_mssql';
+
+	function ADORecordSet_odbtp_mssql($id,$mode=false)
+	{
+		return $this->ADORecordSet_odbtp($id,$mode);
+	}
+}
+
+class ADORecordSet_odbtp_access extends ADORecordSet_odbtp {
+
+	var $databaseType = 'odbtp_access';
+
+	function ADORecordSet_odbtp_access($id,$mode=false)
+	{
+		return $this->ADORecordSet_odbtp($id,$mode);
+	}
+}
+
+class ADORecordSet_odbtp_vfp extends ADORecordSet_odbtp {
+
+	var $databaseType = 'odbtp_vfp';
+
+	function ADORecordSet_odbtp_vfp($id,$mode=false)
+	{
+		return $this->ADORecordSet_odbtp($id,$mode);
+	}
+}
+
+class ADORecordSet_odbtp_oci8 extends ADORecordSet_odbtp {
+
+	var $databaseType = 'odbtp_oci8';
+
+	function ADORecordSet_odbtp_oci8($id,$mode=false)
+	{
+		return $this->ADORecordSet_odbtp($id,$mode);
+	}
+}
+
+class ADORecordSet_odbtp_sybase extends ADORecordSet_odbtp {
+
+	var $databaseType = 'odbtp_sybase';
+
+	function ADORecordSet_odbtp_sybase($id,$mode=false)
+	{
+		return $this->ADORecordSet_odbtp($id,$mode);
+	}
+}
+?>
Index: /Dev/trunk/rdfapi/util/adodb/drivers/adodb-odbtp_unicode.inc.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/drivers/adodb-odbtp_unicode.inc.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/drivers/adodb-odbtp_unicode.inc.php	(revision 12)
@@ -0,0 +1,39 @@
+<?php
+/*
+	V4.94 23 Jan 2007  (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
+  Released under both BSD license and Lesser GPL library license.
+  Whenever there is any discrepancy between the two licenses,
+  the BSD license will take precedence. See License.txt.
+  Set tabs to 4 for best viewing.
+  Latest version is available at http://adodb.sourceforge.net
+*/
+
+// Code contributed by "Robert Twitty" <rtwitty#neutron.ushmm.org>
+
+// security - hide paths
+if (!defined('ADODB_DIR')) die();
+
+/*
+    Because the ODBTP server sends and reads UNICODE text data using UTF-8
+    encoding, the following HTML meta tag must be included within the HTML
+    head section of every HTML form and script page:
+
+    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
+
+    Also, all SQL query strings must be submitted as UTF-8 encoded text.
+*/
+
+if (!defined('_ADODB_ODBTP_LAYER')) {
+	include(ADODB_DIR."/drivers/adodb-odbtp.inc.php");
+}
+
+class ADODB_odbtp_unicode extends ADODB_odbtp {
+	var $databaseType = 'odbtp';
+	var $_useUnicodeSQL = true;
+
+	function ADODB_odbtp_unicode()
+	{
+		$this->ADODB_odbtp();
+	}
+}
+?>
Index: /Dev/trunk/rdfapi/util/adodb/drivers/adodb-oracle.inc.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/drivers/adodb-oracle.inc.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/drivers/adodb-oracle.inc.php	(revision 12)
@@ -0,0 +1,338 @@
+<?php
+/*
+V4.94 23 Jan 2007  (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence.
+
+  Latest version is available at http://adodb.sourceforge.net
+  
+  Oracle data driver. Requires Oracle client. Works on Windows and Unix and Oracle 7.
+  
+  If you are using Oracle 8 or later, use the oci8 driver which is much better and more reliable.
+*/
+
+// security - hide paths
+if (!defined('ADODB_DIR')) die();
+
+class ADODB_oracle extends ADOConnection {
+	var $databaseType = "oracle";
+	var $replaceQuote = "''"; // string to use to replace quotes
+	var $concat_operator='||';
+	var $_curs;
+	var $_initdate = true; // init date to YYYY-MM-DD
+	var $metaTablesSQL = 'select table_name from cat';	
+	var $metaColumnsSQL = "select cname,coltype,width from col where tname='%s' order by colno";
+	var $sysDate = "TO_DATE(TO_CHAR(SYSDATE,'YYYY-MM-DD'),'YYYY-MM-DD')";
+	var $sysTimeStamp = 'SYSDATE';
+	var $connectSID = true;
+	
+	function ADODB_oracle() 
+	{
+	}
+
+	// format and return date string in database date format
+	function DBDate($d)
+	{
+		if (is_string($d)) $d = ADORecordSet::UnixDate($d);
+		return 'TO_DATE('.adodb_date($this->fmtDate,$d).",'YYYY-MM-DD')";
+	}
+	
+	// format and return date string in database timestamp format
+	function DBTimeStamp($ts)
+	{
+
+		if (is_string($ts)) $d = ADORecordSet::UnixTimeStamp($ts);
+		return 'TO_DATE('.adodb_date($this->fmtTimeStamp,$ts).",'RRRR-MM-DD, HH:MI:SS AM')";
+	}
+	
+	
+	function BindDate($d)
+	{
+		$d = ADOConnection::DBDate($d);
+		if (strncmp($d,"'",1)) return $d;
+		
+		return substr($d,1,strlen($d)-2);
+	}
+	
+	function BindTimeStamp($d)
+	{
+		$d = ADOConnection::DBTimeStamp($d);
+		if (strncmp($d,"'",1)) return $d;
+		
+		return substr($d,1,strlen($d)-2);
+	}
+	
+
+	
+	function BeginTrans()
+	{	  
+		 $this->autoCommit = false;
+		 ora_commitoff($this->_connectionID);
+		 return true;
+	}
+
+	
+	function CommitTrans($ok=true) 
+	{ 
+		   if (!$ok) return $this->RollbackTrans();
+		   $ret = ora_commit($this->_connectionID);
+		   ora_commiton($this->_connectionID);
+		   return $ret;
+	}
+
+	
+	function RollbackTrans()
+	{
+		$ret = ora_rollback($this->_connectionID);
+		ora_commiton($this->_connectionID);
+		return $ret;
+	}
+
+
+	/* there seems to be a bug in the oracle extension -- always returns ORA-00000 - no error */
+	function ErrorMsg() 
+ 	{   
+        if ($this->_errorMsg !== false) return $this->_errorMsg;
+
+        if (is_resource($this->_curs)) $this->_errorMsg = @ora_error($this->_curs);
+ 		if (empty($this->_errorMsg)) $this->_errorMsg = @ora_error($this->_connectionID);
+		return $this->_errorMsg;
+	}
+
+ 
+	function ErrorNo() 
+	{
+		if ($this->_errorCode !== false) return $this->_errorCode;
+
+		if (is_resource($this->_curs)) $this->_errorCode = @ora_errorcode($this->_curs);
+		if (empty($this->_errorCode)) $this->_errorCode = @ora_errorcode($this->_connectionID);
+        return $this->_errorCode;
+	}
+
+	
+
+		// returns true or false
+		function _connect($argHostname, $argUsername, $argPassword, $argDatabasename, $mode=0)
+		{
+			if (!function_exists('ora_plogon')) return null;
+				
+            // <G. Giunta 2003/03/03/> Reset error messages before connecting
+            $this->_errorMsg = false;
+		    $this->_errorCode = false;
+        
+            // G. Giunta 2003/08/13 - This looks danegrously suspicious: why should we want to set
+            // the oracle home to the host name of remote DB?
+//			if ($argHostname) putenv("ORACLE_HOME=$argHostname");
+
+			if($argHostname) { // code copied from version submitted for oci8 by Jorma Tuomainen <jorma.tuomainen@ppoy.fi>
+				if (empty($argDatabasename)) $argDatabasename = $argHostname;
+				else {
+					if(strpos($argHostname,":")) {
+						$argHostinfo=explode(":",$argHostname);
+						$argHostname=$argHostinfo[0];
+						$argHostport=$argHostinfo[1];
+					} else {
+						$argHostport="1521";
+					}
+
+
+					if ($this->connectSID) {
+						$argDatabasename="(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=".$argHostname
+						.")(PORT=$argHostport))(CONNECT_DATA=(SID=$argDatabasename)))";
+					} else
+						$argDatabasename="(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=".$argHostname
+						.")(PORT=$argHostport))(CONNECT_DATA=(SERVICE_NAME=$argDatabasename)))";
+				}
+
+			}
+
+			if ($argDatabasename) $argUsername .= "@$argDatabasename";
+
+		//if ($argHostname) print "<p>Connect: 1st argument should be left blank for $this->databaseType</p>";
+			if ($mode = 1)
+				$this->_connectionID = ora_plogon($argUsername,$argPassword);
+			else
+				$this->_connectionID = ora_logon($argUsername,$argPassword);
+			if ($this->_connectionID === false) return false;
+			if ($this->autoCommit) ora_commiton($this->_connectionID);
+			if ($this->_initdate) {
+				$rs = $this->_query("ALTER SESSION SET NLS_DATE_FORMAT='YYYY-MM-DD'");
+				if ($rs) ora_close($rs);
+			}
+
+			return true;
+		}
+
+
+		// returns true or false
+		function _pconnect($argHostname, $argUsername, $argPassword, $argDatabasename)
+		{
+			return $this->_connect($argHostname, $argUsername, $argPassword, $argDatabasename, 1);
+		}
+
+
+		// returns query ID if successful, otherwise false
+		function _query($sql,$inputarr=false)
+		{
+            // <G. Giunta 2003/03/03/> Reset error messages before executing
+            $this->_errorMsg = false;
+		    $this->_errorCode = false;
+
+			$curs = ora_open($this->_connectionID);
+		 
+		 	if ($curs === false) return false;
+			$this->_curs = $curs;
+			if (!ora_parse($curs,$sql)) return false;
+			if (ora_exec($curs)) return $curs;
+            // <G. Giunta 2004/03/03> before we close the cursor, we have to store the error message
+            // that we can obtain ONLY from the cursor (and not from the connection)
+            $this->_errorCode = @ora_errorcode($curs);
+            $this->_errorMsg = @ora_error($curs);
+            // </G. Giunta 2004/03/03>            
+		 	@ora_close($curs);
+			return false;
+		}
+
+
+		// returns true or false
+		function _close()
+		{
+			return @ora_logoff($this->_connectionID);
+		}
+
+
+
+}
+
+
+/*--------------------------------------------------------------------------------------
+		 Class Name: Recordset
+--------------------------------------------------------------------------------------*/
+
+class ADORecordset_oracle extends ADORecordSet {
+
+	var $databaseType = "oracle";
+	var $bind = false;
+
+	function ADORecordset_oracle($queryID,$mode=false)
+	{
+		
+		if ($mode === false) { 
+			global $ADODB_FETCH_MODE;
+			$mode = $ADODB_FETCH_MODE;
+		}
+		$this->fetchMode = $mode;
+		
+		$this->_queryID = $queryID;
+	
+		$this->_inited = true;
+		$this->fields = array();
+		if ($queryID) {
+			$this->_currentRow = 0;
+			$this->EOF = !$this->_fetch();
+			@$this->_initrs();
+		} else {
+			$this->_numOfRows = 0;
+			$this->_numOfFields = 0;
+			$this->EOF = true;
+		}
+		
+		return $this->_queryID;
+	}
+
+
+
+	   /*		Returns: an object containing field information.
+			   Get column information in the Recordset object. fetchField() can be used in order to obtain information about
+			   fields in a certain query result. If the field offset isn't specified, the next field that wasn't yet retrieved by
+			   fetchField() is retrieved.		*/
+
+	   function &FetchField($fieldOffset = -1)
+	   {
+			$fld = new ADOFieldObject;
+			$fld->name = ora_columnname($this->_queryID, $fieldOffset);
+			$fld->type = ora_columntype($this->_queryID, $fieldOffset);
+			$fld->max_length = ora_columnsize($this->_queryID, $fieldOffset);
+			return $fld;
+	   }
+
+	/* Use associative array to get fields array */
+	function Fields($colname)
+	{
+		if (!$this->bind) {
+			$this->bind = array();
+			for ($i=0; $i < $this->_numOfFields; $i++) {
+				$o = $this->FetchField($i);
+				$this->bind[strtoupper($o->name)] = $i;
+			}
+		}
+		
+		 return $this->fields[$this->bind[strtoupper($colname)]];
+	}
+	
+   function _initrs()
+   {
+		   $this->_numOfRows = -1;
+		   $this->_numOfFields = @ora_numcols($this->_queryID);
+   }
+
+
+   function _seek($row)
+   {
+		   return false;
+   }
+
+   function _fetch($ignore_fields=false) {
+// should remove call by reference, but ora_fetch_into requires it in 4.0.3pl1
+		if ($this->fetchMode & ADODB_FETCH_ASSOC)
+			return @ora_fetch_into($this->_queryID,&$this->fields,ORA_FETCHINTO_NULLS|ORA_FETCHINTO_ASSOC);
+   		else 
+			return @ora_fetch_into($this->_queryID,&$this->fields,ORA_FETCHINTO_NULLS);
+   }
+
+   /*		close() only needs to be called if you are worried about using too much memory while your script
+		   is running. All associated result memory for the specified result identifier will automatically be freed.		*/
+
+   function _close() 
+{
+		   return @ora_close($this->_queryID);
+   }
+
+	function MetaType($t,$len=-1)
+	{
+		if (is_object($t)) {
+			$fieldobj = $t;
+			$t = $fieldobj->type;
+			$len = $fieldobj->max_length;
+		}
+		
+		switch (strtoupper($t)) {
+		case 'VARCHAR':
+		case 'VARCHAR2':
+		case 'CHAR':
+		case 'VARBINARY':
+		case 'BINARY':
+				if ($len <= $this->blobSize) return 'C';
+		case 'LONG':
+		case 'LONG VARCHAR':
+		case 'CLOB':
+		return 'X';
+		case 'LONG RAW':
+		case 'LONG VARBINARY':
+		case 'BLOB':
+				return 'B';
+		
+		case 'DATE': return 'D';
+		
+		//case 'T': return 'T';
+		
+		case 'BIT': return 'L';
+		case 'INT': 
+		case 'SMALLINT':
+		case 'INTEGER': return 'I';
+		default: return 'N';
+		}
+	}
+}
+?>
Index: /Dev/trunk/rdfapi/util/adodb/drivers/adodb-pdo.inc.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/drivers/adodb-pdo.inc.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/drivers/adodb-pdo.inc.php	(revision 12)
@@ -0,0 +1,569 @@
+<?php
+/* 
+V4.94 23 Jan 2007  (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence. 
+Set tabs to 4 for best viewing.
+  
+  Latest version is available at http://adodb.sourceforge.net
+  
+  Requires ODBC. Works on Windows and Unix.
+
+	Problems: 
+		Where is float/decimal type in pdo_param_type
+		LOB handling for CLOB/BLOB differs significantly
+*/
+// security - hide paths
+if (!defined('ADODB_DIR')) die();
+
+
+/*
+enum pdo_param_type {
+PDO::PARAM_NULL, 0
+
+/* int as in long (the php native int type).
+ * If you mark a column as an int, PDO expects get_col to return
+ * a pointer to a long 
+PDO::PARAM_INT, 1
+
+/* get_col ptr should point to start of the string buffer 
+PDO::PARAM_STR, 2
+
+/* get_col: when len is 0 ptr should point to a php_stream *,
+ * otherwise it should behave like a string. Indicate a NULL field
+ * value by setting the ptr to NULL 
+PDO::PARAM_LOB, 3
+
+/* get_col: will expect the ptr to point to a new PDOStatement object handle,
+ * but this isn't wired up yet 
+PDO::PARAM_STMT, 4 /* hierarchical result set 
+
+/* get_col ptr should point to a zend_bool 
+PDO::PARAM_BOOL, 5
+
+
+/* magic flag to denote a parameter as being input/output 
+PDO::PARAM_INPUT_OUTPUT = 0x80000000
+};
+*/
+	
+function adodb_pdo_type($t)
+{
+	switch($t) {
+	case 2: return 'VARCHAR';
+	case 3: return 'BLOB';
+	default: return 'NUMERIC';
+	}
+}
+	 
+/*--------------------------------------------------------------------------------------
+--------------------------------------------------------------------------------------*/
+
+////////////////////////////////////////////////
+
+
+
+class ADODB_pdo_base extends ADODB_pdo {
+
+	var $sysDate = "'?'";
+	var $sysTimeStamp = "'?'";
+	
+
+	function _init($parentDriver)
+	{
+		$parentDriver->_bindInputArray = true;
+		#$parentDriver->_connectionID->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY,true);
+	}
+	
+	function ServerInfo()
+	{
+		return ADOConnection::ServerInfo();
+	}
+	
+	function SelectLimit($sql,$nrows=-1,$offset=-1,$inputarr=false,$secs2cache=0)
+	{
+		$ret = ADOConnection::SelectLimit($sql,$nrows,$offset,$inputarr,$secs2cache);
+		return $ret;
+	}
+	
+	function MetaTables()
+	{
+		return false;
+	}
+	
+	function MetaColumns()
+	{
+		return false;
+	}
+}
+
+
+class ADODB_pdo extends ADOConnection {
+	var $databaseType = "pdo";	
+	var $dataProvider = "pdo";
+	var $fmtDate = "'Y-m-d'";
+	var $fmtTimeStamp = "'Y-m-d, h:i:sA'";
+	var $replaceQuote = "''"; // string to use to replace quotes
+	var $hasAffectedRows = true;
+	var $_bindInputArray = true;	
+	var $_genSeqSQL = "create table %s (id integer)";
+	var $_autocommit = true;
+	var $_haserrorfunctions = true;
+	var $_lastAffectedRows = 0;
+	
+	var $_errormsg = false;
+	var $_errorno = false;
+	
+	var $dsnType = '';
+	var $stmt = false;
+	
+	function ADODB_pdo()
+	{
+	}
+	
+	function _UpdatePDO()
+	{
+		$d = &$this->_driver;
+		$this->fmtDate = $d->fmtDate;
+		$this->fmtTimeStamp = $d->fmtTimeStamp;
+		$this->replaceQuote = $d->replaceQuote;
+		$this->sysDate = $d->sysDate;
+		$this->sysTimeStamp = $d->sysTimeStamp;
+		$this->random = $d->random;
+		$this->concat_operator = $d->concat_operator;
+		$this->nameQuote = $d->nameQuote;
+				
+		$this->hasGenID = $d->hasGenID;
+		$this->_genIDSQL = $d->_genIDSQL;
+		$this->_genSeqSQL = $d->_genSeqSQL;
+		$this->_dropSeqSQL = $d->_dropSeqSQL;
+
+		$d->_init($this);
+	}
+	
+	function Time()
+	{
+		if (!empty($this->_driver->_hasdual)) $sql = "select $this->sysTimeStamp from dual";
+		else $sql = "select $this->sysTimeStamp";
+		
+		$rs =& $this->_Execute($sql);
+		if ($rs && !$rs->EOF) return $this->UnixTimeStamp(reset($rs->fields));
+		
+		return false;
+	}
+	
+	// returns true or false
+	function _connect($argDSN, $argUsername, $argPassword, $argDatabasename, $persist=false)
+	{
+		$at = strpos($argDSN,':');
+		$this->dsnType = substr($argDSN,0,$at);
+
+		if ($argDatabasename) {
+			$argDSN .= ';dbname='.$argDatabasename;
+		}
+		try {
+			$this->_connectionID = new PDO($argDSN, $argUsername, $argPassword);
+		} catch (Exception $e) {
+			$this->_connectionID = false;
+			$this->_errorno = -1;
+			//var_dump($e);
+			$this->_errormsg = 'Connection attempt failed: '.$e->getMessage();
+			return false;
+		}
+		
+		if ($this->_connectionID) {
+			switch(ADODB_ASSOC_CASE){
+			case 0: $m = PDO::CASE_LOWER; break;
+			case 1: $m = PDO::CASE_UPPER; break;
+			default:
+			case 2: $m = PDO::CASE_NATURAL; break;
+			}
+			
+			//$this->_connectionID->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_SILENT );
+			$this->_connectionID->setAttribute(PDO::ATTR_CASE,$m);
+			
+			$class = 'ADODB_pdo_'.$this->dsnType;
+			//$this->_connectionID->setAttribute(PDO::ATTR_AUTOCOMMIT,true);
+			switch($this->dsnType) {
+			case 'oci':
+			case 'mysql':
+			case 'pgsql':
+			case 'mssql':
+				include_once(ADODB_DIR.'/drivers/adodb-pdo_'.$this->dsnType.'.inc.php');
+				break;
+			}
+			if (class_exists($class))
+				$this->_driver = new $class();
+			else
+				$this->_driver = new ADODB_pdo_base();
+			
+			$this->_driver->_connectionID = $this->_connectionID;
+			$this->_UpdatePDO();
+			return true;
+		}
+		$this->_driver = new ADODB_pdo_base();
+		return false;
+	}
+	
+	// returns true or false
+	function _pconnect($argDSN, $argUsername, $argPassword, $argDatabasename)
+	{
+		return $this->_connect($argDSN, $argUsername, $argPassword, $argDatabasename, true);
+	}
+	
+	/*------------------------------------------------------------------------------*/
+	
+	
+	function SelectLimit($sql,$nrows=-1,$offset=-1,$inputarr=false,$secs2cache=0) 
+	{	
+		$save = $this->_driver->fetchMode;
+		$this->_driver->fetchMode = $this->fetchMode;
+	 	$this->_driver->debug = $this->debug;
+		$ret = $this->_driver->SelectLimit($sql,$nrows,$offset,$inputarr,$secs2cache);
+		$this->_driver->fetchMode = $save;
+		return $ret;
+	}
+	
+	
+	function ServerInfo()
+	{
+		return $this->_driver->ServerInfo();
+	}
+	
+	function MetaTables($ttype=false,$showSchema=false,$mask=false)
+	{
+		return $this->_driver->MetaTables($ttype,$showSchema,$mask);
+	}
+	
+	function MetaColumns($table,$normalize=true)
+	{
+		return $this->_driver->MetaColumns($table,$normalize);
+	}
+	
+	function InParameter(&$stmt,&$var,$name,$maxLen=4000,$type=false)
+	{
+		$obj = $stmt[1];
+		if ($type) $obj->bindParam($name,$var,$type,$maxLen);
+		else $obj->bindParam($name, $var);
+	}
+	
+	
+	function ErrorMsg()
+	{
+		if ($this->_errormsg !== false) return $this->_errormsg;
+		if (!empty($this->_stmt)) $arr = $this->_stmt->errorInfo();
+		else if (!empty($this->_connectionID)) $arr = $this->_connectionID->errorInfo();
+		else return 'No Connection Established';
+		
+		
+		if ($arr) {
+		 	if (sizeof($arr)<2) return '';
+			if ((integer)$arr[1]) return $arr[2];
+			else return '';
+		} else return '-1';
+	}
+	
+
+	function ErrorNo()
+	{
+		if ($this->_errorno !== false) return $this->_errorno;
+		if (!empty($this->_stmt)) $err = $this->_stmt->errorCode();
+		else if (!empty($this->_connectionID)) {
+			$arr = $this->_connectionID->errorInfo();
+			if (isset($arr[0])) $err = $arr[0];
+			else $err = -1;
+		} else
+			return 0;
+			
+		if ($err == '00000') return 0; // allows empty check
+		return $err;
+	}
+
+	function BeginTrans()
+	{	
+		if (!$this->hasTransactions) return false;
+		if ($this->transOff) return true; 
+		$this->transCnt += 1;
+		$this->_autocommit = false;
+		$this->_connectionID->setAttribute(PDO::ATTR_AUTOCOMMIT,false);
+		return $this->_connectionID->beginTransaction();
+	}
+	
+	function CommitTrans($ok=true) 
+	{ 
+		if (!$this->hasTransactions) return false;
+		if ($this->transOff) return true; 
+		if (!$ok) return $this->RollbackTrans();
+		if ($this->transCnt) $this->transCnt -= 1;
+		$this->_autocommit = true;
+		
+		$ret = $this->_connectionID->commit();
+		$this->_connectionID->setAttribute(PDO::ATTR_AUTOCOMMIT,true);
+		return $ret;
+	}
+	
+	function RollbackTrans()
+	{
+		if (!$this->hasTransactions) return false;
+		if ($this->transOff) return true; 
+		if ($this->transCnt) $this->transCnt -= 1;
+		$this->_autocommit = true;
+		
+		$ret = $this->_connectionID->rollback();
+		$this->_connectionID->setAttribute(PDO::ATTR_AUTOCOMMIT,true);
+		return $ret;
+	}
+	
+	function Prepare($sql)
+	{
+		$this->_stmt = $this->_connectionID->prepare($sql);
+		if ($this->_stmt) return array($sql,$this->_stmt);
+		
+		return false;
+	}
+	
+	function PrepareStmt($sql)
+	{
+		$stmt = $this->_connectionID->prepare($sql);
+		if (!$stmt) return false;
+		$obj = new ADOPDOStatement($stmt,$this);
+		return $obj;
+	}
+	
+	
+	/* returns queryID or false */
+	function _query($sql,$inputarr=false) 
+	{
+		if (is_array($sql)) {
+			$stmt = $sql[1];
+		} else {
+			$stmt = $this->_connectionID->prepare($sql);
+		}
+		#adodb_backtrace();
+		#var_dump($this->_bindInputArray);
+		if ($stmt) {
+			$this->_driver->debug = $this->debug;
+			if ($inputarr) $ok = $stmt->execute($inputarr);
+			else $ok = $stmt->execute();
+		} 
+		
+		
+		$this->_errormsg = false;
+		$this->_errorno = false;
+			
+		if ($ok) {
+			$this->_stmt = $stmt;
+			return $stmt;
+		}
+		
+		if ($stmt) {
+			
+			$arr = $stmt->errorinfo();
+			if ((integer)$arr[1]) {
+				$this->_errormsg = $arr[2];
+				$this->_errorno = $arr[1];
+			}
+
+		} else {
+			$this->_errormsg = false;
+			$this->_errorno = false;
+		}
+		return false;
+	}
+
+	// returns true or false
+	function _close()
+	{
+		$this->_stmt = false;
+		return true;
+	}
+
+	function _affectedrows()
+	{
+		return ($this->_stmt) ? $this->_stmt->rowCount() : 0;
+	}
+	
+	function _insertid()
+	{
+		return ($this->_connectionID) ? $this->_connectionID->lastInsertId() : 0;
+	}
+}
+
+class ADOPDOStatement {
+
+	var $databaseType = "pdo";		
+	var $dataProvider = "pdo";
+	var $_stmt;
+	var $_connectionID;
+	
+	function ADOPDOStatement($stmt,$connection)
+	{
+		$this->_stmt = $stmt;
+		$this->_connectionID = $connection;
+	}
+	
+	function Execute($inputArr=false)
+	{
+		$savestmt = $this->_connectionID->_stmt;
+		$rs = $this->_connectionID->Execute(array(false,$this->_stmt),$inputArr);
+		$this->_connectionID->_stmt = $savestmt;
+		return $rs;
+	}
+	
+	function InParameter(&$var,$name,$maxLen=4000,$type=false)
+	{
+
+		if ($type) $this->_stmt->bindParam($name,$var,$type,$maxLen);
+		else $this->_stmt->bindParam($name, $var);
+	}
+	
+	function Affected_Rows()
+	{
+		return ($this->_stmt) ? $this->_stmt->rowCount() : 0;
+	}
+	
+	function ErrorMsg()
+	{
+		if ($this->_stmt) $arr = $this->_stmt->errorInfo();
+		else $arr = $this->_connectionID->errorInfo();
+
+		if (is_array($arr)) {
+			if ((integer) $arr[0] && isset($arr[2])) return $arr[2];
+			else return '';
+		} else return '-1';
+	}
+	
+	function NumCols()
+	{
+		return ($this->_stmt) ? $this->_stmt->columnCount() : 0;
+	}
+	
+	function ErrorNo()
+	{
+		if ($this->_stmt) return $this->_stmt->errorCode();
+		else return $this->_connectionID->errorInfo();
+	}
+}
+
+/*--------------------------------------------------------------------------------------
+	 Class Name: Recordset
+--------------------------------------------------------------------------------------*/
+
+class ADORecordSet_pdo extends ADORecordSet {	
+	
+	var $bind = false;
+	var $databaseType = "pdo";		
+	var $dataProvider = "pdo";
+	
+	function ADORecordSet_pdo($id,$mode=false)
+	{
+		if ($mode === false) {  
+			global $ADODB_FETCH_MODE;
+			$mode = $ADODB_FETCH_MODE;
+		}
+		$this->adodbFetchMode = $mode;
+		switch($mode) {
+		case ADODB_FETCH_NUM: $mode = PDO::FETCH_NUM; break;
+		case ADODB_FETCH_ASSOC:  $mode = PDO::FETCH_ASSOC; break;
+		
+		case ADODB_FETCH_BOTH: 
+		default: $mode = PDO::FETCH_BOTH; break;
+		}
+		$this->fetchMode = $mode;
+		
+		$this->_queryID = $id;
+		$this->ADORecordSet($id);
+	}
+
+	
+	function Init()
+	{
+		if ($this->_inited) return;
+		$this->_inited = true;
+		if ($this->_queryID) @$this->_initrs();
+		else {
+			$this->_numOfRows = 0;
+			$this->_numOfFields = 0;
+		}
+		if ($this->_numOfRows != 0 && $this->_currentRow == -1) {
+			$this->_currentRow = 0;
+			if ($this->EOF = ($this->_fetch() === false)) {
+				$this->_numOfRows = 0; // _numOfRows could be -1
+			}
+		} else {
+			$this->EOF = true;
+		}
+	}
+	
+	function _initrs()
+	{
+	global $ADODB_COUNTRECS;
+	
+		$this->_numOfRows = ($ADODB_COUNTRECS) ? @$this->_queryID->rowCount() : -1;
+		if (!$this->_numOfRows) $this->_numOfRows = -1;
+		$this->_numOfFields = $this->_queryID->columnCount();
+	}
+
+	// returns the field object
+	function &FetchField($fieldOffset = -1) 
+	{
+		$off=$fieldOffset+1; // offsets begin at 1
+		
+		$o= new ADOFieldObject();
+		$arr = @$this->_queryID->getColumnMeta($fieldOffset);
+		if (!$arr) {
+			$o->name = 'bad getColumnMeta()';
+			$o->max_length = -1;
+			$o->type = 'VARCHAR';
+			$o->precision = 0;
+	#		$false = false;
+			return $o;
+		}
+		//adodb_pr($arr);
+		$o->name = $arr['name'];
+		if (isset($arr['native_type']) && $arr['native_type'] <> "null") $o->type = $arr['native_type'];
+		else $o->type = adodb_pdo_type($arr['pdo_type']);
+		$o->max_length = $arr['len'];
+		$o->precision = $arr['precision'];
+		
+		if (ADODB_ASSOC_CASE == 0) $o->name = strtolower($o->name);
+		else if (ADODB_ASSOC_CASE == 1) $o->name = strtoupper($o->name);
+		return $o;
+	}
+	
+	function _seek($row)
+	{
+		return false;
+	}
+	
+	function _fetch()
+	{
+		if (!$this->_queryID) return false;
+		
+		$this->fields = $this->_queryID->fetch($this->fetchMode);
+		return !empty($this->fields);
+	}
+	
+	function _close() 
+	{
+		$this->_queryID = false;
+	}
+	
+	function Fields($colname)
+	{
+		if ($this->adodbFetchMode != ADODB_FETCH_NUM) return @$this->fields[$colname];
+		
+		if (!$this->bind) {
+			$this->bind = array();
+			for ($i=0; $i < $this->_numOfFields; $i++) {
+				$o = $this->FetchField($i);
+				$this->bind[strtoupper($o->name)] = $i;
+			}
+		}
+		 return $this->fields[$this->bind[strtoupper($colname)]];
+	}
+
+}
+
+?>
Index: /Dev/trunk/rdfapi/util/adodb/drivers/adodb-pdo_mssql.inc.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/drivers/adodb-pdo_mssql.inc.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/drivers/adodb-pdo_mssql.inc.php	(revision 12)
@@ -0,0 +1,61 @@
+<?php
+
+
+/*
+V4.94 23 Jan 2007  (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence.
+  Set tabs to 8.
+ 
+*/ 
+
+class ADODB_pdo_mssql extends ADODB_pdo {
+	
+	var $hasTop = 'top';
+	var $sysDate = 'convert(datetime,convert(char,GetDate(),102),102)';
+	var $sysTimeStamp = 'GetDate()';
+	
+	
+	function _init($parentDriver)
+	{
+	
+		$parentDriver->hasTransactions = false; ## <<< BUG IN PDO mssql driver
+		$parentDriver->_bindInputArray = false;
+		$parentDriver->hasInsertID = true;
+	}
+	
+	function ServerInfo()
+	{
+		return ADOConnection::ServerInfo();
+	}
+	
+	function SelectLimit($sql,$nrows=-1,$offset=-1,$inputarr=false,$secs2cache=0)
+	{
+		$ret = ADOConnection::SelectLimit($sql,$nrows,$offset,$inputarr,$secs2cache);
+		return $ret;
+	}
+	
+	function SetTransactionMode( $transaction_mode ) 
+	{
+		$this->_transmode  = $transaction_mode;
+		if (empty($transaction_mode)) {
+			$this->Execute('SET TRANSACTION ISOLATION LEVEL READ COMMITTED');
+			return;
+		}
+		if (!stristr($transaction_mode,'isolation')) $transaction_mode = 'ISOLATION LEVEL '.$transaction_mode;
+		$this->Execute("SET TRANSACTION ".$transaction_mode);
+	}
+	
+	function MetaTables()
+	{
+		return false;
+	}
+	
+	function MetaColumns()
+	{
+		return false;
+	}
+
+}
+?>
Index: /Dev/trunk/rdfapi/util/adodb/drivers/adodb-pdo_mysql.inc.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/drivers/adodb-pdo_mysql.inc.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/drivers/adodb-pdo_mysql.inc.php	(revision 12)
@@ -0,0 +1,168 @@
+<?php
+
+
+/*
+V4.94 23 Jan 2007  (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence.
+  Set tabs to 8.
+ 
+*/ 
+
+class ADODB_pdo_mysql extends ADODB_pdo {
+	var $metaTablesSQL = "SHOW TABLES";	
+	var $metaColumnsSQL = "SHOW COLUMNS FROM `%s`";
+	var $sysDate = 'CURDATE()';
+	var $sysTimeStamp = 'NOW()';
+	var $nameQuote = '`';
+
+	function _init($parentDriver)
+	{
+	
+		$parentDriver->hasTransactions = false;
+		$parentDriver->_bindInputArray = false;
+		$parentDriver->hasInsertID = true;
+		$parentDriver->_connectionID->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY,true);
+	}
+	
+		// dayFraction is a day in floating point
+	function OffsetDate($dayFraction,$date=false)
+	{		
+		if (!$date) $date = $this->sysDate;
+		
+		$fraction = $dayFraction * 24 * 3600;
+		return $date . ' + INTERVAL ' .	 $fraction.' SECOND';
+		
+//		return "from_unixtime(unix_timestamp($date)+$fraction)";
+	}
+	
+	function ServerInfo()
+	{
+		$arr['description'] = ADOConnection::GetOne("select version()");
+		$arr['version'] = ADOConnection::_findvers($arr['description']);
+		return $arr;
+	}
+	
+	function &MetaTables($ttype=false,$showSchema=false,$mask=false) 
+	{	
+		$save = $this->metaTablesSQL;
+		if ($showSchema && is_string($showSchema)) {
+			$this->metaTablesSQL .= " from $showSchema";
+		}
+		
+		if ($mask) {
+			$mask = $this->qstr($mask);
+			$this->metaTablesSQL .= " like $mask";
+		}
+		$ret =& ADOConnection::MetaTables($ttype,$showSchema);
+		
+		$this->metaTablesSQL = $save;
+		return $ret;
+	}
+	
+	function SetTransactionMode( $transaction_mode ) 
+	{
+		$this->_transmode  = $transaction_mode;
+		if (empty($transaction_mode)) {
+			$this->Execute('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ');
+			return;
+		}
+		if (!stristr($transaction_mode,'isolation')) $transaction_mode = 'ISOLATION LEVEL '.$transaction_mode;
+		$this->Execute("SET SESSION TRANSACTION ".$transaction_mode);
+	}
+	
+ 	function &MetaColumns($table) 
+	{
+		$this->_findschema($table,$schema);
+		if ($schema) {
+			$dbName = $this->database;
+			$this->SelectDB($schema);
+		}
+		global $ADODB_FETCH_MODE;
+		$save = $ADODB_FETCH_MODE;
+		$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
+		
+		if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false);
+		$rs = $this->Execute(sprintf($this->metaColumnsSQL,$table));
+		
+		if ($schema) {
+			$this->SelectDB($dbName);
+		}
+		
+		if (isset($savem)) $this->SetFetchMode($savem);
+		$ADODB_FETCH_MODE = $save;
+		if (!is_object($rs)) {
+			$false = false;
+			return $false;
+		}
+			
+		$retarr = array();
+		while (!$rs->EOF){
+			$fld = new ADOFieldObject();
+			$fld->name = $rs->fields[0];
+			$type = $rs->fields[1];
+			
+			// split type into type(length):
+			$fld->scale = null;
+			if (preg_match("/^(.+)\((\d+),(\d+)/", $type, $query_array)) {
+				$fld->type = $query_array[1];
+				$fld->max_length = is_numeric($query_array[2]) ? $query_array[2] : -1;
+				$fld->scale = is_numeric($query_array[3]) ? $query_array[3] : -1;
+			} elseif (preg_match("/^(.+)\((\d+)/", $type, $query_array)) {
+				$fld->type = $query_array[1];
+				$fld->max_length = is_numeric($query_array[2]) ? $query_array[2] : -1;
+			} elseif (preg_match("/^(enum)\((.*)\)$/i", $type, $query_array)) {
+				$fld->type = $query_array[1];
+				$arr = explode(",",$query_array[2]);
+				$fld->enums = $arr;
+				$zlen = max(array_map("strlen",$arr)) - 2; // PHP >= 4.0.6
+				$fld->max_length = ($zlen > 0) ? $zlen : 1;
+			} else {
+				$fld->type = $type;
+				$fld->max_length = -1;
+			}
+			$fld->not_null = ($rs->fields[2] != 'YES');
+			$fld->primary_key = ($rs->fields[3] == 'PRI');
+			$fld->auto_increment = (strpos($rs->fields[5], 'auto_increment') !== false);
+			$fld->binary = (strpos($type,'blob') !== false);
+			$fld->unsigned = (strpos($type,'unsigned') !== false);
+				
+			if (!$fld->binary) {
+				$d = $rs->fields[4];
+				if ($d != '' && $d != 'NULL') {
+					$fld->has_default = true;
+					$fld->default_value = $d;
+				} else {
+					$fld->has_default = false;
+				}
+			}
+			
+			if ($save == ADODB_FETCH_NUM) {
+				$retarr[] = $fld;
+			} else {
+				$retarr[strtoupper($fld->name)] = $fld;
+			}
+				$rs->MoveNext();
+			}
+		
+			$rs->Close();
+			return $retarr;	
+	}
+		
+	
+	// parameters use PostgreSQL convention, not MySQL
+	function &SelectLimit($sql,$nrows=-1,$offset=-1,$inputarr=false,$secs=0)
+	{
+		$offsetStr =($offset>=0) ? "$offset," : '';
+		// jason judge, see http://phplens.com/lens/lensforum/msgs.php?id=9220
+		if ($nrows < 0) $nrows = '18446744073709551615'; 
+		
+		if ($secs)
+			$rs =& $this->CacheExecute($secs,$sql." LIMIT $offsetStr$nrows",$inputarr);
+		else
+			$rs =& $this->Execute($sql." LIMIT $offsetStr$nrows",$inputarr);
+		return $rs;
+	}
+}
+?>
Index: /Dev/trunk/rdfapi/util/adodb/drivers/adodb-pdo_oci.inc.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/drivers/adodb-pdo_oci.inc.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/drivers/adodb-pdo_oci.inc.php	(revision 12)
@@ -0,0 +1,93 @@
+<?php
+
+
+/*
+V4.94 23 Jan 2007  (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence.
+  Set tabs to 8.
+ 
+*/ 
+
+class ADODB_pdo_oci extends ADODB_pdo_base {
+
+	var $concat_operator='||';
+	var $sysDate = "TRUNC(SYSDATE)";
+	var $sysTimeStamp = 'SYSDATE';
+	var $NLS_DATE_FORMAT = 'YYYY-MM-DD';  // To include time, use 'RRRR-MM-DD HH24:MI:SS'
+	var $random = "abs(mod(DBMS_RANDOM.RANDOM,10000001)/10000000)";
+	var $metaTablesSQL = "select table_name,table_type from cat where table_type in ('TABLE','VIEW')";
+	var $metaColumnsSQL = "select cname,coltype,width, SCALE, PRECISION, NULLS, DEFAULTVAL from col where tname='%s' order by colno"; 
+		
+ 	var $_initdate = true;
+	var $_hasdual = true;
+	
+	function _init($parentDriver)
+	{
+		$parentDriver->_bindInputArray = true;
+		$parentDriver->_nestedSQL = true;
+		if ($this->_initdate) {
+			$parentDriver->Execute("ALTER SESSION SET NLS_DATE_FORMAT='".$this->NLS_DATE_FORMAT."'");
+		}
+	}
+	
+	function &MetaTables($ttype=false,$showSchema=false,$mask=false) 
+	{
+		if ($mask) {
+			$save = $this->metaTablesSQL;
+			$mask = $this->qstr(strtoupper($mask));
+			$this->metaTablesSQL .= " AND table_name like $mask";
+		}
+		$ret =& ADOConnection::MetaTables($ttype,$showSchema);
+		
+		if ($mask) {
+			$this->metaTablesSQL = $save;
+		}
+		return $ret;
+	}
+	
+	function &MetaColumns($table) 
+	{
+	global $ADODB_FETCH_MODE;
+	
+		$false = false;
+		$save = $ADODB_FETCH_MODE;
+		$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
+		if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false);
+		
+		$rs = $this->Execute(sprintf($this->metaColumnsSQL,strtoupper($table)));
+		
+		if (isset($savem)) $this->SetFetchMode($savem);
+		$ADODB_FETCH_MODE = $save;
+		if (!$rs) {
+			return $false;
+		}
+		$retarr = array();
+		while (!$rs->EOF) { //print_r($rs->fields);
+			$fld = new ADOFieldObject();
+	   		$fld->name = $rs->fields[0];
+	   		$fld->type = $rs->fields[1];
+	   		$fld->max_length = $rs->fields[2];
+			$fld->scale = $rs->fields[3];
+			if ($rs->fields[1] == 'NUMBER' && $rs->fields[3] == 0) {
+				$fld->type ='INT';
+	     		$fld->max_length = $rs->fields[4];
+	    	}	
+		   	$fld->not_null = (strncmp($rs->fields[5], 'NOT',3) === 0);
+			$fld->binary = (strpos($fld->type,'BLOB') !== false);
+			$fld->default_value = $rs->fields[6];
+			
+			if ($ADODB_FETCH_MODE == ADODB_FETCH_NUM) $retarr[] = $fld;	
+			else $retarr[strtoupper($fld->name)] = $fld;
+			$rs->MoveNext();
+		}
+		$rs->Close();
+		if (empty($retarr))
+			return  $false;
+		else 
+			return $retarr;
+	}
+}
+
+?>
Index: /Dev/trunk/rdfapi/util/adodb/drivers/adodb-pdo_pgsql.inc.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/drivers/adodb-pdo_pgsql.inc.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/drivers/adodb-pdo_pgsql.inc.php	(revision 12)
@@ -0,0 +1,230 @@
+<?php
+
+/*
+V4.94 23 Jan 2007  (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence.
+  Set tabs to 8.
+ 
+*/ 
+
+class ADODB_pdo_pgsql extends ADODB_pdo {
+	var $metaDatabasesSQL = "select datname from pg_database where datname not in ('template0','template1') order by 1";
+    var $metaTablesSQL = "select tablename,'T' from pg_tables where tablename not like 'pg\_%'
+	and tablename not in ('sql_features', 'sql_implementation_info', 'sql_languages',
+	 'sql_packages', 'sql_sizing', 'sql_sizing_profiles') 
+	union 
+        select viewname,'V' from pg_views where viewname not like 'pg\_%'";
+	//"select tablename from pg_tables where tablename not like 'pg_%' order by 1";
+	var $isoDates = true; // accepts dates in ISO format
+	var $sysDate = "CURRENT_DATE";
+	var $sysTimeStamp = "CURRENT_TIMESTAMP";
+	var $blobEncodeType = 'C';
+	var $metaColumnsSQL = "SELECT a.attname,t.typname,a.attlen,a.atttypmod,a.attnotnull,a.atthasdef,a.attnum 
+		FROM pg_class c, pg_attribute a,pg_type t 
+		WHERE relkind in ('r','v') AND (c.relname='%s' or c.relname = lower('%s')) and a.attname not like '....%%'
+AND a.attnum > 0 AND a.atttypid = t.oid AND a.attrelid = c.oid ORDER BY a.attnum";
+
+	// used when schema defined
+	var $metaColumnsSQL1 = "SELECT a.attname, t.typname, a.attlen, a.atttypmod, a.attnotnull, a.atthasdef, a.attnum 
+FROM pg_class c, pg_attribute a, pg_type t, pg_namespace n 
+WHERE relkind in ('r','v') AND (c.relname='%s' or c.relname = lower('%s'))
+ and c.relnamespace=n.oid and n.nspname='%s' 
+	and a.attname not like '....%%' AND a.attnum > 0 
+	AND a.atttypid = t.oid AND a.attrelid = c.oid ORDER BY a.attnum";
+	
+	// get primary key etc -- from Freek Dijkstra
+	var $metaKeySQL = "SELECT ic.relname AS index_name, a.attname AS column_name,i.indisunique AS unique_key, i.indisprimary AS primary_key 
+	FROM pg_class bc, pg_class ic, pg_index i, pg_attribute a WHERE bc.oid = i.indrelid AND ic.oid = i.indexrelid AND (i.indkey[0] = a.attnum OR i.indkey[1] = a.attnum OR i.indkey[2] = a.attnum OR i.indkey[3] = a.attnum OR i.indkey[4] = a.attnum OR i.indkey[5] = a.attnum OR i.indkey[6] = a.attnum OR i.indkey[7] = a.attnum) AND a.attrelid = bc.oid AND bc.relname = '%s'";
+	
+	var $hasAffectedRows = true;
+	var $hasLimit = false;	// set to true for pgsql 7 only. support pgsql/mysql SELECT * FROM TABLE LIMIT 10
+	// below suggested by Freek Dijkstra 
+	var $true = 't';		// string that represents TRUE for a database
+	var $false = 'f';		// string that represents FALSE for a database
+	var $fmtDate = "'Y-m-d'";	// used by DBDate() as the default date format used by the database
+	var $fmtTimeStamp = "'Y-m-d G:i:s'"; // used by DBTimeStamp as the default timestamp fmt.
+	var $hasMoveFirst = true;
+	var $hasGenID = true;
+	var $_genIDSQL = "SELECT NEXTVAL('%s')";
+	var $_genSeqSQL = "CREATE SEQUENCE %s START %s";
+	var $_dropSeqSQL = "DROP SEQUENCE %s";
+	var $metaDefaultsSQL = "SELECT d.adnum as num, d.adsrc as def from pg_attrdef d, pg_class c where d.adrelid=c.oid and c.relname='%s' order by d.adnum";
+	var $random = 'random()';		/// random function
+	var $concat_operator='||';
+	
+	function _init($parentDriver)
+	{
+	
+		$parentDriver->hasTransactions = false; ## <<< BUG IN PDO pgsql driver
+		$parentDriver->hasInsertID = true;
+		$parentDriver->_nestedSQL = true;
+	}
+	
+	function ServerInfo()
+	{
+		$arr['description'] = ADOConnection::GetOne("select version()");
+		$arr['version'] = ADOConnection::_findvers($arr['description']);
+		return $arr;
+	}
+	
+	function &SelectLimit($sql,$nrows=-1,$offset=-1,$inputarr=false,$secs2cache=0) 
+	{
+		 $offsetStr = ($offset >= 0) ? " OFFSET $offset" : '';
+		 $limitStr  = ($nrows >= 0)  ? " LIMIT $nrows" : '';
+		 if ($secs2cache)
+		  	$rs =& $this->CacheExecute($secs2cache,$sql."$limitStr$offsetStr",$inputarr);
+		 else
+		  	$rs =& $this->Execute($sql."$limitStr$offsetStr",$inputarr);
+		
+		return $rs;
+	}
+	
+	function &MetaTables($ttype=false,$showSchema=false,$mask=false) 
+	{
+		$info = $this->ServerInfo();
+		if ($info['version'] >= 7.3) {
+	    	$this->metaTablesSQL = "select tablename,'T' from pg_tables where tablename not like 'pg\_%'
+			  and schemaname  not in ( 'pg_catalog','information_schema')
+	union 
+        select viewname,'V' from pg_views where viewname not like 'pg\_%'  and schemaname  not in ( 'pg_catalog','information_schema') ";
+		}
+		if ($mask) {
+			$save = $this->metaTablesSQL;
+			$mask = $this->qstr(strtolower($mask));
+			if ($info['version']>=7.3)
+				$this->metaTablesSQL = "
+select tablename,'T' from pg_tables where tablename like $mask and schemaname not in ( 'pg_catalog','information_schema')  
+ union 
+select viewname,'V' from pg_views where viewname like $mask and schemaname  not in ( 'pg_catalog','information_schema')  ";
+			else
+				$this->metaTablesSQL = "
+select tablename,'T' from pg_tables where tablename like $mask 
+ union 
+select viewname,'V' from pg_views where viewname like $mask";
+		}
+		$ret =& ADOConnection::MetaTables($ttype,$showSchema);
+		
+		if ($mask) {
+			$this->metaTablesSQL = $save;
+		}
+		return $ret;
+	}
+	
+	function &MetaColumns($table,$normalize=true) 
+	{
+	global $ADODB_FETCH_MODE;
+	
+		$schema = false;
+		$this->_findschema($table,$schema);
+		
+		if ($normalize) $table = strtolower($table);
+
+		$save = $ADODB_FETCH_MODE;
+		$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
+		if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false);
+		
+		if ($schema) $rs =& $this->Execute(sprintf($this->metaColumnsSQL1,$table,$table,$schema));
+		else $rs =& $this->Execute(sprintf($this->metaColumnsSQL,$table,$table));
+		if (isset($savem)) $this->SetFetchMode($savem);
+		$ADODB_FETCH_MODE = $save;
+		
+		if ($rs === false) {
+			$false = false;
+			return $false;
+		}
+		if (!empty($this->metaKeySQL)) {
+			// If we want the primary keys, we have to issue a separate query
+			// Of course, a modified version of the metaColumnsSQL query using a 
+			// LEFT JOIN would have been much more elegant, but postgres does 
+			// not support OUTER JOINS. So here is the clumsy way.
+			
+			$ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
+			
+			$rskey = $this->Execute(sprintf($this->metaKeySQL,($table)));
+			// fetch all result in once for performance.
+			$keys =& $rskey->GetArray();
+			if (isset($savem)) $this->SetFetchMode($savem);
+			$ADODB_FETCH_MODE = $save;
+			
+			$rskey->Close();
+			unset($rskey);
+		}
+
+		$rsdefa = array();
+		if (!empty($this->metaDefaultsSQL)) {
+			$ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
+			$sql = sprintf($this->metaDefaultsSQL, ($table));
+			$rsdef = $this->Execute($sql);
+			if (isset($savem)) $this->SetFetchMode($savem);
+			$ADODB_FETCH_MODE = $save;
+			
+			if ($rsdef) {
+				while (!$rsdef->EOF) {
+					$num = $rsdef->fields['num'];
+					$s = $rsdef->fields['def'];
+					if (strpos($s,'::')===false && substr($s, 0, 1) == "'") { /* quoted strings hack... for now... fixme */
+						$s = substr($s, 1);
+						$s = substr($s, 0, strlen($s) - 1);
+					}
+
+					$rsdefa[$num] = $s;
+					$rsdef->MoveNext();
+				}
+			} else {
+				ADOConnection::outp( "==> SQL => " . $sql);
+			}
+			unset($rsdef);
+		}
+	
+		$retarr = array();
+		while (!$rs->EOF) { 	
+			$fld = new ADOFieldObject();
+			$fld->name = $rs->fields[0];
+			$fld->type = $rs->fields[1];
+			$fld->max_length = $rs->fields[2];
+			if ($fld->max_length <= 0) $fld->max_length = $rs->fields[3]-4;
+			if ($fld->max_length <= 0) $fld->max_length = -1;
+			if ($fld->type == 'numeric') {
+				$fld->scale = $fld->max_length & 0xFFFF;
+				$fld->max_length >>= 16;
+			}
+			// dannym
+			// 5 hasdefault; 6 num-of-column
+			$fld->has_default = ($rs->fields[5] == 't');
+			if ($fld->has_default) {
+				$fld->default_value = $rsdefa[$rs->fields[6]];
+			}
+
+			//Freek
+			if ($rs->fields[4] == $this->true) {
+				$fld->not_null = true;
+			}
+			
+			// Freek
+			if (is_array($keys)) {
+				foreach($keys as $key) {
+					if ($fld->name == $key['column_name'] AND $key['primary_key'] == $this->true) 
+						$fld->primary_key = true;
+					if ($fld->name == $key['column_name'] AND $key['unique_key'] == $this->true) 
+						$fld->unique = true; // What name is more compatible?
+				}
+			}
+			
+			if ($ADODB_FETCH_MODE == ADODB_FETCH_NUM) $retarr[] = $fld;	
+			else $retarr[($normalize) ? strtoupper($fld->name) : $fld->name] = $fld;
+			
+			$rs->MoveNext();
+		}
+		$rs->Close();
+		if (empty($retarr)) {
+			$false = false;
+			return $false;
+		} else return $retarr;	
+		
+	}
+
+}
+
+?>
Index: /Dev/trunk/rdfapi/util/adodb/drivers/adodb-postgres.inc.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/drivers/adodb-postgres.inc.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/drivers/adodb-postgres.inc.php	(revision 12)
@@ -0,0 +1,14 @@
+<?php
+/*
+ V4.94 23 Jan 2007  (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence.
+  Set tabs to 4.
+  
+  NOTE: Since 3.31, this file is no longer used, and the "postgres" driver is
+  remapped to "postgres7". Maintaining multiple postgres drivers is no easy
+  job, so hopefully this will ensure greater consistency and fewer bugs.
+*/
+
+?>
Index: /Dev/trunk/rdfapi/util/adodb/drivers/adodb-postgres64.inc.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/drivers/adodb-postgres64.inc.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/drivers/adodb-postgres64.inc.php	(revision 12)
@@ -0,0 +1,1064 @@
+<?php
+/*
+ V4.94 23 Jan 2007  (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence.
+  Set tabs to 8.
+  
+  Original version derived from Alberto Cerezal (acerezalp@dbnet.es) - DBNet Informatica & Comunicaciones. 
+  08 Nov 2000 jlim - Minor corrections, removing mysql stuff
+  09 Nov 2000 jlim - added insertid support suggested by "Christopher Kings-Lynne" <chriskl@familyhealth.com.au>
+					jlim - changed concat operator to || and data types to MetaType to match documented pgsql types 
+		 	see http://www.postgresql.org/devel-corner/docs/postgres/datatype.htm  
+  22 Nov 2000 jlim - added changes to FetchField() and MetaTables() contributed by "raser" <raser@mail.zen.com.tw>
+  27 Nov 2000 jlim - added changes to _connect/_pconnect from ideas by "Lennie" <leen@wirehub.nl>
+  15 Dec 2000 jlim - added changes suggested by Additional code changes by "Eric G. Werk" egw@netguide.dk. 
+  31 Jan 2002 jlim - finally installed postgresql. testing
+  01 Mar 2001 jlim - Freek Dijkstra changes, also support for text type
+  
+  See http://www.varlena.com/varlena/GeneralBits/47.php
+  
+	-- What indexes are on my table?
+	select * from pg_indexes where tablename = 'tablename';
+	
+	-- What triggers are on my table?
+	select c.relname as "Table", t.tgname as "Trigger Name", 
+	   t.tgconstrname as "Constraint Name", t.tgenabled as "Enabled",
+	   t.tgisconstraint as "Is Constraint", cc.relname as "Referenced Table",
+	   p.proname as "Function Name"
+	from pg_trigger t, pg_class c, pg_class cc, pg_proc p
+	where t.tgfoid = p.oid and t.tgrelid = c.oid
+	   and t.tgconstrrelid = cc.oid
+	   and c.relname = 'tablename';
+	
+	-- What constraints are on my table?
+	select r.relname as "Table", c.conname as "Constraint Name",
+	   contype as "Constraint Type", conkey as "Key Columns",
+	   confkey as "Foreign Columns", consrc as "Source"
+	from pg_class r, pg_constraint c
+	where r.oid = c.conrelid
+	   and relname = 'tablename';
+
+*/
+
+// security - hide paths
+if (!defined('ADODB_DIR')) die();
+
+function adodb_addslashes($s)
+{
+	$len = strlen($s);
+	if ($len == 0) return "''";
+	if (strncmp($s,"'",1) === 0 && substr($s,$len-1) == "'") return $s; // already quoted
+	
+	return "'".addslashes($s)."'";
+}
+
+class ADODB_postgres64 extends ADOConnection{
+	var $databaseType = 'postgres64';
+	var $dataProvider = 'postgres';
+	var $hasInsertID = true;
+	var $_resultid = false;
+  	var $concat_operator='||';
+	var $metaDatabasesSQL = "select datname from pg_database where datname not in ('template0','template1') order by 1";
+    var $metaTablesSQL = "select tablename,'T' from pg_tables where tablename not like 'pg\_%'
+	and tablename not in ('sql_features', 'sql_implementation_info', 'sql_languages',
+	 'sql_packages', 'sql_sizing', 'sql_sizing_profiles') 
+	union 
+        select viewname,'V' from pg_views where viewname not like 'pg\_%'";
+	//"select tablename from pg_tables where tablename not like 'pg_%' order by 1";
+	var $isoDates = true; // accepts dates in ISO format
+	var $sysDate = "CURRENT_DATE";
+	var $sysTimeStamp = "CURRENT_TIMESTAMP";
+	var $blobEncodeType = 'C';
+	var $metaColumnsSQL = "SELECT a.attname,t.typname,a.attlen,a.atttypmod,a.attnotnull,a.atthasdef,a.attnum 
+		FROM pg_class c, pg_attribute a,pg_type t 
+		WHERE relkind in ('r','v') AND (c.relname='%s' or c.relname = lower('%s')) and a.attname not like '....%%'
+AND a.attnum > 0 AND a.atttypid = t.oid AND a.attrelid = c.oid ORDER BY a.attnum";
+
+	// used when schema defined
+	var $metaColumnsSQL1 = "SELECT a.attname, t.typname, a.attlen, a.atttypmod, a.attnotnull, a.atthasdef, a.attnum 
+FROM pg_class c, pg_attribute a, pg_type t, pg_namespace n 
+WHERE relkind in ('r','v') AND (c.relname='%s' or c.relname = lower('%s'))
+ and c.relnamespace=n.oid and n.nspname='%s' 
+	and a.attname not like '....%%' AND a.attnum > 0 
+	AND a.atttypid = t.oid AND a.attrelid = c.oid ORDER BY a.attnum";
+	
+	// get primary key etc -- from Freek Dijkstra
+	var $metaKeySQL = "SELECT ic.relname AS index_name, a.attname AS column_name,i.indisunique AS unique_key, i.indisprimary AS primary_key 
+	FROM pg_class bc, pg_class ic, pg_index i, pg_attribute a WHERE bc.oid = i.indrelid AND ic.oid = i.indexrelid AND (i.indkey[0] = a.attnum OR i.indkey[1] = a.attnum OR i.indkey[2] = a.attnum OR i.indkey[3] = a.attnum OR i.indkey[4] = a.attnum OR i.indkey[5] = a.attnum OR i.indkey[6] = a.attnum OR i.indkey[7] = a.attnum) AND a.attrelid = bc.oid AND bc.relname = '%s'";
+	
+	var $hasAffectedRows = true;
+	var $hasLimit = false;	// set to true for pgsql 7 only. support pgsql/mysql SELECT * FROM TABLE LIMIT 10
+	// below suggested by Freek Dijkstra 
+	var $true = 'TRUE';		// string that represents TRUE for a database
+	var $false = 'FALSE';		// string that represents FALSE for a database
+	var $fmtDate = "'Y-m-d'";	// used by DBDate() as the default date format used by the database
+	var $fmtTimeStamp = "'Y-m-d H:i:s'"; // used by DBTimeStamp as the default timestamp fmt.
+	var $hasMoveFirst = true;
+	var $hasGenID = true;
+	var $_genIDSQL = "SELECT NEXTVAL('%s')";
+	var $_genSeqSQL = "CREATE SEQUENCE %s START %s";
+	var $_dropSeqSQL = "DROP SEQUENCE %s";
+	var $metaDefaultsSQL = "SELECT d.adnum as num, d.adsrc as def from pg_attrdef d, pg_class c where d.adrelid=c.oid and c.relname='%s' order by d.adnum";
+	var $random = 'random()';		/// random function
+	var $autoRollback = true; // apparently pgsql does not autorollback properly before php 4.3.4
+							// http://bugs.php.net/bug.php?id=25404
+							
+	var $_bindInputArray = false; // requires postgresql 7.3+ and ability to modify database
+	var $disableBlobs = false; // set to true to disable blob checking, resulting in 2-5% improvement in performance.
+	
+	// The last (fmtTimeStamp is not entirely correct: 
+	// PostgreSQL also has support for time zones, 
+	// and writes these time in this format: "2001-03-01 18:59:26+02". 
+	// There is no code for the "+02" time zone information, so I just left that out. 
+	// I'm not familiar enough with both ADODB as well as Postgres 
+	// to know what the concequences are. The other values are correct (wheren't in 0.94)
+	// -- Freek Dijkstra 
+
+	function ADODB_postgres64() 
+	{
+	// changes the metaColumnsSQL, adds columns: attnum[6]
+	}
+	
+	function ServerInfo()
+	{
+		if (isset($this->version)) return $this->version;
+		
+		$arr['description'] = $this->GetOne("select version()");
+		$arr['version'] = ADOConnection::_findvers($arr['description']);
+		$this->version = $arr;
+		return $arr;
+	}
+
+	function IfNull( $field, $ifNull ) 
+	{
+		return " coalesce($field, $ifNull) "; 
+	}
+
+	// get the last id - never tested
+	function pg_insert_id($tablename,$fieldname)
+	{
+		$result=pg_exec($this->_connectionID, "SELECT last_value FROM ${tablename}_${fieldname}_seq");
+		if ($result) {
+			$arr = @pg_fetch_row($result,0);
+			pg_freeresult($result);
+			if (isset($arr[0])) return $arr[0];
+		}
+		return false;
+	}
+	
+/* Warning from http://www.php.net/manual/function.pg-getlastoid.php:
+Using a OID as a unique identifier is not generally wise. 
+Unless you are very careful, you might end up with a tuple having 
+a different OID if a database must be reloaded. */
+	function _insertid($table,$column)
+	{
+		if (!is_resource($this->_resultid) || get_resource_type($this->_resultid) !== 'pgsql result') return false;
+		$oid = pg_getlastoid($this->_resultid);
+		// to really return the id, we need the table and column-name, else we can only return the oid != id
+		return empty($table) || empty($column) ? $oid : $this->GetOne("SELECT $column FROM $table WHERE oid=".(int)$oid);
+	}
+
+// I get this error with PHP before 4.0.6 - jlim
+// Warning: This compilation does not support pg_cmdtuples() in adodb-postgres.inc.php on line 44
+   function _affectedrows()
+   {
+   		if (!is_resource($this->_resultid) || get_resource_type($this->_resultid) !== 'pgsql result') return false;
+	   	return pg_cmdtuples($this->_resultid);
+   }
+   
+	
+		// returns true/false
+	function BeginTrans()
+	{
+		if ($this->transOff) return true;
+		$this->transCnt += 1;
+		return @pg_Exec($this->_connectionID, "begin ".$this->_transmode);
+	}
+	
+	function RowLock($tables,$where,$flds='1 as ignore') 
+	{
+		if (!$this->transCnt) $this->BeginTrans();
+		return $this->GetOne("select $flds from $tables where $where for update");
+	}
+
+	// returns true/false. 
+	function CommitTrans($ok=true) 
+	{ 
+		if ($this->transOff) return true;
+		if (!$ok) return $this->RollbackTrans();
+		
+		$this->transCnt -= 1;
+		return @pg_Exec($this->_connectionID, "commit");
+	}
+	
+	// returns true/false
+	function RollbackTrans()
+	{
+		if ($this->transOff) return true;
+		$this->transCnt -= 1;
+		return @pg_Exec($this->_connectionID, "rollback");
+	}
+	
+	function &MetaTables($ttype=false,$showSchema=false,$mask=false) 
+	{
+		$info = $this->ServerInfo();
+		if ($info['version'] >= 7.3) {
+	    	$this->metaTablesSQL = "select tablename,'T' from pg_tables where tablename not like 'pg\_%'
+			  and schemaname  not in ( 'pg_catalog','information_schema')
+	union 
+        select viewname,'V' from pg_views where viewname not like 'pg\_%'  and schemaname  not in ( 'pg_catalog','information_schema') ";
+		}
+		if ($mask) {
+			$save = $this->metaTablesSQL;
+			$mask = $this->qstr(strtolower($mask));
+			if ($info['version']>=7.3)
+				$this->metaTablesSQL = "
+select tablename,'T' from pg_tables where tablename like $mask and schemaname not in ( 'pg_catalog','information_schema')  
+ union 
+select viewname,'V' from pg_views where viewname like $mask and schemaname  not in ( 'pg_catalog','information_schema')  ";
+			else
+				$this->metaTablesSQL = "
+select tablename,'T' from pg_tables where tablename like $mask 
+ union 
+select viewname,'V' from pg_views where viewname like $mask";
+		}
+		$ret =& ADOConnection::MetaTables($ttype,$showSchema);
+		
+		if ($mask) {
+			$this->metaTablesSQL = $save;
+		}
+		return $ret;
+	}
+	
+	
+	// if magic quotes disabled, use pg_escape_string()
+	function qstr($s,$magic_quotes=false)
+	{
+		if (!$magic_quotes) {
+			if (ADODB_PHPVER >= 0x5200) {
+				return  "'".pg_escape_string($this->_connectionID,$s)."'";
+			} 
+			if (ADODB_PHPVER >= 0x4200) {
+				return  "'".pg_escape_string($s)."'";
+			}
+			if ($this->replaceQuote[0] == '\\'){
+				$s = adodb_str_replace(array('\\',"\0"),array('\\\\',"\\\\000"),$s);
+			}
+			return  "'".str_replace("'",$this->replaceQuote,$s)."'"; 
+		}
+		
+		// undo magic quotes for "
+		$s = str_replace('\\"','"',$s);
+		return "'$s'";
+	}
+	
+	
+	
+	// Format date column in sql string given an input format that understands Y M D
+	function SQLDate($fmt, $col=false)
+	{	
+		if (!$col) $col = $this->sysTimeStamp;
+		$s = 'TO_CHAR('.$col.",'";
+		
+		$len = strlen($fmt);
+		for ($i=0; $i < $len; $i++) {
+			$ch = $fmt[$i];
+			switch($ch) {
+			case 'Y':
+			case 'y':
+				$s .= 'YYYY';
+				break;
+			case 'Q':
+			case 'q':
+				$s .= 'Q';
+				break;
+				
+			case 'M':
+				$s .= 'Mon';
+				break;
+				
+			case 'm':
+				$s .= 'MM';
+				break;
+			case 'D':
+			case 'd':
+				$s .= 'DD';
+				break;
+			
+			case 'H':
+				$s.= 'HH24';
+				break;
+				
+			case 'h':
+				$s .= 'HH';
+				break;
+				
+			case 'i':
+				$s .= 'MI';
+				break;
+			
+			case 's':
+				$s .= 'SS';
+				break;
+			
+			case 'a':
+			case 'A':
+				$s .= 'AM';
+				break;
+				
+			case 'w':
+				$s .= 'D';
+				break;
+			
+			case 'l':
+				$s .= 'DAY';
+				break;
+			
+			 case 'W':
+				$s .= 'WW';
+				break;
+
+			default:
+			// handle escape characters...
+				if ($ch == '\\') {
+					$i++;
+					$ch = substr($fmt,$i,1);
+				}
+				if (strpos('-/.:;, ',$ch) !== false) $s .= $ch;
+				else $s .= '"'.$ch.'"';
+				
+			}
+		}
+		return $s. "')";
+	}
+	
+	
+	
+	/* 
+	* Load a Large Object from a file 
+	* - the procedure stores the object id in the table and imports the object using 
+	* postgres proprietary blob handling routines 
+	*
+	* contributed by Mattia Rossi mattia@technologist.com
+	* modified for safe mode by juraj chlebec
+	*/ 
+	function UpdateBlobFile($table,$column,$path,$where,$blobtype='BLOB') 
+	{ 
+		pg_exec ($this->_connectionID, "begin"); 
+		
+		$fd = fopen($path,'r');
+		$contents = fread($fd,filesize($path));
+		fclose($fd);
+		
+		$oid = pg_lo_create($this->_connectionID);
+		$handle = pg_lo_open($this->_connectionID, $oid, 'w');
+		pg_lo_write($handle, $contents);
+		pg_lo_close($handle);
+		
+		// $oid = pg_lo_import ($path); 
+		pg_exec($this->_connectionID, "commit"); 
+		$rs = ADOConnection::UpdateBlob($table,$column,$oid,$where,$blobtype); 
+		$rez = !empty($rs); 
+		return $rez; 
+	} 
+	
+	/*
+	* Deletes/Unlinks a Blob from the database, otherwise it 
+	* will be left behind
+	*
+	* Returns TRUE on success or FALSE on failure.
+	*
+	* contributed by Todd Rogers todd#windfox.net
+	*/
+	function BlobDelete( $blob )
+	{
+		pg_exec ($this->_connectionID, "begin");
+		$result = @pg_lo_unlink($blob);
+		pg_exec ($this->_connectionID, "commit");
+		return( $result );
+	}
+
+	/*
+		Hueristic - not guaranteed to work.
+	*/
+	function GuessOID($oid)
+	{
+		if (strlen($oid)>16) return false;
+		return is_numeric($oid);
+	}
+	
+	/* 
+	* If an OID is detected, then we use pg_lo_* to open the oid file and read the
+	* real blob from the db using the oid supplied as a parameter. If you are storing
+	* blobs using bytea, we autodetect and process it so this function is not needed.
+	*
+	* contributed by Mattia Rossi mattia@technologist.com
+	*
+	* see http://www.postgresql.org/idocs/index.php?largeobjects.html
+	*
+	* Since adodb 4.54, this returns the blob, instead of sending it to stdout. Also
+	* added maxsize parameter, which defaults to $db->maxblobsize if not defined.
+	*/ 
+	function BlobDecode($blob,$maxsize=false,$hastrans=true) 
+	{
+		if (!$this->GuessOID($blob)) return $blob;
+		
+		if ($hastrans) @pg_exec($this->_connectionID,"begin"); 
+		$fd = @pg_lo_open($this->_connectionID,$blob,"r");
+		if ($fd === false) {
+			if ($hastrans) @pg_exec($this->_connectionID,"commit");
+			return $blob;
+		}
+		if (!$maxsize) $maxsize = $this->maxblobsize;
+		$realblob = @pg_loread($fd,$maxsize); 
+		@pg_loclose($fd); 
+		if ($hastrans) @pg_exec($this->_connectionID,"commit"); 
+		return $realblob;
+	}
+	
+	/* 
+		See http://www.postgresql.org/idocs/index.php?datatype-binary.html
+	 	
+		NOTE: SQL string literals (input strings) must be preceded with two backslashes 
+		due to the fact that they must pass through two parsers in the PostgreSQL 
+		backend.
+	*/
+	function BlobEncode($blob)
+	{
+		if (ADODB_PHPVER >= 0x5200) return pg_escape_bytea($this->_connectionID, $blob);
+		if (ADODB_PHPVER >= 0x4200) return pg_escape_bytea($blob);
+		
+		/*92=backslash, 0=null, 39=single-quote*/
+		$badch = array(chr(92),chr(0),chr(39)); # \  null  '
+		$fixch = array('\\\\134','\\\\000','\\\\047');
+		return adodb_str_replace($badch,$fixch,$blob);
+		
+		// note that there is a pg_escape_bytea function only for php 4.2.0 or later
+	}
+	
+	// assumes bytea for blob, and varchar for clob
+	function UpdateBlob($table,$column,$val,$where,$blobtype='BLOB')
+	{
+	
+		if ($blobtype == 'CLOB') {
+    		return $this->Execute("UPDATE $table SET $column=" . $this->qstr($val) . " WHERE $where");
+		}
+		// do not use bind params which uses qstr(), as blobencode() already quotes data
+		return $this->Execute("UPDATE $table SET $column='".$this->BlobEncode($val)."'::bytea WHERE $where");
+	}
+	
+	function OffsetDate($dayFraction,$date=false)
+	{		
+		if (!$date) $date = $this->sysDate;
+		else if (strncmp($date,"'",1) == 0) {
+			$len = strlen($date);
+			if (10 <= $len && $len <= 12) $date = 'date '.$date;
+			else $date = 'timestamp '.$date;
+		}
+		return "($date+interval'$dayFraction days')";
+	}
+	
+
+	// for schema support, pass in the $table param "$schema.$tabname".
+	// converts field names to lowercase, $upper is ignored
+	// see http://phplens.com/lens/lensforum/msgs.php?id=14018 for more info
+	function &MetaColumns($table,$normalize=true) 
+	{
+	global $ADODB_FETCH_MODE;
+	
+		$schema = false;
+		$false = false;
+		$this->_findschema($table,$schema);
+		
+		if ($normalize) $table = strtolower($table);
+
+		$save = $ADODB_FETCH_MODE;
+		$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
+		if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false);
+		
+		if ($schema) $rs =& $this->Execute(sprintf($this->metaColumnsSQL1,$table,$table,$schema));
+		else $rs =& $this->Execute(sprintf($this->metaColumnsSQL,$table,$table));
+		if (isset($savem)) $this->SetFetchMode($savem);
+		$ADODB_FETCH_MODE = $save;
+		
+		if ($rs === false) {
+			return $false;
+		}
+		if (!empty($this->metaKeySQL)) {
+			// If we want the primary keys, we have to issue a separate query
+			// Of course, a modified version of the metaColumnsSQL query using a 
+			// LEFT JOIN would have been much more elegant, but postgres does 
+			// not support OUTER JOINS. So here is the clumsy way.
+			
+			$ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
+			
+			$rskey = $this->Execute(sprintf($this->metaKeySQL,($table)));
+			// fetch all result in once for performance.
+			$keys =& $rskey->GetArray();
+			if (isset($savem)) $this->SetFetchMode($savem);
+			$ADODB_FETCH_MODE = $save;
+			
+			$rskey->Close();
+			unset($rskey);
+		}
+
+		$rsdefa = array();
+		if (!empty($this->metaDefaultsSQL)) {
+			$ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
+			$sql = sprintf($this->metaDefaultsSQL, ($table));
+			$rsdef = $this->Execute($sql);
+			if (isset($savem)) $this->SetFetchMode($savem);
+			$ADODB_FETCH_MODE = $save;
+			
+			if ($rsdef) {
+				while (!$rsdef->EOF) {
+					$num = $rsdef->fields['num'];
+					$s = $rsdef->fields['def'];
+					if (strpos($s,'::')===false && substr($s, 0, 1) == "'") { /* quoted strings hack... for now... fixme */
+						$s = substr($s, 1);
+						$s = substr($s, 0, strlen($s) - 1);
+					}
+
+					$rsdefa[$num] = $s;
+					$rsdef->MoveNext();
+				}
+			} else {
+				ADOConnection::outp( "==> SQL => " . $sql);
+			}
+			unset($rsdef);
+		}
+	
+		$retarr = array();
+		while (!$rs->EOF) { 	
+			$fld = new ADOFieldObject();
+			$fld->name = $rs->fields[0];
+			$fld->type = $rs->fields[1];
+			$fld->max_length = $rs->fields[2];
+			$fld->attnum = $rs->fields[6];
+			
+			if ($fld->max_length <= 0) $fld->max_length = $rs->fields[3]-4;
+			if ($fld->max_length <= 0) $fld->max_length = -1;
+			if ($fld->type == 'numeric') {
+				$fld->scale = $fld->max_length & 0xFFFF;
+				$fld->max_length >>= 16;
+			}
+			// dannym
+			// 5 hasdefault; 6 num-of-column
+			$fld->has_default = ($rs->fields[5] == 't');
+			if ($fld->has_default) {
+				$fld->default_value = $rsdefa[$rs->fields[6]];
+			}
+
+			//Freek
+			$fld->not_null = $rs->fields[4] == 't';
+			
+			
+			// Freek
+			if (is_array($keys)) {
+				foreach($keys as $key) {
+					if ($fld->name == $key['column_name'] AND $key['primary_key'] == 't') 
+						$fld->primary_key = true;
+					if ($fld->name == $key['column_name'] AND $key['unique_key'] == 't') 
+						$fld->unique = true; // What name is more compatible?
+				}
+			}
+			
+			if ($ADODB_FETCH_MODE == ADODB_FETCH_NUM) $retarr[] = $fld;	
+			else $retarr[($normalize) ? strtoupper($fld->name) : $fld->name] = $fld;
+			
+			$rs->MoveNext();
+		}
+		$rs->Close();
+		if (empty($retarr))
+			return  $false;
+		else
+			return $retarr;	
+		
+	}
+
+	  function &MetaIndexes ($table, $primary = FALSE)
+      {
+         global $ADODB_FETCH_MODE;
+                
+				$schema = false;
+				$this->_findschema($table,$schema);
+
+				if ($schema) { // requires pgsql 7.3+ - pg_namespace used.
+					$sql = '
+SELECT c.relname as "Name", i.indisunique as "Unique", i.indkey as "Columns" 
+FROM pg_catalog.pg_class c 
+JOIN pg_catalog.pg_index i ON i.indexrelid=c.oid 
+JOIN pg_catalog.pg_class c2 ON c2.oid=i.indrelid
+	,pg_namespace n 
+WHERE (c2.relname=\'%s\' or c2.relname=lower(\'%s\')) and c.relnamespace=c2.relnamespace and c.relnamespace=n.oid and n.nspname=\'%s\'';
+				} else {
+	                $sql = '
+SELECT c.relname as "Name", i.indisunique as "Unique", i.indkey as "Columns"
+FROM pg_catalog.pg_class c
+JOIN pg_catalog.pg_index i ON i.indexrelid=c.oid
+JOIN pg_catalog.pg_class c2 ON c2.oid=i.indrelid
+WHERE (c2.relname=\'%s\' or c2.relname=lower(\'%s\'))';
+    			}
+				            
+                if ($primary == FALSE) {
+                	$sql .= ' AND i.indisprimary=false;';
+                }
+                
+                $save = $ADODB_FETCH_MODE;
+                $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
+                if ($this->fetchMode !== FALSE) {
+                        $savem = $this->SetFetchMode(FALSE);
+                }
+                
+                $rs = $this->Execute(sprintf($sql,$table,$table,$schema));
+                if (isset($savem)) {
+                        $this->SetFetchMode($savem);
+                }
+                $ADODB_FETCH_MODE = $save;
+
+                if (!is_object($rs)) {
+                	$false = false;
+					return $false;
+                }
+				
+                $col_names = $this->MetaColumnNames($table,true,true); 
+				//3rd param is use attnum, 
+				// see http://sourceforge.net/tracker/index.php?func=detail&aid=1451245&group_id=42718&atid=433976
+                $indexes = array();
+                while ($row = $rs->FetchRow()) {
+                        $columns = array();
+                        foreach (explode(' ', $row[2]) as $col) {
+                                $columns[] = $col_names[$col];
+                        }
+                        
+                        $indexes[$row[0]] = array(
+                                'unique' => ($row[1] == 't'),
+                                'columns' => $columns
+                        );
+                }
+                return $indexes;
+        }
+
+	// returns true or false
+	//
+	// examples:
+	// 	$db->Connect("host=host1 user=user1 password=secret port=4341");
+	// 	$db->Connect('host1','user1','secret');
+	function _connect($str,$user='',$pwd='',$db='',$ctype=0)
+	{
+		
+		if (!function_exists('pg_connect')) return null;
+		
+		$this->_errorMsg = false;
+		
+		if ($user || $pwd || $db) {
+			$user = adodb_addslashes($user);
+			$pwd = adodb_addslashes($pwd);
+			if (strlen($db) == 0) $db = 'template1';
+			$db = adodb_addslashes($db);
+		   	if ($str)  {
+			 	$host = split(":", $str);
+				if ($host[0]) $str = "host=".adodb_addslashes($host[0]);
+				else $str = '';
+				if (isset($host[1])) $str .= " port=$host[1]";
+				else if (!empty($this->port)) $str .= " port=".$this->port;
+			}
+		   		if ($user) $str .= " user=".$user;
+		   		if ($pwd)  $str .= " password=".$pwd;
+				if ($db)   $str .= " dbname=".$db;
+		}
+
+		//if ($user) $linea = "user=$user host=$linea password=$pwd dbname=$db port=5432";
+		
+		if ($ctype === 1) { // persistent
+			$this->_connectionID = pg_pconnect($str);
+		} else {
+			if ($ctype === -1) { // nconnect, we trick pgsql ext by changing the connection str
+			static $ncnt;
+			
+				if (empty($ncnt)) $ncnt = 1;
+				else $ncnt += 1;
+				
+				$str .= str_repeat(' ',$ncnt);
+			}
+			$this->_connectionID = pg_connect($str);
+		}
+		if ($this->_connectionID === false) return false;
+		$this->Execute("set datestyle='ISO'");
+		
+		$info = $this->ServerInfo();
+		$this->pgVersion = (float) substr($info['version'],0,3);
+		if ($this->pgVersion >= 7.1) { // good till version 999
+			$this->_nestedSQL = true;
+		}
+		return true;
+	}
+	
+	function _nconnect($argHostname, $argUsername, $argPassword, $argDatabaseName)
+	{
+	 	return $this->_connect($argHostname, $argUsername, $argPassword, $argDatabaseName,-1);
+	}
+	 
+	// returns true or false
+	//
+	// examples:
+	// 	$db->PConnect("host=host1 user=user1 password=secret port=4341");
+	// 	$db->PConnect('host1','user1','secret');
+	function _pconnect($str,$user='',$pwd='',$db='')
+	{
+		return $this->_connect($str,$user,$pwd,$db,1);
+	}
+	
+
+	// returns queryID or false
+	function _query($sql,$inputarr)
+	{
+		$this->_errorMsg = false;
+		if ($inputarr) {
+		/*
+			It appears that PREPARE/EXECUTE is slower for many queries.
+			
+			For query executed 1000 times:
+			"select id,firstname,lastname from adoxyz 
+				where firstname not like ? and lastname not like ? and id = ?"
+				
+			with plan = 1.51861286163 secs
+			no plan =   1.26903700829 secs
+
+			
+
+		*/
+			$plan = 'P'.md5($sql);
+				
+			$execp = '';
+			foreach($inputarr as $v) {
+				if ($execp) $execp .= ',';
+				if (is_string($v)) {
+					if (strncmp($v,"'",1) !== 0) $execp .= $this->qstr($v);
+				} else {
+					$execp .= $v;
+				}
+			}
+			
+			if ($execp) $exsql = "EXECUTE $plan ($execp)";
+			else $exsql = "EXECUTE $plan";
+			
+			
+			$rez = @pg_exec($this->_connectionID,$exsql);
+			if (!$rez) {
+			# Perhaps plan does not exist? Prepare/compile plan.
+				$params = '';
+				foreach($inputarr as $v) {
+					if ($params) $params .= ',';
+					if (is_string($v)) {
+						$params .= 'VARCHAR';
+					} else if (is_integer($v)) {
+						$params .= 'INTEGER';
+					} else {
+						$params .= "REAL";
+					}
+				}
+				$sqlarr = explode('?',$sql);
+				//print_r($sqlarr);
+				$sql = '';
+				$i = 1;
+				foreach($sqlarr as $v) {
+					$sql .= $v.' $'.$i;
+					$i++;
+				}
+				$s = "PREPARE $plan ($params) AS ".substr($sql,0,strlen($sql)-2);		
+				//adodb_pr($s);
+				$rez = pg_exec($this->_connectionID,$s);
+				//echo $this->ErrorMsg();
+			}
+			if ($rez)
+				$rez = pg_exec($this->_connectionID,$exsql);
+		} else {
+			//adodb_backtrace();
+			$rez = pg_exec($this->_connectionID,$sql);
+		}
+		// check if no data returned, then no need to create real recordset
+		if ($rez && pg_numfields($rez) <= 0) {
+			if (is_resource($this->_resultid) && get_resource_type($this->_resultid) === 'pgsql result') {
+				pg_freeresult($this->_resultid);
+			}
+			$this->_resultid = $rez;
+			return true;
+		}
+		
+		return $rez;
+	}
+	
+	function _errconnect()
+	{
+		if (defined('DB_ERROR_CONNECT_FAILED')) return DB_ERROR_CONNECT_FAILED;
+		else return 'Database connection failed';
+	}
+
+	/*	Returns: the last error message from previous database operation	*/	
+	function ErrorMsg() 
+	{
+		if ($this->_errorMsg !== false) return $this->_errorMsg;
+		if (ADODB_PHPVER >= 0x4300) {
+			if (!empty($this->_resultid)) {
+				$this->_errorMsg = @pg_result_error($this->_resultid);
+				if ($this->_errorMsg) return $this->_errorMsg;
+			}
+			
+			if (!empty($this->_connectionID)) {
+				$this->_errorMsg = @pg_last_error($this->_connectionID);
+			} else $this->_errorMsg = $this->_errconnect();
+		} else {
+			if (empty($this->_connectionID)) $this->_errconnect();
+			else $this->_errorMsg = @pg_errormessage($this->_connectionID);
+		}
+		return $this->_errorMsg;
+	}
+	
+	function ErrorNo()
+	{
+		$e = $this->ErrorMsg();
+		if (strlen($e)) {
+			return ADOConnection::MetaError($e);
+		 }
+		 return 0;
+	}
+
+	// returns true or false
+	function _close()
+	{
+		if ($this->transCnt) $this->RollbackTrans();
+		if ($this->_resultid) {
+			@pg_freeresult($this->_resultid);
+			$this->_resultid = false;
+		}
+		@pg_close($this->_connectionID);
+		$this->_connectionID = false;
+		return true;
+	}
+	
+	
+	/*
+	* Maximum size of C field
+	*/
+	function CharMax()
+	{
+		return 1000000000;  // should be 1 Gb?
+	}
+	
+	/*
+	* Maximum size of X field
+	*/
+	function TextMax()
+	{
+		return 1000000000; // should be 1 Gb?
+	}
+	
+		
+}
+	
+/*--------------------------------------------------------------------------------------
+	 Class Name: Recordset
+--------------------------------------------------------------------------------------*/
+
+class ADORecordSet_postgres64 extends ADORecordSet{
+	var $_blobArr;
+	var $databaseType = "postgres64";
+	var $canSeek = true;
+	function ADORecordSet_postgres64($queryID,$mode=false) 
+	{
+		if ($mode === false) { 
+			global $ADODB_FETCH_MODE;
+			$mode = $ADODB_FETCH_MODE;
+		}
+		switch ($mode)
+		{
+		case ADODB_FETCH_NUM: $this->fetchMode = PGSQL_NUM; break;
+		case ADODB_FETCH_ASSOC:$this->fetchMode = PGSQL_ASSOC; break;
+		
+		case ADODB_FETCH_DEFAULT:
+		case ADODB_FETCH_BOTH:
+		default: $this->fetchMode = PGSQL_BOTH; break;
+		}
+		$this->adodbFetchMode = $mode;
+		$this->ADORecordSet($queryID);
+	}
+	
+	function &GetRowAssoc($upper=true)
+	{
+		if ($this->fetchMode == PGSQL_ASSOC && !$upper) return $this->fields;
+		$row =& ADORecordSet::GetRowAssoc($upper);
+		return $row;
+	}
+
+	function _initrs()
+	{
+	global $ADODB_COUNTRECS;
+		$qid = $this->_queryID;
+		$this->_numOfRows = ($ADODB_COUNTRECS)? @pg_numrows($qid):-1;
+		$this->_numOfFields = @pg_numfields($qid);
+		
+		// cache types for blob decode check
+		// apparently pg_fieldtype actually performs an sql query on the database to get the type.
+		if (empty($this->connection->noBlobs))
+		for ($i=0, $max = $this->_numOfFields; $i < $max; $i++) {  
+			if (pg_fieldtype($qid,$i) == 'bytea') {
+				$this->_blobArr[$i] = pg_fieldname($qid,$i);
+			}
+		}
+	}
+
+		/* Use associative array to get fields array */
+	function Fields($colname)
+	{
+		if ($this->fetchMode != PGSQL_NUM) return @$this->fields[$colname];
+		
+		if (!$this->bind) {
+			$this->bind = array();
+			for ($i=0; $i < $this->_numOfFields; $i++) {
+				$o = $this->FetchField($i);
+				$this->bind[strtoupper($o->name)] = $i;
+			}
+		}
+		 return $this->fields[$this->bind[strtoupper($colname)]];
+	}
+
+	function &FetchField($off = 0) 
+	{
+		// offsets begin at 0
+		
+		$o= new ADOFieldObject();
+		$o->name = @pg_fieldname($this->_queryID,$off);
+		$o->type = @pg_fieldtype($this->_queryID,$off);
+		$o->max_length = @pg_fieldsize($this->_queryID,$off);
+		return $o;	
+	}
+
+	function _seek($row)
+	{
+		return @pg_fetch_row($this->_queryID,$row);
+	}
+	
+	function _decode($blob)
+	{
+		eval('$realblob="'.adodb_str_replace(array('"','$'),array('\"','\$'),$blob).'";');
+		return $realblob;	
+	}
+	
+	function _fixblobs()
+	{
+		if ($this->fetchMode == PGSQL_NUM || $this->fetchMode == PGSQL_BOTH) {
+			foreach($this->_blobArr as $k => $v) {
+				$this->fields[$k] = ADORecordSet_postgres64::_decode($this->fields[$k]);
+			}
+		}
+		if ($this->fetchMode == PGSQL_ASSOC || $this->fetchMode == PGSQL_BOTH) {
+			foreach($this->_blobArr as $k => $v) {
+				$this->fields[$v] = ADORecordSet_postgres64::_decode($this->fields[$v]);
+			}
+		}
+	}
+	
+	// 10% speedup to move MoveNext to child class
+	function MoveNext() 
+	{
+		if (!$this->EOF) {
+			$this->_currentRow++;
+			if ($this->_numOfRows < 0 || $this->_numOfRows > $this->_currentRow) {
+				$this->fields = @pg_fetch_array($this->_queryID,$this->_currentRow,$this->fetchMode);
+				if (is_array($this->fields) && $this->fields) {
+					if (isset($this->_blobArr)) $this->_fixblobs();
+					return true;
+				}
+			}
+			$this->fields = false;
+			$this->EOF = true;
+		}
+		return false;
+	}		
+	
+	function _fetch()
+	{
+				
+		if ($this->_currentRow >= $this->_numOfRows && $this->_numOfRows >= 0)
+        	return false;
+
+		$this->fields = @pg_fetch_array($this->_queryID,$this->_currentRow,$this->fetchMode);
+		
+		if ($this->fields && isset($this->_blobArr)) $this->_fixblobs();
+			
+		return (is_array($this->fields));
+	}
+
+	function _close() 
+	{ 
+		return @pg_freeresult($this->_queryID);
+	}
+
+	function MetaType($t,$len=-1,$fieldobj=false)
+	{
+		if (is_object($t)) {
+			$fieldobj = $t;
+			$t = $fieldobj->type;
+			$len = $fieldobj->max_length;
+		}
+		switch (strtoupper($t)) {
+				case 'MONEY': // stupid, postgres expects money to be a string
+				case 'INTERVAL':
+				case 'CHAR':
+				case 'CHARACTER':
+				case 'VARCHAR':
+				case 'NAME':
+		   		case 'BPCHAR':
+				case '_VARCHAR':
+				case 'INET':
+				case 'MACADDR':
+					if ($len <= $this->blobSize) return 'C';
+				
+				case 'TEXT':
+					return 'X';
+		
+				case 'IMAGE': // user defined type
+				case 'BLOB': // user defined type
+				case 'BIT':	// This is a bit string, not a single bit, so don't return 'L'
+				case 'VARBIT':
+				case 'BYTEA':
+					return 'B';
+				
+				case 'BOOL':
+				case 'BOOLEAN':
+					return 'L';
+				
+				case 'DATE':
+					return 'D';
+				
+				
+				case 'TIMESTAMP WITHOUT TIME ZONE':
+				case 'TIME':
+				case 'DATETIME':
+				case 'TIMESTAMP':
+				case 'TIMESTAMPTZ':
+					return 'T';
+				
+				case 'SMALLINT': 
+				case 'BIGINT': 
+				case 'INTEGER': 
+				case 'INT8': 
+				case 'INT4':
+				case 'INT2':
+					if (isset($fieldobj) &&
+				empty($fieldobj->primary_key) && empty($fieldobj->unique)) return 'I';
+				
+				case 'OID':
+				case 'SERIAL':
+					return 'R';
+				
+				 default:
+				 	return 'N';
+			}
+	}
+
+}
+?>
Index: /Dev/trunk/rdfapi/util/adodb/drivers/adodb-postgres7.inc.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/drivers/adodb-postgres7.inc.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/drivers/adodb-postgres7.inc.php	(revision 12)
@@ -0,0 +1,264 @@
+<?php
+/*
+ V4.94 23 Jan 2007  (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence.
+  Set tabs to 4.
+  
+  Postgres7 support.
+  28 Feb 2001: Currently indicate that we support LIMIT
+  01 Dec 2001: dannym added support for default values
+*/
+
+// security - hide paths
+if (!defined('ADODB_DIR')) die();
+
+include_once(ADODB_DIR."/drivers/adodb-postgres64.inc.php");
+
+class ADODB_postgres7 extends ADODB_postgres64 {
+	var $databaseType = 'postgres7';	
+	var $hasLimit = true;	// set to true for pgsql 6.5+ only. support pgsql/mysql SELECT * FROM TABLE LIMIT 10
+	var $ansiOuter = true;
+	var $charSet = true; //set to true for Postgres 7 and above - PG client supports encodings
+	
+	function ADODB_postgres7() 
+	{
+		$this->ADODB_postgres64();
+		if (ADODB_ASSOC_CASE !== 2) {
+			$this->rsPrefix .= 'assoc_';
+		}
+		$this->_bindInputArray = PHP_VERSION >= 5.1;
+	}
+
+	
+	// the following should be compat with postgresql 7.2, 
+	// which makes obsolete the LIMIT limit,offset syntax
+	 function &SelectLimit($sql,$nrows=-1,$offset=-1,$inputarr=false,$secs2cache=0) 
+	 {
+		 $offsetStr = ($offset >= 0) ? " OFFSET ".((integer)$offset) : '';
+		 $limitStr  = ($nrows >= 0)  ? " LIMIT ".((integer)$nrows) : '';
+		 if ($secs2cache)
+		  	$rs =& $this->CacheExecute($secs2cache,$sql."$limitStr$offsetStr",$inputarr);
+		 else
+		  	$rs =& $this->Execute($sql."$limitStr$offsetStr",$inputarr);
+		
+		return $rs;
+	 }
+ 	/*
+ 	function Prepare($sql)
+	{
+		$info = $this->ServerInfo();
+		if ($info['version']>=7.3) {
+			return array($sql,false);
+		}
+		return $sql;
+	}
+ 	*/
+
+
+	// from  Edward Jaramilla, improved version - works on pg 7.4
+	function MetaForeignKeys($table, $owner=false, $upper=false)
+	{
+		$sql = 'SELECT t.tgargs as args
+		FROM
+		pg_trigger t,pg_class c,pg_proc p
+		WHERE
+		t.tgenabled AND
+		t.tgrelid = c.oid AND
+		t.tgfoid = p.oid AND
+		p.proname = \'RI_FKey_check_ins\' AND
+		c.relname = \''.strtolower($table).'\'
+		ORDER BY
+			t.tgrelid';
+		
+		$rs =& $this->Execute($sql);
+		
+		if (!$rs || $rs->EOF) return false;
+		
+		$arr =& $rs->GetArray();
+		$a = array();
+		foreach($arr as $v) {
+			$data = explode(chr(0), $v['args']);
+			$size = count($data)-1; //-1 because the last node is empty
+			for($i = 4; $i < $size; $i++) {
+				if ($upper) 
+					$a[strtoupper($data[2])][] = strtoupper($data[$i].'='.$data[++$i]);
+				else 
+					$a[$data[2]][] = $data[$i].'='.$data[++$i];
+			}
+		}
+		return $a;
+	}
+
+	function _query($sql,$inputarr)
+	{
+		if (! $this->_bindInputArray) {
+			// We don't have native support for parameterized queries, so let's emulate it at the parent
+			return ADODB_postgres64::_query($sql, $inputarr);
+		}
+		$this->_errorMsg = false;
+		// -- added Cristiano da Cunha Duarte
+		if ($inputarr) {
+			$sqlarr = explode('?',trim($sql));
+			$sql = '';
+			$i = 1;
+			$last = sizeof($sqlarr)-1;
+			foreach($sqlarr as $v) {
+				if ($last < $i) $sql .= $v;
+				else $sql .= $v.' $'.$i;
+				$i++;
+			}
+			
+			$rez = pg_query_params($this->_connectionID,$sql, $inputarr);
+		} else {
+			$rez = pg_query($this->_connectionID,$sql);
+		}
+		// check if no data returned, then no need to create real recordset
+		if ($rez && pg_numfields($rez) <= 0) {
+			if (is_resource($this->_resultid) && get_resource_type($this->_resultid) === 'pgsql result') {
+				pg_freeresult($this->_resultid);
+			}
+			$this->_resultid = $rez;
+			return true;
+		}		
+		return $rez;
+	}
+	
+ 	 // this is a set of functions for managing client encoding - very important if the encodings
+	// of your database and your output target (i.e. HTML) don't match
+	//for instance, you may have UNICODE database and server it on-site as WIN1251 etc.
+	// GetCharSet - get the name of the character set the client is using now
+	// the functions should work with Postgres 7.0 and above, the set of charsets supported
+	// depends on compile flags of postgres distribution - if no charsets were compiled into the server
+	// it will return 'SQL_ANSI' always
+	function GetCharSet()
+	{
+		//we will use ADO's builtin property charSet
+		$this->charSet = @pg_client_encoding($this->_connectionID);
+		if (!$this->charSet) {
+			return false;
+		} else {
+			return $this->charSet;
+		}
+	}
+	
+	// SetCharSet - switch the client encoding
+	function SetCharSet($charset_name)
+	{
+		$this->GetCharSet();
+		if ($this->charSet !== $charset_name) {
+			$if = pg_set_client_encoding($this->_connectionID, $charset_name);
+			if ($if == "0" & $this->GetCharSet() == $charset_name) {
+				return true;
+			} else return false;
+		} else return true;
+	}
+
+}
+	
+/*--------------------------------------------------------------------------------------
+	 Class Name: Recordset
+--------------------------------------------------------------------------------------*/
+
+class ADORecordSet_postgres7 extends ADORecordSet_postgres64{
+
+	var $databaseType = "postgres7";
+	
+	
+	function ADORecordSet_postgres7($queryID,$mode=false) 
+	{
+		$this->ADORecordSet_postgres64($queryID,$mode);
+	}
+	
+	 	// 10% speedup to move MoveNext to child class
+	function MoveNext() 
+	{
+		if (!$this->EOF) {
+			$this->_currentRow++;
+			if ($this->_numOfRows < 0 || $this->_numOfRows > $this->_currentRow) {
+				$this->fields = @pg_fetch_array($this->_queryID,$this->_currentRow,$this->fetchMode);
+			
+				if (is_array($this->fields)) {
+					if ($this->fields && isset($this->_blobArr)) $this->_fixblobs();
+					return true;
+				}
+			}
+			$this->fields = false;
+			$this->EOF = true;
+		}
+		return false;
+	}		
+
+}
+
+class ADORecordSet_assoc_postgres7 extends ADORecordSet_postgres64{
+
+	var $databaseType = "postgres7";
+	
+	
+	function ADORecordSet_assoc_postgres7($queryID,$mode=false) 
+	{
+		$this->ADORecordSet_postgres64($queryID,$mode);
+	}
+	
+	function _fetch()
+	{
+		if ($this->_currentRow >= $this->_numOfRows && $this->_numOfRows >= 0)
+        	return false;
+
+		$this->fields = @pg_fetch_array($this->_queryID,$this->_currentRow,$this->fetchMode);
+		
+		if ($this->fields) {
+			if (isset($this->_blobArr)) $this->_fixblobs();
+			$this->_updatefields();
+		}
+			
+		return (is_array($this->fields));
+	}
+	
+		// Create associative array
+	function _updatefields()
+	{
+		if (ADODB_ASSOC_CASE == 2) return; // native
+	
+		$arr = array();
+		$lowercase = (ADODB_ASSOC_CASE == 0);
+		
+		foreach($this->fields as $k => $v) {
+			if (is_integer($k)) $arr[$k] = $v;
+			else {
+				if ($lowercase)
+					$arr[strtolower($k)] = $v;
+				else
+					$arr[strtoupper($k)] = $v;
+			}
+		}
+		$this->fields = $arr;
+	}
+	
+	function MoveNext() 
+	{
+		if (!$this->EOF) {
+			$this->_currentRow++;
+			if ($this->_numOfRows < 0 || $this->_numOfRows > $this->_currentRow) {
+				$this->fields = @pg_fetch_array($this->_queryID,$this->_currentRow,$this->fetchMode);
+			
+				if (is_array($this->fields)) {
+					if ($this->fields) {
+						if (isset($this->_blobArr)) $this->_fixblobs();
+					
+						$this->_updatefields();
+					}
+					return true;
+				}
+			}
+			
+			
+			$this->fields = false;
+			$this->EOF = true;
+		}
+		return false;
+	}
+}
+?>
Index: /Dev/trunk/rdfapi/util/adodb/drivers/adodb-postgres8.inc.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/drivers/adodb-postgres8.inc.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/drivers/adodb-postgres8.inc.php	(revision 12)
@@ -0,0 +1,12 @@
+<?php
+/*
+ V4.94 23 Jan 2007  (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence.
+  Set tabs to 4.
+  
+  NOTE: The "postgres8" driver is remapped to "postgres7". 
+*/
+
+?>
Index: /Dev/trunk/rdfapi/util/adodb/drivers/adodb-proxy.inc.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/drivers/adodb-proxy.inc.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/drivers/adodb-proxy.inc.php	(revision 12)
@@ -0,0 +1,33 @@
+<?php
+/*
+V4.94 23 Jan 2007  (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence.
+  Set tabs to 4.
+  
+  Synonym for csv driver.
+*/ 
+
+// security - hide paths
+if (!defined('ADODB_DIR')) die();
+
+if (! defined("_ADODB_PROXY_LAYER")) {
+	 define("_ADODB_PROXY_LAYER", 1 );
+	 include(ADODB_DIR."/drivers/adodb-csv.inc.php");
+	 
+	class ADODB_proxy extends ADODB_csv {
+		var $databaseType = 'proxy';
+		var $databaseProvider = 'csv';
+	}
+	class ADORecordset_proxy extends ADORecordset_csv {
+	var $databaseType = "proxy";		
+	
+		function ADORecordset_proxy($id,$mode=false) 
+		{
+			$this->ADORecordset($id,$mode);
+		}
+	};
+} // define
+	
+?>
Index: /Dev/trunk/rdfapi/util/adodb/drivers/adodb-sapdb.inc.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/drivers/adodb-sapdb.inc.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/drivers/adodb-sapdb.inc.php	(revision 12)
@@ -0,0 +1,184 @@
+<?php
+/* 
+V4.94 23 Jan 2007  (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence. 
+Set tabs to 4 for best viewing.
+  
+  Latest version is available at http://adodb.sourceforge.net
+  
+  SAPDB data driver. Requires ODBC.
+
+*/
+
+// security - hide paths
+if (!defined('ADODB_DIR')) die();
+
+if (!defined('_ADODB_ODBC_LAYER')) {
+	include(ADODB_DIR."/drivers/adodb-odbc.inc.php");
+}
+if (!defined('ADODB_SAPDB')){
+define('ADODB_SAPDB',1);
+
+class ADODB_SAPDB extends ADODB_odbc {
+	var $databaseType = "sapdb";	
+	var $concat_operator = '||';
+	var $sysDate = 'DATE';
+	var $sysTimeStamp = 'TIMESTAMP';
+	var $fmtDate = "'Y-m-d'";	/// used by DBDate() as the default date format used by the database
+	var $fmtTimeStamp = "'Y-m-d H:i:s'"; /// used by DBTimeStamp as the default timestamp fmt.
+	var $hasInsertId = true;
+	var $_bindInputArray = true;
+	
+	function ADODB_SAPDB()
+	{
+		//if (strncmp(PHP_OS,'WIN',3) === 0) $this->curmode = SQL_CUR_USE_ODBC;
+		$this->ADODB_odbc();
+	}
+	
+	function ServerInfo()
+	{
+		$info = ADODB_odbc::ServerInfo();
+		if (!$info['version'] && preg_match('/([0-9.]+)/',$info['description'],$matches)) {
+			$info['version'] = $matches[1];
+		}
+		return $info;
+	}
+
+	function MetaPrimaryKeys($table)
+	{
+		$table = $this->Quote(strtoupper($table));
+
+		return $this->GetCol("SELECT columnname FROM COLUMNS WHERE tablename=$table AND mode='KEY' ORDER BY pos");
+	}
+		
+ 	function &MetaIndexes ($table, $primary = FALSE)
+	{
+		$table = $this->Quote(strtoupper($table));
+
+		$sql = "SELECT INDEXNAME,TYPE,COLUMNNAME FROM INDEXCOLUMNS ".
+			" WHERE TABLENAME=$table".
+			" ORDER BY INDEXNAME,COLUMNNO";
+
+		global $ADODB_FETCH_MODE;
+		$save = $ADODB_FETCH_MODE;
+        $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
+        if ($this->fetchMode !== FALSE) {
+        	$savem = $this->SetFetchMode(FALSE);
+        }
+        
+        $rs = $this->Execute($sql);
+        if (isset($savem)) {
+        	$this->SetFetchMode($savem);
+        }
+        $ADODB_FETCH_MODE = $save;
+
+        if (!is_object($rs)) {
+        	return FALSE;
+        }
+
+		$indexes = array();
+		while ($row = $rs->FetchRow()) {
+            $indexes[$row[0]]['unique'] = $row[1] == 'UNIQUE';
+            $indexes[$row[0]]['columns'][] = $row[2];
+    	}
+		if ($primary) {
+			$indexes['SYSPRIMARYKEYINDEX'] = array(
+					'unique' => True,	// by definition
+					'columns' => $this->GetCol("SELECT columnname FROM COLUMNS WHERE tablename=$table AND mode='KEY' ORDER BY pos"),
+				);
+		}
+        return $indexes;
+	}
+	
+ 	function &MetaColumns ($table)
+	{
+		global $ADODB_FETCH_MODE;
+		$save = $ADODB_FETCH_MODE;
+        $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
+        if ($this->fetchMode !== FALSE) {
+        	$savem = $this->SetFetchMode(FALSE);
+        }
+		$table = $this->Quote(strtoupper($table));
+		
+		$retarr = array();
+		foreach($this->GetAll("SELECT COLUMNNAME,DATATYPE,LEN,DEC,NULLABLE,MODE,\"DEFAULT\",CASE WHEN \"DEFAULT\" IS NULL THEN 0 ELSE 1 END AS HAS_DEFAULT FROM COLUMNS WHERE tablename=$table ORDER BY pos") as $column)
+		{
+			$fld = new ADOFieldObject();
+			$fld->name = $column[0];
+			$fld->type = $column[1];
+			$fld->max_length = $fld->type == 'LONG' ? 2147483647 : $column[2];
+			$fld->scale = $column[3];
+			$fld->not_null = $column[4] == 'NO';
+			$fld->primary_key = $column[5] == 'KEY';
+			if ($fld->has_default = $column[7]) {
+				if ($fld->primary_key && $column[6] == 'DEFAULT SERIAL (1)') {
+					$fld->auto_increment = true;
+					$fld->has_default = false;
+				} else {
+					$fld->default_value = $column[6];
+					switch($fld->type) {
+						case 'VARCHAR':
+						case 'CHARACTER':
+						case 'LONG':
+							$fld->default_value = $column[6];
+							break;
+						default:
+							$fld->default_value = trim($column[6]);
+							break;
+					}
+				}
+			}
+			$retarr[$fld->name] = $fld;	
+		}
+        if (isset($savem)) {
+        	$this->SetFetchMode($savem);
+        }
+        $ADODB_FETCH_MODE = $save;
+
+		return $retarr;
+	}
+	
+	function MetaColumnNames($table)
+	{
+		$table = $this->Quote(strtoupper($table));
+
+		return $this->GetCol("SELECT columnname FROM COLUMNS WHERE tablename=$table ORDER BY pos");
+	}
+	
+	// unlike it seems, this depends on the db-session and works in a multiuser environment
+	function _insertid($table,$column)
+	{
+		return empty($table) ? False : $this->GetOne("SELECT $table.CURRVAL FROM DUAL");
+	}
+
+	/*
+		SelectLimit implementation problems:
+	
+	 	The following will return random 10 rows as order by performed after "WHERE rowno<10"
+	 	which is not ideal...
+		
+	  		select * from table where rowno < 10 order by 1
+	  
+	  	This means that we have to use the adoconnection base class SelectLimit when
+	  	there is an "order by".
+		
+		See http://listserv.sap.com/pipermail/sapdb.general/2002-January/010405.html
+	 */
+	
+};
+ 
+
+class  ADORecordSet_sapdb extends ADORecordSet_odbc {	
+	
+	var $databaseType = "sapdb";		
+	
+	function ADORecordSet_sapdb($id,$mode=false)
+	{
+		$this->ADORecordSet_odbc($id,$mode);
+	}
+}
+
+} //define
+?>
Index: /Dev/trunk/rdfapi/util/adodb/drivers/adodb-sqlanywhere.inc.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/drivers/adodb-sqlanywhere.inc.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/drivers/adodb-sqlanywhere.inc.php	(revision 12)
@@ -0,0 +1,169 @@
+<?php
+/* 
+version V4.94 23 Jan 2007 (c) 2000-2007  John Lim (jlim#natsoft.com.my).  All rights
+reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence. 
+Set tabs to 4 for best viewing.
+
+  Latest version is available at http://adodb.sourceforge.net
+
+  21.02.2002 - Wade Johnson wade@wadejohnson.de
+			   Extended ODBC class for Sybase SQLAnywhere.
+   1) Added support to retrieve the last row insert ID on tables with
+	  primary key column using autoincrement function.
+
+   2) Added blob support.  Usage:
+		 a) create blob variable on db server:
+
+		$dbconn->create_blobvar($blobVarName);
+
+	  b) load blob var from file.  $filename must be complete path
+
+	  $dbcon->load_blobvar_from_file($blobVarName, $filename);
+
+	  c) Use the $blobVarName in SQL insert or update statement in the values
+	  clause:
+
+		$recordSet = $dbconn->Execute('INSERT INTO tabname (idcol, blobcol) '
+		.
+	   'VALUES (\'test\', ' . $blobVarName . ')');
+
+	 instead of loading blob from a file, you can also load from 
+	  an unformatted (raw) blob variable:
+	  $dbcon->load_blobvar_from_var($blobVarName, $varName);
+
+	  d) drop blob variable on db server to free up resources:
+	  $dbconn->drop_blobvar($blobVarName);
+
+  Sybase_SQLAnywhere data driver. Requires ODBC.
+
+*/
+
+// security - hide paths
+if (!defined('ADODB_DIR')) die();
+
+if (!defined('_ADODB_ODBC_LAYER')) {
+ include(ADODB_DIR."/drivers/adodb-odbc.inc.php");
+}
+
+if (!defined('ADODB_SYBASE_SQLANYWHERE')){
+
+ define('ADODB_SYBASE_SQLANYWHERE',1);
+
+ class ADODB_sqlanywhere extends ADODB_odbc {
+  	var $databaseType = "sqlanywhere";	
+	var $hasInsertID = true;
+	
+	function ADODB_sqlanywhere()
+	{
+		$this->ADODB_odbc();
+	}
+
+	 function _insertid() {
+  	   return $this->GetOne('select @@identity');
+	 }
+
+  function create_blobvar($blobVarName) {
+   $this->Execute("create variable $blobVarName long binary");
+   return;
+  }
+
+  function drop_blobvar($blobVarName) {
+   $this->Execute("drop variable $blobVarName");
+   return;
+  }
+
+  function load_blobvar_from_file($blobVarName, $filename) {
+   $chunk_size = 1000;
+
+   $fd = fopen ($filename, "rb");
+
+   $integer_chunks = (integer)filesize($filename) / $chunk_size;
+   $modulus = filesize($filename) % $chunk_size;
+   if ($modulus != 0){
+	$integer_chunks += 1;
+   }
+
+   for($loop=1;$loop<=$integer_chunks;$loop++){
+	$contents = fread ($fd, $chunk_size);
+	$contents = bin2hex($contents);
+
+	$hexstring = '';
+
+	for($loop2=0;$loop2<strlen($contents);$loop2+=2){
+	 $hexstring .= '\x' . substr($contents,$loop2,2);
+	 }
+
+	$hexstring = $this->qstr($hexstring);
+
+	$this->Execute("set $blobVarName = $blobVarName || " . $hexstring);
+   }
+
+   fclose ($fd);
+   return;
+  }
+
+  function load_blobvar_from_var($blobVarName, &$varName) {
+   $chunk_size = 1000;
+
+   $integer_chunks = (integer)strlen($varName) / $chunk_size;
+   $modulus = strlen($varName) % $chunk_size;
+   if ($modulus != 0){
+	$integer_chunks += 1;
+   }
+
+   for($loop=1;$loop<=$integer_chunks;$loop++){
+	$contents = substr ($varName, (($loop - 1) * $chunk_size), $chunk_size);
+	$contents = bin2hex($contents);
+
+	$hexstring = '';
+
+	for($loop2=0;$loop2<strlen($contents);$loop2+=2){
+	 $hexstring .= '\x' . substr($contents,$loop2,2);
+	 }
+
+	$hexstring = $this->qstr($hexstring);
+
+	$this->Execute("set $blobVarName = $blobVarName || " . $hexstring);
+   }
+
+   return;
+  }
+
+ /*
+  Insert a null into the blob field of the table first.
+  Then use UpdateBlob to store the blob.
+
+  Usage:
+
+  $conn->Execute('INSERT INTO blobtable (id, blobcol) VALUES (1, null)');
+  $conn->UpdateBlob('blobtable','blobcol',$blob,'id=1');
+ */
+  function UpdateBlob($table,$column,&$val,$where,$blobtype='BLOB')
+  {
+   $blobVarName = 'hold_blob';
+   $this->create_blobvar($blobVarName);
+   $this->load_blobvar_from_var($blobVarName, $val);
+   $this->Execute("UPDATE $table SET $column=$blobVarName WHERE $where");
+   $this->drop_blobvar($blobVarName);
+   return true;
+  }
+ }; //class
+
+ class  ADORecordSet_sqlanywhere extends ADORecordSet_odbc {	
+
+  var $databaseType = "sqlanywhere";		
+
+ function ADORecordSet_sqlanywhere($id,$mode=false)
+ {
+  $this->ADORecordSet_odbc($id,$mode);
+ }
+
+
+ }; //class
+
+
+} //define
+?>
Index: /Dev/trunk/rdfapi/util/adodb/drivers/adodb-sqlite.inc.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/drivers/adodb-sqlite.inc.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/drivers/adodb-sqlite.inc.php	(revision 12)
@@ -0,0 +1,398 @@
+<?php
+/*
+V4.94 23 Jan 2007  (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence.
+
+  Latest version is available at http://adodb.sourceforge.net
+  
+  SQLite info: http://www.hwaci.com/sw/sqlite/
+    
+  Install Instructions:
+  ====================
+  1. Place this in adodb/drivers
+  2. Rename the file, remove the .txt prefix.
+*/
+
+// security - hide paths
+if (!defined('ADODB_DIR')) die();
+
+class ADODB_sqlite extends ADOConnection {
+	var $databaseType = "sqlite";
+	var $replaceQuote = "''"; // string to use to replace quotes
+	var $concat_operator='||';
+	var $_errorNo = 0;
+	var $hasLimit = true;	
+	var $hasInsertID = true; 		/// supports autoincrement ID?
+	var $hasAffectedRows = true; 	/// supports affected rows for update/delete?
+	var $metaTablesSQL = "SELECT name FROM sqlite_master WHERE type='table' ORDER BY name";
+	var $sysDate = "adodb_date('Y-m-d')";
+	var $sysTimeStamp = "adodb_date('Y-m-d H:i:s')";
+	var $fmtTimeStamp = "'Y-m-d H:i:s'";
+	
+	function ADODB_sqlite() 
+	{
+	}
+	
+/*
+  function __get($name) 
+  {
+  	switch($name) {
+	case 'sysDate': return "'".date($this->fmtDate)."'";
+	case 'sysTimeStamp' : return "'".date($this->sysTimeStamp)."'";
+	}
+  }*/
+	
+	function ServerInfo()
+	{
+		$arr['version'] = sqlite_libversion();
+		$arr['description'] = 'SQLite ';
+		$arr['encoding'] = sqlite_libencoding();
+		return $arr;
+	}
+	
+	function BeginTrans()
+	{	  
+		 if ($this->transOff) return true; 
+		 $ret = $this->Execute("BEGIN TRANSACTION");
+		 $this->transCnt += 1;
+		 return true;
+	}
+	
+	function CommitTrans($ok=true) 
+	{ 
+		if ($this->transOff) return true; 
+		if (!$ok) return $this->RollbackTrans();
+		$ret = $this->Execute("COMMIT");
+		if ($this->transCnt>0)$this->transCnt -= 1;
+		return !empty($ret);
+	}
+	
+	function RollbackTrans()
+	{
+		if ($this->transOff) return true; 
+		$ret = $this->Execute("ROLLBACK");
+		if ($this->transCnt>0)$this->transCnt -= 1;
+		return !empty($ret);
+	}
+	
+	// mark newnham
+	function &MetaColumns($tab)
+	{
+	  global $ADODB_FETCH_MODE;
+	  $false = false;
+	  $save = $ADODB_FETCH_MODE;
+	  $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
+	  if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false);
+	  $rs = $this->Execute("PRAGMA table_info('$tab')");
+	  if (isset($savem)) $this->SetFetchMode($savem);
+	  if (!$rs) {
+	    $ADODB_FETCH_MODE = $save; 
+	    return $false;
+	  }
+	  $arr = array();
+	  while ($r = $rs->FetchRow()) {
+	    $type = explode('(',$r['type']);
+	    $size = '';
+	    if (sizeof($type)==2)
+	    $size = trim($type[1],')');
+	    $fn = strtoupper($r['name']);
+	    $fld = new ADOFieldObject;
+	    $fld->name = $r['name'];
+	    $fld->type = $type[0];
+	    $fld->max_length = $size;
+	    $fld->not_null = $r['notnull'];
+	    $fld->default_value = $r['dflt_value'];
+	    $fld->scale = 0;
+	    if ($save == ADODB_FETCH_NUM) $arr[] = $fld;	
+	    else $arr[strtoupper($fld->name)] = $fld;
+	  }
+	  $rs->Close();
+	  $ADODB_FETCH_MODE = $save;
+	  return $arr;
+	}
+	
+	function _init($parentDriver)
+	{
+	
+		$parentDriver->hasTransactions = false;
+		$parentDriver->hasInsertID = true;
+	}
+
+	function _insertid()
+	{
+		return sqlite_last_insert_rowid($this->_connectionID);
+	}
+	
+	function _affectedrows()
+	{
+        return sqlite_changes($this->_connectionID);
+    }
+	
+	function ErrorMsg() 
+ 	{
+		if ($this->_logsql) return $this->_errorMsg;
+		return ($this->_errorNo) ? sqlite_error_string($this->_errorNo) : '';
+	}
+ 
+	function ErrorNo() 
+	{
+		return $this->_errorNo;
+	}
+	
+	function SQLDate($fmt, $col=false)
+	{
+		$fmt = $this->qstr($fmt);
+		return ($col) ? "adodb_date2($fmt,$col)" : "adodb_date($fmt)";
+	}
+	
+	
+	function _createFunctions()
+	{
+		@sqlite_create_function($this->_connectionID, 'adodb_date', 'adodb_date', 1);
+		@sqlite_create_function($this->_connectionID, 'adodb_date2', 'adodb_date2', 2);
+	}
+	
+
+	// returns true or false
+	function _connect($argHostname, $argUsername, $argPassword, $argDatabasename)
+	{
+		if (!function_exists('sqlite_open')) return null;
+		if (empty($argHostname) && $argDatabasename) $argHostname = $argDatabasename;
+		
+		$this->_connectionID = sqlite_open($argHostname);
+		if ($this->_connectionID === false) return false;
+		$this->_createFunctions();
+		return true;
+	}
+	
+	// returns true or false
+	function _pconnect($argHostname, $argUsername, $argPassword, $argDatabasename)
+	{
+		if (!function_exists('sqlite_open')) return null;
+		if (empty($argHostname) && $argDatabasename) $argHostname = $argDatabasename;
+		
+		$this->_connectionID = sqlite_popen($argHostname);
+		if ($this->_connectionID === false) return false;
+		$this->_createFunctions();
+		return true;
+	}
+
+	// returns query ID if successful, otherwise false
+	function _query($sql,$inputarr=false)
+	{
+		$rez = sqlite_query($sql,$this->_connectionID);
+		if (!$rez) {
+			$this->_errorNo = sqlite_last_error($this->_connectionID);
+		}
+		
+		return $rez;
+	}
+	
+	function &SelectLimit($sql,$nrows=-1,$offset=-1,$inputarr=false,$secs2cache=0) 
+	{
+		$offsetStr = ($offset >= 0) ? " OFFSET $offset" : '';
+		$limitStr  = ($nrows >= 0)  ? " LIMIT $nrows" : ($offset >= 0 ? ' LIMIT 999999999' : '');
+	  	if ($secs2cache)
+	   		$rs =& $this->CacheExecute($secs2cache,$sql."$limitStr$offsetStr",$inputarr);
+	  	else
+	   		$rs =& $this->Execute($sql."$limitStr$offsetStr",$inputarr);
+			
+		return $rs;
+	}
+	
+	/*
+		This algorithm is not very efficient, but works even if table locking
+		is not available.
+		
+		Will return false if unable to generate an ID after $MAXLOOPS attempts.
+	*/
+	var $_genSeqSQL = "create table %s (id integer)";
+	
+	function GenID($seq='adodbseq',$start=1)
+	{	
+		// if you have to modify the parameter below, your database is overloaded,
+		// or you need to implement generation of id's yourself!
+		$MAXLOOPS = 100;
+		//$this->debug=1;
+		while (--$MAXLOOPS>=0) {
+			@($num = $this->GetOne("select id from $seq"));
+			if ($num === false) {
+				$this->Execute(sprintf($this->_genSeqSQL ,$seq));	
+				$start -= 1;
+				$num = '0';
+				$ok = $this->Execute("insert into $seq values($start)");
+				if (!$ok) return false;
+			} 
+			$this->Execute("update $seq set id=id+1 where id=$num");
+			
+			if ($this->affected_rows() > 0) {
+				$num += 1;
+				$this->genID = $num;
+				return $num;
+			}
+		}
+		if ($fn = $this->raiseErrorFn) {
+			$fn($this->databaseType,'GENID',-32000,"Unable to generate unique id after $MAXLOOPS attempts",$seq,$num);
+		}
+		return false;
+	}
+
+	function CreateSequence($seqname='adodbseq',$start=1)
+	{
+		if (empty($this->_genSeqSQL)) return false;
+		$ok = $this->Execute(sprintf($this->_genSeqSQL,$seqname));
+		if (!$ok) return false;
+		$start -= 1;
+		return $this->Execute("insert into $seqname values($start)");
+	}
+	
+	var $_dropSeqSQL = 'drop table %s';
+	function DropSequence($seqname)
+	{
+		if (empty($this->_dropSeqSQL)) return false;
+		return $this->Execute(sprintf($this->_dropSeqSQL,$seqname));
+	}
+	
+	// returns true or false
+	function _close()
+	{
+		return @sqlite_close($this->_connectionID);
+	}
+
+	function &MetaIndexes($table, $primary = FALSE, $owner=false)
+	{
+		$false = false;
+		// save old fetch mode
+        global $ADODB_FETCH_MODE;
+        $save = $ADODB_FETCH_MODE;
+        $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
+        if ($this->fetchMode !== FALSE) {
+               $savem = $this->SetFetchMode(FALSE);
+        }
+		$SQL=sprintf("SELECT name,sql FROM sqlite_master WHERE type='index' AND tbl_name='%s'", strtolower($table));
+        $rs = $this->Execute($SQL);
+        if (!is_object($rs)) {
+			if (isset($savem)) 
+				$this->SetFetchMode($savem);
+			$ADODB_FETCH_MODE = $save;
+            return $false;
+        }
+
+		$indexes = array ();
+		while ($row = $rs->FetchRow()) {
+			if ($primary && preg_match("/primary/i",$row[1]) == 0) continue;
+            if (!isset($indexes[$row[0]])) {
+
+			$indexes[$row[0]] = array(
+				   'unique' => preg_match("/unique/i",$row[1]),
+				   'columns' => array());
+			}
+			/**
+			  * There must be a more elegant way of doing this,
+			  * the index elements appear in the SQL statement
+			  * in cols[1] between parentheses
+			  * e.g CREATE UNIQUE INDEX ware_0 ON warehouse (org,warehouse)
+			  */
+			$cols = explode("(",$row[1]);
+			$cols = explode(")",$cols[1]);
+			array_pop($cols);
+			$indexes[$row[0]]['columns'] = $cols;
+		}
+		if (isset($savem)) { 
+            $this->SetFetchMode($savem);
+			$ADODB_FETCH_MODE = $save;
+		}
+        return $indexes;
+	}
+
+}
+
+/*--------------------------------------------------------------------------------------
+		 Class Name: Recordset
+--------------------------------------------------------------------------------------*/
+
+class ADORecordset_sqlite extends ADORecordSet {
+
+	var $databaseType = "sqlite";
+	var $bind = false;
+
+	function ADORecordset_sqlite($queryID,$mode=false)
+	{
+		
+		if ($mode === false) { 
+			global $ADODB_FETCH_MODE;
+			$mode = $ADODB_FETCH_MODE;
+		}
+		switch($mode) {
+		case ADODB_FETCH_NUM: $this->fetchMode = SQLITE_NUM; break;
+		case ADODB_FETCH_ASSOC: $this->fetchMode = SQLITE_ASSOC; break;
+		default: $this->fetchMode = SQLITE_BOTH; break;
+		}
+		$this->adodbFetchMode = $mode;
+		
+		$this->_queryID = $queryID;
+	
+		$this->_inited = true;
+		$this->fields = array();
+		if ($queryID) {
+			$this->_currentRow = 0;
+			$this->EOF = !$this->_fetch();
+			@$this->_initrs();
+		} else {
+			$this->_numOfRows = 0;
+			$this->_numOfFields = 0;
+			$this->EOF = true;
+		}
+		
+		return $this->_queryID;
+	}
+
+
+	function &FetchField($fieldOffset = -1)
+	{
+		$fld = new ADOFieldObject;
+		$fld->name = sqlite_field_name($this->_queryID, $fieldOffset);
+		$fld->type = 'VARCHAR';
+		$fld->max_length = -1;
+		return $fld;
+	}
+	
+   function _initrs()
+   {
+		$this->_numOfRows = @sqlite_num_rows($this->_queryID);
+		$this->_numOfFields = @sqlite_num_fields($this->_queryID);
+   }
+
+	function Fields($colname)
+	{
+		if ($this->fetchMode != SQLITE_NUM) return $this->fields[$colname];
+		if (!$this->bind) {
+			$this->bind = array();
+			for ($i=0; $i < $this->_numOfFields; $i++) {
+				$o = $this->FetchField($i);
+				$this->bind[strtoupper($o->name)] = $i;
+			}
+		}
+		
+		 return $this->fields[$this->bind[strtoupper($colname)]];
+	}
+	
+   function _seek($row)
+   {
+   		return sqlite_seek($this->_queryID, $row);
+   }
+
+	function _fetch($ignore_fields=false) 
+	{
+		$this->fields = @sqlite_fetch_array($this->_queryID,$this->fetchMode);
+		return !empty($this->fields);
+	}
+	
+	function _close() 
+	{
+	}
+
+}
+?>
Index: /Dev/trunk/rdfapi/util/adodb/drivers/adodb-sqlitepo.inc.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/drivers/adodb-sqlitepo.inc.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/drivers/adodb-sqlitepo.inc.php	(revision 12)
@@ -0,0 +1,62 @@
+<?php
+/*
+V4.94 23 Jan 2007  (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
+  Released under both BSD license and Lesser GPL library license.
+  Whenever there is any discrepancy between the two licenses,
+  the BSD license will take precedence.
+
+  Portable version of sqlite driver, to make it more similar to other database drivers.
+  The main differences are
+
+   1. When selecting (joining) multiple tables, in assoc mode the table
+   	  names are included in the assoc keys in the "sqlite" driver.
+	  
+	  In "sqlitepo" driver, the table names are stripped from the returned column names. 
+	  When this results in a conflict,  the first field get preference.
+
+	Contributed by Herman Kuiper  herman#ozuzo.net  
+*/
+
+if (!defined('ADODB_DIR')) die();
+
+include_once(ADODB_DIR.'/drivers/adodb-sqlite.inc.php');
+
+class ADODB_sqlitepo extends ADODB_sqlite {
+   var $databaseType = 'sqlitepo';
+
+   function ADODB_sqlitepo()
+   {
+      $this->ADODB_sqlite();
+   }
+}
+
+/*--------------------------------------------------------------------------------------
+       Class Name: Recordset
+--------------------------------------------------------------------------------------*/
+
+class ADORecordset_sqlitepo extends ADORecordset_sqlite {
+
+   var $databaseType = 'sqlitepo';
+
+   function ADORecordset_sqlitepo($queryID,$mode=false)
+   {
+      $this->ADORecordset_sqlite($queryID,$mode);
+   }
+   
+   // Modified to strip table names from returned fields
+   function _fetch($ignore_fields=false)
+   {
+      $this->fields = array();
+      $fields = @sqlite_fetch_array($this->_queryID,$this->fetchMode);
+      if(is_array($fields))
+         foreach($fields as $n => $v)
+         {
+            if(($p = strpos($n, ".")) !== false)
+               $n = substr($n, $p+1);
+            $this->fields[$n] = $v;
+         }
+
+      return !empty($this->fields);
+   }
+}
+?>
Index: /Dev/trunk/rdfapi/util/adodb/drivers/adodb-sybase.inc.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/drivers/adodb-sybase.inc.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/drivers/adodb-sybase.inc.php	(revision 12)
@@ -0,0 +1,418 @@
+<?php
+/* 
+V4.94 23 Jan 2007  (c) 2000-2007 John Lim. All rights reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence. 
+  Set tabs to 4 for best viewing.
+  
+  Latest version is available at http://adodb.sourceforge.net
+  
+  Sybase driver contributed by Toni (toni.tunkkari@finebyte.com)
+  
+  - MSSQL date patch applied.
+  
+  Date patch by Toni 15 Feb 2002
+*/
+ 
+ // security - hide paths
+if (!defined('ADODB_DIR')) die();
+
+class ADODB_sybase extends ADOConnection {
+	var $databaseType = "sybase";	
+	var $dataProvider = 'sybase';
+	var $replaceQuote = "''"; // string to use to replace quotes
+	var $fmtDate = "'Y-m-d'";
+	var $fmtTimeStamp = "'Y-m-d H:i:s'";
+	var $hasInsertID = true;
+	var $hasAffectedRows = true;
+  	var $metaTablesSQL="select name from sysobjects where type='U' or type='V'";
+	// see http://sybooks.sybase.com/onlinebooks/group-aw/awg0800e/dbrfen8/@ebt-link;pt=5981;uf=0?target=0;window=new;showtoc=true;book=dbrfen8
+	var $metaColumnsSQL = "SELECT c.column_name, c.column_type, c.width FROM syscolumn c, systable t WHERE t.table_name='%s' AND c.table_id=t.table_id AND t.table_type='BASE'";
+	/*
+	"select c.name,t.name,c.length from 
+	syscolumns c join systypes t on t.xusertype=c.xusertype join sysobjects o on o.id=c.id 
+	where o.name='%s'";
+	*/
+	var $concat_operator = '+'; 
+	var $arrayClass = 'ADORecordSet_array_sybase';
+	var $sysDate = 'GetDate()';
+	var $leftOuter = '*=';
+	var $rightOuter = '=*';
+	
+	function ADODB_sybase() 
+	{			
+	}
+ 
+	// might require begintrans -- committrans
+	function _insertid()
+	{
+		return $this->GetOne('select @@identity');
+	}
+	  // might require begintrans -- committrans
+	function _affectedrows()
+	{
+	   return $this->GetOne('select @@rowcount');
+	}
+
+			  
+	function BeginTrans()
+	{	
+	
+		if ($this->transOff) return true;
+		$this->transCnt += 1;
+		   
+		$this->Execute('BEGIN TRAN');
+		return true;
+	}
+	
+	function CommitTrans($ok=true) 
+	{ 
+		if ($this->transOff) return true;
+		
+		if (!$ok) return $this->RollbackTrans();
+	
+		$this->transCnt -= 1;
+		$this->Execute('COMMIT TRAN');
+		return true;
+	}
+	
+	function RollbackTrans()
+	{
+		if ($this->transOff) return true;
+		$this->transCnt -= 1;
+		$this->Execute('ROLLBACK TRAN');
+		return true;
+	}
+	
+	// http://www.isug.com/Sybase_FAQ/ASE/section6.1.html#6.1.4
+	function RowLock($tables,$where,$flds='top 1 null as ignore') 
+	{
+		if (!$this->_hastrans) $this->BeginTrans();
+		$tables = str_replace(',',' HOLDLOCK,',$tables);
+		return $this->GetOne("select $flds from $tables HOLDLOCK where $where");
+		
+	}	
+		
+	function SelectDB($dbName) 
+	{
+		$this->database = $dbName;
+		$this->databaseName = $dbName; # obsolete, retained for compat with older adodb versions
+		if ($this->_connectionID) {
+			return @sybase_select_db($dbName);		
+		}
+		else return false;	
+	}
+
+	/*	Returns: the last error message from previous database operation
+		Note: This function is NOT available for Microsoft SQL Server.	*/	
+
+	
+	function ErrorMsg()
+	{
+		if ($this->_logsql) return $this->_errorMsg;
+		if (function_exists('sybase_get_last_message'))
+			$this->_errorMsg = sybase_get_last_message();
+		else
+			$this->_errorMsg = isset($php_errormsg) ? $php_errormsg : 'SYBASE error messages not supported on this platform';
+		return $this->_errorMsg;
+	}
+
+	// returns true or false
+	function _connect($argHostname, $argUsername, $argPassword, $argDatabasename)
+	{
+		if (!function_exists('sybase_connect')) return null;
+		
+		$this->_connectionID = sybase_connect($argHostname,$argUsername,$argPassword);
+		if ($this->_connectionID === false) return false;
+		if ($argDatabasename) return $this->SelectDB($argDatabasename);
+		return true;	
+	}
+	// returns true or false
+	function _pconnect($argHostname, $argUsername, $argPassword, $argDatabasename)
+	{
+		if (!function_exists('sybase_connect')) return null;
+		
+		$this->_connectionID = sybase_pconnect($argHostname,$argUsername,$argPassword);
+		if ($this->_connectionID === false) return false;
+		if ($argDatabasename) return $this->SelectDB($argDatabasename);
+		return true;	
+	}
+	
+	// returns query ID if successful, otherwise false
+	function _query($sql,$inputarr)
+	{
+	global $ADODB_COUNTRECS;
+	
+		if ($ADODB_COUNTRECS == false && ADODB_PHPVER >= 0x4300)
+			return sybase_unbuffered_query($sql,$this->_connectionID);
+		else
+			return sybase_query($sql,$this->_connectionID);
+	}
+	
+	// See http://www.isug.com/Sybase_FAQ/ASE/section6.2.html#6.2.12
+	function &SelectLimit($sql,$nrows=-1,$offset=-1,$inputarr=false,$secs2cache=0) 
+	{
+		if ($secs2cache > 0) {// we do not cache rowcount, so we have to load entire recordset
+			$rs =& ADOConnection::SelectLimit($sql,$nrows,$offset,$inputarr,$secs2cache);
+			return $rs;
+		}
+		
+		$nrows = (integer) $nrows;
+		$offset = (integer) $offset;
+		
+		$cnt = ($nrows >= 0) ? $nrows : 999999999;
+		if ($offset > 0 && $cnt) $cnt += $offset;
+		
+		$this->Execute("set rowcount $cnt"); 
+		$rs =& ADOConnection::SelectLimit($sql,$nrows,$offset,$inputarr,0);
+		$this->Execute("set rowcount 0");
+		
+		return $rs;
+	}
+
+	// returns true or false
+	function _close()
+	{ 
+		return @sybase_close($this->_connectionID);
+	}
+	
+	function UnixDate($v)
+	{
+		return ADORecordSet_array_sybase::UnixDate($v);
+	}
+	
+	function UnixTimeStamp($v)
+	{
+		return ADORecordSet_array_sybase::UnixTimeStamp($v);
+	}	
+	
+	
+
+	# Added 2003-10-05 by Chris Phillipson
+    # Used ASA SQL Reference Manual -- http://sybooks.sybase.com/onlinebooks/group-aw/awg0800e/dbrfen8/@ebt-link;pt=16756?target=%25N%15_12018_START_RESTART_N%25
+    # to convert similar Microsoft SQL*Server (mssql) API into Sybase compatible version
+    // Format date column in sql string given an input format that understands Y M D
+    function SQLDate($fmt, $col=false)
+    {
+        if (!$col) $col = $this->sysTimeStamp;
+        $s = '';
+
+        $len = strlen($fmt);
+        for ($i=0; $i < $len; $i++) {
+            if ($s) $s .= '+';
+            $ch = $fmt[$i];
+            switch($ch) {
+            case 'Y':
+            case 'y':
+                $s .= "datename(yy,$col)";
+                break;
+            case 'M':
+                $s .= "convert(char(3),$col,0)";
+                break;
+            case 'm':
+                $s .= "replace(str(month($col),2),' ','0')";
+                break;
+            case 'Q':
+            case 'q':
+                $s .= "datename(qq,$col)";
+                break;
+            case 'D':
+            case 'd':
+                $s .= "replace(str(datepart(dd,$col),2),' ','0')";
+                break;
+            case 'h':
+                $s .= "substring(convert(char(14),$col,0),13,2)";
+                break;
+
+            case 'H':
+                $s .= "replace(str(datepart(hh,$col),2),' ','0')";
+                break;
+
+            case 'i':
+                $s .= "replace(str(datepart(mi,$col),2),' ','0')";
+                break;
+            case 's':
+                $s .= "replace(str(datepart(ss,$col),2),' ','0')";
+                break;
+            case 'a':
+            case 'A':
+                $s .= "substring(convert(char(19),$col,0),18,2)";
+                break;
+
+            default:
+                if ($ch == '\\') {
+                    $i++;
+                    $ch = substr($fmt,$i,1);
+                }
+                $s .= $this->qstr($ch);
+                break;
+            }
+        }
+        return $s;
+    }
+	
+	# Added 2003-10-07 by Chris Phillipson
+    # Used ASA SQL Reference Manual -- http://sybooks.sybase.com/onlinebooks/group-aw/awg0800e/dbrfen8/@ebt-link;pt=5981;uf=0?target=0;window=new;showtoc=true;book=dbrfen8
+    # to convert similar Microsoft SQL*Server (mssql) API into Sybase compatible version
+    function MetaPrimaryKeys($table)
+    {
+        $sql = "SELECT c.column_name " .
+               "FROM syscolumn c, systable t " .
+               "WHERE t.table_name='$table' AND c.table_id=t.table_id " .
+               "AND t.table_type='BASE' " .
+               "AND c.pkey = 'Y' " .
+               "ORDER BY c.column_id";
+
+        $a = $this->GetCol($sql);
+        if ($a && sizeof($a)>0) return $a;
+        return false;
+    }
+}
+	
+/*--------------------------------------------------------------------------------------
+	 Class Name: Recordset
+--------------------------------------------------------------------------------------*/
+global $ADODB_sybase_mths;
+$ADODB_sybase_mths = array(
+	'JAN'=>1,'FEB'=>2,'MAR'=>3,'APR'=>4,'MAY'=>5,'JUN'=>6,
+	'JUL'=>7,'AUG'=>8,'SEP'=>9,'OCT'=>10,'NOV'=>11,'DEC'=>12);
+
+class ADORecordset_sybase extends ADORecordSet {	
+
+	var $databaseType = "sybase";
+	var $canSeek = true;
+	// _mths works only in non-localised system
+	var  $_mths = array('JAN'=>1,'FEB'=>2,'MAR'=>3,'APR'=>4,'MAY'=>5,'JUN'=>6,'JUL'=>7,'AUG'=>8,'SEP'=>9,'OCT'=>10,'NOV'=>11,'DEC'=>12);	
+
+	function ADORecordset_sybase($id,$mode=false)
+	{
+		if ($mode === false) { 
+			global $ADODB_FETCH_MODE;
+			$mode = $ADODB_FETCH_MODE;
+		}
+		if (!$mode) $this->fetchMode = ADODB_FETCH_ASSOC;
+		else $this->fetchMode = $mode;
+		$this->ADORecordSet($id,$mode);
+	}
+	
+	/*	Returns: an object containing field information. 
+		Get column information in the Recordset object. fetchField() can be used in order to obtain information about
+		fields in a certain query result. If the field offset isn't specified, the next field that wasn't yet retrieved by
+		fetchField() is retrieved.	*/
+	function &FetchField($fieldOffset = -1) 
+	{
+		if ($fieldOffset != -1) {
+			$o = @sybase_fetch_field($this->_queryID, $fieldOffset);
+		}
+		else if ($fieldOffset == -1) {	/*	The $fieldOffset argument is not provided thus its -1 	*/
+			$o = @sybase_fetch_field($this->_queryID);
+		}
+		// older versions of PHP did not support type, only numeric
+		if ($o && !isset($o->type)) $o->type = ($o->numeric) ? 'float' : 'varchar';
+		return $o;
+	}
+	
+	function _initrs()
+	{
+	global $ADODB_COUNTRECS;
+		$this->_numOfRows = ($ADODB_COUNTRECS)? @sybase_num_rows($this->_queryID):-1;
+		$this->_numOfFields = @sybase_num_fields($this->_queryID);
+	}
+	
+	function _seek($row) 
+	{
+		return @sybase_data_seek($this->_queryID, $row);
+	}		
+
+	function _fetch($ignore_fields=false) 
+	{
+		if ($this->fetchMode == ADODB_FETCH_NUM) {
+			$this->fields = @sybase_fetch_row($this->_queryID);
+		} else if ($this->fetchMode == ADODB_FETCH_ASSOC) {
+			$this->fields = @sybase_fetch_row($this->_queryID);
+			if (is_array($this->fields)) {
+				$this->fields = $this->GetRowAssoc(ADODB_ASSOC_CASE);
+				return true;
+			}
+			return false;
+		}  else {
+			$this->fields = @sybase_fetch_array($this->_queryID);
+		}
+		if ( is_array($this->fields)) {
+			return true;
+		}
+
+		return false;
+	}
+	
+	/*	close() only needs to be called if you are worried about using too much memory while your script
+		is running. All associated result memory for the specified result identifier will automatically be freed.	*/
+	function _close() {
+		return @sybase_free_result($this->_queryID);		
+	}
+	
+	// sybase/mssql uses a default date like Dec 30 2000 12:00AM
+	function UnixDate($v)
+	{
+		return ADORecordSet_array_sybase::UnixDate($v);
+	}
+	
+	function UnixTimeStamp($v)
+	{
+		return ADORecordSet_array_sybase::UnixTimeStamp($v);
+	}
+}
+
+class ADORecordSet_array_sybase extends ADORecordSet_array {
+	function ADORecordSet_array_sybase($id=-1)
+	{
+		$this->ADORecordSet_array($id);
+	}
+	
+		// sybase/mssql uses a default date like Dec 30 2000 12:00AM
+	function UnixDate($v)
+	{
+	global $ADODB_sybase_mths;
+	
+		//Dec 30 2000 12:00AM
+		if (!ereg( "([A-Za-z]{3})[-/\. ]+([0-9]{1,2})[-/\. ]+([0-9]{4})"
+			,$v, $rr)) return parent::UnixDate($v);
+			
+		if ($rr[3] <= TIMESTAMP_FIRST_YEAR) return 0;
+		
+		$themth = substr(strtoupper($rr[1]),0,3);
+		$themth = $ADODB_sybase_mths[$themth];
+		if ($themth <= 0) return false;
+		// h-m-s-MM-DD-YY
+		return  mktime(0,0,0,$themth,$rr[2],$rr[3]);
+	}
+	
+	function UnixTimeStamp($v)
+	{
+	global $ADODB_sybase_mths;
+		//11.02.2001 Toni Tunkkari toni.tunkkari@finebyte.com
+		//Changed [0-9] to [0-9 ] in day conversion
+		if (!ereg( "([A-Za-z]{3})[-/\. ]([0-9 ]{1,2})[-/\. ]([0-9]{4}) +([0-9]{1,2}):([0-9]{1,2}) *([apAP]{0,1})"
+			,$v, $rr)) return parent::UnixTimeStamp($v);
+		if ($rr[3] <= TIMESTAMP_FIRST_YEAR) return 0;
+		
+		$themth = substr(strtoupper($rr[1]),0,3);
+		$themth = $ADODB_sybase_mths[$themth];
+		if ($themth <= 0) return false;
+		
+		switch (strtoupper($rr[6])) {
+		case 'P':
+			if ($rr[4]<12) $rr[4] += 12;
+			break;
+		case 'A':
+			if ($rr[4]==12) $rr[4] = 0;
+			break;
+		default:
+			break;
+		}
+		// h-m-s-MM-DD-YY
+		return  mktime($rr[4],$rr[5],0,$themth,$rr[2],$rr[3]);
+	}
+}
+?>
Index: /Dev/trunk/rdfapi/util/adodb/drivers/adodb-sybase_ase.inc.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/drivers/adodb-sybase_ase.inc.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/drivers/adodb-sybase_ase.inc.php	(revision 12)
@@ -0,0 +1,119 @@
+<?php
+/*
+  V4.94 23 Jan 2007  (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence.
+  
+  Set tabs to 4.
+  
+  Contributed by Interakt Online. Thx Cristian MARIN cristic#interaktonline.com
+*/
+
+
+require_once ADODB_DIR."/drivers/adodb-sybase.inc.php";
+
+class ADODB_sybase_ase extends ADODB_sybase {
+ 	var $databaseType = "sybase_ase";
+	
+	 var $metaTablesSQL="SELECT sysobjects.name FROM sysobjects, sysusers WHERE sysobjects.type='U' AND sysobjects.uid = sysusers.uid";
+	 var $metaColumnsSQL = "SELECT syscolumns.name AS field_name, systypes.name AS type, systypes.length AS width FROM sysobjects, syscolumns, systypes WHERE sysobjects.name='%s' AND syscolumns.id = sysobjects.id AND systypes.type=syscolumns.type";
+	 var $metaDatabasesSQL ="SELECT a.name FROM master.dbo.sysdatabases a, master.dbo.syslogins b WHERE a.suid = b.suid and a.name like '%' and a.name != 'tempdb' and a.status3 != 256  order by 1";
+
+	function ADODB_sybase_ase()
+	{
+	}
+	
+	// split the Views, Tables and procedures.
+	function &MetaTables($ttype=false,$showSchema=false,$mask=false)
+	{
+		$false = false;
+		if ($this->metaTablesSQL) {
+			// complicated state saving by the need for backward compat
+			
+			if ($ttype == 'VIEWS'){
+						$sql = str_replace('U', 'V', $this->metaTablesSQL);
+			}elseif (false === $ttype){
+						$sql = str_replace('U',"U' OR type='V", $this->metaTablesSQL);
+			}else{ // TABLES OR ANY OTHER 
+						$sql = $this->metaTablesSQL;
+			}
+			$rs = $this->Execute($sql);
+			
+			if ($rs === false || !method_exists($rs, 'GetArray')){
+					return $false;
+			}
+			$arr =& $rs->GetArray();
+
+			$arr2 = array();
+			foreach($arr as $key=>$value){
+					$arr2[] = trim($value['name']);
+			}
+			return $arr2;
+		}
+		return $false;
+	}
+
+	function MetaDatabases()
+	{
+			$arr = array();
+			if ($this->metaDatabasesSQL!='') {
+				$rs = $this->Execute($this->metaDatabasesSQL);
+				if ($rs && !$rs->EOF){
+					while (!$rs->EOF){
+						$arr[] = $rs->Fields('name');
+						$rs->MoveNext();
+					}
+					return $arr;
+				}
+			}
+			return false;
+	}
+
+	// fix a bug which prevent the metaColumns query to be executed for Sybase ASE
+	function &MetaColumns($table,$upper=false) 
+	{
+		$false = false;
+		if (!empty($this->metaColumnsSQL)) {
+		
+			$rs = $this->Execute(sprintf($this->metaColumnsSQL,$table));
+			if ($rs === false) return $false;
+
+			$retarr = array();
+			while (!$rs->EOF) {
+				$fld =& new ADOFieldObject();
+				$fld->name = $rs->Fields('field_name');
+				$fld->type = $rs->Fields('type');
+				$fld->max_length = $rs->Fields('width');
+				$retarr[strtoupper($fld->name)] = $fld;
+				$rs->MoveNext();
+			}
+			$rs->Close();
+			return $retarr;	
+		}
+		return $false;
+	}
+	
+	function getProcedureList($schema)
+	{
+			return false;
+	}
+
+	function ErrorMsg()
+	{
+		if (!function_exists('sybase_connect')){
+				return 'Your PHP doesn\'t contain the Sybase connection module!';
+		}
+		return parent::ErrorMsg();	
+	}
+}
+
+class adorecordset_sybase_ase extends ADORecordset_sybase {
+var $databaseType = "sybase_ase";
+function ADORecordset_sybase_ase($id,$mode=false)
+	{
+		$this->ADORecordSet_sybase($id,$mode);
+	}
+	
+}
+?>
Index: /Dev/trunk/rdfapi/util/adodb/drivers/adodb-vfp.inc.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/drivers/adodb-vfp.inc.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/drivers/adodb-vfp.inc.php	(revision 12)
@@ -0,0 +1,107 @@
+<?php
+/* 
+V4.94 23 Jan 2007  (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence. 
+Set tabs to 4 for best viewing.
+  
+  Latest version is available at http://adodb.sourceforge.net
+  
+  Microsoft Visual FoxPro data driver. Requires ODBC. Works only on MS Windows.
+*/
+
+// security - hide paths
+if (!defined('ADODB_DIR')) die();
+
+if (!defined('_ADODB_ODBC_LAYER')) {
+	include(ADODB_DIR."/drivers/adodb-odbc.inc.php");
+}
+if (!defined('ADODB_VFP')){
+define('ADODB_VFP',1);
+class ADODB_vfp extends ADODB_odbc {
+	var $databaseType = "vfp";	
+	var $fmtDate = "{^Y-m-d}";
+	var $fmtTimeStamp = "{^Y-m-d, h:i:sA}";
+	var $replaceQuote = "'+chr(39)+'" ;
+	var $true = '.T.';
+	var $false = '.F.';
+	var $hasTop = 'top';		// support mssql SELECT TOP 10 * FROM TABLE
+	var $_bindInputArray = false; // strangely enough, setting to true does not work reliably
+	var $sysTimeStamp = 'datetime()';
+	var $sysDate = 'date()';
+	var $ansiOuter = true;
+	var $hasTransactions = false;
+	var $curmode = false ; // See sqlext.h, SQL_CUR_DEFAULT == SQL_CUR_USE_DRIVER == 2L
+	
+	function ADODB_vfp()
+	{
+		$this->ADODB_odbc();
+	}
+	
+	function Time()
+	{
+		return time();
+	}
+	
+	function BeginTrans() { return false;}
+	
+	// quote string to be sent back to database
+	function qstr($s,$nofixquotes=false)
+	{
+		if (!$nofixquotes) return  "'".str_replace("\r\n","'+chr(13)+'",str_replace("'",$this->replaceQuote,$s))."'";
+		return "'".$s."'";
+	}
+
+	
+	// TOP requires ORDER BY for VFP
+	function &SelectLimit($sql,$nrows=-1,$offset=-1, $inputarr=false,$secs2cache=0)
+	{
+		$this->hasTop = preg_match('/ORDER[ \t\r\n]+BY/is',$sql) ? 'top' : false;
+		$ret = ADOConnection::SelectLimit($sql,$nrows,$offset,$inputarr,$secs2cache);
+		return $ret;
+	}
+	
+
+
+};
+ 
+
+class  ADORecordSet_vfp extends ADORecordSet_odbc {	
+	
+	var $databaseType = "vfp";		
+
+	
+	function ADORecordSet_vfp($id,$mode=false)
+	{
+		return $this->ADORecordSet_odbc($id,$mode);
+	}
+
+	function MetaType($t,$len=-1)
+	{
+		if (is_object($t)) {
+			$fieldobj = $t;
+			$t = $fieldobj->type;
+			$len = $fieldobj->max_length;
+		}
+		switch (strtoupper($t)) {
+		case 'C':
+			if ($len <= $this->blobSize) return 'C';
+		case 'M':
+			return 'X';
+			 
+		case 'D': return 'D';
+		
+		case 'T': return 'T';
+		
+		case 'L': return 'L';
+		
+		case 'I': return 'I';
+		
+		default: return 'N';
+		}
+	}
+}
+
+} //define
+?>
Index: /Dev/trunk/rdfapi/util/adodb/lang/adodb-ar.inc.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/lang/adodb-ar.inc.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/lang/adodb-ar.inc.php	(revision 12)
@@ -0,0 +1,34 @@
+<?php
+// by "El-Shamaa, Khaled" <k.el-shamaa#cgiar.org>
+$ADODB_LANG_ARRAY = array (
+			'LANG'			    => 'ar',
+	    DB_ERROR			=> 'ÎØÃ ÛíÑ ãÍÏÏ',
+	    DB_ERROR_ALREADY_EXISTS	=> 'ãæÌæÏ ãÓÈÞÇ',
+	    DB_ERROR_CANNOT_CREATE	=> 'áÇ íãßä ÅäÔÇÁ',
+	    DB_ERROR_CANNOT_DELETE	=> 'áÇ íãßä ÍÐÝ',
+	    DB_ERROR_CANNOT_DROP	=> 'áÇ íãßä ÍÐÝ',
+	    DB_ERROR_CONSTRAINT 	=> 'ÚãáíÉ ÅÏÎÇá ããäæÚÉ',
+	    DB_ERROR_DIVZERO		=> 'ÚãáíÉ ÇáÊÞÓíã Úáì ÕÝÑ',
+	    DB_ERROR_INVALID		=> 'ÛíÑ ÕÍíÍ',
+	    DB_ERROR_INVALID_DATE	=> 'ÕíÛÉ æÞÊ Ãæ ÊÇÑíÎ ÛíÑ ÕÍíÍÉ',
+	    DB_ERROR_INVALID_NUMBER	=> 'ÕíÛÉ ÑÞã ÛíÑ ÕÍíÍÉ',
+	    DB_ERROR_MISMATCH		=> 'ÛíÑ ãÊØÇÈÞ',
+	    DB_ERROR_NODBSELECTED	=> 'áã íÊã ÅÎÊíÇÑ ÞÇÚÏÉ ÇáÈíÇäÇÊ ÈÚÏ',
+	    DB_ERROR_NOSUCHFIELD	=> 'áíÓ åäÇáß ÍÞá ÈåÐÇ ÇáÇÓã',
+	    DB_ERROR_NOSUCHTABLE	=> 'áíÓ åäÇáß ÌÏæá ÈåÐÇ ÇáÇÓã',
+	    DB_ERROR_NOT_CAPABLE	=> 'ÞÇÚÏÉ ÇáÈíÇäÇÊ ÇáãÑÊÈØ ÈåÇ ÛíÑ ÞÇÏÑÉ',
+	    DB_ERROR_NOT_FOUND		=> 'áã íÊã ÅíÌÇÏå',
+	    DB_ERROR_NOT_LOCKED 	=> 'ÛíÑ ãÞÝæá',
+	    DB_ERROR_SYNTAX		=> 'ÎØÃ Ýí ÇáÕíÛÉ',
+	    DB_ERROR_UNSUPPORTED	=> 'ÛíÑ ãÏÚæã',
+	    DB_ERROR_VALUE_COUNT_ON_ROW => 'ÚÏÏ ÇáÞíã Ýí ÇáÓÌá',
+	    DB_ERROR_INVALID_DSN	=> 'DSN ÛíÑ ÕÍíÍ',
+	    DB_ERROR_CONNECT_FAILED	=> 'ÝÔá ÚãáíÉ ÇáÅÊÕÇá',
+	    0			       => 'áíÓ åäÇáß ÃÎØÇÁ', // DB_OK
+	    DB_ERROR_NEED_MORE_DATA	=> 'ÇáÈíÇäÇÊ ÇáãÒæÏÉ ÛíÑ ßÇÝíÉ',
+	    DB_ERROR_EXTENSION_NOT_FOUND=> 'áã íÊã ÅíÌÇÏ ÇáÅÖÇÝÉ ÇáãÊÚáÞÉ',
+	    DB_ERROR_NOSUCHDB		=> 'áíÓ åäÇáß ÞÇÚÏÉ ÈíÇäÇÊ ÈåÐÇ ÇáÇÓã',
+	    DB_ERROR_ACCESS_VIOLATION	=> 'ÓãÇÍíÇÊ ÛíÑ ßÇÝíÉ'
+);
+?>
+		
Index: /Dev/trunk/rdfapi/util/adodb/lang/adodb-bg.inc.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/lang/adodb-bg.inc.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/lang/adodb-bg.inc.php	(revision 12)
@@ -0,0 +1,38 @@
+<?php
+/*
+	Bulgarian language, v1.0, 25.03.2004, encoding by Windows-1251 charset
+	contributed by Valentin Sheiretsky <valio#valio.eu.org>
+*/
+
+$ADODB_LANG_ARRAY = array (
+			'LANG'                      => 'bg',
+            DB_ERROR                    => 'íåèçâåñòíà ãðåøêà',
+            DB_ERROR_ALREADY_EXISTS     => 'âå÷å ñúùåñòâóâà',
+            DB_ERROR_CANNOT_CREATE      => 'íå ìîæå äà áúäå ñúçäàäåíà',
+            DB_ERROR_CANNOT_DELETE      => 'íå ìîæå äà áúäå èçòðèòà',
+            DB_ERROR_CANNOT_DROP        => 'íå ìîæå äà áúäå óíèùîæåíà',
+            DB_ERROR_CONSTRAINT         => 'íàðóøåíî óñëîâèå',
+            DB_ERROR_DIVZERO            => 'äåëåíèå íà íóëà',
+            DB_ERROR_INVALID            => 'íåïðàâèëíî',
+            DB_ERROR_INVALID_DATE       => 'íåêîðåêòíà äàòà èëè ÷àñ',
+            DB_ERROR_INVALID_NUMBER     => 'íåâàëèäåí íîìåð',
+            DB_ERROR_MISMATCH           => 'ïîãðåøíà óïîòðåáà',
+            DB_ERROR_NODBSELECTED       => 'íå å èçáðàíà áàçà äàííè',
+            DB_ERROR_NOSUCHFIELD        => 'íåñúùåñòâóâàùî ïîëå',
+            DB_ERROR_NOSUCHTABLE        => 'íåñúùåñòâóâàùà òàáëèöà',
+            DB_ERROR_NOT_CAPABLE        => 'DB backend not capable',
+            DB_ERROR_NOT_FOUND          => 'íå å íàìåðåíà',
+            DB_ERROR_NOT_LOCKED         => 'íå å çàêëþ÷åíà',
+            DB_ERROR_SYNTAX             => 'ãðåøåí ñèíòàêñèñ',
+            DB_ERROR_UNSUPPORTED        => 'íå ñå ïîääúðæà',
+            DB_ERROR_VALUE_COUNT_ON_ROW => 'íåêîðåêòåí áðîé êîëîíè â ðåäà',
+            DB_ERROR_INVALID_DSN        => 'íåâàëèäåí DSN',
+            DB_ERROR_CONNECT_FAILED     => 'âðúçêàòà íå ìîæå äà áúäå îñúùåñòâåíà',
+            0	                        => 'íÿìà ãðåøêè', // DB_OK
+            DB_ERROR_NEED_MORE_DATA     => 'ïðåäîñòàâåíèòå äàííè ñà íåäîñòàòú÷íè',
+            DB_ERROR_EXTENSION_NOT_FOUND=> 'ðàçøèðåíèåòî íå å íàìåðåíî',
+            DB_ERROR_NOSUCHDB           => 'íåñúùåñòâóâàùà áàçà äàííè',
+            DB_ERROR_ACCESS_VIOLATION   => 'íÿìàòå äîñòàòú÷íî ïðàâà'
+);
+?>
+		
Index: /Dev/trunk/rdfapi/util/adodb/lang/adodb-bgutf8.inc.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/lang/adodb-bgutf8.inc.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/lang/adodb-bgutf8.inc.php	(revision 12)
@@ -0,0 +1,38 @@
+﻿<?php
+/*
+	Bulgarian language, v1.0, 25.03.2004, encoding by UTF-8 charset
+	contributed by Valentin Sheiretsky <valio#valio.eu.org>
+*/
+
+$ADODB_LANG_ARRAY = array (
+            'LANG'                      => 'bgutf8',
+            DB_ERROR                    => 'неизвестна грешка',
+            DB_ERROR_ALREADY_EXISTS     => 'вече съществува',
+            DB_ERROR_CANNOT_CREATE      => 'не може да бъде създадена',
+            DB_ERROR_CANNOT_DELETE      => 'не може да бъде изтрита',
+            DB_ERROR_CANNOT_DROP        => 'не може да бъде унищожена',
+            DB_ERROR_CONSTRAINT         => 'нарушено условие',
+            DB_ERROR_DIVZERO            => 'деление на нула',
+            DB_ERROR_INVALID            => 'неправилно',
+            DB_ERROR_INVALID_DATE       => 'некоректна дата или час',
+            DB_ERROR_INVALID_NUMBER     => 'невалиден номер',
+            DB_ERROR_MISMATCH           => 'погрешна употреба',
+            DB_ERROR_NODBSELECTED       => 'не е избрана база данни',
+            DB_ERROR_NOSUCHFIELD        => 'несъществуващо поле',
+            DB_ERROR_NOSUCHTABLE        => 'несъществуваща таблица',
+            DB_ERROR_NOT_CAPABLE        => 'DB backend not capable',
+            DB_ERROR_NOT_FOUND          => 'не е намерена',
+            DB_ERROR_NOT_LOCKED         => 'не е заключена',
+            DB_ERROR_SYNTAX             => 'грешен синтаксис',
+            DB_ERROR_UNSUPPORTED        => 'не се поддържа',
+            DB_ERROR_VALUE_COUNT_ON_ROW => 'некоректен брой колони в реда',
+            DB_ERROR_INVALID_DSN        => 'невалиден DSN',
+            DB_ERROR_CONNECT_FAILED     => 'връзката не може да бъде осъществена',
+            0	                        => 'няма грешки', // DB_OK
+            DB_ERROR_NEED_MORE_DATA     => 'предоставените данни са недостатъчни',
+            DB_ERROR_EXTENSION_NOT_FOUND=> 'разширението не е намерено',
+            DB_ERROR_NOSUCHDB           => 'несъществуваща база данни',
+            DB_ERROR_ACCESS_VIOLATION   => 'нямате достатъчно права'
+);
+?>
+		
Index: /Dev/trunk/rdfapi/util/adodb/lang/adodb-ca.inc.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/lang/adodb-ca.inc.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/lang/adodb-ca.inc.php	(revision 12)
@@ -0,0 +1,35 @@
+<?php
+// Catalan language
+// contributed by "Josep Lladonosa" jlladono#pie.xtec.es
+$ADODB_LANG_ARRAY = array (
+			'LANG'                      => 'ca',
+            DB_ERROR                    => 'error desconegut',
+            DB_ERROR_ALREADY_EXISTS     => 'ja existeix',
+            DB_ERROR_CANNOT_CREATE      => 'no es pot crear',
+            DB_ERROR_CANNOT_DELETE      => 'no es pot esborrar',
+            DB_ERROR_CANNOT_DROP        => 'no es pot eliminar',
+            DB_ERROR_CONSTRAINT         => 'violació de constraint',
+            DB_ERROR_DIVZERO            => 'divisió per zero',
+            DB_ERROR_INVALID            => 'no és vàlid',
+            DB_ERROR_INVALID_DATE       => 'la data o l\'hora no són vàlides',
+            DB_ERROR_INVALID_NUMBER     => 'el nombre no és vàlid',
+            DB_ERROR_MISMATCH           => 'no hi ha coincidència',
+            DB_ERROR_NODBSELECTED       => 'cap base de dades seleccionada',
+            DB_ERROR_NOSUCHFIELD        => 'camp inexistent',
+            DB_ERROR_NOSUCHTABLE        => 'taula inexistent',
+            DB_ERROR_NOT_CAPABLE        => 'l\'execució secundària de DB no pot',
+            DB_ERROR_NOT_FOUND          => 'no trobat',
+            DB_ERROR_NOT_LOCKED         => 'no blocat',
+            DB_ERROR_SYNTAX             => 'error de sintaxi',
+            DB_ERROR_UNSUPPORTED        => 'no suportat',
+            DB_ERROR_VALUE_COUNT_ON_ROW => 'el nombre de columnes no coincideix amb el nombre de valors en la fila',
+            DB_ERROR_INVALID_DSN        => 'el DSN no és vàlid',
+            DB_ERROR_CONNECT_FAILED     => 'connexió fallida',
+            0	                       => 'cap error', // DB_OK
+            DB_ERROR_NEED_MORE_DATA     => 'les dades subministrades són insuficients',
+            DB_ERROR_EXTENSION_NOT_FOUND=> 'extensió no trobada',
+            DB_ERROR_NOSUCHDB           => 'base de dades inexistent',
+            DB_ERROR_ACCESS_VIOLATION   => 'permisos insuficients'
+);
+?>
+		
Index: /Dev/trunk/rdfapi/util/adodb/lang/adodb-cn.inc.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/lang/adodb-cn.inc.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/lang/adodb-cn.inc.php	(revision 12)
@@ -0,0 +1,35 @@
+<?php
+// Chinese language file contributed by "Cuiyan (cysoft)" cysoft#php.net.
+// Encode by GB2312
+// Simplified Chinese
+$ADODB_LANG_ARRAY = array (
+			'LANG'                      => 'cn',
+            DB_ERROR                    => 'ÎŽÖªŽíÎó',
+            DB_ERROR_ALREADY_EXISTS     => 'ÒÑŸ­ŽæÔÚ',
+            DB_ERROR_CANNOT_CREATE      => '²»ÄÜŽŽœš',
+            DB_ERROR_CANNOT_DELETE      => '²»ÄÜÉŸ³ý',
+            DB_ERROR_CANNOT_DROP        => '²»ÄÜ¶ªÆú',
+            DB_ERROR_CONSTRAINT         => 'ÔŒÊøÏÞÖÆ',
+            DB_ERROR_DIVZERO            => '±»0³ý',
+            DB_ERROR_INVALID            => 'ÎÞÐ§',
+            DB_ERROR_INVALID_DATE       => 'ÎÞÐ§µÄÈÕÆÚ»òÕßÊ±Œä',
+            DB_ERROR_INVALID_NUMBER     => 'ÎÞÐ§µÄÊý×Ö',
+            DB_ERROR_MISMATCH           => '²»Æ¥Åä',
+            DB_ERROR_NODBSELECTED       => 'Ã»ÓÐÊýŸÝ¿â±»Ñ¡Ôñ',
+            DB_ERROR_NOSUCHFIELD        => 'Ã»ÓÐÏàÓŠµÄ×Ö¶Î',
+            DB_ERROR_NOSUCHTABLE        => 'Ã»ÓÐÏàÓŠµÄ±í',
+            DB_ERROR_NOT_CAPABLE        => 'ÊýŸÝ¿âºóÌš²»ŒæÈÝ',
+            DB_ERROR_NOT_FOUND          => 'Ã»ÓÐ·¢ÏÖ',
+            DB_ERROR_NOT_LOCKED         => 'Ã»ÓÐ±»Ëø¶š',
+            DB_ERROR_SYNTAX             => 'Óï·šŽíÎó',
+            DB_ERROR_UNSUPPORTED        => '²»Ö§³Ö',
+            DB_ERROR_VALUE_COUNT_ON_ROW => 'ÔÚÐÐÉÏÀÛŒÆÖµ',
+            DB_ERROR_INVALID_DSN        => 'ÎÞÐ§µÄÊýŸÝÔŽ (DSN)',
+            DB_ERROR_CONNECT_FAILED     => 'Á¬œÓÊ§°Ü',
+            0	                       => 'Ã»ÓÐŽíÎó', // DB_OK
+            DB_ERROR_NEED_MORE_DATA     => 'Ìá¹©µÄÊýŸÝ²»ÄÜ·ûºÏÒªÇó',
+            DB_ERROR_EXTENSION_NOT_FOUND=> 'À©Õ¹Ã»ÓÐ±»·¢ÏÖ',
+            DB_ERROR_NOSUCHDB           => 'Ã»ÓÐÏàÓŠµÄÊýŸÝ¿â',
+            DB_ERROR_ACCESS_VIOLATION   => 'Ã»ÓÐºÏÊÊµÄÈšÏÞ'
+);
+?>
Index: /Dev/trunk/rdfapi/util/adodb/lang/adodb-cz.inc.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/lang/adodb-cz.inc.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/lang/adodb-cz.inc.php	(revision 12)
@@ -0,0 +1,40 @@
+<?php
+
+# Czech language, encoding by ISO 8859-2 charset (Iso Latin-2)
+# For convert to MS Windows use shell command:
+#    iconv -f ISO_8859-2 -t CP1250 < adodb-cz.inc.php
+# For convert to ASCII use shell command:
+#    unaccent ISO_8859-2 < adodb-cz.inc.php
+# v1.0, 19.06.2003 Kamil Jakubovic <jake@host.sk>
+
+$ADODB_LANG_ARRAY = array (
+            'LANG'                      => 'cz',
+            DB_ERROR                    => 'neznámá chyba',
+            DB_ERROR_ALREADY_EXISTS     => 'ji? existuje',
+            DB_ERROR_CANNOT_CREATE      => 'nelze vytvo?it',
+            DB_ERROR_CANNOT_DELETE      => 'nelze smazat',
+            DB_ERROR_CANNOT_DROP        => 'nelze odstranit',
+            DB_ERROR_CONSTRAINT         => 'poru?ení omezující podmínky',
+            DB_ERROR_DIVZERO            => 'd?lení nulou',
+            DB_ERROR_INVALID            => 'neplatné',
+            DB_ERROR_INVALID_DATE       => 'neplatné datum nebo ?as',
+            DB_ERROR_INVALID_NUMBER     => 'neplatné ?íslo',
+            DB_ERROR_MISMATCH           => 'nesouhlasí',
+            DB_ERROR_NODBSELECTED       => '?ádná databáze není vybrána',
+            DB_ERROR_NOSUCHFIELD        => 'pole nenalezeno',
+            DB_ERROR_NOSUCHTABLE        => 'tabulka nenalezena',
+            DB_ERROR_NOT_CAPABLE        => 'nepodporováno',
+            DB_ERROR_NOT_FOUND          => 'nenalezeno',
+            DB_ERROR_NOT_LOCKED         => 'nezam?eno',
+            DB_ERROR_SYNTAX             => 'syntaktická chyba',
+            DB_ERROR_UNSUPPORTED        => 'nepodporováno',
+            DB_ERROR_VALUE_COUNT_ON_ROW => '',
+            DB_ERROR_INVALID_DSN        => 'neplatné DSN',
+            DB_ERROR_CONNECT_FAILED     => 'p?ipojení selhalo',
+            0	                        => 'bez chyb', // DB_OK
+            DB_ERROR_NEED_MORE_DATA     => 'málo zdrojových dat',
+            DB_ERROR_EXTENSION_NOT_FOUND=> 'roz?í?ení nenalezeno',
+            DB_ERROR_NOSUCHDB           => 'databáze neexistuje',
+            DB_ERROR_ACCESS_VIOLATION   => 'nedostate?ná práva'
+);
+?>
Index: /Dev/trunk/rdfapi/util/adodb/lang/adodb-da.inc.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/lang/adodb-da.inc.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/lang/adodb-da.inc.php	(revision 12)
@@ -0,0 +1,33 @@
+<?php
+// Arne Eckmann bananstat#users.sourceforge.net
+$ADODB_LANG_ARRAY = array (
+  	    'LANG'                      => 'da',
+            DB_ERROR                    => 'ukendt fejl',
+            DB_ERROR_ALREADY_EXISTS     => 'eksisterer allerede',
+            DB_ERROR_CANNOT_CREATE      => 'kan ikke oprette',
+            DB_ERROR_CANNOT_DELETE      => 'kan ikke slette',
+            DB_ERROR_CANNOT_DROP        => 'kan ikke droppe',
+            DB_ERROR_CONSTRAINT         => 'begr&aelig;nsning kr&aelig;nket',
+            DB_ERROR_DIVZERO            => 'division med nul',
+            DB_ERROR_INVALID            => 'ugyldig',
+            DB_ERROR_INVALID_DATE       => 'ugyldig dato eller klokkeslet',
+            DB_ERROR_INVALID_NUMBER     => 'ugyldigt tal',
+            DB_ERROR_MISMATCH           => 'mismatch',
+            DB_ERROR_NODBSELECTED       => 'ingen database valgt',
+            DB_ERROR_NOSUCHFIELD        => 'felt findes ikke',
+            DB_ERROR_NOSUCHTABLE        => 'tabel findes ikke',
+            DB_ERROR_NOT_CAPABLE        => 'DB backend opgav',
+            DB_ERROR_NOT_FOUND          => 'ikke fundet',
+            DB_ERROR_NOT_LOCKED         => 'ikke l&aring;st',
+            DB_ERROR_SYNTAX             => 'syntaksfejl',
+            DB_ERROR_UNSUPPORTED        => 'ikke underst&oslash;ttet',
+            DB_ERROR_VALUE_COUNT_ON_ROW => 'resulterende antal felter svarer ikke til foresp&oslash;rgslens antal felter',
+            DB_ERROR_INVALID_DSN        => 'ugyldig DSN',
+            DB_ERROR_CONNECT_FAILED     => 'tilslutning mislykkedes',
+            0	                        => 'ingen fejl', // DB_OK
+            DB_ERROR_NEED_MORE_DATA     => 'utilstr&aelig;kkelige data angivet',
+            DB_ERROR_EXTENSION_NOT_FOUND=> 'udvidelse ikke fundet',
+            DB_ERROR_NOSUCHDB           => 'database ikke fundet',
+            DB_ERROR_ACCESS_VIOLATION   => 'utilstr&aelig;kkelige rettigheder'
+);
+?>
Index: /Dev/trunk/rdfapi/util/adodb/lang/adodb-de.inc.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/lang/adodb-de.inc.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/lang/adodb-de.inc.php	(revision 12)
@@ -0,0 +1,33 @@
+<?php
+// contributed by "Heinz Hombergs" <opn@hhombergs.de>
+$ADODB_LANG_ARRAY = array (
+			'LANG'                      => 'de',
+			DB_ERROR                    => 'Unbekannter Fehler',
+            DB_ERROR_ALREADY_EXISTS     => 'existiert bereits',
+            DB_ERROR_CANNOT_CREATE      => 'kann nicht erstellen',
+            DB_ERROR_CANNOT_DELETE      => 'kann nicht l&ouml;schen',
+            DB_ERROR_CANNOT_DROP        => 'Tabelle oder Index konnte nicht gel&ouml;scht werden',
+            DB_ERROR_CONSTRAINT         => 'Constraint Verletzung',
+            DB_ERROR_DIVZERO            => 'Division durch Null',
+            DB_ERROR_INVALID            => 'ung&uml;ltig',
+            DB_ERROR_INVALID_DATE       => 'ung&uml;ltiges Datum oder Zeit',
+            DB_ERROR_INVALID_NUMBER     => 'ung&uml;ltige Zahl',
+            DB_ERROR_MISMATCH           => 'Unvertr&auml;glichkeit',
+            DB_ERROR_NODBSELECTED       => 'keine Dantebank ausgew&auml;hlt',
+            DB_ERROR_NOSUCHFIELD        => 'Feld nicht vorhanden',
+            DB_ERROR_NOSUCHTABLE        => 'Tabelle nicht vorhanden',
+            DB_ERROR_NOT_CAPABLE        => 'Funktion nicht installiert',
+            DB_ERROR_NOT_FOUND          => 'nicht gefunden',
+            DB_ERROR_NOT_LOCKED         => 'nicht gesperrt',
+            DB_ERROR_SYNTAX             => 'Syntaxfehler',
+            DB_ERROR_UNSUPPORTED        => 'nicht Unterst&uml;tzt',
+            DB_ERROR_VALUE_COUNT_ON_ROW => 'Anzahl der zur&uml;ckgelieferten Felder entspricht nicht der Anzahl der Felder in der Abfrage',
+            DB_ERROR_INVALID_DSN        => 'ung&uml;ltiger DSN',
+            DB_ERROR_CONNECT_FAILED     => 'Verbindung konnte nicht hergestellt werden',
+            0	                       => 'kein Fehler', // DB_OK
+            DB_ERROR_NEED_MORE_DATA     => 'Nicht gen&uml;gend Daten geliefert',
+            DB_ERROR_EXTENSION_NOT_FOUND=> 'erweiterung nicht gefunden',
+            DB_ERROR_NOSUCHDB           => 'keine Datenbank',
+            DB_ERROR_ACCESS_VIOLATION   => 'ungen&uml;gende Rechte'
+);
+?>
Index: /Dev/trunk/rdfapi/util/adodb/lang/adodb-en.inc.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/lang/adodb-en.inc.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/lang/adodb-en.inc.php	(revision 12)
@@ -0,0 +1,34 @@
+<?php
+
+$ADODB_LANG_ARRAY = array (
+			'LANG'                      => 'en',
+            DB_ERROR                    => 'unknown error',
+            DB_ERROR_ALREADY_EXISTS     => 'already exists',
+            DB_ERROR_CANNOT_CREATE      => 'can not create',
+            DB_ERROR_CANNOT_DELETE      => 'can not delete',
+            DB_ERROR_CANNOT_DROP        => 'can not drop',
+            DB_ERROR_CONSTRAINT         => 'constraint violation',
+            DB_ERROR_DIVZERO            => 'division by zero',
+            DB_ERROR_INVALID            => 'invalid',
+            DB_ERROR_INVALID_DATE       => 'invalid date or time',
+            DB_ERROR_INVALID_NUMBER     => 'invalid number',
+            DB_ERROR_MISMATCH           => 'mismatch',
+            DB_ERROR_NODBSELECTED       => 'no database selected',
+            DB_ERROR_NOSUCHFIELD        => 'no such field',
+            DB_ERROR_NOSUCHTABLE        => 'no such table',
+            DB_ERROR_NOT_CAPABLE        => 'DB backend not capable',
+            DB_ERROR_NOT_FOUND          => 'not found',
+            DB_ERROR_NOT_LOCKED         => 'not locked',
+            DB_ERROR_SYNTAX             => 'syntax error',
+            DB_ERROR_UNSUPPORTED        => 'not supported',
+            DB_ERROR_VALUE_COUNT_ON_ROW => 'value count on row',
+            DB_ERROR_INVALID_DSN        => 'invalid DSN',
+            DB_ERROR_CONNECT_FAILED     => 'connect failed',
+            0	                       => 'no error', // DB_OK
+            DB_ERROR_NEED_MORE_DATA     => 'insufficient data supplied',
+            DB_ERROR_EXTENSION_NOT_FOUND=> 'extension not found',
+            DB_ERROR_NOSUCHDB           => 'no such database',
+            DB_ERROR_ACCESS_VIOLATION   => 'insufficient permissions'
+);
+?>
+		
Index: /Dev/trunk/rdfapi/util/adodb/lang/adodb-es.inc.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/lang/adodb-es.inc.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/lang/adodb-es.inc.php	(revision 12)
@@ -0,0 +1,33 @@
+<?php
+// contributed by "Horacio Degiorgi" <horaciod@codigophp.com>
+$ADODB_LANG_ARRAY = array (
+			'LANG'                      => 'es',
+            DB_ERROR                    => 'error desconocido',
+            DB_ERROR_ALREADY_EXISTS     => 'ya existe',
+            DB_ERROR_CANNOT_CREATE      => 'imposible crear',
+            DB_ERROR_CANNOT_DELETE      => 'imposible borrar',
+            DB_ERROR_CANNOT_DROP        => 'imposible hacer drop',
+            DB_ERROR_CONSTRAINT         => 'violacion de constraint',
+            DB_ERROR_DIVZERO            => 'division por cero',
+            DB_ERROR_INVALID            => 'invalido',
+            DB_ERROR_INVALID_DATE       => 'fecha u hora invalida',
+            DB_ERROR_INVALID_NUMBER     => 'numero invalido',
+            DB_ERROR_MISMATCH           => 'error',
+            DB_ERROR_NODBSELECTED       => 'no hay base de datos seleccionada',
+            DB_ERROR_NOSUCHFIELD        => 'campo invalido',
+            DB_ERROR_NOSUCHTABLE        => 'tabla no existe',
+            DB_ERROR_NOT_CAPABLE        => 'capacidad invalida para esta DB',
+            DB_ERROR_NOT_FOUND          => 'no encontrado',
+            DB_ERROR_NOT_LOCKED         => 'no bloqueado',
+            DB_ERROR_SYNTAX             => 'error de sintaxis',
+            DB_ERROR_UNSUPPORTED        => 'no soportado',
+            DB_ERROR_VALUE_COUNT_ON_ROW => 'la cantidad de columnas no corresponden a la cantidad de valores',
+            DB_ERROR_INVALID_DSN        => 'DSN invalido',
+            DB_ERROR_CONNECT_FAILED     => 'fallo la conexion',
+            0	                       => 'sin error', // DB_OK
+            DB_ERROR_NEED_MORE_DATA     => 'insuficientes datos',
+            DB_ERROR_EXTENSION_NOT_FOUND=> 'extension no encontrada',
+            DB_ERROR_NOSUCHDB           => 'base de datos no encontrada',
+            DB_ERROR_ACCESS_VIOLATION   => 'permisos insuficientes'
+);
+?>
Index: /Dev/trunk/rdfapi/util/adodb/lang/adodb-esperanto.inc.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/lang/adodb-esperanto.inc.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/lang/adodb-esperanto.inc.php	(revision 12)
@@ -0,0 +1,35 @@
+<?php
+// Vivu Esperanto cxiam! 
+// Traduko fare de Antono Vasiljev (anders[#]brainactive.org)
+
+$ADODB_LANG_ARRAY = array (
+             'LANG'                      => 'eo',
+            DB_ERROR                    => 'nekonata eraro',
+            DB_ERROR_ALREADY_EXISTS     => 'jam ekzistas',
+            DB_ERROR_CANNOT_CREATE      => 'maleblas krei',
+            DB_ERROR_CANNOT_DELETE      => 'maleblas elimini',
+            DB_ERROR_CANNOT_DROP        => 'maleblas elimini (drop)',
+            DB_ERROR_CONSTRAINT         => 'rompo de kondicxoj de provo',
+            DB_ERROR_DIVZERO            => 'divido per 0 (nul)',
+            DB_ERROR_INVALID            => 'malregule',
+            DB_ERROR_INVALID_DATE       => 'malregula dato kaj tempo',
+            DB_ERROR_INVALID_NUMBER     => 'malregula nombro',
+            DB_ERROR_MISMATCH           => 'eraro',
+            DB_ERROR_NODBSELECTED       => 'datumbazo ne elektita',
+            DB_ERROR_NOSUCHFIELD        => 'ne ekzistas kampo',
+            DB_ERROR_NOSUCHTABLE        => 'ne ekzistas tabelo',
+            DB_ERROR_NOT_CAPABLE        => 'DBMS ne povas',
+            DB_ERROR_NOT_FOUND          => 'ne trovita',
+            DB_ERROR_NOT_LOCKED         => 'ne blokita',
+            DB_ERROR_SYNTAX             => 'sintaksa eraro',
+            DB_ERROR_UNSUPPORTED        => 'ne apogata',
+            DB_ERROR_VALUE_COUNT_ON_ROW => 'nombrilo de valoroj en linio',
+            DB_ERROR_INVALID_DSN        => 'malregula DSN-o',
+            DB_ERROR_CONNECT_FAILED     => 'konekto malsukcesa',
+            0                               => 'cxio bone', // DB_OK
+            DB_ERROR_NEED_MORE_DATA     => 'ne suficxe da datumo',
+            DB_ERROR_EXTENSION_NOT_FOUND=> 'etendo ne trovita',
+            DB_ERROR_NOSUCHDB           => 'datumbazo ne ekzistas',
+            DB_ERROR_ACCESS_VIOLATION   => 'ne suficxe da rajto por atingo'
+);
+?>
Index: /Dev/trunk/rdfapi/util/adodb/lang/adodb-fr.inc.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/lang/adodb-fr.inc.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/lang/adodb-fr.inc.php	(revision 12)
@@ -0,0 +1,33 @@
+<?php
+
+$ADODB_LANG_ARRAY = array (
+	'LANG'                      => 'fr',
+	DB_ERROR                    => 'erreur inconnue',
+	DB_ERROR_ALREADY_EXISTS     => 'existe d&eacute;j&agrave;',
+	DB_ERROR_CANNOT_CREATE      => 'cr&eacute;tion impossible',
+	DB_ERROR_CANNOT_DELETE      => 'effacement impossible',
+	DB_ERROR_CANNOT_DROP        => 'suppression impossible',
+	DB_ERROR_CONSTRAINT         => 'violation de contrainte',
+	DB_ERROR_DIVZERO            => 'division par z&eacute;ro',
+	DB_ERROR_INVALID            => 'invalide',
+	DB_ERROR_INVALID_DATE       => 'date ou heure invalide',
+	DB_ERROR_INVALID_NUMBER     => 'nombre invalide',
+	DB_ERROR_MISMATCH           => 'erreur de concordance',
+	DB_ERROR_NODBSELECTED       => 'pas de base de donn&eacute;ess&eacute;lectionn&eacute;e',
+	DB_ERROR_NOSUCHFIELD        => 'nom de colonne invalide',
+	DB_ERROR_NOSUCHTABLE        => 'table ou vue inexistante',
+	DB_ERROR_NOT_CAPABLE        => 'fonction optionnelle non install&eacute;e',
+	DB_ERROR_NOT_FOUND          => 'pas trouv&eacute;',
+	DB_ERROR_NOT_LOCKED         => 'non verrouill&eacute;',
+	DB_ERROR_SYNTAX             => 'erreur de syntaxe',
+	DB_ERROR_UNSUPPORTED        => 'non support&eacute;',
+	DB_ERROR_VALUE_COUNT_ON_ROW => 'valeur ins&eacute;r&eacute;e trop grande pour colonne',
+	DB_ERROR_INVALID_DSN        => 'DSN invalide',
+	DB_ERROR_CONNECT_FAILED     => '&eacute;chec &agrave; la connexion',
+	0                        => "pas d'erreur", // DB_OK
+	DB_ERROR_NEED_MORE_DATA     => 'donn&eacute;es fournies insuffisantes',
+	DB_ERROR_EXTENSION_NOT_FOUND=> 'extension non trouv&eacute;e',
+	DB_ERROR_NOSUCHDB           => 'base de donn&eacute;es inconnue',
+	DB_ERROR_ACCESS_VIOLATION   => 'droits insuffisants'
+);
+?>
Index: /Dev/trunk/rdfapi/util/adodb/lang/adodb-hu.inc.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/lang/adodb-hu.inc.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/lang/adodb-hu.inc.php	(revision 12)
@@ -0,0 +1,34 @@
+<?php
+# Hungarian language, encoding by ISO 8859-2 charset (Iso Latin-2)
+# Halászvári Gábor <g.halaszvari#portmax.hu>
+$ADODB_LANG_ARRAY = array (
+			'LANG'                      => 'hu',
+            DB_ERROR                    => 'ismeretlen hiba',
+            DB_ERROR_ALREADY_EXISTS     => 'már létezik',
+            DB_ERROR_CANNOT_CREATE      => 'nem sikerült létrehozni',
+            DB_ERROR_CANNOT_DELETE      => 'nem sikerült törölni',
+            DB_ERROR_CANNOT_DROP        => 'nem sikerült eldobni',
+            DB_ERROR_CONSTRAINT         => 'szabályok megszegése',
+            DB_ERROR_DIVZERO            => 'osztás nullával',
+            DB_ERROR_INVALID            => 'érvénytelen',
+            DB_ERROR_INVALID_DATE       => 'érvénytelen dátum vagy idõ',
+            DB_ERROR_INVALID_NUMBER     => 'érvénytelen szám',
+            DB_ERROR_MISMATCH           => 'nem megfelelõ',
+            DB_ERROR_NODBSELECTED       => 'nincs kiválasztott adatbázis',
+            DB_ERROR_NOSUCHFIELD        => 'nincs ilyen mezõ',
+            DB_ERROR_NOSUCHTABLE        => 'nincs ilyen tábla',
+            DB_ERROR_NOT_CAPABLE        => 'DB backend nem támogatja',
+            DB_ERROR_NOT_FOUND          => 'nem található',
+            DB_ERROR_NOT_LOCKED         => 'nincs lezárva',
+            DB_ERROR_SYNTAX             => 'szintaktikai hiba',
+            DB_ERROR_UNSUPPORTED        => 'nem támogatott',
+            DB_ERROR_VALUE_COUNT_ON_ROW => 'soron végzett érték számlálás',
+            DB_ERROR_INVALID_DSN        => 'hibás DSN',
+            DB_ERROR_CONNECT_FAILED     => 'sikertelen csatlakozás',
+            0	                       => 'nincs hiba', // DB_OK
+            DB_ERROR_NEED_MORE_DATA     => 'túl kevés az adat',
+            DB_ERROR_EXTENSION_NOT_FOUND=> 'bõvítmény nem található',
+            DB_ERROR_NOSUCHDB           => 'nincs ilyen adatbázis',
+            DB_ERROR_ACCESS_VIOLATION   => 'nincs jogosultság'
+);
+?>
Index: /Dev/trunk/rdfapi/util/adodb/lang/adodb-it.inc.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/lang/adodb-it.inc.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/lang/adodb-it.inc.php	(revision 12)
@@ -0,0 +1,34 @@
+<?php
+// Italian language file contributed by Tiraboschi Massimiliano aka TiMax  
+// www.maxdev.com  timax@maxdev.com
+$ADODB_LANG_ARRAY = array (
+            'LANG'                      => 'it',
+            DB_ERROR                    => 'errore sconosciuto',
+            DB_ERROR_ALREADY_EXISTS     => 'esiste gi&agrave;',
+            DB_ERROR_CANNOT_CREATE      => 'non posso creare',
+            DB_ERROR_CANNOT_DELETE      => 'non posso cancellare',
+            DB_ERROR_CANNOT_DROP        => 'non posso eliminare',
+            DB_ERROR_CONSTRAINT         => 'violazione constraint',
+            DB_ERROR_DIVZERO            => 'divisione per zero',
+            DB_ERROR_INVALID            => 'non valido',
+            DB_ERROR_INVALID_DATE       => 'data od ora non valida',
+            DB_ERROR_INVALID_NUMBER     => 'numero non valido',
+            DB_ERROR_MISMATCH           => 'diversi',
+            DB_ERROR_NODBSELECTED       => 'nessun database selezionato',
+            DB_ERROR_NOSUCHFIELD        => 'nessun campo trovato',
+            DB_ERROR_NOSUCHTABLE        => 'nessuna tabella trovata',
+            DB_ERROR_NOT_CAPABLE        => 'DB backend non abilitato',
+            DB_ERROR_NOT_FOUND          => 'non trovato',
+            DB_ERROR_NOT_LOCKED         => 'non bloccato',
+            DB_ERROR_SYNTAX             => 'errore di sintassi',
+            DB_ERROR_UNSUPPORTED        => 'non supportato',
+            DB_ERROR_VALUE_COUNT_ON_ROW => 'valore inserito troppo grande per una colonna',
+            DB_ERROR_INVALID_DSN        => 'DSN non valido',
+            DB_ERROR_CONNECT_FAILED     => 'connessione fallita',
+            0                           => 'nessun errore', // DB_OK
+            DB_ERROR_NEED_MORE_DATA     => 'dati inseriti insufficienti',
+            DB_ERROR_EXTENSION_NOT_FOUND=> 'estensione non trovata',
+            DB_ERROR_NOSUCHDB           => 'database non trovato',
+            DB_ERROR_ACCESS_VIOLATION   => 'permessi insufficienti'
+);
+?>
Index: /Dev/trunk/rdfapi/util/adodb/lang/adodb-nl.inc.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/lang/adodb-nl.inc.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/lang/adodb-nl.inc.php	(revision 12)
@@ -0,0 +1,33 @@
+<?php
+// Translated by Pim Koeman (pim#wittenborg-university.com)
+$ADODB_LANG_ARRAY = array (
+			'LANG'                      => 'nl',
+            DB_ERROR                    => 'onbekende fout',
+            DB_ERROR_ALREADY_EXISTS     => 'bestaat al',
+            DB_ERROR_CANNOT_CREATE      => 'kan niet aanmaken',
+            DB_ERROR_CANNOT_DELETE      => 'kan niet wissen',
+            DB_ERROR_CANNOT_DROP        => 'kan niet verwijderen',
+            DB_ERROR_CONSTRAINT         => 'constraint overtreding',
+            DB_ERROR_DIVZERO            => 'poging tot delen door nul',
+            DB_ERROR_INVALID            => 'ongeldig',
+            DB_ERROR_INVALID_DATE       => 'ongeldige datum of tijd',
+            DB_ERROR_INVALID_NUMBER     => 'ongeldig nummer',
+            DB_ERROR_MISMATCH           => 'is incorrect',
+            DB_ERROR_NODBSELECTED       => 'geen database geselecteerd',
+            DB_ERROR_NOSUCHFIELD        => 'onbekend veld',
+            DB_ERROR_NOSUCHTABLE        => 'onbekende tabel',
+            DB_ERROR_NOT_CAPABLE        => 'database systeem is niet tot uitvoer in staat',
+            DB_ERROR_NOT_FOUND          => 'niet gevonden',
+            DB_ERROR_NOT_LOCKED         => 'niet vergrendeld',
+            DB_ERROR_SYNTAX             => 'syntaxis fout',
+            DB_ERROR_UNSUPPORTED        => 'niet ondersteund',
+            DB_ERROR_VALUE_COUNT_ON_ROW => 'waarde telling op rij',
+            DB_ERROR_INVALID_DSN        => 'ongeldige DSN',
+            DB_ERROR_CONNECT_FAILED     => 'connectie mislukt',
+            0	                       => 'geen fout', // DB_OK
+            DB_ERROR_NEED_MORE_DATA     => 'onvoldoende data gegeven',
+            DB_ERROR_EXTENSION_NOT_FOUND=> 'extensie niet gevonden',
+            DB_ERROR_NOSUCHDB           => 'onbekende database',
+            DB_ERROR_ACCESS_VIOLATION   => 'onvoldoende rechten'
+);
+?>
Index: /Dev/trunk/rdfapi/util/adodb/lang/adodb-pl.inc.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/lang/adodb-pl.inc.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/lang/adodb-pl.inc.php	(revision 12)
@@ -0,0 +1,36 @@
+<?php
+
+// Contributed by Grzegorz Pacan <gp#dione.cc>
+
+$ADODB_LANG_ARRAY = array (
+			'LANG'                      => 'pl',
+            DB_ERROR                    => 'niezidentyfikowany b³±d',
+            DB_ERROR_ALREADY_EXISTS     => 'ju¿ istniej±',
+            DB_ERROR_CANNOT_CREATE      => 'nie mo¿na stworzyæ',
+            DB_ERROR_CANNOT_DELETE      => 'nie mo¿na usun±æ',
+            DB_ERROR_CANNOT_DROP        => 'nie mo¿na porzuciæ',
+            DB_ERROR_CONSTRAINT         => 'pogwa³cenie uprawnieñ',
+            DB_ERROR_DIVZERO            => 'dzielenie przez zero',
+            DB_ERROR_INVALID            => 'b³êdny',
+            DB_ERROR_INVALID_DATE       => 'b³êdna godzina lub data',
+            DB_ERROR_INVALID_NUMBER     => 'b³êdny numer',
+            DB_ERROR_MISMATCH           => 'niedopasowanie',
+            DB_ERROR_NODBSELECTED       => 'baza danych nie zosta³a wybrana',
+            DB_ERROR_NOSUCHFIELD        => 'nie znaleziono pola',
+            DB_ERROR_NOSUCHTABLE        => 'nie znaleziono tabeli',
+            DB_ERROR_NOT_CAPABLE        => 'nie zdolny',
+            DB_ERROR_NOT_FOUND          => 'nie znaleziono',
+            DB_ERROR_NOT_LOCKED         => 'nie zakmniêty',
+            DB_ERROR_SYNTAX             => 'b³±d sk³adni',
+            DB_ERROR_UNSUPPORTED        => 'nie obs³uguje',
+            DB_ERROR_VALUE_COUNT_ON_ROW => 'warto¶æ liczona w szeregu',
+            DB_ERROR_INVALID_DSN        => 'b³êdny DSN',
+            DB_ERROR_CONNECT_FAILED     => 'po³±czenie nie zosta³o zrealizowane',
+            0	                       => 'brak b³êdów', // DB_OK
+            DB_ERROR_NEED_MORE_DATA     => 'niedostateczna ilo¶æ informacji',
+            DB_ERROR_EXTENSION_NOT_FOUND=> 'nie znaleziono rozszerzenia',
+            DB_ERROR_NOSUCHDB           => 'nie znaleziono bazy',
+            DB_ERROR_ACCESS_VIOLATION   => 'niedostateczne uprawnienia'
+);
+?>
+		
Index: /Dev/trunk/rdfapi/util/adodb/lang/adodb-pt-br.inc.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/lang/adodb-pt-br.inc.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/lang/adodb-pt-br.inc.php	(revision 12)
@@ -0,0 +1,35 @@
+<?php
+// contributed by "Levi Fukumori" levi _AT_ fukumori _DOT_ com _DOT_ br
+// portugese (brazilian)
+$ADODB_LANG_ARRAY = array (
+			'LANG'                      => 'pt-br',
+            DB_ERROR                    => 'erro desconhecido',
+            DB_ERROR_ALREADY_EXISTS     => 'já existe',
+            DB_ERROR_CANNOT_CREATE      => 'impossível criar',
+            DB_ERROR_CANNOT_DELETE      => 'impossível excluír',
+            DB_ERROR_CANNOT_DROP        => 'impossível remover',
+            DB_ERROR_CONSTRAINT         => 'violação do confinamente',
+            DB_ERROR_DIVZERO            => 'divisão por zero',
+            DB_ERROR_INVALID            => 'inválido',
+            DB_ERROR_INVALID_DATE       => 'data ou hora inválida',
+            DB_ERROR_INVALID_NUMBER     => 'número inválido',
+            DB_ERROR_MISMATCH           => 'erro',
+            DB_ERROR_NODBSELECTED       => 'nenhum banco de dados selecionado',
+            DB_ERROR_NOSUCHFIELD        => 'campo inválido',
+            DB_ERROR_NOSUCHTABLE        => 'tabela inexistente',
+            DB_ERROR_NOT_CAPABLE        => 'capacidade inválida para este BD',
+            DB_ERROR_NOT_FOUND          => 'não encontrado',
+            DB_ERROR_NOT_LOCKED         => 'não bloqueado',
+            DB_ERROR_SYNTAX             => 'erro de sintaxe',
+            DB_ERROR_UNSUPPORTED        => 
+'não suportado',
+            DB_ERROR_VALUE_COUNT_ON_ROW => 'a quantidade de colunas não corresponde ao de valores',
+            DB_ERROR_INVALID_DSN        => 'DSN inválido',
+            DB_ERROR_CONNECT_FAILED     => 'falha na conexão',
+            0				=> 'sem erro', // DB_OK
+            DB_ERROR_NEED_MORE_DATA     => 'dados insuficientes',
+            DB_ERROR_EXTENSION_NOT_FOUND=> 'extensão não encontrada',
+            DB_ERROR_NOSUCHDB           => 'banco de dados não encontrado',
+            DB_ERROR_ACCESS_VIOLATION   => 'permissão insuficiente'
+);
+?>
Index: /Dev/trunk/rdfapi/util/adodb/lang/adodb-ro.inc.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/lang/adodb-ro.inc.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/lang/adodb-ro.inc.php	(revision 12)
@@ -0,0 +1,36 @@
+<?php
+
+/* Romanian - by "bogdan stefan" <sbogdan#rsb.ro> */
+
+$ADODB_LANG_ARRAY = array (
+			'LANG'                      => 'ro',
+            DB_ERROR                    => 'eroare necunoscuta',
+            DB_ERROR_ALREADY_EXISTS     => 'deja exista',
+            DB_ERROR_CANNOT_CREATE      => 'nu se poate creea',
+            DB_ERROR_CANNOT_DELETE      => 'nu se poate sterge',
+            DB_ERROR_CANNOT_DROP        => 'nu se poate executa drop',
+            DB_ERROR_CONSTRAINT         => 'violare de constrain',
+            DB_ERROR_DIVZERO            => 'se divide la zero',
+            DB_ERROR_INVALID            => 'invalid',
+            DB_ERROR_INVALID_DATE       => 'data sau timp invalide',
+            DB_ERROR_INVALID_NUMBER     => 'numar invalid',
+            DB_ERROR_MISMATCH           => 'nepotrivire-mismatch',
+            DB_ERROR_NODBSELECTED       => 'nu exista baza de date selectata',
+            DB_ERROR_NOSUCHFIELD        => 'camp inexistent',
+            DB_ERROR_NOSUCHTABLE        => 'tabela inexistenta',
+            DB_ERROR_NOT_CAPABLE        => 'functie optionala neinstalata',
+            DB_ERROR_NOT_FOUND          => 'negasit',
+            DB_ERROR_NOT_LOCKED         => 'neblocat',
+            DB_ERROR_SYNTAX             => 'eroare de sintaxa',
+            DB_ERROR_UNSUPPORTED        => 'nu e suportat',
+            DB_ERROR_VALUE_COUNT_ON_ROW => 'valoare prea mare pentru coloana',
+            DB_ERROR_INVALID_DSN        => 'DSN invalid',
+            DB_ERROR_CONNECT_FAILED     => 'conectare esuata',
+            0	                       => 'fara eroare', // DB_OK
+            DB_ERROR_NEED_MORE_DATA     => 'data introduse insuficiente',
+            DB_ERROR_EXTENSION_NOT_FOUND=> 'extensie negasita',
+            DB_ERROR_NOSUCHDB           => 'nu exista baza de date',
+            DB_ERROR_ACCESS_VIOLATION   => 'permisiuni insuficiente'
+);
+?>
+
Index: /Dev/trunk/rdfapi/util/adodb/lang/adodb-ru1251.inc.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/lang/adodb-ru1251.inc.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/lang/adodb-ru1251.inc.php	(revision 12)
@@ -0,0 +1,35 @@
+<?php
+
+// Russian language file contributed by "Cyrill Malevanov" cyrill#malevanov.spb.ru.
+
+$ADODB_LANG_ARRAY = array (
+             'LANG'                      => 'ru1251',
+            DB_ERROR                    => 'íåèçâåñòíàÿ îøèáêà',
+            DB_ERROR_ALREADY_EXISTS     => 'óæå ñóùåñòâóåò',
+            DB_ERROR_CANNOT_CREATE      => 'íåâîçìîæíî ñîçäàòü',
+            DB_ERROR_CANNOT_DELETE      => 'íåâîçìîæíî óäàëèòü',
+            DB_ERROR_CANNOT_DROP        => 'íåâîçìîæíî óäàëèòü (drop)',
+            DB_ERROR_CONSTRAINT         => 'íàðóøåíèå óñëîâèé ïðîâåðêè',
+            DB_ERROR_DIVZERO            => 'äåëåíèå íà 0',
+            DB_ERROR_INVALID            => 'íåïðàâèëüíî',
+            DB_ERROR_INVALID_DATE       => 'íåêîððåêòíàÿ äàòà èëè âðåìÿ',
+            DB_ERROR_INVALID_NUMBER     => 'íåêîððåêòíîå ÷èñëî',
+            DB_ERROR_MISMATCH           => 'îøèáêà',
+            DB_ERROR_NODBSELECTED       => 'ÁÄ íå âûáðàíà',
+            DB_ERROR_NOSUCHFIELD        => 'íå ñóùåñòâóåò ïîëå',
+            DB_ERROR_NOSUCHTABLE        => 'íå ñóùåñòâóåò òàáëèöà',
+            DB_ERROR_NOT_CAPABLE        => 'ÑÓÁÄ íå â ñîñòîÿíèè',
+            DB_ERROR_NOT_FOUND          => 'íå íàéäåíî',
+            DB_ERROR_NOT_LOCKED         => 'íå çàáëîêèðîâàíî',
+            DB_ERROR_SYNTAX             => 'ñèíòàêñè÷åñêàÿ îøèáêà',
+            DB_ERROR_UNSUPPORTED        => 'íå ïîääåðæèâàåòñÿ',
+            DB_ERROR_VALUE_COUNT_ON_ROW => 'ñ÷åò÷èê çíà÷åíèé â ñòðîêå',
+            DB_ERROR_INVALID_DSN        => 'íåïðàâèëüíàÿ DSN',
+            DB_ERROR_CONNECT_FAILED     => 'ñîåäèíåíèå íåóñïåøíî',
+            0                               => 'íåò îøèáêè', // DB_OK
+            DB_ERROR_NEED_MORE_DATA     => 'ïðåäîñòàâëåíî íåäîñòàòî÷íî äàííûõ',
+            DB_ERROR_EXTENSION_NOT_FOUND=> 'ðàñøèðåíèå íå íàéäåíî',
+            DB_ERROR_NOSUCHDB           => 'íå ñóùåñòâóåò ÁÄ',
+            DB_ERROR_ACCESS_VIOLATION   => 'íåäîñòàòî÷íî ïðàâ äîñòóïà'
+);
+?>
Index: /Dev/trunk/rdfapi/util/adodb/lang/adodb-sv.inc.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/lang/adodb-sv.inc.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/lang/adodb-sv.inc.php	(revision 12)
@@ -0,0 +1,33 @@
+<?php
+// Christian Tiberg" christian@commsoft.nu
+$ADODB_LANG_ARRAY = array (
+			'LANG'                      => 'en',
+            DB_ERROR                    => 'Okänt fel',
+            DB_ERROR_ALREADY_EXISTS     => 'finns redan',
+            DB_ERROR_CANNOT_CREATE      => 'kan inte skapa',
+            DB_ERROR_CANNOT_DELETE      => 'kan inte ta bort',
+            DB_ERROR_CANNOT_DROP        => 'kan inte släppa',
+            DB_ERROR_CONSTRAINT         => 'begränsning kränkt',
+            DB_ERROR_DIVZERO            => 'division med noll',
+            DB_ERROR_INVALID            => 'ogiltig',
+            DB_ERROR_INVALID_DATE       => 'ogiltigt datum eller tid',
+            DB_ERROR_INVALID_NUMBER     => 'ogiltigt tal',
+            DB_ERROR_MISMATCH           => 'felaktig matchning',
+            DB_ERROR_NODBSELECTED       => 'ingen databas vald',
+            DB_ERROR_NOSUCHFIELD        => 'inget sådant fält',
+            DB_ERROR_NOSUCHTABLE        => 'ingen sådan tabell',
+            DB_ERROR_NOT_CAPABLE        => 'DB backend klarar det inte',
+            DB_ERROR_NOT_FOUND          => 'finns inte',
+            DB_ERROR_NOT_LOCKED         => 'inte låst',
+            DB_ERROR_SYNTAX             => 'syntaxfel',
+            DB_ERROR_UNSUPPORTED        => 'stöds ej',
+            DB_ERROR_VALUE_COUNT_ON_ROW => 'värde räknat på rad',
+            DB_ERROR_INVALID_DSN        => 'ogiltig DSN',
+            DB_ERROR_CONNECT_FAILED     => 'anslutning misslyckades',
+            0	                       => 'inget fel', // DB_OK
+            DB_ERROR_NEED_MORE_DATA     => 'otillräckligt med data angivet',
+            DB_ERROR_EXTENSION_NOT_FOUND=> 'utökning hittades ej',
+            DB_ERROR_NOSUCHDB           => 'ingen sådan databas',
+            DB_ERROR_ACCESS_VIOLATION   => 'otillräckliga rättigheter'
+);
+?>
Index: /Dev/trunk/rdfapi/util/adodb/lang/adodb-uk1251.inc.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/lang/adodb-uk1251.inc.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/lang/adodb-uk1251.inc.php	(revision 12)
@@ -0,0 +1,35 @@
+<?php
+
+// Ukrainian language file contributed by  Alex Rootoff rootoff{AT}pisem.net.
+
+$ADODB_LANG_ARRAY = array (
+             'LANG'                      => 'uk1251',
+            DB_ERROR                    => 'íåâ³äîìà ïîìèëêà',
+            DB_ERROR_ALREADY_EXISTS     => 'âæå ³ñíóº',
+            DB_ERROR_CANNOT_CREATE      => 'íåìîæëèâî ñòâîðèòè',
+            DB_ERROR_CANNOT_DELETE      => 'íåìîæëèâî âèäàëèòè',
+            DB_ERROR_CANNOT_DROP        => 'íåìîæëèâî çíèùèòè (drop)',
+            DB_ERROR_CONSTRAINT         => 'ïîðóøåííÿ óìîâ ïåðåâ³ðêè',
+            DB_ERROR_DIVZERO            => 'ä³ëåííÿ íà 0',
+            DB_ERROR_INVALID            => 'íåïðàâèëüíî',
+            DB_ERROR_INVALID_DATE       => 'íåïðàâèëüíà äàòà ÷è ÷àñ',
+            DB_ERROR_INVALID_NUMBER     => 'íåïðàâèëüíå ÷èñëî',
+            DB_ERROR_MISMATCH           => 'ïîìèëêà',
+            DB_ERROR_NODBSELECTED       => 'íå âèáðàíî ÁÄ',
+            DB_ERROR_NOSUCHFIELD        => 'íå ³ñíóº ïîëå',
+            DB_ERROR_NOSUCHTABLE        => 'íå ³ñíóº òàáëèöÿ',
+            DB_ERROR_NOT_CAPABLE        => 'ÑÓÁÄ íå â ñòàí³',
+            DB_ERROR_NOT_FOUND          => 'íå çíàéäåíî',
+            DB_ERROR_NOT_LOCKED         => 'íå çàáëîêîâàíî',
+            DB_ERROR_SYNTAX             => 'ñèíòàêñè÷íà ïîìèëêà',
+            DB_ERROR_UNSUPPORTED        => 'íå ï³äòðèìóºòüñÿ',
+            DB_ERROR_VALUE_COUNT_ON_ROW => 'ðàõ³âíèê çíà÷åíü â ñòð³÷ö³',
+            DB_ERROR_INVALID_DSN        => 'íåïðàâèëüíà DSN',
+            DB_ERROR_CONNECT_FAILED     => 'ç\'ºäíàííÿ íåóñï³øíå',
+            0                               => 'âñå ãàðàçä', // DB_OK
+            DB_ERROR_NEED_MORE_DATA     => 'íàäàíî íåäîñòàòíüî äàíèõ',
+            DB_ERROR_EXTENSION_NOT_FOUND=> 'ðîçøèðåííÿ íå çíàéäåíî',
+            DB_ERROR_NOSUCHDB           => 'íå ³ñíóº ÁÄ',
+            DB_ERROR_ACCESS_VIOLATION   => 'íåäîñòàòíüî ïðàâ äîñòóïà'
+);
+?>
Index: /Dev/trunk/rdfapi/util/adodb/license.txt
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/license.txt	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/license.txt	(revision 12)
@@ -0,0 +1,182 @@
+ADOdb is dual licensed using BSD and LGPL. 
+
+In plain English, you do not need to distribute your application  in source code form, nor do you need to distribute ADOdb source code, provided you follow the rest of terms of the BSD license.
+
+For more info about ADOdb, visit http://adodb.sourceforge.net/
+
+BSD Style-License
+=================
+
+Copyright (c) 2000, 2001, 2002, 2003, 2004 John Lim
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without modification, 
+are permitted provided that the following conditions are met:
+
+Redistributions of source code must retain the above copyright notice, this list 
+of conditions and the following disclaimer. 
+
+Redistributions in binary form must reproduce the above copyright notice, this list 
+of conditions and the following disclaimer in the documentation and/or other materials 
+provided with the distribution. 
+
+Neither the name of the John Lim nor the names of its contributors may be used to 
+endorse or promote products derived from this software without specific prior written 
+permission. 
+
+DISCLAIMER:
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY 
+EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 
+MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL 
+JOHN LIM OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 
+EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 
+SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 
+HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, 
+OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 
+SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+==========================================================
+GNU LESSER GENERAL PUBLIC LICENSE
+Version 2.1, February 1999 
+ 
+Copyright (C) 1991, 1999 Free Software Foundation, Inc.
+59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+Everyone is permitted to copy and distribute verbatim copies
+of this license document, but changing it is not allowed.
+
+[This is the first released version of the Lesser GPL.  It also counts
+ as the successor of the GNU Library Public License, version 2, hence
+ the version number 2.1.]
+ 
+ 
+Preamble
+The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public Licenses are intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. 
+
+This license, the Lesser General Public License, applies to some specially designated software packages--typically libraries--of the Free Software Foundation and other authors who decide to use it. You can use it too, but we suggest you first think carefully about whether this license or the ordinary General Public License is the better strategy to use in any particular case, based on the explanations below. 
+
+When we speak of free software, we are referring to freedom of use, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish); that you receive source code or can get it if you want it; that you can change the software and use pieces of it in new free programs; and that you are informed that you can do these things. 
+
+To protect your rights, we need to make restrictions that forbid distributors to deny you these rights or to ask you to surrender these rights. These restrictions translate to certain responsibilities for you if you distribute copies of the library or if you modify it. 
+
+For example, if you distribute copies of the library, whether gratis or for a fee, you must give the recipients all the rights that we gave you. You must make sure that they, too, receive or can get the source code. If you link other code with the library, you must provide complete object files to the recipients, so that they can relink them with the library after making changes to the library and recompiling it. And you must show them these terms so they know their rights. 
+
+We protect your rights with a two-step method: (1) we copyright the library, and (2) we offer you this license, which gives you legal permission to copy, distribute and/or modify the library. 
+
+To protect each distributor, we want to make it very clear that there is no warranty for the free library. Also, if the library is modified by someone else and passed on, the recipients should know that what they have is not the original version, so that the original author's reputation will not be affected by problems that might be introduced by others. 
+
+Finally, software patents pose a constant threat to the existence of any free program. We wish to make sure that a company cannot effectively restrict the users of a free program by obtaining a restrictive license from a patent holder. Therefore, we insist that any patent license obtained for a version of the library must be consistent with the full freedom of use specified in this license. 
+
+Most GNU software, including some libraries, is covered by the ordinary GNU General Public License. This license, the GNU Lesser General Public License, applies to certain designated libraries, and is quite different from the ordinary General Public License. We use this license for certain libraries in order to permit linking those libraries into non-free programs. 
+
+When a program is linked with a library, whether statically or using a shared library, the combination of the two is legally speaking a combined work, a derivative of the original library. The ordinary General Public License therefore permits such linking only if the entire combination fits its criteria of freedom. The Lesser General Public License permits more lax criteria for linking other code with the library. 
+
+We call this license the "Lesser" General Public License because it does Less to protect the user's freedom than the ordinary General Public License. It also provides other free software developers Less of an advantage over competing non-free programs. These disadvantages are the reason we use the ordinary General Public License for many libraries. However, the Lesser license provides advantages in certain special circumstances. 
+
+For example, on rare occasions, there may be a special need to encourage the widest possible use of a certain library, so that it becomes a de-facto standard. To achieve this, non-free programs must be allowed to use the library. A more frequent case is that a free library does the same job as widely used non-free libraries. In this case, there is little to gain by limiting the free library to free software only, so we use the Lesser General Public License. 
+
+In other cases, permission to use a particular library in non-free programs enables a greater number of people to use a large body of free software. For example, permission to use the GNU C Library in non-free programs enables many more people to use the whole GNU operating system, as well as its variant, the GNU/Linux operating system. 
+
+Although the Lesser General Public License is Less protective of the users' freedom, it does ensure that the user of a program that is linked with the Library has the freedom and the wherewithal to run that program using a modified version of the Library. 
+
+The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a "work based on the library" and a "work that uses the library". The former contains code derived from the library, whereas the latter must be combined with the library in order to run. 
+
+
+TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
+0. This License Agreement applies to any software library or other program which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Lesser General Public License (also called "this License"). Each licensee is addressed as "you". 
+
+A "library" means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables. 
+
+The "Library", below, refers to any such software library or work which has been distributed under these terms. A "work based on the Library" means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term "modification".) 
+
+"Source code" for a work means the preferred form of the work for making modifications to it. For a library, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the library. 
+
+Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does. 
+
+1. You may copy and distribute verbatim copies of the Library's complete source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and distribute a copy of this License along with the Library. 
+
+You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 
+
+2. You may modify your copy or copies of the Library or any portion of it, thus forming a work based on the Library, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: 
+
+
+a) The modified work must itself be a software library. 
+b) You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change. 
+c) You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License. 
+d) If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful. 
+(For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.) 
+
+These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Library, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. 
+
+Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Library. 
+
+In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 
+
+3. You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices. 
+
+Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy. 
+
+This option is useful when you wish to copy part of the code of the Library into a program that is not a library. 
+
+4. You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange. 
+
+If distribution of object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code. 
+
+5. A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a "work that uses the Library". Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License. 
+
+However, linking a "work that uses the Library" with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a "work that uses the library". The executable is therefore covered by this License. Section 6 states terms for distribution of such executables. 
+
+When a "work that uses the Library" uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law. 
+
+If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.) 
+
+Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself. 
+
+6. As an exception to the Sections above, you may also combine or link a "work that uses the Library" with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer's own use and reverse engineering for debugging such modifications. 
+
+You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things: 
+
+
+a) Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable "work that uses the Library", as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.) 
+b) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (1) uses at run time a copy of the library already present on the user's computer system, rather than copying library functions into the executable, and (2) will operate properly with a modified version of the library, if the user installs one, as long as the modified version is interface-compatible with the version that the work was made with. 
+c) Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution. 
+d) If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place. 
+e) Verify that the user has already received a copy of these materials or that you have already sent this user a copy. 
+For an executable, the required form of the "work that uses the Library" must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the materials to be distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. 
+
+It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute. 
+
+7. You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things: 
+
+
+a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above. 
+b) Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 
+8. You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 
+
+9. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it. 
+
+10. Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties with this License. 
+
+11. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Library. 
+
+If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply, and the section as a whole is intended to apply in other circumstances. 
+
+It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. 
+
+This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 
+
+12. If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 
+
+13. The Free Software Foundation may publish revised and/or new versions of the Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. 
+
+Each version is given a distinguishing version number. If the Library specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation. 
+
+14. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. 
+
+NO WARRANTY 
+
+15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 
+
+16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 
+
+
+END OF TERMS AND CONDITIONS
Index: /Dev/trunk/rdfapi/util/adodb/pear/Auth/Container/ADOdb.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/pear/Auth/Container/ADOdb.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/pear/Auth/Container/ADOdb.php	(revision 12)
@@ -0,0 +1,413 @@
+<?php
+//
+// +----------------------------------------------------------------------+
+// | PHP Version 4                                                        |
+// +----------------------------------------------------------------------+
+// |                                                                      |
+// +----------------------------------------------------------------------+
+// | This source file is subject to version 2.02 of the PHP license,      |
+// | that is bundled with this package in the file LICENSE, and is        |
+// | available at through the world-wide-web at                           |
+// | http://www.php.net/license/2_02.txt.                                 |
+// | If you did not receive a copy of the PHP license and are unable to   |
+// | obtain it through the world-wide-web, please send a note to          |
+// | license@php.net so we can mail you a copy immediately.               |
+// +----------------------------------------------------------------------+
+// | Authors: Martin Jansen <mj@php.net>
+// |	Richard Tango-Lowy <richtl@arscognita.com>                                  |
+// +----------------------------------------------------------------------+
+//
+// $Id: ADOdb.php 350 2007-03-12 10:55:13Z cweiske $
+//
+
+require_once 'Auth/Container.php';
+require_once 'adodb.inc.php';
+require_once 'adodb-pear.inc.php';
+require_once 'adodb-errorpear.inc.php';
+
+/**
+ * Storage driver for fetching login data from a database using ADOdb-PHP.
+ *
+ * This storage driver can use all databases which are supported
+ * by the ADBdb DB abstraction layer to fetch login data.
+ * See http://php.weblogs.com/adodb for information on ADOdb.
+ * NOTE: The ADOdb directory MUST be in your PHP include_path!
+ *
+ * @author   Richard Tango-Lowy <richtl@arscognita.com>
+ * @package  Auth
+ * @version  $Revision: 350 $
+ */
+class Auth_Container_ADOdb extends Auth_Container
+{
+
+    /**
+     * Additional options for the storage container
+     * @var array
+     */
+    var $options = array();
+
+    /**
+     * DB object
+     * @var object
+     */
+    var $db = null;
+    var $dsn = '';
+	
+    /**
+     * User that is currently selected from the DB.
+     * @var string
+     */
+    var $activeUser = '';
+
+    // {{{ Constructor
+
+    /**
+     * Constructor of the container class
+     *
+     * Initate connection to the database via PEAR::ADOdb
+     *
+     * @param  string Connection data or DB object
+     * @return object Returns an error object if something went wrong
+     */
+    function Auth_Container_ADOdb($dsn)
+    {
+        $this->_setDefaults();
+		
+        if (is_array($dsn)) {
+            $this->_parseOptions($dsn);
+
+            if (empty($this->options['dsn'])) {
+                PEAR::raiseError('No connection parameters specified!');
+            }
+        } else {
+        	// Extract db_type from dsn string.
+            $this->options['dsn'] = $dsn;
+        }
+    }
+
+    // }}}
+    // {{{ _connect()
+
+    /**
+     * Connect to database by using the given DSN string
+     *
+     * @access private
+     * @param  string DSN string
+     * @return mixed  Object on error, otherwise bool
+     */
+     function _connect($dsn)
+    {
+        if (is_string($dsn) || is_array($dsn)) {
+        	if(!$this->db) {
+	        	$this->db = &ADONewConnection($dsn);
+	    		if( $err = ADODB_Pear_error() ) {
+	   	    		return PEAR::raiseError($err);
+	    		}
+        	}
+        	
+        } else {
+            return PEAR::raiseError('The given dsn was not valid in file ' . __FILE__ . ' at line ' . __LINE__,
+                                    41,
+                                    PEAR_ERROR_RETURN,
+                                    null,
+                                    null
+                                    );
+        }
+        
+        if(!$this->db) {
+        	return PEAR::raiseError(ADODB_Pear_error());
+        } else {
+        	return true;
+        }
+    }
+
+    // }}}
+    // {{{ _prepare()
+
+    /**
+     * Prepare database connection
+     *
+     * This function checks if we have already opened a connection to
+     * the database. If that's not the case, a new connection is opened.
+     *
+     * @access private
+     * @return mixed True or a DB error object.
+     */
+    function _prepare()
+    {
+    	if(!$this->db) {
+    		$res = $this->_connect($this->options['dsn']);  		
+    	}
+        return true;
+    }
+
+    // }}}
+    // {{{ query()
+
+    /**
+     * Prepare query to the database
+     *
+     * This function checks if we have already opened a connection to
+     * the database. If that's not the case, a new connection is opened.
+     * After that the query is passed to the database.
+     *
+     * @access public
+     * @param  string Query string
+     * @return mixed  a DB_result object or DB_OK on success, a DB
+     *                or PEAR error on failure
+     */
+    function query($query)
+    {
+        $err = $this->_prepare();
+        if ($err !== true) {
+            return $err;
+        }
+        return $this->db->query($query);
+    }
+
+    // }}}
+    // {{{ _setDefaults()
+
+    /**
+     * Set some default options
+     *
+     * @access private
+     * @return void
+     */
+    function _setDefaults()
+    {
+    	$this->options['db_type']	= 'mysql';
+        $this->options['table']       = 'auth';
+        $this->options['usernamecol'] = 'username';
+        $this->options['passwordcol'] = 'password';
+        $this->options['dsn']         = '';
+        $this->options['db_fields']   = '';
+        $this->options['cryptType']   = 'md5';
+    }
+
+    // }}}
+    // {{{ _parseOptions()
+
+    /**
+     * Parse options passed to the container class
+     *
+     * @access private
+     * @param  array
+     */
+    function _parseOptions($array)
+    {
+        foreach ($array as $key => $value) {
+            if (isset($this->options[$key])) {
+                $this->options[$key] = $value;
+            }
+        }
+
+        /* Include additional fields if they exist */
+        if(!empty($this->options['db_fields'])){
+            if(is_array($this->options['db_fields'])){
+                $this->options['db_fields'] = join($this->options['db_fields'], ', ');
+            }
+            $this->options['db_fields'] = ', '.$this->options['db_fields'];
+        }
+    }
+
+    // }}}
+    // {{{ fetchData()
+
+    /**
+     * Get user information from database
+     *
+     * This function uses the given username to fetch
+     * the corresponding login data from the database
+     * table. If an account that matches the passed username
+     * and password is found, the function returns true.
+     * Otherwise it returns false.
+     *
+     * @param   string Username
+     * @param   string Password
+     * @return  mixed  Error object or boolean
+     */
+    function fetchData($username, $password)
+    {
+        // Prepare for a database query
+        $err = $this->_prepare();
+        if ($err !== true) {
+            return PEAR::raiseError($err->getMessage(), $err->getCode());
+        }
+
+        // Find if db_fields contains a *, i so assume all col are selected
+        if(strstr($this->options['db_fields'], '*')){
+            $sql_from = "*";
+        }
+        else{
+            $sql_from = $this->options['usernamecol'] . ", ".$this->options['passwordcol'].$this->options['db_fields'];
+        }
+        
+        $query = "SELECT ".$sql_from.
+                " FROM ".$this->options['table'].
+                " WHERE ".$this->options['usernamecol']." = " . $this->db->Quote($username);
+        
+        $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
+        $rset = $this->db->Execute( $query );
+        $res = $rset->fetchRow();
+
+        if (DB::isError($res)) {
+            return PEAR::raiseError($res->getMessage(), $res->getCode());
+        }
+        if (!is_array($res)) {
+            $this->activeUser = '';
+            return false;
+        }
+        if ($this->verifyPassword(trim($password, "\r\n"),
+                                  trim($res[$this->options['passwordcol']], "\r\n"),
+                                  $this->options['cryptType'])) {
+            // Store additional field values in the session
+            foreach ($res as $key => $value) {
+                if ($key == $this->options['passwordcol'] ||
+                    $key == $this->options['usernamecol']) {
+                    continue;
+                }
+                // Use reference to the auth object if exists
+                // This is because the auth session variable can change so a static call to setAuthData does not make sence
+                if(is_object($this->_auth_obj)){
+                    $this->_auth_obj->setAuthData($key, $value);
+                } else {
+                    Auth::setAuthData($key, $value);
+                }
+            }
+
+            return true;
+        }
+
+        $this->activeUser = $res[$this->options['usernamecol']];
+        return false;
+    }
+
+    // }}}
+    // {{{ listUsers()
+
+    function listUsers()
+    {
+        $err = $this->_prepare();
+        if ($err !== true) {
+            return PEAR::raiseError($err->getMessage(), $err->getCode());
+        }
+
+        $retVal = array();
+
+        // Find if db_fileds contains a *, i so assume all col are selected
+        if(strstr($this->options['db_fields'], '*')){
+            $sql_from = "*";
+        }
+        else{
+            $sql_from = $this->options['usernamecol'] . ", ".$this->options['passwordcol'].$this->options['db_fields'];
+        }
+
+        $query = sprintf("SELECT %s FROM %s",
+                         $sql_from,
+                         $this->options['table']
+                         );
+        $res = $this->db->getAll($query, null, DB_FETCHMODE_ASSOC);
+
+        if (DB::isError($res)) {
+            return PEAR::raiseError($res->getMessage(), $res->getCode());
+        } else {
+            foreach ($res as $user) {
+                $user['username'] = $user[$this->options['usernamecol']];
+                $retVal[] = $user;
+            }
+        }
+        return $retVal;
+    }
+
+    // }}}
+    // {{{ addUser()
+
+    /**
+     * Add user to the storage container
+     *
+     * @access public
+     * @param  string Username
+     * @param  string Password
+     * @param  mixed  Additional information that are stored in the DB
+     *
+     * @return mixed True on success, otherwise error object
+     */
+    function addUser($username, $password, $additional = "")
+    {
+        if (function_exists($this->options['cryptType'])) {
+            $cryptFunction = $this->options['cryptType'];
+        } else {
+            $cryptFunction = 'md5';
+        }
+
+        $additional_key   = '';
+        $additional_value = '';
+
+        if (is_array($additional)) {
+            foreach ($additional as $key => $value) {
+                $additional_key .= ', ' . $key;
+                $additional_value .= ", '" . $value . "'";
+            }
+        }
+
+        $query = sprintf("INSERT INTO %s (%s, %s%s) VALUES ('%s', '%s'%s)",
+                         $this->options['table'],
+                         $this->options['usernamecol'],
+                         $this->options['passwordcol'],
+                         $additional_key,
+                         $username,
+                         $cryptFunction($password),
+                         $additional_value
+                         );
+
+        $res = $this->query($query);
+
+        if (DB::isError($res)) {
+           return PEAR::raiseError($res->getMessage(), $res->getCode());
+        } else {
+          return true;
+        }
+    }
+
+    // }}}
+    // {{{ removeUser()
+
+    /**
+     * Remove user from the storage container
+     *
+     * @access public
+     * @param  string Username
+     *
+     * @return mixed True on success, otherwise error object
+     */
+    function removeUser($username)
+    {
+        $query = sprintf("DELETE FROM %s WHERE %s = '%s'",
+                         $this->options['table'],
+                         $this->options['usernamecol'],
+                         $username
+                         );
+
+        $res = $this->query($query);
+
+        if (DB::isError($res)) {
+           return PEAR::raiseError($res->getMessage(), $res->getCode());
+        } else {
+          return true;
+        }
+    }
+
+    // }}}
+}
+
+function showDbg( $string ) {
+	print "
+-- $string</P>";
+}
+function dump( $var, $str, $vardump = false ) {
+	print "<H4>$str</H4><pre>";
+	( !$vardump ) ? ( print_r( $var )) : ( var_dump( $var ));
+	print "</pre>";
+}
+?>
Index: /Dev/trunk/rdfapi/util/adodb/pear/readme.Auth.txt
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/pear/readme.Auth.txt	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/pear/readme.Auth.txt	(revision 12)
@@ -0,0 +1,20 @@
+From: Rich Tango-Lowy (richtl#arscognita.com)
+Date: Sat, May 29, 2004 11:20 am
+
+OK, I hacked out an ADOdb container for PEAR-Auth. The error handling's 
+a bit of a mess, but all the methods work.
+
+Copy ADOdb.php to your pear/Auth/Container/ directory.
+
+Use the ADOdb container exactly as you would the DB
+container, but specify 'ADOdb' instead of 'DB':
+
+$dsn = "mysql://myuser:mypass@localhost/authdb";
+$a = new Auth("ADOdb", $dsn, "loginFunction");
+
+
+-------------------
+
+John Lim adds:
+
+See http://pear.php.net/manual/en/package.authentication.php
Index: /Dev/trunk/rdfapi/util/adodb/perf/perf-db2.inc.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/perf/perf-db2.inc.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/perf/perf-db2.inc.php	(revision 12)
@@ -0,0 +1,102 @@
+<?php
+/* 
+V4.94 23 Jan 2007  (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence. See License.txt. 
+  Set tabs to 4 for best viewing.
+  
+  Latest version is available at http://adodb.sourceforge.net
+  
+  Library for basic performance monitoring and tuning 
+  
+*/
+
+// security - hide paths
+if (!defined('ADODB_DIR')) die();
+
+// Simple guide to configuring db2: so-so http://www.devx.com/gethelpon/10MinuteSolution/16575
+
+// SELECT * FROM TABLE(SNAPSHOT_APPL('SAMPLE', -1)) as t
+class perf_db2 extends adodb_perf{
+	var $createTableSQL = "CREATE TABLE adodb_logsql (
+		  created TIMESTAMP NOT NULL,
+		  sql0 varchar(250) NOT NULL,
+		  sql1 varchar(4000) NOT NULL,
+		  params varchar(3000) NOT NULL,
+		  tracer varchar(500) NOT NULL,
+		  timer decimal(16,6) NOT NULL
+		)";
+		
+	var $settings = array(
+	'Ratios',
+		'data cache hit ratio' => array('RATIO',
+			"SELECT 
+				case when sum(POOL_DATA_L_READS+POOL_INDEX_L_READS)=0 then 0 
+				else 100*(1-sum(POOL_DATA_P_READS+POOL_INDEX_P_READS)/sum(POOL_DATA_L_READS+POOL_INDEX_L_READS)) end 
+				FROM TABLE(SNAPSHOT_APPL('',-2)) as t",
+			'=WarnCacheRatio'),
+			
+	'Data Cache',
+		'data cache buffers' => array('DATAC',
+		'select sum(npages) from SYSCAT.BUFFERPOOLS',
+			'See <a href=http://www7b.boulder.ibm.com/dmdd/library/techarticle/anshum/0107anshum.html#bufferpoolsize>tuning reference</a>.' ),
+		'cache blocksize' => array('DATAC',
+		'select avg(pagesize) from SYSCAT.BUFFERPOOLS',
+			'' ),
+		'data cache size' => array('DATAC',
+		'select sum(npages*pagesize) from SYSCAT.BUFFERPOOLS',
+			'' ),
+	'Connections',
+		'current connections' => array('SESS',
+			"SELECT count(*) FROM TABLE(SNAPSHOT_APPL_INFO('',-2)) as t",
+			''),
+
+		false
+	);
+
+
+	function perf_db2(&$conn)
+	{
+		$this->conn =& $conn;
+	}
+	
+	function Explain($sql,$partial=false)
+	{
+		$save = $this->conn->LogSQL(false);
+		if ($partial) {
+			$sqlq = $this->conn->qstr($sql.'%');
+			$arr = $this->conn->GetArray("select distinct sql1 from adodb_logsql where sql1 like $sqlq");
+			if ($arr) {
+				foreach($arr as $row) {
+					$sql = reset($row);
+					if (crc32($sql) == $partial) break;
+				}
+			}
+		}
+		$qno = rand();
+		$ok = $this->conn->Execute("EXPLAIN PLAN SET QUERYNO=$qno FOR $sql");
+		ob_start();
+		if (!$ok) echo "<p>Have EXPLAIN tables been created?</p>";
+		else {
+			$rs = $this->conn->Execute("select * from explain_statement where queryno=$qno");
+			if ($rs) rs2html($rs);
+		}
+		$s = ob_get_contents();
+		ob_end_clean();
+		$this->conn->LogSQL($save);
+		
+		$s .= $this->Tracer($sql);
+		return $s;
+	}
+	
+	
+	function Tables()
+	{
+		$rs = $this->conn->Execute("select tabschema,tabname,card as rows,
+			npages pages_used,fpages pages_allocated, tbspace tablespace  
+			from syscat.tables where tabschema not in ('SYSCAT','SYSIBM','SYSSTAT') order by 1,2");
+		return rs2html($rs,false,false,false,false);
+	}
+}
+?>
Index: /Dev/trunk/rdfapi/util/adodb/perf/perf-informix.inc.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/perf/perf-informix.inc.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/perf/perf-informix.inc.php	(revision 12)
@@ -0,0 +1,70 @@
+<?php
+/* 
+V4.94 23 Jan 2007  (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence. See License.txt. 
+  Set tabs to 4 for best viewing.
+  
+  Latest version is available at http://adodb.sourceforge.net
+  
+  Library for basic performance monitoring and tuning 
+  
+*/
+
+// security - hide paths
+if (!defined('ADODB_DIR')) die();
+
+//
+// Thx to  Fernando Ortiz, mailto:fortiz#lacorona.com.mx
+// With info taken from http://www.oninit.com/oninit/sysmaster/index.html
+//
+class perf_informix extends adodb_perf{
+
+	// Maximum size on varchar upto 9.30 255 chars
+	// better truncate varchar to 255 than char(4000) ?
+	var $createTableSQL = "CREATE TABLE adodb_logsql (
+		created datetime year to second NOT NULL,
+		sql0 varchar(250) NOT NULL,
+		sql1 varchar(255) NOT NULL,
+		params varchar(255) NOT NULL,
+		tracer varchar(255) NOT NULL,
+		timer decimal(16,6) NOT NULL
+	)";
+	
+	var $tablesSQL = "select a.tabname tablename, ti_nptotal*2 size_in_k, ti_nextns extents, ti_nrows records from systables c, sysmaster:systabnames a, sysmaster:systabinfo b where c.tabname not matches 'sys*' and c.partnum = a.partnum and c.partnum = b.ti_partnum";
+	
+	var $settings = array(
+	'Ratios',
+		'data cache hit ratio' => array('RATIOH',
+		"select round((1-(wt.value / (rd.value + wr.value)))*100,2)
+		from sysmaster:sysprofile wr, sysmaster:sysprofile rd, sysmaster:sysprofile wt
+		where rd.name = 'pagreads' and
+		wr.name = 'pagwrites' and
+		wt.name = 'buffwts'",
+		'=WarnCacheRatio'),
+	'IO',
+		'data reads' => array('IO',
+		"select value from sysmaster:sysprofile where name='pagreads'",
+		'Page reads'),
+		
+		'data writes' => array('IO',
+		"select value from sysmaster:sysprofile where name='pagwrites'",
+		'Page writes'),
+	
+	'Connections',
+		'current connections' => array('SESS',
+		'select count(*) from sysmaster:syssessions',
+		'Number of sessions'),
+	
+	false
+	
+	);
+	
+	function perf_informix(&$conn)
+	{
+		$this->conn =& $conn;
+	}
+
+}
+?>
Index: /Dev/trunk/rdfapi/util/adodb/perf/perf-mssql.inc.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/perf/perf-mssql.inc.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/perf/perf-mssql.inc.php	(revision 12)
@@ -0,0 +1,164 @@
+<?php
+
+/* 
+V4.94 23 Jan 2007  (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence. See License.txt. 
+  Set tabs to 4 for best viewing.
+  
+  Latest version is available at http://adodb.sourceforge.net
+  
+  Library for basic performance monitoring and tuning 
+  
+*/
+
+// security - hide paths
+if (!defined('ADODB_DIR')) die();
+
+/*
+	MSSQL has moved most performance info to Performance Monitor
+*/
+class perf_mssql extends adodb_perf{
+	var $sql1 = 'cast(sql1 as text)';
+	var $createTableSQL = "CREATE TABLE adodb_logsql (
+		  created datetime NOT NULL,
+		  sql0 varchar(250) NOT NULL,
+		  sql1 varchar(4000) NOT NULL,
+		  params varchar(3000) NOT NULL,
+		  tracer varchar(500) NOT NULL,
+		  timer decimal(16,6) NOT NULL
+		)";
+		
+	var $settings = array(
+	'Ratios',
+		'data cache hit ratio' => array('RATIO',
+			"select round((a.cntr_value*100.0)/b.cntr_value,2) from master.dbo.sysperfinfo a, master.dbo.sysperfinfo b where a.counter_name = 'Buffer cache hit ratio' and b.counter_name='Buffer cache hit ratio base'",
+			'=WarnCacheRatio'),
+		'prepared sql hit ratio' => array('RATIO',
+			array('dbcc cachestats','Prepared',1,100),
+			''),
+		'adhoc sql hit ratio' => array('RATIO',
+			array('dbcc cachestats','Adhoc',1,100),
+			''),
+	'IO',
+		'data reads' => array('IO',
+		"select cntr_value from master.dbo.sysperfinfo where counter_name = 'Page reads/sec'"),
+		'data writes' => array('IO',
+		"select cntr_value from master.dbo.sysperfinfo where counter_name = 'Page writes/sec'"),
+			
+	'Data Cache',
+		'data cache size' => array('DATAC',
+		"select cntr_value*8192 from master.dbo.sysperfinfo where counter_name = 'Total Pages' and object_name='SQLServer:Buffer Manager'",
+			'' ),
+		'data cache blocksize' => array('DATAC',
+			"select 8192",'page size'),
+	'Connections',
+		'current connections' => array('SESS',
+			'=sp_who',
+			''),
+		'max connections' => array('SESS',
+			"SELECT @@MAX_CONNECTIONS",
+			''),
+
+		false
+	);
+	
+	
+	function perf_mssql(&$conn)
+	{
+		if ($conn->dataProvider == 'odbc') {
+			$this->sql1 = 'sql1';
+			//$this->explain = false;
+		}
+		$this->conn =& $conn;
+	}
+	
+	function Explain($sql,$partial=false)
+	{
+		
+		$save = $this->conn->LogSQL(false);
+		if ($partial) {
+			$sqlq = $this->conn->qstr($sql.'%');
+			$arr = $this->conn->GetArray("select distinct sql1 from adodb_logsql where sql1 like $sqlq");
+			if ($arr) {
+				foreach($arr as $row) {
+					$sql = reset($row);
+					if (crc32($sql) == $partial) break;
+				}
+			}
+		}
+		
+		$s = '<p><b>Explain</b>: '.htmlspecialchars($sql).'</p>';
+		$this->conn->Execute("SET SHOWPLAN_ALL ON;");
+		$sql = str_replace('?',"''",$sql);
+		global $ADODB_FETCH_MODE;
+		
+		$save = $ADODB_FETCH_MODE;
+		$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
+		$rs =& $this->conn->Execute($sql);
+		//adodb_printr($rs);
+		$ADODB_FETCH_MODE = $save;
+		if ($rs) {
+			$rs->MoveNext();
+			$s .= '<table bgcolor=white border=0 cellpadding="1" callspacing=0><tr><td nowrap align=center> Rows<td nowrap align=center> IO<td nowrap align=center> CPU<td align=left> &nbsp; &nbsp; Plan</tr>';
+			while (!$rs->EOF) {
+				$s .= '<tr><td>'.round($rs->fields[8],1).'<td>'.round($rs->fields[9],3).'<td align=right>'.round($rs->fields[10],3).'<td nowrap><pre>'.htmlspecialchars($rs->fields[0])."</td></pre></tr>\n"; ## NOTE CORRUPT </td></pre> tag is intentional!!!!
+				$rs->MoveNext();
+			}
+			$s .= '</table>';
+			
+			$rs->NextRecordSet();
+		}
+		
+		$this->conn->Execute("SET SHOWPLAN_ALL OFF;");
+		$this->conn->LogSQL($save);
+		$s .= $this->Tracer($sql);
+		return $s;
+	}
+	
+	function Tables()
+	{
+	global $ADODB_FETCH_MODE;
+	
+		$save = $ADODB_FETCH_MODE;
+		$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
+		//$this->conn->debug=1;
+		$s = '<table border=1 bgcolor=white><tr><td><b>tablename</b></td><td><b>size_in_k</b></td><td><b>index size</b></td><td><b>reserved size</b></td></tr>';
+		$rs1 = $this->conn->Execute("select distinct name from sysobjects where xtype='U'");
+		if ($rs1) {
+			while (!$rs1->EOF) {
+				$tab = $rs1->fields[0];
+				$tabq = $this->conn->qstr($tab);
+				$rs2 = $this->conn->Execute("sp_spaceused $tabq");
+				if ($rs2) {
+					$s .= '<tr><td>'.$tab.'</td><td align=right>'.$rs2->fields[3].'</td><td align=right>'.$rs2->fields[4].'</td><td align=right>'.$rs2->fields[2].'</td></tr>';
+					$rs2->Close();
+				}
+				$rs1->MoveNext();
+			}
+			$rs1->Close();
+		}
+		$ADODB_FETCH_MODE = $save;
+		return $s.'</table>';
+	}
+	
+	function sp_who()
+	{
+		$arr = $this->conn->GetArray('sp_who');
+		return sizeof($arr);
+	}
+	
+	function HealthCheck($cli=false)
+	{
+		
+		$this->conn->Execute('dbcc traceon(3604)');
+		$html =  adodb_perf::HealthCheck($cli);
+		$this->conn->Execute('dbcc traceoff(3604)');
+		return $html;
+	}
+	
+	
+}
+
+?>
Index: /Dev/trunk/rdfapi/util/adodb/perf/perf-mysql.inc.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/perf/perf-mysql.inc.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/perf/perf-mysql.inc.php	(revision 12)
@@ -0,0 +1,315 @@
+<?php
+/* 
+V4.94 23 Jan 2007  (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence. See License.txt. 
+  Set tabs to 4 for best viewing.
+  
+  Latest version is available at http://adodb.sourceforge.net
+  
+  Library for basic performance monitoring and tuning 
+  
+*/
+
+// security - hide paths
+if (!defined('ADODB_DIR')) die();
+
+class perf_mysql extends adodb_perf{
+	
+	var $tablesSQL = 'show table status';
+	
+	var $createTableSQL = "CREATE TABLE adodb_logsql (
+		  created datetime NOT NULL,
+		  sql0 varchar(250) NOT NULL,
+		  sql1 text NOT NULL,
+		  params text NOT NULL,
+		  tracer text NOT NULL,
+		  timer decimal(16,6) NOT NULL
+		)";
+		
+	var $settings = array(
+	'Ratios',
+		'MyISAM cache hit ratio' => array('RATIO',
+			'=GetKeyHitRatio',
+			'=WarnCacheRatio'),
+		'InnoDB cache hit ratio' => array('RATIO',
+			'=GetInnoDBHitRatio',
+			'=WarnCacheRatio'),
+		'data cache hit ratio' => array('HIDE', # only if called
+			'=FindDBHitRatio',
+			'=WarnCacheRatio'),
+		'sql cache hit ratio' => array('RATIO',
+			'=GetQHitRatio',
+			''),
+	'IO',
+		'data reads' => array('IO',
+			'=GetReads',
+			'Number of selects (Key_reads is not accurate)'),
+		'data writes' => array('IO',
+			'=GetWrites',
+			'Number of inserts/updates/deletes * coef (Key_writes is not accurate)'),
+		
+	'Data Cache',
+		'MyISAM data cache size' => array('DATAC',
+			array("show variables", 'key_buffer_size'),
+			'' ),
+		'BDB data cache size' => array('DATAC',
+			array("show variables", 'bdb_cache_size'),
+			'' ),
+		'InnoDB data cache size' => array('DATAC',
+			array("show variables", 'innodb_buffer_pool_size'),
+			'' ),
+	'Memory Usage',
+		'read buffer size' => array('CACHE',
+			array("show variables", 'read_buffer_size'),
+			'(per session)'),
+		'sort buffer size' => array('CACHE',
+			array("show variables", 'sort_buffer_size'),
+			'Size of sort buffer (per session)' ),
+		'table cache' => array('CACHE',
+			array("show variables", 'table_cache'),
+			'Number of tables to keep open'),
+	'Connections',	
+		'current connections' => array('SESS',
+			array('show status','Threads_connected'),
+			''),
+		'max connections' => array( 'SESS',
+			array("show variables",'max_connections'),
+			''),
+	
+		false
+	);
+	
+	function perf_mysql(&$conn)
+	{
+		$this->conn =& $conn;
+	}
+	
+	function Explain($sql,$partial=false)
+	{
+		
+		if (strtoupper(substr(trim($sql),0,6)) !== 'SELECT') return '<p>Unable to EXPLAIN non-select statement</p>';
+		$save = $this->conn->LogSQL(false);
+		if ($partial) {
+			$sqlq = $this->conn->qstr($sql.'%');
+			$arr = $this->conn->GetArray("select distinct sql1 from adodb_logsql where sql1 like $sqlq");
+			if ($arr) {
+				foreach($arr as $row) {
+					$sql = reset($row);
+					if (crc32($sql) == $partial) break;
+				}
+			}
+		}
+		$sql = str_replace('?',"''",$sql);
+		
+		if ($partial) {
+			$sqlq = $this->conn->qstr($sql.'%');
+			$sql = $this->conn->GetOne("select sql1 from adodb_logsql where sql1 like $sqlq");
+		}
+		
+		$s = '<p><b>Explain</b>: '.htmlspecialchars($sql).'</p>';
+		$rs = $this->conn->Execute('EXPLAIN '.$sql);
+		$s .= rs2html($rs,false,false,false,false);
+		$this->conn->LogSQL($save);
+		$s .= $this->Tracer($sql);
+		return $s;
+	}
+	
+	function Tables()
+	{
+		if (!$this->tablesSQL) return false;
+		
+		$rs = $this->conn->Execute($this->tablesSQL);
+		if (!$rs) return false;
+		
+		$html = rs2html($rs,false,false,false,false);
+		return $html;
+	}
+	
+	function GetReads()
+	{
+	global $ADODB_FETCH_MODE;
+		$save = $ADODB_FETCH_MODE;
+		$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
+		if ($this->conn->fetchMode !== false) $savem = $this->conn->SetFetchMode(false);
+		
+		$rs = $this->conn->Execute('show status');
+		
+		if (isset($savem)) $this->conn->SetFetchMode($savem);
+		$ADODB_FETCH_MODE = $save;
+		
+		if (!$rs) return 0;
+		$val = 0;
+		while (!$rs->EOF) {
+			switch($rs->fields[0]) {
+			case 'Com_select': 
+				$val = $rs->fields[1];
+				$rs->Close();
+				return $val;
+			}
+			$rs->MoveNext();
+		} 
+		
+		$rs->Close();
+		
+		return $val;
+	}
+	
+	function GetWrites()
+	{
+	global $ADODB_FETCH_MODE;
+		$save = $ADODB_FETCH_MODE;
+		$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
+		if ($this->conn->fetchMode !== false) $savem = $this->conn->SetFetchMode(false);
+		
+		$rs = $this->conn->Execute('show status');
+		
+		if (isset($savem)) $this->conn->SetFetchMode($savem);
+		$ADODB_FETCH_MODE = $save;
+		
+		if (!$rs) return 0;
+		$val = 0.0;
+		while (!$rs->EOF) {
+			switch($rs->fields[0]) {
+			case 'Com_insert': 
+				$val += $rs->fields[1]; break;
+			case 'Com_delete': 
+				$val += $rs->fields[1]; break;
+			case 'Com_update': 
+				$val += $rs->fields[1]/2;
+				$rs->Close();
+				return $val;
+			}
+			$rs->MoveNext();
+		} 
+		
+		$rs->Close();
+		
+		return $val;
+	}
+	
+	function FindDBHitRatio()
+	{
+		// first find out type of table
+		//$this->conn->debug=1;
+		
+		global $ADODB_FETCH_MODE;
+		$save = $ADODB_FETCH_MODE;
+		$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
+		if ($this->conn->fetchMode !== false) $savem = $this->conn->SetFetchMode(false);
+		
+		$rs = $this->conn->Execute('show table status');
+		
+		if (isset($savem)) $this->conn->SetFetchMode($savem);
+		$ADODB_FETCH_MODE = $save;
+		
+		if (!$rs) return '';
+		$type = strtoupper($rs->fields[1]);
+		$rs->Close();
+		switch($type){
+		case 'MYISAM':
+		case 'ISAM':
+			return $this->DBParameter('MyISAM cache hit ratio').' (MyISAM)';
+		case 'INNODB':
+			return $this->DBParameter('InnoDB cache hit ratio').' (InnoDB)';
+		default:
+			return $type.' not supported';
+		}
+		
+	}
+	
+	function GetQHitRatio()
+	{
+		//Total number of queries = Qcache_inserts + Qcache_hits + Qcache_not_cached
+		$hits = $this->_DBParameter(array("show status","Qcache_hits"));
+		$total = $this->_DBParameter(array("show status","Qcache_inserts"));
+		$total += $this->_DBParameter(array("show status","Qcache_not_cached"));
+		
+		$total += $hits;
+		if ($total) return round(($hits*100)/$total,2);
+		return 0;
+	}
+	
+	/*
+		Use session variable to store Hit percentage, because MySQL
+		does not remember last value of SHOW INNODB STATUS hit ratio
+		
+		# 1st query to SHOW INNODB STATUS
+		0.00 reads/s, 0.00 creates/s, 0.00 writes/s
+		Buffer pool hit rate 1000 / 1000
+		
+		# 2nd query to SHOW INNODB STATUS
+		0.00 reads/s, 0.00 creates/s, 0.00 writes/s
+		No buffer pool activity since the last printout
+	*/
+	function GetInnoDBHitRatio()
+	{
+	global $ADODB_FETCH_MODE;
+	
+		$save = $ADODB_FETCH_MODE;
+		$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
+		if ($this->conn->fetchMode !== false) $savem = $this->conn->SetFetchMode(false);
+		
+		$rs = $this->conn->Execute('show innodb status');
+		
+		if (isset($savem)) $this->conn->SetFetchMode($savem);
+		$ADODB_FETCH_MODE = $save;
+		
+		if (!$rs || $rs->EOF) return 0;
+		$stat = $rs->fields[0];
+		$rs->Close();
+		$at = strpos($stat,'Buffer pool hit rate');
+		$stat = substr($stat,$at,200);
+		if (preg_match('!Buffer pool hit rate\s*([0-9]*) / ([0-9]*)!',$stat,$arr)) {
+			$val = 100*$arr[1]/$arr[2];
+			$_SESSION['INNODB_HIT_PCT'] = $val;
+			return round($val,2);
+		} else {
+			if (isset($_SESSION['INNODB_HIT_PCT'])) return $_SESSION['INNODB_HIT_PCT'];
+			return 0;
+		}
+		return 0;
+	}
+	
+	function GetKeyHitRatio()
+	{
+		$hits = $this->_DBParameter(array("show status","Key_read_requests"));
+		$reqs = $this->_DBParameter(array("show status","Key_reads"));
+		if ($reqs == 0) return 0;
+		
+		return round(($hits/($reqs+$hits))*100,2);
+	}
+	
+    // start hack 
+    var $optimizeTableLow = 'CHECK TABLE %s FAST QUICK';
+    var $optimizeTableHigh = 'OPTIMIZE TABLE %s';
+    
+    /** 
+     * @see adodb_perf#optimizeTable
+     */
+     function optimizeTable( $table, $mode = ADODB_OPT_LOW) 
+     {
+        if ( !is_string( $table)) return false;
+        
+        $conn = $this->conn;
+        if ( !$conn) return false;
+        
+        $sql = '';
+        switch( $mode) {
+            case ADODB_OPT_LOW : $sql = $this->optimizeTableLow; break;
+            case ADODB_OPT_HIGH : $sql = $this->optimizeTableHigh; break;
+            default : 
+            {
+                // May dont use __FUNCTION__ constant for BC (__FUNCTION__ Added in PHP 4.3.0)
+                ADOConnection::outp( sprintf( "<p>%s: '%s' using of undefined mode '%s'</p>", __CLASS__, __FUNCTION__, $mode));
+                return false;
+            }
+        }
+        $sql = sprintf( $sql, $table);
+        
+        return $conn->Execute( $sql) !== false;
+     }
+    // end hack 
+}
+?>
Index: /Dev/trunk/rdfapi/util/adodb/perf/perf-oci8.inc.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/perf/perf-oci8.inc.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/perf/perf-oci8.inc.php	(revision 12)
@@ -0,0 +1,509 @@
+<?php
+/* 
+V4.94 23 Jan 2007  (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence. See License.txt. 
+  Set tabs to 4 for best viewing.
+  
+  Latest version is available at http://adodb.sourceforge.net
+  
+  Library for basic performance monitoring and tuning 
+  
+*/
+
+// security - hide paths
+if (!defined('ADODB_DIR')) die();
+
+class perf_oci8 extends ADODB_perf{
+	
+	var $tablesSQL = "select segment_name as \"tablename\", sum(bytes)/1024 as \"size_in_k\",tablespace_name as \"tablespace\",count(*) \"extents\" from sys.user_extents 
+	   group by segment_name,tablespace_name";
+	 
+	var $version;
+	var $createTableSQL = "CREATE TABLE adodb_logsql (
+		  created date NOT NULL,
+		  sql0 varchar(250) NOT NULL,
+		  sql1 varchar(4000) NOT NULL,
+		  params varchar(4000),
+		  tracer varchar(4000),
+		  timer decimal(16,6) NOT NULL
+		)";
+	
+	var $settings = array(
+	'Ratios',
+		'data cache hit ratio' => array('RATIOH',
+			"select round((1-(phy.value / (cur.value + con.value)))*100,2) 
+			from v\$sysstat cur, v\$sysstat con, v\$sysstat phy
+			where cur.name = 'db block gets' and
+			      con.name = 'consistent gets' and
+			      phy.name = 'physical reads'",
+			'=WarnCacheRatio'),
+		
+		'sql cache hit ratio' => array( 'RATIOH',
+			'select round(100*(sum(pins)-sum(reloads))/sum(pins),2)  from v$librarycache',
+			'increase <i>shared_pool_size</i> if too ratio low'),
+			
+		'datadict cache hit ratio' => array('RATIOH',
+		"select      
+           round((1 - (sum(getmisses) / (sum(gets) +          
+   		 sum(getmisses))))*100,2)
+		from  v\$rowcache",
+		'increase <i>shared_pool_size</i> if too ratio low'),
+		
+		'memory sort ratio' => array('RATIOH',
+		"SELECT ROUND((100 * b.VALUE) /DECODE ((a.VALUE + b.VALUE), 
+       0,1,(a.VALUE + b.VALUE)),2)
+FROM   v\$sysstat a, 
+       v\$sysstat b
+WHERE  a.name = 'sorts (disk)'
+AND    b.name = 'sorts (memory)'",
+	"% of memory sorts compared to disk sorts - should be over 95%"),
+
+	'IO',
+		'data reads' => array('IO',
+		"select value from v\$sysstat where name='physical reads'"),
+	
+	'data writes' => array('IO',
+		"select value from v\$sysstat where name='physical writes'"),
+	
+	'Data Cache',
+		'data cache buffers' => array( 'DATAC',
+		"select a.value/b.value  from v\$parameter a, v\$parameter b 
+			where a.name = 'db_cache_size' and b.name= 'db_block_size'",
+			'Number of cache buffers. Tune <i>db_cache_size</i> if the <i>data cache hit ratio</i> is too low.'),
+		'data cache blocksize' => array('DATAC',
+			"select value from v\$parameter where name='db_block_size'",
+			'' ),			
+	'Memory Pools',
+		'data cache size' => array('DATAC',
+			"select value from v\$parameter where name = 'db_cache_size'",
+			'db_cache_size' ),
+		'shared pool size' => array('DATAC',
+			"select value from v\$parameter where name = 'shared_pool_size'",
+			'shared_pool_size, which holds shared sql, stored procedures, dict cache and similar shared structs' ),
+		'java pool size' => array('DATAJ',
+			"select value from v\$parameter where name = 'java_pool_size'",
+			'java_pool_size' ),
+		'large pool buffer size' => array('CACHE',
+			"select value from v\$parameter where name='large_pool_size'",
+			'this pool is for large mem allocations (not because it is larger than shared pool), for MTS sessions, parallel queries, io buffers (large_pool_size) ' ),
+
+		'pga buffer size' => array('CACHE',			
+			"select value from v\$parameter where name='pga_aggregate_target'",
+			'program global area is private memory for sorting, and hash and bitmap merges - since oracle 9i (pga_aggregate_target)' ),
+
+		
+		'Connections',
+		'current connections' => array('SESS',
+			'select count(*) from sys.v_$session where username is not null',
+			''),
+		'max connections' => array( 'SESS',
+			"select value from v\$parameter where name='sessions'",
+			''),
+
+	'Memory Utilization',		
+		'data cache utilization ratio' => array('RATIOU',
+			"select round((1-bytes/sgasize)*100, 2)
+			from (select sum(bytes) sgasize from sys.v_\$sgastat) s, sys.v_\$sgastat f
+			where name = 'free memory' and pool = 'shared pool'",
+		'Percentage of data cache actually in use - should be over 85%'),
+		
+		'shared pool utilization ratio' => array('RATIOU',
+		'select round((sga.bytes/p.value)*100,2)
+		from v$sgastat sga, v$parameter p
+		where sga.name = \'free memory\' and sga.pool = \'shared pool\'
+		and p.name = \'shared_pool_size\'',
+		'Percentage of shared pool actually used - too low is bad, too high is worse'),
+		
+		'large pool utilization ratio' => array('RATIOU',
+			"select round((1-bytes/sgasize)*100, 2)
+			from (select sum(bytes) sgasize from sys.v_\$sgastat) s, sys.v_\$sgastat f
+			where name = 'free memory' and pool = 'large pool'",
+		'Percentage of large_pool actually in use - too low is bad, too high is worse'),
+		'sort buffer size' => array('CACHE',
+			"select value from v\$parameter where name='sort_area_size'",
+			'max in-mem sort_area_size (per query), uses memory in pga' ),
+
+		'pga usage at peak' => array('RATIOU',
+		'=PGA','Mb utilization at peak transactions (requires Oracle 9i+)'),
+	'Transactions',
+		'rollback segments' => array('ROLLBACK',
+			"select count(*) from sys.v_\$rollstat",
+			''),
+	
+		'peak transactions' => array('ROLLBACK',
+			"select max_utilization  tx_hwm
+    		from sys.v_\$resource_limit
+    		where resource_name = 'transactions'",
+			'Taken from high-water-mark'),
+		'max transactions' => array('ROLLBACK',
+			"select value from v\$parameter where name = 'transactions'",
+			'max transactions / rollback segments < 3.5 (or transactions_per_rollback_segment)'),
+	'Parameters',	
+		'cursor sharing' => array('CURSOR',
+			"select value from v\$parameter where name = 'cursor_sharing'",
+			'Cursor reuse strategy. Recommended is FORCE (8i+) or SIMILAR (9i+). See <a href=http://www.praetoriate.com/oracle_tips_cursor_sharing.htm>cursor_sharing</a>.'),
+		/*
+		'cursor reuse' => array('CURSOR',
+			"select count(*) from (select sql_text_wo_constants, count(*)
+  from t1
+ group by sql_text_wo_constants
+having count(*) > 100)",'These are sql statements that should be using bind variables'),*/
+		'index cache cost' => array('COST',
+			"select value from v\$parameter where name = 'optimizer_index_caching'",
+			'=WarnIndexCost'),
+		'random page cost' => array('COST',
+			"select value from v\$parameter where name = 'optimizer_index_cost_adj'",
+			'=WarnPageCost'),
+		
+		false
+		
+	);
+	
+	
+	function perf_oci8(&$conn)
+	{
+		$savelog = $conn->LogSQL(false);	
+		$this->version = $conn->ServerInfo();
+		$conn->LogSQL($savelog);	
+		$this->conn =& $conn;
+	}
+	
+	function WarnPageCost($val)
+	{
+		if ($val == 100) $s = '<font color=red><b>Too High</b>. </font>';
+		else $s = '';
+		
+		return $s.'Recommended is 20-50 for TP, and 50 for data warehouses. Default is 100. See <a href=http://www.dba-oracle.com/oracle_tips_cost_adj.htm>optimizer_index_cost_adj</a>. ';
+	}
+	
+	function WarnIndexCost($val)
+	{
+		if ($val == 0) $s = '<font color=red><b>Too Low</b>. </font>';
+		else $s = '';
+		
+		return $s.'Percentage of indexed data blocks expected in the cache.
+			Recommended is 20 (fast disk array) to 50 (slower hard disks). Default is 0.
+			 See <a href=http://www.dba-oracle.com/oracle_tips_cbo_part1.htm>optimizer_index_caching</a>.';
+		}
+	
+	function PGA()
+	{
+		if ($this->version['version'] < 9) return 'Oracle 9i or later required';
+		
+		$rs = $this->conn->Execute("select a.mb,a.targ as pga_size_pct,a.pct from 
+	   (select round(pga_target_for_estimate/1024.0/1024.0,0) Mb,
+	   	   pga_target_factor targ,estd_pga_cache_hit_percentage pct,rownum as r 
+	   	   from v\$pga_target_advice) a left join
+	   (select round(pga_target_for_estimate/1024.0/1024.0,0) Mb,
+	   	   pga_target_factor targ,estd_pga_cache_hit_percentage pct,rownum as r 
+	   	   from v\$pga_target_advice) b on 
+	  a.r = b.r+1 where 
+  		b.pct < 100");
+		if (!$rs) return "Only in 9i or later";
+		$rs->Close();
+		if ($rs->EOF) return "PGA could be too big";
+		
+		return reset($rs->fields);
+	}
+	
+	function Explain($sql,$partial=false) 
+	{
+		$savelog = $this->conn->LogSQL(false);
+		$rs =& $this->conn->SelectLimit("select ID FROM PLAN_TABLE");
+		if (!$rs) {
+			echo "<p><b>Missing PLAN_TABLE</b></p>
+<pre>
+CREATE TABLE PLAN_TABLE (
+  STATEMENT_ID                    VARCHAR2(30),
+  TIMESTAMP                       DATE,
+  REMARKS                         VARCHAR2(80),
+  OPERATION                       VARCHAR2(30),
+  OPTIONS                         VARCHAR2(30),
+  OBJECT_NODE                     VARCHAR2(128),
+  OBJECT_OWNER                    VARCHAR2(30),
+  OBJECT_NAME                     VARCHAR2(30),
+  OBJECT_INSTANCE                 NUMBER(38),
+  OBJECT_TYPE                     VARCHAR2(30),
+  OPTIMIZER                       VARCHAR2(255),
+  SEARCH_COLUMNS                  NUMBER,
+  ID                              NUMBER(38),
+  PARENT_ID                       NUMBER(38),
+  POSITION                        NUMBER(38),
+  COST                            NUMBER(38),
+  CARDINALITY                     NUMBER(38),
+  BYTES                           NUMBER(38),
+  OTHER_TAG                       VARCHAR2(255),
+  PARTITION_START                 VARCHAR2(255),
+  PARTITION_STOP                  VARCHAR2(255),
+  PARTITION_ID                    NUMBER(38),
+  OTHER                           LONG,
+  DISTRIBUTION                    VARCHAR2(30)
+);
+</pre>";
+			return false;
+		}
+		
+		$rs->Close();
+	//	$this->conn->debug=1;
+	
+		if ($partial) {
+			$sqlq = $this->conn->qstr($sql.'%');
+			$arr = $this->conn->GetArray("select distinct distinct sql1 from adodb_logsql where sql1 like $sqlq");
+			if ($arr) {
+				foreach($arr as $row) {
+					$sql = reset($row);
+					if (crc32($sql) == $partial) break;
+				}
+			}
+		}
+		
+		$s = "<p><b>Explain</b>: ".htmlspecialchars($sql)."</p>";	
+		
+		$this->conn->BeginTrans();
+		$id = "ADODB ".microtime();
+
+		$rs =& $this->conn->Execute("EXPLAIN PLAN SET STATEMENT_ID='$id' FOR $sql");
+		$m = $this->conn->ErrorMsg();
+		if ($m) {
+			$this->conn->RollbackTrans();
+			$this->conn->LogSQL($savelog);
+			$s .= "<p>$m</p>";
+			return $s;
+		}
+		$rs =& $this->conn->Execute("
+		select 
+  '<pre>'||lpad('--', (level-1)*2,'-') || trim(operation) || ' ' || trim(options)||'</pre>'  as Operation, 
+  object_name,COST,CARDINALITY,bytes
+		FROM plan_table 
+START WITH id = 0  and STATEMENT_ID='$id'  
+CONNECT BY prior id=parent_id and statement_id='$id'");
+		
+		$s .= rs2html($rs,false,false,false,false);
+		$this->conn->RollbackTrans();
+		$this->conn->LogSQL($savelog);
+		$s .= $this->Tracer($sql,$partial);
+		return $s;
+	}
+	
+	
+	function CheckMemory()
+	{
+		if ($this->version['version'] < 9) return 'Oracle 9i or later required';
+		
+		 $rs =& $this->conn->Execute("
+select  a.size_for_estimate as cache_mb_estimate,
+	case when a.size_factor=1 then 
+   		'&lt;&lt;= current'
+	 when a.estd_physical_read_factor-b.estd_physical_read_factor > 0 and a.estd_physical_read_factor<1 then
+		'- BETTER - '
+	else ' ' end as currsize, 
+   a.estd_physical_read_factor-b.estd_physical_read_factor as best_when_0
+   from (select size_for_estimate,size_factor,estd_physical_read_factor,rownum  r from v\$db_cache_advice) a , 
+   (select size_for_estimate,size_factor,estd_physical_read_factor,rownum r from v\$db_cache_advice) b where a.r = b.r-1");
+		if (!$rs) return false;
+		
+		/*
+		The v$db_cache_advice utility show the marginal changes in physical data block reads for different sizes of db_cache_size
+		*/
+		$s = "<h3>Data Cache Estimate</h3>";
+		if ($rs->EOF) {
+			$s .= "<p>Cache that is 50% of current size is still too big</p>";
+		} else {
+			$s .= "Ideal size of Data Cache is when \"best_when_0\" changes from a positive number and becomes zero.";
+			$s .= rs2html($rs,false,false,false,false);
+		}
+		return $s;
+	}
+	
+	/*
+		Generate html for suspicious/expensive sql
+	*/
+	function tohtml(&$rs,$type)
+	{
+		$o1 = $rs->FetchField(0);
+		$o2 = $rs->FetchField(1);
+		$o3 = $rs->FetchField(2);
+		if ($rs->EOF) return '<p>None found</p>';
+		$check = '';
+		$sql = '';
+		$s = "\n\n<table border=1 bgcolor=white><tr><td><b>".$o1->name.'</b></td><td><b>'.$o2->name.'</b></td><td><b>'.$o3->name.'</b></td></tr>';
+		while (!$rs->EOF) {
+			if ($check != $rs->fields[0].'::'.$rs->fields[1]) {
+				if ($check) {
+					$carr = explode('::',$check);
+					$prefix = "<a href=\"?$type=1&sql=".rawurlencode($sql).'&x#explain">';
+					$suffix = '</a>';
+					if (strlen($prefix)>2000) {
+						$prefix = '';
+						$suffix = '';
+					}
+					
+					$s .=  "\n<tr><td align=right>".$carr[0].'</td><td align=right>'.$carr[1].'</td><td>'.$prefix.$sql.$suffix.'</td></tr>';
+				}
+				$sql = $rs->fields[2];
+				$check = $rs->fields[0].'::'.$rs->fields[1];			
+			} else
+				$sql .= $rs->fields[2];
+			if (substr($sql,strlen($sql)-1) == "\0") $sql = substr($sql,0,strlen($sql)-1);
+			$rs->MoveNext();
+		}
+		$rs->Close();
+		
+		$carr = explode('::',$check);
+		$prefix = "<a target=".rand()." href=\"?&hidem=1&$type=1&sql=".rawurlencode($sql).'&x#explain">';
+		$suffix = '</a>';
+		if (strlen($prefix)>2000) {
+			$prefix = '';
+			$suffix = '';
+		}
+		$s .=  "\n<tr><td align=right>".$carr[0].'</td><td align=right>'.$carr[1].'</td><td>'.$prefix.$sql.$suffix.'</td></tr>';
+					
+		return $s."</table>\n\n";
+	}
+	
+	// code thanks to Ixora. 
+	// http://www.ixora.com.au/scripts/query_opt.htm
+	// requires oracle 8.1.7 or later
+	function SuspiciousSQL($numsql=10)
+	{
+		$sql = "
+select
+  substr(to_char(s.pct, '99.00'), 2) || '%'  load,
+  s.executions  executes,
+  p.sql_text
+from
+  ( 
+    select
+      address,
+      buffer_gets,
+      executions,
+      pct,
+      rank() over (order by buffer_gets desc)  ranking
+    from
+      ( 
+	select
+	  address,
+	  buffer_gets,
+	  executions,
+	  100 * ratio_to_report(buffer_gets) over ()  pct
+	from
+	  sys.v_\$sql
+	where
+	  command_type != 47 and module != 'T.O.A.D.'
+      )
+    where
+      buffer_gets > 50 * executions
+  )  s,
+  sys.v_\$sqltext  p
+where
+  s.ranking <= $numsql and
+  p.address = s.address
+order by
+  1 desc, s.address, p.piece";
+
+  		global $ADODB_CACHE_MODE;
+  		if (isset($_GET['expsixora']) && isset($_GET['sql'])) {
+				$partial = empty($_GET['part']);
+				echo "<a name=explain></a>".$this->Explain($_GET['sql'],$partial)."\n";
+		}
+
+		if (isset($_GET['sql'])) return $this->_SuspiciousSQL($numsql);
+		
+		$s = '';
+		$s .= $this->_SuspiciousSQL($numsql);
+		$s .= '<p>';
+		
+		$save = $ADODB_CACHE_MODE;
+		$ADODB_CACHE_MODE = ADODB_FETCH_NUM;
+		if ($this->conn->fetchMode !== false) $savem = $this->conn->SetFetchMode(false);
+		
+		$savelog = $this->conn->LogSQL(false);
+		$rs =& $this->conn->SelectLimit($sql);
+		$this->conn->LogSQL($savelog);
+		
+		if (isset($savem)) $this->conn->SetFetchMode($savem);
+		$ADODB_CACHE_MODE = $save;
+		if ($rs) {
+			$s .= "\n<h3>Ixora Suspicious SQL</h3>";
+			$s .= $this->tohtml($rs,'expsixora');
+		}
+		
+		return $s;
+	}
+	
+	// code thanks to Ixora. 
+	// http://www.ixora.com.au/scripts/query_opt.htm
+	// requires oracle 8.1.7 or later
+	function ExpensiveSQL($numsql = 10)
+	{
+		$sql = "
+select
+  substr(to_char(s.pct, '99.00'), 2) || '%'  load,
+  s.executions  executes,
+  p.sql_text
+from
+  ( 
+    select
+      address,
+      disk_reads,
+      executions,
+      pct,
+      rank() over (order by disk_reads desc)  ranking
+    from
+      (
+	select
+	  address,
+	  disk_reads,
+	  executions,
+	  100 * ratio_to_report(disk_reads) over ()  pct
+	from
+	  sys.v_\$sql
+	where
+	  command_type != 47 and module != 'T.O.A.D.'
+      )
+    where
+      disk_reads > 50 * executions
+  )  s,
+  sys.v_\$sqltext  p
+where
+  s.ranking <= $numsql and
+  p.address = s.address
+order by
+  1 desc, s.address, p.piece
+";
+		global $ADODB_CACHE_MODE;
+  		if (isset($_GET['expeixora']) && isset($_GET['sql'])) {
+			$partial = empty($_GET['part']);	
+			echo "<a name=explain></a>".$this->Explain($_GET['sql'],$partial)."\n";
+		}
+		if (isset($_GET['sql'])) {
+			 $var = $this->_ExpensiveSQL($numsql);
+			 return $var;
+		}
+		
+		$s = '';		
+		$s .= $this->_ExpensiveSQL($numsql);
+		$s .= '<p>';
+		$save = $ADODB_CACHE_MODE;
+		$ADODB_CACHE_MODE = ADODB_FETCH_NUM;
+		if ($this->conn->fetchMode !== false) $savem = $this->conn->SetFetchMode(false);
+		
+		$savelog = $this->conn->LogSQL(false);
+		$rs =& $this->conn->Execute($sql);
+		$this->conn->LogSQL($savelog);
+		
+		if (isset($savem)) $this->conn->SetFetchMode($savem);
+		$ADODB_CACHE_MODE = $save;
+		
+		if ($rs) {
+			$s .= "\n<h3>Ixora Expensive SQL</h3>";
+			$s .= $this->tohtml($rs,'expeixora');
+		}
+	
+		return $s;
+	}
+	
+}
+?>
Index: /Dev/trunk/rdfapi/util/adodb/perf/perf-postgres.inc.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/perf/perf-postgres.inc.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/perf/perf-postgres.inc.php	(revision 12)
@@ -0,0 +1,124 @@
+<?php
+
+/* 
+V4.94 23 Jan 2007  (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence. See License.txt. 
+  Set tabs to 4 for best viewing.
+  
+  Latest version is available at http://adodb.sourceforge.net
+  
+  Library for basic performance monitoring and tuning 
+  
+*/
+
+// security - hide paths
+if (!defined('ADODB_DIR')) die();
+
+/*
+	Notice that PostgreSQL has no sql query cache
+*/
+class perf_postgres extends adodb_perf{
+	
+	var $tablesSQL = 
+	"select a.relname as tablename,(a.relpages+CASE WHEN b.relpages is null THEN 0 ELSE b.relpages END+CASE WHEN c.relpages is null THEN 0 ELSE c.relpages END)*8 as size_in_K,a.relfilenode as \"OID\"  from pg_class a left join pg_class b
+		on b.relname = 'pg_toast_'||trim(a.relfilenode) 
+		left join pg_class c on c.relname = 'pg_toast_'||trim(a.relfilenode)||'_index'
+		where a.relname in (select tablename from pg_tables where tablename not like 'pg_%')";
+	
+	var $createTableSQL = "CREATE TABLE adodb_logsql (
+		  created timestamp NOT NULL,
+		  sql0 varchar(250) NOT NULL,
+		  sql1 text NOT NULL,
+		  params text NOT NULL,
+		  tracer text NOT NULL,
+		  timer decimal(16,6) NOT NULL
+		)";	
+	
+	var $settings = array(
+	'Ratios',
+		'statistics collector' => array('RATIO',
+			"select case when count(*)=3 then 'TRUE' else 'FALSE' end from pg_settings where (name='stats_block_level' or name='stats_row_level' or name='stats_start_collector') and setting='on' ",
+			'Value must be TRUE to enable hit ratio statistics (<i>stats_start_collector</i>,<i>stats_row_level</i> and <i>stats_block_level</i> must be set to true in postgresql.conf)'),
+		'data cache hit ratio' => array('RATIO',
+			"select case when blks_hit=0 then 0 else round( ((1-blks_read::float/blks_hit)*100)::numeric, 2) end from pg_stat_database where datname='\$DATABASE'",
+			'=WarnCacheRatio'),
+	'IO',
+		'data reads' => array('IO',
+		'select sum(heap_blks_read+toast_blks_read) from pg_statio_user_tables',
+		),
+		'data writes' => array('IO',
+		'select round((sum(n_tup_ins/4.0+n_tup_upd/8.0+n_tup_del/4.0)/16)::numeric,2) from pg_stat_user_tables',
+		'Count of inserts/updates/deletes * coef'),
+
+	'Data Cache',
+		'data cache buffers' => array('DATAC',
+			"select setting from pg_settings where name='shared_buffers'",
+			'Number of cache buffers. <a href=http://www.varlena.com/GeneralBits/Tidbits/perf.html#basic>Tuning</a>'),
+		'cache blocksize' => array('DATAC',
+			'select 8192',
+			'(estimate)' ),
+		'data cache size' => array( 'DATAC',
+		"select setting::integer*8192 from pg_settings where name='shared_buffers'",
+			'' ),
+		'operating system cache size' => array( 'DATA',
+		"select setting::integer*8192 from pg_settings where name='effective_cache_size'",
+			'(effective cache size)' ),
+	'Memory Usage',
+	# Postgres 7.5 changelog: Rename server parameters SortMem and VacuumMem to work_mem and maintenance_work_mem;
+		'sort/work buffer size' => array('CACHE',
+			"select setting::integer*1024 from pg_settings where name='sort_mem' or name = 'work_mem' order by name",
+			'Size of sort buffer (per query)' ),
+	'Connections',
+		'current connections' => array('SESS',
+			'select count(*) from pg_stat_activity',
+			''),
+		'max connections' => array('SESS',
+			"select setting from pg_settings where name='max_connections'",
+			''),
+	'Parameters',
+		'rollback buffers' => array('COST',
+			"select setting from pg_settings where name='wal_buffers'",
+			'WAL buffers'),
+		'random page cost' => array('COST',
+			"select setting from pg_settings where name='random_page_cost'",
+			'Cost of doing a seek (default=4). See <a href=http://www.varlena.com/GeneralBits/Tidbits/perf.html#less>random_page_cost</a>'),
+		false
+	);
+	
+	function perf_postgres(&$conn)
+	{
+		$this->conn =& $conn;
+	}
+	
+	function Explain($sql,$partial=false)
+	{
+		$save = $this->conn->LogSQL(false);
+		
+		if ($partial) {
+			$sqlq = $this->conn->qstr($sql.'%');
+			$arr = $this->conn->GetArray("select distinct distinct sql1 from adodb_logsql where sql1 like $sqlq");
+			if ($arr) {
+				foreach($arr as $row) {
+					$sql = reset($row);
+					if (crc32($sql) == $partial) break;
+				}
+			}
+		}
+		$sql = str_replace('?',"''",$sql);
+		$s = '<p><b>Explain</b>: '.htmlspecialchars($sql).'</p>';
+		$rs = $this->conn->Execute('EXPLAIN '.$sql);
+		$this->conn->LogSQL($save);
+		$s .= '<pre>';
+		if ($rs)
+			while (!$rs->EOF) {
+				$s .= reset($rs->fields)."\n";
+				$rs->MoveNext();
+			}
+		$s .= '</pre>';
+		$s .= $this->Tracer($sql,$partial);
+		return $s;
+	}
+}
+?>
Index: /Dev/trunk/rdfapi/util/adodb/pivottable.inc.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/pivottable.inc.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/pivottable.inc.php	(revision 12)
@@ -0,0 +1,187 @@
+<?php
+/** 
+ * @version V4.93 10 Oct 2006 (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
+ * Released under both BSD license and Lesser GPL library license. 
+ * Whenever there is any discrepancy between the two licenses, 
+ * the BSD license will take precedence. 
+ *
+ * Set tabs to 4 for best viewing.
+ * 
+*/
+
+/*
+ * Concept from daniel.lucazeau@ajornet.com. 
+ *
+ * @param db		Adodb database connection
+ * @param tables	List of tables to join
+ * @rowfields		List of fields to display on each row
+ * @colfield		Pivot field to slice and display in columns, if we want to calculate
+ *						ranges, we pass in an array (see example2)
+ * @where			Where clause. Optional.
+ * @aggfield		This is the field to sum. Optional. 
+ *						Since 2.3.1, if you can use your own aggregate function 
+ *						instead of SUM, eg. $aggfield = 'fieldname'; $aggfn = 'AVG';
+ * @sumlabel		Prefix to display in sum columns. Optional.
+ * @aggfn			Aggregate function to use (could be AVG, SUM, COUNT)
+ * @showcount		Show count of records
+ *
+ * @returns			Sql generated
+ */
+ 
+ function PivotTableSQL(&$db,$tables,$rowfields,$colfield, $where=false,
+ 	$aggfield = false,$sumlabel='Sum ',$aggfn ='SUM', $showcount = true)
+ {
+	if ($aggfield) $hidecnt = true;
+	else $hidecnt = false;
+	
+	$iif = strpos($db->databaseType,'access') !== false; 
+		// note - vfp 6 still doesn' work even with IIF enabled || $db->databaseType == 'vfp';
+	
+	//$hidecnt = false;
+	
+ 	if ($where) $where = "\nWHERE $where";
+	if (!is_array($colfield)) $colarr = $db->GetCol("select distinct $colfield from $tables $where order by 1");
+	if (!$aggfield) $hidecnt = false;
+	
+	$sel = "$rowfields, ";
+	if (is_array($colfield)) {
+		foreach ($colfield as $k => $v) {
+			$k = trim($k);
+			if (!$hidecnt) {
+				$sel .= $iif ? 
+					"\n\t$aggfn(IIF($v,1,0)) AS \"$k\", "
+					:
+					"\n\t$aggfn(CASE WHEN $v THEN 1 ELSE 0 END) AS \"$k\", ";
+			}
+			if ($aggfield) {
+				$sel .= $iif ?
+					"\n\t$aggfn(IIF($v,$aggfield,0)) AS \"$sumlabel$k\", "
+					:
+					"\n\t$aggfn(CASE WHEN $v THEN $aggfield ELSE 0 END) AS \"$sumlabel$k\", ";
+			}
+		} 
+	} else {
+		foreach ($colarr as $v) {
+			if (!is_numeric($v)) $vq = $db->qstr($v);
+			else $vq = $v;
+			$v = trim($v);
+			if (strlen($v) == 0	) $v = 'null';
+			if (!$hidecnt) {
+				$sel .= $iif ?
+					"\n\t$aggfn(IIF($colfield=$vq,1,0)) AS \"$v\", "
+					:
+					"\n\t$aggfn(CASE WHEN $colfield=$vq THEN 1 ELSE 0 END) AS \"$v\", ";
+			}
+			if ($aggfield) {
+				if ($hidecnt) $label = $v;
+				else $label = "{$v}_$aggfield";
+				$sel .= $iif ?
+					"\n\t$aggfn(IIF($colfield=$vq,$aggfield,0)) AS \"$label\", "
+					:
+					"\n\t$aggfn(CASE WHEN $colfield=$vq THEN $aggfield ELSE 0 END) AS \"$label\", ";
+			}
+		}
+	}
+	if ($aggfield && $aggfield != '1'){
+		$agg = "$aggfn($aggfield)";
+		$sel .= "\n\t$agg as \"$sumlabel$aggfield\", ";		
+	}
+	
+	if ($showcount)
+		$sel .= "\n\tSUM(1) as Total";
+	else
+		$sel = substr($sel,0,strlen($sel)-2);
+	
+	
+	// Strip aliases
+	$rowfields = preg_replace('/ AS (\w+)/i', '', $rowfields);
+	
+	$sql = "SELECT $sel \nFROM $tables $where \nGROUP BY $rowfields";
+	
+	return $sql;
+ }
+
+/* EXAMPLES USING MS NORTHWIND DATABASE */
+if (0) {
+
+# example1
+#
+# Query the main "product" table
+# Set the rows to CompanyName and QuantityPerUnit
+# and the columns to the Categories
+# and define the joins to link to lookup tables 
+# "categories" and "suppliers"
+#
+
+ $sql = PivotTableSQL(
+ 	$gDB,  											# adodb connection
+ 	'products p ,categories c ,suppliers s',  		# tables
+	'CompanyName,QuantityPerUnit',					# row fields
+	'CategoryName',									# column fields 
+	'p.CategoryID = c.CategoryID and s.SupplierID= p.SupplierID' # joins/where
+);
+ print "<pre>$sql";
+ $rs = $gDB->Execute($sql);
+ rs2html($rs);
+ 
+/*
+Generated SQL:
+
+SELECT CompanyName,QuantityPerUnit, 
+	SUM(CASE WHEN CategoryName='Beverages' THEN 1 ELSE 0 END) AS "Beverages", 
+	SUM(CASE WHEN CategoryName='Condiments' THEN 1 ELSE 0 END) AS "Condiments", 
+	SUM(CASE WHEN CategoryName='Confections' THEN 1 ELSE 0 END) AS "Confections", 
+	SUM(CASE WHEN CategoryName='Dairy Products' THEN 1 ELSE 0 END) AS "Dairy Products", 
+	SUM(CASE WHEN CategoryName='Grains/Cereals' THEN 1 ELSE 0 END) AS "Grains/Cereals", 
+	SUM(CASE WHEN CategoryName='Meat/Poultry' THEN 1 ELSE 0 END) AS "Meat/Poultry", 
+	SUM(CASE WHEN CategoryName='Produce' THEN 1 ELSE 0 END) AS "Produce", 
+	SUM(CASE WHEN CategoryName='Seafood' THEN 1 ELSE 0 END) AS "Seafood", 
+	SUM(1) as Total 
+FROM products p ,categories c ,suppliers s  WHERE p.CategoryID = c.CategoryID and s.SupplierID= p.SupplierID 
+GROUP BY CompanyName,QuantityPerUnit
+*/
+//=====================================================================
+
+# example2
+#
+# Query the main "product" table
+# Set the rows to CompanyName and QuantityPerUnit
+# and the columns to the UnitsInStock for diiferent ranges
+# and define the joins to link to lookup tables 
+# "categories" and "suppliers"
+#
+ $sql = PivotTableSQL(
+ 	$gDB,										# adodb connection
+ 	'products p ,categories c ,suppliers s',	# tables
+	'CompanyName,QuantityPerUnit',				# row fields
+												# column ranges
+array(										
+' 0 ' => 'UnitsInStock <= 0',
+"1 to 5" => '0 < UnitsInStock and UnitsInStock <= 5',
+"6 to 10" => '5 < UnitsInStock and UnitsInStock <= 10',
+"11 to 15"  => '10 < UnitsInStock and UnitsInStock <= 15',
+"16+" =>'15 < UnitsInStock'
+),
+	' p.CategoryID = c.CategoryID and s.SupplierID= p.SupplierID', # joins/where
+	'UnitsInStock', 							# sum this field
+	'Sum'										# sum label prefix
+);
+ print "<pre>$sql";
+ $rs = $gDB->Execute($sql);
+ rs2html($rs);
+ /*
+ Generated SQL:
+ 
+SELECT CompanyName,QuantityPerUnit, 
+	SUM(CASE WHEN UnitsInStock <= 0 THEN UnitsInStock ELSE 0 END) AS "Sum  0 ", 
+	SUM(CASE WHEN 0 < UnitsInStock and UnitsInStock <= 5 THEN UnitsInStock ELSE 0 END) AS "Sum 1 to 5", 
+	SUM(CASE WHEN 5 < UnitsInStock and UnitsInStock <= 10 THEN UnitsInStock ELSE 0 END) AS "Sum 6 to 10", 
+	SUM(CASE WHEN 10 < UnitsInStock and UnitsInStock <= 15 THEN UnitsInStock ELSE 0 END) AS "Sum 11 to 15", 
+	SUM(CASE WHEN 15 < UnitsInStock THEN UnitsInStock ELSE 0 END) AS "Sum 16+",
+	SUM(UnitsInStock) AS "Sum UnitsInStock", 
+	SUM(1) as Total 
+FROM products p ,categories c ,suppliers s  WHERE  p.CategoryID = c.CategoryID and s.SupplierID= p.SupplierID 
+GROUP BY CompanyName,QuantityPerUnit
+ */
+}
+?>
Index: /Dev/trunk/rdfapi/util/adodb/readme.txt
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/readme.txt	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/readme.txt	(revision 12)
@@ -0,0 +1,62 @@
+>> ADODB Library for PHP4
+
+(c) 2000-2004 John Lim (jlim@natsoft.com.my)
+
+Released under both BSD and GNU Lesser GPL library license. 
+This means you can use it in proprietary products.
+ 
+ 
+>> Introduction
+
+PHP's database access functions are not standardised. This creates a 
+need for a database class library to hide the differences between the 
+different databases (encapsulate the differences) so we can easily 
+switch databases.
+
+We currently support MySQL, Interbase, Sybase, PostgreSQL, Oracle, 
+Microsoft SQL server,  Foxpro ODBC, Access ODBC, Informix, DB2,
+Sybase SQL Anywhere, generic ODBC and Microsoft's ADO. 
+
+We hope more people will contribute drivers to support other databases.
+
+
+>> Documentation and Examples
+
+Refer to the adodb/docs directory for full documentation and examples. 
+There is also a  tutorial tute.htm that contrasts ADODB code with 
+mysql code.
+
+
+>>> Files
+Adodb.inc.php is the main file. You need to include only this file.
+
+Adodb-*.inc.php are the database specific driver code.
+
+Test.php contains a list of test commands to exercise the class library.
+
+Adodb-session.php is the PHP4 session handling code.
+
+Testdatabases.inc.php contains the list of databases to apply the tests on.
+
+Benchmark.php is a simple benchmark to test the throughput of a simple SELECT 
+statement for databases described in testdatabases.inc.php. The benchmark
+tables are created in test.php.
+
+readme.htm is the main documentation.
+
+tute.htm is the tutorial.
+
+
+>> More Info
+
+For more information, including installation see readme.htm
+or visit
+           http://adodb.sourceforge.net/
+
+
+>> Feature Requests and Bug Reports
+
+Email to jlim@natsoft.com.my 
+
+
+ 
Index: /Dev/trunk/rdfapi/util/adodb/rsfilter.inc.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/rsfilter.inc.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/rsfilter.inc.php	(revision 12)
@@ -0,0 +1,61 @@
+<?php
+/** 
+ * @version V4.93 10 Oct 2006 (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
+ * Released under both BSD license and Lesser GPL library license. 
+ * Whenever there is any discrepancy between the two licenses, 
+ * the BSD license will take precedence. 
+ *
+ * Set tabs to 4 for best viewing.
+ * 
+ * Latest version is available at http://php.weblogs.com
+ *
+ * Requires PHP4.01pl2 or later because it uses include_once
+*/
+
+/*
+	Filter all fields and all rows in a recordset and returns the 
+	processed recordset. We scroll to the beginning of the new recordset
+	after processing.
+	
+	We pass a recordset and function name to RSFilter($rs,'rowfunc');
+	and the function will be called multiple times, once
+	for each row in the recordset. The function will be passed
+	an array containing one row repeatedly.
+	
+	Example: 
+ 	
+	// ucwords() every element in the recordset
+	function do_ucwords(&$arr,$rs)
+	{
+		foreach($arr as $k => $v) {
+			$arr[$k] = ucwords($v);
+		}
+	}
+	$rs = RSFilter($rs,'do_ucwords');
+ */
+function &RSFilter($rs,$fn)
+{
+	if ($rs->databaseType != 'array') {
+		if (!$rs->connection) return false;
+		
+		$rs = &$rs->connection->_rs2rs($rs);
+	}
+	$rows = $rs->RecordCount();
+	for ($i=0; $i < $rows; $i++) {
+		if (is_array ($fn)) {
+        	$obj = $fn[0];
+        	$method = $fn[1];
+        	$obj->$method ($rs->_array[$i],$rs);
+      } else {
+			$fn($rs->_array[$i],$rs);
+      }
+	  
+	}
+	if (!$rs->EOF) {
+		$rs->_currentRow = 0;
+		$rs->fields = $rs->_array[0];
+	}
+	
+	return $rs;
+}
+?>
Index: /Dev/trunk/rdfapi/util/adodb/server.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/server.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/server.php	(revision 12)
@@ -0,0 +1,100 @@
+<?php
+
+/** 
+ * @version V4.93 10 Oct 2006 (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
+ * Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence. 
+ */
+ 
+/* Documentation on usage is at http://php.weblogs.com/adodb_csv
+ *
+ * Legal query string parameters:
+ * 
+ * sql = holds sql string
+ * nrows = number of rows to return 
+ * offset = skip offset rows of data
+ * fetch = $ADODB_FETCH_MODE
+ * 
+ * example:
+ *
+ * http://localhost/php/server.php?select+*+from+table&nrows=10&offset=2
+ */
+
+
+/* 
+ * Define the IP address you want to accept requests from 
+ * as a security measure. If blank we accept anyone promisciously!
+ */
+$ACCEPTIP = '127.0.0.1';
+
+/*
+ * Connection parameters
+ */
+$driver = 'mysql';
+$host = 'localhost'; // DSN for odbc
+$uid = 'root';
+$pwd = 'garbase-it-is';
+$database = 'test';
+
+/*============================ DO NOT MODIFY BELOW HERE =================================*/
+// $sep must match csv2rs() in adodb.inc.php
+$sep = ' :::: ';
+
+include('./adodb.inc.php');
+include_once(ADODB_DIR.'/adodb-csvlib.inc.php');
+
+function err($s)
+{
+	die('**** '.$s.' ');
+}
+
+// undo stupid magic quotes
+function undomq(&$m) 
+{
+	if (get_magic_quotes_gpc()) {
+		// undo the damage
+		$m = str_replace('\\\\','\\',$m);
+		$m = str_replace('\"','"',$m);
+		$m = str_replace('\\\'','\'',$m);
+		
+	}
+	return $m;
+}
+
+///////////////////////////////////////// DEFINITIONS
+
+
+$remote = $_SERVER["REMOTE_ADDR"]; 
+ 
+
+if (!empty($ACCEPTIP))
+ if ($remote != '127.0.0.1' && $remote != $ACCEPTIP) 
+ 	err("Unauthorised client: '$remote'");
+	
+	
+if (empty($_REQUEST['sql'])) err('No SQL');
+
+
+$conn = &ADONewConnection($driver);
+
+if (!$conn->Connect($host,$uid,$pwd,$database)) err($conn->ErrorNo(). $sep . $conn->ErrorMsg());
+$sql = undomq($_REQUEST['sql']);
+
+if (isset($_REQUEST['fetch']))
+	$ADODB_FETCH_MODE = $_REQUEST['fetch'];
+	
+if (isset($_REQUEST['nrows'])) {
+	$nrows = $_REQUEST['nrows'];
+	$offset = isset($_REQUEST['offset']) ? $_REQUEST['offset'] : -1;
+	$rs = $conn->SelectLimit($sql,$nrows,$offset);
+} else 
+	$rs = $conn->Execute($sql);
+if ($rs){ 
+	//$rs->timeToLive = 1;
+	echo _rs2serialize($rs,$conn,$sql);
+	$rs->Close();
+} else
+	err($conn->ErrorNo(). $sep .$conn->ErrorMsg());
+
+?>
Index: /Dev/trunk/rdfapi/util/adodb/session/adodb-compress-bzip2.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/session/adodb-compress-bzip2.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/session/adodb-compress-bzip2.php	(revision 12)
@@ -0,0 +1,118 @@
+<?php
+
+/*
+V4.94 23 Jan 2007  (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
+         Contributed by Ross Smith (adodb@netebb.com). 
+  Released under both BSD license and Lesser GPL library license.
+  Whenever there is any discrepancy between the two licenses,
+  the BSD license will take precedence.
+	  Set tabs to 4 for best viewing.
+
+*/
+
+if (!function_exists('bzcompress')) {
+	trigger_error('bzip2 functions are not available', E_USER_ERROR);
+	return 0;
+}
+
+/*
+*/
+class ADODB_Compress_Bzip2 {
+	/**
+	 */
+	var $_block_size = null;
+
+	/**
+	 */
+	var $_work_level = null;
+
+	/**
+	 */
+	var $_min_length = 1;
+
+	/**
+	 */
+	function getBlockSize() {
+		return $this->_block_size;
+	}
+
+	/**
+	 */
+	function setBlockSize($block_size) {
+		assert('$block_size >= 1');
+		assert('$block_size <= 9');
+		$this->_block_size = (int) $block_size;
+	}
+
+	/**
+	 */
+	function getWorkLevel() {
+		return $this->_work_level;
+	}
+
+	/**
+	 */
+	function setWorkLevel($work_level) {
+		assert('$work_level >= 0');
+		assert('$work_level <= 250');
+		$this->_work_level = (int) $work_level;
+	}
+
+	/**
+	 */
+	function getMinLength() {
+		return $this->_min_length;
+	}
+
+	/**
+	 */
+	function setMinLength($min_length) {
+		assert('$min_length >= 0');
+		$this->_min_length = (int) $min_length;
+	}
+
+	/**
+	 */
+	function ADODB_Compress_Bzip2($block_size = null, $work_level = null, $min_length = null) {
+		if (!is_null($block_size)) {
+			$this->setBlockSize($block_size);
+		}
+
+		if (!is_null($work_level)) {
+			$this->setWorkLevel($work_level);
+		}
+
+		if (!is_null($min_length)) {
+			$this->setMinLength($min_length);
+		}
+	}
+
+	/**
+	 */
+	function write($data, $key) {
+		if (strlen($data) < $this->_min_length) {
+			return $data;
+		}
+
+		if (!is_null($this->_block_size)) {
+			if (!is_null($this->_work_level)) {
+				return bzcompress($data, $this->_block_size, $this->_work_level);
+			} else {
+				return bzcompress($data, $this->_block_size);
+			}
+		}
+
+		return bzcompress($data);
+	}
+
+	/**
+	 */
+	function read($data, $key) {
+		return $data ? bzdecompress($data) : $data;
+	}
+
+}
+
+return 1;
+
+?>
Index: /Dev/trunk/rdfapi/util/adodb/session/adodb-compress-gzip.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/session/adodb-compress-gzip.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/session/adodb-compress-gzip.php	(revision 12)
@@ -0,0 +1,93 @@
+<?php
+
+
+/*
+V4.94 23 Jan 2007  (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
+         Contributed by Ross Smith (adodb@netebb.com). 
+  Released under both BSD license and Lesser GPL library license.
+  Whenever there is any discrepancy between the two licenses,
+  the BSD license will take precedence.
+	  Set tabs to 4 for best viewing.
+
+*/
+
+if (!function_exists('gzcompress')) {
+	trigger_error('gzip functions are not available', E_USER_ERROR);
+	return 0;
+}
+
+/*
+*/
+class ADODB_Compress_Gzip {
+	/**
+	 */
+	var $_level = null;
+
+	/**
+	 */
+	var $_min_length = 1;
+
+	/**
+	 */
+	function getLevel() {
+		return $this->_level;
+	}
+
+	/**
+	 */
+	function setLevel($level) {
+		assert('$level >= 0');
+		assert('$level <= 9');
+		$this->_level = (int) $level;
+	}
+
+	/**
+	 */
+	function getMinLength() {
+		return $this->_min_length;
+	}
+
+	/**
+	 */
+	function setMinLength($min_length) {
+		assert('$min_length >= 0');
+		$this->_min_length = (int) $min_length;
+	}
+
+	/**
+	 */
+	function ADODB_Compress_Gzip($level = null, $min_length = null) {
+		if (!is_null($level)) {
+			$this->setLevel($level);
+		}
+
+		if (!is_null($min_length)) {
+			$this->setMinLength($min_length);
+		}
+	}
+
+	/**
+	 */
+	function write($data, $key) {
+		if (strlen($data) < $this->_min_length) {
+			return $data;
+		}
+
+		if (!is_null($this->_level)) {
+			return gzcompress($data, $this->_level);
+		} else {
+			return gzcompress($data);
+		}
+	}
+
+	/**
+	 */
+	function read($data, $key) {
+		return $data ? gzuncompress($data) : $data;
+	}
+
+}
+
+return 1;
+
+?>
Index: /Dev/trunk/rdfapi/util/adodb/session/adodb-cryptsession.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/session/adodb-cryptsession.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/session/adodb-cryptsession.php	(revision 12)
@@ -0,0 +1,27 @@
+<?php
+
+
+/*
+V4.94 23 Jan 2007  (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
+         Contributed by Ross Smith (adodb@netebb.com). 
+  Released under both BSD license and Lesser GPL library license.
+  Whenever there is any discrepancy between the two licenses,
+  the BSD license will take precedence.
+	  Set tabs to 4 for best viewing.
+*/
+
+/*
+
+This file is provided for backwards compatibility purposes
+
+*/
+
+if (!defined('ADODB_SESSION')) {
+	require_once dirname(__FILE__) . '/adodb-session.php';
+}
+
+require_once  ADODB_SESSION . '/adodb-encrypt-md5.php';
+
+ADODB_Session::filter(new ADODB_Encrypt_MD5());
+
+?>
Index: /Dev/trunk/rdfapi/util/adodb/session/adodb-cryptsession2.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/session/adodb-cryptsession2.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/session/adodb-cryptsession2.php	(revision 12)
@@ -0,0 +1,27 @@
+<?php
+
+
+/*
+V4.94 23 Jan 2007  (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
+         Contributed by Ross Smith (adodb@netebb.com). 
+  Released under both BSD license and Lesser GPL library license.
+  Whenever there is any discrepancy between the two licenses,
+  the BSD license will take precedence.
+	  Set tabs to 4 for best viewing.
+*/
+
+/*
+
+This file is provided for backwards compatibility purposes
+
+*/
+
+if (!defined('ADODB_SESSION')) {
+	require_once dirname(__FILE__) . '/adodb-session2.php';
+}
+
+require_once  ADODB_SESSION . '/adodb-encrypt-md5.php';
+
+ADODB_Session::filter(new ADODB_Encrypt_MD5());
+
+?>
Index: /Dev/trunk/rdfapi/util/adodb/session/adodb-encrypt-mcrypt.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/session/adodb-encrypt-mcrypt.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/session/adodb-encrypt-mcrypt.php	(revision 12)
@@ -0,0 +1,109 @@
+<?php
+
+
+/*
+V4.94 23 Jan 2007  (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
+         Contributed by Ross Smith (adodb@netebb.com). 
+  Released under both BSD license and Lesser GPL library license.
+  Whenever there is any discrepancy between the two licenses,
+  the BSD license will take precedence.
+	  Set tabs to 4 for best viewing.
+
+*/
+
+if (!function_exists('mcrypt_encrypt')) {
+	trigger_error('Mcrypt functions are not available', E_USER_ERROR);
+	return 0;
+}
+
+/**
+ */
+class ADODB_Encrypt_MCrypt {
+	/**
+	 */
+	var $_cipher;
+
+	/**
+	 */
+	var $_mode;
+
+	/**
+	 */
+	var $_source;
+
+	/**
+	 */
+	function getCipher() {
+		return $this->_cipher;
+	}
+
+	/**
+	 */
+	function setCipher($cipher) {
+		$this->_cipher = $cipher;
+	}
+
+	/**
+	 */
+	function getMode() {
+		return $this->_mode;
+	}
+
+	/**
+	 */
+	function setMode($mode) {
+		$this->_mode = $mode;
+	}
+
+	/**
+	 */
+	function getSource() {
+		return $this->_source;
+	}
+
+	/**
+	 */
+	function setSource($source) {
+		$this->_source = $source;
+	}
+
+	/**
+	 */
+	function ADODB_Encrypt_MCrypt($cipher = null, $mode = null, $source = null) {
+		if (!$cipher) {
+			$cipher = MCRYPT_RIJNDAEL_256;
+		}
+		if (!$mode) {
+			$mode = MCRYPT_MODE_ECB;
+		}
+		if (!$source) {
+			$source = MCRYPT_RAND;
+		}
+
+		$this->_cipher = $cipher;
+		$this->_mode = $mode;
+		$this->_source = $source;
+	}
+
+	/**
+	 */
+	function write($data, $key) {
+		$iv_size = mcrypt_get_iv_size($this->_cipher, $this->_mode);
+		$iv = mcrypt_create_iv($iv_size, $this->_source);
+		return mcrypt_encrypt($this->_cipher, $key, $data, $this->_mode, $iv);
+	}
+
+	/**
+	 */
+	function read($data, $key) {
+		$iv_size = mcrypt_get_iv_size($this->_cipher, $this->_mode);
+		$iv = mcrypt_create_iv($iv_size, $this->_source);
+		$rv = mcrypt_decrypt($this->_cipher, $key, $data, $this->_mode, $iv);
+		return rtrim($rv, "\0");
+	}
+
+}
+
+return 1;
+
+?>
Index: /Dev/trunk/rdfapi/util/adodb/session/adodb-encrypt-md5.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/session/adodb-encrypt-md5.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/session/adodb-encrypt-md5.php	(revision 12)
@@ -0,0 +1,39 @@
+<?php
+
+/*
+V4.94 23 Jan 2007  (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
+         Contributed by Ross Smith (adodb@netebb.com). 
+  Released under both BSD license and Lesser GPL library license.
+  Whenever there is any discrepancy between the two licenses,
+  the BSD license will take precedence.
+	  Set tabs to 4 for best viewing.
+
+*/
+
+// security - hide paths
+if (!defined('ADODB_SESSION')) die();
+
+include_once ADODB_SESSION . '/crypt.inc.php';
+
+/**
+ */
+class ADODB_Encrypt_MD5 {
+	/**
+	 */
+	function write($data, $key) {
+		$md5crypt =& new MD5Crypt();
+		return $md5crypt->encrypt($data, $key);
+	}
+
+	/**
+	 */
+	function read($data, $key) {
+		$md5crypt =& new MD5Crypt();
+		return $md5crypt->decrypt($data, $key);
+	}
+
+}
+
+return 1;
+
+?>
Index: /Dev/trunk/rdfapi/util/adodb/session/adodb-encrypt-secret.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/session/adodb-encrypt-secret.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/session/adodb-encrypt-secret.php	(revision 12)
@@ -0,0 +1,48 @@
+<?php
+
+/*
+V4.94 23 Jan 2007  (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
+         Contributed by Ross Smith (adodb@netebb.com). 
+  Released under both BSD license and Lesser GPL library license.
+  Whenever there is any discrepancy between the two licenses,
+  the BSD license will take precedence.
+	  Set tabs to 4 for best viewing.
+
+*/
+
+@define('HORDE_BASE', dirname(dirname(dirname(__FILE__))) . '/horde');
+
+if (!is_dir(HORDE_BASE)) {
+	trigger_error(sprintf('Directory not found: \'%s\'', HORDE_BASE), E_USER_ERROR);
+	return 0;
+}
+
+include_once HORDE_BASE . '/lib/Horde.php';
+include_once HORDE_BASE . '/lib/Secret.php';
+
+/**
+
+NOTE: On Windows 2000 SP4 with PHP 4.3.1, MCrypt 2.4.x, and Apache 1.3.28,
+the session didn't work properly.
+
+This may be resolved with 4.3.3.
+
+ */
+class ADODB_Encrypt_Secret {
+	/**
+	 */
+	function write($data, $key) {
+		return Secret::write($key, $data);
+	}
+
+	/**
+	 */
+	function read($data, $key) {
+		return Secret::read($key, $data);
+	}
+
+}
+
+return 1;
+
+?>
Index: /Dev/trunk/rdfapi/util/adodb/session/adodb-encrypt-sha1.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/session/adodb-encrypt-sha1.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/session/adodb-encrypt-sha1.php	(revision 12)
@@ -0,0 +1,32 @@
+<?php
+if (!defined('ADODB_SESSION')) die();
+
+include_once ADODB_SESSION . '/crypt.inc.php';
+
+
+/**
+
+ */
+
+class ADODB_Encrypt_SHA1 {
+
+	function write($data, $key) 
+	{
+		$sha1crypt =& new SHA1Crypt();
+		return $sha1crypt->encrypt($data, $key);
+
+	}
+
+
+	function read($data, $key) 
+	{
+		$sha1crypt =& new SHA1Crypt();
+		return $sha1crypt->decrypt($data, $key);
+
+	}
+}
+
+
+
+return 1;
+?>
Index: /Dev/trunk/rdfapi/util/adodb/session/adodb-sess.txt
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/session/adodb-sess.txt	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/session/adodb-sess.txt	(revision 12)
@@ -0,0 +1,131 @@
+John,
+
+I have been an extremely satisfied ADODB user for several years now.
+
+To give you something back for all your hard work, I've spent the last 3
+days rewriting the adodb-session.php code.
+
+----------
+What's New
+----------
+
+Here's a list of the new code's benefits:
+
+* Combines the functionality of the three files:
+
+adodb-session.php
+adodb-session-clob.php
+adodb-cryptsession.php
+
+each with very similar functionality, into a single file adodb-session.php.
+This will ease maintenance and support issues.
+
+* Supports multiple encryption and compression schemes.
+  Currently, we support:
+
+  MD5Crypt (crypt.inc.php)
+  MCrypt
+  Secure (Horde's emulation of MCrypt, if MCrypt module is not available.)
+  GZip
+  BZip2
+
+These can be stacked, so if you want to compress and then encrypt your
+session data, it's easy.
+Also, the built-in MCrypt functions will be *much* faster, and more secure,
+than the MD5Crypt code.
+
+* adodb-session.php contains a single class ADODB_Session that encapsulates
+all functionality.
+  This eliminates the use of global vars and defines (though they are
+supported for backwards compatibility).
+
+* All user defined parameters are now static functions in the ADODB_Session
+class.
+
+New parameters include:
+
+* encryptionKey(): Define the encryption key used to encrypt the session.
+Originally, it was a hard coded string.
+
+* persist(): Define if the database will be opened in persistent mode.
+Originally, the user had to call adodb_sess_open().
+
+* dataFieldName(): Define the field name used to store the session data, as
+'DATA' appears to be a reserved word in the following cases:
+	ANSI SQL
+	IBM DB2
+	MS SQL Server
+	Postgres
+	SAP
+
+* filter(): Used to support multiple, simulataneous encryption/compression
+schemes.
+
+* Debug support is improved thru _rsdump() function, which is called after
+every database call.
+
+------------
+What's Fixed
+------------
+
+The new code includes several bug fixes and enhancements:
+
+* sesskey is compared in BINARY mode for MySQL, to avoid problems with
+session keys that differ only by case.
+  Of course, the user should define the sesskey field as BINARY, to
+correctly fix this problem, otherwise performance will suffer.
+
+* In ADODB_Session::gc(), if $expire_notify is true, the multiple DELETES in
+the original code have been optimized to a single DELETE.
+
+* In ADODB_Session::destroy(), since "SELECT expireref, sesskey FROM $table
+WHERE sesskey = $qkey" will only return a single value, we don't loop on the
+result, we simply process the row, if any.
+
+* We close $rs after every use.
+
+---------------
+What's the Same
+---------------
+
+I know backwards compatibility is *very* important to you.  Therefore, the
+new code is 100% backwards compatible.
+
+If you like my code, but don't "trust" it's backwards compatible, maybe we
+offer it as beta code, in a new directory for a release or two?
+
+------------
+What's To Do
+------------
+
+I've vascillated over whether to use a single function to get/set
+parameters:
+
+$user = ADODB_Session::user(); 	// get
+ADODB_Session::user($user);		// set
+
+or to use separate functions (which is the PEAR/Java way):
+
+$user = ADODB_Session::getUser();
+ADODB_Session::setUser($user);
+
+I've chosen the former as it's makes for a simpler API, and reduces the
+amount of code, but I'd be happy to change it to the latter.
+
+Also, do you think the class should be a singleton class, versus a static
+class?
+
+Let me know if you find this code useful, and will be including it in the
+next release of ADODB.
+
+If so, I will modify the current documentation to detail the new
+functionality.  To that end, what file(s) contain the documentation?  Please
+send them to me if they are not publically available.
+
+Also, if there is *anything* in the code that you like to see changed, let
+me know.
+
+Thanks,
+
+Ross
+
Index: /Dev/trunk/rdfapi/util/adodb/session/adodb-session-clob.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/session/adodb-session-clob.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/session/adodb-session-clob.php	(revision 12)
@@ -0,0 +1,24 @@
+<?php
+
+
+/*
+V4.94 23 Jan 2007  (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
+         Contributed by Ross Smith (adodb@netebb.com). 
+  Released under both BSD license and Lesser GPL library license.
+  Whenever there is any discrepancy between the two licenses,
+  the BSD license will take precedence.
+	  Set tabs to 4 for best viewing.
+*/
+
+/*
+
+This file is provided for backwards compatibility purposes
+
+*/
+
+if (!defined('ADODB_SESSION')) {
+	require_once dirname(__FILE__) . '/adodb-session.php';
+}
+ADODB_Session::clob('CLOB');
+
+?>
Index: /Dev/trunk/rdfapi/util/adodb/session/adodb-session-clob2.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/session/adodb-session-clob2.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/session/adodb-session-clob2.php	(revision 12)
@@ -0,0 +1,24 @@
+<?php
+
+
+/*
+V4.94 23 Jan 2007  (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
+         Contributed by Ross Smith (adodb@netebb.com). 
+  Released under both BSD license and Lesser GPL library license.
+  Whenever there is any discrepancy between the two licenses,
+  the BSD license will take precedence.
+	  Set tabs to 4 for best viewing.
+*/
+
+/*
+
+This file is provided for backwards compatibility purposes
+
+*/
+
+if (!defined('ADODB_SESSION')) {
+	require_once dirname(__FILE__) . '/adodb-session2.php';
+}
+ADODB_Session::clob('CLOB');
+
+?>
Index: /Dev/trunk/rdfapi/util/adodb/session/adodb-session.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/session/adodb-session.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/session/adodb-session.php	(revision 12)
@@ -0,0 +1,934 @@
+<?php
+
+
+/*
+V4.94 23 Jan 2007  (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
+         Contributed by Ross Smith (adodb@netebb.com). 
+  Released under both BSD license and Lesser GPL library license.
+  Whenever there is any discrepancy between the two licenses,
+  the BSD license will take precedence.
+	  Set tabs to 4 for best viewing.
+*/
+
+/*
+	You may want to rename the 'data' field to 'session_data' as
+	'data' appears to be a reserved word for one or more of the following:
+		ANSI SQL
+		IBM DB2
+		MS SQL Server
+		Postgres
+		SAP
+
+	If you do, then execute:
+
+		ADODB_Session::dataFieldName('session_data');
+
+*/
+
+if (!defined('_ADODB_LAYER')) {
+	require realpath(dirname(__FILE__) . '/../adodb.inc.php');
+}
+
+if (defined('ADODB_SESSION')) return 1;
+
+define('ADODB_SESSION', dirname(__FILE__));
+
+
+/* 
+	Unserialize session data manually. See http://phplens.com/lens/lensforum/msgs.php?id=9821 
+	
+	From Kerr Schere, to unserialize session data stored via ADOdb. 
+	1. Pull the session data from the db and loop through it. 
+	2. Inside the loop, you will need to urldecode the data column. 
+	3. After urldecode, run the serialized string through this function:
+
+*/
+function adodb_unserialize( $serialized_string ) 
+{
+	$variables = array( );
+	$a = preg_split( "/(\w+)\|/", $serialized_string, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE );
+	for( $i = 0; $i < count( $a ); $i = $i+2 ) {
+		$variables[$a[$i]] = unserialize( $a[$i+1] );
+	}
+	return( $variables );
+}
+
+/*
+	Thanks Joe Li. See http://phplens.com/lens/lensforum/msgs.php?id=11487&x=1
+	Since adodb 4.61.
+*/
+function adodb_session_regenerate_id() 
+{
+	$conn =& ADODB_Session::_conn();
+	if (!$conn) return false;
+
+	$old_id = session_id();
+	if (function_exists('session_regenerate_id')) {
+		session_regenerate_id();
+	} else {
+		session_id(md5(uniqid(rand(), true)));
+		$ck = session_get_cookie_params();
+		setcookie(session_name(), session_id(), false, $ck['path'], $ck['domain'], $ck['secure']);
+		//@session_start();
+	}
+	$new_id = session_id();
+	$ok =& $conn->Execute('UPDATE '. ADODB_Session::table(). ' SET sesskey='. $conn->qstr($new_id). ' WHERE sesskey='.$conn->qstr($old_id));
+	
+	/* it is possible that the update statement fails due to a collision */
+	if (!$ok) {
+		session_id($old_id);
+		if (empty($ck)) $ck = session_get_cookie_params();
+		setcookie(session_name(), session_id(), false, $ck['path'], $ck['domain'], $ck['secure']);
+		return false;
+	}
+	
+	return true;
+}
+
+/*
+    Generate database table for session data
+    @see http://phplens.com/lens/lensforum/msgs.php?id=12280
+    @return 0 if failure, 1 if errors, 2 if successful.
+	@author Markus Staab http://www.public-4u.de
+*/
+function adodb_session_create_table($schemaFile=null,$conn = null)
+{
+    // set default values
+    if ($schemaFile===null) $schemaFile = ADODB_SESSION . '/session_schema.xml';
+    if ($conn===null) $conn =& ADODB_Session::_conn();
+
+	if (!$conn) return 0;
+
+    $schema = new adoSchema($conn);
+    $schema->ParseSchema($schemaFile);
+    return $schema->ExecuteSchema();
+}
+
+/*!
+	\static
+*/
+class ADODB_Session {
+	/////////////////////
+	// getter/setter methods
+	/////////////////////
+	
+	/*
+	
+	function Lock($lock=null)
+	{
+	static $_lock = false;
+	
+		if (!is_null($lock)) $_lock = $lock;
+		return $lock;
+	}
+	*/
+	/*!
+	*/
+	function driver($driver = null) {
+		static $_driver = 'mysql';
+		static $set = false;
+
+		if (!is_null($driver)) {
+			$_driver = trim($driver);
+			$set = true;
+		} elseif (!$set) {
+			// backwards compatibility
+			if (isset($GLOBALS['ADODB_SESSION_DRIVER'])) {
+				return $GLOBALS['ADODB_SESSION_DRIVER'];
+			}
+		}
+
+		return $_driver;
+	}
+
+	/*!
+	*/
+	function host($host = null) {
+		static $_host = 'localhost';
+		static $set = false;
+
+		if (!is_null($host)) {
+			$_host = trim($host);
+			$set = true;
+		} elseif (!$set) {
+			// backwards compatibility
+			if (isset($GLOBALS['ADODB_SESSION_CONNECT'])) {
+				return $GLOBALS['ADODB_SESSION_CONNECT'];
+			}
+		}
+
+		return $_host;
+	}
+
+	/*!
+	*/
+	function user($user = null) {
+		static $_user = 'root';
+		static $set = false;
+
+		if (!is_null($user)) {
+			$_user = trim($user);
+			$set = true;
+		} elseif (!$set) {
+			// backwards compatibility
+			if (isset($GLOBALS['ADODB_SESSION_USER'])) {
+				return $GLOBALS['ADODB_SESSION_USER'];
+			}
+		}
+
+		return $_user;
+	}
+
+	/*!
+	*/
+	function password($password = null) {
+		static $_password = '';
+		static $set = false;
+
+		if (!is_null($password)) {
+			$_password = $password;
+			$set = true;
+		} elseif (!$set) {
+			// backwards compatibility
+			if (isset($GLOBALS['ADODB_SESSION_PWD'])) {
+				return $GLOBALS['ADODB_SESSION_PWD'];
+			}
+		}
+
+		return $_password;
+	}
+
+	/*!
+	*/
+	function database($database = null) {
+		static $_database = 'xphplens_2';
+		static $set = false;
+
+		if (!is_null($database)) {
+			$_database = trim($database);
+			$set = true;
+		} elseif (!$set) {
+			// backwards compatibility
+			if (isset($GLOBALS['ADODB_SESSION_DB'])) {
+				return $GLOBALS['ADODB_SESSION_DB'];
+			}
+		}
+
+		return $_database;
+	}
+
+	/*!
+	*/
+	function persist($persist = null) 
+	{
+		static $_persist = true;
+
+		if (!is_null($persist)) {
+			$_persist = trim($persist);
+		}
+
+		return $_persist;
+	}
+
+	/*!
+	*/
+	function lifetime($lifetime = null) {
+		static $_lifetime;
+		static $set = false;
+
+		if (!is_null($lifetime)) {
+			$_lifetime = (int) $lifetime;
+			$set = true;
+		} elseif (!$set) {
+			// backwards compatibility
+			if (isset($GLOBALS['ADODB_SESS_LIFE'])) {
+				return $GLOBALS['ADODB_SESS_LIFE'];
+			}
+		}
+		if (!$_lifetime) {
+			$_lifetime = ini_get('session.gc_maxlifetime');
+			if ($_lifetime <= 1) {
+				// bug in PHP 4.0.3 pl 1  -- how about other versions?
+				//print "<h3>Session Error: PHP.INI setting <i>session.gc_maxlifetime</i>not set: $lifetime</h3>";
+				$_lifetime = 1440;
+			}
+		}
+
+		return $_lifetime;
+	}
+
+	/*!
+	*/
+	function debug($debug = null) {
+		static $_debug = false;
+		static $set = false;
+
+		if (!is_null($debug)) {
+			$_debug = (bool) $debug;
+
+			$conn = ADODB_Session::_conn();
+			if ($conn) {
+				$conn->debug = $_debug;
+			}
+			$set = true;
+		} elseif (!$set) {
+			// backwards compatibility
+			if (isset($GLOBALS['ADODB_SESS_DEBUG'])) {
+				return $GLOBALS['ADODB_SESS_DEBUG'];
+			}
+		}
+
+		return $_debug;
+	}
+
+	/*!
+	*/
+	function expireNotify($expire_notify = null) {
+		static $_expire_notify;
+		static $set = false;
+
+		if (!is_null($expire_notify)) {
+			$_expire_notify = $expire_notify;
+			$set = true;
+		} elseif (!$set) {
+			// backwards compatibility
+			if (isset($GLOBALS['ADODB_SESSION_EXPIRE_NOTIFY'])) {
+				return $GLOBALS['ADODB_SESSION_EXPIRE_NOTIFY'];
+			}
+		}
+
+		return $_expire_notify;
+	}
+
+	/*!
+	*/
+	function table($table = null) {
+		static $_table = 'sessions';
+		static $set = false;
+
+		if (!is_null($table)) {
+			$_table = trim($table);
+			$set = true;
+		} elseif (!$set) {
+			// backwards compatibility
+			if (isset($GLOBALS['ADODB_SESSION_TBL'])) {
+				return $GLOBALS['ADODB_SESSION_TBL'];
+			}
+		}
+
+		return $_table;
+	}
+
+	/*!
+	*/
+	function optimize($optimize = null) {
+		static $_optimize = false;
+		static $set = false;
+
+		if (!is_null($optimize)) {
+			$_optimize = (bool) $optimize;
+			$set = true;
+		} elseif (!$set) {
+			// backwards compatibility
+			if (defined('ADODB_SESSION_OPTIMIZE')) {
+				return true;
+			}
+		}
+
+		return $_optimize;
+	}
+
+	/*!
+	*/
+	function syncSeconds($sync_seconds = null) {
+		static $_sync_seconds = 60;
+		static $set = false;
+
+		if (!is_null($sync_seconds)) {
+			$_sync_seconds = (int) $sync_seconds;
+			$set = true;
+		} elseif (!$set) {
+			// backwards compatibility
+			if (defined('ADODB_SESSION_SYNCH_SECS')) {
+				return ADODB_SESSION_SYNCH_SECS;
+			}
+		}
+
+		return $_sync_seconds;
+	}
+
+	/*!
+	*/
+	function clob($clob = null) {
+		static $_clob = false;
+		static $set = false;
+
+		if (!is_null($clob)) {
+			$_clob = strtolower(trim($clob));
+			$set = true;
+		} elseif (!$set) {
+			// backwards compatibility
+			if (isset($GLOBALS['ADODB_SESSION_USE_LOBS'])) {
+				return $GLOBALS['ADODB_SESSION_USE_LOBS'];
+			}
+		}
+
+		return $_clob;
+	}
+
+	/*!
+	*/
+	function dataFieldName($data_field_name = null) {
+		static $_data_field_name = 'data';
+
+		if (!is_null($data_field_name)) {
+			$_data_field_name = trim($data_field_name);
+		}
+
+		return $_data_field_name;
+	}
+
+	/*!
+	*/
+	function filter($filter = null) {
+		static $_filter = array();
+
+		if (!is_null($filter)) {
+			if (!is_array($filter)) {
+				$filter = array($filter);
+			}
+			$_filter = $filter;
+		}
+
+		return $_filter;
+	}
+
+	/*!
+	*/
+	function encryptionKey($encryption_key = null) {
+		static $_encryption_key = 'CRYPTED ADODB SESSIONS ROCK!';
+
+		if (!is_null($encryption_key)) {
+			$_encryption_key = $encryption_key;
+		}
+
+		return $_encryption_key;
+	}
+
+	/////////////////////
+	// private methods
+	/////////////////////
+
+	/*!
+	*/
+	function &_conn($conn=null) {
+		return $GLOBALS['ADODB_SESS_CONN'];
+	}
+
+	/*!
+	*/
+	function _crc($crc = null) {
+		static $_crc = false;
+
+		if (!is_null($crc)) {
+			$_crc = $crc;
+		}
+
+		return $_crc;
+	}
+
+	/*!
+	*/
+	function _init() {
+		session_module_name('user');
+		session_set_save_handler(
+			array('ADODB_Session', 'open'),
+			array('ADODB_Session', 'close'),
+			array('ADODB_Session', 'read'),
+			array('ADODB_Session', 'write'),
+			array('ADODB_Session', 'destroy'),
+			array('ADODB_Session', 'gc')
+		);
+	}
+
+
+	/*!
+	*/
+	function _sessionKey() {
+		// use this function to create the encryption key for crypted sessions
+		// crypt the used key, ADODB_Session::encryptionKey() as key and session_id() as salt
+		return crypt(ADODB_Session::encryptionKey(), session_id());
+	}
+
+	/*!
+	*/
+	function _dumprs($rs) {
+		$conn	=& ADODB_Session::_conn();
+		$debug	= ADODB_Session::debug();
+
+		if (!$conn) {
+			return;
+		}
+
+		if (!$debug) {
+			return;
+		}
+
+		if (!$rs) {
+			echo "<br />\$rs is null or false<br />\n";
+			return;
+		}
+
+		//echo "<br />\nAffected_Rows=",$conn->Affected_Rows(),"<br />\n";
+
+		if (!is_object($rs)) {
+			return;
+		}
+
+		require_once ADODB_SESSION.'/../tohtml.inc.php';
+		rs2html($rs);
+	}
+
+	/////////////////////
+	// public methods
+	/////////////////////
+	
+	function config($driver, $host, $user, $password, $database=false,$options=false)
+	{
+		ADODB_Session::driver($driver);
+		ADODB_Session::host($host);
+		ADODB_Session::user($user);
+		ADODB_Session::password($password);
+		ADODB_Session::database($database);
+		
+		if ($driver == 'oci8' || $driver == 'oci8po') $options['lob'] = 'CLOB';
+		
+		if (isset($options['table'])) ADODB_Session::table($options['table']);
+		if (isset($options['lob'])) ADODB_Session::clob($options['lob']);
+		if (isset($options['debug'])) ADODB_Session::debug($options['debug']);
+	}
+
+	/*!
+		Create the connection to the database.
+
+		If $conn already exists, reuse that connection
+	*/
+	function open($save_path, $session_name, $persist = null) 
+	{
+		$conn =& ADODB_Session::_conn();
+
+		if ($conn) {
+			return true;
+		}
+
+		$database	= ADODB_Session::database();
+		$debug		= ADODB_Session::debug();
+		$driver		= ADODB_Session::driver();
+		$host		= ADODB_Session::host();
+		$password	= ADODB_Session::password();
+		$user		= ADODB_Session::user();
+
+		if (!is_null($persist)) {
+			ADODB_Session::persist($persist);
+		} else {
+			$persist = ADODB_Session::persist();
+		}
+
+# these can all be defaulted to in php.ini
+#		assert('$database');
+#		assert('$driver');
+#		assert('$host');
+
+		$conn =& ADONewConnection($driver);
+
+		if ($debug) {
+			$conn->debug = true;
+//			ADOConnection::outp( " driver=$driver user=$user pwd=$password db=$database ");
+		}
+
+		if ($persist) {
+			switch($persist) {
+			default:
+			case 'P': $ok = $conn->PConnect($host, $user, $password, $database); break;
+			case 'C': $ok = $conn->Connect($host, $user, $password, $database); break;
+			case 'N': $ok = $conn->NConnect($host, $user, $password, $database); break;
+			}
+		} else {
+			$ok = $conn->Connect($host, $user, $password, $database);
+		}
+
+		if ($ok) $GLOBALS['ADODB_SESS_CONN'] =& $conn;
+		else
+			ADOConnection::outp('<p>Session: connection failed</p>', false);
+		
+
+		return $ok;
+	}
+
+	/*!
+		Close the connection
+	*/
+	function close() 
+	{
+/*
+		$conn =& ADODB_Session::_conn();
+		if ($conn) $conn->Close();
+*/
+		return true;
+	}
+
+	/*
+		Slurp in the session variables and return the serialized string
+	*/
+	function read($key) 
+	{
+		$conn	=& ADODB_Session::_conn();
+		$data	= ADODB_Session::dataFieldName();
+		$filter	= ADODB_Session::filter();
+		$table	= ADODB_Session::table();
+
+		if (!$conn) {
+			return '';
+		}
+
+		//assert('$table');
+
+		$qkey = $conn->quote($key);
+		$binary = $conn->dataProvider === 'mysql' ? '/*! BINARY */' : '';
+	
+		$sql = "SELECT $data FROM $table WHERE sesskey = $binary $qkey AND expiry >= " . time();
+		/* Lock code does not work as it needs to hold transaction within whole page, and we don't know if 
+		  developer has commited elsewhere... :(
+		 */
+		#if (ADODB_Session::Lock())
+		#	$rs =& $conn->RowLock($table, "$binary sesskey = $qkey AND expiry >= " . time(), $data);
+		#else
+		
+			$rs =& $conn->Execute($sql);
+		//ADODB_Session::_dumprs($rs);
+		if ($rs) {
+			if ($rs->EOF) {
+				$v = '';
+			} else {
+				$v = reset($rs->fields);
+				$filter = array_reverse($filter);
+				foreach ($filter as $f) {
+					if (is_object($f)) {
+						$v = $f->read($v, ADODB_Session::_sessionKey());
+					}
+				}
+				$v = rawurldecode($v);
+			}
+
+			$rs->Close();
+
+			ADODB_Session::_crc(strlen($v) . crc32($v));
+			return $v;
+		}
+
+		return '';
+	}
+
+	/*!
+		Write the serialized data to a database.
+
+		If the data has not been modified since the last read(), we do not write.
+	*/
+	function write($key, $val) 
+	{
+	global $ADODB_SESSION_READONLY;
+	
+		if (!empty($ADODB_SESSION_READONLY)) return;
+		
+		$clob			= ADODB_Session::clob();
+		$conn			=& ADODB_Session::_conn();
+		$crc			= ADODB_Session::_crc();
+		$data			= ADODB_Session::dataFieldName();
+		$debug			= ADODB_Session::debug();
+		$driver			= ADODB_Session::driver();
+		$expire_notify	= ADODB_Session::expireNotify();
+		$filter			= ADODB_Session::filter();
+		$lifetime		= ADODB_Session::lifetime();
+		$table			= ADODB_Session::table();
+	
+		if (!$conn) {
+			return false;
+		}
+		$qkey = $conn->qstr($key);
+	
+		//assert('$table');
+
+		$expiry = time() + $lifetime;
+
+		$binary = $conn->dataProvider === 'mysql' ? '/*! BINARY */' : '';
+
+		// crc32 optimization since adodb 2.1
+		// now we only update expiry date, thx to sebastian thom in adodb 2.32
+		if ($crc !== false && $crc == (strlen($val) . crc32($val))) {
+			if ($debug) {
+				echo '<p>Session: Only updating date - crc32 not changed</p>';
+			}
+			
+			$expirevar = '';
+			if ($expire_notify) {
+				$var = reset($expire_notify);
+				global $$var;
+				if (isset($$var)) {
+					$expirevar = $$var;
+				}
+			}
+			
+			
+			$sql = "UPDATE $table SET expiry = ".$conn->Param('0').",expireref=".$conn->Param('1')." WHERE $binary sesskey = ".$conn->Param('2')." AND expiry >= ".$conn->Param('3');
+			$rs =& $conn->Execute($sql,array($expiry,$expirevar,$key,time()));
+			return true;
+		}
+		$val = rawurlencode($val);
+		foreach ($filter as $f) {
+			if (is_object($f)) {
+				$val = $f->write($val, ADODB_Session::_sessionKey());
+			}
+		}
+
+		$arr = array('sesskey' => $key, 'expiry' => $expiry, $data => $val, 'expireref' => '');
+		if ($expire_notify) {
+			$var = reset($expire_notify);
+			global $$var;
+			if (isset($$var)) {
+				$arr['expireref'] = $$var;
+			}
+		}
+
+		if (!$clob) {	// no lobs, simply use replace()
+			$arr[$data] = $conn->qstr($val);
+			$rs = $conn->Replace($table, $arr, 'sesskey', $autoQuote = true);
+			
+		} else {
+			// what value shall we insert/update for lob row?
+			switch ($driver) {
+				// empty_clob or empty_lob for oracle dbs
+				case 'oracle':
+				case 'oci8':
+				case 'oci8po':
+				case 'oci805':
+					$lob_value = sprintf('empty_%s()', strtolower($clob));
+					break;
+
+				// null for all other
+				default:
+					$lob_value = 'null';
+					break;
+			}
+			
+			$conn->StartTrans();
+			$expiryref = $conn->qstr($arr['expireref']);
+			// do we insert or update? => as for sesskey
+			$rs =& $conn->Execute("SELECT COUNT(*) AS cnt FROM $table WHERE $binary sesskey = $qkey");
+			if ($rs && reset($rs->fields) > 0) {
+				$sql = "UPDATE $table SET expiry = $expiry, $data = $lob_value, expireref=$expiryref WHERE  sesskey = $qkey";
+			} else {
+				$sql = "INSERT INTO $table (expiry, $data, sesskey,expireref) VALUES ($expiry, $lob_value, $qkey,$expiryref)";
+			}
+			if ($rs)$rs->Close();
+			
+
+			$err = '';
+			$rs1 =& $conn->Execute($sql);
+			if (!$rs1) $err = $conn->ErrorMsg()."\n";
+			
+			$rs2 =& $conn->UpdateBlob($table, $data, $val, " sesskey=$qkey", strtoupper($clob));
+			if (!$rs2) $err .= $conn->ErrorMsg()."\n";
+			
+			$rs = ($rs && $rs2) ? true : false;
+			$conn->CompleteTrans();
+		}
+
+		if (!$rs) {
+			ADOConnection::outp('<p>Session Replace: ' . $conn->ErrorMsg() . '</p>', false);
+			return false;
+		}  else {
+			// bug in access driver (could be odbc?) means that info is not committed
+			// properly unless select statement executed in Win2000
+			if ($conn->databaseType == 'access') {
+				$sql = "SELECT sesskey FROM $table WHERE $binary sesskey = $qkey";
+				$rs =& $conn->Execute($sql);
+				ADODB_Session::_dumprs($rs);
+				if ($rs) {
+					$rs->Close();
+				}
+			}
+		}/*
+		if (ADODB_Session::Lock()) {
+			$conn->CommitTrans();
+		}*/
+		return $rs ? true : false;
+	}
+
+	/*!
+	*/
+	function destroy($key) {
+		$conn			=& ADODB_Session::_conn();
+		$table			= ADODB_Session::table();
+		$expire_notify	= ADODB_Session::expireNotify();
+
+		if (!$conn) {
+			return false;
+		}
+
+		//assert('$table');
+
+		$qkey = $conn->quote($key);
+		$binary = $conn->dataProvider === 'mysql' ? '/*! BINARY */' : '';
+
+		if ($expire_notify) {
+			reset($expire_notify);
+			$fn = next($expire_notify);
+			$savem = $conn->SetFetchMode(ADODB_FETCH_NUM);
+			$sql = "SELECT expireref, sesskey FROM $table WHERE $binary sesskey = $qkey";
+			$rs =& $conn->Execute($sql);
+			ADODB_Session::_dumprs($rs);
+			$conn->SetFetchMode($savem);
+			if (!$rs) {
+				return false;
+			}
+			if (!$rs->EOF) {
+				$ref = $rs->fields[0];
+				$key = $rs->fields[1];
+				//assert('$ref');
+				//assert('$key');
+				$fn($ref, $key);
+			}
+			$rs->Close();
+		}
+
+		$sql = "DELETE FROM $table WHERE $binary sesskey = $qkey";
+		$rs =& $conn->Execute($sql);
+		ADODB_Session::_dumprs($rs);
+
+		return $rs ? true : false;
+	}
+
+	/*!
+	*/
+	function gc($maxlifetime) 
+	{
+		$conn			=& ADODB_Session::_conn();
+		$debug			= ADODB_Session::debug();
+		$expire_notify	= ADODB_Session::expireNotify();
+		$optimize		= ADODB_Session::optimize();
+		$sync_seconds	= ADODB_Session::syncSeconds();
+		$table			= ADODB_Session::table();
+
+		if (!$conn) {
+			return false;
+		}
+
+
+		$time			= time();
+		$binary = $conn->dataProvider === 'mysql' ? '/*! BINARY */' : '';
+
+		if ($expire_notify) {
+			reset($expire_notify);
+			$fn = next($expire_notify);
+			$savem = $conn->SetFetchMode(ADODB_FETCH_NUM);
+			$sql = "SELECT expireref, sesskey FROM $table WHERE expiry < $time";
+			$rs =& $conn->Execute($sql);
+			ADODB_Session::_dumprs($rs);
+			$conn->SetFetchMode($savem);
+			if ($rs) {
+				$conn->StartTrans();
+				$keys = array();
+				while (!$rs->EOF) {
+					$ref = $rs->fields[0];
+					$key = $rs->fields[1];
+					$fn($ref, $key);
+					$del = $conn->Execute("DELETE FROM $table WHERE sesskey=".$conn->Param('0'),array($key));
+					$rs->MoveNext();
+				}
+				$rs->Close();
+				
+				$conn->CompleteTrans();
+			}
+		} else {
+		
+			if (1) {
+				$sql = "SELECT sesskey FROM $table WHERE expiry < $time";
+				$arr =& $conn->GetAll($sql);
+				foreach ($arr as $row) {
+					$sql2 = "DELETE FROM $table WHERE sesskey=".$conn->Param('0');
+					$conn->Execute($sql2,array($row[0]));
+				}
+			} else {
+				$sql = "DELETE FROM $table WHERE expiry < $time";
+				$rs =& $conn->Execute($sql);
+				ADODB_Session::_dumprs($rs);
+				if ($rs) $rs->Close();
+			}
+			if ($debug) {
+				ADOConnection::outp("<p><b>Garbage Collection</b>: $sql</p>");
+			}
+		}
+
+		// suggested by Cameron, "GaM3R" <gamr@outworld.cx>
+		if ($optimize) {
+			$driver = ADODB_Session::driver();
+
+			if (preg_match('/mysql/i', $driver)) {
+				$sql = "OPTIMIZE TABLE $table";
+			}
+			if (preg_match('/postgres/i', $driver)) {
+				$sql = "VACUUM $table";
+			}
+			if (!empty($sql)) {
+				$conn->Execute($sql);
+			}
+		}
+
+		if ($sync_seconds) {
+			$sql = 'SELECT ';
+			if ($conn->dataProvider === 'oci8') {
+				$sql .= "TO_CHAR({$conn->sysTimeStamp}, 'RRRR-MM-DD HH24:MI:SS')";
+			} else {
+				$sql .= $conn->sysTimeStamp;
+			}
+			$sql .= " FROM $table";
+
+			$rs =& $conn->SelectLimit($sql, 1);
+			if ($rs && !$rs->EOF) {
+				$dbts = reset($rs->fields);
+				$rs->Close();
+				$dbt = $conn->UnixTimeStamp($dbts);
+				$t = time();
+
+				if (abs($dbt - $t) >= $sync_seconds) {
+					$msg = __FILE__ .
+						": Server time for webserver {$_SERVER['HTTP_HOST']} not in synch with database: " .
+						" database=$dbt ($dbts), webserver=$t (diff=". (abs($dbt - $t) / 60) . ' minutes)';
+					error_log($msg);
+					if ($debug) {
+						ADOConnection::outp("<p>$msg</p>");
+					}
+				}
+			}
+		}
+
+		return true;
+	}
+}
+
+ADODB_Session::_init();
+if (empty($ADODB_SESSION_READONLY))
+	register_shutdown_function('session_write_close');
+
+// for backwards compatability only
+function adodb_sess_open($save_path, $session_name, $persist = true) {
+	return ADODB_Session::open($save_path, $session_name, $persist);
+}
+
+// for backwards compatability only
+function adodb_sess_gc($t)
+{	
+	return ADODB_Session::gc($t);
+}
+
+?>
Index: /Dev/trunk/rdfapi/util/adodb/session/adodb-session2.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/session/adodb-session2.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/session/adodb-session2.php	(revision 12)
@@ -0,0 +1,941 @@
+<?php
+
+
+/*
+V4.94 23 Jan 2007  (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
+         Contributed by Ross Smith (adodb@netebb.com). 
+  Released under both BSD license and Lesser GPL library license.
+  Whenever there is any discrepancy between the two licenses,
+  the BSD license will take precedence.
+	  Set tabs to 4 for best viewing.
+	  
+
+*/
+
+/*
+
+CREATE Table SCripts
+
+Oracle
+======
+
+CREATE TABLE SESSIONS2
+(
+  SESSKEY    VARCHAR2(48 BYTE)                  NOT NULL,
+  EXPIRY     DATE                               NOT NULL,
+  EXPIREREF  VARCHAR2(200 BYTE),
+  CREATED    DATE                               NOT NULL,
+  MODIFIED   DATE                               NOT NULL,
+  SESSDATA   CLOB,
+  PRIMARY KEY(SESSKEY)
+);
+
+
+CREATE INDEX SESS2_EXPIRY ON SESSIONS2(EXPIRY);
+CREATE UNIQUE INDEX SESS2_PK ON SESSIONS2(SESSKEY);
+CREATE INDEX SESS2_EXP_REF ON SESSIONS2(EXPIREREF);
+
+
+ 
+ MySQL
+ =====
+ 
+CREATE TABLE sessions2(
+	sesskey VARCHAR( 64 ) NOT NULL DEFAULT '',
+	expiry TIMESTAMP NOT NULL ,
+	expireref VARCHAR( 250 ) DEFAULT '',
+	created TIMESTAMP NOT NULL ,
+	modified TIMESTAMP NOT NULL ,
+	sessdata LONGTEXT DEFAULT '',
+	PRIMARY KEY ( sesskey ) ,
+	INDEX sess2_expiry( expiry ),
+	INDEX sess2_expireref( expireref )
+)
+
+
+*/
+
+if (!defined('_ADODB_LAYER')) {
+	require realpath(dirname(__FILE__) . '/../adodb.inc.php');
+}
+
+if (defined('ADODB_SESSION')) return 1;
+
+define('ADODB_SESSION', dirname(__FILE__));
+define('ADODB_SESSION2', ADODB_SESSION);
+
+/* 
+	Unserialize session data manually. See http://phplens.com/lens/lensforum/msgs.php?id=9821 
+	
+	From Kerr Schere, to unserialize session data stored via ADOdb. 
+	1. Pull the session data from the db and loop through it. 
+	2. Inside the loop, you will need to urldecode the data column. 
+	3. After urldecode, run the serialized string through this function:
+
+*/
+function adodb_unserialize( $serialized_string ) 
+{
+	$variables = array( );
+	$a = preg_split( "/(\w+)\|/", $serialized_string, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE );
+	for( $i = 0; $i < count( $a ); $i = $i+2 ) {
+		$variables[$a[$i]] = unserialize( $a[$i+1] );
+	}
+	return( $variables );
+}
+
+/*
+	Thanks Joe Li. See http://phplens.com/lens/lensforum/msgs.php?id=11487&x=1
+	Since adodb 4.61.
+*/
+function adodb_session_regenerate_id() 
+{
+	$conn =& ADODB_Session::_conn();
+	if (!$conn) return false;
+
+	$old_id = session_id();
+	if (function_exists('session_regenerate_id')) {
+		session_regenerate_id();
+	} else {
+		session_id(md5(uniqid(rand(), true)));
+		$ck = session_get_cookie_params();
+		setcookie(session_name(), session_id(), false, $ck['path'], $ck['domain'], $ck['secure']);
+		//@session_start();
+	}
+	$new_id = session_id();
+	$ok =& $conn->Execute('UPDATE '. ADODB_Session::table(). ' SET sesskey='. $conn->qstr($new_id). ' WHERE sesskey='.$conn->qstr($old_id));
+	
+	/* it is possible that the update statement fails due to a collision */
+	if (!$ok) {
+		session_id($old_id);
+		if (empty($ck)) $ck = session_get_cookie_params();
+		setcookie(session_name(), session_id(), false, $ck['path'], $ck['domain'], $ck['secure']);
+		return false;
+	}
+	
+	return true;
+}
+
+/*
+    Generate database table for session data
+    @see http://phplens.com/lens/lensforum/msgs.php?id=12280
+    @return 0 if failure, 1 if errors, 2 if successful.
+	@author Markus Staab http://www.public-4u.de
+*/
+function adodb_session_create_table($schemaFile=null,$conn = null)
+{
+    // set default values
+    if ($schemaFile===null) $schemaFile = ADODB_SESSION . '/session_schema2.xml';
+    if ($conn===null) $conn =& ADODB_Session::_conn();
+
+	if (!$conn) return 0;
+
+    $schema = new adoSchema($conn);
+    $schema->ParseSchema($schemaFile);
+    return $schema->ExecuteSchema();
+}
+
+/*!
+	\static
+*/
+class ADODB_Session {
+	/////////////////////
+	// getter/setter methods
+	/////////////////////
+	
+	/*
+	
+	function Lock($lock=null)
+	{
+	static $_lock = false;
+	
+		if (!is_null($lock)) $_lock = $lock;
+		return $lock;
+	}
+	*/
+	/*!
+	*/
+	function driver($driver = null) 
+	{
+		static $_driver = 'mysql';
+		static $set = false;
+
+		if (!is_null($driver)) {
+			$_driver = trim($driver);
+			$set = true;
+		} elseif (!$set) {
+			// backwards compatibility
+			if (isset($GLOBALS['ADODB_SESSION_DRIVER'])) {
+				return $GLOBALS['ADODB_SESSION_DRIVER'];
+			}
+		}
+
+		return $_driver;
+	}
+
+	/*!
+	*/
+	function host($host = null) {
+		static $_host = 'localhost';
+		static $set = false;
+
+		if (!is_null($host)) {
+			$_host = trim($host);
+			$set = true;
+		} elseif (!$set) {
+			// backwards compatibility
+			if (isset($GLOBALS['ADODB_SESSION_CONNECT'])) {
+				return $GLOBALS['ADODB_SESSION_CONNECT'];
+			}
+		}
+
+		return $_host;
+	}
+
+	/*!
+	*/
+	function user($user = null) 
+	{
+		static $_user = 'root';
+		static $set = false;
+
+		if (!is_null($user)) {
+			$_user = trim($user);
+			$set = true;
+		} elseif (!$set) {
+			// backwards compatibility
+			if (isset($GLOBALS['ADODB_SESSION_USER'])) {
+				return $GLOBALS['ADODB_SESSION_USER'];
+			}
+		}
+
+		return $_user;
+	}
+
+	/*!
+	*/
+	function password($password = null) 
+	{
+		static $_password = '';
+		static $set = false;
+
+		if (!is_null($password)) {
+			$_password = $password;
+			$set = true;
+		} elseif (!$set) {
+			// backwards compatibility
+			if (isset($GLOBALS['ADODB_SESSION_PWD'])) {
+				return $GLOBALS['ADODB_SESSION_PWD'];
+			}
+		}
+
+		return $_password;
+	}
+
+	/*!
+	*/
+	function database($database = null) 
+	{
+		static $_database = '';
+		static $set = false;
+		
+		if (!is_null($database)) {
+			$_database = trim($database);
+			$set = true;
+		} elseif (!$set) {
+			// backwards compatibility
+			if (isset($GLOBALS['ADODB_SESSION_DB'])) {
+				return $GLOBALS['ADODB_SESSION_DB'];
+			}
+		}
+		return $_database;
+	}
+
+	/*!
+	*/
+	function persist($persist = null) 
+	{
+		static $_persist = true;
+
+		if (!is_null($persist)) {
+			$_persist = trim($persist);
+		}
+
+		return $_persist;
+	}
+
+	/*!
+	*/
+	function lifetime($lifetime = null) 
+	{
+		static $_lifetime;
+		static $set = false;
+
+		if (!is_null($lifetime)) {
+			$_lifetime = (int) $lifetime;
+			$set = true;
+		} elseif (!$set) {
+			// backwards compatibility
+			if (isset($GLOBALS['ADODB_SESS_LIFE'])) {
+				return $GLOBALS['ADODB_SESS_LIFE'];
+			}
+		}
+		if (!$_lifetime) {
+			$_lifetime = ini_get('session.gc_maxlifetime');
+			if ($_lifetime <= 1) {
+				// bug in PHP 4.0.3 pl 1  -- how about other versions?
+				//print "<h3>Session Error: PHP.INI setting <i>session.gc_maxlifetime</i>not set: $lifetime</h3>";
+				$_lifetime = 1440;
+			}
+		}
+
+		return $_lifetime;
+	}
+
+	/*!
+	*/
+	function debug($debug = null) 
+	{
+		static $_debug = false;
+		static $set = false;
+
+		if (!is_null($debug)) {
+			$_debug = (bool) $debug;
+
+			$conn = ADODB_Session::_conn();
+			if ($conn) {
+				$conn->debug = $_debug;
+			}
+			$set = true;
+		} elseif (!$set) {
+			// backwards compatibility
+			if (isset($GLOBALS['ADODB_SESS_DEBUG'])) {
+				return $GLOBALS['ADODB_SESS_DEBUG'];
+			}
+		}
+
+		return $_debug;
+	}
+
+	/*!
+	*/
+	function expireNotify($expire_notify = null) 
+	{
+		static $_expire_notify;
+		static $set = false;
+
+		if (!is_null($expire_notify)) {
+			$_expire_notify = $expire_notify;
+			$set = true;
+		} elseif (!$set) {
+			// backwards compatibility
+			if (isset($GLOBALS['ADODB_SESSION_EXPIRE_NOTIFY'])) {
+				return $GLOBALS['ADODB_SESSION_EXPIRE_NOTIFY'];
+			}
+		}
+
+		return $_expire_notify;
+	}
+
+	/*!
+	*/
+	function table($table = null) 
+	{
+		static $_table = 'sessions2';
+		static $set = false;
+
+		if (!is_null($table)) {
+			$_table = trim($table);
+			$set = true;
+		} elseif (!$set) {
+			// backwards compatibility
+			if (isset($GLOBALS['ADODB_SESSION_TBL'])) {
+				return $GLOBALS['ADODB_SESSION_TBL'];
+			}
+		}
+
+		return $_table;
+	}
+
+	/*!
+	*/
+	function optimize($optimize = null) 
+	{
+		static $_optimize = false;
+		static $set = false;
+
+		if (!is_null($optimize)) {
+			$_optimize = (bool) $optimize;
+			$set = true;
+		} elseif (!$set) {
+			// backwards compatibility
+			if (defined('ADODB_SESSION_OPTIMIZE')) {
+				return true;
+			}
+		}
+
+		return $_optimize;
+	}
+
+	/*!
+	*/
+	function syncSeconds($sync_seconds = null) {
+		//echo ("<p>WARNING: ADODB_SESSION::syncSeconds is longer used, please remove this function for your code</p>");
+		
+		return 0;
+	}
+
+	/*!
+	*/
+	function clob($clob = null) {
+		static $_clob = false;
+		static $set = false;
+
+		if (!is_null($clob)) {
+			$_clob = strtolower(trim($clob));
+			$set = true;
+		} elseif (!$set) {
+			// backwards compatibility
+			if (isset($GLOBALS['ADODB_SESSION_USE_LOBS'])) {
+				return $GLOBALS['ADODB_SESSION_USE_LOBS'];
+			}
+		}
+
+		return $_clob;
+	}
+
+	/*!
+	*/
+	function dataFieldName($data_field_name = null) {
+		//echo ("<p>WARNING: ADODB_SESSION::dataFieldName() is longer used, please remove this function for your code</p>");
+		return '';
+	}
+
+	/*!
+	*/
+	function filter($filter = null) {
+		static $_filter = array();
+
+		if (!is_null($filter)) {
+			if (!is_array($filter)) {
+				$filter = array($filter);
+			}
+			$_filter = $filter;
+		}
+
+		return $_filter;
+	}
+
+	/*!
+	*/
+	function encryptionKey($encryption_key = null) {
+		static $_encryption_key = 'CRYPTED ADODB SESSIONS ROCK!';
+
+		if (!is_null($encryption_key)) {
+			$_encryption_key = $encryption_key;
+		}
+
+		return $_encryption_key;
+	}
+
+	/////////////////////
+	// private methods
+	/////////////////////
+
+	/*!
+	*/
+	function &_conn($conn=null) {
+		return $GLOBALS['ADODB_SESS_CONN'];
+	}
+
+	/*!
+	*/
+	function _crc($crc = null) {
+		static $_crc = false;
+
+		if (!is_null($crc)) {
+			$_crc = $crc;
+		}
+
+		return $_crc;
+	}
+
+	/*!
+	*/
+	function _init() {
+		session_module_name('user');
+		session_set_save_handler(
+			array('ADODB_Session', 'open'),
+			array('ADODB_Session', 'close'),
+			array('ADODB_Session', 'read'),
+			array('ADODB_Session', 'write'),
+			array('ADODB_Session', 'destroy'),
+			array('ADODB_Session', 'gc')
+		);
+	}
+
+
+	/*!
+	*/
+	function _sessionKey() {
+		// use this function to create the encryption key for crypted sessions
+		// crypt the used key, ADODB_Session::encryptionKey() as key and session_id() as salt
+		return crypt(ADODB_Session::encryptionKey(), session_id());
+	}
+
+	/*!
+	*/
+	function _dumprs($rs) {
+		$conn	=& ADODB_Session::_conn();
+		$debug	= ADODB_Session::debug();
+
+		if (!$conn) {
+			return;
+		}
+
+		if (!$debug) {
+			return;
+		}
+
+		if (!$rs) {
+			echo "<br />\$rs is null or false<br />\n";
+			return;
+		}
+
+		//echo "<br />\nAffected_Rows=",$conn->Affected_Rows(),"<br />\n";
+
+		if (!is_object($rs)) {
+			return;
+		}
+
+		require_once ADODB_SESSION.'/../tohtml.inc.php';
+		rs2html($rs);
+	}
+
+	/////////////////////
+	// public methods
+	/////////////////////
+	
+	function config($driver, $host, $user, $password, $database=false,$options=false)
+	{
+		ADODB_Session::driver($driver);
+		ADODB_Session::host($host);
+		ADODB_Session::user($user);
+		ADODB_Session::password($password);
+		ADODB_Session::database($database);
+		
+		if ($driver == 'oci8' || $driver == 'oci8po') $options['lob'] = 'CLOB';
+		
+		if (isset($options['table'])) ADODB_Session::table($options['table']);
+		if (isset($options['lob'])) ADODB_Session::clob($options['lob']);
+		if (isset($options['debug'])) ADODB_Session::debug($options['debug']);
+	}
+
+	/*!
+		Create the connection to the database.
+
+		If $conn already exists, reuse that connection
+	*/
+	function open($save_path, $session_name, $persist = null) 
+	{
+		$conn =& ADODB_Session::_conn();
+
+		if ($conn) {
+			return true;
+		}
+
+		$database	= ADODB_Session::database();
+		$debug		= ADODB_Session::debug();
+		$driver		= ADODB_Session::driver();
+		$host		= ADODB_Session::host();
+		$password	= ADODB_Session::password();
+		$user		= ADODB_Session::user();
+
+		if (!is_null($persist)) {
+			ADODB_Session::persist($persist);
+		} else {
+			$persist = ADODB_Session::persist();
+		}
+
+# these can all be defaulted to in php.ini
+#		assert('$database');
+#		assert('$driver');
+#		assert('$host');
+
+		$conn =& ADONewConnection($driver);
+
+		if ($debug) {
+			$conn->debug = true;		
+			ADOConnection::outp( " driver=$driver user=$user db=$database ");
+		}
+		
+		if ($persist) {
+			switch($persist) {
+			default:
+			case 'P': $ok = $conn->PConnect($host, $user, $password, $database); break;
+			case 'C': $ok = $conn->Connect($host, $user, $password, $database); break;
+			case 'N': $ok = $conn->NConnect($host, $user, $password, $database); break;
+			}
+		} else {
+			$ok = $conn->Connect($host, $user, $password, $database);
+		}
+
+		if ($ok) $GLOBALS['ADODB_SESS_CONN'] =& $conn;
+		else
+			ADOConnection::outp('<p>Session: connection failed</p>', false);
+		
+
+		return $ok;
+	}
+
+	/*!
+		Close the connection
+	*/
+	function close() 
+	{
+/*
+		$conn =& ADODB_Session::_conn();
+		if ($conn) $conn->Close();
+*/
+		return true;
+	}
+
+	/*
+		Slurp in the session variables and return the serialized string
+	*/
+	function read($key) 
+	{
+		$conn	=& ADODB_Session::_conn();
+		$filter	= ADODB_Session::filter();
+		$table	= ADODB_Session::table();
+
+		if (!$conn) {
+			return '';
+		}
+
+		//assert('$table');
+
+		$qkey = $conn->quote($key);
+		$binary = $conn->dataProvider === 'mysql' ? '/*! BINARY */' : '';
+	
+		$sql = "SELECT sessdata FROM $table WHERE sesskey = $binary $qkey AND expiry >= " . $conn->sysTimeStamp;
+		/* Lock code does not work as it needs to hold transaction within whole page, and we don't know if 
+		  developer has commited elsewhere... :(
+		 */
+		#if (ADODB_Session::Lock())
+		#	$rs =& $conn->RowLock($table, "$binary sesskey = $qkey AND expiry >= " . time(), sessdata);
+		#else
+		
+			$rs =& $conn->Execute($sql);
+		//ADODB_Session::_dumprs($rs);
+		if ($rs) {
+			if ($rs->EOF) {
+				$v = '';
+			} else {
+				$v = reset($rs->fields);
+				$filter = array_reverse($filter);
+				foreach ($filter as $f) {
+					if (is_object($f)) {
+						$v = $f->read($v, ADODB_Session::_sessionKey());
+					}
+				}
+				$v = rawurldecode($v);
+			}
+
+			$rs->Close();
+
+			ADODB_Session::_crc(strlen($v) . crc32($v));
+			return $v;
+		}
+
+		return '';
+	}
+
+	/*!
+		Write the serialized data to a database.
+
+		If the data has not been modified since the last read(), we do not write.
+	*/
+	function write($key, $val) 
+	{
+	global $ADODB_SESSION_READONLY;
+	
+		if (!empty($ADODB_SESSION_READONLY)) return;
+		
+		$clob			= ADODB_Session::clob();
+		$conn			=& ADODB_Session::_conn();
+		$crc			= ADODB_Session::_crc();
+		$debug			= ADODB_Session::debug();
+		$driver			= ADODB_Session::driver();
+		$expire_notify	= ADODB_Session::expireNotify();
+		$filter			= ADODB_Session::filter();
+		$lifetime		= ADODB_Session::lifetime();
+		$table			= ADODB_Session::table();
+	
+		if (!$conn) {
+			return false;
+		}
+	
+		$sysTimeStamp = $conn->sysTimeStamp;
+		
+		//assert('$table');
+
+		$expiry = $conn->OffsetDate($lifetime/(24*3600),$sysTimeStamp);
+
+		$binary = $conn->dataProvider === 'mysql' ? '/*! BINARY */' : '';
+
+		// crc32 optimization since adodb 2.1
+		// now we only update expiry date, thx to sebastian thom in adodb 2.32
+		if ($crc !== false && $crc == (strlen($val) . crc32($val))) {
+			if ($debug) {
+				echo '<p>Session: Only updating date - crc32 not changed</p>';
+			}
+			
+			$expirevar = '';
+			if ($expire_notify) {
+				$var = reset($expire_notify);
+				global $$var;
+				if (isset($$var)) {
+					$expirevar = $$var;
+				}
+			}
+			
+			
+			$sql = "UPDATE $table SET expiry = $expiry ,expireref=".$conn->Param('0').", modified = $sysTimeStamp WHERE $binary sesskey = ".$conn->Param('1')." AND expiry >= $sysTimeStamp";
+			$rs =& $conn->Execute($sql,array($expirevar,$key));
+			return true;
+		}
+		$val = rawurlencode($val);
+		foreach ($filter as $f) {
+			if (is_object($f)) {
+				$val = $f->write($val, ADODB_Session::_sessionKey());
+			}
+		}
+
+		$expireref = '';
+		if ($expire_notify) {
+			$var = reset($expire_notify);
+			global $$var;
+			if (isset($$var)) {
+				$expireref = $$var;
+			}
+		} 
+
+		if (!$clob) {	// no lobs, simply use replace()
+			$rs =& $conn->Execute("SELECT COUNT(*) AS cnt FROM $table WHERE $binary sesskey = ".$conn->Param(0),array($key));
+			if ($rs) $rs->Close();
+					
+			if ($rs && reset($rs->fields) > 0) {
+				$sql = "UPDATE $table SET expiry=$expiry, sessdata=".$conn->Param(0).", expireref= ".$conn->Param(1).",modified=$sysTimeStamp WHERE sesskey = ".$conn->Param('2');
+				
+			} else {
+				$sql = "INSERT INTO $table (expiry, sessdata, expireref, sesskey, created, modified) 
+					VALUES ($expiry,".$conn->Param('0').", ". $conn->Param('1').", ".$conn->Param('2').", $sysTimeStamp, $sysTimeStamp)";
+			}
+			
+	
+			$rs =& $conn->Execute($sql,array($val,$expireref,$key));
+			
+		} else {
+			// what value shall we insert/update for lob row?
+			switch ($driver) {
+				// empty_clob or empty_lob for oracle dbs
+				case 'oracle':
+				case 'oci8':
+				case 'oci8po':
+				case 'oci805':
+					$lob_value = sprintf('empty_%s()', strtolower($clob));
+					break;
+
+				// null for all other
+				default:
+					$lob_value = 'null';
+					break;
+			}
+			
+			$conn->StartTrans();
+			
+			$rs =& $conn->Execute("SELECT COUNT(*) AS cnt FROM $table WHERE $binary sesskey = ".$conn->Param(0),array($key));
+			if ($rs) $rs->Close();
+					
+			if ($rs && reset($rs->fields) > 0) {
+				$sql = "UPDATE $table SET expiry=$expiry, sessdata=$lob_value, expireref= ".$conn->Param(0).",modified=$sysTimeStamp WHERE sesskey = ".$conn->Param('1');
+				
+			} else {
+				$sql = "INSERT INTO $table (expiry, sessdata, expireref, sesskey, created, modified) 
+					VALUES ($expiry,$lob_value, ". $conn->Param('0').", ".$conn->Param('1').", $sysTimeStamp, $sysTimeStamp)";
+			}
+			
+			$rs =& $conn->Execute($sql,array($expireref,$key));
+			
+			$qkey = $conn->qstr($key);
+			$rs2 =& $conn->UpdateBlob($table, 'sessdata', $val, " sesskey=$qkey", strtoupper($clob));
+			$rs = @$conn->CompleteTrans();
+			
+			
+		}
+
+		if (!$rs) {
+			ADOConnection::outp('<p>Session Replace: ' . $conn->ErrorMsg() . '</p>', false);
+			return false;
+		}  else {
+			// bug in access driver (could be odbc?) means that info is not committed
+			// properly unless select statement executed in Win2000
+			if ($conn->databaseType == 'access') {
+				$sql = "SELECT sesskey FROM $table WHERE $binary sesskey = $qkey";
+				$rs =& $conn->Execute($sql);
+				ADODB_Session::_dumprs($rs);
+				if ($rs) {
+					$rs->Close();
+				}
+			}
+		}/*
+		if (ADODB_Session::Lock()) {
+			$conn->CommitTrans();
+		}*/
+		return $rs ? true : false;
+	}
+
+	/*!
+	*/
+	function destroy($key) {
+		$conn			=& ADODB_Session::_conn();
+		$table			= ADODB_Session::table();
+		$expire_notify	= ADODB_Session::expireNotify();
+
+		if (!$conn) {
+			return false;
+		}
+
+		//assert('$table');
+
+		$qkey = $conn->quote($key);
+		$binary = $conn->dataProvider === 'mysql' ? '/*! BINARY */' : '';
+
+		if ($expire_notify) {
+			reset($expire_notify);
+			$fn = next($expire_notify);
+			$savem = $conn->SetFetchMode(ADODB_FETCH_NUM);
+			$sql = "SELECT expireref, sesskey FROM $table WHERE $binary sesskey = $qkey";
+			$rs =& $conn->Execute($sql);
+			ADODB_Session::_dumprs($rs);
+			$conn->SetFetchMode($savem);
+			if (!$rs) {
+				return false;
+			}
+			if (!$rs->EOF) {
+				$ref = $rs->fields[0];
+				$key = $rs->fields[1];
+				//assert('$ref');
+				//assert('$key');
+				$fn($ref, $key);
+			}
+			$rs->Close();
+		}
+
+		$sql = "DELETE FROM $table WHERE $binary sesskey = $qkey";
+		$rs =& $conn->Execute($sql);
+		ADODB_Session::_dumprs($rs);
+		if ($rs) {
+			$rs->Close();
+		}
+
+		return $rs ? true : false;
+	}
+
+	/*!
+	*/
+	function gc($maxlifetime) 
+	{
+		$conn			=& ADODB_Session::_conn();
+		$debug			= ADODB_Session::debug();
+		$expire_notify	= ADODB_Session::expireNotify();
+		$optimize		= ADODB_Session::optimize();
+		$table			= ADODB_Session::table();
+
+		if (!$conn) {
+			return false;
+		}
+
+		//assert('$table');
+
+		$time = $conn->sysTimeStamp;
+		$binary = $conn->dataProvider === 'mysql' ? '/*! BINARY */' : '';
+
+		if ($expire_notify) {
+			reset($expire_notify);
+			$fn = next($expire_notify);
+			$savem = $conn->SetFetchMode(ADODB_FETCH_NUM);
+			$sql = "SELECT expireref, sesskey FROM $table WHERE expiry < $time";
+			$rs =& $conn->Execute($sql);
+			ADODB_Session::_dumprs($rs);
+			$conn->SetFetchMode($savem);
+			if ($rs) {
+				$conn->StartTrans();
+				$keys = array();
+				while (!$rs->EOF) {
+					$ref = $rs->fields[0];
+					$key = $rs->fields[1];
+					$fn($ref, $key);
+					$del = $conn->Execute("DELETE FROM $table WHERE sesskey=".$conn->Param('0'),array($key));
+					$rs->MoveNext();
+				}
+				$rs->Close();
+				
+				$conn->CompleteTrans();
+			}
+		} else {
+		
+			if (0) {
+				$sql = "SELECT sesskey FROM $table WHERE expiry < $time";
+				$arr =& $conn->GetAll($sql);
+				foreach ($arr as $row) {
+					$sql2 = "DELETE FROM $table WHERE sesskey=".$conn->Param('0');
+					$conn->Execute($sql2,array($row[0]));
+				}
+			} else {
+				$sql = "DELETE FROM $table WHERE expiry < $time";
+				$rs =& $conn->Execute($sql);
+				ADODB_Session::_dumprs($rs);
+				if ($rs) $rs->Close();
+			}
+			if ($debug) {
+				ADOConnection::outp("<p><b>Garbage Collection</b>: $sql</p>");
+			}
+		}
+
+		// suggested by Cameron, "GaM3R" <gamr@outworld.cx>
+		if ($optimize) {
+			$driver = ADODB_Session::driver();
+
+			if (preg_match('/mysql/i', $driver)) {
+				$sql = "OPTIMIZE TABLE $table";
+			}
+			if (preg_match('/postgres/i', $driver)) {
+				$sql = "VACUUM $table";
+			}
+			if (!empty($sql)) {
+				$conn->Execute($sql);
+			}
+		}
+
+		
+		return true;
+	}
+}
+
+ADODB_Session::_init();
+if (empty($ADODB_SESSION_READONLY))
+	register_shutdown_function('session_write_close');
+
+// for backwards compatability only
+function adodb_sess_open($save_path, $session_name, $persist = true) {
+	return ADODB_Session::open($save_path, $session_name, $persist);
+}
+
+// for backwards compatability only
+function adodb_sess_gc($t)
+{	
+	return ADODB_Session::gc($t);
+}
+
+?>
Index: /Dev/trunk/rdfapi/util/adodb/session/adodb-sessions.mysql.sql
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/session/adodb-sessions.mysql.sql	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/session/adodb-sessions.mysql.sql	(revision 12)
@@ -0,0 +1,16 @@
+-- $CVSHeader$
+
+CREATE DATABASE /*! IF NOT EXISTS */ adodb_sessions;
+
+USE adodb_sessions;
+
+DROP TABLE /*! IF EXISTS */ sessions;
+
+CREATE TABLE /*! IF NOT EXISTS */ sessions (
+	sesskey		CHAR(32)	/*! BINARY */ NOT NULL DEFAULT '',
+	expiry		INT(11)		/*! UNSIGNED */ NOT NULL DEFAULT 0,
+	expireref	VARCHAR(64)	DEFAULT '',
+	data		LONGTEXT	DEFAULT '',
+	PRIMARY KEY	(sesskey),
+	INDEX expiry (expiry)
+);
Index: /Dev/trunk/rdfapi/util/adodb/session/adodb-sessions.oracle.clob.sql
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/session/adodb-sessions.oracle.clob.sql	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/session/adodb-sessions.oracle.clob.sql	(revision 12)
@@ -0,0 +1,15 @@
+-- $CVSHeader$
+
+DROP TABLE adodb_sessions;
+
+CREATE TABLE sessions (
+	sesskey		CHAR(32)	DEFAULT '' NOT NULL,
+	expiry		INT		DEFAULT 0 NOT NULL,
+	expireref	VARCHAR(64)	DEFAULT '',
+	data		CLOB		DEFAULT '',
+	PRIMARY KEY	(sesskey)
+);
+
+CREATE INDEX ix_expiry ON sessions (expiry);
+
+QUIT;
Index: /Dev/trunk/rdfapi/util/adodb/session/adodb-sessions.oracle.sql
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/session/adodb-sessions.oracle.sql	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/session/adodb-sessions.oracle.sql	(revision 12)
@@ -0,0 +1,16 @@
+-- $CVSHeader$
+
+DROP TABLE adodb_sessions;
+
+CREATE TABLE sessions (
+	sesskey		CHAR(32)	DEFAULT '' NOT NULL,
+	expiry		INT		DEFAULT 0 NOT NULL,
+	expireref	VARCHAR(64)	DEFAULT '',
+	data		VARCHAR(4000)	DEFAULT '',
+	PRIMARY KEY	(sesskey),
+	INDEX expiry (expiry)
+);
+
+CREATE INDEX ix_expiry ON sessions (expiry);
+
+QUIT;
Index: /Dev/trunk/rdfapi/util/adodb/session/crypt.inc.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/session/crypt.inc.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/session/crypt.inc.php	(revision 12)
@@ -0,0 +1,161 @@
+<?php
+//	 Session Encryption by Ari Kuorikoski <ari.kuorikoski@finebyte.com>
+class MD5Crypt{
+		function keyED($txt,$encrypt_key)
+		{
+				$encrypt_key = md5($encrypt_key);
+				$ctr=0;
+				$tmp = "";
+				for ($i=0;$i<strlen($txt);$i++){
+						if ($ctr==strlen($encrypt_key)) $ctr=0;
+						$tmp.= substr($txt,$i,1) ^ substr($encrypt_key,$ctr,1);
+						$ctr++;
+				}
+				return $tmp;
+		}
+
+		function Encrypt($txt,$key)
+		{
+				srand((double)microtime()*1000000);
+				$encrypt_key = md5(rand(0,32000));
+				$ctr=0;
+				$tmp = "";
+				for ($i=0;$i<strlen($txt);$i++)
+				{
+				if ($ctr==strlen($encrypt_key)) $ctr=0;
+				$tmp.= substr($encrypt_key,$ctr,1) .
+				(substr($txt,$i,1) ^ substr($encrypt_key,$ctr,1));
+				$ctr++;
+				}
+				return base64_encode($this->keyED($tmp,$key));
+		}
+
+		function Decrypt($txt,$key)
+		{
+				$txt = $this->keyED(base64_decode($txt),$key);
+				$tmp = "";
+				for ($i=0;$i<strlen($txt);$i++){
+						$md5 = substr($txt,$i,1);
+						$i++;
+						$tmp.= (substr($txt,$i,1) ^ $md5);
+				}
+				return $tmp;
+		}
+
+		function RandPass()
+		{
+				$randomPassword = "";
+				srand((double)microtime()*1000000);
+				for($i=0;$i<8;$i++)
+				{
+						$randnumber = rand(48,120);
+
+						while (($randnumber >= 58 && $randnumber <= 64) || ($randnumber >= 91 && $randnumber <= 96))
+						{
+								$randnumber = rand(48,120);
+						}
+
+						$randomPassword .= chr($randnumber);
+				}
+				return $randomPassword;
+		}
+
+}
+
+
+class SHA1Crypt{
+
+		function keyED($txt,$encrypt_key)
+		{
+
+				$encrypt_key = sha1($encrypt_key);
+				$ctr=0;
+				$tmp = "";
+
+				for ($i=0;$i<strlen($txt);$i++){
+						if ($ctr==strlen($encrypt_key)) $ctr=0;
+						$tmp.= substr($txt,$i,1) ^ substr($encrypt_key,$ctr,1);
+						$ctr++;
+				}
+				return $tmp;
+
+		}
+
+
+
+		function Encrypt($txt,$key)
+		{
+
+				srand((double)microtime()*1000000);
+				$encrypt_key = sha1(rand(0,32000));
+				$ctr=0;
+				$tmp = "";
+
+				for ($i=0;$i<strlen($txt);$i++)
+
+				{
+
+				if ($ctr==strlen($encrypt_key)) $ctr=0;
+
+				$tmp.= substr($encrypt_key,$ctr,1) .
+
+				(substr($txt,$i,1) ^ substr($encrypt_key,$ctr,1));
+
+				$ctr++;
+
+				}
+
+				return base64_encode($this->keyED($tmp,$key));
+
+		}
+
+
+
+		function Decrypt($txt,$key)
+		{
+
+				$txt = $this->keyED(base64_decode($txt),$key);
+
+				$tmp = "";
+
+				for ($i=0;$i<strlen($txt);$i++){
+
+						$sha1 = substr($txt,$i,1);
+
+						$i++;
+
+						$tmp.= (substr($txt,$i,1) ^ $sha1);
+
+				}
+
+				return $tmp;
+		}
+
+
+
+		function RandPass()
+		{
+				$randomPassword = "";
+				srand((double)microtime()*1000000);
+
+				for($i=0;$i<8;$i++)
+				{
+
+						$randnumber = rand(48,120);
+
+						while (($randnumber >= 58 && $randnumber <= 64) || ($randnumber >= 91 && $randnumber <= 96))
+						{
+								$randnumber = rand(48,120);
+						}
+
+						$randomPassword .= chr($randnumber);
+				}
+
+				return $randomPassword;
+
+		}
+
+
+
+}
+?>
Index: /Dev/trunk/rdfapi/util/adodb/session/old/adodb-cryptsession.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/session/old/adodb-cryptsession.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/session/old/adodb-cryptsession.php	(revision 12)
@@ -0,0 +1,324 @@
+<?php
+/*
+V4.94 23 Jan 2007  (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence.
+	Made table name configurable - by David Johnson djohnson@inpro.net
+	Encryption by Ari Kuorikoski <ari.kuorikoski@finebyte.com>
+	
+  Set tabs to 4 for best viewing.
+  
+  Latest version of ADODB is available at http://php.weblogs.com/adodb
+  ======================================================================
+  
+ This file provides PHP4 session management using the ADODB database
+wrapper library.
+ 
+ Example
+ =======
+ 
+	include('adodb.inc.php');
+	#---------------------------------#
+	include('adodb-cryptsession.php'); 
+	#---------------------------------#
+	session_start();
+	session_register('AVAR');
+	$_SESSION['AVAR'] += 1;
+	print "
+-- \$_SESSION['AVAR']={$_SESSION['AVAR']}</p>";
+
+ 
+ Installation
+ ============
+ 1. Create a new database in MySQL or Access "sessions" like
+so:
+ 
+  create table sessions (
+	   SESSKEY char(32) not null,
+	   EXPIRY int(11) unsigned not null,
+	   EXPIREREF varchar(64),
+	   DATA CLOB,
+	  primary key (sesskey)
+  );
+  
+  2. Then define the following parameters. You can either modify
+     this file, or define them before this file is included:
+	 
+  	$ADODB_SESSION_DRIVER='database driver, eg. mysql or ibase';
+	$ADODB_SESSION_CONNECT='server to connect to';
+	$ADODB_SESSION_USER ='user';
+	$ADODB_SESSION_PWD ='password';
+	$ADODB_SESSION_DB ='database';
+	$ADODB_SESSION_TBL = 'sessions'
+	
+  3. Recommended is PHP 4.0.2 or later. There are documented
+session bugs in earlier versions of PHP.
+
+*/
+
+
+include_once('crypt.inc.php');
+
+if (!defined('_ADODB_LAYER')) {
+	include (dirname(__FILE__).'/adodb.inc.php');
+}
+
+ /* if database time and system time is difference is greater than this, then give warning */
+ define('ADODB_SESSION_SYNCH_SECS',60); 
+
+if (!defined('ADODB_SESSION')) {
+
+ define('ADODB_SESSION',1);
+ 
+GLOBAL 	$ADODB_SESSION_CONNECT, 
+	$ADODB_SESSION_DRIVER,
+	$ADODB_SESSION_USER,
+	$ADODB_SESSION_PWD,
+	$ADODB_SESSION_DB,
+	$ADODB_SESS_CONN,
+	$ADODB_SESS_LIFE,
+	$ADODB_SESS_DEBUG,
+	$ADODB_SESS_INSERT,
+	$ADODB_SESSION_EXPIRE_NOTIFY,
+	$ADODB_SESSION_TBL; 
+
+	//$ADODB_SESS_DEBUG = true;
+	
+	/* SET THE FOLLOWING PARAMETERS */
+if (empty($ADODB_SESSION_DRIVER)) {
+	$ADODB_SESSION_DRIVER='mysql';
+	$ADODB_SESSION_CONNECT='localhost';
+	$ADODB_SESSION_USER ='root';
+	$ADODB_SESSION_PWD ='';
+	$ADODB_SESSION_DB ='xphplens_2';
+}
+
+if (empty($ADODB_SESSION_TBL)){
+	$ADODB_SESSION_TBL = 'sessions';
+}
+
+if (empty($ADODB_SESSION_EXPIRE_NOTIFY)) {
+	$ADODB_SESSION_EXPIRE_NOTIFY = false;
+}
+
+function ADODB_Session_Key() 
+{
+$ADODB_CRYPT_KEY = 'CRYPTED ADODB SESSIONS ROCK!';
+
+	/* USE THIS FUNCTION TO CREATE THE ENCRYPTION KEY FOR CRYPTED SESSIONS	*/
+	/* Crypt the used key, $ADODB_CRYPT_KEY as key and session_ID as SALT	*/
+	return crypt($ADODB_CRYPT_KEY, session_ID());
+}
+
+$ADODB_SESS_LIFE = ini_get('session.gc_maxlifetime');
+if ($ADODB_SESS_LIFE <= 1) {
+	// bug in PHP 4.0.3 pl 1  -- how about other versions?
+	//print "<h3>Session Error: PHP.INI setting <i>session.gc_maxlifetime</i>not set: $ADODB_SESS_LIFE</h3>";
+	$ADODB_SESS_LIFE=1440;
+}
+
+function adodb_sess_open($save_path, $session_name) 
+{
+GLOBAL 	$ADODB_SESSION_CONNECT, 
+	$ADODB_SESSION_DRIVER,
+	$ADODB_SESSION_USER,
+	$ADODB_SESSION_PWD,
+	$ADODB_SESSION_DB,
+	$ADODB_SESS_CONN,
+	$ADODB_SESS_DEBUG;
+	
+	$ADODB_SESS_INSERT = false;
+	
+	if (isset($ADODB_SESS_CONN)) return true;
+	
+	$ADODB_SESS_CONN = ADONewConnection($ADODB_SESSION_DRIVER);
+	if (!empty($ADODB_SESS_DEBUG)) {
+		$ADODB_SESS_CONN->debug = true;
+		print" conn=$ADODB_SESSION_CONNECT user=$ADODB_SESSION_USER pwd=$ADODB_SESSION_PWD db=$ADODB_SESSION_DB ";
+	}
+	return $ADODB_SESS_CONN->PConnect($ADODB_SESSION_CONNECT,
+			$ADODB_SESSION_USER,$ADODB_SESSION_PWD,$ADODB_SESSION_DB);
+	
+}
+
+function adodb_sess_close() 
+{
+global $ADODB_SESS_CONN;
+
+	if ($ADODB_SESS_CONN) $ADODB_SESS_CONN->Close();
+	return true;
+}
+
+function adodb_sess_read($key) 
+{
+$Crypt = new MD5Crypt;
+global $ADODB_SESS_CONN,$ADODB_SESS_INSERT,$ADODB_SESSION_TBL;
+	$rs = $ADODB_SESS_CONN->Execute("SELECT data FROM $ADODB_SESSION_TBL WHERE sesskey = '$key' AND expiry >= " . time());
+	if ($rs) {
+		if ($rs->EOF) {
+			$ADODB_SESS_INSERT = true;
+			$v = '';
+		} else {
+			// Decrypt session data
+			$v = rawurldecode($Crypt->Decrypt(reset($rs->fields), ADODB_Session_Key()));
+		}
+		$rs->Close();
+		return $v;
+	}
+	else $ADODB_SESS_INSERT = true;
+	
+	return '';
+}
+
+function adodb_sess_write($key, $val) 
+{
+$Crypt = new MD5Crypt;
+	global $ADODB_SESS_INSERT,$ADODB_SESS_CONN, $ADODB_SESS_LIFE, $ADODB_SESSION_TBL,$ADODB_SESSION_EXPIRE_NOTIFY;
+
+	$expiry = time() + $ADODB_SESS_LIFE;
+
+	// encrypt session data..	
+	$val = $Crypt->Encrypt(rawurlencode($val), ADODB_Session_Key());
+	
+	$arr = array('sesskey' => $key, 'expiry' => $expiry, 'data' => $val);
+	if ($ADODB_SESSION_EXPIRE_NOTIFY) {
+		$var = reset($ADODB_SESSION_EXPIRE_NOTIFY);
+		global $$var;
+		$arr['expireref'] = $$var;
+	}
+	$rs = $ADODB_SESS_CONN->Replace($ADODB_SESSION_TBL,
+	    $arr,
+    	'sesskey',$autoQuote = true);
+
+	if (!$rs) {
+		ADOConnection::outp( '
+-- Session Replace: '.$ADODB_SESS_CONN->ErrorMsg().'</p>',false);
+	} else {
+		// bug in access driver (could be odbc?) means that info is not commited
+		// properly unless select statement executed in Win2000
+	
+	if ($ADODB_SESS_CONN->databaseType == 'access') $rs = $ADODB_SESS_CONN->Execute("select sesskey from $ADODB_SESSION_TBL WHERE sesskey='$key'");
+	}
+	return isset($rs);
+}
+
+function adodb_sess_destroy($key) 
+{
+	global $ADODB_SESS_CONN, $ADODB_SESSION_TBL,$ADODB_SESSION_EXPIRE_NOTIFY;
+	
+	if ($ADODB_SESSION_EXPIRE_NOTIFY) {
+		reset($ADODB_SESSION_EXPIRE_NOTIFY);
+		$fn = next($ADODB_SESSION_EXPIRE_NOTIFY);
+		$savem = $ADODB_SESS_CONN->SetFetchMode(ADODB_FETCH_NUM);
+		$rs = $ADODB_SESS_CONN->Execute("SELECT expireref,sesskey FROM $ADODB_SESSION_TBL WHERE sesskey='$key'");
+		$ADODB_SESS_CONN->SetFetchMode($savem);
+		if ($rs) {
+			$ADODB_SESS_CONN->BeginTrans();
+			while (!$rs->EOF) {
+				$ref = $rs->fields[0];
+				$key = $rs->fields[1];
+				$fn($ref,$key);
+				$del = $ADODB_SESS_CONN->Execute("DELETE FROM $ADODB_SESSION_TBL WHERE sesskey='$key'");
+				$rs->MoveNext();
+			}
+			$ADODB_SESS_CONN->CommitTrans();
+		}
+	} else {
+		$qry = "DELETE FROM $ADODB_SESSION_TBL WHERE sesskey = '$key'";
+		$rs = $ADODB_SESS_CONN->Execute($qry);
+	}
+	return $rs ? true : false;
+}
+
+
+function adodb_sess_gc($maxlifetime) {
+	global $ADODB_SESS_CONN, $ADODB_SESSION_TBL,$ADODB_SESSION_EXPIRE_NOTIFY,$ADODB_SESS_DEBUG;
+
+	if ($ADODB_SESSION_EXPIRE_NOTIFY) {
+		reset($ADODB_SESSION_EXPIRE_NOTIFY);
+		$fn = next($ADODB_SESSION_EXPIRE_NOTIFY);
+		$savem = $ADODB_SESS_CONN->SetFetchMode(ADODB_FETCH_NUM);
+		$t = time();
+		$rs = $ADODB_SESS_CONN->Execute("SELECT expireref,sesskey FROM $ADODB_SESSION_TBL WHERE expiry < $t");
+		$ADODB_SESS_CONN->SetFetchMode($savem);
+		if ($rs) {
+			$ADODB_SESS_CONN->BeginTrans();
+			while (!$rs->EOF) {
+				$ref = $rs->fields[0];
+				$key = $rs->fields[1];
+				$fn($ref,$key);
+				//$del = $ADODB_SESS_CONN->Execute("DELETE FROM $ADODB_SESSION_TBL WHERE sesskey='$key'");
+				$rs->MoveNext();
+			}
+			$rs->Close();
+			
+			$ADODB_SESS_CONN->Execute("DELETE FROM $ADODB_SESSION_TBL WHERE expiry < $t");
+			$ADODB_SESS_CONN->CommitTrans();
+		}
+	} else {
+		$qry = "DELETE FROM $ADODB_SESSION_TBL WHERE expiry < " . time();
+		$ADODB_SESS_CONN->Execute($qry);
+	}
+	
+	// suggested by Cameron, "GaM3R" <gamr@outworld.cx>
+	if (defined('ADODB_SESSION_OPTIMIZE'))
+	{
+	global $ADODB_SESSION_DRIVER;
+	
+		switch( $ADODB_SESSION_DRIVER ) {
+			case 'mysql':
+			case 'mysqlt':
+				$opt_qry = 'OPTIMIZE TABLE '.$ADODB_SESSION_TBL;
+				break;
+			case 'postgresql':
+			case 'postgresql7':
+				$opt_qry = 'VACUUM '.$ADODB_SESSION_TBL;	
+				break;
+		}
+	}
+	
+	if ($ADODB_SESS_CONN->dataProvider === 'oci8') $sql = 'select  TO_CHAR('.($ADODB_SESS_CONN->sysTimeStamp).', \'RRRR-MM-DD HH24:MI:SS\') from '. $ADODB_SESSION_TBL;
+	else $sql = 'select '.$ADODB_SESS_CONN->sysTimeStamp.' from '. $ADODB_SESSION_TBL;
+	
+	$rs =& $ADODB_SESS_CONN->SelectLimit($sql,1);
+	if ($rs && !$rs->EOF) {
+	
+		$dbts = reset($rs->fields);
+		$rs->Close();
+		$dbt = $ADODB_SESS_CONN->UnixTimeStamp($dbts);
+		$t = time();
+		if (abs($dbt - $t) >= ADODB_SESSION_SYNCH_SECS) {
+			$msg = 
+			__FILE__.": Server time for webserver {$_SERVER['HTTP_HOST']} not in synch with database: database=$dbt ($dbts), webserver=$t (diff=".(abs($dbt-$t)/3600)." hrs)";
+			error_log($msg);
+			if ($ADODB_SESS_DEBUG) ADOConnection::outp("
+-- $msg</p>");
+		}
+	}
+	
+	return true;
+}
+
+session_module_name('user'); 
+session_set_save_handler(
+	"adodb_sess_open",
+	"adodb_sess_close",
+	"adodb_sess_read",
+	"adodb_sess_write",
+	"adodb_sess_destroy",
+	"adodb_sess_gc");
+}
+
+/*  TEST SCRIPT -- UNCOMMENT */
+/*
+if (0) {
+
+	session_start();
+	session_register('AVAR');
+	$_SESSION['AVAR'] += 1;
+	print "
+-- \$_SESSION['AVAR']={$_SESSION['AVAR']}</p>";
+}
+*/
+?>
Index: /Dev/trunk/rdfapi/util/adodb/session/old/adodb-session-clob.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/session/old/adodb-session-clob.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/session/old/adodb-session-clob.php	(revision 12)
@@ -0,0 +1,448 @@
+<?php
+/*
+  V4.93 10 Oct 2006  (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence.
+	  Set tabs to 4 for best viewing.
+  
+  Latest version of ADODB is available at http://php.weblogs.com/adodb
+  ======================================================================
+  
+ This file provides PHP4 session management using the ADODB database
+ wrapper library, using Oracle CLOB's to store data. Contributed by achim.gosse@ddd.de.
+
+ Example
+ =======
+ 
+	include('adodb.inc.php');
+	include('adodb-session.php');
+	session_start();
+	session_register('AVAR');
+	$_SESSION['AVAR'] += 1;
+	print "
+-- \$_SESSION['AVAR']={$_SESSION['AVAR']}</p>";
+	
+To force non-persistent connections, call adodb_session_open first before session_start():
+
+	include('adodb.inc.php');
+	include('adodb-session.php');
+	adodb_session_open(false,false,false);
+	session_start();
+	session_register('AVAR');
+	$_SESSION['AVAR'] += 1;
+	print "
+-- \$_SESSION['AVAR']={$_SESSION['AVAR']}</p>";
+
+ 
+ Installation
+ ============
+ 1. Create this table in your database (syntax might vary depending on your db):
+ 
+  create table sessions (
+	   SESSKEY char(32) not null,
+	   EXPIRY int(11) unsigned not null,
+	   EXPIREREF varchar(64),
+	   DATA CLOB,
+	  primary key (sesskey)
+  );
+
+
+  2. Then define the following parameters in this file:
+  	$ADODB_SESSION_DRIVER='database driver, eg. mysql or ibase';
+	$ADODB_SESSION_CONNECT='server to connect to';
+	$ADODB_SESSION_USER ='user';
+	$ADODB_SESSION_PWD ='password';
+	$ADODB_SESSION_DB ='database';
+	$ADODB_SESSION_TBL = 'sessions'
+	$ADODB_SESSION_USE_LOBS = false; (or, if you wanna use CLOBS (= 'CLOB') or ( = 'BLOB')
+	
+  3. Recommended is PHP 4.1.0 or later. There are documented
+	 session bugs in earlier versions of PHP.
+
+  4. If you want to receive notifications when a session expires, then
+  	 you can tag a session with an EXPIREREF, and before the session
+	 record is deleted, we can call a function that will pass the EXPIREREF
+	 as the first parameter, and the session key as the second parameter.
+	 
+	 To do this, define a notification function, say NotifyFn:
+	 
+	 	function NotifyFn($expireref, $sesskey)
+	 	{
+	 	}
+	 
+	 Then you need to define a global variable $ADODB_SESSION_EXPIRE_NOTIFY.
+	 This is an array with 2 elements, the first being the name of the variable
+	 you would like to store in the EXPIREREF field, and the 2nd is the 
+	 notification function's name.
+	 
+	 In this example, we want to be notified when a user's session 
+	 has expired, so we store the user id in the global variable $USERID, 
+	 store this value in the EXPIREREF field:
+	 
+	 	$ADODB_SESSION_EXPIRE_NOTIFY = array('USERID','NotifyFn');
+		
+	Then when the NotifyFn is called, we are passed the $USERID as the first
+	parameter, eg. NotifyFn($userid, $sesskey).
+*/
+
+if (!defined('_ADODB_LAYER')) {
+	include (dirname(__FILE__).'/adodb.inc.php');
+}
+
+if (!defined('ADODB_SESSION')) {
+
+ define('ADODB_SESSION',1);
+ 
+ /* if database time and system time is difference is greater than this, then give warning */
+ define('ADODB_SESSION_SYNCH_SECS',60); 
+
+/****************************************************************************************\
+	Global definitions
+\****************************************************************************************/
+GLOBAL 	$ADODB_SESSION_CONNECT, 
+	$ADODB_SESSION_DRIVER,
+	$ADODB_SESSION_USER,
+	$ADODB_SESSION_PWD,
+	$ADODB_SESSION_DB,
+	$ADODB_SESS_CONN,
+	$ADODB_SESS_LIFE,
+	$ADODB_SESS_DEBUG,
+	$ADODB_SESSION_EXPIRE_NOTIFY,
+	$ADODB_SESSION_CRC,
+	$ADODB_SESSION_USE_LOBS,
+	$ADODB_SESSION_TBL;
+	
+	if (!isset($ADODB_SESSION_USE_LOBS)) $ADODB_SESSION_USE_LOBS = 'CLOB';
+	
+	$ADODB_SESS_LIFE = ini_get('session.gc_maxlifetime');
+	if ($ADODB_SESS_LIFE <= 1) {
+	 // bug in PHP 4.0.3 pl 1  -- how about other versions?
+	 //print "<h3>Session Error: PHP.INI setting <i>session.gc_maxlifetime</i>not set: $ADODB_SESS_LIFE</h3>";
+	 	$ADODB_SESS_LIFE=1440;
+	}
+	$ADODB_SESSION_CRC = false;
+	//$ADODB_SESS_DEBUG = true;
+	
+	//////////////////////////////////
+	/* SET THE FOLLOWING PARAMETERS */
+	//////////////////////////////////
+	
+	if (empty($ADODB_SESSION_DRIVER)) {
+		$ADODB_SESSION_DRIVER='mysql';
+		$ADODB_SESSION_CONNECT='localhost';
+		$ADODB_SESSION_USER ='root';
+		$ADODB_SESSION_PWD ='';
+		$ADODB_SESSION_DB ='xphplens_2';
+	}
+	
+	if (empty($ADODB_SESSION_EXPIRE_NOTIFY)) {
+		$ADODB_SESSION_EXPIRE_NOTIFY = false;
+	}
+	//  Made table name configurable - by David Johnson djohnson@inpro.net
+	if (empty($ADODB_SESSION_TBL)){
+		$ADODB_SESSION_TBL = 'sessions';
+	}
+	
+
+	// defaulting $ADODB_SESSION_USE_LOBS
+	if (!isset($ADODB_SESSION_USE_LOBS) || empty($ADODB_SESSION_USE_LOBS)) {
+		$ADODB_SESSION_USE_LOBS = false;
+	}
+
+	/*
+	$ADODB_SESS['driver'] = $ADODB_SESSION_DRIVER;
+	$ADODB_SESS['connect'] = $ADODB_SESSION_CONNECT;
+	$ADODB_SESS['user'] = $ADODB_SESSION_USER;
+	$ADODB_SESS['pwd'] = $ADODB_SESSION_PWD;
+	$ADODB_SESS['db'] = $ADODB_SESSION_DB;
+	$ADODB_SESS['life'] = $ADODB_SESS_LIFE;
+	$ADODB_SESS['debug'] = $ADODB_SESS_DEBUG;
+	
+	$ADODB_SESS['debug'] = $ADODB_SESS_DEBUG;
+	$ADODB_SESS['table'] = $ADODB_SESS_TBL;
+	*/
+	
+/****************************************************************************************\
+	Create the connection to the database. 
+	
+	If $ADODB_SESS_CONN already exists, reuse that connection
+\****************************************************************************************/
+function adodb_sess_open($save_path, $session_name,$persist=true) 
+{
+GLOBAL $ADODB_SESS_CONN;
+	if (isset($ADODB_SESS_CONN)) return true;
+	
+GLOBAL 	$ADODB_SESSION_CONNECT, 
+	$ADODB_SESSION_DRIVER,
+	$ADODB_SESSION_USER,
+	$ADODB_SESSION_PWD,
+	$ADODB_SESSION_DB,
+	$ADODB_SESS_DEBUG;
+	
+	// cannot use & below - do not know why...
+	$ADODB_SESS_CONN = ADONewConnection($ADODB_SESSION_DRIVER);
+	if (!empty($ADODB_SESS_DEBUG)) {
+		$ADODB_SESS_CONN->debug = true;
+		ADOConnection::outp( " conn=$ADODB_SESSION_CONNECT user=$ADODB_SESSION_USER pwd=$ADODB_SESSION_PWD db=$ADODB_SESSION_DB ");
+	}
+	if ($persist) $ok = $ADODB_SESS_CONN->PConnect($ADODB_SESSION_CONNECT,
+			$ADODB_SESSION_USER,$ADODB_SESSION_PWD,$ADODB_SESSION_DB);
+	else $ok = $ADODB_SESS_CONN->Connect($ADODB_SESSION_CONNECT,
+			$ADODB_SESSION_USER,$ADODB_SESSION_PWD,$ADODB_SESSION_DB);
+	
+	if (!$ok) ADOConnection::outp( "
+-- Session: connection failed</p>",false);
+}
+
+/****************************************************************************************\
+	Close the connection
+\****************************************************************************************/
+function adodb_sess_close() 
+{
+global $ADODB_SESS_CONN;
+
+	if ($ADODB_SESS_CONN) $ADODB_SESS_CONN->Close();
+	return true;
+}
+
+/****************************************************************************************\
+	Slurp in the session variables and return the serialized string
+\****************************************************************************************/
+function adodb_sess_read($key) 
+{
+global $ADODB_SESS_CONN,$ADODB_SESSION_TBL,$ADODB_SESSION_CRC;
+
+	$rs = $ADODB_SESS_CONN->Execute("SELECT data FROM $ADODB_SESSION_TBL WHERE sesskey = '$key' AND expiry >= " . time());
+	if ($rs) {
+		if ($rs->EOF) {
+			$v = '';
+		} else 
+			$v = rawurldecode(reset($rs->fields));
+			
+		$rs->Close();
+		
+		// new optimization adodb 2.1
+		$ADODB_SESSION_CRC = strlen($v).crc32($v);
+		
+		return $v;
+	}
+	
+	return ''; // thx to Jorma Tuomainen, webmaster#wizactive.com
+}
+
+/****************************************************************************************\
+	Write the serialized data to a database.
+	
+	If the data has not been modified since adodb_sess_read(), we do not write.
+\****************************************************************************************/
+function adodb_sess_write($key, $val) 
+{
+	global
+		$ADODB_SESS_CONN, 
+		$ADODB_SESS_LIFE, 
+		$ADODB_SESSION_TBL,
+		$ADODB_SESS_DEBUG, 
+		$ADODB_SESSION_CRC,
+		$ADODB_SESSION_EXPIRE_NOTIFY,
+		$ADODB_SESSION_DRIVER,			// added
+		$ADODB_SESSION_USE_LOBS;		// added
+
+	$expiry = time() + $ADODB_SESS_LIFE;
+	
+	// crc32 optimization since adodb 2.1
+	// now we only update expiry date, thx to sebastian thom in adodb 2.32
+	if ($ADODB_SESSION_CRC !== false && $ADODB_SESSION_CRC == strlen($val).crc32($val)) {
+		if ($ADODB_SESS_DEBUG) echo "
+-- Session: Only updating date - crc32 not changed</p>";
+		$qry = "UPDATE $ADODB_SESSION_TBL SET expiry=$expiry WHERE sesskey='$key' AND expiry >= " . time();
+		$rs = $ADODB_SESS_CONN->Execute($qry);	
+		return true;
+	}
+	$val = rawurlencode($val);
+	
+	$arr = array('sesskey' => $key, 'expiry' => $expiry, 'data' => $val);
+	if ($ADODB_SESSION_EXPIRE_NOTIFY) {
+		$var = reset($ADODB_SESSION_EXPIRE_NOTIFY);
+		global $$var;
+		$arr['expireref'] = $$var;
+	}
+
+	
+	if ($ADODB_SESSION_USE_LOBS === false) {	// no lobs, simply use replace()
+		$rs = $ADODB_SESS_CONN->Replace($ADODB_SESSION_TBL,$arr, 'sesskey',$autoQuote = true);
+		if (!$rs) {
+			$err = $ADODB_SESS_CONN->ErrorMsg();
+		}
+	} else {
+		// what value shall we insert/update for lob row?
+		switch ($ADODB_SESSION_DRIVER) {
+			// empty_clob or empty_lob for oracle dbs
+			case "oracle":
+			case "oci8":
+			case "oci8po":
+			case "oci805":
+				$lob_value = sprintf("empty_%s()", strtolower($ADODB_SESSION_USE_LOBS));
+				break;
+
+			// null for all other
+			default:
+				$lob_value = "null";
+				break;
+		}
+
+		// do we insert or update? => as for sesskey
+		$res = $ADODB_SESS_CONN->Execute("select count(*) as cnt from $ADODB_SESSION_TBL where sesskey = '$key'");
+		if ($res && reset($res->fields) > 0) {
+			$qry = sprintf("update %s set expiry = %d, data = %s where sesskey = '%s'", $ADODB_SESSION_TBL, $expiry, $lob_value, $key);
+		} else {
+			// insert
+			$qry = sprintf("insert into %s (sesskey, expiry, data) values ('%s', %d, %s)", $ADODB_SESSION_TBL, $key, $expiry, $lob_value);
+		}
+
+		$err = "";
+		$rs1 = $ADODB_SESS_CONN->Execute($qry);
+		if (!$rs1) {
+			$err .= $ADODB_SESS_CONN->ErrorMsg()."\n";
+		}
+		$rs2 = $ADODB_SESS_CONN->UpdateBlob($ADODB_SESSION_TBL, 'data', $val, "sesskey='$key'", strtoupper($ADODB_SESSION_USE_LOBS));
+		if (!$rs2) {
+			$err .= $ADODB_SESS_CONN->ErrorMsg()."\n";
+		}
+		$rs = ($rs1 && $rs2) ? true : false;
+	}
+
+	if (!$rs) {
+		ADOConnection::outp( '
+-- Session Replace: '.nl2br($err).'</p>',false);
+	}  else {
+		// bug in access driver (could be odbc?) means that info is not commited
+		// properly unless select statement executed in Win2000
+		if ($ADODB_SESS_CONN->databaseType == 'access') 
+			$rs = $ADODB_SESS_CONN->Execute("select sesskey from $ADODB_SESSION_TBL WHERE sesskey='$key'");
+	}
+	return !empty($rs);
+}
+
+function adodb_sess_destroy($key) 
+{
+	global $ADODB_SESS_CONN, $ADODB_SESSION_TBL,$ADODB_SESSION_EXPIRE_NOTIFY;
+	
+	if ($ADODB_SESSION_EXPIRE_NOTIFY) {
+		reset($ADODB_SESSION_EXPIRE_NOTIFY);
+		$fn = next($ADODB_SESSION_EXPIRE_NOTIFY);
+		$savem = $ADODB_SESS_CONN->SetFetchMode(ADODB_FETCH_NUM);
+		$rs = $ADODB_SESS_CONN->Execute("SELECT expireref,sesskey FROM $ADODB_SESSION_TBL WHERE sesskey='$key'");
+		$ADODB_SESS_CONN->SetFetchMode($savem);
+		if ($rs) {
+			$ADODB_SESS_CONN->BeginTrans();
+			while (!$rs->EOF) {
+				$ref = $rs->fields[0];
+				$key = $rs->fields[1];
+				$fn($ref,$key);
+				$del = $ADODB_SESS_CONN->Execute("DELETE FROM $ADODB_SESSION_TBL WHERE sesskey='$key'");
+				$rs->MoveNext();
+			}
+			$ADODB_SESS_CONN->CommitTrans();
+		}
+	} else {
+		$qry = "DELETE FROM $ADODB_SESSION_TBL WHERE sesskey = '$key'";
+		$rs = $ADODB_SESS_CONN->Execute($qry);
+	}
+	return $rs ? true : false;
+}
+
+function adodb_sess_gc($maxlifetime) 
+{
+	global $ADODB_SESS_DEBUG, $ADODB_SESS_CONN, $ADODB_SESSION_TBL,$ADODB_SESSION_EXPIRE_NOTIFY;
+	
+	if ($ADODB_SESSION_EXPIRE_NOTIFY) {
+		reset($ADODB_SESSION_EXPIRE_NOTIFY);
+		$fn = next($ADODB_SESSION_EXPIRE_NOTIFY);
+		$savem = $ADODB_SESS_CONN->SetFetchMode(ADODB_FETCH_NUM);
+		$t = time();
+		$rs = $ADODB_SESS_CONN->Execute("SELECT expireref,sesskey FROM $ADODB_SESSION_TBL WHERE expiry < $t");
+		$ADODB_SESS_CONN->SetFetchMode($savem);
+		if ($rs) {
+			$ADODB_SESS_CONN->BeginTrans();
+			while (!$rs->EOF) {
+				$ref = $rs->fields[0];
+				$key = $rs->fields[1];
+				$fn($ref,$key);
+				$del = $ADODB_SESS_CONN->Execute("DELETE FROM $ADODB_SESSION_TBL WHERE sesskey='$key'");
+				$rs->MoveNext();
+			}
+			$rs->Close();
+			
+			//$ADODB_SESS_CONN->Execute("DELETE FROM $ADODB_SESSION_TBL WHERE expiry < $t");
+			$ADODB_SESS_CONN->CommitTrans();
+			
+		}
+	} else {
+		$ADODB_SESS_CONN->Execute("DELETE FROM $ADODB_SESSION_TBL WHERE expiry < " . time());
+	
+		if ($ADODB_SESS_DEBUG) ADOConnection::outp("
+-- <b>Garbage Collection</b>: $qry</p>");
+	}
+	// suggested by Cameron, "GaM3R" <gamr@outworld.cx>
+	if (defined('ADODB_SESSION_OPTIMIZE')) {
+	global $ADODB_SESSION_DRIVER;
+	
+		switch( $ADODB_SESSION_DRIVER ) {
+			case 'mysql':
+			case 'mysqlt':
+				$opt_qry = 'OPTIMIZE TABLE '.$ADODB_SESSION_TBL;
+				break;
+			case 'postgresql':
+			case 'postgresql7':
+				$opt_qry = 'VACUUM '.$ADODB_SESSION_TBL;	
+				break;
+		}
+		if (!empty($opt_qry)) {
+			$ADODB_SESS_CONN->Execute($opt_qry);
+		}
+	}
+	if ($ADODB_SESS_CONN->dataProvider === 'oci8') $sql = 'select  TO_CHAR('.($ADODB_SESS_CONN->sysTimeStamp).', \'RRRR-MM-DD HH24:MI:SS\') from '. $ADODB_SESSION_TBL;
+	else $sql = 'select '.$ADODB_SESS_CONN->sysTimeStamp.' from '. $ADODB_SESSION_TBL;
+	
+	$rs =& $ADODB_SESS_CONN->SelectLimit($sql,1);
+	if ($rs && !$rs->EOF) {
+	
+		$dbts = reset($rs->fields);
+		$rs->Close();
+		$dbt = $ADODB_SESS_CONN->UnixTimeStamp($dbts);
+		$t = time();
+		if (abs($dbt - $t) >= ADODB_SESSION_SYNCH_SECS) {
+			$msg = 
+			__FILE__.": Server time for webserver {$_SERVER['HTTP_HOST']} not in synch with database: database=$dbt ($dbts), webserver=$t (diff=".(abs($dbt-$t)/3600)." hrs)";
+			error_log($msg);
+			if ($ADODB_SESS_DEBUG) ADOConnection::outp("
+-- $msg</p>");
+		}
+	}
+	
+	return true;
+}
+
+session_module_name('user'); 
+session_set_save_handler(
+	"adodb_sess_open",
+	"adodb_sess_close",
+	"adodb_sess_read",
+	"adodb_sess_write",
+	"adodb_sess_destroy",
+	"adodb_sess_gc");
+}
+
+/*  TEST SCRIPT -- UNCOMMENT */
+
+if (0) {
+
+	session_start();
+	session_register('AVAR');
+	$_SESSION['AVAR'] += 1;
+	ADOConnection::outp( "
+-- \$_SESSION['AVAR']={$_SESSION['AVAR']}</p>",false);
+}
+
+?>
Index: /Dev/trunk/rdfapi/util/adodb/session/old/adodb-session.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/session/old/adodb-session.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/session/old/adodb-session.php	(revision 12)
@@ -0,0 +1,439 @@
+<?php
+/*
+V4.93 10 Oct 2006  (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence.
+	  Set tabs to 4 for best viewing.
+  
+  Latest version of ADODB is available at http://php.weblogs.com/adodb
+  ======================================================================
+  
+ This file provides PHP4 session management using the ADODB database
+wrapper library.
+ 
+ Example
+ =======
+ 
+	include('adodb.inc.php');
+	include('adodb-session.php');
+	session_start();
+	session_register('AVAR');
+	$_SESSION['AVAR'] += 1;
+	print "
+-- \$_SESSION['AVAR']={$_SESSION['AVAR']}</p>";
+	
+To force non-persistent connections, call adodb_session_open first before session_start():
+
+	include('adodb.inc.php');
+	include('adodb-session.php');
+	adodb_sess_open(false,false,false);
+	session_start();
+	session_register('AVAR');
+	$_SESSION['AVAR'] += 1;
+	print "
+-- \$_SESSION['AVAR']={$_SESSION['AVAR']}</p>";
+
+ 
+ Installation
+ ============
+ 1. Create this table in your database (syntax might vary depending on your db):
+ 
+  create table sessions (
+	   SESSKEY char(32) not null,
+	   EXPIRY int(11) unsigned not null,
+	   EXPIREREF varchar(64),
+	   DATA text not null,
+	  primary key (sesskey)
+  );
+  
+  For oracle:
+    create table sessions (
+	   SESSKEY char(32) not null,
+	   EXPIRY DECIMAL(16)  not null,
+	   EXPIREREF varchar(64),
+	   DATA varchar(4000) not null,
+	  primary key (sesskey)
+  );
+
+
+  2. Then define the following parameters. You can either modify
+     this file, or define them before this file is included:
+	 
+  	$ADODB_SESSION_DRIVER='database driver, eg. mysql or ibase';
+	$ADODB_SESSION_CONNECT='server to connect to';
+	$ADODB_SESSION_USER ='user';
+	$ADODB_SESSION_PWD ='password';
+	$ADODB_SESSION_DB ='database';
+	$ADODB_SESSION_TBL = 'sessions'
+	
+  3. Recommended is PHP 4.1.0 or later. There are documented
+	 session bugs in earlier versions of PHP.
+
+  4. If you want to receive notifications when a session expires, then
+  	 you can tag a session with an EXPIREREF, and before the session
+	 record is deleted, we can call a function that will pass the EXPIREREF
+	 as the first parameter, and the session key as the second parameter.
+	 
+	 To do this, define a notification function, say NotifyFn:
+	 
+	 	function NotifyFn($expireref, $sesskey)
+	 	{
+	 	}
+	 
+	 Then you need to define a global variable $ADODB_SESSION_EXPIRE_NOTIFY.
+	 This is an array with 2 elements, the first being the name of the variable
+	 you would like to store in the EXPIREREF field, and the 2nd is the 
+	 notification function's name.
+	 
+	 In this example, we want to be notified when a user's session 
+	 has expired, so we store the user id in the global variable $USERID, 
+	 store this value in the EXPIREREF field:
+	 
+	 	$ADODB_SESSION_EXPIRE_NOTIFY = array('USERID','NotifyFn');
+		
+	Then when the NotifyFn is called, we are passed the $USERID as the first
+	parameter, eg. NotifyFn($userid, $sesskey).
+*/
+
+if (!defined('_ADODB_LAYER')) {
+	include (dirname(__FILE__).'/adodb.inc.php');
+}
+
+if (!defined('ADODB_SESSION')) {
+
+ define('ADODB_SESSION',1);
+ 
+ /* if database time and system time is difference is greater than this, then give warning */
+ define('ADODB_SESSION_SYNCH_SECS',60); 
+
+ /*
+	Thanks Joe Li. See http://phplens.com/lens/lensforum/msgs.php?id=11487&x=1
+*/
+function adodb_session_regenerate_id() 
+{
+	$conn =& ADODB_Session::_conn();
+	if (!$conn) return false;
+
+	$old_id = session_id();
+	if (function_exists('session_regenerate_id')) {
+		session_regenerate_id();
+	} else {
+		session_id(md5(uniqid(rand(), true)));
+		$ck = session_get_cookie_params();
+		setcookie(session_name(), session_id(), false, $ck['path'], $ck['domain'], $ck['secure']);
+		//@session_start();
+	}
+	$new_id = session_id();
+	$ok =& $conn->Execute('UPDATE '. ADODB_Session::table(). ' SET sesskey='. $conn->qstr($new_id). ' WHERE sesskey='.$conn->qstr($old_id));
+	
+	/* it is possible that the update statement fails due to a collision */
+	if (!$ok) {
+		session_id($old_id);
+		if (empty($ck)) $ck = session_get_cookie_params();
+		setcookie(session_name(), session_id(), false, $ck['path'], $ck['domain'], $ck['secure']);
+		return false;
+	}
+	
+	return true;
+}
+
+/****************************************************************************************\
+	Global definitions
+\****************************************************************************************/
+GLOBAL 	$ADODB_SESSION_CONNECT, 
+	$ADODB_SESSION_DRIVER,
+	$ADODB_SESSION_USER,
+	$ADODB_SESSION_PWD,
+	$ADODB_SESSION_DB,
+	$ADODB_SESS_CONN,
+	$ADODB_SESS_LIFE,
+	$ADODB_SESS_DEBUG,
+	$ADODB_SESSION_EXPIRE_NOTIFY,
+	$ADODB_SESSION_CRC,
+	$ADODB_SESSION_TBL;
+	
+	
+	$ADODB_SESS_LIFE = ini_get('session.gc_maxlifetime');
+	if ($ADODB_SESS_LIFE <= 1) {
+	 // bug in PHP 4.0.3 pl 1  -- how about other versions?
+	 //print "<h3>Session Error: PHP.INI setting <i>session.gc_maxlifetime</i>not set: $ADODB_SESS_LIFE</h3>";
+	 	$ADODB_SESS_LIFE=1440;
+	}
+	$ADODB_SESSION_CRC = false;
+	//$ADODB_SESS_DEBUG = true;
+	
+	//////////////////////////////////
+	/* SET THE FOLLOWING PARAMETERS */
+	//////////////////////////////////
+	
+	if (empty($ADODB_SESSION_DRIVER)) {
+		$ADODB_SESSION_DRIVER='mysql';
+		$ADODB_SESSION_CONNECT='localhost';
+		$ADODB_SESSION_USER ='root';
+		$ADODB_SESSION_PWD ='';
+		$ADODB_SESSION_DB ='xphplens_2';
+	}
+	
+	if (empty($ADODB_SESSION_EXPIRE_NOTIFY)) {
+		$ADODB_SESSION_EXPIRE_NOTIFY = false;
+	}
+	//  Made table name configurable - by David Johnson djohnson@inpro.net
+	if (empty($ADODB_SESSION_TBL)){
+		$ADODB_SESSION_TBL = 'sessions';
+	}
+	
+	/*
+	$ADODB_SESS['driver'] = $ADODB_SESSION_DRIVER;
+	$ADODB_SESS['connect'] = $ADODB_SESSION_CONNECT;
+	$ADODB_SESS['user'] = $ADODB_SESSION_USER;
+	$ADODB_SESS['pwd'] = $ADODB_SESSION_PWD;
+	$ADODB_SESS['db'] = $ADODB_SESSION_DB;
+	$ADODB_SESS['life'] = $ADODB_SESS_LIFE;
+	$ADODB_SESS['debug'] = $ADODB_SESS_DEBUG;
+	
+	$ADODB_SESS['debug'] = $ADODB_SESS_DEBUG;
+	$ADODB_SESS['table'] = $ADODB_SESS_TBL;
+	*/
+	
+/****************************************************************************************\
+	Create the connection to the database. 
+	
+	If $ADODB_SESS_CONN already exists, reuse that connection
+\****************************************************************************************/
+function adodb_sess_open($save_path, $session_name,$persist=true) 
+{
+GLOBAL $ADODB_SESS_CONN;
+	if (isset($ADODB_SESS_CONN)) return true;
+	
+GLOBAL 	$ADODB_SESSION_CONNECT, 
+	$ADODB_SESSION_DRIVER,
+	$ADODB_SESSION_USER,
+	$ADODB_SESSION_PWD,
+	$ADODB_SESSION_DB,
+	$ADODB_SESS_DEBUG;
+	
+	// cannot use & below - do not know why...
+	$ADODB_SESS_CONN = ADONewConnection($ADODB_SESSION_DRIVER);
+	if (!empty($ADODB_SESS_DEBUG)) {
+		$ADODB_SESS_CONN->debug = true;
+		ADOConnection::outp( " conn=$ADODB_SESSION_CONNECT user=$ADODB_SESSION_USER pwd=$ADODB_SESSION_PWD db=$ADODB_SESSION_DB ");
+	}
+	if ($persist) $ok = $ADODB_SESS_CONN->PConnect($ADODB_SESSION_CONNECT,
+			$ADODB_SESSION_USER,$ADODB_SESSION_PWD,$ADODB_SESSION_DB);
+	else $ok = $ADODB_SESS_CONN->Connect($ADODB_SESSION_CONNECT,
+			$ADODB_SESSION_USER,$ADODB_SESSION_PWD,$ADODB_SESSION_DB);
+	
+	if (!$ok) ADOConnection::outp( "
+-- Session: connection failed</p>",false);
+}
+
+/****************************************************************************************\
+	Close the connection
+\****************************************************************************************/
+function adodb_sess_close() 
+{
+global $ADODB_SESS_CONN;
+
+	if ($ADODB_SESS_CONN) $ADODB_SESS_CONN->Close();
+	return true;
+}
+
+/****************************************************************************************\
+	Slurp in the session variables and return the serialized string
+\****************************************************************************************/
+function adodb_sess_read($key) 
+{
+global $ADODB_SESS_CONN,$ADODB_SESSION_TBL,$ADODB_SESSION_CRC;
+
+	$rs = $ADODB_SESS_CONN->Execute("SELECT data FROM $ADODB_SESSION_TBL WHERE sesskey = '$key' AND expiry >= " . time());
+	if ($rs) {
+		if ($rs->EOF) {
+			$v = '';
+		} else 
+			$v = rawurldecode(reset($rs->fields));
+			
+		$rs->Close();
+		
+		// new optimization adodb 2.1
+		$ADODB_SESSION_CRC = strlen($v).crc32($v);
+		
+		return $v;
+	}
+	
+	return ''; // thx to Jorma Tuomainen, webmaster#wizactive.com
+}
+
+/****************************************************************************************\
+	Write the serialized data to a database.
+	
+	If the data has not been modified since adodb_sess_read(), we do not write.
+\****************************************************************************************/
+function adodb_sess_write($key, $val) 
+{
+	global
+		$ADODB_SESS_CONN, 
+		$ADODB_SESS_LIFE, 
+		$ADODB_SESSION_TBL,
+		$ADODB_SESS_DEBUG, 
+		$ADODB_SESSION_CRC,
+		$ADODB_SESSION_EXPIRE_NOTIFY;
+
+	$expiry = time() + $ADODB_SESS_LIFE;
+	
+	// crc32 optimization since adodb 2.1
+	// now we only update expiry date, thx to sebastian thom in adodb 2.32
+	if ($ADODB_SESSION_CRC !== false && $ADODB_SESSION_CRC == strlen($val).crc32($val)) {
+		if ($ADODB_SESS_DEBUG) echo "
+-- Session: Only updating date - crc32 not changed</p>";
+		$qry = "UPDATE $ADODB_SESSION_TBL SET expiry=$expiry WHERE sesskey='$key' AND expiry >= " . time();
+		$rs = $ADODB_SESS_CONN->Execute($qry);	
+		return true;
+	}
+	$val = rawurlencode($val);
+	
+	$arr = array('sesskey' => $key, 'expiry' => $expiry, 'data' => $val);
+	if ($ADODB_SESSION_EXPIRE_NOTIFY) {
+		$var = reset($ADODB_SESSION_EXPIRE_NOTIFY);
+		global $$var;
+		$arr['expireref'] = $$var;
+	}
+	$rs = $ADODB_SESS_CONN->Replace($ADODB_SESSION_TBL,$arr,
+    	'sesskey',$autoQuote = true);
+	
+	if (!$rs) {
+		ADOConnection::outp( '
+-- Session Replace: '.$ADODB_SESS_CONN->ErrorMsg().'</p>',false);
+	}  else {
+		// bug in access driver (could be odbc?) means that info is not commited
+		// properly unless select statement executed in Win2000
+		if ($ADODB_SESS_CONN->databaseType == 'access') 
+			$rs = $ADODB_SESS_CONN->Execute("select sesskey from $ADODB_SESSION_TBL WHERE sesskey='$key'");
+	}
+	return !empty($rs);
+}
+
+function adodb_sess_destroy($key) 
+{
+	global $ADODB_SESS_CONN, $ADODB_SESSION_TBL,$ADODB_SESSION_EXPIRE_NOTIFY;
+	
+	if ($ADODB_SESSION_EXPIRE_NOTIFY) {
+		reset($ADODB_SESSION_EXPIRE_NOTIFY);
+		$fn = next($ADODB_SESSION_EXPIRE_NOTIFY);
+		$savem = $ADODB_SESS_CONN->SetFetchMode(ADODB_FETCH_NUM);
+		$rs = $ADODB_SESS_CONN->Execute("SELECT expireref,sesskey FROM $ADODB_SESSION_TBL WHERE sesskey='$key'");
+		$ADODB_SESS_CONN->SetFetchMode($savem);
+		if ($rs) {
+			$ADODB_SESS_CONN->BeginTrans();
+			while (!$rs->EOF) {
+				$ref = $rs->fields[0];
+				$key = $rs->fields[1];
+				$fn($ref,$key);
+				$del = $ADODB_SESS_CONN->Execute("DELETE FROM $ADODB_SESSION_TBL WHERE sesskey='$key'");
+				$rs->MoveNext();
+			}
+			$ADODB_SESS_CONN->CommitTrans();
+		}
+	} else {
+		$qry = "DELETE FROM $ADODB_SESSION_TBL WHERE sesskey = '$key'";
+		$rs = $ADODB_SESS_CONN->Execute($qry);
+	}
+	return $rs ? true : false;
+}
+
+function adodb_sess_gc($maxlifetime) 
+{
+	global $ADODB_SESS_DEBUG, $ADODB_SESS_CONN, $ADODB_SESSION_TBL,$ADODB_SESSION_EXPIRE_NOTIFY;
+	
+	if ($ADODB_SESSION_EXPIRE_NOTIFY) {
+		reset($ADODB_SESSION_EXPIRE_NOTIFY);
+		$fn = next($ADODB_SESSION_EXPIRE_NOTIFY);
+		$savem = $ADODB_SESS_CONN->SetFetchMode(ADODB_FETCH_NUM);
+		$t = time();
+		$rs =& $ADODB_SESS_CONN->Execute("SELECT expireref,sesskey FROM $ADODB_SESSION_TBL WHERE expiry < $t");
+		$ADODB_SESS_CONN->SetFetchMode($savem);
+		if ($rs) {
+			$ADODB_SESS_CONN->BeginTrans();
+			while (!$rs->EOF) {
+				$ref = $rs->fields[0];
+				$key = $rs->fields[1];
+				$fn($ref,$key);
+				$del = $ADODB_SESS_CONN->Execute("DELETE FROM $ADODB_SESSION_TBL WHERE sesskey='$key'");
+				$rs->MoveNext();
+			}
+			$rs->Close();
+			
+			$ADODB_SESS_CONN->CommitTrans();
+			
+		}
+	} else {
+		$qry = "DELETE FROM $ADODB_SESSION_TBL WHERE expiry < " . time();
+		$ADODB_SESS_CONN->Execute($qry);
+	
+		if ($ADODB_SESS_DEBUG) ADOConnection::outp("
+-- <b>Garbage Collection</b>: $qry</p>");
+	}
+	// suggested by Cameron, "GaM3R" <gamr@outworld.cx>
+	if (defined('ADODB_SESSION_OPTIMIZE')) {
+	global $ADODB_SESSION_DRIVER;
+	
+		switch( $ADODB_SESSION_DRIVER ) {
+			case 'mysql':
+			case 'mysqlt':
+				$opt_qry = 'OPTIMIZE TABLE '.$ADODB_SESSION_TBL;
+				break;
+			case 'postgresql':
+			case 'postgresql7':
+				$opt_qry = 'VACUUM '.$ADODB_SESSION_TBL;	
+				break;
+		}
+		if (!empty($opt_qry)) {
+			$ADODB_SESS_CONN->Execute($opt_qry);
+		}
+	}
+	if ($ADODB_SESS_CONN->dataProvider === 'oci8') $sql = 'select  TO_CHAR('.($ADODB_SESS_CONN->sysTimeStamp).', \'RRRR-MM-DD HH24:MI:SS\') from '. $ADODB_SESSION_TBL;
+	else $sql = 'select '.$ADODB_SESS_CONN->sysTimeStamp.' from '. $ADODB_SESSION_TBL;
+	
+	$rs =& $ADODB_SESS_CONN->SelectLimit($sql,1);
+	if ($rs && !$rs->EOF) {
+	
+		$dbts = reset($rs->fields);
+		$rs->Close();
+		$dbt = $ADODB_SESS_CONN->UnixTimeStamp($dbts);
+		$t = time();
+	
+		if (abs($dbt - $t) >= ADODB_SESSION_SYNCH_SECS) {
+		
+			$msg = 
+			__FILE__.": Server time for webserver {$_SERVER['HTTP_HOST']} not in synch with database: database=$dbt ($dbts), webserver=$t (diff=".(abs($dbt-$t)/3600)." hrs)";
+			error_log($msg);
+			if ($ADODB_SESS_DEBUG) ADOConnection::outp("
+-- $msg</p>");
+		}
+	}
+	
+	return true;
+}
+
+session_module_name('user'); 
+session_set_save_handler(
+	"adodb_sess_open",
+	"adodb_sess_close",
+	"adodb_sess_read",
+	"adodb_sess_write",
+	"adodb_sess_destroy",
+	"adodb_sess_gc");
+}
+
+/*  TEST SCRIPT -- UNCOMMENT */
+
+if (0) {
+
+	session_start();
+	session_register('AVAR');
+	$_SESSION['AVAR'] += 1;
+	ADOConnection::outp( "
+-- \$_SESSION['AVAR']={$_SESSION['AVAR']}</p>",false);
+}
+
+?>
Index: /Dev/trunk/rdfapi/util/adodb/session/old/crypt.inc.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/session/old/crypt.inc.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/session/old/crypt.inc.php	(revision 12)
@@ -0,0 +1,64 @@
+<?php
+//	 Session Encryption by Ari Kuorikoski <ari.kuorikoski@finebyte.com>
+class MD5Crypt{
+		function keyED($txt,$encrypt_key)
+		{
+				$encrypt_key = md5($encrypt_key);
+				$ctr=0;
+				$tmp = "";
+				for ($i=0;$i<strlen($txt);$i++){
+						if ($ctr==strlen($encrypt_key)) $ctr=0;
+						$tmp.= substr($txt,$i,1) ^ substr($encrypt_key,$ctr,1);
+						$ctr++;
+				}
+				return $tmp;
+		}
+
+		function Encrypt($txt,$key)
+		{
+				srand((double)microtime()*1000000);
+				$encrypt_key = md5(rand(0,32000));
+				$ctr=0;
+				$tmp = "";
+				for ($i=0;$i<strlen($txt);$i++)
+				{
+				if ($ctr==strlen($encrypt_key)) $ctr=0;
+				$tmp.= substr($encrypt_key,$ctr,1) .
+				(substr($txt,$i,1) ^ substr($encrypt_key,$ctr,1));
+				$ctr++;
+				}
+				return base64_encode($this->keyED($tmp,$key));
+		}
+
+		function Decrypt($txt,$key)
+		{
+				$txt = $this->keyED(base64_decode($txt),$key);
+				$tmp = "";
+				for ($i=0;$i<strlen($txt);$i++){
+						$md5 = substr($txt,$i,1);
+						$i++;
+						$tmp.= (substr($txt,$i,1) ^ $md5);
+				}
+				return $tmp;
+		}
+
+		function RandPass()
+		{
+				$randomPassword = "";
+				srand((double)microtime()*1000000);
+				for($i=0;$i<8;$i++)
+				{
+						$randnumber = rand(48,120);
+
+						while (($randnumber >= 58 && $randnumber <= 64) || ($randnumber >= 91 && $randnumber <= 96))
+						{
+								$randnumber = rand(48,120);
+						}
+
+						$randomPassword .= chr($randnumber);
+				}
+				return $randomPassword;
+		}
+
+}
+?>
Index: /Dev/trunk/rdfapi/util/adodb/session/session_schema.xml
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/session/session_schema.xml	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/session/session_schema.xml	(revision 12)
@@ -0,0 +1,26 @@
+<?xml version="1.0"?>
+<schema version="0.2">
+  <table name="sessions">
+    <desc>table for ADOdb session-management</desc>
+
+    <field name="SESSKEY" type="C" size="32">
+      <descr>session key</descr>
+      <KEY/>
+      <NOTNULL/>
+    </field>
+ 
+    <field name="EXPIRY" type="I" size="11">
+      <descr></descr>
+      <NOTNULL/>
+    </field>
+
+    <field name="EXPIREREF" type="C" size="64">
+      <descr></descr>
+    </field>
+
+    <field name="DATA" type="XL">
+      <descr></descr>
+      <NOTNULL/>
+    </field>
+  </table>
+</schema>
Index: /Dev/trunk/rdfapi/util/adodb/session/session_schema2.xml
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/session/session_schema2.xml	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/session/session_schema2.xml	(revision 12)
@@ -0,0 +1,38 @@
+<?xml version="1.0"?>
+<schema version="0.3">
+  <table name="sessions2">
+    <desc>table for ADOdb session-management</desc>
+
+    <field name="SESSKEY" type="C" size="64">
+      <descr>session key</descr>
+      <KEY/>
+      <NOTNULL/>
+    </field>
+ 
+
+	
+    <field name="EXPIRY" type="T">
+      <descr></descr>
+      <NOTNULL/>
+    </field>
+	
+	 	<field name="CREATED" type="T">
+	     <descr></descr>
+      <NOTNULL/>
+    </field>
+	
+	 	<field name="MODIFIED" type="T">
+	     <descr></descr>
+      <NOTNULL/>
+    </field>
+
+    <field name="EXPIREREF" type="C" size="250">
+      <descr></descr>
+    </field>
+
+    <field name="SESSDATA" type="XL">
+      <descr></descr>
+      <NOTNULL/>
+    </field>
+  </table>
+</schema>
Index: /Dev/trunk/rdfapi/util/adodb/tests/benchmark.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/tests/benchmark.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/tests/benchmark.php	(revision 12)
@@ -0,0 +1,84 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
+
+<html>
+<head>
+	<title>ADODB Benchmarks</title>
+</head> 
+
+<body>
+<?php 
+/*
+V4.81 3 May 2006  (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence.
+  
+  Benchmark code to test the speed to the ADODB library with different databases.
+  This is a simplistic benchmark to be used as the basis for further testing.
+  It should not be used as proof of the superiority of one database over the other.
+*/ 
+ 
+$testmssql = true;
+//$testvfp = true;
+$testoracle = true;
+$testado = true; 
+$testibase = true;
+$testaccess = true;
+$testmysql = true;
+$testsqlite = true;;
+
+set_time_limit(240); // increase timeout
+
+include("../tohtml.inc.php");
+include("../adodb.inc.php");
+
+function testdb(&$db,$createtab="create table ADOXYZ (id int, firstname char(24), lastname char(24), created date)")
+{
+GLOBAL $ADODB_version,$ADODB_FETCH_MODE;
+
+	adodb_backtrace();
+	
+	$max = 100;
+	$sql = 'select * from ADOXYZ';
+	$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
+	
+	//print "<h3>ADODB Version: $ADODB_version Host: <i>$db->host</i> &nbsp; Database: <i>$db->database</i></h3>";
+	
+	// perform query once to cache results so we are only testing throughput 
+	$rs = $db->Execute($sql);
+	if (!$rs){
+		print "Error in recordset<p>";
+		return;
+	}	
+	$arr = $rs->GetArray();
+	//$db->debug = true;
+	global $ADODB_COUNTRECS;
+	$ADODB_COUNTRECS = false;
+	$start = microtime();
+	for ($i=0; $i < $max; $i++) {
+		$rs =& $db->Execute($sql);	
+		$arr =& $rs->GetArray();
+	   //		 print $arr[0][1];
+	}
+	$end =  microtime();
+	$start = explode(' ',$start);
+	$end = explode(' ',$end);
+	
+	//print_r($start);
+	//print_r($end);
+	
+	  //  print_r($arr);
+	$total = $end[0]+trim($end[1]) - $start[0]-trim($start[1]);
+	printf ("<p>seconds = %8.2f for %d iterations each with %d records</p>",$total,$max, sizeof($arr));
+	flush();
+
+
+		//$db->Close();
+}
+include("testdatabases.inc.php");
+
+?>
+
+
+</body>
+</html>
Index: /Dev/trunk/rdfapi/util/adodb/tests/client.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/tests/client.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/tests/client.php	(revision 12)
@@ -0,0 +1,198 @@
+<html>
+<body bgcolor=white>
+<?php
+/** 
+ * V4.50 6 July 2004  (c) 2001-2002 John Lim (jlim#natsoft.com.my). All rights reserved.
+ * Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence. 
+ * 
+ * set tabs to 8
+ */
+ 
+ // documentation on usage is at http://php.weblogs.com/adodb_csv
+ 
+ echo PHP_VERSION,'<br>';
+ var_dump(parse_url('odbc_mssql://userserver/'));
+ die();
+ 
+include('../adodb.inc.php');
+include('../tohtml.inc.php');
+
+ function &send2server($url,$sql)
+ {
+	$url .= '?sql='.urlencode($sql);
+	print "<p>$url</p>";
+	$rs = csv2rs($url,$err);
+	if ($err) print $err;
+	return $rs;
+ }
+ 
+ function print_pre($s)
+ {
+ 	print "<pre>";print_r($s);print "</pre>";
+ }
+
+
+$serverURL = 'http://localhost/php/phplens/adodb/server.php';
+$testhttp = false;
+
+$sql1 = "insertz into products (productname) values ('testprod 1')";
+$sql2 = "insert into products (productname) values ('testprod 1')";
+$sql3 = "insert into products (productname) values ('testprod 2')";
+$sql4 = "delete from products where productid>80";
+$sql5 = 'select * from products';
+	
+if ($testhttp) {
+	print "<a href=#c>Client Driver Tests</a><p>";
+	print "<h3>Test Error</h3>";
+	$rs = send2server($serverURL,$sql1);
+	print_pre($rs);
+	print "<hr />";
+	
+	print "<h3>Test Insert</h3>";
+	
+	$rs = send2server($serverURL,$sql2);
+	print_pre($rs);
+	print "<hr />";
+	
+	print "<h3>Test Insert2</h3>";
+	
+	$rs = send2server($serverURL,$sql3);
+	print_pre($rs);
+	print "<hr />";
+	
+	print "<h3>Test Delete</h3>";
+	
+	$rs = send2server($serverURL,$sql4);
+	print_pre($rs);
+	print "<hr />";
+	
+	
+	print "<h3>Test Select</h3>";
+	$rs = send2server($serverURL,$sql5);
+	if ($rs) rs2html($rs);
+	
+	print "<hr />";
+}
+
+
+print "<a name=c><h1>CLIENT Driver Tests</h1>";
+$conn = ADONewConnection('csv');
+$conn->Connect($serverURL);
+$conn->debug = true;
+
+print "<h3>Bad SQL</h3>";
+
+$rs = $conn->Execute($sql1);
+
+print "<h3>Insert SQL 1</h3>";
+$rs = $conn->Execute($sql2);
+
+print "<h3>Insert SQL 2</h3>";
+$rs = $conn->Execute($sql3);
+
+print "<h3>Select SQL</h3>";
+$rs = $conn->Execute($sql5);
+if ($rs) rs2html($rs);
+
+print "<h3>Delete SQL</h3>";
+$rs = $conn->Execute($sql4);
+
+print "<h3>Select SQL</h3>";
+$rs = $conn->Execute($sql5);
+if ($rs) rs2html($rs);
+
+
+/* EXPECTED RESULTS FOR HTTP TEST:
+
+Test Insert
+http://localhost/php/adodb/server.php?sql=insert+into+products+%28productname%29+values+%28%27testprod%27%29
+
+adorecordset Object
+(
+	[dataProvider] => native
+	[fields] => 
+	[blobSize] => 64
+	[canSeek] => 
+	[EOF] => 1
+	[emptyTimeStamp] =>  
+	[emptyDate] =>  
+	[debug] => 
+	[timeToLive] => 0
+	[bind] => 
+	[_numOfRows] => -1
+	[_numOfFields] => 0
+	[_queryID] => 1
+	[_currentRow] => -1
+	[_closed] => 
+	[_inited] => 
+	[sql] => insert into products (productname) values ('testprod')
+	[affectedrows] => 1
+	[insertid] => 81
+)
+
+
+--------------------------------------------------------------------------------
+
+Test Insert2
+http://localhost/php/adodb/server.php?sql=insert+into+products+%28productname%29+values+%28%27testprod%27%29
+
+adorecordset Object
+(
+	[dataProvider] => native
+	[fields] => 
+	[blobSize] => 64
+	[canSeek] => 
+	[EOF] => 1
+	[emptyTimeStamp] =>  
+	[emptyDate] =>  
+	[debug] => 
+	[timeToLive] => 0
+	[bind] => 
+	[_numOfRows] => -1
+	[_numOfFields] => 0
+	[_queryID] => 1
+	[_currentRow] => -1
+	[_closed] => 
+	[_inited] => 
+	[sql] => insert into products (productname) values ('testprod')
+	[affectedrows] => 1
+	[insertid] => 82
+)
+
+
+--------------------------------------------------------------------------------
+
+Test Delete
+http://localhost/php/adodb/server.php?sql=delete+from+products+where+productid%3E80
+
+adorecordset Object
+(
+	[dataProvider] => native
+	[fields] => 
+	[blobSize] => 64
+	[canSeek] => 
+	[EOF] => 1
+	[emptyTimeStamp] =>  
+	[emptyDate] =>  
+	[debug] => 
+	[timeToLive] => 0
+	[bind] => 
+	[_numOfRows] => -1
+	[_numOfFields] => 0
+	[_queryID] => 1
+	[_currentRow] => -1
+	[_closed] => 
+	[_inited] => 
+	[sql] => delete from products where productid>80
+	[affectedrows] => 2
+	[insertid] => 0
+)
+
+[more stuff deleted]
+ .
+ . 
+ .
+*/
+?>
Index: /Dev/trunk/rdfapi/util/adodb/tests/pdo.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/tests/pdo.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/tests/pdo.php	(revision 12)
@@ -0,0 +1,94 @@
+<?php
+error_reporting(E_ALL);
+include('../adodb.inc.php');
+
+echo "<pre>";
+try {
+	echo "New Connection\n";
+	
+	
+	$dsn = 'pdo_mysql://root:@localhost/northwind?persist';
+	
+	if (!empty($dsn)) {
+		$DB =& NewADOConnection($dsn) || die("CONNECT FAILED");
+		$connstr = $dsn;
+	} else {
+	
+		$DB = NewADOConnection('pdo');
+		
+		echo "Connect\n";
+		
+		$u = ''; $p = '';
+		/*
+		$connstr = 'odbc:nwind';
+		
+		$connstr = 'oci:';
+		$u = 'scott';
+		$p = 'natsoft';
+		
+		
+		$connstr ="sqlite:d:\inetpub\adodb\sqlite.db";
+		*/
+		
+		$connstr = "mysql:dbname=northwind";
+		$u = 'root';
+		
+		$connstr = "pgsql:dbname=test";
+		$u = 'tester';
+		$p = 'test';
+		
+		$DB->Connect($connstr,$u,$p) || die("CONNECT FAILED");
+	
+	}
+	
+	echo "connection string=$connstr\n Execute\n";
+	
+	//$ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
+	$rs = $DB->Execute("select * from ADOXYZ where id<3");
+	if  ($DB->ErrorNo()) echo "*** errno=".$DB->ErrorNo() . " ".($DB->ErrorMsg())."\n";
+	
+	
+	//print_r(get_class_methods($DB->_stmt));
+	
+	if (!$rs) die("NO RS");
+	
+	echo "Meta\n";
+	for ($i=0; $i < $rs->NumCols(); $i++) {
+		var_dump($rs->FetchField($i));
+		echo "<br>";
+	}
+	
+	echo "FETCH\n";
+	$cnt = 0;
+	while (!$rs->EOF) {
+		adodb_pr($rs->fields); 
+		$rs->MoveNext();
+		if ($cnt++ > 1000) break;
+	}
+	
+	echo "<br>--------------------------------------------------------<br>\n\n\n";
+	
+	$stmt = $DB->PrepareStmt("select * from ADOXYZ");
+	
+	$rs = $stmt->Execute();
+	$cols = $stmt->NumCols(); // execute required
+	
+	echo "COLS = $cols";
+	for($i=1;$i<=$cols;$i++) {
+		$v = $stmt->_stmt->getColumnMeta($i);
+		var_dump($v);
+	}
+	
+	echo "e=".$stmt->ErrorNo() . " ".($stmt->ErrorMsg())."\n";
+	while ($arr = $rs->FetchRow()) {
+		adodb_pr($arr);
+	}
+	die("DONE\n");
+
+} catch (exception $e) {
+	echo "<pre>";
+	echo $e;
+	echo "</pre>";
+}
+
+?>
Index: /Dev/trunk/rdfapi/util/adodb/tests/test-active-record.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/tests/test-active-record.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/tests/test-active-record.php	(revision 12)
@@ -0,0 +1,82 @@
+<?php
+
+	include_once('../adodb.inc.php');
+	include_once('../adodb-active-record.inc.php');
+	
+	// uncomment the following if you want to test exceptions
+	if (@$_GET['except']) {
+		if (PHP_VERSION >= 5) {
+			include('../adodb-exceptions.inc.php');
+			echo "<h3>Exceptions included</h3>";
+		}
+	}
+
+	$db = NewADOConnection('mysql://root@localhost/northwind');
+	$db->debug=1;
+	ADOdb_Active_Record::SetDatabaseAdapter($db);
+
+	$db->Execute("CREATE TEMPORARY TABLE `persons` (
+	                `id` int(10) unsigned NOT NULL auto_increment,
+	                `name_first` varchar(100) NOT NULL default '',
+	                `name_last` varchar(100) NOT NULL default '',
+	                `favorite_color` varchar(100) NOT NULL default '',
+	                PRIMARY KEY  (`id`)
+	            ) ENGINE=MyISAM;
+	           ");
+			   
+	class Person extends ADOdb_Active_Record{}
+	$person = new Person();
+	
+	echo "<p>Output of getAttributeNames: ";
+	var_dump($person->getAttributeNames());
+	
+	/**
+	 * Outputs the following:
+	 * array(4) {
+	 *    [0]=>
+	 *    string(2) "id"
+	 *    [1]=>
+	 *    string(9) "name_first"
+	 *    [2]=>
+	 *    string(8) "name_last"
+	 *    [3]=>
+	 *    string(13) "favorite_color"
+	 *  }
+	 */
+	
+	$person = new Person();
+	$person->name_first = 'Andi';
+	$person->name_last  = 'Gutmans';
+	$person->save(); // this save() will fail on INSERT as favorite_color is a must fill...
+	
+	
+	$person = new Person();
+	$person->name_first     = 'Andi';
+	$person->name_last      = 'Gutmans';
+	$person->favorite_color = 'blue';
+	$person->save(); // this save will perform an INSERT successfully
+	
+	echo "<p>The Insert ID generated:"; print_r($person->id);
+	
+	$person->favorite_color = 'red';
+	$person->save(); // this save() will perform an UPDATE
+	
+	$person = new Person();
+	$person->name_first     = 'John';
+	$person->name_last      = 'Lim';
+	$person->favorite_color = 'lavender';
+	$person->save(); // this save will perform an INSERT successfully
+	
+	// load record where id=2 into a new ADOdb_Active_Record
+	$person2 = new Person();
+	$person2->Load('id=2');
+	
+	var_dump($person2);
+	
+	$activeArr = $db->GetActiveRecordsClass($class = "Person",$table = "persons","id=".$db->Param(0),array(2));
+	$person2 =& $activeArr[0];
+	echo "<p>Name (should be John): ",$person->name_first, " <br> Class (should be Person): ",get_class($person2);	
+	
+
+
+?>
Index: /Dev/trunk/rdfapi/util/adodb/tests/test-active-recs2.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/tests/test-active-recs2.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/tests/test-active-recs2.php	(revision 12)
@@ -0,0 +1,75 @@
+<?php
+error_reporting(E_ALL);
+include('../adodb.inc.php');
+
+include('../adodb-active-record.inc.php');
+
+###########################
+
+$ADODB_ACTIVE_CACHESECS = 36;
+
+$DBMS = @$_GET['db'];
+if ($DBMS == 'mysql') {
+	$db = NewADOConnection('mysql://root@localhost/northwind');
+} else if ($DBMS == 'postgres') {
+	$db = NewADOConnection('postgres');
+	$db->Connect("localhost","tester","test","test");
+} else
+	$db = NewADOConnection('oci8://scott:natsoft@/');
+
+
+$arr = $db->ServerInfo();
+echo "<h3>$db->dataProvider: {$arr['description']}</h3>";
+
+$arr = $db->GetActiveRecords('products',' productid<10');
+adodb_pr($arr);
+
+ADOdb_Active_Record::SetDatabaseAdapter($db);
+if  (!$db)  die('failed');
+
+
+
+
+$rec = new ADODB_Active_Record('photos');
+
+$rec = new ADODB_Active_Record('products');
+
+
+adodb_pr($rec->getAttributeNames());
+
+echo "<hr>";
+
+
+$rec->load('productid=2');
+adodb_pr($rec);
+
+$db->debug=1;
+
+
+$rec->productname = 'Changie Chan'.rand();
+
+$rec->insert();
+$rec->update();
+
+$rec->productname = 'Changie Chan 99';
+$rec->replace();
+
+
+$rec2 = new ADODB_Active_Record('products');
+$rec->load('productid=3');
+$rec->save();
+
+$rec = new ADODB_Active_record('products');
+$rec->productname = 'John ActiveRec';
+$rec->notes = 22;
+#$rec->productid=0;
+$rec->discontinued=1;
+$rec->Save();
+$rec->supplierid=33;
+$rec->Save();
+$rec->discontinued=0;
+$rec->Save();
+$rec->Delete();
+
+echo "<p>Affected Rows after delete=".$db->Affected_Rows()."</p>";
+?>
Index: /Dev/trunk/rdfapi/util/adodb/tests/test-datadict.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/tests/test-datadict.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/tests/test-datadict.php	(revision 12)
@@ -0,0 +1,248 @@
+<?php
+/*
+
+  V4.81 3 May 2006  (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence.
+	
+  Set tabs to 4 for best viewing.
+
+*/
+
+error_reporting(E_ALL);
+include_once('../adodb.inc.php');
+
+foreach(array('sapdb','sybase','mysql','access','oci8po','postgres','odbc_mssql','odbc','db2','firebird','informix') as $dbType) {
+	echo "<h3>$dbType</h3><p>";
+	$db = NewADOConnection($dbType);
+	$dict = NewDataDictionary($db);
+
+	if (!$dict) continue;
+	$dict->debug = 1;
+	
+	$opts = array('REPLACE','mysql' => 'ENGINE=INNODB', 'oci8' => 'TABLESPACE USERS');
+	
+/*	$flds = array(
+		array('id',	'I',								
+							'AUTO','KEY'),
+							
+		array('name' => 'firstname', 'type' => 'varchar','size' => 30,
+							'DEFAULT'=>'Joan'),
+							
+		array('lastname','varchar',28,
+							'DEFAULT'=>'Chen','key'),
+							
+		array('averylonglongfieldname','X',1024,
+							'NOTNULL','default' => 'test'),
+							
+		array('price','N','7.2',
+							'NOTNULL','default' => '0.00'),
+							
+		array('MYDATE', 'D', 
+							'DEFDATE'),
+		array('TS','T',
+							'DEFTIMESTAMP')
+	);*/
+	
+	$flds = "
+ID            I           AUTO KEY,
+FIRSTNAME     VARCHAR(30) DEFAULT 'Joan' INDEX idx_name,
+LASTNAME      VARCHAR(28) DEFAULT 'Chen' key INDEX idx_name,
+averylonglongfieldname X(1024) DEFAULT 'test',
+price         N(7.2)  DEFAULT '0.00',
+MYDATE        D      DEFDATE INDEX idx_date,
+BIGFELLOW     X      NOTNULL,
+TS            T      DEFTIMESTAMP";
+
+
+	$sqla = $dict->CreateDatabase('KUTU',array('postgres'=>"LOCATION='/u01/postdata'"));
+	$dict->SetSchema('KUTU');
+	
+	$sqli = ($dict->CreateTableSQL('testtable',$flds, $opts));
+	$sqla = array_merge($sqla,$sqli);
+	
+	$sqli = $dict->CreateIndexSQL('idx','testtable','price,firstname,lastname',array('BITMAP','FULLTEXT','CLUSTERED','HASH'));
+	$sqla = array_merge($sqla,$sqli);
+	$sqli = $dict->CreateIndexSQL('idx2','testtable','price,lastname');//,array('BITMAP','FULLTEXT','CLUSTERED'));
+	$sqla = array_merge($sqla,$sqli);
+	
+	$addflds = array(array('height', 'F'),array('weight','F'));
+	$sqli = $dict->AddColumnSQL('testtable',$addflds);
+	$sqla = array_merge($sqla,$sqli);
+	$addflds = array(array('height', 'F','NOTNULL'),array('weight','F','NOTNULL'));
+	$sqli = $dict->AlterColumnSQL('testtable',$addflds);
+	$sqla = array_merge($sqla,$sqli);
+	
+	
+	printsqla($dbType,$sqla);
+	
+	if (file_exists('d:\inetpub\wwwroot\php\phplens\adodb\adodb.inc.php'))
+	if ($dbType == 'mysqlt') {
+		$db->Connect('localhost', "root", "", "test");
+		$dict->SetSchema('');
+		$sqla2 = $dict->ChangeTableSQL('adoxyz',$flds);
+		if ($sqla2) printsqla($dbType,$sqla2);
+	}
+	if ($dbType == 'postgres') {
+		if (@$db->Connect('localhost', "tester", "test", "test"));
+		$dict->SetSchema('');
+		$sqla2 = $dict->ChangeTableSQL('adoxyz',$flds);
+		if ($sqla2) printsqla($dbType,$sqla2);
+	}
+	
+	if ($dbType == 'odbc_mssql') {
+		$dsn = $dsn = "PROVIDER=MSDASQL;Driver={SQL Server};Server=localhost;Database=northwind;";
+		if (@$db->Connect($dsn, "sa", "natsoft", "test"));
+		$dict->SetSchema('');
+		$sqla2 = $dict->ChangeTableSQL('adoxyz',$flds);
+		if ($sqla2) printsqla($dbType,$sqla2);
+	}
+	
+	
+	
+	adodb_pr($dict->databaseType);
+	printsqla($dbType, $dict->DropColumnSQL('table',array('my col','`col2_with_Quotes`','A_col3','col3(10)')));
+	printsqla($dbType, $dict->ChangeTableSQL('adoxyz','LASTNAME varchar(32)'));
+	
+}
+
+function printsqla($dbType,$sqla)
+{
+	print "<pre>";
+	//print_r($dict->MetaTables());
+	foreach($sqla as $s) {
+		$s = htmlspecialchars($s);
+		print "$s;\n";
+		if ($dbType == 'oci8') print "/\n";
+	}
+	print "</pre><hr />";
+}
+
+/***
+
+Generated SQL:
+
+mysql
+
+CREATE DATABASE KUTU;
+DROP TABLE KUTU.testtable;
+CREATE TABLE KUTU.testtable (
+id               INTEGER NOT NULL AUTO_INCREMENT,
+firstname        VARCHAR(30) DEFAULT 'Joan',
+lastname         VARCHAR(28) NOT NULL DEFAULT 'Chen',
+averylonglongfieldname LONGTEXT NOT NULL,
+price            NUMERIC(7,2) NOT NULL DEFAULT 0.00,
+MYDATE           DATE DEFAULT CURDATE(),
+                 PRIMARY KEY (id, lastname)
+)TYPE=ISAM;
+CREATE FULLTEXT INDEX idx ON KUTU.testtable (firstname,lastname);
+CREATE INDEX idx2 ON KUTU.testtable (price,lastname);
+ALTER TABLE KUTU.testtable  ADD height           DOUBLE;
+ALTER TABLE KUTU.testtable  ADD weight           DOUBLE;
+ALTER TABLE KUTU.testtable  MODIFY COLUMN height           DOUBLE NOT NULL;
+ALTER TABLE KUTU.testtable  MODIFY COLUMN weight           DOUBLE NOT NULL;
+
+
+--------------------------------------------------------------------------------
+
+oci8
+
+CREATE USER KUTU IDENTIFIED BY tiger;
+/
+GRANT CREATE SESSION, CREATE TABLE,UNLIMITED TABLESPACE,CREATE SEQUENCE TO KUTU;
+/
+DROP TABLE KUTU.testtable CASCADE CONSTRAINTS;
+/
+CREATE TABLE KUTU.testtable (
+id               NUMBER(16) NOT NULL,
+firstname        VARCHAR(30) DEFAULT 'Joan',
+lastname         VARCHAR(28) DEFAULT 'Chen' NOT NULL,
+averylonglongfieldname CLOB NOT NULL,
+price            NUMBER(7,2) DEFAULT 0.00 NOT NULL,
+MYDATE           DATE DEFAULT TRUNC(SYSDATE),
+                 PRIMARY KEY (id, lastname)
+)TABLESPACE USERS;
+/
+DROP SEQUENCE KUTU.SEQ_testtable;
+/
+CREATE SEQUENCE KUTU.SEQ_testtable;
+/
+CREATE OR REPLACE TRIGGER KUTU.TRIG_SEQ_testtable BEFORE insert ON KUTU.testtable 
+		FOR EACH ROW
+		BEGIN
+		  select KUTU.SEQ_testtable.nextval into :new.id from dual;
+		END;
+/
+CREATE BITMAP INDEX idx ON KUTU.testtable (firstname,lastname);
+/
+CREATE INDEX idx2 ON KUTU.testtable (price,lastname);
+/
+ALTER TABLE testtable ADD (
+ height           NUMBER,
+ weight           NUMBER);
+/
+ALTER TABLE testtable MODIFY(
+ height           NUMBER NOT NULL,
+ weight           NUMBER NOT NULL);
+/
+
+
+--------------------------------------------------------------------------------
+
+postgres
+AlterColumnSQL not supported for PostgreSQL
+
+
+CREATE DATABASE KUTU LOCATION='/u01/postdata';
+DROP TABLE KUTU.testtable;
+CREATE TABLE KUTU.testtable (
+id               SERIAL,
+firstname        VARCHAR(30) DEFAULT 'Joan',
+lastname         VARCHAR(28) DEFAULT 'Chen' NOT NULL,
+averylonglongfieldname TEXT NOT NULL,
+price            NUMERIC(7,2) DEFAULT 0.00 NOT NULL,
+MYDATE           DATE DEFAULT CURRENT_DATE,
+                 PRIMARY KEY (id, lastname)
+);
+CREATE INDEX idx ON KUTU.testtable USING HASH (firstname,lastname);
+CREATE INDEX idx2 ON KUTU.testtable (price,lastname);
+ALTER TABLE KUTU.testtable  ADD height           FLOAT8;
+ALTER TABLE KUTU.testtable  ADD weight           FLOAT8;
+
+
+--------------------------------------------------------------------------------
+
+odbc_mssql
+
+CREATE DATABASE KUTU;
+DROP TABLE KUTU.testtable;
+CREATE TABLE KUTU.testtable (
+id               INT IDENTITY(1,1) NOT NULL,
+firstname        VARCHAR(30) DEFAULT 'Joan',
+lastname         VARCHAR(28) DEFAULT 'Chen' NOT NULL,
+averylonglongfieldname TEXT NOT NULL,
+price            NUMERIC(7,2) DEFAULT 0.00 NOT NULL,
+MYDATE           DATETIME DEFAULT GetDate(),
+                 PRIMARY KEY (id, lastname)
+);
+CREATE CLUSTERED INDEX idx ON KUTU.testtable (firstname,lastname);
+CREATE INDEX idx2 ON KUTU.testtable (price,lastname);
+ALTER TABLE KUTU.testtable  ADD
+ height           REAL,
+ weight           REAL;
+ALTER TABLE KUTU.testtable  ALTER COLUMN height           REAL NOT NULL;
+ALTER TABLE KUTU.testtable  ALTER COLUMN weight           REAL NOT NULL;
+
+
+--------------------------------------------------------------------------------
+*/
+
+
+echo "<h1>Test XML Schema</h1>";
+$ff = file('xmlschema.xml');
+echo "<pre>";
+foreach($ff as $xml) echo htmlspecialchars($xml);
+echo "</pre>";
+include_once('test-xmlschema.php');
+?>
Index: /Dev/trunk/rdfapi/util/adodb/tests/test-perf.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/tests/test-perf.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/tests/test-perf.php	(revision 12)
@@ -0,0 +1,50 @@
+<?php
+
+include_once('../adodb-perf.inc.php');
+
+error_reporting(E_ALL);
+session_start();
+
+if (isset($_GET)) {
+	foreach($_GET as $k => $v) {
+		if (strncmp($k,'test',4) == 0) $_SESSION['_db'] = $k;
+	}
+} 
+
+if (isset($_SESSION['_db'])) {
+	$_db = $_SESSION['_db'];
+	$_GET[$_db] = 1;
+	$$_db = 1;
+}
+
+echo "<h1>Performance Monitoring</h1>";
+include_once('testdatabases.inc.php');
+
+
+function testdb($db) 
+{
+	if (!$db) return;
+	echo "<font size=1>";print_r($db->ServerInfo()); echo " user=".$db->user."</font>";
+	
+	$perf = NewPerfMonitor($db); 
+	
+	# unit tests
+	if (0) {
+		//$DB->debug=1;
+		echo "Data Cache Size=".$perf->DBParameter('data cache size').'<p>';
+		echo $perf->HealthCheck();
+		echo($perf->SuspiciousSQL());
+		echo($perf->ExpensiveSQL());
+		echo($perf->InvalidSQL());
+		echo $perf->Tables();
+	
+		echo "<pre>";
+		echo $perf->HealthCheckCLI();
+		$perf->Poll(3);
+		die();
+	}
+	
+	if ($perf) $perf->UI(3);
+}
+ 
+?>
Index: /Dev/trunk/rdfapi/util/adodb/tests/test-pgblob.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/tests/test-pgblob.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/tests/test-pgblob.php	(revision 12)
@@ -0,0 +1,88 @@
+<?php
+
+function getmicrotime()
+{
+	$t = microtime();
+	$t = explode(' ',$t);
+	return (float)$t[1]+ (float)$t[0];
+}
+
+function doloop()
+{
+global $db,$MAX;
+	
+	$sql = "select id,firstname,lastname from adoxyz where 
+		firstname not like ? and lastname not like ? and id=?";
+	$offset = 0;
+	/*$sql = "select * from juris9.employee join juris9.emp_perf_plan on epp_empkey = emp_id 
+		where emp_name not like ? and emp_name not like ? and emp_id=28000+?";
+	$offset = 28000;*/
+	for ($i=1; $i <= $MAX; $i++) {
+		$db->Param(false);
+		$x = (rand() % 10) + 1;
+		$db->debug= ($i==1);
+		$id = $db->GetOne($sql,
+			array('Z%','Z%',$x));
+		if($id != $offset+$x) {
+			print "<p>Error at $x";
+			break;
+		}
+	}
+}
+
+include_once('../adodb.inc.php');
+$db = NewADOConnection('postgres7');
+$db->PConnect('localhost','tester','test','test') || die("failed connection");
+
+$enc = "GIF89a%01%00%01%00%80%FF%00%C0%C0%C0%00%00%00%21%F9%04%01%00%00%00%00%2C%00%00%00%00%01%00%01%00%00%01%012%00%3Bt_clear.gif%0D";
+$val = rawurldecode($enc);
+
+$MAX = 1000;
+
+adodb_pr($db->ServerInfo());
+
+echo "<h4>Testing PREPARE/EXECUTE PLAN</h4>";
+
+
+$db->_bindInputArray = true; // requires postgresql 7.3+ and ability to modify database
+$t = getmicrotime();
+doloop();
+echo '<p>',$MAX,' times, with plan=',getmicrotime() - $t,'</p>';
+
+
+$db->_bindInputArray = false;
+$t = getmicrotime();
+doloop();
+echo '<p>',$MAX,' times, no plan=',getmicrotime() - $t,'</p>';
+
+
+
+echo "<h4>Testing UPDATEBLOB</h4>";
+$db->debug=1;
+
+### TEST BEGINS
+
+$db->Execute("insert into photos (id,name) values(9999,'dot.gif')");
+$db->UpdateBlob('photos','photo',$val,'id=9999');
+$v = $db->GetOne('select photo from photos where id=9999');
+
+
+### CLEANUP
+
+$db->Execute("delete from photos where id=9999");
+
+### VALIDATION
+
+if ($v !== $val) echo "<b>*** ERROR: Inserted value does not match downloaded val<b>";
+else echo "<b>*** OK: Passed</b>";
+
+echo "<pre>";
+echo "INSERTED: ", $enc;
+echo "<hr />";
+echo"RETURNED: ", rawurlencode($v);
+echo "<hr /><p>";
+echo "INSERTED: ", $val;
+echo "<hr />";
+echo "RETURNED: ", $v;
+
+?>
Index: /Dev/trunk/rdfapi/util/adodb/tests/test-php5.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/tests/test-php5.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/tests/test-php5.php	(revision 12)
@@ -0,0 +1,108 @@
+<?php
+/*
+  V4.81 3 May 2006  (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence.
+  Set tabs to 8.
+ */
+
+
+error_reporting(E_ALL);
+
+$path = dirname(__FILE__);
+
+include("$path/../adodb-exceptions.inc.php");
+include("$path/../adodb.inc.php");	
+
+echo "<h3>PHP ".PHP_VERSION."</h3>\n";
+try {
+
+$dbt = 'mysql';
+
+try {
+switch($dbt) {
+case 'oci8po':
+	$db = NewADOConnection("oci8po");
+	
+	$db->Connect('','scott','natsoft');
+	break;
+default:
+case 'mysql':
+	$db = NewADOConnection("mysql");
+	$db->Connect('localhost','root','','northwind');
+	break;
+	
+case 'mysqli':
+	$db = NewADOConnection("mysqli://root:@localhost/northwind");
+	//$db->Connect('localhost','root','','test');
+	break;
+}
+} catch (exception $e){
+	echo "Connect Failed";
+	adodb_pr($e);
+	die();
+}
+
+$db->debug=1;
+
+$cnt = $db->GetOne("select count(*) from adoxyz where ?<id and id<?",array(10,20));
+$stmt = $db->Prepare("select * from adoxyz where ?<id and id<?");
+if (!$stmt) echo $db->ErrorMsg(),"\n";
+$rs = $db->Execute($stmt,array(10,20));
+
+echo  "<hr /> Foreach Iterator Test (rand=".rand().")<hr />";
+$i = 0;
+foreach($rs as $v) {
+	$i += 1;
+	echo "rec $i: "; $s1 = adodb_pr($v,true); $s2 = adodb_pr($rs->fields,true);
+	if ($s1 != $s2 && !empty($v)) {adodb_pr($s1); adodb_pr($s2);}
+	else echo "passed<br>";
+	flush();
+}
+
+
+if ($i != $cnt) die("actual cnt is $i, cnt should be $cnt\n");
+else echo "Count $i is correct<br>";
+
+$rs = $db->Execute("select bad from badder");
+
+} catch (exception $e) {
+	adodb_pr($e);
+	echo "<h3>adodb_backtrace:</h3>\n";
+	$e = adodb_backtrace($e->gettrace());
+}
+
+$rs = $db->Execute("select distinct id, firstname,lastname from adoxyz order by id");
+echo "Result=\n",$rs,"</p>";
+
+echo "<h3>Active Record</h3>";
+try {
+	include_once("../adodb-active-record.inc.php");
+	class City extends ADOdb_Active_Record{};
+	$a = new City();
+
+} catch(exception $e){
+	echo $e->getMessage();
+}
+
+try {
+	
+	ADOdb_Active_Record::SetDatabaseAdapter($db);
+	$a = new City();
+	
+	echo "<p>Successfully created City()<br>";
+	var_dump($a->GetPrimaryKeys());
+	$a->city = 'Kuala Lumpur';
+	$a->Save();
+	$a->Update();
+	$a->SetPrimaryKeys(array('city'));	
+	$a->country = "M'sia";
+	$a->save();
+	$a->Delete();
+} catch(exception $e){
+	echo $e->getMessage();
+}
+
+include_once("test-active-record.php");
+?>
Index: /Dev/trunk/rdfapi/util/adodb/tests/test-xmlschema.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/tests/test-xmlschema.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/tests/test-xmlschema.php	(revision 12)
@@ -0,0 +1,54 @@
+<?PHP
+
+// V4.50 6 July 2004
+
+error_reporting(E_ALL);
+include_once( "../adodb.inc.php" );
+include_once( "../adodb-xmlschema03.inc.php" );
+
+// To build the schema, start by creating a normal ADOdb connection:
+$db = ADONewConnection( 'mysql' );
+$db->Connect( 'localhost', 'root', '', 'test' ) || die('fail connect1');
+
+// To create a schema object and build the query array.
+$schema = new adoSchema( $db );
+
+// To upgrade an existing schema object, use the following 
+// To upgrade an existing database to the provided schema,
+// uncomment the following line:
+#$schema->upgradeSchema();
+
+print "<b>SQL to build xmlschema.xml</b>:\n<pre>";
+// Build the SQL array
+$sql = $schema->ParseSchema( "xmlschema.xml" );
+
+var_dump( $sql );
+print "</pre>\n";
+
+// Execute the SQL on the database
+//$result = $schema->ExecuteSchema( $sql );
+
+// Finally, clean up after the XML parser
+// (PHP won't do this for you!)
+//$schema->Destroy();
+
+
+
+print "<b>SQL to build xmlschema-mssql.xml</b>:\n<pre>";
+
+$db2 = ADONewConnection('mssql');
+$db2->Connect('','adodb','natsoft','northwind') || die("Fail 2");
+
+$db2->Execute("drop table simple_table");
+
+$schema = new adoSchema( $db2 );
+$sql = $schema->ParseSchema( "xmlschema-mssql.xml" );
+
+print_r( $sql );
+print "</pre>\n";
+
+$db2->debug=1;
+
+foreach ($sql as $s)
+$db2->Execute($s);
+?>
Index: /Dev/trunk/rdfapi/util/adodb/tests/test.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/tests/test.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/tests/test.php	(revision 12)
@@ -0,0 +1,1743 @@
+<?php
+/* 
+V4.80 8 Mar 2006  (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence. 
+  Set tabs to 4 for best viewing.
+	
+  Latest version is available at http://adodb.sourceforge.net
+*/
+
+
+if (!defined('E_STRICT')) define('E_STRICT',0);
+error_reporting(E_ALL|E_STRICT);
+
+$ADODB_FLUSH = true;
+
+define('ADODB_ASSOC_CASE',0);
+
+
+function getmicrotime()
+{
+	$t = microtime();
+	$t = explode(' ',$t);
+	return (float)$t[1]+ (float)$t[0];
+}
+
+
+if (PHP_VERSION < 5) include_once('../adodb-pear.inc.php');
+//--------------------------------------------------------------------------------------
+//define('ADODB_ASSOC_CASE',1);
+//
+function Err($msg)
+{
+	print "<b>$msg</b><br>";
+	flush();
+}
+
+function CheckWS($conn)
+{
+global $ADODB_EXTENSION;
+
+	include_once('../session/adodb-session.php');
+	if (defined('CHECKWSFAIL')){ echo " TESTING $conn ";flush();}
+	$saved = $ADODB_EXTENSION;
+	$db = ADONewConnection($conn);
+	$ADODB_EXTENSION = $saved;
+	if (headers_sent()) {
+		print "<p><b>White space detected in adodb-$conn.inc.php or include file...</b></p>";
+		//die();
+	}
+}
+
+function do_strtolower(&$arr)
+{
+	foreach($arr as $k => $v) {
+		if (is_object($v)) $arr[$k] = adodb_pr($v,true);
+		else $arr[$k] = strtolower($v);
+	}
+}
+
+
+function CountExecs($db, $sql, $inputarray)
+{
+global $EXECS;  $EXECS++;
+}
+
+function CountCachedExecs($db, $secs2cache, $sql, $inputarray)
+{
+global $CACHED; $CACHED++;
+}
+
+// the table creation code is specific to the database, so we allow the user 
+// to define their own table creation stuff
+
+function testdb(&$db,$createtab="create table ADOXYZ (id int, firstname char(24), lastname char(24), created date)")
+{
+GLOBAL $ADODB_vers,$ADODB_CACHE_DIR,$ADODB_FETCH_MODE,$ADODB_COUNTRECS;
+
+	//adodb_pr($db);
+	
+?>	<form method=GET>
+	</p>
+	<table width=100% ><tr><td bgcolor=beige>&nbsp;</td></tr></table>
+	</p>
+<?php  
+	$create =false;
+	/*$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
+	
+	$rs = $db->Execute('select lastname,firstname,lastname,id from ADOXYZ');
+	$arr = $rs->GetAssoc();
+	echo "<pre>";print_r($arr);
+	die();*/
+	
+	if (!$db) die("testdb: database not inited");
+	GLOBAL $EXECS, $CACHED;
+	
+	$EXECS = 0;
+	$CACHED = 0;
+	//$db->Execute("drop table adodb_logsql");
+	if ((rand()%3) == 0) @$db->Execute("delete from adodb_logsql");
+	$db->debug=1;
+	
+	$db->fnExecute = 'CountExecs';
+	$db->fnCacheExecute = 'CountCachedExecs';
+	
+	if (empty($_GET['nolog'])) {
+		echo "<h3>SQL Logging enabled</h3>";
+		$db->LogSQL();/*
+		$sql =
+"SELECT t1.sid, t1.sid, t1.title, t1.hometext, t1.notes, t1.aid, t1.informant, 
+t2.url, t2.email, t1.catid, t3.title, t1.topic, t4.topicname, t4.topicimage, 
+t4.topictext, t1.score, t1.ratings, t1.counter, t1.comments, t1.acomm 
+FROM `nuke_stories` `t1`, `nuke_authors` `t2`, `nuke_stories_cat` `t3`, `nuke_topics` `t4` 
+	WHERE ((t2.aid=t1.aid) AND (t3.catid=t1.catid) AND (t4.topicid=t1.topic) 
+	AND ((t1.alanguage='german') OR (t1.alanguage='')) AND (t1.ihome='0')) 
+	ORDER BY t1.time DESC";
+		$db->SelectLimit($sql);
+		echo $db->ErrorMsg();*/
+	}
+	$ADODB_CACHE_DIR = dirname(TempNam('/tmp','testadodb'));
+	$db->debug = false;
+	//print $db->UnixTimeStamp('2003-7-22 23:00:00');
+	
+	$phpv = phpversion();
+	if (defined('ADODB_EXTENSION')) $ext = ' &nbsp; Extension '.ADODB_EXTENSION.' installed';
+	else $ext = '';
+	print "<h3>ADODB Version: $ADODB_vers Host: <i>$db->host</i> &nbsp; Database: <i>$db->database</i> &nbsp; PHP: $phpv $ext</h3>";
+	
+	flush();
+
+	if (function_exists('date_default_timezone_set')) date_default_timezone_set('Asia/Kuala_Lumpur');
+	
+	$arr = $db->ServerInfo();
+	print_r($arr);
+	echo E_ALL,' ',E_STRICT, "<br>";
+	$e = error_reporting(E_ALL | E_STRICT);
+	echo error_reporting(),'<p>';
+	flush();
+	#$db->debug=1;
+	$tt  = $db->Time(); 
+	if ($tt == 0) echo '<br><b>$db->Time failed</b>';
+	else echo "<br>db->Time: ".date('d-m-Y H:i:s',$tt);
+	echo '<br>';
+	
+	echo "Date=",$db->UserDate('2002-04-07'),'<br>';
+	print "<i>date1</i> (1969-02-20) = ".$db->DBDate('1969-2-20');
+	print "<br><i>date1</i> (1999-02-20) = ".$db->DBDate('1999-2-20');
+	print "<br><i>date1.1</i> 1999 = ".$db->DBDate("'1999'");
+	print "<br><i>date2</i> (1970-1-2) = ".$db->DBDate(24*3600)."<p>";
+	print "<i>ts1</i> (1999-02-20 13:40:50) = ".$db->DBTimeStamp('1999-2-20 1:40:50 pm');
+	print "<br><i>ts1.1</i> (1999-02-20 13:40:00) = ".$db->DBTimeStamp('1999-2-20 13:40');
+	print "<br><i>ts2</i> (1999-02-20) = ".$db->DBTimeStamp('1999-2-20');
+	print "<br><i>ts3</i> (1970-1-2 +/- timezone) = ".$db->DBTimeStamp(24*3600);
+	print "<br> Fractional TS (1999-2-20 13:40:50.91): ".$db->DBTimeStamp($db->UnixTimeStamp('1999-2-20 13:40:50.91+1'));
+	 $dd = $db->UnixDate('1999-02-20');
+	print "<br>unixdate</i> 1999-02-20 = ".date('Y-m-d',$dd)."<p>";
+	print "<br><i>ts4</i> =".($db->UnixTimeStamp("19700101000101")+8*3600);
+	print "<br><i>ts5</i> =".$db->DBTimeStamp($db->UnixTimeStamp("20040110092123"));
+	print "<br><i>ts6</i> =".$db->UserTimeStamp("20040110092123");
+	print "<br><i>ts7</i> =".$db->DBTimeStamp("20040110092123");
+	flush();
+	// mssql too slow in failing bad connection
+	if (false && $db->databaseType != 'mssql') {
+		print "<p>Testing bad connection. Ignore following error msgs:<br>";
+		$db2 = ADONewConnection();
+		$rez = $db2->Connect("bad connection");
+		$err = $db2->ErrorMsg();
+		print "<i>Error='$err'</i></p>";
+		if ($rez) print "<b>Cannot check if connection failed.</b> The Connect() function returned true.</p>";
+	}
+	#error_reporting($e);
+	flush();
+
+	//$ADODB_COUNTRECS=false;
+	$rs=$db->Execute('select * from ADOXYZ order by id');
+	if($rs === false) $create = true;
+	else $rs->Close();
+	
+	//if ($db->databaseType !='vfp') $db->Execute("drop table ADOXYZ");
+	
+	if ($create) {
+		if (false && $db->databaseType == 'ibase') {
+			print "<b>Please create the following table for testing:</b></p>$createtab</p>";
+			return;
+		} else {
+			$db->debug = 99;
+		#	$e = error_reporting(E_ALL-E_WARNING);
+			$db->Execute($createtab);
+		#	error_reporting($e);
+		}
+	}
+	#error_reporting(E_ALL);
+	echo "<p>Testing Metatypes</p>";
+	$t = $db->MetaType('varchar');
+	if ($t != 'C') Err("Bad Metatype for varchar");
+	
+	$rs = $db->Execute("delete from ADOXYZ"); // some ODBC drivers will fail the drop so we delete
+	if ($rs) {
+		if(! $rs->EOF) print "<b>Error: </b>RecordSet returned by Execute('delete...') should show EOF</p>";
+		$rs->Close();
+	} else print "err=".$db->ErrorMsg();
+
+	print "<p>Test select on empty table, FetchField when EOF, and GetInsertSQL</p>";
+	$rs = $db->Execute("select id,firstname from ADOXYZ where id=9999");
+	if ($rs && !$rs->EOF) print "<b>Error: </b>RecordSet returned by Execute(select...') on empty table should show EOF</p>";
+	if ($rs->EOF && (($ox = $rs->FetchField(0)) && !empty($ox->name))) {
+		$record['id'] = 99;
+		$record['firstname'] = 'John';
+		$sql =  $db->GetInsertSQL($rs, $record);
+		if (strtoupper($sql) != strtoupper("INSERT INTO ADOXYZ ( id, firstname ) VALUES ( 99, 'John' )")) Err("GetInsertSQL does not work on empty table: $sql");
+	} else {
+		Err("FetchField does not work on empty recordset, meaning GetInsertSQL will fail...");
+	}
+	if ($rs) $rs->Close();
+	flush();
+	//$db->debug=true;	
+	print "<p>Testing Commit: ";
+	$time = $db->DBDate(time());
+	if (!$db->BeginTrans()) {
+		print '<b>Transactions not supported</b></p>';
+		if ($db->hasTransactions) Err("hasTransactions should be false");
+	} else { /* COMMIT */
+		if (!$db->hasTransactions) Err("hasTransactions should be true");
+		if ($db->transCnt != 1) Err("Invalid transCnt = $db->transCnt (should be 1)");
+		$rs = $db->Execute("insert into ADOXYZ (id,firstname,lastname,created) values (99,'Should Not','Exist (Commit)',$time)");
+		if ($rs && $db->CommitTrans()) {
+			$rs->Close();
+			$rs = $db->Execute("select * from ADOXYZ where id=99");
+			if ($rs === false || $rs->EOF) {
+				print '<b>Data not saved</b></p>';
+				$rs = $db->Execute("select * from ADOXYZ where id=99");
+				print_r($rs);
+				die();
+			} else print 'OK</p>';
+			if ($rs) $rs->Close();
+		} else {
+			if (!$rs) {
+				print "<b>Insert failed</b></p>";
+				$db->RollbackTrans();
+			} else print "<b>Commit failed</b></p>";
+		}
+		if ($db->transCnt != 0) Err("Invalid transCnt = $db->transCnt (should be 0)");
+		
+		/* ROLLBACK */	
+		if (!$db->BeginTrans()) print "<p><b>Error in BeginTrans</b>()</p>";
+		print "<p>Testing Rollback: ";
+		$db->Execute("insert into ADOXYZ (id,firstname,lastname,created) values (100,'Should Not','Exist (Rollback)',$time)");
+		if ($db->RollbackTrans()) {
+			$rs = $db->Execute("select * from ADOXYZ where id=100");
+			if ($rs && !$rs->EOF) print '<b>Fail: Data should rollback</b></p>';
+			else print 'OK</p>';
+			if ($rs) $rs->Close();
+		} else
+			print "<b>Commit failed</b></p>";
+			
+		$rs = $db->Execute('delete from ADOXYZ where id>50');
+		if ($rs) $rs->Close();
+		
+		if ($db->transCnt != 0) Err("Invalid transCnt = $db->transCnt (should be 0)");
+	}
+	
+	if (1) {
+		print "<p>Testing MetaDatabases()</p>";
+		print_r( $db->MetaDatabases());
+
+		print "<p>Testing MetaTables() and MetaColumns()</p>";
+		$a = $db->MetaTables();
+		if ($a===false) print "<b>MetaTables not supported</b></p>";
+		else {
+			print "Array of tables and views: "; 
+			foreach($a as $v) print " ($v) ";
+			print '</p>';
+		}
+		
+		$a = $db->MetaTables('VIEW');
+		if ($a===false) print "<b>MetaTables not supported (views)</b></p>";
+		else {
+			print "Array of views: "; 
+			foreach($a as $v) print " ($v) ";
+			print '</p>';
+		}
+		
+		$a = $db->MetaTables(false,false,'aDo%');
+		if ($a===false) print "<b>MetaTables not supported (mask)</b></p>";
+		else {
+			print "Array of ado%: "; 
+			foreach($a as $v) print " ($v) ";
+			print '</p>';
+		}
+		
+		$a = $db->MetaTables('TABLE');
+		if ($a===false) print "<b>MetaTables not supported</b></p>";
+		else {
+			print "Array of tables: "; 
+			foreach($a as $v) print " ($v) ";
+			print '</p>';
+		}
+		
+		$db->debug=0;
+		$rez = $db->MetaColumns("NOSUCHTABLEHERE");
+		if ($rez !== false) {
+			Err("MetaColumns error handling failed");
+			var_dump($rez);
+		}
+		$db->debug=1;
+		$a = $db->MetaColumns('ADOXYZ');
+		if ($a===false) print "<b>MetaColumns not supported</b></p>";
+		else {
+			print "<p>Columns of ADOXYZ: <font size=1><br>";
+			foreach($a as $v) {print_r($v); echo "<br>";}
+			echo "</font>";
+		}
+		
+		print "<p>Testing MetaIndexes</p>";
+		
+		$a = $db->MetaIndexes(('ADOXYZ'),true);
+		if ($a===false) print "<b>MetaIndexes not supported</b></p>";
+		else {
+			print "<p>Indexes of ADOXYZ: <font size=1><br>";
+			adodb_pr($a);
+			echo "</font>";
+		}
+		print "<p>Testing MetaPrimaryKeys</p>";
+		$a = $db->MetaPrimaryKeys('ADOXYZ');
+		var_dump($a);
+	}
+	$rs = $db->Execute('delete from ADOXYZ');
+	if ($rs) $rs->Close();
+	
+	$db->debug = false;
+	
+	
+	switch ($db->databaseType) {
+	case 'vfp':
+		
+		if (0) {
+			// memo test
+			$rs = $db->Execute("select data from memo");
+			rs2html($rs);
+		}
+		break;
+
+	case 'postgres7':
+	case 'postgres64':
+	case 'postgres':
+	case 'ibase':
+		print "<p>Encode=".$db->BlobEncode("abc\0d\"'
+ef")."</p>";//'
+
+		print "<p>Testing Foreign Keys</p>";
+		$arr = $db->MetaForeignKeys('ADOXYZ',false,true);
+		print_r($arr);
+		if (!$arr) Err("No MetaForeignKeys");
+		break;
+	
+	case 'odbc_mssql':
+	case 'mssqlpo':
+		print "<p>Testing Foreign Keys</p>";
+		$arr = $db->MetaForeignKeys('Orders',false,true);
+		print_r($arr);
+		if (!$arr) Err("Bad MetaForeignKeys");
+		if ($db->databaseType == 'odbc_mssql') break;
+	
+	case 'mssql': 
+	
+		
+/*
+ASSUME Northwind available...
+
+CREATE PROCEDURE SalesByCategory
+	@CategoryName nvarchar(15), @OrdYear nvarchar(4) = '1998'
+AS
+IF @OrdYear != '1996' AND @OrdYear != '1997' AND @OrdYear != '1998' 
+BEGIN
+	SELECT @OrdYear = '1998'
+END
+
+SELECT ProductName,
+	TotalPurchase=ROUND(SUM(CONVERT(decimal(14,2), OD.Quantity * (1-OD.Discount) * OD.UnitPrice)), 0)
+FROM [Order Details] OD, Orders O, Products P, Categories C
+WHERE OD.OrderID = O.OrderID 
+	AND OD.ProductID = P.ProductID 
+	AND P.CategoryID = C.CategoryID
+	AND C.CategoryName = @CategoryName
+	AND SUBSTRING(CONVERT(nvarchar(22), O.OrderDate, 111), 1, 4) = @OrdYear
+GROUP BY ProductName
+ORDER BY ProductName
+GO
+
+
+CREATE PROCEDURE ADODBTestSP
+@a nvarchar(25)
+AS
+SELECT GETDATE() AS T, @a AS A
+GO
+*/
+		print "<h4>Testing Stored Procedures for mssql</h4>";
+		$saved = $db->debug;
+		$db->debug=true;
+		$assoc = $ADODB_FETCH_MODE;
+		$ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
+		$cmd = $db->PrepareSP('ADODBTestSP');
+		$ss = "You should see me in the output.";
+		$db->InParameter($cmd,$ss,'a');
+		$rs = $db->Execute($cmd);
+		#var_dump($rs->fields);
+		echo $rs->fields['T']." --- ".$rs->fields['A']."---<br>";
+
+		$cat = 'Dairy Products';
+		$yr = '1998';
+		
+		$stmt = $db->PrepareSP('SalesByCategory');
+		$db->InParameter($stmt,$cat,'CategoryName');
+		$db->InParameter($stmt,$yr,'OrdYear');
+		$rs = $db->Execute($stmt);
+		rs2html($rs);
+		
+		$cat = 'Grains/Cereals';
+		$yr = 1998;
+		
+		$stmt = $db->PrepareSP('SalesByCategory');
+		$db->InParameter($stmt,$cat,'CategoryName');
+		$db->InParameter($stmt,$yr,'OrdYear');
+		$rs = $db->Execute($stmt);
+		rs2html($rs);
+		
+		$ADODB_FETCH_MODE = $assoc;
+		
+		/*
+		Test out params - works in PHP 4.2.3 and 4.3.3 and 4.3.8 but not 4.3.0:
+		
+			CREATE PROCEDURE at_date_interval 
+				@days INTEGER, 
+				@start VARCHAR(20) OUT, 
+				@end VARCHAR(20) OUT 	
+			AS 
+			BEGIN 
+				set @start = CONVERT(VARCHAR(20), getdate(), 101) 
+				set @end =CONVERT(VARCHAR(20), dateadd(day, @days, getdate()), 101 ) 
+			END
+			GO
+		*/
+		$db->debug=1;
+		$stmt = $db->PrepareSP('at_date_interval');
+		$days = 10;
+		$begin_date = '';
+		$end_date = '';
+		$db->InParameter($stmt,$days,'days', 4, SQLINT4); 
+		$db->OutParameter($stmt,$begin_date,'start', 20, SQLVARCHAR ); 
+		$db->OutParameter($stmt,$end_date,'end', 20, SQLVARCHAR ); 
+		$db->Execute($stmt);
+		if (empty($begin_date) or empty($end_date) or $begin_date == $end_date) {
+			Err("MSSQL SP Test for OUT Failed");
+			print "begin=$begin_date end=$end_date<p>";
+		} else print "(Today +10days) = (begin=$begin_date end=$end_date)<p>";
+	
+		$db->debug = $saved;
+		break;
+	case 'oci8': 
+	case 'oci8po':
+		
+		if (0) {
+		$t = getmicrotime();
+		$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
+		$arr = $db->GetArray('select * from abalone_tree');
+		$arr = $db->GetArray('select * from abalone_tree');
+		$arr = $db->GetArray('select * from abalone_tree');
+		echo "<p>t = ",getmicrotime() - $t,"</p>";
+		die();
+		}
+		
+		# cleanup
+		$db->Execute("delete from photos where id=99 or id=1");
+		$db->Execute("insert into photos (id) values(1)");
+		$db->Execute("update photos set photo=null,descclob=null where id=1");
+		
+		$saved = $db->debug;
+		$db->debug=true;
+		
+		
+
+		/*
+		CREATE TABLE PHOTOS
+		(
+		  ID           NUMBER(16),
+		  PHOTO        BLOB,
+		  DESCRIPTION  VARCHAR2(4000 BYTE),
+		  DESCCLOB     CLOB
+		);
+		
+		INSERT INTO PHOTOS (ID) VALUES(1);
+		*/
+		$s = '';
+		for ($i = 0; $i <= 500; $i++) {
+			$s .= '1234567890';
+		}
+		
+		$sql = "INSERT INTO photos ( ID, photo) ".
+			"VALUES ( :id, empty_blob() )".
+			" RETURNING photo INTO :xx";
+
+		
+		$blob_data = $s;
+		$id = 99;
+		
+ 		$stmt = $db->PrepareSP($sql);
+		$db->InParameter($stmt, $id, 'id');
+		$blob = $db->InParameter($stmt, $s, 'xx',-1, OCI_B_BLOB);
+		$db->StartTrans();
+		$result = $db->Execute($stmt);
+		$db->CompleteTrans();
+		
+		$s2= $db->GetOne("select photo from photos where id=99");
+		echo "<br>---$s2";
+		if ($s !== $s2) Err("insert blob does not match");
+
+		print "<h4>Testing Blob: size=".strlen($s)."</h4>";
+		$ok = $db->Updateblob('photos','photo',$s,'id=1');
+		if (!$ok) Err("Blob failed 1");
+		else {
+			$s2= $db->GetOne("select photo from photos where id=1");
+			if ($s !== $s2) Err("updateblob does not match");
+		}
+		
+		print "<h4>Testing Clob: size=".strlen($s)."</h4>";
+		$ok = $db->UpdateClob('photos','descclob',$s,'id=1');
+		if (!$ok) Err("Clob failed 1");
+		else {
+			$s2= $db->GetOne("select descclob from photos where id=1");
+			if ($s !== $s2) Err("updateclob does not match");
+		}
+		
+		
+		$s = '';
+		$s2 = '';
+		print "<h4>Testing Foreign Keys</h4>";
+		$arr = $db->MetaForeignKeys('emp','scott');
+		print_r($arr);
+		if (!$arr) Err("Bad MetaForeignKeys");
+/*
+-- TEST PACKAGE
+-- "Set scan off" turns off substitution variables. 
+Set scan off; 
+
+CREATE OR REPLACE PACKAGE Adodb AS
+TYPE TabType IS REF CURSOR RETURN TAB%ROWTYPE;
+PROCEDURE open_tab (tabcursor IN OUT TabType,tablenames IN VARCHAR);
+PROCEDURE open_tab2 (tabcursor IN OUT TabType,tablenames IN OUT VARCHAR) ;
+PROCEDURE data_out(input IN VARCHAR, output OUT VARCHAR);
+PROCEDURE data_in(input IN VARCHAR);
+PROCEDURE myproc (p1 IN NUMBER, p2 OUT NUMBER);
+END Adodb;
+/
+
+
+CREATE OR REPLACE PACKAGE BODY Adodb AS
+PROCEDURE open_tab (tabcursor IN OUT TabType,tablenames IN VARCHAR) IS
+	BEGIN
+		OPEN tabcursor FOR SELECT * FROM TAB WHERE tname LIKE tablenames;
+	END open_tab;
+
+	PROCEDURE open_tab2 (tabcursor IN OUT TabType,tablenames IN OUT VARCHAR) IS
+	BEGIN
+		OPEN tabcursor FOR SELECT * FROM TAB WHERE tname LIKE tablenames;
+		tablenames := 'TEST';
+	END open_tab2;
+
+PROCEDURE data_out(input IN VARCHAR, output OUT VARCHAR) IS
+	BEGIN
+		output := 'Cinta Hati '||input;
+	END;
+	
+PROCEDURE data_in(input IN VARCHAR) IS
+	ignore varchar(1000);
+	BEGIN
+		ignore := input;
+	END;
+
+PROCEDURE myproc (p1 IN NUMBER, p2 OUT NUMBER) AS
+BEGIN
+p2 := p1;
+END;
+END Adodb;
+/
+
+*/
+
+		print "<h4>Testing Cursor Variables</h4>";
+		$rs = $db->ExecuteCursor("BEGIN adodb.open_tab(:zz,'A%'); END;",'zz');
+	
+		if ($rs && !$rs->EOF) {
+			$v = $db->GetOne("SELECT count(*) FROM tab where tname like 'A%'");
+			if ($v == $rs->RecordCount()) print "Test 1 RowCount: OK<p>";
+			else Err("Test 1 RowCount ".$rs->RecordCount().", actual = $v");
+		} else {
+			print "<b>Error in using Cursor Variables 1</b><p>";
+		}
+		$rs->Close();
+		
+		print "<h4>Testing Stored Procedures for oci8</h4>";
+		
+		$stmt = $db->PrepareSP("BEGIN adodb.data_out(:a1, :a2); END;");
+		$a1 = 'Malaysia';
+		//$a2 = ''; # a2 doesn't even need to be defined!
+		$db->InParameter($stmt,$a1,'a1');
+		$db->OutParameter($stmt,$a2,'a2');
+		$rs = $db->Execute($stmt);
+		if ($rs) {
+			if ($a2 !== 'Cinta Hati Malaysia') print "<b>Stored Procedure Error: a2 = $a2</b><p>";
+			else echo  "OK: a2=$a2<p>";
+		} else {
+			print "<b>Error in using Stored Procedure IN/Out Variables</b><p>";
+		}
+		
+		$tname = 'A%';
+		
+		$stmt = $db->PrepareSP('select * from tab where tname like :tablename');
+		$db->Parameter($stmt,$tname,'tablename');
+		$rs = $db->Execute($stmt);
+		rs2html($rs);
+		
+		$stmt = $db->PrepareSP("begin adodb.data_in(:a1); end;");
+		$db->InParameter($stmt,$a1,'a1');
+		$db->Execute($stmt);
+		
+		$db->debug = $saved;
+		break;
+	
+	default:
+		break;
+	}
+	$arr = array(
+		array(1,'Caroline','Miranda'),
+		array(2,'John','Lim'),
+		array(3,'Wai Hun','See')
+	);
+	//$db->debug=1;
+	print "<p>Testing Bulk Insert of 3 rows</p>";
+
+	$sql = "insert into ADOXYZ (id,firstname,lastname) values (".$db->Param('0').",".$db->Param('1').",".$db->Param('2').")";
+	$db->StartTrans();
+	$db->Execute($sql,$arr);
+	$db->CompleteTrans();
+	$rs = $db->Execute('select * from ADOXYZ order by id');
+	if (!$rs || $rs->RecordCount() != 3) Err("Bad bulk insert");
+	
+	rs2html($rs);
+	
+	$db->Execute('delete from ADOXYZ');
+		
+	print "<p>Inserting 50 rows</p>";
+
+	for ($i = 0; $i < 5; $i++) {	
+
+	$time = $db->DBDate(time());
+	if (empty($_GET['hide'])) $db->debug = true;
+	switch($db->databaseType){
+	case 'mssqlpo':
+	case 'mssql':
+		$sqlt = "CREATE TABLE mytable (
+  row1 INT  IDENTITY(1,1) NOT NULL,
+  row2 varchar(16),
+  PRIMARY KEY  (row1))";
+  		//$db->debug=1;
+  		if (!$db->Execute("delete from mytable")) 
+			$db->Execute($sqlt);
+			
+		$ok = $db->Execute("insert into mytable (row2) values ('test')");
+		$ins_id=$db->Insert_ID();
+		echo "Insert ID=";var_dump($ins_id);
+		if ($ins_id == 0) Err("Bad Insert_ID()");
+		$ins_id2 = $db->GetOne("select row1 from mytable");
+		if ($ins_id != $ins_id2) Err("Bad Insert_ID() 2");
+		
+		$arr = array(0=>'Caroline',1=>'Miranda');
+		$sql = "insert into ADOXYZ (id,firstname,lastname,created) values ($i*10+0,?,?,$time)";
+		break;
+	case 'mysqli':
+	case 'mysqlt':
+	case 'mysql':
+		$sqlt = "CREATE TABLE `mytable` (
+  `row1` int(11) NOT NULL auto_increment,
+  `row2` varchar(16) NOT NULL default '',
+  PRIMARY KEY  (`row1`),
+  KEY `myindex` (`row1`,`row2`)
+) ";
+		if (!$db->Execute("delete from mytable")) 
+			$db->Execute($sqlt);
+			
+		$ok = $db->Execute("insert into mytable (row2) values ('test')");
+		$ins_id=$db->Insert_ID();
+		echo "Insert ID=";var_dump($ins_id);
+		if ($ins_id == 0) Err("Bad Insert_ID()");
+		$ins_id2 = $db->GetOne("select row1 from mytable");
+		if ($ins_id != $ins_id2) Err("Bad Insert_ID() 2");
+		
+	default:
+		$arr = array(0=>'Caroline',1=>'Miranda');
+		$sql = "insert into ADOXYZ (id,firstname,lastname,created) values ($i*10+0,?,?,$time)";
+		break;
+	
+	case 'oci8':
+	case 'oci805':
+		$arr = array('first'=>'Caroline','last'=>'Miranda');
+		$amt = rand() % 100;
+		$sql = "insert into ADOXYZ (id,firstname,lastname,created) values ($i*10+0,:first,:last,$time)";		
+		break;
+	}
+	if ($i & 1) {
+		$sql = $db->Prepare($sql);
+	}
+	$rs = $db->Execute($sql,$arr);
+		
+	if ($rs === false) Err( 'Error inserting with parameters');
+	else $rs->Close();
+	$db->debug = false;
+	$db->Execute("insert into ADOXYZ (id,firstname,lastname,created) values ($i*10+1,'John','Lim',$time)");
+	/*$ins_id=$db->Insert_ID();
+	echo "Insert ID=";var_dump($ins_id);*/
+	if ($db->databaseType == 'mysql') if ($ins_id == 0) Err('Bad Insert_ID');
+	$db->Execute("insert into ADOXYZ (id,firstname,lastname,created) values ($i*10+2,'Mary','Lamb',$time )");
+	$db->Execute("insert into ADOXYZ (id,firstname,lastname,created) values ($i*10+3,'George','Washington',$time )");
+	$db->Execute("insert into ADOXYZ (id,firstname,lastname,created) values ($i*10+4,'Mr. Alan','Tam',$time )");
+	$db->Execute("insert into ADOXYZ (id,firstname,lastname,created) values ($i*10+5,'Alan',".$db->quote("Turing'ton").",$time )");
+	$db->Execute("insert into ADOXYZ (id,firstname,lastname,created)values ($i*10+6,'Serena','Williams',$time )");
+	$db->Execute("insert into ADOXYZ (id,firstname,lastname,created) values ($i*10+7,'Yat Sun','Sun',$time )");
+	$db->Execute("insert into ADOXYZ (id,firstname,lastname,created) values ($i*10+8,'Wai Hun','See',$time )");
+	$db->Execute("insert into ADOXYZ (id,firstname,lastname,created) values ($i*10+9,'Steven','Oey',$time )");
+	} // for
+	if (1) {
+	$db->debug=1;
+	$ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
+	$cnt = $db->GetOne("select count(*) from ADOXYZ");
+	$rs = $db->Execute('update ADOXYZ set id=id+1');	
+	if (!is_object($rs)) {
+		print_r($rs);
+		err("Update should return object");
+	} 
+	if (!$rs) err("Update generated error");
+	
+	$nrows = $db->Affected_Rows();   
+	if ($nrows === false) print "<p><b>Affected_Rows() not supported</b></p>";
+	else if ($nrows != $cnt)  print "<p><b>Affected_Rows() Error: $nrows returned (should be 50) </b></p>";
+	else print "<p>Affected_Rows() passed</p>";
+	}
+	
+	if ($db->dataProvider == 'oci8')  $array = array('zid'=>1,'zdate'=>date('Y-m-d',time()));
+	else $array=array(1,date('Y-m-d',time()));
+	
+	
+	#$array = array(1,date('Y-m-d',time()));
+	$id = $db->GetOne("select id from ADOXYZ 
+		where id=".$db->Param('zid')." and created>=".$db->Param('ZDATE')."",
+		$array);
+	if ($id != 1) Err("Bad bind; id=$id");
+	else echo "<br>Bind date/integer 1 passed";
+	
+	$array =array(1,$db->BindDate(time()));
+	$id = $db->GetOne("select id from ADOXYZ 
+		where id=".$db->Param('0')." and created>=".$db->Param('1')."",
+		$array);
+	if ($id != 1) Err("Bad bind; id=$id");
+	else echo "<br>Bind date/integer 2 passed";
+	
+	$db->debug = false;
+	$ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
+ //////////////////////////////////////////////////////////////////////////////////////////
+	
+	$rs = $db->Execute("select * from ADOXYZ where firstname = 'not known'");
+	if (!$rs ||  !$rs->EOF) print "<p><b>Error on empty recordset</b></p>";
+	else if ($rs->RecordCount() != 0) {
+		print "<p><b>Error on RecordCount. Should be 0. Was ".$rs->RecordCount()."</b></p>"; 
+		print_r($rs->fields);
+	}
+	if ($db->databaseType !== 'odbc') {
+		$rs = $db->Execute("select id,firstname,lastname,created,".$db->random." from ADOXYZ order by id");
+		if ($rs) {
+			if ($rs->RecordCount() != 50) {
+				print "<p><b>RecordCount returns ".$rs->RecordCount().", should be 50</b></p>";
+				adodb_pr($rs->GetArray());
+				$poc = $rs->PO_RecordCount('ADOXYZ');
+				if ($poc == 50) print "<p> &nbsp; &nbsp; PO_RecordCount passed</p>";
+				else print "<p><b>PO_RecordCount returns wrong value: $poc</b></p>";
+			} else print "<p>RecordCount() passed</p>";
+			if (isset($rs->fields['firstname'])) print '<p>The fields columns can be indexed by column name.</p>';
+			else {
+				Err( '<p>The fields columns <i>cannot</i> be indexed by column name.</p>');
+				print_r($rs->fields);
+			}
+			if (empty($_GET['hide'])) rs2html($rs);
+		}
+		else print "<p><b>Error in Execute of SELECT with random</b></p>";
+	}
+	$val = $db->GetOne("select count(*) from ADOXYZ");
+	 if ($val == 50) print "<p>GetOne returns ok</p>";
+	 else print "<p><b>Fail: GetOne returns $val</b></p>";
+
+	 echo "<b>GetRow Test</b>";
+	$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
+	$val1 = $db->GetRow("select count(*) from ADOXYZ");
+	$val2 = $db->GetRow("select count(*) from ADOXYZ");
+	 if ($val1[0] == 50 and sizeof($val1) == 1 and $val2[0] == 50 and sizeof($val2) == 1) print "<p>GetRow returns ok</p>";
+	 else {
+	 	print_r($val);
+	 	print "<p><b>Fail: GetRow returns {$val2[0]}</b></p>";
+	}
+
+	print "<p>FetchObject/FetchNextObject Test</p>";
+	$rs = $db->Execute('select * from ADOXYZ');
+	if ($rs) {
+		if (empty($rs->connection)) print "<b>Connection object missing from recordset</b></br>";
+		
+		while ($o = $rs->FetchNextObject()) { // calls FetchObject internally
+			if (!is_string($o->FIRSTNAME) || !is_string($o->LASTNAME)) {
+				print_r($o);
+				print "<p><b>Firstname is not string</b></p>";
+				break;
+			}
+		}
+	} else {
+		print "<p><b>Failed rs</b></p>";
+		die("<p>ADOXYZ table cannot be read - die()");
+	}
+	$ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
+	print "<p>FetchObject/FetchNextObject Test 2</p>";
+	#$db->debug=99;
+	$rs = $db->Execute('select * from ADOXYZ');
+	if (empty($rs->connection)) print "<b>Connection object missing from recordset</b></br>";
+	print_r($rs->fields);
+	while ($o = $rs->FetchNextObject()) { // calls FetchObject internally
+		if (!is_string($o->FIRSTNAME) || !is_string($o->LASTNAME)) {
+			print_r($o);
+			print "<p><b>Firstname is not string</b></p>";
+			break;
+		}
+	}
+	$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
+	
+	$savefetch = $ADODB_FETCH_MODE;
+	$ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
+	
+	print "<p>CacheSelectLimit  Test...</p>";
+	$db->debug=1;
+	$rs = $db->CacheSelectLimit('select  id, firstname from  ADOXYZ order by id',2);
+	
+	if ($rs && !$rs->EOF) {
+		if (isset($rs->fields[0])) {
+			Err("ASSOC has numeric fields");
+			print_r($rs->fields);
+		}
+		if ($rs->fields['id'] != 1)  {Err("Error"); print_r($rs->fields);};
+		if (trim($rs->fields['firstname']) != 'Caroline')  {print Err("Error 2"); print_r($rs->fields);};
+		
+		$rs->MoveNext();
+		if ($rs->fields['id'] != 2)  {Err("Error 3"); print_r($rs->fields);};
+		$rs->MoveNext();
+		if (!$rs->EOF) {
+			Err("Error EOF");
+			print_r($rs);
+		}
+	}
+	
+	print "<p>FETCH_MODE = ASSOC: Should get 1, Caroline</p>";
+	$rs = $db->SelectLimit('select id,firstname from ADOXYZ order by id',2);
+	if ($rs && !$rs->EOF) {
+		if (ADODB_ASSOC_CASE == 2) {
+			$id = 'ID';
+			$fname = 'FIRSTNAME';
+		}else {
+			$id = 'id';
+			$fname = 'firstname';
+		}
+		if ($rs->fields[$id] != 1)  {Err("Error 1"); print_r($rs->fields);};
+		if (trim($rs->fields[$fname]) != 'Caroline')  {Err("Error 2"); print_r($rs->fields);};
+		$rs->MoveNext();
+		if ($rs->fields[$id] != 2)  {Err("Error 3"); print_r($rs->fields);};
+		$rs->MoveNext();
+		if (!$rs->EOF) Err("Error EOF");
+		else if (is_array($rs->fields) || $rs->fields) {
+			Err("Error: ## fields should be set to false on EOF");
+			print_r($rs->fields);
+		}
+	}
+	
+	$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
+	print "<p>FETCH_MODE = NUM: Should get 1, Caroline</p>";
+	$rs = $db->SelectLimit('select id,firstname from ADOXYZ order by id',1);
+	if ($rs && !$rs->EOF) {
+		if (isset($rs->fields['id'])) Err("FETCH_NUM has ASSOC fields");
+		if ($rs->fields[0] != 1)  {Err("Error 1"); print_r($rs->fields);};
+		if (trim($rs->fields[1]) != 'Caroline')  {Err("Error 2");print_r($rs->fields);};
+		$rs->MoveNext();
+		if (!$rs->EOF) Err("Error EOF");
+
+	}
+	$ADODB_FETCH_MODE = $savefetch;
+	
+	$db->debug = false;
+	print "<p>GetRowAssoc Upper: Should get 1, Caroline</p>";
+	$rs = $db->SelectLimit('select id,firstname from ADOXYZ order by id',1);
+	if ($rs && !$rs->EOF) {
+		$arr = $rs->GetRowAssoc();
+		if ($arr['ID'] != 1) {Err("Error 1");print_r($arr);};
+		if (trim($arr['FIRSTNAME']) != 'Caroline') {Err("Error 2"); print_r($arr);};
+		$rs->MoveNext();
+		if (!$rs->EOF) Err("Error EOF");
+
+	}
+	print "<p>GetRowAssoc Lower: Should get 1, Caroline</p>";
+	$rs = $db->SelectLimit('select id,firstname from ADOXYZ order by id',1);
+	if ($rs && !$rs->EOF) {
+		$arr = $rs->GetRowAssoc(false);
+		if ($arr['id'] != 1) {Err("Error 1"); print_r($arr);};
+		if (trim($arr['firstname']) != 'Caroline') {Err("Error 2"); print_r($arr);};
+
+	}
+	
+	print "<p>GetCol Test</p>";
+	$col = $db->GetCol('select distinct firstname from ADOXYZ order by 1');
+	if (!is_array($col)) Err("Col size is wrong");
+	if (trim($col[0]) != 'Alan' or trim($col[9]) != 'Yat Sun') Err("Col elements wrong");
+
+	$db->debug = true;
+	
+		
+	echo "<p>Date Update Test</p>";
+	$zdate = date('Y-m-d',time()+3600*24);
+	$zdate = $db->DBDate($zdate);
+	$db->Execute("update ADOXYZ set created=$zdate where id=1");
+	$row = $db->GetRow("select created,firstname from ADOXYZ where id=1");
+	print_r($row); echo "<br>";
+	
+	
+	
+	print "<p>SelectLimit Distinct Test 1: Should see Caroline, John and Mary</p>";
+	$rs = $db->SelectLimit('select distinct * from ADOXYZ order by id',3);
+	
+	
+	if ($rs && !$rs->EOF) {
+		if (trim($rs->fields[1]) != 'Caroline') Err("Error 1 (exp Caroline), ".$rs->fields[1]);
+		$rs->MoveNext();
+		
+		if (trim($rs->fields[1]) != 'John') Err("Error 2 (exp John), ".$rs->fields[1]);
+		$rs->MoveNext();
+		if (trim($rs->fields[1]) != 'Mary') Err("Error 3 (exp Mary),".$rs->fields[1]);
+		$rs->MoveNext();
+		if (! $rs->EOF) Err("Error EOF");
+		//rs2html($rs);
+	} else Err("Failed SelectLimit Test 1");
+	
+	print "<p>SelectLimit Test 2: Should see Mary, George and Mr. Alan</p>";
+	$rs = $db->SelectLimit('select * from ADOXYZ order by id',3,2);
+	if ($rs && !$rs->EOF) {
+		if (trim($rs->fields[1]) != 'Mary') Err("Error 1 - No Mary, instead: ".$rs->fields[1]);
+		$rs->MoveNext();
+		if (trim($rs->fields[1]) != 'George')Err("Error 2 - No George, instead: ".$rs->fields[1]);
+		$rs->MoveNext();
+		if (trim($rs->fields[1]) != 'Mr. Alan') Err("Error 3 - No Mr. Alan, instead: ".$rs->fields[1]);
+		$rs->MoveNext();
+		if (! $rs->EOF) Err("Error EOF");
+	//	rs2html($rs);
+	}
+	 else Err("Failed SelectLimit Test 2 ". ($rs ? 'EOF':'no RS'));
+	
+	print "<p>SelectLimit Test 3: Should see Wai Hun and Steven</p>";
+	$db->debug=1;
+	global $A; $A=1;
+	$rs = $db->SelectLimit('select * from ADOXYZ order by id',-1,48);
+	$A=0;
+	if ($rs && !$rs->EOF) {
+		if (empty($rs->connection)) print "<b>Connection object missing from recordset</b></br>";
+		if (trim($rs->fields[1]) != 'Wai Hun') Err("Error 1 ".$rs->fields[1]);
+		$rs->MoveNext();
+		if (trim($rs->fields[1]) != 'Steven') Err("Error 2 ".$rs->fields[1]);
+		$rs->MoveNext();
+		if (! $rs->EOF) {
+			Err("Error EOF");
+		}
+		//rs2html($rs);
+	}
+	 else Err("Failed SelectLimit Test 3");
+		$db->debug = false;
+	
+	
+	$rs = $db->Execute("select * from ADOXYZ order by id");
+	print "<p>Testing Move()</p>";	
+	if (!$rs)Err( "Failed Move SELECT");
+	else {
+		if (!$rs->Move(2)) {
+			if (!$rs->canSeek) print "<p>$db->databaseType: <b>Move(), MoveFirst() nor MoveLast() not supported.</b></p>";
+			else print '<p><b>RecordSet->canSeek property should be set to false</b></p>';
+		} else {
+			$rs->MoveFirst();
+			if (trim($rs->Fields("firstname")) != 'Caroline') {
+				print "<p><b>$db->databaseType: MoveFirst failed -- probably cannot scroll backwards</b></p>";
+			}
+			else print "MoveFirst() OK<BR>";
+						
+						// Move(3) tests error handling -- MoveFirst should not move cursor
+			$rs->Move(3);
+			if (trim($rs->Fields("firstname")) != 'George') {
+				print '<p>'.$rs->Fields("id")."<b>$db->databaseType: Move(3) failed</b></p>";
+			} else print "Move(3) OK<BR>";
+						
+			$rs->Move(7);
+			if (trim($rs->Fields("firstname")) != 'Yat Sun') {
+				print '<p>'.$rs->Fields("id")."<b>$db->databaseType: Move(7) failed</b></p>";
+				print_r($rs);
+			} else print "Move(7) OK<BR>";
+			if ($rs->EOF) Err("Move(7) is EOF already");
+			$rs->MoveLast();
+			if (trim($rs->Fields("firstname")) != 'Steven'){
+				 print '<p>'.$rs->Fields("id")."<b>$db->databaseType: MoveLast() failed</b></p>";
+				 print_r($rs);
+			}else print "MoveLast() OK<BR>";
+			$rs->MoveNext();
+			if (!$rs->EOF) err("Bad MoveNext");
+			if ($rs->canSeek) {
+				$rs->Move(3);
+				if (trim($rs->Fields("firstname")) != 'George') {
+					print '<p>'.$rs->Fields("id")."<b>$db->databaseType: Move(3) after MoveLast failed</b></p>";
+					
+				} else print "Move(3) after MoveLast() OK<BR>";
+			}
+			
+			print "<p>Empty Move Test";
+			$rs = $db->Execute("select * from ADOXYZ where id > 0 and id < 0");
+			$rs->MoveFirst();
+			if (!$rs->EOF || $rs->fields) Err("Error in empty move first");
+		}
+	}
+	
+	$rs = $db->Execute('select * from ADOXYZ where id = 2');
+	if ($rs->EOF || !is_array($rs->fields)) Err("Error in select");
+	$rs->MoveNext();
+	if (!$rs->EOF) Err("Error in EOF (xx) ");
+ //	$db->debug=true;
+	print "<p>Testing ADODB_FETCH_ASSOC and concat: concat firstname and lastname</p>";
+
+	$save = $ADODB_FETCH_MODE;
+	$ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
+	if ($db->dataProvider == 'postgres') {
+		$sql = "select ".$db->Concat('cast(firstname as varchar)',$db->qstr(' '),'lastname')." as fullname,id,".$db->sysTimeStamp." as d from ADOXYZ";
+		$rs = $db->Execute($sql);
+	} else {
+		$sql = "select distinct ".$db->Concat('firstname',$db->qstr(' '),'lastname')." as fullname,id,".$db->sysTimeStamp." as d from ADOXYZ";
+		$rs = $db->Execute($sql);
+	}
+	if ($rs) {
+		if (empty($_GET['hide'])) rs2html($rs);
+	} else {
+		Err( "Failed Concat:".$sql);
+	}
+	$ADODB_FETCH_MODE = $save;
+	print "<hr />Testing GetArray() ";
+	//$ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
+	
+	$rs = $db->Execute("select * from ADOXYZ order by id");
+	if ($rs) {
+		$arr = $rs->GetArray(10);
+		if (sizeof($arr) != 10 || trim($arr[1][1]) != 'John' || trim($arr[1][2]) != 'Lim') print $arr[1][1].' '.$arr[1][2]."<b> &nbsp; ERROR</b><br>";
+		else print " OK<BR>";
+	}
+	
+	$arr = $db->GetArray("select x from ADOXYZ");
+	$e = $db->ErrorMsg(); $e2 = $db->ErrorNo();
+	echo "Testing error handling, should see illegal column 'x' error=<i>$e ($e2) </i><br>";
+	if (!$e || !$e2) Err("Error handling did not work");
+	print "Testing FetchNextObject for 1 object ";
+	$rs = $db->Execute("select distinct lastname,firstname from ADOXYZ where firstname='Caroline'");
+	$fcnt = 0;
+	if ($rs)
+	while ($o = $rs->FetchNextObject()) {
+		$fcnt += 1;	
+	}
+	if ($fcnt == 1) print " OK<BR>";
+	else print "<b>FAILED</b><BR>";
+	
+	$stmt = $db->Prepare("select * from ADOXYZ where id < 3");
+	$rs = $db->Execute($stmt);
+	if (!$rs) Err("Prepare failed");
+	else {
+		$arr = $rs->GetArray();
+		if (!$arr) Err("Prepare failed 2");
+		if (sizeof($arr) != 2) Err("Prepare failed 3");
+	}
+	print "Testing GetAssoc() ";
+	$savecrecs = $ADODB_COUNTRECS;
+	$ADODB_COUNTRECS = false;
+	//$arr = $db->GetArray("select  lastname,firstname from ADOXYZ");
+	//print_r($arr);
+	print "<hr />";
+	$rs = $db->Execute("select distinct lastname,firstname,created from ADOXYZ");
+	
+	if ($rs) {
+		$arr = $rs->GetAssoc();
+		//print_r($arr);
+		if (empty($arr['See']) || trim(reset($arr['See'])) != 'Wai Hun') print $arr['See']." &nbsp; <b>ERROR</b><br>";
+		else print " OK 1";
+	}
+	
+	$arr = $db->GetAssoc("select distinct lastname,firstname from ADOXYZ");
+	if ($arr) {
+		//print_r($arr);
+		if (empty($arr['See']) || trim($arr['See']) != 'Wai Hun') print $arr['See']." &nbsp; <b>ERROR</b><br>";
+		else print " OK 2<BR>";
+	}
+	// Comment this out to test countrecs = false
+	$ADODB_COUNTRECS = $savecrecs;
+	$db->debug=1;
+	$query = $db->Prepare("select count(*) from ADOXYZ");
+	$rs = $db->CacheExecute(10,$query);
+	if (reset($rs->fields) != 50) echo Err("$cnt wrong for Prepare/CacheGetOne");
+	
+	for ($loop=0; $loop < 1; $loop++) {
+	print "Testing GetMenu() and CacheExecute<BR>";
+	$db->debug = true;
+	$rs = $db->CacheExecute(4,"select distinct firstname,lastname from ADOXYZ");
+	
+	
+
+
+	if ($rs) print 'With blanks, Steven selected:'. $rs->GetMenu('menu','Steven').'<BR>'; 
+	else print " Fail<BR>";
+	$rs = $db->CacheExecute(4,"select distinct firstname,lastname from ADOXYZ");
+	
+	if ($rs) print ' No blanks, Steven selected: '. $rs->GetMenu('menu','Steven',false).'<BR>';
+	else print " Fail<BR>";
+	
+	$rs = $db->CacheExecute(4,"select distinct firstname,lastname from ADOXYZ");
+	
+	if ($rs) print ' 1st line set to **** , Steven selected: '. $rs->GetMenu('menu','Steven','1st:****').'<BR>';
+	else print " Fail<BR>";
+	
+
+	
+	$rs = $db->CacheExecute(4,"select distinct firstname,lastname from ADOXYZ");
+	if ($rs) print ' Multiple, Alan selected: '. $rs->GetMenu('menu','Alan',false,true).'<BR>';
+	else print " Fail<BR>";
+	print '</p><hr />';
+	
+	$rs = $db->CacheExecute(4,"select distinct firstname,lastname from ADOXYZ");
+	if ($rs) {
+		print ' Multiple, Alan and George selected: '. $rs->GetMenu('menu',array('Alan','George'),false,true);
+		if (empty($rs->connection)) print "<b>Connection object missing from recordset</b></br>";
+	} else print " Fail<BR>";
+	print '</p><hr />';
+	
+	print "Testing GetMenu3()<br>";
+	$rs = $db->Execute("select ".$db->Concat('firstname',"'-'",'id').",id, lastname from ADOXYZ order by lastname,id");
+	if ($rs) print "Grouped Menu: ".$rs->GetMenu3('name');
+	else Err('Grouped Menu GetMenu3()');
+	print "<hr />";
+
+	print "Testing GetMenu2() <BR>";
+	$rs = $db->CacheExecute(4,"select distinct firstname,lastname from ADOXYZ");
+	if ($rs) print 'With blanks, Steven selected:'. $rs->GetMenu2('menu',('Oey')).'<BR>'; 
+	else print " Fail<BR>";
+	$rs = $db->CacheExecute(6,"select distinct firstname,lastname from ADOXYZ");
+	if ($rs) print ' No blanks, Steven selected: '. $rs->GetMenu2('menu',('Oey'),false).'<BR>';
+	else print " Fail<BR>";
+	}
+	echo "<h3>CacheExecute</h3>";
+
+	$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
+	$rs = $db->CacheExecute(6,"select distinct firstname,lastname from ADOXYZ");
+	print_r($rs->fields); echo $rs->fetchMode;echo "<br>";
+	echo $rs->Fields('firstname');
+	
+	$ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
+	$rs = $db->CacheExecute(6,"select distinct firstname,lastname from ADOXYZ");
+	print_r($rs->fields);echo "<br>";
+	echo $rs->Fields('firstname');
+	$db->debug = false;
+	
+	$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
+	// phplens
+	
+	$sql = 'select * from ADOXYZ where 0=1';
+	echo "<p>**Testing '$sql' (phplens compat 1)</p>";
+	$rs = $db->Execute($sql);
+	if (!$rs) err( "<b>No recordset returned for '$sql'</b>");
+	if (!$rs->FieldCount()) err( "<b>No fields returned for $sql</b>");
+	if (!$rs->FetchField(1)) err( "<b>FetchField failed for $sql</b>");
+	
+	$sql = 'select * from ADOXYZ order by 1';
+	echo "<p>**Testing '$sql' (phplens compat 2)</p>";
+	$rs = $db->Execute($sql);
+	if (!$rs) err( "<b>No recordset returned for '$sql'<br>".$db->ErrorMsg()."</b>");
+	
+	
+	$sql = 'select * from ADOXYZ order by 1,1';
+	echo "<p>**Testing '$sql' (phplens compat 3)</p>";
+	$rs = $db->Execute($sql);
+	if (!$rs) err( "<b>No recordset returned for '$sql'<br>".$db->ErrorMsg()."</b>");
+	
+	
+	// Move
+	$rs1 = $db->Execute("select id from ADOXYZ where id <= 2 order by 1");
+	$rs2 = $db->Execute("select id from ADOXYZ where id = 3 or id = 4 order by 1");
+
+	if ($rs1) $rs1->MoveLast();
+	if ($rs2) $rs2->MoveLast();
+	
+	if (empty($rs1) || empty($rs2) || $rs1->fields[0] != 2 || $rs2->fields[0] != 4) {
+		$a = $rs1->fields[0];
+		$b = $rs2->fields[0];
+		print "<p><b>Error in multiple recordset test rs1=$a rs2=$b (should be rs1=2 rs2=4)</b></p>";
+	} else
+		print "<p>Testing multiple recordsets OK</p>";
+		
+	
+	echo "<p> GenID test: ";
+	for ($i=1; $i <= 10; $i++) 
+		echo  "($i: ",$val = $db->GenID($db->databaseType.'abcseq6' ,5), ") ";
+	if ($val == 0) Err("GenID not supported");
+	
+	if ($val) {
+		$db->DropSequence('abc_seq2');
+		$db->CreateSequence('abc_seq2');
+		$val = $db->GenID('abc_seq2');
+		$db->DropSequence('abc_seq2');
+		$db->CreateSequence('abc_seq2');
+		$val = $db->GenID('abc_seq2');
+		if ($val != 1) Err("Drop and Create Sequence not supported ($val)");
+	}
+	echo "<p>";
+	
+	if (substr($db->dataProvider,0,3) != 'notused') { // used to crash ado
+		$sql = "select firstnames from ADOXYZ";
+		print "<p>Testing execution of illegal statement: <i>$sql</i></p>";
+		if ($db->Execute($sql) === false) {
+			print "<p>This returns the following ErrorMsg(): <i>".$db->ErrorMsg()."</i> and ErrorNo(): ".$db->ErrorNo().'</p>';
+		} else 
+			print "<p><b>Error in error handling -- Execute() should return false</b></p>";
+	} else 
+		print "<p><b>ADO skipped error handling of bad select statement</b></p>";
+	
+	print "<p>ASSOC TEST 2<br>";
+	$ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
+	$rs = $db->query('select * from ADOXYZ order by id');
+	if ($ee = $db->ErrorMsg()) {
+		Err("Error message=$ee");
+	}
+	if ($ee = $db->ErrorNo()) {
+		Err("Error No = $ee");
+	}
+	print_r($rs->fields);
+	for($i=0;$i<$rs->FieldCount();$i++) 
+	{ 
+		$fld=$rs->FetchField($i); 
+		print "<br> Field name is ".$fld->name; 
+		print " ".$rs->Fields($fld->name); 
+	} 
+
+		
+	print "<p>BOTH TEST 2<br>";
+	if ($db->dataProvider == 'ado') {
+		print "<b>ADODB_FETCH_BOTH not supported</b> for dataProvider=".$db->dataProvider."<br>";
+	} else {
+		$ADODB_FETCH_MODE = ADODB_FETCH_BOTH;
+		$rs = $db->query('select * from ADOXYZ order by id');
+		for($i=0;$i<$rs->FieldCount();$i++) 
+		{ 
+			$fld=$rs->FetchField($i); 
+			print "<br> Field name is ".$fld->name; 
+			print " ".$rs->Fields($fld->name); 
+		} 
+	}
+	
+	print "<p>NUM TEST 2<br>";
+	$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
+	$rs = $db->query('select * from ADOXYZ order by id');
+	for($i=0;$i<$rs->FieldCount();$i++) 
+	{ 
+		$fld=$rs->FetchField($i); 
+		print "<br> Field name is ".$fld->name; 
+		print " ".$rs->Fields($fld->name); 
+	} 
+	
+	print "<p>ASSOC Test of SelectLimit<br>";
+	$ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
+	$rs = $db->selectlimit('select * from ADOXYZ order by id',3,4);
+	$cnt = 0;
+	while ($rs && !$rs->EOF) {
+		$cnt += 1;
+		if (!isset($rs->fields['firstname'])) {
+			print "<br><b>ASSOC returned numeric field</b></p>";
+			break;
+		}
+		$rs->MoveNext();
+	}
+	if ($cnt != 3) print "<br><b>Count should be 3, instead it was $cnt</b></p>";
+	
+	
+	$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
+	if ($db->sysDate) {
+		$saved = $db->debug;
+		$db->debug = 1;
+		$rs = $db->Execute("select {$db->sysDate} from ADOXYZ where id=1");
+		if (ADORecordSet::UnixDate(date('Y-m-d')) != $rs->UnixDate($rs->fields[0])) {
+			print "<p><b>Invalid date {$rs->fields[0]}</b></p>";
+		} else
+			print "<p>Passed \$sysDate test ({$rs->fields[0]})</p>";
+		
+		print_r($rs->FetchField(0));
+		print time();
+		$db->debug=$saved;
+	} else {
+		print "<p><b>\$db->sysDate not defined</b></p>";
+	}
+
+	print "<p>Test CSV</p>";
+	include_once('../toexport.inc.php');
+	//$ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
+	$rs = $db->SelectLimit('select id,firstname,lastname,created,\'He, he\' he,\'"\' q  from ADOXYZ',10);	
+	
+	print "<pre>";
+	print rs2csv($rs);
+	print "</pre>";
+	
+	$rs = $db->SelectLimit('select id,firstname,lastname,created,\'The	"young man", he said\' from ADOXYZ',10);	
+	
+	if (PHP_VERSION < 5) {
+		print "<pre>";
+		rs2tabout($rs);
+		print "</pre>";
+	}
+	print " CacheFlush ";
+	$db->CacheFlush();
+	
+	$date = $db->SQLDate('d-m-M-Y-\QQ h:i:s A');
+	$sql = "SELECT $date from ADOXYZ";
+	print "<p>Test SQLDate: ".htmlspecialchars($sql)."</p>";
+	$rs = $db->SelectLimit($sql,1);
+	$d = date('d-m-M-Y-').'Q'.(ceil(date('m')/3.0)).date(' h:i:s A');
+	if (!$rs) Err("SQLDate query returned no recordset");
+	else if ($d != $rs->fields[0]) Err("SQLDate 1 failed expected: <br>act:$d <br>sql:".$rs->fields[0]);
+	
+	$date = $db->SQLDate('d-m-M-Y-\QQ h:i:s A',$db->DBDate("1974-02-25"));
+	$sql = "SELECT $date from ADOXYZ";
+	print "<p>Test SQLDate: ".htmlspecialchars($sql)."</p>";
+	$db->debug=1;
+	$rs = $db->SelectLimit($sql,1);
+	$ts = ADOConnection::UnixDate('1974-02-25');
+	$d = date('d-m-M-Y-',$ts).'Q'.(ceil(date('m',$ts)/3.0)).date(' h:i:s A',$ts);
+	if (!$rs) {
+		Err("SQLDate query returned no recordset");
+		echo $db->ErrorMsg(),'<br>';
+	} else if ($d != reset($rs->fields)) {
+		Err("SQLDate 2 failed expected: <br>act:$d <br>sql:".$rs->fields[0].' <br>'.$db->ErrorMsg());
+	}
+	
+	
+	print "<p>Test Filter</p>";
+	$db->debug = 1;
+	
+	$rs = $db->SelectLimit('select * from ADOXYZ where id < 3 order by id');
+	
+	$rs = RSFilter($rs,'do_strtolower');
+	if (trim($rs->fields[1]) != 'caroline'  && trim($rs->fields[2]) != 'miranda') {
+		err('**** RSFilter failed');
+		print_r($rs->fields);
+	}
+	
+	rs2html($rs);
+		
+	$db->debug=1;
+	
+	
+	print "<p>Test Replace</p>";
+	
+	$ret = $db->Replace('ADOXYZ', 
+		array('id'=>1,'firstname'=>'Caroline','lastname'=>'Miranda'),
+		array('id'),
+		$autoq = true);
+	if (!$ret) echo "<p>Error in replacing existing record</p>";
+	else {
+		$saved = $db->debug;
+		$db->debug = 0;
+		$savec = $ADODB_COUNTRECS;
+		$ADODB_COUNTRECS = true;
+		$rs = $db->Execute('select * FROM ADOXYZ where id=1');
+		$db->debug = $saved;
+		if ($rs->RecordCount() != 1) {
+			$cnt = $rs->RecordCount();
+			rs2html($rs);
+			print "<b>Error - Replace failed, count=$cnt</b><p>";
+		}
+		$ADODB_COUNTRECS = $savec;
+	}
+	$ret = $db->Replace('ADOXYZ', 
+		array('id'=>1000,'firstname'=>'Harun','lastname'=>'Al-Rashid'),
+		array('id','firstname'),
+		$autoq = true);
+	if ($ret != 2) print "<b>Replace failed: </b>";
+	print "test A return value=$ret (2 expected) <p>";
+	
+	$ret = $db->Replace('ADOXYZ', 
+		array('id'=>1000,'firstname'=>'Sherazade','lastname'=>'Al-Rashid'),
+		'id',
+		$autoq = true);
+	if ($ret != 1) 
+		if ($db->dataProvider == 'ibase' && $ret == 2);
+		else print "<b>Replace failed: </b>";
+	print "test B return value=$ret (1 or if ibase then 2 expected) <p>";
+	
+	print "<h3>rs2rs Test</h3>";
+	
+	$rs = $db->Execute('select * from ADOXYZ where id>= 1 order by id');
+	$rs = $db->_rs2rs($rs);
+	$rs->valueX = 'X';
+	$rs->MoveNext();
+	$rs = $db->_rs2rs($rs);
+	if (!isset($rs->valueX)) err("rs2rs does not preserve array recordsets");
+	if (reset($rs->fields) != 1) err("rs2rs does not move to first row: id=".reset($rs->fields));
+
+	/////////////////////////////////////////////////////////////
+	include_once('../pivottable.inc.php');
+	print "<h3>Pivot Test</h3>";
+	$db->debug=true;
+ 	$sql = PivotTableSQL(
+ 		$db,  			# adodb connection
+ 		'ADOXYZ',  		# tables
+		'firstname',	# row fields
+		'lastname',		# column fields 
+		false,			# join
+		'ID', 			# sum
+		'Sum ',			# label for sum
+		'sum',			# aggregate function
+		true
+	);
+	$rs = $db->Execute($sql);
+	if ($rs) rs2html($rs);
+	else Err("Pivot sql error");
+	
+	$pear = true; //true;
+	$db->debug=false;
+	
+	if ($pear) {
+	// PEAR TESTS BELOW
+	$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
+	
+	include_once "PEAR.php";
+	$rs = $db->query('select * from ADOXYZ where id>0 and id<10 order by id');
+	
+	$i = 0;
+	if ($rs && !$rs->EOF) {
+		while ($arr = $rs->fetchRow()) {
+			$i++;
+			//print "$i ";
+			if ($arr[0] != $i) {
+				print_r($arr);
+				print "<p><b>PEAR DB emulation error 1.</b></p>";
+				$pear = false;
+				break;
+			}
+		}
+		$rs->Close();
+	}
+	
+	
+	if ($i != $db->GetOne('select count(*) from ADOXYZ where id>0 and id<10')) {
+		print "<p><b>PEAR DB emulation error 1.1 EOF ($i)</b></p>";
+		$pear = false;
+	}
+	
+	$rs = $db->limitQuery('select * from ADOXYZ where id>0 order by id',$i=3,$top=3);
+	$i2 = $i;
+	if ($rs && !$rs->EOF) {
+
+		while (!is_object($rs->fetchInto($arr))) {
+			$i2++;
+			
+	//			print_r($arr);
+	//		print "$i ";print_r($arr);
+			if ($arr[0] != $i2) {
+				print "<p><b>PEAR DB emulation error 2.</b></p>";
+				$pear = false;
+				break;
+			}
+		}
+		$rs->Close();
+	}
+	if ($i2 != $i+$top) {
+		print "<p><b>PEAR DB emulation error 2.1 EOF (correct=$i+$top, actual=$i2)</b></p>";
+		$pear = false;
+	}
+	}
+	if ($pear) print "<p>PEAR DB emulation passed.</p>";
+	flush();
+
+	
+	$rs = $db->SelectLimit("select ".$db->sysDate." from ADOXYZ",1);
+	$date = $rs->fields[0];
+	if (!$date) Err("Bad sysDate");
+	else {
+		$ds = $db->UserDate($date,"d m Y");
+		if ($ds != date("d m Y")) Err("Bad UserDate: ".$ds.' expected='.date("d m Y"));
+		else echo "Passed UserDate: $ds<p>";
+	}
+	$db->debug=1;
+	if ($db->dataProvider == 'oci8') 
+		$rs = $db->SelectLimit("select to_char(".$db->sysTimeStamp.",'YYYY-MM-DD HH24:MI:SS') from ADOXYZ",1);
+	else 
+		$rs = $db->SelectLimit("select ".$db->sysTimeStamp." from ADOXYZ",1);
+	$date = $rs->fields[0];
+	if (!$date) Err("Bad sysTimeStamp");
+	else {
+		$ds = $db->UserTimeStamp($date,"H \\h\\r\\s-d m Y");
+		if ($ds != date("H \\h\\r\\s-d m Y")) Err("Bad UserTimeStamp: ".$ds.", correct is ".date("H \\h\\r\\s-d m Y"));
+		else echo "Passed UserTimeStamp: $ds<p>";
+		
+		$date = 100;
+		$ds = $db->UserTimeStamp($date,"H \\h\\r\\s-d m Y");
+		$ds2 = date("H \\h\\r\\s-d m Y",$date);
+		if ($ds != $ds2) Err("Bad UserTimeStamp 2: $ds: $ds2");
+		else echo "Passed UserTimeStamp 2: $ds<p>";
+	}
+	flush();
+	
+	if ($db->hasTransactions) {
+		$db->debug=1;
+		echo "<p>Testing StartTrans CompleteTrans</p>";
+		$db->raiseErrorFn = false;
+		
+		$db->SetTransactionMode('SERIALIZABLE');
+		$db->StartTrans();
+		$rs = $db->Execute('select * from notable');
+			$db->StartTrans();
+				$db->BeginTrans();
+			$db->Execute("update ADOXYZ set firstname='Carolx' where id=1");
+				$db->CommitTrans();
+			$db->CompleteTrans();
+		$rez = $db->CompleteTrans();
+		$db->SetTransactionMode('');
+		$db->debug=0;
+		if ($rez !== false) {
+			if (is_null($rez)) Err("Error: _transOK not modified");
+			else Err("Error: CompleteTrans (1) should have failed");
+		} else {
+			$name = $db->GetOne("Select firstname from ADOXYZ where id=1");
+			if ($name == "Carolx") Err("Error: CompleteTrans (2) should have failed");
+			else echo "<p> -- Passed StartTrans test1 - rolling back</p>";
+		}
+		
+		$db->StartTrans();
+			$db->BeginTrans();
+		$db->Execute("update ADOXYZ set firstname='Carolx' where id=1");
+			$db->RollbackTrans();
+		$rez = $db->CompleteTrans();
+		if ($rez !== true) Err("Error: CompleteTrans (1) should have succeeded");
+		else {
+			$name = $db->GetOne("Select firstname from ADOXYZ where id=1");
+			if (trim($name) != "Carolx") Err("Error: CompleteTrans (2) should have succeeded, returned name=$name");
+			else echo "<p> -- Passed StartTrans test2 - commiting</p>";
+		}
+	}
+	flush();
+	$saved = $db->debug;
+	$db->debug=1;
+	$cnt = _adodb_getcount($db, 'select * from ADOXYZ where firstname in (select firstname from ADOXYZ)');
+	echo "<b>Count=</b> $cnt";
+	$db->debug=$saved;
+	
+	global $TESTERRS;
+	$debugerr = true;
+	
+	global $ADODB_LANG;$ADODB_LANG = 'fr';
+	$db->debug = false;
+	$TESTERRS = 0;
+	$db->raiseErrorFn = 'adodb_test_err';
+	global $ERRNO; // from adodb_test_err
+	$db->Execute('select * from nowhere');
+	$metae = $db->MetaError($ERRNO);
+	if ($metae !== DB_ERROR_NOSUCHTABLE) print "<p><b>MetaError=".$metae." wrong</b>, should be ".DB_ERROR_NOSUCHTABLE."</p>";
+	else print "<p>MetaError ok (".DB_ERROR_NOSUCHTABLE."): ".$db->MetaErrorMsg($metae)."</p>";
+	if ($TESTERRS != 1) print "<b>raiseErrorFn select nowhere failed</b><br>";
+	$rs = $db->Execute('select * from ADOXYZ');
+	if ($debugerr) print " Move";
+	$rs->Move(100);
+	$rs->_queryID = false;
+	if ($debugerr) print " MoveNext";
+	$rs->MoveNext();
+	if ($debugerr) print " $rs=false";
+	$rs = false;
+
+	flush();
+	
+	print "<p>SetFetchMode() tests</p>";
+	$db->SetFetchMode(ADODB_FETCH_ASSOC);
+	$rs = $db->SelectLimit('select firstname from ADOXYZ',1);
+	if (!isset($rs->fields['firstname'])) Err("BAD FETCH ASSOC");
+	
+	$ADODB_FETCH_MODE = ADODB_FETCH_NUM;	
+	$rs = $db->SelectLimit('select firstname from ADOXYZ',1);
+	//var_dump($rs->fields);
+	if (!isset($rs->fields['firstname'])) Err("BAD FETCH ASSOC");
+	
+	$ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;	
+	$db->SetFetchMode(ADODB_FETCH_NUM);
+	$rs = $db->SelectLimit('select firstname from ADOXYZ',1);
+	if (!isset($rs->fields[0])) Err("BAD FETCH NUM");
+	
+	flush();
+	
+	print "<p>Test MetaTables again with SetFetchMode()</p>";
+	$ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
+	$db->SetFetchMode(ADODB_FETCH_ASSOC);
+	print_r($db->MetaTables());
+	print "<p>";
+	
+	////////////////////////////////////////////////////////////////////
+	
+	print "<p>Testing Bad Connection</p>";
+	flush();
+	
+	if (true || PHP_VERSION < 5)  {
+		if ($db->dataProvider == 'odbtp') $db->databaseType = 'odbtp';
+		$conn = NewADOConnection($db->databaseType);
+		$conn->raiseErrorFn = 'adodb_test_err';
+		if (1) $conn->PConnect('abc','baduser','badpassword');
+		if ($TESTERRS == 2) print "raiseErrorFn tests passed<br>";
+		else print "<b>raiseErrorFn tests failed ($TESTERRS)</b><br>";
+		
+		flush();
+	}
+	////////////////////////////////////////////////////////////////////
+	
+	global $nocountrecs;
+	
+	if (isset($nocountrecs) && $ADODB_COUNTRECS) err("Error: \$ADODB_COUNTRECS is set");
+	if (empty($nocountrecs) && $ADODB_COUNTRECS==false) err("Error: \$ADODB_COUNTRECS is not set");
+
+	flush();
+?>
+	</p>
+	<table width=100% ><tr><td bgcolor=beige>&nbsp;</td></tr></table>
+	</p></form>
+<?php
+
+	if ($rs1) $rs1->Close();
+	if ($rs2) $rs2->Close();
+	if ($rs) $rs->Close();
+	$db->Close();
+	
+	if ($db->transCnt != 0) Err("Error in transCnt=$db->transCnt (should be 0)");
+	
+	
+	printf("<p>Total queries=%d; total cached=%d</p>",$EXECS+$CACHED, $CACHED);
+	flush();
+}
+
+function adodb_test_err($dbms, $fn, $errno, $errmsg, $p1=false, $p2=false)
+{
+global $TESTERRS,$ERRNO;
+
+	$ERRNO = $errno;
+	$TESTERRS += 1;
+	print "<i>** $dbms ($fn): errno=$errno &nbsp; errmsg=$errmsg ($p1,$p2)</i><br>";
+}
+
+//--------------------------------------------------------------------------------------
+
+
+@set_time_limit(240); // increase timeout
+
+include("../tohtml.inc.php");
+include("../adodb.inc.php");
+include("../rsfilter.inc.php");
+
+/* White Space Check */
+
+if (isset($_SERVER['argv'][1])) {
+	//print_r($_SERVER['argv']);
+	$_GET[$_SERVER['argv'][1]] = 1;
+}
+
+if (@$_SERVER['COMPUTERNAME'] == 'TIGRESS') {
+	CheckWS('mysqlt');
+	CheckWS('postgres');
+	CheckWS('oci8po');
+	
+	CheckWS('firebird');
+	CheckWS('sybase');
+	if (!ini_get('safe_mode')) CheckWS('informix');
+
+	CheckWS('ado_mssql');
+	CheckWS('ado_access');
+	CheckWS('mssql');
+	
+	CheckWS('vfp');
+	CheckWS('sqlanywhere');
+	CheckWS('db2');
+	CheckWS('access');
+	CheckWS('odbc_mssql');
+	CheckWS('firebird15');
+	//
+	CheckWS('oracle');
+	CheckWS('proxy');
+	CheckWS('fbsql');
+	print "White Space Check complete<p>";
+}
+if (sizeof($_GET) == 0) $testmysql = true;
+
+
+foreach($_GET as $k=>$v)  {
+	//global $$k;
+	$$k = $v;
+}	
+if (strpos(PHP_VERSION,'5') === 0) {
+	//$testaccess=1;
+	//$testmssql = 1;
+	//$testsqlite=1;
+}
+?>
+<html>
+<title>ADODB Testing</title>
+<body bgcolor=white>
+<H1>ADODB Test</H1>
+
+This script tests the following databases: Interbase, Oracle, Visual FoxPro, Microsoft Access (ODBC and ADO), MySQL, MSSQL (ODBC, native, ADO). 
+There is also support for Sybase, PostgreSQL.</p>
+For the latest version of ADODB, visit <a href=http://adodb.sourceforge.net/>adodb.sourceforge.net</a>.</p>
+
+Test <a href=test4.php>GetInsertSQL/GetUpdateSQL</a> &nbsp; 
+	<a href=testsessions.php>Sessions</a> &nbsp;
+	<a href=testpaging.php>Paging</a> &nbsp;
+	<a href=test-perf.php>Perf Monitor</a><p>
+<?php
+include('./testdatabases.inc.php');
+
+echo "<br>vers=",ADOConnection::Version();
+
+
+include_once('../adodb-time.inc.php');
+if (isset($_GET['time'])) adodb_date_test();
+
+?>
+<p><i>ADODB Database Library  (c) 2000-2007 John Lim. All rights reserved. Released under BSD and LGPL, PHP <?php echo PHP_VERSION ?>.</i></p>
+</body>
+</html>
Index: /Dev/trunk/rdfapi/util/adodb/tests/test2.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/tests/test2.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/tests/test2.php	(revision 12)
@@ -0,0 +1,26 @@
+<?php
+
+// BASIC ADO test
+
+	include_once('../adodb.inc.php');
+
+	$db = &ADONewConnection("ado_access");
+	$db->debug=1;
+	$access = 'd:\inetpub\wwwroot\php\NWIND.MDB';
+	$myDSN =  'PROVIDER=Microsoft.Jet.OLEDB.4.0;'
+		. 'DATA SOURCE=' . $access . ';';
+		
+	echo "<p>PHP ",PHP_VERSION,"</p>";
+	
+	$db->Connect($myDSN) || die('fail');
+	
+	print_r($db->ServerInfo());
+	
+	try {
+	$rs = $db->Execute("select $db->sysTimeStamp,* from adoxyz where id>02xx");
+	print_r($rs->fields);
+	} catch(exception $e) {
+	print_r($e);
+	echo "<p> Date m/d/Y =",$db->UserDate($rs->fields[4],'m/d/Y');
+	}
+?>
Index: /Dev/trunk/rdfapi/util/adodb/tests/test3.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/tests/test3.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/tests/test3.php	(revision 12)
@@ -0,0 +1,44 @@
+<?php
+/*
+  V4.80 8 Mar 2006  (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence.
+  Set tabs to 8.
+ */
+
+
+error_reporting(E_ALL);
+
+$path = dirname(__FILE__);
+
+include("$path/../adodb-exceptions.inc.php");
+include("$path/../adodb.inc.php");	
+
+try {
+$db = NewADOConnection("oci8");
+$db->Connect('','scott','natsoft');
+$db->debug=1;
+
+$cnt = $db->GetOne("select count(*) from adoxyz");
+$rs = $db->Execute("select * from adoxyz order by id");
+
+$i = 0;
+foreach($rs as $k => $v) {
+	$i += 1;
+	echo $k; adodb_pr($v);
+	flush();
+}
+
+if ($i != $cnt) die("actual cnt is $i, cnt should be $cnt\n");
+
+
+
+$rs = $db->Execute("select bad from badder");
+
+} catch (exception $e) {
+	adodb_pr($e);
+	$e = adodb_backtrace($e->trace);
+}
+
+?>
Index: /Dev/trunk/rdfapi/util/adodb/tests/test4.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/tests/test4.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/tests/test4.php	(revision 12)
@@ -0,0 +1,143 @@
+<?php
+
+/** 
+ * @version V4.50 6 July 2004 (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
+ * Released under both BSD license and Lesser GPL library license. 
+ * Whenever there is any discrepancy between the two licenses, 
+ * the BSD license will take precedence. 
+ *
+ * Set tabs to 4 for best viewing.
+ * 
+ * Latest version is available at http://php.weblogs.com
+ *
+ * Test GetUpdateSQL and GetInsertSQL.
+ */
+ 
+error_reporting(E_ALL);
+function testsql()
+{
+
+
+include('../adodb.inc.php');
+include('../tohtml.inc.php');
+
+global $ADODB_FORCE_TYPE;
+
+
+//==========================
+// This code tests an insert
+
+$sql = "
+SELECT * 
+FROM ADOXYZ WHERE id = -1"; 
+// Select an empty record from the database 
+
+
+#$conn = &ADONewConnection("mssql");  // create a connection
+#$conn->PConnect("", "sa", "natsoft", "northwind"); // connect to MySQL, testdb
+
+$conn = &ADONewConnection("mysql");  // create a connection
+$conn->PConnect("localhost", "root", "", "test"); // connect to MySQL, testdb
+
+
+#$conn =& ADONewConnection('oci8po');
+#$conn->Connect('','scott','natsoft');
+
+if (PHP_VERSION  >= 5) {
+	$connstr = "mysql:dbname=northwind";
+	$u = 'root';$p='';
+	$conn =& ADONewConnection('pdo');
+	$conn->Connect($connstr, $u, $p);
+}
+//$ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
+
+
+$conn->debug=1;
+$conn->Execute("delete from adoxyz where lastname like 'Smi%'");
+
+$rs = $conn->Execute($sql); // Execute the query and get the empty recordset
+$record = array(); // Initialize an array to hold the record data to insert
+
+if (strpos($conn->databaseType,'mysql')===false) $record['id'] = 751;
+$record["firstname"] = 'Jann';
+$record["lastname"] = "Smitts";
+$record["created"] = time();
+
+$insertSQL = $conn->GetInsertSQL($rs, $record);
+$conn->Execute($insertSQL); // Insert the record into the database
+
+if (strpos($conn->databaseType,'mysql')===false) $record['id'] = 752;
+// Set the values for the fields in the record
+$record["firstname"] = 'anull';
+$record["lastname"] = "Smith\$@//";
+$record["created"] = time();
+
+if (isset($_GET['f'])) $ADODB_FORCE_TYPE = $_GET['f'];
+
+//$record["id"] = -1;
+
+// Pass the empty recordset and the array containing the data to insert
+// into the GetInsertSQL function. The function will process the data and return
+// a fully formatted insert sql statement.
+$insertSQL = $conn->GetInsertSQL($rs, $record);
+$conn->Execute($insertSQL); // Insert the record into the database
+
+
+
+$insertSQL2 = $conn->GetInsertSQL($table='ADOXYZ', $record);
+if ($insertSQL != $insertSQL2) echo "<p><b>Walt's new stuff failed</b>: $insertSQL2</p>";
+//==========================
+// This code tests an update
+
+$sql = "
+SELECT * 
+FROM ADOXYZ WHERE lastname=".$conn->Param('var'). " ORDER BY 1"; 
+// Select a record to update 
+
+$varr = array('var'=>$record['lastname'].'');
+$rs = $conn->Execute($sql,$varr); // Execute the query and get the existing record to update
+if (!$rs || $rs->EOF) print "<p><b>No record found!</b></p>";
+
+$record = array(); // Initialize an array to hold the record data to update
+
+
+// Set the values for the fields in the record
+$record["firstName"] = "Caroline".rand();
+//$record["lasTname"] = ""; // Update Caroline's lastname from Miranda to Smith
+$record["creAted"] = '2002-12-'.(rand()%30+1);
+$record['num'] = '';
+// Pass the single record recordset and the array containing the data to update
+// into the GetUpdateSQL function. The function will process the data and return
+// a fully formatted update sql statement.
+// If the data has not changed, no recordset is returned
+
+$updateSQL = $conn->GetUpdateSQL($rs, $record);
+$conn->Execute($updateSQL,$varr); // Update the record in the database
+if ($conn->Affected_Rows() != 1)print "<p><b>Error1 </b>: Rows Affected=".$conn->Affected_Rows().", should be 1</p>";
+
+$record["firstName"] = "Caroline".rand();
+$record["lasTname"] = "Smithy Jones"; // Update Caroline's lastname from Miranda to Smith
+$record["creAted"] = '2002-12-'.(rand()%30+1);
+$record['num'] = 331;
+$updateSQL = $conn->GetUpdateSQL($rs, $record);
+$conn->Execute($updateSQL,$varr); // Update the record in the database
+if ($conn->Affected_Rows() != 1)print "<p><b>Error 2</b>: Rows Affected=".$conn->Affected_Rows().", should be 1</p>";
+
+$rs = $conn->Execute("select * from ADOXYZ where lastname like 'Sm%'");
+//adodb_pr($rs);
+rs2html($rs);
+
+$record["firstName"] = "Carol-new-".rand();
+$record["lasTname"] = "Smithy"; // Update Caroline's lastname from Miranda to Smith
+$record["creAted"] = '2002-12-'.(rand()%30+1);
+$record['num'] = 331;
+
+$conn->AutoExecute('ADOXYZ',$record,'UPDATE', "lastname like 'Sm%'");
+$rs = $conn->Execute("select * from ADOXYZ where lastname like 'Sm%'");
+//adodb_pr($rs);
+rs2html($rs);
+}
+
+
+testsql();
+?>
Index: /Dev/trunk/rdfapi/util/adodb/tests/test5.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/tests/test5.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/tests/test5.php	(revision 12)
@@ -0,0 +1,47 @@
+<?php
+/* 
+V4.80 8 Mar 2006  (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence. 
+  Set tabs to 4 for best viewing.
+	
+  Latest version is available at http://adodb.sourceforge.net
+*/
+
+
+// Select an empty record from the database 
+
+include('../adodb.inc.php');
+include('../tohtml.inc.php');
+
+include('../adodb-errorpear.inc.php');
+
+if (0) {
+	$conn = &ADONewConnection('mysql');
+	$conn->debug=1;
+	$conn->PConnect("localhost","root","","xphplens");
+	print $conn->databaseType.':'.$conn->GenID().'<br>';
+}
+
+if (0) {
+	$conn = &ADONewConnection("oci8");  // create a connection
+	$conn->debug=1;
+	$conn->PConnect("falcon", "scott", "tiger", "juris8.ecosystem.natsoft.com.my"); // connect to MySQL, testdb
+	print $conn->databaseType.':'.$conn->GenID();
+}
+
+if (0) {
+	$conn = &ADONewConnection("ibase");  // create a connection
+	$conn->debug=1;
+	$conn->Connect("localhost:c:\\Interbase\\Examples\\Database\\employee.gdb", "sysdba", "masterkey", ""); // connect to MySQL, testdb
+	print $conn->databaseType.':'.$conn->GenID().'<br>';
+}
+
+if (0) {
+	$conn = &ADONewConnection('postgres');
+	$conn->debug=1;
+	@$conn->PConnect("susetikus","tester","test","test");
+	print $conn->databaseType.':'.$conn->GenID().'<br>';
+}
+?>
Index: /Dev/trunk/rdfapi/util/adodb/tests/test_rs_array.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/tests/test_rs_array.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/tests/test_rs_array.php	(revision 12)
@@ -0,0 +1,47 @@
+<?php
+
+include_once('../adodb.inc.php');
+$rs = new ADORecordSet_array();
+
+$array = array(
+array ('Name', 'Age'),
+array ('John', '12'),
+array ('Jill', '8'),
+array ('Bill', '49')
+);
+
+$typearr = array('C','I');
+
+
+$rs->InitArray($array,$typearr);
+
+while (!$rs->EOF) {
+	print_r($rs->fields);echo "<br>";
+	$rs->MoveNext();
+}
+
+echo "<hr /> 1 Seek<br>";
+$rs->Move(1);
+while (!$rs->EOF) {
+	print_r($rs->fields);echo "<br>";
+	$rs->MoveNext();
+}
+
+echo "<hr /> 2 Seek<br>";
+$rs->Move(2);
+while (!$rs->EOF) {
+	print_r($rs->fields);echo "<br>";
+	$rs->MoveNext();
+}
+
+echo "<hr /> 3 Seek<br>";
+$rs->Move(3);
+while (!$rs->EOF) {
+	print_r($rs->fields);echo "<br>";
+	$rs->MoveNext();
+}
+
+
+
+die();
+?>
Index: /Dev/trunk/rdfapi/util/adodb/tests/testcache.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/tests/testcache.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/tests/testcache.php	(revision 12)
@@ -0,0 +1,29 @@
+<html>
+<body>
+<?php
+/* 
+V4.80 8 Mar 2006  (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence. 
+  Set tabs to 4 for best viewing.
+	
+  Latest version is available at http://adodb.sourceforge.net
+*/
+
+$ADODB_CACHE_DIR = dirname(tempnam('/tmp',''));
+include("../adodb.inc.php");
+
+if (isset($access)) {
+	$db=ADONewConnection('access');
+	$db->PConnect('nwind');
+} else {
+	$db = ADONewConnection('mysql');
+	$db->PConnect('mangrove','root','','xphplens');
+}
+if (isset($cache)) $rs = $db->CacheExecute(120,'select * from products');
+else $rs = $db->Execute('select * from products');
+
+$arr = $rs->GetArray();
+print sizeof($arr);
+?>
Index: /Dev/trunk/rdfapi/util/adodb/tests/testdatabases.inc.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/tests/testdatabases.inc.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/tests/testdatabases.inc.php	(revision 12)
@@ -0,0 +1,442 @@
+<?php
+  
+/*
+V4.80 8 Mar 2006  (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence.
+*/ 
+ 
+ /* this file is used by the ADODB test program: test.php */
+ ?>
+
+<table><tr valign=top><td>
+<form method=get>
+<input type=checkbox name="testaccess" value=1 <?php echo !empty($testaccess) ? 'checked' : '' ?>> <b>Access</b><br>
+<input type=checkbox name="testibase" value=1 <?php echo !empty($testibase) ? 'checked' : '' ?>> <b>Interbase</b><br>
+<input type=checkbox name="testmssql" value=1 <?php echo !empty($testmssql) ? 'checked' : '' ?>> <b>MSSQL</b><br>
+ <input type=checkbox name="testmysql" value=1 <?php echo !empty($testmysql) ? 'checked' : '' ?>> <b>MySQL</b><br>
+<input type=checkbox name="testmysqlodbc" value=1 <?php echo !empty($testmysqlodbc) ? 'checked' : '' ?>> <b>MySQL ODBC</b><br>
+<input type=checkbox name="testmysqli" value=1 <?php echo !empty($testmysqli) ? 'checked' : '' ?>> <b>MySQLi</b>
+<br>
+<td><input type=checkbox name="testsqlite" value=1 <?php echo !empty($testsqlite) ? 'checked' : '' ?>> <b>SQLite</b><br>
+<input type=checkbox name="testproxy" value=1 <?php echo !empty($testproxy) ? 'checked' : '' ?>> <b>MySQL Proxy</b><br>
+<input type=checkbox name="testoracle" value=1 <?php echo !empty($testoracle) ? 'checked' : '' ?>> <b>Oracle (oci8)</b> <br>
+<input type=checkbox name="testpostgres" value=1 <?php echo !empty($testpostgres) ? 'checked' : '' ?>> <b>PostgreSQL</b><br>
+<input type=checkbox name="testpgodbc" value=1 <?php echo !empty($testpgodbc) ? 'checked' : '' ?>> <b>PostgreSQL ODBC</b><br>
+<td>
+<input type=checkbox name="testpdopgsql" value=1 <?php echo !empty($testpdopgsql) ? 'checked' : '' ?>> <b>PgSQL PDO</b><br>
+<input type=checkbox name="testpdomysql" value=1 <?php echo !empty($testpdomysql) ? 'checked' : '' ?>> <b>MySQL PDO</b><br>
+<input type=checkbox name="testpdosqlite" value=1 <?php echo !empty($testpdosqlite) ? 'checked' : '' ?>> <b>SQLite PDO</b><br>
+<input type=checkbox name="testpdoaccess" value=1 <?php echo !empty($testpdoaccess) ? 'checked' : '' ?>> <b>Access PDO</b><br>
+<input type=checkbox name="testpdomssql" value=1 <?php echo !empty($testpdomssql) ? 'checked' : '' ?>> <b>MSSQL PDO</b><br>
+
+<input type=checkbox name="testpdoora" value=1 <?php echo !empty($testpdoora) ? 'checked' : '' ?>> <b>OCI PDO</b><br>
+
+<td><input type=checkbox name="testdb2" value=1 <?php echo !empty($testdb2) ? 'checked' : '' ?>> DB2<br>
+<input type=checkbox name="testvfp" value=1 <?php echo !empty($testvfp) ? 'checked' : '' ?>> VFP+ODBTP<br>
+<input type=checkbox name="testado" value=1 <?php echo !empty($testado) ? 'checked' : '' ?>> ADO (for mssql and access)<br>
+<input type=checkbox name="nocountrecs" value=1 <?php echo !empty($nocountrecs) ? 'checked' : '' ?>> $ADODB_COUNTRECS=false<br>
+<input type=checkbox name="nolog" value=1 <?php echo !empty($nolog) ? 'checked' : '' ?>> No SQL Logging<br>
+<input type=checkbox name="time" value=1 <?php echo !empty($_GET['time']) ? 'checked' : '' ?>> ADOdb time test
+</table>
+<input type=submit>
+</form>
+
+<?php
+
+if ($ADODB_FETCH_MODE != ADODB_FETCH_DEFAULT) print "<h3>FETCH MODE IS NOT ADODB_FETCH_DEFAULT</h3>";
+
+if (isset($nocountrecs)) $ADODB_COUNTRECS = false;
+
+// cannot test databases below, but we include them anyway to check
+// if they parse ok...
+
+if (!strpos(PHP_VERSION,'5') === 0) {
+	ADOLoadCode("sybase");
+	//ADOLoadCode("postgres");
+	//ADOLoadCode("postgres7");
+	ADOLoadCode("firebird");
+	ADOLoadCode("borland_ibase");
+	ADOLoadCode("informix");
+	ADOLoadCode("sqlanywhere");
+//	ADOLoadCode('mysqli');
+}
+
+
+flush();
+if (!empty($testpostgres)) {
+	//ADOLoadCode("postgres");
+
+	$db = &ADONewConnection('postgres');
+	print "<h1>Connecting $db->databaseType...</h1>";
+	if ($db->Connect("localhost","tester","test","test")) {
+		testdb($db,"create table ADOXYZ (id integer, firstname char(24), lastname varchar,created date)");
+	}else
+		print "ERROR: PostgreSQL requires a database called test on server, user tester, password test.<BR>".$db->ErrorMsg();
+}
+
+if (!empty($testpgodbc)) { 
+	
+	$db = &ADONewConnection('odbc');
+	$db->hasTransactions = false;
+	print "<h1>Connecting $db->databaseType...</h1>";
+	
+	if ($db->PConnect('Postgresql')) {
+		$db->hasTransactions = true;
+		testdb($db,
+		"create table ADOXYZ (id int, firstname char(24), lastname char(24), created date) type=innodb");
+	} else print "ERROR: PostgreSQL requires a database called test on server, user tester, password test.<BR>".$db->ErrorMsg();
+}
+
+if (!empty($testibase)) {
+	//$_GET['nolog'] = true;
+	$db = &ADONewConnection('firebird');
+	print "<h1>Connecting $db->databaseType...</h1>";
+	if ($db->PConnect("localhost:d:\\firebird\\151\\examples\\EMPLOYEE.fdb", "sysdba", "masterkey", ""))
+		testdb($db,"create table ADOXYZ (id integer, firstname char(24), lastname char(24),price numeric(12,2),created date)");
+	 else print "ERROR: Interbase test requires a database called employee.gdb".'<BR>'.$db->ErrorMsg();
+	
+}
+
+
+if (!empty($testsqlite)) {
+	$path =urlencode('d:\inetpub\adodb\sqlite.db');
+	$dsn = "sqlite://$path/";
+	$db = ADONewConnection($dsn);
+	//echo $dsn;
+	
+	//$db = &ADONewConnection('sqlite');
+	
+
+	if ($db && $db->PConnect("d:\\inetpub\\adodb\\sqlite.db", "", "", "")) {
+		print "<h1>Connecting $db->databaseType...</h1>";
+		testdb($db,"create table ADOXYZ (id int, firstname char(24), lastname char(24),created datetime)");
+	} else 
+		print "ERROR: SQLite";
+	
+}
+
+if (!empty($testpdopgsql)) {
+	$connstr = "pgsql:dbname=test";
+	$u = 'tester';$p='test';
+	$db = &ADONewConnection('pdo');
+	print "<h1>Connecting $db->databaseType...</h1>";
+	$db->Connect($connstr,$u,$p) || die("CONNECT FAILED");
+	testdb($db,
+		"create table ADOXYZ (id int, firstname char(24), lastname char(24), created date)");
+}
+
+if (!empty($testpdomysql)) {
+	$connstr = "mysql:dbname=northwind";
+	$u = 'root';$p='';
+	$db = &ADONewConnection('pdo');
+	print "<h1>Connecting $db->databaseType...</h1>";
+	$db->Connect($connstr,$u,$p) || die("CONNECT FAILED");
+	
+	testdb($db,
+		"create table ADOXYZ (id int, firstname char(24), lastname char(24), created date)");
+}
+
+if (!empty($testpdomssql)) {
+	$connstr = "mssql:dbname=northwind";
+	$u = 'sa';$p='natsoft';
+	$db = &ADONewConnection('pdo');
+	print "<h1>Connecting $db->databaseType...</h1>";
+	$db->Connect($connstr,$u,$p) || die("CONNECT FAILED");
+	
+	testdb($db,
+		"create table ADOXYZ (id int, firstname char(24), lastname char(24), created date)");
+}
+
+if (!empty($testpdosqlite)) {
+	$connstr = "sqlite:d:/inetpub/adodb/sqlite-pdo.db3";
+	$u = '';$p='';
+	$db = &ADONewConnection('pdo');
+	$db->hasTransactions = false;
+	print "<h1>Connecting $db->databaseType...</h1>";
+	$db->Connect($connstr,$u,$p) || die("CONNECT FAILED");
+	testdb($db,
+		"create table ADOXYZ (id int, firstname char(24), lastname char(24), created date)");
+}
+
+if (!empty($testpdoaccess)) {
+	$connstr = 'odbc:nwind';
+	$u = '';$p='';
+	$db = &ADONewConnection('pdo');
+	$db->hasTransactions = false;
+	print "<h1>Connecting $db->databaseType...</h1>";
+	$db->Connect($connstr,$u,$p) || die("CONNECT FAILED");
+	testdb($db,
+		"create table ADOXYZ (id int, firstname char(24), lastname char(24), created date)");
+}
+
+if (!empty($testpdoora)) {
+	$connstr = 'oci:';
+	$u = 'scott';$p='natsoft';
+	$db = &ADONewConnection('pdo');
+	#$db->hasTransactions = false;
+	print "<h1>Connecting $db->databaseType...</h1>";
+	$db->Connect($connstr,$u,$p) || die("CONNECT FAILED");
+	testdb($db,
+		"create table ADOXYZ (id int, firstname char(24), lastname char(24), created date)");
+}
+
+// REQUIRES ODBC DSN CALLED nwind
+if (!empty($testaccess)) {
+	$db = &ADONewConnection('access');
+	print "<h1>Connecting $db->databaseType...</h1>";
+	$access = 'd:\inetpub\wwwroot\php\NWIND.MDB';
+	$dsn = "nwind";
+	$dsn = "Driver={Microsoft Access Driver (*.mdb)};Dbq=$access;Uid=Admin;Pwd=;";
+	
+	//$dsn =  'Provider=Microsoft.Jet.OLEDB.4.0;DATA SOURCE=' . $access . ';';
+	if ($db->PConnect($dsn, "", "", ""))
+		testdb($db,"create table ADOXYZ (id int, firstname char(24), lastname char(24),created datetime)");
+	else print "ERROR: Access test requires a Windows ODBC DSN=nwind, Access driver";
+	
+}
+
+if (!empty($testaccess) && !empty($testado)) { // ADO ACCESS
+
+	$db = &ADONewConnection("ado_access");
+	print "<h1>Connecting $db->databaseType...</h1>";
+	
+	$access = 'd:\inetpub\wwwroot\php\NWIND.MDB';
+	$myDSN =  'PROVIDER=Microsoft.Jet.OLEDB.4.0;'
+		. 'DATA SOURCE=' . $access . ';';
+		//. 'USER ID=;PASSWORD=;';
+	$_GET['nolog'] = 1;
+	if ($db->PConnect($myDSN, "", "", "")) {
+		print "ADO version=".$db->_connectionID->version."<br>";
+		testdb($db,"create table ADOXYZ (id int, firstname char(24), lastname char(24),created datetime)");
+	} else print "ERROR: Access test requires a Access database $access".'<BR>'.$db->ErrorMsg();
+	
+}
+
+if (!empty($testvfp)) { // ODBC
+	$db = &ADONewConnection('vfp');
+	print "<h1>Connecting $db->databaseType...</h1>";flush();
+
+	if ( $db->PConnect("vfp-adoxyz")) {
+		testdb($db,"create table d:\\inetpub\\adodb\\ADOXYZ (id int, firstname char(24), lastname char(24),created date)");
+	 } else print "ERROR: Visual FoxPro test requires a Windows ODBC DSN=vfp-adoxyz, VFP driver";
+	
+	echo "<hr />";
+	$db = &ADONewConnection('odbtp');
+	
+	if ( $db->PConnect('localhost','DRIVER={Microsoft Visual FoxPro Driver};SOURCETYPE=DBF;SOURCEDB=d:\inetpub\adodb;EXCLUSIVE=NO;')) {
+	print "<h1>Connecting $db->databaseType...</h1>";flush();
+	testdb($db,"create table d:\\inetpub\\adodb\\ADOXYZ (id int, firstname char(24), lastname char(24),created date)");
+	 } else print "ERROR: Visual FoxPro odbtp requires a Windows ODBC DSN=vfp-adoxyz, VFP driver";
+	
+}
+
+
+// REQUIRES MySQL server at localhost with database 'test'
+if (!empty($testmysql)) { // MYSQL
+
+
+	if (PHP_VERSION >= 5 || $_SERVER['HTTP_HOST'] == 'localhost') $server = 'localhost';
+	else $server = "mangrove";
+	$user = 'root'; $password = ''; $database = 'northwind';
+	$db = &ADONewConnection("mysqlt://$user:$password@$server/$database?persist");
+	print "<h1>Connecting $db->databaseType...</h1>";
+	
+	if (true || $db->PConnect($server, "root", "", "northwind")) {
+		//$db->Execute("DROP TABLE ADOXYZ") || die('fail drop');
+		//$db->debug=1;$db->Execute('drop table ADOXYZ');
+		testdb($db,
+		"create table ADOXYZ (id int, firstname char(24), lastname char(24), created date) Type=InnoDB");
+	} else print "ERROR: MySQL test requires a MySQL server on localhost, userid='admin', password='', database='test'".'<BR>'.$db->ErrorMsg();
+}
+
+// REQUIRES MySQL server at localhost with database 'test'
+if (!empty($testmysqli)) { // MYSQL
+
+	$db = &ADONewConnection('mysqli');
+	print "<h1>Connecting $db->databaseType...</h1>";
+	if (PHP_VERSION >= 5 || $_SERVER['HTTP_HOST'] == 'localhost') $server = 'localhost';
+	else $server = "mangrove";
+	if ($db->PConnect($server, "root", "", "northwind")) {
+		//$db->debug=1;$db->Execute('drop table ADOXYZ');
+		testdb($db,
+		"create table ADOXYZ (id int, firstname char(24), lastname char(24), created date)");
+	} else print "ERROR: MySQL test requires a MySQL server on localhost, userid='admin', password='', database='test'".'<BR>'.$db->ErrorMsg();
+}
+
+
+// REQUIRES MySQL server at localhost with database 'test'
+if (!empty($testmysqlodbc)) { // MYSQL
+	
+	$db = &ADONewConnection('odbc');
+	$db->hasTransactions = false;
+	print "<h1>Connecting $db->databaseType...</h1>";
+	if ($_SERVER['HTTP_HOST'] == 'localhost') $server = 'localhost';
+	else $server = "mangrove";
+	if ($db->PConnect('mysql', "root", ""))
+		testdb($db,
+		"create table ADOXYZ (id int, firstname char(24), lastname char(24), created date) type=innodb");
+	else print "ERROR: MySQL test requires a MySQL server on localhost, userid='admin', password='', database='test'".'<BR>'.$db->ErrorMsg();
+}
+
+if (!empty($testproxy)){
+	$db = &ADONewConnection('proxy');
+	print "<h1>Connecting $db->databaseType...</h1>";
+	if ($_SERVER['HTTP_HOST'] == 'localhost') $server = 'localhost';
+
+	if ($db->PConnect('http://localhost/php/phplens/adodb/server.php'))
+		testdb($db,
+		"create table ADOXYZ (id int, firstname char(24), lastname char(24), created date) type=innodb");
+	else print "ERROR: MySQL test requires a MySQL server on localhost, userid='admin', password='', database='test'".'<BR>'.$db->ErrorMsg();
+
+}
+
+ADOLoadCode('oci805');
+ADOLoadCode("oci8po");
+	
+if (!empty($testoracle)) {
+	$dsn = "oci8po://juris10:natsoft@sherkhan?persist";
+	$db = ADONewConnection($dsn );//'oci8');
+	
+	//$db->debug=1;
+	print "<h1>Connecting $db->databaseType...</h1>";
+	if (true || $db->Connect('', "scott", "natsoft",''))
+		testdb($db,"create table ADOXYZ (id int, firstname varchar(24), lastname varchar(24),created date)");
+	else 
+		print "ERROR: Oracle test requires an Oracle server setup with scott/natsoft".'<BR>'.$db->ErrorMsg();
+
+}
+ADOLoadCode("oracle"); // no longer supported
+if (false && !empty($testoracle)) { 
+	
+	$db = ADONewConnection();
+	print "<h1>Connecting $db->databaseType...</h1>";
+	if ($db->PConnect("", "scott", "tiger", "natsoft.domain"))
+		testdb($db,"create table ADOXYZ (id int, firstname varchar(24), lastname varchar(24),created date)");
+	else print "ERROR: Oracle test requires an Oracle server setup with scott/tiger".'<BR>'.$db->ErrorMsg();
+
+}
+
+ADOLoadCode("odbc_db2"); // no longer supported
+if (!empty($testdb2)) {
+	if (PHP_VERSION>=5.1) {
+		$db = ADONewConnection("db2");
+		print "<h1>Connecting $db->databaseType...</h1>";
+		
+		#$db->curMode = SQL_CUR_USE_ODBC;
+		#$dsn = "driver={IBM db2 odbc DRIVER};Database=test;hostname=localhost;port=50000;protocol=TCPIP; uid=natsoft; pwd=guest";
+		if ($db->Connect('localhost','natsoft','guest','test')) {
+			testdb($db,"create table ADOXYZ (id int, firstname varchar(24), lastname varchar(24),created date)");
+		} else print "ERROR: DB2 test requires an server setup with odbc data source db2_sample".'<BR>'.$db->ErrorMsg();
+	} else { 
+		$db = ADONewConnection("odbc_db2");
+		print "<h1>Connecting $db->databaseType...</h1>";
+		
+		$dsn = "db2test";
+		#$db->curMode = SQL_CUR_USE_ODBC;
+		#$dsn = "driver={IBM db2 odbc DRIVER};Database=test;hostname=localhost;port=50000;protocol=TCPIP; uid=natsoft; pwd=guest";
+		if ($db->Connect($dsn)) {
+			testdb($db,"create table ADOXYZ (id int, firstname varchar(24), lastname varchar(24),created date)");
+		} else print "ERROR: DB2 test requires an server setup with odbc data source db2_sample".'<BR>'.$db->ErrorMsg();
+	}
+echo "<hr />";
+flush();
+	$dsn = "driver={IBM db2 odbc DRIVER};Database=sample;hostname=localhost;port=50000;protocol=TCPIP; uid=root; pwd=natsoft";
+	
+	$db = ADONewConnection('odbtp');
+	if ($db->Connect('127.0.0.1',$dsn)) {
+		
+		$db->debug=1;
+		 $arr = $db->GetArray( "||SQLProcedures" ); adodb_pr($arr);
+	     $arr = $db->GetArray( "||SQLProcedureColumns|||GET_ROUTINE_SAR" );adodb_pr($arr);
+	
+		testdb($db,"create table ADOXYZ (id int, firstname varchar(24), lastname varchar(24),created date)");
+	} else echo ("ERROR Connection");
+	echo $db->ErrorMsg();
+}
+
+
+$server = 'sherkhan';
+
+
+
+ADOLoadCode("mssqlpo");
+if (!empty($testmssql)) { // MS SQL Server -- the extension is buggy -- probably better to use ODBC
+	$db = ADONewConnection("mssqlpo");
+	//$db->debug=1;
+	print "<h1>Connecting $db->databaseType...</h1>";
+	
+	$ok = $db->Connect('','adodb','natsoft','northwind');
+
+	if ($ok or $db->PConnect("mangrove", "sa", "natsoft", "ai")) {
+		AutoDetect_MSSQL_Date_Order($db);
+	//	$db->Execute('drop table adoxyz');
+		testdb($db,"create table ADOXYZ (id int, firstname char(24) null, lastname char(24) null,created datetime null)");
+	} else print "ERROR: MSSQL test 2 requires a MS SQL 7 on a server='192.168.0.1', userid='adodb', password='natsoft', database='ai'".'<BR>'.$db->ErrorMsg();
+	
+}
+
+
+ADOLoadCode('odbc_mssql');
+if (!empty($testmssql)) { // MS SQL Server via ODBC
+	$db = ADONewConnection();
+	
+	print "<h1>Connecting $db->databaseType...</h1>";
+	
+	$dsn = "PROVIDER=MSDASQL;Driver={SQL Server};Server=$server;Database=northwind;";
+	
+	if ($db->PConnect($dsn, "adodb", "natsoft", ""))  {
+		testdb($db,"create table ADOXYZ (id int, firstname char(24) null, lastname char(24) null,created datetime null)");
+	}
+	else print "ERROR: MSSQL test 1 requires a MS SQL 7 server setup with DSN setup";
+
+}
+
+ADOLoadCode("ado_mssql");
+if (!empty($testmssql) && !empty($testado) ) { // ADO ACCESS MSSQL -- thru ODBC -- DSN-less
+	
+	$db = &ADONewConnection("ado_mssql");
+	//$db->debug=1;
+	print "<h1>Connecting DSN-less $db->databaseType...</h1>";
+	
+	$myDSN="PROVIDER=MSDASQL;DRIVER={SQL Server};"
+		. "SERVER=$server;DATABASE=NorthWind;UID=adodb;PWD=natsoft;Trusted_Connection=No";
+
+		
+	if ($db->PConnect($myDSN, "", "", ""))
+		testdb($db,"create table ADOXYZ (id int, firstname char(24) null, lastname char(24) null,created datetime null)");
+	else print "ERROR: MSSQL test 2 requires MS SQL 7";
+	
+}
+
+if (!empty($testmssql) && !empty($testado)) { // ADO ACCESS MSSQL with OLEDB provider
+
+	$db = &ADONewConnection("ado_mssql");
+	print "<h1>Connecting DSN-less OLEDB Provider $db->databaseType...</h1>";
+	//$db->debug=1;
+	$myDSN="SERVER=localhost;DATABASE=northwind;Trusted_Connection=yes";
+	if ($db->PConnect($myDSN, "adodb", "natsoft", 'SQLOLEDB')) {
+		testdb($db,"create table ADOXYZ (id int, firstname char(24), lastname char(24),created datetime)");
+	} else print "ERROR: MSSQL test 2 requires a MS SQL 7 on a server='mangrove', userid='sa', password='', database='ai'";
+
+}
+
+
+if (extension_loaded('odbtp') && !empty($testmssql)) { // MS SQL Server via ODBC
+	$db = ADONewConnection('odbtp');
+	
+	$dsn = "PROVIDER=MSDASQL;Driver={SQL Server};Server=$server;Database=northwind;uid=adodb;pwd=natsoft";
+	
+	if ($db->PConnect('localhost',$dsn, "", ""))  {
+		print "<h1>Connecting $db->databaseType...</h1>";				
+		testdb($db,"create table ADOXYZ (id int, firstname char(24) null, lastname char(24) null,created datetime null)");
+	}
+	else print "ERROR: MSSQL test 1 requires a MS SQL 7 server setup with DSN setup";
+
+}
+
+
+print "<h3>Tests Completed</h3>";
+
+?>
Index: /Dev/trunk/rdfapi/util/adodb/tests/testgenid.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/tests/testgenid.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/tests/testgenid.php	(revision 12)
@@ -0,0 +1,36 @@
+<?php
+/*
+	V4.50 6 July 2004 
+	
+	Run multiple copies of this php script at the same time
+	to test unique generation of id's in multiuser mode
+*/
+include_once('../adodb.inc.php');
+$testaccess = true;
+include_once('testdatabases.inc.php');
+
+function testdb(&$db,$createtab="create table ADOXYZ (id int, firstname char(24), lastname char(24), created date)")
+{
+	$table = 'adodbseq';
+	
+	$db->Execute("drop table $table");
+	//$db->debug=true;
+	
+	$ctr = 5000;
+	$lastnum = 0;
+	
+	while (--$ctr >= 0) {
+		$num = $db->GenID($table);
+		if ($num === false) {	
+			print "GenID returned false";
+			break;
+		}
+		if ($lastnum + 1 == $num) print " $num ";
+		else {
+			print " <font color=red>$num</font> ";
+			flush();
+		}
+		$lastnum = $num;
+	}
+}
+?>
Index: /Dev/trunk/rdfapi/util/adodb/tests/testmssql.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/tests/testmssql.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/tests/testmssql.php	(revision 12)
@@ -0,0 +1,76 @@
+<?php
+
+/** 
+ * @version V4.50 6 July 2004 (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
+ * Released under both BSD license and Lesser GPL library license. 
+ * Whenever there is any discrepancy between the two licenses, 
+ * the BSD license will take precedence. 
+ *
+ * Set tabs to 4 for best viewing.
+ * 
+ * Latest version is available at http://php.weblogs.com
+ *
+ * Test GetUpdateSQL and GetInsertSQL.
+ */
+ 
+error_reporting(E_ALL);
+
+
+include('../adodb.inc.php');
+include('../tohtml.inc.php');
+
+//==========================
+// This code tests an insert
+
+
+
+$conn = &ADONewConnection("mssql");  // create a connection
+$conn->Connect('127.0.0.1','adodb','natsoft','northwind') or die('Fail');
+
+$conn->debug =1;
+$query = 'select * from products';
+$conn->SetFetchMode(ADODB_FETCH_ASSOC);
+$rs = $conn->Execute($query);
+echo "<pre>";
+while( !$rs->EOF ) {
+	$output[] = $rs->fields;
+	var_dump($rs->fields);
+	$rs->MoveNext();
+	print "<p>";
+}
+die();
+
+
+$p = $conn->Prepare('insert into products (productname,unitprice,dcreated) values (?,?,?)');
+echo "<pre>";
+print_r($p);
+
+$conn->debug=1;
+$conn->Execute($p,array('John'.rand(),33.3,$conn->DBDate(time())));
+
+$p = $conn->Prepare('select * from products where productname like ?');
+$arr = $conn->getarray($p,array('V%'));
+print_r($arr);
+die();
+
+//$conn = &ADONewConnection("mssql");
+//$conn->Connect('mangrove','sa','natsoft','ai');
+
+//$conn->Connect('mangrove','sa','natsoft','ai');
+$conn->debug=1;
+$conn->Execute('delete from blobtest');
+
+$conn->Execute('insert into blobtest (id) values(1)');
+$conn->UpdateBlobFile('blobtest','b1','../cute_icons_for_site/adodb.gif','id=1');
+$rs = $conn->Execute('select b1 from blobtest where id=1');
+
+$output = "c:\\temp\\test_out-".date('H-i-s').".gif"; 
+print "Saving file <b>$output</b>, size=".strlen($rs->fields[0])."<p>";
+$fd = fopen($output, "wb"); 
+fwrite($fd, $rs->fields[0]); 
+fclose($fd); 
+
+print " <a href=file://$output>View Image</a>";
+//$rs = $conn->Execute('SELECT id,SUBSTRING(b1, 1, 10) FROM blobtest');
+//rs2html($rs);
+?>
Index: /Dev/trunk/rdfapi/util/adodb/tests/testoci8.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/tests/testoci8.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/tests/testoci8.php	(revision 12)
@@ -0,0 +1,83 @@
+<html>
+<body>
+<?php
+/* 
+V4.80 8 Mar 2006  (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence. 
+  Set tabs to 4 for best viewing.
+	
+  Latest version is available at http://adodb.sourceforge.net
+*/
+error_reporting(63);
+include("../adodb.inc.php");
+include("../tohtml.inc.php");
+
+if (0) {
+	$db = ADONewConnection('oci8po');
+	
+	$db->PConnect('','scott','natsoft');
+	if (!empty($testblob)) {
+		$varHoldingBlob = 'ABC DEF GEF John TEST';
+		$num = time()%10240;
+		// create table atable (id integer, ablob blob);
+		$db->Execute('insert into ATABLE (id,ablob) values('.$num.',empty_blob())');
+		$db->UpdateBlob('ATABLE', 'ablob', $varHoldingBlob, 'id='.$num, 'BLOB');
+		
+		$rs = &$db->Execute('select * from atable');
+		
+		if (!$rs) die("Empty RS");
+		if ($rs->EOF) die("EOF RS");
+		rs2html($rs);
+	}
+	$stmt = $db->Prepare('select * from adoxyz where id=?');
+	for ($i = 1; $i <= 10; $i++) {
+	$rs = &$db->Execute(
+		$stmt,
+		array($i));
+			
+		if (!$rs) die("Empty RS");
+		if ($rs->EOF) die("EOF RS");
+		rs2html($rs);
+	}
+}
+if (1) {
+	$db = ADONewConnection('oci8');
+	$db->PConnect('','scott','natsoft');
+	$db->debug = true;
+	$db->Execute("delete from emp where ename='John'");
+	print $db->Affected_Rows().'<BR>';
+	$stmt = &$db->Prepare('insert into emp (empno, ename) values (:empno, :ename)');
+	$rs = $db->Execute($stmt,array('empno'=>4321,'ename'=>'John'));
+	// prepare not quite ready for prime time
+	//$rs = $db->Execute($stmt,array('empno'=>3775,'ename'=>'John'));
+	if (!$rs) die("Empty RS");
+	
+	$db->setfetchmode(ADODB_FETCH_NUM);
+	
+	$vv = 'A%';
+	$stmt = $db->PrepareSP("BEGIN adodb.open_tab2(:rs,:tt); END;",true);
+	$db->OutParameter($stmt, $cur, 'rs', -1, OCI_B_CURSOR);
+	$db->OutParameter($stmt, $vv, 'tt');
+	$rs = $db->Execute($stmt);
+	while (!$rs->EOF) {
+		adodb_pr($rs->fields);
+		$rs->MoveNext();
+	}
+	echo " val = $vv";
+
+}
+
+if (0) {
+	$db = ADONewConnection('odbc_oracle');
+	if (!$db->PConnect('local_oracle','scott','tiger')) die('fail connect');
+	$db->debug = true;
+	$rs = &$db->Execute(
+		'select * from adoxyz where firstname=? and trim(lastname)=?',
+		array('first'=>'Caroline','last'=>'Miranda'));
+	if (!$rs) die("Empty RS");
+	if ($rs->EOF) die("EOF RS");
+	rs2html($rs);
+}
+?>
Index: /Dev/trunk/rdfapi/util/adodb/tests/testoci8cursor.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/tests/testoci8cursor.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/tests/testoci8cursor.php	(revision 12)
@@ -0,0 +1,111 @@
+<?php
+/* 
+V4.80 8 Mar 2006  (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence. 
+  Set tabs to 4 for best viewing.
+	
+  Latest version is available at http://adodb.sourceforge.net
+*/
+
+/*
+	Test for Oracle Variable Cursors, which are treated as ADOdb recordsets.
+	
+	We have 2 examples. The first shows us using the Parameter statement. 
+	The second shows us using the new ExecuteCursor($sql, $cursorName)
+	function.
+	
+------------------------------------------------------------------
+-- TEST PACKAGE YOU NEED TO INSTALL ON ORACLE - run from sql*plus
+------------------------------------------------------------------
+
+
+-- TEST PACKAGE
+CREATE OR REPLACE PACKAGE adodb AS
+TYPE TabType IS REF CURSOR RETURN tab%ROWTYPE;
+PROCEDURE open_tab (tabcursor IN OUT TabType,tablenames in varchar);
+PROCEDURE data_out(input IN varchar, output OUT varchar); 
+
+procedure myproc (p1 in number, p2 out number);
+END adodb;
+/
+
+CREATE OR REPLACE PACKAGE BODY adodb AS
+PROCEDURE open_tab (tabcursor IN OUT TabType,tablenames in varchar) IS
+	BEGIN
+		OPEN tabcursor FOR SELECT * FROM tab where tname like tablenames;
+	END open_tab;
+	
+PROCEDURE data_out(input IN varchar, output OUT varchar) IS
+	BEGIN
+		output := 'Cinta Hati '||input;
+	END;
+	
+procedure myproc (p1 in number, p2 out number) as
+begin
+p2 := p1;
+end;
+END adodb;
+/
+
+------------------------------------------------------------------
+-- END PACKAGE
+------------------------------------------------------------------
+
+*/
+
+include('../adodb.inc.php');
+include('../tohtml.inc.php');
+
+	error_reporting(E_ALL);
+	$db = ADONewConnection('oci8');
+	$db->PConnect('','scott','natsoft');
+	$db->debug = 99;
+
+
+/*
+*/
+
+	define('MYNUM',5);
+	
+
+	$rs = $db->ExecuteCursor("BEGIN adodb.open_tab(:RS,'A%'); END;");
+	
+	if ($rs && !$rs->EOF) {
+		print "Test 1 RowCount: ".$rs->RecordCount()."<p>";
+	} else {
+		print "<b>Error in using Cursor Variables 1</b><p>";
+	}
+	
+	print "<h4>Testing Stored Procedures for oci8</h4>";
+	
+	$stid = $db->PrepareSP('BEGIN adodb.myproc('.MYNUM.', :myov); END;');
+	$db->OutParameter($stid, $myov, 'myov');
+	$db->Execute($stid);
+	if ($myov != MYNUM) print "<p><b>Error with myproc</b></p>";
+	
+	
+	$stmt = $db->PrepareSP("BEGIN adodb.data_out(:a1, :a2); END;",true);
+	$a1 = 'Malaysia';
+	//$a2 = ''; # a2 doesn't even need to be defined!
+	$db->InParameter($stmt,$a1,'a1');
+	$db->OutParameter($stmt,$a2,'a2');
+	$rs = $db->Execute($stmt);
+	if ($rs) {
+		if ($a2 !== 'Cinta Hati Malaysia') print "<b>Stored Procedure Error: a2 = $a2</b><p>";
+		else echo  "OK: a2=$a2<p>";
+	} else {
+		print "<b>Error in using Stored Procedure IN/Out Variables</b><p>";
+	}
+	
+	
+	$tname = 'A%';
+	
+	$stmt = $db->PrepareSP('select * from tab where tname like :tablename');
+	$db->Parameter($stmt,$tname,'tablename');
+	$rs = $db->Execute($stmt);
+	rs2html($rs);
+		
+		
+?>
Index: /Dev/trunk/rdfapi/util/adodb/tests/testpaging.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/tests/testpaging.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/tests/testpaging.php	(revision 12)
@@ -0,0 +1,86 @@
+<?php
+/* 
+V4.80 8 Mar 2006  (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence. 
+  Set tabs to 4 for best viewing.
+	
+  Latest version is available at http://adodb.sourceforge.net
+*/
+
+error_reporting(E_ALL);
+
+
+include_once('../adodb.inc.php');
+include_once('../adodb-pager.inc.php');
+
+$driver = 'oci8';
+$sql = 'select  ID, firstname as "First Name", lastname as "Last Name" from adoxyz  order  by  id';
+//$sql = 'select count(*),firstname from adoxyz group by firstname order by 2 ';
+//$sql = 'select distinct firstname, lastname from adoxyz  order  by  firstname';
+
+if ($driver == 'postgres') {
+	$db = NewADOConnection('postgres');
+	$db->PConnect('localhost','tester','test','test');
+}
+
+if ($driver == 'access') {
+	$db = NewADOConnection('access');
+	$db->PConnect("nwind", "", "", "");
+}
+
+if ($driver == 'ibase') {
+	$db = NewADOConnection('ibase');
+	$db->PConnect("localhost:e:\\firebird\\examples\\employee.gdb", "sysdba", "masterkey", "");
+	$sql = 'select distinct firstname, lastname  from adoxyz  order  by  firstname';
+
+}
+if ($driver == 'mssql') {
+	$db = NewADOConnection('mssql');
+	$db->Connect('JAGUAR\vsdotnet','adodb','natsoft','northwind');
+}
+if ($driver == 'oci8') {
+	$db = NewADOConnection('oci8');
+	$db->Connect('','scott','natsoft');
+	
+$sql = "select * from (select  ID, firstname as \"First Name\", lastname as \"Last Name\" from adoxyz 
+	 order  by  1)";
+}
+
+if ($driver == 'access') {
+	$db = NewADOConnection('access');
+	$db->Connect('nwind');
+}
+
+if (empty($driver) or $driver == 'mysql') {
+	$db = NewADOConnection('mysql');
+	$db->Connect('localhost','root','','test');
+}
+
+//$db->pageExecuteCountRows = false;
+
+$db->debug = true;
+
+if (0) {
+$rs = &$db->Execute($sql);
+include_once('../toexport.inc.php');
+print "<pre>";
+print rs2csv($rs); # return a string
+
+print '<hr />';
+$rs->MoveFirst(); # note, some databases do not support MoveFirst
+print rs2tab($rs); # return a string
+
+print '<hr />';
+$rs->MoveFirst();
+rs2tabout($rs); # send to stdout directly
+print "</pre>";
+}
+
+$pager = new ADODB_Pager($db,$sql);
+$pager->showPageLinks = true;
+$pager->linksPerPage = 10;
+$pager->cache = 60;
+$pager->Render($rows=7);
+?>
Index: /Dev/trunk/rdfapi/util/adodb/tests/testpear.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/tests/testpear.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/tests/testpear.php	(revision 12)
@@ -0,0 +1,34 @@
+<?php
+/* 
+V4.80 8 Mar 2006  (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence. 
+  Set tabs to 4 for best viewing.
+	
+  Latest version is available at http://adodb.sourceforge.net
+*/
+
+error_reporting(E_ALL);
+
+include_once('../adodb-pear.inc.php');
+$username = 'root';
+$password = '';
+$hostname = 'localhost';
+$databasename = 'xphplens';
+$driver = 'mysql';
+
+$dsn = "$driver://$username:$password@$hostname/$databasename";
+
+$db = DB::Connect($dsn);
+$db->setFetchMode(ADODB_FETCH_ASSOC);
+$rs = $db->Query('select firstname,lastname from adoxyz');
+$cnt = 0;
+while ($arr = $rs->FetchRow()) {
+	print_r($arr);
+	print "<br>";
+	$cnt += 1;
+}
+
+if ($cnt != 50) print "<b>Error in \$cnt = $cnt</b>";
+?>
Index: /Dev/trunk/rdfapi/util/adodb/tests/testsessions.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/tests/testsessions.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/tests/testsessions.php	(revision 12)
@@ -0,0 +1,90 @@
+<?php
+
+/* 
+V4.80 8 Mar 2006  (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence. 
+  Set tabs to 4 for best viewing.
+	
+  Latest version is available at http://adodb.sourceforge.net
+*/
+
+function NotifyExpire($ref,$key)
+{
+	print "<p><b>Notify Expiring=$ref, sessionkey=$key</b></p>";
+}
+
+//-------------------------------------------------------------------
+	
+error_reporting(E_ALL);
+
+
+ob_start();
+include('../session/adodb-cryptsession2.php');
+
+$options['debug'] = 99;
+$db = 'postgres';
+
+#### CONNECTION
+switch($db) {
+case 'oci8': 
+	$options['table'] = 'adodb_sessions2';
+	ADOdb_Session::config('oci8', '', 'jcollect', 'natsoft', '',$options);
+	break;
+
+case 'postgres':
+	ADOdb_Session::config('postgres', 'localhost', 'tester', 'test', 'test',$options);
+	break;
+	
+case 'mysql':
+default:
+	ADOdb_Session::config('mysql', 'localhost', 'root', '', 'xphplens_2',$options);
+	break;
+
+
+}
+	
+
+	
+#### SETUP NOTIFICATION
+	$USER = 'JLIM'.rand();
+	$ADODB_SESSION_EXPIRE_NOTIFY = array('USER','NotifyExpire');
+
+	adodb_session_create_table();
+	session_start();
+
+	adodb_session_regenerate_id();
+	
+### SETUP SESSION VARIABLES 
+	if (empty($_SESSION['MONKEY'])) $_SESSION['MONKEY'] = array(1,'abc',44.41);
+	else $_SESSION['MONKEY'][0] += 1;
+	if (!isset($_GET['nochange'])) @$_SESSION['AVAR'] += 1;
+
+	
+### START DISPLAY
+	print "<h3>PHP ".PHP_VERSION."</h3>";
+	print "<p><b>\$_SESSION['AVAR']={$_SESSION['AVAR']}</b></p>";
+	
+	print "<hr /> <b>Cookies</b>: ";
+	print_r($_COOKIE);
+	
+	var_dump($_SESSION['MONKEY']);
+	
+### RANDOMLY PERFORM Garbage Collection
+### In real-production environment, this is done for you
+### by php's session extension, which calls adodb_sess_gc()
+### automatically for you. See php.ini's
+### session.cookie_lifetime and session.gc_probability
+
+	if (rand() % 5 == 0) {
+	
+		print "<hr /><p><b>Garbage Collection</b></p>";
+		adodb_sess_gc(10);
+		
+		if (rand() % 2 == 0) {
+			print "<p>Random session destroy</p>";
+			session_destroy();
+		}
+	}
+?>
Index: /Dev/trunk/rdfapi/util/adodb/tests/time.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/tests/time.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/tests/time.php	(revision 12)
@@ -0,0 +1,17 @@
+<?php
+
+include_once('../adodb-time.inc.php');
+//adodb_date_test();
+?>
+<?php 
+//require("adodb-time.inc.php"); 
+
+$datestring = "1963-12-04"; // string normally from mySQL 
+$stringArray = explode("-", $datestring);
+$date = adodb_mktime(0,0,0,$stringArray[1],$stringArray[2],$stringArray[0]); 
+
+$convertedDate = date("d-M-Y", $date); // converted string to UK style date
+
+echo( "Birthday: $convertedDate" ); //why is string returned as one day (3 not 4) less for this example??
+
+?>
Index: /Dev/trunk/rdfapi/util/adodb/tests/tmssql.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/tests/tmssql.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/tests/tmssql.php	(revision 12)
@@ -0,0 +1,80 @@
+<?php
+error_reporting(E_ALL);
+ini_set('mssql.datetimeconvert',0); 
+
+function tmssql()
+{
+	print "<h3>mssql</h3>";
+	$db = mssql_connect('JAGUAR\vsdotnet','adodb','natsoft') or die('No Connection');
+	mssql_select_db('northwind',$db);
+	
+	$rs = mssql_query('select getdate() as date',$db);
+	$o = mssql_fetch_row($rs);
+	print_r($o);
+	mssql_free_result($rs);
+	
+	print "<p>Delete</p>"; flush();
+	$rs2 = mssql_query('delete from adoxyz',$db);
+	$p = mssql_num_rows($rs2);
+	mssql_free_result($rs2);
+
+}
+
+function tpear()
+{
+include_once('DB.php');
+
+	print "<h3>PEAR</h3>";
+	$username = 'adodb';
+	$password = 'natsoft';
+	$hostname = 'JAGUAR\vsdotnet';
+	$databasename = 'northwind';
+	
+	$dsn = "mssql://$username:$password@$hostname/$databasename";
+	$conn = &DB::connect($dsn);
+	print "date=".$conn->GetOne('select getdate()')."<br>";
+	@$conn->query('create table tester (id integer)');
+	print "<p>Delete</p>"; flush();
+	$rs = $conn->query('delete from tester');
+	print "date=".$conn->GetOne('select getdate()')."<br>";
+}
+
+function tadodb()
+{
+include_once('../adodb.inc.php');
+
+	print "<h3>ADOdb</h3>";
+	$conn = NewADOConnection('mssql');
+	$conn->Connect('JAGUAR\vsdotnet','adodb','natsoft','northwind');
+//	$conn->debug=1;
+	print "date=".$conn->GetOne('select getdate()')."<br>";
+	$conn->Execute('create table tester (id integer)');
+	print "<p>Delete</p>"; flush();
+	$rs = $conn->Execute('delete from tester');
+	print "date=".$conn->GetOne('select getdate()')."<br>";
+}
+
+
+$ACCEPTIP = '127.0.0.1';
+
+$remote = $_SERVER["REMOTE_ADDR"]; 
+
+if (!empty($ACCEPTIP))
+ if ($remote != '127.0.0.1' && $remote != $ACCEPTIP) 
+ 	die("Unauthorised client: '$remote'");
+	
+?>
+<a href=tmssql.php?do=tmssql>mssql</a>
+<a href=tmssql.php?do=tpear>pear</a>
+<a href=tmssql.php?do=tadodb>adodb</a>
+<?php
+if (!empty($_GET['do'])) {
+	$do = $_GET['do'];
+	switch($do) {
+	case 'tpear':
+	case 'tadodb':
+	case 'tmssql':
+		$do();
+	}
+}
+?>
Index: /Dev/trunk/rdfapi/util/adodb/tests/xmlschema-mssql.xml
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/tests/xmlschema-mssql.xml	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/tests/xmlschema-mssql.xml	(revision 12)
@@ -0,0 +1,34 @@
+<?xml version="1.0"?>
+<schema version="0.3">
+<table name="simple_table">
+<field name="id" type="I" size="11">
+<KEY/>
+<AUTOINCREMENT/>
+</field>
+<field name="name" type="C" size="3">
+<DEFAULT value="no"/>
+</field>
+<field name="description" type="X"></field>
+<index name="id">
+<UNIQUE/>
+<col>id</col>
+</index>
+<index name="id_2">
+<col>id</col>
+</index>
+<data>
+</data>
+</table>
+  <sql>
+    <descr>SQL to be executed only on specific platforms</descr>
+    <query platform="postgres|postgres7">
+      insert into mytable ( row1, row2 ) values ( 12, 'postgres stuff' )
+    </query>
+    <query platform="mysql">
+      insert into mytable ( row1, row2 ) values ( 12, 'mysql stuff' )
+    </query>
+	<query platform="mssql">
+      INSERT into simple_table ( name, description ) values ( '12', 'Microsoft stuff' )
+    </query>
+  </sql>
+</schema>
Index: /Dev/trunk/rdfapi/util/adodb/tests/xmlschema.xml
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/tests/xmlschema.xml	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/tests/xmlschema.xml	(revision 12)
@@ -0,0 +1,33 @@
+<?xml version="1.0"?>
+<schema version="0.3">
+  <table name="mytable">
+    <field name="row1" type="I">
+      <descr>An integer row that's a primary key and autoincrements</descr>
+      <KEY/>
+      <AUTOINCREMENT/>
+    </field>
+    <field name="row2" type="C" size="16">
+      <descr>A 16 character varchar row that can't be null</descr>
+      <NOTNULL/>
+    </field>
+    <index name="myindex">
+      <col>row1</col>
+      <col>row2</col>
+    </index>
+  </table>
+  <sql>
+    <descr>SQL to be executed only on specific platforms</descr>
+    <query platform="postgres|postgres7">
+      insert into mytable ( row1, row2 ) values ( 12, 'postgres stuff' )
+    </query>
+    <query platform="mysql">
+      insert into mytable ( row1, row2 ) values ( 12, 'mysql stuff' )
+    </query>
+	<query platform="mssql">
+      insert into mytable ( row1, row2 ) values ( 12, 'Microsoft stuff' )
+    </query>
+  </sql>
+  <table name="obsoletetable">
+    <DROP/>
+  </table>
+</schema>
Index: /Dev/trunk/rdfapi/util/adodb/toexport.inc.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/toexport.inc.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/toexport.inc.php	(revision 12)
@@ -0,0 +1,133 @@
+<?php
+
+/** 
+ * @version V4.93 10 Oct 2006 (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
+ * Released under both BSD license and Lesser GPL library license. 
+ * Whenever there is any discrepancy between the two licenses, 
+ * the BSD license will take precedence. 
+ *
+ * Code to export recordsets in several formats:
+ *
+ * AS VARIABLE
+ * $s = rs2csv($rs); # comma-separated values
+ * $s = rs2tab($rs); # tab delimited
+ * 
+ * TO A FILE
+ * $f = fopen($path,'w');
+ * rs2csvfile($rs,$f);
+ * fclose($f);
+ *
+ * TO STDOUT
+ * rs2csvout($rs);
+ */
+ 
+// returns a recordset as a csv string
+function rs2csv(&$rs,$addtitles=true)
+{
+	return _adodb_export($rs,',',',',false,$addtitles);
+}
+
+// writes recordset to csv file 
+function rs2csvfile(&$rs,$fp,$addtitles=true)
+{
+	_adodb_export($rs,',',',',$fp,$addtitles);
+}
+
+// write recordset as csv string to stdout
+function rs2csvout(&$rs,$addtitles=true)
+{
+	$fp = fopen('php://stdout','wb');
+	_adodb_export($rs,',',',',true,$addtitles);
+	fclose($fp);
+}
+
+function rs2tab(&$rs,$addtitles=true)
+{
+	return _adodb_export($rs,"\t",',',false,$addtitles);
+}
+
+// to file pointer
+function rs2tabfile(&$rs,$fp,$addtitles=true)
+{
+	_adodb_export($rs,"\t",',',$fp,$addtitles);
+}
+
+// to stdout
+function rs2tabout(&$rs,$addtitles=true)
+{
+	$fp = fopen('php://stdout','wb');
+	_adodb_export($rs,"\t",' ',true,$addtitles);
+	if ($fp) fclose($fp);
+}
+
+function _adodb_export(&$rs,$sep,$sepreplace,$fp=false,$addtitles=true,$quote = '"',$escquote = '"',$replaceNewLine = ' ')
+{
+	if (!$rs) return '';
+	//----------
+	// CONSTANTS
+	$NEWLINE = "\r\n";
+	$BUFLINES = 100;
+	$escquotequote = $escquote.$quote;
+	$s = '';
+	
+	if ($addtitles) {
+		$fieldTypes = $rs->FieldTypesArray();
+		reset($fieldTypes);
+		while(list(,$o) = each($fieldTypes)) {
+			
+			$v = $o->name;
+			if ($escquote) $v = str_replace($quote,$escquotequote,$v);
+			$v = strip_tags(str_replace("\n", $replaceNewLine, str_replace("\r\n",$replaceNewLine,str_replace($sep,$sepreplace,$v))));
+			$elements[] = $v;
+			
+		}
+		$s .= implode($sep, $elements).$NEWLINE;
+	}
+	$hasNumIndex = isset($rs->fields[0]);
+	
+	$line = 0;
+	$max = $rs->FieldCount();
+	
+	while (!$rs->EOF) {
+		$elements = array();
+		$i = 0;
+		
+		if ($hasNumIndex) {
+			for ($j=0; $j < $max; $j++) {
+				$v = $rs->fields[$j];
+				if (!is_object($v)) $v = trim($v);
+				else $v = 'Object';
+				if ($escquote) $v = str_replace($quote,$escquotequote,$v);
+				$v = strip_tags(str_replace("\n", $replaceNewLine, str_replace("\r\n",$replaceNewLine,str_replace($sep,$sepreplace,$v))));
+				
+				if (strpos($v,$sep) !== false || strpos($v,$quote) !== false) $elements[] = "$quote$v$quote";
+				else $elements[] = $v;
+			}
+		} else { // ASSOCIATIVE ARRAY
+			foreach($rs->fields as $v) {
+				if ($escquote) $v = str_replace($quote,$escquotequote,trim($v));
+				$v = strip_tags(str_replace("\n", $replaceNewLine, str_replace("\r\n",$replaceNewLine,str_replace($sep,$sepreplace,$v))));
+				
+				if (strpos($v,$sep) !== false || strpos($v,$quote) !== false) $elements[] = "$quote$v$quote";
+				else $elements[] = $v;
+			}
+		}
+		$s .= implode($sep, $elements).$NEWLINE;
+		$rs->MoveNext();
+		$line += 1;
+		if ($fp && ($line % $BUFLINES) == 0) {
+			if ($fp === true) echo $s;
+			else fwrite($fp,$s);
+			$s = '';
+		}
+	}
+	
+	if ($fp) {
+		if ($fp === true) echo $s;
+		else fwrite($fp,$s);
+		$s = '';
+	}
+	
+	return $s;
+}
+?>
Index: /Dev/trunk/rdfapi/util/adodb/tohtml.inc.php
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/tohtml.inc.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/tohtml.inc.php	(revision 12)
@@ -0,0 +1,195 @@
+<?php 
+/*
+  V4.93 10 Oct 2006  (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence.
+  
+  Some pretty-printing by Chris Oxenreider <oxenreid@state.net>
+*/ 
+  
+// specific code for tohtml
+GLOBAL $gSQLMaxRows,$gSQLBlockRows,$ADODB_ROUND;
+
+$ADODB_ROUND=4; // rounding
+$gSQLMaxRows = 1000; // max no of rows to download
+$gSQLBlockRows=20; // max no of rows per table block
+
+// RecordSet to HTML Table
+//------------------------------------------------------------
+// Convert a recordset to a html table. Multiple tables are generated
+// if the number of rows is > $gSQLBlockRows. This is because
+// web browsers normally require the whole table to be downloaded
+// before it can be rendered, so we break the output into several
+// smaller faster rendering tables.
+//
+// $rs: the recordset
+// $ztabhtml: the table tag attributes (optional)
+// $zheaderarray: contains the replacement strings for the headers (optional)
+//
+//  USAGE:
+//	include('adodb.inc.php');
+//	$db = ADONewConnection('mysql');
+//	$db->Connect('mysql','userid','password','database');
+//	$rs = $db->Execute('select col1,col2,col3 from table');
+//	rs2html($rs, 'BORDER=2', array('Title1', 'Title2', 'Title3'));
+//	$rs->Close();
+//
+// RETURNS: number of rows displayed
+
+
+function rs2html(&$rs,$ztabhtml=false,$zheaderarray=false,$htmlspecialchars=true,$echo = true)
+{
+$s ='';$rows=0;$docnt = false;
+GLOBAL $gSQLMaxRows,$gSQLBlockRows,$ADODB_ROUND;
+
+	if (!$rs) {
+		printf(ADODB_BAD_RS,'rs2html');
+		return false;
+	}
+	
+	if (! $ztabhtml) $ztabhtml = "BORDER='1' WIDTH='98%'";
+	//else $docnt = true;
+	$typearr = array();
+	$ncols = $rs->FieldCount();
+	$hdr = "<TABLE COLS=$ncols $ztabhtml><tr>\n\n";
+	for ($i=0; $i < $ncols; $i++) {	
+		$field = $rs->FetchField($i);
+		if ($field) {
+			if ($zheaderarray) $fname = $zheaderarray[$i];
+			else $fname = htmlspecialchars($field->name);	
+			$typearr[$i] = $rs->MetaType($field->type,$field->max_length);
+ 			//print " $field->name $field->type $typearr[$i] ";
+		} else {
+			$fname = 'Field '.($i+1);
+			$typearr[$i] = 'C';
+		}
+		if (strlen($fname)==0) $fname = '&nbsp;';
+		$hdr .= "<TH>$fname</TH>";
+	}
+	$hdr .= "\n</tr>";
+	if ($echo) print $hdr."\n\n";
+	else $html = $hdr;
+	
+	// smart algorithm - handles ADODB_FETCH_MODE's correctly by probing...
+	$numoffset = isset($rs->fields[0]) ||isset($rs->fields[1]) || isset($rs->fields[2]);
+	while (!$rs->EOF) {
+		
+		$s .= "<TR valign=top>\n";
+		
+		for ($i=0; $i < $ncols; $i++) {
+			if ($i===0) $v=($numoffset) ? $rs->fields[0] : reset($rs->fields);
+			else $v = ($numoffset) ? $rs->fields[$i] : next($rs->fields);
+			
+			$type = $typearr[$i];
+			switch($type) {
+			case 'D':
+				if (empty($v)) $s .= "<TD> &nbsp; </TD>\n";
+				else if (!strpos($v,':')) {
+					$s .= "	<TD>".$rs->UserDate($v,"D d, M Y") ."&nbsp;</TD>\n";
+				}
+				break;
+			case 'T':
+				if (empty($v)) $s .= "<TD> &nbsp; </TD>\n";
+				else $s .= "	<TD>".$rs->UserTimeStamp($v,"D d, M Y, h:i:s") ."&nbsp;</TD>\n";
+			break;
+			
+			case 'N':
+				if (abs(abs($v) - round($v,0)) < 0.00000001)
+					$v = round($v);
+				else
+					$v = round($v,$ADODB_ROUND);
+			case 'I':
+				$s .= "	<TD align=right>".stripslashes((trim($v))) ."&nbsp;</TD>\n";
+			   	
+			break;
+			/*
+			case 'B':
+				if (substr($v,8,2)=="BM" ) $v = substr($v,8);
+				$mtime = substr(str_replace(' ','_',microtime()),2);
+				$tmpname = "tmp/".uniqid($mtime).getmypid();
+				$fd = @fopen($tmpname,'a');
+				@ftruncate($fd,0);
+				@fwrite($fd,$v);
+				@fclose($fd);
+				if (!function_exists ("mime_content_type")) {
+				  function mime_content_type ($file) {
+				    return exec("file -bi ".escapeshellarg($file));
+				  }
+				}
+				$t = mime_content_type($tmpname);
+				$s .= (substr($t,0,5)=="image") ? " <td><img src='$tmpname' alt='$t'></td>\\n" : " <td><a
+				href='$tmpname'>$t</a></td>\\n";
+				break;
+			*/
+
+			default:
+				if ($htmlspecialchars) $v = htmlspecialchars(trim($v));
+				$v = trim($v);
+				if (strlen($v) == 0) $v = '&nbsp;';
+				$s .= "	<TD>". str_replace("\n",'<br>',stripslashes($v)) ."</TD>\n";
+			  
+			}
+		} // for
+		$s .= "</TR>\n\n";
+			  
+		$rows += 1;
+		if ($rows >= $gSQLMaxRows) {
+			$rows = "<p>Truncated at $gSQLMaxRows</p>";
+			break;
+		} // switch
+
+		$rs->MoveNext();
+	
+	// additional EOF check to prevent a widow header
+		if (!$rs->EOF && $rows % $gSQLBlockRows == 0) {
+	
+		//if (connection_aborted()) break;// not needed as PHP aborts script, unlike ASP
+			if ($echo) print $s . "</TABLE>\n\n";
+			else $html .= $s ."</TABLE>\n\n";
+			$s = $hdr;
+		}
+	} // while
+
+	if ($echo) print $s."</TABLE>\n\n";
+	else $html .= $s."</TABLE>\n\n";
+	
+	if ($docnt) if ($echo) print "<H2>".$rows." Rows</H2>";
+	
+	return ($echo) ? $rows : $html;
+ }
+ 
+// pass in 2 dimensional array
+function arr2html(&$arr,$ztabhtml='',$zheaderarray='')
+{
+	if (!$ztabhtml) $ztabhtml = 'BORDER=1';
+	
+	$s = "<TABLE $ztabhtml>";//';print_r($arr);
+
+	if ($zheaderarray) {
+		$s .= '<TR>';
+		for ($i=0; $i<sizeof($zheaderarray); $i++) {
+			$s .= "	<TH>{$zheaderarray[$i]}</TH>\n";
+		}
+		$s .= "\n</TR>";
+	}
+	
+	for ($i=0; $i<sizeof($arr); $i++) {
+		$s .= '<TR>';
+		$a = &$arr[$i];
+		if (is_array($a)) 
+			for ($j=0; $j<sizeof($a); $j++) {
+				$val = $a[$j];
+				if (empty($val)) $val = '&nbsp;';
+				$s .= "	<TD>$val</TD>\n";
+			}
+		else if ($a) {
+			$s .=  '	<TD>'.$a."</TD>\n";
+		} else $s .= "	<TD>&nbsp;</TD>\n";
+		$s .= "\n</TR>\n";
+	}
+	$s .= '</TABLE>';
+	print $s;
+}
+
+?>
Index: /Dev/trunk/rdfapi/util/adodb/xmlschema.dtd
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/xmlschema.dtd	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/xmlschema.dtd	(revision 12)
@@ -0,0 +1,39 @@
+<?xml version="1.0"?>
+<!DOCTYPE adodb_schema [
+<!ELEMENT schema (table*, sql*)>
+<!ATTLIST schema version CDATA #REQUIRED>
+<!ELEMENT table ((field+|DROP), CONSTRAINT*, descr?, index*, data*)>
+<!ELEMENT field ((NOTNULL|KEY|PRIMARY)?, (AUTO|AUTOINCREMENT)?, (DEFAULT|DEFDATE|DEFTIMESTAMP)?, 
+NOQUOTE?, CONSTRAINT*, descr?)>
+<!ELEMENT data (row+)>
+<!ELEMENT row (f+)>
+<!ELEMENT f (#CDATA)>
+<!ELEMENT descr (#CDATA)>
+<!ELEMENT NOTNULL EMPTY>
+<!ELEMENT KEY EMPTY>
+<!ELEMENT PRIMARY EMPTY>
+<!ELEMENT AUTO EMPTY>
+<!ELEMENT AUTOINCREMENT EMPTY>
+<!ELEMENT DEFAULT EMPTY>
+<!ELEMENT DEFDATE EMPTY>
+<!ELEMENT DEFTIMESTAMP EMPTY>
+<!ELEMENT NOQUOTE EMPTY>
+<!ELEMENT DROP EMPTY>
+<!ELEMENT CONSTRAINT (#CDATA)>
+<!ATTLIST table name CDATA #REQUIRED platform CDATA #IMPLIED version CDATA #IMPLIED>
+<!ATTLIST field name CDATA #REQUIRED type (C|C2|X|X2|B|D|T|L|I|F|N) #REQUIRED size CDATA #IMPLIED>
+<!ATTLIST data platform CDATA #IMPLIED>
+<!ATTLIST f name CDATA #IMPLIED>
+<!ATTLIST DEFAULT VALUE CDATA #REQUIRED>
+<!ELEMENT index ((col+|DROP), CLUSTERED?, BITMAP?, UNIQUE?, FULLTEXT?, HASH?, descr?)>
+<!ELEMENT col (#CDATA)>
+<!ELEMENT CLUSTERED EMPTY>
+<!ELEMENT BITMAP EMPTY>
+<!ELEMENT UNIQUE EMPTY>
+<!ELEMENT FULLTEXT EMPTY>
+<!ELEMENT HASH EMPTY>
+<!ATTLIST index name CDATA #REQUIRED platform CDATA #IMPLIED>
+<!ELEMENT sql (query+, descr?)>
+<!ELEMENT query (#CDATA)>
+<!ATTLIST sql name CDATA #IMPLIED platform CDATA #IMPLIED, key CDATA, prefixmethod (AUTO|MANUAL|NONE) >
+] >
Index: /Dev/trunk/rdfapi/util/adodb/xmlschema03.dtd
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/xmlschema03.dtd	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/xmlschema03.dtd	(revision 12)
@@ -0,0 +1,43 @@
+<?xml version="1.0"?>
+<!DOCTYPE adodb_schema [
+<!ELEMENT schema (table*, sql*)>
+<!ATTLIST schema version CDATA #REQUIRED>
+<!ELEMENT table (descr?, (field+|DROP), constraint*, opt*, index*, data*)>
+<!ATTLIST table name CDATA #REQUIRED platform CDATA #IMPLIED version CDATA #IMPLIED>
+<!ELEMENT field (descr?, (NOTNULL|KEY|PRIMARY)?, (AUTO|AUTOINCREMENT)?, (DEFAULT|DEFDATE|DEFTIMESTAMP)?, NOQUOTE?, UNSIGNED?, constraint*, opt*)>
+<!ATTLIST field name CDATA #REQUIRED type (C|C2|X|X2|B|D|T|L|I|F|N) #REQUIRED size CDATA #IMPLIED opts CDATA #IMPLIED>
+<!ELEMENT data (descr?, row+)>
+<!ATTLIST data platform CDATA #IMPLIED>
+<!ELEMENT row (f+)>
+<!ELEMENT f (#CDATA)>
+<!ATTLIST f name CDATA #IMPLIED>
+<!ELEMENT descr (#CDATA)>
+<!ELEMENT NOTNULL EMPTY>
+<!ELEMENT KEY EMPTY>
+<!ELEMENT PRIMARY EMPTY>
+<!ELEMENT AUTO EMPTY>
+<!ELEMENT AUTOINCREMENT EMPTY>
+<!ELEMENT DEFAULT EMPTY>
+<!ATTLIST DEFAULT value CDATA #REQUIRED>
+<!ELEMENT DEFDATE EMPTY>
+<!ELEMENT DEFTIMESTAMP EMPTY>
+<!ELEMENT NOQUOTE EMPTY>
+<!ELEMENT UNSIGNED EMPTY>
+<!ELEMENT DROP EMPTY>
+<!ELEMENT constraint (#CDATA)>
+<!ATTLIST constraint platform CDATA #IMPLIED>
+<!ELEMENT opt (#CDATA)>
+<!ATTLIST opt platform CDATA #IMPLIED>
+<!ELEMENT index ((col+|DROP), CLUSTERED?, BITMAP?, UNIQUE?, FULLTEXT?, HASH?, descr?)>
+<!ATTLIST index name CDATA #REQUIRED platform CDATA #IMPLIED>
+<!ELEMENT col (#CDATA)>
+<!ELEMENT CLUSTERED EMPTY>
+<!ELEMENT BITMAP EMPTY>
+<!ELEMENT UNIQUE EMPTY>
+<!ELEMENT FULLTEXT EMPTY>
+<!ELEMENT HASH EMPTY>
+<!ELEMENT sql (query+, descr?)>
+<!ATTLIST sql name CDATA #IMPLIED platform CDATA #IMPLIED, key CDATA, prefixmethod (AUTO|MANUAL|NONE)>
+<!ELEMENT query (#CDATA)>
+<!ATTLIST query platform CDATA #IMPLIED>
+]>
Index: /Dev/trunk/rdfapi/util/adodb/xsl/convert-0.1-0.2.xsl
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/xsl/convert-0.1-0.2.xsl	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/xsl/convert-0.1-0.2.xsl	(revision 12)
@@ -0,0 +1,205 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<xsl:stylesheet version="1.0"
+	xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
+>
+	<xsl:output method="xml" indent="yes" omit-xml-declaration="no" encoding="UTF-8"/>
+	
+	<!-- Schema -->
+	<xsl:template match="/">
+		<xsl:comment>
+ADODB XMLSchema
+http://adodb-xmlschema.sourceforge.net
+</xsl:comment>
+		
+		<xsl:element name="schema">
+			<xsl:attribute name="version">0.2</xsl:attribute>
+			
+			<xsl:apply-templates select="schema/table|schema/sql"/>
+		</xsl:element>
+	</xsl:template>
+	
+	<!-- Table -->
+	<xsl:template match="table">
+		<xsl:variable name="table_name" select="@name"/>
+		
+		<xsl:element name="table">
+			<xsl:attribute name="name"><xsl:value-of select="$table_name"/></xsl:attribute>
+			
+			<xsl:if test="string-length(@platform) > 0">
+				<xsl:attribute name="platform"><xsl:value-of select="@platform"/></xsl:attribute>
+			</xsl:if>
+			
+			<xsl:if test="string-length(@version) > 0">
+				<xsl:attribute name="version"><xsl:value-of select="@version"/></xsl:attribute>
+			</xsl:if>
+			
+			<xsl:apply-templates select="descr[1]"/>
+			
+			<xsl:choose>
+				<xsl:when test="count(DROP) > 0">
+					<xsl:element name="DROP"/>
+				</xsl:when>
+				<xsl:otherwise>
+					<xsl:apply-templates select="field"/>
+				</xsl:otherwise>
+			</xsl:choose>
+			
+			<xsl:apply-templates select="constraint"/>
+			
+			<xsl:apply-templates select="../index[@table=$table_name]"/>
+		</xsl:element>
+	</xsl:template>
+	
+	<!-- Field -->
+	<xsl:template match="field">
+		<xsl:element name="field">
+			<xsl:attribute name="name"><xsl:value-of select="@name"/></xsl:attribute>
+			<xsl:attribute name="type"><xsl:value-of select="@type"/></xsl:attribute>
+			
+			<xsl:if test="string-length(@size) > 0">
+				<xsl:attribute name="size"><xsl:value-of select="@size"/></xsl:attribute>
+			</xsl:if>
+			
+			<xsl:choose>
+				<xsl:when test="count(PRIMARY) > 0">
+					<xsl:element name="PRIMARY"/>
+				</xsl:when>
+				<xsl:when test="count(KEY) > 0">
+					<xsl:element name="KEY"/>
+				</xsl:when>
+				<xsl:when test="count(NOTNULL) > 0">
+					<xsl:element name="NOTNULL"/>
+				</xsl:when>
+			</xsl:choose>
+			
+			<xsl:choose>
+				<xsl:when test="count(AUTO) > 0">
+					<xsl:element name="AUTO"/>
+				</xsl:when>
+				<xsl:when test="count(AUTOINCREMENT) > 0">
+					<xsl:element name="AUTOINCREMENT"/>
+				</xsl:when>
+			</xsl:choose>
+			
+			<xsl:choose>
+				<xsl:when test="count(DEFAULT) > 0">
+					<xsl:element name="DEFAULT">
+						<xsl:attribute name="value">
+							<xsl:value-of select="DEFAULT[1]/@value"/>
+						</xsl:attribute>
+					</xsl:element>
+				</xsl:when>
+				<xsl:when test="count(DEFDATE) > 0">
+					<xsl:element name="DEFDATE">
+						<xsl:attribute name="value">
+							<xsl:value-of select="DEFDATE[1]/@value"/>
+						</xsl:attribute>
+					</xsl:element>
+				</xsl:when>
+				<xsl:when test="count(DEFTIMESTAMP) > 0">
+					<xsl:element name="DEFTIMESTAMP">
+						<xsl:attribute name="value">
+							<xsl:value-of select="DEFTIMESTAMP[1]/@value"/>
+						</xsl:attribute>
+					</xsl:element>
+				</xsl:when>
+			</xsl:choose>
+			
+			<xsl:if test="count(NOQUOTE) > 0">
+				<xsl:element name="NOQUOTE"/>
+			</xsl:if>
+			
+			<xsl:apply-templates select="constraint"/>
+		</xsl:element>
+	</xsl:template>
+	
+	<!-- Constraint -->
+	<xsl:template match="constraint">
+		<xsl:element name="constraint">
+			<xsl:value-of select="normalize-space(text())"/>
+		</xsl:element>
+	</xsl:template>
+	
+	<!-- Index -->
+	<xsl:template match="index">
+		<xsl:element name="index">
+			<xsl:attribute name="name"><xsl:value-of select="@name"/></xsl:attribute>
+			
+			<xsl:apply-templates select="descr[1]"/>
+			
+			<xsl:if test="count(CLUSTERED) > 0">
+				<xsl:element name="CLUSTERED"/>
+			</xsl:if>
+			
+			<xsl:if test="count(BITMAP) > 0">
+				<xsl:element name="BITMAP"/>
+			</xsl:if>
+			
+			<xsl:if test="count(UNIQUE) > 0">
+				<xsl:element name="UNIQUE"/>
+			</xsl:if>
+			
+			<xsl:if test="count(FULLTEXT) > 0">
+				<xsl:element name="FULLTEXT"/>
+			</xsl:if>
+			
+			<xsl:if test="count(HASH) > 0">
+				<xsl:element name="HASH"/>
+			</xsl:if>
+			
+			<xsl:choose>
+				<xsl:when test="count(DROP) > 0">
+					<xsl:element name="DROP"/>
+				</xsl:when>
+				<xsl:otherwise>
+					<xsl:apply-templates select="col"/>
+				</xsl:otherwise>
+			</xsl:choose>
+		</xsl:element>
+	</xsl:template>
+	
+	<!-- Index Column -->
+	<xsl:template match="col">
+		<xsl:element name="col">
+			<xsl:value-of select="normalize-space(text())"/>
+		</xsl:element>
+	</xsl:template>
+	
+	<!-- SQL QuerySet -->
+	<xsl:template match="sql">
+		<xsl:element name="sql">
+			<xsl:if test="string-length(@platform) > 0">
+				<xsl:attribute name="platform"><xsl:value-of select="@platform"/></xsl:attribute>
+			</xsl:if>
+			
+			<xsl:if test="string-length(@key) > 0">
+				<xsl:attribute name="key"><xsl:value-of select="@key"/></xsl:attribute>
+			</xsl:if>
+			
+			<xsl:if test="string-length(@prefixmethod) > 0">
+				<xsl:attribute name="prefixmethod"><xsl:value-of select="@prefixmethod"/></xsl:attribute>
+			</xsl:if>
+			
+			<xsl:apply-templates select="descr[1]"/>
+			<xsl:apply-templates select="query"/>
+		</xsl:element>
+	</xsl:template>
+	
+	<!-- Query -->
+	<xsl:template match="query">
+		<xsl:element name="query">
+			<xsl:if test="string-length(@platform) > 0">
+				<xsl:attribute name="platform"><xsl:value-of select="@platform"/></xsl:attribute>
+			</xsl:if>
+			
+			<xsl:value-of select="normalize-space(text())"/>
+		</xsl:element>
+	</xsl:template>
+	
+	<!-- Description -->
+	<xsl:template match="descr">
+		<xsl:element name="descr">
+			<xsl:value-of select="normalize-space(text())"/>
+		</xsl:element>
+	</xsl:template>
+</xsl:stylesheet>
Index: /Dev/trunk/rdfapi/util/adodb/xsl/convert-0.1-0.3.xsl
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/xsl/convert-0.1-0.3.xsl	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/xsl/convert-0.1-0.3.xsl	(revision 12)
@@ -0,0 +1,221 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<xsl:stylesheet version="1.0"
+	xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
+>
+	<xsl:output method="xml" indent="yes" omit-xml-declaration="no" encoding="UTF-8"/>
+	
+	<!-- Schema -->
+	<xsl:template match="/">
+		<xsl:comment>
+ADODB XMLSchema
+http://adodb-xmlschema.sourceforge.net
+</xsl:comment>
+		
+		<xsl:element name="schema">
+			<xsl:attribute name="version">0.3</xsl:attribute>
+			
+			<xsl:apply-templates select="schema/table|schema/sql"/>
+		</xsl:element>
+	</xsl:template>
+	
+	<!-- Table -->
+	<xsl:template match="table">
+		<xsl:variable name="table_name" select="@name"/>
+		
+		<xsl:element name="table">
+			<xsl:attribute name="name"><xsl:value-of select="$table_name"/></xsl:attribute>
+			
+			<xsl:if test="string-length(@platform) > 0">
+				<xsl:attribute name="platform"><xsl:value-of select="@platform"/></xsl:attribute>
+			</xsl:if>
+			
+			<xsl:if test="string-length(@version) > 0">
+				<xsl:attribute name="version"><xsl:value-of select="@version"/></xsl:attribute>
+			</xsl:if>
+			
+			<xsl:apply-templates select="descr[1]"/>
+			
+			<xsl:choose>
+				<xsl:when test="count(DROP) > 0">
+					<xsl:element name="DROP"/>
+				</xsl:when>
+				<xsl:otherwise>
+					<xsl:apply-templates select="field"/>
+				</xsl:otherwise>
+			</xsl:choose>
+			
+			<xsl:apply-templates select="constraint"/>
+			
+			<xsl:apply-templates select="../index[@table=$table_name]"/>
+		</xsl:element>
+	</xsl:template>
+	
+	<!-- Field -->
+	<xsl:template match="field">
+		<xsl:element name="field">
+			<xsl:attribute name="name"><xsl:value-of select="@name"/></xsl:attribute>
+			<xsl:attribute name="type"><xsl:value-of select="@type"/></xsl:attribute>
+			
+			<xsl:if test="string-length(@size) > 0">
+				<xsl:attribute name="size"><xsl:value-of select="@size"/></xsl:attribute>
+			</xsl:if>
+			
+			<xsl:choose>
+				<xsl:when test="string-length(@opts) = 0"/>
+				<xsl:when test="@opts = 'UNSIGNED'">
+					<xsl:element name="UNSIGNED"/>
+				</xsl:when>
+				<xsl:when test="contains(@opts,'UNSIGNED')">
+					<xsl:attribute name="opts">
+						<xsl:value-of select="concat(substring-before(@opts,'UNSIGNED'),substring-after(@opts,'UNSIGNED'))"/>
+					</xsl:attribute>
+					<xsl:element name="UNSIGNED"/>
+				</xsl:when>
+				<xsl:otherwise>
+					<xsl:attribute name="opts"><xsl:value-of select="@opts"/></xsl:attribute>
+				</xsl:otherwise>
+			</xsl:choose>
+			
+			<xsl:choose>
+				<xsl:when test="count(PRIMARY) > 0">
+					<xsl:element name="PRIMARY"/>
+				</xsl:when>
+				<xsl:when test="count(KEY) > 0">
+					<xsl:element name="KEY"/>
+				</xsl:when>
+				<xsl:when test="count(NOTNULL) > 0">
+					<xsl:element name="NOTNULL"/>
+				</xsl:when>
+			</xsl:choose>
+			
+			<xsl:choose>
+				<xsl:when test="count(AUTO) > 0">
+					<xsl:element name="AUTO"/>
+				</xsl:when>
+				<xsl:when test="count(AUTOINCREMENT) > 0">
+					<xsl:element name="AUTOINCREMENT"/>
+				</xsl:when>
+			</xsl:choose>
+			
+			<xsl:choose>
+				<xsl:when test="count(DEFAULT) > 0">
+					<xsl:element name="DEFAULT">
+						<xsl:attribute name="value">
+							<xsl:value-of select="DEFAULT[1]/@value"/>
+						</xsl:attribute>
+					</xsl:element>
+				</xsl:when>
+				<xsl:when test="count(DEFDATE) > 0">
+					<xsl:element name="DEFDATE">
+						<xsl:attribute name="value">
+							<xsl:value-of select="DEFDATE[1]/@value"/>
+						</xsl:attribute>
+					</xsl:element>
+				</xsl:when>
+				<xsl:when test="count(DEFTIMESTAMP) > 0">
+					<xsl:element name="DEFTIMESTAMP">
+						<xsl:attribute name="value">
+							<xsl:value-of select="DEFTIMESTAMP[1]/@value"/>
+						</xsl:attribute>
+					</xsl:element>
+				</xsl:when>
+			</xsl:choose>
+			
+			<xsl:if test="count(NOQUOTE) > 0">
+				<xsl:element name="NOQUOTE"/>
+			</xsl:if>
+			
+			<xsl:apply-templates select="constraint"/>
+		</xsl:element>
+	</xsl:template>
+	
+	<!-- Constraint -->
+	<xsl:template match="constraint">
+		<xsl:element name="constraint">
+			<xsl:value-of select="normalize-space(text())"/>
+		</xsl:element>
+	</xsl:template>
+	
+	<!-- Index -->
+	<xsl:template match="index">
+		<xsl:element name="index">
+			<xsl:attribute name="name"><xsl:value-of select="@name"/></xsl:attribute>
+			
+			<xsl:apply-templates select="descr[1]"/>
+			
+			<xsl:if test="count(CLUSTERED) > 0">
+				<xsl:element name="CLUSTERED"/>
+			</xsl:if>
+			
+			<xsl:if test="count(BITMAP) > 0">
+				<xsl:element name="BITMAP"/>
+			</xsl:if>
+			
+			<xsl:if test="count(UNIQUE) > 0">
+				<xsl:element name="UNIQUE"/>
+			</xsl:if>
+			
+			<xsl:if test="count(FULLTEXT) > 0">
+				<xsl:element name="FULLTEXT"/>
+			</xsl:if>
+			
+			<xsl:if test="count(HASH) > 0">
+				<xsl:element name="HASH"/>
+			</xsl:if>
+			
+			<xsl:choose>
+				<xsl:when test="count(DROP) > 0">
+					<xsl:element name="DROP"/>
+				</xsl:when>
+				<xsl:otherwise>
+					<xsl:apply-templates select="col"/>
+				</xsl:otherwise>
+			</xsl:choose>
+		</xsl:element>
+	</xsl:template>
+	
+	<!-- Index Column -->
+	<xsl:template match="col">
+		<xsl:element name="col">
+			<xsl:value-of select="normalize-space(text())"/>
+		</xsl:element>
+	</xsl:template>
+	
+	<!-- SQL QuerySet -->
+	<xsl:template match="sql">
+		<xsl:element name="sql">
+			<xsl:if test="string-length(@platform) > 0">
+				<xsl:attribute name="platform"><xsl:value-of select="@platform"/></xsl:attribute>
+			</xsl:if>
+			
+			<xsl:if test="string-length(@key) > 0">
+				<xsl:attribute name="key"><xsl:value-of select="@key"/></xsl:attribute>
+			</xsl:if>
+			
+			<xsl:if test="string-length(@prefixmethod) > 0">
+				<xsl:attribute name="prefixmethod"><xsl:value-of select="@prefixmethod"/></xsl:attribute>
+			</xsl:if>
+			
+			<xsl:apply-templates select="descr[1]"/>
+			<xsl:apply-templates select="query"/>
+		</xsl:element>
+	</xsl:template>
+	
+	<!-- Query -->
+	<xsl:template match="query">
+		<xsl:element name="query">
+			<xsl:if test="string-length(@platform) > 0">
+				<xsl:attribute name="platform"><xsl:value-of select="@platform"/></xsl:attribute>
+			</xsl:if>
+			
+			<xsl:value-of select="normalize-space(text())"/>
+		</xsl:element>
+	</xsl:template>
+	
+	<!-- Description -->
+	<xsl:template match="descr">
+		<xsl:element name="descr">
+			<xsl:value-of select="normalize-space(text())"/>
+		</xsl:element>
+	</xsl:template>
+</xsl:stylesheet>
Index: /Dev/trunk/rdfapi/util/adodb/xsl/convert-0.2-0.1.xsl
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/xsl/convert-0.2-0.1.xsl	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/xsl/convert-0.2-0.1.xsl	(revision 12)
@@ -0,0 +1,207 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<xsl:stylesheet version="1.0"
+	xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
+>
+	<xsl:output method="xml" indent="yes" omit-xml-declaration="no" encoding="UTF-8"/>
+	
+	<!-- Schema -->
+	<xsl:template match="/">
+		<xsl:comment>
+ADODB XMLSchema
+http://adodb-xmlschema.sourceforge.net
+</xsl:comment>
+		
+		<xsl:element name="schema">
+			<xsl:attribute name="version">0.1</xsl:attribute>
+			
+			<xsl:apply-templates select="schema/table|schema/sql"/>
+		</xsl:element>
+	</xsl:template>
+	
+	<!-- Table -->
+	<xsl:template match="table">
+		<xsl:variable name="table_name" select="@name"/>
+		
+		<xsl:element name="table">
+			<xsl:attribute name="name"><xsl:value-of select="$table_name"/></xsl:attribute>
+			
+			<xsl:if test="string-length(@platform) > 0">
+				<xsl:attribute name="platform"><xsl:value-of select="@platform"/></xsl:attribute>
+			</xsl:if>
+			
+			<xsl:if test="string-length(@version) > 0">
+				<xsl:attribute name="version"><xsl:value-of select="@version"/></xsl:attribute>
+			</xsl:if>
+			
+			<xsl:apply-templates select="descr[1]"/>
+			
+			<xsl:choose>
+				<xsl:when test="count(DROP) > 0">
+					<xsl:element name="DROP"/>
+				</xsl:when>
+				<xsl:otherwise>
+					<xsl:apply-templates select="field"/>
+				</xsl:otherwise>
+			</xsl:choose>
+			
+			<xsl:apply-templates select="constraint"/>
+			
+		</xsl:element>
+		
+		<xsl:apply-templates select="index"/>
+	</xsl:template>
+	
+	<!-- Field -->
+	<xsl:template match="field">
+		<xsl:element name="field">
+			<xsl:attribute name="name"><xsl:value-of select="@name"/></xsl:attribute>
+			<xsl:attribute name="type"><xsl:value-of select="@type"/></xsl:attribute>
+			
+			<xsl:if test="string-length(@size) > 0">
+				<xsl:attribute name="size"><xsl:value-of select="@size"/></xsl:attribute>
+			</xsl:if>
+			
+			<xsl:choose>
+				<xsl:when test="count(PRIMARY) > 0">
+					<xsl:element name="PRIMARY"/>
+				</xsl:when>
+				<xsl:when test="count(KEY) > 0">
+					<xsl:element name="KEY"/>
+				</xsl:when>
+				<xsl:when test="count(NOTNULL) > 0">
+					<xsl:element name="NOTNULL"/>
+				</xsl:when>
+			</xsl:choose>
+			
+			<xsl:choose>
+				<xsl:when test="count(AUTO) > 0">
+					<xsl:element name="AUTO"/>
+				</xsl:when>
+				<xsl:when test="count(AUTOINCREMENT) > 0">
+					<xsl:element name="AUTOINCREMENT"/>
+				</xsl:when>
+			</xsl:choose>
+			
+			<xsl:choose>
+				<xsl:when test="count(DEFAULT) > 0">
+					<xsl:element name="DEFAULT">
+						<xsl:attribute name="value">
+							<xsl:value-of select="DEFAULT[1]/@value"/>
+						</xsl:attribute>
+					</xsl:element>
+				</xsl:when>
+				<xsl:when test="count(DEFDATE) > 0">
+					<xsl:element name="DEFDATE">
+						<xsl:attribute name="value">
+							<xsl:value-of select="DEFDATE[1]/@value"/>
+						</xsl:attribute>
+					</xsl:element>
+				</xsl:when>
+				<xsl:when test="count(DEFTIMESTAMP) > 0">
+					<xsl:element name="DEFDTIMESTAMP">
+						<xsl:attribute name="value">
+							<xsl:value-of select="DEFTIMESTAMP[1]/@value"/>
+						</xsl:attribute>
+					</xsl:element>
+				</xsl:when>
+			</xsl:choose>
+			
+			<xsl:if test="count(NOQUOTE) > 0">
+				<xsl:element name="NOQUOTE"/>
+			</xsl:if>
+			
+			<xsl:apply-templates select="constraint"/>
+		</xsl:element>
+	</xsl:template>
+	
+	<!-- Constraint -->
+	<xsl:template match="constraint">
+		<xsl:element name="constraint">
+			<xsl:value-of select="normalize-space(text())"/>
+		</xsl:element>
+	</xsl:template>
+	
+	<!-- Index -->
+	<xsl:template match="index">
+		<xsl:element name="index">
+			<xsl:attribute name="name"><xsl:value-of select="@name"/></xsl:attribute>
+			<xsl:attribute name="table"><xsl:value-of select="../@name"/></xsl:attribute>
+			
+			<xsl:apply-templates select="descr[1]"/>
+			
+			<xsl:if test="count(CLUSTERED) > 0">
+				<xsl:element name="CLUSTERED"/>
+			</xsl:if>
+			
+			<xsl:if test="count(BITMAP) > 0">
+				<xsl:element name="BITMAP"/>
+			</xsl:if>
+			
+			<xsl:if test="count(UNIQUE) > 0">
+				<xsl:element name="UNIQUE"/>
+			</xsl:if>
+			
+			<xsl:if test="count(FULLTEXT) > 0">
+				<xsl:element name="FULLTEXT"/>
+			</xsl:if>
+			
+			<xsl:if test="count(HASH) > 0">
+				<xsl:element name="HASH"/>
+			</xsl:if>
+			
+			<xsl:choose>
+				<xsl:when test="count(DROP) > 0">
+					<xsl:element name="DROP"/>
+				</xsl:when>
+				<xsl:otherwise>
+					<xsl:apply-templates select="col"/>
+				</xsl:otherwise>
+			</xsl:choose>
+		</xsl:element>
+	</xsl:template>
+	
+	<!-- Index Column -->
+	<xsl:template match="col">
+		<xsl:element name="col">
+			<xsl:value-of select="normalize-space(text())"/>
+		</xsl:element>
+	</xsl:template>
+	
+	<!-- SQL QuerySet -->
+	<xsl:template match="sql">
+		<xsl:element name="sql">
+			<xsl:if test="string-length(@platform) > 0">
+				<xsl:attribute name="platform"><xsl:value-of select="@platform"/></xsl:attribute>
+			</xsl:if>
+			
+			<xsl:if test="string-length(@key) > 0">
+				<xsl:attribute name="key"><xsl:value-of select="@key"/></xsl:attribute>
+			</xsl:if>
+			
+			<xsl:if test="string-length(@prefixmethod) > 0">
+				<xsl:attribute name="prefixmethod"><xsl:value-of select="@prefixmethod"/></xsl:attribute>
+			</xsl:if>
+			
+			<xsl:apply-templates select="descr[1]"/>
+			<xsl:apply-templates select="query"/>
+		</xsl:element>
+	</xsl:template>
+	
+	<!-- Query -->
+	<xsl:template match="query">
+		<xsl:element name="query">
+			<xsl:if test="string-length(@platform) > 0">
+				<xsl:attribute name="platform"><xsl:value-of select="@platform"/></xsl:attribute>
+			</xsl:if>
+			
+			<xsl:value-of select="normalize-space(text())"/>
+		</xsl:element>
+	</xsl:template>
+	
+	<!-- Description -->
+	<xsl:template match="descr">
+		<xsl:element name="descr">
+			<xsl:value-of select="normalize-space(text())"/>
+		</xsl:element>
+	</xsl:template>
+</xsl:stylesheet>
Index: /Dev/trunk/rdfapi/util/adodb/xsl/convert-0.2-0.3.xsl
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/xsl/convert-0.2-0.3.xsl	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/xsl/convert-0.2-0.3.xsl	(revision 12)
@@ -0,0 +1,281 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<xsl:stylesheet version="1.0"
+	xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
+>
+	<xsl:output method="xml" indent="yes" omit-xml-declaration="no" encoding="UTF-8"/>
+	
+	<!-- Schema -->
+	<xsl:template match="/">
+		<xsl:comment>
+ADODB XMLSchema
+http://adodb-xmlschema.sourceforge.net
+</xsl:comment>
+		
+		<xsl:element name="schema">
+			<xsl:attribute name="version">0.3</xsl:attribute>
+			
+			<xsl:apply-templates select="schema/table|schema/sql"/>
+		</xsl:element>
+	</xsl:template>
+	
+	<!-- Table -->
+	<xsl:template match="table">
+		<xsl:element name="table">
+			<xsl:attribute name="name"><xsl:value-of select="@name"/></xsl:attribute>
+			
+			<xsl:if test="string-length(@platform) > 0">
+				<xsl:attribute name="platform"><xsl:value-of select="@platform"/></xsl:attribute>
+			</xsl:if>
+			
+			<xsl:if test="string-length(@version) > 0">
+				<xsl:attribute name="version"><xsl:value-of select="@version"/></xsl:attribute>
+			</xsl:if>
+			
+			<xsl:apply-templates select="descr[1]"/>
+			
+			<xsl:choose>
+				<xsl:when test="count(DROP) > 0">
+					<xsl:element name="DROP"/>
+				</xsl:when>
+				<xsl:otherwise>
+					<xsl:apply-templates select="field"/>
+				</xsl:otherwise>
+			</xsl:choose>
+			
+			<xsl:apply-templates select="constraint"/>
+			
+			<xsl:apply-templates select="opt"/>
+			
+			<xsl:apply-templates select="index"/>
+			
+			<xsl:apply-templates select="data"/>
+		</xsl:element>
+	</xsl:template>
+	
+	<!-- Field -->
+	<xsl:template match="field">
+		<xsl:element name="field">
+			<xsl:attribute name="name"><xsl:value-of select="@name"/></xsl:attribute>
+			<xsl:attribute name="type"><xsl:value-of select="@type"/></xsl:attribute>
+			
+			<xsl:if test="string-length(@size) > 0">
+				<xsl:attribute name="size"><xsl:value-of select="@size"/></xsl:attribute>
+			</xsl:if>
+			
+			<xsl:choose>
+				<xsl:when test="string-length(@opts) = 0">
+					<xsl:if test="count(UNSIGNED) > 0">
+						<xsl:element name="UNSIGNED"/>
+					</xsl:if>
+				</xsl:when>
+				<xsl:when test="@opts = 'UNSIGNED'">
+					<xsl:element name="UNSIGNED"/>
+				</xsl:when>
+				<xsl:when test="contains(@opts,'UNSIGNED')">
+					<xsl:attribute name="opts">
+						<xsl:value-of select="concat(substring-before(@opts,'UNSIGNED'),substring-after(@opts,'UNSIGNED'))"/>
+					</xsl:attribute>
+					<xsl:element name="UNSIGNED"/>
+				</xsl:when>
+				<xsl:otherwise>
+					<xsl:attribute name="opts"><xsl:value-of select="@opts"/></xsl:attribute>
+					<xsl:if test="count(UNSIGNED) > 0">
+						<xsl:element name="UNSIGNED"/>
+					</xsl:if>
+				</xsl:otherwise>
+			</xsl:choose>
+			
+			<xsl:apply-templates select="descr[1]"/>
+			
+			<xsl:choose>
+				<xsl:when test="count(PRIMARY) > 0">
+					<xsl:element name="PRIMARY"/>
+				</xsl:when>
+				<xsl:when test="count(KEY) > 0">
+					<xsl:element name="KEY"/>
+				</xsl:when>
+				<xsl:when test="count(NOTNULL) > 0">
+					<xsl:element name="NOTNULL"/>
+				</xsl:when>
+			</xsl:choose>
+			
+			<xsl:choose>
+				<xsl:when test="count(AUTO) > 0">
+					<xsl:element name="AUTO"/>
+				</xsl:when>
+				<xsl:when test="count(AUTOINCREMENT) > 0">
+					<xsl:element name="AUTOINCREMENT"/>
+				</xsl:when>
+			</xsl:choose>
+			
+			<xsl:choose>
+				<xsl:when test="count(DEFAULT) > 0">
+					<xsl:element name="DEFAULT">
+						<xsl:attribute name="value">
+							<xsl:value-of select="DEFAULT[1]/@value"/>
+						</xsl:attribute>
+					</xsl:element>
+				</xsl:when>
+				<xsl:when test="count(DEFDATE) > 0">
+					<xsl:element name="DEFDATE">
+						<xsl:attribute name="value">
+							<xsl:value-of select="DEFDATE[1]/@value"/>
+						</xsl:attribute>
+					</xsl:element>
+				</xsl:when>
+				<xsl:when test="count(DEFTIMESTAMP) > 0">
+					<xsl:element name="DEFTIMESTAMP">
+						<xsl:attribute name="value">
+							<xsl:value-of select="DEFTIMESTAMP[1]/@value"/>
+						</xsl:attribute>
+					</xsl:element>
+				</xsl:when>
+			</xsl:choose>
+			
+			<xsl:if test="count(NOQUOTE) > 0">
+				<xsl:element name="NOQUOTE"/>
+			</xsl:if>
+			
+			<xsl:apply-templates select="constraint"/>
+			
+			<xsl:apply-templates select="opt"/>
+		</xsl:element>
+	</xsl:template>
+	
+	<!-- Constraint -->
+	<xsl:template match="constraint">
+		<xsl:element name="constraint">
+			<xsl:if test="string-length(@platform) > 0">
+				<xsl:attribute name="platform"><xsl:value-of select="@platform"/></xsl:attribute>
+			</xsl:if>
+			
+			<xsl:value-of select="normalize-space(text())"/>
+		</xsl:element>
+	</xsl:template>
+	
+	<!-- Opt -->
+	<xsl:template match="opt">
+		<xsl:element name="opt">
+			<xsl:if test="string-length(@platform) > 0">
+				<xsl:attribute name="platform"><xsl:value-of select="@platform"/></xsl:attribute>
+			</xsl:if>
+			
+			<xsl:value-of select="normalize-space(text())"/>
+		</xsl:element>
+	</xsl:template>
+	
+	<!-- Index -->
+	<xsl:template match="index">
+		<xsl:element name="index">
+			<xsl:attribute name="name"><xsl:value-of select="@name"/></xsl:attribute>
+			
+			<xsl:apply-templates select="descr[1]"/>
+			
+			<xsl:if test="count(CLUSTERED) > 0">
+				<xsl:element name="CLUSTERED"/>
+			</xsl:if>
+			
+			<xsl:if test="count(BITMAP) > 0">
+				<xsl:element name="BITMAP"/>
+			</xsl:if>
+			
+			<xsl:if test="count(UNIQUE) > 0">
+				<xsl:element name="UNIQUE"/>
+			</xsl:if>
+			
+			<xsl:if test="count(FULLTEXT) > 0">
+				<xsl:element name="FULLTEXT"/>
+			</xsl:if>
+			
+			<xsl:if test="count(HASH) > 0">
+				<xsl:element name="HASH"/>
+			</xsl:if>
+			
+			<xsl:choose>
+				<xsl:when test="count(DROP) > 0">
+					<xsl:element name="DROP"/>
+				</xsl:when>
+				<xsl:otherwise>
+					<xsl:apply-templates select="col"/>
+				</xsl:otherwise>
+			</xsl:choose>
+		</xsl:element>
+	</xsl:template>
+	
+	<!-- Index Column -->
+	<xsl:template match="col">
+		<xsl:element name="col">
+			<xsl:value-of select="normalize-space(text())"/>
+		</xsl:element>
+	</xsl:template>
+	
+	<!-- SQL QuerySet -->
+	<xsl:template match="sql">
+		<xsl:element name="sql">
+			<xsl:if test="string-length(@platform) > 0">
+				<xsl:attribute name="platform"><xsl:value-of select="@platform"/></xsl:attribute>
+			</xsl:if>
+			
+			<xsl:if test="string-length(@key) > 0">
+				<xsl:attribute name="key"><xsl:value-of select="@key"/></xsl:attribute>
+			</xsl:if>
+			
+			<xsl:if test="string-length(@prefixmethod) > 0">
+				<xsl:attribute name="prefixmethod"><xsl:value-of select="@prefixmethod"/></xsl:attribute>
+			</xsl:if>
+			
+			<xsl:apply-templates select="descr[1]"/>
+			
+			<xsl:apply-templates select="query"/>
+		</xsl:element>
+	</xsl:template>
+	
+	<!-- Query -->
+	<xsl:template match="query">
+		<xsl:element name="query">
+			<xsl:if test="string-length(@platform) > 0">
+				<xsl:attribute name="platform"><xsl:value-of select="@platform"/></xsl:attribute>
+			</xsl:if>
+			
+			<xsl:value-of select="normalize-space(text())"/>
+		</xsl:element>
+	</xsl:template>
+	
+	<!-- Description -->
+	<xsl:template match="descr">
+		<xsl:element name="descr">
+			<xsl:value-of select="normalize-space(text())"/>
+		</xsl:element>
+	</xsl:template>
+	
+	<!-- Data -->
+	<xsl:template match="data">
+		<xsl:element name="data">
+			<xsl:if test="string-length(@platform) > 0">
+				<xsl:attribute name="platform"><xsl:value-of select="@platform"/></xsl:attribute>
+			</xsl:if>
+			
+			<xsl:apply-templates select="descr[1]"/>
+			
+			<xsl:apply-templates select="row"/>
+		</xsl:element>
+	</xsl:template>
+	
+	<!-- Data Row -->
+	<xsl:template match="row">
+		<xsl:element name="row">
+			<xsl:apply-templates select="f"/>
+		</xsl:element>
+	</xsl:template>
+	
+	<!-- Data Field -->
+	<xsl:template match="f">
+		<xsl:element name="f">
+			<xsl:if test="string-length(@name) > 0">
+				<xsl:attribute name="name"><xsl:value-of select="@name"/></xsl:attribute>
+			</xsl:if>
+			
+			<xsl:value-of select="normalize-space(text())"/>
+		</xsl:element>
+	</xsl:template>
+</xsl:stylesheet>
Index: /Dev/trunk/rdfapi/util/adodb/xsl/remove-0.2.xsl
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/xsl/remove-0.2.xsl	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/xsl/remove-0.2.xsl	(revision 12)
@@ -0,0 +1,54 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<xsl:stylesheet version="1.0"
+	xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
+>
+	<xsl:output method="xml" indent="yes" omit-xml-declaration="no" encoding="UTF-8"/>
+	
+	<!-- Schema -->
+	<xsl:template match="/">
+		<xsl:comment>
+ADODB XMLSchema
+http://adodb-xmlschema.sourceforge.net
+</xsl:comment>
+		
+		<xsl:comment>
+Uninstallation Schema
+</xsl:comment>
+		
+		<xsl:element name="schema">
+			<xsl:attribute name="version">0.2</xsl:attribute>
+			
+			<xsl:apply-templates select="schema/table">
+				<xsl:sort select="position()" data-type="number" order="descending"/>
+			</xsl:apply-templates>
+		</xsl:element>
+	</xsl:template>
+	
+	<!-- Table -->
+	<xsl:template match="table">
+		<xsl:if test="count(DROP) = 0">
+			<xsl:element name="table">
+				<xsl:attribute name="name"><xsl:value-of select="@name"/></xsl:attribute>
+				
+				<xsl:if test="string-length(@platform) > 0">
+					<xsl:attribute name="platform"><xsl:value-of select="@platform"/></xsl:attribute>
+				</xsl:if>
+				
+				<xsl:if test="string-length(@version) > 0">
+					<xsl:attribute name="version"><xsl:value-of select="@version"/></xsl:attribute>
+				</xsl:if>
+				
+				<xsl:apply-templates select="descr[1]"/>
+				
+				<xsl:element name="DROP"/>
+			</xsl:element>
+		</xsl:if>
+	</xsl:template>
+	
+	<!-- Description -->
+	<xsl:template match="descr">
+		<xsl:element name="descr">
+			<xsl:value-of select="normalize-space(text())"/>
+		</xsl:element>
+	</xsl:template>
+</xsl:stylesheet>
Index: /Dev/trunk/rdfapi/util/adodb/xsl/remove-0.3.xsl
===================================================================
--- /Dev/trunk/rdfapi/util/adodb/xsl/remove-0.3.xsl	(revision 12)
+++ /Dev/trunk/rdfapi/util/adodb/xsl/remove-0.3.xsl	(revision 12)
@@ -0,0 +1,54 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<xsl:stylesheet version="1.0"
+	xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
+>
+	<xsl:output method="xml" indent="yes" omit-xml-declaration="no" encoding="UTF-8"/>
+	
+	<!-- Schema -->
+	<xsl:template match="/">
+		<xsl:comment>
+ADODB XMLSchema
+http://adodb-xmlschema.sourceforge.net
+</xsl:comment>
+		
+		<xsl:comment>
+Uninstallation Schema
+</xsl:comment>
+		
+		<xsl:element name="schema">
+			<xsl:attribute name="version">0.3</xsl:attribute>
+			
+			<xsl:apply-templates select="schema/table">
+				<xsl:sort select="position()" data-type="number" order="descending"/>
+			</xsl:apply-templates>
+		</xsl:element>
+	</xsl:template>
+	
+	<!-- Table -->
+	<xsl:template match="table">
+		<xsl:if test="count(DROP) = 0">
+			<xsl:element name="table">
+				<xsl:attribute name="name"><xsl:value-of select="@name"/></xsl:attribute>
+				
+				<xsl:if test="string-length(@platform) > 0">
+					<xsl:attribute name="platform"><xsl:value-of select="@platform"/></xsl:attribute>
+				</xsl:if>
+				
+				<xsl:if test="string-length(@version) > 0">
+					<xsl:attribute name="version"><xsl:value-of select="@version"/></xsl:attribute>
+				</xsl:if>
+				
+				<xsl:apply-templates select="descr[1]"/>
+				
+				<xsl:element name="DROP"/>
+			</xsl:element>
+		</xsl:if>
+	</xsl:template>
+	
+	<!-- Description -->
+	<xsl:template match="descr">
+		<xsl:element name="descr">
+			<xsl:value-of select="normalize-space(text())"/>
+		</xsl:element>
+	</xsl:template>
+</xsl:stylesheet>
Index: /Dev/trunk/rdfapi/util/magpie/AUTHORS
===================================================================
--- /Dev/trunk/rdfapi/util/magpie/AUTHORS	(revision 12)
+++ /Dev/trunk/rdfapi/util/magpie/AUTHORS	(revision 12)
@@ -0,0 +1,1 @@
+kellan <kellan@protest.net>
Index: /Dev/trunk/rdfapi/util/magpie/CHANGES
===================================================================
--- /Dev/trunk/rdfapi/util/magpie/CHANGES	(revision 12)
+++ /Dev/trunk/rdfapi/util/magpie/CHANGES	(revision 12)
@@ -0,0 +1,41 @@
+Version 0.72
+-----------
+    - fix security exploit: http://www.sec-consult.com/216.html
+    
+Version 0.7
+-----------
+    - support for input and output charset encoding
+      based on the work in FoF, uses iconv or mbstring if available
+    -
+
+Version 0.6
+-----------
+    - basic support for Atom syndication format
+      including support for Atom content constructs
+    - fixed support for private feeds (HTTP Auth and SSL)
+      (thanks to silverorange.com for providing test feeds)
+	- support for some broken webservers
+
+Version 0.52
+-----------
+    - support GZIP content negoiation
+    - PHP 4.3.2 support
+
+Version 0.4
+-----------
+	- improved error handling, better access for script authors
+	- included example scripts of working with MagpieRSS
+	- new Smarty plugin for RSS date parsing
+
+Version 0.3
+-----------
+	- added support for conditional gets (Last-Modified, ETag)
+	- now use Snoopy to handle fetching RSS files
+	
+Version 0.2
+-----------
+	- MAJOR CLEAN UP
+	- removed kludgy $options array in favour of constants
+	- phased out returning arrays
+	- added better error handling
+	- re-worked comments
Index: /Dev/trunk/rdfapi/util/magpie/ChangeLog
===================================================================
--- /Dev/trunk/rdfapi/util/magpie/ChangeLog	(revision 12)
+++ /Dev/trunk/rdfapi/util/magpie/ChangeLog	(revision 12)
@@ -0,0 +1,405 @@
+2005-10-28 14:11  kellan
+
+	* extlib/Snoopy.class.inc: a better solution
+
+2005-10-28 11:51  kellan
+
+	* extlib/Snoopy.class.inc: fix arbtriary code execution
+	  vulnerability when using curl+ssl
+
+	  http://www.sec-consult.com/216.html
+
+2005-03-08 10:46  kellan
+
+	* rss_parse.inc: fix bug w/ atom and date normalization
+
+2005-02-09 14:59  kellan
+
+	* rss_fetch.inc: fix stale cache bug
+
+2005-01-28 02:27  kellan
+
+	* rss_parse.inc: support php w/o array_change_case
+
+2005-01-23 20:02  kellan
+
+	* rss_fetch.inc: fix cache bug introduced by charset encoding
+
+2005-01-12 09:14  kellan
+
+	* rss_cache.inc, rss_fetch.inc: more sanity checks for when things
+	  go wrong
+
+2004-12-12 13:44  kellan
+
+	* INSTALL, rss_cache.inc, rss_utils.inc: detab
+
+2004-11-23 20:15  kellan
+
+	* rss_parse.inc: fix calling iconv instead of mb_convert_encoding
+
+2004-11-22 02:11  kellan
+
+	* CHANGES, ChangeLog, rss_parse.inc, scripts/magpie_debug.php: last
+	  bit of tidying
+
+2004-11-22 01:45  kellan
+
+	* rss_fetch.inc: detab, bump version
+
+2004-11-22 01:43  kellan
+
+	* rss_parse.inc: was filtering too much
+
+2004-11-22 00:03  kellan
+
+	* rss_fetch.inc, rss_parse.inc: cache on $url . $output_encoding
+	  otherwise we can get munged output
+
+2004-11-21 23:52  kellan
+
+	* rss_parse.inc: add WARNING
+
+2004-11-21 23:45  kellan
+
+	* rss_parse.inc: don't set ERROR on notice or warning (rss_fetch
+	  dies on parse errors)
+
+2004-11-21 23:44  kellan
+
+	* rss_fetch.inc: add encoding defines (fix timeout error reporting)
+
+2004-11-21 20:21  kellan
+
+	* rss_parse.inc: incorporate steve's patch
+
+2004-11-21 19:26  kellan
+
+	* rss_parse.inc: remove old debugging functions, totally
+	  arbitrarily.	might break stuff.  can't really explain why i'm
+	  doing this.
+
+2004-10-28 15:52  kellan
+
+	* rss_parse.inc: fixed '=' instead of '=='
+
+2004-10-26 00:48  kellan
+
+	* rss_parse.inc: chance epoch to timestamp to conform w/ php naming
+	  conventions
+
+2004-06-15 12:00  kellan
+
+	* rss_parse.inc: [no log message]
+
+2004-04-26 14:16  kellan
+
+	* rss_fetch.inc: bump version
+
+2004-04-26 12:36  kellan
+
+	* rss_parse.inc: fix field doubling
+
+2004-04-24 17:47  kellan
+
+	* CHANGES, ChangeLog: updated
+
+2004-04-24 17:35  kellan
+
+	* rss_fetch.inc: bumped version
+
+2004-04-24 16:52  kellan
+
+	* rss_parse.inc: support arbitrary atom content constructs
+
+	  some refactoring
+
+2004-04-24 16:15  kellan
+
+	* rss_parse.inc: support summary content contstruct.  add normalize
+	  function
+
+2004-03-27 16:29  kellan
+
+	* extlib/Snoopy.class.inc: accept self-signed certs
+
+2004-03-27 12:53  kellan
+
+	* extlib/Snoopy.class.inc: fixed SSL support   * set status   * set
+	  error on bad curl
+
+	  (also ripped out big chunks of dead weight (submit_form) which
+	  were getting in my way
+
+2004-01-25 02:25  kellan
+
+	* rss_parse.inc: make RSS 1.0's rdf:about available
+
+2004-01-25 02:07  kellan
+
+	* rss_parse.inc: clean up text, and line formats.  add support item
+	  rdf:about
+
+2004-01-24 23:40  kellan
+
+	* CHANGES, ChangeLog: update changes
+
+2004-01-24 23:37  kellan
+
+	* rss_fetch.inc: updated version
+
+2004-01-24 23:35  kellan
+
+	* rss_parse.inc: whitespace
+
+2004-01-24 23:23  kellan
+
+	* extlib/Snoopy.class.inc: support badly formatted http headers
+
+2004-01-24 23:20  kellan
+
+	* rss_parse.inc: added alpha atom parsing support
+
+2003-06-25 22:34  kellan
+
+	* extlib/Snoopy.class.inc: fixed fread 4.3.2 compatibility problems
+
+2003-06-13 11:31  kellan
+
+	* rss_fetch.inc: reset cache on 304
+
+2003-06-12 21:37  kellan
+
+	* rss_cache.inc, rss_fetch.inc, rss_parse.inc, rss_utils.inc:
+	  bumped up version numbers
+
+2003-06-12 21:32  kellan
+
+	* htdocs/index.html: updated news
+
+2003-06-12 21:27  kellan
+
+	* NEWS: a manual blog :)
+
+2003-06-12 21:22  kellan
+
+	* htdocs/index.html: fully qualified img
+
+2003-06-12 21:20  kellan
+
+	* htdocs/index.html: clean up.	added badge.
+
+2003-06-12 21:04  kellan
+
+	* rss_utils.inc: clean up regex
+
+2003-06-12 21:02  kellan
+
+	* rss_cache.inc: suppress some warnings
+
+2003-05-30 20:44  kellan
+
+	* extlib/Snoopy.class.inc: more comments, cleaned up notice
+
+2003-05-30 15:14  kellan
+
+	* extlib/Snoopy.class.inc: don't advertise gzip support if the user
+	  hasn't built php with gzinflate support
+
+2003-05-12 22:32  kellan
+
+	* ChangeLog: changes
+
+2003-05-12 22:11  kellan
+
+	* htdocs/index.html: announce 0.5
+
+2003-05-12 21:42  kellan
+
+	* htdocs/index.html: change
+
+2003-05-12 21:39  kellan
+
+	* rss_fetch.inc: use gzip
+
+2003-05-12 21:37  kellan
+
+	* extlib/Snoopy.class.inc: added support gzip encoded content
+	  negoiation
+
+2003-05-12 21:32  kellan
+
+	* rss_cache.inc, rss_fetch.inc, rss_parse.inc, rss_utils.inc: fixed
+	  typoes
+
+2003-04-26 21:44  kellan
+
+	* rss_parse.inc: fix minor typo
+
+2003-04-18 08:19  kellan
+
+	* htdocs/cookbook.html: updated cookbook to show more code for
+	  limiting items
+
+2003-03-03 16:02  kellan
+
+	* rss_parse.inc, scripts/magpie_slashbox.php: committed (or
+	  adpated) patch from Nicola (www.technick.com) to quell 'Undefined
+	  Indexes' notices
+
+2003-03-03 15:59  kellan
+
+	* rss_fetch.inc: commited patch from nicola (www.technick.com) to
+	  quell 'undefined indexes' notices.
+
+	  * Magpie now automatically includes its version in the
+	  user-agent, & whether cacheing is turned on.
+
+2003-02-12 01:22  kellan
+
+	* CHANGES, ChangeLog: ChangeLog now auto-generated by cvs2cl
+
+2003-02-12 00:21  kellan
+
+	* rss_fetch.inc: better errors, hopefully stomped on pesky notices
+
+2003-02-12 00:19  kellan
+
+	* rss_parse.inc: check to see is xml is supported, if not die
+
+	  also throw better xml errors
+
+2003-02-12 00:18  kellan
+
+	* rss_cache.inc: hopefully cleared up some notices that were being
+	  thrown into the log
+
+	  fixed a debug statement that was being called as an error
+
+2003-02-12 00:15  kellan
+
+	* scripts/: magpie_simple.php, magpie_slashbox.php: moved
+	  magpie_simple to magpie_slashbox, and replaced it with a simpler
+	  demo.
+
+2003-02-12 00:02  kellan
+
+	* INSTALL, README, TROUBLESHOOTING: Improved documentation.  Better
+	  install instructions.
+
+	  TROUBLESHOOTING cover common installation and usage problems
+
+2003-01-22 14:40  kellan
+
+	* htdocs/cookbook.html: added cookbook.html
+
+2003-01-21 23:47  kellan
+
+	* cookbook: a magpie cookbook
+
+2003-01-20 10:09  kellan
+
+	* ChangeLog: updated
+
+2003-01-20 09:23  kellan
+
+	* scripts/simple_smarty.php: minor clean up
+
+2003-01-20 09:15  kellan
+
+	* scripts/README: added smarty url
+
+2003-01-20 09:14  kellan
+
+	* magpie_simple.php, htdocs/index.html, scripts/README,
+	  scripts/magpie_debug.php, scripts/magpie_simple.php,
+	  scripts/simple_smarty.php,
+	  scripts/smarty_plugin/modifier.rss_date_parse.php,
+	  scripts/templates/simple.smarty: Added scripts directory for
+	  examples on how to use MagpieRSS
+
+	  magpie_simple - is a simple example magpie_debug - spew all the
+	  information from a parsed RSS feed simple_smary - example of
+	  using magpie with Smarty template system
+	  smarty_plugin/modifier.rss_date_parse.php - support file for the
+	  smarty demo templates/simple.smary - template for the smarty demo
+
+2003-01-20 09:11  kellan
+
+	* rss_fetch.inc, rss_parse.inc: changes to error handling to give
+	  script authors more access to magpie's errors.
+
+	  added method magpie_error() to retrieve global MAGPIE_ERROR
+	  variable for when fetch_rss() returns false
+
+2002-10-26 19:02  kellan
+
+	* htdocs/index.html: putting the website under source control
+
+2002-10-26 18:43  kellan
+
+	* AUTHORS, ChangeLog, INSTALL, README: some documentation to make
+	  it all look official :)
+
+2002-10-25 23:04  kellan
+
+	* magpie_simple.php: quxx
+
+2002-10-25 23:04  kellan
+
+	* rss_parse.inc: added support for textinput and image
+
+2002-10-25 19:23  kellan
+
+	* magpie_simple.php, rss_cache.inc, rss_fetch.inc, rss_parse.inc,
+	  rss_utils.inc: switched to using Snoopy for fetching remote RSS
+	  files.
+
+	  added support for conditional gets
+
+2002-10-25 19:22  kellan
+
+	* rss_cache.inc, rss_fetch.inc, rss_parse.inc, rss_utils.inc:
+	  Change comment style to slavishly imitate the phpinsider style
+	  found in Smarty and Snoopy :)
+
+2002-10-25 19:18  kellan
+
+	* extlib/Snoopy.class.inc: added Snoopy in order to support
+	  conditional gets
+
+2002-10-23 23:19  kellan
+
+	* magpie_simple.php, rss_cache.inc, rss_fetch.inc, rss_parse.inc:
+	  MAJOR CLEANUP!
+
+	  * rss_fetch got rid of the options array, replaced it with a more
+	  PHP-like solution of using defines.  constants are setup, with
+	  defaults, in the function init()
+
+	  got rid of the idiom of passing back an array, its was awkward to
+	  deal with in PHP, and unusual (and consquently confusing to
+	  people).  now i return true/false values, and try to setup error
+	  string where appropiate (rss_cache has the most complete example
+	  of this)
+
+	  change the logic for interacting with the cache
+
+	  * rss_cache major re-working of how error are handled.  tried to
+	  make the code more resillient.  the cache is now much more aware
+	  of MAX_AGE, where before this was being driven out of rss_fetch
+	  (which was silly)
+
+	  * rss_parse properly handles xml parse errors.  used to sail
+	  along blithely unaware.
+
+2002-09-11 11:11  kellan
+
+	* rss_cache.inc, rss_parse.inc, magpie_simple.php, rss_fetch.inc,
+	  rss_utils.inc: Initial revision
+
+2002-09-11 11:11  kellan
+
+	* rss_cache.inc, rss_parse.inc, magpie_simple.php, rss_fetch.inc,
+	  rss_utils.inc: initial import
+
Index: /Dev/trunk/rdfapi/util/magpie/INSTALL
===================================================================
--- /Dev/trunk/rdfapi/util/magpie/INSTALL	(revision 12)
+++ /Dev/trunk/rdfapi/util/magpie/INSTALL	(revision 12)
@@ -0,0 +1,143 @@
+REQUIREMENTS
+
+    MapieRSS requires a recent PHP 4+ (developed with 4.2.0)
+    with xml (expat) support.
+    
+    Optionally:
+      * PHP5 with libxml2 support.
+      * cURL for SSL support
+      * iconv (preferred) or mb_string for expanded character set support
+    
+QUICK START
+
+    Magpie consists of 4 files (rss_fetch.inc, rss_parser.inc, rss_cache.inc, 
+    and rss_utils.inc), and the directory extlib (which contains a modified 
+    version of the Snoopy HTTP client)
+    
+    Copy these 5 resources to a directory named 'magpierss' in the same 
+    directory as your PHP script.
+    
+    At the top of your script add the following line:
+    
+        require_once('magpierss/rss_fetch.inc');
+    
+    Now you can use the fetch_rss() method:
+      
+        $rss = fetch_rss($url);
+        
+    Done.  That's it.   See README for more details on using MagpieRSS.
+
+NEXT STEPS
+
+    Important:  you'll probably want to get the cache directory working in 
+    order to speed up your application, and not abuse the webserver you're 
+    downloading the RSS from.
+    
+    Optionally you can install MagpieRSS in your PHP include path in order to 
+    make it available server wide.
+    
+    Lastly you might want to look through the constants in rss_fetch.inc see if 
+    there is anything you want to override (the defaults are pretty good)
+
+    For more info, or if you have trouble, see TROUBLESHOOTING
+
+SETTING UP CACHING
+
+    Magpie has built-in transparent caching.  With caching Magpie will only 
+    fetch and parse RSS feeds when there is new content.  Without this feature 
+    your pages will be slow, and the sites serving the RSS feed will be annoyed 
+    with you.
+    
+** Simple and Automatic **
+    
+    By default Magpie will try to create a cache directory named 'cache' in the
+    same directory as your PHP script.
+    
+** Creating a Local Cache Directory **
+    
+    Often this will fail, because your webserver doesn't have sufficient 
+    permissions to create the directory. 
+    
+    Exact instructions for how to do this will vary from install to install and 
+    platform to platform.  The steps are:
+    
+    1.  Make a directory named 'cache'
+    2.  Give the web server write access to that directory.
+    
+    An example of how to do this on Debian would be:
+    
+    1.  mkdir /path/to/script/cache
+    2.  chgrp www-data /path/to/script/cache
+    3.  chmod 775 /path/to/script/cache
+    
+    On other Unixes you'll need to change 'www-data' to what ever user Apache 
+    runs as. (on MacOS X the user would be 'www')
+    
+** Cache in /tmp **
+    
+    Sometimes you won't be able to create a local cache directory.  Some reasons 
+    might be:
+    
+    1.  No shell account
+    2.  Insufficient permissions to change ownership of a directory
+    3.  Webserver runs as 'nobody'
+    
+    In these situations using a cache directory in /tmp can often be a good 
+    option.
+    
+    The drawback is /tmp is public, so anyone on the box can read the cache 
+    files.  Usually RSS feeds are public information, so you'll have to decide 
+    how much of an issue that is.
+
+    To use /tmp as your cache directory you need to add the following line to 
+    your script:
+        
+        define('MAGPIE_CACHE_DIR', '/tmp/magpie_cache');
+        
+** Global Cache **
+
+    If you have several applications using Magpie, you can create a single 
+    shared cache directory, either using the /tmp cache, or somewhere else on 
+    the system.
+    
+    The upside is that you'll distribute fetching and parsing feeds across 
+    several applications.
+    
+INSTALLING MAGPIE SERVER WIDE
+
+    Rather then following the Quickstart instructions which requires you to have 
+    a copy of Magpie per application, alternately you can place it in some 
+    shared location.
+    
+** Adding Magpie to Your Include Path **
+
+    Copy the 5 resources (rss_fetch.inc, rss_parser.inc, rss_cache.inc,         
+    rss_utils.inc, and extlib) to a directory named 'magpierss' in your include 
+    path.  Now any PHP file on your system can use Magpie with:
+    
+        require_once('magpierss/rss_fetch.inc');
+
+    Different installs have different include paths, and you'll have to figure 
+    out what your include_path is.
+    
+    From shell you can try: 
+        
+        php -i | grep 'include_path'
+
+    Alternatley you can create a phpinfo.php file with contains:
+    
+        <?php phpinfo(); ?>
+    
+    Debian's default is:  
+        
+        /usr/share/php 
+        
+    (though more idealogically pure location would be /usr/local/share/php)
+    
+    Apple's default include path is:
+    
+        /usr/lib/php
+        
+    While the Entropy PHP build seems to use:
+    
+        /usr/local/php/lib/php
Index: /Dev/trunk/rdfapi/util/magpie/NEWS
===================================================================
--- /Dev/trunk/rdfapi/util/magpie/NEWS	(revision 12)
+++ /Dev/trunk/rdfapi/util/magpie/NEWS	(revision 12)
@@ -0,0 +1,53 @@
+MagpieRSS News
+
+MAGPIERSS 0.51 RELEASED
+	* important bugfix!
+	* fix "silent failure" when PHP doesn't have zlib
+
+FEED ON FEEDS USES MAGPIE
+	* web-based RSS aggregator built with Magpie
+	* easy to install, easy to use.
+	http://minutillo.com/steve/feedonfeeds/
+	
+MAGPIERSS 0.5 RELEASED
+	* supports transparent HTTP gzip content negotiation for reduced bandwidth usage
+    * quashed some undefined index notices
+
+MAGPIERSS 0.46 RELEASED
+    * minor release, more error handling clean up
+    * documentation fixes, simpler example
+    * new trouble shooting guide for installation and usage problems 
+      http://magpierss.sourceforge.net/TROUBLESHOOTING
+
+MAGPIE NEWS AS RSS
+    * releases, bug fixes, releated stories in RSS
+    
+MAGPIERSS COOKBOOK: SIMPLE PHP RSS HOW TOS
+    * answers some of the most frequently asked Magpie questions
+    * feedback, suggestions, requests, recipes welcome
+      http://magpierss.sourceforge.net/cookbook.html
+
+MAGPIERSS 0.4 RELEASED!
+    * improved error handling, more flexibility for script authors, backwards compatible
+    * new and better examples! including using MagpieRSS and Smarty
+    * new Smarty plugin for RSS date parsing
+      http://smarty.php.net
+
+INFINITE PENGUIN NOW SUPPORTS MAGPIE 0.3
+    * simple, sophisticated RSS viewer
+    * includes auto-generated javascript ticker from RSS feed
+      http://www.infinitepenguins.net/rss/
+
+TRAUMWIND RELEASES REX BACKEND FOR MAGPIERSS
+    * drop in support using regex based XML parser
+    * parses improperly formed XML that chokes expat
+      http://traumwind.de/blog/magpie/magpie_alike.php
+
+MAGPIERSS 0.3 RELEASED!
+    * Support added for HTTP Conditional GETs.
+      http://fishbowl.pastiche.org/archives/001132.html
+
+MAGPIERSS 0.2!
+    * Major clean up of the code. Easier to use.
+    * Simpler install on shared hosts.
+    * Better documentation and comments.
Index: /Dev/trunk/rdfapi/util/magpie/README
===================================================================
--- /Dev/trunk/rdfapi/util/magpie/README	(revision 12)
+++ /Dev/trunk/rdfapi/util/magpie/README	(revision 12)
@@ -0,0 +1,48 @@
+NAME
+
+	MagpieRSS - a simple RSS integration tool
+
+SYNOPSIS
+
+	require_once(rss_fetch.inc);
+	$url = $_GET['url'];
+	$rss = fetch_rss( $url );
+	
+	echo "Channel Title: " . $rss->channel['title'] . "<p>";
+	echo "<ul>";
+	foreach ($rss->items as $item) {
+		$href = $item['link'];
+		$title = $item['title'];
+		echo "<li><a href=$href>$title</a></li>";
+	}
+	echo "</ul>";
+
+DESCRIPTION
+
+	MapieRSS is an XML-based RSS parser in PHP.  It attempts to be "PHP-like",
+	and simple to use.
+	
+	Some features include:
+	
+	* supports RSS 0.9 - 1.0, with limited RSS 2.0 support
+	* supports namespaces, and modules, including mod_content and mod_event
+	* open minded [1]
+	* simple, functional interface, to object oriented backend parser
+	* automatic caching of parsed RSS objects makes its easy to integrate
+	* supports conditional GET with Last-Modified, and ETag
+	* uses constants for easy override of default behaviour 
+	* heavily commented
+
+
+1. By open minded I mean Magpie will accept any tag it finds in good faith that
+   it was supposed to be here.  For strict validation, look elsewhere.
+
+
+GETTING STARTED
+
+	
+
+COPYRIGHT:
+	Copyright(c) 2002 kellan@protest.net. All rights reserved.
+	This software is released under the GNU General Public License.
+	Please read the disclaimer at the top of the Snoopy.class.inc file.
Index: /Dev/trunk/rdfapi/util/magpie/TROUBLESHOOTING
===================================================================
--- /Dev/trunk/rdfapi/util/magpie/TROUBLESHOOTING	(revision 12)
+++ /Dev/trunk/rdfapi/util/magpie/TROUBLESHOOTING	(revision 12)
@@ -0,0 +1,152 @@
+TROUBLESHOOTING
+
+
+Trouble Installing MagpieRSS:
+
+1.	Fatal error: Failed opening required '/path/to/script/rss_fetch.inc' 
+	(include_path='.:/usr/local/lib/php:/usr/local/lib/php/pear') 
+
+2.	Cache couldn't make dir './cache'.
+
+3.	Fatal error: Failed to load PHP's XML Extension. 
+	http://www.php.net/manual/en/ref.xml.php
+
+Trouble Using MagpieRSS
+
+4.	Warning: MagpieRSS: Failed to fetch example.com/index.rdf. 
+	(HTTP Error: Invalid protocol "")
+
+5.	Warning: MagpieRSS: Failed to parse RSS file. 
+	(not well-formed (invalid token) at line 19, column 98)
+
+6.	Warning: MagpieRSS: Failed to fetch http://localhost/rss/features.1-0.rss. 
+	(HTTP Response: HTTP/1.1 404 Not Found)
+
+If you would rather provide a custom error, see the COOKBOOK
+(http://magpierss.sf.net/cookbook.html) recipe 2.
+
+*************************************************************************
+1.	Fatal error: Failed opening required '/path/to/script/rss_fetch.inc' 
+	(include_path='.:/usr/local/lib/php:/usr/local/lib/php/pear') 
+	
+	This could mean that:
+	
+	a) PHP can't find the MagpieRSS files.
+	b) PHP found them the MagpieRSS files, but can't read them.
+	
+	a. Telling PHP where to look for MagpieRSS file.
+	
+	This might mean your PHP program can't find the MagpieRSS libraries. 
+	Magpie relies on 4 include files, rss_fetch.inc, rss_parse.inc,
+	rss_cache.inc, rss_util.inc, and for normal use you'll need all 4 (see the
+	cookbook for exceptions).
+
+	This can be fixed by making sure the MagpieRSS files are in your include
+	path.
+	
+	If you can edit your include path (for example your on a shared host) then
+	you need to replace:
+	
+	require_once('rss_fetch.inc');
+		
+	-with-
+		
+	define('MAGPIE_DIR', '/path/to/magpierss/');
+	require_once(MAGPIE_DIR.'rss_fetch.inc');
+
+	b.  PHP can't read the MagpieRSS files
+	
+	All PHP libraries need to be readable by your webserver.
+	
+	On Unix you can accomplish this with:
+	
+	chmod 755 rss_fetch.inc rss_parse.inc rss_cache.inc rss_util.inc
+	
+*************************************************************************
+2. Cache couldn't make dir './cache'.
+
+	MagpieRSS caches the results of fetched and parsed RSS to reduce the load on
+	both your server, and the remote server providing the RSS.  It does this by
+	writing files to a cache directory.
+
+	This error means the webserver doesn't have write access to the current
+	directory.
+	
+	a. Make a webserver writeable cache directory
+	
+	Find the webserver's group. (on my system it is 'www')
+	
+	mkdir ./cache
+	chgrp www directory_name
+	chmod g+w directory_name
+	
+	(this is the best, and desired solution)
+	
+	b. Tell MagpieRSS to create the cache directory somewhere the webserver can
+	write to.
+	
+	define('MAGPIE_CACHE_DIR', '/tmp/magpierss');
+
+	(this is not a great solution, and might have security considerations)
+		
+	c. Turn off cacheing.  
+	
+	Magpie can work fine with cacheing, but it will be slower, and you might
+	become a nuiance to the RSS provider, but it is an option.
+	
+	define('MAGPIE_CACHE_ON', 0);
+	
+	d. And lastly, do NOT
+	
+	chmod 777 ./cache
+	
+	Any of the above solutions are better then this.
+
+	NOTE: If none of this works for you, let me know.  I've got root, and a
+	custom compiled Apache on almost any box I ever touch, so I can be a little
+	out of touch with reality.  But I won't know that if I don't feedback.
+
+************************************************************************* 3.
+3.	Fatal error: Failed to load PHP's XML Extension. 
+	http://www.php.net/manual/en/ref.xml.php
+
+	-or-
+	
+	Fatal error: Failed to create an instance of PHP's XML parser.
+	http://www.php.net/manual/en/ref.xml.php
+	
+	Make sure your PHP was built with --with-xml
+	
+	This has been turned on by default for several versions of PHP, but it might
+	be turned off in your build.
+	
+	See php.net for details on building and configuring PHP.
+
+
+*************************************************************************
+4.	Warning: MagpieRSS: Failed to fetch index.rdf. 
+	(HTTP Error: Invalid protocol "")
+	
+	You need to put http:// in front of your the URL to your RSS feed
+
+*************************************************************************	
+5.	Warning: MagpieRSS: Failed to parse RSS file. 
+	(not well-formed (invalid token) at line 19, column 98)
+
+	There is a problem with the RSS feed you are trying to read. 
+	MagpieRSS is an XML parser, and therefore can't parse RSS feed with invalid
+	characters.  Some RSS parser are based on regular expressions, and can
+	parse invalid RSS but they have their own problems.
+
+	You could try contacting the author of the RSS feed, and pointing them to
+	the online RSS validator at:
+	
+	http://feeds.archive.org/validator/
+
+*************************************************************************	
+6.	Warning: MagpieRSS: Failed to fetch http://example.com/index.rdf 
+	(HTTP Response: HTTP/1.1 404 Not Found)
+
+	Its a 404!  The RSS file ain't there.
+	
+	
Index: /Dev/trunk/rdfapi/util/magpie/cookbook
===================================================================
--- /Dev/trunk/rdfapi/util/magpie/cookbook	(revision 12)
+++ /Dev/trunk/rdfapi/util/magpie/cookbook	(revision 12)
@@ -0,0 +1,125 @@
+MAGPIERSS RECIPES:  Cooking with Corbies
+
+         "Four and twenty blackbirds baked in a pie."
+
+1. LIMIT THE NUMBER OF HEADLINES(AKA ITEMS) RETURNED.
+
+PROBLEM:
+
+You want to display the 10 (or 3) most recent headlines, but the RSS feed
+contains 15.
+
+SOLUTION:
+
+$num_items = 10;
+$rss = fetch_rss($url);
+
+$items = array_slice($rss->items, 0, $num_items);
+
+DISCUSSION:
+
+Rather then trying to limit the number of items Magpie parses, a much simpler,
+and more flexible approach is to take a "slice" of the array of items.  And
+array_slice() is smart enough to do the right thing if the feed has less items
+then $num_items.
+
+See: http://www.php.net/array_slice
+
+
+2. DISPLAY A CUSTOM ERROR MESSAGE IF SOMETHING GOES WRONG
+
+PROBLEM:
+
+You don't want Magpie's error messages showing up if something goes wrong.
+
+SOLUTION:
+
+# Magpie throws USER_WARNINGS only
+# so you can cloak these, by only showing ERRORs
+error_reporting(E_ERROR);
+
+# check the return value of fetch_rss()
+
+$rss = fetch_rss($url);
+
+if ( $rss ) {
+...display rss feed...
+}
+else {
+	echo "An error occured!  " .
+	     "Consider donating more $$$ for restoration of services." .
+		 "<br>Error Message: "	. magpie_error();
+}
+
+DISCUSSION:
+
+MagpieRSS triggers a warning in a number of circumstances.  The 2 most common
+circumstances are:  if the specified RSS file isn't properly formed (usually
+because it includes illegal HTML), or if Magpie can't download the remote RSS
+file, and there is no cached version.  
+
+If you don't want your users to see these warnings change your error_reporting
+settings to only display ERRORs.  Another option is to turn off display_error,
+so that WARNINGs, and NOTICEs still go to the error_log but not to the webpages.
+
+You can do this with:
+
+ini_set('display_errors', 0);
+
+See: http://www.php.net/error_reporting,
+     http://www.php.net/ini_set, 
+	 http://www.php.net/manual/en/ref.errorfunc.php
+
+3. GENERATE A NEW RSS FEED
+
+PROBLEM:
+
+Create an RSS feed for other people to use.
+
+SOLUTION:
+
+Use Useful Inc's RSSWriter (http://usefulinc.com/rss/rsswriter/)
+
+DISCUSSION:
+
+An example of turning a Magpie parsed RSS object back into an RSS file is forth
+coming.  In the meantime RSSWriter has great documentation.
+
+4. DISPLAY HEADLINES MORE RECENT THEN X DATE
+
+PROBLEM:
+
+You only want to display headlines that were published on, or after a certain
+date.
+
+
+SOLUTION:
+
+require 'rss_utils.inc';
+
+# get all headlines published today
+$today = getdate();
+
+# today, 12AM
+$date = mktime(0,0,0,$today['mon'], $today['mday'], $today['year']);
+
+$rss = fetch_rss($url);
+
+foreach ( $rss->items as $item ) {
+	$published = parse_w3cdtf($item['dc']['date']);
+	if ( $published >= $date ) {
+		echo "Title: " . $item['title'];
+		echo "Published: " . date("h:i:s A", $published);
+		echo "<p>";
+	}
+}
+
+DISCUSSION:
+
+This recipe only works for RSS 1.0 feeds that include the <dc:date> field.
+(which is very good RSS style)
+
+parse_w3cdtf is defined in rss_utils.inc, and parses RSS style dates into Unix
+epoch seconds.  
+
+See: http://www.php.net/manual/en/ref.datetime.php
Index: /Dev/trunk/rdfapi/util/magpie/extlib/Snoopy.class.inc
===================================================================
--- /Dev/trunk/rdfapi/util/magpie/extlib/Snoopy.class.inc	(revision 12)
+++ /Dev/trunk/rdfapi/util/magpie/extlib/Snoopy.class.inc	(revision 12)
@@ -0,0 +1,900 @@
+<?php
+
+/*************************************************
+
+Snoopy - the PHP net client
+Author: Monte Ohrt <monte@ispi.net>
+Copyright (c): 1999-2000 ispi, all rights reserved
+Version: 1.0
+
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+
+You may contact the author of Snoopy by e-mail at:
+monte@ispi.net
+
+Or, write to:
+Monte Ohrt
+CTO, ispi
+237 S. 70th suite 220
+Lincoln, NE 68510
+
+The latest version of Snoopy can be obtained from:
+http://snoopy.sourceforge.com
+
+*************************************************/
+
+class Snoopy
+{
+	/**** Public variables ****/
+	
+	/* user definable vars */
+
+	var $host			=	"www.php.net";		// host name we are connecting to
+	var $port			=	80;					// port we are connecting to
+	var $proxy_host		=	"";					// proxy host to use
+	var $proxy_port		=	"";					// proxy port to use
+	var $agent			=	"Snoopy v1.0";		// agent we masquerade as
+	var	$referer		=	"";					// referer info to pass
+	var $cookies		=	array();			// array of cookies to pass
+												// $cookies["username"]="joe";
+	var	$rawheaders		=	array();			// array of raw headers to send
+												// $rawheaders["Content-type"]="text/html";
+
+	var $maxredirs		=	5;					// http redirection depth maximum. 0 = disallow
+	var $lastredirectaddr	=	"";				// contains address of last redirected address
+	var	$offsiteok		=	true;				// allows redirection off-site
+	var $maxframes		=	0;					// frame content depth maximum. 0 = disallow
+	var $expandlinks	=	true;				// expand links to fully qualified URLs.
+												// this only applies to fetchlinks()
+												// or submitlinks()
+	var $passcookies	=	true;				// pass set cookies back through redirects
+												// NOTE: this currently does not respect
+												// dates, domains or paths.
+	
+	var	$user			=	"";					// user for http authentication
+	var	$pass			=	"";					// password for http authentication
+	
+	// http accept types
+	var $accept			=	"image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, */*";
+	
+	var $results		=	"";					// where the content is put
+		
+	var $error			=	"";					// error messages sent here
+	var	$response_code	=	"";					// response code returned from server
+	var	$headers		=	array();			// headers returned from server sent here
+	var	$maxlength		=	500000;				// max return data length (body)
+	var $read_timeout	=	0;					// timeout on read operations, in seconds
+												// supported only since PHP 4 Beta 4
+												// set to 0 to disallow timeouts
+	var $timed_out		=	false;				// if a read operation timed out
+	var	$status			=	0;					// http request status
+	
+	var	$curl_path		=	"/usr/bin/curl";
+												// Snoopy will use cURL for fetching
+												// SSL content if a full system path to
+												// the cURL binary is supplied here.
+												// set to false if you do not have
+												// cURL installed. See http://curl.haxx.se
+												// for details on installing cURL.
+												// Snoopy does *not* use the cURL
+												// library functions built into php,
+												// as these functions are not stable
+												// as of this Snoopy release.
+	
+	// send Accept-encoding: gzip?
+	var $use_gzip		= true;	
+	
+	/**** Private variables ****/	
+	
+	var	$_maxlinelen	=	4096;				// max line length (headers)
+	
+	var $_httpmethod	=	"GET";				// default http request method
+	var $_httpversion	=	"HTTP/1.0";			// default http request version
+	var $_submit_method	=	"POST";				// default submit method
+	var $_submit_type	=	"application/x-www-form-urlencoded";	// default submit type
+	var $_mime_boundary	=   "";					// MIME boundary for multipart/form-data submit type
+	var $_redirectaddr	=	false;				// will be set if page fetched is a redirect
+	var $_redirectdepth	=	0;					// increments on an http redirect
+	var $_frameurls		= 	array();			// frame src urls
+	var $_framedepth	=	0;					// increments on frame depth
+	
+	var $_isproxy		=	false;				// set if using a proxy server
+	var $_fp_timeout	=	30;					// timeout for socket connection
+
+/*======================================================================*\
+	Function:	fetch
+	Purpose:	fetch the contents of a web page
+				(and possibly other protocols in the
+				future like ftp, nntp, gopher, etc.)
+	Input:		$URI	the location of the page to fetch
+	Output:		$this->results	the output text from the fetch
+\*======================================================================*/
+
+	function fetch($URI)
+	{
+	
+		//preg_match("|^([^:]+)://([^:/]+)(:[\d]+)*(.*)|",$URI,$URI_PARTS);
+		$URI_PARTS = parse_url($URI);
+		if (!empty($URI_PARTS["user"]))
+			$this->user = $URI_PARTS["user"];
+		if (!empty($URI_PARTS["pass"]))
+			$this->pass = $URI_PARTS["pass"];
+				
+		switch($URI_PARTS["scheme"])
+		{
+			case "http":
+				$this->host = $URI_PARTS["host"];
+				if(!empty($URI_PARTS["port"]))
+					$this->port = $URI_PARTS["port"];
+				if($this->_connect($fp))
+				{
+					if($this->_isproxy)
+					{
+						// using proxy, send entire URI
+						$this->_httprequest($URI,$fp,$URI,$this->_httpmethod);
+					}
+					else
+					{
+						$path = $URI_PARTS["path"].(isset($URI_PARTS["query"]) ? "?".$URI_PARTS["query"] : "");
+						// no proxy, send only the path
+						$this->_httprequest($path, $fp, $URI, $this->_httpmethod);
+					}
+					
+					$this->_disconnect($fp);
+
+					if($this->_redirectaddr)
+					{
+						/* url was redirected, check if we've hit the max depth */
+						if($this->maxredirs > $this->_redirectdepth)
+						{
+							// only follow redirect if it's on this site, or offsiteok is true
+							if(preg_match("|^http://".preg_quote($this->host)."|i",$this->_redirectaddr) || $this->offsiteok)
+							{
+								/* follow the redirect */
+								$this->_redirectdepth++;
+								$this->lastredirectaddr=$this->_redirectaddr;
+								$this->fetch($this->_redirectaddr);
+							}
+						}
+					}
+
+					if($this->_framedepth < $this->maxframes && count($this->_frameurls) > 0)
+					{
+						$frameurls = $this->_frameurls;
+						$this->_frameurls = array();
+						
+						while(list(,$frameurl) = each($frameurls))
+						{
+							if($this->_framedepth < $this->maxframes)
+							{
+								$this->fetch($frameurl);
+								$this->_framedepth++;
+							}
+							else
+								break;
+						}
+					}					
+				}
+				else
+				{
+					return false;
+				}
+				return true;					
+				break;
+			case "https":
+				if(!$this->curl_path || (!is_executable($this->curl_path))) {
+					$this->error = "Bad curl ($this->curl_path), can't fetch HTTPS \n";
+					return false;
+				}
+				$this->host = $URI_PARTS["host"];
+				if(!empty($URI_PARTS["port"]))
+					$this->port = $URI_PARTS["port"];
+				if($this->_isproxy)
+				{
+					// using proxy, send entire URI
+					$this->_httpsrequest($URI,$URI,$this->_httpmethod);
+				}
+				else
+				{
+					$path = $URI_PARTS["path"].($URI_PARTS["query"] ? "?".$URI_PARTS["query"] : "");
+					// no proxy, send only the path
+					$this->_httpsrequest($path, $URI, $this->_httpmethod);
+				}
+
+				if($this->_redirectaddr)
+				{
+					/* url was redirected, check if we've hit the max depth */
+					if($this->maxredirs > $this->_redirectdepth)
+					{
+						// only follow redirect if it's on this site, or offsiteok is true
+						if(preg_match("|^http://".preg_quote($this->host)."|i",$this->_redirectaddr) || $this->offsiteok)
+						{
+							/* follow the redirect */
+							$this->_redirectdepth++;
+							$this->lastredirectaddr=$this->_redirectaddr;
+							$this->fetch($this->_redirectaddr);
+						}
+					}
+				}
+
+				if($this->_framedepth < $this->maxframes && count($this->_frameurls) > 0)
+				{
+					$frameurls = $this->_frameurls;
+					$this->_frameurls = array();
+
+					while(list(,$frameurl) = each($frameurls))
+					{
+						if($this->_framedepth < $this->maxframes)
+						{
+							$this->fetch($frameurl);
+							$this->_framedepth++;
+						}
+						else
+							break;
+					}
+				}					
+				return true;					
+				break;
+			default:
+				// not a valid protocol
+				$this->error	=	'Invalid protocol "'.$URI_PARTS["scheme"].'"\n';
+				return false;
+				break;
+		}		
+		return true;
+	}
+
+
+
+/*======================================================================*\
+	Private functions
+\*======================================================================*/
+	
+	
+/*======================================================================*\
+	Function:	_striplinks
+	Purpose:	strip the hyperlinks from an html document
+	Input:		$document	document to strip.
+	Output:		$match		an array of the links
+\*======================================================================*/
+
+	function _striplinks($document)
+	{	
+		preg_match_all("'<\s*a\s+.*href\s*=\s*			# find <a href=
+						([\"\'])?					# find single or double quote
+						(?(1) (.*?)\\1 | ([^\s\>]+))		# if quote found, match up to next matching
+													# quote, otherwise match up to next space
+						'isx",$document,$links);
+						
+
+		// catenate the non-empty matches from the conditional subpattern
+
+		while(list($key,$val) = each($links[2]))
+		{
+			if(!empty($val))
+				$match[] = $val;
+		}				
+		
+		while(list($key,$val) = each($links[3]))
+		{
+			if(!empty($val))
+				$match[] = $val;
+		}		
+		
+		// return the links
+		return $match;
+	}
+
+/*======================================================================*\
+	Function:	_stripform
+	Purpose:	strip the form elements from an html document
+	Input:		$document	document to strip.
+	Output:		$match		an array of the links
+\*======================================================================*/
+
+	function _stripform($document)
+	{	
+		preg_match_all("'<\/?(FORM|INPUT|SELECT|TEXTAREA|(OPTION))[^<>]*>(?(2)(.*(?=<\/?(option|select)[^<>]*>[\r\n]*)|(?=[\r\n]*))|(?=[\r\n]*))'Usi",$document,$elements);
+		
+		// catenate the matches
+		$match = implode("\r\n",$elements[0]);
+				
+		// return the links
+		return $match;
+	}
+
+	
+	
+/*======================================================================*\
+	Function:	_striptext
+	Purpose:	strip the text from an html document
+	Input:		$document	document to strip.
+	Output:		$text		the resulting text
+\*======================================================================*/
+
+	function _striptext($document)
+	{
+		
+		// I didn't use preg eval (//e) since that is only available in PHP 4.0.
+		// so, list your entities one by one here. I included some of the
+		// more common ones.
+								
+		$search = array("'<script[^>]*?>.*?</script>'si",	// strip out javascript
+						"'<[\/\!]*?[^<>]*?>'si",			// strip out html tags
+						"'([\r\n])[\s]+'",					// strip out white space
+						"'&(quote|#34);'i",					// replace html entities
+						"'&(amp|#38);'i",
+						"'&(lt|#60);'i",
+						"'&(gt|#62);'i",
+						"'&(nbsp|#160);'i",
+						"'&(iexcl|#161);'i",
+						"'&(cent|#162);'i",
+						"'&(pound|#163);'i",
+						"'&(copy|#169);'i"
+						);				
+		$replace = array(	"",
+							"",
+							"\\1",
+							"\"",
+							"&",
+							"<",
+							">",
+							" ",
+							chr(161),
+							chr(162),
+							chr(163),
+							chr(169));
+					
+		$text = preg_replace($search,$replace,$document);
+								
+		return $text;
+	}
+
+/*======================================================================*\
+	Function:	_expandlinks
+	Purpose:	expand each link into a fully qualified URL
+	Input:		$links			the links to qualify
+				$URI			the full URI to get the base from
+	Output:		$expandedLinks	the expanded links
+\*======================================================================*/
+
+	function _expandlinks($links,$URI)
+	{
+		
+		preg_match("/^[^\?]+/",$URI,$match);
+
+		$match = preg_replace("|/[^\/\.]+\.[^\/\.]+$|","",$match[0]);
+				
+		$search = array( 	"|^http://".preg_quote($this->host)."|i",
+							"|^(?!http://)(\/)?(?!mailto:)|i",
+							"|/\./|",
+							"|/[^\/]+/\.\./|"
+						);
+						
+		$replace = array(	"",
+							$match."/",
+							"/",
+							"/"
+						);			
+				
+		$expandedLinks = preg_replace($search,$replace,$links);
+
+		return $expandedLinks;
+	}
+
+/*======================================================================*\
+	Function:	_httprequest
+	Purpose:	go get the http data from the server
+	Input:		$url		the url to fetch
+				$fp			the current open file pointer
+				$URI		the full URI
+				$body		body contents to send if any (POST)
+	Output:		
+\*======================================================================*/
+	
+	function _httprequest($url,$fp,$URI,$http_method,$content_type="",$body="")
+	{
+		if($this->passcookies && $this->_redirectaddr)
+			$this->setcookies();
+			
+		$URI_PARTS = parse_url($URI);
+		if(empty($url))
+			$url = "/";
+		$headers = $http_method." ".$url." ".$this->_httpversion."\r\n";		
+		if(!empty($this->agent))
+			$headers .= "User-Agent: ".$this->agent."\r\n";
+		if(!empty($this->host) && !isset($this->rawheaders['Host']))
+			$headers .= "Host: ".$this->host."\r\n";
+		if(!empty($this->accept))
+			$headers .= "Accept: ".$this->accept."\r\n";
+		
+		if($this->use_gzip) {
+			// make sure PHP was built with --with-zlib
+			// and we can handle gzipp'ed data
+			if ( function_exists(gzinflate) ) {
+			   $headers .= "Accept-encoding: gzip\r\n";
+			}
+			else {
+			   trigger_error(
+			   	"use_gzip is on, but PHP was built without zlib support.".
+				"  Requesting file(s) without gzip encoding.", 
+				E_USER_NOTICE);
+			}
+		}
+		
+		if(!empty($this->referer))
+			$headers .= "Referer: ".$this->referer."\r\n";
+		if(!empty($this->cookies))
+		{			
+			if(!is_array($this->cookies))
+				$this->cookies = (array)$this->cookies;
+	
+			reset($this->cookies);
+			if ( count($this->cookies) > 0 ) {
+				$cookie_headers .= 'Cookie: ';
+				foreach ( $this->cookies as $cookieKey => $cookieVal ) {
+				$cookie_headers .= $cookieKey."=".urlencode($cookieVal)."; ";
+				}
+				$headers .= substr($cookie_headers,0,-2) . "\r\n";
+			} 
+		}
+		if(!empty($this->rawheaders))
+		{
+			if(!is_array($this->rawheaders))
+				$this->rawheaders = (array)$this->rawheaders;
+			while(list($headerKey,$headerVal) = each($this->rawheaders))
+				$headers .= $headerKey.": ".$headerVal."\r\n";
+		}
+		if(!empty($content_type)) {
+			$headers .= "Content-type: $content_type";
+			if ($content_type == "multipart/form-data")
+				$headers .= "; boundary=".$this->_mime_boundary;
+			$headers .= "\r\n";
+		}
+		if(!empty($body))	
+			$headers .= "Content-length: ".strlen($body)."\r\n";
+		if(!empty($this->user) || !empty($this->pass))	
+			$headers .= "Authorization: BASIC ".base64_encode($this->user.":".$this->pass)."\r\n";
+
+		$headers .= "\r\n";
+		
+		// set the read timeout if needed
+		if ($this->read_timeout > 0)
+			socket_set_timeout($fp, $this->read_timeout);
+		$this->timed_out = false;
+		
+		fwrite($fp,$headers.$body,strlen($headers.$body));
+		
+		$this->_redirectaddr = false;
+		unset($this->headers);
+		
+		// content was returned gzip encoded?
+		$is_gzipped = false;
+						
+		while($currentHeader = fgets($fp,$this->_maxlinelen))
+		{
+			if ($this->read_timeout > 0 && $this->_check_timeout($fp))
+			{
+				$this->status=-100;
+				return false;
+			}
+				
+		//	if($currentHeader == "\r\n")
+			if(preg_match("/^\r?\n$/", $currentHeader) )
+			      break;
+						
+			// if a header begins with Location: or URI:, set the redirect
+			if(preg_match("/^(Location:|URI:)/i",$currentHeader))
+			{
+				// get URL portion of the redirect
+				preg_match("/^(Location:|URI:)\s+(.*)/",chop($currentHeader),$matches);
+				// look for :// in the Location header to see if hostname is included
+				if(!preg_match("|\:\/\/|",$matches[2]))
+				{
+					// no host in the path, so prepend
+					$this->_redirectaddr = $URI_PARTS["scheme"]."://".$this->host.":".$this->port;
+					// eliminate double slash
+					if(!preg_match("|^/|",$matches[2]))
+							$this->_redirectaddr .= "/".$matches[2];
+					else
+							$this->_redirectaddr .= $matches[2];
+				}
+				else
+					$this->_redirectaddr = $matches[2];
+			}
+		
+			if(preg_match("|^HTTP/|",$currentHeader))
+			{
+                if(preg_match("|^HTTP/[^\s]*\s(.*?)\s|",$currentHeader, $status))
+				{
+					$this->status= $status[1];
+                }				
+				$this->response_code = $currentHeader;
+			}
+			
+			if (preg_match("/Content-Encoding: gzip/", $currentHeader) ) {
+				$is_gzipped = true;
+			}
+			
+			$this->headers[] = $currentHeader;
+		}
+
+		# $results = fread($fp, $this->maxlength);
+		$results = "";
+		while ( $data = fread($fp, $this->maxlength) ) {
+		    $results .= $data;
+		    if (
+		        strlen($results) > $this->maxlength ) {
+		        break;
+		    }
+		}
+		
+		// gunzip
+		if ( $is_gzipped ) {
+			// per http://www.php.net/manual/en/function.gzencode.php
+			$results = substr($results, 10);
+			$results = gzinflate($results);
+		}
+		
+		if ($this->read_timeout > 0 && $this->_check_timeout($fp))
+		{
+			$this->status=-100;
+			return false;
+		}
+		
+		// check if there is a a redirect meta tag
+		
+		if(preg_match("'<meta[\s]*http-equiv[^>]*?content[\s]*=[\s]*[\"\']?\d+;[\s]+URL[\s]*=[\s]*([^\"\']*?)[\"\']?>'i",$results,$match))
+		{
+			$this->_redirectaddr = $this->_expandlinks($match[1],$URI);	
+		}
+
+		// have we hit our frame depth and is there frame src to fetch?
+		if(($this->_framedepth < $this->maxframes) && preg_match_all("'<frame\s+.*src[\s]*=[\'\"]?([^\'\"\>]+)'i",$results,$match))
+		{
+			$this->results[] = $results;
+			for($x=0; $x<count($match[1]); $x++)
+				$this->_frameurls[] = $this->_expandlinks($match[1][$x],$URI_PARTS["scheme"]."://".$this->host);
+		}
+		// have we already fetched framed content?
+		elseif(is_array($this->results))
+			$this->results[] = $results;
+		// no framed content
+		else
+			$this->results = $results;
+		
+		return true;
+	}
+
+/*======================================================================*\
+	Function:	_httpsrequest
+	Purpose:	go get the https data from the server using curl
+	Input:		$url		the url to fetch
+				$URI		the full URI
+				$body		body contents to send if any (POST)
+	Output:		
+\*======================================================================*/
+	
+	function _httpsrequest($url,$URI,$http_method,$content_type="",$body="")
+	{
+		if($this->passcookies && $this->_redirectaddr)
+			$this->setcookies();
+
+		$headers = array();		
+					
+		$URI_PARTS = parse_url($URI);
+		if(empty($url))
+			$url = "/";
+		// GET ... header not needed for curl
+		//$headers[] = $http_method." ".$url." ".$this->_httpversion;		
+		if(!empty($this->agent))
+			$headers[] = "User-Agent: ".$this->agent;
+		if(!empty($this->host))
+			$headers[] = "Host: ".$this->host;
+		if(!empty($this->accept))
+			$headers[] = "Accept: ".$this->accept;
+		if(!empty($this->referer))
+			$headers[] = "Referer: ".$this->referer;
+		if(!empty($this->cookies))
+		{			
+			if(!is_array($this->cookies))
+				$this->cookies = (array)$this->cookies;
+	
+			reset($this->cookies);
+			if ( count($this->cookies) > 0 ) {
+				$cookie_str = 'Cookie: ';
+				foreach ( $this->cookies as $cookieKey => $cookieVal ) {
+				$cookie_str .= $cookieKey."=".urlencode($cookieVal)."; ";
+				}
+				$headers[] = substr($cookie_str,0,-2);
+			}
+		}
+		if(!empty($this->rawheaders))
+		{
+			if(!is_array($this->rawheaders))
+				$this->rawheaders = (array)$this->rawheaders;
+			while(list($headerKey,$headerVal) = each($this->rawheaders))
+				$headers[] = $headerKey.": ".$headerVal;
+		}
+		if(!empty($content_type)) {
+			if ($content_type == "multipart/form-data")
+				$headers[] = "Content-type: $content_type; boundary=".$this->_mime_boundary;
+			else
+				$headers[] = "Content-type: $content_type";
+		}
+		if(!empty($body))	
+			$headers[] = "Content-length: ".strlen($body);
+		if(!empty($this->user) || !empty($this->pass))	
+			$headers[] = "Authorization: BASIC ".base64_encode($this->user.":".$this->pass);
+			
+		for($curr_header = 0; $curr_header < count($headers); $curr_header++) {
+			$cmdline_params .= " -H \"".$headers[$curr_header]."\"";
+		}
+			  	                         
+		if(!empty($body))
+			$cmdline_params .= " -d \"$body\"";
+		
+		if($this->read_timeout > 0)
+			$cmdline_params .= " -m ".$this->read_timeout;
+		
+		$headerfile = uniqid(time());
+		
+		# accept self-signed certs
+		$cmdline_params .= " -k"; 
+		exec($this->curl_path." -D \"/tmp/$headerfile\"".escapeshellcmd($cmdline_params)." ".escapeshellcmd($URI),$results,$return);
+		
+		if($return)
+		{
+			$this->error = "Error: cURL could not retrieve the document, error $return.";
+			return false;
+		}
+			
+			
+		$results = implode("\r\n",$results);
+		
+		$result_headers = file("/tmp/$headerfile");
+						
+		$this->_redirectaddr = false;
+		unset($this->headers);
+						
+		for($currentHeader = 0; $currentHeader < count($result_headers); $currentHeader++)
+		{
+			
+			// if a header begins with Location: or URI:, set the redirect
+			if(preg_match("/^(Location: |URI: )/i",$result_headers[$currentHeader]))
+			{
+				// get URL portion of the redirect
+				preg_match("/^(Location: |URI:)(.*)/",chop($result_headers[$currentHeader]),$matches);
+				// look for :// in the Location header to see if hostname is included
+				if(!preg_match("|\:\/\/|",$matches[2]))
+				{
+					// no host in the path, so prepend
+					$this->_redirectaddr = $URI_PARTS["scheme"]."://".$this->host.":".$this->port;
+					// eliminate double slash
+					if(!preg_match("|^/|",$matches[2]))
+							$this->_redirectaddr .= "/".$matches[2];
+					else
+							$this->_redirectaddr .= $matches[2];
+				}
+				else
+					$this->_redirectaddr = $matches[2];
+			}
+		
+			if(preg_match("|^HTTP/|",$result_headers[$currentHeader]))
+			{
+			    $this->response_code = $result_headers[$currentHeader];
+			    if(preg_match("|^HTTP/[^\s]*\s(.*?)\s|",$this->response_code, $match))
+			    {
+				$this->status= $match[1];
+                	    }
+			}
+			$this->headers[] = $result_headers[$currentHeader];
+		}
+
+		// check if there is a a redirect meta tag
+		
+		if(preg_match("'<meta[\s]*http-equiv[^>]*?content[\s]*=[\s]*[\"\']?\d+;[\s]+URL[\s]*=[\s]*([^\"\']*?)[\"\']?>'i",$results,$match))
+		{
+			$this->_redirectaddr = $this->_expandlinks($match[1],$URI);	
+		}
+
+		// have we hit our frame depth and is there frame src to fetch?
+		if(($this->_framedepth < $this->maxframes) && preg_match_all("'<frame\s+.*src[\s]*=[\'\"]?([^\'\"\>]+)'i",$results,$match))
+		{
+			$this->results[] = $results;
+			for($x=0; $x<count($match[1]); $x++)
+				$this->_frameurls[] = $this->_expandlinks($match[1][$x],$URI_PARTS["scheme"]."://".$this->host);
+		}
+		// have we already fetched framed content?
+		elseif(is_array($this->results))
+			$this->results[] = $results;
+		// no framed content
+		else
+			$this->results = $results;
+
+		unlink("/tmp/$headerfile");
+		
+		return true;
+	}
+
+/*======================================================================*\
+	Function:	setcookies()
+	Purpose:	set cookies for a redirection
+\*======================================================================*/
+	
+	function setcookies()
+	{
+		for($x=0; $x<count($this->headers); $x++)
+		{
+		if(preg_match("/^set-cookie:[\s]+([^=]+)=([^;]+)/i", $this->headers[$x],$match))
+			$this->cookies[$match[1]] = $match[2];
+		}
+	}
+
+	
+/*======================================================================*\
+	Function:	_check_timeout
+	Purpose:	checks whether timeout has occurred
+	Input:		$fp	file pointer
+\*======================================================================*/
+
+	function _check_timeout($fp)
+	{
+		if ($this->read_timeout > 0) {
+			$fp_status = socket_get_status($fp);
+			if ($fp_status["timed_out"]) {
+				$this->timed_out = true;
+				return true;
+			}
+		}
+		return false;
+	}
+
+/*======================================================================*\
+	Function:	_connect
+	Purpose:	make a socket connection
+	Input:		$fp	file pointer
+\*======================================================================*/
+	
+	function _connect(&$fp)
+	{
+		if(!empty($this->proxy_host) && !empty($this->proxy_port))
+			{
+				$this->_isproxy = true;
+				$host = $this->proxy_host;
+				$port = $this->proxy_port;
+			}
+		else
+		{
+			$host = $this->host;
+			$port = $this->port;
+		}
+	
+		$this->status = 0;
+		
+		if($fp = fsockopen(
+					$host,
+					$port,
+					$errno,
+					$errstr,
+					$this->_fp_timeout
+					))
+		{
+			// socket connection succeeded
+
+			return true;
+		}
+		else
+		{
+			// socket connection failed
+			$this->status = $errno;
+			switch($errno)
+			{
+				case -3:
+					$this->error="socket creation failed (-3)";
+				case -4:
+					$this->error="dns lookup failure (-4)";
+				case -5:
+					$this->error="connection refused or timed out (-5)";
+				default:
+					$this->error="connection failed (".$errno.")";
+			}
+			return false;
+		}
+	}
+/*======================================================================*\
+	Function:	_disconnect
+	Purpose:	disconnect a socket connection
+	Input:		$fp	file pointer
+\*======================================================================*/
+	
+	function _disconnect($fp)
+	{
+		return(fclose($fp));
+	}
+
+	
+/*======================================================================*\
+	Function:	_prepare_post_body
+	Purpose:	Prepare post body according to encoding type
+	Input:		$formvars  - form variables
+				$formfiles - form upload files
+	Output:		post body
+\*======================================================================*/
+	
+	function _prepare_post_body($formvars, $formfiles)
+	{
+		settype($formvars, "array");
+		settype($formfiles, "array");
+
+		if (count($formvars) == 0 && count($formfiles) == 0)
+			return;
+		
+		switch ($this->_submit_type) {
+			case "application/x-www-form-urlencoded":
+				reset($formvars);
+				while(list($key,$val) = each($formvars)) {
+					if (is_array($val) || is_object($val)) {
+						while (list($cur_key, $cur_val) = each($val)) {
+							$postdata .= urlencode($key)."[]=".urlencode($cur_val)."&";
+						}
+					} else
+						$postdata .= urlencode($key)."=".urlencode($val)."&";
+				}
+				break;
+
+			case "multipart/form-data":
+				$this->_mime_boundary = "Snoopy".md5(uniqid(microtime()));
+				
+				reset($formvars);
+				while(list($key,$val) = each($formvars)) {
+					if (is_array($val) || is_object($val)) {
+						while (list($cur_key, $cur_val) = each($val)) {
+							$postdata .= "--".$this->_mime_boundary."\r\n";
+							$postdata .= "Content-Disposition: form-data; name=\"$key\[\]\"\r\n\r\n";
+							$postdata .= "$cur_val\r\n";
+						}
+					} else {
+						$postdata .= "--".$this->_mime_boundary."\r\n";
+						$postdata .= "Content-Disposition: form-data; name=\"$key\"\r\n\r\n";
+						$postdata .= "$val\r\n";
+					}
+				}
+				
+				reset($formfiles);
+				while (list($field_name, $file_names) = each($formfiles)) {
+					settype($file_names, "array");
+					while (list(, $file_name) = each($file_names)) {
+						if (!is_readable($file_name)) continue;
+
+						$fp = fopen($file_name, "r");
+						$file_content = fread($fp, filesize($file_name));
+						fclose($fp);
+						$base_name = basename($file_name);
+
+						$postdata .= "--".$this->_mime_boundary."\r\n";
+						$postdata .= "Content-Disposition: form-data; name=\"$field_name\"; filename=\"$base_name\"\r\n\r\n";
+						$postdata .= "$file_content\r\n";
+					}
+				}
+				$postdata .= "--".$this->_mime_boundary."--\r\n";
+				break;
+		}
+
+		return $postdata;
+	}
+}
+
+?>
Index: /Dev/trunk/rdfapi/util/magpie/htdocs/cookbook.html
===================================================================
--- /Dev/trunk/rdfapi/util/magpie/htdocs/cookbook.html	(revision 12)
+++ /Dev/trunk/rdfapi/util/magpie/htdocs/cookbook.html	(revision 12)
@@ -0,0 +1,237 @@
+<html>
+	<head>
+	<title>Magie RSS Recipes:  Simple PHP RSS How To</title>
+	<style>
+	body {
+		font-family:trebuchet MS, trebuchet, verdana, arial, sans-serif; 
+		font-size: 11px; 
+	
+	}
+	
+	pre { font-family: "Courier New", monospace; 
+      padding: 1em; 
+      margin: 0.2em 2.5em 0.2em 3em;
+      background-color: #efeff5;
+      border: 1px solid #cfcfcf;
+      white-space: pre;
+ 	}
+
+	</style>
+	</head>
+	<body>
+<p>
+<h1>MagpieRSS Recipes:  Cooking with Corbies</h1>
+
+<div align="center"><h3><em>"Four and twenty blackbirds baked in a
+pie."</em></h3></div>
+</p>
+<p>
+<ol>
+<li><a href="#limit">Limit the Number of Headlines(aka Items) Returned</a></li>
+<li><a href="#error_message">Display a Custom Error Message if Something Goes
+Wrong</a></li>
+<li><a href="#write_rss">Generate a New RSS Feed</a></li>
+<li><a href="#by_date">Display Headlines More Recent then X Date</a></li>
+<li><a href="#from_file">Parse a Local File Containing RSS</a></li>
+
+</ol>
+</p>
+
+<a name="limit"></a><h2>1. Limit the Number of Headlines(aka Items) Returned.</h2>
+
+<h3>Problem:</h3>
+
+You want to display the 10 (or 3 or whatever) most recent headlines, but the RSS feed
+contains 15.
+
+<h3>Solution:</h3>
+
+<pre>
+$num_items = 10;
+$rss = fetch_rss($url);
+
+$items = array_slice($rss->items, 0, $num_items);
+
+foreach ( $items as $item ) {
+</pre>
+<h3>Discussion:</h3>
+
+Rather then trying to limit the number of items Magpie parses, a much simpler,
+and more flexible approach is to take a "slice" of the array of items.  And
+array_slice() is smart enough to do the right thing if the feed has less items
+then $num_items.
+
+<h3>See:</h3> <a href="http://www.php.net/array_slice">http://www.php.net/array_slice</a>
+</p>
+
+<a name="error_message"></a><h2>2. Display a Custom Error Message if Something Goes Wrong</h2>
+
+<h3>Problem:</h3>
+
+You don't want Magpie's error messages showing up if something goes wrong.
+
+<h3>Solution:</h3>
+<pre>
+# Magpie throws USER_WARNINGS only
+# so you can cloak these, by only showing ERRORs
+error_reporting(E_ERROR);
+
+# check the return value of fetch_rss()
+
+$rss = fetch_rss($url);
+
+if ( $rss ) {
+...display rss feed...
+}
+else {
+   echo "An error occured!  " .
+        "Consider donating more $$$ for restoration of services." .
+        "&lt;br&gt;Error Message: " . magpie_error();
+}
+</pre>
+<h3>Discussion:</h3>
+
+MagpieRSS triggers a warning in a number of circumstances.  The 2 most common
+circumstances are:  if the specified RSS file isn't properly formed (usually
+because it includes illegal HTML), or if Magpie can't download the remote RSS
+file, and there is no cached version.  
+
+If you don't want your users to see these warnings change your error_reporting
+settings to only display ERRORs.<br />
+Another option is to turn off display_error,
+so that WARNINGs, and NOTICEs still go to the error_log but not to the webpages.
+
+You can do this with:
+
+<pre>
+# you can also do this in your php.ini file
+ini_set('display_errors', 0);
+</pre>
+
+<h3>See:</h3>
+<a
+href="http://www.php.net/error_reporting">http://www.php.net/error_reporting</a>,<br
+/>
+<a href="http://www.php.net/ini_set">http://www.php.net/ini_set</a>, <br />
+<a
+href="http://www.php.net/manual/en/ref.errorfunc.php">http://www.php.net/manual/en/ref.errorfunc.php</a><br
+/>
+
+<a name="write_rss"></a><h2>3. Generate a New RSS Feed</h2>
+
+<h3>Problem:</h3>
+
+Create an RSS feed for other people to use.
+
+<h3>Solution:</h3>
+
+Use Useful Inc's <a href="http://usefulinc.com/rss/rsswriter/">RSSWriter</a>.
+
+<h3>Discussion:</h3>
+
+An example of turning a Magpie parsed RSS object back into an RSS file is
+forthcoming.  In the meantime RSSWriter is well documented.
+
+<a name="by_date"></a><h2>4. Display Headlines More Recent then X Date</h2>
+
+<h3>Problem:</h3>
+
+You only want to display headlines that were published on, or after a certain
+date.
+
+
+<h3>Solution:</h3>
+<pre>
+require_once('rss_utils.inc');
+
+# get all headlines published today
+$today = getdate();
+
+# today, 12AM
+$date = mktime(0,0,0,$today['mon'], $today['mday'], $today['year']);
+
+$rss = fetch_rss($url);
+
+foreach ( $rss->items as $item ) {
+   $published = parse_w3cdtf($item['dc']['date']);
+   if ( $published &gt;= $date ) {
+        echo "Title: " . $item['title'];
+        echo "Published: " . date("h:i:s A", $published);
+        echo "&lt;p&gt;";
+    }
+}
+</pre>
+<h3>Discussion:</h3>
+
+This recipe only works for RSS 1.0 feeds that include the <dc:date> field.
+(which is very good RSS style) <br /> 
+<code>parse_w3cdtf()</code> is defined in
+<code>rss_utils.inc</code>, and parses RSS style dates into Unix epoch
+seconds.  
+
+<h3>See: </h3>
+<a
+href="http://www.php.net/manual/en/ref.datetime.php">http://www.php.net/manual/en/ref.datetime.php</a>
+
+<a name="from_file"></a>
+<h2>5. Parse a Local File Containing RSS</h2>
+<h3>Problem:</h3>
+MagpieRSS provides <code>fetch_rss()</code> which takes a URL and returns a
+parsed RSS object, but what if you want to parse a file stored locally that
+doesn't have a URL?
+
+<h3>Solution</h3>
+<pre>
+require_once('rss_parse.inc');
+
+$rss_file = 'some_rss_file.rdf';
+$rss_string = read_file($rss_file);
+$rss = new MagpieRSS( $rss_string );
+
+if ( $rss and !$rss->ERROR) {
+...display rss...
+}
+else {
+    echo "Error: " . $rss->ERROR;
+}
+
+# efficiently read a file into a string
+# in php >= 4.3.0 you can simply use file_get_contents()
+#
+function read_file($filename) {
+    $fh = fopen($filename, 'r') or die($php_errormsg);
+    $rss_string = fread($fh, filesize($filename) );
+    fclose($fh);
+    return $rss_string;
+}
+</pre>
+
+<h3>Discussion</h3>
+Here we are using MagpieRSS's RSS parser directly without the convience wrapper
+of <code>fetch_rss()</code>.  We read the contents of the RSS file into a
+string, and pass it to the parser constructor.  Notice also that error handling
+is subtly different.
+
+<h3>See: </h3>
+<a
+href="http://www.php.net/manual/en/ref.filesystem.php">http://www.php.net/manual/en/ref.filesystem.php</a>,<br
+/>
+<a
+href="http://www.php.net/manual/en/language.oop.php">http://www.php.net/manual/en/language.oop.php</a>
+
+<!-- 
+<a name="link"></a><h2>#. Recipe</h2>
+<h3>Problem:</h3>
+Problem description
+<h3>Solution</h3>
+<pre>
+code
+</pre>
+<h3>Discussion/h3>
+Discuss code
+<h3>See: </h3>
+Documentation links:
+-->
+
+</body>
+</html>
Index: /Dev/trunk/rdfapi/util/magpie/htdocs/index.html
===================================================================
--- /Dev/trunk/rdfapi/util/magpie/htdocs/index.html	(revision 12)
+++ /Dev/trunk/rdfapi/util/magpie/htdocs/index.html	(revision 12)
@@ -0,0 +1,419 @@
+<html>
+  <head>
+  <title>Magpie RSS - PHP RSS Parser</title>
+  <link rel="alternate" type="application/rss+xml" title="RSS"
+        href="http://laughingmeme.org/magpierss.rdf" />
+  <style>
+	body {
+		font-family:trebuchet MS, trebuchet, verdana, arial, sans-serif; 
+		font-size: 11px; 
+	
+	}
+	
+	pre { font-family: "Courier New", monospace; 
+      padding: 1em; 
+      margin: 0.2em 2.5em 0.2em 3em;
+      background-color: #efeff5;
+      border: 1px solid #cfcfcf;
+      white-space: pre;
+ }
+
+	li.news {
+		padding-bottom:15px;
+	}
+
+	a.nav { color: #FFFFFF; }
+	
+	div.nav {
+		width: 2in;
+		float: right;
+		border: 2px solid #cfcfcf;
+		padding: 5px;
+		background-color: #996699;
+	}
+	
+  </style> 
+  </head>
+  <body>
+  	<img src="magpie-photo.jpg">
+	<h1>MagpieRSS</h1>
+	<p>
+	<h2>MagpieRSS provides an XML-based (expat) RSS parser in PHP.</h2>
+	<p>
+	MagpieRSS is compatible with RSS .9 through RSS 1.0, and supports the
+	RSS 1.0's modules. (with a few exceptions)
+	<p>
+	<div class="nav">
+	<center><h3>Project Info</h3></center>
+	<ul>
+	<li><a class="nav"
+href="http://sourceforge.net/project/showfiles.php?group_id=55691">Download
+Magpie</a></li>
+	<li><a class="nav"
+href="http://sourceforge.net/mail/?group_id=55691">Mailing
+Lists</a></li>
+	<li><a class="nav" href="#news">News!</a></li>
+	<li><a class="nav" href="#why">Why?</a></li>
+	<li><a class="nav" href="#features">Features</a></li>
+	<li><a class="nav" href="#philosophy">Philosophy</a></li>
+	<li><a class="nav" href="#usage">Usage Examples</a></li>
+	<li><a class="nav" href="/cookbook.html">Cookbook</a></li>
+	<li><a class="nav" href="#todo">Todo</a></li>
+<li style="list-style: none; padding-top: 5px;"><a title="Keep up on MagpieRSS news via RSS" href="http://laughingmeme.org/magpierss.rdf"><img
+src="http://magpierss.sf.net/black_grey_magpie_news.gif" border="0"></a></li>
+</ul>
+</div>
+	<a name="news"></a>
+	<h3>News!</h3>
+	<ul>
+
+<li class="news">
+		<a 
+href="http://sourceforge.net/project/showfiles.php?group_id=55691">MagpieRSS
+0.51 Released</a>
+<ul>
+<li> important bugfix!</li>
+<li> fix <a href="http://laughingmeme.org/archives/000811.html
+">"silent failure"</a> when PHP doesn't have zlib</li>
+</ul>
+
+</li>
+
+<li class="news">
+		<a href="http://minutillo.com/steve/feedonfeeds/">Feed On Feeds Uses Magpie</a>
+<ul>
+<li> server based PHP RSS aggregator built with MagpieRSS</li>
+<li> easy to install, easy to use.</li>
+</ul>
+
+</li>
+
+
+<li class="news">
+		<a 
+href="http://sourceforge.net/project/showfiles.php?group_id=55691&release_id=158897">MagpieRSS
+0.5 Released</a>
+<ul>
+<li> supports transparent HTTP gzip content negotiation for reduced bandwidth usage</li> 
+<li> quashed some undefined index notices</li>
+</ul>
+
+</li>
+
+
+<li class="news">
+		<a 
+href="http://sourceforge.net/project/showfiles.php?group_id=55691&release_id=139643">MagpieRSS
+0.46 Released</a>
+<ul>
+<li> minor release, more error handling clean up</li> 
+<li> documentation fixes, simpler example</li>
+<li> new <a href="/TROUBLESHOOTING">trouble shooting</a> guide for installation and usage problems</a>
+</ul>
+
+</li>
+
+<li class="news">
+		<a 
+href="http://laughingmeme.org/magpierss.rdf">Magpie News as RSS</a>
+<ul>
+<li> releases, bug fixes, releated stories as an RSS feed</li> 
+</ul>
+
+</li>
+
+
+<li class="news">
+		<a 
+href="http://magpierss.sourceforge.net/cookbook.html">MagpieRSS
+Cookbook: Simple PHP RSS How Tos</a>
+<ul>
+<li> answers some of the most frequently asked Magpie questions</li> 
+<li> feedback, suggestions, requests, recipes welcome</li>
+</ul>
+
+</li>
+
+<li clas="news">
+ <a href="http://sourceforge.net/project/showfiles.php?group_id=55691&release_id=134850">MagpieRSS 0.4 Released!</a>
+<ul>
+<li> improved error handling, more flexibility for script authors,
+backwards compatible</li>
+<li> new and better examples!  including using MagpieRSS and <a
+href="http://smarty.php.net">Smarty</a></li>
+<li> new Smarty plugin for RSS date parsing</li>
+</ul>
+<br />
+</li>
+<!--
+<li class="news">
+<a href="http://www.infinitepenguins.net/rss/">Infinite Penguin now
+supports Magpie 0.3</a>
+<ul>
+<li> simple, sophisticated RSS viewer</li> 
+<li> includes auto-generated javascript ticker from RSS feed</li>
+</ul>
+
+</li>
+
+
+<li class="news">
+<a
+href="http://traumwind.tierpfad.de/blog/magpie/magpie_alike.php">Traumwind
+releases REX backend for MagpieRSS</a>
+<ul>
+<li>drop in support using regex based XML parser</li>
+<li>parses improperly formed XML that chokes expat</li>
+</ul>
+
+</li>
+
+<li class="news">
+		<a
+href="http://sourceforge.net/project/showfiles.php?group_id=55691&release_id=118652">
+		MagpieRSS 0.3 Released!</a>
+		<ul>
+		  <li>Support added for 
+			 <a href="http://fishbowl.pastiche.org/archives/001132.html">HTTP
+			 Conditional GETs</a>.</li>
+		  <li>See <a href="http://sourceforge.net/project/shownotes.php?group_id=55691&release_id=118652">ChangeLog</a>
+		  for more info.</li>
+	    </ul>
+		</li>
+		<li class="news">MagpieRSS 0.2!</a>
+		<ul>
+		  <li>Major clean up of the code.  Easier to use.</li>
+		  <li>Simpler install on shared hosts.</li>
+	      <li>Better documentation and comments.</li>
+		</ul>
+		</li>
+		<li class="news">We've <a href="http://sourceforge.net/projects/magpierss/">moved to
+		Sourceforge!</a></li>
+	-->
+	</ul>
+	</p>
+	<p>
+	<a name="why"></a>
+	<h3>Why?</h3>
+	I wrote MagpieRSS out of a frustration with the limitations of existing
+	solutions.   In particular many of the existing PHP solutions seemed to:
+	<ul>
+	<li>use a parser based on regular expressions, making for an inherently
+	fragile solution
+	<li>only support early versions of RSS
+	<li>discard all the interesting information besides item title, description,
+	and link.
+	<li>not build proper separation between parsing the RSS and displaying it.
+	</ul>
+	In particular I failed to find any PHP RSS parsers that could sufficiently
+	parse RSS 1.0 feeds, to be useful on the RSS based event feeds we generate
+	at <a href="http://protest.net">Protest.net</a>.
+	</p>
+	<p>
+	<a name="features"></a>
+	<h3>Features</h3>
+
+<ul>
+	<li class="toplevel">
+	<h4>Easy to Use</h4>
+	As simple as:
+<pre>
+require('rss_fetch.inc');
+$rss = fetch_rss($url);
+</pre>
+
+	</li>
+	<li class="toplevel">
+		<h4>Parses RSS 0.9 - RSS 1.0</h4>
+
+		Parses most RSS formats, including support for 
+		<a href="http://www.purl.org/rss/1.0/modules/">1.0 modules</a> and limited
+		namespace support.  RSS is packed into convenient data structures; easy to
+		use in PHP, and appropriate for passing to a templating system, like 
+		<a href="http://smarty.php.net">Smarty</a>.
+	</li>
+	<li>
+	<h4>Integrated Object Cache</h4>
+	
+	Caching the parsed RSS means that the 2nd request is fast, and that
+including the rss_fetch call in your PHP page won't destroy your performance,
+and force you to reply on an external cron job. And it happens transparently.
+
+	</li>
+	<li>
+	<h4>HTTP Conditional GETs</h4>
+	
+	Save bandwidth and speed up download times with intelligent use of
+	Last-Modified and ETag.<br /> See <a
+	href="http://fishbowl.pastiche.org/archives/001132.html">HTTP Conditional Get for RSS Hackers</a>
+	</li>
+	
+	<li><h4>Configurable</h4>
+	
+	Makes extensive use of constants to allow overriding default behaviour, and
+	installation on shared hosts.
+	</li>
+	<li><h4>Modular</h4>
+	<ul>
+		<li>rss_fetch.inc - wraps a simple interface (<code>fetch_rss()</code>)
+		around the library.
+		<li>rss_parse.inc - provides the RSS parser, and the RSS object
+		<li>rss_cache.inc - a simple (no GC) object cache, optimized for RSS objects
+		<li>rss_utils.inc - utility functions for working with RSS.  currently
+		provides <code>parse_w3cdtf()</code>, for parsing <a
+		href="http://www.w3.org/TR/NOTE-datetime">W3CDTF</a> into epoch seconds.
+	</ul>
+</ul>
+
+	
+	</p>
+<p>
+	<a name="philosophy"></a>
+	<h3>Magpie's approach to parsing RSS</h3>
+
+	Magpie takes a naive, and inclusive approach. Absolutely
+	non-validating, as long as the RSS feed is well formed, Magpie will
+	cheerfully parse new, and never before seen tags in your RSS feeds.
+	</p>
+	<p>
+	This makes it very simple support the varied versions of RSS simply, but
+	forces the consumer of a RSS feed to be cognizant of how it is
+	structured.(at least if you want to do something fancy)
+	</p>
+	<p>
+	Magpie parses a RSS feed into a simple object, with 4 fields:
+	<code>channel</code>, <code>items</code>, <code>image</code>, and
+	<code>textinput</code>.
+	</p>	
+	<p>
+	<h4>channel</h4>
+	<code>$rss->channel</code> contains key-value pairs of all tags, without
+	nested tags, found between the root tag (&lt;rdf:RDF&gt;, or &lt;rss&gt;) 
+	and the end of the document.
+	</p>
+	<p>
+	<h4>items</h4>
+	<code>$rss->items</code> is an array of associative arrays, each one
+	describing a single item.  An example that looks like:
+	<pre>
+&lt;item rdf:about="http://protest.net/NorthEast/calendrome.cgi?span=event&#38;ID=210257"&gt;
+&lt;title&gt;Weekly Peace Vigil&lt;/title&gt;
+&lt;link&gt;http://protest.net/NorthEast/calendrome.cgi?span=event&#38;ID=210257&lt;/link&gt;
+&lt;description&gt;Wear a white ribbon&lt;/description&gt;
+&lt;dc:subject&gt;Peace&lt;/dc:subject&gt;
+&lt;ev:startdate&gt;2002-06-01T11:00:00&lt;/ev:startdate&gt;
+&lt;ev:location&gt;Northampton, MA&lt;/ev:location&gt;
+&lt;ev:enddate&gt;2002-06-01T12:00:00&lt;/ev:enddate&gt;
+&lt;ev:type&gt;Protest&lt;/ev:type&gt;
+&lt;/item&gt;
+	</pre><p>
+	Is parsed, and pushed on the <code>$rss-&gt;items</code> array as:
+	<p><pre>
+array(
+	title =&gt; 'Weekly Peace Vigil',
+	link =&gt; 'http://protest.net/NorthEast/calendrome.cgi?span=event&#38;ID=210257',
+	description =&gt; 'Wear a white ribbon',
+	dc =&gt; array (
+			subject =&gt; 'Peace'
+		),
+	ev =&gt; array (
+		startdate =&gt; '2002-06-01T11:00:00',
+		enddate =&gt; '2002-06-01T12:00:00',
+		type =&gt; 'Protest',
+		location =&gt; 'Northampton, MA'
+	)
+);
+</pre>
+</p>
+<p>
+<h4>image and textinput</h4>
+<code>$rss->image</code> and <code>$rss-textinput</code> are associative arrays
+including name-value pairs for anything found between the respective parent
+tags.
+</p>
+<p>
+<a name="usage"></a>
+<h3>Usage Examples:</h3>
+
+A very simple example would be:
+<pre>
+require_once 'rss_fetch.inc';
+
+$url = 'http://magpie.sf.net/samples/imc.1-0.rdf';
+$rss = fetch_rss($url);
+
+echo "Site: ", $rss->channel['title'], "&lt;br&gt;\n";
+foreach ($rss->items as $item ) {
+	$title = $item[title];
+	$url   = $item[link];
+	echo "&lt;a href=$url&gt;$title&lt;/a&gt;&lt;/li&gt;&lt;br&gt;\n";
+}
+</pre>
+More soon....in the meantime you can check out a 
+<a href="http://www.infinitepenguins.net/rss/">cool tool built with
+MagpieRSS</a>, version 0.1.
+</p>
+<p>
+<a name="todo"></a>
+<h3>Todos</h3>
+	<h4>RSS Parser</h4>
+	<ul>
+		<li>Swap in a smarter parser that includes optional 
+		support for validation, and required fields.</li>
+		
+		<li>Support RSS 2.0 (as much as I'm annoyed by it)</li>
+		
+		<li>Improve support for modules that rely on attributes</li>
+	</ul>
+	
+	<h4>RSS Cache</h4>
+	<ul>
+		<li>Light-weight garbage collection
+	</ul>
+	
+	<h4>Fetch RSS</h4>
+	<ul>
+	<li>Attempt to <a
+	href="http://diveintomark.org/archives/2002/08/15.html">auto-detect an
+	RSS feed</a>, given a URL following, much like <a
+	href="http://diveintomark.org/projects/misc/rssfinder.py.txt">rssfinder.py</a>does.
+	</li>
+	</ul>
+	<h4>Misc</h4>
+		<ul>
+		<li>More examples</li>
+		<li>A test suite</li>
+		<li>RSS generation, perhaps with <a
+	href="http://usefulinc.com/rss/rsswriter/">RSSwriter</a>?
+		</li>
+		</ul>
+	
+</p>
+<p>
+<h3>RSS Resources</h3>
+	<ul>
+	<li><a href="http://mnot.net/rss/tutorial/">RSS Tutorial for Content Publishers
+	and Webmasters</a> is a great place to start.
+	<li><a href="http://gils.utah.gov/rss/">RSS Workshop:  Publish and Syndicate
+	Your News to the Web</a> is also a good introduction</li>
+	<li><a href="http://www.disobey.com/amphetadesk/finding_more.html">Finding
+	More Channels</a> on how to find RSS feeds.
+	<li>Hammersley's <a href="http://rss.benhammersley.com/">Content Syndication
+	with XML and RSS</a> is a blog covering RSS current events.
+	<li><a href="http://groups.yahoo.com/group/rss-dev/">RSS-DEV mailing
+	list</a> is generally a very helpful, informative space, with the occasional
+	heated debate	
+	<li><a href="http://feeds.archive.org/validator/">RSS Validator</a>
+	</ul>.
+</p>
+<h3>License and Contact Info</h3>
+Magpie is distributed under the GPL license...
+<p>
+coded by: kellan (at) protest.net, feedback is always appreciated.
+<p>
+<a href="http://sourceforge.net"><img
+src="http://sourceforge.net/sflogo.php?group_id=55691&amp;type=3" 
+width="125" height="37" border="0" alt="SourceForge.net Logo"></a>
+<img src="http://laughingmeme.org/magpie_views.gif">
+</body>
+</html>
Index: /Dev/trunk/rdfapi/util/magpie/rss_cache.inc
===================================================================
--- /Dev/trunk/rdfapi/util/magpie/rss_cache.inc	(revision 12)
+++ /Dev/trunk/rdfapi/util/magpie/rss_cache.inc	(revision 12)
@@ -0,0 +1,200 @@
+<?php
+/*
+ * Project:     MagpieRSS: a simple RSS integration tool
+ * File:        rss_cache.inc, a simple, rolling(no GC), cache 
+ *              for RSS objects, keyed on URL.
+ * Author:      Kellan Elliott-McCrea <kellan@protest.net>
+ * Version:     0.51
+ * License:     GPL
+ *
+ * The lastest version of MagpieRSS can be obtained from:
+ * http://magpierss.sourceforge.net
+ *
+ * For questions, help, comments, discussion, etc., please join the
+ * Magpie mailing list:
+ * http://lists.sourceforge.net/lists/listinfo/magpierss-general
+ *
+ */
+
+class RSSCache {
+    var $BASE_CACHE = './cache';    // where the cache files are stored
+    var $MAX_AGE    = 3600;         // when are files stale, default one hour
+    var $ERROR      = "";           // accumulate error messages
+    
+    function RSSCache ($base='', $age='') {
+        if ( $base ) {
+            $this->BASE_CACHE = $base;
+        }
+        if ( $age ) {
+            $this->MAX_AGE = $age;
+        }
+        
+        // attempt to make the cache directory
+        if ( ! file_exists( $this->BASE_CACHE ) ) {
+            $status = @mkdir( $this->BASE_CACHE, 0755 );
+            
+            // if make failed 
+            if ( ! $status ) {
+                $this->error(
+                    "Cache couldn't make dir '" . $this->BASE_CACHE . "'."
+                );
+            }
+        }
+    }
+    
+/*=======================================================================*\
+    Function:   set
+    Purpose:    add an item to the cache, keyed on url
+    Input:      url from wich the rss file was fetched
+    Output:     true on sucess  
+\*=======================================================================*/
+    function set ($url, $rss) {
+        $this->ERROR = "";
+        $cache_file = $this->file_name( $url );
+        $fp = @fopen( $cache_file, 'w' );
+        
+        if ( ! $fp ) {
+            $this->error(
+                "Cache unable to open file for writing: $cache_file"
+            );
+            return 0;
+        }
+        
+        
+        $data = $this->serialize( $rss );
+        fwrite( $fp, $data );
+        fclose( $fp );
+        
+        return $cache_file;
+    }
+    
+/*=======================================================================*\
+    Function:   get
+    Purpose:    fetch an item from the cache
+    Input:      url from wich the rss file was fetched
+    Output:     cached object on HIT, false on MISS 
+\*=======================================================================*/ 
+    function get ($url) {
+        $this->ERROR = "";
+        $cache_file = $this->file_name( $url );
+        
+        if ( ! file_exists( $cache_file ) ) {
+            $this->debug( 
+                "Cache doesn't contain: $url (cache file: $cache_file)"
+            );
+            return 0;
+        }
+        
+        $fp = @fopen($cache_file, 'r');
+        if ( ! $fp ) {
+            $this->error(
+                "Failed to open cache file for reading: $cache_file"
+            );
+            return 0;
+        }
+        
+        if ($filesize = filesize($cache_file) ) {
+        	$data = fread( $fp, filesize($cache_file) );
+        	$rss = $this->unserialize( $data );
+        
+        	return $rss;
+    	}
+    	
+    	return 0;
+    }
+
+/*=======================================================================*\
+    Function:   check_cache
+    Purpose:    check a url for membership in the cache
+                and whether the object is older then MAX_AGE (ie. STALE)
+    Input:      url from wich the rss file was fetched
+    Output:     cached object on HIT, false on MISS 
+\*=======================================================================*/     
+    function check_cache ( $url ) {
+        $this->ERROR = "";
+        $filename = $this->file_name( $url );
+        
+        if ( file_exists( $filename ) ) {
+            // find how long ago the file was added to the cache
+            // and whether that is longer then MAX_AGE
+            $mtime = filemtime( $filename );
+            $age = time() - $mtime;
+            if ( $this->MAX_AGE > $age ) {
+                // object exists and is current
+                return 'HIT';
+            }
+            else {
+                // object exists but is old
+                return 'STALE';
+            }
+        }
+        else {
+            // object does not exist
+            return 'MISS';
+        }
+    }
+
+	function cache_age( $cache_key ) {
+		$filename = $this->file_name( $url );
+		if ( file_exists( $filename ) ) {
+			$mtime = filemtime( $filename );
+            $age = time() - $mtime;
+			return $age;
+		}
+		else {
+			return -1;	
+		}
+	}
+	
+/*=======================================================================*\
+    Function:   serialize
+\*=======================================================================*/     
+    function serialize ( $rss ) {
+        return serialize( $rss );
+    }
+
+/*=======================================================================*\
+    Function:   unserialize
+\*=======================================================================*/     
+    function unserialize ( $data ) {
+        return unserialize( $data );
+    }
+    
+/*=======================================================================*\
+    Function:   file_name
+    Purpose:    map url to location in cache
+    Input:      url from wich the rss file was fetched
+    Output:     a file name
+\*=======================================================================*/     
+    function file_name ($url) {
+        $filename = md5( $url );
+        return join( DIRECTORY_SEPARATOR, array( $this->BASE_CACHE, $filename ) );
+    }
+
+/*=======================================================================*\
+    Function:   error
+    Purpose:    register error
+\*=======================================================================*/         
+    function error ($errormsg, $lvl=E_USER_WARNING) {
+        // append PHP's error message if track_errors enabled
+        if ( isset($php_errormsg) ) { 
+            $errormsg .= " ($php_errormsg)";
+        }
+        $this->ERROR = $errormsg;
+        if ( MAGPIE_DEBUG ) {
+            trigger_error( $errormsg, $lvl);
+        }
+        else {
+            error_log( $errormsg, 0);
+        }
+    }
+    
+    function debug ($debugmsg, $lvl=E_USER_NOTICE) {
+        if ( MAGPIE_DEBUG ) {
+            $this->error("MagpieRSS [debug] $debugmsg", $lvl);
+        }
+    }
+
+}
+
+?>
Index: /Dev/trunk/rdfapi/util/magpie/rss_fetch.inc
===================================================================
--- /Dev/trunk/rdfapi/util/magpie/rss_fetch.inc	(revision 12)
+++ /Dev/trunk/rdfapi/util/magpie/rss_fetch.inc	(revision 12)
@@ -0,0 +1,458 @@
+<?php
+/*
+ * Project:     MagpieRSS: a simple RSS integration tool
+ * File:        rss_fetch.inc, a simple functional interface
+                to fetching and parsing RSS files, via the
+                function fetch_rss()
+ * Author:      Kellan Elliott-McCrea <kellan@protest.net>
+ * License:     GPL
+ *
+ * The lastest version of MagpieRSS can be obtained from:
+ * http://magpierss.sourceforge.net
+ *
+ * For questions, help, comments, discussion, etc., please join the
+ * Magpie mailing list:
+ * magpierss-general@lists.sourceforge.net
+ *
+ */
+ 
+// Setup MAGPIE_DIR for use on hosts that don't include
+// the current path in include_path.
+// with thanks to rajiv and smarty
+if (!defined('DIR_SEP')) {
+    define('DIR_SEP', DIRECTORY_SEPARATOR);
+}
+
+if (!defined('MAGPIE_DIR')) {
+    define('MAGPIE_DIR', dirname(__FILE__) . DIR_SEP);
+}
+
+require_once( MAGPIE_DIR . 'rss_parse.inc' );
+require_once( MAGPIE_DIR . 'rss_cache.inc' );
+
+// for including 3rd party libraries
+define('MAGPIE_EXTLIB', MAGPIE_DIR . 'extlib' . DIR_SEP);
+require_once( MAGPIE_EXTLIB . 'Snoopy.class.inc');
+
+
+/* 
+ * CONSTANTS - redefine these in your script to change the
+ * behaviour of fetch_rss() currently, most options effect the cache
+ *
+ * MAGPIE_CACHE_ON - Should Magpie cache parsed RSS objects? 
+ * For me a built in cache was essential to creating a "PHP-like" 
+ * feel to Magpie, see rss_cache.inc for rationale
+ *
+ *
+ * MAGPIE_CACHE_DIR - Where should Magpie cache parsed RSS objects?
+ * This should be a location that the webserver can write to.   If this 
+ * directory does not already exist Mapie will try to be smart and create 
+ * it.  This will often fail for permissions reasons.
+ *
+ *
+ * MAGPIE_CACHE_AGE - How long to store cached RSS objects? In seconds.
+ *
+ *
+ * MAGPIE_CACHE_FRESH_ONLY - If remote fetch fails, throw error
+ * instead of returning stale object?
+ *
+ * MAGPIE_DEBUG - Display debugging notices?
+ *
+*/
+
+
+/*=======================================================================*\
+    Function: fetch_rss: 
+    Purpose:  return RSS object for the give url
+              maintain the cache
+    Input:    url of RSS file
+    Output:   parsed RSS object (see rss_parse.inc)
+
+    NOTES ON CACHEING:  
+    If caching is on (MAGPIE_CACHE_ON) fetch_rss will first check the cache.
+    
+    NOTES ON RETRIEVING REMOTE FILES:
+    If conditional gets are on (MAGPIE_CONDITIONAL_GET_ON) fetch_rss will
+    return a cached object, and touch the cache object upon recieving a
+    304.
+    
+    NOTES ON FAILED REQUESTS:
+    If there is an HTTP error while fetching an RSS object, the cached
+    version will be return, if it exists (and if MAGPIE_CACHE_FRESH_ONLY is off)
+\*=======================================================================*/
+
+define('MAGPIE_VERSION', '0.72');
+
+$MAGPIE_ERROR = "";
+
+function fetch_rss ($url) {
+    // initialize constants
+    init();
+    
+    if ( !isset($url) ) {
+        error("fetch_rss called without a url");
+        return false;
+    }
+    
+    // if cache is disabled
+    if ( !MAGPIE_CACHE_ON ) {
+        // fetch file, and parse it
+        $resp = _fetch_remote_file( $url );
+        if ( is_success( $resp->status ) ) {
+            return _response_to_rss( $resp );
+        }
+        else {
+            error("Failed to fetch $url and cache is off");
+            return false;
+        }
+    } 
+    // else cache is ON
+    else {
+        // Flow
+        // 1. check cache
+        // 2. if there is a hit, make sure its fresh
+        // 3. if cached obj fails freshness check, fetch remote
+        // 4. if remote fails, return stale object, or error
+        
+        $cache = new RSSCache( MAGPIE_CACHE_DIR, MAGPIE_CACHE_AGE );
+        
+        if (MAGPIE_DEBUG and $cache->ERROR) {
+            debug($cache->ERROR, E_USER_WARNING);
+        }
+        
+        
+        $cache_status    = 0;       // response of check_cache
+        $request_headers = array(); // HTTP headers to send with fetch
+        $rss             = 0;       // parsed RSS object
+        $errormsg        = 0;       // errors, if any
+        
+        // store parsed XML by desired output encoding
+        // as character munging happens at parse time
+        $cache_key       = $url . MAGPIE_OUTPUT_ENCODING;
+        
+        if (!$cache->ERROR) {
+            // return cache HIT, MISS, or STALE
+            $cache_status = $cache->check_cache( $cache_key);
+        }
+                
+        // if object cached, and cache is fresh, return cached obj
+        if ( $cache_status == 'HIT' ) {
+            $rss = $cache->get( $cache_key );
+            if ( isset($rss) and $rss ) {
+                // should be cache age
+                $rss->from_cache = 1;
+                if ( MAGPIE_DEBUG > 1) {
+                    debug("MagpieRSS: Cache HIT", E_USER_NOTICE);
+                }
+                return $rss;
+            }
+        }
+        
+        // else attempt a conditional get
+        
+        // setup headers
+        if ( $cache_status == 'STALE' ) {
+            $rss = $cache->get( $cache_key );
+            if ( $rss and $rss->etag and $rss->last_modified ) {
+                $request_headers['If-None-Match'] = $rss->etag;
+                $request_headers['If-Last-Modified'] = $rss->last_modified;
+            }
+        }
+        
+        $resp = _fetch_remote_file( $url, $request_headers );
+        
+        if (isset($resp) and $resp) {
+          if ($resp->status == '304' ) {
+                // we have the most current copy
+                if ( MAGPIE_DEBUG > 1) {
+                    debug("Got 304 for $url");
+                }
+                // reset cache on 304 (at minutillo insistent prodding)
+                $cache->set($cache_key, $rss);
+                return $rss;
+            }
+            elseif ( is_success( $resp->status ) ) {
+                $rss = _response_to_rss( $resp );
+                if ( $rss ) {
+                    if (MAGPIE_DEBUG > 1) {
+                        debug("Fetch successful");
+                    }
+                    // add object to cache
+                    $cache->set( $cache_key, $rss );
+                    return $rss;
+                }
+            }
+            else {
+                $errormsg = "Failed to fetch $url ";
+                if ( $resp->status == '-100' ) {
+                    $errormsg .= "(Request timed out after " . MAGPIE_FETCH_TIME_OUT . " seconds)";
+                }
+                elseif ( $resp->error ) {
+                    # compensate for Snoopy's annoying habbit to tacking
+                    # on '\n'
+                    $http_error = substr($resp->error, 0, -2); 
+                    $errormsg .= "(HTTP Error: $http_error)";
+                }
+                else {
+                    $errormsg .=  "(HTTP Response: " . $resp->response_code .')';
+                }
+            }
+        }
+        else {
+            $errormsg = "Unable to retrieve RSS file for unknown reasons.";
+        }
+        
+        // else fetch failed
+        
+        // attempt to return cached object
+        if ($rss) {
+            if ( MAGPIE_DEBUG ) {
+                debug("Returning STALE object for $url");
+            }
+            return $rss;
+        }
+        
+        // else we totally failed
+        error( $errormsg ); 
+        
+        return false;
+        
+    } // end if ( !MAGPIE_CACHE_ON ) {
+} // end fetch_rss()
+
+/*=======================================================================*\
+    Function:   error
+    Purpose:    set MAGPIE_ERROR, and trigger error
+\*=======================================================================*/
+
+function error ($errormsg, $lvl=E_USER_WARNING) {
+        global $MAGPIE_ERROR;
+        
+        // append PHP's error message if track_errors enabled
+        if ( isset($php_errormsg) ) { 
+            $errormsg .= " ($php_errormsg)";
+        }
+        if ( $errormsg ) {
+            $errormsg = "MagpieRSS: $errormsg";
+            $MAGPIE_ERROR = $errormsg;
+            trigger_error( $errormsg, $lvl);                
+        }
+}
+
+function debug ($debugmsg, $lvl=E_USER_NOTICE) {
+    trigger_error("MagpieRSS [debug] $debugmsg", $lvl);
+}
+            
+/*=======================================================================*\
+    Function:   magpie_error
+    Purpose:    accessor for the magpie error variable
+\*=======================================================================*/
+function magpie_error ($errormsg="") {
+    global $MAGPIE_ERROR;
+    
+    if ( isset($errormsg) and $errormsg ) { 
+        $MAGPIE_ERROR = $errormsg;
+    }
+    
+    return $MAGPIE_ERROR;   
+}
+
+/*=======================================================================*\
+    Function:   _fetch_remote_file
+    Purpose:    retrieve an arbitrary remote file
+    Input:      url of the remote file
+                headers to send along with the request (optional)
+    Output:     an HTTP response object (see Snoopy.class.inc)  
+\*=======================================================================*/
+function _fetch_remote_file ($url, $headers = "" ) {
+    // Snoopy is an HTTP client in PHP
+    $client = new Snoopy();
+    $client->agent = MAGPIE_USER_AGENT;
+    $client->read_timeout = MAGPIE_FETCH_TIME_OUT;
+    $client->use_gzip = MAGPIE_USE_GZIP;
+    if (is_array($headers) ) {
+        $client->rawheaders = $headers;
+    }
+    
+    @$client->fetch($url);
+    return $client;
+
+}
+
+/*=======================================================================*\
+    Function:   _response_to_rss
+    Purpose:    parse an HTTP response object into an RSS object
+    Input:      an HTTP response object (see Snoopy)
+    Output:     parsed RSS object (see rss_parse)
+\*=======================================================================*/
+function _response_to_rss ($resp) {
+    $rss = new MagpieRSS( $resp->results, MAGPIE_OUTPUT_ENCODING, MAGPIE_INPUT_ENCODING, MAGPIE_DETECT_ENCODING );
+    
+    // if RSS parsed successfully       
+    if ( $rss and !$rss->ERROR) {
+        
+        // find Etag, and Last-Modified
+        foreach($resp->headers as $h) {
+            // 2003-03-02 - Nicola Asuni (www.tecnick.com) - fixed bug "Undefined offset: 1"
+            if (strpos($h, ": ")) {
+                list($field, $val) = explode(": ", $h, 2);
+            }
+            else {
+                $field = $h;
+                $val = "";
+            }
+            
+            if ( $field == 'ETag' ) {
+                $rss->etag = $val;
+            }
+            
+            if ( $field == 'Last-Modified' ) {
+                $rss->last_modified = $val;
+            }
+        }
+        
+        return $rss;    
+    } // else construct error message
+    else {
+        $errormsg = "Failed to parse RSS file.";
+        
+        if ($rss) {
+            $errormsg .= " (" . $rss->ERROR . ")";
+        }
+        error($errormsg);
+        
+        return false;
+    } // end if ($rss and !$rss->error)
+}
+
+/*=======================================================================*\
+    Function:   init
+    Purpose:    setup constants with default values
+                check for user overrides
+\*=======================================================================*/
+function init () {
+    if ( defined('MAGPIE_INITALIZED') ) {
+        return;
+    }
+    else {
+        define('MAGPIE_INITALIZED', true);
+    }
+    
+    if ( !defined('MAGPIE_CACHE_ON') ) {
+        define('MAGPIE_CACHE_ON', true);
+    }
+
+    if ( !defined('MAGPIE_CACHE_DIR') ) {
+        define('MAGPIE_CACHE_DIR', './cache');
+    }
+
+    if ( !defined('MAGPIE_CACHE_AGE') ) {
+        define('MAGPIE_CACHE_AGE', 60*60); // one hour
+    }
+
+    if ( !defined('MAGPIE_CACHE_FRESH_ONLY') ) {
+        define('MAGPIE_CACHE_FRESH_ONLY', false);
+    }
+
+    if ( !defined('MAGPIE_OUTPUT_ENCODING') ) {
+        define('MAGPIE_OUTPUT_ENCODING', 'ISO-8859-1');
+    }
+    
+    if ( !defined('MAGPIE_INPUT_ENCODING') ) {
+        define('MAGPIE_INPUT_ENCODING', null);
+    }
+    
+    if ( !defined('MAGPIE_DETECT_ENCODING') ) {
+        define('MAGPIE_DETECT_ENCODING', true);
+    }
+    
+    if ( !defined('MAGPIE_DEBUG') ) {
+        define('MAGPIE_DEBUG', 0);
+    }
+    
+    if ( !defined('MAGPIE_USER_AGENT') ) {
+        $ua = 'MagpieRSS/'. MAGPIE_VERSION . ' (+http://magpierss.sf.net';
+        
+        if ( MAGPIE_CACHE_ON ) {
+            $ua = $ua . ')';
+        }
+        else {
+            $ua = $ua . '; No cache)';
+        }
+        
+        define('MAGPIE_USER_AGENT', $ua);
+    }
+    
+    if ( !defined('MAGPIE_FETCH_TIME_OUT') ) {
+        define('MAGPIE_FETCH_TIME_OUT', 5); // 5 second timeout
+    }
+    
+    // use gzip encoding to fetch rss files if supported?
+    if ( !defined('MAGPIE_USE_GZIP') ) {
+        define('MAGPIE_USE_GZIP', true);    
+    }
+}
+
+// NOTE: the following code should really be in Snoopy, or at least
+// somewhere other then rss_fetch!
+
+/*=======================================================================*\
+    HTTP STATUS CODE PREDICATES
+    These functions attempt to classify an HTTP status code
+    based on RFC 2616 and RFC 2518.
+    
+    All of them take an HTTP status code as input, and return true or false
+
+    All this code is adapted from LWP's HTTP::Status.
+\*=======================================================================*/
+
+
+/*=======================================================================*\
+    Function:   is_info
+    Purpose:    return true if Informational status code
+\*=======================================================================*/
+function is_info ($sc) { 
+    return $sc >= 100 && $sc < 200; 
+}
+
+/*=======================================================================*\
+    Function:   is_success
+    Purpose:    return true if Successful status code
+\*=======================================================================*/
+function is_success ($sc) { 
+    return $sc >= 200 && $sc < 300; 
+}
+
+/*=======================================================================*\
+    Function:   is_redirect
+    Purpose:    return true if Redirection status code
+\*=======================================================================*/
+function is_redirect ($sc) { 
+    return $sc >= 300 && $sc < 400; 
+}
+
+/*=======================================================================*\
+    Function:   is_error
+    Purpose:    return true if Error status code
+\*=======================================================================*/
+function is_error ($sc) { 
+    return $sc >= 400 && $sc < 600; 
+}
+
+/*=======================================================================*\
+    Function:   is_client_error
+    Purpose:    return true if Error status code, and its a client error
+\*=======================================================================*/
+function is_client_error ($sc) { 
+    return $sc >= 400 && $sc < 500; 
+}
+
+/*=======================================================================*\
+    Function:   is_client_error
+    Purpose:    return true if Error status code, and its a server error
+\*=======================================================================*/
+function is_server_error ($sc) { 
+    return $sc >= 500 && $sc < 600; 
+}
+
+?>
Index: /Dev/trunk/rdfapi/util/magpie/rss_parse.inc
===================================================================
--- /Dev/trunk/rdfapi/util/magpie/rss_parse.inc	(revision 12)
+++ /Dev/trunk/rdfapi/util/magpie/rss_parse.inc	(revision 12)
@@ -0,0 +1,605 @@
+<?php
+
+/**
+* Project:     MagpieRSS: a simple RSS integration tool
+* File:        rss_parse.inc  - parse an RSS or Atom feed
+*               return as a simple object.
+*
+* Handles RSS 0.9x, RSS 2.0, RSS 1.0, and Atom 0.3
+*
+* The lastest version of MagpieRSS can be obtained from:
+* http://magpierss.sourceforge.net
+*
+* For questions, help, comments, discussion, etc., please join the
+* Magpie mailing list:
+* magpierss-general@lists.sourceforge.net
+*
+* @author           Kellan Elliott-McCrea <kellan@protest.net>
+* @version          0.7a
+* @license          GPL
+*
+*/
+
+define('RSS', 'RSS');
+define('ATOM', 'Atom');
+
+require_once (MAGPIE_DIR . 'rss_utils.inc');
+
+/**
+* Hybrid parser, and object, takes RSS as a string and returns a simple object.
+*
+* see: rss_fetch.inc for a simpler interface with integrated caching support
+*
+*/
+class MagpieRSS {
+    var $parser;
+    
+    var $current_item   = array();  // item currently being parsed
+    var $items          = array();  // collection of parsed items
+    var $channel        = array();  // hash of channel fields
+    var $textinput      = array();
+    var $image          = array();
+    var $feed_type;
+    var $feed_version;
+    var $encoding       = '';       // output encoding of parsed rss
+    
+    var $_source_encoding = '';     // only set if we have to parse xml prolog
+    
+    var $ERROR = "";
+    var $WARNING = "";
+    
+    // define some constants
+    
+    var $_CONTENT_CONSTRUCTS = array('content', 'summary', 'info', 'title', 'tagline', 'copyright');
+    var $_KNOWN_ENCODINGS    = array('UTF-8', 'US-ASCII', 'ISO-8859-1');
+
+    // parser variables, useless if you're not a parser, treat as private
+    var $stack              = array(); // parser stack
+    var $inchannel          = false;
+    var $initem             = false;
+    var $incontent          = false; // if in Atom <content mode="xml"> field 
+    var $intextinput        = false;
+    var $inimage            = false;
+    var $current_namespace  = false;
+    
+
+    /**
+     *  Set up XML parser, parse source, and return populated RSS object..
+     *   
+     *  @param string $source           string containing the RSS to be parsed
+     *
+     *  NOTE:  Probably a good idea to leave the encoding options alone unless
+     *         you know what you're doing as PHP's character set support is
+     *         a little weird.
+     *
+     *  NOTE:  A lot of this is unnecessary but harmless with PHP5 
+     *
+     *
+     *  @param string $output_encoding  output the parsed RSS in this character 
+     *                                  set defaults to ISO-8859-1 as this is PHP's
+     *                                  default.
+     *
+     *                                  NOTE: might be changed to UTF-8 in future
+     *                                  versions.
+     *                               
+     *  @param string $input_encoding   the character set of the incoming RSS source. 
+     *                                  Leave blank and Magpie will try to figure it
+     *                                  out.
+     *                                  
+     *                                   
+     *  @param bool   $detect_encoding  if false Magpie won't attempt to detect
+     *                                  source encoding. (caveat emptor)
+     *
+     */
+    function MagpieRSS ($source, $output_encoding='ISO-8859-1', 
+                        $input_encoding=null, $detect_encoding=true) 
+    {   
+        # if PHP xml isn't compiled in, die
+        #
+        if (!function_exists('xml_parser_create')) {
+            $this->error( "Failed to load PHP's XML Extension. " . 
+                          "http://www.php.net/manual/en/ref.xml.php",
+                           E_USER_ERROR );
+        }
+        
+        list($parser, $source) = $this->create_parser($source, 
+                $output_encoding, $input_encoding, $detect_encoding);
+        
+        
+        if (!is_resource($parser)) {
+            $this->error( "Failed to create an instance of PHP's XML parser. " .
+                          "http://www.php.net/manual/en/ref.xml.php",
+                          E_USER_ERROR );
+        }
+
+        
+        $this->parser = $parser;
+        
+        # pass in parser, and a reference to this object
+        # setup handlers
+        #
+        xml_set_object( $this->parser, $this );
+        xml_set_element_handler($this->parser, 
+                'feed_start_element', 'feed_end_element' );
+                        
+        xml_set_character_data_handler( $this->parser, 'feed_cdata' ); 
+    
+        $status = xml_parse( $this->parser, $source );
+        
+        if (! $status ) {
+            $errorcode = xml_get_error_code( $this->parser );
+            if ( $errorcode != XML_ERROR_NONE ) {
+                $xml_error = xml_error_string( $errorcode );
+                $error_line = xml_get_current_line_number($this->parser);
+                $error_col = xml_get_current_column_number($this->parser);
+                $errormsg = "$xml_error at line $error_line, column $error_col";
+
+                $this->error( $errormsg );
+            }
+        }
+        
+        xml_parser_free( $this->parser );
+
+        $this->normalize();
+    }
+    
+    function feed_start_element($p, $element, &$attrs) {
+        $el = $element = strtolower($element);
+        $attrs = array_change_key_case($attrs, CASE_LOWER);
+        
+        // check for a namespace, and split if found
+        $ns = false;
+        if ( strpos( $element, ':' ) ) {
+            list($ns, $el) = split( ':', $element, 2); 
+        }
+        if ( $ns and $ns != 'rdf' ) {
+            $this->current_namespace = $ns;
+        }
+            
+        # if feed type isn't set, then this is first element of feed
+        # identify feed from root element
+        #
+        if (!isset($this->feed_type) ) {
+            if ( $el == 'rdf' ) {
+                $this->feed_type = RSS;
+                $this->feed_version = '1.0';
+            }
+            elseif ( $el == 'rss' ) {
+                $this->feed_type = RSS;
+                $this->feed_version = $attrs['version'];
+            }
+            elseif ( $el == 'feed' ) {
+                $this->feed_type = ATOM;
+                $this->feed_version = $attrs['version'];
+                $this->inchannel = true;
+            }
+            return;
+        }
+    
+        if ( $el == 'channel' ) 
+        {
+            $this->inchannel = true;
+        }
+        elseif ($el == 'item' or $el == 'entry' ) 
+        {
+            $this->initem = true;
+            if ( isset($attrs['rdf:about']) ) {
+                $this->current_item['about'] = $attrs['rdf:about']; 
+            }
+        }
+        
+        // if we're in the default namespace of an RSS feed,
+        //  record textinput or image fields
+        elseif ( 
+            $this->feed_type == RSS and 
+            $this->current_namespace == '' and 
+            $el == 'textinput' ) 
+        {
+            $this->intextinput = true;
+        }
+        
+        elseif (
+            $this->feed_type == RSS and 
+            $this->current_namespace == '' and 
+            $el == 'image' ) 
+        {
+            $this->inimage = true;
+        }
+        
+        # handle atom content constructs
+        elseif ( $this->feed_type == ATOM and in_array($el, $this->_CONTENT_CONSTRUCTS) )
+        {
+            // avoid clashing w/ RSS mod_content
+            if ($el == 'content' ) {
+                $el = 'atom_content';
+            }
+            
+            $this->incontent = $el;
+            
+            
+        }
+        
+        // if inside an Atom content construct (e.g. content or summary) field treat tags as text
+        elseif ($this->feed_type == ATOM and $this->incontent ) 
+        {
+            // if tags are inlined, then flatten
+            $attrs_str = join(' ', 
+                    array_map('map_attrs', 
+                    array_keys($attrs), 
+                    array_values($attrs) ) );
+            
+            $this->append_content( "<$element $attrs_str>"  );
+                    
+            array_unshift( $this->stack, $el );
+        }
+        
+        // Atom support many links per containging element.
+        // Magpie treats link elements of type rel='alternate'
+        // as being equivalent to RSS's simple link element.
+        //
+        elseif ($this->feed_type == ATOM and $el == 'link' ) 
+        {
+            if ( isset($attrs['rel']) and $attrs['rel'] == 'alternate' ) 
+            {
+                $link_el = 'link';
+            }
+            else {
+                $link_el = 'link_' . $attrs['rel'];
+            }
+            
+            $this->append($link_el, $attrs['href']);
+        }
+        // set stack[0] to current element
+        else {
+            array_unshift($this->stack, $el);
+        }
+    }
+    
+
+    
+    function feed_cdata ($p, $text) {
+        if ($this->feed_type == ATOM and $this->incontent) 
+        {
+            $this->append_content( $text );
+        }
+        else {
+            $current_el = join('_', array_reverse($this->stack));
+            $this->append($current_el, $text);
+        }
+    }
+    
+    function feed_end_element ($p, $el) {
+        $el = strtolower($el);
+        
+        if ( $el == 'item' or $el == 'entry' ) 
+        {
+            $this->items[] = $this->current_item;
+            $this->current_item = array();
+            $this->initem = false;
+        }
+        elseif ($this->feed_type == RSS and $this->current_namespace == '' and $el == 'textinput' ) 
+        {
+            $this->intextinput = false;
+        }
+        elseif ($this->feed_type == RSS and $this->current_namespace == '' and $el == 'image' ) 
+        {
+            $this->inimage = false;
+        }
+        elseif ($this->feed_type == ATOM and in_array($el, $this->_CONTENT_CONSTRUCTS) )
+        {   
+            $this->incontent = false;
+        }
+        elseif ($el == 'channel' or $el == 'feed' ) 
+        {
+            $this->inchannel = false;
+        }
+        elseif ($this->feed_type == ATOM and $this->incontent  ) {
+            // balance tags properly
+            // note:  i don't think this is actually neccessary
+            if ( $this->stack[0] == $el ) 
+            {
+                $this->append_content("</$el>");
+            }
+            else {
+                $this->append_content("<$el />");
+            }
+
+            array_shift( $this->stack );
+        }
+        else {
+            array_shift( $this->stack );
+        }
+        
+        $this->current_namespace = false;
+    }
+    
+    function concat (&$str1, $str2="") {
+        if (!isset($str1) ) {
+            $str1="";
+        }
+        $str1 .= $str2;
+    }
+    
+    
+    
+    function append_content($text) {
+        if ( $this->initem ) {
+            $this->concat( $this->current_item[ $this->incontent ], $text );
+        }
+        elseif ( $this->inchannel ) {
+            $this->concat( $this->channel[ $this->incontent ], $text );
+        }
+    }
+    
+    // smart append - field and namespace aware
+    function append($el, $text) {
+        if (!$el) {
+            return;
+        }
+        if ( $this->current_namespace ) 
+        {
+            if ( $this->initem ) {
+                $this->concat(
+                    $this->current_item[ $this->current_namespace ][ $el ], $text);
+            }
+            elseif ($this->inchannel) {
+                $this->concat(
+                    $this->channel[ $this->current_namespace][ $el ], $text );
+            }
+            elseif ($this->intextinput) {
+                $this->concat(
+                    $this->textinput[ $this->current_namespace][ $el ], $text );
+            }
+            elseif ($this->inimage) {
+                $this->concat(
+                    $this->image[ $this->current_namespace ][ $el ], $text );
+            }
+        }
+        else {
+            if ( $this->initem ) {
+                $this->concat(
+                    $this->current_item[ $el ], $text);
+            }
+            elseif ($this->intextinput) {
+                $this->concat(
+                    $this->textinput[ $el ], $text );
+            }
+            elseif ($this->inimage) {
+                $this->concat(
+                    $this->image[ $el ], $text );
+            }
+            elseif ($this->inchannel) {
+                $this->concat(
+                    $this->channel[ $el ], $text );
+            }
+            
+        }
+    }
+    
+    function normalize () {
+        // if atom populate rss fields
+        if ( $this->is_atom() ) {
+            $this->channel['description'] = $this->channel['tagline'];
+            for ( $i = 0; $i < count($this->items); $i++) {
+                $item = $this->items[$i];
+                if ( isset($item['summary']) )
+                    $item['description'] = $item['summary'];
+                if ( isset($item['atom_content']))
+                    $item['content']['encoded'] = $item['atom_content'];
+                
+                $atom_date = (isset($item['issued']) ) ? $item['issued'] : $item['modified'];
+                if ( $atom_date ) {
+                    $epoch = @parse_w3cdtf($atom_date);
+                    if ($epoch and $epoch > 0) {
+                        $item['date_timestamp'] = $epoch;
+                    }
+                }
+                
+                $this->items[$i] = $item;
+            }       
+        }
+        elseif ( $this->is_rss() ) {
+            $this->channel['tagline'] = $this->channel['description'];
+            for ( $i = 0; $i < count($this->items); $i++) {
+                $item = $this->items[$i];
+                if ( isset($item['description']))
+                    $item['summary'] = $item['description'];
+                if ( isset($item['content']['encoded'] ) )
+                    $item['atom_content'] = $item['content']['encoded'];
+                
+                if ( $this->is_rss() == '1.0' and isset($item['dc']['date']) ) {
+                    $epoch = @parse_w3cdtf($item['dc']['date']);
+                    if ($epoch and $epoch > 0) {
+                        $item['date_timestamp'] = $epoch;
+                    }
+                }
+                elseif ( isset($item['pubdate']) ) {
+                    $epoch = @strtotime($item['pubdate']);
+                    if ($epoch > 0) {
+                        $item['date_timestamp'] = $epoch;
+                    }
+                }
+                
+                $this->items[$i] = $item;
+            }
+        }
+    }
+    
+    
+    function is_rss () {
+        if ( $this->feed_type == RSS ) {
+            return $this->feed_version; 
+        }
+        else {
+            return false;
+        }
+    }
+    
+    function is_atom() {
+        if ( $this->feed_type == ATOM ) {
+            return $this->feed_version;
+        }
+        else {
+            return false;
+        }
+    }
+
+    /**
+    * return XML parser, and possibly re-encoded source
+    *
+    */
+    function create_parser($source, $out_enc, $in_enc, $detect) {
+        if ( substr(phpversion(),0,1) == 5) {
+            $parser = $this->php5_create_parser($in_enc, $detect);
+        }
+        else {
+            list($parser, $source) = $this->php4_create_parser($source, $in_enc, $detect);
+        }
+        if ($out_enc) {
+            $this->encoding = $out_enc;
+            xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, $out_enc);
+        }
+        
+        return array($parser, $source);
+    }
+    
+    /**
+    * Instantiate an XML parser under PHP5
+    *
+    * PHP5 will do a fine job of detecting input encoding
+    * if passed an empty string as the encoding. 
+    *
+    * All hail libxml2!
+    *
+    */
+    function php5_create_parser($in_enc, $detect) {
+        // by default php5 does a fine job of detecting input encodings
+        if(!$detect && $in_enc) {
+            return xml_parser_create($in_enc);
+        }
+        else {
+            return xml_parser_create('');
+        }
+    }
+    
+    /**
+    * Instaniate an XML parser under PHP4
+    *
+    * Unfortunately PHP4's support for character encodings
+    * and especially XML and character encodings sucks.  As
+    * long as the documents you parse only contain characters
+    * from the ISO-8859-1 character set (a superset of ASCII,
+    * and a subset of UTF-8) you're fine.  However once you
+    * step out of that comfy little world things get mad, bad,
+    * and dangerous to know.
+    *
+    * The following code is based on SJM's work with FoF
+    * @see http://minutillo.com/steve/weblog/2004/6/17/php-xml-and-character-encodings-a-tale-of-sadness-rage-and-data-loss
+    *
+    */
+    function php4_create_parser($source, $in_enc, $detect) {
+        if ( !$detect ) {
+            return array(xml_parser_create($in_enc), $source);
+        }
+        
+        if (!$in_enc) {
+            if (preg_match('/<?xml.*encoding=[\'"](.*?)[\'"].*?>/m', $source, $m)) {
+                $in_enc = strtoupper($m[1]);
+                $this->source_encoding = $in_enc;
+            }
+            else {
+                $in_enc = 'UTF-8';
+            }
+        }
+        
+        if ($this->known_encoding($in_enc)) {
+            return array(xml_parser_create($in_enc), $source);
+        }
+        
+        // the dectected encoding is not one of the simple encodings PHP knows
+        
+        // attempt to use the iconv extension to
+        // cast the XML to a known encoding
+        // @see http://php.net/iconv
+       
+        if (function_exists('iconv'))  {
+            $encoded_source = iconv($in_enc,'UTF-8', $source);
+            if ($encoded_source) {
+                return array(xml_parser_create('UTF-8'), $encoded_source);
+            }
+        }
+        
+        // iconv didn't work, try mb_convert_encoding
+        // @see http://php.net/mbstring
+        if(function_exists('mb_convert_encoding')) {
+            $encoded_source = mb_convert_encoding($source, 'UTF-8', $in_enc );
+            if ($encoded_source) {
+                return array(xml_parser_create('UTF-8'), $encoded_source);
+            }
+        }
+        
+        // else 
+        $this->error("Feed is in an unsupported character encoding. ($in_enc) " .
+                     "You may see strange artifacts, and mangled characters.",
+                     E_USER_NOTICE);
+            
+        return array(xml_parser_create(), $source);
+    }
+    
+    function known_encoding($enc) {
+        $enc = strtoupper($enc);
+        if ( in_array($enc, $this->_KNOWN_ENCODINGS) ) {
+            return $enc;
+        }
+        else {
+            return false;
+        }
+    }
+
+    function error ($errormsg, $lvl=E_USER_WARNING) {
+        // append PHP's error message if track_errors enabled
+        if ( isset($php_errormsg) ) { 
+            $errormsg .= " ($php_errormsg)";
+        }
+        if ( MAGPIE_DEBUG ) {
+            trigger_error( $errormsg, $lvl);        
+        }
+        else {
+            error_log( $errormsg, 0);
+        }
+        
+        $notices = E_USER_NOTICE|E_NOTICE;
+        if ( $lvl&$notices ) {
+            $this->WARNING = $errormsg;
+        } else {
+            $this->ERROR = $errormsg;
+        }
+    }
+    
+    
+} // end class RSS
+
+function map_attrs($k, $v) {
+    return "$k=\"$v\"";
+}
+
+// patch to support medieval versions of PHP4.1.x, 
+// courtesy, Ryan Currie, ryan@digibliss.com
+
+if (!function_exists('array_change_key_case')) {
+	define("CASE_UPPER",1);
+	define("CASE_LOWER",0);
+
+
+	function array_change_key_case($array,$case=CASE_LOWER) {
+       if ($case=CASE_LOWER) $cmd=strtolower;
+       elseif ($case=CASE_UPPER) $cmd=strtoupper;
+       foreach($array as $key=>$value) {
+               $output[$cmd($key)]=$value;
+       }
+       return $output;
+	}
+
+}
+
+?>
Index: /Dev/trunk/rdfapi/util/magpie/rss_utils.inc
===================================================================
--- /Dev/trunk/rdfapi/util/magpie/rss_utils.inc	(revision 12)
+++ /Dev/trunk/rdfapi/util/magpie/rss_utils.inc	(revision 12)
@@ -0,0 +1,67 @@
+<?php
+/*
+ * Project:     MagpieRSS: a simple RSS integration tool
+ * File:        rss_utils.inc, utility methods for working with RSS
+ * Author:      Kellan Elliott-McCrea <kellan@protest.net>
+ * Version:     0.51
+ * License:     GPL
+ *
+ * The lastest version of MagpieRSS can be obtained from:
+ * http://magpierss.sourceforge.net
+ *
+ * For questions, help, comments, discussion, etc., please join the
+ * Magpie mailing list:
+ * magpierss-general@lists.sourceforge.net
+ */
+
+
+/*======================================================================*\
+    Function: parse_w3cdtf
+    Purpose:  parse a W3CDTF date into unix epoch
+
+    NOTE: http://www.w3.org/TR/NOTE-datetime
+\*======================================================================*/
+
+function parse_w3cdtf ( $date_str ) {
+    
+    # regex to match wc3dtf
+    $pat = "/(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})(:(\d{2}))?(?:([-+])(\d{2}):?(\d{2})|(Z))?/";
+    
+    if ( preg_match( $pat, $date_str, $match ) ) {
+        list( $year, $month, $day, $hours, $minutes, $seconds) = 
+            array( $match[1], $match[2], $match[3], $match[4], $match[5], $match[6]);
+        
+        # calc epoch for current date assuming GMT
+        $epoch = gmmktime( $hours, $minutes, $seconds, $month, $day, $year);
+        
+        $offset = 0;
+        if ( $match[10] == 'Z' ) {
+            # zulu time, aka GMT
+        }
+        else {
+            list( $tz_mod, $tz_hour, $tz_min ) =
+                array( $match[8], $match[9], $match[10]);
+            
+            # zero out the variables
+            if ( ! $tz_hour ) { $tz_hour = 0; }
+            if ( ! $tz_min ) { $tz_min = 0; }
+        
+            $offset_secs = (($tz_hour*60)+$tz_min)*60;
+            
+            # is timezone ahead of GMT?  then subtract offset
+            #
+            if ( $tz_mod == '+' ) {
+                $offset_secs = $offset_secs * -1;
+            }
+            
+            $offset = $offset_secs; 
+        }
+        $epoch = $epoch + $offset;
+        return $epoch;
+    }
+    else {
+        return -1;
+    }
+}
+
+?>
Index: /Dev/trunk/rdfapi/util/magpie/scripts/README
===================================================================
--- /Dev/trunk/rdfapi/util/magpie/scripts/README	(revision 12)
+++ /Dev/trunk/rdfapi/util/magpie/scripts/README	(revision 12)
@@ -0,0 +1,27 @@
+Some example on how to use Magpie:
+
+* magpie_simple.php *
+  Simple example of fetching and parsing an RSS file. Expects to be
+  called with a query param 'rss_url=http://<some rss file>'
+
+* simple_smarty.php *
+  Similiar to magpie_simple, but using the Smarty template engine to do
+  display.  Also demostrates using rss_utils.inc and a smarty plugin to
+  parse and display when each RSS item was published.
+
+* magpie_debug.php *
+  Displays all the information available from a parsed feed.
+
+* smarty_plugin/modifier.rss_date_parse.php *
+ 
+  A Smarty plugin for parsing RSS style dates.  You must include rss_utils.inc
+  for this plugin to work.  It also must be installed in the Smarty plugin
+  directory, see the Smarty docs for details.
+
+* templates/simple.smarty
+  A Smarty template used by simple_smarty.php which demostrates
+  displaying an RSS feed and using the date parse plugin.
+  
+  
+The Smarty template engine and documentation on how to use it are available from
+http://smarty.php.net
Index: /Dev/trunk/rdfapi/util/magpie/scripts/magpie_debug.php
===================================================================
--- /Dev/trunk/rdfapi/util/magpie/scripts/magpie_debug.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/magpie/scripts/magpie_debug.php	(revision 12)
@@ -0,0 +1,80 @@
+<?php
+
+ini_set('display_errors', 1);
+ini_set('error_reporting', E_ALL);
+define('MAGPIE_OUTPUT_ENCODING', 'UTF-8');
+define('MAGPIE_DIR', '../');
+define('MAGPIE_DEBUG', 1);
+
+// flush cache quickly for debugging purposes, don't do this on a live site
+define('MAGPIE_CACHE_AGE', 10);
+
+require_once(MAGPIE_DIR.'rss_fetch.inc');
+
+
+if ( isset($_GET['url']) ) {
+	$url = $_GET['url'];
+}
+else {
+	$url = 'http://magpierss.sf.net/test.rss';
+}
+
+
+test_library_support();
+
+$rss = fetch_rss( $url );
+	
+if ($rss) {
+	echo "<h3>Example Output</h3>";
+	echo "Channel: " . $rss->channel['title'] . "<p>";
+	echo "<ul>";
+	foreach ($rss->items as $item) {
+		$href = $item['link'];
+		$title = $item['title'];	
+		echo "<li><a href=$href>$title</a></li>";
+	}
+	echo "</ul>";
+}
+else {
+	echo "Error: " . magpie_error();
+}
+?>
+
+<form>
+	RSS URL: <input type="text" size="30" name="url" value="<?php echo $url ?>"><br />
+	<input type="submit" value="Parse RSS">
+</form>
+
+<h3>Parsed Results (var_dump'ed)</h3>
+<pre>
+<?php var_dump($rss); ?>
+</pre>
+
+<?php
+
+function test_library_support() {
+   if (!function_exists('xml_parser_create')) {
+	   echo "<b>Error:</b> PHP compiled without XML support (--with-xml), Mapgie won't work without PHP support for XML.<br />\n";
+	   exit;
+   }
+   else {
+	   echo "<b>OK:</b> Found an XML parser. <br />\n";
+   }
+   
+   if ( ! function_exists('gzinflate') ) {
+	   echo "<b>Warning:</b>  PHP compiled without Zlib support (--with-zlib). No support for GZIP encoding.<br />\n";
+   }
+   else {
+	   echo "<b>OK:</b>  Support for GZIP encoding.<br />\n";
+   }
+   
+   if ( ! (function_exists('iconv') and function_exists('mb_convert_encoding') ) ) {
+	   echo "<b>Warning:</b>  No support for iconv (--with-iconv) or multi-byte strings (--enable-mbstring)." .  
+		   "No support character set munging.<br />\n";
+   }
+   else {
+	   echo "<b>OK:</b>  Support for character munging.<br />\n";
+   }
+}
+
+?>
Index: /Dev/trunk/rdfapi/util/magpie/scripts/magpie_simple.php
===================================================================
--- /Dev/trunk/rdfapi/util/magpie/scripts/magpie_simple.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/magpie/scripts/magpie_simple.php	(revision 12)
@@ -0,0 +1,29 @@
+<?php
+
+define('MAGPIE_DIR', '../');
+require_once(MAGPIE_DIR.'rss_fetch.inc');
+
+$url = $_GET['url'];
+
+if ( $url ) {
+	$rss = fetch_rss( $url );
+	echo "Channel: " . $rss->channel['title'] . "<p>";
+	echo "<ul>";
+	foreach ($rss->items as $item) {
+		$href = $item['link'];
+		$title = $item['title'];	
+		echo "<li><a href=$href>$title</a></li>";
+	}
+	echo "</ul>";
+}
+?>
+
+<form>
+	RSS URL: <input type="text" size="30" name="url" value="<?php echo $url ?>"><br />
+	<input type="submit" value="Parse RSS">
+</form>
+  
+<p>
+<h2>Security Note:</h2>
+This is a simple <b>example</b> script.  If this was a <b>real</b> script we probably wouldn't allow  strangers to submit random URLs, and we certainly wouldn't simply echo anything passed in the URL.  Additionally its a bad idea to leave this example script lying around.
+</p>
Index: /Dev/trunk/rdfapi/util/magpie/scripts/magpie_slashbox.php
===================================================================
--- /Dev/trunk/rdfapi/util/magpie/scripts/magpie_slashbox.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/magpie/scripts/magpie_slashbox.php	(revision 12)
@@ -0,0 +1,66 @@
+<?php
+
+define('MAGPIE_DIR', '../');
+require_once(MAGPIE_DIR.'rss_fetch.inc');
+	
+$url = $_GET['rss_url'];
+
+?>
+
+<html
+<body LINK="#999999" VLINK="#000000">
+
+<form>
+<input type="text" name="rss_url" size="40" value="<?php echo $url ?>"><input type="Submit">
+</form>
+
+<?php
+
+if ( $url ) {
+	echo "displaying: $url<p>";
+	$rss = fetch_rss( $url );
+	echo slashbox ($rss);
+}
+
+echo "<pre>";
+print_r($rss);
+echo "</pre>";
+?>
+
+</body>
+</html>
+
+<?php
+
+# just some quick and ugly php to generate html
+#
+#
+function slashbox ($rss) {
+	echo "<table cellpadding=2 cellspacing=0><tr>";
+	echo "<td bgcolor=#006666>";
+	
+	# get the channel title and link properties off of the rss object
+	#
+	$title = $rss->channel['title'];
+	$link = $rss->channel['link'];
+	
+	echo "<a href=$link><font color=#FFFFFF><b>$title</b></font></a>";
+	echo "</td></tr>";
+	
+	# foreach over each item in the array.
+	# displaying simple links
+	#
+	# we could be doing all sorts of neat things with the dublin core
+	# info, or the event info, or what not, but keeping it simple for now.
+	#
+	foreach ($rss->items as $item ) {
+		echo "<tr><td bgcolor=#cccccc>";
+		echo "<a href=$item[link]>";
+		echo $item['title'];
+		echo "</a></td></tr>";
+	}		
+	
+	echo "</table>";
+}
+
+?>
Index: /Dev/trunk/rdfapi/util/magpie/scripts/simple_smarty.php
===================================================================
--- /Dev/trunk/rdfapi/util/magpie/scripts/simple_smarty.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/magpie/scripts/simple_smarty.php	(revision 12)
@@ -0,0 +1,58 @@
+<?php
+
+// Define path to Smarty files (don't forget trailing slash)
+// and load library.  (you'll want to change this value)
+//
+// NOTE:  you can also simply add Smarty to your include path
+define('SMARTY_DIR', '/home/kellan/projs/magpierss/scripts/Smarty/');
+require_once(SMARTY_DIR.'Smarty.class.php');
+
+// define path to Magpie files and load library
+// (you'll want to change this value)
+//
+// NOTE: you can also simple add MagpieRSS to your include path
+define('MAGPIE_DIR', '/home/kellan/projs/magpierss/');
+require_once(MAGPIE_DIR.'rss_fetch.inc');
+require_once(MAGPIE_DIR.'rss_utils.inc');
+
+
+// optionally show lots of debugging info
+# define('MAGPIE_DEBUG', 2);
+
+// optionally flush cache quickly for debugging purposes, 
+// don't do this on a live site
+# define('MAGPIE_CACHE_AGE', 10);
+
+// use cache?  default is yes.  see rss_fetch for other Magpie options
+# define('MAGPIE_CACHE_ON', 1)
+
+// setup template object
+$smarty = new Smarty;
+$smarty->compile_check = true;
+
+// url of an rss file
+$url = $_GET['rss_url'];
+
+
+if ( $url ) {
+	// assign a variable to smarty for use in the template
+	$smarty->assign('rss_url', $url);
+	
+	// use MagpieRSS to fetch remote RSS file, and parse it
+	$rss = fetch_rss( $url );
+	
+	// if fetch_rss returned false, we encountered an error
+	if ( !$rss ) {
+		$smarty->assign( 'error', magpie_error() );
+	}
+	$smarty->assign('rss', $rss );
+	
+	$item = $rss->items[0];
+	$date = parse_w3cdtf( $item['dc']['date'] );
+	$smarty->assign( 'date', $date );
+}
+
+// parse smarty template, and display using the variables we assigned
+$smarty->display('simple.smarty');
+
+?>
Index: /Dev/trunk/rdfapi/util/magpie/scripts/smarty_plugin/modifier.rss_date_parse.php
===================================================================
--- /Dev/trunk/rdfapi/util/magpie/scripts/smarty_plugin/modifier.rss_date_parse.php	(revision 12)
+++ /Dev/trunk/rdfapi/util/magpie/scripts/smarty_plugin/modifier.rss_date_parse.php	(revision 12)
@@ -0,0 +1,31 @@
+<?php
+
+/*
+ * Smarty plugin
+ * -------------------------------------------------------------
+ * Type:     modifier
+ * Name:     rss_date_parse
+ * Purpose:  parse rss date into unix epoch
+ * Input:    string: rss date
+ *			 default_date:  default date if $rss_date is empty
+ *
+ * NOTE!!!  parse_w3cdtf provided by MagpieRSS's rss_utils.inc
+ *          this file needs to be included somewhere in your script
+ * -------------------------------------------------------------
+ */
+ 
+function smarty_modifier_rss_date_parse ($rss_date, $default_date=null)
+{
+	if($rss_date != '') {
+    	return parse_w3cdtf( $rss_date );
+	} elseif (isset($default_date) && $default_date != '') {		
+    	return parse_w3cdtf( $default_date );
+	} else {
+		return;
+	}
+}
+
+
+
+
+?>
Index: /Dev/trunk/rdfapi/util/magpie/scripts/templates/simple.smarty
===================================================================
--- /Dev/trunk/rdfapi/util/magpie/scripts/templates/simple.smarty	(revision 12)
+++ /Dev/trunk/rdfapi/util/magpie/scripts/templates/simple.smarty	(revision 12)
@@ -0,0 +1,46 @@
+<html>
+<head>
+<title>A Simple RSS Box:  I'm not a designer</title>
+</head>
+<body>
+
+<form>
+<b>RSS File:</b> 
+<input type=text" name="rss_url" value="{$rss_url}" size="50"> 
+<input type="submit">
+</form>
+
+<b>Displaying:</b> {$rss_url}
+<p>
+
+{* if $error display the error 
+  elseif parsed RSS object display the RSS 
+  else solicit user for a URL 
+*}
+
+{if $error }
+<b>Error:</b> {$error}
+{elseif $rss}
+<table border=1>
+  <tr>
+    <th colspan=2>
+      <a href="{$rss->channel.link}">{$rss->channel.title}</a>
+    </th>
+  </tr>
+  	{foreach from=$rss->items item=item}
+  	 <tr>
+	  <td>
+	  <a href="{$item.link}">{$item.title}</a>
+  	  </td>
+	  <td>
+	   {$item.dc.date|rss_date_parse|date_format:"%A, %B %e, %Y"}
+	  </td>
+	</tr>
+	{/foreach}
+</table>
+{else}
+  Enter the URL of an RSS file to display.
+{/if}
+
+</body>
+</html>
Index: /Dev/trunk/rdfapi/vocabulary/ATOM_C.php
===================================================================
--- /Dev/trunk/rdfapi/vocabulary/ATOM_C.php	(revision 12)
+++ /Dev/trunk/rdfapi/vocabulary/ATOM_C.php	(revision 12)
@@ -0,0 +1,206 @@
+<?php
+/**
+*   ATOM Vocabulary (Resource)
+*
+*   @version $Id: ATOM_C.php 431 2007-05-01 15:49:19Z cweiske $
+*   @author Tobias GauÃ (tobias.gauss@web.de)
+*   @package vocabulary
+*
+*   Wrapper, defining resources for all terms of the
+*   ATOM Vocabulary;.
+*   For details about ATOM see: http://semtext.org/atom/atom.html.
+*   Using the wrapper allows you to define all aspects of
+*   the vocabulary in one spot, simplifing implementation and
+*   maintainence.
+*/
+class ATOM{
+
+	function TYPE()
+	{
+		return  new Resource(ATOM_NS . 'type');
+
+	}
+
+	function MODE()
+	{
+		return  new Resource(ATOM_NS . 'mode');
+
+	}
+
+	function NAME()
+	{
+		return  new Resource(ATOM_NS . 'name');
+
+	}
+
+	function URL()
+	{
+		return  new Resource(ATOM_NS . 'url');
+
+	}
+
+	function EMAIL()
+	{
+		return  new Resource(ATOM_NS . 'email');
+
+	}
+
+	function REL()
+	{
+		return  new Resource(ATOM_NS . 'rel');
+
+	}
+
+	function HREF()
+	{
+		return  new Resource(ATOM_NS . 'href');
+
+	}
+
+	function TITLE()
+	{
+		return  new Resource(ATOM_NS . 'title');
+
+	}
+
+	function ATOM_CONSTRUCT()
+	{
+		return  new Resource(ATOM_NS . 'AtomConstruct');
+
+	}
+
+	function CONTENT()
+	{
+		return  new Resource(ATOM_NS . 'Content');
+
+	}
+
+	function PERSON()
+	{
+		return  new Resource(ATOM_NS . 'Person');
+
+	}
+
+	function VALUE()
+	{
+		return  new Resource(ATOM_NS . 'value');
+
+	}
+
+	function LINK()
+	{
+		return  new Resource(ATOM_NS . 'Link');
+
+	}
+
+	function FEED()
+	{
+		return  new Resource(ATOM_NS . 'Feed');
+
+	}
+
+	function VERSION()
+	{
+		return  new Resource(ATOM_NS . 'version');
+
+	}
+
+	function LANG()
+	{
+		return  new Resource(ATOM_NS . 'lang');
+
+	}
+
+	function AUTHOR()
+	{
+		return  new Resource(ATOM_NS . 'author');
+
+	}
+
+	function CONTRIBUTOR()
+	{
+		return  new Resource(ATOM_NS . 'contributor');
+
+	}
+
+	function TAGLINE()
+	{
+		return  new Resource(ATOM_NS . 'tagline');
+
+	}
+
+	function GENERATOR()
+	{
+		return  new Resource(ATOM_NS . 'generator');
+
+	}
+
+	function COPYRIGHT()
+	{
+		return  new Resource(ATOM_NS . 'copyright');
+
+	}
+
+	function INFO()
+	{
+		return  new Resource(ATOM_NS . 'info');
+
+	}
+
+	function MODIFIED()
+	{
+		return  new Resource(ATOM_NS . 'modified');
+
+	}
+
+	function ENTRY()
+	{
+		return  new Resource(ATOM_NS . 'Entry');
+
+	}
+
+	function HAS_CHILD()
+	{
+		return  new Resource(ATOM_NS . 'hasChild');
+
+	}
+
+	function HAS_ENTRY()
+	{
+		return  new Resource(ATOM_NS . 'hasEntry');
+
+	}
+
+	function HAS_LINK()
+	{
+		return  new Resource(ATOM_NS . 'hasLink');
+
+	}
+
+	function HAS_TITLE()
+	{
+		return  new Resource(ATOM_NS . 'hasTitle');
+
+	}
+
+	function ISSUED()
+	{
+		return  new Resource(ATOM_NS . 'issued');
+
+	}
+
+	function CREATED()
+	{
+		return  new Resource(ATOM_NS . 'created');
+
+	}
+
+	function SUMMARY()
+	{
+		return  new Resource(ATOM_NS . 'summary');
+	}
+}
+
+
+
+?>
Index: /Dev/trunk/rdfapi/vocabulary/ATOM_RES.php
===================================================================
--- /Dev/trunk/rdfapi/vocabulary/ATOM_RES.php	(revision 12)
+++ /Dev/trunk/rdfapi/vocabulary/ATOM_RES.php	(revision 12)
@@ -0,0 +1,206 @@
+<?php
+/**
+*   ATOM Vocabulary (Resource)
+*
+*   @version $Id: ATOM_RES.php 431 2007-05-01 15:49:19Z cweiske $
+*   @author Tobias GauÃ (tobias.gauss@web.de)
+*   @package vocabulary
+*
+*   Wrapper, defining resources for all terms of the
+*   ATOM Vocabulary;.
+*   For details about ATOM see: http://semtext.org/atom/atom.html.
+*   Using the wrapper allows you to define all aspects of
+*   the vocabulary in one spot, simplifing implementation and
+*   maintainence.
+*/
+class ATOM_RES{
+
+	function TYPE()
+	{
+		return  new ResResource(ATOM_NS . 'type');
+
+	}
+
+	function MODE()
+	{
+		return  new ResResource(ATOM_NS . 'mode');
+
+	}
+
+	function NAME()
+	{
+		return  new ResResource(ATOM_NS . 'name');
+
+	}
+
+	function URL()
+	{
+		return  new ResResource(ATOM_NS . 'url');
+
+	}
+
+	function EMAIL()
+	{
+		return  new ResResource(ATOM_NS . 'email');
+
+	}
+
+	function REL()
+	{
+		return  new ResResource(ATOM_NS . 'rel');
+
+	}
+
+	function HREF()
+	{
+		return  new ResResource(ATOM_NS . 'href');
+
+	}
+
+	function TITLE()
+	{
+		return  new ResResource(ATOM_NS . 'title');
+
+	}
+
+	function ATOM_CONSTRUCT()
+	{
+		return  new ResResource(ATOM_NS . 'AtomConstruct');
+
+	}
+
+	function CONTENT()
+	{
+		return  new ResResource(ATOM_NS . 'Content');
+
+	}
+
+	function PERSON()
+	{
+		return  new ResResource(ATOM_NS . 'Person');
+
+	}
+
+	function VALUE()
+	{
+		return  new ResResource(ATOM_NS . 'value');
+
+	}
+
+	function LINK()
+	{
+		return  new ResResource(ATOM_NS . 'Link');
+
+	}
+
+	function FEED()
+	{
+		return  new ResResource(ATOM_NS . 'Feed');
+
+	}
+
+	function VERSION()
+	{
+		return  new ResResource(ATOM_NS . 'version');
+
+	}
+
+	function LANG()
+	{
+		return  new ResResource(ATOM_NS . 'lang');
+
+	}
+
+	function AUTHOR()
+	{
+		return  new ResResource(ATOM_NS . 'author');
+
+	}
+
+	function CONTRIBUTOR()
+	{
+		return  new ResResource(ATOM_NS . 'contributor');
+
+	}
+
+	function TAGLINE()
+	{
+		return  new ResResource(ATOM_NS . 'tagline');
+
+	}
+
+	function GENERATOR()
+	{
+		return  new ResResource(ATOM_NS . 'generator');
+
+	}
+
+	function COPYRIGHT()
+	{
+		return  new ResResource(ATOM_NS . 'copyright');
+
+	}
+
+	function INFO()
+	{
+		return  new ResResource(ATOM_NS . 'info');
+
+	}
+
+	function MODIFIED()
+	{
+		return  new ResResource(ATOM_NS . 'modified');
+
+	}
+
+	function ENTRY()
+	{
+		return  new ResResource(ATOM_NS . 'Entry');
+
+	}
+
+	function HAS_CHILD()
+	{
+		return  new ResResource(ATOM_NS . 'hasChild');
+
+	}
+
+	function HAS_ENTRY()
+	{
+		return  new ResResource(ATOM_NS . 'hasEntry');
+
+	}
+
+	function HAS_LINK()
+	{
+		return  new ResResource(ATOM_NS . 'hasLink');
+
+	}
+
+	function HAS_TITLE()
+	{
+		return  new ResResource(ATOM_NS . 'hasTitle');
+
+	}
+
+	function ISSUED()
+	{
+		return  new ResResource(ATOM_NS . 'issued');
+
+	}
+
+	function CREATED()
+	{
+		return  new ResResource(ATOM_NS . 'created');
+
+	}
+
+	function SUMMARY()
+	{
+		return  new ResResource(ATOM_NS . 'summary');
+	}
+}
+
+
+
+?>
Index: /Dev/trunk/rdfapi/vocabulary/DC.php
===================================================================
--- /Dev/trunk/rdfapi/vocabulary/DC.php	(revision 12)
+++ /Dev/trunk/rdfapi/vocabulary/DC.php	(revision 12)
@@ -0,0 +1,80 @@
+<?php
+// ----------------------------------------------------------------------------------
+// Dublin Core Vocabulary
+// ----------------------------------------------------------------------------------
+// @version                  : $Id: DC.php 268 2006-05-15 05:28:09Z tgauss $
+// Authors                   : Chris Bizer (chris@bizer.de)
+//
+// Description               : Wrapper, defining resources for all terms of the Dublin 
+//							   Core Vocabulary. For details about DC see: http://dublincore.org/
+// 							   Using the wrapper allows you to define all aspects of 
+//                             the vocabulary in one spot, simplifing implementation and 
+//                             maintainence. Working with the vocabulary, you should use 
+//                             these resources as shortcuts in your code. 
+//							   
+
+
+
+ 
+// DC concepts
+$DC_contributor = new Resource(DC_NS . 'contributor');    
+$DC_coverage = new Resource(DC_NS . 'coverage');  
+$DC_creator = new Resource(DC_NS . 'creator');  
+$DC_date = new Resource(DC_NS . 'date');  
+$DC_description = new Resource(DC_NS . 'description');  
+$DC_format = new Resource(DC_NS . 'format');  
+$DC_identifier = new Resource(DC_NS . 'identifier');  
+$DC_language = new Resource(DC_NS . 'language');  
+$DC_publisher = new Resource(DC_NS . 'publisher');  
+$DC_rights = new Resource(DC_NS . 'rights');  
+$DC_source = new Resource(DC_NS . 'source');  
+$DC_subject = new Resource(DC_NS . 'subject');  
+$DC_title = new Resource(DC_NS . 'title');  
+$DC_type = new Resource(DC_NS . 'type');  
+
+// Dublin Core Metadata Element Set (DCMES) 1.1
+$DCMES_name = array('contributor', 'coverage', 'creator', 'date',
+		    'description', 'format', 'identifier', 'language', 
+		    'publisher', 'relation', 'rights', 'source', 
+		    'subject', 'title', 'type');
+
+foreach ($DCMES_name as $name) {
+    $DCMES[$name] = new Resource(DC_NS . $name);
+    $GLOBALS['DC_' . $name] = $DCMES[$name];
+}
+
+// Other Elements and Element Refinements
+$DCTERM_name = array('abstract', 'accessRights', 'alternative', 'audience', 
+		     'available', 'bibliographicCitation', 'conformsTo',
+		     'created', 'dateAccepted', 'dateCopyrighted', 
+		     'dateSubmitted', 'educationLevel', 'extent',
+		     'hasFormat', 'hasPart', 'hasVersion', 
+		     'isFormatOf', 'isPartOf', 'isReferencedBy', 'isReplacedBy',
+		     'isRequiredBy', 'issued', 'isVersionOf', 'license',
+		     'mediator', 'medium', 'modified', 'references',
+		     'replaces', 'requires', 'rightsHolder', 'spatial',
+		     'tableOfContents', 'temporal', 'valid');
+foreach ($DCTERM_name as $name) {
+    $DCTERM[$name] = new Resource(DCTERM_NS . $name);
+}
+
+// Encoding schemes
+$scheme_name = array('Box', 'DCMIType', 'IMT', 'ISO3166', 'ISO639-2',
+		     'LCC', 'LCSH', 'MESH', 'Period', 'Point',
+		     'RFC1766', 'RFC3066', 'TGN', 'UDC', 'URI',
+		     'W3CDTF');
+
+foreach ($scheme_name as $name) {
+   $DCTERM[$name] = new Resource(DCTERM_NS . $name);
+}
+
+// DCMI Type Vocabulary
+$DCMITYPE_names = array('Collection', 'Dataset', 'Event', 'Image',
+			'InteractiveResource', 'MovingImage', 'PhysicalObject',
+			'Service', 'Software', 'Sound', 'StillImage', 'Text');
+
+foreach ($DCMITYPE_names as $name) {
+    $DCMITYPE[$name] = new Resource(DCMITYPE_NS . $name);
+}
+
+?>
Index: /Dev/trunk/rdfapi/vocabulary/DC_C.php
===================================================================
--- /Dev/trunk/rdfapi/vocabulary/DC_C.php	(revision 12)
+++ /Dev/trunk/rdfapi/vocabulary/DC_C.php	(revision 12)
@@ -0,0 +1,486 @@
+<?php
+/**
+*   Dublin Core Vocabulary (Resource)
+*
+*   @version $Id: DC_C.php 431 2007-05-01 15:49:19Z cweiske $
+*   @author Chris Bizer (chris@bizer.de)
+*   @package vocabulary
+*
+*   Wrapper, defining resources for all terms of the Dublin
+*   Core Vocabulary. For details about DC see: http://dublincore.org/
+*   Using the wrapper allows you to define all aspects of
+*   the vocabulary in one spot, simplifing implementation and
+*   maintainence.
+*/
+class DC{
+	// DC concepts
+	function CONTRIBUTOR()
+	{
+		return  new Resource(DC_NS . 'contributor');
+
+	}
+
+	function COVERAGE()
+	{
+		return  new Resource(DC_NS . 'coverage');
+
+	}
+
+	function CREATOR()
+	{
+		return  new Resource(DC_NS . 'creator');
+
+	}
+
+	function DATE()
+	{
+		return  new Resource(DC_NS . 'date');
+
+	}
+
+	function DESCRIPTION()
+	{
+		return  new Resource(DC_NS . 'description');
+
+	}
+
+	function FORMAT()
+	{
+		return  new Resource(DC_NS . 'format');
+
+	}
+
+	function IDENTIFIER()
+	{
+		return  new Resource(DC_NS . 'identifier');
+
+	}
+
+	function LANGUAGE()
+	{
+		return  new Resource(DC_NS . 'language');
+
+	}
+
+	function PUBLISHER()
+	{
+		return  new Resource(DC_NS . 'publisher');
+
+	}
+
+	function RIGHTS()
+	{
+		return  new Resource(DC_NS . 'rights');
+
+	}
+
+	function SOURCE()
+	{
+		return  new Resource(DC_NS . 'source');
+
+	}
+
+	function SUBJECT()
+	{
+		return  new Resource(DC_NS . 'subject');
+
+	}
+
+	function TITLE()
+	{
+		return  new Resource(DC_NS . 'title');
+
+	}
+
+	function TYPE()
+	{
+		return  new Resource(DC_NS . 'type');
+	}
+
+
+	// Other Elements and Element Refinements
+	function ABSTRACT_()
+	{
+		return  new Resource(DCTERM_NS . 'abstract');
+
+	}
+
+	function ACCESS_RIGHTS()
+	{
+		return  new Resource(DCTERM_NS . 'accessRights');
+
+	}
+
+	function ALTERNATIVE()
+	{
+		return  new Resource(DCTERM_NS . 'alternative');
+
+	}
+
+	function AUDIENCE()
+	{
+		return  new Resource(DCTERM_NS . 'audience');
+
+	}
+
+	function AVAILABLE()
+	{
+		return  new Resource(DCTERM_NS . 'available');
+
+	}
+
+	function BIBLIOGRAPHIC_CITATION()
+	{
+		return  new Resource(DCTERM_NS . 'bibliographicCitation');
+
+	}
+
+	function CONFORMS_TO()
+	{
+		return  new Resource(DCTERM_NS . 'conformsTo');
+
+	}
+
+	function CREATED()
+	{
+		return  new Resource(DCTERM_NS . 'created');
+
+	}
+
+	function DATE_ACCEPTED()
+	{
+		return  new Resource(DCTERM_NS . 'dateAccepted');
+
+	}
+
+	function DATE_COPYRIGHTED()
+	{
+		return  new Resource(DCTERM_NS . 'dateCopyrighted');
+
+	}
+
+	function DATE_SUBMITTED()
+	{
+		return  new Resource(DCTERM_NS . 'dateSubmitted');
+
+	}
+
+	function EDUCATION_LEVEL()
+	{
+		return  new Resource(DCTERM_NS . 'educationLevel');
+
+	}
+
+	function EXTENT()
+	{
+		return  new Resource(DCTERM_NS . 'extent');
+
+	}
+
+	function HAS_FORMAT()
+	{
+		return  new Resource(DCTERM_NS . 'hasFormat');
+
+	}
+
+	function HAS_PART()
+	{
+		return  new Resource(DCTERM_NS . 'hasPart');
+
+	}
+
+	function HAS_VERSION()
+	{
+		return  new Resource(DCTERM_NS . 'hasVersion');
+
+	}
+
+	function IS_FORMAT_OF()
+	{
+		return  new Resource(DCTERM_NS . 'isFormatOf');
+
+	}
+
+	function IS_PART_OF()
+	{
+		return  new Resource(DCTERM_NS . 'isPartOf');
+
+	}
+
+	function IS_REFERENCED_BY()
+	{
+		return  new Resource(DCTERM_NS . 'isReferencedBy');
+
+	}
+
+	function IS_REPLACED_BY()
+	{
+		return  new Resource(DCTERM_NS . 'isReplacedBy');
+
+	}
+
+	function IS_REQUIRED_BY()
+	{
+		return  new Resource(DCTERM_NS . 'isRequiredBy');
+
+	}
+
+	function ISSUED()
+	{
+		return  new Resource(DCTERM_NS . 'issued');
+
+	}
+
+	function IS_VERSION_OF()
+	{
+		return  new Resource(DCTERM_NS . 'isVersionOf');
+
+	}
+
+	function LICENSE()
+	{
+		return  new Resource(DCTERM_NS . 'license');
+
+	}
+
+	function MEDIATOR()
+	{
+		return  new Resource(DCTERM_NS . 'mediator');
+
+	}
+
+	function MEDIUM()
+	{
+		return  new Resource(DCTERM_NS . 'medium');
+
+	}
+
+	function MODIFIED()
+	{
+		return  new Resource(DCTERM_NS . 'modified');
+
+	}
+
+	function REFERENCES()
+	{
+		return  new Resource(DCTERM_NS . 'references');
+
+	}
+
+	function REPLACES()
+	{
+		return  new Resource(DCTERM_NS . 'replaces');
+
+	}
+
+	function REQUIRES()
+	{
+		return  new Resource(DCTERM_NS . 'requires');
+
+	}
+
+	function RIGHTS_HOLDER()
+	{
+		return  new Resource(DCTERM_NS . 'rightsHolder');
+
+	}
+
+	function SPATIAL()
+	{
+		return  new Resource(DCTERM_NS . 'spatial');
+
+	}
+
+	function TABLE_OF_CONTENTS()
+	{
+		return  new Resource(DCTERM_NS . 'tableOfContents');
+
+	}
+
+	function TEMPORAL()
+	{
+		return  new Resource(DCTERM_NS . 'temporal');
+
+	}
+
+	function VALID()
+	{
+		return  new Resource(DCTERM_NS . 'valid');
+
+	}
+
+
+	// Encoding schemes
+	function BOX()
+	{
+		return  new Resource(DCTERM_NS . 'Box');
+
+	}
+
+	function DCMI_TYPE()
+	{
+		return  new Resource(DCTERM_NS . 'DCMIType');
+
+	}
+
+	function IMT()
+	{
+		return  new Resource(DCTERM_NS . 'IMT');
+
+	}
+
+	function ISO3166()
+	{
+		return  new Resource(DCTERM_NS . 'ISO3166');
+
+	}
+
+	function ISO639_2()
+	{
+		return  new Resource(DCTERM_NS . 'ISO639-2');
+
+	}
+
+	function LCC()
+	{
+		return  new Resource(DCTERM_NS . 'LCC');
+
+	}
+
+	function LCSH()
+	{
+		return  new Resource(DCTERM_NS . 'LCSH');
+
+	}
+
+	function MESH()
+	{
+		return  new Resource(DCTERM_NS . 'MESH');
+
+	}
+
+	function PERIOD()
+	{
+		return  new Resource(DCTERM_NS . 'Period');
+
+	}
+
+	function POINT()
+	{
+		return  new Resource(DCTERM_NS . 'Point');
+
+	}
+
+	function RFC1766()
+	{
+		return  new Resource(DCTERM_NS . 'RFC1766');
+
+	}
+
+	function RFC3066()
+	{
+		return  new Resource(DCTERM_NS . 'RFC3066');
+
+	}
+
+	function TGN()
+	{
+		return  new Resource(DCTERM_NS . 'TGN');
+
+	}
+
+	function UDC()
+	{
+		return  new Resource(DCTERM_NS . 'UDC');
+
+	}
+
+	function URI()
+	{
+		return  new Resource(DCTERM_NS . 'URI');
+
+	}
+
+	function W3CDTF()
+	{
+		return  new Resource(DCTERM_NS . 'W3CDTF');
+
+	}
+
+
+	// DCMI Type Vocabulary
+	function COLLECTION()
+	{
+		return  new Resource(DCMITYPE_NS . 'Collection');
+
+	}
+
+	function DATASET()
+	{
+		return  new Resource(DCMITYPE_NS . 'Dataset');
+
+	}
+
+	function EVENT()
+	{
+		return  new Resource(DCMITYPE_NS . 'Event');
+
+	}
+
+	function IMAGE()
+	{
+		return  new Resource(DCMITYPE_NS . 'Image');
+
+	}
+
+	function INTERACTIVERESOURCE()
+	{
+		return  new Resource(DCMITYPE_NS . 'Interactive_Resource');
+
+	}
+
+	function MOVINGIMAGE()
+	{
+		return  new Resource(DCMITYPE_NS . 'Moving_Image');
+
+	}
+
+	function PHYSICALOBJECT()
+	{
+		return  new Resource(DCMITYPE_NS . 'Physical_Object');
+
+	}
+
+	function SERVICE()
+	{
+		return  new Resource(DCMITYPE_NS . 'Service');
+
+	}
+
+	function SOFTWARE()
+	{
+		return  new Resource(DCMITYPE_NS . 'Software');
+
+	}
+
+	function SOUND()
+	{
+		return  new Resource(DCMITYPE_NS . 'Sound');
+
+	}
+
+	function STILLIMAGE()
+	{
+		return  new Resource(DCMITYPE_NS . 'Still_Image');
+
+	}
+
+	function TEXT()
+	{
+		return  new Resource(DCMITYPE_NS . 'Text');
+	}
+
+}
+
+
+?>
Index: /Dev/trunk/rdfapi/vocabulary/DC_RES.php
===================================================================
--- /Dev/trunk/rdfapi/vocabulary/DC_RES.php	(revision 12)
+++ /Dev/trunk/rdfapi/vocabulary/DC_RES.php	(revision 12)
@@ -0,0 +1,486 @@
+<?php
+/**
+*   Dublin Core Vocabulary (ResResource)
+*
+*   @version $Id: DC_RES.php 431 2007-05-01 15:49:19Z cweiske $
+*   @author Chris Bizer (chris@bizer.de)
+*   @package vocabulary
+*
+*   Wrapper, defining resources for all terms of the Dublin
+*   Core Vocabulary. For details about DC see: http://dublincore.org/
+*   Using the wrapper allows you to define all aspects of
+*   the vocabulary in one spot, simplifing implementation and
+*   maintainence.
+*/
+class DC_RES{
+	// DC concepts
+	function CONTRIBUTOR()
+	{
+		return  new ResResource(DC_NS . 'contributor');
+
+	}
+
+	function COVERAGE()
+	{
+		return  new ResResource(DC_NS . 'coverage');
+
+	}
+
+	function CREATOR()
+	{
+		return  new ResResource(DC_NS . 'creator');
+
+	}
+
+	function DATE()
+	{
+		return  new ResResource(DC_NS . 'date');
+
+	}
+
+	function DESCRIPTION()
+	{
+		return  new ResResource(DC_NS . 'description');
+
+	}
+
+	function FORMAT()
+	{
+		return  new ResResource(DC_NS . 'format');
+
+	}
+
+	function IDENTIFIER()
+	{
+		return  new ResResource(DC_NS . 'identifier');
+
+	}
+
+	function LANGUAGE()
+	{
+		return  new ResResource(DC_NS . 'language');
+
+	}
+
+	function PUBLISHER()
+	{
+		return  new ResResource(DC_NS . 'publisher');
+
+	}
+
+	function RIGHTS()
+	{
+		return  new ResResource(DC_NS . 'rights');
+
+	}
+
+	function SOURCE()
+	{
+		return  new ResResource(DC_NS . 'source');
+
+	}
+
+	function SUBJECT()
+	{
+		return  new ResResource(DC_NS . 'subject');
+
+	}
+
+	function TITLE()
+	{
+		return  new ResResource(DC_NS . 'title');
+
+	}
+
+	function TYPE()
+	{
+		return  new ResResource(DC_NS . 'type');
+	}
+
+
+	// Other Elements and Element Refinements
+	function ABSTRACT_()
+	{
+		return  new ResResource(DCTERM_NS . 'abstract');
+
+	}
+
+	function ACCESS_RIGHTS()
+	{
+		return  new ResResource(DCTERM_NS . 'accessRights');
+
+	}
+
+	function ALTERNATIVE()
+	{
+		return  new ResResource(DCTERM_NS . 'alternative');
+
+	}
+
+	function AUDIENCE()
+	{
+		return  new ResResource(DCTERM_NS . 'audience');
+
+	}
+
+	function AVAILABLE()
+	{
+		return  new ResResource(DCTERM_NS . 'available');
+
+	}
+
+	function BIBLIOGRAPHIC_CITATION()
+	{
+		return  new ResResource(DCTERM_NS . 'bibliographicCitation');
+
+	}
+
+	function CONFORMS_TO()
+	{
+		return  new ResResource(DCTERM_NS . 'conformsTo');
+
+	}
+
+	function CREATED()
+	{
+		return  new ResResource(DCTERM_NS . 'created');
+
+	}
+
+	function DATE_ACCEPTED()
+	{
+		return  new ResResource(DCTERM_NS . 'dateAccepted');
+
+	}
+
+	function DATE_COPYRIGHTED()
+	{
+		return  new ResResource(DCTERM_NS . 'dateCopyrighted');
+
+	}
+
+	function DATE_SUBMITTED()
+	{
+		return  new ResResource(DCTERM_NS . 'dateSubmitted');
+
+	}
+
+	function EDUCATION_LEVEL()
+	{
+		return  new ResResource(DCTERM_NS . 'educationLevel');
+
+	}
+
+	function EXTENT()
+	{
+		return  new ResResource(DCTERM_NS . 'extent');
+
+	}
+
+	function HAS_FORMAT()
+	{
+		return  new ResResource(DCTERM_NS . 'hasFormat');
+
+	}
+
+	function HAS_PART()
+	{
+		return  new ResResource(DCTERM_NS . 'hasPart');
+
+	}
+
+	function HAS_VERSION()
+	{
+		return  new ResResource(DCTERM_NS . 'hasVersion');
+
+	}
+
+	function IS_FORMAT_OF()
+	{
+		return  new ResResource(DCTERM_NS . 'isFormatOf');
+
+	}
+
+	function IS_PART_OF()
+	{
+		return  new ResResource(DCTERM_NS . 'isPartOf');
+
+	}
+
+	function IS_REFERENCED_BY()
+	{
+		return  new ResResource(DCTERM_NS . 'isReferencedBy');
+
+	}
+
+	function IS_REPLACED_BY()
+	{
+		return  new ResResource(DCTERM_NS . 'isReplacedBy');
+
+	}
+
+	function IS_REQUIRED_BY()
+	{
+		return  new ResResource(DCTERM_NS . 'isRequiredBy');
+
+	}
+
+	function ISSUED()
+	{
+		return  new ResResource(DCTERM_NS . 'issued');
+
+	}
+
+	function IS_VERSION_OF()
+	{
+		return  new ResResource(DCTERM_NS . 'isVersionOf');
+
+	}
+
+	function LICENSE()
+	{
+		return  new ResResource(DCTERM_NS . 'license');
+
+	}
+
+	function MEDIATOR()
+	{
+		return  new ResResource(DCTERM_NS . 'mediator');
+
+	}
+
+	function MEDIUM()
+	{
+		return  new ResResource(DCTERM_NS . 'medium');
+
+	}
+
+	function MODIFIED()
+	{
+		return  new ResResource(DCTERM_NS . 'modified');
+
+	}
+
+	function REFERENCES()
+	{
+		return  new ResResource(DCTERM_NS . 'references');
+
+	}
+
+	function REPLACES()
+	{
+		return  new ResResource(DCTERM_NS . 'replaces');
+
+	}
+
+	function REQUIRES()
+	{
+		return  new ResResource(DCTERM_NS . 'requires');
+
+	}
+
+	function RIGHTS_HOLDER()
+	{
+		return  new ResResource(DCTERM_NS . 'rightsHolder');
+
+	}
+
+	function SPATIAL()
+	{
+		return  new ResResource(DCTERM_NS . 'spatial');
+
+	}
+
+	function TABLE_OF_CONTENTS()
+	{
+		return  new ResResource(DCTERM_NS . 'tableOfContents');
+
+	}
+
+	function TEMPORAL()
+	{
+		return  new ResResource(DCTERM_NS . 'temporal');
+
+	}
+
+	function VALID()
+	{
+		return  new ResResource(DCTERM_NS . 'valid');
+
+	}
+
+
+	// Encoding schemes
+	function BOX()
+	{
+		return  new ResResource(DCTERM_NS . 'Box');
+
+	}
+
+	function DCMI_TYPE()
+	{
+		return  new ResResource(DCTERM_NS . 'DCMIType');
+
+	}
+
+	function IMT()
+	{
+		return  new ResResource(DCTERM_NS . 'IMT');
+
+	}
+
+	function ISO3166()
+	{
+		return  new ResResource(DCTERM_NS . 'ISO3166');
+
+	}
+
+	function ISO639_2()
+	{
+		return  new ResResource(DCTERM_NS . 'ISO639-2');
+
+	}
+
+	function LCC()
+	{
+		return  new ResResource(DCTERM_NS . 'LCC');
+
+	}
+
+	function LCSH()
+	{
+		return  new ResResource(DCTERM_NS . 'LCSH');
+
+	}
+
+	function MESH()
+	{
+		return  new ResResource(DCTERM_NS . 'MESH');
+
+	}
+
+	function PERIOD()
+	{
+		return  new ResResource(DCTERM_NS . 'Period');
+
+	}
+
+	function POINT()
+	{
+		return  new ResResource(DCTERM_NS . 'Point');
+
+	}
+
+	function RFC1766()
+	{
+		return  new ResResource(DCTERM_NS . 'RFC1766');
+
+	}
+
+	function RFC3066()
+	{
+		return  new ResResource(DCTERM_NS . 'RFC3066');
+
+	}
+
+	function TGN()
+	{
+		return  new ResResource(DCTERM_NS . 'TGN');
+
+	}
+
+	function UDC()
+	{
+		return  new ResResource(DCTERM_NS . 'UDC');
+
+	}
+
+	function URI()
+	{
+		return  new ResResource(DCTERM_NS . 'URI');
+
+	}
+
+	function W3CDTF()
+	{
+		return  new ResResource(DCTERM_NS . 'W3CDTF');
+
+	}
+
+
+	// DCMI Type Vocabulary
+	function COLLECTION()
+	{
+		return  new ResResource(DCMITYPE_NS . 'Collection');
+
+	}
+
+	function DATASET()
+	{
+		return  new ResResource(DCMITYPE_NS . 'Dataset');
+
+	}
+
+	function EVENT()
+	{
+		return  new ResResource(DCMITYPE_NS . 'Event');
+
+	}
+
+	function IMAGE()
+	{
+		return  new ResResource(DCMITYPE_NS . 'Image');
+
+	}
+
+	function INTERACTIVE_RESOURCE()
+	{
+		return  new ResResource(DCMITYPE_NS . 'Interactive_Resource');
+
+	}
+
+	function MOVINGIMAGE()
+	{
+		return  new ResResource(DCMITYPE_NS . 'Moving_Image');
+
+	}
+
+	function PHYSICALOBJECT()
+	{
+		return  new ResResource(DCMITYPE_NS . 'Physical_Object');
+
+	}
+
+	function SERVICE()
+	{
+		return  new ResResource(DCMITYPE_NS . 'Service');
+
+	}
+
+	function SOFTWARE()
+	{
+		return  new ResResource(DCMITYPE_NS . 'Software');
+
+	}
+
+	function SOUND()
+	{
+		return  new Resource(DCMITYPE_NS . 'Sound');
+
+	}
+
+	function STILLIMAGE()
+	{
+		return  new ResResource(DCMITYPE_NS . 'Still_Image');
+
+	}
+
+	function TEXT()
+	{
+		return  new ResResource(DCMITYPE_NS . 'Text');
+	}
+}
+
+
+
+?>
Index: /Dev/trunk/rdfapi/vocabulary/FOAF.php
===================================================================
--- /Dev/trunk/rdfapi/vocabulary/FOAF.php	(revision 12)
+++ /Dev/trunk/rdfapi/vocabulary/FOAF.php	(revision 12)
@@ -0,0 +1,87 @@
+<?php
+/**
+*   Friend of a Friend (FOAF) Vocabulary (Resource)
+*
+*   @version $Id: FOAF.php 431 2007-05-01 15:49:19Z cweiske $
+*   @author Tobias GauÃ (tobias.gauss@web.de)
+*   @package vocabulary
+*
+*   Wrapper, defining resources for all terms of the
+*   Friend of a Friend project (FOAF).
+*   For details about FOAF see: http://xmlns.com/foaf/0.1/.
+*   Using the wrapper allows you to define all aspects of
+*   the vocabulary in one spot, simplifing implementation and
+*   maintainence.
+*/
+
+
+
+// FOAF concepts
+$FOAF_Agent = new Resource(FOAF_NS . 'Agent');
+$FOAF_Document = new Resource(FOAF_NS . 'Document');
+$FOAF_Group = new Resource(FOAF_NS . 'Group');
+$FOAF_Image = new Resource(FOAF_NS . 'Image');
+$FOAF_OnlineAccount = new Resource(FOAF_NS . 'OnlineAccount');
+$FOAF_OnlineChatAccount = new Resource(FOAF_NS . 'OnlineChatAccount');
+$FOAF_OnlineEcommerceAccount = new Resource(FOAF_NS . 'OnlineEcommerceAccount');
+$FOAF_OnlineGamingAccount = new Resource(FOAF_NS . 'OnlineGamingAccount');
+$FOAF_Organization = new Resource(FOAF_NS . 'Organization');
+$FOAF_Person = new Resource(FOAF_NS . 'Person');
+$FOAF_PersonalProfileDocument = new Resource(FOAF_NS . 'PersonalProfileDocument');
+$FOAF_Project = new Resource(FOAF_NS . 'Project');
+$FOAF_accountName = new Resource(FOAF_NS . 'accountName');
+$FOAF_accountServiceHomepage = new Resource(FOAF_NS . 'accountServiceHomepage');
+$FOAF_aimChatID = new Resource(FOAF_NS . 'aimChatID');
+$FOAF_based_near = new Resource(FOAF_NS . 'based_near');
+$FOAF_currentProject = new Resource(FOAF_NS . 'currentProject');
+$FOAF_depiction = new Resource(FOAF_NS . 'depiction');
+$FOAF_depicts = new Resource(FOAF_NS . 'depicts');
+$FOAF_dnaChecksum = new Resource(FOAF_NS . 'dnaChecksum');
+$FOAF_family_name = new Resource(FOAF_NS . 'family_name');
+$FOAF_firstName = new Resource(FOAF_NS . 'firstName');
+$FOAF_fundedBy = new Resource(FOAF_NS . 'fundedBy');
+$FAOF_geekcode = new Resource(FOAF_NS . 'geekcode');
+$FOAF_gender = new Resource(FOAF_NS . 'gender');
+$FOAF_givenname = new Resource(FOAF_NS . 'givenname');
+$FOAF_holdsAccount = new Resource(FOAF_NS . 'holdsAccount');
+$FOAF_homepage = new Resource(FOAF_NS . 'homepage');
+$FOAF_icqChatID = new Resource(FOAF_NS . 'icqChatID');
+$FOAF_img = new Resource(FOAF_NS . 'img');
+$FOAF_interest = new Resource(FOAF_NS . 'interest');
+$FOAF_jabberID = new Resource(FOAF_NS . 'jabberID');
+$FOAF_knows = new Resource(FOAF_NS . 'knows');
+$FOAF_logo = new Resource(FOAF_NS . 'logo');
+$FOAF_made = new Resource(FOAF_NS . 'made');
+$FOAF_maker = new Resource(FOAF_NS . 'maker');
+$FOAF_mbox = new Resource(FOAF_NS . 'mbox');
+$FOAF_mbox_sha1sum = new Resource(FOAF_NS . 'mbox_sha1sum');
+$FOAF_member = new Resource(FOAF_NS . 'member');
+$FOAF_membershipClass =new Resource(FOAF_NS . 'membershipClass');
+$FOAF_msnChatID = new Resource(FOAF_NS . 'msnChatID');
+$FOAF_myersBriggs = new Resource(FOAF_NS . 'myersBriggs');
+$FOAF_name = new Resource(FOAF_NS . 'name');
+$FOAF_nick = new Resource(FOAF_NS . 'nick');
+$FOAF_page = new Resource(FOAF_NS . 'page');
+$FOAF_pastProject = new Resource(FOAF_NS . 'pastProject');
+$FOAF_phone = new Resource(FOAF_NS . 'phone');
+$FOAF_plan = new Resource(FOAF_NS . 'plan');
+$FOAF_primaryTopic = new Resource(FOAF_NS . 'primaryTopic');
+$FOAF_publications = new Resource(FOAF_NS . 'publications');
+$FOAF_schoolHomepage = new Resource (FOAF_NS . 'schoolHomepage');
+$FOAF_sha1 = new Resource (FOAF_NS . 'sha1');
+$FOAF_surname = new Resource (FOAF_NS . 'surname');
+$FOAF_theme = new Resource(FOAF_NS . 'theme');
+$FOAF_thumbnail = new Resource(FOAF_NS . 'thumbnail');
+$FOAF_tipjar = new Resource(FOAF_NS . 'tipjar');
+$FOAF_title = new Resource(FOAF_NS . 'title');
+$FOAF_topic = new Resource(FOAF_NS . 'topic');
+$FOAF_topic_interest = new Resource(FOAF_NS . 'topic_interest');
+$FOAF_weblog = new Resource(FOAF_NS . 'weblog');
+$FOAF_workInfoHomepage = new Resource(FOAF_NS . 'workInfoHomepage');
+$FOAF_workplaceHomepage = new Resource(FOAF_NS . 'workplaceHomepage');
+$FOAF_yahooChatID = new Resource(FOAF_NS . 'yahooChatID');
+
+
+
+
+?>
Index: /Dev/trunk/rdfapi/vocabulary/FOAF_C.php
===================================================================
--- /Dev/trunk/rdfapi/vocabulary/FOAF_C.php	(revision 12)
+++ /Dev/trunk/rdfapi/vocabulary/FOAF_C.php	(revision 12)
@@ -0,0 +1,401 @@
+<?php
+/**
+*   Friend of a Friend (FOAF) Vocabulary (Resource)
+*
+*   @version $Id: FOAF_C.php 431 2007-05-01 15:49:19Z cweiske $
+*   @author Tobias GauÃ (tobias.gauss@web.de)
+*   @package vocabulary
+*
+*   Wrapper, defining resources for all terms of the
+*   Friend of a Friend project (FOAF).
+*   For details about FOAF see: http://xmlns.com/foaf/0.1/.
+*   Using the wrapper allows you to define all aspects of
+*   the vocabulary in one spot, simplifing implementation and
+*   maintainence.
+*/
+class FOAF{
+
+
+	function AGENT()
+	{
+		return  new Resource(FOAF_NS . 'Agent');
+
+	}
+
+	function DOCUMENT()
+	{
+		return  new Resource(FOAF_NS . 'Document');
+
+	}
+
+	function GROUP()
+	{
+		return  new Resource(FOAF_NS . 'Group');
+
+	}
+
+	function IMAGE()
+	{
+		return  new Resource(FOAF_NS . 'Image');
+
+	}
+
+	function ONLINE_ACCOUNT()
+	{
+		return  new Resource(FOAF_NS . 'OnlineAccount');
+
+	}
+
+	function ONLINE_CHAT_ACCOUNT()
+	{
+		return  new Resource(FOAF_NS . 'OnlineChatAccount');
+
+	}
+
+	function ONLINE_ECOMMERCE_ACCOUNT()
+	{
+		return  new Resource(FOAF_NS . 'OnlineEcommerceAccount');
+
+	}
+
+	function ONLINE_GAMING_ACCOUNT()
+	{
+		return  new Resource(FOAF_NS . 'OnlineGamingAccount');
+
+	}
+
+	function ORGANIZATION()
+	{
+		return  new Resource(FOAF_NS . 'Organization');
+
+	}
+
+	function PERSON()
+	{
+		return  new Resource(FOAF_NS . 'Person');
+
+	}
+
+	function PERSONAL_PROFILE_DOCUMENT()
+	{
+		return  new Resource(FOAF_NS . 'PersonalProfileDocument');
+
+	}
+
+	function PROJECT()
+	{
+		return  new Resource(FOAF_NS . 'Project');
+
+	}
+
+	function ACCOUNT_NAME()
+	{
+		return  new Resource(FOAF_NS . 'accountName');
+
+	}
+
+	function ACCOUNT_SERVICE_HOMEPAGE()
+	{
+		return  new Resource(FOAF_NS . 'accountServiceHomepage');
+
+	}
+
+	function AIM_CHAT_ID()
+	{
+		return  new Resource(FOAF_NS . 'aimChatID');
+
+	}
+
+	function BASED_NEAR()
+	{
+		return  new Resource(FOAF_NS . 'based_near');
+
+	}
+
+	function CURRENT_PROJECT()
+	{
+		return  new Resource(FOAF_NS . 'currentProject');
+
+	}
+
+	function DEPICTION()
+	{
+		return  new Resource(FOAF_NS . 'depiction');
+
+	}
+
+	function DEPICTS()
+	{
+		return  new Resource(FOAF_NS . 'depicts');
+
+	}
+
+	function DNA_CHECKSUM()
+	{
+		return  new Resource(FOAF_NS . 'dnaChecksum');
+
+	}
+
+	function FAMILY_NAME()
+	{
+		return  new Resource(FOAF_NS . 'family_name');
+
+	}
+
+	function FIRST_NAME()
+	{
+		return  new Resource(FOAF_NS . 'firstName');
+
+	}
+
+	function FUNDED_BY()
+	{
+		return  new Resource(FOAF_NS . 'fundedBy');
+
+	}
+
+	function GEEKCODE()
+	{
+		return  new Resource(FOAF_NS . 'geekcode');
+
+	}
+
+	function GENDER()
+	{
+		return  new Resource(FOAF_NS . 'gender');
+
+	}
+
+	function GIVENNAME()
+	{
+		return  new Resource(FOAF_NS . 'givenname');
+
+	}
+
+	function HOLDS_ACCOUNT()
+	{
+		return  new Resource(FOAF_NS . 'holdsAccount');
+
+	}
+
+	function HOMEPAGE()
+	{
+		return  new Resource(FOAF_NS . 'homepage');
+
+	}
+
+	function ICQ_CHAT_ID()
+	{
+		return  new Resource(FOAF_NS . 'icqChatID');
+
+	}
+
+	function IMG()
+	{
+		return  new Resource(FOAF_NS . 'img');
+
+	}
+
+	function INTEREST()
+	{
+		return  new Resource(FOAF_NS . 'interest');
+
+	}
+
+	function JABBER_ID()
+	{
+		return  new Resource(FOAF_NS . 'jabberID');
+
+	}
+
+	function KNOWS()
+	{
+		return  new Resource(FOAF_NS . 'knows');
+
+	}
+
+	function LOGO()
+	{
+		return  new Resource(FOAF_NS . 'logo');
+
+	}
+
+	function MADE()
+	{
+		return  new Resource(FOAF_NS . 'made');
+
+	}
+
+	function MAKER()
+	{
+		return  new Resource(FOAF_NS . 'maker');
+
+	}
+
+	function MBOX()
+	{
+		return  new Resource(FOAF_NS . 'mbox');
+
+	}
+
+	function MBOX_SHA1SUM()
+	{
+		return  new Resource(FOAF_NS . 'mbox_sha1sum');
+
+	}
+
+	function MEMBER()
+	{
+		return  new Resource(FOAF_NS . 'member');
+
+	}
+
+	function MEMBERSHIP_CLASS()
+	{
+		return new Resource(FOAF_NS . 'membershipClass');
+
+	}
+
+	function MSN_CHAT_ID()
+	{
+		return  new Resource(FOAF_NS . 'msnChatID');
+
+	}
+
+	function MYERS_BRIGGS()
+	{
+		return  new Resource(FOAF_NS . 'myersBriggs');
+
+	}
+
+	function NAME()
+	{
+		return  new Resource(FOAF_NS . 'name');
+
+	}
+
+	function NICK()
+	{
+		return  new Resource(FOAF_NS . 'nick');
+
+	}
+
+	function PAGE()
+	{
+		return  new Resource(FOAF_NS . 'page');
+
+	}
+
+	function PAST_PROJECT()
+	{
+		return  new Resource(FOAF_NS . 'pastProject');
+
+	}
+
+	function PHONE()
+	{
+		return  new Resource(FOAF_NS . 'phone');
+
+	}
+
+	function PLAN()
+	{
+		return  new Resource(FOAF_NS . 'plan');
+
+	}
+
+	function PRIMARY_TOPIC()
+	{
+		return  new Resource(FOAF_NS . 'primaryTopic');
+
+	}
+
+	function PUBLICATIONS()
+	{
+		return  new Resource(FOAF_NS . 'publications');
+
+	}
+
+	function SCHOOL_HOMEPAGE()
+	{
+		return  new Resource (FOAF_NS . 'schoolHomepage');
+
+	}
+
+	function SHA1()
+	{
+		return  new Resource (FOAF_NS . 'sha1');
+
+	}
+
+	function SURNAME()
+	{
+		return  new Resource (FOAF_NS . 'surname');
+
+	}
+
+	function THEME()
+	{
+		return  new Resource(FOAF_NS . 'theme');
+
+	}
+
+	function THUMBNAIL()
+	{
+		return  new Resource(FOAF_NS . 'thumbnail');
+
+	}
+
+	function TIPJAR()
+	{
+		return  new Resource(FOAF_NS . 'tipjar');
+
+	}
+
+	function TITLE()
+	{
+		return  new Resource(FOAF_NS . 'title');
+
+	}
+
+	function TOPIC()
+	{
+		return  new Resource(FOAF_NS . 'topic');
+
+	}
+
+	function TOPIC_INTEREST()
+	{
+		return  new Resource(FOAF_NS . 'topic_interest');
+
+	}
+
+	function WEBLOG()
+	{
+		return  new Resource(FOAF_NS . 'weblog');
+
+	}
+
+	function WORK_INFO_HOMEPAGE()
+	{
+		return  new Resource(FOAF_NS . 'workInfoHomepage');
+
+	}
+
+	function WORKPLACE_HOMEPAGE()
+	{
+		return  new Resource(FOAF_NS . 'workplaceHomepage');
+
+	}
+
+	function YAHOO_CHAT_ID()
+	{
+		return  new Resource(FOAF_NS . 'yahooChatID');
+	}
+}
+
+
+
+
+
+?>
Index: /Dev/trunk/rdfapi/vocabulary/FOAF_RES.php
===================================================================
--- /Dev/trunk/rdfapi/vocabulary/FOAF_RES.php	(revision 12)
+++ /Dev/trunk/rdfapi/vocabulary/FOAF_RES.php	(revision 12)
@@ -0,0 +1,399 @@
+<?php
+/**
+*   Friend of a Friend (FOAF) Vocabulary (ResResource)
+*
+*   @version $Id: FOAF_RES.php 431 2007-05-01 15:49:19Z cweiske $
+*   @author Tobias GauÃ (tobias.gauss@web.de)
+*   @package vocabulary
+*
+*   Wrapper, defining resources for all terms of the
+*   Friend of a Friend project (FOAF).
+*   For details about FOAF see: http://xmlns.com/foaf/0.1/.
+*   Using the wrapper allows you to define all aspects of
+*   the vocabulary in one spot, simplifing implementation and
+*   maintainence.
+*/
+class FOAF_RES{
+
+	function AGENT()
+	{
+		return  new ResResource(FOAF_NS . 'Agent');
+
+	}
+
+	function DOCUMENT()
+	{
+		return  new ResResource(FOAF_NS . 'Document');
+
+	}
+
+	function GROUP()
+	{
+		return  new ResResource(FOAF_NS . 'Group');
+
+	}
+
+	function IMAGE()
+	{
+		return  new ResResource(FOAF_NS . 'Image');
+
+	}
+
+	function ONLINE_ACCOUNT()
+	{
+		return  new ResResource(FOAF_NS . 'OnlineAccount');
+
+	}
+
+	function ONLINE_CHAT_ACCOUNT()
+	{
+		return  new ResResource(FOAF_NS . 'OnlineChatAccount');
+
+	}
+
+	function ONLINE_ECOMMERCE_ACCOUNT()
+	{
+		return  new ResResource(FOAF_NS . 'OnlineEcommerceAccount');
+
+	}
+
+	function ONLINE_GAMING_ACCOUNT()
+	{
+		return  new ResResource(FOAF_NS . 'OnlineGamingAccount');
+
+	}
+
+	function ORGANIZATION()
+	{
+		return  new ResResource(FOAF_NS . 'Organization');
+
+	}
+
+	function PERSON()
+	{
+		return  new ResResource(FOAF_NS . 'Person');
+
+	}
+
+	function PERSONAL_PROFILE_DOCUMENT()
+	{
+		return  new ResResource(FOAF_NS . 'PersonalProfileDocument');
+
+	}
+
+	function PROJECT()
+	{
+		return  new ResResource(FOAF_NS . 'Project');
+
+	}
+
+	function ACCOUNT_NAME()
+	{
+		return  new ResResource(FOAF_NS . 'accountName');
+
+	}
+
+	function ACCOUNT_SERVICE_HOMEPAGE()
+	{
+		return  new ResResource(FOAF_NS . 'accountServiceHomepage');
+
+	}
+
+	function AIM_CHAT_ID()
+	{
+		return  new ResResource(FOAF_NS . 'aimChatID');
+
+	}
+
+	function BASED_NEAR()
+	{
+		return  new ResResource(FOAF_NS . 'based_near');
+
+	}
+
+	function CURRENT_PROJECT()
+	{
+		return  new ResResource(FOAF_NS . 'currentProject');
+
+	}
+
+	function DEPICTION()
+	{
+		return  new ResResource(FOAF_NS . 'depiction');
+
+	}
+
+	function DEPICTS()
+	{
+		return  new ResResource(FOAF_NS . 'depicts');
+
+	}
+
+	function DNA_CHECKSUM()
+	{
+		return  new ResResource(FOAF_NS . 'dnaChecksum');
+
+	}
+
+	function FAMILY_NAME()
+	{
+		return  new ResResource(FOAF_NS . 'family_name');
+
+	}
+
+	function FIRST_NAME()
+	{
+		return  new ResResource(FOAF_NS . 'firstName');
+
+	}
+
+	function FUNDED_BY()
+	{
+		return  new ResResource(FOAF_NS . 'fundedBy');
+
+	}
+
+	function GEEKCODE()
+	{
+		return  new ResResource(FOAF_NS . 'geekcode');
+
+	}
+
+	function GENDER()
+	{
+		return  new ResResource(FOAF_NS . 'gender');
+
+	}
+
+	function GIVENNAME()
+	{
+		return  new ResResource(FOAF_NS . 'givenname');
+
+	}
+
+	function HOLDS_ACCOUNT()
+	{
+		return  new ResResource(FOAF_NS . 'holdsAccount');
+
+	}
+
+	function HOMEPAGE()
+	{
+		return  new ResResource(FOAF_NS . 'homepage');
+
+	}
+
+	function ICQ_CHAT_ID()
+	{
+		return  new ResResource(FOAF_NS . 'icqChatID');
+
+	}
+
+	function IMG()
+	{
+		return  new ResResource(FOAF_NS . 'img');
+
+	}
+
+	function INTEREST()
+	{
+		return  new ResResource(FOAF_NS . 'interest');
+
+	}
+
+	function JABBER_ID()
+	{
+		return  new ResResource(FOAF_NS . 'jabberID');
+
+	}
+
+	function KNOWS()
+	{
+		return  new ResResource(FOAF_NS . 'knows');
+
+	}
+
+	function LOGO()
+	{
+		return  new ResResource(FOAF_NS . 'logo');
+
+	}
+
+	function MADE()
+	{
+		return  new ResResource(FOAF_NS . 'made');
+
+	}
+
+	function MAKER()
+	{
+		return  new ResResource(FOAF_NS . 'maker');
+
+	}
+
+	function MBOX()
+	{
+		return  new ResResource(FOAF_NS . 'mbox');
+
+	}
+
+	function MBOX_SHA1SUM()
+	{
+		return  new ResResource(FOAF_NS . 'mbox_sha1sum');
+
+	}
+
+	function MEMBER()
+	{
+		return  new ResResource(FOAF_NS . 'member');
+
+	}
+
+	function MEMBERSHIP_CLASS()
+	{
+		return new ResResource(FOAF_NS . 'membershipClass');
+
+	}
+
+	function MSN_CHAT_ID()
+	{
+		return  new ResResource(FOAF_NS . 'msnChatID');
+
+	}
+
+	function MYERS_BRIGGS()
+	{
+		return  new ResResource(FOAF_NS . 'myersBriggs');
+
+	}
+
+	function NAME()
+	{
+		return  new ResResource(FOAF_NS . 'name');
+
+	}
+
+	function NICK()
+	{
+		return  new ResResource(FOAF_NS . 'nick');
+
+	}
+
+	function PAGE()
+	{
+		return  new ResResource(FOAF_NS . 'page');
+
+	}
+
+	function PAST_PROJECT()
+	{
+		return  new ResResource(FOAF_NS . 'pastProject');
+
+	}
+
+	function PHONE()
+	{
+		return  new ResResource(FOAF_NS . 'phone');
+
+	}
+
+	function PLAN()
+	{
+		return  new ResResource(FOAF_NS . 'plan');
+
+	}
+
+	function PRIMARY_TOPIC()
+	{
+		return  new ResResource(FOAF_NS . 'primaryTopic');
+
+	}
+
+	function PUBLICATIONS()
+	{
+		return  new ResResource(FOAF_NS . 'publications');
+
+	}
+
+	function SCHOOL_HOMEPAGE()
+	{
+		return  new ResResource (FOAF_NS . 'schoolHomepage');
+
+	}
+
+	function SHA1()
+	{
+		return  new ResResource (FOAF_NS . 'sha1');
+
+	}
+
+	function SURNAME()
+	{
+		return  new ResResource (FOAF_NS . 'surname');
+
+	}
+
+	function THEME()
+	{
+		return  new ResResource(FOAF_NS . 'theme');
+
+	}
+
+	function THUMBNAIL()
+	{
+		return  new ResResource(FOAF_NS . 'thumbnail');
+
+	}
+
+	function TIPJAR()
+	{
+		return  new ResResource(FOAF_NS . 'tipjar');
+
+	}
+
+	function TITLE()
+	{
+		return  new ResResource(FOAF_NS . 'title');
+
+	}
+
+	function TOPIC()
+	{
+		return  new ResResource(FOAF_NS . 'topic');
+
+	}
+
+	function TOPIC_INTEREST()
+	{
+		return  new ResResource(FOAF_NS . 'topic_interest');
+
+	}
+
+	function WEBLOG()
+	{
+		return  new ResResource(FOAF_NS . 'weblog');
+
+	}
+
+	function WORK_INFO_HOMEPAGE()
+	{
+		return  new ResResource(FOAF_NS . 'workInfoHomepage');
+
+	}
+
+	function WORKPLACE_HOMEPAGE()
+	{
+		return  new ResResource(FOAF_NS . 'workplaceHomepage');
+
+	}
+
+	function YAHOO_CHAT_ID()
+	{
+		return  new ResResource(FOAF_NS . 'yahooChatID');
+	}
+}
+
+
+
+
+?>
Index: /Dev/trunk/rdfapi/vocabulary/OWL.php
===================================================================
--- /Dev/trunk/rdfapi/vocabulary/OWL.php	(revision 12)
+++ /Dev/trunk/rdfapi/vocabulary/OWL.php	(revision 12)
@@ -0,0 +1,66 @@
+<?php
+/**
+*   OWL Vocabulary
+*
+*   @version $Id: OWL.php 431 2007-05-01 15:49:19Z cweiske $
+*   @author Daniel Westphal (dawe@gmx.de)
+*   @package vocabulary
+*
+*   Wrapper, defining resources for all terms of theWeb
+*   Ontology Language (OWL). For details about OWL see:
+*   http://www.w3.org/TR/owl-ref/
+*   Using the wrapper allows you to define all aspects of
+*   the vocabulary in one spot, simplifing implementation and
+*   maintainence.
+*/
+
+// OWL concepts
+$OWL_AnnotationProperty = new Resource(OWL_NS . 'AnnotationProperty');
+$OWL_AllDifferent = new Resource(OWL_NS . 'AllDifferent');
+$OWL_allValuesFrom = new Resource(OWL_NS . 'allValuesFrom');
+$OWL_backwardCompatibleWith = new Resource(OWL_NS . 'backwardCompatibleWith');
+$OWL_cardinality = new Resource(OWL_NS . 'cardinality');
+$OWL_Class = new Resource(OWL_NS . 'Class');
+$OWL_complementOf = new Resource(OWL_NS . 'complementOf');
+$OWL_Datatype = new Resource(OWL_NS . 'Datatype');
+$OWL_DatatypeProperty = new Resource(OWL_NS . 'DatatypeProperty');
+$OWL_DataRange = new Resource(OWL_NS . 'DataRange');
+$OWL_DatatypeRestriction = new Resource(OWL_NS . 'DatatypeRestriction');
+$OWL_DeprecatedClass = new Resource(OWL_NS . 'DeprecatedClass');
+$OWL_DeprecatedProperty = new Resource(OWL_NS . 'DeprecatedProperty');
+$OWL_distinctMembers = new Resource(OWL_NS . 'distinctMembers');
+$OWL_differentFrom = new Resource(OWL_NS . 'differentFrom');
+$OWL_disjointWith = new Resource(OWL_NS . 'disjointWith');
+$OWL_equivalentClass = new Resource(OWL_NS . 'equivalentClass');
+$OWL_equivalentProperty = new Resource(OWL_NS . 'equivalentProperty');
+$OWL_FunctionalProperty = new Resource(OWL_NS . 'FunctionalProperty');
+$OWL_hasValue = new Resource(OWL_NS . 'hasValue');
+$OWL_incompatibleWith = new Resource(OWL_NS . 'incompatibleWith');
+$OWL_imports = new Resource(OWL_NS . 'imports');
+$OWL_intersectionOf = new Resource(OWL_NS . 'intersectionOf');
+$OWL_InverseFunctionalProperty = new Resource(OWL_NS . 'InverseFunctionalProperty');
+$OWL_inverseOf = new Resource(OWL_NS . 'inverseOf');
+$OWL_maxCardinality = new Resource(OWL_NS . 'maxCardinality');
+$OWL_minCardinality = new Resource(OWL_NS . 'minCardinality');
+$OWL_Nothing = new Resource(OWL_NS . 'Nothing');
+$OWL_ObjectClass = new Resource(OWL_NS . 'ObjectClass');
+$OWL_ObjectProperty = new Resource(OWL_NS . 'ObjectProperty');
+$OWL_ObjectRestriction = new Resource(OWL_NS . 'ObjectRestriction');
+$OWL_oneOf = new Resource(OWL_NS . 'oneOf');
+$OWL_onProperty = new Resource(OWL_NS . 'onProperty');
+$OWL_Ontology = new Resource(OWL_NS . 'Ontology');
+$OWL_priorVersion = new Resource(OWL_NS . 'priorVersion');
+$OWL_Property = new Resource(OWL_NS . 'Property');
+$OWL_Restriction = new Resource(OWL_NS . 'Restriction');
+$OWL_sameAs = new Resource(OWL_NS . 'sameAs');
+$OWL_sameClassAs = new Resource(OWL_NS . 'sameClassAs');
+$OWL_sameIndividualAs = new Resource(OWL_NS . 'sameIndividualAs');
+$OWL_samePropertyAs = new Resource(OWL_NS . 'samePropertyAs');
+$OWL_someValuesFrom = new Resource(OWL_NS . 'someValuesFrom');
+$OWL_SymmetricProperty = new Resource(OWL_NS . 'SymmetricProperty');
+$OWL_Thing = new Resource(OWL_NS . 'Thing');
+$OWL_TransitiveProperty = new Resource(OWL_NS . 'TransitiveProperty');
+$OWL_unionOf = new Resource(OWL_NS . 'unionOf');
+$OWL_versionInfo = new Resource(OWL_NS . 'versionInfo');
+
+?>
Index: /Dev/trunk/rdfapi/vocabulary/OWL_C.php
===================================================================
--- /Dev/trunk/rdfapi/vocabulary/OWL_C.php	(revision 12)
+++ /Dev/trunk/rdfapi/vocabulary/OWL_C.php	(revision 12)
@@ -0,0 +1,303 @@
+<?php
+/**
+*   OWL Vocabulary (Resource)
+*
+*   @version $Id: OWL_C.php 431 2007-05-01 15:49:19Z cweiske $
+*   @author Daniel Westphal (dawe@gmx.de)
+*   @package vocabulary
+*
+*   Wrapper, defining resources for all terms of theWeb
+*   Ontology Language (OWL). For details about OWL see:
+*   http://www.w3.org/TR/owl-ref/
+*   Using the wrapper allows you to define all aspects of
+*   the vocabulary in one spot, simplifing implementation and
+*   maintainence.
+*/
+class OWL{
+
+	// OWL concepts
+	function ANNOTATION_PROPERTY()
+	{
+		return  new Resource(OWL_NS . 'AnnotationProperty');
+
+	}
+
+	function ALL_DIFFERENT()
+	{
+		return  new Resource(OWL_NS . 'AllDifferent');
+
+	}
+
+	function ALL_VALUES_FROM()
+	{
+		return  new Resource(OWL_NS . 'allValuesFrom');
+
+	}
+
+	function BACKWARD_COMPATIBLE_WITH()
+	{
+		return  new Resource(OWL_NS . 'backwardCompatibleWith');
+
+	}
+
+	function CARDINALITY()
+	{
+		return  new Resource(OWL_NS . 'cardinality');
+
+	}
+
+	function OWL_CLASS()
+	{
+		return  new Resource(OWL_NS . 'Class');
+
+	}
+
+	function COMPLEMENT_OF()
+	{
+		return  new Resource(OWL_NS . 'complementOf');
+
+	}
+
+	function DATATYPE()
+	{
+		return  new Resource(OWL_NS . 'Datatype');
+
+	}
+
+	function DATATYPE_PROPERTY()
+	{
+		return  new Resource(OWL_NS . 'DatatypeProperty');
+
+	}
+
+	function DATA_RANGE()
+	{
+		return  new Resource(OWL_NS . 'DataRange');
+
+	}
+
+	function DATATYPE_RESTRICTION()
+	{
+		return  new Resource(OWL_NS . 'DatatypeRestriction');
+
+	}
+
+	function DEPRECATED_CLASS()
+	{
+		return  new Resource(OWL_NS . 'DeprecatedClass');
+
+	}
+
+	function DEPRECATED_PROPERTY()
+	{
+		return  new Resource(OWL_NS . 'DeprecatedProperty');
+
+	}
+
+	function DISTINCT_MEMBERS()
+	{
+		return  new Resource(OWL_NS . 'distinctMembers');
+
+	}
+
+	function DIFFERENT_FROM()
+	{
+		return  new Resource(OWL_NS . 'differentFrom');
+
+	}
+
+	function DISJOINT_WITH()
+	{
+		return  new Resource(OWL_NS . 'disjointWith');
+
+	}
+
+	function EQUIVALENT_CLASS()
+	{
+		return  new Resource(OWL_NS . 'equivalentClass');
+
+	}
+
+	function EQUIVALENT_PROPERTY()
+	{
+		return  new Resource(OWL_NS . 'equivalentProperty');
+
+	}
+
+	function FUNCTIONAL_PROPERTY()
+	{
+		return  new Resource(OWL_NS . 'FunctionalProperty');
+
+	}
+
+	function HAS_VALUE()
+	{
+		return  new Resource(OWL_NS . 'hasValue');
+
+	}
+
+	function INCOMPATIBLE_WITH()
+	{
+		return  new Resource(OWL_NS . 'incompatibleWith');
+
+	}
+
+	function IMPORTS()
+	{
+		return  new Resource(OWL_NS . 'imports');
+
+	}
+
+	function INTERSECTION_OF()
+	{
+		return  new Resource(OWL_NS . 'intersectionOf');
+
+	}
+
+	function INVERSE_FUNCTIONAL_PROPERTY()
+	{
+		return  new Resource(OWL_NS . 'InverseFunctionalProperty');
+
+	}
+
+	function INVERSE_OF()
+	{
+		return  new Resource(OWL_NS . 'inverseOf');
+
+	}
+
+	function MAX_CARDINALITY()
+	{
+		return  new Resource(OWL_NS . 'maxCardinality');
+
+	}
+
+	function MIN_CARDINALITY()
+	{
+		return  new Resource(OWL_NS . 'minCardinality');
+
+	}
+
+	function NOTHING()
+	{
+		return  new Resource(OWL_NS . 'Nothing');
+
+	}
+
+	function OBJECT_CLASS()
+	{
+		return  new Resource(OWL_NS . 'ObjectClass');
+
+	}
+
+	function OBJECT_PROPERTY()
+	{
+		return  new Resource(OWL_NS . 'ObjectProperty');
+
+	}
+
+	function OBJECT_RESTRICTION()
+	{
+		return  new Resource(OWL_NS . 'ObjectRestriction');
+
+	}
+
+	function ONE_OF()
+	{
+		return  new Resource(OWL_NS . 'oneOf');
+
+	}
+
+	function ON_PROPERTY()
+	{
+		return  new Resource(OWL_NS . 'onProperty');
+
+	}
+
+	function ONTOLOGY()
+	{
+		return  new Resource(OWL_NS . 'Ontology');
+
+	}
+
+	function PRIOR_VERSION()
+	{
+		return  new Resource(OWL_NS . 'priorVersion');
+
+	}
+
+	function PROPERTY()
+	{
+		return  new Resource(OWL_NS . 'Property');
+
+	}
+
+	function RESTRICTION()
+	{
+		return  new Resource(OWL_NS . 'Restriction');
+
+	}
+
+	function SAME_AS()
+	{
+		return  new Resource(OWL_NS . 'sameAs');
+
+	}
+
+	function SAME_CLASS_AS()
+	{
+		return  new Resource(OWL_NS . 'sameClassAs');
+
+	}
+
+	function SAME_INDIVIDUAL_AS()
+	{
+		return  new Resource(OWL_NS . 'sameIndividualAs');
+
+	}
+
+	function SAME_PROPERTY_AS()
+	{
+		return  new Resource(OWL_NS . 'samePropertyAs');
+
+	}
+
+	function SOME_VALUES_FROM()
+	{
+		return  new Resource(OWL_NS . 'someValuesFrom');
+
+	}
+
+	function SYMMETRIC_PROPERTY()
+	{
+		return  new Resource(OWL_NS . 'SymmetricProperty');
+
+	}
+
+	function THING()
+	{
+		return  new Resource(OWL_NS . 'Thing');
+
+	}
+
+	function TRANSITIVE_PROPERTY()
+	{
+		return  new Resource(OWL_NS . 'TransitiveProperty');
+
+	}
+
+	function UNION_OF()
+	{
+		return  new Resource(OWL_NS . 'unionOf');
+
+	}
+
+	function VERSION_INFO()
+	{
+		return  new Resource(OWL_NS . 'versionInfo');
+	}
+
+}
+
+
+?>
Index: /Dev/trunk/rdfapi/vocabulary/OWL_RES.php
===================================================================
--- /Dev/trunk/rdfapi/vocabulary/OWL_RES.php	(revision 12)
+++ /Dev/trunk/rdfapi/vocabulary/OWL_RES.php	(revision 12)
@@ -0,0 +1,303 @@
+<?php
+/**
+*   OWL Vocabulary (ResResource)
+*
+*   @version $Id: OWL_RES.php 431 2007-05-01 15:49:19Z cweiske $
+*   @author Daniel Westphal (dawe@gmx.de)
+*   @package vocabulary
+*
+*   Wrapper, defining resources for all terms of theWeb
+*   Ontology Language (OWL). For details about OWL see:
+*   http://www.w3.org/TR/owl-ref/
+*   Using the wrapper allows you to define all aspects of
+*   the vocabulary in one spot, simplifing implementation and
+*   maintainence.
+*/
+class OWL_RES{
+
+	// OWL concepts
+	function ANNOTATION_PROPERTY()
+	{
+		return  new ResResource(OWL_NS . 'AnnotationProperty');
+
+	}
+
+	function ALL_DIFFERENT()
+	{
+		return  new ResResource(OWL_NS . 'AllDifferent');
+
+	}
+
+	function ALL_VALUES_FROM()
+	{
+		return  new ResResource(OWL_NS . 'allValuesFrom');
+
+	}
+
+	function BACKWARD_COMPATIBLE_WITH()
+	{
+		return  new ResResource(OWL_NS . 'backwardCompatibleWith');
+
+	}
+
+	function CARDINALITY()
+	{
+		return  new ResResource(OWL_NS . 'cardinality');
+
+	}
+
+	function OWL_CLASS()
+	{
+		return  new ResResource(OWL_NS . 'Class');
+
+	}
+
+	function COMPLEMENT_OF()
+	{
+		return  new ResResource(OWL_NS . 'complementOf');
+
+	}
+
+	function DATATYPE()
+	{
+		return  new ResResource(OWL_NS . 'Datatype');
+
+	}
+
+	function DATATYPE_PROPERTY()
+	{
+		return  new ResResource(OWL_NS . 'DatatypeProperty');
+
+	}
+
+	function DATA_RANGE()
+	{
+		return  new ResResource(OWL_NS . 'DataRange');
+
+	}
+
+	function DATATYPE_RESTRICTION()
+	{
+		return  new ResResource(OWL_NS . 'DatatypeRestriction');
+
+	}
+
+	function DEPRECATED_CLASS()
+	{
+		return  new ResResource(OWL_NS . 'DeprecatedClass');
+
+	}
+
+	function DEPRECATED_PROPERTY()
+	{
+		return  new ResResource(OWL_NS . 'DeprecatedProperty');
+
+	}
+
+	function DISTINCT_MEMBERS()
+	{
+		return  new ResResource(OWL_NS . 'distinctMembers');
+
+	}
+
+	function DIFFERENT_FROM()
+	{
+		return  new ResResource(OWL_NS . 'differentFrom');
+
+	}
+
+	function DISJOINT_WITH()
+	{
+		return  new ResResource(OWL_NS . 'disjointWith');
+
+	}
+
+	function EQUIVALENT_CLASS()
+	{
+		return  new ResResource(OWL_NS . 'equivalentClass');
+
+	}
+
+	function EQUIVALENT_PROPERTY()
+	{
+		return  new ResResource(OWL_NS . 'equivalentProperty');
+
+	}
+
+	function FUNCTIONAL_PROPERTY()
+	{
+		return  new ResResource(OWL_NS . 'FunctionalProperty');
+
+	}
+
+	function HAS_VALUE()
+	{
+		return  new ResResource(OWL_NS . 'hasValue');
+
+	}
+
+	function INCOMPATIBLE_WITH()
+	{
+		return  new ResResource(OWL_NS . 'incompatibleWith');
+
+	}
+
+	function IMPORTS()
+	{
+		return  new ResResource(OWL_NS . 'imports');
+
+	}
+
+	function INTERSECTION_OF()
+	{
+		return  new ResResource(OWL_NS . 'intersectionOf');
+
+	}
+
+	function INVERSE_FUNCTIONAL_PROPERTY()
+	{
+		return  new ResResource(OWL_NS . 'InverseFunctionalProperty');
+
+	}
+
+	function INVERSE_OF()
+	{
+		return  new ResResource(OWL_NS . 'inverseOf');
+
+	}
+
+	function MAX_CARDINALITY()
+	{
+		return  new ResResource(OWL_NS . 'maxCardinality');
+
+	}
+
+	function MIN_CARDINALITY()
+	{
+		return  new ResResource(OWL_NS . 'minCardinality');
+
+	}
+
+	function NOTHING()
+	{
+		return  new ResResource(OWL_NS . 'Nothing');
+
+	}
+
+	function OBJECT_CLASS()
+	{
+		return  new ResResource(OWL_NS . 'ObjectClass');
+
+	}
+
+	function OBJECT_PROPERTY()
+	{
+		return  new ResResource(OWL_NS . 'ObjectProperty');
+
+	}
+
+	function OBJECT_RESTRICTION()
+	{
+		return  new ResResource(OWL_NS . 'ObjectRestriction');
+
+	}
+
+	function ONE_OF()
+	{
+		return  new ResResource(OWL_NS . 'oneOf');
+
+	}
+
+	function ON_PROPERTY()
+	{
+		return  new ResResource(OWL_NS . 'onProperty');
+
+	}
+
+	function ONTOLOGY()
+	{
+		return  new ResResource(OWL_NS . 'Ontology');
+
+	}
+
+	function PRIOR_VERSION()
+	{
+		return  new ResResource(OWL_NS . 'priorVersion');
+
+	}
+
+	function PROPERTY()
+	{
+		return  new ResResource(OWL_NS . 'Property');
+
+	}
+
+	function RESTRICTION()
+	{
+		return  new ResResource(OWL_NS . 'Restriction');
+
+	}
+
+	function SAME_AS()
+	{
+		return  new ResResource(OWL_NS . 'sameAs');
+
+	}
+
+	function SAME_CLASS_AS()
+	{
+		return  new ResResource(OWL_NS . 'sameClassAs');
+
+	}
+
+	function SAME_INDIVIDUAL_AS()
+	{
+		return  new ResResource(OWL_NS . 'sameIndividualAs');
+
+	}
+
+	function SAME_PROPERTY_AS()
+	{
+		return  new ResResource(OWL_NS . 'samePropertyAs');
+
+	}
+
+	function SOME_VALUES_FROM()
+	{
+		return  new ResResource(OWL_NS . 'someValuesFrom');
+
+	}
+
+	function SYMMETRIC_PROPERTY()
+	{
+		return  new ResResource(OWL_NS . 'SymmetricProperty');
+
+	}
+
+	function THING()
+	{
+		return  new ResResource(OWL_NS . 'Thing');
+
+	}
+
+	function TRANSITIVE_PROPERTY()
+	{
+		return  new ResResource(OWL_NS . 'TransitiveProperty');
+
+	}
+
+	function UNION_OF()
+	{
+		return  new ResResource(OWL_NS . 'unionOf');
+
+	}
+
+	function VERSION_INFO()
+	{
+		return  new ResResource(OWL_NS . 'versionInfo');
+	}
+}
+
+
+
+?>
Index: /Dev/trunk/rdfapi/vocabulary/RDF.php
===================================================================
--- /Dev/trunk/rdfapi/vocabulary/RDF.php	(revision 12)
+++ /Dev/trunk/rdfapi/vocabulary/RDF.php	(revision 12)
@@ -0,0 +1,49 @@
+<?php
+/**
+*   Resource Description Framework (RDF) Vocabulary
+*
+*   @version $Id: RDF.php 431 2007-05-01 15:49:19Z cweiske $
+*   @author Daniel Westphal (dawe@gmx.de)
+*   @package vocabulary
+*
+*   Wrapper, defining resources for all terms of the
+*   Resource Description Framework (RDF).
+*   For details about RDF see: http://www.w3.org/RDF/.
+*   Using the wrapper allows you to define all aspects of
+*   the vocabulary in one spot, simplifing implementation and
+*   maintainence.
+*/
+
+
+// RDF concepts (constants are defined in constants.php)
+$RDF_Alt = new Resource(RDF_NAMESPACE_URI . RDF_ALT);
+$RDF_Bag = new Resource(RDF_NAMESPACE_URI . RDF_BAG);
+$RDF_Property = new Resource(RDF_NAMESPACE_URI . RDF_PROPERTY);
+$RDF_Seq = new Resource(RDF_NAMESPACE_URI . RDF_SEQ);
+$RDF_Statement = new Resource(RDF_NAMESPACE_URI . RDF_STATEMENT);
+$RDF_List = new Resource(RDF_NAMESPACE_URI . RDF_LIST);
+$RDF_nil = new Resource(RDF_NAMESPACE_URI . RDF_NIL);
+$RDF_type = new Resource(RDF_NAMESPACE_URI . RDF_TYPE);
+$RDF_rest = new Resource(RDF_NAMESPACE_URI . RDF_REST);
+$RDF_first = new Resource(RDF_NAMESPACE_URI . RDF_FIRST);
+$RDF_subject = new Resource(RDF_NAMESPACE_URI . RDF_SUBJECT);
+$RDF_predicate = new Resource(RDF_NAMESPACE_URI . RDF_PREDICATE);
+$RDF_object = new Resource(RDF_NAMESPACE_URI . RDF_OBJECT);
+$RDF_Description = new Resource(RDF_NAMESPACE_URI . RDF_DESCRIPTION);
+$RDF_ID = new Resource(RDF_NAMESPACE_URI . RDF_ID);
+$RDF_about = new Resource(RDF_NAMESPACE_URI . RDF_ABOUT);
+$RDF_aboutEach = new Resource(RDF_NAMESPACE_URI . RDF_ABOUT_EACH);
+$RDF_aboutEachPrefix = new Resource(RDF_NAMESPACE_URI . RDF_ABOUT_EACH_PREFIX);
+$RDF_bagID = new Resource(RDF_NAMESPACE_URI . RDF_BAG_ID);
+$RDF_resource = new Resource(RDF_NAMESPACE_URI . RDF_RESOURCE);
+$RDF_parseType = new Resource(RDF_NAMESPACE_URI . RDF_PARSE_TYPE);
+$RDF_Literal = new Resource(RDF_NAMESPACE_URI . RDF_PARSE_TYPE_LITERAL);
+$RDF_Resource = new Resource(RDF_NAMESPACE_URI . RDF_PARSE_TYPE_RESOURCE);
+$RDF_li = new Resource(RDF_NAMESPACE_URI . RDF_LI);
+$RDF_nodeID = new Resource(RDF_NAMESPACE_URI . RDF_NODEID);
+$RDF_datatype = new Resource(RDF_NAMESPACE_URI . RDF_DATATYPE);
+$RDF_seeAlso = new Resource(RDF_NAMESPACE_URI . RDF_SEEALSO);
+
+
+
+?>
Index: /Dev/trunk/rdfapi/vocabulary/RDFS.php
===================================================================
--- /Dev/trunk/rdfapi/vocabulary/RDFS.php	(revision 12)
+++ /Dev/trunk/rdfapi/vocabulary/RDFS.php	(revision 12)
@@ -0,0 +1,34 @@
+<?php
+/**
+*   RDF Vocabulary Description Language 1.0: RDF Schema (RDFS) Vocabulary
+*
+*   @version $Id: RDFS.php 431 2007-05-01 15:49:19Z cweiske $
+*   @author Daniel Westphal (dawe@gmx.de)
+*   @package vocabulary
+*
+*   Wrapper, defining resources for all terms of the
+*   RDF Schema (RDFS).
+*   For details about RDFS see: http://www.w3.org/TR/rdf-schema/.
+*   Using the wrapper allows you to define all aspects of
+*   the vocabulary in one spot, simplifing implementation and
+*   maintainence.
+*/
+// RDFS concepts
+$RDFS_Resource = new Resource(RDF_SCHEMA_URI . 'Resource');
+$RDFS_Literal = new Resource(RDF_SCHEMA_URI . 'Literal');
+$RDFS_Class = new Resource(RDF_SCHEMA_URI . 'Class');
+$RDFS_Datatype = new Resource(RDF_SCHEMA_URI . 'Datatype');
+$RDFS_Container = new Resource(RDF_SCHEMA_URI . 'Container');
+$RDFS_ContainerMembershipProperty = new Resource(RDF_SCHEMA_URI . 'ContainerMembershipProperty');
+$RDFS_subClassOf = new Resource(RDF_SCHEMA_URI . 'subClassOf');
+$RDFS_subPropertyOf = new Resource(RDF_SCHEMA_URI . 'subPropertyOf');
+$RDFS_domain = new Resource(RDF_SCHEMA_URI . 'domain');
+$RDFS_range = new Resource(RDF_SCHEMA_URI . 'range');
+$RDFS_label = new Resource(RDF_SCHEMA_URI . 'label');
+$RDFS_comment = new Resource(RDF_SCHEMA_URI . 'comment');
+$RDFS_member = new Resource(RDF_SCHEMA_URI . 'member');
+$RDFS_seeAlso = new Resource(RDF_SCHEMA_URI . 'seeAlso');
+$RDFS_isDefinedBy = new Resource(RDF_SCHEMA_URI . 'isDefinedBy');
+
+
+?>
Index: /Dev/trunk/rdfapi/vocabulary/RDFS_C.php
===================================================================
--- /Dev/trunk/rdfapi/vocabulary/RDFS_C.php	(revision 12)
+++ /Dev/trunk/rdfapi/vocabulary/RDFS_C.php	(revision 12)
@@ -0,0 +1,108 @@
+<?php
+/**
+*   RDF Vocabulary Description Language 1.0: RDF Schema (RDFS) Vocabulary (Resource)
+*
+*   @version $Id: RDFS_C.php 431 2007-05-01 15:49:19Z cweiske $
+*   @author Daniel Westphal (dawe@gmx.de)
+*   @package vocabulary
+*
+*   Wrapper, defining resources for all terms of the
+*   RDF Schema (RDFS).
+*   For details about RDFS see: http://www.w3.org/TR/rdf-schema/.
+*   Using the wrapper allows you to define all aspects of
+*   the vocabulary in one spot, simplifing implementation and
+*   maintainence.
+*/
+class RDFS{
+
+	function RESOURCE()
+	{
+		return  new Resource(RDF_SCHEMA_URI . 'Resource');
+
+	}
+
+	function LITERAL()
+	{
+		return  new Resource(RDF_SCHEMA_URI . 'Literal');
+
+	}
+
+	function RDFS_CLASS()
+	{
+		return  new Resource(RDF_SCHEMA_URI . 'Class');
+
+	}
+
+	function DATATYPE()
+	{
+		return  new Resource(RDF_SCHEMA_URI . 'Datatype');
+
+	}
+
+	function CONTAINER()
+	{
+		return  new Resource(RDF_SCHEMA_URI . 'Container');
+
+	}
+
+	function CONTAINER_MEMBERSHIP_PROPERTY()
+	{
+		return  new Resource(RDF_SCHEMA_URI . 'ContainerMembershipProperty');
+
+	}
+
+	function SUB_CLASS_OF()
+	{
+		return  new Resource(RDF_SCHEMA_URI . 'subClassOf');
+
+	}
+
+	function SUB_PROPERTY_OF()
+	{
+		return  new Resource(RDF_SCHEMA_URI . 'subPropertyOf');
+
+	}
+
+	function DOMAIN()
+	{
+		return  new Resource(RDF_SCHEMA_URI . 'domain');
+
+	}
+
+	function RANGE()
+	{
+		return  new Resource(RDF_SCHEMA_URI . 'range');
+
+	}
+
+	function LABEL()
+	{
+		return  new Resource(RDF_SCHEMA_URI . 'label');
+
+	}
+
+	function COMMENT()
+	{
+		return  new Resource(RDF_SCHEMA_URI . 'comment');
+
+	}
+
+	function MEMBER()
+	{
+		return  new Resource(RDF_SCHEMA_URI . 'member');
+
+	}
+
+	function SEEALSO()
+	{
+		return  new Resource(RDF_SCHEMA_URI . 'seeAlso');
+
+	}
+
+	function IS_DEFINED_BY()
+	{
+		return  new Resource(RDF_SCHEMA_URI . 'isDefinedBy');
+	}
+
+}
+?>
Index: /Dev/trunk/rdfapi/vocabulary/RDFS_RES.php
===================================================================
--- /Dev/trunk/rdfapi/vocabulary/RDFS_RES.php	(revision 12)
+++ /Dev/trunk/rdfapi/vocabulary/RDFS_RES.php	(revision 12)
@@ -0,0 +1,107 @@
+<?php
+/**
+*   RDF Vocabulary Description Language 1.0: RDF Schema (RDFS) Vocabulary (ResResource)
+*
+*   @version $Id: RDFS_RES.php 431 2007-05-01 15:49:19Z cweiske $
+*   @author Daniel Westphal (dawe@gmx.de)
+*   @package vocabulary
+*
+*   Wrapper, defining resources for all terms of the
+*   RDF Schema (RDFS).
+*   For details about RDFS see: http://www.w3.org/TR/rdf-schema/.
+*   Using the wrapper allows you to define all aspects of
+*   the vocabulary in one spot, simplifing implementation and
+*   maintainence.
+*/
+class RDFS_RES{
+
+	function RESOURCE()
+	{
+		return  new ResResource(RDF_SCHEMA_URI . 'Resource');
+
+	}
+
+	function LITERAL()
+	{
+		return  new ResResource(RDF_SCHEMA_URI . 'Literal');
+
+	}
+
+	function RDFS_CLASS()
+	{
+		return  new ResResource(RDF_SCHEMA_URI . 'Class');
+
+	}
+
+	function DATATYPE()
+	{
+		return  new ResResource(RDF_SCHEMA_URI . 'Datatype');
+
+	}
+
+	function CONTAINER()
+	{
+		return  new ResResource(RDF_SCHEMA_URI . 'Container');
+
+	}
+
+	function CONTAINER_MEMBERSHIP_PROPERTY()
+	{
+		return  new ResResource(RDF_SCHEMA_URI . 'ContainerMembershipProperty');
+
+	}
+
+	function SUB_CLASS_OF()
+	{
+		return  new ResResource(RDF_SCHEMA_URI . 'subClassOf');
+
+	}
+
+	function SUB_PROPERTY_OF()
+	{
+		return  new ResResource(RDF_SCHEMA_URI . 'subPropertyOf');
+
+	}
+
+	function DOMAIN()
+	{
+		return  new ResResource(RDF_SCHEMA_URI . 'domain');
+
+	}
+
+	function RANGE()
+	{
+		return  new ResResource(RDF_SCHEMA_URI . 'range');
+
+	}
+
+	function LABEL()
+	{
+		return  new ResResource(RDF_SCHEMA_URI . 'label');
+
+	}
+
+	function COMMENT()
+	{
+		return  new ResResource(RDF_SCHEMA_URI . 'comment');
+
+	}
+
+	function MEMBER()
+	{
+		return  new ResResource(RDF_SCHEMA_URI . 'member');
+
+	}
+
+	function SEEALSO()
+	{
+		return  new ResResource(RDF_SCHEMA_URI . 'seeAlso');
+
+	}
+
+	function IS_DEFINED_BY()
+	{
+		return  new ResResource(RDF_SCHEMA_URI . 'isDefinedBy');
+	}
+}
+?>
Index: /Dev/trunk/rdfapi/vocabulary/RDF_C.php
===================================================================
--- /Dev/trunk/rdfapi/vocabulary/RDF_C.php	(revision 12)
+++ /Dev/trunk/rdfapi/vocabulary/RDF_C.php	(revision 12)
@@ -0,0 +1,182 @@
+<?php
+/**
+*   Resource Description Framework (RDF) Vocabulary (Resource)
+*
+*   @version $Id: RDF_C.php 431 2007-05-01 15:49:19Z cweiske $
+*   @author Daniel Westphal (dawe@gmx.de)
+*   @package vocabulary
+*
+*   Wrapper, defining resources for all terms of the
+*   Resource Description Framework (RDF).
+*   For details about RDF see: http://www.w3.org/RDF/.
+*   Using the wrapper allows you to define all aspects of
+*   the vocabulary in one spot, simplifing implementation and
+*   maintainence.
+*/
+class RDF{
+
+	// RDF concepts (constants are defined in constants.php)
+	function ALT()
+	{
+		return  new Resource(RDF_NAMESPACE_URI . RDF_ALT);
+
+	}
+
+	function BAG()
+	{
+		return  new Resource(RDF_NAMESPACE_URI . RDF_BAG);
+
+	}
+
+	function PROPERTY()
+	{
+		return  new Resource(RDF_NAMESPACE_URI . RDF_PROPERTY);
+
+	}
+
+	function SEQ()
+	{
+		return  new Resource(RDF_NAMESPACE_URI . RDF_SEQ);
+
+	}
+
+	function STATEMENT()
+	{
+		return  new Resource(RDF_NAMESPACE_URI . RDF_STATEMENT);
+
+	}
+
+	function RDF_LIST()
+	{
+		return  new Resource(RDF_NAMESPACE_URI . RDF_LIST);
+
+	}
+
+	function NIL()
+	{
+		return  new Resource(RDF_NAMESPACE_URI . RDF_NIL);
+
+	}
+
+	function TYPE()
+	{
+		return  new Resource(RDF_NAMESPACE_URI . RDF_TYPE);
+
+	}
+
+	function REST()
+	{
+		return  new Resource(RDF_NAMESPACE_URI . RDF_REST);
+
+	}
+
+	function FIRST()
+	{
+		return  new Resource(RDF_NAMESPACE_URI . RDF_FIRST);
+
+	}
+
+	function SUBJECT()
+	{
+		return  new Resource(RDF_NAMESPACE_URI . RDF_SUBJECT);
+
+	}
+
+	function PREDICATE()
+	{
+		return  new Resource(RDF_NAMESPACE_URI . RDF_PREDICATE);
+
+	}
+
+	function OBJECT()
+	{
+		return  new Resource(RDF_NAMESPACE_URI . RDF_OBJECT);
+
+	}
+
+	function DESCRIPTION()
+	{
+		return  new Resource(RDF_NAMESPACE_URI . RDF_DESCRIPTION);
+
+	}
+
+	function ID()
+	{
+		return  new Resource(RDF_NAMESPACE_URI . RDF_ID);
+
+	}
+
+	function ABOUT()
+	{
+		return  new Resource(RDF_NAMESPACE_URI . RDF_ABOUT);
+
+	}
+
+	function ABOUT_EACH()
+	{
+		return  new Resource(RDF_NAMESPACE_URI . RDF_ABOUT_EACH);
+
+	}
+
+	function ABOUT_EACH_PREFIX()
+	{
+		return  new Resource(RDF_NAMESPACE_URI . RDF_ABOUT_EACH_PREFIX);
+
+	}
+
+	function BAG_ID()
+	{
+		return  new Resource(RDF_NAMESPACE_URI . RDF_BAG_ID);
+
+	}
+
+	function RESOURCE()
+	{
+		return  new Resource(RDF_NAMESPACE_URI . RDF_RESOURCE);
+
+	}
+
+	function PARSE_TYPE()
+	{
+		return  new Resource(RDF_NAMESPACE_URI . RDF_PARSE_TYPE);
+
+	}
+
+	function LITERAL()
+	{
+		return  new Resource(RDF_NAMESPACE_URI . RDF_PARSE_TYPE_LITERAL);
+
+	}
+
+	function PARSE_TYPE_RESOURCE()
+	{
+		return  new Resource(RDF_NAMESPACE_URI . RDF_PARSE_TYPE_RESOURCE);
+
+	}
+
+	function LI()
+	{
+		return  new Resource(RDF_NAMESPACE_URI . RDF_LI);
+
+	}
+
+	function NODE_ID()
+	{
+		return  new Resource(RDF_NAMESPACE_URI . RDF_NODEID);
+
+	}
+
+	function DATATYPE()
+	{
+		return  new Resource(RDF_NAMESPACE_URI . RDF_DATATYPE);
+
+	}
+
+	function SEE_ALSO()
+	{
+		return  new Resource(RDF_NAMESPACE_URI . RDF_SEEALSO);
+	}
+}
+
+
+?>
Index: /Dev/trunk/rdfapi/vocabulary/RDF_RES.php
===================================================================
--- /Dev/trunk/rdfapi/vocabulary/RDF_RES.php	(revision 12)
+++ /Dev/trunk/rdfapi/vocabulary/RDF_RES.php	(revision 12)
@@ -0,0 +1,182 @@
+<?php
+/**
+*   Resource Description Framework (RDF) Vocabulary (ResResource)
+*
+*   @version $Id: RDF_RES.php 431 2007-05-01 15:49:19Z cweiske $
+*   @author Daniel Westphal (dawe@gmx.de)
+*   @package vocabulary
+*
+*   Wrapper, defining resources for all terms of the
+*   Resource Description Framework (RDF).
+*   For details about RDF see: http://www.w3.org/RDF/.
+*   Using the wrapper allows you to define all aspects of
+*   the vocabulary in one spot, simplifing implementation and
+*   maintainence.
+*/
+class RDF_RES{
+
+	// RDF concepts (constants are defined in constants.php)
+	function ALT()
+	{
+		return  new ResResource(RDF_NAMESPACE_URI . RDF_ALT);
+
+	}
+
+	function BAG()
+	{
+		return  new ResResource(RDF_NAMESPACE_URI . RDF_BAG);
+
+	}
+
+	function PROPERTY()
+	{
+		return  new ResResource(RDF_NAMESPACE_URI . RDF_PROPERTY);
+
+	}
+
+	function SEQ()
+	{
+		return  new ResResource(RDF_NAMESPACE_URI . RDF_SEQ);
+
+	}
+
+	function STATEMENT()
+	{
+		return  new ResResource(RDF_NAMESPACE_URI . RDF_STATEMENT);
+
+	}
+
+	function RDF_LIST()
+	{
+		return  new ResResource(RDF_NAMESPACE_URI . RDF_LIST);
+
+	}
+
+	function NIL()
+	{
+		return  new ResResource(RDF_NAMESPACE_URI . RDF_NIL);
+
+	}
+
+	function TYPE()
+	{
+		return  new ResResource(RDF_NAMESPACE_URI . RDF_TYPE);
+
+	}
+
+	function REST()
+	{
+		return  new ResResource(RDF_NAMESPACE_URI . RDF_REST);
+
+	}
+
+	function FIRST()
+	{
+		return  new ResResource(RDF_NAMESPACE_URI . RDF_FIRST);
+
+	}
+
+	function SUBJECT()
+	{
+		return  new ResResource(RDF_NAMESPACE_URI . RDF_SUBJECT);
+
+	}
+
+	function PREDICATE()
+	{
+		return  new ResResource(RDF_NAMESPACE_URI . RDF_PREDICATE);
+
+	}
+
+	function OBJECT()
+	{
+		return  new ResResource(RDF_NAMESPACE_URI . RDF_OBJECT);
+
+	}
+
+	function DESCRIPTION()
+	{
+		return  new ResResource(RDF_NAMESPACE_URI . RDF_DESCRIPTION);
+
+	}
+
+	function ID()
+	{
+		return  new ResResource(RDF_NAMESPACE_URI . RDF_ID);
+
+	}
+
+	function ABOUT()
+	{
+		return  new ResResource(RDF_NAMESPACE_URI . RDF_ABOUT);
+
+	}
+
+	function ABOUT_EACH()
+	{
+		return  new ResResource(RDF_NAMESPACE_URI . RDF_ABOUT_EACH);
+
+	}
+
+	function ABOUT_EACH_PREFIX()
+	{
+		return  new ResResource(RDF_NAMESPACE_URI . RDF_ABOUT_EACH_PREFIX);
+
+	}
+
+	function BAG_ID()
+	{
+		return  new ResResource(RDF_NAMESPACE_URI . RDF_BAG_ID);
+
+	}
+
+	function RESOURCE()
+	{
+		return  new ResResource(RDF_NAMESPACE_URI . RDF_RESOURCE);
+
+	}
+
+	function PARSE_TYPE()
+	{
+		return  new ResResource(RDF_NAMESPACE_URI . RDF_PARSE_TYPE);
+
+	}
+
+	function LITERAL()
+	{
+		return  new ResResource(RDF_NAMESPACE_URI . RDF_PARSE_TYPE_LITERAL);
+
+	}
+
+	function PARSE_TYPE_RESOURCE()
+	{
+		return  new ResResource(RDF_NAMESPACE_URI . RDF_PARSE_TYPE_RESOURCE);
+
+	}
+
+	function LI()
+	{
+		return  new ResResource(RDF_NAMESPACE_URI . RDF_LI);
+
+	}
+
+	function NODE_ID()
+	{
+		return  new ResResource(RDF_NAMESPACE_URI . RDF_NODEID);
+
+	}
+
+	function DATATYPE()
+	{
+		return  new ResResource(RDF_NAMESPACE_URI . RDF_DATATYPE);
+
+	}
+
+	function SEE_ALSO()
+	{
+		return  new ResResource(RDF_NAMESPACE_URI . RDF_SEEALSO);
+	}
+}
+
+
+?>
Index: /Dev/trunk/rdfapi/vocabulary/RSS.php
===================================================================
--- /Dev/trunk/rdfapi/vocabulary/RSS.php	(revision 12)
+++ /Dev/trunk/rdfapi/vocabulary/RSS.php	(revision 12)
@@ -0,0 +1,34 @@
+<?php
+/**
+*   RSS Vocabulary
+*
+*   @version $Id: RSS.php 431 2007-05-01 15:49:19Z cweiske $
+*   @author Tobias GauÃ (tobias.gauss@web.de)
+*   @package vocabulary
+*
+*   Wrapper, defining resources for all terms of
+*   RSS.
+*   For details about RSS see: http://purl.org/rss/1.0/.
+*   Using the wrapper allows you to define all aspects of
+*   the vocabulary in one spot, simplifing implementation and
+*   maintainence.
+*/
+// RSS concepts
+$RSS_channel = new Resource(RSS_NS . 'channel');
+$RSS_image = new Resource(RSS_NS . 'image');
+$RSS_item = new Resource(RSS_NS . 'item');
+$RSS_textinput = new Resource(RSS_NS . 'textinput');
+
+$RSS_items = new Resource(RSS_NS . 'items');
+$RSS_title = new Resource(RSS_NS . 'title');
+$RSS_link = new Resource(RSS_NS . 'link');
+$RSS_url = new Resource(RSS_NS . 'url');
+$RSS_description = new Resource(RSS_NS . 'description');
+$RSS_name = new Resource(RSS_NS . 'name');
+
+
+
+
+
+
+?>
Index: /Dev/trunk/rdfapi/vocabulary/RSS_C.php
===================================================================
--- /Dev/trunk/rdfapi/vocabulary/RSS_C.php	(revision 12)
+++ /Dev/trunk/rdfapi/vocabulary/RSS_C.php	(revision 12)
@@ -0,0 +1,80 @@
+<?php
+/**
+*   RSS Vocabulary (Resource)
+*
+*   @version $Id: RSS_C.php 431 2007-05-01 15:49:19Z cweiske $
+*   @author Tobias GauÃ (tobias.gauss@web.de)
+*   @package vocabulary
+*
+*   Wrapper, defining resources for all terms of
+*   RSS.
+*   For details about RSS see: http://purl.org/rss/1.0/.
+*   Using the wrapper allows you to define all aspects of
+*   the vocabulary in one spot, simplifing implementation and
+*   maintainence.
+*/
+class RSS{
+
+	function CHANNEL()
+	{
+		return  new Resource(RSS_NS . 'channel');
+
+	}
+
+	function IMAGE()
+	{
+		return  new Resource(RSS_NS . 'image');
+
+	}
+
+	function ITEM()
+	{
+		return  new Resource(RSS_NS . 'item');
+
+	}
+
+	function TEXTINPUT()
+	{
+		return  new Resource(RSS_NS . 'textinput');
+
+	}
+
+	function ITEMS()
+	{
+		return  new Resource(RSS_NS . 'items');
+
+	}
+
+	function TITLE()
+	{
+		return  new Resource(RSS_NS . 'title');
+
+	}
+
+	function LINK()
+	{
+		return  new Resource(RSS_NS . 'link');
+
+	}
+
+	function URL()
+	{
+		return  new Resource(RSS_NS . 'url');
+
+	}
+
+	function DESCRIPTION()
+	{
+		return  new Resource(RSS_NS . 'description');
+
+	}
+
+	function NAME()
+	{
+		return  new Resource(RSS_NS . 'name');
+	}
+}
+
+
+
+?>
Index: /Dev/trunk/rdfapi/vocabulary/RSS_RES.php
===================================================================
--- /Dev/trunk/rdfapi/vocabulary/RSS_RES.php	(revision 12)
+++ /Dev/trunk/rdfapi/vocabulary/RSS_RES.php	(revision 12)
@@ -0,0 +1,79 @@
+<?php
+/**
+*   RSS Vocabulary (ResResource)
+*
+*   @version $Id: RSS_RES.php 431 2007-05-01 15:49:19Z cweiske $
+*   @author Tobias GauÃ (tobias.gauss@web.de)
+*   @package vocabulary
+*
+*   Wrapper, defining resources for all terms of
+*   RSS.
+*   For details about RSS see: http://purl.org/rss/1.0/.
+*   Using the wrapper allows you to define all aspects of
+*   the vocabulary in one spot, simplifing implementation and
+*   maintainence.
+*/
+class RSS_RES{
+
+	function CHANNEL()
+	{
+		return  new ResResource(RSS_NS . 'channel');
+
+	}
+
+	function IMAGE()
+	{
+		return  new ResResource(RSS_NS . 'image');
+
+	}
+
+	function ITEM()
+	{
+		return  new ResResource(RSS_NS . 'item');
+
+	}
+
+	function TEXTINPUT()
+	{
+		return  new ResResource(RSS_NS . 'textinput');
+
+	}
+
+	function ITEMS()
+	{
+		return  new ResResource(RSS_NS . 'items');
+
+	}
+
+	function TITLE()
+	{
+		return  new ResResource(RSS_NS . 'title');
+
+	}
+
+	function LINK()
+	{
+		return  new ResResource(RSS_NS . 'link');
+
+	}
+
+	function URL()
+	{
+		return  new ResResource(RSS_NS . 'url');
+
+	}
+
+	function DESCRIPTION()
+	{
+		return  new ResResource(RSS_NS . 'description');
+
+	}
+
+	function NAME()
+	{
+		return  new ResResource(RSS_NS . 'name');
+	}
+}
+
+
+?>
Index: /Dev/trunk/rdfapi/vocabulary/VCARD.php
===================================================================
--- /Dev/trunk/rdfapi/vocabulary/VCARD.php	(revision 12)
+++ /Dev/trunk/rdfapi/vocabulary/VCARD.php	(revision 12)
@@ -0,0 +1,66 @@
+<?php
+/**
+*   vCard profile defined by RFC 2426 - Vocabulary
+*
+*   @version $Id: VCARD.php 431 2007-05-01 15:49:19Z cweiske $
+*   @author Daniel Westphal (dawe@gmx.de)
+*   @package vocabulary
+*
+*   Wrapper, defining resources for all terms of the
+*   vCard Vocabulary.
+*   For details about vCard see: http://www.w3.org/TR/vcard-rdf .
+*   Using the wrapper allows you to define all aspects of
+*   the vocabulary in one spot, simplifing implementation and
+*   maintainence.
+*/
+
+// VCARD concepts
+$VCARD_UID = new Resource(VCARD_NS.'UID');
+$VCARD_ORGPROPERTIES = new Resource(VCARD_NS . 'ORGPROPERTIES');
+$VCARD_ADRTYPES = new Resource(VCARD_NS . 'ADRTYPES');
+$VCARD_NPROPERTIES = new Resource(VCARD_NS . 'NPROPERTIES');
+$VCARD_EMAILTYPES = new Resource(VCARD_NS . 'EMAILTYPES');
+$VCARD_TELTYPES = new Resource(VCARD_NS . 'TELTYPES');
+$VCARD_ADRPROPERTIES = new Resource(VCARD_NS . 'ADRPROPERTIES');
+$VCARD_TZTYPES = new Resource(VCARD_NS . 'TZTYPES');
+$VCARD_Street = new Resource(VCARD_NS . 'Street');
+$VCARD_AGENT = new Resource(VCARD_NS . 'AGENT');
+$VCARD_SOURCE = new Resource(VCARD_NS . 'SOURCE');
+$VCARD_BDAY = new Resource(VCARD_NS . 'BDAY');
+$VCARD_REV = new Resource(VCARD_NS . 'REV');
+$VCARD_SORT_STRING = new Resource(VCARD_NS . 'SORT_STRING');
+$VCARD_Orgname = new Resource(VCARD_NS . 'Orgname');
+$VCARD_CATEGORIES = new Resource(VCARD_NS . 'CATEGORIES');
+$VCARD_N = new Resource(VCARD_NS . 'N');
+$VCARD_Pcode = new Resource(VCARD_NS . 'Pcode');
+$VCARD_Prefix = new Resource(VCARD_NS . 'Prefix');
+$VCARD_PHOTO = new Resource(VCARD_NS . 'PHOTO');
+$VCARD_FN = new Resource(VCARD_NS . 'FN');
+$VCARD_Suffix = new Resource(VCARD_NS . 'Suffix');
+$VCARD_CLASS = new Resource(VCARD_NS . 'CLASS');
+$VCARD_ADR = new Resource(VCARD_NS . 'ADR');
+$VCARD_Region = new Resource(VCARD_NS . 'Region');
+$VCARD_GEO = new Resource(VCARD_NS . 'GEO');
+$VCARD_Extadd = new Resource(VCARD_NS . 'Extadd');
+$VCARD_GROUP = new Resource(VCARD_NS . 'GROUP');
+$VCARD_EMAIL = new Resource(VCARD_NS . 'EMAIL');
+$VCARD_Family = new Resource(VCARD_NS . 'Family');
+$VCARD_TZ = new Resource(VCARD_NS . 'TZ');
+$VCARD_NAME = new Resource(VCARD_NS . 'NAME');
+$VCARD_Orgunit = new Resource(VCARD_NS . 'Orgunit');
+$VCARD_Country = new Resource(VCARD_NS . 'Country');
+$VCARD_SOUND = new Resource(VCARD_NS . 'SOUND');
+$VCARD_TITLE = new Resource(VCARD_NS . 'TITLE');
+$VCARD_MAILER = new Resource(VCARD_NS . 'MAILER');
+$VCARD_Other = new Resource(VCARD_NS . 'Other');
+$VCARD_Locality = new Resource(VCARD_NS . 'Locality');
+$VCARD_Pobox = new Resource(VCARD_NS . 'Pobox');
+$VCARD_KEY = new Resource(VCARD_NS . 'KEY');
+$VCARD_PRODID = new Resource(VCARD_NS . 'PRODID');
+$VCARD_Given = new Resource(VCARD_NS . 'Given');
+$VCARD_LABEL = new Resource(VCARD_NS . 'LABEL');
+$VCARD_TEL = new Resource(VCARD_NS . 'TEL');
+$VCARD_NICKNAME = new Resource(VCARD_NS . 'NICKNAME');
+$VCARD_ROLE = new Resource(VCARD_NS . 'ROLE');
+
+?>
Index: /Dev/trunk/rdfapi/vocabulary/VCARD_C.php
===================================================================
--- /Dev/trunk/rdfapi/vocabulary/VCARD_C.php	(revision 12)
+++ /Dev/trunk/rdfapi/vocabulary/VCARD_C.php	(revision 12)
@@ -0,0 +1,301 @@
+<?php
+/**
+*   vCard profile defined by RFC 2426 - Vocabulary (Resource)
+*
+*   @version $Id: VCARD_C.php 431 2007-05-01 15:49:19Z cweiske $
+*   @author Daniel Westphal (dawe@gmx.de)
+*   @package vocabulary
+*
+*   Wrapper, defining resources for all terms of the
+*   vCard Vocabulary.
+*   For details about vCard see: http://www.w3.org/TR/vcard-rdf .
+*   Using the wrapper allows you to define all aspects of
+*   the vocabulary in one spot, simplifing implementation and
+*   maintainence.
+*/
+class VCARD{
+
+	// VCARD concepts
+	function UID()
+	{
+		return  new Resource(VCARD_NS.'UID');
+
+	}
+
+	function ORGPROPERTIES()
+	{
+		return  new Resource(VCARD_NS . 'ORGPROPERTIES');
+
+	}
+
+	function ADRTYPES()
+	{
+		return  new Resource(VCARD_NS . 'ADRTYPES');
+
+	}
+
+	function NPROPERTIES()
+	{
+		return  new Resource(VCARD_NS . 'NPROPERTIES');
+
+	}
+
+	function EMAILTYPES()
+	{
+		return  new Resource(VCARD_NS . 'EMAILTYPES');
+
+	}
+
+	function TELTYPES()
+	{
+		return  new Resource(VCARD_NS . 'TELTYPES');
+
+	}
+
+	function ADRPROPERTIES()
+	{
+		return  new Resource(VCARD_NS . 'ADRPROPERTIES');
+
+	}
+
+	function TZTYPES()
+	{
+		return  new Resource(VCARD_NS . 'TZTYPES');
+
+	}
+
+	function STREET()
+	{
+		return  new Resource(VCARD_NS . 'Street');
+
+	}
+
+	function AGENT()
+	{
+		return  new Resource(VCARD_NS . 'AGENT');
+
+	}
+
+	function SOURCE()
+	{
+		return  new Resource(VCARD_NS . 'SOURCE');
+
+	}
+
+	function BDAY()
+	{
+		return  new Resource(VCARD_NS . 'BDAY');
+
+	}
+
+	function REV()
+	{
+		return  new Resource(VCARD_NS . 'REV');
+
+	}
+
+	function SORT_STRING()
+	{
+		return  new Resource(VCARD_NS . 'SORT_STRING');
+
+	}
+
+	function ORGNAME()
+	{
+		return  new Resource(VCARD_NS . 'Orgname');
+
+	}
+
+	function CATEGORIES()
+	{
+		return  new Resource(VCARD_NS . 'CATEGORIES');
+
+	}
+
+	function N()
+	{
+		return  new Resource(VCARD_NS . 'N');
+
+	}
+
+	function PCODE()
+	{
+		return  new Resource(VCARD_NS . 'Pcode');
+
+	}
+
+	function PREFIX()
+	{
+		return  new Resource(VCARD_NS . 'Prefix');
+
+	}
+
+	function PHOTO()
+	{
+		return  new Resource(VCARD_NS . 'PHOTO');
+
+	}
+
+	function FN()
+	{
+		return  new Resource(VCARD_NS . 'FN');
+
+	}
+
+	function SUFFIX()
+	{
+		return  new Resource(VCARD_NS . 'Suffix');
+
+	}
+
+	function VCARD_CLASS()
+	{
+		return  new Resource(VCARD_NS . 'CLASS');
+
+	}
+
+	function ADR()
+	{
+		return  new Resource(VCARD_NS . 'ADR');
+
+	}
+
+	function REGION()
+	{
+		return  new Resource(VCARD_NS . 'Region');
+
+	}
+
+	function GEO()
+	{
+		return  new Resource(VCARD_NS . 'GEO');
+
+	}
+
+	function EXTADD()
+	{
+		return  new Resource(VCARD_NS . 'Extadd');
+
+	}
+
+	function GROUP()
+	{
+		return  new Resource(VCARD_NS . 'GROUP');
+
+	}
+
+	function EMAIL()
+	{
+		return  new Resource(VCARD_NS . 'EMAIL');
+
+	}
+
+	function FAMILY()
+	{
+		return  new Resource(VCARD_NS . 'Family');
+
+	}
+
+	function TZ()
+	{
+		return  new Resource(VCARD_NS . 'TZ');
+
+	}
+
+	function NAME()
+	{
+		return  new Resource(VCARD_NS . 'NAME');
+
+	}
+
+	function ORGUNIT()
+	{
+		return  new Resource(VCARD_NS . 'Orgunit');
+
+	}
+
+	function COUNTRY()
+	{
+		return  new Resource(VCARD_NS . 'Country');
+
+	}
+
+	function SOUND()
+	{
+		return  new Resource(VCARD_NS . 'SOUND');
+
+	}
+
+	function TITLE()
+	{
+		return  new Resource(VCARD_NS . 'TITLE');
+
+	}
+
+	function MAILER()
+	{
+		return  new Resource(VCARD_NS . 'MAILER');
+
+	}
+
+	function OTHER()
+	{
+		return  new Resource(VCARD_NS . 'Other');
+
+	}
+
+	function LOCALITY()
+	{
+		return  new Resource(VCARD_NS . 'Locality');
+
+	}
+
+	function POBOX()
+	{
+		return  new Resource(VCARD_NS . 'Pobox');
+
+	}
+
+	function KEY()
+	{
+		return  new Resource(VCARD_NS . 'KEY');
+
+	}
+
+	function PRODID()
+	{
+		return  new Resource(VCARD_NS . 'PRODID');
+
+	}
+
+	function GIVEN()
+	{
+		return  new Resource(VCARD_NS . 'Given');
+
+	}
+
+	function LABEL()
+	{
+		return  new Resource(VCARD_NS . 'LABEL');
+
+	}
+
+	function TEL()
+	{
+		return  new Resource(VCARD_NS . 'TEL');
+
+	}
+
+	function NICKNAME()
+	{
+		return  new Resource(VCARD_NS . 'NICKNAME');
+
+	}
+
+	function ROLE()
+	{
+		return  new Resource(VCARD_NS . 'ROLE');
+	}
+}
+
+?>
Index: /Dev/trunk/rdfapi/vocabulary/VCARD_RES.php
===================================================================
--- /Dev/trunk/rdfapi/vocabulary/VCARD_RES.php	(revision 12)
+++ /Dev/trunk/rdfapi/vocabulary/VCARD_RES.php	(revision 12)
@@ -0,0 +1,302 @@
+<?php
+/**
+*   vCard profile defined by RFC 2426 - Vocabulary (ResResource)
+*
+*   @version $Id: VCARD_RES.php 431 2007-05-01 15:49:19Z cweiske $
+*   @author Daniel Westphal (dawe@gmx.de)
+*   @package vocabulary
+*
+*   Wrapper, defining resources for all terms of the
+*   vCard Vocabulary.
+*   For details about vCard see: http://www.w3.org/TR/vcard-rdf .
+*   Using the wrapper allows you to define all aspects of
+*   the vocabulary in one spot, simplifing implementation and
+*   maintainence.
+*/
+class VCARD_RES{
+
+	// VCARD concepts
+	function UID()
+	{
+		return  new ResResource(VCARD_NS.'UID');
+
+	}
+
+	function ORGPROPERTIES()
+	{
+		return  new ResResource(VCARD_NS . 'ORGPROPERTIES');
+
+	}
+
+	function ADRTYPES()
+	{
+		return  new ResResource(VCARD_NS . 'ADRTYPES');
+
+	}
+
+	function NPROPERTIES()
+	{
+		return  new ResResource(VCARD_NS . 'NPROPERTIES');
+
+	}
+
+	function EMAILTYPES()
+	{
+		return  new ResResource(VCARD_NS . 'EMAILTYPES');
+
+	}
+
+	function TELTYPES()
+	{
+		return  new ResResource(VCARD_NS . 'TELTYPES');
+
+	}
+
+	function ADRPROPERTIES()
+	{
+		return  new ResResource(VCARD_NS . 'ADRPROPERTIES');
+
+	}
+
+	function TZTYPES()
+	{
+		return  new ResResource(VCARD_NS . 'TZTYPES');
+
+	}
+
+	function STREET()
+	{
+		return  new ResResource(VCARD_NS . 'Street');
+
+	}
+
+	function AGENT()
+	{
+		return  new ResResource(VCARD_NS . 'AGENT');
+
+	}
+
+	function SOURCE()
+	{
+		return  new ResResource(VCARD_NS . 'SOURCE');
+
+	}
+
+	function BDAY()
+	{
+		return  new ResResource(VCARD_NS . 'BDAY');
+
+	}
+
+	function REV()
+	{
+		return  new ResResource(VCARD_NS . 'REV');
+
+	}
+
+	function SORT_STRING()
+	{
+		return  new ResResource(VCARD_NS . 'SORT_STRING');
+
+	}
+
+	function ORGNAME()
+	{
+		return  new ResResource(VCARD_NS . 'Orgname');
+
+	}
+
+	function CATEGORIES()
+	{
+		return  new ResResource(VCARD_NS . 'CATEGORIES');
+
+	}
+
+	function N()
+	{
+		return  new ResResource(VCARD_NS . 'N');
+
+	}
+
+	function PCODE()
+	{
+		return  new ResResource(VCARD_NS . 'Pcode');
+
+	}
+
+	function PREFIX()
+	{
+		return  new ResResource(VCARD_NS . 'Prefix');
+
+	}
+
+	function PHOTO()
+	{
+		return  new ResResource(VCARD_NS . 'PHOTO');
+
+	}
+
+	function FN()
+	{
+		return  new ResResource(VCARD_NS . 'FN');
+
+	}
+
+	function SUFFIX()
+	{
+		return  new ResResource(VCARD_NS . 'Suffix');
+
+	}
+
+	function VCARD_CLASS()
+	{
+		return  new ResResource(VCARD_NS . 'CLASS');
+
+	}
+
+	function ADR()
+	{
+		return  new ResResource(VCARD_NS . 'ADR');
+
+	}
+
+	function REGION()
+	{
+		return  new ResResource(VCARD_NS . 'Region');
+
+	}
+
+	function GEO()
+	{
+		return  new ResResource(VCARD_NS . 'GEO');
+
+	}
+
+	function EXTADD()
+	{
+		return  new ResResource(VCARD_NS . 'Extadd');
+
+	}
+
+	function GROUP()
+	{
+		return  new ResResource(VCARD_NS . 'GROUP');
+
+	}
+
+	function EMAIL()
+	{
+		return  new ResResource(VCARD_NS . 'EMAIL');
+
+	}
+
+	function FAMILY()
+	{
+		return  new ResResource(VCARD_NS . 'Family');
+
+	}
+
+	function TZ()
+	{
+		return  new ResResource(VCARD_NS . 'TZ');
+
+	}
+
+	function NAME()
+	{
+		return  new ResResource(VCARD_NS . 'NAME');
+
+	}
+
+	function ORGUNIT()
+	{
+		return  new ResResource(VCARD_NS . 'Orgunit');
+
+	}
+
+	function COUNTRY()
+	{
+		return  new ResResource(VCARD_NS . 'Country');
+
+	}
+
+	function SOUND()
+	{
+		return  new ResResource(VCARD_NS . 'SOUND');
+
+	}
+
+	function TITLE()
+	{
+		return  new ResResource(VCARD_NS . 'TITLE');
+
+	}
+
+	function MAILER()
+	{
+		return  new ResResource(VCARD_NS . 'MAILER');
+
+	}
+
+	function OTHER()
+	{
+		return  new ResResource(VCARD_NS . 'Other');
+
+	}
+
+	function LOCALITY()
+	{
+		return  new ResResource(VCARD_NS . 'Locality');
+
+	}
+
+	function POBOX()
+	{
+		return  new ResResource(VCARD_NS . 'Pobox');
+
+	}
+
+	function KEY()
+	{
+		return  new ResResource(VCARD_NS . 'KEY');
+
+	}
+
+	function PRODID()
+	{
+		return  new ResResource(VCARD_NS . 'PRODID');
+
+	}
+
+	function GIVEN()
+	{
+		return  new ResResource(VCARD_NS . 'Given');
+
+	}
+
+	function LABEL()
+	{
+		return  new ResResource(VCARD_NS . 'LABEL');
+
+	}
+
+	function TEL()
+	{
+		return  new ResResource(VCARD_NS . 'TEL');
+
+	}
+
+	function NICKNAME()
+	{
+		return  new ResResource(VCARD_NS . 'NICKNAME');
+
+	}
+
+	function ROLE()
+	{
+		return  new ResResource(VCARD_NS . 'ROLE');
+	}
+
+}
+
+?>
Index: /Dev/trunk/rdfapi/vocabulary/Vocabulary.php
===================================================================
--- /Dev/trunk/rdfapi/vocabulary/Vocabulary.php	(revision 12)
+++ /Dev/trunk/rdfapi/vocabulary/Vocabulary.php	(revision 12)
@@ -0,0 +1,19 @@
+<?php
+/**
+*   Vocabulary
+*
+*   @version $Id: Vocabulary.php 431 2007-05-01 15:49:19Z cweiske $
+*   @author Tobias GauÃ <tobias.gauss@web.de>
+*   @package vocabulary
+*
+*/
+
+// Include vocabularies
+require_once RDFAPI_INCLUDE_DIR . 'vocabulary/RDF.php';
+require_once RDFAPI_INCLUDE_DIR . 'vocabulary/RDFS.php';
+require_once RDFAPI_INCLUDE_DIR . 'vocabulary/OWL.php';
+require_once RDFAPI_INCLUDE_DIR . 'vocabulary/DC.php';
+require_once RDFAPI_INCLUDE_DIR . 'vocabulary/VCARD.php';
+require_once RDFAPI_INCLUDE_DIR . 'vocabulary/FOAF.php';
+require_once RDFAPI_INCLUDE_DIR . 'vocabulary/RSS.php';
+?>
Index: /Dev/trunk/rdfapi/vocabulary/VocabularyClass.php
===================================================================
--- /Dev/trunk/rdfapi/vocabulary/VocabularyClass.php	(revision 12)
+++ /Dev/trunk/rdfapi/vocabulary/VocabularyClass.php	(revision 12)
@@ -0,0 +1,20 @@
+<?php
+/**
+*   Vocabulary
+*
+*   @version $Id: VocabularyClass.php 431 2007-05-01 15:49:19Z cweiske $
+*   @author Tobias GauÃ <tobias.gauss@web.de>
+*   @package vocabulary
+*
+*/
+
+// Include vocabularies
+require_once RDFAPI_INCLUDE_DIR . 'vocabulary/ATOM_C.php';
+require_once RDFAPI_INCLUDE_DIR . 'vocabulary/RDF_C.php';
+require_once RDFAPI_INCLUDE_DIR . 'vocabulary/RDFS_C.php';
+require_once RDFAPI_INCLUDE_DIR . 'vocabulary/OWL_C.php';
+require_once RDFAPI_INCLUDE_DIR . 'vocabulary/DC_C.php';
+require_once RDFAPI_INCLUDE_DIR . 'vocabulary/VCARD_C.php';
+require_once RDFAPI_INCLUDE_DIR . 'vocabulary/FOAF_C.php';
+require_once RDFAPI_INCLUDE_DIR . 'vocabulary/RSS_C.php';
+?>
Index: /Dev/trunk/rdfapi/vocabulary/VocabularyRes.php
===================================================================
--- /Dev/trunk/rdfapi/vocabulary/VocabularyRes.php	(revision 12)
+++ /Dev/trunk/rdfapi/vocabulary/VocabularyRes.php	(revision 12)
@@ -0,0 +1,21 @@
+<?php
+/**
+*   Vocabulary
+*
+*   @version $Id: VocabularyRes.php 431 2007-05-01 15:49:19Z cweiske $
+*   @author Tobias GauÃ <tobias.gauss@web.de>
+*   @package vocabulary
+*
+*/
+
+// Include vocabularies
+include_once RDFAPI_INCLUDE_DIR . PACKAGE_RESMODEL);
+require_once RDFAPI_INCLUDE_DIR . 'vocabulary/ATOM_RES.php';
+require_once RDFAPI_INCLUDE_DIR . 'vocabulary/RDF_RES.php';
+require_once RDFAPI_INCLUDE_DIR . 'vocabulary/RDFS_RES.php';
+require_once RDFAPI_INCLUDE_DIR . 'vocabulary/OWL_RES.php';
+require_once RDFAPI_INCLUDE_DIR . 'vocabulary/DC_RES.php';
+require_once RDFAPI_INCLUDE_DIR . 'vocabulary/VCARD_RES.php';
+require_once RDFAPI_INCLUDE_DIR . 'vocabulary/FOAF_RES.php';
+require_once RDFAPI_INCLUDE_DIR . 'vocabulary/RSS_RES.php';
+?>
Index: /Dev/trunk/submitsurvey.php
===================================================================
--- /Dev/trunk/submitsurvey.php	(revision 12)
+++ /Dev/trunk/submitsurvey.php	(revision 12)
@@ -0,0 +1,38 @@
+<?php require 'classes/master.php';
+
+
+$surveyRDFWriter = new SurveyRDFWriter();
+
+$sTitle = $_POST['surveyTitle'];
+
+$surveyRDFWriter->createSurvey($sTitle,$_POST['surveyDescription']);
+
+$done = $surveyRDFWriter->saveSurvey($sTitle);
+
+echo 'Done';
+
+$surveyDRFReader = new SurveyRDFReader();
+
+$surveyDRFReader->loadSurvey($sTitle);
+
+$result = $surveyDRFReader->readSurveyTitle();
+
+foreach($result as $line){
+  $value = $line['?surveyTitle'];
+    if($value != "")
+      echo $value->toString()."<br/>";
+    else
+      echo "undbound<br/>";
+}
+
+$result2 = $surveyDRFReader->readSurveyDescription();
+
+foreach($result2 as $line){
+  $value = $line['?surveyDescription'];
+    if($value != "")
+      echo $value->toString()."<br/>";
+    else
+      echo "undbound<br/>";
+}
+
+?>
