Initial revision
authorchriskl <chriskl>
Mon, 11 Feb 2002 09:32:47 +0000 (09:32 +0000)
committerchriskl <chriskl>
Mon, 11 Feb 2002 09:32:47 +0000 (09:32 +0000)
62 files changed:
classes/database/ADODB_base.php [new file with mode: 0644]
classes/database/BaseDB.php [new file with mode: 0644]
classes/database/Postgres.php [new file with mode: 0755]
classes/database/Postgres71.php [new file with mode: 0644]
conf/config.inc [new file with mode: 0644]
lang/english.php [new file with mode: 0755]
lang/template.php [new file with mode: 0644]
libraries/adodb/adodb-access.inc.php [new file with mode: 0755]
libraries/adodb/adodb-ado.inc.php [new file with mode: 0755]
libraries/adodb/adodb-ado_access.inc.php [new file with mode: 0755]
libraries/adodb/adodb-ado_mssql.inc.php [new file with mode: 0755]
libraries/adodb/adodb-cryptsession.php [new file with mode: 0755]
libraries/adodb/adodb-csv.inc.php [new file with mode: 0755]
libraries/adodb/adodb-db2.inc.php [new file with mode: 0755]
libraries/adodb/adodb-errorhandler.inc.php [new file with mode: 0755]
libraries/adodb/adodb-errorpear.inc.php [new file with mode: 0755]
libraries/adodb/adodb-fbsql.inc.php [new file with mode: 0755]
libraries/adodb/adodb-ibase.inc.php [new file with mode: 0755]
libraries/adodb/adodb-mssql.inc.php [new file with mode: 0755]
libraries/adodb/adodb-mysql.inc.php [new file with mode: 0755]
libraries/adodb/adodb-mysqlt.inc.php [new file with mode: 0755]
libraries/adodb/adodb-oci8.inc.php [new file with mode: 0755]
libraries/adodb/adodb-odbc.inc.php [new file with mode: 0755]
libraries/adodb/adodb-odbc_mssql.inc.php [new file with mode: 0755]
libraries/adodb/adodb-odbc_oracle.inc.php [new file with mode: 0755]
libraries/adodb/adodb-oracle.inc.php [new file with mode: 0755]
libraries/adodb/adodb-pear.inc.php [new file with mode: 0755]
libraries/adodb/adodb-postgres.inc.php [new file with mode: 0755]
libraries/adodb/adodb-postgres7.inc.php [new file with mode: 0755]
libraries/adodb/adodb-proxy.inc.php [new file with mode: 0755]
libraries/adodb/adodb-session.php [new file with mode: 0755]
libraries/adodb/adodb-sybase.inc.php [new file with mode: 0755]
libraries/adodb/adodb-vfp.inc.php [new file with mode: 0755]
libraries/adodb/adodb.gif [new file with mode: 0755]
libraries/adodb/adodb.inc.php [new file with mode: 0755]
libraries/adodb/adodb.png [new file with mode: 0755]
libraries/adodb/benchmark.php [new file with mode: 0755]
libraries/adodb/client.php [new file with mode: 0755]
libraries/adodb/crypt.inc.php [new file with mode: 0755]
libraries/adodb/license.txt [new file with mode: 0755]
libraries/adodb/readme.htm [new file with mode: 0755]
libraries/adodb/readme.txt [new file with mode: 0755]
libraries/adodb/server.php [new file with mode: 0755]
libraries/adodb/test.php [new file with mode: 0755]
libraries/adodb/test2.php [new file with mode: 0755]
libraries/adodb/test3.php [new file with mode: 0755]
libraries/adodb/test4.php [new file with mode: 0755]
libraries/adodb/test5.php [new file with mode: 0755]
libraries/adodb/testcache.php [new file with mode: 0755]
libraries/adodb/testdatabases.inc.php [new file with mode: 0755]
libraries/adodb/testoci8.php [new file with mode: 0755]
libraries/adodb/testpaging.php [new file with mode: 0755]
libraries/adodb/testpear.php [new file with mode: 0755]
libraries/adodb/testsessions.php [new file with mode: 0755]
libraries/adodb/tohtml.inc.php [new file with mode: 0755]
libraries/adodb/tute.htm [new file with mode: 0755]
public_html/browser.php [new file with mode: 0644]
public_html/databases.php [new file with mode: 0755]
public_html/index.php [new file with mode: 0755]
public_html/intro.php [new file with mode: 0755]
public_html/login.php [new file with mode: 0755]
public_html/topbar.php [new file with mode: 0755]

diff --git a/classes/database/ADODB_base.php b/classes/database/ADODB_base.php
new file mode 100644 (file)
index 0000000..1fb1a22
--- /dev/null
@@ -0,0 +1,298 @@
+<?php
+
+/*
+ * Parent class of all ADODB objects.
+ *
+ * $Id: ADODB_base.php,v 1.1 2002/02/11 09:32:47 chriskl Exp $
+ */
+
+include_once('../libraries/adodb/adodb-errorhandler.inc.php');
+include_once('../libraries/adodb/adodb.inc.php');
+
+class ADODB_base {
+
+       var $conn;
+
+       /**
+        * Base constructor
+        * @param $fetchMode Defaults to associative.  Override for different behaviour
+        */
+       function ADODB_base($type, $fetchMode = ADODB_FETCH_ASSOC) {
+               $this->conn->databaseType = $type;
+               $this->conn = &ADONewConnection($type);
+               $this->conn->setFetchMode($fetchMode);
+       }
+
+       /**
+        * Cleans (escapes) a string
+        * @param $str The string to clean, by reference
+        * @return The cleaned string
+        */
+       function clean(&$str) {
+               $str = addslashes($str);
+               return $str;
+       }
+
+       /**
+        * Retrieves a ResultSet from a query
+        * @param $sql The SQL statement to be executed
+        * @return A recordset
+        */
+       function selectSet($sql) {
+               // Execute the statement
+               $rs = $this->conn->Execute($sql);
+
+               // If failure, return error value
+               if (!$rs) return $this->conn->ErrorNo();
+
+               return $rs;
+       }
+
+       /**
+        * Retrieves a single value from a query
+        *
+        * @@ assumes that the query will return only one row - returns field value in the first row
+        *
+        * @param $sql The SQL statement to be executed
+        * @param $field The field name to be returned
+        * @return A single field value
+        * @return -1 No rows were found
+        */
+       function selectField($sql, $field) {
+               // Execute the statement
+               $rs = $this->conn->Execute($sql);
+
+               // If failure, or no rows returned, return error value
+               if (!$rs) return $this->conn->ErrorNo();
+               elseif ($rs->RecordCount() == 0) return -1;
+
+               return $rs->f[$field];
+       }
+
+       /**
+        * Delete from the database
+        * @param $table The name of the table
+        * @param $conditions (array) A map of field names to conditions
+        * @return 0 success
+        * @return -1 on referential integrity violation
+        * @return -2 on no rows deleted
+        */
+       function delete($table, $conditions) {
+               $this->clean($table);
+
+               reset($conditions);
+
+               // Build clause
+               $sql = '';
+               while(list($key, $value) = each($conditions)) {
+                       $this->clean($key);
+                       $this->clean($value);
+                       if ($sql) $sql .= " AND {$key}='{$value}'";
+                       else $sql = "DELETE FROM {$table} WHERE {$key}='{$value}'";
+               }
+
+               // Check for failures
+               if (!$this->conn->Execute($sql)) {
+                       // Check for referential integrity failure
+                       if (stristr($this->conn->ErrorMsg(), 'referential'))
+                               return -1;
+               }
+
+               // Check for no rows modified
+               if ($this->conn->Affected_Rows() == 0) return -2;
+
+               return $this->conn->ErrorNo();
+       }
+
+       /**
+        * Insert a set of values into the database
+        * @param $table The table to insert into
+        * @param $vars (array) A mapping of the field names to the values to be inserted
+        * @return 0 success
+        * @return -1 if a unique constraint is violated
+        * @return -2 if a referential constraint is violated
+        */
+       function insert($table, $vars) {
+               $this->clean($table);
+
+               reset($vars);
+
+               // Build clause
+               $fields = '';
+               $values = '';
+               while(list($key, $value) = each($vars)) {
+                       $this->clean($key);
+                       $this->clean($value);
+
+                       if ($fields) $fields .= ", {$key}";
+                       else $fields = "INSERT INTO {$table} ({$key}";
+
+                       if ($values) $values .= ", '{$value}'";
+                       else $values = ") VALUES ('{$value}'";
+               }
+
+               // Check for failures
+               if (!$this->conn->Execute($fields . $values . ')')) {
+                       // Check for unique constraint failure
+                       if (stristr($this->conn->ErrorMsg(), 'unique'))
+                               return -1;
+                       // Check for referential integrity failure
+                       elseif (stristr($this->conn->ErrorMsg(), 'referential'))
+                               return -2;
+               }
+
+               return $this->conn->ErrorNo();
+       }
+
+       /**
+        * Update a row in the database
+        * @param $table The table that is to be updated
+        * @param $vars (array) A mapping of the field names to the values to be updated
+        * @param $where (array) A mapping of field names to values for the where clause
+        * @param $nulls (array, optional) An array of fields to be set null
+        * @return 0 success
+        * @return -1 if a unique constraint is violated
+        * @return -2 if a referential constraint is violated
+        * @return -3 on no rows deleted
+        */
+       function update($table, $vars, $where, $nulls = array()) {
+               $this->clean($table);
+
+               $setClause = '';
+               $whereClause = '';
+
+               // Populate the syntax arrays
+               reset($vars);
+               while(list($key, $value) = each($vars)) {
+                       $this->clean($key);
+                       $this->clean($value);
+                       if ($setClause) $setClause .= ", {$key}='{$value}'";
+                       else $setClause = "UPDATE {$table} SET {$key}='{$value}'";
+               }
+
+               reset($nulls);
+               while(list(, $value) = each($nulls)) {
+                       $this->clean($value);
+                       if ($setClause) $setClause .= ", {$value}=NULL";
+                       else $setClause = "UPDATE {$table} SET {$value}=NULL";
+               }
+
+               reset($where);
+               while(list($key, $value) = each($where)) {
+                       $this->clean($key);
+                       $this->clean($value);
+                       if ($whereClause) $whereClause .= " AND {$key}='{$value}'";
+                       else $whereClause = " WHERE {$key}='{$value}'";
+               }
+
+               // Check for failures
+               if (!$this->conn->Execute($setClause . $whereClause)) {
+                       // Check for unique constraint failure
+                       if (stristr($this->conn->ErrorMsg(), 'unique'))
+                               return -1;
+                       // Check for referential integrity failure
+                       elseif (stristr($this->conn->ErrorMsg(), 'referential'))
+                               return -2;
+               }
+
+               // Check for no rows modified
+               if ($this->conn->Affected_Rows() == 0) return -3;
+
+               return $this->conn->ErrorNo();
+       }
+
+       /**
+        * Begin a transaction
+        * @return 0 success
+        */
+       function beginTransaction() {
+               return !$this->conn->BeginTrans();
+       }
+
+       /**
+        * End a transaction
+        * @return 0 success
+        */
+       function endTransaction() {
+               return !$this->conn->CommitTrans();
+       }
+
+       /**
+        * Roll back a transaction
+        * @return 0 success
+        */
+       function rollbackTransaction() {
+               return !$this->conn->RollbackTrans();
+       }
+
+       // Type conversion routines
+
+       /**
+        * Converts an array of identifiers into a bitset, given a bitset definition
+        * Duplicate flags are silently ignored.
+        * Note: This is not case insensitive.
+        * @param flags An array of identifiers
+        * @param allowed The definition of allowed identifiers, mapping identifier -> bit index
+        * @return A string representation of the bitset
+        */
+       function dbBitSet(&$flags, &$allowed) {
+               $bitset = (int)0;
+               for ($i = 0; $i < sizeof($flags); $i++) {
+                       if (isset($allowed[$flags[$i]])) {
+                               $bitset |= (1 << $allowed[$flags[$i]]);
+                       }
+               }
+
+               // Left-pad the bitset to match the database size
+               // Important!
+               $bitset = decbin($bitset);
+               $bitset = str_pad($bitset, sizeof($allowed), '0', STR_PAD_LEFT);
+
+               return 'b' . $bitset;
+       }
+
+       /** 
+        * Change an int from a database bitset field back into an array of identifiers
+        * @param $bitset The database bitset, in database format (B'10101')
+        * @param $allowed The definition of allowed identifiers, mapping identifier -> bit index
+        * @return An array of identifiers
+        */
+       function phpBitSet($bitset, &$allowed) {
+               // @@ NOTE: Should we be doing better error handling here?
+               // @@ This condition will catch both NULL values (correctly) and borked values (incorrectly)
+               if (!ereg("^[01]+$", $bitset)) return array();
+
+               $intset = bindec($bitset);
+
+               $temp = array();
+
+               reset($allowed);
+               while (list($k, $v) = each($allowed)) {
+                       if ($intset & (1 << $v)) $temp[] = $k;
+               }
+               return $temp;
+       }
+
+       /** 
+        * Change the value of a parameter to 't' or 'f' depending on whether it evaluates to true or false
+        * @param $parameter the parameter
+        */
+       function dbBool(&$parameter) {
+               if ($parameter) $parameter = 't';
+               else $parameter = 'f';
+
+               return $parameter;
+       }
+
+       /** 
+        * Change a parameter from 't' or 'f' to a boolean, (others evaluate to false)
+        * @param $parameter the parameter
+        */
+       function phpBool($parameter) {
+               $parameter = ($parameter == 't');
+               return $parameter;
+       }
+
+}
+
+?>
diff --git a/classes/database/BaseDB.php b/classes/database/BaseDB.php
new file mode 100644 (file)
index 0000000..c5722ab
--- /dev/null
@@ -0,0 +1,70 @@
+<?php\r
+\r
+/**\r
+ * A class that implements the DB interface for Postgres\r
+ * Note: This class uses ADODB and returns RecordSets.\r
+ *\r
+ * $Id: BaseDB.php,v 1.1 2002/02/11 09:32:47 chriskl Exp $\r
+ */\r
+\r
+include_once('../classes/database/ADODB_base.php');\r
+\r
+class BaseDB extends ADODB_base {\r
+\r
+       // Filter objects for user?\r
+       var $_filterTables = true;\r
+\r
+       function BaseDB($type) {\r
+               $this->ADODB_base($type);\r
+       }\r
+\r
+       /**\r
+        * Set object filtering for user\r
+        * @param $state (boolean)\r
+        */\r
+       function setFilterTables($state) {\r
+               $this->$_filterTables = $state;\r
+       }\r
+\r
+/*\r
+       // Feature functions\r
+\r
+       // Is "ALTER TABLE" with add column supported? \r
+       function supportsAlterTableWithAddColumn() {}\r
+       \r
+       // Is "ALTER TABLE" with drop column supported? \r
+       function supportsAlterTableWithDropColumn() \r
+\r
+       // Are both data definition and data manipulation statements within a transaction supported? \r
+       function supportsDataDefinitionAndDataManipulationTransactions() \r
+\r
+       // Are only data manipulation statements within a transaction supported? \r
+       function supportsDataManipulationTransactionsOnly() \r
+\r
+       // Does the database treat mixed case unquoted SQL identifiers as case sensitive and as a result store them in mixed case? A JDBC CompliantTM driver will always return false. \r
+       function supportsMixedCaseIdentifiers() \r
+\r
+       // Does the database treat mixed case quoted SQL identifiers as case sensitive and as a result store them in mixed case? A JDBC CompliantTM driver will always return true. \r
+       function supportsMixedCaseQuotedIdentifiers() \r
+\r
+       // Can columns be defined as non-nullable? A JDBC CompliantTM driver always returns true. \r
+       function supportsNonNullableColumns() \r
+\r
+       // Are stored procedure calls using the stored procedure escape syntax supported? \r
+       function supportsStoredProcedures() \r
+       \r
+       // Are transactions supported? If not, invoking the method commit is a noop and the isolation level is TRANSACTION_NONE. \r
+       function supportsTransactions() \r
+\r
+       // Can you define your own aggregates?\r
+       function supportsAggregates()\r
+\r
+       // Can you define your own operators?\r
+       function supportsOperators()\r
+\r
+       // Database manipulation\r
+\r
+*/\r
+}\r
+\r
+?>
\ No newline at end of file
diff --git a/classes/database/Postgres.php b/classes/database/Postgres.php
new file mode 100755 (executable)
index 0000000..db43021
--- /dev/null
@@ -0,0 +1,599 @@
+<?php\r
+\r
+/**\r
+ * A class that implements the DB interface for Postgres\r
+ * Note: This class uses ADODB and returns RecordSets.\r
+ *\r
+ * $Id: Postgres.php,v 1.1 2002/02/11 09:32:47 chriskl Exp $\r
+ */\r
+\r
+include_once('ADODB_base.pclass');\r
+\r
+class Postgres extends BaseDB {\r
+\r
+       function Postgres() {\r
+               $this->User = 'auadmin';\r
+               $this->Password = 'bfd12hutz';\r
+\r
+               $this->BaseDB();\r
+       }\r
+\r
+       // Flag functions\r
+\r
+       /**\r
+        * Retrieves the flags of the specified user\r
+        * @param $user_id The ID of the user\r
+        * @param $values (optional) Return array as values, rather than keys\r
+        * @return An array containing the flag names as it keys with values of true\r
+        */\r
+       function &getUserFlags($user_id, $values = false) {\r
+               $this->clean($meal_id);\r
+               $sql = "SELECT fl.name FROM users_flags uf, medidiets_flags fl WHERE uf.flag_id = fl.flag_id AND uf.user_id = '{$user_id}'";\r
+               $rs = $this->selectSet($sql);\r
+\r
+               $flags = array();\r
+               while (!$rs->EOF) {\r
+                       if ($values)\r
+                               $flags[] = $rs->f['name'];\r
+                       else\r
+                               $flags[$rs->f['name']] = true;\r
+                       $rs->moveNext();\r
+               }\r
+\r
+               return $flags;\r
+       }\r
+\r
+       /**\r
+        * Retrieves a user's profile and plan joined\r
+        * @param $user_id The ID of the user whose data is to be returned\r
+        * @return A recordset\r
+        */\r
+       function &getProfileAndPlan($user_id) {\r
+               $this->clean($user_id);\r
+\r
+               $sql = "SELECT * FROM users_profiles_tmp up, medidiets_plans mp WHERE up.user_id='$user_id' AND up.plan_id=mp.plan_id";\r
+\r
+               return $this->selectSet($sql);\r
+       }\r
+\r
+       // Plan functions\r
+\r
+       /**\r
+        * Returns all existing plans\r
+        * @return A recordset\r
+        */\r
+       function &getPlans() {\r
+               $sql = "SELECT * FROM medidiets_plans ORDER BY calories";\r
+               return $this->selectSet($sql);\r
+       }\r
+\r
+       /*\r
+        * Finds a meal plan that matches the given number of calories most closely\r
+        * @param $cals The number of calories the plan should be\r
+        * @return (array) The ID of the plan found, and the actual cals\r
+        */\r
+       function &findPlan($cals) {\r
+               $this->clean($cals);\r
+\r
+               $sql = "SELECT plan_id, calories, ABS(calories::numeric - '$cals') AS diff FROM medidiets_plans ORDER BY diff LIMIT 1";\r
+               $rs = $this->selectSet($sql);\r
+\r
+               return array($rs->f['plan_id'], $rs->f['calories']);\r
+       }\r
+\r
+       /*\r
+        * Finds all meals that adhere to the given options, randomly ordered\r
+        * @param $cals The number of calories the plan should be\r
+        * @param $when_id The meal of the day to find meals for\r
+        * @param $flags An array of flag names to be excluded\r
+        * @param $names (optional) Specify whether to return names as well, sorted\r
+        * @return A recordset\r
+        */\r
+       function &findMeals($cals, $when_id, $flags, $names = false) {\r
+               $this->clean($cals);\r
+               $this->clean($when_id);\r
+               $flag_str = implode("','", $flags);\r
+\r
+               if ($names) {\r
+                       $params = 'meal_id, name';\r
+                       $order = 'name';\r
+               }\r
+               else {\r
+                       $params = 'meal_id';\r
+                       $order = 'RANDOM()';\r
+               }\r
+\r
+               $sql = "\r
+                       SELECT \r
+                               {$params}\r
+                       FROM \r
+                               medidiets_meals mm\r
+                       WHERE \r
+                               mm.calories='{$cals}'\r
+                               AND mm.when_id='{$when_id}'\r
+                               AND mm.visible\r
+                               AND NOT mm.pending\r
+                               AND mm.meal_id NOT IN (\r
+                                       SELECT \r
+                                               DISTINCT (meal_id)\r
+                                       FROM \r
+                                               medidiets_flags_map mfp, medidiets_flags mf \r
+                                       WHERE\r
+                                               mfp.flag_id=mf.flag_id\r
+                                               AND mf.name IN ('{$flag_str}')\r
+                               )\r
+                       ORDER BY {$order}\r
+               ";\r
+\r
+               return $this->selectSet($sql);\r
+       }\r
+\r
+       /*\r
+        * Inserts meals into a range of dates for a user\r
+        * @param $user_id The ID of the user we're inserting for\r
+        * @param $start_date The date at which to start the insertion\r
+        * @param $no_days The number of days to insert\r
+        * @return 0 success\r
+        * @return -1 transaction error\r
+        * @return -2 profile/plan retrieval error\r
+        * @return -3 meal list retrieval error\r
+        * @return -4 insertion failure\r
+        * @@ What happens if no breakfasts could be found?!?!?\r
+        */\r
+       function createMealPlan($user_id, $start_date, $no_days)  {\r
+               global $defaultCountryCode;\r
+\r
+               // begin transaction\r
+               $status = $this->beginTransaction();\r
+               if ($status != 0) return -1;\r
+\r
+               // Get user data, joined with plan data?\r
+               $data = &$this->getProfileAndPlan($user_id);\r
+               $data->f['seasonal'] = $this->phpBool($data->f['seasonal']);\r
+               $flags = &$this->getUserFlags($user_id, true);\r
+               \r
+               // Seasonal menus\r
+               if ($data->f['seasonal']) {\r
+                       if ($defaultCountryCode == 'AU')\r
+                               $is_summer = in_array(date('m'), array(10, 11, 12, 1, 2, 3));\r
+                       else\r
+                               $is_summer = in_array(date('m'), array(4, 5, 6, 7, 8, 9));\r
+\r
+                       if ($is_summer) $flags[] = 'NOT_SUMMER';\r
+                       else $flags[] = 'NOT_WINTER';\r
+               }\r
+\r
+               // Convenience\r
+               $b_flags = $flags;\r
+               if ($data->f['mp_breakfast'] == 'C') $b_flags[] = 'NOT_CONVENIENT';\r
+               $l_flags = $flags;\r
+               if ($data->f['mp_lunch'] == 'C') $l_flags[] = 'NOT_CONVENIENT';\r
+               $d_flags = $flags;\r
+               if ($data->f['mp_dinner'] == 'C') $d_flags[] = 'NOT_CONVENIENT';\r
+\r
+               // Get lists of breakfasts, lunches, dinners and snacks, ordered\r
+               // randomly.\r
+               if ($data->f['breakfast'] > 0) {\r
+                       $breakfasts = &$this->findMeals($data->f['breakfast'], 1, $b_flags);\r
+                       if (!$breakfasts) {\r
+                               $this->rollbackTransaction();\r
+                               return -3;\r
+                       }\r
+                       if ($breakfasts->recordCount() == 0) reportError("User {$user_id} could not find a {$data->f['breakfast']} cal breakfast for " . \r
+                               implode(',', $b_flags) . " flags.");\r
+               }\r
+               if ($data->f['lunch'] > 0) {\r
+                       $lunches = &$this->findMeals($data->f['lunch'], 2, $l_flags);\r
+                       if (!$lunches) {\r
+                               $this->rollbackTransaction();\r
+                               return -3;\r
+                       }\r
+                       if ($lunches->recordCount() == 0) reportError("User {$user_id} could not find a {$data->f['lunch']} cal lunch for " . \r
+                               implode(',', $l_flags) . " flags.");\r
+               }\r
+               if ($data->f['dinner'] > 0) {\r
+                       $dinners = &$this->findMeals($data->f['dinner'], 3, $d_flags);\r
+                       if (!$dinners) {\r
+                               $this->rollbackTransaction();\r
+                               return -3;\r
+                       }\r
+                       if ($dinners->recordCount() == 0) reportError("User {$user_id} could not find a {$data->f['dinner']} cal dinner for " . \r
+                               implode(',', $d_flags) . " flags.");\r
+               }\r
+               if ($data->f['snack'] > 0) {\r
+                       $snacks = &$this->findMeals($data->f['snack'], 4, $flags);              \r
+                       if (!$snacks) {\r
+                               $this->rollbackTransaction();\r
+                               return -3;\r
+                       }\r
+                       if ($snacks->recordCount() == 0) reportError("User {$user_id} could not find a {$data->f['snack']} cal snack for " . \r
+                               implode(',', $flags) . " flags.");\r
+               }\r
+\r
+               // For each day, insert a breakfast, lunch, dinner and snack\r
+               list($sy, $sm, $sd) = explode('-', $start_date);\r
+               for ($i = 0; $i < $no_days; $i++) {\r
+                       $temp = array();\r
+                       $temp['user_id'] = $user_id;\r
+                       $temp['date'] = date('Y-m-d', mktime(0, 0, 0, $sm, $sd + $i, $sy));\r
+                       // Breakfast\r
+                       if ($data->f['breakfast'] > 0 && $breakfasts->recordCount() > 0) {\r
+                               $temp['breakfast_id'] = $breakfasts->f['meal_id'];\r
+                               $breakfasts->moveNext();\r
+                               if ($breakfasts->EOF) $breakfasts->moveFirst();\r
+                       }\r
+                       // Lunch\r
+                       if ($data->f['lunch'] > 0 && $lunches->recordCount() > 0) {\r
+                               $temp['lunch_id'] = $lunches->f['meal_id'];\r
+                               $lunches->moveNext();\r
+                               if ($lunches->EOF) $lunches->moveFirst();\r
+                  }\r
+                       // Dinner\r
+                       if ($data->f['dinner'] > 0 && $dinners->recordCount() > 0) {\r
+                               $temp['dinner_id'] = $dinners->f['meal_id'];\r
+                               $dinners->moveNext();\r
+                               if ($dinners->EOF) $dinners->moveFirst();\r
+                       }\r
+                       // Snack\r
+                       if ($data->f['snack'] > 0 && $snacks->recordCount() > 0) {\r
+                               $temp['snack_id'] = $snacks->f['meal_id'];\r
+                               $snacks->moveNext();\r
+                               if ($snacks->EOF) $snacks->moveFirst();\r
+                       }\r
+\r
+                       $status = $this->insert('users_mealplans', $temp);\r
+                       if ($status != 0) {\r
+                               $this->rollbackTransaction();\r
+                               return -4;\r
+                       }\r
+                       unset($temp);\r
+               }\r
+\r
+               // @@ Take care of overriding preferences\r
+\r
+               return $this->endTransaction();\r
+       }\r
+\r
+       /**\r
+        * Records a user's meal substitution to the database\r
+        * @param $user_id The ID of the user to be updated\r
+        * @param $date The date to update\r
+        * @param $when_id The meal to replace\r
+        * @param $meal_id The new meal to substitute\r
+        * @return 0 success\r
+        */\r
+       function setUserMeal($user_id, $date, $when_id, $meal_id) {\r
+               $fields = array('', 'breakfast_id', 'lunch_id', 'dinner_id', 'snack_id');\r
+               return $this->update('users_mealplans',\r
+                       array($fields[$when_id] => $meal_id),\r
+                       array('user_id' => $user_id, 'date' => $date));\r
+       }\r
+\r
+       /**\r
+        * Retrieves a user's shopping list\r
+        * @param $user_id The ID fo the user to retrieve\r
+        * @param $date The date from which to retrieve\r
+        * @param $num_days The number of days from the date forward to retrieve\r
+        */\r
+       function &getShoppingList($user_id, $from, $to) {\r
+               $this->clean($user_id);\r
+               $this->clean($date);\r
+\r
+               $sql = "\r
+                       SELECT description, food_id, name, measurement, base, type, name_pl, measurement_pl, qty, SUM(quantity) AS quantity FROM (\r
+                               (SELECT \r
+                                       mcf.description, mf.food_id, mf.name, mf.measurement, mf.base, mf.type, mf.name_pl, mf.measurement_pl, mf.quantity AS qty, mfm.quantity AS quantity \r
+                               FROM \r
+                                       medidiets_categories_foods mcf, medidiets_foods mf, medidiets_foods_map mfm, users_mealplans um \r
+                               WHERE \r
+                                       mcf.category_id=mf.category_id\r
+                                       AND mf.food_id=mfm.food_id \r
+                                       AND mfm.meal_id IN (um.breakfast_id, um.lunch_id, um.dinner_id, um.snack_id)\r
+                                       AND um.date BETWEEN '$from' AND '$to'\r
+                                       AND user_id='$user_id')\r
+                               UNION ALL\r
+                               (SELECT \r
+                                       mcf.description, mf.food_id, mf.name, mf.measurement, mf.base, mf.type, mf.name_pl, mf.measurement_pl, mf.quantity AS qty, mi.quantity AS quantity \r
+                               FROM \r
+                                       medidiets_categories_foods mcf, medidiets_foods mf, medidiets_ingredients mi, medidiets_recipes_map mrm, users_mealplans um \r
+                               WHERE \r
+                                       mcf.category_id=mf.category_id\r
+                                       AND mf.food_id=mi.food_id \r
+                                       AND mi.recipe_id=mrm.recipe_id \r
+                                       AND mrm.meal_id IN (um.breakfast_id, um.lunch_id, um.dinner_id, um.snack_id) \r
+                                       AND um.date BETWEEN '$from' AND '$to'\r
+                                       AND user_id='$user_id')\r
+                       ) AS subselect\r
+                       GROUP BY description, food_id, name, measurement, base, type, name_pl, measurement_pl, qty\r
+               ";\r
+\r
+          return $this->selectSet($sql);\r
+       }\r
+\r
+       // Miscellaneous functions\r
+\r
+       /*\r
+        * Returns an array with the correct imperial or metric units\r
+        * @return Array containing measurements\r
+        */\r
+       function getDefaultUnits() {\r
+               global $defaultMeasurements;\r
+\r
+               if ($defaultMeasurement == 'imperial') {\r
+                       $units = array('M' => 'oz', 'V' => 'fl.oz');\r
+               }\r
+               else {\r
+                       $units = array('M' => 'g', 'V' => 'mL');\r
+               }\r
+\r
+               return $units;\r
+       }\r
+\r
+       /*\r
+        * A helper function to convert decimals to fractions\r
+        * @param A decimal number to convert\r
+        * @return The formatted version of the number\r
+        */\r
+       function _fracConvert($num) {\r
+               $decpart = $num - floor($num);\r
+\r
+               switch ($decpart * 4) {\r
+                       case 0:\r
+                               return number_format($num, 0);\r
+                               break;\r
+                       case 1:\r
+                               if (floor($num) != 0)\r
+                                       return number_format(floor($num), 0) . ' 1/4';\r
+                               else\r
+                                       return '1/4';\r
+                               break;\r
+                       case 2:\r
+                               if (floor($num) != 0)\r
+                                       return number_format(floor($num), 0) . ' 1/2';\r
+                               else\r
+                                       return '1/2';\r
+                               break;\r
+                       case 3:\r
+                               if (floor($num) != 0)\r
+                                       return number_format(floor($num), 0) . ' 3/4';\r
+                               else\r
+                                       return '3/4';\r
+                               break;\r
+                       default:\r
+                               if ($decpart == 0.33) {\r
+                                       if (floor($num) != 0)\r
+                                               return number_format(floor($num), 0) . ' 1/3';\r
+                                       else\r
+                                               return '1/3';\r
+                               }\r
+                               elseif ($decpart == 0.66 || $decpart == 0.67) {\r
+                                       if (floor($num) != 0)\r
+                                               return number_format(floor($num), 0) . ' 2/3';\r
+                                       else\r
+                                               return '2/3';\r
+                               }\r
+                               else return number_format($num, 2);\r
+\r
+                               break;\r
+               }\r
+       }\r
+\r
+       /**\r
+        * Return the string to be used to as the display for the ingredient\r
+        *\r
+        * The string is to be formatted depending upon the values of the measurement\r
+        * and base variables.  The string will also use the $defaultMeasurement\r
+        * specified in the network config files.\r
+        *\r
+        * @param $name The name of the food of the ingredient\r
+        * @param $name The pluralised form of the name\r
+        * @param $quantity The amount of ingredient\r
+        * @param $measurement The measurement of the food of the ingredient ('' if none)\r
+        * @param $measurement The pluralised form of the measurement ('' if none)\r
+        * @param $base The base size of the food of the ingredient ('' if none)\r
+        * @param $type The base type of the food of the ingredient ('M' - mass, 'V' - volume)\r
+        * @param $show_qty (optional) If false, only gives the name, not the quantity\r
+        * @param $how How the ingredient is prepared.\r
+        *\r
+        */\r
+       function getIngredientDisplay($name, $name_pl, $quantity, $measurement, $measurement_pl, $base, $type, $how, $show_qty = true) {\r
+               global $defaultMeasurement;\r
+\r
+               // set display units depending on defaultMeasurement\r
+               $units = $this->getDefaultUnits();\r
+\r
+               // if quantity is an integer value show only the integer\r
+               if ($quantity == (int)$quantity) $quantity = (int)$quantity;\r
+\r
+               // discard fractional part of base size, cos who can measure half a gram?\r
+               if ($base != '') {\r
+                       $base = round($base);\r
+                       if ($base == 0) $base = 1;\r
+               }\r
+\r
+               if ($measurement != '' && $base != '') {\r
+                       // both measurement and base are set\r
+                       // eg. "2 1/2 375mL cans of Tomato Soup"\r
+                       $display_qty = $this->_fracConvert($quantity) . ' ';\r
+                       $display_nam = $base . $units[$type] . ' ';\r
+                       $display_nam .= ($quantity > 1) ? $measurement_pl : $measurement;\r
+                       $display_nam .= ' of ' . $name;\r
+               }\r
+               elseif ($measurement != '') {\r
+                       // measurement is set but base is not\r
+                       // eg. "4 2/3 slices of Bread"\r
+                       $display_qty = $this->_fracConvert($quantity) . ' ';\r
+                       $display_nam = ($quantity > 1) ? $measurement_pl : $measurement;\r
+                       $display_nam .= ' of ' . $name;\r
+               }\r
+               elseif ($base != '') {\r
+                       // base is set but measurement is not\r
+                       // eg. "500g of Beef"\r
+                       $display_qty = ceil($quantity * $base);\r
+                       $display_nam = $units[$type] . ' of ' . $name;\r
+               }\r
+               else {\r
+                       // neither measurement nor base is set\r
+                       // eg. "1 1/2 Apples"\r
+                       $display_qty = $this->_fracConvert($quantity) . ' ';\r
+                       $display_nam = ($quantity > 1) ? $name_pl : $name;\r
+               }\r
+               // Add 'crumbed', etc.\r
+               if ($how != '') $display_nam .= ", {$how}";\r
+\r
+               if ($show_qty)\r
+                       return $display_qty . $display_nam;\r
+               else\r
+                       return $display_nam;\r
+\r
+       }\r
+\r
+       // Meal Manipulation Functions\r
+\r
+       /**\r
+        * Retrieve the Nutritional Data for a Food associated with a given meal\r
+        * @param $meal_id The ID of the meal\r
+        * @param $food_id The ID of the food\r
+        * @return The set of nutritional data and food information\r
+        */\r
+       function &getMealFood($meal_id, $food_id) {\r
+               $this->clean($meal_id);\r
+               $this->clean($food_id);\r
+               $sql = "SELECT f.*, fm.* FROM medidiets_foods_map fm, medidiets_foods f WHERE fm.food_id = f.food_id AND fm.meal_id = '{$meal_id}' AND fm.food_id = '{$food_id}'";\r
+               return $this->selectSet($sql);\r
+       }\r
+\r
+       /**\r
+        * Retrieves all categories in the database, with all fields, sorted\r
+        * alphabetically.  This userland function excludes all categories with id's\r
+        * less than zero!\r
+        * @return A recordset\r
+        */\r
+       function &getRecipeCategories() {\r
+               $sql = "SELECT * FROM medidiets_categories_rec WHERE category_id >= 0 ORDER BY description";\r
+               return $this->selectSet($sql);\r
+       }\r
+\r
+       /**\r
+        * Retrieve the Nutritional Data for a Food associated with a given recipe\r
+        * @param $recipe_id The ID of the recipe\r
+        * @param $food_id The ID of the food\r
+        * @return The set of nutritional data and food information\r
+        */\r
+       function &getRecipeIngredient($recipe_id, $food_id) {\r
+               $this->clean($recipe_id);\r
+               $this->clean($food_id);\r
+               $sql = "SELECT f.*, fm.* FROM medidiets_ingredients fm, medidiets_foods f WHERE fm.food_id = f.food_id AND fm.recipe_id = '{$recipe_id}' AND fm.food_id = '{$food_id}'";\r
+               return $this->selectSet($sql);\r
+       }\r
+\r
+       /**\r
+        * Retrieve a particular recipe\r
+        * @param $recipe_id The ID of the recipe to retrieve\r
+        * @return a recordset\r
+        */\r
+       function &getRecipe($recipe_id) {\r
+               $this->clean($recipe_id);\r
+               $sql = "SELECT * FROM medidiets_recipes WHERE recipe_id='{$recipe_id}'";\r
+               return $this->selectSet($sql);\r
+       }\r
+\r
+       /**\r
+        * Retrieve all recipes in a particular category, sorted alphabetically\r
+        * This userland version of the function doesn't show magic recipes.\r
+        * @param $category_id The ID of the category in which to search\r
+        * @param $data A boolean switch to retrieve the nutritional data for the recipe (default false)\r
+        * @return a recordset\r
+        */\r
+       function &getRecipes($category_id, $data = false) {\r
+               $this->clean($category_id);\r
+               if ($data) {\r
+                       $sql = "SELECT * FROM\r
+                                                               medidiets_recipes r LEFT JOIN\r
+                                                               (SELECT i.recipe_id,\r
+                                                                       sum(i.quantity * f.calories) AS calories,\r
+                                                                       sum(i.quantity * f.kilojoules) AS kilojoules,\r
+                                                                       sum(i.quantity * f.protein) AS protein,\r
+                                                                       sum(i.quantity * f.fat) AS fat,\r
+                                                                       sum(i.quantity * f.saturated_fat) AS saturated_fat,\r
+                                                                       sum(i.quantity * f.carbohydrate) AS carbohydrate,\r
+                                                                       sum(i.quantity * f.sugar) AS sugar,\r
+                                                                       sum(i.quantity * f.fiber) AS fiber,\r
+                                                                       sum(i.quantity * f.cholesterol) AS cholesterol,\r
+                                                                       sum(i.quantity * f.sodium) AS sodium,\r
+                                                                       sum(i.quantity * f.potassium) AS potassium,\r
+                                                                       sum(i.quantity * f.calcium) AS calcium,\r
+                                                                       sum(i.quantity * f.iron) AS iron,\r
+                                                                       sum(i.quantity * f.zinc) AS zinc\r
+                                                               FROM\r
+                                                                       medidiets_ingredients i,\r
+                                                                       medidiets_foods f\r
+                                                               WHERE i.food_id = f.food_id\r
+                                                               GROUP BY i.recipe_id\r
+                                                               ) AS sub\r
+                                                       ON r.recipe_id = sub.recipe_id\r
+                                                       AND r.category_id = '{$category_id}'\r
+                                                       AND r.recipe_id >= 0\r
+                                                       ORDER BY r.name";\r
+               }\r
+               else {\r
+                       $sql = "SELECT * FROM medidiets_recipes WHERE category_id='{$category_id}' AND recipe_id >= 0 ORDER BY name";\r
+               }\r
+\r
+               return $this->selectSet($sql);\r
+       }\r
+\r
+       /**\r
+        * Retrieve the nutritional data for the specified recipe\r
+        * @param $recipe_id The ID of the recipe to retrieve\r
+        * @return a recordset\r
+        */\r
+       function &getRecipeData($recipe_id) {\r
+               $this->clean($recipe_id);\r
+               $sql = "SELECT * FROM\r
+                                                       medidiets_recipes r LEFT JOIN\r
+                                                       (SELECT i.recipe_id,\r
+                                                               sum(i.quantity * f.calories) AS total_calories,\r
+                                                               sum(i.quantity * f.kilojoules) AS total_kilojoules,\r
+                                                               sum(i.quantity * f.protein) AS total_protein,\r
+                                                               sum(i.quantity * f.fat) AS total_fat,\r
+                                                               sum(i.quantity * f.saturated_fat) AS total_saturated_fat,\r
+                                                               sum(i.quantity * f.carbohydrate) AS total_carbohydrate,\r
+                                                               sum(i.quantity * f.sugar) AS total_sugar,\r
+                                                               sum(i.quantity * f.fiber) AS total_fiber,\r
+                                                               sum(i.quantity * f.cholesterol) AS total_cholesterol,\r
+                                                               sum(i.quantity * f.sodium) AS total_sodium,\r
+                                                               sum(i.quantity * f.potassium) AS total_potassium,\r
+                                                               sum(i.quantity * f.calcium) AS total_calcium,\r
+                                                               sum(i.quantity * f.iron) AS total_iron,\r
+                                                               sum(i.quantity * f.zinc) AS total_zinc\r
+                                                       FROM\r
+                                                               medidiets_ingredients i,\r
+                                                               medidiets_foods f\r
+                                                       WHERE i.food_id = f.food_id\r
+                                                       GROUP BY i.recipe_id\r
+                                                       ) AS sub\r
+                                               ON r.recipe_id = sub.recipe_id\r
+                                               WHERE r.recipe_id = '{$recipe_id}'";\r
+               return $this->selectSet($sql);\r
+       }\r
+\r
+       /**\r
+        * Retrieve all ingredients for a recipe, sorted by their oid\r
+        * @param $recipe_id The ID of the recipe to which the ingredients are needed\r
+        * @return a recordset\r
+        */\r
+       function &getRecipeIngredients($recipe_id) {\r
+               $this->clean($recipe_id);\r
+               // @@ i.quantity must be after the f.* in the select until f.quantity removed...\r
+               $sql = "SELECT f.*, i.quantity, i.how FROM medidiets_foods f, medidiets_ingredients i\r
+                                               WHERE f.food_id = i.food_id\r
+                                               AND i.recipe_id = '{$recipe_id}'\r
+                                               ORDER BY i.oid";\r
+\r
+               return $this->selectSet($sql);\r
+       }\r
+\r
+}\r
+\r
+?>
\ No newline at end of file
diff --git a/classes/database/Postgres71.php b/classes/database/Postgres71.php
new file mode 100644 (file)
index 0000000..34239d7
--- /dev/null
@@ -0,0 +1,428 @@
+<?php\r
+\r
+/**\r
+ * A class that implements the DB interface for Postgres\r
+ * Note: This class uses ADODB and returns RecordSets.\r
+ *\r
+ * $Id: Postgres71.php,v 1.1 2002/02/11 09:32:48 chriskl Exp $\r
+ */\r
+\r
+// @@@ THOUGHT: What about inherits? ie. use of ONLY???\r
+\r
+include_once('../classes/database/BaseDB.php');\r
+\r
+class Postgres71 extends BaseDB {\r
+\r
+       function Postgres71($host, $port, $database, $user, $password) {\r
+               $this->BaseDB('postgres7');\r
+\r
+//             $this->conn->host = $host;\r
+               //$this->Port = $port;\r
+\r
+               $this->conn->connect($host, $user, $password, $database);\r
+       }\r
+\r
+       /**\r
+        * Return all database available on the server\r
+        * @return A list of databases, sorted alphabetically\r
+        */\r
+       function &getDatabases() {\r
+               $sql = "SELECT pdb.datname, pdb.datistemplate, pde.description FROM \r
+                                       pg_database pdb LEFT JOIN pg_description pde ON pdb.oid=pde.objoid\r
+                                       ORDER BY pdb.datname";\r
+               return $this->selectSet($sql);\r
+       }\r
+\r
+       /**\r
+        * Return all information about a particular database\r
+        * @param $database The name of the database to retrieve\r
+        * @return The database info\r
+        */\r
+       function &getDatabase($database) {\r
+               $this->clean($database);\r
+               $sql = "SELECT * FROM pg_database WHERE datname='{$database}'";\r
+               return $this->selectRow($sql);\r
+       }\r
+\r
+       /**\r
+        * Drops a database\r
+        * @param $database The name of the database to retrieve\r
+        * @return 0 success\r
+        */\r
+       function dropDatabase($database) {\r
+               $this->clean($database);\r
+               $sql = "DROP DATABASE \"{$database}\"";\r
+       }\r
+\r
+       // Table functions\r
+\r
+       /**\r
+        * Return all tables in current database\r
+        * @return All tables, sorted alphabetically \r
+        */\r
+       function &getTables() {\r
+               $sql = "SELECT * FROM pg_class ORDER BY relname";\r
+               return $this->selectSet($sql);\r
+       }\r
+\r
+       /**\r
+        * Return all information relating to a table\r
+        * @param $table The name of the table\r
+        * @return Table information\r
+        */\r
+       function &getTableByName($table) {\r
+               $this->clean($table);\r
+               $sql = "SELECT * FROM pg_class WHERE relname='{$table}'";\r
+               return $this->selectRow($sql);\r
+       }\r
+\r
+       // @@ Need create table - tricky!!\r
+       \r
+       /**\r
+        * Removes a table from the database\r
+        * @param $table\r
+        * @return 0 success\r
+        */\r
+       function dropTable($table) {\r
+               $this->clean($table);\r
+               \r
+               $sql = "DROP TABLE \"{$table}\"";\r
+\r
+               // @@ How do you do this?\r
+               return $this->execute($sql);\r
+       }\r
+\r
+       /**\r
+        * Renames a table\r
+        * @param $table The table to be renamed\r
+        * @param $newName The new name for the table\r
+        * @return 0 success\r
+        */\r
+       function renameTable($table, $newName) {\r
+               $this->clean($table);\r
+               $this->clean($newName);\r
+               $sql = "ALTER TABLE \"{$table}\" RENAME TO \"{$newName}\"";\r
+\r
+               // @@ How do you do this?\r
+               return $this->execute($sql);\r
+       }\r
+\r
+       /**\r
+        * Adds a check constraint to a table\r
+        * @param $table The table to which to add the check\r
+        * @param $definition The definition of the check\r
+        * @param $name (optional) The name to give the check, otherwise default name is assigned\r
+        * @return 0 success\r
+        */\r
+       function addCheckConstraint($table, $definition, $name = '') {\r
+               $this->clean($table);\r
+               $this->clean($name);\r
+               // @@ how the heck do you clean definition???\r
+               \r
+               if ($name != '')\r
+                       $sql = "ALTER TABLE \"{$table}\" ADD CONSTRAINT \"{$name}\" CHECK ({$definition})";\r
+               else\r
+                       $sql = "ALTER TABLE \"{$table}\" ADD CHECK ({$definition})";\r
+\r
+               // @@ How do you do this?\r
+               return $this->execute($sql);\r
+       }\r
+       \r
+       /**\r
+        * Drops a check constraint from a table\r
+        * @param $table The table from which to drop the check\r
+        * @param $name The name of the check to be dropped\r
+        * @return 0 success\r
+        * @return -2 transaction error\r
+        * @return -3 lock error\r
+        * @return -4 check drop error\r
+        */\r
+       function dropCheckConstraint($table, $name) {\r
+               $this->clean($table);\r
+               $this->clean($name);\r
+               \r
+               // Begin transaction\r
+               $status = $this->beginTransaction();\r
+               if ($status != 0) return -2;\r
+\r
+               // Properly lock the table\r
+               $sql = "LOCK TABLE \"{$table}\" IN ACCESS EXCLUSIVE MODE";\r
+               $status = $this->execute($sql);\r
+               if ($status != 0) {\r
+                       $this->rollbackTransaction();\r
+                       return -3;\r
+               }\r
+\r
+               // Delete the check constraint\r
+               $sql = "DELETE FROM pg_relcheck WHERE rcrelid=(SELECT oid FROM pg_class WHERE relname='{$table}') AND rcname='{$name}'";\r
+          $status = $this->execute($sql);\r
+               if ($status != 0) {\r
+                       $this->rollbackTransaction();\r
+                       return -4;\r
+               }\r
+               \r
+               // Update the pg_class catalog to reflect the new number of checks\r
+               $sql = "UPDATE pg_class SET relchecks=(SELECT COUNT(*) FROM pg_relcheck WHERE \r
+                                       rcrelid=(SELECT oid FROM pg_class WHERE relname='{$table}')) \r
+                                       WHERE relname='{$table}'";\r
+          $status = $this->execute($sql);\r
+               if ($status != 0) {\r
+                       $this->rollbackTransaction();\r
+                       return -4;\r
+               }\r
+\r
+               // Otherwise, close the transaction\r
+               return $this->endTransaction();\r
+       }       \r
+\r
+       /**\r
+        * Adds a unique constraint to a table\r
+        * @param $table The table to which to add the unique\r
+        * @param $fields (array) An array of fields over which to add the unique\r
+        * @param $name (optional) The name to give the unique, otherwise default name is assigned\r
+        * @return 0 success\r
+        */\r
+       function addUniqueConstraint($table, $fields, $name = '') {\r
+               $this->clean($table);\r
+               $this->arrayClean($fields);\r
+               $this->clean($name);\r
+               \r
+               if ($name != '')\r
+                       $sql = "CREATE UNIQUE INDEX \"{$name}\" ON \"{$table}\"(\"" . join('","', $fields) . "\")";\r
+               else return -99; // Not supported\r
+\r
+               // @@ How do you do this?\r
+               return $this->execute($sql);\r
+       }\r
+\r
+       /**\r
+        * Drops a unique constraint from a table\r
+        * @param $table The table from which to drop the unique\r
+        * @param $name The name of the unique\r
+        * @return 0 success\r
+        */\r
+       function dropUniqueConstraint($table, $name) {\r
+               $this->clean($table);\r
+               $this->clean($name);\r
+               \r
+               $sql = "DROP INDEX \"{$name}\"";\r
+\r
+               // @@ How do you do this?\r
+               return $this->execute($sql);\r
+       }       \r
+        \r
+       /**\r
+        * Adds a primary key constraint to a table\r
+        * @param $table The table to which to add the primery key\r
+        * @param $fields (array) An array of fields over which to add the primary key\r
+        * @param $name (optional) The name to give the key, otherwise default name is assigned\r
+        * @return 0 success\r
+        */\r
+       function addPrimaryKeyConstraint($table, $fields, $name = '') {\r
+               // This function can be faked with a unique index and a catalog twiddle, however\r
+               // how do we ensure that it's only used on NOT NULL fields?\r
+               return -99; // Not supported.\r
+       }\r
+\r
+       /**\r
+        * Drops a primary key constraint from a table\r
+        * @param $table The table from which to drop the primary key\r
+        * @param $name The name of the primary key\r
+        * @return 0 success\r
+        */\r
+       function dropPrimaryKeyConstraint($table, $name) {\r
+               $this->clean($table);\r
+               $this->clean($name);\r
+               \r
+               $sql = "DROP INDEX \"{$name}\"";\r
+\r
+               // @@ How do you do this?\r
+               return $this->execute($sql);\r
+       }       \r
+       \r
+       /**\r
+        * Changes the owner of a table\r
+        * @param $table The table whose owner is to change\r
+        * @param $owner The new owner (username) of the table\r
+        * @return 0 success\r
+        */\r
+       function setOwnerOfTable($table, $owner) {\r
+               $this->clean($table);\r
+               $this->clean($owner);\r
+               \r
+               $sql = "ALTER TABLE \"{$table}\" OWNER TO \"{$owner}\"";\r
+\r
+               // @@ How do you do this?\r
+               return $this->execute($sql);\r
+       }\r
+\r
+       // Column Functions\r
+\r
+       /**\r
+        * Add a new column to a table\r
+        * @param $table The table to add to\r
+        * @param $column The name of the new column\r
+        * @param $type The type of the column\r
+        * @param $size (optional) The optional size of the column (ie. 30 for varchar(30))\r
+        * @return 0 success\r
+        */\r
+       function addColumnToTable($table, $column, $type, $size = '') {\r
+               $this->clean($table);\r
+               $this->clean($column);\r
+               $this->clean($type);\r
+               $this->clean($size);\r
+               // @@ How the heck do you properly clean type and size?\r
+               \r
+               if ($size == '')\r
+                       $sql = "ALTER TABLE \"{$table}\" ADD COLUMN \"{$column}\" {$type}";\r
+               else\r
+                       $sql = "ALTER TABLE \"{$table}\" ADD COLUMN \"{$column}\" {$type}({$size})";\r
+\r
+               // @@ How do you do this?\r
+               return $this->execute($sql);\r
+       }\r
+\r
+       /**\r
+        * Drops a column from a table\r
+        * @param $table The table from which to drop\r
+        * @param $column The column name to drop\r
+        * @return 0 success\r
+        */\r
+       function dropColumnFromTable($table, $column) {\r
+               return -99; // Not implemented\r
+       }\r
+\r
+       /**\r
+        * Sets default value of a column\r
+        * @param $table The table from which to drop\r
+        * @param $column The column name to set\r
+        * @param $default The new default value\r
+        * @return 0 success\r
+        */\r
+       function setColumnDefault($table, $column, $default) {\r
+               $this->clean($table);\r
+               $this->clean($column);\r
+               // @@ How the heck do you clean default clause?\r
+               \r
+               $sql = "ALTER TABLE \"{$table}\" ALTER COLUMN \"{$column}\" SET DEFAULT {$default}";\r
+\r
+               // @@ How do you do this?\r
+               return $this->execute($sql);\r
+       }\r
+\r
+       /**\r
+        * Drops default value of a column\r
+        * @param $table The table from which to drop\r
+        * @param $column The column name to drop default\r
+        * @return 0 success\r
+        */\r
+       function dropColumnDefault($table, $column) {\r
+               $this->clean($table);\r
+               $this->clean($column);\r
+\r
+               $sql = "ALTER TABLE \"{$table}\" ALTER COLUMN \"{$column}\" DROP DEFAULT";\r
+\r
+               // @@ How do you do this?\r
+               return $this->execute($sql);\r
+       }\r
+\r
+       /**\r
+        * Sets whether or not a column can contain NULLs\r
+        * @param $table The table that contains the column\r
+        * @param $column The column to alter\r
+        * @param $state True to set null, false to set not null\r
+        * @return 0 success\r
+        * @return -1 attempt to set not null, but column contains nulls\r
+        * @return -2 transaction error\r
+        * @return -3 lock error\r
+        * @return -4 update error\r
+        */\r
+       function setColumnNull($table, $column, $state) {\r
+               $this->clean($table);\r
+               $this->clean($column);\r
+\r
+               // Begin transaction\r
+               $status = $this->beginTransaction();\r
+               if ($status != 0) return -2;\r
+\r
+               // Properly lock the table\r
+               $sql = "LOCK TABLE \"{$table}\" IN ACCESS EXCLUSIVE MODE";\r
+               $status = $this->execute($sql);\r
+               if ($status != 0) {\r
+                       $this->rollbackTransaction();\r
+                       return -3;\r
+               }\r
+\r
+               // Check for existing nulls\r
+               if (!$state) {\r
+                       $sql = "SELECT COUNT(*) AS total FROM \"{$table}\" WHERE \"{$column}\" IS NULL";\r
+                       $result = $this->selectField($sql, 'total');\r
+                       if ($result > 0) {\r
+                               $this->rollbackTransaction();\r
+                               return -1;\r
+                       }\r
+               }\r
+               \r
+               // Otherwise update the table.  Note the reverse-sensed $state variable\r
+               $sql = "UPDATE pg_attribute SET attnotnull = " . ($state) ? 'false' : 'true' . " \r
+                                       WHERE attrelid = (SELECT oid FROM pg_class WHERE relname = '{$table}') \r
+                                       AND attname = '{$column}'";\r
+          $status = $this->execute($sql);\r
+               if ($status != 0) {\r
+                       $this->rollbackTransaction();\r
+                       return -4;\r
+               }\r
+\r
+               // Otherwise, close the transaction\r
+               return $this->endTransaction();\r
+       }\r
+\r
+       /**\r
+        * Renames a column in a table\r
+        * @param $table The table containing the column to be renamed\r
+        * @param $column The column to be renamed\r
+        * @param $newName The new name for the column\r
+        * @return 0 success\r
+        */\r
+       function renameColumn($table, $column, $newName) {\r
+               $this->clean($table);\r
+               $this->clean($column);\r
+               $this->clean($newName);\r
+\r
+               $sql = "ALTER TABLE \"{$table}\" RENAME COLUMN \"{$column}\" TO \"{$newName}\"";\r
+\r
+               // @@ how?\r
+               return $this->execute($sql);\r
+       }\r
+/*\r
+       function &getIndices()\r
+       function &getIndex()\r
+       function setIndex()\r
+       function delIndex()\r
+\r
+       function &getSequences()\r
+       function &getSequence()\r
+       function setSequence()\r
+       function delSequence()\r
+\r
+       // DML Functions\r
+\r
+       function doSelect()\r
+       function doDelete()\r
+       function doUpdate()\r
+*/\r
+\r
+       // Capabilities\r
+       function hasTables() { return true; }\r
+       function hasViews() { return true; }\r
+       function hasSequences() { return true; }\r
+       function hasFunctions() { return true; }\r
+       function hasTriggers() { return true; }\r
+       function hasOperators() { return true; }\r
+       function hasTypes() { return true; }\r
+       function hasAggregates() { return true; }\r
+       function hasRules() { return true; }\r
+\r
+}\r
+\r
+?>
\ No newline at end of file
diff --git a/conf/config.inc b/conf/config.inc
new file mode 100644 (file)
index 0000000..617d1b4
--- /dev/null
@@ -0,0 +1,62 @@
+<?php\r
+\r
+       /**\r
+        * Central WebDB configuration\r
+        *\r
+        * $Id: config.inc,v 1.1 2002/02/11 09:32:49 chriskl Exp $\r
+        */\r
+\r
+       // Set error reporting level\r
+       error_reporting(E_ALL);\r
+\r
+       // App settings\r
+       $appName = 'WebDB';\r
+       $appIntro = 'Welcome to WebDB.';\r
+       $appBase = '/home/chriskl/public_html/webdb';\r
+       $appVersion = '1-dev';\r
+       \r
+       // GUI settings\r
+       $guiLeftFrameWidth = 150;\r
+\r
+       // Servers and types\r
+       $confServers = array();\r
+       $confServers[0]['desc'] = 'Houston';\r
+       $confServers[0]['host'] = 'database.internal';\r
+       $confServers[0]['port'] = '5432';\r
+       $confServers[0]['type'] = 'Postgres71';\r
+       $confServers[0]['default'] = 'template1';\r
+\r
+       // Language\r
+       include_once($appBase . '/lang/template.php');\r
+       \r
+       // If login action is set, then set login variables\r
+       if (isset($formServer) && isset($formUsername) && isset($formPassword)) {\r
+               $webdbServerID = $formServer;\r
+               $webdbUsername = $formUsername;\r
+               $webdbPassword = $formPassword;\r
+               setCookie('webdbServerID', $webdbServerID);\r
+               setCookie('webdbUsername', $webdbUsername);\r
+               setCookie('webdbPassword', $webdbPassword);\r
+       }\r
+               \r
+       // If the logged in settings aren't present, put up the login screen\r
+       if (!isset($webdbUsername) || !isset($webdbPassword) || !isset($webdbServerID) || !isset($confServers[$webdbServerID])) {\r
+               include($appBase . '/public_html/login.php');\r
+               exit;\r
+       }\r
+       \r
+       // Create data accessor object, if valid\r
+       if (isset($webdbServerID) && isset($confServers[$webdbServerID])) {\r
+               $_type = $confServers[$webdbServerID]['type'];\r
+               include_once($appBase . '/classes/database/' . $_type . '.php');\r
+               $data = new $_type(     $confServers[$webdbServerID]['host'],\r
+                                                                       $confServers[$webdbServerID]['port'],\r
+                                                                       $confServers[$webdbServerID]['default'],\r
+                                                                       $webdbUsername,\r
+                                                                       $webdbPassword);\r
+       }\r
+\r
+\r
+       \r
+\r
+?>
\ No newline at end of file
diff --git a/lang/english.php b/lang/english.php
new file mode 100755 (executable)
index 0000000..152d6b2
--- /dev/null
@@ -0,0 +1,31 @@
+<?php\r
+\r
+       /**\r
+        * Main access point to WebDB.\r
+        *\r
+        * $Id: english.php,v 1.1 2002/02/11 09:32:49 chriskl Exp $\r
+        */\r
+\r
+       // Include application functions\r
+       include_once('../conf/config.inc');\r
+\r
+?>\r
+\r
+<html>\r
+<head>\r
+<title><?= $appName ?></title>\r
+</head>\r
+\r
+<frameset rows="50, *" border="0" frameborder="0">\r
+       <frame src="topbar.php" name="topbar">\r
+       <frameset cols="<?= $guiLeftFrameWidth ?>,*" border="0" frameborder="0">\r
+         <frame src="browser.php" name="browser">\r
+         <frame src="detail.php" name="detail">\r
+       </frameset>\r
+</frameset>\r
+<noframes>\r
+<body>\r
+       <?= $strNoFrames ?>\r
+</body>\r
+</noframes>\r
+</html>
\ No newline at end of file
diff --git a/lang/template.php b/lang/template.php
new file mode 100644 (file)
index 0000000..a819a5f
--- /dev/null
@@ -0,0 +1,16 @@
+<?php\r
+\r
+       /**\r
+        * Language template file for WebDB.  Use this to base language\r
+        * files.\r
+        *\r
+        * $Id: template.php,v 1.1 2002/02/11 09:32:49 chriskl Exp $\r
+        */\r
+\r
+       $appLang = 'english';\r
+\r
+       $strNoFrames = 'You need a frames-enabled browser to use this application.';\r
+       $strLogin = 'Login';\r
+       \r
+       \r
+?>
\ No newline at end of file
diff --git a/libraries/adodb/adodb-access.inc.php b/libraries/adodb/adodb-access.inc.php
new file mode 100755 (executable)
index 0000000..d8fe7fa
--- /dev/null
@@ -0,0 +1,54 @@
+<?php\r
+/* \r
+V1.53 13 Nov 2001 (c) 2000, 2001 John Lim (jlim@natsoft.com.my). All rights reserved.\r
+  Released under both BSD license and Lesser GPL library license. \r
+  Whenever there is any discrepancy between the two licenses, \r
+  the BSD license will take precedence. See License.txt. \r
+  Set tabs to 4 for best viewing.\r
+  \r
+  Latest version is available at http://php.weblogs.com/\r
+  \r
+  Microsoft Access data driver. Requires ODBC. Works only on MS Windows.\r
+*/\r
+if (!defined('_ADODB_ODBC_LAYER')) {\r
+       include(ADODB_DIR."/adodb-odbc.inc.php");\r
+}\r
+ if (!defined('_ADODB_ACCESS')) {\r
+       define('_ADODB_ACCESS',1);\r
+class  ADODB_access extends ADODB_odbc {       \r
+       var $databaseType = 'access';\r
+       var $hasTop = true;             // support mssql SELECT TOP 10 * FROM TABLE\r
+       var $fmtDate = "#Y-m-d#";\r
+       var $fmtTimeStamp = "#Y-m-d h:i:sA#"; // note not comma\r
+       var $_bindInputArray = false;\r
+\r
+       function BeginTrans() { return false;}\r
+       \r
+       function &MetaTables()\r
+       {\r
+               $qid = odbc_tables($this->_connectionID);\r
+               $rs = new ADORecordSet_odbc($qid);\r
+               //print_r($rs);\r
+               $arr = &$rs->GetArray();\r
+               \r
+               $arr2 = array();\r
+               for ($i=0; $i < sizeof($arr); $i++) {\r
+                       if ($arr[$i][2] && substr($arr[$i][2],0,4) != 'MSys')\r
+                               $arr2[] = $arr[$i][2];\r
+               }\r
+               return $arr2;\r
+       }\r
+}\r
+\r
\r
+class  ADORecordSet_access extends ADORecordSet_odbc { \r
+       \r
+       var $databaseType = "access";           \r
+       \r
+       function ADORecordSet_access($id)\r
+       {\r
+               return $this->ADORecordSet_odbc($id);\r
+       }\r
+}\r
+} // class\r
+?>
\ No newline at end of file
diff --git a/libraries/adodb/adodb-ado.inc.php b/libraries/adodb/adodb-ado.inc.php
new file mode 100755 (executable)
index 0000000..73ef407
--- /dev/null
@@ -0,0 +1,522 @@
+<?php\r
+/* \r
+V1.53 13 Nov 2001 (c) 2000, 2001 John Lim (jlim@natsoft.com.my). All rights reserved.\r
+  Released under both BSD license and Lesser GPL library license. \r
+  Whenever there is any discrepancy between the two licenses, \r
+  the BSD license will take precedence. \r
+Set tabs to 4 for best viewing.\r
+  \r
+  Latest version is available at http://php.weblogs.com/\r
+  \r
+    Microsoft ADO data driver. Requires ADO. Works only on MS Windows.\r
+*/\r
+  define("_ADODB_ADO_LAYER", 1 );\r
+/*--------------------------------------------------------------------------------------\r
+--------------------------------------------------------------------------------------*/\r
+  \r
+class ADODB_ado extends ADOConnection {\r
+       var $databaseType = "ado";      \r
+       var $_bindInputArray = false;\r
+       var $fmtDate = "'Y-m-d'";\r
+       var $fmtTimeStamp = "'Y-m-d, h:i:sA'";\r
+       var $replaceQuote = "''"; // string to use to replace quotes\r
+       var $dataProvider = "ado";      \r
+    var $hasAffectedRows = true;\r
+       var $adoParameterType = 201; // 201 = long varchar, 203=long wide varchar, 205 = long varbinary\r
+       var $_affectedRows = false;\r
+       \r
+       function ADODB_ado() \r
+       {       \r
+       }\r
+\r
+       \r
+    function _affectedrows()\r
+    {\r
+            return $this->_affectedRows;\r
+    }\r
+         \r
+       function _connect($argHostname, $argUsername, $argPassword, $argProvider= 'MSDASQL')\r
+       {\r
+               $u = 'UID';\r
+               $p = 'PWD';\r
+       \r
+               $dbc = new COM('ADODB.Connection');\r
+               if (! $dbc) return false;\r
+               /* // handle SQL server provider specially ? no need\r
+               if ($argProvider) {\r
+                       if ($argProvider == "SQLOLEDB") { // SQL Server Provider\r
+                       } \r
+               }*/\r
+               if ($argProvider) $dbc->Provider = $argProvider;\r
+               else $dbc->Provider ='MSDASQL';\r
+               \r
+               if ($argUsername) $argHostname .= ";$u=$argUsername";\r
+               if ($argPassword)$argHostname .= ";$p=$argPassword";\r
+               \r
+               if ($this->debug) print "<p>Host=".$argHostname."<BR>version=$dbc->version</p>";\r
+               // @ added below for php 4.0.1 and earlier\r
+               @$dbc->Open((string) $argHostname);\r
+\r
+               $this->_connectionID = $dbc;\r
+               return  $dbc != false;\r
+       }\r
+       \r
+       // returns true or false\r
+       function _pconnect($argHostname, $argUsername, $argPassword, $argProvider='MSDASQL')\r
+       {\r
+               $dbc = new COM("ADODB.Connection");\r
+               if (! $dbc) return false;\r
+               \r
+               if ($argProvider) $dbc->Provider = $argProvider;\r
+               else $dbc->Provider ='MSDASQL';\r
+               \r
+               if ($argUsername) $argHostname .= ";UID=$argUsername";\r
+               if ($argPassword)$argHostname .= ";PWD=$argPassword";\r
+               \r
+               if ($this->debug) print "<p>Host=".$argHostname."<BR>version=$dbc->version</p>";\r
+               $dbc->Open((string) $argHostname);\r
+               \r
+               $this->_connectionID = $dbc;\r
+               return  $dbc != false;\r
+       }       \r
+       \r
+/*\r
+       adSchemaCatalogs        = 1,\r
+       adSchemaCharacterSets   = 2,\r
+       adSchemaCollations      = 3,\r
+       adSchemaColumns = 4,\r
+       adSchemaCheckConstraints        = 5,\r
+       adSchemaConstraintColumnUsage   = 6,\r
+       adSchemaConstraintTableUsage    = 7,\r
+       adSchemaKeyColumnUsage  = 8,\r
+       adSchemaReferentialContraints   = 9,\r
+       adSchemaTableConstraints        = 10,\r
+       adSchemaColumnsDomainUsage      = 11,\r
+       adSchemaIndexes = 12,\r
+       adSchemaColumnPrivileges        = 13,\r
+       adSchemaTablePrivileges = 14,\r
+       adSchemaUsagePrivileges = 15,\r
+       adSchemaProcedures      = 16,\r
+       adSchemaSchemata        = 17,\r
+       adSchemaSQLLanguages    = 18,\r
+       adSchemaStatistics      = 19,\r
+       adSchemaTables  = 20,\r
+       adSchemaTranslations    = 21,\r
+       adSchemaProviderTypes   = 22,\r
+       adSchemaViews   = 23,\r
+       adSchemaViewColumnUsage = 24,\r
+       adSchemaViewTableUsage  = 25,\r
+       adSchemaProcedureParameters     = 26,\r
+       adSchemaForeignKeys     = 27,\r
+       adSchemaPrimaryKeys     = 28,\r
+       adSchemaProcedureColumns        = 29,\r
+       adSchemaDBInfoKeywords  = 30,\r
+       adSchemaDBInfoLiterals  = 31,\r
+       adSchemaCubes   = 32,\r
+       adSchemaDimensions      = 33,\r
+       adSchemaHierarchies     = 34,\r
+       adSchemaLevels  = 35,\r
+       adSchemaMeasures        = 36,\r
+       adSchemaProperties      = 37,\r
+       adSchemaMembers = 38\r
+\r
+*/\r
+       \r
+       function MetaTables()\r
+       {\r
+               $arr= array();\r
+               $dbc = $this->_connectionID;\r
+               \r
+               $adors=@$dbc->OpenSchema(20);//tables\r
+               if ($adors){\r
+                       $f = $adors->Fields(2);//table/view name\r
+                       $t = $adors->Fields(3);//table type\r
+                       while (!$adors->EOF){\r
+                               $tt=substr($t->value,0,6);\r
+                               if ($tt!='SYSTEM' && $tt !='ACCESS')\r
+                                       $arr[]=$f->value;\r
+                               //print $f->value . ' ' . $t->value.'<br>';\r
+                               $adors->MoveNext();\r
+                       }\r
+                       $adors->Close();\r
+               }\r
+               \r
+               return $arr;\r
+       }\r
+       \r
+       function MetaColumns($table)\r
+       {\r
+               $table = strtoupper($table);\r
+               $arr= array();\r
+               $dbc = $this->_connectionID;\r
+               \r
+               $adors=@$dbc->OpenSchema(4);//tables\r
+       \r
+               if ($adors){\r
+                       $t = $adors->Fields(2);//table/view name\r
+                       while (!$adors->EOF){\r
+                               \r
+                               \r
+                               if (strtoupper($t->Value) == $table) {\r
+                               \r
+                                       $fld = new ADOFieldObject();\r
+                                       $c = $adors->Fields(3);\r
+                                       $fld->name = $c->Value;\r
+                                       $fld->type = 'CHAR'; // cannot discover type in ADO!\r
+                                       $fld->max_length = -1;\r
+                                       $arr[strtoupper($fld->name)]=$fld;\r
+                               }\r
+               \r
+                               $adors->MoveNext();\r
+                       }\r
+                       $adors->Close();\r
+               }\r
+               \r
+               return $arr;\r
+       }\r
+       \r
+       /* returns queryID or false */\r
+       function &_query($sql,$inputarr=false) \r
+       {\r
+               \r
+               $dbc = $this->_connectionID;\r
+               \r
+       //      return rs       \r
+               if ($inputarr) {\r
+                       $oCmd = new COM('ADODB.Command');\r
+                       $oCmd->ActiveConnection = $dbc;\r
+                       $oCmd->CommandText = $sql;\r
+                       $oCmd->CommandType = 1;\r
+\r
+                       foreach($inputarr as $val) {\r
+                               // name, type, direction 1 = input, len,\r
+                               $this->adoParameterType = 130;\r
+                               $p = $oCmd->CreateParameter('name',$this->adoParameterType,1,strlen($val),$val);\r
+                               //print $p->Type.' '.$p->value;\r
+                               $oCmd->Parameters->Append($p);\r
+                       }\r
+                       $p = false;\r
+                       $rs = $oCmd->Execute();\r
+                       $e = $dbc->Errors;\r
+                       if ($dbc->Errors->Count > 0) return false;\r
+                       return $rs;\r
+               }\r
+\r
+               $rs = @$dbc->Execute($sql,$this->_affectedRows);        \r
+       \r
+               if ($dbc->Errors->Count > 0) return false;\r
+               return $rs;\r
+       }\r
+\r
+       \r
+       function BeginTrans() \r
+       { \r
+               $o = $this->_connectionID->Properties("Transaction DDL");\r
+               if (!$o) return false;\r
+               @$this->_connectionID->BeginTrans();\r
+               return true;\r
+       }\r
+       function CommitTrans() { \r
+               @$this->_connectionID->CommitTrans();\r
+               return true;\r
+       }\r
+       function RollbackTrans() {\r
+               @$this->_connectionID->RollbackTrans();\r
+               return true;\r
+       }\r
+       \r
+       /*      Returns: the last error message from previous database operation        */      \r
+\r
+       function ErrorMsg() \r
+       {\r
+               $errc = $this->_connectionID->Errors;\r
+               if ($errc->Count == 0) return '';\r
+               $err = $errc->Item($errc->Count-1);\r
+               return $err->Description;\r
+       }\r
+       \r
+       function ErrorNo() \r
+       {\r
+               $errc = $this->_connectionID->Errors;\r
+               if ($errc->Count == 0) return 0;\r
+               $err = $errc->Item($errc->Count-1);\r
+               return $err->NativeError;\r
+       }\r
+\r
+       // returns true or false\r
+       function _close()\r
+       {\r
+               if ($this->_connectionID) $this->_connectionID->Close();\r
+               $this->_connectionID = false;\r
+               return true;\r
+       }\r
+       \r
+       \r
+}\r
+       \r
+/*--------------------------------------------------------------------------------------\r
+        Class Name: Recordset\r
+--------------------------------------------------------------------------------------*/\r
+\r
+class ADORecordSet_ado extends ADORecordSet {  \r
+       \r
+       var $bind = false;\r
+       var $databaseType = "ado";      \r
+       var $dataProvider = "ado";      \r
+       var $_tarr = false; // caches the types\r
+       var $_flds; // and field objects\r
+        var $canSeek = true;\r
+       var $hideErrors = true;\r
+             \r
+       function ADORecordSet_ado(&$id)\r
+       {\r
+       global $ADODB_FETCH_MODE;\r
+       \r
+               $this->fetchMode = $ADODB_FETCH_MODE;\r
+               return $this->ADORecordSet($id);\r
+       }\r
+\r
+\r
+       // returns the field object\r
+       function FetchField($fieldOffset = -1) {\r
+               $off=$fieldOffset+1; // offsets begin at 1\r
+               \r
+               $o= new ADOFieldObject();\r
+               $rs = $this->_queryID;\r
+               $f = $rs->Fields($fieldOffset);\r
+               $o->name = $f->Name;\r
+               $o->type = $f->Type;\r
+               $o->max_length = $f->DefinedSize;\r
+               \r
+               //print "off=$off name=$o->name type=$o->type len=$o->max_length<br>";\r
+               return $o;\r
+       }\r
+       \r
+       /* Use associative array to get fields array */\r
+       function Fields($colname)\r
+       {\r
+               if (!$this->bind) {\r
+                       $this->bind = array();\r
+                       for ($i=0; $i < $this->_numOfFields; $i++) {\r
+                               $o = $this->FetchField($i);\r
+                               $this->bind[strtoupper($o->name)] = $i;\r
+                       }\r
+               }\r
+               \r
+                return $this->fields[$this->bind[strtoupper($colname)]];\r
+       }\r
+\r
+               \r
+       function _initrs()\r
+       {\r
+               $rs = $this->_queryID;\r
+               $this->_numOfRows = $rs->RecordCount;\r
+               \r
+               $f = $rs->Fields;\r
+               $this->_numOfFields = $f->Count;\r
+       }\r
+       \r
+       \r
+        // should only be used to move forward as we normally use forward-only cursors\r
+       function _seek($row)\r
+       {\r
+                $rs = $this->_queryID; \r
+            // absoluteposition doesn't work -- my maths is wrong ?\r
+            //    $rs->AbsolutePosition->$row-2;\r
+            //    return true;\r
+                 if ($this->_currentRow > $row) return false;\r
+                $rs->Move((integer)$row - $this->_currentRow-1); //adBookmarkFirst\r
+               return true;\r
+       }\r
+       \r
+/*\r
+       OLEDB types\r
+       \r
+     enum DBTYPEENUM\r
+    {  DBTYPE_EMPTY    = 0,\r
+       DBTYPE_NULL     = 1,\r
+       DBTYPE_I2       = 2,\r
+       DBTYPE_I4       = 3,\r
+       DBTYPE_R4       = 4,\r
+       DBTYPE_R8       = 5,\r
+       DBTYPE_CY       = 6,\r
+       DBTYPE_DATE     = 7,\r
+       DBTYPE_BSTR     = 8,\r
+       DBTYPE_IDISPATCH        = 9,\r
+       DBTYPE_ERROR    = 10,\r
+       DBTYPE_BOOL     = 11,\r
+       DBTYPE_VARIANT  = 12,\r
+       DBTYPE_IUNKNOWN = 13,\r
+       DBTYPE_DECIMAL  = 14,\r
+       DBTYPE_UI1      = 17,\r
+       DBTYPE_ARRAY    = 0x2000,\r
+       DBTYPE_BYREF    = 0x4000,\r
+       DBTYPE_I1       = 16,\r
+       DBTYPE_UI2      = 18,\r
+       DBTYPE_UI4      = 19,\r
+       DBTYPE_I8       = 20,\r
+       DBTYPE_UI8      = 21,\r
+       DBTYPE_GUID     = 72,\r
+       DBTYPE_VECTOR   = 0x1000,\r
+       DBTYPE_RESERVED = 0x8000,\r
+       DBTYPE_BYTES    = 128,\r
+       DBTYPE_STR      = 129,\r
+       DBTYPE_WSTR     = 130,\r
+       DBTYPE_NUMERIC  = 131,\r
+       DBTYPE_UDT      = 132,\r
+       DBTYPE_DBDATE   = 133,\r
+       DBTYPE_DBTIME   = 134,\r
+       DBTYPE_DBTIMESTAMP      = 135\r
+       \r
+       ADO Types\r
+       \r
+       adEmpty = 0,\r
+       adTinyInt       = 16,\r
+       adSmallInt      = 2,\r
+       adInteger       = 3,\r
+       adBigInt        = 20,\r
+       adUnsignedTinyInt       = 17,\r
+       adUnsignedSmallInt      = 18,\r
+       adUnsignedInt   = 19,\r
+       adUnsignedBigInt        = 21,\r
+       adSingle        = 4,\r
+       adDouble        = 5,\r
+       adCurrency      = 6,\r
+       adDecimal       = 14,\r
+       adNumeric       = 131,\r
+       adBoolean       = 11,\r
+       adError = 10,\r
+       adUserDefined   = 132,\r
+       adVariant       = 12,\r
+       adIDispatch     = 9,\r
+       adIUnknown      = 13,   \r
+       adGUID  = 72,\r
+       adDate  = 7,\r
+       adDBDate        = 133,\r
+       adDBTime        = 134,\r
+       adDBTimeStamp   = 135,\r
+       adBSTR  = 8,\r
+       adChar  = 129,\r
+       adVarChar       = 200,\r
+       adLongVarChar   = 201,\r
+       adWChar = 130,\r
+       adVarWChar      = 202,\r
+       adLongVarWChar  = 203,\r
+       adBinary        = 128,\r
+       adVarBinary     = 204,\r
+       adLongVarBinary = 205,\r
+       adChapter       = 136,\r
+       adFileTime      = 64,\r
+       adDBFileTime    = 137,\r
+       adPropVariant   = 138,\r
+       adVarNumeric    = 139\r
+*/\r
+       function MetaType($t,$len=-1)\r
+       {\r
+               switch ($t) {\r
+               case 12: // variant\r
+               case 8: // bstr\r
+               case 129: //char\r
+               case 130: //wc\r
+               case 200: // varc\r
+               case 202:// varWC\r
+               case 128: // bin\r
+               case 204: // varBin\r
+               case 72: // guid\r
+                       if ($len <= $this->blobSize) return 'C';\r
+               \r
+               case 201:\r
+               case 203:\r
+                       return 'X';\r
+               case 128:\r
+               case 204:\r
+               case 205:\r
+                        return 'B';\r
+               case 7:\r
+               case 133: return 'D';\r
+               \r
+               case 134:\r
+               case 135: return 'T';\r
+               \r
+               case 11: return 'L';\r
+               \r
+               case 16://      adTinyInt       = 16,\r
+               case 2://adSmallInt     = 2,\r
+               case 3://adInteger      = 3,\r
+               case 4://adBigInt       = 20,\r
+               case 17://adUnsignedTinyInt     = 17,\r
+               case 18://adUnsignedSmallInt    = 18,\r
+               case 19://adUnsignedInt = 19,\r
+               case 20://adUnsignedBigInt      = 21,\r
+                       return 'I';\r
+               default: return 'N';\r
+               }\r
+       }\r
+       \r
+       // time stamp not supported yet\r
+       function _fetch()\r
+       {       \r
+               $rs = $this->_queryID;\r
+               if ($rs->EOF) return false;\r
+               $this->fields = array();\r
+       \r
+               if (!$this->_tarr) {\r
+                       $tarr = array();\r
+                       $flds = array();\r
+                       for ($i=0,$max = $this->_numOfFields; $i < $max; $i++) {\r
+                               $f = $rs->Fields($i);\r
+                               $flds[] = $f;\r
+                               $tarr[] = $f->Type;\r
+                       }\r
+                       // bind types and flds only once\r
+                       $this->_tarr = $tarr; \r
+                       $this->_flds = $flds;\r
+               }\r
+               $t = reset($this->_tarr);\r
+               $f = reset($this->_flds);\r
+               \r
+               if ($this->hideErrors)  $olde = error_reporting(E_ERROR|E_CORE_ERROR);// sometimes $f->value be null\r
+               for ($i=0,$max = $this->_numOfFields; $i < $max; $i++) {\r
+\r
+                       switch($t) {\r
+                               \r
+                       case 133:// A date value (yyyymmdd) \r
+                               $val = $f->value;\r
+                               $this->fields[] = substr($val,0,4).'-'.substr($val,4,2).'-'.substr($val,6,2);\r
+                               break;\r
+                       case 7: // adDate\r
+                               $this->fields[] = date('Y-m-d',(integer)$f->value);\r
+                               break;\r
+                       case 1: // null\r
+                               $this->fields[] = false;\r
+                               break;\r
+                       case 6: // currency is not supported properly;\r
+                               print '<br><b>'.$f->Name.': currency type not supported by PHP</b><br>';\r
+                               $this->fields[] = (float) $f->value;\r
+                               break;\r
+                       default:\r
+                               $this->fields[] = $f->value; \r
+                               break;\r
+                       }\r
+                       //print " $f->value $t, ";\r
+                       $f = next($this->_flds);\r
+                       $t = next($this->_tarr);\r
+               } // for\r
+               if ($this->hideErrors) error_reporting($olde);\r
+               @$rs->MoveNext(); // @ needed for some versions of PHP!\r
+               \r
+               if ($this->fetchMode == ADODB_FETCH_ASSOC) {\r
+                       $this->fields = $this->GetRowAssoc(false);\r
+               }\r
+               return true;\r
+       }\r
+       \r
+       \r
+       function _close() {\r
+               $this->_flds = false;\r
+               $this->_queryID = false;        \r
+       }\r
+\r
+}\r
+\r
+?>
\ No newline at end of file
diff --git a/libraries/adodb/adodb-ado_access.inc.php b/libraries/adodb/adodb-ado_access.inc.php
new file mode 100755 (executable)
index 0000000..3a087e3
--- /dev/null
@@ -0,0 +1,38 @@
+<?php\r
+/* \r
+V1.53 13 Nov 2001 (c) 2000, 2001 John Lim (jlim@natsoft.com.my). All rights reserved.\r
+Released under both BSD license and Lesser GPL library license. \r
+Whenever there is any discrepancy between the two licenses, \r
+the BSD license will take precedence. See License.txt. \r
+Set tabs to 4 for best viewing.\r
+  \r
+  Latest version is available at http://php.weblogs.com/\r
+  \r
+    Microsoft Access ADO data driver. Requires ADO and ODBC. Works only on MS Windows.\r
+*/\r
+\r
+if (!defined('_ADODB_ADO_LAYER')) {\r
+       include(ADODB_DIR."/adodb-ado.inc.php");\r
+}\r
+\r
+class  ADODB_ado_access extends ADODB_ado {    \r
+       var $databaseType = 'ado_access';\r
+       var $hasTop = true;             // support mssql SELECT TOP 10 * FROM TABLE\r
+       var $fmtDate = "#Y-m-d#";\r
+       var $fmtTimeStamp = "#Y-m-d h:i:sA#";// note no comma\r
+\r
+       function BeginTrans() { return false;}\r
+\r
+}\r
+\r
\r
+class  ADORecordSet_ado_access extends ADORecordSet_ado {      \r
+       \r
+       var $databaseType = "ado_access";               \r
+       \r
+       function ADORecordSet_ado_access(&$id)\r
+       {\r
+               return $this->ADORecordSet_ado($id);\r
+       }\r
+}\r
+?>
\ No newline at end of file
diff --git a/libraries/adodb/adodb-ado_mssql.inc.php b/libraries/adodb/adodb-ado_mssql.inc.php
new file mode 100755 (executable)
index 0000000..024da4c
--- /dev/null
@@ -0,0 +1,36 @@
+<?php\r
+/* \r
+V1.53 13 Nov 2001 (c) 2000, 2001 John Lim (jlim@natsoft.com.my). All rights reserved.\r
+  Released under both BSD license and Lesser GPL library license. \r
+  Whenever there is any discrepancy between the two licenses, \r
+  the BSD license will take precedence. \r
+Set tabs to 4 for best viewing.\r
+  \r
+  Latest version is available at http://php.weblogs.com/\r
+  \r
+  Microsoft SQL Server ADO data driver. Requires ADO and MSSQL client. \r
+  Works only on MS Windows.\r
+  \r
+  It is normally better to use the mssql driver directly because it is much faster. \r
+  This file is only a technology demonstration and for test purposes.\r
+*/\r
+\r
+if (!defined('_ADODB_ADO_LAYER')) {\r
+       include(ADODB_DIR."/adodb-ado.inc.php");\r
+}\r
+\r
+class  ADODB_ado_mssql extends ADODB_ado {     \r
+var $databaseType = 'ado_mssql';\r
+var $hasTop = true;\r
+}\r
\r
+class  ADORecordSet_ado_mssql extends ADORecordSet_ado {       \r
+       \r
+       var $databaseType = 'ado_mssql';\r
+       \r
+       function ADORecordSet_ado_mssql(&$id)\r
+       {\r
+               return $this->ADORecordSet_ado($id);\r
+       }\r
+}\r
+?>
\ No newline at end of file
diff --git a/libraries/adodb/adodb-cryptsession.php b/libraries/adodb/adodb-cryptsession.php
new file mode 100755 (executable)
index 0000000..e13c2e4
--- /dev/null
@@ -0,0 +1,245 @@
+<?php\r
+/*\r
+V1.31 20 August 2001 (c) 2000, 2001 John Lim (jlim@natsoft.com.my). All rights reserved.\r
+  Released under both BSD license and Lesser GPL library license. \r
+  Whenever there is any discrepancy between the two licenses, \r
+  the BSD license will take precedence.\r
+       Made table name configurable - by David Johnson djohnson@inpro.net\r
+    Encryption by Ari Kuorikoski <ari.kuorikoski@finebyte.com>\r
+  Set tabs to 4 for best viewing.\r
+  \r
+  Latest version of ADODB is available at http://php.weblogs.com/adodb\r
+  ======================================================================\r
+  \r
+ This file provides PHP4 session management using the ADODB database\r
+wrapper library.\r
\r
+ Example\r
+ =======\r
\r
+       GLOBAL $HTTP_SESSION_VARS;\r
+       include('adodb.inc.php');\r
+       include('adodb-session.php');\r
+       session_start();\r
+       session_register('AVAR');\r
+       $HTTP_SESSION_VARS['AVAR'] += 1;\r
+       print "<p>\$HTTP_SESSION_VARS['AVAR']={$HTTP_SESSION_VARS['AVAR']}</p>";\r
+\r
\r
+ Installation\r
+ ============\r
+ 1. Create a new database in MySQL or Access "sessions" like\r
+so:\r
\r
+  create table sessions (\r
+       SESSKEY char(32) not null,\r
+       EXPIRY int(11) unsigned not null,\r
+       DATA text not null,\r
+      primary key (sesskey)\r
+  );\r
+  \r
+  2. Then define the following parameters in this file:\r
+       $ADODB_SESSION_DRIVER='database driver, eg. mysql or ibase';\r
+       $ADODB_SESSION_CONNECT='server to connect to';\r
+       $ADODB_SESSION_USER ='user';\r
+       $ADODB_SESSION_PWD ='password';\r
+       $ADODB_SESSION_DB ='database';\r
+       $ADODB_SESSION_TBL = 'sessions'\r
+       \r
+  3. Recommended is PHP 4.0.2 or later. There are documented\r
+session bugs in \r
+     earlier versions of PHP.\r
+\r
+*/\r
+\r
+\r
+include_once('crypt.inc.php');\r
+\r
+if (!defined('_ADODB_LAYER')) {\r
+       include ('adodb.inc.php');\r
+}\r
+\r
+\r
+\r
+if (!defined('ADODB_SESSION')) {\r
+\r
+ define('ADODB_SESSION',1);\r
\r
+GLOBAL         $ADODB_SESSION_CONNECT, \r
+       $ADODB_SESSION_DRIVER,\r
+       $ADODB_SESSION_USER,\r
+       $ADODB_SESSION_PWD,\r
+       $ADODB_SESSION_DB,\r
+       $ADODB_SESS_CONN,\r
+       $ADODB_SESS_LIFE,\r
+       $ADODB_SESS_DEBUG,\r
+       $ADODB_SESS_INSERT; \r
+\r
+       //$ADODB_SESS_DEBUG = true;\r
+       \r
+       /* SET THE FOLLOWING PARAMETERS */\r
+if (empty($ADODB_SESSION_DRIVER)) {\r
+       $ADODB_SESSION_DRIVER='mysql';\r
+       $ADODB_SESSION_CONNECT='serverName';\r
+       $ADODB_SESSION_USER ='PhpSessions';\r
+       $ADODB_SESSION_PWD ='sessions';\r
+       $ADODB_SESSION_DB ='sessions';\r
+}\r
+if (empty($ADODB_SESSION_TBL)){\r
+       $ADODB_SESSION_TBL = 'sessions';\r
+}\r
+\r
+\r
+function ADODB_Session_Key() \r
+{\r
+$ADODB_CRYPT_KEY = 'CRYPTED ADODB SESSIONS ROCK!';\r
+\r
+       /* USE THIS FUNCTION TO CREATE THE ENCRYPTION KEY FOR CRYPTED SESSIONS  */\r
+       /* Crypt the used key, $ADODB_CRYPT_KEY as key and session_ID as SALT   */\r
+       return crypt($ADODB_CRYPT_KEY, session_ID());\r
+}\r
+\r
+$ADODB_SESS_LIFE = get_cfg_var('session.gc_maxlifetime');\r
+if ($ADODB_SESS_LIFE <= 1) {\r
+       // bug in PHP 4.0.3 pl 1  -- how about other versions?\r
+       //print "<h3>Session Error: PHP.INI setting <i>session.gc_maxlifetime</i>not set: $ADODB_SESS_LIFE</h3>";\r
+       $ADODB_SESS_LIFE=1440;\r
+}\r
+\r
+function adodb_sess_open($save_path, $session_name) \r
+{\r
+GLOBAL         $ADODB_SESSION_CONNECT, \r
+       $ADODB_SESSION_DRIVER,\r
+       $ADODB_SESSION_USER,\r
+       $ADODB_SESSION_PWD,\r
+       $ADODB_SESSION_DB,\r
+       $ADODB_SESS_CONN,\r
+       $ADODB_SESS_DEBUG;\r
+       \r
+       $ADODB_SESS_INSERT = false;\r
+       \r
+       if (isset($ADODB_SESS_CONN)) return true;\r
+       \r
+       $ADODB_SESS_CONN = ADONewConnection($ADODB_SESSION_DRIVER);\r
+       if (!empty($ADODB_SESS_DEBUG)) {\r
+               $ADODB_SESS_CONN->debug = true;\r
+               print" conn=$ADODB_SESSION_CONNECT user=$ADODB_SESSION_USER pwd=$ADODB_SESSION_PWD db=$ADODB_SESSION_DB ";\r
+       }\r
+       return $ADODB_SESS_CONN->PConnect($ADODB_SESSION_CONNECT,\r
+                       $ADODB_SESSION_USER,$ADODB_SESSION_PWD,$ADODB_SESSION_DB);\r
+       \r
+}\r
+\r
+function adodb_sess_close() \r
+{\r
+global $ADODB_SESS_CONN;\r
+\r
+       if ($ADODB_SESS_CONN) $ADODB_SESS_CONN->Close();\r
+       return true;\r
+}\r
+\r
+function adodb_sess_read($key) \r
+{\r
+$Crypt = new MD5Crypt;\r
+global $ADODB_SESS_CONN,$ADODB_SESS_INSERT,$ADODB_SESSION_TBL;\r
+       $rs = $ADODB_SESS_CONN->Execute("SELECT data FROM $ADODB_SESSION_TBL WHERE sesskey = '$key' AND expiry >= " . time());\r
+       if ($rs) {\r
+               if ($rs->EOF) {\r
+                       $ADODB_SESS_INSERT = true;\r
+                       $v = '';\r
+               } else {\r
+                       // Decrypt session data\r
+                       $v = rawurldecode($Crypt->Decrypt($rs->fields[0], ADODB_Session_Key()));\r
+               }\r
+               $rs->Close();\r
+               return $v;\r
+       }\r
+       else $ADODB_SESS_INSERT = true;\r
+       \r
+       return false;\r
+}\r
+\r
+function adodb_sess_write($key, $val) \r
+{\r
+$Crypt = new MD5Crypt;\r
+       global $ADODB_SESS_INSERT,$ADODB_SESS_CONN, $ADODB_SESS_LIFE, $ADODB_SESSION_TBL;\r
+\r
+       $expiry = time() + $ADODB_SESS_LIFE;\r
+\r
+       // encrypt session data..       \r
+       $val = $Crypt->Encrypt(rawurlencode($val), ADODB_Session_Key());\r
+       $qry = "UPDATE $ADODB_SESSION_TBL SET expiry=$expiry,data='$val' WHERE sesskey='$key'";\r
+       $rs = $ADODB_SESS_CONN->Execute($qry);\r
+       if ($rs) $rs->Close();\r
+       else print '<p>Session Update: '.$ADODB_SESS_CONN->ErrorMsg().'</p>';\r
+       \r
+       if ($ADODB_SESS_INSERT || $rs === false) {\r
+               $qry = "INSERT INTO $ADODB_SESSION_TBL(sesskey,expiry,data) VALUES ('$key',$expiry,'$val')";\r
+               $rs = $ADODB_SESS_CONN->Execute($qry);\r
+               if ($rs) $rs->Close();\r
+               else print '<p>Session Insert: '.$ADODB_SESS_CONN->ErrorMsg().'</p>';\r
+       }\r
+       // bug in access driver (could be odbc?) means that info is not commited\r
+       // properly unless select statement executed in Win2000\r
+       if ($ADODB_SESS_CONN->databaseType == 'access') $rs = $ADODB_SESS_CONN->Execute("select sesskey from $ADODB_SESSION_TBL WHERE sesskey='$key'");\r
+\r
+       return isset($rs);\r
+}\r
+\r
+function adodb_sess_destroy($key) \r
+{\r
+       global $ADODB_SESS_CONN, $ADODB_SESSION_TBL;\r
+\r
+       $qry = "DELETE FROM $ADODB_SESSION_TBL WHERE sesskey = '$key'";\r
+       $rs = $ADODB_SESS_CONN->Execute($qry);\r
+       if ($rs) $rs->Close();\r
+       return $rs;\r
+}\r
+\r
+function adodb_sess_gc($maxlifetime) {\r
+       global $ADODB_SESS_CONN, $ADODB_SESSION_TBL;\r
+\r
+       $qry = "DELETE FROM $ADODB_SESSION_TBL WHERE expiry < " . time();\r
+       $rs = $ADODB_SESS_CONN->Execute($qry);\r
+       if ($rs) $rs->Close();\r
+       \r
+       // suggested by Cameron, "GaM3R" <gamr@outworld.cx>\r
+       if (defined('ADODB_SESSION_OPTIMIZE'))\r
+       {\r
+               switch( $ADODB_SESSION_DRIVER ) {\r
+                       case 'mysql':\r
+                       case 'mysqlt':\r
+                               $opt_qry = 'OPTIMIZE TABLE '.$ADODB_SESSION_TBL;\r
+                               break;\r
+                       case 'postgresql':\r
+                       case 'postgresql7':\r
+                               $opt_qry = 'VACUUM '.$ADODB_SESSION_TBL;        \r
+                               break;\r
+               }\r
+       }\r
+       \r
+       return true;\r
+}\r
+\r
+session_module_name('user'); \r
+session_set_save_handler(\r
+       "adodb_sess_open",\r
+       "adodb_sess_close",\r
+       "adodb_sess_read",\r
+       "adodb_sess_write",\r
+       "adodb_sess_destroy",\r
+       "adodb_sess_gc");\r
+}\r
+\r
+/*  TEST SCRIPT -- UNCOMMENT */\r
+/*\r
+if (0) {\r
+GLOBAL $HTTP_SESSION_VARS;\r
+\r
+       session_start();\r
+       session_register('AVAR');\r
+       $HTTP_SESSION_VARS['AVAR'] += 1;\r
+       print "<p>\$HTTP_SESSION_VARS['AVAR']={$HTTP_SESSION_VARS['AVAR']}</p>";\r
+}\r
+*/\r
+?>
\ No newline at end of file
diff --git a/libraries/adodb/adodb-csv.inc.php b/libraries/adodb/adodb-csv.inc.php
new file mode 100755 (executable)
index 0000000..e056df0
--- /dev/null
@@ -0,0 +1,147 @@
+<?php\r
+/*\r
+V1.53 13 Nov 2001 (c) 2000, 2001 John Lim (jlim@natsoft.com.my). All rights reserved.\r
+  Released under both BSD license and Lesser GPL library license. \r
+  Whenever there is any discrepancy between the two licenses, \r
+  the BSD license will take precedence.\r
+  Set tabs to 4.\r
+  \r
+  Currently unsupported: MetaDatabases, MetaTables and MetaColumns, and also inputarr in Execute.\r
+  Native types have been converted to MetaTypes.\r
+  Transactions not supported yet.\r
+*/ \r
+\r
+if (! defined("_ADODB_CSV_LAYER")) {\r
+ define("_ADODB_CSV_LAYER", 1 );\r
+\r
+class ADODB_csv extends ADOConnection {\r
+       var $databaseType = 'csv';\r
+    var $hasInsertID = true;\r
+    var $hasAffectedRows = true;       \r
+       var $fmtTimeStamp = "'Y-m-d H:i:s'";\r
+       var $_affectedrows=0;\r
+       var $_insertid=0;\r
+       var $_url;\r
+       var $replaceQuote = "''"; // string to use to replace quotes\r
+       \r
+       function ADODB_csv() \r
+       {                       \r
+       }\r
+       \r
+        function _insertid()\r
+        {\r
+                return $this->_insertid;\r
+        }\r
+        \r
+        function _affectedrows()\r
+        {\r
+                return $this->_affectedrows;\r
+        }\r
+  \r
+       function &MetaDatabases()\r
+       {\r
+               return false;\r
+       }\r
+\r
+       \r
+       // returns true or false\r
+       function _connect($argHostname, $argUsername, $argPassword, $argDatabasename)\r
+       {\r
+               $this->_url = $argHostname;\r
+               return true;    \r
+       }\r
+       \r
+       // returns true or false\r
+       function _pconnect($argHostname, $argUsername, $argPassword, $argDatabasename)\r
+       {\r
+               $this->_url = $argHostname;\r
+               return true;\r
+       }\r
+       \r
+       function &MetaColumns($table) \r
+       {\r
+               return false;\r
+       }\r
+               \r
+               \r
+       // parameters use PostgreSQL convention, not MySQL\r
+       function &SelectLimit($sql,$nrows=-1,$offset=-1,$arg3=false)\r
+       {\r
+               $url = $this->_url.'?sql='.urlencode($sql)."&nrows=$nrows&$offset=&offset&arg3=".urlencode($arg3);\r
+               $err = false;\r
+               $rs = csv2rs($url,$err,false);\r
+               if ($this->debug) print "$url<br><i>$err</i><br>";\r
+\r
+               $at = strpos($err,'::::');\r
+               if ($at === false) {            \r
+                       $this->_errorMsg = $err;\r
+                       $this->_errorNo = (integer)$err;\r
+               } else {\r
+                       $this->_errorMsg = substr($err,$at+4,1024);\r
+                       $this->_errorNo = -9999;\r
+               }\r
+               if (is_object($rs)) {\r
+                       $rs->databaseType='csv';\r
+               }\r
+               return $rs;\r
+       }\r
+       \r
+       // returns queryID or false\r
+       function Execute($sql,$inputarr=false,$arg3=false)\r
+       {\r
+               $url =  $this->_url.'?sql='.urlencode($sql);\r
+               if ($arg3) $url .= "&arg3=".urlencode($arg3);\r
+               $err = false;\r
+               \r
+               $rs = csv2rs($url,$err,false);\r
+               if ($this->debug) print urldecode($url)."<br><i>$err</i><br>";\r
+               $at = strpos($err,'::::');\r
+               if ($at === false) {            \r
+                       $this->_errorMsg = $err;\r
+                       $this->_errorNo = (integer)$err;\r
+               } else {\r
+                       $this->_errorMsg = substr($err,$at+4,1024);\r
+                       $this->_errorNo = -9999;\r
+               }\r
+               if (is_object($rs)) {\r
+                       $this->_affectedrows = $rs->affectedrows;\r
+                       $this->_insertid = $rs->insertid;\r
+                       $rs->databaseType='csv';\r
+               }\r
+               return $rs;\r
+       }\r
+\r
+       /*      Returns: the last error message from previous database operation        */      \r
+       function ErrorMsg() \r
+       {\r
+               return $this->_errorMsg;\r
+       }\r
+       \r
+       /*      Returns: the last error number from previous database operation */      \r
+       function ErrorNo() \r
+       {\r
+               return $this->_errorNo;\r
+       }\r
+       \r
+       // returns true or false\r
+       function _close()\r
+       {\r
+               return true;\r
+       }\r
+} // class\r
+\r
+class ADORecordset_csv extends ADORecordset {\r
+       function ADORecordset_csv($id)\r
+       {\r
+               $this->ADORecordset($id);\r
+       }\r
+       \r
+       function _close()\r
+       {\r
+               return true;\r
+       }\r
+}\r
+\r
+} // define\r
+       \r
+?>
\ No newline at end of file
diff --git a/libraries/adodb/adodb-db2.inc.php b/libraries/adodb/adodb-db2.inc.php
new file mode 100755 (executable)
index 0000000..7bf5702
--- /dev/null
@@ -0,0 +1,163 @@
+<?php\r
+/* \r
+V1.53 13 Nov 2001 (c) 2000, 2001 John Lim (jlim@natsoft.com.my). All rights reserved.\r
+  Released under both BSD license and Lesser GPL library license. \r
+  Whenever there is any discrepancy between the two licenses, \r
+  the BSD license will take precedence. \r
+Set tabs to 4 for best viewing.\r
+  \r
+  Latest version is available at http://php.weblogs.com/\r
+  \r
+  DB2 data driver. Requires ODBC.\r
\r
+From phpdb list:\r
+\r
+Hi Andrew,\r
+\r
+thanks a lot for your help. Today we discovered what\r
+our real problem was:\r
+\r
+After "playing" a little bit with the php-scripts that try\r
+to connect to the IBM DB2, we set the optional parameter\r
+Cursortype when calling odbc_pconnect(....).\r
+\r
+And the exciting thing: When we set the cursor type\r
+to SQL_CUR_USE_ODBC Cursor Type, then\r
+the whole query speed up from 1 till 10 seconds\r
+to 0.2 till 0.3 seconds for 100 records. Amazing!!!\r
+\r
+Therfore, PHP is just almost fast as calling the DB2\r
+from Servlets using JDBC (don't take too much care\r
+about the speed at whole: the database was on a\r
+completely other location, so the whole connection\r
+was made over a slow network connection).\r
+\r
+I hope this helps when other encounter the same\r
+problem when trying to connect to DB2 from\r
+PHP.\r
+\r
+Kind regards,\r
+Christian Szardenings\r
+\r
+2 Oct 2001\r
+Mark Newnham has discovered that the SQL_CUR_USE_ODBC is not supported by \r
+IBM's DB2 ODBC driver, so this must be a 3rd party ODBC driver.\r
+\r
+From the IBM CLI Reference:\r
+\r
+SQL_ATTR_ODBC_CURSORS (DB2 CLI v5) \r
+This connection attribute is defined by ODBC, but is not supported by DB2\r
+CLI. Any attempt to set or get this attribute will result in an SQLSTATE of\r
+HYC00 (Driver not capable). \r
+\r
+A 32-bit option specifying how the Driver Manager uses the ODBC cursor\r
+library. \r
+\r
+So I guess this means the message below was related to using a 3rd party\r
+odbc driver.\r
+\r
+*/\r
+\r
+if (!defined('_ADODB_ODBC_LAYER')) {\r
+       include(ADODB_DIR."/adodb-odbc.inc.php");\r
+}\r
+if (!defined('ADODB_DB2')){\r
+define('ADODB_DB2',1);\r
+class ADODB_DB2 extends ADODB_odbc {\r
+       var $databaseType = "db2";      \r
+       var $concat_operator = 'CONCAT';\r
+       //var $curmode = SQL_CUR_USE_ODBC;\r
+\r
+// returns true or false\r
+// curmode is not properly supported by DB2 odbc driver according to Mark Newnham\r
+       function _connect($argDSN, $argUsername, $argPassword, $argDatabasename)\r
+       {\r
+       global $php_errormsg;\r
+       \r
+               $php_errormsg = '';\r
+               $this->_connectionID = odbc_connect($argDSN,$argUsername,$argPassword);\r
+               $this->_errorMsg = $php_errormsg;\r
+\r
+               //if ($this->_connectionID) odbc_autocommit($this->_connectionID,true);\r
+               return $this->_connectionID != false;\r
+       }\r
+       // returns true or false\r
+       function _pconnect($argDSN, $argUsername, $argPassword, $argDatabasename)\r
+       {\r
+       global $php_errormsg;\r
+               $php_errormsg = '';\r
+               $this->_connectionID = odbc_pconnect($argDSN,$argUsername,$argPassword);\r
+               $this->_errorMsg = $php_errormsg;\r
+               \r
+               //if ($this->_connectionID) odbc_autocommit($this->_connectionID,true);\r
+               return $this->_connectionID != false;\r
+       }\r
+       \r
+       function &SelectLimit($sql,$nrows=-1,$offset=-1,$arg3=false)\r
+       {\r
+               if ($offset <= 0) {\r
+               // could also use " OPTIMIZE FOR $nrows ROWS "\r
+                       $sql .=  " FETCH FIRST $nrows ROWS ONLY ";\r
+                       return $this->Execute($sql,false,$arg3);\r
+               } else\r
+                       return ADOConnection::SelectLimit($sql,$nrows,$offset,$arg3);\r
+       }\r
+       \r
+};\r
\r
+\r
+class  ADORecordSet_db2 extends ADORecordSet_odbc {    \r
+       \r
+       var $databaseType = "db2";              \r
+       \r
+       function ADORecordSet_db2($id)\r
+       {\r
+               $this->ADORecordSet_odbc($id);\r
+       }\r
+\r
+       function MetaType($t,$len=-1,$fieldobj=false)\r
+       {\r
+               switch (strtoupper($t)) {\r
+               case 'VARCHAR':\r
+               case 'CHAR':\r
+               case 'CHARACTER':\r
+                       if ($len <= $this->blobSize) return 'C';\r
+               \r
+               case 'LONGCHAR':\r
+               case 'TEXT':\r
+               case 'CLOB':\r
+               case 'DBCLOB': // double-byte\r
+                       return 'X';\r
+               \r
+               case 'BLOB':\r
+               case 'GRAPHIC':\r
+               case 'VARGRAPHIC':\r
+                       return 'B';\r
+                       \r
+               case 'DATE':\r
+                       return 'D';\r
+               \r
+               case 'TIME':\r
+               case 'TIMESTAMP':\r
+                       return 'T';\r
+               \r
+               //case 'BOOLEAN': \r
+               //case 'BIT':\r
+               //      return 'L';\r
+                       \r
+               //case 'COUNTER':\r
+               //      return 'R';\r
+                       \r
+               case 'INT':\r
+               case 'INTEGER':\r
+               case 'BIGINT':\r
+               case 'SMALLINT':\r
+                       return 'I';\r
+                       \r
+               default: return 'N';\r
+               }\r
+       }\r
+}\r
+\r
+} //define\r
+?>
\ No newline at end of file
diff --git a/libraries/adodb/adodb-errorhandler.inc.php b/libraries/adodb/adodb-errorhandler.inc.php
new file mode 100755 (executable)
index 0000000..71e7449
--- /dev/null
@@ -0,0 +1,73 @@
+<?php\r
+/**\r
+ * @version V1.53 13 Nov 2001  (c) 2000, 2001 John Lim (jlim@natsoft.com.my). All rights reserved.\r
+ * Released under both BSD license and Lesser GPL library license.\r
+  Whenever there is any discrepancy between the two licenses,\r
+  the BSD license will take precedence.\r
+ *\r
+ * Set tabs to 4 for best viewing.\r
+ *\r
+ * Latest version is available at http://php.weblogs.com\r
+ *\r
+*/\r
+\r
+define('ADODB_ERROR_HANDLER','ADODB_Error_Handler');\r
+\r
+  /**\r
+* Default Error Handler. This will be called with the following params\r
+*\r
+* @param $dbms         the RDBMS you are connecting to\r
+* @param $fn           the name of the calling function (in uppercase)\r
+* @param $errno                the native error number from the database\r
+* @param $errmsg       the native error msg from the database\r
+* @param $p1           $fn specific parameter - see below\r
+* @param $P2           $fn specific parameter - see below\r
+       */\r
+function ADODB_Error_Handler($dbms, $fn, $errno, $errmsg, $p1=false, $p2=false)\r
+{\r
+       switch($fn) {\r
+       case 'EXECUTE':\r
+               $sql = $p1;\r
+               $inputparams = $p2;\r
+\r
+               $s = "$dbms error: [$errno: $errmsg] in $fn(\"$sql\")\n";\r
+               break;\r
+\r
+       case 'PCONNECT':\r
+       case 'CONNECT':\r
+               $host = $p1;\r
+               $database = $p2;\r
+\r
+               $s = "$dbms error: [$errno: $errmsg] in $fn($host, ?, ?, $database)\n";\r
+               break;\r
+       default:\r
+               $s = "$dbms error: [$errno: $errmsg] in $fn($p1, $p2)\n";\r
+               break;\r
+       }\r
+       /*\r
+       * Log connection error somewhere\r
+       *       0 message is sent to PHP's system logger, using the Operating System's system\r
+       *               logging mechanism or a file, depending on what the error_log configuration\r
+       *               directive is set to.\r
+       *       1 message is sent by email to the address in the destination parameter.\r
+       *               This is the only message type where the fourth parameter, extra_headers is used.\r
+       *               This message type uses the same internal function as mail() does.\r
+       *       2 message is sent through the PHP debugging connection.\r
+       *               This option is only available if remote debugging has been enabled.\r
+       *               In this case, the destination parameter specifies the host name or IP address\r
+       *               and optionally, port number, of the socket receiving the debug information.\r
+       *       3 message is appended to the file destination\r
+       */\r
+       if (defined('ADODB_ERROR_LOG_TYPE')) {\r
+               $t = date('Y-m-d H:i:s');\r
+               if (defined('ADODB_ERROR_LOG_DEST'))\r
+                       error_log("($t) $s", ADODB_ERROR_LOG_TYPE, ADODB_ERROR_LOG_DEST);\r
+               else\r
+                       error_log("($t) $s", ADODB_ERROR_LOG_TYPE);\r
+       }\r
+\r
+\r
+       //print "<p>$s</p>";\r
+       trigger_error($s,E_USER_ERROR);\r
+}\r
+?>\r
diff --git a/libraries/adodb/adodb-errorpear.inc.php b/libraries/adodb/adodb-errorpear.inc.php
new file mode 100755 (executable)
index 0000000..19b049f
--- /dev/null
@@ -0,0 +1,86 @@
+<?php\r
+/** \r
+ * @version V1.53 13 Nov 2001 (c) 2000, 2001 John Lim (jlim@natsoft.com.my). All rights reserved.\r
+ * Released under both BSD license and Lesser GPL library license. \r
+  Whenever there is any discrepancy between the two licenses, \r
+  the BSD license will take precedence. \r
+ *\r
+ * Set tabs to 4 for best viewing.\r
+ * \r
+ * Latest version is available at http://php.weblogs.com\r
+ * \r
+*/\r
+include_once('PEAR.php');\r
+\r
+define('ADODB_ERROR_HANDLER','ADODB_Error_PEAR');\r
+\r
+/*\r
+* Enabled the following if you want to terminate scripts when an error occurs\r
+*/\r
+//PEAR::setErrorHandling (PEAR_ERROR_DIE);\r
+\r
+/*\r
+* Name of the PEAR_Error derived class to call.\r
+*/\r
+if (!defined('ADODB_PEAR_ERROR_CLASS')) define('ADODB_PEAR_ERROR_CLASS','PEAR_Error');\r
+\r
+/*\r
+* Store the last PEAR_Error object here\r
+*/\r
+global $ADODB_Last_PEAR_Error; $ADODB_Last_PEAR_Error = false;\r
+\r
+  /**\r
+* Error Handler with PEAR support. This will be called with the following params\r
+*\r
+* @param $dbms         the RDBMS you are connecting to\r
+* @param $fn           the name of the calling function (in uppercase)\r
+* @param $errno                the native error number from the database \r
+* @param $errmsg       the native error msg from the database\r
+* @param $p1           $fn specific parameter - see below\r
+* @param $P2           $fn specific parameter - see below\r
+       */\r
+function ADODB_Error_PEAR($dbms, $fn, $errno, $errmsg, $p1=false, $p2=false)\r
+{\r
+global $ADODB_Last_PEAR_Error;\r
+       switch($fn) {\r
+       case 'EXECUTE':\r
+               $sql = $p1;\r
+               $inputparams = $p2;\r
+               \r
+               $s = "$dbms error: [$errno: $errmsg] in $fn(\"$sql\")";\r
+               break;\r
+               \r
+       case 'PCONNECT':\r
+       case 'CONNECT':\r
+               $host = $p1;\r
+               $database = $p2;\r
+               \r
+               $s = "$dbms error: [$errno: $errmsg] in $fn($host, ?, ?, $database)";\r
+               break;\r
+               \r
+       default:\r
+               $s = "$dbms error: [$errno: $errmsg] in $fn($p1, $p2)";\r
+               break;\r
+       }\r
+       \r
+       $class = ADODB_PEAR_ERROR_CLASS;\r
+       $ADODB_Last_PEAR_Error = new $class($s, $errno,\r
+               $GLOBALS['_PEAR_default_error_mode'],\r
+               $GLOBALS['_PEAR_default_error_options'], \r
+               $errmsg);\r
+               \r
+       //print "<p>!$s</p>";\r
+}\r
+\r
+/**\r
+* Returns last PEAR_Error object. This error might be for an error that\r
+* occured several sql statements ago.\r
+*/\r
+function &ADODB_PEAR_Error()\r
+{\r
+global $ADODB_Last_PEAR_Error;\r
+\r
+       return $ADODB_Last_PEAR_Error;\r
+}\r
+               \r
+?>
\ No newline at end of file
diff --git a/libraries/adodb/adodb-fbsql.inc.php b/libraries/adodb/adodb-fbsql.inc.php
new file mode 100755 (executable)
index 0000000..a1f894f
--- /dev/null
@@ -0,0 +1,251 @@
+<?php\r
+/*\r
+ @version V1.53 13 Nov 2001 (c) 2000, 2001 John Lim (jlim@natsoft.com.my). All rights reserved.\r
+ Released under both BSD license and Lesser GPL library license. \r
+  Whenever there is any discrepancy between the two licenses, \r
+  the BSD license will take precedence. \r
+ Contribution by Frank M. Kromann <frank@frontbase.com>. \r
+  Set tabs to 8.\r
+*/ \r
+\r
+if (! defined("_ADODB_FBSQL_LAYER")) {\r
+ define("_ADODB_FBSQL_LAYER", 1 );\r
+\r
+class ADODB_fbsql extends ADOConnection {\r
+       var $databaseType = 'fbsql';\r
+        var $hasInsertID = true;\r
+        var $hasAffectedRows = true;   \r
+       var $metaTablesSQL = "SHOW TABLES";     \r
+       var $metaColumnsSQL = "SHOW COLUMNS FROM %s";\r
+       var $fmtTimeStamp = "'Y-m-d H:i:s'";\r
+       var $hasLimit = false;\r
+       \r
+       function ADODB_fbsql() \r
+       {                       \r
+       }\r
+       \r
+        function _insertid()\r
+        {\r
+                return fbsql_insert_id($this->_connectionID);\r
+        }\r
+        \r
+        function _affectedrows()\r
+        {\r
+                return fbsql_affected_rows($this->_connectionID);\r
+        }\r
+  \r
+       function &MetaDatabases()\r
+       {\r
+               $qid = fbsql_list_dbs($this->_connectionID);\r
+               $arr = array();\r
+               $i = 0;\r
+               $max = fbsql_num_rows($qid);\r
+               while ($i < $max) {\r
+                       $arr[] = fbsql_tablename($qid,$i);\r
+                       $i += 1;\r
+               }\r
+               return $arr;\r
+       }\r
+\r
+       // returns concatenated string\r
+       function Concat()\r
+       {\r
+               $s = "";\r
+               $arr = func_get_args();\r
+               $first = true;\r
+\r
+               foreach($arr as $a) {\r
+                       if ($first) {\r
+                               $s = $a;\r
+                               $first = false;\r
+                       } else $s .= ','.$a;\r
+               }\r
+               if (sizeof($s) > 0) return "CONCAT($s)";\r
+               else return '';\r
+       }\r
+       \r
+       // returns true or false\r
+       function _connect($argHostname, $argUsername, $argPassword, $argDatabasename)\r
+       {\r
+               $this->_connectionID = fbsql_connect($argHostname,$argUsername,$argPassword);\r
+               if ($this->_connectionID === false) return false;\r
+               if ($argDatabasename) return $this->SelectDB($argDatabasename);\r
+               return true;    \r
+       }\r
+       \r
+       // returns true or false\r
+       function _pconnect($argHostname, $argUsername, $argPassword, $argDatabasename)\r
+       {\r
+               $this->_connectionID = fbsql_pconnect($argHostname,$argUsername,$argPassword);\r
+               if ($this->_connectionID === false) return false;\r
+               if ($argDatabasename) return $this->SelectDB($argDatabasename);\r
+               return true;    \r
+       }\r
+       \r
+       function &MetaColumns($table) \r
+       {\r
+               if ($this->metaColumnsSQL) {\r
+               \r
+                       $rs = $this->Execute(sprintf($this->metaColumnsSQL,$table));\r
+                       \r
+                       if ($rs === false) return false;\r
+                       \r
+                       $retarr = array();\r
+                       while (!$rs->EOF){\r
+                               $fld = new ADOFieldObject();\r
+                               $fld->name = $rs->fields[0];\r
+                               $fld->type = $rs->fields[1];\r
+                                       \r
+                               // split type into type(length):\r
+                               if (preg_match("/^(.+)\((\d+)\)$/", $fld->type, $query_array)) {\r
+                                       $fld->type = $query_array[1];\r
+                                       $fld->max_length = $query_array[2];\r
+                               } else {\r
+                                       $fld->max_length = -1;\r
+                               }\r
+                               $fld->not_null = ($rs->fields[2] != 'YES');\r
+                               $fld->primary_key = ($rs->fields[3] == 'PRI');\r
+                               $fld->auto_increment = (strpos($rs->fields[5], 'auto_increment') !== false);\r
+                               $fld->binary = (strpos($fld->type,'blob') !== false);\r
+                               \r
+                               $retarr[strtoupper($fld->name)] = $fld; \r
+                               $rs->MoveNext();\r
+                       }\r
+                       $rs->Close();\r
+                       return $retarr; \r
+               }\r
+               return false;\r
+       }\r
+               \r
+       // returns true or false\r
+       function SelectDB($dbName) \r
+       {\r
+               $this->databaseName = $dbName;\r
+               if ($this->_connectionID) {\r
+                       return @fbsql_select_db($dbName,$this->_connectionID);          \r
+               }\r
+               else return false;      \r
+       }\r
+       \r
+       \r
+       // returns queryID or false\r
+       function _query($sql,$inputarr)\r
+       {\r
+               return fbsql_query("$sql;",$this->_connectionID);\r
+       }\r
+\r
+       /*      Returns: the last error message from previous database operation        */      \r
+       function ErrorMsg() \r
+       {\r
+               $this->_errorMsg = @fbsql_error($this->_connectionID);\r
+               return $this->_errorMsg;\r
+       }\r
+       \r
+       /*      Returns: the last error number from previous database operation */      \r
+       function ErrorNo() \r
+       {\r
+               return @fbsql_errno($this->_connectionID);\r
+       }\r
+       \r
+       // returns true or false\r
+       function _close()\r
+       {\r
+               return @fbsql_close($this->_connectionID);\r
+       }\r
+               \r
+}\r
+       \r
+/*--------------------------------------------------------------------------------------\r
+        Class Name: Recordset\r
+--------------------------------------------------------------------------------------*/\r
+\r
+class ADORecordSet_fbsql extends ADORecordSet{ \r
+       \r
+       var $databaseType = "fbsql";\r
+       var $canSeek = true;\r
+       \r
+       function ADORecordSet_fbsql($queryID) {\r
+               return $this->ADORecordSet($queryID);\r
+       }\r
+       \r
+       function _initrs()\r
+       {\r
+       GLOBAL $ADODB_COUNTRECS;\r
+               $this->_numOfRows = ($ADODB_COUNTRECS) ? @fbsql_num_rows($this->_queryID):-1;\r
+               $this->_numOfFields = @fbsql_num_fields($this->_queryID);\r
+       }\r
+       \r
+\r
+\r
+       function &FetchField($fieldOffset = -1) {\r
+               if ($fieldOffset != -1) {\r
+                       $o =  @fbsql_fetch_field($this->_queryID, $fieldOffset);\r
+                       //$o->max_length = -1; // fbsql returns the max length less spaces -- so it is unrealiable\r
+                       $f = @fbsql_field_flags($this->_queryID,$fieldOffset);\r
+                       $o->binary = (strpos($f,'binary')!== false);\r
+               }\r
+               else if ($fieldOffset == -1) {  /*      The $fieldOffset argument is not provided thus its -1   */\r
+                       $o = @fbsql_fetch_field($this->_queryID);// fbsql returns the max length less spaces -- so it is unrealiable\r
+                       //$o->max_length = -1;\r
+               }\r
+               \r
+               return $o;\r
+       }\r
+               \r
+       function _seek($row)\r
+       {\r
+               return @fbsql_data_seek($this->_queryID,$row);\r
+       }\r
+       \r
+       function _fetch($ignore_fields=false)\r
+       {\r
+               $this->fields = @fbsql_fetch_array($this->_queryID);\r
+               return ($this->fields == true);\r
+       }\r
+       \r
+       function _close() {\r
+               return @fbsql_free_result($this->_queryID);             \r
+       }\r
+       \r
+       function MetaType($t,$len=-1,$fieldobj=false)\r
+       {\r
+               $len = -1; // fbsql max_length is not accurate\r
+               switch (strtoupper($t)) {\r
+               case 'CHARACTER':\r
+               case 'CHARACTER VARYING': \r
+               case 'BLOB': \r
+               case 'CLOB': \r
+               case 'BIT': \r
+               case 'BIT VARYING': \r
+                       if ($len <= $this->blobSize) return 'C';\r
+                       \r
+               // so we have to check whether binary...\r
+               case 'IMAGE':\r
+               case 'LONGBLOB': \r
+               case 'BLOB':\r
+               case 'MEDIUMBLOB':\r
+                       return !empty($fieldobj->binary) ? 'B' : 'X';\r
+                       \r
+               case 'DATE': return 'D';\r
+               \r
+               case 'TIME':\r
+               case 'TIME WITH TIME ZONE':\r
+               case 'TIMESTAMP': \r
+               case 'TIMESTAMP WITH TIME ZONE': return 'T';\r
+               \r
+               case 'PRIMARY_KEY':\r
+                       return 'R';\r
+               case 'INTEGER':\r
+               case 'SMALLINT': \r
+               case 'BOOLEAN':\r
+                       \r
+                       if (!empty($fieldobj->primary_key)) return 'R';\r
+                       else return 'I';\r
+               \r
+               default: return 'N';\r
+               }\r
+       }\r
+\r
+} //class\r
+} // defined\r
+?>
\ No newline at end of file
diff --git a/libraries/adodb/adodb-ibase.inc.php b/libraries/adodb/adodb-ibase.inc.php
new file mode 100755 (executable)
index 0000000..2e5e7e7
--- /dev/null
@@ -0,0 +1,349 @@
+<?php\r
+/*\r
+V1.53 13 Nov 2001 (c) 2000, 2001 John Lim (jlim@natsoft.com.my). All rights reserved.  \r
+  Released under both BSD license and Lesser GPL library license. \r
+  Whenever there is any discrepancy between the two licenses, \r
+  the BSD license will take precedence.\r
+\r
+  Latest version is available at http://php.weblogs.com/\r
+  \r
+  Interbase data driver. Requires interbase client. Works on Windows and Unix.\r
+\r
+  3 Jan 2001 -- suggestions by Hans-Peter Oeri <kampfcaspar75@oeri.ch>\r
+       changed transaction handling and added experimental blob stuff\r
+  \r
+  Docs to interbase at the website\r
+   http://www.synectics.co.za/php3/tutorial/IB_PHP3_API.html\r
+   \r
+  To use gen_id(), see\r
+   http://www.volny.cz/iprenosil/interbase/ip_ib_code.htm#_code_creategen\r
+   \r
+   $rs = $conn->Execute('select gen_id(adodb,1) from rdb$database');\r
+   $id = $rs->fields[0];\r
+   $conn->Execute("insert into table (id, col1,...) values ($id, $val1,...)");\r
+*/\r
+\r
+class ADODB_ibase extends ADOConnection {\r
+    var $databaseType = "ibase";\r
+    var $replaceQuote = "\'"; // string to use to replace quotes\r
+    var $fmtDate = "'Y-m-d'";\r
+    var $fmtTimeStamp = "'Y-m-d, H:i:s'";\r
+    var $concat_operator='||';\r
+    var $_transactionID;\r
+       var $metaTablesSQL = "select rdb\$relation_name from rdb\$relations where rdb\$relation_name not like 'RDB\$%'";\r
+       var $metaColumnsSQL = "select a.rdb\$field_name,b.rdb\$field_type,b.rdb\$field_length from rdb\$relation_fields a join rdb\$fields b on a.rdb\$field_source=b.rdb\$field_name where rdb\$relation_name ='%s'";\r
+       var $ibasetrans = IBASE_DEFAULT;\r
+       var $hasGenID = true;\r
+       var $_bindInputArray = true;\r
+       \r
+       // note the generator starts from 0, unlike others which start from 1\r
+       var $_genIDSQL = "SELECT Gen_ID(%s,1) FROM RDB\$DATABASE";\r
+       var $_genSeqSQL = "INSERT INTO RDB\$GENERATORS (RDB\$GENERATOR_NAME) VALUES (UPPER('%s'))";\r
+\r
+    function ADODB_ibase() \r
+       {\r
+        ibase_timefmt('%Y-%m-%d');\r
+       }\r
+\r
+    function BeginTrans()\r
+       {      \r
+               //return false; // currently not working properly\r
+               \r
+            $this->autoCommit = false;\r
+               $this->_transactionID = $this->_connectionID;//ibase_trans($this->ibasetrans, $this->_connectionID);\r
+               return $this->_transactionID;\r
+       }\r
+       \r
+       function CommitTrans()\r
+       {\r
+               $ret = false;\r
+               $this->autoCommit = true;\r
+               if ($this->_transactionID) {\r
+                               //print ' commit ';\r
+                       $ret = ibase_commit($this->_transactionID);\r
+               }\r
+               $this->_transactionID = false;\r
+               return $ret;\r
+       }\r
+       \r
+       function RollbackTrans()\r
+       {\r
+               $ret = false;\r
+               $this->autoCommit = true;\r
+               if ($this->_transactionID) \r
+                     $ret = ibase_rollback($this->_transactionID);\r
+               $this->_transactionID = false;   \r
+               \r
+               return $ret;\r
+       }\r
+\r
+        function SelectDB($dbName) {\r
+               return false;\r
+        }\r
+\r
+       function _handleerror()\r
+       {\r
+               $this->_errorMsg = ibase_errmsg($this->_connectionID);\r
+       }\r
+\r
+        function ErrorNo() {\r
+               if (preg_match('/error code = ([\-0-9]*)/i', $this->_errorMsg,$arr)) return (integer) $arr[1];\r
+               else return 0;\r
+        }\r
+       \r
+        function ErrorMsg() {\r
+                return $this->_errorMsg;\r
+        }\r
+       \r
+        // returns true or false\r
+        function _connect($argHostname, $argUsername, $argPassword, $argDatabasename)\r
+        {  \r
+               if ($this->charSet)\r
+                       $this->_connectionID = ibase_connect($argHostname,$argUsername,$argPassword,$this->charSet);\r
+               else        \r
+                       $this->_connectionID = ibase_connect($argHostname,$argUsername,$argPassword);\r
+               \r
+               if ($this->_connectionID === false) {\r
+                       $this->_handleerror();\r
+                       return false;\r
+               }\r
+               \r
+                return true;\r
+        }\r
+        // returns true or false\r
+        function _pconnect($argHostname, $argUsername, $argPassword, $argDatabasename)\r
+        {\r
+                       if ($this->charSet)\r
+                               $this->_connectionID = ibase_pconnect($argHostname,$argUsername,$argPassword,$this->charSet);\r
+               else        \r
+                               $this->_connectionID = ibase_pconnect($argHostname,$argUsername,$argPassword);\r
+                    \r
+               if ($this->_connectionID === false) {\r
+                               $this->_handleerror();\r
+                               return false;\r
+                       }\r
+          \r
+            return true;\r
+        }\r
+\r
+        // returns query ID if successful, otherwise false\r
+        function _query($sql,$iarr=false)\r
+        { \r
+               if (!$this->autoCommit && $this->_transactionID) {\r
+                       if (is_array($iarr)) {  \r
+                               switch(sizeof($iarr)) {\r
+                               case 1: $ret = ibase_query($this->_transactionID,$sql,$iarr[0]); break;\r
+                               case 2: $ret = ibase_query($this->_transactionID,$sql,$iarr[0],$iarr[1]); break;\r
+                               case 3: $ret = ibase_query($this->_transactionID,$sql,$iarr[0],$iarr[1],$iarr[2]); break;\r
+                               case 4: $ret = ibase_query($this->_transactionID,$sql,$iarr[0],$iarr[1],$iarr[2],$iarr[3]); break;\r
+                               default: print "<p>Too many parameters to ibase query $sql</p>";\r
+                               case 5: $ret = ibase_query($this->_transactionID,$sql,$iarr[0],$iarr[1],$iarr[2],$iarr[3],$iarr[4]); break;\r
+                               }\r
+                       } else $ret = ibase_query($this->_transactionID,$sql); \r
+               } else {\r
+                       if (is_array($iarr)) {\r
+                               switch(sizeof($iarr)) {\r
+                               case 1: $ret = ibase_query($this->_connectionID,$sql,$iarr[0]); break;\r
+                               case 2: $ret = ibase_query($this->_connectionID,$sql,$iarr[0],$iarr[1]); break;\r
+                               case 3: $ret = ibase_query($this->_connectionID,$sql,$iarr[0],$iarr[1],$iarr[2]); break;\r
+                               case 4: $ret = ibase_query($this->_connectionID,$sql,$iarr[0],$iarr[1],$iarr[2],$iarr[3]); break;\r
+                               default: print "<p>Too many parameters to ibase query $sql</p>";\r
+                               case 5: $ret = ibase_query($this->_connectionID,$sql,$iarr[0],$iarr[1],$iarr[2],$iarr[3],$iarr[4]); break;\r
+                               \r
+                               } \r
+                       } else $ret = ibase_query($this->_connectionID,$sql);\r
+            if ($ret === true) ibase_commit($this->_connectionID);\r
+               }\r
+               $this->_handleerror();\r
+        return $ret;\r
+    }\r
+\r
+     // returns true or false\r
+     function _close()\r
+     {       \r
+        if ($this->autoCommit) ibase_commit($this->_connectionID);\r
+               else ibase_rollback($this->_connectionID);\r
+\r
+        return @ibase_close($this->_connectionID);\r
+     }\r
+       \r
+        // returns array of ADOFieldObjects for current table\r
+       function &MetaColumns($table) \r
+       {\r
+       \r
+               if ($this->metaColumnsSQL) {\r
+               \r
+                       $rs = $this->Execute(sprintf($this->metaColumnsSQL,strtoupper($table)));\r
+                       if ($rs === false) return false;\r
+\r
+                       $retarr = array();\r
+                       while (!$rs->EOF) { //print_r($rs->fields);\r
+                               $fld = new ADOFieldObject();\r
+                               $fld->name = $rs->fields[0];\r
+                               $tt = $rs->fields[1];\r
+                               switch($tt)\r
+                               {\r
+                               case 7:\r
+                               case 8:\r
+                               case 9:$tt = 'INTEGER'; break;\r
+                               case 10:\r
+                               case 27:\r
+                               case 11:$tt = 'FLOAT'; break;\r
+                               default:\r
+                               case 40:\r
+                               case 14:$tt = 'CHAR'; break;\r
+                               case 35:$tt = 'DATE'; break;\r
+                               case 37:$tt = 'VARCHAR'; break;\r
+                               case 261:$tt = 'BLOB'; break;\r
+                               case 13:\r
+                               case 35:$tt = 'TIMESTAMP'; break;\r
+                               }\r
+                               $fld->type = $tt;\r
+                               $fld->max_length = $rs->fields[2];\r
+                               $retarr[strtoupper($fld->name)] = $fld; \r
+                               \r
+                               $rs->MoveNext();\r
+                       }\r
+                       $rs->Close();\r
+                       return $retarr; \r
+               }\r
+               return false;\r
+       }\r
+       \r
+       // warning - this code is experimental and might not be available in the future\r
+       function &BlobEncode( $blob ) \r
+       {\r
+               $blobid = ibase_blob_create( $this->_connectionID);\r
+               ibase_blob_add( $blobid, $blob );\r
+               return ibase_blob_close( $blobid );\r
+       }\r
+       \r
+       // warning - this code is experimental and might not be available in the future\r
+       function &BlobDecode( $blob ) \r
+       {\r
+               $blobid = ibase_blob_open( $blob );\r
+               $realblob = ibase_blob_get( $blobid,299999); // 2nd param is max size of blob -- Kevin Boillet <kevinboillet@yahoo.fr>\r
+               ibase_blob_close( $blobid );\r
+\r
+               return( $realblob );\r
+       } \r
+       \r
+       /*\r
+               Insert a null into the blob field of the table first.\r
+               Then use UpdateBlob to store the blob.\r
+               \r
+               Usage:\r
+                \r
+               $conn->Execute('INSERT INTO blobtable (id, blobcol) VALUES (1, null)');\r
+               $conn->UpdateBlob('blobtable','blobcol',$blob,'id=1');\r
+       */\r
+       function UpdateBlob($table,$column,$val,$where,$blobtype='BLOB')\r
+       {\r
+               $blob_id = ibase_blob_create($this->_connectionID);\r
+               ibase_blob_add($blob_id, $val);\r
+               $blob_id_str = ibase_blob_close($blob_id);\r
+               return $this->Execute("UPDATE $table SET $column=(?) WHERE $where",array($blob_id_str)) != false;\r
+       }\r
+}\r
+\r
+/*--------------------------------------------------------------------------------------\r
+         Class Name: Recordset\r
+--------------------------------------------------------------------------------------*/\r
+\r
+class ADORecordset_ibase extends ADORecordSet \r
+{\r
+\r
+    var $databaseType = "ibase";\r
+       var $bind=false;\r
+       \r
+        function ADORecordset_ibase($id)\r
+        {\r
+                return $this->ADORecordSet($id);\r
+        }\r
+\r
+        /*        Returns: an object containing field information.\r
+                Get column information in the Recordset object. fetchField() can be used in order to obtain information about\r
+                fields in a certain query result. If the field offset isn't specified, the next field that wasn't yet retrieved by\r
+                fetchField() is retrieved.        */\r
+\r
+        function &FetchField($fieldOffset = -1)\r
+        {\r
+                 $fld = new ADOFieldObject;\r
+                 $ibf = ibase_field_info($this->_queryID,$fieldOffset);\r
+                 $fld->name = $ibf['name'];\r
+                                if (empty($fld->name)) $fld->name = $ibf['alias'];\r
+                 $fld->type = $ibf['type'];\r
+                 $fld->max_length = $ibf['length'];\r
+                 if ($this->debug) print_r($fld);\r
+                 return $fld;\r
+        }\r
+\r
+        function _initrs()\r
+        {\r
+                $this->_numOfRows = -1;\r
+                $this->_numOfFields = @ibase_num_fields($this->_queryID);\r
+        }\r
+\r
+        function _seek($row)\r
+        {\r
+                return false;\r
+        }\r
+\r
+        function _fetch() {\r
+\r
+                $f = ibase_fetch_row($this->_queryID); \r
+                if ($f === false) return false;\r
+                $this->fields = $f;\r
+                return true;\r
+        }\r
+\r
+       /* Use associative array to get fields array */\r
+       function Fields($colname)\r
+       {\r
+               if (!$this->bind) {\r
+                       $this->bind = array();\r
+                       for ($i=0; $i < $this->_numOfFields; $i++) {\r
+                               $o = $this->FetchField($i);\r
+                               $this->bind[strtoupper($o->name)] = $i;\r
+                       }\r
+               }\r
+               \r
+                return $this->fields[$this->bind[strtoupper($colname)]];\r
+               \r
+       }\r
+       \r
+       \r
+        function _close() \r
+               {\r
+                return @ibase_free_result($this->_queryID);\r
+        }\r
+\r
+        function MetaType($t,$len=-1)\r
+        {\r
+                switch (strtoupper($t)) {\r
+               case 'CHAR':\r
+                       return 'C';\r
+                       \r
+              \r
+               case 'TEXT':\r
+               case 'VARCHAR':\r
+                case 'VARYING':\r
+                        if ($len <= $this->blobSize) return 'C';\r
+                       return 'X';\r
+                 case 'BLOB':\r
+                        return 'B';\r
+               \r
+                 case 'TIMESTAMP':\r
+                 case 'DATE': return 'D';\r
+                \r
+                //case 'T': return 'T';\r
+\r
+                //case 'L': return 'L';\r
+               case 'INT': \r
+               case 'SHORT':\r
+               case 'INTEGER': return 'I';\r
+                default: return 'N';\r
+                }\r
+        }\r
+}\r
+?>\r
diff --git a/libraries/adodb/adodb-mssql.inc.php b/libraries/adodb/adodb-mssql.inc.php
new file mode 100755 (executable)
index 0000000..b1c3a63
--- /dev/null
@@ -0,0 +1,279 @@
+<?php\r
+/* \r
+V1.53 13 Nov 2001 (c) 2000, 2001 John Lim (jlim@natsoft.com.my). All rights reserved.\r
+  Released under both BSD license and Lesser GPL library license. \r
+  Whenever there is any discrepancy between the two licenses, \r
+  the BSD license will take precedence. \r
+Set tabs to 4 for best viewing.\r
+  \r
+  Latest version is available at http://php.weblogs.com/\r
+  \r
+  Native mssql driver. Requires mssql client. Works on Windows. \r
+  To configure for Unix, see \r
+       http://phpbuilder.com/columns/alberto20000919.php3\r
+       \r
+  To configure datetime, look for and modify sqlcommn.loc, \r
+       typically found in c:\mssql\install\r
+  alternatively use \r
+       CONVERT(char(12),datecol,120)\r
+*/\r
+\r
+\r
+class ADODB_mssql extends ADOConnection {\r
+       var $databaseType = "mssql";    \r
+       var $replaceQuote = "''"; // string to use to replace quotes\r
+       var $fmtDate = "'Y-m-d'";\r
+       var $fmtTimeStamp = "'Y-m-d h:i:sA'";\r
+       var $hasInsertID = true;\r
+        var $hasAffectedRows = true;\r
+       var $metaTablesSQL="select name 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'))";\r
+       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'";\r
+       var $hasTop = true;             // support mssql SELECT TOP 10 * FROM TABLE\r
+       var $_hastrans = false;\r
+       \r
+       function ADODB_mssql() {                        \r
+       }\r
+\r
+        // might require begintrans -- committrans\r
+        function _insertid()\r
+        {\r
+                $rs = $this->Execute('select @@identity');\r
+                if ($rs == false || $rs->EOF) return false;\r
+               $id = $rs->fields[0];\r
+               $rs->Close();\r
+               return $id;\r
+        }\r
+          // might require begintrans -- committrans\r
+        function _affectedrows()\r
+        {\r
+                $rs = $this->Execute('select @@rowcount');\r
+                if ($rs == false || $rs->EOF) return false;\r
+               $id = $rs->fields[0];\r
+               $rs->Close();\r
+               return $id;\r
+        }\r
+        function BeginTrans()\r
+       {       \r
+               $this->_hastrans = true;\r
+        $this->Execute('BEGIN TRAN');\r
+        return true;\r
+       }\r
+       // Reserved for future expansion\r
+       function CommitTrans()\r
+       {\r
+               $this->_hastrans = false;\r
+        $this->Execute('COMMIT TRAN');\r
+        return true;\r
+       }\r
+       // Reserved for future expansion\r
+       function RollbackTrans()\r
+       {\r
+               $this->_hastrans = false;\r
+        $this->Execute('ROLLBACK TRAN');\r
+        return true;\r
+       }\r
+       \r
+       \r
+       //From: Fernando Moreira <FMoreira@imediata.pt>\r
+        function MetaDatabases() \r
+               { \r
+                if(@mssql_select_db("master")) { \r
+                         $qry="select name from sysdatabases where name <> 'master'"; \r
+                         if($rs=@mssql_query($qry)){ \r
+                                 $tmpAr=$ar=array(); \r
+                                 while($tmpAr=@mssql_fetch_row($rs)) \r
+                                         $ar[]=$tmpAr[0]; \r
+                                @mssql_select_db($this->databaseName); \r
+                                 if(sizeof($ar)) \r
+                                         return($ar); \r
+                                 else \r
+                                         return(false); \r
+                         } else { \r
+                                 @mssql_select_db($this->databaseName); \r
+                                 return(false); \r
+                         } \r
+                 } \r
+                 return(false); \r
+        } \r
+\r
+       function SelectDB($dbName) \r
+       {\r
+               $this->databaseName = $dbName;\r
+               if ($this->_connectionID) {\r
+                       return @mssql_select_db($dbName);               \r
+               }\r
+               else return false;      \r
+       }\r
+       /*      Returns: the last error message from previous database operation\r
+               Note: This function is NOT available for Microsoft SQL Server.  */\r
+       function ErrorMsg() \r
+       {\r
+               $this->_errorMsg = mssql_get_last_message();\r
+               return $this->_errorMsg;\r
+       }\r
+       \r
+       function ErrorNo() \r
+       {\r
+               $id = @mssql_query("select @@ERROR",$this->_connectionID);\r
+               if (!$id) return false;\r
+               $arr = mssql_fetch_array($id);\r
+               @mssql_free_result($id);\r
+               if (is_array($arr)) return $arr[0];\r
+       else return -1;\r
+       }\r
+       \r
+       // returns true or false\r
+       function _connect($argHostname, $argUsername, $argPassword, $argDatabasename)\r
+       {\r
+               $this->_connectionID = mssql_connect($argHostname,$argUsername,$argPassword);\r
+               if ($this->_connectionID === false) return false;\r
+               //$this->Execute('SET DATEFORMAT ymd');\r
+               if ($argDatabasename) return $this->SelectDB($argDatabasename);\r
+               return true;    \r
+       }\r
+       \r
+       \r
+       // returns true or false\r
+       function _pconnect($argHostname, $argUsername, $argPassword, $argDatabasename)\r
+       {\r
+               $this->_connectionID = mssql_pconnect($argHostname,$argUsername,$argPassword);\r
+               if ($this->_connectionID === false) return false;\r
+               //$this->Execute('SET DATEFORMAT ymd');\r
+               if ($argDatabasename) return $this->SelectDB($argDatabasename);\r
+               return true;    \r
+       }\r
+       \r
+       // returns query ID if successful, otherwise false\r
+       function _query($sql,$inputarr)\r
+       {\r
+               $val= mssql_query($sql,$this->_connectionID);\r
+               return $val;\r
+       }\r
+       \r
+       // returns true or false\r
+       function _close()\r
+       { \r
+               if ($this->_hastrans) $this->RollbackTrans();\r
+               return @mssql_close($this->_connectionID);\r
+       }\r
+       \r
+       \r
+}\r
+       \r
+/*--------------------------------------------------------------------------------------\r
+        Class Name: Recordset\r
+--------------------------------------------------------------------------------------*/\r
+global $ADODB_mssql_mths;\r
+$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);\r
+\r
+class ADORecordset_mssql extends ADORecordSet {        \r
+\r
+       var $databaseType = "mssql";\r
+       var $canSeek = true;\r
+       // _mths works only in non-localised system\r
+               \r
+       function ADORecordset_mssql($id)\r
+       {\r
+               return $this->ADORecordSet($id);\r
+       }\r
+       \r
+\r
+       /* Use associative array to get fields array */\r
+       function Fields($colname)\r
+       {\r
+               if (!$this->bind) {\r
+                       $this->bind = array();\r
+                       for ($i=0; $i < $this->_numOfFields; $i++) {\r
+                               $o = $this->FetchField($i);\r
+                               $this->bind[strtoupper($o->name)] = $i;\r
+                       }\r
+               }\r
+               \r
+                return $this->fields[$this->bind[strtoupper($colname)]];\r
+       }\r
+       \r
+       /*      Returns: an object containing field information. \r
+               Get column information in the Recordset object. fetchField() can be used in order to obtain information about\r
+               fields in a certain query result. If the field offset isn't specified, the next field that wasn't yet retrieved by\r
+               fetchField() is retrieved.      */\r
+\r
+       function FetchField($fieldOffset = -1) \r
+       {\r
+               if ($fieldOffset != -1) {\r
+                       return @mssql_fetch_field($this->_queryID, $fieldOffset);\r
+               }\r
+               else if ($fieldOffset == -1) {  /*      The $fieldOffset argument is not provided thus its -1   */\r
+                       return @mssql_fetch_field($this->_queryID);\r
+               }\r
+               return null;\r
+       }\r
+       \r
+       function _initrs()\r
+       {\r
+       GLOBAL $ADODB_COUNTRECS;\r
+               $this->_numOfRows = ($ADODB_COUNTRECS)? @mssql_num_rows($this->_queryID):-1;\r
+               $this->_numOfFields = @mssql_num_fields($this->_queryID);\r
+       }\r
+       \r
+       function _seek($row) \r
+       {\r
+               return @mssql_data_seek($this->_queryID, $row);\r
+       }\r
+\r
+       // INSERT UPDATE DELETE returns false even if no error occurs in 4.0.4\r
+       // also the date format has been changed from YYYY-mm-dd to dd MMM YYYY in 4.0.4. Idiot!\r
+       function _fetch($ignore_fields=false) \r
+       {\r
+               $this->fields = @mssql_fetch_array($this->_queryID);\r
+               //print_r($this->fields);\r
+               return (!empty($this->fields));\r
+       }\r
+       \r
+       /*      close() only needs to be called if you are worried about using too much memory while your script\r
+               is running. All associated result memory for the specified result identifier will automatically be freed.       */\r
+\r
+       function _close() {\r
+               return @mssql_free_result($this->_queryID);             \r
+       }\r
+\r
+       // mssql uses a default date like Dec 30 2000 12:00AM\r
+       function UnixDate($v)\r
+       {\r
+       global $ADODB_mssql_mths;\r
+       \r
+               //Dec 30 2000 12:00AM\r
+               if (!ereg( "([A-Za-z]{3})[-/\. ]+([0-9]{1,2})[-/\. ]+([0-9]{4}))"\r
+                       ,$v, $rr)) return parent::UnixDate($v);\r
+                       \r
+               if ($rr[3] <= 1970) return 0;\r
+               \r
+               $themth = substr(strtoupper($rr[1]),0,3);\r
+               $themth = $ADODB_mssql_mths[$themth];\r
+               if ($themth <= 0) return false;\r
+               // h-m-s-MM-DD-YY\r
+               return  mktime(0,0,0,$themth,$rr[2],$rr[3]);\r
+       }\r
+       \r
+       function UnixTimeStamp($v)\r
+       {\r
+       global $ADODB_mssql_mths;\r
+       \r
+               //Dec 30 2000 12:00AM\r
+               if (!ereg( "([A-Za-z]{3})[-/\. ]+([0-9]{1,2})[-/\. ]+([0-9]{4}) +([0-9]{1,2}):([0-9]{1,2}) *([apAP]{0,1})"\r
+                       ,$v, $rr)) return parent::UnixTimeStamp($v);\r
+               if ($rr[3] <= 1970) return 0;\r
+               \r
+               $themth = substr(strtoupper($rr[1]),0,3);\r
+               $themth = $ADODB_mssql_mths[$themth];\r
+               if ($themth <= 0) return false;\r
+               \r
+               if (strtoupper($rr[6]) == 'P') {\r
+                       if ($rr[4]<12) $rr[4] += 12;\r
+               } else {\r
+                       if ($rr[4]==12) $rr[4] = 0;\r
+               }\r
+               // h-m-s-MM-DD-YY\r
+               return  mktime($rr[4],$rr[5],0,$themth,$rr[2],$rr[3]);\r
+       }\r
+}\r
+?>
\ No newline at end of file
diff --git a/libraries/adodb/adodb-mysql.inc.php b/libraries/adodb/adodb-mysql.inc.php
new file mode 100755 (executable)
index 0000000..c3c2e7d
--- /dev/null
@@ -0,0 +1,352 @@
+<?php\r
+/*\r
+V1.53 13 Nov 2001 (c) 2000, 2001 John Lim (jlim@natsoft.com.my). All rights reserved.\r
+  Released under both BSD license and Lesser GPL library license. \r
+  Whenever there is any discrepancy between the two licenses, \r
+  the BSD license will take precedence.\r
+  Set tabs to 8.\r
+  \r
+  MySQL code that does not support transactions. Use mysqlt if you need transactions.\r
+  Requires mysql client. Works on Windows and Unix.\r
+  \r
+ 28 Feb 2001: MetaColumns bug fix - suggested by  Freek Dijkstra (phpeverywhere@macfreek.com)\r
+*/ \r
+\r
+if (! defined("_ADODB_MYSQL_LAYER")) {\r
+ define("_ADODB_MYSQL_LAYER", 1 );\r
+\r
+class ADODB_mysql extends ADOConnection {\r
+       var $databaseType = 'mysql';\r
+    var $hasInsertID = true;\r
+    var $hasAffectedRows = true;       \r
+       var $metaTablesSQL = "SHOW TABLES";     \r
+       var $metaColumnsSQL = "SHOW COLUMNS FROM %s";\r
+       var $fmtTimeStamp = "'Y-m-d H:i:s'";\r
+       var $hasLimit = true;\r
+       var $hasMoveFirst = true;\r
+       var $hasGenID = true;\r
+       \r
+       function ADODB_mysql() \r
+       {                       \r
+       }\r
+       \r
+    function _insertid()\r
+    {\r
+            return mysql_insert_id($this->_connectionID);\r
+    }\r
+    \r
+    function _affectedrows()\r
+    {\r
+            return mysql_affected_rows($this->_connectionID);\r
+    }\r
+  \r
+       // See http://www.mysql.com/doc/M/i/Miscellaneous_functions.html\r
+       // Reference on Last_Insert_ID on the recommended way to simulate sequences\r
+       var $_genIDSQL = "update %s set id=LAST_INSERT_ID(id+1);";\r
+       var $_genSeqSQL = "create table %s (id int not null)";\r
+       var $_genSeq2SQL = "insert into %s values (0)";\r
+       \r
+       function GenID($seqname='adodbseq')\r
+       {\r
+               if (!$this->hasGenID) return false;\r
+               \r
+               $getnext = sprintf($this->_genIDSQL,$seqname);\r
+               $rs = @$this->Execute($getnext);\r
+               if (!$rs) {\r
+                       $u = strtoupper($seqname);\r
+                       $this->Execute(sprintf($this->_genSeqSQL,$seqname));\r
+                       $this->Execute(sprintf($this->_genSeq2SQL,$seqname));\r
+                       $rs = $this->Execute($getnext);\r
+               }\r
+               $this->genID = mysql_insert_id($this->_connectionID);\r
+               \r
+               if ($rs) $rs->Close();\r
+               \r
+               return $this->genID;\r
+       }\r
+       \r
+       function &MetaDatabases()\r
+       {\r
+               $qid = mysql_list_dbs($this->_connectionID);\r
+               $arr = array();\r
+               $i = 0;\r
+               $max = mysql_num_rows($qid);\r
+               while ($i < $max) {\r
+                       $arr[] = mysql_tablename($qid,$i);\r
+                       $i += 1;\r
+               }\r
+               return $arr;\r
+       }\r
+\r
+       // returns concatenated string\r
+       function Concat()\r
+       {\r
+               $s = "";\r
+               $arr = func_get_args();\r
+               $first = true;\r
+               /*\r
+               foreach($arr as $a) {\r
+                       if ($first) {\r
+                               $s = $a;\r
+                               $first = false;\r
+                       } else $s .= ','.$a;\r
+               }*/\r
+               \r
+               // suggestion by andrew005@mnogo.ru\r
+               $s = implode(',',$arr); \r
+               if (strlen($s) > 0) return "CONCAT($s)";\r
+               else return '';\r
+       }\r
+       \r
+       // returns true or false\r
+       function _connect($argHostname, $argUsername, $argPassword, $argDatabasename)\r
+       {\r
+               $this->_connectionID = mysql_connect($argHostname,$argUsername,$argPassword);\r
+               if ($this->_connectionID === false) return false;\r
+               if ($argDatabasename) return $this->SelectDB($argDatabasename);\r
+               return true;    \r
+       }\r
+       \r
+       // returns true or false\r
+       function _pconnect($argHostname, $argUsername, $argPassword, $argDatabasename)\r
+       {\r
+               $this->_connectionID = mysql_pconnect($argHostname,$argUsername,$argPassword);\r
+               if ($this->_connectionID === false) return false;\r
+               if ($argDatabasename) return $this->SelectDB($argDatabasename);\r
+               return true;    \r
+       }\r
+       \r
+       function &MetaColumns($table) \r
+       {\r
+               if ($this->metaColumnsSQL) {\r
+               \r
+                       $rs = $this->Execute(sprintf($this->metaColumnsSQL,$table));\r
+                       \r
+                       if ($rs === false) return false;\r
+                       \r
+                       $retarr = array();\r
+                       while (!$rs->EOF){\r
+                               $fld = new ADOFieldObject();\r
+                               $fld->name = $rs->fields[0];\r
+                               $fld->type = $rs->fields[1];\r
+                                       \r
+                               // split type into type(length):\r
+                               if (preg_match("/^(.+)\((\d+)\)$/", $fld->type, $query_array)) {\r
+                                       $fld->type = $query_array[1];\r
+                                       $fld->max_length = $query_array[2];\r
+                               } else {\r
+                                       $fld->max_length = -1;\r
+                               }\r
+                               $fld->not_null = ($rs->fields[2] != 'YES');\r
+                               $fld->primary_key = ($rs->fields[3] == 'PRI');\r
+                               $fld->auto_increment = (strpos($rs->fields[5], 'auto_increment') !== false);\r
+                               $fld->binary = (strpos($fld->type,'blob') !== false);\r
+                               \r
+                               $retarr[strtoupper($fld->name)] = $fld; \r
+                               $rs->MoveNext();\r
+                       }\r
+                       $rs->Close();\r
+                       return $retarr; \r
+               }\r
+               return false;\r
+       }\r
+               \r
+       // returns true or false\r
+       function SelectDB($dbName) \r
+       {\r
+               $this->databaseName = $dbName;\r
+               if ($this->_connectionID) {\r
+                       return @mysql_select_db($dbName,$this->_connectionID);          \r
+               }\r
+               else return false;      \r
+       }\r
+       \r
+       // parameters use PostgreSQL convention, not MySQL\r
+       function &SelectLimit($sql,$nrows=-1,$offset=-1,$inputarr=false, $arg3=false,$secs=0)\r
+       {\r
+               $offsetStr =($offset>=0) ? "$offset," : '';\r
+               \r
+               return ($secs) ? $this->CacheExecute($secs,$sql." LIMIT $offsetStr$nrows",$inputarr,$arg3)\r
+                       : $this->Execute($sql." LIMIT $offsetStr$nrows",$inputarr,$arg3);\r
+               \r
+       }\r
+       \r
+       // returns queryID or false\r
+       function _query($sql,$inputarr)\r
+       {\r
+       global $ADODB_COUNTRECS;\r
+               if($ADODB_COUNTRECS) return mysql_query($sql,$this->_connectionID);\r
+               else return mysql_unbuffered_query($sql,$this->_connectionID); // requires PHP >= 4.0.6\r
+       }\r
+\r
+       /*      Returns: the last error message from previous database operation        */      \r
+       function ErrorMsg() \r
+       {\r
+               if (!empty($this->_connectionID)) $this->_errorMsg = @mysql_error();\r
+               else $this->_errorMsg = @mysql_error($this->_connectionID);\r
+           return $this->_errorMsg;\r
+       }\r
+       \r
+       /*      Returns: the last error number from previous database operation */      \r
+       function ErrorNo() \r
+       {\r
+                       if (empty($this->_connectionID))  return @mysql_errno();\r
+                       else return @mysql_errno($this->_connectionID);\r
+       }\r
+       \r
+       // returns true or false\r
+       function _close()\r
+       {\r
+               @mysql_close($this->_connectionID);\r
+               $this->_connectionID = false;\r
+       }\r
+               \r
+}\r
+       \r
+/*--------------------------------------------------------------------------------------\r
+        Class Name: Recordset\r
+--------------------------------------------------------------------------------------*/\r
+\r
+class ADORecordSet_mysql extends ADORecordSet{ \r
+       \r
+       var $databaseType = "mysql";\r
+       var $canSeek = true;\r
+       \r
+       function ADORecordSet_mysql($queryID) {\r
+       GLOBAL $ADODB_FETCH_MODE;\r
+       \r
+               switch ($ADODB_FETCH_MODE)\r
+               {\r
+               case ADODB_FETCH_NUM: $this->fetchMode = MYSQL_NUM; break;\r
+               case ADODB_FETCH_ASSOC:$this->fetchMode = MYSQL_ASSOC; break;\r
+               default:\r
+               case ADODB_FETCH_DEFAULT:\r
+               case ADODB_FETCH_BOTH:$this->fetchMode = MYSQL_BOTH; break;\r
+               }\r
+       \r
+               $this->ADORecordSet($queryID);  \r
+       }\r
+       \r
+       function _initrs()\r
+       {\r
+       GLOBAL $ADODB_COUNTRECS;\r
+               $this->_numOfRows = ($ADODB_COUNTRECS) ? @mysql_num_rows($this->_queryID):-1;\r
+               $this->_numOfFields = @mysql_num_fields($this->_queryID);\r
+       }\r
+       \r
+       function &FetchField($fieldOffset = -1) {\r
+               if ($fieldOffset != -1) {\r
+                       $o =  @mysql_fetch_field($this->_queryID, $fieldOffset);\r
+                       $f = @mysql_field_flags($this->_queryID,$fieldOffset);\r
+                       $o->max_length = @mysql_field_len($this->_queryID,$fieldOffset); // suggested by: Jim Nicholson (jnich@att.com)\r
+                       //$o->max_length = -1; // mysql returns the max length less spaces -- so it is unrealiable\r
+                       $o->binary = (strpos($f,'binary')!== false);\r
+               }\r
+               else if ($fieldOffset == -1) {  /*      The $fieldOffset argument is not provided thus its -1   */\r
+                       $o = @mysql_fetch_field($this->_queryID);\r
+                       $o->max_length = @mysql_field_len($this->_queryID); // suggested by: Jim Nicholson (jnich@att.com)\r
+                       //$o->max_length = -1; // mysql returns the max length less spaces -- so it is unrealiable\r
+               }\r
+               \r
+               return $o;\r
+       }\r
+\r
+       function &GetRowAssoc($upper=true)\r
+       {\r
+               if ($this->fetchMode == MYSQL_ASSOC && !$upper) return $rs->fields;\r
+               return ADORecordSet::GetRowAssoc($upper);\r
+       }\r
+       \r
+       \r
+       function _seek($row)\r
+       {\r
+               return @mysql_data_seek($this->_queryID,$row);\r
+       }\r
+       \r
+       /*function &FetchRow()\r
+       {\r
+               if ($this->EOF) return false;\r
+               \r
+               $arr = $this->fields;\r
+               $this->_currentRow++;\r
+                       // using & below slows things down by 20%!\r
+               $this->fields = @mysql_fetch_array($this->_queryID,$this->fetchMode);\r
+                       \r
+               if (is_array($this->fields)) return $arr;\r
+               $this->EOF = true;\r
+               return false;\r
+       }*/\r
+       \r
+       // 10% speedup to move MoveNext to child class\r
+       function MoveNext() \r
+       {\r
+               if (!$this->EOF) {              \r
+                       $this->_currentRow++;\r
+                       // using & below slows things down by 20%!\r
+                       $this->fields = @mysql_fetch_array($this->_queryID,$this->fetchMode);\r
+                       \r
+                       if (is_array($this->fields)) return true;\r
+                       $this->EOF = true;\r
+               }\r
+               return false;\r
+       }       \r
+       \r
+       function _fetch()\r
+       {\r
+               $this->fields = @mysql_fetch_array($this->_queryID,$this->fetchMode);\r
+               return (is_array($this->fields));\r
+       }\r
+       \r
+       function _close() {\r
+               @mysql_free_result($this->_queryID);    \r
+               $this->_queryID = false;        \r
+       }\r
+       \r
+       function MetaType($t,$len=-1,$fieldobj=false)\r
+       {\r
+               $len = -1; // mysql max_length is not accurate\r
+               switch (strtoupper($t)) {\r
+               case 'STRING': \r
+               case 'CHAR':\r
+               case 'VARCHAR': \r
+               case 'TINYBLOB': \r
+               case 'TINYTEXT': \r
+               case 'ENUM': \r
+               case 'SET': \r
+                       if ($len <= $this->blobSize) return 'C';\r
+                       \r
+               case 'TEXT':\r
+               case 'LONGTEXT': \r
+               case 'MEDIUMTEXT':\r
+                       return 'X';\r
+                       \r
+               // php_mysql extension always returns 'blob' even if 'text'\r
+               // so we have to check whether binary...\r
+               case 'IMAGE':\r
+               case 'LONGBLOB': \r
+               case 'BLOB':\r
+               case 'MEDIUMBLOB':\r
+                       return !empty($fieldobj->binary) ? 'B' : 'X';\r
+                       \r
+               case 'DATE': return 'D';\r
+               \r
+               case 'DATETIME':\r
+               case 'TIMESTAMP': return 'T';\r
+               \r
+               case 'INT': \r
+               case 'INTEGER':\r
+               case 'BIGINT':\r
+               case 'TINYINT':\r
+               case 'MEDIUMINT':\r
+               case 'SMALLINT': \r
+                       \r
+                       if (!empty($fieldobj->primary_key)) return 'R';\r
+                       else return 'I';\r
+               \r
+               default: return 'N';\r
+               }\r
+       }\r
+\r
+}\r
+}\r
+?>
\ No newline at end of file
diff --git a/libraries/adodb/adodb-mysqlt.inc.php b/libraries/adodb/adodb-mysqlt.inc.php
new file mode 100755 (executable)
index 0000000..3b1a72b
--- /dev/null
@@ -0,0 +1,53 @@
+<?php\r
+\r
+/*\r
+V1.53 13 Nov 2001 (c) 2000, 2001 John Lim (jlim@natsoft.com.my). All rights reserved.\r
+  Released under both BSD license and Lesser GPL library license. \r
+  Whenever there is any discrepancy between the two licenses, \r
+  the BSD license will take precedence.\r
+  Set tabs to 8.\r
+  \r
+  MySQL code that supports transactions. For MySQL 3.23 or later.\r
+  Code from James Poon <jpoon88@yahoo.com>\r
+  \r
+  Requires mysql client. Works on Windows and Unix.\r
+*/\r
+\r
+\r
+include_once(ADODB_DIR."/adodb-mysql.inc.php");\r
+\r
+\r
+class ADODB_mysqlt extends ADODB_mysql {\r
+       var $databaseType = 'mysqlt';\r
+       \r
+       function BeginTrans()\r
+       {       \r
+               $this->Execute('SET AUTOCOMMIT=0');\r
+               $this->Execute('BEGIN');\r
+               return true;\r
+       }\r
+       \r
+       function CommitTrans()\r
+       {\r
+               $this->Execute('COMMIT');\r
+               $this->Execute('SET AUTOCOMMIT=1');\r
+               return true;\r
+       }\r
+       \r
+       function RollbackTrans()\r
+       {\r
+               $this->Execute('ROLLBACK');\r
+               $this->Execute('SET AUTOCOMMIT=1');\r
+               return true;\r
+       }\r
+       \r
+}\r
+\r
+class ADORecordSet_mysqlt extends ADORecordSet_mysql{  \r
+       var $databaseType = "mysqlt";\r
+       \r
+       function ADORecordSet_mysqlt($queryID) {\r
+               return $this->ADORecordSet_mysql($queryID);\r
+       }\r
+}\r
+?>
\ No newline at end of file
diff --git a/libraries/adodb/adodb-oci8.inc.php b/libraries/adodb/adodb-oci8.inc.php
new file mode 100755 (executable)
index 0000000..98f62ef
--- /dev/null
@@ -0,0 +1,503 @@
+<?php\r
+/*\r
+V1.53 13 Nov 2001 (c) 2000, 2001 John Lim. All rights reserved.\r
+  Released under both BSD license and Lesser GPL library license. \r
+  Whenever there is any discrepancy between the two licenses, \r
+  the BSD license will take precedence.\r
+\r
+  Latest version is available at http://php.weblogs.com/\r
+  \r
+  Code contributed by George Fourlanos <fou@infomap.gr>\r
+  \r
+  13 Nov 2000 jlim - removed all ora_* references.\r
+*/\r
+\r
+/*\r
+NLS_Date_Format\r
+Allows you to use a date format other than the Oracle Lite default. When a literal\r
+character string appears where a date value is expected, the Oracle Lite database\r
+tests the string to see if it matches the formats of Oracle, SQL-92, or the value\r
+specified for this parameter in the POLITE.INI file. Setting this parameter also\r
+defines the default format used in the TO_CHAR or TO_DATE functions when no\r
+other format string is supplied.\r
+For Oracle the default is dd-mon-yy or dd-mon-yyyy, and for SQL-92 the default is\r
+yy-mm-dd or yyyy-mm-dd.\r
+Using 'RR' in the format forces two-digit years less than or equal to 49 to be\r
+interpreted as years in the 21st century (2000\962049), and years over 50 as years in\r
+the 20th century (1950\961999). Setting the RR format as the default for all two-digit\r
+year entries allows you to become year-2000 compliant. For example:\r
+NLS_DATE_FORMAT='RR-MM-DD'\r
+You can also modify the date format using the ALTER SESSION command. See the\r
+Oracle Lite SQL Reference for more information.\r
+*/\r
+class ADODB_oci8 extends ADOConnection {\r
+    var $databaseType = 'oci8';\r
+       var $dataProvider = 'oci8';\r
+    var $replaceQuote = "''"; // string to use to replace quotes\r
+    var $concat_operator='||';\r
+       var $_stmt;\r
+       var $_commit = OCI_COMMIT_ON_SUCCESS;\r
+       var $_initdate = true; // init date to YYYY-MM-DD\r
+       var $metaTablesSQL = "select table_name from cat where table_type in ('TABLE','VIEW')";\r
+       var $metaColumnsSQL = "select cname,coltype,width from col where tname='%s' order by colno";\r
+       var $_bindInputArray = true;\r
+       var $hasGenID = true;\r
+       var $_genIDSQL = "SELECT %s.nextval FROM DUAL";\r
+       var $_genSeqSQL = "CREATE SEQUENCE %s";\r
+       var $hasAffectedRows = true;\r
+       \r
+    function ADODB_oci8() {\r
+    }\r
+       \r
+       function Affected_Rows()\r
+       {\r
+               return OCIRowCount($this->_stmt);\r
+       }\r
+       \r
+       // format and return date string in database date format\r
+       function DBDate($d)\r
+       {\r
+               return 'TO_DATE('.date($this->fmtDate,$d).",'YYYY-MM-DD')";\r
+       }\r
+       \r
+       // format and return date string in database timestamp format\r
+       function DBTimeStamp($ts)\r
+       {\r
+               return 'TO_DATE('.date($this->fmtTimeStamp,$ts).",'RRRR-MM-DD, HH:MI:SS AM')";\r
+       }\r
+       \r
+    function BeginTrans()\r
+       {      \r
+         $this->autoCommit = false;\r
+         $this->_commit = OCI_DEFAULT;\r
+         return true;\r
+       }\r
+       \r
+       function CommitTrans()\r
+       {\r
+        $ret = OCIcommit($this->_connectionID);\r
+           $this->_commit = OCI_COMMIT_ON_SUCCESS;\r
+           $this->autoCommit = true;\r
+           return $ret;\r
+       }\r
+       \r
+       function RollbackTrans()\r
+       {\r
+        $ret = OCIrollback($this->_connectionID);\r
+               $this->_commit = OCI_COMMIT_ON_SUCCESS;\r
+           $this->autoCommit = true;\r
+               return $ret;\r
+       }\r
+        \r
+    function SelectDB($dbName) \r
+       {\r
+        return false;\r
+    }\r
+\r
+       /* there seems to be a bug in the oracle extension -- always returns ORA-00000 - no error */\r
+        function ErrorMsg() \r
+               {\r
+                       $arr = @OCIerror($this->_stmt);\r
+                       if ($arr === false) {\r
+                               $arr = @OCIerror($this->_connectionID);\r
+                               if ($arr === false) $arr = @OCIError();\r
+                               if ($arr === false) return '';\r
+                       }\r
+            $this->_errorMsg = $arr['message'];\r
+            return $this->_errorMsg;\r
+        }\r
+       \r
+       function ErrorNo() \r
+       {\r
+               if (is_resource($this->_stmt))\r
+                       $arr = @ocierror($this->_stmt);\r
+               else {\r
+                       $arr = @ocierror($this->_connectionID);\r
+                       if ($arr === false) $arr = @ocierror();\r
+                       if ($arr == false) return '';\r
+               }\r
+        return $arr['code'];\r
+    }\r
+/*\r
+NATSOFT.DOMAIN =\r
+  (DESCRIPTION =\r
+    (ADDRESS_LIST =\r
+      (ADDRESS = (PROTOCOL = TCP)(HOST = kermit)(PORT = 1523))\r
+    )\r
+    (CONNECT_DATA =\r
+      (SERVICE_NAME = natsoft.domain)\r
+    )\r
+  )\r
+*/\r
+  \r
+        // returns true or false\r
+    function _connect($argHostname, $argUsername, $argPassword, $argDatabasename)\r
+    {\r
+                        \r
+       if($argHostname) { // added by Jorma Tuomainen <jorma.tuomainen@ppoy.fi>\r
+               if(strpos($argHostname,":")) {\r
+                               $argHostinfo=explode(":",$argHostname);\r
+                       $argHostname=$argHostinfo[0];\r
+                $argHostport=$argHostinfo[1];\r
+               } else {\r
+                       $argHostport="1521";\r
+                       }\r
+\r
+                       $argDatabasename="(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=".$argHostname\r
+                               .")(PORT=$argHostport))(CONNECT_DATA=(SERVICE_NAME=$argDatabasename)))";\r
+       }\r
+                               \r
+               //if ($argHostname) print "<p>Connect: 1st argument should be left blank for $this->databaseType</p>";\r
+        $this->_connectionID = OCIlogon($argUsername,$argPassword, $argDatabasename);\r
+        if ($this->_connectionID === false) return false;\r
+               if ($this->_initdate) {\r
+                       $this->Execute("ALTER SESSION SET NLS_DATE_FORMAT='YYYY-MM-DD'");\r
+               }\r
+        return true;\r
+       }\r
+        // returns true or false\r
+    function _pconnect($argHostname, $argUsername, $argPassword, $argDatabasename)\r
+       {\r
+               if($argHostname) { // added by Jorma Tuomainen <jorma.tuomainen@ppoy.fi>\r
+               if(strpos($argHostname,":")) {\r
+                               $argHostinfo=explode(":",$argHostname);\r
+                       $argHostname=$argHostinfo[0];\r
+                $argHostport=$argHostinfo[1];\r
+               } else {\r
+                       $argHostport="1521";\r
+                       }\r
+\r
+                       $argDatabasename="(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=".$argHostname\r
+                               .")(PORT=".$argHostport."))(CONNECT_DATA=(SERVICE_NAME=".$argDatabasename.")))";\r
+       }\r
+               $this->_connectionID = OCIplogon($argUsername,$argPassword, $argDatabasename);\r
+        if ($this->_connectionID === false) return false;\r
+               if ($this->_initdate) {\r
+                       $this->Execute("ALTER SESSION SET NLS_DATE_FORMAT='YYYY-MM-DD'");\r
+               }\r
+        return true;\r
+       }\r
+\r
+       \r
+       /**\r
+       * Usage:\r
+       * Store BLOBs and CLOBs\r
+       *\r
+       * Example: to store $var in a blob\r
+       *\r
+       *       $conn->Execute('insert into TABLE (id,ablobb) values(12,empty_blob())');\r
+       *       $conn->UpdateBlob('TABLE', 'COLUMN', $var, 'ID=1', 'BLOB');\r
+       *       \r
+       *       $blobtype supports 'BLOB' and 'CLOB'\r
+       *\r
+       *  to get length of LOB:\r
+       *       select DBMS_LOB.GETLENGTH(ablob) from TABLE\r
+       */\r
+\r
+       function UpdateBlob($table,$column,$val,$where,$blobtype='BLOB')\r
+       {\r
+               switch(strtoupper($blobtype)) {\r
+               default: print "<b>UpdateBlob</b>: Unknown blobtype=$blobtype<br>"; return false;\r
+               case 'BLOB': $type = OCI_B_BLOB; break;\r
+               case 'CLOB': $type = OCI_B_CLOB; break;\r
+               }\r
+               \r
+               $sql = "UPDATE $table set $column=EMPTY_{$blobtype}() WHERE $where RETURNING $column INTO :blob";\r
+               \r
+               $desc = OCINewDescriptor($this->_connectionID, OCI_D_LOB);\r
+               $arr['blob'] = array($desc,-1,$type);\r
+               \r
+               $this->BeginTrans();\r
+               $rs = $this->Execute($sql,$arr);\r
+               $rez = !empty($rs);\r
+               $desc->save($val);\r
+               $desc->free();\r
+               $this->CommitTrans();\r
+               \r
+               if ($rez) $rs->Close();\r
+               return $rez;\r
+       }\r
+       \r
+       /*\r
+               Example of usage:\r
+               \r
+               $stmt = $this->Prepare('insert into emp (empno, ename) values (:empno, :ename)');\r
+       */\r
+       function &Prepare($sql)\r
+       {\r
+               return $sql;\r
+       /*\r
+       ## doesn't work reliably, so emulate\r
+               if ($this->debug) {\r
+                       print "<hr>($this->databaseType): ".htmlspecialchars($sql)."<hr>";\r
+               }\r
+               return OCIParse($this->_connectionID,$sql);\r
+       */\r
+       }\r
+       \r
+       // returns query ID if successful, otherwise false\r
+       function _query($sql,$inputarr)\r
+       {\r
+               //if (!is_resource($sql))\r
+               $stmt=OCIParse($this->_connectionID,$sql);\r
+               //else $stmt = $sql;\r
+               \r
+               $this->_stmt = $stmt;\r
+               if (!$stmt) return false;\r
+               if (is_array($inputarr)) {\r
+                       foreach($inputarr as $k => $v) {\r
+                               if (is_array($v)) {\r
+                                       OCIBindByName($stmt,":$k",$inputarr[$k][0],$v[1],$v[2]);\r
+                                       //print_r($v);\r
+                               } else {\r
+                                       $len = -1;\r
+                                       if ($inputarr[$k] === ' ') $len = 1;\r
+                                       OCIBindByName($stmt,":$k",$inputarr[$k],$len);\r
+                                       //print " :$k $len ";\r
+                               }\r
+                       }\r
+               }\r
+               if (OCIExecute($stmt,$this->_commit)) {\r
+                  /* Now this could be an Update/Insert or Delete */\r
+                       if (strtoupper(substr($sql,0,6)) !== 'SELECT') return true;\r
+                       return $stmt;\r
+               }\r
+           return false;\r
+       }\r
+       \r
+       // returns true or false\r
+       function _close()\r
+       {\r
+               if (!$this->autoCommit) OCIRollback($this->_connectionID);\r
+               OCILogoff($this->_connectionID);\r
+               $this->_stmt = false;\r
+               $this->_connectionID = false;\r
+       }\r
+\r
+       function MetaPrimaryKeys($table)\r
+       {\r
+       // tested with oracle 8.1.7\r
+               $table = strtoupper($table);\r
+               $sql = "SELECT /*+ RULE */ distinct b.column_name\r
+   FROM ALL_CONSTRAINTS a\r
+      , ALL_CONS_COLUMNS b\r
+  WHERE ( UPPER(b.table_name) = ('$table'))\r
+    AND (UPPER(a.table_name) = ('$table') and a.constraint_type = 'P')\r
+    AND (a.constraint_name = b.constraint_name)";\r
+               $rs = $this->Execute($sql);\r
+               if ($rs && !$rs->EOF) {\r
+                       $arr = $rs->GetArray();\r
+                       $a = array();\r
+                       foreach($arr as $v) {\r
+                               $a[] = $v[0];\r
+                       }\r
+                       return $a;\r
+               }\r
+               else return false;\r
+       }\r
+\r
+}\r
+\r
+/*--------------------------------------------------------------------------------------\r
+         Class Name: Recordset\r
+--------------------------------------------------------------------------------------*/\r
+\r
+class ADORecordset_oci8 extends ADORecordSet {\r
+\r
+    var $databaseType = 'oci8';\r
+       var $bind=false;\r
+       var $_fieldobjs;\r
+       \r
+        function ADORecordset_oci8($queryID)\r
+        {\r
+               global $ADODB_FETCH_MODE;\r
+               \r
+               switch ($ADODB_FETCH_MODE)\r
+               {\r
+               default:\r
+               case ADODB_FETCH_NUM: $this->fetchMode = OCI_NUM+OCI_RETURN_NULLS+OCI_RETURN_LOBS; break;\r
+               case ADODB_FETCH_ASSOC:$this->fetchMode = OCI_ASSOC+OCI_RETURN_NULLS+OCI_RETURN_LOBS; break;\r
+               case ADODB_FETCH_DEFAULT:\r
+               case ADODB_FETCH_BOTH:$this->fetchMode = OCI_NUM+OCI_ASSOC+OCI_RETURN_NULLS+OCI_RETURN_LOBS; break;\r
+               }\r
+       \r
+               \r
+               $this->_inited = true;\r
+               $this->_queryID = $queryID;\r
+               $this->fields = array();\r
+               if ($queryID) {\r
+                       $this->_currentRow = 0;\r
+                       $this->EOF = !$this->_fetch();\r
+                       @$this->_initrs();\r
+               } else {\r
+                       $this->_numOfRows = 0;\r
+                       $this->_numOfFields = 0;\r
+                       $this->EOF = true;\r
+               }\r
+        }\r
+\r
+\r
+\r
+        /*        Returns: an object containing field information.\r
+                Get column information in the Recordset object. fetchField() can be used in order to obtain information about\r
+                fields in a certain query result. If the field offset isn't specified, the next field that wasn't yet retrieved by\r
+                fetchField() is retrieved.        */\r
+\r
+        function &_FetchField($fieldOffset = -1)\r
+        {\r
+                 $fld = new ADOFieldObject;\r
+                                $fieldOffset += 1;\r
+                 $fld->name =OCIcolumnname($this->_queryID, $fieldOffset);\r
+                 $fld->type = OCIcolumntype($this->_queryID, $fieldOffset);\r
+                 $fld->max_length = OCIcolumnsize($this->_queryID, $fieldOffset);\r
+                                if ($fld->type == 'NUMBER') {\r
+                                       //$p = OCIColumnPrecision($this->_queryID, $fieldOffset);\r
+                                       $sc = OCIColumnScale($this->_queryID, $fieldOffset);\r
+                                       if ($sc == 0) $fld->type = 'INT';\r
+                                }\r
+                 return $fld;\r
+        }\r
+       \r
+       /* For some reason, OCIcolumnname fails when called after _initrs() so we cache it */\r
+       function &FetchField($fieldOffset = -1)\r
+       {\r
+               return $this->_fieldobjs[$fieldOffset];\r
+       }\r
+       \r
+       /**\r
+        * return recordset as a 2-dimensional array.\r
+        *\r
+        * @param [nRows]  is the number of rows to return. -1 means every row.\r
+        *\r
+        * @return an array indexed by the rows (0-based) from the recordset\r
+        */\r
+       function &GetArray($nRows = -1) \r
+       {\r
+               $results = array();\r
+               /*if ($nRows == -1) {\r
+                // doesnt work becoz it creates 2D array by column instead of row\r
+                       $n = OCIFetchStatement($this->_queryID,$results);\r
+                       print_r($results);\r
+                       $this->EOF = true;\r
+                       $this->_currentRow = $n;\r
+                       return $results;\r
+               }*/\r
+               \r
+               $results = array();\r
+               $cnt = 0;\r
+               while (!$this->EOF && $nRows != $cnt) {\r
+                       $results[$cnt++] = $this->fields;\r
+                       $this->MoveNext();\r
+               }\r
+               \r
+               return $results;\r
+       }\r
+       \r
+       // 10% speedup to move MoveNext to child class\r
+       function MoveNext() \r
+       {\r
+               if (!$this->EOF) {              \r
+                       $this->_currentRow++;\r
+                       if(@OCIfetchinto($this->_queryID,$this->fields,$this->fetchMode))\r
+                               return true;\r
+                       \r
+                       $this->EOF = true;\r
+               }\r
+               return false;\r
+       }       \r
+       \r
+       /* Optimize SelectLimit() by using OCIFetch() instead of OCIFetchInto() */\r
+       function &GetArrayLimit($nrows,$offset=-1) \r
+       {\r
+               if ($offset <= 0) return $this->GetArray($nrows);\r
+               for ($i=1; $i < $offset; $i++) \r
+                       if (!@OCIFetch($this->_queryID)) return array();\r
+                       \r
+               if (!@OCIfetchinto($this->_queryID,$this->fields,$this->fetchMode)) return array();\r
+               $results = array();\r
+               $cnt = 0;\r
+               while (!$this->EOF && $nrows != $cnt) {\r
+                       $results[$cnt++] = $this->fields;\r
+                       $this->MoveNext();\r
+               }\r
+               \r
+               return $results;\r
+       }\r
+       \r
+       /* Use associative array to get fields array */\r
+       function Fields($colname)\r
+       {\r
+               if (!$this->bind) {\r
+                       $this->bind = array();\r
+                       for ($i=0; $i < $this->_numOfFields; $i++) {\r
+                               $o = $this->FetchField($i);\r
+                               $this->bind[strtoupper($o->name)] = $i;\r
+                       }\r
+               }\r
+               \r
+                return $this->fields[$this->bind[strtoupper($colname)]];\r
+               \r
+       }\r
+       \r
+        function _initrs()\r
+        {\r
+            $this->_numOfRows = -1;\r
+            $this->_numOfFields = OCInumcols($this->_queryID);\r
+                       if ($this->_numOfFields>0) {\r
+                               $this->_fieldobjs = array();\r
+                               $max = $this->_numOfFields;\r
+                               for ($i=0;$i<$max; $i++) $this->_fieldobjs[] = $this->_FetchField($i);\r
+                       }\r
+               //print_r($this->_fieldobjs);\r
+        }\r
+\r
+       \r
+        function _seek($row)\r
+        {\r
+                return false;\r
+        }\r
+\r
+        function _fetch() {\r
+                return @OCIfetchinto($this->_queryID,$this->fields,$this->fetchMode);\r
+        }\r
+\r
+        /*        close() only needs to be called if you are worried about using too much memory while your script\r
+                is running. All associated result memory for the specified result identifier will automatically be freed.        */\r
+\r
+        function _close() {\r
+              OCIFreeStatement($this->_queryID);\r
+                         $this->_queryID = false;\r
+        }\r
+\r
+        function MetaType($t,$len=-1)\r
+        {\r
+               switch (strtoupper($t)) {\r
+               case 'VARCHAR':\r
+               case 'VARCHAR2':\r
+               case 'CHAR':\r
+                       case 'VARBINARY':\r
+                       case 'BINARY':\r
+                               if ($len <= $this->blobSize) return 'C';\r
+               case 'LONG':\r
+                       case 'LONG VARCHAR':\r
+                       case 'CLOB';\r
+                               return 'X';\r
+                               \r
+                       case 'LONG RAW':\r
+                       case 'LONG VARBINARY':\r
+                       case 'BLOB':\r
+                     return 'B';\r
+       \r
+               case 'DATE': return 'D';\r
+       \r
+               //case 'T': return 'T';\r
+       \r
+               case 'BIT': return 'L';\r
+                       case 'INT': \r
+                       case 'SMALLINT':\r
+                       case 'INTEGER': return 'I';\r
+            default: return 'N';\r
+            }\r
+        }\r
+}\r
+?>\r
diff --git a/libraries/adodb/adodb-odbc.inc.php b/libraries/adodb/adodb-odbc.inc.php
new file mode 100755 (executable)
index 0000000..dda609d
--- /dev/null
@@ -0,0 +1,369 @@
+<?php\r
+/* \r
+V1.53 13 Nov 2001 (c) 2000, 2001 John Lim (jlim@natsoft.com.my). All rights reserved.\r
+  Released under both BSD license and Lesser GPL library license. \r
+  Whenever there is any discrepancy between the two licenses, \r
+  the BSD license will take precedence. \r
+Set tabs to 4 for best viewing.\r
+  \r
+  Latest version is available at http://php.weblogs.com/\r
+  \r
+  Requires ODBC. Works on Windows and Unix.\r
+*/\r
+  define("_ADODB_ODBC_LAYER", 1 );\r
+        \r
+/*--------------------------------------------------------------------------------------\r
+--------------------------------------------------------------------------------------*/\r
+\r
+  \r
+class ADODB_odbc extends ADOConnection {\r
+       var $databaseType = "odbc";     \r
+       var $fmtDate = "'Y-m-d'";\r
+       var $fmtTimeStamp = "'Y-m-d, h:i:sA'";\r
+       var $replaceQuote = "''"; // string to use to replace quotes\r
+       var $dataProvider = "odbc";\r
+       var $hasAffectedRows = true;\r
+       var $binmode = ODBC_BINMODE_RETURN;\r
+       //var $longreadlen = 8000; // default number of chars to return for a Blob/Long field\r
+       var $_bindInputArray = false;      \r
+       var $_haserrorfunctions = false;\r
+       var $curmode = SQL_CUR_USE_DRIVER; // See sqlext.h, SQL_CUR_DEFAULT == SQL_CUR_USE_DRIVER == 2L\r
+       \r
+       function ADODB_odbc() \r
+       {       \r
+               $this->_haserrorfunctions = (strnatcmp(PHP_VERSION,'4.0.5')>=0);\r
+       }\r
+\r
+       function ErrorMsg()\r
+       {\r
+               if ($this->_haserrorfunctions) {\r
+       //      print_r($this->_connectionID);\r
+                       if (empty($this->_connectionID)) return @odbc_errormsg();\r
+                       return @odbc_errormsg($this->_connectionID);\r
+               } else return ADOConnection::ErrorMsg();\r
+       }\r
+       function ErrorNo()\r
+       {\r
+               if ($this->_haserrorfunctions) {\r
+                       if (empty($this->_connectionID)) $e = @odbc_error(); \r
+                       else $e = @odbc_error($this->_connectionID);\r
+                       \r
+                        // bug in 4.0.6, error number can be corrupted string (should be 6 digits)\r
+                        // so we check and patch\r
+                       if (strlen($e)<=2) return 0;\r
+                       return $e;\r
+               } else return ADOConnection::ErrorNo();\r
+       }\r
+       \r
+       \r
+       // returns true or false\r
+       function _connect($argDSN, $argUsername, $argPassword, $argDatabasename)\r
+       {\r
+       global $php_errormsg;\r
+       \r
+               $php_errormsg = '';\r
+               $this->_connectionID = odbc_connect($argDSN,$argUsername,$argPassword,$this->curmode);\r
+               $this->_errorMsg = $php_errormsg;\r
+\r
+               //if ($this->_connectionID) odbc_autocommit($this->_connectionID,true);\r
+               return $this->_connectionID != false;\r
+       }\r
+       \r
+       // returns true or false\r
+       function _pconnect($argDSN, $argUsername, $argPassword, $argDatabasename)\r
+       {\r
+       global $php_errormsg;\r
+               $php_errormsg = '';\r
+               $this->_connectionID = odbc_pconnect($argDSN,$argUsername,$argPassword,$this->curmode);\r
+               $this->_errorMsg = $php_errormsg;\r
+               \r
+               //if ($this->_connectionID) odbc_autocommit($this->_connectionID,true);\r
+               return $this->_connectionID != false;\r
+       }\r
+\r
+       function BeginTrans()\r
+       {       \r
+        return odbc_autocommit($this->_connectionID,false);\r
+       }\r
+       \r
+       function CommitTrans()\r
+       {\r
+        $ret = odbc_commit($this->_connectionID);\r
+               odbc_autocommit($this->_connectionID,true);\r
+               return $ret;\r
+       }\r
+       \r
+       function RollbackTrans()\r
+       {\r
+        $ret = odbc_rollback($this->_connectionID);\r
+               odbc_autocommit($this->_connectionID,true);\r
+               return $ret;\r
+       }\r
+       \r
+       function &MetaTables()\r
+       {\r
+               $qid = odbc_tables($this->_connectionID);\r
+               $rs = new ADORecordSet_odbc($qid);\r
+               //print_r($rs);\r
+               $arr = &$rs->GetArray();\r
+               $rs->Close();\r
+               $arr2 = array();\r
+               for ($i=0; $i < sizeof($arr); $i++) {\r
+                       if ($arr[$i][2]) $arr2[] = $arr[$i][2];\r
+               }\r
+               return $arr2;\r
+       }\r
+       \r
+/*\r
+/ SQL data type codes /\r
+#define        SQL_UNKNOWN_TYPE        0\r
+#define SQL_CHAR            1\r
+#define SQL_NUMERIC         2\r
+#define SQL_DECIMAL         3\r
+#define SQL_INTEGER         4\r
+#define SQL_SMALLINT        5\r
+#define SQL_FLOAT           6\r
+#define SQL_REAL            7\r
+#define SQL_DOUBLE          8\r
+#if (ODBCVER >= 0x0300)\r
+#define SQL_DATETIME        9\r
+#endif\r
+#define SQL_VARCHAR        12\r
+\r
+/ One-parameter shortcuts for date/time data types /\r
+#if (ODBCVER >= 0x0300)\r
+#define SQL_TYPE_DATE      91\r
+#define SQL_TYPE_TIME      92\r
+#define SQL_TYPE_TIMESTAMP 93\r
+*/\r
+       function ODBCTypes($t)\r
+       {\r
+               switch ((integer)$t) {\r
+               case 1: \r
+               case 12:\r
+               case 0:\r
+                       return 'C';\r
+               case -1: //text\r
+                       return 'X';\r
+               case -4: //image\r
+                       return 'B';\r
+                               \r
+               case 91:\r
+               case 11:\r
+                       return 'D';\r
+                       \r
+               case 92:\r
+               case 93:\r
+               case 9: return 'T';\r
+               case 4:\r
+               case 5:\r
+               case -6:\r
+                       return 'I';\r
+                       \r
+               case -11: // uniqidentifier\r
+                       return 'R';\r
+               case -7: //bit\r
+                       return 'L';\r
+               \r
+               default:\r
+                       return 'N';\r
+               }\r
+       }\r
+       \r
+       function &MetaColumns($table)\r
+       {\r
+               $table = strtoupper($table);\r
+               \r
+       /* // for some reason, cannot view only 1 table with odbc_columns -- bug?\r
+               $qid = odbc_tables($this->_connectionID);\r
+               $rs = new ADORecordSet_odbc($qid);\r
+               if (!$rs) return false;\r
+               while (!$rs->EOF) {\r
+                       if ($table == strtoupper($rs->fields[2])) {\r
+                               $q = $rs->fields[0];\r
+                               $o = $rs->fields[1];\r
+                               break;\r
+                       }\r
+                       $rs->MoveNext();\r
+               }\r
+               $rs->Close();\r
+               \r
+               $qid = odbc_columns($this->_connectionID,$q,$o,strtoupper($table),'%');\r
+       */\r
+               $qid = odbc_columns($this->_connectionID);\r
+               $rs = new ADORecordSet_odbc($qid);\r
+               if (!$rs) return false;\r
+               \r
+               $retarr = array();\r
+               while (!$rs->EOF) {\r
+                       if (strtoupper($rs->fields[2]) == $table) {\r
+                               $fld = new ADOFieldObject();\r
+                               $fld->name = $rs->fields[3];\r
+                               $fld->type = $this->ODBCTypes($rs->fields[4]);\r
+                               $fld->max_length = $rs->fields[7];\r
+                               $retarr[strtoupper($fld->name)] = $fld; \r
+                       } else if (sizeof($retarr)>0)\r
+                               break;\r
+                       $rs->MoveNext();\r
+               }\r
+               $rs->Close(); //-- crashes 4.03pl1 -- why?\r
+               \r
+               return $retarr;\r
+       }\r
+       \r
+       function &Prepare($sql)\r
+       {\r
+               if ($this->debug) {\r
+                       print "<hr>($this->databaseType): ".htmlspecialchars($sql)."<hr>";\r
+               }\r
+               return odbc_prepare($this->_connectionID,$sql);\r
+       }\r
+\r
+       /* returns queryID or false */\r
+       function _query($sql,$inputarr=false) \r
+       {\r
+       GLOBAL $php_errormsg;\r
+               $php_errormsg = '';\r
+               $this->_error = '';\r
+               \r
+               if ($inputarr) {\r
+                       if (is_resource($sql)) $stmtid = $sql;\r
+                       else $stmtid = odbc_prepare($this->_connectionID,$sql);\r
+                       if ($stmtid == false) {\r
+                               $this->_errorMsg = $php_errormsg;\r
+                               return false;\r
+                       }\r
+                       //print_r($inputarr);\r
+                       if (! odbc_execute($stmtid,$inputarr)) {\r
+                               @odbc_free_result($stmtid);\r
+                               return false;\r
+                       }\r
+                       \r
+               } else\r
+                       $stmtid = odbc_exec($this->_connectionID,$sql);\r
+               \r
+               if ($stmtid) {\r
+                       odbc_binmode($stmtid,$this->binmode);\r
+                       odbc_longreadlen($stmtid,$this->maxblobsize);\r
+               }\r
+               $this->_errorMsg = $php_errormsg;\r
+               return $stmtid;\r
+       }\r
+\r
+       /*\r
+               Insert a null into the blob field of the table first.\r
+               Then use UpdateBlob to store the blob.\r
+               \r
+               Usage:\r
+                \r
+               $conn->Execute('INSERT INTO blobtable (id, blobcol) VALUES (1, null)');\r
+               $conn->UpdateBlob('blobtable','blobcol',$blob,'id=1');\r
+       */\r
+       function UpdateBlob($table,$column,$val,$where,$blobtype='BLOB')\r
+       {\r
+               return $this->Execute("UPDATE $table SET $column=? WHERE $where",array($val)) != false;\r
+       }\r
+       \r
+       // returns true or false\r
+       function _close()\r
+       {\r
+               return @odbc_close($this->_connectionID);\r
+       }\r
+       \r
+        function _affectedrows()\r
+        {\r
+                return  odbc_num_rows($this->_queryID);\r
+        }\r
+       \r
+}\r
+       \r
+/*--------------------------------------------------------------------------------------\r
+        Class Name: Recordset\r
+--------------------------------------------------------------------------------------*/\r
+\r
+class ADORecordSet_odbc extends ADORecordSet { \r
+       \r
+       var $bind = false;\r
+       var $databaseType = "odbc";             \r
+       var $dataProvider = "odbc";\r
+       \r
+       function ADORecordSet_odbc($id)\r
+       {\r
+       global $ADODB_FETCH_MODE;\r
+       \r
+               $this->fetchMode = $ADODB_FETCH_MODE;\r
+               return $this->ADORecordSet($id);\r
+       }\r
+\r
+\r
+       // returns the field object\r
+       function &FetchField($fieldOffset = -1) {\r
+               \r
+               $off=$fieldOffset+1; // offsets begin at 1\r
+               \r
+               $o= new ADOFieldObject();\r
+               $o->name = @odbc_field_name($this->_queryID,$off);\r
+               $o->type = @odbc_field_type($this->_queryID,$off);\r
+               $o->max_length = @odbc_field_len($this->_queryID,$off);\r
+               \r
+               return $o;\r
+       }\r
+       \r
+       /* Use associative array to get fields array */\r
+       function Fields($colname)\r
+       {\r
+               if (!$this->bind) {\r
+                       $this->bind = array();\r
+                       for ($i=0; $i < $this->_numOfFields; $i++) {\r
+                               $o = $this->FetchField($i);\r
+                               $this->bind[strtoupper($o->name)] = $i;\r
+                       }\r
+               }\r
+\r
+                return $this->fields[$this->bind[strtoupper($colname)]];\r
+               \r
+       }\r
+       \r
+               \r
+       function _initrs()\r
+       {\r
+               $this->_numOfRows = @odbc_num_rows($this->_queryID);\r
+               $this->_numOfFields = @odbc_num_fields($this->_queryID);\r
+       }       \r
+       \r
+       function _seek($row)\r
+       {\r
+               return false;\r
+       }\r
+       \r
+       function MoveNext() \r
+       {\r
+               if ($this->_numOfRows != 0 && !$this->EOF) {            \r
+                       $this->_currentRow++;\r
+                       $row = 0;\r
+                       if (odbc_fetch_into($this->_queryID,$row,$this->fields)) return true;\r
+               }\r
+               $this->EOF = true;\r
+               return false;\r
+       }       \r
+       \r
+       function _fetch()\r
+       {\r
+               $row = 0;\r
+               $rez = odbc_fetch_into($this->_queryID,$row,$this->fields);\r
+               if ($rez && $this->fetchMode == ADODB_FETCH_ASSOC) {\r
+                       $this->fields = $this->GetRowAssoc(false);\r
+               }\r
+               return $rez;\r
+       }\r
+       \r
+       function _close() {\r
+               \r
+               return @odbc_free_result($this->_queryID);              \r
+       }\r
+       \r
+\r
+\r
+}\r
+\r
+?>
\ No newline at end of file
diff --git a/libraries/adodb/adodb-odbc_mssql.inc.php b/libraries/adodb/adodb-odbc_mssql.inc.php
new file mode 100755 (executable)
index 0000000..8045281
--- /dev/null
@@ -0,0 +1,38 @@
+<?php\r
+/* \r
+V1.53 13 Nov 2001 (c) 2000, 2001 John Lim (jlim@natsoft.com.my). All rights reserved.\r
+  Released under both BSD license and Lesser GPL library license. \r
+  Whenever there is any discrepancy between the two licenses, \r
+  the BSD license will take precedence. \r
+Set tabs to 4 for best viewing.\r
+  \r
+  Latest version is available at http://php.weblogs.com/\r
+  \r
+  MSSQL support via ODBC. Requires ODBC. Works on Windows and Unix. \r
+  For Unix configuration, see http://phpbuilder.com/columns/alberto20000919.php3\r
+*/\r
+\r
+if (!defined('_ADODB_ODBC_LAYER')) {\r
+       include(ADODB_DIR."/adodb-odbc.inc.php");\r
+}\r
+\r
\r
+class  ADODB_odbc_mssql extends ADODB_odbc {   \r
+       var $databaseType = 'odbc_mssql';\r
+       var $fmtDate = "'Y-m-d'";\r
+       var $fmtTimeStamp = "'Y-m-d h:i:sA'";\r
+       var $_bindInputArray = true;\r
+       var $hasTop = true;             // support mssql/interbase SELECT TOP 10 * FROM TABLE\r
+\r
+} \r
\r
+class  ADORecordSet_odbc_mssql extends ADORecordSet_odbc {     \r
+       \r
+       var $databaseType = 'odbc_mssql';\r
+       \r
+       function ADORecordSet_odbc_mssql($id)\r
+       {\r
+               return $this->ADORecordSet_odbc($id);\r
+       }\r
+}\r
+?>
\ No newline at end of file
diff --git a/libraries/adodb/adodb-odbc_oracle.inc.php b/libraries/adodb/adodb-odbc_oracle.inc.php
new file mode 100755 (executable)
index 0000000..5d8301f
--- /dev/null
@@ -0,0 +1,104 @@
+<?php\r
+/* \r
+V1.53 13 Nov 2001 (c) 2000, 2001 John Lim (jlim@natsoft.com.my). All rights reserved.\r
+  Released under both BSD license and Lesser GPL library license. \r
+  Whenever there is any discrepancy between the two licenses, \r
+  the BSD license will take precedence. \r
+Set tabs to 4 for best viewing.\r
+  \r
+  Latest version is available at http://php.weblogs.com/\r
+  \r
+  Oracle support via ODBC. Requires ODBC. Works on Windows. \r
+*/\r
+\r
+if (!defined('_ADODB_ODBC_LAYER')) {\r
+       include(ADODB_DIR."/adodb-odbc.inc.php");\r
+}\r
+\r
\r
+class  ADODB_odbc_oracle extends ADODB_odbc {  \r
+       var $databaseType = 'odbc_oracle';\r
+       var $replaceQuote = "''"; // string to use to replace quotes\r
+    var $concat_operator='||';\r
+       var $fmtDate = "'Y-m-d 00:00:00'"; \r
+       var $fmtTimeStamp = "'Y-m-d h:i:sA'";\r
+       var $metaTablesSQL = 'select table_name from cat';\r
+       var $metaColumnsSQL = "select cname,coltype,width from col where tname='%s' order by colno";\r
+       //var $_bindInputArray = false;\r
+       \r
+       function &MetaTables() \r
+       {\r
+               if ($this->metaTablesSQL) {\r
+                       $rs = $this->Execute($this->metaTablesSQL);\r
+                       if ($rs === false) return false;\r
+                       $arr = $rs->GetArray();\r
+                       $arr2 = array();\r
+                       for ($i=0; $i < sizeof($arr); $i++) {\r
+                               $arr2[] = $arr[$i][0];\r
+                       }\r
+                       $rs->Close();\r
+                       return $arr2;\r
+               }\r
+               return false;\r
+       }\r
+       \r
+    function &MetaColumns($table) \r
+       {\r
+               if (!empty($this->metaColumnsSQL)) {\r
+               \r
+                       $rs = $this->Execute(sprintf($this->metaColumnsSQL,strtoupper($table)));\r
+                       if ($rs === false) return false;\r
+\r
+                       $retarr = array();\r
+                       while (!$rs->EOF) { //print_r($rs->fields);\r
+                               $fld = new ADOFieldObject();\r
+                               $fld->name = $rs->fields[0];\r
+                               $fld->type = $rs->fields[1];\r
+                               $fld->max_length = $rs->fields[2];\r
+                               $retarr[strtoupper($fld->name)] = $fld; \r
+                               \r
+                               $rs->MoveNext();\r
+                       }\r
+                       $rs->Close();\r
+                       return $retarr; \r
+               }\r
+               return false;\r
+       }\r
+\r
+       // returns true or false\r
+       function _connect($argDSN, $argUsername, $argPassword, $argDatabasename)\r
+       {\r
+       global $php_errormsg;\r
+       \r
+               $php_errormsg = '';\r
+               $this->_connectionID = odbc_connect($argDSN,$argUsername,$argPassword,SQL_CUR_USE_ODBC );\r
+               $this->_errorMsg = $php_errormsg;\r
+               \r
+               $this->Execute("ALTER SESSION SET NLS_DATE_FORMAT='YYYY-MM-DD HH24:MI:SS'");\r
+               //if ($this->_connectionID) odbc_autocommit($this->_connectionID,true);\r
+               return $this->_connectionID != false;\r
+       }\r
+       // returns true or false\r
+       function _pconnect($argDSN, $argUsername, $argPassword, $argDatabasename)\r
+       {\r
+       global $php_errormsg;\r
+               $php_errormsg = '';\r
+               $this->_connectionID = odbc_pconnect($argDSN,$argUsername,$argPassword,SQL_CUR_USE_ODBC );\r
+               $this->_errorMsg = $php_errormsg;\r
+               \r
+               $this->Execute("ALTER SESSION SET NLS_DATE_FORMAT='YYYY-MM-DD HH24:MI:SS'");\r
+               //if ($this->_connectionID) odbc_autocommit($this->_connectionID,true);\r
+               return $this->_connectionID != false;\r
+       }\r
+} \r
\r
+class  ADORecordSet_odbc_oracle extends ADORecordSet_odbc {    \r
+       \r
+       var $databaseType = 'odbc_oracle';\r
+       \r
+       function ADORecordSet_odbc_oracle($id)\r
+       {\r
+               return $this->ADORecordSet_odbc($id);\r
+       }\r
+}\r
+?>
\ No newline at end of file
diff --git a/libraries/adodb/adodb-oracle.inc.php b/libraries/adodb/adodb-oracle.inc.php
new file mode 100755 (executable)
index 0000000..5dce538
--- /dev/null
@@ -0,0 +1,243 @@
+<?php\r
+/*\r
+V1.53 13 Nov 2001 (c) 2000, 2001 John Lim (jlim@natsoft.com.my). All rights reserved.\r
+  Released under both BSD license and Lesser GPL library license. \r
+  Whenever there is any discrepancy between the two licenses, \r
+  the BSD license will take precedence.\r
+\r
+  Latest version is available at http://php.weblogs.com/\r
+  \r
+  Oracle data driver. Requires Oracle client. Works on Windows and Unix and Oracle 7 and 8.\r
+  \r
+  If you are using Oracle 8, use the oci8 driver as ErrorMsg() and ErrorNo() work properly,\r
+  \r
+*/\r
+\r
+// select table_name from cat -- MetaTables\r
+// \r
+class ADODB_oracle extends ADOConnection {\r
+    var $databaseType = "oracle";\r
+    var $replaceQuote = "\'"; // string to use to replace quotes\r
+    var $concat_operator='||';\r
+       var $_curs;\r
+       var $_initdate = true; // init date to YYYY-MM-DD\r
+       var $metaTablesSQL = 'select table_name from cat';      \r
+       var $metaColumnsSQL = "select cname,coltype,width from col where tname='%s' order by colno";\r
+      \r
+       function ADODB_oracle() \r
+       {\r
+    }\r
+\r
+       // format and return date string in database date format\r
+       function DBDate($d)\r
+       {\r
+               return 'TO_DATE('.date($this->fmtDate,$d).",'YYYY-MM-DD')";\r
+       }\r
+       \r
+       // format and return date string in database timestamp format\r
+       function DBTimeStamp($ts)\r
+       {\r
+               return 'TO_DATE('.date($this->fmtTimeStamp,$ts).",'YYYY-MM-DD, HH:RR:SSAM')";\r
+       }\r
+       \r
+        function BeginTrans()\r
+       {      \r
+               $this->autoCommit = false;\r
+               ora_commitoff($this->_connectionID);\r
+               return true;\r
+       }\r
+       \r
+       function CommitTrans()\r
+       {\r
+           $ret = ora_commit($this->_connectionID);\r
+              ora_commiton($this->_connectionID);\r
+              return $ret;\r
+       }\r
+       \r
+       function RollbackTrans()\r
+       {\r
+                $ret = ora_rollback($this->_connectionID);\r
+                ora_commiton($this->_connectionID);\r
+               return $ret;\r
+       }\r
+        \r
+        function SelectDB($dbName) {\r
+               return false;\r
+        }\r
+\r
+       /* there seems to be a bug in the oracle extension -- always returns ORA-00000 - no error */\r
+        function ErrorMsg() {\r
+                $this->_errorMsg = @ora_error($this->_curs);\r
+               if (!$this->_errorMsg) $this->_errorMsg = @ora_error($this->_connectionID);\r
+                return $this->_errorMsg;\r
+        }\r
+       \r
+       function ErrorNo() {\r
+                $err = @ora_errorcode($this->_curs);\r
+               if (!$err) return @ora_errorcode($this->_connectionID);\r
+        }\r
+       \r
+\r
+        // returns true or false\r
+        function _connect($argHostname, $argUsername, $argPassword, $argDatabasename)\r
+        {\r
+               if ($argHostname) putenv("ORACLE_HOME=$argHostname");\r
+               //if ($argHostname) print "<p>Connect: 1st argument should be left blank for $this->databaseType</p>";\r
+                $this->_connectionID = ora_logon($argUsername,$argPassword);\r
+                if ($this->_connectionID === false) return false;\r
+                if ($this->autoCommit) ora_commiton($this->_connectionID);\r
+               if ($this->_initdate) $this->Execute("ALTER SESSION SET NLS_DATE_FORMAT='YYYY-MM-DD'");\r
+\r
+                return true;\r
+        }\r
+        // returns true or false\r
+        function _pconnect($argHostname, $argUsername, $argPassword, $argDatabasename)\r
+        {\r
+               if ($argHostname) putenv("ORACLE_HOME=$argHostname");\r
+               //if ($argHostname) print "<p>PConnect: 1st argument should be left blank for $this->databaseType</p>";\r
+                $this->_connectionID = ora_plogon($argUsername,$argPassword);\r
+                if ($this->_connectionID === false) return false;\r
+                if ($this->autoCommit) ora_commiton($this->_connectionID);\r
+               if ($this->_initdate) $this->Execute("ALTER SESSION SET NLS_DATE_FORMAT='YYYY-MM-DD'");\r
+\r
+                return true;\r
+        }\r
+\r
+        // returns query ID if successful, otherwise false\r
+        function _query($sql,$inputarr)\r
+        {\r
+                 $curs = ora_open($this->_connectionID);\r
+                \r
+                if ($curs === false) return false;\r
+               $this->_curs = $curs;\r
+               if (!ora_parse($curs,$sql)) return false;\r
+               if (ora_exec($curs)) return $curs;\r
+               \r
+                @ora_close($curs);\r
+                 return false;\r
+        }\r
+\r
+        // returns true or false\r
+        function _close()\r
+        {\r
+               if (!$this->autoCommit) ora_rollback($this->_connectionID);\r
+                return @ora_close($this->_connectionID);\r
+        }\r
+\r
+\r
+}\r
+\r
+/*--------------------------------------------------------------------------------------\r
+         Class Name: Recordset\r
+--------------------------------------------------------------------------------------*/\r
+\r
+class ADORecordset_oracle extends ADORecordSet {\r
+\r
+        var $databaseType = "oracle";\r
+       var $bind = false;\r
+       \r
+        function ADORecordset_oracle($queryID)\r
+        {\r
+               $this->_queryID = $queryID;\r
+       \r
+               $this->_inited = true;\r
+               $this->fields = array();\r
+               if ($queryID) {\r
+                       $this->_currentRow = 0;\r
+                       $this->EOF = !$this->_fetch();\r
+                       @$this->_initrs();\r
+               } else {\r
+                       $this->_numOfRows = 0;\r
+                       $this->_numOfFields = 0;\r
+                       $this->EOF = true;\r
+               }\r
+               \r
+               return $this->_queryID;\r
+        }\r
+\r
+\r
+\r
+        /*        Returns: an object containing field information.\r
+                Get column information in the Recordset object. fetchField() can be used in order to obtain information about\r
+                fields in a certain query result. If the field offset isn't specified, the next field that wasn't yet retrieved by\r
+                fetchField() is retrieved.        */\r
+\r
+        function FetchField($fieldOffset = -1)\r
+        {\r
+                 $fld = new ADOFieldObject;\r
+                 $fld->name = ora_columnname($this->_queryID, $fieldOffset);\r
+                 $fld->type = ora_columntype($this->_queryID, $fieldOffset);\r
+                 $fld->max_length = ora_columnsize($this->_queryID, $fieldOffset);\r
+                 return $fld;\r
+        }\r
+\r
+       /* Use associative array to get fields array */\r
+       function Fields($colname)\r
+       {\r
+               if (!$this->bind) {\r
+                       $this->bind = array();\r
+                       for ($i=0; $i < $this->_numOfFields; $i++) {\r
+                               $o = $this->FetchField($i);\r
+                               $this->bind[strtoupper($o->name)] = $i;\r
+                       }\r
+               }\r
+               \r
+                return $this->fields[$this->bind[strtoupper($colname)]];\r
+               \r
+       }\r
+       \r
+        function _initrs()\r
+        {\r
+                $this->_numOfRows = -1;\r
+                $this->_numOfFields = @ora_numcols($this->_queryID);\r
+        }\r
+\r
+       \r
+        function _seek($row)\r
+        {\r
+                return false;\r
+        }\r
+\r
+        function _fetch($ignore_fields=false) {\r
+       // should remove call by reference, but ora_fetch_into requires it in 4.0.3pl1\r
+                return @ora_fetch_into($this->_queryID,&$this->fields,ORA_FETCHINTO_NULLS);\r
+        }\r
+\r
+        /*        close() only needs to be called if you are worried about using too much memory while your script\r
+                is running. All associated result memory for the specified result identifier will automatically be freed.        */\r
+\r
+        function _close() {\r
+                return @ora_close($this->_queryID);\r
+        }\r
+\r
+        function MetaType($t,$len=-1)\r
+        {\r
+                switch (strtoupper($t)) {\r
+                case 'VARCHAR':\r
+                case 'VARCHAR2':\r
+                case 'CHAR':\r
+               case 'VARBINARY':\r
+               case 'BINARY':\r
+                        if ($len <= $this->blobSize) return 'C';\r
+                case 'LONG':\r
+               case 'LONG VARCHAR':\r
+               case 'CLOB':\r
+                       return 'X';\r
+                case 'LONG RAW':\r
+               case 'LONG VARBINARY':\r
+               case 'BLOB':\r
+                        return 'B';\r
+\r
+                case 'DATE': return 'D';\r
+\r
+                //case 'T': return 'T';\r
+\r
+                case 'BIT': return 'L';\r
+               case 'INT': \r
+               case 'SMALLINT':\r
+               case 'INTEGER': return 'I';\r
+                default: return 'N';\r
+                }\r
+        }\r
+}\r
+?>
\ No newline at end of file
diff --git a/libraries/adodb/adodb-pear.inc.php b/libraries/adodb/adodb-pear.inc.php
new file mode 100755 (executable)
index 0000000..6d8385d
--- /dev/null
@@ -0,0 +1,348 @@
+<?php\r
+/** \r
+ * @version V1.53 13 Nov 2001 (c) 2000, 2001 John Lim (jlim@natsoft.com.my). All rights reserved.\r
+ * Released under both BSD license and Lesser GPL library license. \r
+ * Whenever there is any discrepancy between the two licenses, \r
+ * the BSD license will take precedence. \r
+ *\r
+ * Set tabs to 4 for best viewing.\r
+ * \r
+ * PEAR DB Emulation Layer for ADODB.\r
+ *\r
+ * The following code is modelled on PEAR DB code by Stig Bakken <ssb@fast.no>                                   |\r
+ * and Tomas V.V.Cox <cox@idecnet.com>    \r
+ */\r
+\r
+ /*\r
+ We support:\r
\r
+ DB_Common\r
+ ---------\r
+       query - returns PEAR_Error on error\r
+       limitQuery - return PEAR_Error on error\r
+       prepare - does not return PEAR_Error on error\r
+       execute - does not return PEAR_Error on error\r
+       setFetchMode - supports ASSOC and ORDERED\r
+       errorNative\r
+       quote\r
+       nextID\r
+       free\r
+       \r
+ DB_Result\r
+ ---------\r
+       numRows - returns -1 if not supported\r
+       numCols\r
+       fetchInto - does not support passing of fetchmode\r
+       fetchRows - does not support passing of fetchmode\r
+       free\r
+ */\r
\r
+define('ADODB_PEAR',dirname(__FILE__));\r
+require_once "PEAR.php";\r
+require_once ADODB_PEAR."/adodb-errorpear.inc.php";\r
+require_once ADODB_PEAR."/adodb.inc.php";\r
+\r
+if (!defined('DB_OK')) {\r
+define("DB_OK",    0);\r
+define("DB_ERROR",-1);\r
+/**\r
+ * This is a special constant that tells DB the user hasn't specified\r
+ * any particular get mode, so the default should be used.\r
+ */\r
+\r
+define('DB_FETCHMODE_DEFAULT', 0);\r
+\r
+/**\r
+ * Column data indexed by numbers, ordered from 0 and up\r
+ */\r
+\r
+define('DB_FETCHMODE_ORDERED', 1);\r
+\r
+/**\r
+ * Column data indexed by column names\r
+ */\r
+\r
+define('DB_FETCHMODE_ASSOC', 2);\r
+\r
+/* for compatibility */\r
+\r
+define('DB_GETMODE_ORDERED', DB_FETCHMODE_ORDERED);\r
+define('DB_GETMODE_ASSOC',   DB_FETCHMODE_ASSOC);\r
+\r
+/**\r
+ * these are constants for the tableInfo-function\r
+ * they are bitwised or'ed. so if there are more constants to be defined\r
+ * in the future, adjust DB_TABLEINFO_FULL accordingly\r
+ */\r
+\r
+define('DB_TABLEINFO_ORDER', 1);\r
+define('DB_TABLEINFO_ORDERTABLE', 2);\r
+define('DB_TABLEINFO_FULL', 3);\r
+}\r
+\r
+/**\r
+ * The main "DB" class is simply a container class with some static\r
+ * methods for creating DB objects as well as some utility functions\r
+ * common to all parts of DB.\r
+ *\r
+ */\r
+\r
+class DB\r
+{\r
+    /**\r
+     * Create a new DB object for the specified database type\r
+     *\r
+     * @param $type string database type, for example "mysql"\r
+     *\r
+     * @return object a newly created DB object, or a DB error code on\r
+     * error\r
+     */\r
+\r
+    function &factory($type)\r
+    {\r
+        @include_once("adodb-$type.inc.php");\r
+\r
+        $classname = "DB_${type}";\r
+\r
+        if (!class_exists($classname)) {\r
+            return PEAR::raiseError(null, DB_ERROR_NOT_FOUND,\r
+                                    null, null, null, 'DB_Error', true);\r
+        }\r
+\r
+        @$obj =& new $classname;\r
+\r
+        return $obj;\r
+    }\r
+\r
+    /**\r
+     * Create a new DB object and connect to the specified database\r
+     *\r
+     * @param $dsn mixed "data source name", see the DB::parseDSN\r
+     * method for a description of the dsn format.  Can also be\r
+     * specified as an array of the format returned by DB::parseDSN.\r
+     *\r
+     * @param $options mixed if boolean (or scalar), tells whether\r
+     * this connection should be persistent (for backends that support\r
+     * this).  This parameter can also be an array of options, see\r
+     * DB_common::setOption for more information on connection\r
+     * options.\r
+     *\r
+     * @return object a newly created DB connection object, or a DB\r
+     * error object on error\r
+     *\r
+     * @see DB::parseDSN\r
+     * @see DB::isError\r
+     */\r
+    function &connect($dsn, $options = false)\r
+    {\r
+        if (is_array($dsn)) {\r
+            $dsninfo = $dsn;\r
+        } else {\r
+            $dsninfo = DB::parseDSN($dsn);\r
+        }\r
+               switch ($dsninfo["phptype"]) {\r
+                       case 'pgsql':   $type = 'postgres7'; break;\r
+                       default:                $type = $dsninfo["phptype"]; break;\r
+               }\r
+\r
+        if (is_array($options) && isset($options["debug"]) &&\r
+            $options["debug"] >= 2) {\r
+            // expose php errors with sufficient debug level\r
+             @include_once("adodb-$type.inc.php");\r
+        } else {\r
+             @include_once("adodb-$type.inc.php");\r
+        }\r
+\r
+        @$obj =& NewADOConnection($type);\r
+\r
+        if (is_array($options)) {\r
+            $persist = !empty($options['persistent']);\r
+        } else {\r
+               $persist = true;\r
+        }\r
+\r
+               if($persist) $ok = $obj->PConnect($dsninfo['hostspec'], $dsninfo['username'],$dsninfo['password'],$dsninfo['database']);\r
+               else  $ok = $obj->Connect($dsninfo['hostspec'], $dsninfo['username'],$dsninfo['password'],$dsninfo['database']);\r
+               \r
+               if (!$ok) return ADODB_PEAR_Error();\r
+        return $obj;\r
+    }\r
+\r
+    /**\r
+     * Return the DB API version\r
+     *\r
+     * @return int the DB API version number\r
+     */\r
+    function apiVersion()\r
+    {\r
+        return 2;\r
+    }\r
+\r
+    /**\r
+     * Tell whether a result code from a DB method is an error\r
+     *\r
+     * @param $value int result code\r
+     *\r
+     * @return bool whether $value is an error\r
+     */\r
+    function isError($value)\r
+    {\r
+        return (is_object($value) &&\r
+                (get_class($value) == 'db_error' ||\r
+                 is_subclass_of($value, 'db_error')));\r
+    }\r
+\r
+\r
+    /**\r
+     * Tell whether a result code from a DB method is a warning.\r
+     * Warnings differ from errors in that they are generated by DB,\r
+     * and are not fatal.\r
+     *\r
+     * @param $value mixed result value\r
+     *\r
+     * @return bool whether $value is a warning\r
+     */\r
+    function isWarning($value)\r
+    {\r
+        return is_object($value) &&\r
+            (get_class( $value ) == "db_warning" ||\r
+             is_subclass_of($value, "db_warning"));\r
+    }\r
+\r
+    /**\r
+     * Parse a data source name\r
+     *\r
+     * @param $dsn string Data Source Name to be parsed\r
+     *\r
+     * @return array an associative array with the following keys:\r
+     *\r
+     *  phptype: Database backend used in PHP (mysql, odbc etc.)\r
+     *  dbsyntax: Database used with regards to SQL syntax etc.\r
+     *  protocol: Communication protocol to use (tcp, unix etc.)\r
+     *  hostspec: Host specification (hostname[:port])\r
+     *  database: Database to use on the DBMS server\r
+     *  username: User name for login\r
+     *  password: Password for login\r
+     *\r
+     * The format of the supplied DSN is in its fullest form:\r
+     *\r
+     *  phptype(dbsyntax)://username:password@protocol+hostspec/database\r
+     *\r
+     * Most variations are allowed:\r
+     *\r
+     *  phptype://username:password@protocol+hostspec:110//usr/db_file.db\r
+     *  phptype://username:password@hostspec/database_name\r
+     *  phptype://username:password@hostspec\r
+     *  phptype://username@hostspec\r
+     *  phptype://hostspec/database\r
+     *  phptype://hostspec\r
+     *  phptype(dbsyntax)\r
+     *  phptype\r
+     *\r
+     * @author Tomas V.V.Cox <cox@idecnet.com>\r
+     */\r
+    function parseDSN($dsn)\r
+    {\r
+        if (is_array($dsn)) {\r
+            return $dsn;\r
+        }\r
+\r
+        $parsed = array(\r
+            'phptype'  => false,\r
+            'dbsyntax' => false,\r
+            'protocol' => false,\r
+            'hostspec' => false,\r
+            'database' => false,\r
+            'username' => false,\r
+            'password' => false\r
+        );\r
+\r
+        // Find phptype and dbsyntax\r
+        if (($pos = strpos($dsn, '://')) !== false) {\r
+            $str = substr($dsn, 0, $pos);\r
+            $dsn = substr($dsn, $pos + 3);\r
+        } else {\r
+            $str = $dsn;\r
+            $dsn = NULL;\r
+        }\r
+\r
+        // Get phptype and dbsyntax\r
+        // $str => phptype(dbsyntax)\r
+        if (preg_match('|^(.+?)\((.*?)\)$|', $str, $arr)) {\r
+            $parsed['phptype'] = $arr[1];\r
+            $parsed['dbsyntax'] = (empty($arr[2])) ? $arr[1] : $arr[2];\r
+        } else {\r
+            $parsed['phptype'] = $str;\r
+            $parsed['dbsyntax'] = $str;\r
+        }\r
+\r
+        if (empty($dsn)) {\r
+            return $parsed;\r
+        }\r
+\r
+        // Get (if found): username and password\r
+        // $dsn => username:password@protocol+hostspec/database\r
+        if (($at = strpos($dsn,'@')) !== false) {\r
+            $str = substr($dsn, 0, $at);\r
+            $dsn = substr($dsn, $at + 1);\r
+            if (($pos = strpos($str, ':')) !== false) {\r
+                $parsed['username'] = urldecode(substr($str, 0, $pos));\r
+                $parsed['password'] = urldecode(substr($str, $pos + 1));\r
+            } else {\r
+                $parsed['username'] = urldecode($str);\r
+            }\r
+        }\r
+\r
+        // Find protocol and hostspec\r
+        // $dsn => protocol+hostspec/database\r
+        if (($pos=strpos($dsn, '/')) !== false) {\r
+            $str = substr($dsn, 0, $pos);\r
+            $dsn = substr($dsn, $pos + 1);\r
+        } else {\r
+            $str = $dsn;\r
+            $dsn = NULL;\r
+        }\r
+\r
+        // Get protocol + hostspec\r
+        // $str => protocol+hostspec\r
+        if (($pos=strpos($str, '+')) !== false) {\r
+            $parsed['protocol'] = substr($str, 0, $pos);\r
+            $parsed['hostspec'] = urldecode(substr($str, $pos + 1));\r
+        } else {\r
+            $parsed['hostspec'] = urldecode($str);\r
+        }\r
+\r
+        // Get dabase if any\r
+        // $dsn => database\r
+        if (!empty($dsn)) {\r
+            $parsed['database'] = $dsn;\r
+        }\r
+\r
+        return $parsed;\r
+    }\r
+\r
+    /**\r
+     * Load a PHP database extension if it is not loaded already.\r
+     *\r
+     * @access public\r
+     *\r
+     * @param $name the base name of the extension (without the .so or\r
+     * .dll suffix)\r
+     *\r
+     * @return bool true if the extension was already or successfully\r
+     * loaded, false if it could not be loaded\r
+     */\r
+    function assertExtension($name)\r
+    {\r
+        if (!extension_loaded($name)) {\r
+            $dlext = (substr(PHP_OS, 0, 3) == 'WIN') ? '.dll' : '.so';\r
+            @dl($name . $dlext);\r
+        }\r
+        if (!extension_loaded($name)) {\r
+            return false;\r
+        }\r
+        return true;\r
+    }\r
+}\r
+\r
+?>
\ No newline at end of file
diff --git a/libraries/adodb/adodb-postgres.inc.php b/libraries/adodb/adodb-postgres.inc.php
new file mode 100755 (executable)
index 0000000..4ccff2f
--- /dev/null
@@ -0,0 +1,377 @@
+<?php\r
+/*\r
+ V1.53 13 Nov 2001 (c) 2000, 2001 John Lim (jlim@natsoft.com.my). All rights reserved.\r
+  Released under both BSD license and Lesser GPL library license. \r
+  Whenever there is any discrepancy between the two licenses, \r
+  the BSD license will take precedence.\r
+  Set tabs to 8.\r
+  \r
+  Original version derived from Alberto Cerezal (acerezalp@dbnet.es) - DBNet Informatica & Comunicaciones. \r
+  08 Nov 2000 jlim - Minor corrections, removing mysql stuff\r
+  09 Nov 2000 jlim - added insertid support suggested by "Christopher Kings-Lynne" <chriskl@familyhealth.com.au>\r
+                    jlim - changed concat operator to || and data types to MetaType to match documented pgsql types \r
+               see http://www.postgresql.org/devel-corner/docs/postgres/datatype.htm  \r
+  22 Nov 2000 jlim - added changes to FetchField() and MetaTables() contributed by "raser" <raser@mail.zen.com.tw>\r
+  27 Nov 2000 jlim - added changes to _connect/_pconnect from ideas by "Lennie" <leen@wirehub.nl>\r
+  15 Dec 2000 jlim - added changes suggested by Additional code changes by "Eric G. Werk" egw@netguide.dk. \r
+  31 Jan 2001 jlim - finally installed postgresql. testing\r
+  01 Mar 2001 jlim - Freek Dijkstra changes, also support for text type\r
+*/\r
+\r
+class ADODB_postgres extends ADOConnection{\r
+       var $databaseType = 'postgres';\r
+    var $hasInsertID = true;\r
+    var $_resultid = false;\r
+       var $concat_operator='||';\r
+       var $metaTablesSQL = "select tablename from pg_tables where tablename not like 'pg_%' order by 1";\r
+\r
+/*\r
+# show tables and views suggestion\r
+"SELECT c.relname AS tablename FROM pg_class c \r
+       WHERE (c.relhasrules AND (EXISTS (\r
+               SELECT r.rulename FROM pg_rewrite r WHERE r.ev_class = c.oid AND bpchar(r.ev_type) = '1'\r
+               ))) OR (c.relkind = 'v') AND c.relname NOT LIKE 'pg_%' \r
+UNION \r
+SELECT tablename FROM pg_tables WHERE tablename NOT LIKE 'pg_%' ORDER BY 1"\r
+*/\r
+       var $metaColumnsSQL = "SELECT a.attname,t.typname,a.attlen,a.atttypmod,a.attnotnull FROM pg_class c, pg_attribute a,pg_type t WHERE relkind = 'r' AND c.relname='%s' AND a.attnum > 0 AND a.atttypid = t.oid AND a.attrelid = c.oid ORDER BY a.attnum";\r
+       // get primary key etc -- from Freek Dijkstra\r
+       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'";\r
+       \r
+       var $_hastrans = false;\r
+       var $hasAffectedRows = true;\r
+       var $hasTop = false;            \r
+       var $hasLimit = false;  // set to true for pgsql 7 only. support pgsql/mysql SELECT * FROM TABLE LIMIT 10\r
+       // below suggested by Freek Dijkstra \r
+       var $true = 't';                // string that represents TRUE for a database\r
+       var $false = 'f';               // string that represents FALSE for a database\r
+       var $fmtDate = "'Y-m-d'";       // used by DBDate() as the default date format used by the database\r
+       var $fmtTimeStamp = "'Y-m-d h:i:s'"; // used by DBTimeStamp as the default timestamp fmt.\r
+       var $hasMoveFirst = true;\r
+       var $hasGenID = true;\r
+       var $_genIDSQL = "SELECT NEXTVAL('%s')";\r
+       var $_genSeqSQL = "CREATE SEQUENCE %s";\r
+       \r
+       // The last (fmtTimeStamp is not entirely correct: \r
+       // PostgreSQL also has support for time zones, \r
+       // and writes these time in this format: "2001-03-01 18:59:26+02". \r
+       // There is no code for the "+02" time zone information, so I just left that out. \r
+       // I'm not familiar enough with both ADODB as well as Postgres \r
+       // to know what the concequences are. The other values are correct (wheren't in 0.94)\r
+       // -- Freek Dijkstra \r
+\r
+       function ADODB_postgres() \r
+       {\r
+       }\r
+       \r
+       // get the last id - never tested\r
+       function pg_insert_id($tablename,$fieldname)\r
+       {\r
+               $result=pg_exec($this->_connectionID, "SELECT last_value FROM ${tablename}_${fieldname}_seq");\r
+               if ($result) {\r
+                       $arr = @pg_fetch_row($result,0);\r
+                       pg_freeresult($result);\r
+                       if (isset($arr[0])) return $arr[0];\r
+               }\r
+               return false;\r
+       }\r
+       \r
+/* Warning from http://www.php.net/manual/function.pg-getlastoid.php:\r
+Using a OID as a unique identifier is not generally wise. \r
+Unless you are very careful, you might end up with a tuple having \r
+a different OID if a database must be reloaded. */\r
+    function _insertid()\r
+    {\r
+           return pg_getlastoid($this->_resultid);\r
+    }\r
+\r
+// I get this error with PHP before 4.0.6 - jlim\r
+// Warning: This compilation does not support pg_cmdtuples() in d:/inetpub/wwwroot/php/adodb/adodb-postgres.inc.php on line 44\r
+   function _affectedrows()\r
+   {\r
+       return pg_cmdtuples($this->_resultid);      \r
+   }\r
+\r
+       \r
+               // returns true/false\r
+       function BeginTrans()\r
+       {\r
+               $this->_hastrans = true;\r
+               return @pg_Exec($this->_connectionID, "begin");\r
+       }\r
+\r
+       // returns true/false. \r
+       function CommitTrans()\r
+       {\r
+               $this->_hastrans = false;\r
+               return @pg_Exec($this->_connectionID, "commit");\r
+       }\r
+       \r
+       // returns true/false\r
+       function RollbackTrans()\r
+       {\r
+               $this->_hastrans = false;\r
+               return @pg_Exec($this->_connectionID, "rollback");\r
+       }\r
+\r
+       // converts table to lowercase \r
+         function &MetaColumns($table) \r
+       {\r
+               if (!empty($this->metaColumnsSQL)) {\r
+                       // the following is the only difference -- we lowercase it\r
+                       $rs = $this->Execute(sprintf($this->metaColumnsSQL,strtolower($table)));\r
+                       if ($rs === false) return false;\r
+                       \r
+                       if (!empty($this->metaKeySQL)) {\r
+                               // If we want the primary keys, we have to issue a separate query\r
+                               // Of course, a modified version of the metaColumnsSQL query using a \r
+                               // LEFT JOIN would have been much more elegant, but postgres does \r
+                               // not support OUTER JOINS. So here is the clumsy way.\r
+                               $rskey = $this->Execute(sprintf($this->metaKeySQL,strtolower($table)));\r
+                               // fetch all result in once for performance.\r
+                               $keys = $rskey->GetArray();\r
+                               $rskey->Close();\r
+                               unset($rskey);\r
+                       }\r
+\r
+                       $retarr = array();\r
+                       while (!$rs->EOF) { //print_r($rs->fields);\r
+                               $fld = new ADOFieldObject();\r
+                               $fld->name = $rs->fields[0];\r
+                               $fld->type = $rs->fields[1];\r
+                               $fld->max_length = $rs->fields[2];\r
+                               if ($fld->max_length <= 0) $fld->max_length = $rs->fields[3]-4;\r
+                               if ($fld->max_length <= 0) $fld->max_length = -1;\r
+                               \r
+                               //Freek\r
+                               if ($rs->fields[4] == $this->true) {\r
+                                       $fld->not_null = true;\r
+                               }\r
+                               \r
+                               // Freek\r
+                               if (is_array($keys)) {\r
+                                       reset ($keys);\r
+                                       while (list($x,$key) = each($keys)) {\r
+                                               if ($fld->name == $key['column_name'] AND $key['primary_key'] == $this->true) \r
+                                                       $fld->primary_key = true;\r
+                                               if ($fld->name == $key['column_name'] AND $key['unique_key'] == $this->true) \r
+                                                       $fld->unique = true; // What name is more compatible?\r
+                                       }\r
+                               }\r
+                               \r
+                               $retarr[strtoupper($fld->name)] = $fld; \r
+                               \r
+                               $rs->MoveNext();\r
+                       }\r
+                       $rs->Close();\r
+                       return $retarr; \r
+               }\r
+               return false;\r
+       }\r
+\r
+\r
+       // returns true or false\r
+       //\r
+       // examples:\r
+       //      $db->Connect("host=host1 user=user1 password=secret port=4341");\r
+       //      $db->Connect('host1','user1','secret');\r
+       function _connect($str,$user='',$pwd='',$db='')\r
+       {           \r
+               if ($user || $pwd || $db) {\r
+               if ($str)  {\r
+                               $host = split(":", $str);\r
+                               if ($host[0]) $str = "host=$host[0]";\r
+                               else $str = 'localhost';\r
+                               if (isset($host[1])) $str .= " port=$host[1]";\r
+                       }\r
+                       if ($user) $str .= " user=".$user;\r
+                       if ($pwd)  $str .= " password=".$pwd;\r
+                       if ($db)   $str .= " dbname=".$db;\r
+               }\r
+               \r
+               //if ($user) $linea = "user=$user host=$linea password=$pwd dbname=$db port=5432";\r
+               $this->_connectionID = pg_connect($str);\r
+               if ($this->_connectionID === false) return false;\r
+               $this->Execute("set datestyle='ISO'");\r
+                return true;\r
+       }\r
+       \r
+       // returns true or false\r
+       //\r
+       // examples:\r
+       //      $db->PConnect("host=host1 user=user1 password=secret port=4341");\r
+       //      $db->PConnect('host1','user1','secret');\r
+       function _pconnect($str,$user='',$pwd='',$db='')\r
+       {\r
+               if ($user || $pwd || $db) {\r
+                       if ($str)  {\r
+                               $host = split(":", $str);\r
+                               if ($host[0]) $str = "host=$host[0]";\r
+                               else $str = 'localhost';\r
+                               if (isset($host[1])) $str .= " port=$host[1]";\r
+                       }\r
+                       if ($user) $str .= " user=".$user;\r
+                       if ($pwd)  $str .= " password=".$pwd;\r
+                       if ($db)   $str .= " dbname=".$db;\r
+               }//print $str;\r
+               $this->_connectionID = pg_pconnect($str);\r
+               if ($this->_connectionID === false) return false;\r
+               $this->Execute("set datestyle='ISO'");\r
+               return true;\r
+       }\r
+\r
+       // returns queryID or false\r
+       function _query($sql,$inputarr)\r
+       {\r
+                $this->_resultid= pg_Exec($this->_connectionID,$sql);\r
+                return $this->_resultid;\r
+       }\r
+       \r
+\r
+       /*      Returns: the last error message from previous database operation        */      \r
+       function ErrorMsg() \r
+       {\r
+               if (empty($this->_connectionID)) $this->_errorMsg = @pg_errormessage();\r
+               else $this->_errorMsg = @pg_errormessage($this->_connectionID);\r
+           return $this->_errorMsg;\r
+       }\r
+\r
+       // returns true or false\r
+       function _close()\r
+       {\r
+               if ($this->_hastrans) $this->RollbackTrans();\r
+               @pg_close($this->_connectionID);\r
+               $this->_resultid = false;\r
+               $this->_connectionID = false;\r
+               return true;\r
+       }\r
+               \r
+}\r
+       \r
+/*--------------------------------------------------------------------------------------\r
+        Class Name: Recordset\r
+--------------------------------------------------------------------------------------*/\r
+\r
+class ADORecordSet_postgres extends ADORecordSet{\r
+\r
+       var $databaseType = "postgres";\r
+       var $canSeek = true;\r
+       function ADORecordSet_postgres($queryID) {\r
+       global $ADODB_FETCH_MODE;\r
+       \r
+               switch ($ADODB_FETCH_MODE)\r
+               {\r
+               case ADODB_FETCH_NUM: $this->fetchMode = PGSQL_NUM; break;\r
+               case ADODB_FETCH_ASSOC:$this->fetchMode = PGSQL_ASSOC; break;\r
+               default:\r
+               case ADODB_FETCH_DEFAULT:\r
+               case ADODB_FETCH_BOTH:$this->fetchMode = PGSQL_BOTH; break;\r
+               }\r
+       \r
+               $this->ADORecordSet($queryID);\r
+       }\r
+       \r
+       function &GetRowAssoc($upper=true)\r
+       {\r
+               if ($this->fetchMode == PGSQL_ASSOC && !$upper) return $rs->fields;\r
+               return ADORecordSet::GetRowAssoc($upper);\r
+       }\r
+\r
+       function _initrs()\r
+       {\r
+       global $ADODB_COUNTRECS;\r
+               $this->_numOfRows = ($ADODB_COUNTRECS)? @pg_numrows($this->_queryID):-1;\r
+               $this->_numOfFields = @pg_numfields($this->_queryID);\r
+       }\r
+\r
+       function &FetchField($fieldOffset = 0) \r
+       {\r
+               $off=$fieldOffset; // offsets begin at 0\r
+               \r
+               $o= new ADOFieldObject();\r
+               $o->name = @pg_fieldname($this->_queryID,$off);\r
+               $o->type = @pg_fieldtype($this->_queryID,$off);\r
+               $o->max_length = @pg_fieldsize($this->_queryID,$off);\r
+               //print_r($o);          \r
+               //print "off=$off name=$o->name type=$o->type len=$o->max_length<br>";\r
+               return $o;      \r
+       }\r
+\r
+       function _seek($row)\r
+       {\r
+               return @pg_fetch_row($this->_queryID,$row);\r
+       }\r
+       \r
+       // 10% speedup to move MoveNext to child class\r
+       function MoveNext() \r
+       {\r
+               if (!$this->EOF) {              \r
+                       $this->_currentRow++;\r
+                       $this->fields = @pg_fetch_array($this->_queryID,$this->_currentRow,$this->fetchMode);\r
+                       if (is_array($this->fields)) return true;\r
+               }\r
+               $this->EOF = true;\r
+               return false;\r
+       }       \r
+       function _fetch()\r
+       {\r
+               $this->fields = @pg_fetch_array($this->_queryID,$this->_currentRow,$this->fetchMode);\r
+               return (is_array($this->fields));\r
+       }\r
+\r
+       function _close() {\r
+               return @pg_freeresult($this->_queryID);\r
+       }\r
+\r
+       function MetaType($t,$len=-1,$fieldobj=false)\r
+       {\r
+               switch (strtoupper($t)) {\r
+                   case 'CHAR':\r
+                   case 'CHARACTER':\r
+                   case 'VARCHAR':\r
+                   case 'NAME':\r
+                               case 'BPCHAR':\r
+                       if ($len <= $this->blobSize) return 'C';\r
+                               \r
+                   case 'TEXT':\r
+                       return 'X';\r
+               \r
+                       case 'IMAGE': // user defined type\r
+                       case 'BLOB': // user defined type\r
+                   case 'BIT': // This is a bit string, not a single bit, so don't return 'L'\r
+                   case 'VARBIT':\r
+                       case 'BYTEA':\r
+                       return 'B';\r
+                   \r
+                   case 'BOOL':\r
+                   case 'BOOLEAN':\r
+                       return 'L';\r
+                               \r
+                   case 'DATE':\r
+                       return 'D';\r
+                   \r
+                   case 'TIME':\r
+                   case 'DATETIME':\r
+                   case 'TIMESTAMP':\r
+                       return 'T';\r
+                   \r
+                   case 'SMALLINT': \r
+                   case 'BIGINT': \r
+                   case 'INTEGER': \r
+                   case 'INT8': \r
+                   case 'INT4':\r
+                   case 'INT2':\r
+                       if (isset($fieldobj) &&\r
+                               empty($fieldobj->primary_key) && empty($fieldobj->unique)) return 'I';\r
+                               \r
+                   case 'OID':\r
+                   case 'SERIAL':\r
+                       return 'R';\r
+                               \r
+                    default:\r
+                       return 'N';\r
+               }\r
+       }\r
+\r
+}\r
+?>\r
diff --git a/libraries/adodb/adodb-postgres7.inc.php b/libraries/adodb/adodb-postgres7.inc.php
new file mode 100755 (executable)
index 0000000..d529327
--- /dev/null
@@ -0,0 +1,62 @@
+<?php\r
+/*\r
+ V1.53 13 Nov 2001 (c) 2000, 2001 John Lim (jlim@natsoft.com.my). All rights reserved.\r
+  Released under both BSD license and Lesser GPL library license. \r
+  Whenever there is any discrepancy between the two licenses, \r
+  the BSD license will take precedence.\r
+  Set tabs to 4.\r
+  \r
+  Postgres7 support.\r
+  28 Feb 2001: Currently indicate that we support LIMIT\r
+*/\r
+\r
+include_once(ADODB_DIR."/adodb-postgres.inc.php");\r
+\r
+class ADODB_postgres7 extends ADODB_postgres {\r
+       var $databaseType = 'postgres7';        \r
+       var $hasLimit = true;   // set to true for pgsql 6.5+ only. support pgsql/mysql SELECT * FROM TABLE LIMIT 10\r
+\r
+       function ADODB_postgres7() \r
+       {\r
+       }\r
+\r
+       // the following should be compat with postgresql 7.2, \r
+       // which makes obsolete the LIMIT limit,offset syntax\r
+        function &SelectLimit($sql,$nrows=-1,$offset=-1,$inputarr=false,$arg3=false,$secs2cache=0) \r
+        {\r
+         $offsetStr = ($offset >= 0) ? " OFFSET $offset" : '';\r
+         $limitStr  = ($nrows >= 0)  ? " LIMIT $nrows" : '';\r
+         return $secs2cache ?\r
+          $this->CacheExecute($secs2cache,$sql."$limitStr$offsetStr",$inputarr,$arg3)\r
+         :\r
+          $this->Execute($sql."$limitStr$offsetStr",$inputarr,$arg3);\r
+        }\r
\r
+       // 10% speedup to move MoveNext to child class\r
+       function MoveNext() \r
+       {\r
+               if (!$this->EOF) {              \r
+                       $this->_currentRow++;\r
+                       $this->fields = @pg_fetch_array($this->_queryID,$this->_currentRow,$this->fetchMode);\r
+                       if (is_array($this->fields)) return true;\r
+               }\r
+               $this->EOF = true;\r
+               return false;\r
+       }       \r
+}\r
+       \r
+/*--------------------------------------------------------------------------------------\r
+        Class Name: Recordset\r
+--------------------------------------------------------------------------------------*/\r
+\r
+class ADORecordSet_postgres7 extends ADORecordSet_postgres{\r
+\r
+       var $databaseType = "postgres7";\r
+\r
+       function ADORecordSet_postgres7($queryID) \r
+       {\r
+               $this->ADORecordSet_postgres($queryID);\r
+       }\r
+\r
+}\r
+?>\r
diff --git a/libraries/adodb/adodb-proxy.inc.php b/libraries/adodb/adodb-proxy.inc.php
new file mode 100755 (executable)
index 0000000..02a6fca
--- /dev/null
@@ -0,0 +1,28 @@
+<?php\r
+/*\r
+V1.53 13 Nov 2001 (c) 2000, 2001 John Lim (jlim@natsoft.com.my). All rights reserved.\r
+  Released under both BSD license and Lesser GPL library license. \r
+  Whenever there is any discrepancy between the two licenses, \r
+  the BSD license will take precedence.\r
+  Set tabs to 4.\r
+  \r
+  Synonym for csv driver.\r
+*/ \r
+\r
+if (! defined("_ADODB_PROXY_LAYER")) {\r
+        define("_ADODB_PROXY_LAYER", 1 );\r
+        include(ADODB_DIR."/adodb-csv.inc.php");\r
+        \r
+       class ADODB_proxy extends ADODB_csv {\r
+               var $databaseType = 'proxy';\r
+           \r
+               function ADODB_proxy() \r
+               {\r
+               }\r
+       }\r
+       class ADORecordset_proxy extends ADORecordset_csv {\r
+       var $databaseType = "proxy";            \r
+       };\r
+} // define\r
+       \r
+?>
\ No newline at end of file
diff --git a/libraries/adodb/adodb-session.php b/libraries/adodb/adodb-session.php
new file mode 100755 (executable)
index 0000000..821c1a7
--- /dev/null
@@ -0,0 +1,228 @@
+<?php\r
+/*\r
+V1.53 13 Nov 2001 (c) 2000, 2001 John Lim (jlim@natsoft.com.my). All rights reserved.\r
+  Released under both BSD license and Lesser GPL library license. \r
+  Whenever there is any discrepancy between the two licenses, \r
+  the BSD license will take precedence.\r
+       Made table name configurable - by David Johnson djohnson@inpro.net\r
+\r
+  Set tabs to 4 for best viewing.\r
+  \r
+  Latest version of ADODB is available at http://php.weblogs.com/adodb\r
+  ======================================================================\r
+  \r
+ This file provides PHP4 session management using the ADODB database\r
+wrapper library.\r
\r
+ Example\r
+ =======\r
\r
+       GLOBAL $HTTP_SESSION_VARS;\r
+       include('adodb.inc.php');\r
+       include('adodb-session.php');\r
+       session_start();\r
+       session_register('AVAR');\r
+       $HTTP_SESSION_VARS['AVAR'] += 1;\r
+       print "<p>\$HTTP_SESSION_VARS['AVAR']={$HTTP_SESSION_VARS['AVAR']}</p>";\r
+\r
\r
+ Installation\r
+ ============\r
+ 1. Create a new database in MySQL or Access "sessions" like\r
+so:\r
\r
+  create table sessions (\r
+       SESSKEY char(32) not null,\r
+       EXPIRY int(11) unsigned not null,\r
+       DATA text not null,\r
+      primary key (sesskey)\r
+  );\r
+  \r
+  2. Then define the following parameters in this file:\r
+       $ADODB_SESSION_DRIVER='database driver, eg. mysql or ibase';\r
+       $ADODB_SESSION_CONNECT='server to connect to';\r
+       $ADODB_SESSION_USER ='user';\r
+       $ADODB_SESSION_PWD ='password';\r
+       $ADODB_SESSION_DB ='database';\r
+       $ADODB_SESSION_TBL = 'sessions'\r
+       \r
+  3. Recommended is PHP 4.0.2 or later. There are documented\r
+session bugs in \r
+     earlier versions of PHP.\r
+\r
+*/\r
+\r
+if (!defined('_ADODB_LAYER')) {\r
+       include ('adodb.inc.php');\r
+}\r
+\r
+\r
+\r
+if (!defined('ADODB_SESSION')) {\r
+\r
+ define('ADODB_SESSION',1);\r
\r
+GLOBAL         $ADODB_SESSION_CONNECT, \r
+       $ADODB_SESSION_DRIVER,\r
+       $ADODB_SESSION_USER,\r
+       $ADODB_SESSION_PWD,\r
+       $ADODB_SESSION_DB,\r
+       $ADODB_SESS_CONN,\r
+       $ADODB_SESS_LIFE,\r
+       $ADODB_SESS_DEBUG,\r
+       $ADODB_SESS_INSERT; \r
+\r
+       //$ADODB_SESS_DEBUG = true;\r
+       \r
+       /* SET THE FOLLOWING PARAMETERS */\r
+if (empty($ADODB_SESSION_DRIVER)) {\r
+       $ADODB_SESSION_DRIVER='mysql';\r
+       $ADODB_SESSION_CONNECT='localhost';\r
+       $ADODB_SESSION_USER ='root';\r
+       $ADODB_SESSION_PWD ='';\r
+       $ADODB_SESSION_DB ='xphplens_2';\r
+}\r
+if (empty($ADODB_SESSION_TBL)){\r
+       $ADODB_SESSION_TBL = 'sessions';\r
+}\r
+\r
+$ADODB_SESS_LIFE = get_cfg_var('session.gc_maxlifetime');\r
+if ($ADODB_SESS_LIFE <= 1) {\r
+       // bug in PHP 4.0.3 pl 1  -- how about other versions?\r
+       //print "<h3>Session Error: PHP.INI setting <i>session.gc_maxlifetime</i>not set: $ADODB_SESS_LIFE</h3>";\r
+       $ADODB_SESS_LIFE=1440;\r
+}\r
+\r
+function adodb_sess_open($save_path, $session_name) \r
+{\r
+GLOBAL         $ADODB_SESSION_CONNECT, \r
+       $ADODB_SESSION_DRIVER,\r
+       $ADODB_SESSION_USER,\r
+       $ADODB_SESSION_PWD,\r
+       $ADODB_SESSION_DB,\r
+       $ADODB_SESS_CONN,\r
+       $ADODB_SESS_DEBUG;\r
+       \r
+       $ADODB_SESS_INSERT = false;\r
+       \r
+       if (isset($ADODB_SESS_CONN)) return true;\r
+       \r
+       $ADODB_SESS_CONN = ADONewConnection($ADODB_SESSION_DRIVER);\r
+       if (!empty($ADODB_SESS_DEBUG)) {\r
+               $ADODB_SESS_CONN->debug = true;\r
+               print" conn=$ADODB_SESSION_CONNECT user=$ADODB_SESSION_USER pwd=$ADODB_SESSION_PWD db=$ADODB_SESSION_DB ";\r
+       }\r
+       return $ADODB_SESS_CONN->PConnect($ADODB_SESSION_CONNECT,\r
+                       $ADODB_SESSION_USER,$ADODB_SESSION_PWD,$ADODB_SESSION_DB);\r
+       \r
+}\r
+\r
+function adodb_sess_close() \r
+{\r
+global $ADODB_SESS_CONN;\r
+\r
+       if ($ADODB_SESS_CONN) $ADODB_SESS_CONN->Close();\r
+       return true;\r
+}\r
+\r
+function adodb_sess_read($key) \r
+{\r
+global $ADODB_SESS_CONN,$ADODB_SESS_INSERT,$ADODB_SESSION_TBL;\r
+       $rs = $ADODB_SESS_CONN->Execute("SELECT data FROM $ADODB_SESSION_TBL WHERE sesskey = '$key' AND expiry >= " . time());\r
+       if ($rs) {\r
+               if ($rs->EOF) {\r
+                       $ADODB_SESS_INSERT = true;\r
+                       $v = '';\r
+               } else \r
+                       $v = rawurldecode($rs->fields[0]);\r
+                       \r
+               $rs->Close();\r
+               return $v;\r
+       }\r
+       else $ADODB_SESS_INSERT = true;\r
+       \r
+       return false;\r
+}\r
+\r
+function adodb_sess_write($key, $val) \r
+{\r
+       global $ADODB_SESS_INSERT,$ADODB_SESS_CONN, $ADODB_SESS_LIFE, $ADODB_SESSION_TBL;\r
+\r
+       $expiry = time() + $ADODB_SESS_LIFE;\r
+       \r
+       $val = rawurlencode($val);\r
+       $qry = "UPDATE $ADODB_SESSION_TBL SET expiry=$expiry,data='$val' WHERE sesskey='$key'";\r
+       $rs = $ADODB_SESS_CONN->Execute($qry);\r
+       if ($rs) $rs->Close();\r
+       else print '<p>Session Update: '.$ADODB_SESS_CONN->ErrorMsg().'</p>';\r
+       \r
+       if ($ADODB_SESS_INSERT || $rs === false) {\r
+               $qry = "INSERT INTO $ADODB_SESSION_TBL(sesskey,expiry,data) VALUES ('$key',$expiry,'$val')";\r
+               $rs = $ADODB_SESS_CONN->Execute($qry);\r
+               if ($rs) $rs->Close();\r
+               else print '<p>Session Insert: '.$ADODB_SESS_CONN->ErrorMsg().'</p>';\r
+       }\r
+       // bug in access driver (could be odbc?) means that info is not commited\r
+       // properly unless select statement executed in Win2000\r
+       if ($ADODB_SESS_CONN->databaseType == 'access') $rs = $ADODB_SESS_CONN->Execute("select sesskey from $ADODB_SESSION_TBL WHERE sesskey='$key'");\r
+\r
+       return isset($rs);\r
+}\r
+\r
+function adodb_sess_destroy($key) \r
+{\r
+       global $ADODB_SESS_CONN, $ADODB_SESSION_TBL;\r
+\r
+       $qry = "DELETE FROM $ADODB_SESSION_TBL WHERE sesskey = '$key'";\r
+       $rs = $ADODB_SESS_CONN->Execute($qry);\r
+       if ($rs) $rs->Close();\r
+       return $rs;\r
+}\r
+\r
+function adodb_sess_gc($maxlifetime) {\r
+       global $ADODB_SESS_CONN, $ADODB_SESSION_TBL;\r
+\r
+       $qry = "DELETE FROM $ADODB_SESSION_TBL WHERE expiry < " . time();\r
+       $rs = $ADODB_SESS_CONN->Execute($qry);\r
+       if ($rs) $rs->Close();\r
+       \r
+       // suggested by Cameron, "GaM3R" <gamr@outworld.cx>\r
+       if (defined('ADODB_SESSION_OPTIMIZE'))\r
+       {\r
+               switch( $ADODB_SESSION_DRIVER ) {\r
+                       case 'mysql':\r
+                       case 'mysqlt':\r
+                               $opt_qry = 'OPTIMIZE TABLE '.$ADODB_SESSION_TBL;\r
+                               break;\r
+                       case 'postgresql':\r
+                       case 'postgresql7':\r
+                               $opt_qry = 'VACUUM '.$ADODB_SESSION_TBL;        \r
+                               break;\r
+               }\r
+       }\r
+       \r
+       return true;\r
+}\r
+\r
+session_module_name('user'); \r
+session_set_save_handler(\r
+       "adodb_sess_open",\r
+       "adodb_sess_close",\r
+       "adodb_sess_read",\r
+       "adodb_sess_write",\r
+       "adodb_sess_destroy",\r
+       "adodb_sess_gc");\r
+}\r
+\r
+/*  TEST SCRIPT -- UNCOMMENT */\r
+\r
+if (0) {\r
+GLOBAL $HTTP_SESSION_VARS;\r
+\r
+       session_start();\r
+       session_register('AVAR');\r
+       $HTTP_SESSION_VARS['AVAR'] += 1;\r
+       print "<p>\$HTTP_SESSION_VARS['AVAR']={$HTTP_SESSION_VARS['AVAR']}</p>";\r
+}\r
+\r
+?>\r
diff --git a/libraries/adodb/adodb-sybase.inc.php b/libraries/adodb/adodb-sybase.inc.php
new file mode 100755 (executable)
index 0000000..1bd01b0
--- /dev/null
@@ -0,0 +1,215 @@
+<?php\r
+/* \r
+V1.53 13 Nov 2001 (c) 2000, 2001 John Lim. All rights reserved.\r
+  Released under both BSD license and Lesser GPL library license. \r
+  Whenever there is any discrepancy between the two licenses, \r
+  the BSD license will take precedence. \r
+  Set tabs to 4 for best viewing.\r
+  \r
+  Latest version is available at http://php.weblogs.com/\r
+  \r
+  Sybase driver contributed by Toni (toni.tunkkari@finebyte.com)\r
+*/\r
\r
+class ADODB_sybase extends ADOConnection {\r
+       var $databaseType = "sybase";   \r
+       var $replaceQuote = "''"; // string to use to replace quotes\r
+       var $fmtDate = "'Y-m-d H:i:s'";\r
+       var $fmtTimeStamp = "'Y-m-d H:i:s'";\r
+       var $hasInsertID = true;\r
+        var $hasAffectedRows = true;\r
+       var $metaTablesSQL="select name from sysobjects where type='U' or type='V'";\r
+       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'";\r
+       var $concat_operator = '+'; \r
+       \r
+       function ADODB_sybase() {                       \r
+       }\r
\r
+        // might require begintrans -- committrans\r
+        function _insertid()\r
+        {\r
+                $rs = $this->Execute('select @@identity');\r
+                if ($rs == false || $rs->EOF) return false;\r
+               $id = $rs->fields[0];\r
+               $rs->Close();\r
+               return $id;\r
+        }\r
+          // might require begintrans -- committrans\r
+        function _affectedrows()\r
+        {\r
+                $rs = $this->Execute('select @@rowcount');\r
+                if ($rs == false || $rs->EOF) return false;\r
+               $id = $rs->fields[0];\r
+               $rs->Close();\r
+               return $id;\r
+        }\r
+\r
+              \r
+        function BeginTrans()\r
+       {       \r
+               $this->Execute('BEGIN TRAN');\r
+               return true;\r
+       }\r
+       \r
+       function CommitTrans()\r
+       {\r
+                $this->Execute('COMMIT TRAN');\r
+                return true;\r
+       }\r
+       \r
+       function RollbackTrans()\r
+       {\r
+                $this->Execute('ROLLBACK TRAN');\r
+                return true;\r
+       }\r
+       \r
+        \r
+       function SelectDB($dbName) {\r
+               $this->databaseName = $dbName;\r
+               if ($this->_connectionID) {\r
+                       return @sybase_select_db($dbName);              \r
+               }\r
+               else return false;      \r
+       }\r
+\r
+       /*      Returns: the last error message from previous database operation\r
+               Note: This function is NOT available for Microsoft SQL Server.  */      \r
+\r
+       function ErrorMsg() {\r
+               $this->_errorMsg = sybase_get_last_message();\r
+               return $this->_errorMsg;\r
+       }\r
+\r
+       // returns true or false\r
+       function _connect($argHostname, $argUsername, $argPassword, $argDatabasename)\r
+       {\r
+               $this->_connectionID = sybase_connect($argHostname,$argUsername,$argPassword);\r
+               if ($this->_connectionID === false) return false;\r
+               if ($argDatabasename) return $this->SelectDB($argDatabasename);\r
+               return true;    \r
+       }\r
+       // returns true or false\r
+       function _pconnect($argHostname, $argUsername, $argPassword, $argDatabasename)\r
+       {\r
+               $this->_connectionID = sybase_pconnect($argHostname,$argUsername,$argPassword);\r
+               if ($this->_connectionID === false) return false;\r
+               if ($argDatabasename) return $this->SelectDB($argDatabasename);\r
+               return true;    \r
+       }\r
+       \r
+       // returns query ID if successful, otherwise false\r
+       function _query($sql,$inputarr)\r
+       {\r
+               //@sybase_free_result($this->_queryID);\r
+               return sybase_query($sql,$this->_connectionID);\r
+       }\r
+       \r
+       // returns true or false\r
+       function _close()\r
+       { \r
+               return @sybase_close($this->_connectionID);\r
+       }\r
+       \r
+       \r
+}\r
+       \r
+/*--------------------------------------------------------------------------------------\r
+        Class Name: Recordset\r
+--------------------------------------------------------------------------------------*/\r
+global $ADODB_sybase_mths;\r
+$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);\r
+\r
+class ADORecordset_sybase extends ADORecordSet {       \r
+\r
+       var $databaseType = "sybase";\r
+       var $canSeek = true;\r
+       // _mths works only in non-localised system\r
+       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);    \r
+       \r
+       function ADORecordset_sybase($id)\r
+       {\r
+               return $this->ADORecordSet($id);\r
+       }\r
+       \r
+\r
+       /*      Returns: an object containing field information. \r
+               Get column information in the Recordset object. fetchField() can be used in order to obtain information about\r
+               fields in a certain query result. If the field offset isn't specified, the next field that wasn't yet retrieved by\r
+               fetchField() is retrieved.      */\r
+       function &FetchField($fieldOffset = -1) \r
+       {\r
+               if ($fieldOffset != -1) {\r
+                       $o = @sybase_fetch_field($this->_queryID, $fieldOffset);\r
+               }\r
+               else if ($fieldOffset == -1) {  /*      The $fieldOffset argument is not provided thus its -1   */\r
+                       $o = @sybase_fetch_field($this->_queryID);\r
+               }\r
+               // older versions of PHP did not support type, only numeric\r
+               if ($o && !isset($o->type)) $o->type = ($o->numeric) ? 'float' : 'varchar';\r
+               return $o;\r
+       }\r
+       \r
+       function _initrs()\r
+       {\r
+       global $ADODB_COUNTRECS;\r
+               $this->_numOfRows = ($ADODB_COUNTRECS)? @sybase_num_rows($this->_queryID):-1;\r
+               $this->_numOfFields = @sybase_num_fields($this->_queryID);\r
+       }\r
+       \r
+       function _seek($row) \r
+       {\r
+               return @sybase_data_seek($this->_queryID, $row);\r
+       }               \r
+\r
+       function _fetch($ignore_fields=false) {\r
+               $this->fields = @sybase_fetch_array($this->_queryID);\r
+               return ($this->fields == true);\r
+       }\r
+       \r
+       /*      close() only needs to be called if you are worried about using too much memory while your script\r
+               is running. All associated result memory for the specified result identifier will automatically be freed.       */\r
+       function _close() {\r
+               return @sybase_free_result($this->_queryID);            \r
+       }\r
+       \r
+       // sybase/mssql uses a default date like Dec 30 2000 12:00AM\r
+       function UnixDate($v)\r
+       {\r
+       global $ADODB_sybase_mths;\r
+               //Dec 30 2000 12:00AM\r
+               // added fix by Toni for day 15 Mar 2001\r
+               if (!ereg( "([A-Za-z]{3})[-/\. ]([0-9 ]{1,2})[-/\. ]([0-9]{4}))"\r
+                       ,$v, $rr)) return parent::UnixDate($v);\r
+                       \r
+               if ($rr[3] <= 1970) return 0;\r
+               \r
+               $themth = substr(strtoupper($rr[1]),0,3);\r
+               $themth = $ADODB_sybase_mths[$themth];\r
+               if ($themth <= 0) return false;\r
+               // h-m-s-MM-DD-YY\r
+               return  mktime(0,0,0,$themth,$rr[2],$rr[3]);\r
+       }\r
+       \r
+       function UnixTimeStamp($v)\r
+       {\r
+       global $ADODB_sybase_mths;\r
+               //Dec 30 2000 12:00AM\r
+               if (!ereg( "([A-Za-z]{3})[-/\. ]([0-9]{1,2})[-/\. ]([0-9]{4}) +([0-9]{1,2}):([0-9]{1,2}) *([apAP]{0,1})"\r
+                       ,$v, $rr)) return parent::UnixTimeStamp($v);\r
+               if ($rr[3] <= 1970) return 0;\r
+               \r
+               $themth = substr(strtoupper($rr[1]),0,3);\r
+               $themth = $ADODB_sybase_mths[$themth];\r
+               if ($themth <= 0) return false;\r
+               \r
+               if (strtoupper($rr[6]) == 'P') {\r
+                       if ($rr[4]<12) $rr[4] += 12;\r
+               } else {\r
+                       if ($rr[4]==12) $rr[4] = 0;\r
+               }\r
+               // h-m-s-MM-DD-YY\r
+               return  mktime($rr[4],$rr[5],0,$themth,$rr[2],$rr[3]);\r
+       }\r
+\r
+}\r
+?>
\ No newline at end of file
diff --git a/libraries/adodb/adodb-vfp.inc.php b/libraries/adodb/adodb-vfp.inc.php
new file mode 100755 (executable)
index 0000000..dcde32c
--- /dev/null
@@ -0,0 +1,79 @@
+<?php\r
+/* \r
+V1.53 13 Nov 2001 (c) 2000, 2001 John Lim (jlim@natsoft.com.my). All rights reserved.\r
+  Released under both BSD license and Lesser GPL library license. \r
+  Whenever there is any discrepancy between the two licenses, \r
+  the BSD license will take precedence. \r
+Set tabs to 4 for best viewing.\r
+  \r
+  Latest version is available at http://php.weblogs.com/\r
+  \r
+  Microsoft Visual FoxPro data driver. Requires ODBC. Works only on MS Windows.\r
+*/\r
+\r
+if (!defined('_ADODB_ODBC_LAYER')) {\r
+       include(ADODB_DIR."/adodb-odbc.inc.php");\r
+}\r
+if (!defined('ADODB_VFP')){\r
+define('ADODB_VFP',1);\r
+class ADODB_vfp extends ADODB_odbc {\r
+       var $databaseType = "vfp";      \r
+       var $fmtDate = "{^Y-m-d}";\r
+       var $fmtTimeStamp = "{^Y-m-d, h:i:sA}";\r
+       var $replaceQuote = "'+chr(39)+'" ;\r
+       var $true = '.T.';\r
+       var $false = '.F.';\r
+       var $hasTop = true;             // support mssql SELECT TOP 10 * FROM TABLE\r
+\r
+       function BeginTrans() { return false;}\r
+\r
+       // quote string to be sent back to database\r
+       function qstr($s,$nofixquotes=false)\r
+       {\r
+               if (!$nofixquotes) return  "'".str_replace("\r\n","'+chr(13)+'",str_replace("'",$this->replaceQuote,$s))."'";\r
+               return "'".$s."'";\r
+       }\r
+       \r
+       // TOP requires ORDER BY for VFP\r
+       function &SelectLimit($sql,$nrows=-1,$offset=-1, $inputarr=false,$arg3=false,$secs2cache=0)\r
+       {\r
+               if (!preg_match('/ORDER[ \t\r\n]+BY/i',$sql)) $sql .= ' ORDER BY 1';\r
+               return ADOConnection::SelectLimit($sql,$nrows,$offset,$inputarr,$arg3,$secs2cache);\r
+       }\r
+       \r
+};\r
\r
+\r
+class  ADORecordSet_vfp extends ADORecordSet_odbc {    \r
+       \r
+       var $databaseType = "vfp";              \r
+\r
+       \r
+       function ADORecordSet_vfp($id)\r
+       {\r
+               return $this->ADORecordSet_odbc($id);\r
+       }\r
+\r
+       function MetaType($t,$len=-1)\r
+       {\r
+               switch (strtoupper($t)) {\r
+               case 'C':\r
+                       if ($len <= $this->blobSize) return 'C';\r
+               case 'M':\r
+                       return 'X';\r
+                        \r
+               case 'D': return 'D';\r
+               \r
+               case 'T': return 'T';\r
+               \r
+               case 'L': return 'L';\r
+               \r
+               case 'I': return 'I';\r
+               \r
+               default: return 'N';\r
+               }\r
+       }\r
+}\r
+\r
+} //define\r
+?>
\ No newline at end of file
diff --git a/libraries/adodb/adodb.gif b/libraries/adodb/adodb.gif
new file mode 100755 (executable)
index 0000000..47b6f2d
Binary files /dev/null and b/libraries/adodb/adodb.gif differ
diff --git a/libraries/adodb/adodb.inc.php b/libraries/adodb/adodb.inc.php
new file mode 100755 (executable)
index 0000000..299a4f9
--- /dev/null
@@ -0,0 +1,2332 @@
+<?php \r
+\r
+/** \r
+ * @version V1.53 13 Nov 2001 (c) 2000, 2001 John Lim (jlim@natsoft.com.my). All rights reserved.\r
+ * Released under both BSD license and Lesser GPL library license. \r
+  Whenever there is any discrepancy between the two licenses, \r
+  the BSD license will take precedence. \r
+ *\r
+ * Set tabs to 4 for best viewing.\r
+ * \r
+ * Latest version is available at http://php.weblogs.com\r
+ * \r
+ * This is the main include file for ADODB.\r
+ * It has all the generic functionality of ADODB. \r
+ * Database specific drivers are stored in the adodb-*.inc.php files.\r
+ *\r
+ * Requires PHP4.01pl2 or later because it uses include_once\r
+*/\r
+\r
+ if (!defined('_ADODB_LAYER')) {\r
+       define('_ADODB_LAYER',1);\r
+       \r
+       define('ADODB_BAD_RS','<p>Bad $rs in %s. Connection or SQL invalid. Try using $connection->debug=true;</p>');\r
+       \r
+       define('ADODB_FETCH_DEFAULT',0);\r
+       define('ADODB_FETCH_NUM',1);\r
+       define('ADODB_FETCH_ASSOC',2);\r
+       define('ADODB_FETCH_BOTH',3);\r
+       \r
+       GLOBAL \r
+               $ADODB_vers,            // database version\r
+               $ADODB_Database,        // last database driver used\r
+               $ADODB_COUNTRECS,       // count number of records returned - slows down query\r
+               $ADODB_CACHE_DIR,       // directory to cache recordsets\r
+               $ADODB_FETCH_MODE;      // DEFAULT, NUM, ASSOC or BOTH. Default follows native driver default...\r
+       \r
+       $ADODB_FETCH_MODE = ADODB_FETCH_DEFAULT;\r
+       /** \r
+        * SET THE VALUE BELOW TO THE DIRECTORY WHERE THIS FILE RESIDES\r
+        * ADODB_RootPath has been renamed ADODB_DIR \r
+        */\r
+       if (!defined('ADODB_DIR')) define('ADODB_DIR',dirname(__FILE__));\r
+       \r
+       if (!isset($ADODB_CACHE_DIR)) $ADODB_CACHE_DIR = '/tmp';\r
+       else if (strpos($ADODB_CACHE_DIR,':/') !== false) die("Illegal \$ADODB_CACHE_DIR");\r
+       \r
+       //==============================================================================================        \r
+       // CHANGE NOTHING BELOW UNLESS YOU ARE CODING\r
+       //==============================================================================================        \r
+\r
+       // using PHPCONFIG protocol overrides ADODB_DIR\r
+       //if (isset($PHPCONFIG_DIR)) $ADODB_DIR=$PHPCONFIG_DIR.'/../adodb';\r
+\r
+       srand(((double)microtime())*1000000);\r
+       /**\r
+        * Name of last database driver loaded into memory.\r
+        */\r
+       $ADODB_Database = '';\r
+       \r
+       /**\r
+        * ADODB version as a string.\r
+        */\r
+       $ADODB_vers = 'V1.53 13 Nov 2001 (c) 2000, 2001 John Lim (jlim@natsoft.com.my). All rights reserved. Released BSD & LGPL.';\r
+\r
+       /**\r
+        * Determines whether recordset->RecordCount() is used. \r
+        * Set to false for highest performance -- RecordCount() will always return -1 then.\r
+        */\r
+       $ADODB_COUNTRECS = true; \r
+\r
+       /**\r
+        * Helper class for FetchFields -- holds info on a column\r
+        */\r
+       class ADOFieldObject { \r
+               var $name = '';\r
+               var $max_length=0;\r
+               var $type="";\r
+       }\r
+\r
+       \r
+       /**\r
+        * Connection object. For connecting to databases, and executing queries.\r
+        */ \r
+       class ADOConnection {\r
+       /*\r
+        * PUBLIC VARS \r
+        */\r
+       var $dataProvider = 'native';\r
+       var $databaseType = ''; // RDBMS currently in use, eg. odbc, mysql, mssql                                       \r
+       var $database = '';     // Name of database to be used. \r
+       var $host = '';         //The hostname of the database server   \r
+       var $user = '';         // The username which is used to connect to the database server. \r
+       var $password = '';     // Password for the username\r
+       var $debug = false;     // if set to true will output sql statements\r
+       var $maxblobsize = 8000; // maximum size of blobs or large text fields -- some databases die otherwise like foxpro\r
+       var $concat_operator = '+';     // default concat operator -- change to || for Oracle/Interbase \r
+       var $fmtDate = "'Y-m-d'";       // used by DBDate() as the default date format used by the database\r
+       var $fmtTimeStamp = "'Y-m-d, h:i:s A'"; // used by DBTimeStamp as the default timestamp fmt.\r
+       var $true = '1';                // string that represents TRUE for a database\r
+       var $false = '0';               // string that represents FALSE for a database\r
+       var $replaceQuote = "\\'";      // string to use to replace quotes\r
+    var $hasInsertID = false;  // supports autoincrement ID?\r
+    var $hasAffectedRows = false;      // supports affected rows for update/delete?\r
+    var $autoCommit = true; \r
+       var $charSet=false;             // character set to use - only for interbase\r
+       var $metaTablesSQL = '';\r
+       var $hasTop = false;            // support mssql/access SELECT TOP 10 * FROM TABLE\r
+       var $hasLimit = false;          // support pgsql/mysql SELECT * FROM TABLE LIMIT 10\r
+       var $readOnly = false;          // this is a readonly database ?\r
+       var $hasMoveFirst = false;\r
+       var $hasGenID = false; // can generate sequences using GenID();\r
+       var $genID = false; // sequence id used by GenID();\r
+       var $raiseErrorFn = false;\r
+       \r
+       /*\r
+        * PRIVATE VARS\r
+        */\r
+       var $_connectionID      = false;        // The returned link identifier whenever a successful database connection is made.      */\r
+               \r
+       var $_errorMsg = '';            // A variable which was used to keep the returned last error message.  The value will\r
+                                       //then returned by the errorMsg() function      \r
+                                               \r
+       var $_queryID = false;          // This variable keeps the last created result link identifier.         */\r
+       \r
+       var $_isPersistentConnection = false;   // A boolean variable to state whether its a persistent connection or normal connection.        */\r
+       \r
+       var $_bindInputArray = false; // set to true if ADOConnection.Execute() permits binding of array parameters.\r
+       \r
+       /**\r
+        * Constructor\r
+        */\r
+       function ADOConnection()                        \r
+       {\r
+               die('Virtual Class -- cannot instantiate');\r
+       }\r
+       \r
+       /**\r
+        * Connect to database\r
+        *\r
+        * @param [argHostname]         Host to connect to\r
+        * @param [argUsername]         Userid to login\r
+        * @param [argPassword]         Associated password\r
+        * @param [argDatabaseName]     database\r
+        *\r
+        * @return true or false\r
+        */       \r
+       function Connect($argHostname = "", $argUsername = "", $argPassword = "", $argDatabaseName = "") {\r
+               if ($argHostname != "") $this->host = $argHostname;\r
+               if ($argUsername != "") $this->user = $argUsername;\r
+               if ($argPassword != "") $this->password = $argPassword; // not stored for security reasons\r
+               if ($argDatabaseName != "") $this->database = $argDatabaseName;         \r
+               \r
+               if ($this->_connect($this->host, $this->user, $this->password, $this->database))\r
+                       return true;\r
+                       \r
+               if ($fn = $this->raiseErrorFn) {\r
+                       $fn($this->databaseType,'CONNECT',$this->ErrorNo(),$this->ErrorMsg(),$this->host,$this->database);\r
+               }\r
+               if ($this->debug) print $this->host.': '.$this->ErrorMsg().'<br>';\r
+               \r
+               return false;\r
+       }       \r
+       \r
+       /**\r
+        * Establish persistent connect to database\r
+        *\r
+        * @param [argHostname]         Host to connect to\r
+        * @param [argUsername]         Userid to login\r
+        * @param [argPassword]         Associated password\r
+        * @param [argDatabaseName]     database\r
+        *\r
+        * @return return true or false\r
+        */     \r
+       function PConnect($argHostname = "", $argUsername = "", $argPassword = "", $argDatabaseName = "")\r
+       {\r
+               if ($argHostname != "") $this->host = $argHostname;\r
+               if ($argUsername != "") $this->user = $argUsername;\r
+               if ($argPassword != "") $this->password = $argPassword;\r
+               if ($argDatabaseName != "") $this->database = $argDatabaseName;                 \r
+                       \r
+               if ($this->_pconnect($this->host, $this->user, $this->password, $this->database)) {\r
+                       $this->_isPersistentConnection = true;  \r
+                       return true;                    \r
+               }\r
+               if ($fn = $this->raiseErrorFn) {\r
+                       $fn($this->databaseType,'PCONNECT', $this->ErrorNo(),$this->ErrorMsg(),$this->host,$this->database);\r
+               }\r
+               if ($this->debug) print $this->host.': '.$this->ErrorMsg().'<br>';\r
+               \r
+               return false;\r
+       }\r
+       \r
+       /**\r
+        * Should prepare the sql statement and return the stmt resource.\r
+        * For databases that do not support this, we return the $sql. To ensure\r
+        * compatibility with databases that do not support prepare:\r
+        *\r
+        *   $stmt = $db->Prepare("insert into table (id, name) values (?,?)");\r
+        *   $db->Execute($stmt,array(1,'Jill')) or die('insert failed');\r
+        *   $db->Execute($stmt,array(2,'Joe')) or die('insert failed');\r
+        *\r
+        * @param sql   SQL to send to database\r
+        *\r
+        * @return return TRUE or FALSE, or the $sql.\r
+        *\r
+        */     \r
+       function Prepare($sql)\r
+       {\r
+               return $sql;\r
+       }\r
+       \r
+       /**\r
+       * PEAR DB Compat - do not use internally. \r
+       */\r
+       function Quote($s)\r
+       {\r
+               return $this->qstr($s);\r
+       }\r
+       \r
+       /**\r
+       * PEAR DB Compat - do not use internally. \r
+       */\r
+       function ErrorNative()\r
+    {\r
+        return $this->ErrorNo();\r
+    }\r
+\r
+   /**\r
+       * PEAR DB Compat - do not use internally. \r
+       */\r
+    function nextId($seq_name)\r
+       {\r
+               return $this->GenID($seq_name);\r
+       }\r
+       \r
+       /**\r
+       * PEAR DB Compat - do not use internally. \r
+       *\r
+       * Appears that the fetch modes for NUMERIC and ASSOC are identical!\r
+       */\r
+       function SetFetchMode($mode)\r
+       {\r
+       global $ADODB_FETCH_MODE;\r
+               $ADODB_FETCH_MODE = $mode;\r
+       }\r
+       \r
+       /**\r
+       * PEAR DB Compat - do not use internally. \r
+       */\r
+       function &Query($sql, $inputarr=false)\r
+       {\r
+               $rs = &$this->Execute($sql, $inputarr);\r
+               if (!$rs && defined('ADODB_PEAR')) return ADODB_PEAR_Error();\r
+               return $rs;\r
+       }\r
+       \r
+       /**\r
+       * PEAR DB Compat - do not use internally\r
+       */\r
+       function &LimitQuery($sql, $offset, $count)\r
+       {\r
+               $rs = &$this->SelectLimit($sql, $count, $offset); // swap \r
+               if (!$rs && defined('ADODB_PEAR')) return ADODB_PEAR_Error();\r
+               return $rs;\r
+       }\r
+       \r
+       /**\r
+       * PEAR DB Compat - do not use internally\r
+       */\r
+       function Free()\r
+       {\r
+               return $this->Close();\r
+       }\r
+       \r
+       /**\r
+        * Execute SQL \r
+        *\r
+        * @param sql           SQL statement to execute\r
+        * @param [inputarr]    holds the input data to bind to. Null elements will be set to null.\r
+        * @param [arg3]        reserved for john lim for future use\r
+        * @return              RecordSet or false\r
+        */\r
+       function &Execute($sql,$inputarr=false,$arg3=false) \r
+       {\r
+               if (!$this->_bindInputArray && $inputarr) {\r
+                       $sqlarr = explode('?',$sql);\r
+                       $sql = '';\r
+                       $i = 0;\r
+                       foreach($inputarr as $v) {\r
+\r
+                               $sql .= $sqlarr[$i];\r
+                               // from Ron Baldwin <ron.baldwin@sourceprose.com>\r
+                               // Only quote string types      \r
+                               if (gettype($v) == 'string')\r
+                                       $sql .= "'".$v."'";\r
+                               else if ($v === null)\r
+                                       $sql .= 'NULL';\r
+                               else\r
+                                       $sql .= $v;\r
+                               $i += 1;\r
+       \r
+                       }\r
+                       $sql .= $sqlarr[$i];\r
+                       if ($i+1 != sizeof($sqlarr))    print "Input Array does not match ?: ".htmlspecialchars($sql);\r
+                       $inputarr = false;\r
+               }\r
+               \r
+               if ($this->debug) {\r
+                       $ss = '';\r
+                       if ($inputarr) {\r
+                               //$inputarr[7] = '2003-01-01';\r
+                               foreach ($inputarr as $kk => $vv)  {\r
+                                       if (is_string($vv) && strlen($vv)>100) $vv = substr($vv,0,64).'...';\r
+                                       $ss .= "($kk=>'$vv') ";\r
+                               }\r
+                               $ss = "[ $ss ]";\r
+                       }\r
+                       print "<hr>($this->databaseType): ".htmlspecialchars($sql)." &nbsp; <code>$ss</code><hr>";\r
+                       $this->_queryID = $this->_query($sql,$inputarr,$arg3);\r
+                       if ($this->databaseType == 'mssql') { // ErrorNo is a slow function call in mssql\r
+                               if($this->ErrorMsg()) {\r
+                                       $err = $this->ErrorNo();\r
+                                       if ($err) print $err.': '.$this->ErrorMsg().'<br>';\r
+                               }\r
+                       } else \r
+                               if ($this->ErrorNo()) print $this->ErrorNo().': '.$this->ErrorMsg().'<br>';\r
+                               \r
+               } else \r
+                       $this->_queryID =@$this->_query($sql,$inputarr,$arg3);\r
+               \r
+               if ($this->_queryID === false) {\r
+                       if ($fn = $this->raiseErrorFn) {\r
+                               $fn($this->databaseType,'EXECUTE',$this->ErrorNo(),$this->ErrorMsg(),$sql,$inputarr);\r
+                       }\r
+                       return false;\r
+               } else if ($this->_queryID === true){\r
+                       $rs = new ADORecordSet_empty();\r
+                       return $rs;\r
+               }\r
+               $rsclass = "ADORecordSet_".$this->databaseType;\r
+               \r
+               $rs = new $rsclass($this->_queryID); // &new not supported by older PHP versions\r
+               $rs->Init();\r
+               //$this->_insertQuery(&$rs); PHP4 handles closing automatically\r
+\r
+               if (is_string($sql)) $rs->sql = $sql;\r
+               return $rs;\r
+       }\r
+       \r
+       /**\r
+        * Generates a sequence id and stores it in $this->genID;\r
+        * GenID is only available if $this->hasGenID = true;\r
+        *\r
+        * @seqname             name of sequence to use\r
+        * \r
+        * @return              false if not supported, otherwise a sequence id\r
+        */\r
+       \r
+       function GenID($seqname='adodbseq')\r
+       {\r
+               if (!$this->hasGenID) return false;\r
+               \r
+               $getnext = sprintf($this->_genIDSQL,$seqname);\r
+               $rs = @$this->Execute($getnext);\r
+               if (!$rs) {\r
+                       $u = strtoupper($seqname);\r
+                       $createseq = \r
+                       $this->Execute(sprintf($this->_genSeqSQL,$seqname));\r
+                       $rs = $this->Execute($getnext);\r
+               }\r
+               if ($rs && !$rs->EOF) $this->genID = (integer) $rs->fields[0];\r
+               else $this->genID = false;\r
+               \r
+               if ($rs) $rs->Close();\r
+               \r
+               return $this->genID;\r
+       }\r
+       \r
+       \r
+       /**\r
+        * @return  the last inserted ID. Not all databases support this.\r
+        */ \r
+        function Insert_ID()\r
+        {\r
+                if ($this->hasInsertID) return $this->_insertid();\r
+                if ($this->debug) print '<p>Insert_ID error</p>';\r
+                return false;\r
+        }\r
+       \r
+        /**\r
+        * @return  # rows affected by UPDATE/DELETE\r
+        */ \r
+        function Affected_Rows()\r
+        {\r
+                if ($this->hasAffectedRows) {\r
+                       $val = $this->_affectedrows();\r
+                       return ($val < 0) ? false : $val;\r
+                }\r
+                        \r
+                if ($this->debug) print '<p>Affected_Rows error</p>';\r
+                return false;\r
+        }\r
+       \r
+        /**\r
+        * @return  the last error message\r
+        */\r
+       function ErrorMsg()\r
+       {\r
+               return '!! '.strtoupper($this->dataProvider.' '.$this->databaseType).': '.$this->_errorMsg;\r
+       }\r
+       \r
+       \r
+       /**\r
+        * @return the last error number. Normally 0 means no error.\r
+        */\r
+       function ErrorNo() \r
+       {\r
+               return ($this->_errorMsg) ? -1 : 0;\r
+       }\r
+       \r
+       /**\r
+        * @returns an array with the primary key columns in it.\r
+        */\r
+       function MetaPrimaryKeys($table)\r
+       {\r
+               return false;\r
+       }\r
+       \r
+       /**\r
+        * Choose a database to connect to. Many databases do not support this.\r
+        *\r
+        * @param dbName        is the name of the database to select\r
+        * @return              true or false\r
+        */\r
+       function SelectDB($dbName) \r
+       {return false;}\r
+       \r
+       \r
+       /**\r
+       * Will select, getting rows from $offset (1-based), for $nrows. \r
+       * This simulates the MySQL "select * from table limit $offset,$nrows" , and\r
+       * the PostgreSQL "select * from table limit $nrows offset $offset". Note that\r
+       * MySQL and PostgreSQL parameter ordering is the opposite of the other.\r
+       * eg. \r
+       *  SelectLimit('select * from table',3); will return rows 1 to 3 (1-based)\r
+       *  SelectLimit('select * from table',3,2); will return rows 3 to 5 (1-based)\r
+       *\r
+       * Uses SELECT TOP for Microsoft databases, and FIRST_ROWS CBO hint for Oracle 8+\r
+       * BUG: Currently SelectLimit fails with $sql with LIMIT or TOP clause already set\r
+       *\r
+       * @param sql\r
+       * @param [offset]       is the row to start calculations from (1-based)\r
+       * @param [rows]         is the number of rows to get\r
+       * @param [inputarr]     array of bind variables\r
+       * @param [arg3]         is a private parameter only used by jlim\r
+       * @param [secs2cache]           is a private parameter only used by jlim\r
+       * @return               the recordset ($rs->databaseType == 'array')\r
+       */\r
+       function &SelectLimit($sql,$nrows=-1,$offset=-1, $inputarr=false,$arg3=false,$secs2cache=0)\r
+       {\r
+               if ($this->hasTop && $nrows > 0 && $offset <= 0) {\r
+               // suggested by Reinhard Balling. Access requires top after distinct \r
+                       $sql = eregi_replace(\r
+                       '(^select[\\t\\n ]*(distinct|distinctrow )?)','\\1 top '.$nrows.' ',$sql);\r
+                       if ($secs2cache>0) return $this->CacheExecute($secs2cache, $sql,$inputarr,$arg3);\r
+                       else return $this->Execute($sql,$inputarr,$arg3);\r
+               } else if ($this->dataProvider == 'oci8') {\r
+                       $sql = eregi_replace('^select','SELECT /*+FIRST_ROWS*/',$sql);\r
+                       if ($offset <= 0) {\r
+                               /*if (preg_match('/\bwhere\b/i',$sql)) {\r
+                                       $sql = preg_replace('/where/i',"where rownum <= $nrows and ",$sql);\r
+                               } else*/ \r
+                               // doesn't work becoz sort is after rownum is executed - also preg_replace\r
+                               // is a heuristic that might not work if there is an or\r
+                                       $sql = "select * from ($sql) where rownum <= :lens_sellimit_rownum";\r
+                                       $inputarr['lens_sellimit_rownum'] = $nrows;\r
+                       }/* else {\r
+                               # THIS DOES NOT WORK -- WHY?\r
+                                       $sql = "select * from ($sql) where rownum between :lens_sellimit_rownum1 and :lens_sellimit_rownum2";\r
+                                       $end = $offset+$nrows;\r
+                                       if ($offset < $end) {\r
+                                               $inputarr['lens_sellimit_rownum1'] = $offset;\r
+                                               $inputarr['lens_sellimit_rownum2'] = $end;\r
+                                       } else {\r
+                                               $inputarr['lens_sellimit_rownum1'] = $end;\r
+                                               $inputarr['lens_sellimit_rownum2'] = $offset;\r
+                                       }\r
+                                       $offset = -1;\r
+                                       $this->debug=true;\r
+                       }*/\r
+               }\r
+               if ($secs2cache>0) $rs = &$this->CacheExecute($secs2cache,$sql,$inputarr,$arg3);\r
+               else $rs = &$this->Execute($sql,$inputarr,$arg3);\r
+               if ($rs && !$rs->EOF) {\r
+                       return $this->_rs2rs($rs,$nrows,$offset);\r
+               }\r
+               //print_r($rs);\r
+               return $rs;\r
+       }\r
+       \r
+       /**\r
+       * Convert recordset to an array recordset\r
+       * input recordset's cursor should be at beginning, and\r
+       * old $rs will be closed.\r
+       *\r
+       * @param rs                     the recordset to copy\r
+       * @param [nrows]        number of rows to retrieve (optional)\r
+       * @param [offset]       offset by number of rows (optional)\r
+       * @return                       the new recordset\r
+       */\r
+       function &_rs2rs(&$rs,$nrows=-1,$offset=-1)\r
+       {\r
+               \r
+               $arr = &$rs->GetArrayLimit($nrows,$offset);\r
+               $flds = array();\r
+               for ($i=0, $max=$rs->FieldCount(); $i < $max; $i++)\r
+                       $flds[] = &$rs->FetchField($i);\r
+               \r
+               $rs->Close();\r
+               $rs2 = new ADORecordSet_array();\r
+                       \r
+               $rs2->InitArrayFields($arr,$flds);\r
+               return $rs2;\r
+       }\r
+       \r
+       /**\r
+       * Return first element of first row of sql statement. Recordset is disposed\r
+       * for you.\r
+       *\r
+       * @param sql                    SQL statement\r
+       * @param [inputarr]             input bind array\r
+       */\r
+       function GetOne($sql,$inputarr=false)\r
+       {\r
+               $rs = $this->Execute($sql,$inputarr);\r
+               if ($rs && !$rs->EOF) {\r
+                       $rs->Close();\r
+                       return $rs->fields[0];\r
+               }\r
+               return false;\r
+       }\r
+       \r
+       /**\r
+       * Return all rows. Compat with PEAR DB\r
+       *\r
+       * @param sql                    SQL statement\r
+       * @param [inputarr]             input bind array\r
+       */\r
+       function GetAll($sql,$inputarr=false)\r
+       {\r
+               $rs = $this->Execute($sql,$inputarr);\r
+               if (!$rs) \r
+                       if (defined('ADODB_PEAR')) return ADODB_PEAR_Error();\r
+                       else return false;\r
+               return $rs->GetArray();\r
+       }\r
+       \r
+       /**\r
+       * Return one row of sql statement. Recordset is disposed for you.\r
+       *\r
+       * @param sql                    SQL statement\r
+       * @param [inputarr]             input bind array\r
+       */\r
+       function GetRow($sql,$inputarr=false)\r
+       {\r
+               $rs = $this->Execute($sql,$inputarr);\r
+               if ($rs && !$rs->EOF) {\r
+                       $rs->Close();\r
+                       return $rs->fields;\r
+               }\r
+               return false;\r
+       }\r
+       \r
+       \r
+       \r
+       /**\r
+       * Will select, getting rows from $offset (1-based), for $nrows. \r
+       * This simulates the MySQL "select * from table limit $offset,$nrows" , and\r
+       * the PostgreSQL "select * from table limit $nrows offset $offset". Note that\r
+       * MySQL and PostgreSQL parameter ordering is the opposite of the other.\r
+       * eg. \r
+       *  CacheSelectLimit(15,'select * from table',3); will return rows 1 to 3 (1-based)\r
+       *  CacheSelectLimit(15,'select * from table',3,2); will return rows 3 to 5 (1-based)\r
+       *\r
+       * BUG: Currently CacheSelectLimit fails with $sql with LIMIT or TOP clause already set\r
+       *\r
+       * @param secs2cache     seconds to cache data, set to 0 to force query\r
+       * @param sql\r
+       * @param [offset]       is the row to start calculations from (1-based)\r
+       * @param [nrows]        is the number of rows to get\r
+       * @param [inputarr]     array of bind variables\r
+       * @param [arg3]         is a private parameter only used by jlim\r
+       * @return               the recordset ($rs->databaseType == 'array')\r
+       */\r
+       function &CacheSelectLimit($secs2cache,$sql,$nrows=-1,$offset=-1,$inputarr=false, $arg3=false)\r
+       {\r
+               return $this->SelectLimit($sql,$nrows,$offset,$inputarr,$arg3,$secs2cache);\r
+       }\r
+       \r
+       function CacheFlush($sql)\r
+       {\r
+               $f = $this->_gencachename($sql);\r
+               adodb_write_file($f,'');\r
+               @unlink($f);\r
+       }\r
+       \r
+       function _gencachename($sql)\r
+       {\r
+       global $ADODB_CACHE_DIR;\r
+       \r
+               return $ADODB_CACHE_DIR.'/adodb_'.md5($sql.$this->databaseType.$this->database.$this->user).'.cache';\r
+       }\r
+       /**\r
+        * Execute SQL, caching recordsets.\r
+        *\r
+        * @param secs2cache    seconds to cache data, set to 0 to force query\r
+        * @param sql           SQL statement to execute\r
+        * @param [inputarr]    holds the input data  to bind to\r
+        * @param [arg3]        reserved for john lim for future use\r
+        * @return              RecordSet or false\r
+        */\r
+       function &CacheExecute($secs2cache,$sql,$inputarr=false,$arg3=false)\r
+       {\r
+               // cannot cache if $inputarr set\r
+               if ($inputarr) return $this->Execute($sql, $inputarr, $arg3); \r
+               \r
+               $md5file = $this->_gencachename($sql);\r
+               $err = '';\r
+               \r
+               if ($secs2cache > 0)$rs = &csv2rs($md5file,$err,$secs2cache);\r
+               else {\r
+                       $err='Timeout 1';\r
+                       $rs = false;\r
+               }\r
+               \r
+               if (!$rs) {\r
+                       if ($this->debug) print " $md5file cache failure: $err<br>";\r
+                       $rs = &$this->Execute($sql,$inputarr,$arg3);\r
+                       if ($rs) {\r
+                               $eof = $rs->EOF;\r
+                               $rs = &$this->_rs2rs($rs);\r
+                               $txt = &rs2csv($rs,false,$sql);\r
+                               \r
+                               if (!adodb_write_file($md5file,$txt,$this->debug) && $this->debug) print ' Cache write error<br>';\r
+                               if ($rs->EOF && !$eof) {\r
+                                       $rs = &csv2rs($md5file,$err);\r
+                               }\r
+                       } else\r
+                               @unlink($md5file);\r
+               }else if ($this->debug){ \r
+                       $ttl = $rs->timeCreated + $secs2cache - time();\r
+                       print " $md5file success ttl=$ttl<br>";\r
+               }\r
+               return $rs;\r
+       }\r
+       \r
+    /**\r
+        * Generates an Update Query based on an existing recordset.\r
+        * $arrFields is an associative array of fields with the value\r
+        * that should be assigned.\r
+        *\r
+        * Note: This function should only be used on a recordset\r
+        *       that is run against a single table.\r
+        *\r
+        * "Jonathan Younger" <jyounger@unilab.com>\r
+        */\r
+       function GetUpdateSQL(&$rs, $arrFields,$forceUpdate=false)\r
+       {\r
+               if (!$rs) {\r
+                       printf(ADODB_BAD_RS,'GetUpdateSQL');\r
+                       return false;\r
+               }\r
+       \r
+               // Get the table name from the existing query.\r
+               eregi("FROM ([]0-9a-z_\[-]*)", $rs->sql, $tableName);\r
+\r
+               // Get the full where clause excluding the word "WHERE" from\r
+               // the existing query.\r
+               eregi("WHERE ([]0-9a-z=' \(\)\[\t\r\n_-]*)", $rs->sql, $whereClause);\r
+\r
+               // updateSQL will contain the full update query when all\r
+               // processing has completed.\r
+               $updateSQL = "UPDATE " . $tableName[1] . " SET ";\r
+               \r
+               // Loop through all of the fields in the recordset\r
+               for ($i=0, $max=$rs->FieldCount(); $i < $max; $i++) {\r
+               \r
+                       // Get the field from the recordset\r
+                       $field = $rs->FetchField($i);\r
+\r
+                       // If the recordset field is one\r
+                       // of the fields passed in then process.\r
+                       if (isset($arrFields[$field->name])) {\r
+\r
+                               // If the existing field value in the recordset\r
+                               // is different from the value passed in then\r
+                               // go ahead and append the field name and new value to\r
+                               // the update query.\r
+\r
+                               if ($forceUpdate || strcmp($rs->fields[$i], $arrFields[$field->name])) {\r
+                                       // Set the counter for the number of fields that will be updated.\r
+                                       $fieldUpdatedCount++;\r
+\r
+                                       // Based on the datatype of the field\r
+                                       // Format the value properly for the database\r
+                                       switch($rs->MetaType($field->type)) {\r
+                                               case "C":\r
+                                               case "X":\r
+                                                       $updateSQL .= $field->name . " = " . $this->qstr($arrFields[$field->name]) . ", ";\r
+                                                       break;\r
+                                               case "D":\r
+                                                       $updateSQL .= $field->name . " = " . $this->DBDate($arrFields[$field->name]) . ", ";\r
+                                                       break;\r
+                                               case "T":\r
+                                                       $updateSQL .= $field->name . " = " . $this->DBTimeStamp($arrFields[$field->name]) . ", ";\r
+                                                       break;\r
+                                               default:\r
+                                                       $updateSQL .= $field->name . " = " . $arrFields[$field->name] . ", ";\r
+                                                       break;\r
+                                       };\r
+                               };\r
+               };\r
+               };\r
+\r
+               // If there were any modified fields then build the rest of the update query.\r
+               if ($fieldUpdatedCount > 0 || $forceUpdate) {\r
+                       // Strip off the comma and space on the end of the update query.\r
+                       $updateSQL = substr($updateSQL, 0, -2);\r
+\r
+                       // If the recordset has a where clause then use that same where clause\r
+                       // for the update.\r
+                       if ($whereClause[1]) $updateSQL .= " WHERE " . $whereClause[1];\r
+\r
+                       return $updateSQL;\r
+               } else {\r
+                       return false;\r
+               };\r
+       }\r
+\r
+\r
+       /**\r
+        * Generates an Insert Query based on an existing recordset.\r
+        * $arrFields is an associative array of fields with the value\r
+        * that should be assigned.\r
+        *\r
+        * Note: This function should only be used on a recordset\r
+        *       that is run against a single table.\r
+        */\r
+       function GetInsertSQL(&$rs, $arrFields)\r
+       {\r
+               if (!$rs) {\r
+                       printf(ADODB_BAD_RS,'GetInsertSQL');\r
+                       return false;\r
+               }\r
+               // Get the table name from the existing query.\r
+               eregi("FROM ([0-9a-z_-]*)", $rs->sql, $tableName);\r
+\r
+               // Loop through all of the fields in the recordset\r
+               for ($i=0, $max=$rs->FieldCount(); $i < $max; $i++) {\r
+\r
+                       // Get the field from the recordset\r
+                       $field = $rs->FetchField($i);\r
+                       // If the recordset field is one\r
+                       // of the fields passed in then process.\r
+                       if (isset($arrFields[$field->name])) {\r
+       \r
+                               // Set the counter for the number of fields that will be inserted.\r
+                               $fieldInsertedCount++;\r
+\r
+                               // Get the name of the fields to insert\r
+                               $fields .= $field->name . ", ";\r
+\r
+                               // Based on the datatype of the field\r
+                               // Format the value properly for the database\r
+                               switch($rs->MetaType($field->type)) {\r
+                                       case "C":\r
+                                       case "X":\r
+                                               $values .= $this->qstr($arrFields[$field->name]) . ", ";\r
+                                               break;\r
+                                       case "D":\r
+                                               $values .= $this->DBDate($arrFields[$field->name]) . ", ";\r
+                                               break;\r
+                                       case "T":\r
+                                               $values .= $this->DBTimeStamp($arrFields[$field->name]) . ", ";\r
+                                               break;\r
+                                       default:\r
+                                               $values .= $arrFields[$field->name] . ", ";\r
+                                               break;\r
+                               };\r
+               };\r
+       };\r
+\r
+               // If there were any inserted fields then build the rest of the insert query.\r
+               if ($fieldInsertedCount > 0) {\r
+\r
+                       // Strip off the comma and space on the end of both the fields\r
+                       // and their values.\r
+                       $fields = substr($fields, 0, -2);\r
+                       $values = substr($values, 0, -2);\r
+\r
+                       // Append the fields and their values to the insert query.\r
+                       $insertSQL = "INSERT INTO " . $tableName[1] . " ( $fields ) VALUES ( $values )";\r
+\r
+                       return $insertSQL;\r
+\r
+               } else {\r
+                       return false;\r
+               };\r
+       }\r
+\r
+       /**\r
+       * Usage:\r
+       *       UpdateBlob('TABLE', 'COLUMN', $var, 'ID=1', 'BLOB');\r
+       *       \r
+       *       $blobtype supports 'BLOB' and 'CLOB'\r
+       *\r
+       *       $conn->Execute('INSERT INTO blobtable (id, blobcol) VALUES (1, null)');\r
+       *       $conn->UpdateBlob('blobtable','blobcol',$blob,'id=1');\r
+       */\r
+       function UpdateBlob($table,$column,$val,$where,$blobtype='BLOB')\r
+       {\r
+               $sql = "UPDATE $table SET $column=".$this->qstr($val)." where $where";\r
+               $rs = $this->Execute($sql);\r
+               \r
+               $rez = !empty($rs);\r
+               if ($rez) $rs->Close();\r
+               return $rez;\r
+       }\r
+       \r
+       /**\r
+       * Usage:\r
+       *       UpdateBlob('TABLE', 'COLUMN', $var, 'ID=1', 'CLOB');\r
+       *\r
+       *       $conn->Execute('INSERT INTO clobtable (id, clobcol) VALUES (1, null)');\r
+       *       $conn->UpdateClob('clobtable','clobcol',$clob,'id=1');\r
+       */\r
+       function UpdateClob($table,$column,$val,$where)\r
+       {\r
+               return $this->UpdateBlob($table,$column,$val,$where,'CLOB');\r
+       }\r
+       \r
+       \r
+       function BlankRecordSet($id=false)\r
+       {\r
+               $rsclass = "ADORecordSet_".$this->databaseType;\r
+               return new $rsclass($id);\r
+       }\r
+       \r
+       \r
+       /**\r
+        * Close Connection\r
+        */\r
+       function Close() \r
+       {\r
+               return $this->_close();\r
+               \r
+               // "Simon Lee" <simon@mediaroad.com> reports that persistent connections need \r
+               // to be closed too!\r
+               //if ($this->_isPersistentConnection != true) return $this->_close();\r
+               //else return true;     \r
+       }\r
+       \r
+       /**\r
+        * Begin a Transaction. Must be followed by CommitTrans() or RollbackTrans().\r
+        *\r
+        * @return true if succeeded or false if database does not support transactions\r
+        */\r
+       function BeginTrans() {return false;}\r
+       \r
+       /**\r
+        * If database does not support transactions, always return true as data always commited\r
+        *\r
+        * @return true/false.\r
+        */\r
+       function CommitTrans() \r
+       { return true;}\r
+       \r
+       /**\r
+        * If database does not support transactions, rollbacks always fail, so return false\r
+        *\r
+        * @return true/false.\r
+        */\r
+       function RollbackTrans() \r
+       { return false;}\r
+\r
+\r
+        /**\r
+        * return the databases that the driver can connect to. \r
+        * Some databases will return an empty array.\r
+        *\r
+        * @return an array of database names.\r
+        */\r
+        function &MetaDatabases() \r
+               {return false;}\r
+        \r
+       /**\r
+        * @return  array of tables for current database.\r
+        */ \r
+    function &MetaTables() \r
+       {\r
+               if ($this->metaTablesSQL) {\r
+                       $rs = $this->Execute($this->metaTablesSQL);\r
+                       if ($rs === false) return false;\r
+                       $arr = $rs->GetArray();\r
+                       $arr2 = array();\r
+                       for ($i=0; $i < sizeof($arr); $i++) {\r
+                               $arr2[] = $arr[$i][0];\r
+                       }\r
+                       $rs->Close();\r
+                       return $arr2;\r
+               }\r
+               return false;\r
+       }\r
+       \r
+       /**\r
+        * List columns in a database as an array of ADOFieldObjects. \r
+        * See top of file for definition of object.\r
+        *\r
+        * @params table        table name to query\r
+        *\r
+        * @return  array of ADOFieldObjects for current table.\r
+        */ \r
+    function &MetaColumns($table) \r
+       {\r
+       \r
+               if (!empty($this->metaColumnsSQL)) {\r
+               \r
+                       $rs = $this->Execute(sprintf($this->metaColumnsSQL,strtoupper($table)));\r
+                       if ($rs === false) return false;\r
+\r
+                       $retarr = array();\r
+                       while (!$rs->EOF) { //print_r($rs->fields);\r
+                               $fld = new ADOFieldObject();\r
+                               $fld->name = $rs->fields[0];\r
+                               $fld->type = $rs->fields[1];\r
+                               $fld->max_length = $rs->fields[2];\r
+                               $retarr[strtoupper($fld->name)] = $fld; \r
+                               \r
+                               $rs->MoveNext();\r
+                       }\r
+                       $rs->Close();\r
+                       return $retarr; \r
+               }\r
+               return false;\r
+       }\r
+      \r
+               \r
+       /**\r
+        * Different SQL databases used different methods to combine strings together.\r
+        * This function provides a wrapper. \r
+        * \r
+        * @param s     variable number of string parameters\r
+        *\r
+        * Usage: $db->Concat($str1,$str2);\r
+        * \r
+        * @return concatenated string\r
+        */      \r
+       function Concat()\r
+       {       \r
+               $arr = func_get_args();\r
+               return implode($this->concat_operator, $arr);\r
+       }\r
+       \r
+       /**\r
+        * Converts a date "d" to a string that the database can understand.\r
+        *\r
+        * @param d     a date in Unix date time format.\r
+        *\r
+        * @return  date string in database date format\r
+        */\r
+       function DBDate($d)\r
+       {\r
+       // note that we are limited to 1970 to 2038\r
+               return date($this->fmtDate,$d);\r
+       }\r
+       \r
+       /**\r
+        * Converts a timestamp "ts" to a string that the database can understand.\r
+        *\r
+        * @param ts    a timestamp in Unix date time format.\r
+        *\r
+        * @return  timestamp string in database timestamp format\r
+        */\r
+       function DBTimeStamp($ts)\r
+       {\r
+               return date($this->fmtTimeStamp,$ts);\r
+       }\r
+       \r
+       /**\r
+        * Converts a timestamp "ts" to a string that the database can understand.\r
+        * An example is  $db->qstr("Don't bother",magic_quotes_runtime());\r
+        * \r
+        * @param s                     the string to quote\r
+        * @param [magic_quotes]        if $s is GET/POST var, set to get_magic_quotes_gpc().\r
+        *                              This undoes the stupidity of magic quotes for GPC.\r
+        *\r
+        * @return  quoted string to be sent back to database\r
+        */\r
+       function qstr($s,$magic_quotes=false)\r
+       {       \r
+       $nofixquotes=false;\r
+               if (!$magic_quotes) {\r
+               \r
+                       if ($this->replaceQuote[0] == '\\'){\r
+                               $s = str_replace('\\','\\\\',$s);\r
+                       }\r
+                       return  "'".str_replace("'",$this->replaceQuote,$s)."'";\r
+               }\r
+               \r
+               // undo magic quotes for "\r
+               $s = str_replace('\\"','"',$s);\r
+               \r
+               if ($this->replaceQuote == "\\'")  // ' already quoted, no need to change anything\r
+                       return "'$s'";\r
+               else {// change \' to '' for sybase/mssql\r
+                       $s = str_replace('\\\\','\\',$s);\r
+                       return "'".str_replace("\\'",$this->replaceQuote,$s)."'";\r
+               }\r
+       }\r
+\r
+       \r
+       /**\r
+       * Will select the supplied $page number from a recordset, given that it is paginated in pages of \r
+       * $nrows rows per page. It also saves two boolean values saying if the given page is the first \r
+       * and/or last one of the recordset. Added by Iván Oliva to provide recordset pagination.\r
+       *\r
+       * See readme.htm#ex8 for an example of usage.\r
+       *\r
+       * @param sql\r
+       * @param nrows          is the number of rows per page to get\r
+       * @param page           is the page number to get (1-based)\r
+       * @param [inputarr]     array of bind variables\r
+       * @param [arg3]         is a private parameter only used by jlim\r
+       * @param [secs2cache]           is a private parameter only used by jlim\r
+       * @return               the recordset ($rs->databaseType == 'array')\r
+       *\r
+       * NOTE: phpLens uses a different algorithm and does not use PageExecute().\r
+       *\r
+       */\r
+       \r
+function &PageExecute($sql, $nrows, $page, $inputarr=false, $arg3=false, $secs2cache=0) \r
+{\r
+       $atfirstpage = false;\r
+       $atlastpage = false;\r
+       \r
+       if (!isset($page) || $page <= 1) {      // If page number <= 1, then we are at the first page\r
+               $page = 1;\r
+               $atfirstpage = true;\r
+       }\r
+       if ($nrows <= 0) $nrows = 10;   // If an invalid nrows is supplied, we assume a default value of 10 rows per page\r
+       \r
+       // ***** Here we check whether $page is the last page or whether we are trying to retrieve a page number greater than \r
+       // the last page number.\r
+       $pagecounter = $page + 1;\r
+       $pagecounteroffset = ($pagecounter * $nrows) - $nrows;\r
+       if ($secs2cache>0) $rstest = &$this->CacheSelectLimit($secs2cache, $sql, $nrows, $pagecounteroffset, $inputarr, $arg3);\r
+       else $rstest = &$this->SelectLimit($sql, $nrows, $pagecounteroffset, $inputarr, $arg3, $secs2cache);\r
+       if ($rstest) {\r
+               while ($rstest->EOF && $pagecounter>0) {\r
+                       $atlastpage = true;\r
+                       $pagecounter--;\r
+                       $pagecounteroffset = $pagecounter * ($nrows-1);\r
+                       if ($secs2cache>0) $rstest = &$this->CacheSelectLimit($secs2cache, $sql, $nrows, $pagecounteroffset, $inputarr, $arg3);\r
+                       else $rstest = &$this->SelectLimit($sql, $nrows, $pagecounteroffset, $inputarr, $arg3, $secs2cache);\r
+               }\r
+               $rstest->Close();\r
+       }\r
+       if ($atlastpage) {      // If we are at the last page or beyond it, we are going to retrieve it\r
+               $page = $pagecounter;\r
+               if ($page == 1) $atfirstpage = true;    // We have to do this again in case the last page is the same as the first\r
+                       //... page, that is, the recordset has only 1 page.\r
+       }\r
+       \r
+       // We get the data we want\r
+       $offset = $page * ($nrows-1);\r
+       if ($secs2cache > 0) $rsreturn = &$this->CacheSelectLimit($secs2cache, $sql, $nrows, $offset, $inputarr, $arg3);\r
+       else $rsreturn = &$this->SelectLimit($sql, $nrows, $offset, $inputarr, $arg3, $secs2cache);\r
+       \r
+       // Before returning the RecordSet, we set the pagination properties we need\r
+       if ($rsreturn) {\r
+               $rsreturn->AbsolutePage($page);\r
+               $rsreturn->AtFirstPage($atfirstpage);\r
+               $rsreturn->AtLastPage($atlastpage);\r
+       }\r
+       return $rsreturn;\r
+\r
+       }\r
+       \r
+               \r
+       /**\r
+       * Will select the supplied $page number from a recordset, given that it is paginated in pages of \r
+       * $nrows rows per page. It also saves two boolean values saying if the given page is the first \r
+       * and/or last one of the recordset. Added by Iván Oliva to provide recordset pagination.\r
+       *\r
+       * @param secs2cache     seconds to cache data, set to 0 to force query\r
+       * @param sql\r
+       * @param nrows          is the number of rows per page to get\r
+       * @param page           is the page number to get (1-based)\r
+       * @param [inputarr]     array of bind variables\r
+       * @param [arg3]         is a private parameter only used by jlim\r
+       * @return               the recordset ($rs->databaseType == 'array')\r
+       */\r
+       function &CachePageExecute($secs2cache, $sql, $nrows, $page,$inputarr=false, $arg3=false) {\r
+               return $this->PageExecute($sql, $nrows, $page, $inputarr, $arg3,$secs2cache);\r
+       }\r
+\r
+} // end class ADOConnection\r
+       \r
+       \r
+       \r
+       //==============================================================================================        \r
+       \r
+       /**\r
+       * Used by ADORecordSet->FetchObj()\r
+       */\r
+       class ADOFetchObj {\r
+       };\r
+       \r
+       \r
+       /**\r
+       * Lightweight recordset when there are no records to be returned\r
+       */\r
+       class ADORecordSet_empty\r
+       {\r
+               var $dataProvider = 'empty';\r
+               var $EOF = true;\r
+               var $_numOfRows = 0;\r
+               var $fields = false;\r
+               var $f = false;\r
+               function RowCount() {return 0;}\r
+               function RecordCount() {return 0;}\r
+               function Close(){return true;}\r
+       }\r
+       \r
+       /**\r
+        * RecordSet class that represents the dataset returned by the database.\r
+        * To keep memory overhead low, this class holds only the current row in memory.\r
+        * No prefetching of data is done, so the RecordCount() can return -1 (not known).\r
+        */\r
+       class ADORecordSet {\r
+       /*\r
+        * public variables     \r
+        */\r
+       var $dataProvider = "native";\r
+       var $fields = false; // holds the current row data\r
+       var $f = false;\r
+       var $blobSize = 64;     // any varchar/char field this size or greater is treated as a blob\r
+                               // in other words, we use a text area for editting.\r
+       var $canSeek = false;   // indicates that seek is supported\r
+       var $sql;               // sql text\r
+       var $EOF = false;       /* Indicates that the current record position is after the last record in a Recordset object. */\r
+       \r
+       var $emptyTimeStamp = '&nbsp;'; // what to display when $time==0\r
+       var $emptyDate = '&nbsp;'; // what to display when $time==0\r
+       var $debug = false;\r
+       var $timeCreated=0;     // datetime in Unix format rs created -- for cached recordsets\r
+\r
+       var $bind = false;      // used by Fields() to hold array - should be private?\r
+       var $fetchMode;         // default fetch mode\r
+       /*\r
+        *      private variables       \r
+        */\r
+       var $_numOfRows = -1;   \r
+       var $_numOfFields = -1; \r
+       var $_queryID = -1;     /* This variable keeps the result link identifier.      */\r
+       var $_currentRow = -1;  /* This variable keeps the current row in the Recordset.        */\r
+       var $_closed = false;   /* has recordset been closed */\r
+       var $_inited = false;   /* Init() should only be called once */\r
+       var $_obj;              /* Used by FetchObj */\r
+       var $_names;\r
+       \r
+       var $_currentPage = -1; /* Added by Iván Oliva to implement recordset pagination */\r
+       var $_atFirstPage = false;      /* Added by Iván Oliva to implement recordset pagination */\r
+       var $_atLastPage = false;       /* Added by Iván Oliva to implement recordset pagination */\r
+\r
+       \r
+       /**\r
+        * Constructor\r
+        *\r
+        * @param queryID       this is the queryID returned by ADOConnection->_query()\r
+        *\r
+        */\r
+       function ADORecordSet(&$queryID) \r
+       {\r
+               $this->_queryID = $queryID;\r
+               $this->f = &$this->fields;\r
+       }\r
+       \r
+       function Init()\r
+       {\r
+               if ($this->_inited) return;\r
+               $this->_inited = true;\r
+               \r
+               if ($this->_queryID) @$this->_initrs();\r
+               else {\r
+                       $this->_numOfRows = 0;\r
+                       $this->_numOfFields = 0;\r
+               }\r
+               if ($this->_numOfRows != 0 && $this->_numOfFields && $this->_currentRow == -1) {\r
+                       $this->_currentRow = 0;\r
+                       $this->EOF = ($this->_fetch() === false);\r
+               } else \r
+                       $this->EOF = true;\r
+       }\r
+       /**\r
+        * Generate a <SELECT> string from a recordset, and return the string.\r
+        * If the recordset has 2 cols, we treat the 1st col as the containing \r
+        * the text to display to the user, and 2nd col as the return value. Default\r
+        * strings are compared with the FIRST column.\r
+        *\r
+        * @param name                  name of <SELECT>\r
+        * @param [defstr]              the value to hilite. Use an array for multiple hilites for listbox.\r
+        * @param [blank1stItem]        true to leave the 1st item in list empty\r
+        * @param [multiple]            true for listbox, false for popup\r
+        * @param [size]                #rows to show for listbox. not used by popup\r
+        * @param [selectAttr]          additional attributes to defined for <SELECT>.\r
+        *                              useful for holding javascript onChange='...' handlers.\r
+        & @param [compareFields0]      when we have 2 cols in recordset, we compare the defstr with \r
+        *                              column 0 (1st col) if this is true. This is not documented.\r
+        *\r
+        * @return HTML\r
+        *\r
+        * changes by glen.davies@cce.ac.nz to support multiple hilited items\r
+        */\r
+        \r
+       function GetMenu($name,$defstr='',$blank1stItem=true,$multiple=false,\r
+                       $size=0, $selectAttr='',$compareFields0=true)\r
+       {\r
+               $hasvalue = false;\r
+\r
+               if ($multiple or is_array($defstr)) {\r
+                       if ($size==0) $size=5;\r
+                       $attr = " multiple size=$size";\r
+                       if (!strpos($name,'[]')) $name .= '[]';\r
+               } else if ($size) $attr = " size=$size";\r
+               else $attr ='';\r
+               \r
+                               \r
+               $s = "<select name=\"$name\"$attr $selectAttr>";\r
+               if ($blank1stItem) $s .= "\n<option></option>";\r
+       \r
+               if ($this->FieldCount() > 1) $hasvalue=true;\r
+               else $compareFields0 = true;\r
+               \r
+               while(!$this->EOF) {\r
+                       $zval = trim($this->fields[0]);\r
+                       $selected = trim($this->fields[$compareFields0 ? 0 : 1]);\r
+                       \r
+                       if ($blank1stItem && $zval=="") {\r
+                               $this->MoveNext();\r
+                               continue;\r
+                       }\r
+                       if ($hasvalue) \r
+                               $value = 'value="'.htmlspecialchars(trim($this->fields[1])).'"';\r
+                       \r
+                       \r
+                       if (is_array($defstr))  {\r
+                               \r
+                               if (in_array($selected,$defstr)) \r
+                                       $s .= "<option selected $value>".htmlspecialchars($zval).'</option>';\r
+                               else \r
+                                       $s .= "\n<option ".$value.'>'.htmlspecialchars($zval).'</option>';\r
+                       }\r
+                       else {\r
+                               if (strcasecmp($selected,$defstr)==0) \r
+                                       $s .= "<option selected $value>".htmlspecialchars($zval).'</option>';\r
+                               else \r
+                                       $s .= "\n<option ".$value.'>'.htmlspecialchars($zval).'</option>';\r
+                       }\r
+                       $this->MoveNext();\r
+               } // while\r
+               \r
+               return $s ."\n</select>\n";\r
+       }\r
+       /**\r
+        * Generate a <SELECT> string from a recordset, and return the string.\r
+        * If the recordset has 2 cols, we treat the 1st col as the containing \r
+        * the text to display to the user, and 2nd col as the return value. Default\r
+        * strings are compared with the SECOND column.\r
+        *\r
+        */\r
+       function GetMenu2($name,$defstr='',$blank1stItem=true,$multiple=false,$size=0, $selectAttr='')  \r
+       {\r
+               return ADORecordSet::GetMenu($name,$defstr,$blank1stItem,$multiple,$size, $selectAttr,false);\r
+       }\r
+\r
+\r
+       /**\r
+        * return recordset as a 2-dimensional array.\r
+        *\r
+        * @param [nRows]  is the number of rows to return. -1 means every row.\r
+        *\r
+        * @return an array indexed by the rows (0-based) from the recordset\r
+        */\r
+       function &GetArray($nRows = -1) \r
+       {\r
+               $results = array();\r
+               $cnt = 0;\r
+               while (!$this->EOF && $nRows != $cnt) {\r
+                       $results[$cnt++] = $this->fields;\r
+                       $this->MoveNext();\r
+               }\r
+               \r
+               return $results;\r
+       }\r
+       /**\r
+        * return recordset as a 2-dimensional array. \r
+        * Helper function for ADOConnection->SelectLimit()\r
+        *\r
+        * @param offset        is the row to start calculations from (1-based)\r
+        * @param [nrows]       is the number of rows to return\r
+        *\r
+        * @return an array indexed by the rows (0-based) from the recordset\r
+        */\r
+       function &GetArrayLimit($nrows,$offset=-1) \r
+       {\r
+               if ($offset <= 0) return $this->GetArray($nrows);\r
+               $this->Move($offset);\r
+               \r
+               $results = array();\r
+               $cnt = 0;\r
+               while (!$this->EOF && $nrows != $cnt) {\r
+                       $results[$cnt++] = $this->fields;\r
+                       $this->MoveNext();\r
+               }\r
+               \r
+               return $results;\r
+       }\r
+       \r
+       /**\r
+        * Synonym for GetArray() for compatibility with ADO.\r
+        *\r
+        * @param [nRows]  is the number of rows to return. -1 means every row.\r
+        *\r
+        * @return an array indexed by the rows (0-based) from the recordset\r
+        */\r
+       function &GetRows($nRows = -1) \r
+       {\r
+               return $this->GetArray($nRows);\r
+       }\r
+       \r
+       /**\r
+        * return whole recordset as a 2-dimensional associative array if there are more than 2 columns. \r
+        * The first column is treated as the key and is not included in the array. \r
+        * If there is only 2 columns, it will return a 1 dimensional array of key-value pairs unless\r
+        * $force_array == true.\r
+        *\r
+        * @param [force_array] has only meaning if we have 2 data columns. If false, a 1 dimensional\r
+        *      array is returned, otherwise a 2 dimensional array is returned. If this sounds confusing,\r
+        *      read the source.\r
+        *\r
+        * @return an associative array indexed by the first column of the array, \r
+        *      or false if the  data has less than 2 cols.\r
+        */\r
+       function &GetAssoc($force_array = false) {\r
+               $cols = $this->_numOfFields;\r
+               if ($cols < 2) {\r
+                       return false;\r
+               }\r
+               $results = array();\r
+               if ($cols > 2 || $force_array) {\r
+                       while (!$this->EOF) {\r
+                               $results[trim($this->fields[0])] = array_slice($this->fields, 1);\r
+                               $this->MoveNext();\r
+                       }\r
+               } else {\r
+                       // return scalar values\r
+                       while (!$this->EOF) {\r
+                       // some bug in mssql PHP 4.02 -- doesn't handle references properly so we FORCE creating a new string\r
+                               $val = ''.$this->fields[1]; \r
+                               $results[trim($this->fields[0])] = $val;\r
+                               $this->MoveNext();\r
+                       }\r
+               }\r
+               return $results; \r
+       }\r
+       \r
+       /**\r
+        *\r
+        * @param v     is the character timestamp in YYYY-MM-DD hh:mm:ss format\r
+        * @param fmt   is the format to apply to it, using date()\r
+        *\r
+        * @return a timestamp formated as user desires\r
+        */\r
+       function UserTimeStamp($v,$fmt='Y-m-d H:i:s')\r
+       {\r
+               $tt = $this->UnixTimeStamp($v);\r
+               // $tt == -1 if pre 1970\r
+               if (($tt === false || $tt == -1) && $v != false) return $v;\r
+               if ($tt == 0) return $this->emptyTimeStamp;\r
+               \r
+               return date($fmt,$tt);\r
+       }\r
+       \r
+       /**\r
+        * @param v     is the character date in YYYY-MM-DD format\r
+        * @param fmt   is the format to apply to it, using date()\r
+        *\r
+        * @return a date formated as user desires\r
+        */\r
+       function UserDate($v,$fmt='Y-m-d')\r
+       {\r
+               $tt = $this->UnixDate($v);\r
+               // $tt == -1 if pre 1970\r
+               if (($tt === false || $tt == -1) && $v != false) return $v;\r
+               else if ($tt == 0) return $this->emptyDate;\r
+               else if ($tt == -1) { // pre-1970\r
+               }\r
+               return date($fmt,$tt);\r
+       \r
+       }\r
+       \r
+       /**\r
+        * @param $v is a date string in YYYY-MM-DD format\r
+        *\r
+        * @return date in unix timestamp format, or 0 if before 1970, or false if invalid date format\r
+        */\r
+       function UnixDate($v)\r
+       {\r
+               if (!ereg( "([0-9]{4})[-/\.]?([0-9]{1,2})[-/\.]?([0-9]{1,2})", \r
+                       $v, $rr)) return false;\r
+                       \r
+               if ($rr[1] <= 1970) return 0;\r
+               // h-m-s-MM-DD-YY\r
+               return mktime(0,0,0,$rr[2],$rr[3],$rr[1]);\r
+       }\r
+       \r
+\r
+       \r
+       /**\r
+        * @param $v is a timestamp string in YYYY-MM-DD HH-NN-SS format\r
+        *\r
+        * @return date in unix timestamp format, or 0 if before 1970, or false if invalid date format\r
+        */\r
+       function UnixTimeStamp($v)\r
+       {\r
+               if (!ereg( "([0-9]{4})[-/\.]?([0-9]{1,2})[-/\.]?([0-9]{1,2})[ ]?([0-9]{1,2}):?([0-9]{1,2}):?([0-9]{1,2})", \r
+                       $v, $rr)) return false;\r
+               \r
+               if ($rr[1] <= 1970 && $rr[2]<= 1) return 0;\r
+               // h-m-s-MM-DD-YY\r
+               return  mktime($rr[4],$rr[5],$rr[6],$rr[2],$rr[3],$rr[1]);\r
+       }\r
+       \r
+       /**\r
+       * PEAR DB Compat - do not use internally\r
+       */\r
+       function Free()\r
+       {\r
+               return $this->Close();\r
+       }\r
+       \r
+       /**\r
+       * PEAR DB compat, number of rows\r
+       */\r
+       function NumRows()\r
+       {\r
+               return $this->_numOfRows;\r
+       }\r
+       \r
+       /**\r
+       * PEAR DB compat, number of cols\r
+       */\r
+       function NumCols()\r
+       {\r
+               return $this->_numOfCols;\r
+       }\r
+       \r
+       /**\r
+       * Fetch a row, returning false if no more rows. \r
+       * This is PEAR DB compat mode.\r
+       *\r
+       * @return false or array containing the current record\r
+       */\r
+       function &FetchRow()\r
+       {\r
+               if ($this->EOF) return false;\r
+               $arr = $this->fields;\r
+               $this->MoveNext();\r
+               return $arr;\r
+       }\r
+       \r
+       /**\r
+       * Fetch a row, returning PEAR_Error if no more rows. \r
+       * This is PEAR DB compat mode.\r
+       *\r
+       * @return false or array containing the current record\r
+       */\r
+       function FetchInto(&$arr)\r
+       {\r
+               if ($this->EOF) return new PEAR_Error('EOF',-1);;\r
+               $arr = $this->fields;\r
+               $this->MoveNext();\r
+               return 0; // DB_OK\r
+       }\r
+       \r
+       /**\r
+        * Move to the first row in the recordset. Many databases do NOT support this.\r
+        *\r
+        * @return true or false\r
+        */\r
+       function MoveFirst() \r
+       {\r
+               if ($this->_currentRow == 0) return true;\r
+               return $this->Move(0);                  \r
+       }                       \r
+\r
+       /**\r
+        * Move to the last row in the recordset. \r
+        *\r
+        * @return true or false\r
+        */\r
+       function MoveLast() \r
+       {\r
+               if ($this->_numOfRows >= 0) return $this->Move($this->_numOfRows-1);\r
+                while (!$this->EOF) $this->MoveNext();\r
+               return true;\r
+       }\r
+       \r
+       /**\r
+        * Move to next record in the recordset.\r
+        *\r
+        * @return true if there still rows available, or false if there are no more rows (EOF).\r
+        */\r
+       function MoveNext() \r
+       {\r
+               if (!$this->EOF) {\r
+                       $this->_currentRow++;\r
+                       if ($this->_fetch()) return true;\r
+               }\r
+               $this->EOF = true;\r
+               return false;\r
+       }       \r
+       \r
+       /**\r
+        * Random access to a specific row in the recordset. Some databases do not support\r
+        * access to previous rows in the databases (no scrolling backwards).\r
+        *\r
+        * @param rowNumber is the row to move to (0-based)\r
+        *\r
+        * @return true if there still rows available, or false if there are no more rows (EOF).\r
+        */\r
+       function Move($rowNumber = 0) \r
+       {\r
+               if ($rowNumber == $this->_currentRow) return true;\r
+               if ($rowNumber > $this->_numOfRows)\r
+                       if ($this->_numOfRows != -1) $rowNumber = $this->_numOfRows-1;\r
+   \r
+        if ($this->canSeek) {\r
+               if ($this->_seek($rowNumber)) {\r
+                               $this->_currentRow = $rowNumber;\r
+                               if ($this->_fetch()) {\r
+                                       $this->EOF = false;     \r
+                                   //  $this->_currentRow += 1;                        \r
+                                       return true;\r
+                               }\r
+                       } else \r
+                               return false;\r
+        } else {\r
+            if ($rowNumber < $this->_currentRow) return false;\r
+            while (! $this->EOF && $this->_currentRow < $rowNumber) {\r
+                               $this->_currentRow++;\r
+                if (!$this->_fetch()) $this->EOF = true;\r
+                       }\r
+            return !($this->EOF);\r
+        }\r
+               \r
+               $this->fields = null;   \r
+               $this->EOF = true;\r
+               return false;\r
+       }\r
+               \r
+       /**\r
+        * Get the value of a field in the current row by column name.\r
+        * Will not work if ADODB_FETCH_MODE is set to ADODB_FETCH_NUM.\r
+        * \r
+        * @param colname  is the field to access\r
+        *\r
+        * @return the value of $colname column\r
+        */\r
+       function Fields($colname)\r
+       {\r
+               return $this->fields[$colname];\r
+       }\r
+       \r
+  /**\r
+   * Use associative array to get fields array for databases that do not support\r
+   * associative arrays. Submitted by Paolo S. Asioli paolo.asioli@libero.it\r
+   *\r
+   * If you don't want uppercase cols, set $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC\r
+   * before you execute your SQL statement, and access $rs->fields['col'] directly.\r
+   */\r
+       function &GetRowAssoc($upper=true)\r
+       {\r
+        \r
+               if (!$this->bind) {\r
+                       $this->bind = array();\r
+                       for ($i=0; $i < $this->_numOfFields; $i++) {\r
+                               $o = $this->FetchField($i);\r
+                               $this->bind[($upper) ? strtoupper($o->name) : $o->name] = $i;\r
+                       }\r
+               }\r
+               \r
+               $record = array();\r
+               foreach($this->bind as $k => $v) {\r
+            $record[$k] = $this->fields[$v];\r
+        }\r
+\r
+        return $record;\r
+    }\r
+       \r
+       /**\r
+        * Clean up \r
+        *\r
+        * @return true or false\r
+        */\r
+       function Close() \r
+       {\r
+               if (!$this->_closed) {\r
+                       $this->_closed = true;\r
+                       return $this->_close();         \r
+               } else\r
+                       return true;\r
+       }\r
+       \r
+       /**\r
+        * synonyms RecordCount and RowCount    \r
+        *\r
+        * @return the number of rows or -1 if this is not supported\r
+        */\r
+       function RecordCount() {return $this->_numOfRows;}\r
+       \r
+       /**\r
+        * synonyms RecordCount and RowCount    \r
+        *\r
+        * @return the number of rows or -1 if this is not supported\r
+        */\r
+       function RowCount() {return $this->_numOfRows;} \r
+       \r
+       \r
+       /**\r
+        * @return the current row in the recordset. If at EOF, will return the last row. 0-based.\r
+        */\r
+       function CurrentRow() {return $this->_currentRow;}\r
+       \r
+       /**\r
+        * synonym for CurrentRow -- for ADO compat\r
+        *\r
+        * @return the current row in the recordset. If at EOF, will return the last row. 0-based.\r
+        */\r
+       function AbsolutePosition() {return $this->_currentRow;}\r
+       \r
+       /**\r
+        * @return the number of columns in the recordset. Some databases will set this to 0\r
+        * if no records are returned, others will return the number of columns in the query.\r
+        */\r
+       function FieldCount() {return $this->_numOfFields;}   \r
+\r
+\r
+       /**\r
+        * Get the ADOFieldObject of a specific column.\r
+        *\r
+        * @param fieldoffset   is the column position to access(0-based).\r
+        *\r
+        * @return the ADOFieldObject for that column, or false.\r
+        */\r
+       function &FetchField($fieldoffset) \r
+       {\r
+               // must be defined by child class\r
+       }       \r
+       \r
+       /**\r
+       * Return the fields array of the current row as an object for convenience.\r
+       * \r
+       * @param $isupper to set the object property names to uppercase\r
+       *\r
+       * @return the object with the properties set to the fields of the current row\r
+       */\r
+       function &FetchObject($isupper=true)\r
+       {\r
+               if (empty($this->_obj)) {\r
+                       $this->_obj = new ADOFetchObj();\r
+                       $this->_names = array();\r
+                       for ($i=0; $i <$this->_numOfFields; $i++) {\r
+                               $f = $this->FetchField($i);\r
+                               $this->_names[] = $f->name;\r
+                       }\r
+               }\r
+               $i = 0;\r
+               $o = &$this->_obj;\r
+               for ($i=0; $i <$this->_numOfFields; $i++) {\r
+                       $name = $this->_names[$i];\r
+                       if ($isupper) $n = strtoupper($name);\r
+                       else $n = $name;\r
+                       \r
+                       $o->$n = $this->Fields($name);\r
+               }\r
+               return $o;\r
+       }\r
+       /**\r
+       * Return the fields array of the current row as an object for convenience.\r
+       * \r
+       * @param $isupper to set the object property names to uppercase\r
+       *\r
+       * @return the object with the properties set to the fields of the current row,\r
+       *       or false if EOF\r
+       *\r
+       * Fixed bug reported by tim@orotech.net\r
+       */\r
+       function &FetchNextObject($isupper=true)\r
+       {\r
+               $o = false;\r
+               if ($this->_numOfRows != 0 && !$this->EOF) {\r
+                       $o = $this->FetchObject($isupper);      \r
+                       $this->_currentRow++;\r
+                       if ($this->_fetch()) return $o;\r
+               }\r
+               $this->EOF = true;\r
+               return $o;\r
+       }\r
+       \r
+       /**\r
+        * Get the metatype of the column. This is used for formatting. This is because\r
+        * many databases use different names for the same type, so we transform the original\r
+        * type to our standardised version which uses 1 character codes:\r
+        *\r
+        * @param t  is the type passed in. Normally is ADOFieldObject->type.\r
+        * @param len is the maximum length of that field. This is because we treat character\r
+        *      fields bigger than a certain size as a 'B' (blob).\r
+        * @param fieldobj is the field object returned by the database driver. Can hold\r
+        *      additional info (eg. primary_key for mysql).\r
+        * \r
+        * @return the general type of the data: \r
+        *      C for character < 200 chars\r
+        *      X for teXt (>= 200 chars)\r
+        *      B for Binary\r
+        *      N for numeric floating point\r
+        *      D for date\r
+        *      T for timestamp\r
+        *      L for logical/Boolean\r
+        *      I for integer\r
+        *      R for autoincrement counter/integer\r
+        * \r
+        *\r
+       */\r
+       function MetaType($t,$len=-1,$fieldobj=false)\r
+       {\r
+               switch (strtoupper($t)) {\r
+               case 'VARCHAR':\r
+               case 'VARCHAR2':\r
+               case 'CHAR':\r
+               case 'STRING':\r
+               case 'C':\r
+               case 'NCHAR':\r
+               case 'NVARCHAR':\r
+               case 'VARYING':\r
+               case 'BPCHAR':\r
+                       if (!empty($this)) if ($len <= $this->blobSize) return 'C';\r
+                       else if ($len <= 250) return 'C';\r
+               \r
+               case 'LONGCHAR':\r
+               case 'TEXT':\r
+               case 'M':\r
+               case 'X':\r
+               case 'CLOB':\r
+               case 'LONG':\r
+                       return 'X';\r
+               \r
+               case 'BLOB':\r
+               case 'NTEXT':\r
+               case 'BINARY':\r
+               case 'VARBINARY':\r
+               case 'LONGBINARY':\r
+               case 'B':\r
+                       return 'B';\r
+                       \r
+               case 'DATE':\r
+               case 'D':\r
+                       return 'D';\r
+               \r
+               \r
+               case 'TIME':\r
+               case 'TIMESTAMP':\r
+               case 'DATETIME':\r
+               case 'T':\r
+                       return 'T';\r
+               \r
+               case 'BOOLEAN': \r
+               case 'BIT':\r
+               case 'L':\r
+                       return 'L';\r
+                       \r
+               case 'COUNTER':\r
+               case 'R':\r
+                       return 'R';\r
+                       \r
+               case 'INT':\r
+               case 'INTEGER':\r
+               case 'SHORT':\r
+               case 'TINYINT':\r
+               case 'SMALLINT':\r
+               case 'I':\r
+                       if (!empty($fieldobj->primary_key)) return 'R';\r
+                       return 'I';\r
+                       \r
+               default: return 'N';\r
+               }\r
+       }\r
+       \r
+       function _close() {}\r
+       \r
+       /**\r
+        * set/returns the current recordset page when paginating\r
+        */\r
+       function AbsolutePage($page=-1)\r
+       {\r
+               if ($page != -1) $this->_currentPage = $page;\r
+               return $this->_currentPage;\r
+       }\r
+       \r
+       /**\r
+        * set/returns the status of the atFirstPage flag when paginating\r
+        */\r
+       function AtFirstPage($status=false)\r
+       {\r
+               if ($status != false) $this->_atFirstPage = $status;\r
+               return $this->_atFirstPage;\r
+       }\r
+       \r
+       /**\r
+        * set/returns the status of the atLastPage flag when paginating\r
+        */\r
+       function AtLastPage($status=false)\r
+       {\r
+               if ($status != false) $this->_atLastPage = $status;\r
+               return $this->_atLastPage;\r
+       }\r
+} // end class ADORecordSet\r
+       \r
+       //==============================================================================================        \r
+       \r
+       /**\r
+        * This class encapsulates the concept of a recordset created in memory\r
+        * as an array. This is useful for the creation of cached recordsets.\r
+        * \r
+        * Note that the constructor is different from the standard.\r
+        */\r
+       \r
+       class ADORecordSet_array extends ADORecordSet\r
+       {\r
+               var $databaseType = "array";\r
+       \r
+               var $_array;    // holds the 2-dimensional data array\r
+               var $_types;    // the array of types of each column (C B I L M)\r
+               var $_colnames; // names of each column in array\r
+               var $_skiprow1; // skip 1st row because it holds column names\r
+               var $_fieldarr; // holds array of field objects\r
+               var $canSeek = true;\r
+               var $affectedrows = false;\r
+               var $insertid = false;\r
+               var $sql = '';\r
+               /**\r
+                * Constructor\r
+                *\r
+                */\r
+               function ADORecordSet_array($fakeid=1)\r
+               {\r
+                       $this->ADORecordSet($fakeid); // fake queryID\r
+               }\r
+               \r
+               \r
+               /**\r
+                * Setup the Array. Later we will have XML-Data and CSV handlers\r
+                *\r
+                * @param array         is a 2-dimensional array holding the data.\r
+                *                      The first row should hold the column names \r
+                *                      unless paramter $colnames is used.\r
+                * @param typearr       holds an array of types. These are the same types \r
+                *                      used in MetaTypes (C,B,L,I,N).\r
+                * @param [colnames]    array of column names. If set, then the first row of\r
+                *                      $array should not hold the column names.\r
+                */\r
+               function InitArray(&$array,$typearr,$colnames=false)\r
+               {\r
+                       $this->_array = $array;\r
+                       $this->_types = &$typearr;      \r
+                       if ($colnames) {\r
+                               $this->_skiprow1 = false;\r
+                               $this->_colnames = $colnames;\r
+                       } else $this->_colnames = $array[0];\r
+                       \r
+                       $this->Init();\r
+               }\r
+               /**\r
+                * Setup the Array and datatype file objects\r
+                *\r
+                * @param array         is a 2-dimensional array holding the data.\r
+                *                      The first row should hold the column names \r
+                *                      unless paramter $colnames is used.\r
+                * @param fieldarr      holds an array of ADOFieldObject's.\r
+                */\r
+               function InitArrayFields(&$array,&$fieldarr)\r
+               {\r
+                       $this->_array = &$array;\r
+                       $this->_skiprow1= false;\r
+                       if ($fieldarr) {\r
+                               $this->_fieldobjects = &$fieldarr;\r
+                       } \r
+                       \r
+                       $this->Init();\r
+               }\r
+               \r
+               function _initrs()\r
+               {\r
+                       $this->_numOfRows =  sizeof($this->_array);\r
+                       if ($this->_skiprow1) $this->_numOfRows -= 1;\r
+               \r
+                       $this->_numOfFields =(isset($this->_fieldobjects)) ?\r
+                                sizeof($this->_fieldobjects):sizeof($this->_types);\r
+               }\r
+               \r
+               /* Use associative array to get fields array */\r
+               function Fields($colname)\r
+               {\r
+                       if (!$this->bind) {\r
+                               $this->bind = array();\r
+                               for ($i=0; $i < $this->_numOfFields; $i++) {\r
+                                       $o = $this->FetchField($i);\r
+                                       $this->bind[strtoupper($o->name)] = $i;\r
+                               }\r
+                       }\r
+                       \r
+                        return $this->fields[$this->bind[strtoupper($colname)]];\r
+               }\r
+               \r
+               function &FetchField($fieldOffset = -1) \r
+               {\r
+                       if (isset($this->_fieldobjects)) {\r
+                               return $this->_fieldobjects[$fieldOffset];\r
+                       }\r
+                       $o =  new ADOFieldObject();\r
+                       $o->name = $this->_colnames[$fieldOffset];\r
+                       $o->type =  $this->_types[$fieldOffset];\r
+                       $o->max_length = -1; // length not known\r
+                       \r
+                       return $o;\r
+               }\r
+                       \r
+               function _seek($row)\r
+               {\r
+                       return true;\r
+               }\r
+               \r
+               function _fetch()\r
+               {\r
+                       $pos = $this->_currentRow;\r
+                       \r
+                       if ($this->_skiprow1) {\r
+                               if ($this->_numOfRows <= $pos-1) return false;\r
+                               $pos += 1;\r
+                       } else {\r
+                               if ($this->_numOfRows <= $pos) return false;\r
+                       }\r
+                       \r
+                       $this->fields = $this->_array[$pos];\r
+                       return true;\r
+               }\r
+               \r
+               function _close() \r
+               {\r
+                       return true;    \r
+               }\r
+               \r
+               \r
+       \r
+       } // ADORecordSet_array\r
+\r
+       //==============================================================================================        \r
+       // HELPER FUNCTIONS\r
+       //==============================================================================================                        \r
+       \r
+    /**\r
+        * Synonym for ADOLoadCode.\r
+        *\r
+        * @deprecated\r
+        */\r
+       function ADOLoadDB($dbType) { return ADOLoadCode($dbType);}\r
+        \r
+    /**\r
+        * Load the code for a specific database driver\r
+        */\r
+    function ADOLoadCode($dbType) \r
+       {\r
+       GLOBAL $ADODB_Database;\r
+       \r
+               if (!$dbType) return false;\r
+               $ADODB_Database = strtolower($dbType);\r
+               switch ($ADODB_Database) {\r
+                       case 'maxsql': $ADODB_Database = 'mysqlt'; break;\r
+                       case 'pgsql': $ADODB_Database = 'postgres7'; break;\r
+               }\r
+               include_once(ADODB_DIR."/adodb-$ADODB_Database.inc.php");               \r
+               return true;            \r
+       }\r
+\r
+       /**\r
+        * synonym for ADONewConnection for people who cannot remember the correct name\r
+        */\r
+       function &NewADOConnection($db='')\r
+       {\r
+               return ADONewConnection($db);\r
+       }\r
+       \r
+       /**\r
+        * Instantiate a new Connection class for a specific database driver.\r
+        *\r
+        * @param [db]  is the database Connection object to create. If undefined,\r
+        *      use the last database driver that was loaded by ADOLoadCode().\r
+        *\r
+        * @return the freshly created instance of the Connection class.\r
+        */\r
+       function &ADONewConnection($db='')\r
+       {\r
+       GLOBAL $ADODB_Database;\r
+       \r
+               if ($db) {\r
+                       if ($ADODB_Database != $db) ADOLoadCode($db);\r
+               } else { \r
+                       if (!empty($ADODB_Database)) $db = $ADODB_Database;\r
+                       else print "<p>ADONewConnection: No database driver defined</p>";\r
+               }\r
+               \r
+               $cls = 'ADODB_'.$db;\r
+               $obj = new $cls();\r
+               if (defined('ADODB_ERROR_HANDLER')) {\r
+                       $obj->raiseErrorFn = ADODB_ERROR_HANDLER;\r
+               }\r
+               return $obj;\r
+       }\r
+       \r
+       /* High speed rs2csv 10% faster */\r
+       function & xrs2csv(&$rs)\r
+       {\r
+               return time()."\n".serialize($rs);\r
+       }\r
+       function & xcsv2rs($url,&$err,$timeout)\r
+       {\r
+               $t = filemtime($url);// this is cached - should we clearstatcache() ?\r
+               if ($t === false) {\r
+                       $err = 'File not found 1';\r
+                       return false;\r
+               }\r
+               \r
+               if (time() > $t + $timeout){\r
+                       $err = " Timeout 1";\r
+                       return false;\r
+               }\r
+               \r
+               $fp = @fopen($url,'r');\r
+               if (!$fp) {\r
+                       $err = ' file not found ';\r
+                       return false;\r
+               }\r
+               \r
+               flock($fp,LOCK_SH);\r
+               $t = fgets($fp,100);\r
+               if ($t === false){\r
+                       fclose($fp);\r
+                       $err =  " EOF 1 ";\r
+                       return false;\r
+               }\r
+               /*\r
+               if (time() > ((integer)$t) + $timeout){\r
+                       fclose($fp);\r
+                       $err = " Timeout 2";\r
+                       return false;\r
+               }*/\r
+               \r
+               $txt = &fread($fp,1999999); // Increase if EOF 2 error returned\r
+               fclose($fp);\r
+               $o = @unserialize($txt);\r
+               if (!is_object($o)) {\r
+                       $err = " EOF 2";\r
+                       return false;\r
+               }\r
+               $o->timeCreated = $t;\r
+               return $o;\r
+       }\r
+       \r
+       /**\r
+        * convert a recordset into CSV format\r
+        *\r
+        * @param rs    the recordset\r
+        *\r
+        * @return      the CSV formated data\r
+        */\r
+       function &rs2csv(&$rs,$conn=false,$sql='')\r
+       {\r
+               $max =  $rs->FieldCount();\r
+               if ($sql) $sql = urlencode($sql);\r
+               // metadata setup\r
+               \r
+               if ($max <= 0 || $rs->EOF) { // no data returned\r
+                       if (is_object($conn)) {\r
+                               $sql .= ','.$conn->Affected_Rows();\r
+                               $sql .= ','.$conn->Insert_ID();\r
+                       } else\r
+                               $sql .= ',,';\r
+                       \r
+                       $text = "====-1,0,$sql\n";\r
+                       return $text;\r
+               } else {\r
+                       $tt = ($rs->timeCreated) ? $rs->timeCreated : time();\r
+                       $line = "====0,$tt,$sql\n";\r
+               }\r
+               // column definitions\r
+               for($i=0; $i < $max; $i++) {\r
+                       $o = $rs->FetchField($i);\r
+                       $line .= urlencode($o->name).':'.$rs->MetaType($o->type,$o->max_length).":$o->max_length,";\r
+               }\r
+               $text = substr($line,0,strlen($line)-1)."\n";\r
+               \r
+               \r
+               // get data\r
+               if ($rs->databaseType == 'array') {\r
+                       $text .= serialize($rs->_array);\r
+               } else {\r
+                       $rows = array();\r
+                       while (!$rs->EOF) {     \r
+                               $rows[] = $rs->fields;\r
+                               $rs->MoveNext();\r
+                       } \r
+                       $text .= serialize($rows);\r
+               }\r
+               $rs->MoveFirst();\r
+               return $text;\r
+       }\r
+\r
+       \r
+/**\r
+* Open CSV file and convert it into Data. \r
+*\r
+* @param url           file/ftp/http url\r
+* @param err           returns the error message\r
+* @param timeout       dispose if recordset has been alive for $timeout secs\r
+*\r
+* @return              recordset, or false if error occured. If no\r
+*                      error occurred in sql INSERT/UPDATE/DELETE, \r
+*                      empty recordset is returned\r
+*/\r
+       function &csv2rs($url,&$err,$timeout=0)\r
+       {\r
+               $fp = @fopen($url,'r');\r
+               $err = false;\r
+               if (!$fp) {\r
+                       $err = $url.'file/URL not found';\r
+                       return false;\r
+               }\r
+               flock($fp, LOCK_SH);\r
+               $arr = array();\r
+               $ttl = 0;\r
+               \r
+               if ($meta = fgetcsv ($fp, 8192, ",")) {\r
+                       // check if error message\r
+                       if (substr($meta[0],0,4) === '****') {\r
+                               $err = trim(substr($meta[0],4,1024));\r
+                               fclose($fp);\r
+                               return false;\r
+                       }\r
+                       // check for meta data\r
+                       // $meta[0] is -1 means return an empty recordset\r
+                       // $meta[1] contains a time \r
+       \r
+                       if (substr($meta[0],0,4) ===  '====') {\r
+                       \r
+                               if ($meta[0] == "====-1") {\r
+                                       if (sizeof($meta) < 5) {\r
+                                               $err = "Corrupt first line for format -1";\r
+                                               fclose($fp);\r
+                                               return false;\r
+                                       }\r
+                                       fclose($fp);\r
+                                       \r
+                                       if ($timeout > 0) {\r
+                                               $err = ' Timeout for insert/update/delete illegal';\r
+                                               return false;\r
+                                       }\r
+                                       $val = 1;\r
+                                       $rs = new ADORecordSet($val);\r
+                                       $rs->EOF = true;\r
+                                       $rs->_numOfFields=0;\r
+                                       $rs->sql = urldecode($meta[2]);\r
+                                       $rs->affectedrows = (integer)$meta[3];\r
+                                       $rs->insertid = $meta[4];       \r
+                                       $rs->aa = '100';\r
+                                       return $rs;\r
+                               }\r
+                       # Under high volume loads, we want only 1 thread/process to _write_file\r
+                       # so that we don't have 50 processes queueing to write the same data.\r
+                       # Would require probabilistic blocking write \r
+                       #\r
+                       # -2 sec before timeout, give processes 1/16 chance of writing to file with blocking io\r
+                       # -1 sec after timeout give processes 1/4 chance of writing with blocking\r
+                       # +0 sec after timeout, give processes 100% chance writing with blocking\r
+                               if (sizeof($meta) > 1) {\r
+                                       if($timeout >0){ \r
+                                               $tdiff = $meta[1]+$timeout - time();\r
+                                               if ($tdiff <= 2) {\r
+                                                       switch($tdiff) {\r
+                                                       case 2: \r
+                                                               if ((rand() & 15) == 0) {\r
+                                                                       fclose($fp);\r
+                                                                       $err = "Timeout 2";\r
+                                                                       return false;\r
+                                                               }\r
+                                                               break;\r
+                                                       case 1:\r
+                                                               if ((rand() & 3) == 0) {\r
+                                                                       fclose($fp);\r
+                                                                       $err = "Timeout 1";\r
+                                                                       return false;\r
+                                                               }\r
+                                                               break;\r
+                                                       default: \r
+                                                               fclose($fp);\r
+                                                               $err = "Timeout 0";\r
+                                                               return false;\r
+                                                       } // switch\r
+                                                       \r
+                                               } // if check flush cache\r
+                                       }// (timeout>0)\r
+                                       $ttl = $meta[1];\r
+                               }\r
+                               $meta = fgetcsv($fp, 8192, ",");\r
+                               if (!$meta) {\r
+                                       fclose($fp);\r
+                                       $err = "Unexpected EOF 1";\r
+                                       return false;\r
+                               }\r
+                       }\r
+\r
+                       // Get Column definitions\r
+                       $flds = array();\r
+                       foreach($meta as $o) {\r
+                               $o2 = explode(':',$o);\r
+                               if (sizeof($o2)!=3) {\r
+                                       $arr[] = $meta;\r
+                                       $flds = false;\r
+                                       break;\r
+                               }\r
+                               $fld = new ADOFieldObject();\r
+                               $fld->name = urldecode($o2[0]);\r
+                               $fld->type = $o2[1];\r
+                               $fld->max_length = $o2[2];\r
+                               $flds[] = $fld;\r
+                       }\r
+               } else {\r
+                       fclose($fp);\r
+                       $err = "Recordset had unexpected EOF 2";\r
+                       //print "$url ";print_r($meta);\r
+                       //die();\r
+                       return false;\r
+               }\r
+               \r
+               // slurp in the data\r
+               $text = fread($fp,1999999);\r
+               fclose($fp);\r
+               //$text = substr($text,0,44);\r
+               $arr = @unserialize($text);\r
+               \r
+               //var_dump($arr);\r
+               if (!is_array($arr)) {\r
+                       $err = "Recordset had unexpected EOF 3";\r
+                       return false;\r
+               }\r
+               $rs = new ADORecordSet_array();\r
+               $rs->timeCreated = $ttl;\r
+               $rs->InitArrayFields($arr,$flds);\r
+               return $rs;\r
+       }\r
+\r
+       function adodb_write_file($filename, $contents,$debug=false)\r
+       { \r
+       # http://www.php.net/bugs.php?id=9203 Bug that flock fails on Windows\r
+       # So to simulate locking, we assume that rename is an atomic operation.\r
+       # First we delete $filename, then we create a $tempfile write to it and \r
+       # rename to the desired $filename. If the rename works, then we successfully \r
+       # modified the file exclusively.\r
+       # What a stupid need - having to simulate locking.\r
+       # Risks:\r
+       # 1. $tempfile name is not unique -- very very low\r
+       # 2. unlink($filename) fails -- ok, rename will fail\r
+       # 3. adodb reads stale file because unlink fails -- ok, $rs timeout occurs\r
+       # 4. another process creates $filename between unlink() and rename() -- ok, rename() fails and  cache updated\r
+               if (strpos(strtoupper(PHP_OS),'WIN') !== false) {\r
+                       // skip the decimal place\r
+                       $mtime = substr(str_replace(' ','_',microtime()),2); \r
+                       // unlink will let some latencies develop, so uniqid() is more random\r
+                       @unlink($filename);\r
+                       // getmypid() actually returns 0 on Win98 - never mind!\r
+                       $tmpname = $filename.uniqid($mtime).getmypid();\r
+                       if (!($fd = fopen($tmpname,'a'))) return false;\r
+                       $ok = ftruncate($fd,0);                 \r
+                       if (!fwrite($fd,$contents)) $ok = false;\r
+                       fclose($fd);\r
+                       chmod($tmpname,0644);\r
+                       if (!@rename($tmpname,$filename)) {\r
+                               unlink($tmpname);\r
+                               $ok = false;\r
+                       }\r
+                       if ($debug && !$ok) print " Rename $tmpname ".($ok? 'ok' : 'failed')." <br>";\r
+                       return $ok;\r
+               }\r
+               if (!($fd = fopen($filename, 'a'))) return false;\r
+               if (flock($fd, LOCK_EX) && ftruncate($fd, 0)) {\r
+                       $ok = fwrite( $fd, $contents );\r
+                       fclose($fd);\r
+                       chmod($filename,0644);\r
+               }else {\r
+                       fclose($fd);\r
+                       if ($debug)print " Failed acquiring lock for $filename<br>";\r
+                       $ok = false;\r
+               }\r
+       \r
+               return $ok;\r
+       }\r
+               \r
+               \r
+\r
+\r
+} // defined\r
+?>
\ No newline at end of file
diff --git a/libraries/adodb/adodb.png b/libraries/adodb/adodb.png
new file mode 100755 (executable)
index 0000000..ad92e09
Binary files /dev/null and b/libraries/adodb/adodb.png differ
diff --git a/libraries/adodb/benchmark.php b/libraries/adodb/benchmark.php
new file mode 100755 (executable)
index 0000000..8c11e16
--- /dev/null
@@ -0,0 +1,78 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">\r
+\r
+<html>\r
+<head>\r
+       <title>ADODB Benchmarks</title>\r
+</head> \r
+\r
+<body>\r
+<?php \r
+/*\r
+V1.53 13 Nov 2001 (c) 2000, 2001 John Lim (jlim@natsoft.com.my). All rights reserved.\r
+  Released under both BSD license and Lesser GPL library license. \r
+  Whenever there is any discrepancy between the two licenses, \r
+  the BSD license will take precedence.\r
+  \r
+  Benchmark code to test the speed to the ADODB library with different databases.\r
+  This is a simplistic benchmark to be used as the basis for further testing.\r
+  It should not be used as proof of the superiority of one database over the other.\r
+*/ \r
\r
+$testmssql = true;\r
+$testvfp = true;\r
+$testoracle = false;\r
+$testado = true; \r
+$testibase = true;\r
+$testaccess = true;\r
+$testmysql = true;\r
+\r
+set_time_limit(240); // increase timeout\r
+\r
+include("tohtml.inc.php");\r
+include("adodb.inc.php");\r
+\r
+function testdb(&$db,$createtab="create table ADOXYZ (id int, firstname char(24), lastname char(24), created date)")\r
+{\r
+GLOBAL $ADODB_version;\r
+\r
+\r
+       $max = 10;\r
+       $sql = 'select * from ADOXYZ';\r
+       \r
+       print "<h3>ADODB Version: $ADODB_version Host: <i>$db->host</i> &nbsp; Database: <i>$db->database</i></h3>";\r
+\r
+       // perform query once to cache results so we are only testing throughput \r
+       $rs = $db->Execute($sql);       \r
+       $arr = $rs->GetArray();\r
+       //$db->debug = true;\r
+\r
+       $start = microtime();\r
+       for ($i=0; $i < $max; $i++) {\r
+               $rs = $db->Execute($sql);       \r
+               $arr = &$rs->GetArray();\r
+//                print $arr[0][1];\r
+       }\r
+       $end =  microtime();\r
+       \r
+       $start = explode(' ',$start);\r
+       $end = explode(' ',$end);\r
+       print_r($start);\r
+       print_r($end);\r
+      //  print_r($arr);\r
+       $total = $end[0]+trim($end[1]) - $start[0]-trim($start[1]);\r
+       printf ("<p>seconds = %8.2f for %d iterations each with %d records</p>",$total,$max, sizeof($arr));\r
+\r
+?>\r
+       </p>\r
+       <table width=100% ><tr><td bgcolor=beige>&nbsp;</td></tr></table>\r
+       </p>\r
+<?php\r
+        $db->Close();\r
+}\r
+include("testdatabases.inc.php");\r
+AD\r
+?>\r
+\r
+\r
+</body>\r
+</html>\r
diff --git a/libraries/adodb/client.php b/libraries/adodb/client.php
new file mode 100755 (executable)
index 0000000..1b4e1fa
--- /dev/null
@@ -0,0 +1,194 @@
+<html>\r
+<body bgcolor=white>\r
+<?php\r
+/** \r
+ * (c)2001 John Lim (jlim@natsoft.com.my). All rights reserved.\r
+ * Released under both BSD license and Lesser GPL library license. \r
+  Whenever there is any discrepancy between the two licenses, \r
+  the BSD license will take precedence. \r
+ * \r
+ * set tabs to 8\r
+ */\r
\r
+ // documentation on usage is at http://php.weblogs.com/adodb_csv\r
\r
+include('./adodb.inc.php');\r
+include('./tohtml.inc.php');\r
+\r
+ function &send2server($url,$sql)\r
+ {\r
+       $url .= '?sql='.urlencode($sql);\r
+       print "<p>$url</p>";\r
+       $rs = csv2rs($url,$err);\r
+       if ($err) print $err;\r
+       return $rs;\r
+ }\r
\r
+ function print_pre($s)\r
+ {\r
+       print "<pre>";print_r($s);print "</pre>";\r
+ }\r
+\r
+\r
+$serverURL = 'http://localhost/php/adodb/server.php';\r
+$testhttp = false;\r
+\r
+$sql1 = "insertz into products (productname) values ('testprod 1')";\r
+$sql2 = "insert into products (productname) values ('testprod 1')";\r
+$sql3 = "insert into products (productname) values ('testprod 2')";\r
+$sql4 = "delete from products where productid>80";\r
+$sql5 = 'select * from products';\r
+       \r
+if ($testhttp) {\r
+       print "<a href=#c>Client Driver Tests</a><p>";\r
+       print "<h3>Test Error</h3>";\r
+       $rs = send2server($serverURL,$sql1);\r
+       print_pre($rs);\r
+       print "<hr>";\r
+       \r
+       print "<h3>Test Insert</h3>";\r
+       \r
+       $rs = send2server($serverURL,$sql2);\r
+       print_pre($rs);\r
+       print "<hr>";\r
+       \r
+       print "<h3>Test Insert2</h3>";\r
+       \r
+       $rs = send2server($serverURL,$sql3);\r
+       print_pre($rs);\r
+       print "<hr>";\r
+       \r
+       print "<h3>Test Delete</h3>";\r
+       \r
+       $rs = send2server($serverURL,$sql4);\r
+       print_pre($rs);\r
+       print "<hr>";\r
+       \r
+       \r
+       print "<h3>Test Select</h3>";\r
+       $rs = send2server($serverURL,$sql5);\r
+       if ($rs) rs2html($rs);\r
+       \r
+       print "<hr>";\r
+}\r
+\r
+\r
+print "<a name=c><h1>CLIENT Driver Tests</h1>";\r
+$conn = ADONewConnection('csv');\r
+$conn->Connect($serverURL);\r
+$conn->debug = true;\r
+\r
+print "<h3>Bad SQL</h3>";\r
+\r
+$rs = $conn->Execute($sql1);\r
+\r
+print "<h3>Insert SQL 1</h3>";\r
+$rs = $conn->Execute($sql2);\r
+\r
+print "<h3>Insert SQL 2</h3>";\r
+$rs = $conn->Execute($sql3);\r
+\r
+print "<h3>Select SQL</h3>";\r
+$rs = $conn->Execute($sql5);\r
+if ($rs) rs2html($rs);\r
+\r
+print "<h3>Delete SQL</h3>";\r
+$rs = $conn->Execute($sql4);\r
+\r
+print "<h3>Select SQL</h3>";\r
+$rs = $conn->Execute($sql5);\r
+if ($rs) rs2html($rs);\r
+\r
+\r
+/* EXPECTED RESULTS FOR HTTP TEST:\r
+\r
+Test Insert\r
+http://localhost/php/adodb/server.php?sql=insert+into+products+%28productname%29+values+%28%27testprod%27%29\r
+\r
+adorecordset Object\r
+(\r
+    [dataProvider] => native\r
+    [fields] => \r
+    [blobSize] => 64\r
+    [canSeek] => \r
+    [EOF] => 1\r
+    [emptyTimeStamp] =>  \r
+    [emptyDate] =>  \r
+    [debug] => \r
+    [timeToLive] => 0\r
+    [bind] => \r
+    [_numOfRows] => -1\r
+    [_numOfFields] => 0\r
+    [_queryID] => 1\r
+    [_currentRow] => -1\r
+    [_closed] => \r
+    [_inited] => \r
+    [sql] => insert into products (productname) values ('testprod')\r
+    [affectedrows] => 1\r
+    [insertid] => 81\r
+)\r
+\r
+\r
+--------------------------------------------------------------------------------\r
+\r
+Test Insert2\r
+http://localhost/php/adodb/server.php?sql=insert+into+products+%28productname%29+values+%28%27testprod%27%29\r
+\r
+adorecordset Object\r
+(\r
+    [dataProvider] => native\r
+    [fields] => \r
+    [blobSize] => 64\r
+    [canSeek] => \r
+    [EOF] => 1\r
+    [emptyTimeStamp] =>  \r
+    [emptyDate] =>  \r
+    [debug] => \r
+    [timeToLive] => 0\r
+    [bind] => \r
+    [_numOfRows] => -1\r
+    [_numOfFields] => 0\r
+    [_queryID] => 1\r
+    [_currentRow] => -1\r
+    [_closed] => \r
+    [_inited] => \r
+    [sql] => insert into products (productname) values ('testprod')\r
+    [affectedrows] => 1\r
+    [insertid] => 82\r
+)\r
+\r
+\r
+--------------------------------------------------------------------------------\r
+\r
+Test Delete\r
+http://localhost/php/adodb/server.php?sql=delete+from+products+where+productid%3E80\r
+\r
+adorecordset Object\r
+(\r
+    [dataProvider] => native\r
+    [fields] => \r
+    [blobSize] => 64\r
+    [canSeek] => \r
+    [EOF] => 1\r
+    [emptyTimeStamp] =>  \r
+    [emptyDate] =>  \r
+    [debug] => \r
+    [timeToLive] => 0\r
+    [bind] => \r
+    [_numOfRows] => -1\r
+    [_numOfFields] => 0\r
+    [_queryID] => 1\r
+    [_currentRow] => -1\r
+    [_closed] => \r
+    [_inited] => \r
+    [sql] => delete from products where productid>80\r
+    [affectedrows] => 2\r
+    [insertid] => 0\r
+)\r
+\r
+[more stuff deleted]\r
+ .\r
+ . \r
+ .\r
+*/\r
+?>\r
diff --git a/libraries/adodb/crypt.inc.php b/libraries/adodb/crypt.inc.php
new file mode 100755 (executable)
index 0000000..d936811
--- /dev/null
@@ -0,0 +1,60 @@
+<?php\r
+class MD5Crypt{\r
+        function keyED($txt,$encrypt_key){\r
+                $encrypt_key = md5($encrypt_key);\r
+                $ctr=0;\r
+                $tmp = "";\r
+                for ($i=0;$i<strlen($txt);$i++){\r
+                        if ($ctr==strlen($encrypt_key)) $ctr=0;\r
+                        $tmp.= substr($txt,$i,1) ^ substr($encrypt_key,$ctr,1);\r
+                        $ctr++;\r
+                }\r
+                return $tmp;\r
+        }\r
+\r
+        function Encrypt($txt,$key){\r
+                srand((double)microtime()*1000000);\r
+                $encrypt_key = md5(rand(0,32000));\r
+                $ctr=0;\r
+                $tmp = "";\r
+                for ($i=0;$i<strlen($txt);$i++)\r
+                {\r
+                if ($ctr==strlen($encrypt_key)) $ctr=0;\r
+                $tmp.= substr($encrypt_key,$ctr,1) .\r
+                (substr($txt,$i,1) ^ substr($encrypt_key,$ctr,1));\r
+                $ctr++;\r
+                }\r
+                return base64_encode($this->keyED($tmp,$key));\r
+        }\r
+\r
+        function Decrypt($txt,$key){\r
+                $txt = $this->keyED(base64_decode($txt),$key);\r
+                $tmp = "";\r
+                for ($i=0;$i<strlen($txt);$i++){\r
+                        $md5 = substr($txt,$i,1);\r
+                        $i++;\r
+                        $tmp.= (substr($txt,$i,1) ^ $md5);\r
+                }\r
+                return $tmp;\r
+        }\r
+\r
+        function RandPass()\r
+        {\r
+                $randomPassword = "";\r
+                srand((double)microtime()*1000000);\r
+                for($i=0;$i<8;$i++)\r
+                {\r
+                        $randnumber = rand(48,120);\r
+\r
+                        while (($randnumber >= 58 && $randnumber <= 64) || ($randnumber >= 91 && $randnumber <= 96))\r
+                        {\r
+                                $randnumber = rand(48,120);\r
+                        }\r
+\r
+                        $randomPassword .= chr($randnumber);\r
+                }\r
+                return $randomPassword;\r
+        }\r
+\r
+}\r
+?>\r
diff --git a/libraries/adodb/license.txt b/libraries/adodb/license.txt
new file mode 100755 (executable)
index 0000000..752f010
--- /dev/null
@@ -0,0 +1,161 @@
+This software is dual licensed using BSD-Style and LGPL. Where there is any discrepancy, the BSD-Style license will take precedence.\r
+\r
+BSD Style-License\r
+=================\r
+\r
+Copyright (c) 2000, 2001 John Lim\r
+All rights reserved.\r
+\r
+Redistribution and use in source and binary forms, with or without modification, \r
+are permitted provided that the following conditions are met:\r
+\r
+Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. \r
+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. \r
+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. \r
+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 THE REGENTS 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.\r
+\r
+==========================================================\r
+GNU LESSER GENERAL PUBLIC LICENSE\r
+Version 2.1, February 1999 \r
\r
+Copyright (C) 1991, 1999 Free Software Foundation, Inc.\r
+59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\r
+Everyone is permitted to copy and distribute verbatim copies\r
+of this license document, but changing it is not allowed.\r
+\r
+[This is the first released version of the Lesser GPL.  It also counts\r
+ as the successor of the GNU Library Public License, version 2, hence\r
+ the version number 2.1.]\r
\r
\r
+Preamble\r
+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. \r
+\r
+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. \r
+\r
+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. \r
+\r
+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. \r
+\r
+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. \r
+\r
+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. \r
+\r
+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. \r
+\r
+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. \r
+\r
+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. \r
+\r
+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. \r
+\r
+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. \r
+\r
+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. \r
+\r
+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. \r
+\r
+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. \r
+\r
+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. \r
+\r
+\r
+TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION\r
+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". \r
+\r
+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. \r
+\r
+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".) \r
+\r
+"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. \r
+\r
+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. \r
+\r
+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. \r
+\r
+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. \r
+\r
+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: \r
+\r
+\r
+a) The modified work must itself be a software library. \r
+b) You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change. \r
+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. \r
+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. \r
+(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.) \r
+\r
+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. \r
+\r
+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. \r
+\r
+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. \r
+\r
+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. \r
+\r
+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. \r
+\r
+This option is useful when you wish to copy part of the code of the Library into a program that is not a library. \r
+\r
+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. \r
+\r
+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. \r
+\r
+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. \r
+\r
+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. \r
+\r
+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. \r
+\r
+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.) \r
+\r
+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. \r
+\r
+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. \r
+\r
+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: \r
+\r
+\r
+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.) \r
+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. \r
+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. \r
+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. \r
+e) Verify that the user has already received a copy of these materials or that you have already sent this user a copy. \r
+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. \r
+\r
+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. \r
+\r
+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: \r
+\r
+\r
+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. \r
+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. \r
+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. \r
+\r
+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. \r
+\r
+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. \r
+\r
+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. \r
+\r
+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. \r
+\r
+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. \r
+\r
+This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. \r
+\r
+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. \r
+\r
+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. \r
+\r
+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. \r
+\r
+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. \r
+\r
+NO WARRANTY \r
+\r
+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. \r
+\r
+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. \r
+\r
+\r
+END OF TERMS AND CONDITIONS
\ No newline at end of file
diff --git a/libraries/adodb/readme.htm b/libraries/adodb/readme.htm
new file mode 100755 (executable)
index 0000000..92d9b45
--- /dev/null
@@ -0,0 +1,1518 @@
+<html>\r
+<head>\r
+<title>ADODB Manual</title>\r
+<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">\r
+</head>\r
+  \r
+<body bgcolor="#FFFFFF">\r
+\r
+<h1>ADODB Library for PHP4</h1>\r
+<p>V1.53 13 Nov 2001 (c) 2000-2001 John Lim (jlim@natsoft.com.my)</p>\r
+<p>This software is dual licensed using BSD-Style and LGPL. \r
+Where there is any discrepancy, the BSD-Style license will take precedence. \r
+This means you can use it in proprietary and commercial products.</p>\r
+<p><a href="#intro"><b>Introduction</b></a><b><br>\r
+ <a href="#features">Unique Features</a><br>\r
+ <a href="#changes">Change Log</a></b><b><br>\r
+ <a href="#users">How People are using ADODB</a><br>\r
+ <a href="#bugs">Feature Requests and Bug Reports</a><br>\r
+ </b><b><a href="#install">Installation<br>\r
+ </a><a href="#coding">Initializing Code</a></b> <a href=#ADOLoadCode><font size="2">ADOLoadCode</font></a> \r
+ <font size="2"><a href=#adonewconnection>ADONewConnection</a></font>\r
+  <font size="2"><a href=#adonewconnection>NewADOConnection</a></font><br>\r
+   <b> <a href="#drivers">Supported Databases</a></b><br>\r
+ <b> <a href="#quickstart">Tutorial</a></b><br>\r
+ <a href="#ex1">Example 1: Select</a><br>\r
+ <a href="#ex2">Example 2: Advanced Select</a><br>\r
+ <a href="#ex3">Example 3: Insert</a><br>\r
+ <a href="#ex4">Example 4: Debugging</a> &nbsp;<a href="#exrs2html">rs2html example</a><br>\r
+ <a href="#ex5">Example 5: MySQL and Menus</a><br>\r
+ <a href="#ex6">Example 6: Connecting to Multiple Databases at once</a> <br>\r
+ <a href="#ex7">Example 7: Generating Update and Insert SQL</a> <br>\r
+ <a href="#ex8">Example 8: Implementing Scrolling with Next and Previous</a> <br>\r
+<b> <a href="#errorhandling">Using Custom Error Handlers and PEAR_Error</a><br>\r
+ <a href="#caching">Caching</a></b></p>\r
+<p><a href="#ref"><b>Reference</b></a><br>\r
+  <a href="#ADOConnection"><b>ADOConnection</b></a>: <a href="#connect"><font size="2">Connect</font></a> \r
+  <font size="2"><a href="#pconnect">PConnect</a> <a href="#execute">Execute</a> \r
+  <a href="#cacheexecute">CacheExecute</a> <a href="#SelectLimit">SelectLimit</a> \r
+  <a href="#cacheSelectLimit">CacheSelectLimit</a> <a href="#CacheFlush">CacheFlush</a> \r
+  <a href="#Close">Close</a> <a href="#concat">Concat</a> <a href="#dbdate">DBDate</a> \r
+  <a href="#dbtimestamp">DBTimeStamp</a> <a href="#qstr">qstr</a> <a href="#begintrans">BeginTrans</a> \r
+  <a href="#committrans">CommitTrans</a> <a href="#rollbacktrans">RollbackTrans</a></font> \r
+  <font size="2"><a href="#affected_rows">Affected_Rows</a> <a href="#inserted_id">Insert_ID</a></font> \r
+  <font size="2"><a href="#errormsg">ErrorMsg</a> <a href="#errorno">ErrorNo</a> \r
+  <a href="#metadatabases">MetaDatabases</a> <a href="#metatables">MetaTables \r
+  </a><a href="#blankrecordset">BlankRecordSet</a> <a href="#metacolumns">MetaColumns</a> \r
+  <a href="#genid">GenID</a> <a href="#getupdatesql">GetUpdateSQL</a> <a href="#getinsertsql">GetInsertSQL</a> \r
+  <a href="#updateblob">UpdateBlob</a> <a href="#pageexecute">PageExecute</a> \r
+  <a href="#cachepageexecute">CachePageExecute</a></font><br>\r
+  <a href="#ADORecordSet"><b>ADORecordSet</b></a>: <a href="#getassoc"><font size="2">GetAssoc</font></a> \r
+  <font size="2"><a href="#getarray">GetArray</a> <a href="#getrows">GetRows</a> <a href="#getmenu">GetMenu</a> <a href="#getmenu2">GetMenu2</a>  \r
+  <a href="#userdate">UserDate</a> <a href="#usertimestamp">UserTimeStamp</a> \r
+  <a href="#unixdate">UnixDate</a> <a href="#unixtimestamp">UnixTimeStamp</a> \r
+  <a href="#move">Move</a> <a href="#movenext">MoveNext</a> <a href="#movefirst">MoveFirst</a> \r
+  <a href="#movelast">MoveLast</a>  <a href="#getrowassoc">GetRowAssoc</a>  <a href="#fields">Fields</a> <a href="#fetchfield">FetchField</a> \r
+  <a href="#currentrow">CurrentRow</a> <a href="#abspos">AbsolutePosition</a> \r
+  <a href="#fieldcount">FieldCount</a> <a href="#recordcount">RecordCount</a> \r
+  <a href="#fetchobject">FetchObject</a> <a href="#fetchnextobject">FetchNextObject</a> \r
+  <a href="#rsclose">Close</a> <a href="#metatype">MetaType</a>\r
+  <a href="#atfirstpage">AtFirstPage</a>\r
+   <a href="#atlastpage">AtLastPage</a>\r
+    <a href="#absolutepage">AbsolutePage</a>\r
+       </font>  <br>\r
+  <a href="#rs2html"><b>rs2html</b></a>&nbsp; <a href="#exrs2html">example</a><br>\r
+  <a href="#adodiff">Differences between ADODB and ADO</a><br>\r
+  <a href="#driverguide"><b>Database Driver Guide<br>\r
+  </b></a> </p>\r
+<h2>Introduction<a name="intro"></a></h2>\r
+<p>PHP's database access functions are not standardised. This creates a need for \r
+ a database class library to hide the differences between the different databases \r
+ (encapsulate the differences) so we can easily switch databases.</p>\r
+<p>We currently support MySQL, Interbase, Oracle, Microsoft SQL Server, Sybase, \r
+  PostgreSQL, FrontBase, Foxpro, Access, ADO and ODBC. We have had successful reports of connecting\r
+  to Progress and DB2 via ODBC. We hope more people \r
+  will contribute drivers to support other databases.</p>\r
+<p>PHP4 supports session variables. You can store your session information using \r
+  ADODB for true portability and scalability. See adodb-session.php for more information.</p>\r
+<h2>Unique Features of ADODB<a name="features"></a></h2>\r
+<ul>\r
+  <li><b>Easy for Windows programmers</b> to adapt to because many of the conventions \r
+    are similar to Microsoft's ADO.</li>\r
+  <li>Unlike other PHP database classes which focus only on select statements, \r
+    <b>we provide support code to handle inserts and updates which can be adapted \r
+    to multiple databases quickly.</b> Methods are provided for date handling, \r
+    string concatenation and string quoting characters for differing databases.</li>\r
+  <li>A<b> metatype system </b>is built in so that we can figure out that types \r
+    such as CHAR, TEXT and STRING are equivalent in different databases.</li>\r
+  <li><b>Easy to port</b> because all the database dependant code are stored in \r
+    stub functions. You do not need to port the core logic of the classes.</li>\r
+  <li><b>PHP4 session support</b>. See adodb-session.php.</li>\r
+</ul>\r
+<h2>Change Log<a name="Changes"></a></h2>\r
+<p><b>1.53 7 Nov 2001</b></p>\r
+Added support for ADODB_FETCH_ASSOC for ado and odbc drivers.<p>\r
+Tuned GetRowAssoc(false) in postgresql and mysql.<p>\r
+Stephen Van Dyke contributed adodb icon, accepted with some minor mods.<p>\r
+Enabled Affected_Rows() for postgresql<p>\r
+Speedup for Concat() using implode()<p>\r
+Fixed some more bugs in PageExecute() to prevent infinite loops<p>\r
+<p><b>1.52 5 Nov 2001</b></p>\r
+Spelling error in CacheExecute() caused it to fail. $ql should be $sql in line 625!<p>\r
+Added fixes for parsing [ and ] in GetUpdateSQL().\r
+<p><b>1.51 5 Nov 2001</b></p>\r
+<p>Oci8 SelectLimit() speedup by using OCIFetch().\r
+<p>Oci8 was mistakenly reporting errors when $db->debug = true.\r
+<p>If a connection failed with ODBC, it was not correctly reported - fixed.\r
+<p>_connectionID was inited to -1, changed to false.\r
+<p>Added $rs->FetchRow(), to simplify API, ala PEAR DB\r
+<p>Added PEAR DB compat mode, which is still faster than PEAR! See adodb-pear.inc.php.\r
+<p>Removed postgres pconnect debugging statement.\r
+<p><b>1.50 31 Oct 2001</b></p>\r
+<p>ADODBConnection renamed to ADOConnection, and ADODBFieldObject to ADOFieldObject.\r
+<p>PageExecute() now checks for empty $rs correctly, and the errors in the docs on this subject have been fixed.\r
+<p>odbc_error() does not return 6 digit error correctly at times. Implemented workaround.\r
+<p>Added ADORecordSet_empty class. This will speedup INSERTS/DELETES/UPDATES because the return\r
+object created is much smaller.\r
+<p>Added Prepare() to odbc, and oci8 (but doesn't work properly for oci8 still).\r
+<p>Made pgsql a synonym for postgre7, and changed SELECT LIMIT to use OFFSET for compat with \r
+postgres 7.2.\r
+<p>Revised adodb-cryptsession.php thanks to Ari.\r
+<p>Set resources to false on _close, to force freeing of resources.\r
+<p>Added adodb-errorhandler.inc.php, adodb-errorpear.inc.php and raiseErrorFn on Freek's urging.\r
+<p>GetRowAssoc($toUpper=true): $toUpper added as default.\r
+<p>Errors when connecting to a database were not captured formerly. Now we do it correctly.\r
+<p><b>1.40 19 September 2001</b></p>\r
+<p>PageExecute() to implement page scrolling added. Code and idea by Iván Oliva.</p>\r
+<p>Some minor postgresql fixes.</p>\r
+<p>Added sequence support using GenID() for postgresql, oci8, mysql, interbase.</p>\r
+<p>Added UpdateBlob support for interbase (untested).</p>\r
+<p>Added encrypted sessions (see adodb-cryptsession.php). By Ari Kuorikoski <kuoriari@finebyte.com></p>\r
+<p><b>1.31 21 August 2001</b></p>\r
+<p>Many bug fixes thanks to "GaM3R (Cameron)" <gamr@outworld.cx>. Some session changes due to Gam3r.\r
+<p>Fixed qstr() to quote \ also.\r
+<p>rs2html() now pretty printed.\r
+<p>Jonathan Younger jyounger@unilab.com contributed the great idea GetUpdateSQL() and GetInsertSQL() which\r
+generates SQL to update and insert into a table from a recordset. Modify the recordset fields\r
+array, then can this function to generate the SQL (the SQL is not executed).\r
+<p>"Nicola Fankhauser" <nicola.fankhauser@couniq.com> found some bugs in date handling for mssql.</p>\r
+<p>Added minimal Oracle support for LOBs. Still under development.</p>\r
+Added $ADODB_FETCH_MODE so you can control whether recordsets return arrays which are\r
+numeric, associative or both. This is a global variable you set. Currently only MySQL, Oci8, Postgres\r
+drivers support this.\r
+<p>PostgreSQL properly closes recordsets now. Reported by several people.\r
+<p>\r
+Added UpdateBlob() for Oracle. A hack to make it easier to save blobs.\r
+<p>\r
+Oracle timestamps did not display properly. Fixed.\r
+<p><b>1.20 6 June 2001</b></p>\r
+<p>Now Oracle can connect using tnsnames.ora or server and service name</p>\r
+<p>Extensive Oci8 speed optimizations. \r
+Oci8 code revised to support variable binding, and /*+ FIRST_ROWS */ hint.</p>\r
+<p>Worked around some 4.0.6 bugs in odbc_fetch_into().</p>\r
+<p>Paolo S. Asioli paolo.asioli@libero.it suggested GetRowAssoc().</p>\r
+<p>Escape quotes for oracle wrongly set to \'. Now '' is used.</p>\r
+<p>Variable binding now works in ODBC also.</p>\r
+<p>Jumped to version 1.20 because I don't like 13 :-)</p>\r
+<p><b>1.12 6 June 2001</b></p>\r
+<p>Changed $ADODB_DIR to ADODB_DIR constant to plug a security loophole.</p>\r
+<p>Changed _close() to close persistent connections also. Prevents connection leaks.</p>\r
+<p>Major revision of oracle and oci8 drivers. \r
+Added OCI_RETURN_NULLS and OCI_RETURN_LOBS to OCIFetchInto(). BLOB, CLOB and VARCHAR2 recognition\r
+in MetaType() improved. MetaColumns() returns columns in correct sort order.</p>\r
+<p>Interbase timestamp input format was wrong. Fixed.</p>\r
+<p><b>1.11 20 May 2001</b></p>\r
+<p>Improved file locking for Windows.</p>\r
+<p>Probabilistic flushing of cache to avoid avalanche updates when cache timeouts.</p>\r
+<p>Cached recordset timestamp not saved in some scenarios. Fixed.</p>\r
+<p><b>1.10 19 May 2001</b></p>\r
+<p>Added caching. CacheExecute() and CacheSelectLimit().\r
+<p>Added csv driver. See <a href=http:#php.weblogs.com/adodb_csv>http:#php.weblogs.com/adodb_csv</a>.\r
+<p>Fixed SelectLimit(), SELECT TOP not working under certain circumstances.\r
+<p>Added better Frontbase support of MetaTypes() by Frank M. Kromann.\r
+<p><b>1.01 24 April 2001</b></p>\r
+<p>Fixed SelectLimit bug. \ not quoted properly.\r
+<p>SelectLimit: SELECT TOP -1 * FROM TABLE not support by Microsoft. Fixed.</p>\r
+<p>GetMenu improved by glen.davies@cce.ac.nz to support multiple hilited items<p>\r
+<p>FetchNextObject() did not work with only 1 record returned. Fixed bug reported by $tim@orotech.net</p>\r
+<p>Fixed mysql field max_length problem. Fix suggested by Jim Nicholson (jnich@att.com)</p>\r
+<p><b>1.00 16 April 2001</b></p>\r
+<p>Given some brilliant suggestions on how to simplify ADODB by akul. You no longer need to\r
+setup $ADODB_DIR yourself, and ADOLoadCode() is automatically called by ADONewConnection(), \r
+simplifying the startup code.</p>\r
+<p>FetchNextObject() added. Suggested by Jakub Marecek. This makes FetchObject() obsolete, as\r
+this is more flexible and powerful.</p>\r
+<p>Misc fixes to SelectLimit() to support Access (top must follow distinct) and Fields() \r
+in the array recordset. From Reinhard Balling.</p>\r
+<p><b>0.96 27 Mar 2001</b></p>\r
+<p>ADOConnection Close() did not return a value correctly. Thanks to akul@otamedia.com.</p>\r
+<p>When the horrible magic_quotes is enabled, back-slash (\) is changed to double-backslash (\\).\r
+This doesn't make sense for Microsoft/Sybase databases. We fix this in qstr().</p>\r
+<p>Fixed Sybase date problem in UnixDate() thanks to Toni Tunkkari. Also fixed MSSQL problem\r
+in UnixDate() - thanks to milhouse31@hotmail.com.</p>\r
+<p>MoveNext() moved to leaf classes for speed in MySQL/PostgreSQL. 10-15% speedup.</p>\r
+<p>Added null handling in bindInputArray in Execute() -- Ron Baldwin suggestion.</p>\r
+<p>Fixed some option tags. Thanks to john@jrmstudios.com.</p>\r
+<p><b>0.95 13 Mar 2001</b></p>\r
+<p>Added postgres7 database driver which supports LIMIT and other version 7 stuff in the future.</p>\r
+<p>Added SelectLimit to ADOConnection to simulate PostgreSQL's "select * from table limit 10 offset 3".\r
+Added helper function GetArrayLimit() to ADORecordSet.</p>\r
+<p>Fixed mysql metacolumns bug. Thanks to Freek Dijkstra (phpeverywhere@macfreek.com).</p>\r
+<p>Also many PostgreSQL changes by Freek. He almost rewrote the whole PostgreSQL driver!</p>\r
+<p>Added fix to input parameters in Execute for non-strings by Ron Baldwin.</p>\r
+<p>Added new metatype, X for TeXt. Formerly, metatype B for Blob also included\r
+text fields. Now 'B' is for binary/image data. 'X' for textual data.</p>\r
+<p>Fixed $this->GetArray() in GetRows().</p>\r
+<p>Oracle and OCI8: 1st parameter is always blank -- now warns if it is filled.</p>\r
+<p>Now <i>hasLimit</i> and <i>hasTop</i> added to indicate whether \r
+SELECT * FROM TABLE LIMIT 10 or SELECT TOP 10 * FROM TABLE are supported.</p>\r
+<p><b>0.94 04 Feb 2001</b></p>\r
+<p>Added ADORecordSet::GetRows() for compatibility with Microsoft ADO. Synonym for GetArray().</p>\r
+<p>Added new metatype 'R' to represent autoincrement numbers.</p>\r
+<p>Added ADORecordSet.FetchObject() to return a row as an object.</p>\r
+<p>Finally got a Linux box to test PostgreSql. Many fixes.</p>\r
+<p>Fixed copyright misspellings in 0.93.</p>\r
+<p>Fixed mssql MetaColumns type bug.</p>\r
+<p>Worked around odbc bug in PHP4 for sessions.</p>\r
+<p>Fixed many documentation bugs (affected_rows, metadatabases, qstr).</p>\r
+<p>Fixed MySQL timestamp format (removed comma).</p>\r
+<p>Interbase driver did not call ibase_pconnect(). Fixed.</p>\r
+<p><b>0.93 18 Jan 2001</b></p>\r
+<p>Fixed GetMenu bug.</p>\r
+<p>Simplified Interbase commit and rollback.</p>\r
+<p>Default behaviour on closing a connection is now to rollback all active transactions.</p>\r
+<p>Added field object handling for array recordset for future XML compatibility.</p>\r
+<p>Added arr2html() to convert array to html table.</p>\r
+<p><b>0.92 2 Jan 2001</b></p>\r
+<p>Interbase Commit and Rollback should be working again.</p>\r
+<p>Changed initialisation of ADORecordSet. This is internal and should not affect users. We\r
+are doing this to support cached recordsets in the future.</p>\r
+<p>Implemented ADORecordSet_array class. This allows you to simulate a database recordset\r
+with an array.</p>\r
+<p>Added UnixDate() and UnixTimeStamp() to ADORecordSet.</p>\r
+<p><b>0.91 21 Dec 2000</b></p>\r
+<p>Fixed ODBC so ErrorMsg() is working.</p>\r
+<p>Worked around ADO unrecognised null (0x1) value problem in COM.</p>\r
+<p>Added Sybase support for FetchField() type</p>\r
+<p>Removed debugging code and unneeded html from various files</p>\r
+<p>Changed to javadoc style comments to adodb.inc.php.</p>\r
+<p>Added maxsql as synonym for mysqlt</p>\r
+<p>Now ODBC downloads first 8K of blob by default\r
+<p><b>0.90 15 Nov 2000</b></p>\r
+<p>Lots of testing of Microsoft ADO. Should be more stable now.</p>\r
+<p>Added $ADODB_COUNTREC. Set to false for high speed selects.</p>\r
+<p>Added Sybase support. Contributed by Toni Tunkkari (toni.tunkkari@finebyte.com). Bug in Sybase \r
+  API: GetFields is unable to determine date types.</p>\r
+<p>Changed behaviour of RecordSet.GetMenu() to support size parameter (listbox) properly.</p>\r
+<p>Added emptyDate and emptyTimeStamp to RecordSet class that defines how to represent \r
+  empty dates.</p>\r
+<p>Added MetaColumns($table) that returns an array of ADOFieldObject's listing \r
+  the columns of a table.</p>\r
+<p>Added transaction support for PostgresSQL -- thanks to "Eric G. Werk" egw@netguide.dk.</p>\r
+<p>Added adodb-session.php for session support.</p>\r
+<p><b>0.80 30 Nov 2000</b></p>\r
+<p>Added support for charSet for interbase. Implemented MetaTables for most databases. \r
+  PostgreSQL more extensively tested.</p>\r
+<p><b>0.71 22 Nov 2000</b></p>\r
+<p>Switched from using require_once to include/include_once for backward compatability with PHP 4.02 and earlier.</p>\r
+<p><b>0.70 15 Nov 2000</b></p>\r
+<p>Calls by reference have been removed (call_time_pass_reference=Off) to ensure compatibility with future versions of PHP, \r
+except in Oracle 7 driver due to a bug in php_oracle.dll.</p>\r
+<p>PostgreSQL database driver contributed by Alberto Cerezal (acerezalp@dbnet.es). \r
+</p>\r
+<p>Oci8 driver for Oracle 8 contributed by George Fourlanos (fou@infomap.gr).</p>\r
+<p>Added <i>mysqlt</i> database driver to support MySQL 3.23 which has transaction \r
+ support. </p>\r
+<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>\r
+<p>Error message checking is now included in test suite.</p>\r
+<p>MoveNext() did not check EOF properly -- fixed.</p>\r
+<p><b>0.60 Nov 8 2000</b></p>\r
+<p>Fixed some constructor bugs in ODBC and ADO. Added ErrorNo function to ADOConnection \r
+ class. </p>\r
+<p><b>0.51 Oct 18 2000</b></p>\r
+<p>Fixed some interbase bugs.</p>\r
+<p><b>0.50 Oct 16 2000</b></p>\r
+<p>Interbase commit/rollback changed to be compatible with PHP 4.03. </p>\r
+<p>CommitTrans( ) will now return true if transactions not supported. </p>\r
+<p>Conversely RollbackTrans( ) will return false if transactions not supported. \r
+</p>\r
+<p><b>0.46 Oct 12</b></p>\r
+Many Oracle compatibility issues fixed. \r
+<p><b>0.40 Sept 26</b></p>\r
+<p>Many bug fixes</p>\r
+<p>Now Code for BeginTrans, CommitTrans and RollbackTrans is working. So is the Affected_Rows\r
+and Insert_ID. Added above functions to test.php.</p>\r
+<p>ADO type handling was busted in 0.30. Fixed.</p>\r
+<p>Generalised Move( ) so it works will all databases, including ODBC.</p>\r
+<p><b>0.30 Sept 18</b></p>\r
+<p>Renamed ADOLoadDB to ADOLoadCode. This is clearer.</p>\r
+<p>Added BeginTrans, CommitTrans and RollbackTrans functions.</p>\r
+<p>Added Affected_Rows() and Insert_ID(), _affectedrows() and _insertID(), ListTables(), \r
+ ListDatabases(), ListColumns().</p>\r
+<p>Need to add New_ID() and hasInsertID and hasAffectedRows, autoCommit </p>\r
+<p><b>0.20 Sept 12</b></p>\r
+<p>Added support for Microsoft's ADO.</p>\r
+<p>Added new field to ADORecordSet -- canSeek</p>\r
+<p>Added new parameter to _fetch($ignore_fields = false). Setting to true will \r
+ not update fields array for faster performance.</p>\r
+<p>Added new field to ADORecordSet/ADOConnection -- dataProvider to indicate whether \r
+ a class is derived from odbc or ado.</p>\r
+<p>Changed class ODBCFieldObject to ADOFieldObject -- not documented currently.</p>\r
+<p>Added benchmark.php and testdatabases.inc.php to the test suite.</p>\r
+<p>Added to ADORecordSet FastForward( ) for future high speed scrolling. Not documented.</p>\r
+<p>Realised that ADO's Move( ) uses relative positioning. ADODB uses absolute. \r
+</p>\r
+<p><b>0.10 Sept 9 2000</b></p>\r
+<p>First release</p>\r
+<h2>How People are using ADODB<a name="users"></a></h2>\r
+Here are some examples of how people are using ADODB:\r
+<ul>\r
+<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.\r
+\r
+<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.\r
+\r
+<li><a href=http:#www.andrew.cmu.edu/~rdanyliw/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.\r
+\r
+<li><a href=http:#www.cccsoftware.org/>CCC</a> is a web based inventory /contact management / POS / job tracking / job billing system specially designed for computer service shops, but should be useful to anyone that needs accountability of any of any of the things listed. By Ryan Fox.\r
+</ul>\r
+\r
+<h2>Feature Requests and Bug Reports<a name="bugs"></a></h2>\r
+<p>Feature requests and bug reports can be emailed to <a href="mailto:jlim@natsoft.com.my">jlim@natsoft.com.my</a> \r
+ or posted to <a href="http:#php.weblogs.com/discuss/msgReader$96">http:#php.weblogs.com/discuss/msgReader$96</a>.</p>\r
+<h2>Installation Guide<a name="install"></a></h2>\r
+<p>Make sure you are running PHP4.01pl2 or later (it uses require_once and include_once). \r
+Unpack all the files into a directory accessible by your webserver. \r
+</p>\r
+<p>To test you will need a database. Open <i>testdatabases.inc.php</i> and modify \r
+ the connection parameters to suit your database. This script will create a new \r
+ table in the database and perform various tests.</p>\r
+<p>That's it!</p>\r
+<h3>Code Initialization<a name="coding"></a></h3>\r
+<p>When running ADODB, at least two files are loaded. First is adodb.inc.php, \r
+ which contains all functions used by all database classes. The code specific \r
+ to a particular database is in the adodb-????.inc.php file.</p>\r
+<p>For example, to connect to a mysql database:</p>\r
+<pre>\r
+include('/path/to/set/here/adodb.inc.php');\r
+$conn = &amp;ADONewConnection('mysql');\r
+</pre>\r
+<p>Whenever you need to connect to a database, you create a Connection object \r
+ using the <b><a name=adonewconnection>ADONewConnection</a></b>( ) function. \r
+  ADONewConnection accepts one optional parameter, the &lt;database-name-here&gt;. \r
+  If no parameter is specified, it will create a new ADOConnection for the last \r
+  database loaded by ADOLoadCode( ). <b>NewADOConnection</b>( ) \r
+  is the same function.</p>\r
+<p>At this point, you are not connected to the database. \r
+You will use <code>$conn-><a href=#connect>Connect()</a></code> or \r
+<code>$conn-><a href=#pconnect>PConnect()</a></code> to perform the actual connection.</p>\r
+<p>See the examples below in the Tutorial.</p>\r
+ <h3><a name=drivers></a>Databases Supported</h3>\r
+<table width="100%" border="1">\r
+  <tr valign="top"> \r
+    <td><b>Name</b></td>\r
+    <td><b>Database</b></td>\r
+    <td><b><font size="2">RecordCount() usable</font></b></td>\r
+    <td><b>Prerequisites</b></td>\r
+    <td><b>Operating Systems</b></td>\r
+  </tr>\r
+  <tr valign="top"> \r
+    <td><b>access</b></td>\r
+    <td>Microsoft Access. You need to create an ODBC DSN.</td>\r
+    <td>N</td>\r
+    <td>ODBC </td>\r
+    <td>Windows only</td>\r
+  </tr>\r
+  <tr valign="top"> \r
+    <td><b>ado</b></td>\r
+    <td>Generic ADO, not tuned for specific databases. Slower than ODBC, but allows \r
+      DSN-less connections.</td>\r
+    <td>? depends on database</td>\r
+    <td>ADO and OLEDB provider</td>\r
+    <td>Windows only</td>\r
+  </tr>\r
+  <tr valign="top"> \r
+    <td><b>ado_access</b></td>\r
+    <td>Microsoft Access using ADO. Slower than ODBC, but allows DSN-less connections.</td>\r
+    <td>N</td>\r
+    <td>ADO and OLEDB provider for Access</td>\r
+    <td>Windows only</td>\r
+  </tr>\r
+  <tr valign="top"> \r
+    <td><b>vfp</b></td>\r
+    <td>Microsoft Visual FoxPro. You need to create an ODBC DSN.</td>\r
+    <td>N</td>\r
+    <td>ODBC</td>\r
+    <td>Windows only</td>\r
+  </tr>\r
+  <tr valign="top"> \r
+    <td><b>ibase</b></td>\r
+    <td>Interbase. Some users report you might need to use this<br>\r
+$db->PConnect('localhost:c:\ibase\employee.gdb', "sysdba", "masterkey") to connect.</td>\r
+    <td>N</td>\r
+    <td>Interbase client</td>\r
+    <td>Unix and Windows</td>\r
+  </tr>\r
+  <tr valign="top"> \r
+    <td><b>mssql</b></td>\r
+    <td> \r
+      <p>Microsoft SQL Server 7.</p>\r
+    </td>\r
+    <td>Y</td>\r
+    <td>Mssql client</td>\r
+    <td> \r
+      <p>Unix and Windows. <a href="http:#phpbuilder.com/columns/alberto20000919.php3"><br>\r
+        Unix install howto</a>.</p>\r
+    </td>\r
+  </tr>\r
+  <tr valign="top"> \r
+    <td><b>mysql</b></td>\r
+    <td>MySQL without transaction support (3.22)</td>\r
+    <td>Y</td>\r
+    <td>MySQL client</td>\r
+    <td>Unix and Windows</td>\r
+  </tr>\r
+  <tr valign="top"> \r
+    <td><b>mysqlt</b> or <b>maxsql</b></td>\r
+    <td>MySQL with transaction support (3.23)</td>\r
+    <td>Y</td>\r
+    <td>MySQL client</td>\r
+    <td>Unix and Windows</td>\r
+  </tr>\r
+  <tr valign="top"> \r
+    <td><b>oci8</b></td>\r
+    <td>Oracle 8. Has more functionality than <i>oracle</i> driver (Affected_Rows). \r
+       You might have to putenv('ORACLE_HOME=...') before Connect/PConnect.<p>\r
+       There are 2 ways of connecting - \r
+       with server IP and service name: <br>PConnect('serverip:1521','scott','tiger','service'), or\r
+       using an entry in the tnsnames.ora: <br>PConnect('', 'scott', 'tiger', 'tnsname').\r
+       </td>\r
+    <td>N</td>\r
+    <td>Oracle client</td>\r
+    <td>Unix and Windows</td>\r
+  </tr>\r
+  <tr valign="top"> \r
+    <td><b>odbc</b></td>\r
+    <td>Generic ODBC, not tuned for specific databases. \r
+       To connect, use <br>PConnect('DSN','user','pwd').</td>\r
+    <td>? depends on database</td>\r
+    <td>ODBC</td>\r
+    <td>Unix and Windows. <a href="http:#phpbuilder.com/columns/alberto20000919.php3?page=4">Unix \r
+      hints.</a></td>\r
+  </tr>\r
+  <tr valign="top"> \r
+    <td><b>oracle</b></td>\r
+    <td>Oracle 7 or 8 support. Obsolete.</td>\r
+    <td>N</td>\r
+    <td>Oracle client</td>\r
+    <td>Unix and Windows</td>\r
+  </tr>\r
+  <tr valign="top"> \r
+    <td><b>postgres</b></td>\r
+    <td>PostgreSQL which does not support LIMIT internally.</td>\r
+    <td>Y</td>\r
+    <td>PostgreSQL client</td>\r
+    <td>Unix and Windows. </td>\r
+  </tr>\r
+   <tr valign="top"> \r
+    <td><b>postgres7</b></td>\r
+    <td>PostgreSQL which supports LIMIT and other version 7 functionality.</td>\r
+    <td>Y</td>\r
+    <td>PostgreSQL client</td>\r
+    <td>Unix and Windows. </td>\r
+  </tr>\r
+   <tr valign="top"> \r
+    <td><b>sybase</b></td>\r
+    <td>Sybase. </td>\r
+    <td>Y</td>\r
+    <td>Sybase client</td>\r
+    <td> \r
+      <p>Unix and Windows. <a href="http:#www.finebyte.com/docs/sybase/ASA-PHP-Linux.html">Unix \r
+        hints</a>.</p>\r
+    </td>\r
+  </tr>\r
+     <tr valign="top"> \r
+    <td><b>db2</b></td>\r
+    <td>DB2. Warning: this is experimental. Please email me if there are problems.</td>\r
+    <td>Y</td>\r
+    <td>DB2 CLI/ODBC interface</td>\r
+    <td> \r
+      <p>Unix and Windows. <a href="http:#www.faqts.com/knowledge_base/view.phtml/aid/6283/fid/14">Unix \r
+        install hints</a>.</p>\r
+    </td>\r
+  </tr>\r
+   \r
+     <tr valign="top"> \r
+    <td><b>fbsql</b></td>\r
+    <td>FrontBase. Warning: this is experimental. Please email me if there are problems.</td>\r
+    <td>Y</td>\r
+    <td>?</td>\r
+    <td> \r
+      <p>Unix and Windows</p>\r
+    </td>\r
+  </tr>\r
+</table>\r
+<p>RecordCount() usable indicates whether RecordCount() returns -1 instead of \r
+  the number of rows when a SELECT statement is executed. For highest performance, \r
+  disable RecordCount() by setting the global variable $ADODB_COUNTRECS=false. \r
+  For the reason why, see the notes to <a href="http:#php.net/manual/function.sybase-num-rows.php">http:#php.net/manual/function.sybase-num-rows.php</a></p>\r
+<p>Other database drivers used for testing ADODB.</p>\r
+<table width="100%" border="0">\r
+ <tr valign="top"> \r
+  <td width="9%"><b>ado_mssql</b></td>\r
+  <td width="88%">Microsoft SQL Server 7 using Microsoft ADO. This database driver \r
+   is only for test purposes. Use the mssql driver instead.</td>\r
+ </tr>\r
+ <tr valign="top"> \r
+  <td width="9%"><b>odbc_mssql</b></td>\r
+  <td width="88%">Microsoft SQL Server 7 using ODBC. This database driver is only \r
+   for test purposes. Use the mssql driver instead.</td>\r
+ </tr>\r
+</table>\r
+\r
+<hr>\r
+<h1>Tutorial<a name="quickstart"></a></h1>\r
+<h3>Example 1: Select Statement<a name="ex1"></a></h3>\r
+<p>Task: Connect to the Access Northwind database, display the first 2 columns \r
+  of each row.</p>\r
+<p>In this example, we create a ADOConnection object, which represents the connection \r
+ to the database. The connection is initiated with <a href="#pconnect"><font face="Courier New, Courier, mono">PConnect</font></a>, \r
+ which is a persistent connection. Whenever we want to query the database, we \r
+ call the <font face="Courier New, Courier, mono">ADOConnection.<a href="#execute">Execute</a>()</font> \r
+ function. This returns an ADORecordSet object which is actually a cursor that \r
+ holds the current row in the array <font face="Courier New, Courier, mono">fields[]</font>. \r
+ We use <font face="Courier New, Courier, mono"><a href="#movenext">MoveNext</a>()</font> \r
+ to move from row to row.</p>\r
+<p>NB: A useful function that is not used in this example is \r
+<font face="Courier New, Courier, mono"><a href="#selectlimit">SelectLimit</a></font>, which\r
+allows us to limit the number of rows shown.\r
+<pre>\r
+&lt;?\r
+<font face="Courier New, Courier, mono"><b>include</b>('adodb.inc.php');       # load code common to ADODB\r
+$<font color="#660000">conn</font> = &amp;ADONewConnection('access');    # create a connection\r
+$<font color="#660000">conn</font>->PConnect('northwind');   # connect to MS-Access, northwind db\r
+$<font color="#660000">recordSet</font> = &amp;$<font color="#660000">conn</font>->Execute('select * from products');\r
+\r
+<b>while</b> (!$<font color="#660000">recordSet</font>-&gt;EOF) &#123;\r
+       <b>print</b> $<font color="#660000">recordSet</font>->fields[0].' '.$<font color="#660000">recordSet</font>->fields[1].'&lt;BR&gt;';\r
+       $<font color="#660000">recordSet</font>-&gt;MoveNext();\r
+&#125;\r
+\r
+$<font color="#660000">recordSet</font>->Close(); # optional\r
+$<font color="#660000">conn</font>->Close(); # optional\r
+</font>\r
+?>\r
+</pre>\r
+<p>The $<font face="Courier New, Courier, mono">recordSet</font> returned stores \r
+ the current row in the <font face="Courier New, Courier, mono">$recordSet-&gt;fields</font> \r
+ array, indexed by column number (starting from zero). We use the <font face="Courier New, Courier, mono"><a href="#movenext">MoveNext</a>()</font> \r
+ function to move to the next row. The <font face="Courier New, Courier, mono">EOF</font> \r
+ property is set to true when end-of-file is reached. </p>\r
+<p>An associative array by column name is also provided by emulation; because \r
+ some database extensions do not provide associative arrays, we have two functions,  \r
+ <font face="Courier New, Courier, mono">Fields()</font> and <font face="Courier New, Courier, mono">GetRowAssoc()</font> \r
+ to emulate associative arrays. For example to access the ProductID field value, \r
+ we can use <font face="Courier New, Courier, mono">$recordSet-&gt;<a href="#fields">Fields</a>('productID'). \r
+ </font>Note that this is not an array, but a function. Column names for this \r
+ function are case-insensitive.</p><p>\r
+ Alternatively, use\r
+ $recordSet-&gt;<font face="Courier New, Courier, mono"><a href=#getrowassoc>GetRowAssoc()</a></font> to return\r
+ an associative array where the element keys are the column names (upper-cased).\r
+  This is only available since ADODB 1.20.\r
+ </p>\r
+<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>. \r
+ Note that it can return -1 if the number of rows returned cannot be determined.</p>\r
+<h3>Example 2: Advanced Select with Field Objects<a name="ex2"></a></h3>\r
+<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>\r
+<pre>\r
+&lt;?\r
+<font face="Courier New, Courier, mono"><b>include</b>('adodb.inc.php');       # load code common to ADODB\r
+$<font color="#660000">conn</font> = &amp;ADONewConnection('access');    # create a connection\r
+$<font color="#660000">conn</font>->PConnect('northwind');   # connect to MS-Access, northwind db\r
+$<font color="#660000">recordSet</font> = &amp;$<font color="#660000">conn</font>->Execute('select CustomerID,OrderDate from Orders');\r
+\r
+<b>while</b> (!$<font color="#660000">recordSet</font>-&gt;EOF) &#123;\r
+       $<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>\r
+       $<font color="#660000">type</font> = <font color="#336600"><b>$</b><font color="#660000">recordSet</font><b>-&gt;MetaType</b></font>($fld-&gt;type);\r
+\r
+       <b>if</b> ( $<font color="#660000">type</font> == 'D' || $<font color="#660000">type</font> == 'T') \r
+               <b>print</b> $<font color="#660000">recordSet</font>-&gt;fields[0].' '.\r
+                       <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;';\r
+       <b>else </b>\r
+               <b>print</b> $<font color="#660000">recordSet</font>->fields[0].' '.$<font color="#660000">recordSet</font>->fields[1].'&lt;BR&gt;';\r
+\r
+       $<font color="#660000">recordSet</font>-&gt;MoveNext();\r
+&#125;\r
+\r
+$<font color="#660000">recordSet</font>->Close(); # optional\r
+$<font color="#660000">conn</font>->Close(); # optional\r
+</font>\r
+?>\r
+</pre>\r
+<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> \r
+ This returns an object with at least 3 fields.</p>\r
+<ul>\r
+ <li><b>name</b>: name of column</li>\r
+ <li> <b>type</b>: native field type of column</li>\r
+ <li> <b>max_length</b>: maximum length of field. Some databases such as MySQL \r
+  do not return the maximum length of the field correctly. In these cases max_length \r
+  will be set to -1.</li>\r
+</ul>\r
+<p>We then use <font face="Courier New, Courier, mono"><a href="#metatype">MetaType</a>()</font> \r
+ to translate the native type to a <i>generic</i> type. Currently the following \r
+ <i>generic</i> types are defined:</p>\r
+<ul>\r
+ <li><b>C</b>: character fields that should be shown in a &lt;input type=&quot;text&quot;&gt; \r
+  tag.</li>\r
+ <li><b>X</b>: TeXt, large text fields that should be shown in a &lt;textarea&gt;</li>\r
+ <li><b>B</b>: Blobs, or Binary Large Objects. Typically images.\r
+ <li><b>D</b>: Date field</li>\r
+ <li><b>T</b>: Timestamp field</li>\r
+ <li><b>L</b>: Logical field (boolean or bit-field)</li>\r
+ <li><b>N</b>: Numeric field. Includes autoincrement, numeric, floating point, \r
+  real and integer. </li>\r
+ <li><b>R</b>: Serial field. Includes serial, autoincrement integers. This works for selected databases. </li>\r
+</ul>\r
+<p>If the metatype is of type date or timestamp, then we print it using the user \r
+ defined date format with <font face="Courier New, Courier, mono"><a href="#userdate">UserDate</a>(),</font> \r
+ which converts the PHP SQL date string format to a user defined one. Another \r
+ use for <font face="Courier New, Courier, mono"><a href="#metatype">MetaType</a>()</font> \r
+ is data validation before doing an SQL insert or update.</p>\r
+<h3>Example 3: Inserting<a name="ex3"></a></h3>\r
+<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>\r
+<pre>\r
+&lt;?\r
+<b>include</b>('adodb.inc.php');       # load code common to ADODB\r
+$<font color="#660000">conn</font> = &amp;ADONewConnection('access');    # create a connection\r
+$<font color="#660000">conn</font>->PConnect('northwind');   # connect to MS-Access, northwind db\r
+\r
+$<font color="#660000">shipto</font> = <font color="#006600"><b>$conn-&gt;qstr</b></font>(&quot;<i>John's Old Shoppe</i>&quot;);\r
+\r
+$<font color="#660000">sql</font> = &quot;insert into orders (customerID,EmployeeID,OrderDate,$shipto) &quot;;\r
+$<font color="#660000">sql</font> .= &quot;values ('ANATR',2,&quot;.<b><font color="#006600">$conn-&gt;DBDate(</font>time()<font color="#006600">)</font></b><font color="#006600">.</font>&quot;,$<font color="#660000">shipto</font>)&quot;;\r
+\r
+<b>if</b> ($<font color="#660000">conn</font>->Execute($<font color="#660000">sql</font>) <font color="#336600"><b>=== false</b></font>) &#123;\r
+       <b>print</b> 'error inserting: '.<font color="#336600"><b>$conn-&gt;ErrorMsg()</b></font>.'&lt;BR&gt;';\r
+&#125;\r
+?>\r
+</pre>\r
+<p>In this example, we see the advanced date and quote handling facilities of \r
+  ADODB. The unix timestamp (which is a long integer) is appropriately formated \r
+  for Access with <font face="Courier New, Courier, mono"><a href="#dbdate">DBDate</a>()</font>, \r
+  and the right escape character is used for quoting the <i>John's Old Shoppe</i>, \r
+  which is<b> </b><i>John'<b>'</b>s Old Shoppe</i> and not PHP's default <i>John\<b>'</b>s \r
+  Old Shoppe</i> with <font face="Courier New, Courier, mono"><a href="#qstr">qstr</a>()</font>. \r
+</p>\r
+<p>Observe the error-handling of the Execute statement. False is returned by<font face="Courier New, Courier, mono"> \r
+ <a href="#execute">Execute</a>() </font>if an error occured. The error message \r
+ for the last error that occurred is displayed in <font face="Courier New, Courier, mono"><a href="#errormsg">ErrorMsg</a>()</font>. \r
+ Note: <i>php_track_errors</i> might have to be enabled for error messages to \r
+ be saved.</p>\r
+<h3> Example 4: Debugging<a name="ex4"></a></h3>\r
+<pre>&lt;?\r
+\r
+<b>include</b>('adodb.inc.php');       # load code common to ADODB\r
+$<font color="#663300">conn</font> = &amp;ADONewConnection('access');    # create a connection\r
+$<font color="#663300">conn</font>->PConnect('northwind');   # connect to MS-Access, northwind db\r
+<font color="#000000">$<font color="#663300">shipto</font> = <b>$conn-&gt;qstr</b>(&quot;John's Old Shoppe&quot;);\r
+$<font color="#663300">sql</font> = &quot;insert into orders (customerID,EmployeeID,OrderDate,ShipName) &quot;;\r
+$<font color="#663300">sql</font> .= &quot;values ('ANATR',2,&quot;.$<font color="#663300">conn</font>-&gt;FormatDate(time()).&quot;,$shipto)&quot;;\r
+<b><font color="#336600">$<font color="#663300">conn</font>-&gt;debug = true;</font></b>\r
+<b>if</b> ($<font color="#663300">conn</font>->Execute($sql) <b>=== false</b>) <b>print</b> 'error inserting';</font>\r
+\r
+?&gt;\r
+</pre>\r
+<p>In the above example, we have turned on debugging by setting <b>debug = true</b>. \r
+ This will display the SQL statement before execution, and also show any error \r
+ messages. There is no need to call <font face="Courier New, Courier, mono"><a href="#errormsg">ErrorMsg</a>()</font> \r
+ in this case. For displaying the recordset, see the <font face="Courier New, Courier, mono"><a href="#exrs2html">rs2html</a>() \r
+ </font>example.</p>\r
+ <p>Also see the section on <a href=#errorhandling>Custom Error Handlers</a>.</p>\r
+<h3>Example 5: MySQL and Menus<a name="ex5"></a></h3>\r
+<p>Connect to MySQL database <i>agora</i>, and generate a &lt;select&gt; menu \r
+ from an SQL statement where the &lt;option&gt; captions are in the 1st column, \r
+ and the value to send back to the server is in the 2nd column.</p>\r
+<pre>&lt;?\r
+<b>include</b>('adodb.inc.php'); # load code common to ADODB\r
+$<font color="#663300">conn</font> = &amp;ADONewConnection('mysql');  # create a connection\r
+$<font color="#663300">conn</font>->PConnect('localhost','userid','','agora');# connect to MySQL, agora db\r
+<font color="#000000">$<font color="#663300">sql</font> = 'select CustomerName, CustomerID from customers';\r
+$<font color="#663300">rs</font> = $<font color="#663300">conn</font>->Execute($sql);\r
+<b>print</b> <b><font color="#336600">$<font color="#663300">rs</font>-&gt;GetMenu('GetCust','Mary Rosli');\r
+?&gt;</font></b></font></pre>\r
+<p>Here we define a menu named GetCust, with the menu option 'Mary Rosli' selected. \r
+ See <a href="#getmenu"><font face="Courier New, Courier, mono">GetMenu</font></a><font face="Courier New, Courier, mono">()</font>. \r
+ We also have functions that return the recordset as an array: <font face="Courier New, Courier, mono"><a href="#getarray">GetArray</a>()</font>, \r
+ and as an associative array with the key being the first column: <a href="#getassoc">GetAssoc</a>().</p>\r
+<h3>Example 6: Connecting to 2 Databases At Once<a name="ex6"></a></h3>\r
+<pre>&lt;?\r
+<b>include</b>('adodb.inc.php');     # load code common to ADODB\r
+$<font color="#663300">conn1</font> = &amp;ADONewConnection('mysql');  # create a mysql connection\r
+$<font color="#663300">conn2</font> = &amp;ADONewConnection('oracle');  # create a oracle connection\r
+\r
+$conn1-&gt;PConnect($server, $userid, $password, $database);\r
+$conn2-&gt;PConnect(false, $ora_userid, $ora_pwd, $tnsname);\r
+\r
+$conn1-&gt;Execute('insert ...');\r
+$conn2-&gt;Execute('update ...');\r
+?&gt;</pre>\r
+\r
+<h3>Example 7: Generating Update and Insert SQL<a name="ex7"></a></h3>\r
+ADODB 1.31 and later supports two new recordset functions: GetUpdateSQL( ) and \r
+GetInsertSQL( ). This allow you to perform a "SELECT * FROM table query WHERE...",\r
+make a copy of the $rs->fields, modify the fields, and then generate the SQL to\r
+update or insert into the table automatically.\r
+<p>\r
+We show how the functions can be used when\r
+accessing a table with the following fields: (ID, FirstName, LastName, Created).\r
+<p>\r
+Before these functions can be called, you need to initialize the recordset by\r
+performing a select on the table. Idea and code by Jonathan Younger jyounger@unilab.com.\r
+<p>\r
+<pre>&lt;?\r
+#==============================================\r
+# SAMPLE GetUpdateSQL() and GetInsertSQL() code\r
+#==============================================\r
+include('adodb.inc.php');\r
+include('tohtml.inc.php');\r
+\r
+#==========================\r
+# This code tests an insert\r
+\r
+$sql = "SELECT * FROM ADOXYZ WHERE id = -1"; \r
+# Select an empty record from the database \r
+\r
+$conn = &ADONewConnection("mysql");  # create a connection\r
+$conn->debug=1;\r
+$conn->PConnect("localhost", "admin", "", "test"); # connect to MySQL, testdb\r
+$rs = $conn->Execute($sql); # Execute the query and get the empty recordset\r
+\r
+$record = array(); # Initialize an array to hold the record data to insert\r
+\r
+# Set the values for the fields in the record\r
+$record["firstname"] = "Bob";\r
+$record["lastname"] = "Smith";\r
+$record["created"] = time();\r
+\r
+# Pass the empty recordset and the array containing the data to insert\r
+# into the GetInsertSQL function. The function will process the data and return\r
+# a fully formatted insert sql statement.\r
+$insertSQL = $conn->GetInsertSQL($rs, $record);\r
+\r
+$conn->Execute($insertSQL); # Insert the record into the database\r
+\r
+#==========================\r
+# This code tests an update\r
+\r
+$sql = "SELECT * FROM ADOXYZ WHERE id = 1"; \r
+# Select a record to update \r
+\r
+$rs = $conn->Execute($sql); # Execute the query and get the existing record to update\r
+\r
+$record = array(); # Initialize an array to hold the record data to update\r
+\r
+# Set the values for the fields in the record\r
+$record["firstname"] = "Caroline";\r
+$record["lastname"] = "Smith"; # Update Caroline's lastname from Miranda to Smith\r
+\r
+# Pass the single record recordset and the array containing the data to update\r
+# into the GetUpdateSQL function. The function will process the data and return\r
+# a fully formatted update sql statement with the correct WHERE clause.\r
+# If the data has not changed, no recordset is returned\r
+$updateSQL = $conn->GetUpdateSQL($rs, $record);\r
+\r
+$conn->Execute($updateSQL); # Update the record in the database\r
+$conn->Close();\r
+?>\r
+</pre>\r
+<h3>Example 8: Implementing Scrolling with Next and Previous<a name="ex8"></a></h3>\r
+<p>\r
+Code and idea by Iván Oliva. <p>\r
+We use the HTTP Get variable $next_page to keep track of what page to go next and\r
+ store the current page in the session variable $curr_page.\r
+<p>\r
+We call the connection object's PageExecute() function to generate the appropriate recordset, \r
+then use the recordset's AtFirstPage() and AtLastPage() functions to determine \r
+whether to display the next and previous buttons. \r
+\r
+<pre>\r
+&lt;?php\r
+include_once('adodb.inc.php');\r
+include_once('tohtml.inc.php');\r
+<b>session_register('curr_page');</b>\r
+\r
+$db = NewADOConnection('mysql');\r
+$db->Connect('localhost','root','','xphplens');\r
+<b>$num_of_rows_per_page = 10;\r
+$sql = 'select * from products';\r
+\r
+if (isset($HTTP_GET_VARS['next_page']))\r
+       $curr_page = $HTTP_GET_VARS['next_page'];\r
+if (empty($curr_page)) $curr_page = 1; ## at first page\r
+\r
+$rs = $db->PageExecute($sql, $num_of_rows_per_page, $curr_page);</b>\r
+if (!$rs) die('Query Failed');\r
+\r
+if (!$rs->EOF && (!$rs-><b>AtFirstPage</b>() || !$rs-><b>AtLastPage</b>())) {\r
+       if (!$rs-><b>AtFirstPage</b>()) {\r
+?>\r
+&lt;a href="&lt;?php echo $PHPSELF,'?next_page=',$rs-><b>AbsolutePage</b>() - 1 ?>">Previous page&lt;/a>\r
+&lt;?php\r
+       }\r
+       if (!$rs-><b>AtLastPage</b>()) {\r
+?>\r
+&lt;a href="&lt;?php echo $PHPSELF,'?next_page=',$rs-><b>AbsolutePage</b>() + 1 ?>">Next page&lt;/a>\r
+&lt;?php\r
+       }\r
+       rs2html($rs);\r
+}\r
+?>\r
+</pre>\r
+The above code can be found in the <i>testpaging.php</i> example included with this release.\r
+<p>\r
+<a name=errorhandling></a> \r
+<h2>Using Custom Error Handlers and PEAR_Error</h2>\r
+Apart from the old $con->debug = true; way of debugging, ADODB 1.50 onwards provides \r
+another way of handling errors using ADODB's configurable custom handlers. <p>\r
+ADODB provides two custom handlers which you can modify for your needs.\r
+The first one is in the <b>adodb-errorhandler.inc.php</b> file. This makes\r
+use of the standard PHP functions <a href=http://php.net/error_reporting>error_reporting</a>\r
+to control what error messages types to display,\r
+and <a href=http://php.net/trigger_error>trigger_error</a> which invokes the default\r
+PHP error handler.\r
+<p>\r
+Including the above file  will cause <i>trigger_error($errorstring,E_USER_ERROR)</i>\r
+to be called when Connect() or PConnect() fails, or a function that executes SQL statements such as\r
+ Execute() or SelectLimit() has an error. This file should be included before you create any \r
+ ADOConnection objects.<p>\r
+ If you define error_reporting(0), no errors will be shown. \r
+ If you set error_reporting(E_ALL), all errors will be displayed on the screen.\r
+ <pre>\r
+&lt;?php\r
+<b>error_reporting(E_ALL); # show any error messages triggered\r
+include('adodb-errorhandler.inc.php');</b>\r
+include('adodb.inc.php');\r
+include('tohtml.inc.php');\r
+$c = NewADOConnection('mysql');\r
+$c->PConnect('localhost','root','','northwind');\r
+$rs=$c->Execute('select * from productsz'); #invalid table productsz');\r
+if ($rs) $rs2html($rs);\r
+?>\r
+</pre>\r
+ <p>\r
+ If you want to log the error message, you can do so by defining the following optional\r
+  constants ADODB_ERROR_LOG_TYPE and ADODB_ERROR_LOG_DEST. ADODB_ERROR_LOG_TYPE is \r
+  the error log message type (see <a href=http://php.net/error_log>error_log</a>\r
+  in the PHP manual). In this case we set \r
+  it to 3, which means log to the file defined by the constant ADODB_ERROR_LOG_DEST.\r
+ <pre>\r
+&lt;?php\r
+<b>error_reporting(0); # do not echo any errors\r
+define('ADODB_ERROR_LOG_TYPE',3);\r
+define('ADODB_ERROR_LOG_DEST','C:\errors.log');\r
+include('adodb-errorhandler.inc.php');</b>\r
+include('adodb.inc.php');\r
+include('tohtml.inc.php');\r
+$c = NewADOConnection('mysql');\r
+$c->PConnect('localhost','root','','northwind');\r
+$rs=$c->Execute('select * from productsz'); #invalid table productsz');\r
+if ($rs) $rs2html($rs);\r
+?>\r
+</pre>\r
+The following message will be logged in the error.log file:\r
+<pre>\r
+(2001-10-28 14:20:38) mysql error: [1146: Table 'northwind.productsz' doesn't exist] in\r
+ EXECUTE("select * from productsz")\r
+</pre>\r
+The second error handler is <b>adodb-errorpear.inc.php</b>. \r
+This will create a PEAR_Error derived object whenever an error occurs. \r
+The last PEAR_Error object created can be retrieved using ADODB_Pear_Error().\r
+<pre>\r
+&lt;?php\r
+<b>include('adodb-errorpear.inc.php');</b>\r
+include('adodb.inc.php');\r
+include('tohtml.inc.php');\r
+$c = NewADOConnection('mysql');\r
+$c->PConnect('localhost','root','','northwind');\r
+$rs=$c->Execute('select * from productsz'); #invalid table productsz');\r
+if ($rs) $rs2html($rs);\r
+else {\r
+       <b>$e = ADODB_Pear_Error();\r
+       echo '&lt;p>',$e->message(),'&lt;/p>';</b>\r
+}\r
+?>\r
+</pre>\r
+You can use also a PEAR_Error derived class by defining the constant \r
+ADODB_PEAR_ERROR_CLASS before the adodb-errorpear.inc.php file is included. And instead\r
+of retrieving the error message yourself with $e->message, you can set the default error handler\r
+ in the beginning of the PHP script to PEAR_ERROR_DIE, which will cause an error message to be printed, \r
+ then halt script execution:\r
+<pre>\r
+include('PEAR.php');\r
+PEAR::setErrorHandling('PEAR_ERROR_DIE');\r
+</pre>\r
+<p>\r
+<a name=caching></a> \r
+<h2>Caching of Recordsets</h2>\r
+<p>ADODB now supports caching of recordsets using the  CacheExecute( ), \r
+CachePageExecute( ) and CacheSelectLimit( ) functions. There are similar to the\r
+non-cache functions, except that they take a new first parameter, $secs2cache.\r
+<p>\r
+  An example of use is the following: \r
+<pre>\r
+<b>include</b>('adodb.inc.php'); # load code common to ADODB\r
+$ADODB_CACHE_DIR = '/usr/adodb_cache';\r
+$<font color="#663300">conn</font> = &amp;ADONewConnection('mysql');  # create a connection\r
+$<font color="#663300">conn</font>->PConnect('localhost','userid','','agora');# connect to MySQL, agora db\r
+<font color="#000000">$<font color="#663300">sql</font> = 'select CustomerName, CustomerID from customers';\r
+$<font color="#663300">rs</font> = $<font color="#663300">conn</font>->CacheExecute(15,$sql);\r
+</font></pre>\r
+<font color="#000000"> The first parameter is the number of seconds to cache the \r
+query. Subsequent calls to that query will used the cached version stored in $ADODB_CACHE_DIR. \r
+To force a query and flush the cache, call CacheExecute() with the first parameter \r
+set to zero. Alternatively, use CacheFlush($sql) call.\r
+<p>Windows Note: flock() is buggy in PHP 4.0.5 and earlier on Windows. So we use \r
+  a non-blocking technique with rename(). \r
+<hr>\r
+<h1>Class Reference<a name="Ref"></a></h1>\r
+<p>Function parameters with [ ] around them are optional.</p>\r
+<h2>$ADODB_FETCH_MODE</h2>\r
+<p>This is a global variable that determines how arrays are retrieved by Execute( \r
+  ). You can change this variable between invocations of Execute( ) and the fetch \r
+  mode will be modified.</p>\r
+<p>The following constants are defined:</p>\r
+  </font>\r
+<p><font color="#000000">define('ADODB_FETCH_DEFAULT',0);<br>\r
+  define('ADODB_FETCH_NUM',1);<br>\r
+  define('ADODB_FETCH_ASSOC',2);<br>\r
+  define('ADODB_FETCH_BOTH',3); </font><font color="#000000"></font></p>\r
+<font color="#000000">\r
+<h2>ADOConnection<a name="ADOConnection"></a></h2>\r
+<p>Object that performs the connection to the database, executes SQL statements \r
+  and has a set of utility functions for standardising the format of SQL statements \r
+  for issues such as concatenation and date formats.</p>\r
+<hr>\r
+<h3>ADOConnection Fields</h3>\r
+<p><b>databaseType</b>: Name of the database system we are connecting to. Eg. \r
+  <b>odbc</b> or <b>mssql</b> or <b>mysql</b>.</p>\r
+<p><b>dataProvider</b>: The underlying mechanism used to connect to the database. \r
+  Normally set to <b>native</b>, unless using <b>odbc</b> or <b>ado</b>.</p>\r
+<p><b>host: </b>Name of server or data source name (DSN) to connect to.</p>\r
+<p><b>database</b>: Name of the database or to connect to. If ado is used, it \r
+  will hold the ado data provider.</p>\r
+<p><b>user</b>: Login id to connect to database. Password is not saved for security \r
+  reasons.</p>\r
+<p><b>raiseErrorFn</b>: Allows you to define an error handling function. \r
+See adodb-errorhandler.inc.php for an example.</p>\r
+<p><b>debug</b>: Set to <i>true</i> to make debug statements to appear.</p>\r
+<p><b>concat_operator</b>: Set to '+' or '||' normally. The operator used to concatenate \r
+  strings in SQL. Used by the <b><a href="#concat">Concat</a></b> function.</p>\r
+<p><b>fmtDate</b>: The format used by the <b><a href="#dbdate">DBDate</a></b> \r
+  function to send dates to the database. is '#Y-m-d#' for Microsoft Access, and \r
+  '\'Y-m-d\'' for MySQL.</p>\r
+<p><b>fmtTimeStamp: </b>The format used by the <b><a href="#dbtimestamp">DBTimeStamp</a></b> \r
+  function to send timestamps to the database. </p>\r
+<p><b>true</b>: The value used to represent true.Eg. '.T.'. for Foxpro, '1' for \r
+  Microsoft SQL.</p>\r
+<p><b>false: </b> The value used to represent false. Eg. '.F.'. for Foxpro, '0' \r
+  for Microsoft SQL.</p>\r
+<p><b>replaceQuote</b>: The string used to escape quotes. Eg. double single-quotes \r
+  for Microsoft SQL, and backslash-quote for MySQL. Used by <a href="#qstr">qstr</a>.</p>\r
+<p><b>autoCommit</b>: indicates whether automatic commit is enabled. Default is \r
+  true.</p>\r
+<p><b>charSet</b>: set the default charset to use. Currently only interbase supports \r
+  this. </p>\r
+<p><b>metaTablesSQL</b>: SQL statement to return a list of available tables. Eg. \r
+  <i>SHOW TABLES</i> in MySQL.</p>\r
+<p><b>genID</b>: The latest id generated by GenID() if supported by the database.</p>\r
+<hr>\r
+<h3>ADOConnection Main Functions</h3>\r
+<p><b>ADOConnection( )</b></p>\r
+<p>Constructor function. Do not call this directly. Use ADONewConnection( ) instead.</p>\r
+<p><b>Connect<a name="Connect"></a>($host,[$user],[$password],[$database])</b></p>\r
+<p>Non-persistent connect to data source or server $<b>host</b>, using userid \r
+  $<b>user </b>and password $<b>password</b>. If the server supports multiple \r
+  databases, connect to database $<b>database</b>. </p>\r
+ <p>Returns true/false depending on connection.</p>\r
+<p>ADO Note: If you are using a Microsoft ADO and not OLEDB, you can set the $database \r
+  parameter to the OLEDB data provider you are using.</p>\r
+<p>PostgreSQL: An alternative way of connecting to the database is to pass the \r
+  standard PostgreSQL connection string in the first parameter $host, and the \r
+  other parameters will be ignored.</p>\r
+<p>For Oracle and Oci8, the $host variable holds the optional ORACLE_HOME variable. The\r
+$database variable holds the TNSName to use. The following connection strings work:\r
+ <pre> $conn->Connect(false, 'scott', 'tiger', 'OracleSID');\r
+ $conn->Connect('server:1521', 'scott', 'tiger', 'OracleDB');</pre>\r
+<p>There are many examples of connecting to a database at \r
+<a href="http://php.weblogs.com/adodb">php.weblogs.com/adodb</a>, and in the \r
+testdatabases.inc.php file included in the release.</p>\r
+<p><b>PConnect<a name="PConnect"></a>($host,[$user],[$password],[$database])</b></p>\r
+<p>Persistent connect to data source or server $<b>host</b>, using userid $<b>user</b> \r
+  and password $<b>password</b>. If the server supports multiple databases, connect \r
+  to database $<b>database</b>.</p>\r
+<p>Returns true/false depending on connection. See Connect( ) above for more info.</p>\r
+<p><b>Execute<a name="Execute"></a>($sql,$inputarr=false)</b></p>\r
+<p>Execute SQL statement $<b>sql</b> and return derived class of ADORecordSet \r
+  if successful. Note that a record set is always returned on success, even if we are executing \r
+  an insert or update statement.</p>\r
+<p>Returns derived class of ADORecordSet. Eg. if connecting via mysql, then ADORecordSet_mysql \r
+  would be returned. False is returned if there was an error in executing the sql.</p>\r
+<p>The $inputarr parameter can be used for binding variables to parameters. Below \r
+  is an Oracle example:</p>\r
+<pre>\r
+ $conn->Execute("SELECT * FROM TABLE WHERE COND=:val", array('val'=> $val));\r
+ </pre>\r
+<p>Another example, using ODBC,which uses the ? convention:</p>\r
+<pre>\r
+  $conn->Execute("SELECT * FROM TABLE WHERE COND=?", array($val));\r
+</pre>\r
+<i>Binding variables</i><br>\r
+Variable binding speeds the compilation and caching of SQL statements, leading \r
+to higher performance. Currently Oracle and ODBC support variable binding. ODBC \r
+style ? binding is emulated in databases that do not support binding. \r
+<p> Variable binding in ODBC: \r
+<pre>\r
+$rs = $db->Execute('select * from table where val=?', array('10'));\r
+</pre>\r
+Variable binding in Oracle: \r
+<pre>\r
+$rs = $db->Execute('select name from table where val=:key', \r
+  array('key' => 10));\r
+</pre>\r
+<p><b>CacheExecute<a name="CacheExecute"></a>($secs2cache,$sql,$inputarr=false)</b></p>\r
+<p>Similar to Execute, except that the recordset is cached for $secs2cache seconds \r
+  in the $ADODB_CACHE_DIR directory. If CacheExecute() is called again with the \r
+  same parameters, same database, same userid, same password, and the cached recordset \r
+  has not expired, the cached recordset is returned. \r
+<pre>\r
+  include('adodb.inc.php'); \r
+  include('tohtml.inc.php');\r
+  $<b>ADODB_CACHE_DIR</b> = '/usr/local/adodbcache';\r
+  $conn = &ADONewConnection('mysql'); \r
+  $conn->PConnect('localhost','userid','password','database');\r
+  $rs = $conn-><b>CacheExecute</b>(15, 'select * from table'); # cache 15 secs\r
+  rs2html($rs); /* recordset to html table */  \r
+</pre>\r
+<p></p>\r
+<p> If multiple calls to CacheExecute() are made and the recordset is still cached, \r
+  the $secs2cache parameter does not prolong the time the recordset is cached \r
+  (it is ignored). Use CacheExecute() only with SELECT statements.</p>\r
+<p>Performance note: I have done some benchmarks and found that they vary so greatly \r
+  that it's better to talk about when caching is of benefit. When your database \r
+  server is <i>much slower </i>than your Web server or the database is <i>very \r
+  overloaded </i>then ADODB's caching is good because it reduces the load on your \r
+  database server. If your database server is lightly loaded or much faster than \r
+  your Web server, then caching could actually reduce performance. </p>\r
+<p><b>SelectLimit<a name="SelectLimit"></a>($sql,$numrows=-1,$offset=-1,$inputarr=false)</b></p>\r
+<p>Returns a recordset if successful. Returns false otherwise. Performs a select \r
+  statement, simulating PostgreSQL's SELECT statement, LIMIT $numrows OFFSET $offset \r
+  clause.</p>\r
+<p>In PostgreSQL, SELECT * FROM TABLE LIMIT 3 will return the first 3 records \r
+  only. The equivalent is <code>$connection->SelectLimit('SELECT * FROM TABLE',3)</code>. \r
+  This functionality is simulated for databases that do not possess this feature.</p>\r
+<p>And SELECT * FROM TABLE LIMIT 3 OFFSET 2 will return records 3, 4 and 5 (eg. \r
+  after record 2, return 3 rows). The equivalent in ADODB is <code>$connection->SelectLimit('SELECT \r
+  * FROM TABLE',3,2)</code>.</p>\r
+<p>Note that this is the <i>opposite</i> of MySQL's LIMIT clause. You can also \r
+  set <code>$connection->SelectLimit('SELECT * FROM TABLE',-1,10)</code> to get \r
+  rows 11 to the last row.</p>\r
+<p>The last parameter $inputarr is for databases that support variable binding \r
+  such as Oracle oci8. This substantially reduces SQL compilation overhead. Below \r
+  is an Oracle example:</p>\r
+<pre>\r
+ $conn->SelectLimit("SELECT * FROM TABLE WHERE COND=:val", 100,-1,array('val'=> $val));\r
+ </pre>\r
+<p>Ron Wilson reports that SelectLimit does not work with UNIONs and suggested \r
+  the following solution for mssql: \r
+<pre>\r
+>In addition, I found a way to structure the Select Union so that it will\r
+> work with the optimization in place.  It works under MS-SQL, don't know\r
+> about the others...  When updating the help file, you could use this as an\r
+> example of how to structure the SQL --\r
+<i>No it doesn't work with MySQL.</i>\r
+> \r
+> Change:\r
+>  Select column1 From table1\r
+>  Union\r
+>  Select column2 From table2\r
+> \r
+> To:\r
+>  Select * From (\r
+>   Select column1 From table1\r
+>   Union\r
+>   Select column2 From table2\r
+>   )\r
+>  As dummytable\r
+> \r
+> Ron\r
+\r
+</pre>\r
+<p><b>CacheSelectLimit<a name="CacheSelectLimit"></a>($secs2cache,$sql,$numrows=-1,$offset=-1,$inputarr=false)</b></p>\r
+<p>Similar to SelectLimit, except that the recordset returned is cached for $secs2cache \r
+  seconds in the $ADODB_CACHE_DIR directory. </p>\r
+<p><b>CacheFlush<a name="CacheFlush"></a>($sql)</b></p>\r
+<p>Flush (delete) any cached recordsets of the SQL statement $sql in $ADODB_CACHE_DIR.</p>\r
+<p><b>ErrorMsg<a name="ErrorMsg"></a>()</b></p>\r
+<p>Returns the last status or error message. This can return a string even if \r
+  no error occurs. Use ErrorNo to check if an error has occurred.</p>\r
+<p>Note: If <b>debug</b> is enabled, the SQL error message is always displayed \r
+  when the <b>Execute</b> function is called.</p>\r
+<p><b>ErrorNo<a name="errorno"></a>()</b></p>\r
+<p>Returns the last error number. Note that this is not supported by some databases \r
+  such as ODBC, and in this case returns 0.</p>\r
+<p><b>GenID<a name="genid"></a>($seqName = 'adodbseq')</b></p>\r
+<p>Generate a sequence number. Works for interbase, mysql, postgresql, oci8 drivers \r
+  currently. Uses $seqName as the name of the sequence. GenID() will automatically create\r
+  the sequence for you if it does not exist (provided the userid has permission to do so).</p>\r
+<p><b>UpdateBlob<a name="updateblob"></a>($table,$column,$val,$where,$blobtype='BLOB')</b></p>\r
+Allows you to store a blob (in $val) into $table into $column in a row at $where. \r
+The $blobtype is an optional parameter, only useful for oci8; legal values for \r
+oci8 are 'CLOB' and 'BLOB'. \r
+<p> Usage: \r
+<p> \r
+<pre>\r
+       $conn->Execute('INSERT INTO blobtable (id, blobcol) VALUES (1, null)');\r
+       $conn->UpdateBlob('blobtable','blobcol',$blobvalue,'id=1');\r
+</pre>\r
+<p> Returns true if succesful, false otherwise. Supported by MySQL, PostgreSQL, Oci8 \r
+  and Interbase drivers. Other drivers might work.</p>\r
+<p>Note that when an Interbase blob is retrieved using SELECT, it still needs to be decoded \r
+using $connection->DecodeBlob($blob); to derive the original value.\r
+<p><b>GetUpdateSQL<a name="getupdatesql"></a>(&$rs, $arrFields, $forceUpdate=false)</b></p>\r
+<p>Generate SQL to update a table given a recordset $rs, and the modified fields \r
+  of the array $arrFields (which must be an associative array holding the column \r
+  names and the new values) are compared with the current recordset. If $forceUpdate \r
+  is true, then we also generate the SQL even if $arrFields is identical to $rs-&gt;fields.    \r
+  Requires the recordset to be associative.</p>\r
+<p><b>GetInsertSQL<a name="getinsertsql"></a>(&$rs, $arrFields)</b></p>\r
+<p>Generate SQL to insert into a table given a recordset $rs. Requires the query \r
+  to be associative.</p>\r
+<b>PageExecute<a name="pageexecute"></a>($sql, $nrows, $page, $inputarr=false)</b> \r
+<p>Used for pagination of recordset. $page is 1-based. See <a href="#ex8">Example \r
+  8</a>.</p>\r
+</font> \r
+<p><font color="#000000"><b>CachePageExecute<a name="cachepageexecute"></a>($secs2cache, \r
+  $sql, $nrows, $page, $inputarr=false)</b> </font></p>\r
+<p><font color="#000000">Used for pagination of recordset. $page is 1-baed. See \r
+  <a href="#ex8">Example 8</a>. Caching version of PageExecute.</font></p>\r
+<font color="#000000"> \r
+<p></p>\r
+<p><b>Close<a name="Close"></a>( )</b></p>\r
+<p>Close the database connection. PHP4 proudly states that we no longer have to \r
+  clean up at the end of the connection because the reference counting mechanism \r
+  of PHP4 will automatically clean up for us.</p>\r
+<p><b>BeginTrans<a name="Begintrans"></a>( )</b></p>\r
+<p>Begin a transaction. Turns off autoCommit. Returns true if successful. Some \r
+  databases will always return false if transaction support is not available. \r
+  Interbase, Oracle and MSSQL support transactions. Note that transaction support \r
+  is not available for Microsoft ADO due to some bugs in PHP 4.02. Use the native \r
+  transaction support of your RDBMS. Any open transactions will be rolled back \r
+  when the connection is closed.</p>\r
+<p><b>CommitTrans<a name="CommitTrans"></a>( )</b></p>\r
+<p>End a transaction successfully. Returns true if successful. If the database \r
+  does not support transactions, will return true also as data is always committed. \r
+</p>\r
+<p><b>RollbackTrans<a name="RollbackTrans"></a>( )</b></p>\r
+<p>End a transaction, rollback all changes. Returns true if successful. If the \r
+  database does not support transactions, will return false as data is never rollbacked. \r
+</p>\r
+<hr>\r
+<h3>ADOConnection Utility Functions</h3>\r
+<p><b>BlankRecordSet<a name="blankrecordset"></a>([$queryid])</b></p>\r
+<p>Returns an empty recordset. This is useful if you require the use of some ADORecordSet \r
+  utility function such as UnixDate.</p>\r
+<p><b>Concat<a name="Concat"></a>($s1,$s2,....)</b></p>\r
+<p>Generates the sql string used to concatenate $s1, $s2, etc together. Uses the \r
+  string in the concat_operator field to generate the concatenation. Override \r
+  this function if a concatenation operator is not used, eg. MySQL.</p>\r
+<p>Returns the concatenated string.</p>\r
+<p><b>DBDate<a name="DBDate"></a>($date)</b></p>\r
+<p>Format the $<b>date</b> in the format the database accepts. Uses the fmtDate \r
+  field, which holds the format to use..</p>\r
+<p>Returns the date as a string.</p>\r
+<p><b>DBTimeStamp<a name="DBTimeStamp"></a>($ts)</b></p>\r
+<p>Format the timestamp $<b>ts</b> in the format the database accepts. Uses the \r
+  fmtTimeStamp field, which holds the format to use..</p>\r
+<p>Returns the timestamp as a string.</p>\r
+<p><b>qstr<a name="qstr"></a>($s,[$magic_quotes_enabled</b>=false]<b>)</b></p>\r
+<p>Quotes a string to be sent to the database. The $<b>magic_quotes_enabled</b> \r
+  parameter may look funny, but the idea is if you are quoting a string extracted \r
+  from a POST/GET variable, then pass get_magic_quotes_gpc() as the second parameter. \r
+  This will ensure that the variable is not quoted twice, once by <i>qstr</i> \r
+  and once by the <i>magic_quotes_gpc</i>.</p>\r
+<p>Eg.<font face="Courier New, Courier, mono"> $s = $db-&gt;qstr(HTTP_GET_VARS['name'],get_magic_quotes_gpc());</font></p>\r
+<p>Returns the quoted string.</p>\r
+<p><b>Affected_Rows<a name="Affected_Rows"></a>( )</b></p>\r
+<p>Returns the number of rows affected by a update or delete statement. Returns \r
+  false if function not supported.</p>\r
+<p>Only supported for MySQL, MSSQL and ODBC currently. This function might only \r
+  give accurate results if you perform it in a transaction if you are using persistent \r
+  connections. This is because the connection you are assigned for one Execute(&nbsp;) \r
+  might differ from the next Execute(&nbsp;).</p>\r
+<p><b>Insert_ID<a name="Inserted_ID"></a>( )</b></p>\r
+<p>Returns the last autonumbering ID inserted. Returns false if function not supported. \r
+</p>\r
+<p>Only supported for PostgreSQL, MySQL and MSSQL currently. PostgreSQL returns \r
+  the OID, which can change on a database reload. This function might only give \r
+  accurate results if you perform it in a transaction if you are using persistent \r
+  connections. This is because the connection you are assigned for one Execute(&nbsp;) \r
+  might differ from the next Execute(&nbsp;).</p>\r
+<p><b>MetaDatabases<a name="metadatabases"></a>()</b></p>\r
+<p>Returns a list of databases available on the server as an array. You have to \r
+  connect to the server first. Only available for ODBC, MySQL and ADO.</p>\r
+<p><b>MetaTables<a name="metatables"></a>()</b></p>\r
+<p>Returns an array of tables and views for the current database as an array. \r
+  The array should exclude system catalog tables if possible.</p>\r
+<p><b>MetaColumns<a name="metacolumns"></a>($table)</b></p>\r
+<p>Returns an array of ADOFieldObject's, one field object for every column of \r
+  $table. Currently Sybase does not recognise date types, and ADO cannot identify \r
+  the correct data type (so we default to varchar).. </p>\r
+<hr>\r
+<h2>ADORecordSet<a name="ADORecordSet"></a></h2>\r
+<p>When an SQL statement successfully is executed by <font face="Courier New, Courier, mono">ADOConnection-&gt;Execute($sql),</font>an \r
+  ADORecordSet object is returned. This object contains a virtual cursor so we \r
+  can move from row to row, functions to obtain information about the columns \r
+  and column types, and helper functions to deal with formating the results to \r
+  show to the user.</p>\r
+<h3>ADORecordSet Fields</h3>\r
+<p><b>fields: </b>Array containing the current row. This is not associative, but \r
+  is an indexed array from 0 to columns-1. See also the function <b><a href="#fields">Fields</a></b>, \r
+  which behaves like an associative array.</p>\r
+<p><b>dataProvider</b>: The underlying mechanism used to connect to the database. \r
+  Normally set to <b>native</b>, unless using <b>odbc</b> or <b>ado</b>.</p>\r
+<p><b>blobSize</b>: Maximum size of a char, string or varchar object before it \r
+  is treated as a Blob (Blob's should be shown with textarea's). See the <a href="#metatype">MetaType</a> \r
+  function.</p>\r
+<p><b>sql</b>: Holds the sql statement used to generate this record set.</p>\r
+<p><b>canSeek</b>: Set to true if Move( ) function works.</p>\r
+<p><b>EOF</b>: True if we have scrolled the cursor past the last record.</p>\r
+<h3>ADORecordSet Functions</h3>\r
+<p><b>ADORecordSet( )</b></p>\r
+<p>Constructer. Normally you never call this function yourself.</p>\r
+<p><b>GetAssoc<a name="GetAssoc"></a>([$force_array])</b></p>\r
+<p>Generates an associative array from the recordset if the number of columns \r
+  is greater than 2. The array is generated from the current cursor position till \r
+  EOF. The first column of the recordset becomes the key to the rest of the array. \r
+  If the columns is equal to two, then the key directly maps to the value unless \r
+  $force_array is set to true, when an array is created for each key. Inspired \r
+  by PEAR's getAssoc.</p>\r
+<p>Example:</p>\r
+<p>We have the following data in a recordset:</p>\r
+<p>row1: Apple, Fruit, Edible<br>\r
+  row2: Cactus, Plant, Inedible<br>\r
+  row3: Rose, Flower, Edible</p>\r
+<p>GetAssociation will generate the following associative array:</p>\r
+<p>Apple =&gt; [Fruit, Edible]<br>\r
+  Cactus =&gt; [Plant, Inedible]<br>\r
+  Rose =&gt; [Flower,Edible]</p>\r
+<p>Returns:</p>\r
+<p>The associative array, or false if an error occurs.</p>\r
+<p><b>GetArray<a name="GetArray"></a>([$number_of_rows])</b></p>\r
+<p>Generate an array from the current cursor position, indexed from 0 to $number_of_rows \r
+  - 1. If $number_of_rows is undefined, till EOF.</p>\r
+<p><b>GetRows<a name="GetRows"></a>([$number_of_rows])</b></p>\r
+<p>Synonym for GetArray() for compatibility with Microsoft ADO.</p>\r
+<p> <b>GetMenu<a name="GetMenu"></a>($name, [$default_str=''], [$blank1stItem=true], \r
+  [$multiple_select=false], [$size=0], [$moreAttr=''])</b></p>\r
+<p>Generate a HTML menu (&lt;select&gt;&lt;option&gt;&lt;option&gt;&lt;/select&gt;). \r
+  The first column of the recordset (fields[0]) will hold the string to display \r
+  in the option tags. If the recordset has more than 1 column, the second column \r
+  (fields[1]) is the value to send back to the web server.. The menu will be given \r
+  the name $<i>name</i>. \r
+<p> If $<i>default_str</i> is defined, then if $<i>default_str</i> == fields[0], \r
+  that field is selected. If $<i>blank1stItem</i> is true, the first option is \r
+  empty. $<i>Default_str</i> can be array for a multiple select listbox.</p>\r
+<p>To get a listbox, set the $<i>size</i> to a non-zero value (or pass $default_str \r
+  as an array). If $<i>multiple_select</i> is true then a listbox will be generated \r
+  with $<i>size</i> items (or if $size==0, then 5 items) visible, and we will \r
+  return an array to a server. Lastly use $<i>moreAttr </i> to add additional \r
+  attributes such as javascript or styles. </p>\r
+<p>Menu Example 1: <code>GetMenu('menu1','A',true)</code> will generate a menu: \r
+  <select name='menu1'>\r
+    <option> \r
+    <option value=1 selected>A \r
+    <option value=2>B \r
+    <option value=3>C \r
+  </select>\r
+  for the data (A,1), (B,2), (C,3). Also see <a href="#ex5">example 5</a>.</p>\r
+<p>Menu Example 2: For the same data, <code>GetMenu('menu1',array('A','B'),false)</code> \r
+  will generate a menu with both A and B selected: <br>\r
+  <select name='menu1' multiple size=3>\r
+    <option value=1 selected>A \r
+    <option value=2 selected>B \r
+    <option value=3>C \r
+  </select>\r
+<p> <b>GetMenu2<a name="GetMenu2"></a>($name, [$default_str=''], [$blank1stItem=true], \r
+  [$multiple_select=false], [$size=0], [$moreAttr=''])</b></p>\r
+<p>This is nearly identical to GetMenu, except that the $<i>default_str</i> is \r
+  matched to fields[1] (the option values).</p>\r
+<p>Menu Example 3: Given the data in menu example 2, <code>GetMenu2('menu1',array('1','2'),false)</code> \r
+  will generate a menu with both A and B selected in menu example 2, but this \r
+  time the selection is based on the 2nd column, which holds the values to return \r
+  to the Web server. \r
+<p><b>UserDate<a name="UserDate"></a>($str, [$fmt])</b></p>\r
+<p>Converts the date string $<b>str</b> to another format.UserDate calls UnixDate \r
+  to parse $<b>str</b>, and $<b>fmt</b> defaults to Y-m-d if not defined.</p>\r
+<p><b>UserTimeStamp<a name="UserTimeStamp"></a>($str, [$fmt])</b></p>\r
+<p>Converts the timestamp string $<b>str</b> to another format. UserTimeStamp \r
+  calls UnixTimeStamp to parse $<b>str</b>, and $<b>fmt</b> defaults to Y-m-d \r
+  H:i:s if not defined.</p>\r
+<p><b>UnixDate<a name="unixdate"></a>($str)</b></p>\r
+<p>Parses the date string $<b>str</b> and returns it in unix mktime format (eg. \r
+  a number indicating the seconds after January 1st, 1970). Expects the date to \r
+  be in Y-m-d h:i:s format, except for Sybase and Microsoft SQL Server, where \r
+  M d Y is also accepted (the 3 letter month strings are controlled by a global \r
+  array, which might need localisation).</p>\r
+<p><b>UnixTimeStamp<a name="unixtimestamp"></a>($str)</b></p>\r
+<p>Parses the timestamp string $<b>str</b> and returns it in unix mktime format \r
+  (eg. a number indicating the seconds after January 1st, 1970). Expects the date \r
+  to be in Y-m-d H:i:s format, except for Sybase and Microsoft SQL Server, where \r
+  M d Y h:i:sA is also accepted (the 3 letter month strings are controlled by \r
+  a global array, which might need localisation)..</p>\r
+<p><b>MoveNext<a name="MoveNext"></a>( )</b></p>\r
+<p>Move the internal cursor to the next row. The <b>fields</b> array is automatically \r
+  updated. Return false if unable to do so, otherwise true.. </p>\r
+<p><b>Move<a name="Move"></a>($to)</b></p>\r
+<p>Moves the internal cursor to a specific row $<b>to</b>. Rows are zero-based \r
+  eg. 0 is the first row. The <b>fields</b> array is automatically updated. For \r
+  databases that do not support scrolling internally, ADODB will simulate forward \r
+  scrolling. Some databases do not support backward scrolling. If the $<b>to</b> \r
+  position is after the EOF, $<b>to</b> will move to the end of the RecordSet \r
+  for most databases. Some obscure databases using odbc might not behave this \r
+  way.</p>\r
+<p>Note: This function uses <i>absolute positioning</i>, unlike Microsoft's ADO.</p>\r
+<p>Returns true or false. If false, the internal cursor is not moved in most implementations, \r
+  so AbsolutePosition( ) will return the last cursor position before the Move( \r
+  ). </p>\r
+<p><b>MoveFirst<a name="MoveFirst"></a>()</b></p>\r
+<p>Internally calls Move(0). Note that some databases do not support this function.</p>\r
+<p><b>MoveLast<a name="MoveLast"></a>()</b></p>\r
+<p>Internally calls Move(RecordCount()-1). Note that some databases do not support \r
+  this function.</p>\r
+<p><b>GetRowAssoc</b><a name="getrowassoc"></a>($toUpper=true)</p>\r
+<p>Returns an associative array containing the current row. The keys to the array \r
+  are the column names. The column names are upper-cased for easy access. To get \r
+  the next row, you will still need to call MoveNext(). </p>\r
+<p>For example:<br>\r
+  Array ( [ID] => 1 [FIRSTNAME] => Caroline [LASTNAME] => Miranda [CREATED] => \r
+  2001-07-05 ) </p>\r
+</font>\r
+<p><font color="#000000"><b>AbsolutePage<a name="absolutepage"></a>($page=-1) </b></font></p>\r
+<p>Returns the current page. Requires PageExecute()/CachePageExecute() to be called. See <a href=#ex8>Example 8</a>.</p>\r
+<font color="#000000"> \r
+<p><b>AtFirstPage<a name="AtFirstPage">($status='')</a></b></p>\r
+<p>Returns true if at first page (1-based). Requires PageExecute()/CachePageExecute() to be called. See <a href=#ex8>Example 8</a>.</p>\r
+<p><b>AtLastPage<a name="AtLastPage">($status='')</a></b></p>\r
+<p>Returns true if at last page (1-based). Requires PageExecute()/CachePageExecute() to be called. See <a href=#ex8>Example 8</a>.</p>\r
+<p><b>Fields</b><a name="fields"></a>(<b>$colname</b>)</p>\r
+<p>Some database extensions (eg. MySQL) return arrays that are both associative \r
+  and indexed if you use the native extensions. GetRowAssoc() does not return \r
+  arrays that combine associative and indexed elements.</p>\r
+<p>Returns the value of the associated column $<b>colname</b> for the current \r
+  row. The column name is case-insensitive.</p>\r
+<p><b>FetchField<a name="FetchField"></a>($column_number)</b></p>\r
+<p>Returns an object containing the <b>name</b>, <b>type</b> and <b>max_length</b> \r
+  of the associated field. If the max_length cannot be determined reliably, it \r
+  will be set to -1. The column numbers are zero-based. See <a href="#ex2">example \r
+  2.</a></p>\r
+<p><b>FieldCount<a name="FieldCount"></a>( )</b></p>\r
+<p>Returns the number of fields (columns) in the record set.</p>\r
+<p><b>RecordCount<a name="RecordCount"></a>( )</b></p>\r
+<p>Returns the number of rows in the record set. Note that some databases do not \r
+  support this, and will return -1. RowCount is a synonym for RecordCount.</p>\r
+<p>The following databases are known to return -1. Oci8, Oracle, Interbase.</p>\r
+<p><b>FetchObject<a name="FetchObject"></a>($toupper=true)</b></p>\r
+<p>Returns the current row as an object. If you set $toupper to true, then the \r
+  object fields are set to upper-case. Note: The newer FetchNextObject() is the \r
+  recommended way of accessing rows as objects. See below.</p>\r
+<p><b>FetchNextObject<a name="FetchNextObject"></a>($toupper=true)</b></p>\r
+<p>Gets the current row as an object and moves to the next row automatically. \r
+  Returns false if at end-of-file. If you set $toupper to true, then the object \r
+  fields are set to upper-case.</p>\r
+<pre>\r
+$rs = $db->Execute('select firstname,lastname from table');\r
+if ($rs) {\r
+       while ($o = $rs->FetchNextObject()) {\r
+               print "$o->FIRSTNAME, $o->LASTNAME&lt;BR>";\r
+       }\r
+}\r
+</pre>\r
+<p>There is some trade-off in speed in using FetchNextObject(). If performance \r
+  is important, you should access rows with the <code>fields[]</code> array. \r
+<p> \r
+<p><b>CurrentRow<a name="CurrentRow"></a>( )</b></p>\r
+<p>Returns the current row of the record set. 0 is the first row.</p>\r
+<p><b>AbsolutePosition<a name="abspos"></a>( )</b></p>\r
+<p>Synonym for <b>CurrentRow</b> for compatibility with ADO. Returns the current \r
+  row of the record set. 0 is the first row.</p>\r
+<p><b>MetaType<a name="MetaType"></a>($nativeDBType[,$field_max_length],[$fieldobj])</b></p>\r
+<p>Determine what <i>generic</i> meta type a database field type is given its \r
+  native type $<b>nativeDBType</b> and the length of the field $<b>field_max_length</b>. \r
+  Note that field_max_length can be -1 if it is not known. The field object returned \r
+  by the database driver can be passed in $<b>fieldobj</b>. This is useful for \r
+  databases such as <i>mysql</i> which has additional properties in the field \r
+  object such as <i>primary_key</i>.</p>\r
+<p>Uses the field <b>blobSize</b> and compares it with $<b>field_max_length</b> \r
+  to determine whether the character field is actually a blob.</p>\r
+<p>Returns:</p>\r
+<ul>\r
+  <li><b>C</b>: Character fields that should be shown in a &lt;input type=&quot;text&quot;&gt; \r
+    tag. </li>\r
+  <li><b>B</b>: Blob, or large text fields that should be shown in a &lt;textarea&gt;</li>\r
+  <li><b>D</b>: Date field</li>\r
+  <li><b>T</b>: Timestamp field</li>\r
+  <li><b>L</b>: Logical field (boolean or bit-field)</li>\r
+  <li><b>N</b>: Numeric field. Includes decimal, numeric, floating point, and \r
+    real. </li>\r
+  <li><b>I</b>: Integer field. </li>\r
+  <li><b>R</b>: Counter or Autoincrement field. Must be numeric.</li>\r
+</ul>\r
+<p><b>Close( )<a name="rsclose"></a></b></p>\r
+<p>Close the recordset.</p>\r
+<hr>\r
+<h3>function rs2html<a name="rs2html"></a>($adorecordset,[$tableheader_attributes], \r
+  [$col_titles])</h3>\r
+<p>This is a standalone function (rs2html = recordset to html) that is similar \r
+  to PHP's <i>odbc_result_all</i> function, it prints a ADORecordSet, $<b>adorecordset</b> \r
+  as a HTML table. $<b>tableheader_attributes</b> allow you to control the table \r
+  <i>cellpadding</i>, <i>cellspacing</i> and <i>border</i> attributes. Lastly \r
+  you can replace the database column names with your own column titles with the \r
+  array $<b>col_titles</b>. This is designed more as a quick debugging mechanism, \r
+  not a production table recordset viewer.</p>\r
+<p>You will need to include the file <i>tohtml.inc.php</i>.</p>\r
+<p>Example of rs2html:<b><font color="#336600"><a name="exrs2html"></a></font></b></p>\r
+<pre><b><font color="#336600">&lt;?\r
+include('tohtml.inc.php')</font></b>; # load code common to ADODB \r
+<b>include</b>('adodb.inc.php'); # load code common to ADODB \r
+$<font color="#663300">conn</font> = &amp;ADONewConnection('mysql');   # create a connection \r
+$<font color="#663300">conn</font>->PConnect('localhost','userid','','agora');# connect to MySQL, agora db\r
+<font color="#000000">$<font color="#663300">sql</font> = 'select CustomerName, CustomerID from customers'; \r
+$<font color="#663300">rs</font>   = $<font color="#663300">conn</font>->Execute($sql); \r
+<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>'));\r
+?&gt;</b></font></pre>\r
+<hr>\r
+<h3>Differences Between this ADODB library and Microsoft ADO<a name="adodiff"></a></h3>\r
+<ol>\r
+  <li>ADODB only supports recordsets created by a connection object. Recordsets \r
+    cannot be created independently.</li>\r
+  <li>ADO properties are implemented as functions in ADODB. This makes it easier \r
+    to implement any enhanced ADO functionality in the future.</li>\r
+  <li>ADODB's <font face="Courier New, Courier, mono">ADORecordSet-&gt;Move()</font> \r
+    uses absolute positioning, not relative. Bookmarks are not supported.</li>\r
+  <li><font face="Courier New, Courier, mono">ADORecordSet-&gt;AbsolutePosition() \r
+    </font>cannot be used to move the record cursor.</li>\r
+  <li>ADO Parameter objects are not supported.</li>\r
+  <li>Recordset properties for paging records are available, but implemented as in <a href=#ex8>Example 8</a>.</li>\r
+</ol>\r
+<hr>\r
+<h1>Database Driver Guide<a name="DriverGuide"></a></h1>\r
+<p>This describes how to create a class to connect to a new database. To ensure \r
+  there is no duplication of work, kindly email me at jlim@natsoft.com.my if you \r
+  decide to create such a class.</p>\r
+<p>First decide on a name in lower case to call the database type. Let's say we \r
+  call it xbase. </p>\r
+<p>Then we need to create two classes ADOConnection_xbase and ADORecordSet_xbase \r
+  in the file adodb-xbase.inc.php.</p>\r
+<p>The simplest form of database driver is an adaptation of an existing ODBC driver. \r
+  Then we just need to create the class <i>ADOConnection_xbase extends ADOConnection_odbc</i> \r
+  to support the new <b>date</b> and <b>timestamp</b> formats, the <b>concatenation</b> \r
+  operator used, <b>true</b> and <b>false</b>. For the<i> ADORecordSet_xbase extends \r
+  ADORecordSet_odbc </i>we need to change the <b>MetaType</b> function. See<b> \r
+  adodb-vfp.inc.php</b> as an example.</p>\r
+<p>More complicated is a totally new database driver that connects to a new PHP \r
+  extension. Then you will need to implement several functions. Fortunately, you \r
+  do not have to modify most of the complex code. You only need to override a \r
+  few stub functions. See <b>adodb-mysql.inc.php</b> for example.</p>\r
+<p>The default date format of ADODB internally is YYYY-MM-DD (Ansi-92). All dates \r
+  should be converted to that format when passing to an ADODB date function. See \r
+  Oracle for an example how we use ALTER SESSION to change the default date format \r
+  in _pconnect _connect.</p>\r
+<p><b>ADOConnection Functions to Override</b></p>\r
+<p>Defining a constructor for your ADOConnection derived function is optional. \r
+  There is no need to call the base class constructor.</p>\r
+<p>_<b>connect</b>: Low level implementation of Connect. Returns true or false. \r
+  Should set the _<b>connectionID</b>.</p>\r
+<p>_<b>pconnect:</b> Low level implemention of PConnect. Returns true or false. \r
+  Should set the _<b>connectionID</b>.</p>\r
+<p>_<b>query</b>: Execute a query. Returns the queryID, or false.</p>\r
+<p>_<b>close: </b>Close the connection -- PHP should clean up all recordsets. \r
+</p>\r
+<p><b>ErrorMsg</b>: Stores the error message in the private variable _errorMsg. \r
+</p>\r
+<p>The ADOConnection functions BeginTrans( ), CommitTrans( ), RollbackTrans( ) \r
+  are reserved for future expansion.</p>\r
+<p><b>ADOConnection Fields to Set</b></p>\r
+<p>_<b>bindInputArray</b>: Set to true if binding of parameters for SQL inserts \r
+  and updates is allowed using ?, eg. as with ODBC.</p>\r
+<p><b>fmtDate</b></p>\r
+<p><b>fmtTimeStamp</b></p>\r
+<p><b>true</b></p>\r
+<p><b>false</b></p>\r
+<p><b>concat_operator</b></p>\r
+<p><b>replaceQuote</b></p>\r
+<p><b>hasLimit</b> support SELECT * FROM TABLE LIMIT 10 of MySQL.</p>\r
+<p><b>hasTop</b> support Microsoft style SELECT TOP 10 * FROM TABLE.</p>\r
+<p><b>ADORecordSet Functions to Override</b></p>\r
+<p>You will need to define a constructor for your ADORecordSet derived class that \r
+  calls the parent class constructor.</p>\r
+<p><b>FetchField: </b> as documented above in ADORecordSet</p>\r
+<p>_<b>initrs</b>: low level initialization of the recordset: setup the _<b>numOfRows</b> \r
+  and _<b>numOfFields</b> fields -- called by the constructor.</p>\r
+<p>_<b>seek</b>: seek to a particular row. Do not load the data into the fields \r
+  array. This is done by _fetch. Returns true or false. Note that some implementations \r
+  such as Interbase do not support seek. Set canSeek to false.</p>\r
+<p>_<b>fetch</b>: fetch a row using the database extension function and then move \r
+  to the next row. Sets the <b>fields</b> array. If the parameter $ignore_fields \r
+  is true then there is no need to populate the <b>fields</b> array, just move \r
+  to the next row. then Returns true or false.</p>\r
+<p>_<b>close</b>: close the recordset</p>\r
+<p><b>Fields</b>: If the array row returned by the PHP extension is not an associative \r
+  one, you will have to override this. See adodb-odbc.inc.php for an example. \r
+  For databases such as MySQL and MSSQL where an associative array is returned, \r
+  there is no need to override this function.</p>\r
+<p><b>ADOConnection Fields to Set</b></p>\r
+<p>canSeek: Set to true if the _seek function works.</p>\r
+<h2>ToDo:</h2>\r
+<p>See the <a href=http:#php.weblogs.com/adodb-todo-roadmap>RoadMap</a> article.</p>\r
+</font>\r
+</body>\r
+</html>\r
diff --git a/libraries/adodb/readme.txt b/libraries/adodb/readme.txt
new file mode 100755 (executable)
index 0000000..62cd89a
--- /dev/null
@@ -0,0 +1,57 @@
+>> ADODB Library for PHP4\r
+\r
+(c) 2000, 2001 John Lim (jlim@natsoft.com.my) (jlim@natsoft.com.my)\r
+\r
+Released under both BSD and GNU Lesser GPL library license. \r
+This means you can use it in proprietary products.\r
\r
\r
+>> Introduction\r
+\r
+PHP's database access functions are not standardised. This creates a \r
+need for a database class library to hide the differences between the \r
+different databases (encapsulate the differences) so we can easily \r
+switch databases.\r
+\r
+We currently support MySQL, Interbase, Sybase, PostgreSQL, Oracle, \r
+Microsoft SQL server,  Foxpro ODBC, Access ODBC, generic ODBC and \r
+Microsoft's ADO. We hope more people will contribute drivers to support \r
+other databases.\r
+\r
+\r
+>> Documentation and Examples\r
+\r
+Refer to readme.htm for full documentation and examples. There is also a \r
+tutorial tute.htm that contrasts ADODB code with mysql code.\r
+\r
+\r
+>>> Files\r
+Adodb.inc.php is the main file. You need to include only this file.\r
+\r
+Adodb-*.inc.php are the database specific driver code.\r
+\r
+Test.php contains a list of test commands to exercise the class library.\r
+\r
+Adodb-session.php is the PHP4 session handling code.\r
+\r
+Testdatabases.inc.php contains the list of databases to apply the tests on.\r
+\r
+Benchmark.php is a simple benchmark to test the throughput of a simple SELECT \r
+statement for databases described in testdatabases.inc.php. The benchmark\r
+tables are created in test.php.\r
+\r
+readme.htm is the main documentation.\r
+\r
+tute.htm is the tutorial.\r
+\r
+\r
+>> More Info\r
+\r
+For more information, including installation see readme.htm\r
+\r
+\r
+>> Feature Requests and Bug Reports\r
+\r
+Email to jlim@natsoft.com.my \r
+\r
\ No newline at end of file
diff --git a/libraries/adodb/server.php b/libraries/adodb/server.php
new file mode 100755 (executable)
index 0000000..9b58d26
--- /dev/null
@@ -0,0 +1,92 @@
+<?php\r
+/** \r
+ * (c)2001 John Lim (jlim@natsoft.com.my). All rights reserved.\r
+ * Released under both BSD license and Lesser GPL library license. \r
+  Whenever there is any discrepancy between the two licenses, \r
+  the BSD license will take precedence. \r
+ */\r
\r
+/* Documentation on usage is at http://php.weblogs.com/adodb_csv\r
+ *\r
+ * Legal query string parameters:\r
+ * \r
+ * sql = holds sql string\r
+ * nrows = number of rows to return \r
+ * offset = skip offset rows of data\r
+ * \r
+ * example:\r
+ *\r
+ * http://localhost/php/server.php?select+*+from+table&nrows=10&offset=2\r
+ */\r
+\r
+\r
+/* \r
+ * Define the IP address you want to accept requests from \r
+ * as a security measure. If blank we accept anyone promisciously!\r
+ */\r
+$ACCEPTIP = '';\r
+\r
+/*\r
+ * Connection parameters\r
+ */\r
+$driver = 'mysql';\r
+$host = 'mangrove'; // DSN for odbc\r
+$uid = 'root';\r
+$pwd = '';\r
+$database = 'xphplens';\r
+\r
+/*============================ DO NOT MODIFY BELOW HERE =================================*/\r
+// $sep must match csv2rs() in adodb.inc.php\r
+$sep = ' :::: ';\r
+\r
+include('./adodb.inc.php');\r
+\r
+function err($s)\r
+{\r
+       die('**** '.$s.' ');\r
+}\r
+\r
+// undo stupid magic quotes\r
+function undomq(&$m) \r
+{\r
+       if (get_magic_quotes_gpc()) {\r
+               // undo the damage\r
+               $m = str_replace('\\\\','\\',$m);\r
+               $m = str_replace('\"','"',$m);\r
+               $m = str_replace('\\\'','\'',$m);\r
+               \r
+       }\r
+       return $m;\r
+}\r
+\r
+///////////////////////////////////////// DEFINITIONS\r
+\r
+\r
+if (isset($REMOTE_ADDR)) $remote = $REMOTE_ADDR; // Apache\r
+else $remote = $HTTP_SERVER_VARS["REMOTE_ADDR"]; // IIS\r
\r
+if (empty($HTTP_GET_VARS['sql'])) err('No SQL');\r
+\r
+if (!empty($ACCEPTIP))\r
+ if ($remote != '127.0.0.1' && $remote != $ACCEPTIP) \r
+       err("Unauthorised client: '$remote'");\r
+\r
+\r
+$conn = &ADONewConnection($driver);\r
+if (!$conn->Connect($host,$uid,$pwd,$database)) err($conn->ErrorNo(). $sep . $conn->ErrorMsg());\r
+$sql = undomq($HTTP_GET_VARS['sql']);\r
+\r
+if (isset($HTTP_GET_VARS['nrows'])) {\r
+       $nrows = $HTTP_GET_VARS['nrows'];\r
+       $offset = isset($HTTP_GET_VARS['offset']) ? $HTTP_GET_VARS['offset'] : -1;\r
+       $rs = $conn->SelectLimit($sql,$nrows,$offset);\r
+} else \r
+       $rs = $conn->Execute($sql);\r
+if ($rs){ \r
+       //$rs->timeToLive = 1;\r
+       print rs2csv($rs,$conn,$sql);\r
+       $rs->Close();\r
+} else\r
+       err($conn->ErrorNo(). $sep .$conn->ErrorMsg());\r
+\r
+?>
\ No newline at end of file
diff --git a/libraries/adodb/test.php b/libraries/adodb/test.php
new file mode 100755 (executable)
index 0000000..f7b3fe6
--- /dev/null
@@ -0,0 +1,436 @@
+<?php\r
+/* \r
+V1.53 13 Nov 2001 (c) 2000, 2001 John Lim (jlim@natsoft.com.my). All rights reserved.\r
+  Released under both BSD license and Lesser GPL library license. \r
+  Whenever there is any discrepancy between the two licenses, \r
+  the BSD license will take precedence. \r
+  Set tabs to 4 for best viewing.\r
+    \r
+  Latest version is available at http://php.weblogs.com/\r
+*/\r
+       \r
+?><html>\r
+<title>ADODB TEST</title>\r
+<body bgcolor=white>\r
+<H1>ADODB Test</H1>\r
+\r
+This script tests the following databases: Interbase, Oracle, Visual FoxPro, Microsoft Access (ODBC and ADO), MySQL, MSSQL (ODBC, native, ADO). \r
+There is also support for Sybase, PostgreSQL.</p>\r
+For the latest version of ADODB, visit <a href=http://php.weblogs.com/ADODB>php.weblogs.com</a>.</p>\r
+<?php\r
+\r
+// Set the following control flags to true/false to enable testing for a particular database.\r
+\r
+//$testoracle = true;\r
+//$testibase = true;\r
+\r
+$testaccess = true;\r
+$testpostgres = true;\r
+$testmysql = true;\r
+//$testmssql = true;\r
+$testvfp = true;\r
+//$testado = true;\r
+\r
+error_reporting(63);\r
+\r
+set_time_limit(240); // increase timeout\r
+\r
+include("./tohtml.inc.php");\r
+include("./adodb.inc.php");            \r
+\r
+// the table creation code is specific to the database, so we allow the user \r
+// to define their own table creation stuff\r
+function testdb(&$db,$createtab="create table ADOXYZ (id int, firstname char(24), lastname char(24), created date)")\r
+{\r
+GLOBAL $ADODB_vers,$ADODB_CACHE_DIR;\r
+?>     <form>\r
+       </p>\r
+       <table width=100% ><tr><td bgcolor=beige>&nbsp;</td></tr></table>\r
+       </p>\r
+<?php  \r
+       $create =false;\r
+       $ADODB_CACHE_DIR = dirname(TempNam('/tmp','testadodb'));\r
+       \r
+       $db->debug = false;\r
+       \r
+       $phpv = phpversion();\r
+       print "<h3>ADODB Version: $ADODB_vers Host: <i>$db->host</i> &nbsp; Database: <i>$db->database</i> &nbsp; PHP: $phpv</h3>";\r
+       $e = error_reporting(63-E_WARNING);\r
+       print "<p>Testing bad connection. Ignore following error msgs:<br>";\r
+       $db2 = ADONewConnection();\r
+       $rez = $db2->Connect("bad connection");\r
+       $err = $db2->ErrorMsg();\r
+       error_reporting($e);\r
+       \r
+       print "<i>Error='$err'</i></p>";\r
+       if ($rez) print "<b>Cannot check if connection failed.</b> The Connect() function returned true.</p>";\r
+       \r
+       $rs=$db->Execute('select * from adoxyz');\r
+       if($rs === false) $create = true;\r
+       else $rs->Close();\r
+       \r
+       //if ($db->databaseType !='vfp') $db->Execute("drop table ADOXYZ");\r
+        \r
+       if ($create) {\r
+                if ($db->databaseType == 'ibase') {\r
+                        print "<b>Please create the following table for testing:</b></p>$createtab</p>";\r
+                        return;\r
+                } else\r
+                        $db->Execute($createtab);\r
+        }\r
+       \r
+       $rs = &$db->Execute("delete from ADOXYZ"); // some ODBC drivers will fail the drop so we delete\r
+       if ($rs) {\r
+               if(! $rs->EOF)print "<b>Error: </b>RecordSet returned by Execute('delete...') should show EOF</p>";\r
+               $rs->Close();\r
+       } else print "err=".$db->ErrorMsg();\r
+       \r
+       print "<p>Test select on empty table</p>";\r
+       $rs = &$db->Execute("select * from ADOXYZ where id=9999");\r
+       if ($rs && !$rs->EOF) print "<b>Error: </b>RecordSet returned by Execute(select...') on empty table should show EOF</p>";\r
+       if ($rs) $rs->Close();\r
+       \r
+       \r
+       $db->debug=false;       \r
+       print "<p>Testing Commit: ";\r
+       $time = $db->DBDate(time());\r
+       if (!$db->BeginTrans()) print '<b>Transactions not supported</b></p>';\r
+       else { /* COMMIT */\r
+               $rs = $db->Execute("insert into ADOXYZ values (99,'Should Not','Exist (Commit)',$time)");\r
+               if ($rs && $db->CommitTrans()) {\r
+                       $rs->Close();\r
+                       $rs = &$db->Execute("select * from ADOXYZ where id=99");\r
+                       if ($rs === false || $rs->EOF) {\r
+                               print '<b>Data not saved</b></p>';\r
+                               $rs = &$db->Execute("select * from ADOXYZ where id=99");\r
+                               print_r($rs);\r
+                               die();\r
+                       } else print 'OK</p>';\r
+                       if ($rs) $rs->Close();\r
+               } else\r
+                       print "<b>Commit failed</b></p>";\r
+               \r
+               /* ROLLBACK */  \r
+               if (!$db->BeginTrans()) print "<p><b>Error in BeginTrans</b>()</p>";\r
+               print "<p>Testing Rollback: ";\r
+               $db->Execute("insert into ADOXYZ values (100,'Should Not','Exist (Rollback)',$time)");\r
+               if ($db->RollbackTrans()) {\r
+                       $rs = $db->Execute("select * from ADOXYZ where id=100");\r
+                       if ($rs && !$rs->EOF) print '<b>Fail: Data should rollback</b></p>';\r
+                       else print 'OK</p>';\r
+                       if ($rs) $rs->Close();\r
+               } else\r
+                       print "<b>Commit failed</b></p>";\r
+                       \r
+               $rs = &$db->Execute('delete from ADOXYZ where id>50');\r
+               if ($rs) $rs->Close();\r
+       }\r
+       \r
+       if (1) {\r
+               print "<p>Testing MetaTables() and MetaColumns()</p>";\r
+               $a = $db->MetaTables();\r
+               if ($a===false) print "<b>MetaTables not supported</b></p>";\r
+               else {\r
+                       print "Array of tables: "; \r
+                       foreach($a as $v) print " ($v) ";\r
+                       print '</p>';\r
+               }\r
+               $a = $db->MetaColumns('ADOXYZ');\r
+               if ($a===false) print "<b>MetaColumns not supported</b></p>";\r
+               else {\r
+                       print "<p>Columns of ADOXYZ: ";\r
+                       foreach($a as $v) print " ($v->name $v->type $v->max_length) ";\r
+               }\r
+       }\r
+       $rs = &$db->Execute('delete from ADOXYZ');\r
+       if ($rs) $rs->Close();\r
+       \r
+       $db->debug = false;\r
+       \r
+       print "<p>Inserting 50 rows</p>";\r
+\r
+       for ($i = 0; $i < 5; $i++) {    \r
+       \r
+       $time = $db->DBDate(time());\r
+       $db->debug = true;\r
+       switch($db->dataProvider){\r
+       case 'ado':\r
+       default:\r
+               \r
+               $arr = array(0=>'Caroline',1=>'Miranda');\r
+               $rs = $db->Execute("insert into ADOXYZ (id,firstname,lastname,created) values ($i*10+0,?,?,$time)",$arr);\r
+               if ($rs === false) print '<b>Error inserting with parameters</b><br>';\r
+        else $rs->Close();\r
+               break;\r
+\r
+       case 'oci8':\r
+               $arr = array('first'=>'Caroline','last'=>'Miranda');\r
+               $rs = $db->Execute("insert into ADOXYZ (id,firstname,lastname,created) values ($i*10+0,:first,:last,$time)",$arr);\r
+               if ($rs === false) print '<b>Error inserting with parameters</b><br>';\r
+        else $rs->Close();\r
+               break;\r
+       /*\r
+       case 'odbc':\r
+       // currently there are bugs using parameters with ODBC with PHP 4\r
+               $rs=$db->Execute("insert into ADOXYZ (id,firstname,lastname,created) values ($i*10+0,'Caroline','Miranda',$time)");\r
+               if ($rs === false) print $rs->ErrorMsg.'<b>Error inserting Caroline</b><br>';\r
+                else $rs->Close();\r
+               break;*/\r
+       }\r
+       $db->debug = false;\r
+       $db->Execute("insert into ADOXYZ (id,firstname,lastname,created) values ($i*10+1,'John','Lim',$time)");\r
+       $db->Execute("insert into ADOXYZ (id,firstname,lastname,created) values ($i*10+2,'Mary','Lamb',$time )");\r
+       $db->Execute("insert into ADOXYZ (id,firstname,lastname,created) values ($i*10+3,'George','Washington',$time )");\r
+       $db->Execute("insert into ADOXYZ (id,firstname,lastname,created) values ($i*10+4,'Mr. Alan','Tam',$time )");\r
+       $db->Execute("insert into ADOXYZ (id,firstname,lastname,created) values ($i*10+5,'Alan','Turing',$time )");\r
+       $db->Execute("insert into ADOXYZ (id,firstname,lastname,created)values ($i*10+6,'Serena','Williams',$time )");\r
+       $db->Execute("insert into ADOXYZ (id,firstname,lastname,created) values ($i*10+7,'Yat Sun','Sun',$time )");\r
+       $db->Execute("insert into ADOXYZ (id,firstname,lastname,created) values ($i*10+8,'Wai Hun','See',$time )");\r
+       $db->Execute("insert into ADOXYZ (id,firstname,lastname,created) values ($i*10+9,'Steven','Oey',$time )");\r
+       }\r
+        \r
+    $db->Execute('update ADOXYZ set id=id+1');\r
+    $nrows = $db->Affected_Rows();\r
+    if ($nrows === false) print "<p><b>Affected_Rows() not supported</b></p>";\r
+    else if ($nrows != 50)  print "<p><b>Affected_Rows() Error: $nrows returned (should be 50) </b></p>";\r
+    else print "<p>Affected_Rows() passed</p>";\r
+       $db->debug = false;\r
+\r
+ ///////////////////////////////\r
+       \r
+       $rs = &$db->Execute("select * from ADOXYZ order by id");\r
+       if ($rs) {\r
+               if ($rs->RecordCount() != 50) print "<p><b>RecordCount returns -1</b></p>";\r
+               if (isset($rs->fields['firstname'])) print '<p>The fields columns can be indexed by column name.</p>';\r
+               else print '<p>The fields columns <i>cannot</i> be indexed by column name.</p>';\r
+               rs2html($rs);\r
+       }\r
+       else print "<b>Error in Execute of SELECT</b></p>";\r
+       \r
+       print "<p>FetchObject/FetchNextObject Test</p>";\r
+       $rs = &$db->Execute('select * from ADOXYZ');\r
+       while ($o = $rs->FetchNextObject()) { // calls FetchObject internally\r
+               if (!is_string($o->FIRSTNAME) || !is_string($o->LASTNAME)) {\r
+                       print_r($o);\r
+                       print "<p><b>Firstname is not string</b></p>";\r
+                       break;\r
+               }\r
+       }\r
+       \r
+       global $ADODB_FETCH_MODE;\r
+       $savefetch = $ADODB_FETCH_MODE;\r
+       $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;\r
+       print "<p>FETCH_MODE = ASSOC: Should get 1, Caroline</p>";\r
+       $rs = &$db->SelectLimit('select id,firstname from ADOXYZ order by id',1);\r
+       if ($rs && !$rs->EOF) {\r
+               if ($rs->fields['id'] != 1)  {print "<b>Error 1</b><br>"; print_r($rs->fields);};\r
+               if (trim($rs->fields['firstname']) != 'Caroline')  {print "<b>Error 2</b><br>"; print_r($rs->fields);};\r
+       }\r
+       $ADODB_FETCH_MODE = ADODB_FETCH_NUM;\r
+       print "<p>FETCH_MODE = NUM: Should get 1, Caroline</p>";\r
+       $rs = &$db->SelectLimit('select id,firstname from ADOXYZ order by id',1);\r
+       if ($rs && !$rs->EOF) {\r
+               if ($rs->fields[0] != 1)  {print "<b>Error 1</b><br>"; print_r($rs->fields);};\r
+               if (trim($rs->fields[1]) != 'Caroline')  {print "<b>Error 2</b><br>"; print_r($rs->fields);};\r
+\r
+       }\r
+       $ADODB_FETCH_MODE = $savefetch;\r
+       \r
+       print "<p>GetRowAssoc Upper: Should get 1, Caroline</p>";\r
+       $rs = &$db->SelectLimit('select id,firstname from ADOXYZ order by id',1);\r
+       if ($rs && !$rs->EOF) {\r
+               $arr = &$rs->GetRowAssoc();\r
+               if ($arr['ID'] != 1) {print "<b>Error 1</b><br>"; print_r($arr);};\r
+               if (trim($arr['FIRSTNAME']) != 'Caroline') {print "<b>Error 2</b><br>"; print_r($arr);};\r
+       }\r
+       print "<p>GetRowAssoc Lower: Should get 1, Caroline</p>";\r
+       $rs = &$db->SelectLimit('select id,firstname from ADOXYZ order by id',1);\r
+       if ($rs && !$rs->EOF) {\r
+               $arr = &$rs->GetRowAssoc(false);\r
+               if ($arr['id'] != 1) {print "<b>Error 1</b><br>"; print_r($arr);};\r
+               if (trim($arr['firstname']) != 'Caroline') {print "<b>Error 2</b><br>"; print_r($arr);};\r
+\r
+       }\r
+       \r
+       print "<p>SelectLimit Test 1: Should see Caroline, John and Mary</p>";\r
+       $rs = &$db->SelectLimit('select distinct * from ADOXYZ order by id',3);\r
+       if ($rs && !$rs->EOF) {\r
+               if (trim($rs->fields[1]) != 'Caroline') print "<b>Error 1</b><br>";\r
+               $rs->MoveNext();\r
+               if (trim($rs->fields[1]) != 'John') print "<b>Error 2</b><br>";\r
+               $rs->MoveNext();\r
+               if (trim($rs->fields[1]) != 'Mary') print "<b>Error 3</b><br>";\r
+               $rs->MoveNext();\r
+               if (! $rs->EOF) print "<b>Not EOF</b><br>";\r
+               //rs2html($rs);\r
+       }\r
+       else "<p><b>Failed SelectLimit Test 1</b></p>";\r
+       print "<p>SelectLimit Test 2: Should see Mary, George and Mr. Alan</p>";\r
+       $rs = &$db->SelectLimit('select * from ADOXYZ order by id',3,2);\r
+       if ($rs && !$rs->EOF) {\r
+               if (trim($rs->fields[1]) != 'Mary') print "<b>Error 1</b><br>";\r
+               $rs->MoveNext();\r
+               if (trim($rs->fields[1]) != 'George') print "<b>Error 2</b><br>";\r
+               $rs->MoveNext();\r
+               if (trim($rs->fields[1]) != 'Mr. Alan') print "<b>Error 3</b><br>";\r
+               $rs->MoveNext();\r
+               if (! $rs->EOF) print "<b>Not EOF</b><br>";\r
+       //      rs2html($rs);\r
+       }\r
+       else "<p><b>Failed SelectLimit Test 2</b></p>";\r
+       \r
+       print "<p>SelectLimit Test 3: Should see Wai Hun and Steven</p>";\r
+       $rs = &$db->SelectLimit('select * from ADOXYZ order by id',-1,48);\r
+       if ($rs && !$rs->EOF) {\r
+               if (trim($rs->fields[1]) != 'Wai Hun') print "<b>Error 1</b><br>";\r
+               $rs->MoveNext();\r
+               if (trim($rs->fields[1]) != 'Steven') print "<b>Error 2</b><br>";\r
+               $rs->MoveNext();\r
+               if (! $rs->EOF) print "<b>Not EOF</b><br>";\r
+               //rs2html($rs);\r
+       }\r
+       else "<p><b>Failed SelectLimit Test 3</b></p>";\r
+       \r
+        $rs = &$db->Execute("select * from ADOXYZ order by id");\r
+       print "<p>Testing Move()</p>";  \r
+       if (!$rs)print "<b>Failed Move SELECT</b></p>";\r
+       else {\r
+               if (!$rs->Move(2)) {\r
+                       if (!$rs->canSeek) print "<p>$db->databaseType: <b>Move(), MoveFirst() nor MoveLast() not supported.</b></p>";\r
+                       else print '<p><b>RecordSet->canSeek property should be set to false</b></p>';\r
+               } else {\r
+                       $rs->MoveFirst();\r
+                       if (trim($rs->Fields("firstname")) != 'Caroline') {\r
+                               print "<p><b>$db->databaseType: MoveFirst failed -- probably cannot scroll backwards</b></p>";\r
+                       }\r
+                       else print "MoveFirst() OK<BR>";\r
+                        \r
+                        // Move(3) tests error handling -- MoveFirst should not move cursor\r
+                       $rs->Move(3);\r
+                       if (trim($rs->Fields("firstname")) != 'George') {\r
+                               print '<p>'.$rs->Fields("id")."<b>$db->databaseType: Move(3) failed</b></p>";\r
+                               print_r($rs);\r
+                       } else print "Move(3) OK<BR>";\r
+                        \r
+                       $rs->Move(7);\r
+                       if (trim($rs->Fields("firstname")) != 'Yat Sun') {\r
+                               print '<p>'.$rs->Fields("id")."<b>$db->databaseType: Move(7) failed</b></p>";\r
+                               print_r($rs);\r
+                       } else print "Move(7) OK<BR>";\r
+\r
+                       $rs->MoveLast();\r
+                       if (trim($rs->Fields("firstname")) != 'Steven'){\r
+                                print '<p>'.$rs->Fields("id")."<b>$db->databaseType: MoveLast() failed</b></p>";\r
+                                print_r($rs);\r
+                       }else print "MoveLast() OK<BR>";\r
+               }\r
+       }\r
+       \r
+ //    $db->debug=true;\r
+       print "<p>Testing concat: concat firstname and lastname</p>";\r
+       \r
+       if ($db->databaseType == 'postgres')\r
+               $rs = &$db->Execute("select distinct ".$db->Concat('(firstname',$db->qstr(' ').')','lastname')." from ADOXYZ");\r
+       else\r
+               $rs = &$db->Execute("select distinct ".$db->Concat('firstname',$db->qstr(' '),'lastname')." from ADOXYZ");\r
+       if ($rs) {\r
+               rs2html($rs);\r
+       } else print "<b>Failed Concat</b></p>";\r
+       \r
+       print "<hr>Testing GetArray() ";\r
+       $rs = &$db->Execute("select * from ADOXYZ order by id");\r
+       if ($rs) {\r
+               $arr = &$rs->GetArray(10);\r
+               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>";\r
+               else print " OK<BR>";\r
+       }\r
+       \r
+       print "Testing FetchNextObject for 1 object ";\r
+       $rs = &$db->Execute("select distinct lastname,firstname from ADOXYZ where firstname='Caroline'");\r
+       $fcnt = 0;\r
+       if ($rs)\r
+       while ($o = $rs->FetchNextObject()) {\r
+               $fcnt += 1;     \r
+       }\r
+       if ($fcnt == 1) print " OK<BR>";\r
+       else print "<b>FAILED</b><BR>";\r
+       \r
+       print "Testing GetAssoc() ";\r
+       $rs = &$db->Execute("select distinct lastname,firstname from ADOXYZ");\r
+       if ($rs) {\r
+               $arr = $rs->GetAssoc();\r
+               if (trim($arr['See']) != 'Wai Hun') print $arr['See']." &nbsp; <b>ERROR</b><br>";\r
+               else print " OK<BR>";\r
+       }\r
+       \r
+       for ($loop=0; $loop < 1; $loop++) {\r
+       print "Testing GetMenu() and CacheExecute<BR>";\r
+       $db->debug = true;\r
+       $rs = &$db->CacheExecute(4,"select distinct firstname,lastname from ADOXYZ");\r
+       if ($rs) print 'With blanks, Steven selected:'. $rs->GetMenu('menu','Steven').'<BR>'; \r
+       else print " Fail<BR>";\r
+       $rs = &$db->CacheExecute(4,"select distinct firstname,lastname from ADOXYZ");\r
+       if ($rs) print ' No blanks, Steven selected: '. $rs->GetMenu('menu','Steven',false).'<BR>';\r
+       else print " Fail<BR>";\r
+       \r
+       $rs = &$db->CacheExecute(4,"select distinct firstname,lastname from ADOXYZ");\r
+       if ($rs) print ' Multiple, Alan selected: '. $rs->GetMenu('menu','Alan',false,true).'<BR>';\r
+       else print " Fail<BR>";\r
+       print '</p><hr>';\r
+       \r
+       $rs = &$db->CacheExecute(4,"select distinct firstname,lastname from ADOXYZ");\r
+       if ($rs) print ' Multiple, Alan and George selected: '. $rs->GetMenu('menu',array('Alan','George'),false,true);\r
+       else print " Fail<BR>";\r
+       print '</p><hr>';\r
+       \r
+       print "Testing GetMenu2() <BR>";\r
+       $rs = &$db->CacheExecute(4,"select distinct firstname,lastname from ADOXYZ");\r
+       if ($rs) print 'With blanks, Steven selected:'. $rs->GetMenu2('menu',('Oey')).'<BR>'; \r
+       else print " Fail<BR>";\r
+       $rs = &$db->CacheExecute(4,"select distinct firstname,lastname from ADOXYZ");\r
+       if ($rs) print ' No blanks, Steven selected: '. $rs->GetMenu2('menu',('Oey'),false).'<BR>';\r
+       else print " Fail<BR>";\r
+       }\r
+       \r
+       $db->debug = false;\r
+       $rs1 = &$db->Execute("select id from ADOXYZ where id = 2 or id = 1 order by 1");\r
+       $rs2 = &$db->Execute("select id from ADOXYZ where id = 3 or id = 4 order by 1");\r
+       \r
+       if ($rs1) $rs1->MoveLast();\r
+       if ($rs2) $rs2->MoveLast();\r
+       \r
+\r
+       if (empty($rs1) || empty($rs2) || $rs1->fields[0] != 2 || $rs2->fields[0] != 4) {\r
+               $a = $rs1->fields[0];\r
+               $b = $rs2->fields[0];\r
+               print "<p><b>Error in multiple recordset test rs1=$a rs2=%b (should be rs1=2 rs2=4)</b></p>";\r
+       } else\r
+               print "<p>Testing multiple recordsets</p>";\r
+       $sql = "seleckt zcol from NoSuchTable_xyz";\r
+       print "<p>Testing execution of illegal statement: <i>$sql</i></p>";\r
+       if ($db->Execute($sql) === false) {\r
+               print "<p>This returns the following ErrorMsg(): <i>".$db->ErrorMsg()."</i> and ErrorNo(): ".$db->ErrorNo().'</p>';\r
+       } else \r
+               print "<p><b>Error in error handling -- Execute() should return false</b></p>";\r
+\r
+       echo "<p> GenID test: ";\r
+       for ($i=1; $i <= 10; $i++)\r
+               echo  "($i: ",$db->GenID('abc'), ") ";\r
+       echo "<p>";\r
+?>\r
+       </p>\r
+       <table width=100% ><tr><td bgcolor=beige>&nbsp;</td></tr></table>\r
+       </p></form>\r
+<?php\r
+       if ($rs1) $rs1->Close();\r
+       if ($rs2) $rs2->Close();\r
+        if ($rs) $rs->Close();\r
+        $db->Close();\r
+}\r
+\r
+include('./testdatabases.inc.php');\r
+\r
+?>\r
+<p><i>ADODB Database Library  (c) 2000, 2001 John Lim. All rights reserved. Released under BSD and LGPL.</i></p>\r
+</body>\r
+</html>\r
diff --git a/libraries/adodb/test2.php b/libraries/adodb/test2.php
new file mode 100755 (executable)
index 0000000..03b0e1d
--- /dev/null
@@ -0,0 +1,52 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">\r
+\r
+<html>\r
+<head>\r
+       <title>Untitled</title>\r
+</head>\r
+\r
+<body>\r
+<?php\r
+/*\r
+  V1.53 13 Nov 2001 (c) 2000, 2001 John Lim (jlim@natsoft.com.my). All rights reserved.\r
+  Released under both BSD license and Lesser GPL library license. \r
+  Whenever there is any discrepancy between the two licenses, \r
+  the BSD license will take precedence.\r
+  Set tabs to 8.\r
+ */\r
+# test connecting to 2 MySQL databases simultaneously\r
+\r
+include("tohtml.inc.php");\r
+include("adodb.inc.php");      \r
+\r
+ADOLoadCode('mysql');\r
+\r
+$c1 = ADONewConnection('mysql');\r
+$c2 = ADONewConnection('mysql');\r
+\r
+if (!$c1->PConnect('flipper','','',"test")) \r
+       die("Cannot connect to flipper");\r
+if (!$c2->PConnect('mangrove','root','',"northwind")) \r
+       die("Cannot connect to mangrove");\r
+\r
+print "<h3>Flipper</h3>";\r
+$t = $c1->MetaTables(); # list all tables in DB\r
+print_r($t);\r
+# select * from last table in DB\r
+rs2html($c1->Execute("select * from ".$t[sizeof($t)-1])); \r
+\r
+print "<h3>Mangrove</h3>";\r
+$t = $c2->MetaTables();\r
+print_r($t);\r
+rs2html($c2->Execute("select * from ".$t[sizeof($t)-1] ));\r
+\r
+print "<h3>Flipper</h3>";\r
+$t = $c1->MetaTables();\r
+print_r($t);\r
+rs2html($c1->Execute("select * from ".$t[sizeof($t)-1]));\r
+\r
+?>\r
+\r
+\r
+</body>\r
+</html>\r
diff --git a/libraries/adodb/test3.php b/libraries/adodb/test3.php
new file mode 100755 (executable)
index 0000000..4e69d6c
--- /dev/null
@@ -0,0 +1,30 @@
+<code>\r
+<?php\r
+/*\r
+  V1.53 13 Nov 2001 (c) 2000, 2001 John Lim (jlim@natsoft.com.my). All rights reserved.\r
+  Released under both BSD license and Lesser GPL library license. \r
+  Whenever there is any discrepancy between the two licenses, \r
+  the BSD license will take precedence.\r
+  Set tabs to 8.\r
+ */\r
+#test Move\r
+include("adodb.inc.php");      \r
+\r
+$c1 = &ADONewConnection('postgres');\r
+if (!$c1->PConnect("susetikus","tester","test","test")) \r
+       die("Cannot connect to database");\r
+\r
+# select * from last table in DB\r
+$rs = $c1->Execute("select * from adoxyz order by 1"); \r
+\r
+$i = 0;\r
+$max = $rs->RecordCount();\r
+if ($max == -1) "RecordCount returns -1<br>";\r
+while (!$rs->EOF and $i < $max) {\r
+       $rs->Move($i);\r
+       print_r( $rs->fields);\r
+       print '<BR>';\r
+       $i++;\r
+}\r
+?>\r
+</code>
\ No newline at end of file
diff --git a/libraries/adodb/test4.php b/libraries/adodb/test4.php
new file mode 100755 (executable)
index 0000000..59bb385
--- /dev/null
@@ -0,0 +1,64 @@
+<?php\r
+\r
+\r
+function testsql()\r
+{\r
+\r
+include('adodb.inc.php');\r
+include('tohtml.inc.php');\r
+\r
+//==========================\r
+// This code tests an insert\r
+\r
+$sql = "SELECT * FROM ADOXYZ WHERE id = -1"; \r
+// Select an empty record from the database \r
+\r
+$conn = &ADONewConnection("mysql");  // create a connection\r
+$conn->debug=1;\r
+$conn->PConnect("localhost", "admin", "", "test"); // connect to MySQL, testdb\r
+$rs = $conn->Execute($sql); // Execute the query and get the empty recordset\r
+\r
+$record = array(); // Initialize an array to hold the record data to insert\r
+\r
+// Set the values for the fields in the record\r
+$record["firstname"] = "Bob";\r
+$record["lastname"] = "Smith";\r
+$record["created"] = time();\r
+\r
+// Pass the empty recordset and the array containing the data to insert\r
+// into the GetInsertSQL function. The function will process the data and return\r
+// a fully formatted insert sql statement.\r
+$insertSQL = $conn->GetInsertSQL($rs, $record);\r
+\r
+$conn->Execute($insertSQL); // Insert the record into the database\r
+\r
+\r
+\r
+//==========================\r
+// This code tests an update\r
+\r
+$sql = "SELECT * FROM ADOXYZ WHERE id = 1"; \r
+// Select a record to update \r
+\r
+$rs = $conn->Execute($sql); // Execute the query and get the existing record to update\r
+\r
+$record = array(); // Initialize an array to hold the record data to update\r
+\r
+// Set the values for the fields in the record\r
+$record["firstname"] = "Caroline";\r
+$record["lastname"] = "Smith"; // Update Caroline's lastname from Miranda to Smith\r
+\r
+\r
+// Pass the single record recordset and the array containing the data to update\r
+// into the GetUpdateSQL function. The function will process the data and return\r
+// a fully formatted update sql statement.\r
+// If the data has not changed, no recordset is returned\r
+$updateSQL = $conn->GetUpdateSQL($rs, $record);\r
+\r
+$conn->Execute($updateSQL); // Update the record in the database\r
+\r
+}\r
+\r
+\r
+testsql();\r
+?>
\ No newline at end of file
diff --git a/libraries/adodb/test5.php b/libraries/adodb/test5.php
new file mode 100755 (executable)
index 0000000..e4c95f1
--- /dev/null
@@ -0,0 +1,35 @@
+<?php\r
+\r
+// Select an empty record from the database \r
+\r
+include('adodb.inc.php');\r
+include('tohtml.inc.php');\r
+\r
+if (0) {\r
+       $conn = &ADONewConnection('mysql');\r
+       $conn->debug=1;\r
+       $conn->PConnect("localhost","root","","xphplens");\r
+       print $conn->databaseType.':'.$conn->GenID().'<br>';\r
+}\r
+\r
+if (0) {\r
+       $conn = &ADONewConnection("oci8");  // create a connection\r
+       $conn->debug=1;\r
+       $conn->PConnect("falcon", "scott", "tiger", "juris8.ecosystem.natsoft.com.my"); // connect to MySQL, testdb\r
+       print $conn->databaseType.':'.$conn->GenID();\r
+}\r
+\r
+if (0) {\r
+       $conn = &ADONewConnection("ibase");  // create a connection\r
+       $conn->debug=1;\r
+       $conn->Connect("localhost:c:\\Interbase\\Examples\\Database\\employee.gdb", "sysdba", "masterkey", ""); // connect to MySQL, testdb\r
+       print $conn->databaseType.':'.$conn->GenID().'<br>';\r
+}\r
+\r
+if (0) {\r
+       $conn = &ADONewConnection('postgres');\r
+       $conn->debug=1;\r
+       @$conn->PConnect("susetikus","tester","test","test");\r
+       print $conn->databaseType.':'.$conn->GenID().'<br>';\r
+}\r
+?>\r
diff --git a/libraries/adodb/testcache.php b/libraries/adodb/testcache.php
new file mode 100755 (executable)
index 0000000..d0e3a0f
--- /dev/null
@@ -0,0 +1,20 @@
+<html>\r
+<body>\r
+<?php\r
+\r
+$ADODB_CACHE_DIR = dirname(tempnam('/tmp',''));\r
+include("adodb.inc.php");\r
+\r
+if (isset($access)) {\r
+       $db=ADONewConnection('access');\r
+       $db->PConnect('nwind');\r
+} else {\r
+       $db = ADONewConnection('mysql');\r
+       $db->PConnect('mangrove','root','','xphplens');\r
+}\r
+if (isset($cache)) $rs = $db->CacheExecute(120,'select * from products');\r
+else $rs = $db->Execute('select * from products');\r
+\r
+$arr = $rs->GetArray();\r
+print sizeof($arr);\r
+?>
\ No newline at end of file
diff --git a/libraries/adodb/testdatabases.inc.php b/libraries/adodb/testdatabases.inc.php
new file mode 100755 (executable)
index 0000000..5841e80
--- /dev/null
@@ -0,0 +1,164 @@
+<?php\r
+  \r
+/*\r
+V1.53 13 Nov 2001 (c) 2000, 2001 John Lim (jlim@natsoft.com.my). All rights reserved.\r
+  Released under both BSD license and Lesser GPL library license. \r
+  Whenever there is any discrepancy between the two licenses, \r
+  the BSD license will take precedence.\r
+*/ \r
\r
+ /* this file is used by the ADODB test program: test.php */\r
\r
+// cannot test databases below, but we include them anyway to check\r
+// if they parse ok...\r
+ADOLoadCode("sybase");\r
+ADOLoadCode("postgres");\r
+ADOLoadCode("postgres7");\r
+\r
+if (!empty($testpostgres)) {\r
+       //ADOLoadCode("postgres");\r
+       $db = &ADONewConnection('postgres');\r
+       print "<h1>Connecting $db->databaseType...</h1>";\r
+       if (@$db->PConnect("susetikus","tester","test","test")) {\r
+               testdb($db,"create table ADOXYZ (id integer, firstname char(24), lastname varchar,created date)");\r
+       }else\r
+               print "ERROR: PostgreSQL requires a database called test on server susetikus, user tester, password test.<BR>".$db->ErrorMsg();\r
+}\r
+if (!empty($testibase)) {\r
+       \r
+       $db = &ADONewConnection('ibase');\r
+       print "<h1>Connecting $db->databaseType...</h1>";\r
+       if (@$db->PConnect("localhost:c:\\interbase\\examples\\database\\employee.gdb", "sysdba", "masterkey", ""))\r
+               testdb($db,"create table ADOXYZ (id integer, firstname char(24), lastname char(24),created date)");\r
+        else print "ERROR: Interbase test requires a database called employee.gdb".'<BR>'.$db->ErrorMsg();\r
+       \r
+}\r
+\r
+// REQUIRES ODBC DSN CALLED nwind\r
+if (!empty($testaccess)) {\r
+\r
+       $db = &ADONewConnection('access');\r
+       print "<h1>Connecting $db->databaseType...</h1>";\r
+       \r
+       if (@$db->PConnect("northwind", "", "", ""))\r
+               testdb($db,"create table ADOXYZ (id int, firstname char(24), lastname char(24),created datetime)");\r
+       else print "ERROR: Access test requires a Windows ODBC DSN=nwind, Access driver";\r
+       \r
+}\r
+\r
+if (!empty($testaccess) && !empty($testado)) { // ADO ACCESS\r
+       \r
+       $db = &ADONewConnection("ado_access");\r
+       print "<h1>Connecting $db->databaseType...</h1>";\r
+       \r
+       $access = 'd:\inetpub\wwwroot\php\NWIND.MDB';\r
+       $myDSN =  'PROVIDER=Microsoft.Jet.OLEDB.4.0;'\r
+               . 'DATA SOURCE=' . $access . ';';\r
+               //. 'USER ID=;PASSWORD=;';\r
+       \r
+       if (@$db->PConnect($myDSN, "", "", "")) {\r
+               print "ADO version=".$db->_connectionID->version."<br>";\r
+               testdb($db,"create table ADOXYZ (id int, firstname char(24), lastname char(24),created datetime)");\r
+       } else print "ERROR: Access test requires a Access database $access".'<BR>'.$db->ErrorMsg();\r
+       \r
+}\r
+\r
+if (!empty($testvfp)) { // ODBC\r
+\r
+       \r
+       $db = &ADONewConnection('vfp');\r
+       print "<h1>Connecting $db->databaseType...</h1>";\r
+       if (@$db->PConnect("logos2", "", "", ""))\r
+               testdb($db,"create table d:\\inetpub\\wwwroot\\logos2\\data\\ADOXYZ (id int, firstname char(24), lastname char(24),created date)");\r
+        else print "ERROR: Visual FoxPro test requires a Windows ODBC DSN=logos2, VFP driver";\r
+       \r
+}\r
+\r
+\r
+// REQUIRES MySQL server at localhost with database 'test'\r
+if (!empty($testmysql)) { // MYSQL\r
+       \r
+       $db = &ADONewConnection('mysqlt');\r
+       print "<h1>Connecting $db->databaseType...</h1>";\r
+       if (@$db->PConnect("localhost", "root", "", "test"))\r
+               testdb($db);\r
+       else print "ERROR: MySQL test requires a MySQL server on localhost, userid='admin', password='', database='test'".'<BR>'.$db->ErrorMsg();\r
+       \r
+}\r
+\r
+ADOLoadCode("oci8");\r
+if (!empty($testoracle)) { \r
+       \r
+       $db = ADONewConnection();\r
+       print "<h1>Connecting $db->databaseType...</h1>";\r
+       if ($db->PConnect("localhost:4321", "scott", "tiger", "natsoft.domain"))\r
+       //if ($db->PConnect("falcon", "scott", "tiger", "juris8.ecosystem.natsoft.com.my"))\r
+               testdb($db,"create table ADOXYZ (id int, firstname varchar(24), lastname varchar(24),created date)");\r
+       else print "ERROR: Oracle test requires an Oracle server setup with scott/tiger".'<BR>'.$db->ErrorMsg();\r
+\r
+}\r
+ADOLoadCode("oracle");\r
+if (!empty($testoracle)) { \r
+       \r
+       $db = ADONewConnection();\r
+       print "<h1>Connecting $db->databaseType...</h1>";\r
+       if ($db->PConnect("", "scott", "tiger", "natsoft.domain"))\r
+               testdb($db,"create table ADOXYZ (id int, firstname varchar(24), lastname varchar(24),created date)");\r
+       else print "ERROR: Oracle test requires an Oracle server setup with scott/tiger".'<BR>'.$db->ErrorMsg();\r
+\r
+}\r
+\r
+\r
+ADOLoadCode("odbc_mssql");\r
+if (!empty($testmssql)) { // MS SQL Server via ODBC\r
+       \r
+       $db = ADONewConnection();\r
+       print "<h1>Connecting $db->databaseType...</h1>";\r
+       if (@$db->PConnect("lensengine", "sa", "", ""))\r
+               testdb($db,"create table ADOXYZ (id int, firstname char(24), lastname char(24),created datetime)");\r
+       else print "ERROR: MSSQL test 1 requires a MS SQL 7 server setup with DSN='lensengine', userid='sa', password=''";\r
+\r
+}\r
+\r
+ADOLoadCode("ado_mssql");\r
+\r
+if (!empty($testmssql) && !empty($testado) ) { // ADO ACCESS MSSQL -- thru ODBC -- DSN-less\r
+       \r
+       $db = &ADONewConnection("ado_mssql");\r
+       print "<h1>Connecting DSN-less $db->databaseType...</h1>";\r
+       \r
+       $myDSN="PROVIDER=MSDASQL;DRIVER={SQL Server};"\r
+               . "SERVER=mangrove;DATABASE=ai;UID=sa;PWD=;"  ;\r
+\r
+               \r
+       if (@$db->PConnect($myDSN, "", "", ""))\r
+               testdb($db,"create table ADOXYZ (id int, firstname char(24), lastname char(24),created datetime)");\r
+       else print "ERROR: MSSQL test 2 requires a MS SQL 7 on a server='mangrove', userid='sa', password='', database='ai'";\r
+       \r
+}\r
+\r
+\r
+ADOLoadCode("mssql");\r
+if (!empty($testmssql)) { // MS SQL Server -- the extension is buggy -- probably better to use ODBC\r
+       $db = ADONewConnection();\r
+       print "<h1>Connecting $db->databaseType...</h1>";\r
+       if (@$db->PConnect("mangrove", "sa", "", "ai"))\r
+               testdb($db,"create table ADOXYZ (id int, firstname char(24), lastname char(24),created datetime)");\r
+       else print "ERROR: MSSQL test 2 requires a MS SQL 7 on a server='192.168.0.1', userid='sa', password='', database='ai'".'<BR>'.$db->ErrorMsg();\r
+       \r
+}\r
+\r
+if (!empty($testmssql) && !empty($testado)) { // ADO ACCESS MSSQL with OLEDB provider\r
+\r
+       $db = &ADONewConnection("ado_mssql");\r
+       print "<h1>Connecting DSN-less OLEDB Provider $db->databaseType...</h1>";\r
+       \r
+       $myDSN="SERVER=mangrove;DATABASE=ai;";\r
+               \r
+       if (@$db->PConnect($myDSN, "sa", "", 'SQLOLEDB'))\r
+               testdb($db,"create table ADOXYZ (id int, firstname char(24), lastname char(24),created datetime)");\r
+       else print "ERROR: MSSQL test 2 requires a MS SQL 7 on a server='mangrove', userid='sa', password='', database='ai'";\r
+\r
+}\r
+\r
+?>
\ No newline at end of file
diff --git a/libraries/adodb/testoci8.php b/libraries/adodb/testoci8.php
new file mode 100755 (executable)
index 0000000..fa8180e
--- /dev/null
@@ -0,0 +1,43 @@
+<html>\r
+<body>\r
+<?php\r
+error_reporting(63);\r
+include("adodb.inc.php");\r
+include("tohtml.inc.php");\r
+\r
+if (1) {\r
+       $db = ADONewConnection('oci8');\r
+       $db->PConnect('','scott','tiger');\r
+       $db->debug = true;\r
+       $rs = &$db->Execute(\r
+               'select * from adoxyz where firstname=:first and trim(lastname)=:last',\r
+               array('first'=>'Caroline','last'=>'Miranda'));\r
+       if (!$rs) die("Empty RS");\r
+       if ($rs->EOF) die("EOF RS");\r
+       rs2html($rs);\r
+}\r
+if (1) {\r
+       $db = ADONewConnection('oci8');\r
+       $db->PConnect('','scott','tiger');\r
+       $db->debug = true;\r
+       $db->Execute("delete from emp where ename='John'");\r
+       print $db->Affected_Rows().'<BR>';\r
+       $stmt = &$db->Prepare('insert into emp (empno, ename) values (:empno, :ename)');\r
+       $rs = $db->Execute($stmt,array('empno'=>4321,'ename'=>'John'));\r
+       // prepare not quite ready for prime time\r
+       //$rs = $db->Execute($stmt,array('empno'=>3775,'ename'=>'John'));\r
+       if (!$rs) die("Empty RS");\r
+}\r
+\r
+if (0) {\r
+       $db = ADONewConnection('odbc_oracle');\r
+       if (!$db->PConnect('local_oracle','scott','tiger')) die('fail connect');\r
+       $db->debug = true;\r
+       $rs = &$db->Execute(\r
+               'select * from adoxyz where firstname=? and trim(lastname)=?',\r
+               array('first'=>'Caroline','last'=>'Miranda'));\r
+       if (!$rs) die("Empty RS");\r
+       if ($rs->EOF) die("EOF RS");\r
+       rs2html($rs);\r
+}\r
+?>
\ No newline at end of file
diff --git a/libraries/adodb/testpaging.php b/libraries/adodb/testpaging.php
new file mode 100755 (executable)
index 0000000..09c2681
--- /dev/null
@@ -0,0 +1,36 @@
+<?php\r
+error_reporting(63);\r
+include_once('adodb-pear.inc.php');\r
+include_once('tohtml.inc.php');\r
+session_register('curr_page');\r
+\r
+$db = NewADOConnection('mysql');\r
+$db->debug = true;\r
+//$db->Connect('localhost:4321','scott','tiger','natsoft.domain');\r
+$db->Connect('localhost','root','','xphplens');\r
+$num_of_rows_per_page = 10;\r
+$sql = "select * from adoxyz where firstname = 'John'";\r
+\r
+if (isset($HTTP_GET_VARS['next_page']))\r
+       $curr_page = $HTTP_GET_VARS['next_page'];\r
+if (empty($curr_page)) $curr_page = 1; ## at first page\r
+\r
+$rs = $db->CachePageExecute(15,$sql, $num_of_rows_per_page, $curr_page);\r
+if (!$rs) die('Query Failed');\r
+\r
+if (!$rs->EOF && (!$rs->AtFirstPage() || !$rs->AtLastPage())) {\r
+       if (!$rs->AtFirstPage()) {\r
+?>\r
+<a href="<?php echo $PHP_SELF,'?next_page=',$rs->AbsolutePage() - 1 ?>">Previous page</a>\r
+<?php\r
+       }\r
+       if (!$rs->AtLastPage()) {\r
+?>\r
+<a href="<?php echo $PHP_SELF,'?next_page=',$rs->AbsolutePage() + 1 ?>">Next page</a>\r
+<?php\r
+       }\r
+       rs2html($rs);\r
+}\r
+\r
+\r
+?>\r
diff --git a/libraries/adodb/testpear.php b/libraries/adodb/testpear.php
new file mode 100755 (executable)
index 0000000..34bf4b7
--- /dev/null
@@ -0,0 +1,17 @@
+<?php\r
+include('adodb.inc.php');\r
+include('tohtml.inc.php');\r
+\r
+$db = NewADOConnection('pear');\r
+$db->databaseDriver = 'mysql';\r
+$db->debug = true;\r
+$db->Connect('localhost','root','','xphplens');\r
+$rs = $db->Execute('select * from products');\r
+rs2html($rs);\r
+\r
+print "<h3>Test Errors</h3>";\r
+$rs = $db->Execute('select * from productz');\r
+if ($rs) print "Recordset returned - wrong!<br>";\r
+\r
+$db->Connect('localhost','root','','nodb_xphplens');\r
+?>
\ No newline at end of file
diff --git a/libraries/adodb/testsessions.php b/libraries/adodb/testsessions.php
new file mode 100755 (executable)
index 0000000..a935a24
--- /dev/null
@@ -0,0 +1,12 @@
+<?php\r
+\r
+GLOBAL $HTTP_SESSION_VARS;\r
+       include('adodb.inc.php');\r
+       include('adodb-session.php');\r
+       session_start();\r
+       session_register('AVAR');\r
+       $HTTP_SESSION_VARS['AVAR'] += 1;\r
+       $AVAR += 1;\r
+       print "<p>\$HTTP_SESSION_VARS['AVAR']={$HTTP_SESSION_VARS['AVAR']}</p>";\r
+       \r
+?>
\ No newline at end of file
diff --git a/libraries/adodb/tohtml.inc.php b/libraries/adodb/tohtml.inc.php
new file mode 100755 (executable)
index 0000000..1204475
--- /dev/null
@@ -0,0 +1,150 @@
+<?php \r
+/*\r
+V1.53 13 Nov 2001 (c) 2000, 2001 John Lim (jlim@natsoft.com.my). All rights reserved.\r
+  Released under both BSD license and Lesser GPL library license. \r
+  Whenever there is any discrepancy between the two licenses, \r
+  the BSD license will take precedence.\r
+  \r
+  Some pretty-printing by Chris Oxenreider <oxenreid@state.net>\r
+*/ \r
+  \r
+// specific code for tohtml\r
+GLOBAL $gSQLMaxRows,$gSQLBlockRows;\r
+        \r
+$gSQLMaxRows = 1000; // max no of rows to download\r
+$gSQLBlockRows=20; // max no of rows per table block\r
+\r
+// RecordSet to HTML Table\r
+//------------------------------------------------------------\r
+// Convert a recordset to a html table. Multiple tables are generated\r
+// if the number of rows is > $gSQLBlockRows. This is because\r
+// web browsers normally require the whole table to be downloaded\r
+// before it can be rendered, so we break the output into several\r
+// smaller faster rendering tables.\r
+//\r
+// $rs: the recordset\r
+// $ztabhtml: the table tag attributes (optional)\r
+// $zheaderarray: contains the replacement strings for the headers (optional)\r
+//\r
+//  USAGE:\r
+//    include('adodb.inc.php');\r
+//    ADOLoadCode('mysql');\r
+//    $db = ADONewConnection();\r
+//    $db->Connect('mysql','userid','password','database');\r
+//    $rs = $db->Execute('select col1,col2,col3 from table');\r
+//  rs2html($rs, 'BORDER=2', array('Title1', 'Title2', 'Title3'));\r
+//    $rs->Close();\r
+//\r
+// RETURNS: number of rows displayed\r
+function rs2html(&$rs,$ztabhtml='',$zheaderarray="")\r
+{\r
+$s ='';$rows=0;$docnt = false;\r
+GLOBAL $gSQLMaxRows,$gSQLBlockRows;\r
+\r
+       if (!$rs) {\r
+               printf(ADODB_BAD_RS,'rs2html');\r
+               return false;\r
+       }\r
+       \r
+       if (! $ztabhtml) $ztabhtml = "BORDER='1' WIDTH='98%'";\r
+       else $docnt = true;\r
+       $typearr = array();\r
+       $ncols = $rs->FieldCount();\r
+    $hdr = "<TABLE COLS=$ncols $ztabhtml>\n\n";\r
+       \r
+       for ($i=0; $i < $ncols; $i++) { \r
+               $field = $rs->FetchField($i);\r
+               if ($zheaderarray) $fname = $zheaderarray[$i];\r
+               else $fname = htmlspecialchars($field->name);   \r
+               $typearr[$i] = $rs->MetaType($field->type,$field->max_length);\r
+            \r
+               if (empty($fname)) $fname = '&nbsp;';\r
+               $hdr .= "<TH>$fname</TH>";\r
+         }\r
+\r
+               print $hdr."\n\n";\r
+       \r
+               while (!$rs->EOF) {\r
+            $s .= "<TR>\n";\r
+            for ($i=0; $i < $ncols; $i++) {\r
+            $type = $typearr[$i];\r
+                        \r
+                       switch($type) {\r
+                       case 'T':\r
+                               $s .= " <TD>".$rs->UserTimeStamp($rs->fields[$i],"D d, M Y, h:i:s") ."&nbsp;</TD>\n";\r
+                               break;\r
+                       case 'D':\r
+                               $s .= " <TD>".$rs->UserDate($rs->fields[$i],"D d, M Y") ."&nbsp;</TD>\n";\r
+                               break;\r
+                       case 'I':\r
+                       case 'N':\r
+                               $s .= " <TD align=right>".htmlspecialchars(trim($rs->fields[$i])) ."&nbsp;</TD>\n";\r
+                $s = stripslashes($s);\r
+                $s = urldecode($s);\r
+                               break;\r
+                       default:\r
+                               $s .= " <TD>".htmlspecialchars(trim($rs->fields[$i])) ."&nbsp;</TD>\n";\r
+                $s = stripslashes($s);\r
+                $s = urldecode($s);\r
+                       }\r
+                }\r
+                $s .= "</TR>\n\n";\r
+               \r
+               $rows += 1;\r
+               if ($rows >= $gSQLMaxRows) {\r
+                       $rows = "<p>Truncated at $gSQLMaxRows</p>";\r
+                       break;\r
+               } // switch\r
+\r
+               $rs->MoveNext();\r
+               \r
+               // additional EOF check to prevent a widow header\r
+               if (!$rs->EOF && $rows % $gSQLBlockRows == 0) {\r
+               \r
+                       //if (connection_aborted()) break;// not needed as PHP aborts script, unlike ASP\r
+                        print $s . "</TABLE>\n\n";\r
+                        $s = $hdr;\r
+               }\r
+        } // while\r
+       \r
+               print $s."</TABLE>\n\n";\r
+\r
+       if ($docnt) print "<H2>".$rows." Rows</H2>";\r
+       \r
+       return $rows;\r
+ }\r
\r
+\r
+function arr2html(&$arr,$ztabhtml='',$zheaderarray='')\r
+{\r
+       if (!$ztabhtml) $ztabhtml = 'BORDER=1';\r
+       \r
+       $s = "<TABLE $ztabhtml>";//';print_r($arr);\r
+\r
+       if ($zheaderarray) {\r
+               $s .= '<TR>';\r
+               for ($i=0; $i<sizeof($zheaderarray); $i++) {\r
+                       $s .= "    <TD>{$zheaderarray[$i]}</TD>\n";\r
+               }\r
+               $s .= "\n</TR>";\r
+       }\r
+       \r
+       for ($i=0; $i<sizeof($arr); $i++) {\r
+               $s .= '<TR>';\r
+               $a = &$arr[$i];\r
+               if (is_array($a)) \r
+                       for ($j=0; $j<sizeof($a); $j++) {\r
+                               $val = $a[$j];\r
+                               if (empty($val)) $val = '&nbsp;';\r
+                               $s .= "    <TD>$val</TD>\n";\r
+                       }\r
+               else if ($a) {\r
+                       $s .=  '    <TD>'.$a."</TD>\n";\r
+               } else $s .= "    <TD>&nbsp;</TD>\n";\r
+               $s .= "\n</TR>\n";\r
+       }\r
+       $s .= '</TABLE>';\r
+       print $s;\r
+}\r
+\r
+\r
diff --git a/libraries/adodb/tute.htm b/libraries/adodb/tute.htm
new file mode 100755 (executable)
index 0000000..dbe7c3c
--- /dev/null
@@ -0,0 +1,273 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">\r
+\r
+<html>\r
+<head>\r
+       <title>Tutorial: Moving from MySQL to ADODB</title>\r
+</head>\r
+\r
+<body>\r
+<h1>Tutorial: Moving from MySQL to ADODB</h1>\r
+\r
+<pre>        You say eether and I say eyether, \r
+        You say neether and I say nyther; \r
+        Eether, eyether, neether, nyther - \r
+        Let's call the whole thing off ! \r
+<br>\r
+        You like potato and I like po-tah-to, \r
+        You like tomato and I like to-mah-to; \r
+        Potato, po-tah-to, tomato, to-mah-to - \r
+        Let's call the whole thing off ! \r
+</pre>\r
+<p>I love this song, especially the version with Louis Armstrong and Ella singing \r
+  duet. It is all about how hard it is for two people in love to be compatible \r
+  with each other. It's about compromise and finding a common ground, and that's \r
+  what this article is all about. \r
+<p>PHP is all about creating dynamic web-sites with the least fuss and the most \r
+  fun. To create these websites we need to use databases to retrieve login information, \r
+  to splash dynamic news onto the web page and store forum postings. So let's \r
+  say we were using the popular MySQL database for this. Your company has done \r
+  such a fantastic job that the Web site is more popular than your wildest dreams. \r
+  You find that MySQL cannot scale to handle the workload; time to switch databases. \r
+<p> Unfortunately in PHP every database is accessed slightly differently. To connect \r
+  to MySQL, you would use <i>mysql_connect()</i>; when you decide to upgrade to \r
+  Oracle or Microsoft SQL Server, you would use <i>ocilogon() </i>or <i>mssql_connect()</i> \r
+  respectively. What is worse is that the parameters you use for the different \r
+  connect functions are different also.. One database says po-tato, the other \r
+  database says pota-to. Oh-oh. \r
+<h3>Let's NOT call the whole thing off</h3>\r
+<p>A database wrapper library such as ADODB comes in handy when you need to ensure portability. It provides \r
+  you with a common API to communicate with any supported database so you don't have to call things off. <p>\r
+\r
+<p>ADODB stands for Active Data Objects DataBase (sorry computer guys are sometimes \r
+  not very original). ADODB currently supports MySQL, PostgreSQL, Oracle, Interbase, \r
+  Microsoft SQL Server, Access, FoxPro, Sybase, ODBC and ADO. You can download \r
+  ADODB from <a href=http://php.weblogs.com/adodb><a href="http://php.weblogs.com/adodb">http://php.weblogs.com/adodb</a></a>.\r
+<h3>MySQL Example</h3>\r
+<p>The most common database used with PHP is MySQL, so I guess you should be familiar \r
+  with the following code. It connects to a MySQL server at <i>localhost</i>, \r
+  database <i>mydb</i>, and executes an SQL select statement. The results are \r
+  printed, one line per row. \r
+<pre><font color="#666600">$db = <b>mysql_connect</b>(&quot;localhost&quot;, &quot;root&quot;, &quot;password&quot;);\r
+<b>mysql_select_db</b>(&quot;mydb&quot;,$db);</font>\r
+<font color="#660000">$result = <b>mysql_query</b>(&quot;SELECT * FROM employees&quot;,$db)</font><code><font color="#663300">;\r
+if ($result === false) die(&quot;failed&quot;);</font></code> \r
+<font color="#006666"><b>while</b> ($fields =<b> mysql_fetch_row</b>($result)) &#123;\r
+ <b>for</b> ($i=0, $max=sizeof($fields); $i &lt; $max; $i++) &#123;\r
+        <b>print</b> $fields[$i].' ';\r
+ &#125;\r
+ <b>print</b> &quot;&lt;br&gt;\n&quot;;\r
+&#125;</font> \r
+</pre>\r
+<p>The above code has been color-coded by section. The first section is the connection \r
+  phase. The second is the execution of the SQL, and the last section is displaying \r
+  the fields. The <i>while</i> loop scans the rows of the result, while the <i>for</i> \r
+  loop scans the fields in one row.</p>\r
+<p>Here is the equivalent code in ADODB</p>\r
+<pre><b><font color="#666600"> include(&quot;adodb.inc.php&quot;);</b>\r
+ $db = <b>NewADOConnection</b>('mysql');\r
+ $db-&gt;<b>Connect</b>(&quot;localhost&quot;, &quot;root&quot;, &quot;password&quot;, &quot;mydb&quot;);</font>\r
+ <font color="#663300">$result = $db-&gt;<b>Execute</b>(&quot;SELECT * FROM employees&quot;);\r
+ </font><font color="#663300"></font><code><font color="#663300">if ($result === false) die(&quot;failed&quot;)</font></code><code><font color="#663300">;</font></code>  \r
+ <font color="#006666"><b>while</b> (!$result-&gt;EOF) &#123;\r
+    <b>for</b> ($i=0, $max=$result-&gt;<b>FieldCount</b>(); $i &lt; $max; $i++)\r
+           <b>print</b> $result-&gt;fields[$i].' ';\r
+    $result-&gt;<b>MoveNext</b>();\r
+    <b>print</b> &quot;&lt;br&gt;\n&quot;;\r
+ &#125;</font> </pre>\r
+<p></p>\r
+<p>Now porting to Oracle is as simple as changing the second line to <code>NewADOConnection('oracle')</code>. \r
+  Let's walk through the code...</p>\r
+<h3>Connecting to the Database</h3>\r
+<p></p>\r
+<pre><b><font color="#666600">include(&quot;adodb.inc.php&quot;);</b>\r
+$db = <b>NewADOConnection</b>('mysql');\r
+$db-&gt;<b>Connect</b>(&quot;localhost&quot;, &quot;root&quot;, &quot;password&quot;, &quot;mydb&quot;);</font></pre>\r
+<p>The connection code is a bit more sophisticated than MySQL's because our needs \r
+  are more sophisticated. In ADODB, we use an object-oriented approach to managing \r
+  the complexity of handling multiple databases. We have different classes to \r
+  handle different databases. If you aren't familiar with object-oriented programing, \r
+  don't worry -- the complexity is all hidden away in the<code> NewADOConnection()</code> \r
+  function.</p>\r
+<p>To conserve memory, we only load the PHP code specific to the database you \r
+  are connecting to. We do this by calling <code>NewADOConnection(databasedriver)</code>. \r
+  Legal database drivers include <i>mysql, mssql, oracle, oci8, postgres, sybase, \r
+  vfp, access, ibase </i>and many others.</p>\r
+<p>Then we create a new instance of the connection class by calling <code>NewADOConnection()</code>. \r
+  Finally we connect to the database using <code>$db-&gt;Connect(). </code></p>\r
+<h3>Executing the SQL</h3>\r
+<p><code><font color="#663300">$result = $db-&gt;<b>Execute</b>(&quot;SELECT * \r
+  FROM employees&quot;);<br>\r
+  if ($result === false) die(&quot;failed&quot;)</font></code><code><font color="#663300">;</font></code> \r
+  <br>\r
+</p>\r
+<p>Sending the SQL statement to the server is straight forward. Execute() will \r
+  return a recordset object on successful execution. You should check $result \r
+  as we do above.\r
+<p>An issue that confuses beginners is the fact that we have two types of objects \r
+  in ADODB, the connection object and the recordset object. When do we use each?\r
+<p>The connection object ($db) is responsible for connecting to the database, \r
+  formatting your SQL and querying the database server. The recordset object ($result) \r
+  is responsible for retrieving the results and formatting the reply as text or \r
+  as an array.\r
+<p>The only thing I need to add is that ADODB provides several helper functions \r
+  for making INSERT and UPDATE statements easier, which we will cover in the Advanced \r
+  section. \r
+<h3>Retrieving the Data<br>\r
+</h3>\r
+<pre><font color="#006666"><b>while</b> (!$result-&gt;EOF) &#123;\r
+   <b>for</b> ($i=0, $max=$result-&gt;<b>FieldCount</b>(); $i &lt; $max; $i++)\r
+       <b>print</b> $result-&gt;fields[$i].' ';\r
+   $result-&gt;<b>MoveNext</b>();\r
+   <b>print</b> &quot;&lt;br&gt;\n&quot;;\r
+&#125;</font></pre>\r
+<p>The paradigm for getting the data is that it's like reading a file. For every \r
+  line, we check first whether we have reached the end-of-file (EOF). While not \r
+  end-of-file, loop through each field in the row. Then move to the next line \r
+  (MoveNext) and repeat. \r
+<p>The <code>$result-&gt;fields[]</code> array is generated by the PHP database \r
+  extension. Some database extensions do not index the array by field name (unlike \r
+  MySQL). To guarantee portability, use <code>$result-&gt;Fields($fieldname)</code>. \r
+  Note that this is a function, not an array. \r
+<h3>Other Useful Functions</h3>\r
+<p><code>$recordset-&gt;Move($pos)</code> scrolls to that particular row. ADODB supports forward \r
+  scrolling for all databases. Some databases will not support backwards scrolling. \r
+  This is normally not a problem as you can always cache records to simulate backwards \r
+  scrolling. \r
+<p><code>$recordset-&gt;RecordCount()</code> returns the number of records accessed by the \r
+  SQL statement. Some databases will return -1 because it is not supported. \r
+<p><code>$recordset-&gt;GetArray()</code> returns the result as an array. \r
+<p><code>rs2html($recordset)</code> is a function that is generates a HTML table based on the \r
+  $recordset passed to it. An example with the relevant lines in bold:\r
+<pre>   include('adodb.inc.php'); \r
+   <b>include('tohtml.inc.php');</b> /* includes the rs2html function */\r
+   $conn = &amp;ADONewConnection('mysql'); \r
+   $conn-&gt;PConnect('localhost','userid','password','database');\r
+   $rs = $conn-&gt;Execute('select * from table');\r
+  <b> rs2html($rs)</b>; /* recordset to html table */ </pre>\r
+<p>There are many other helper functions that are listed in the documentation available at <a href="http://php.weblogs.com/adodb_manual"><a href="http://php.weblogs.com/adodb_manual">http://php.weblogs.com/adodb_manual</a></a>. \r
+<h2>Advanced Material</h2>\r
+<h3>Inserts and Updates </h3>\r
+<p>Let's say you want to insert the following data into a database. \r
+<p><b>ID</b> = 3<br>\r
+  <b>TheDate</b>=mktime(0,0,0,8,31,2001) /* 31st August 2001 */<br>\r
+  <b>Note</b>= sugar why don't we call it off \r
+<p>When you move to another database, your insert might no longer work.</p>\r
+<p>The first problem is that each database has a different default date format. \r
+  MySQL expects YYYY-MM-DD format, while other databases have different defaults. \r
+  ADODB has a function called DBDate() that addresses this issue by converting \r
+  converting the date to the correct format.</p>\r
+<p>The next problem is that the <b>don't</b> in the Note needs to be quoted. In \r
+  MySQL, we use <b>don\'t</b> but in some other databases (Sybase, Access, Microsoft \r
+  SQL Server) we use <b>don''t. </b>The qstr() function addresses this issue.</p>\r
+<p>So how do we use the functions? Like this:</p>\r
+<pre>$sql = &quot;INSERT INTO table (id, thedate,note) values (&quot; \r
+   . $<b>ID</b> . ','\r
+   . $db-&gt;DBDate($<b>TheDate</b>) .','\r
+   . $db-&gt;qstr($<b>Note</b>).&quot;)&quot;;\r
+$db-&gt;Execute($sql);</pre>\r
+<p>ADODB also supports <code>$connection-&gt;Affected_Rows()</code> (returns the \r
+  number of rows affected by last update or delete) and <code>$recordset-&gt;Insert_ID()</code> \r
+  (returns last autoincrement number generated by an insert statement). Be forewarned \r
+  that not all databases support the two functions.<br>\r
+</p>\r
+<h3>MetaTypes</h3>\r
+<p>You can find out more information about each of the fields (I use the words \r
+  fields and columns interchangebly) you are selecting by calling the recordset \r
+  method <code>FetchField($fieldoffset)</code>. This will return an object with \r
+  3 properties: name, type and max_length. \r
+<pre>For example:</pre>\r
+<pre>$recordset = $conn-&gt;Execute(&quot;select adate from table&quot;);<br>$f0 = $recordset-&gt;FetchField(0);\r
+</pre>\r
+<p>Then <code>$f0-&gt;name</code> will hold <i>'adata'</i>, <code>$f0-&gt;type</code> \r
+  will be set to '<i>date'</i>. If the max_length is unknown, it will be set to \r
+  -1. \r
+<p>One problem with handling different databases is that each database often calls \r
+  the same type by a different name. For example a <i>timestamp</i> type is called \r
+  <i>datetime</i> in one database and <i>time</i> in another. So ADODB has a special \r
+  <code>MetaType($type, $max_length)</code> function that standardises the types \r
+  to the following: \r
+<p>C: character and varchar types<br>\r
+  X: text or long character (eg. more than 255 bytes wide).<br>\r
+  B: blob or binary image<br>\r
+  D: date<br>\r
+  T: timestamp<br>\r
+  L: logical (boolean)<br>\r
+  I: integer<br>\r
+  N: numeric (float, double, money) \r
+<p>In the above date example, \r
+<p><code>$recordset = $conn-&gt;Execute(&quot;select adate from table&quot;);<br>\r
+  $f0 = $recordset-&gt;FetchField(0);<br>\r
+  $type = $recordset-&gt;MetaType($f0-&gt;type, $f0-&gt;max_length);<br>\r
+  print $type; /* should print 'D'</code> */\r
+<p> \r
+<p><b>Select Limit and Top Support</b> \r
+<p>ADODB has a function called $connection->SelectLimit($sql,$nrows,$offset) that allows\r
+you to retrieve a subset of the recordset. This will take advantage of native\r
+SELECT TOP on Microsoft products and SELECT ... LIMIT with PostgreSQL and MySQL, and\r
+emulated if the database does not support it.\r
+<p><b>Caching Support</b> \r
+<p>ADODB allows you to cache recordsets in your file system, and only requery the database\r
+server after a certain timeout period with $connection->CacheExecute($secs2cache,$sql) and \r
+$connection->CacheSelectLimit($secs2cache,$sql,$nrows,$offset).\r
+<p><b>PHP4 Session Handler Support</b> \r
+<p>ADODB also supports PHP4 session handlers. You can store your session variables \r
+  in a database for true scalability using ADODB. For further information, visit \r
+  <a href="http://php.weblogs.com/adodb-sessions"><a href="http://php.weblogs.com/adodb-sessions">http://php.weblogs.com/adodb-sessions</a></a>\r
+<h3>Commercial Use Encouraged</h3>\r
+<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>\r
+\r
+<h2>Conclusion</h2>\r
+<p>As a thank you for finishing this article, here are the complete lyrics for \r
+  <i>let's call the whole thing off</i>.<br>\r
+  <br>\r
+<pre>\r
+   Refrain \r
+<br>\r
+        You say eether and I say eyether, \r
+        You say neether and I say nyther; \r
+        Eether, eyether, neether, nyther - \r
+        Let's call the whole thing off ! \r
+<br>\r
+        You like potato and I like po-tah-to, \r
+        You like tomato and I like to-mah-to; \r
+        Potato, po-tah-to, tomato, to-mah-to - \r
+        Let's call the whole thing off ! \r
+<br>\r
+But oh, if we call the whole thing off, then we must part. \r
+And oh, if we ever part, then that might break my heart. \r
+<br>\r
+        So, if you like pajamas and I like pa-jah-mas, \r
+        I'll wear pajamas and give up pa-jah-mas. \r
+        For we know we \r
+        Need each other, so we \r
+        Better call the calling off off. \r
+        Let's call the whole thing off ! \r
+<br>\r
+   Second Refrain \r
+<br>\r
+        You say laughter and I say lawfter, \r
+        You say after and I say awfter; \r
+        Laughter, lawfter, after, awfter - \r
+        Let's call the whole thing off ! \r
+<br>\r
+        You like vanilla and I like vanella, \r
+        You, sa's'parilla and I sa's'parella; \r
+        Vanilla, vanella, choc'late, strawb'ry - \r
+        Let's call the whole thing off ! \r
+<br>\r
+But oh, if we call the whole thing off, then we must part. \r
+And oh, if we ever part, then that might break my heart. \r
+<br>\r
+        So, if you go for oysters and I go for ersters, \r
+        I'll order oysters and cancel the ersters. \r
+        For we know we \r
+        Need each other, so we \r
+        Better call the calling off off. \r
+        Let's call the whole thing off ! \r
+  </pre>\r
+<p><font size=2>Song and lyrics by George and Ira Gershwin, introduced by Fred Astaire and Ginger Rogers\r
+in the film "Shall We Dance?"  </font><p>\r
+\r
+\r
+</body>\r
+</html>\r
diff --git a/public_html/browser.php b/public_html/browser.php
new file mode 100644 (file)
index 0000000..7acd0df
--- /dev/null
@@ -0,0 +1,46 @@
+<?php\r
+\r
+       /**\r
+        * Main object browser\r
+        *\r
+        * $Id: browser.php,v 1.1 2002/02/11 09:33:08 chriskl Exp $\r
+        */\r
+\r
+       // Include application functions\r
+       include_once('../conf/config.inc');\r
+?>\r
+\r
+<html>\r
+<head>\r
+<title><?= $appName ?></title>\r
+<body>\r
+<?php\r
+\r
+       $databases = &$data->getDatabases();\r
+       while (!$databases->EOF) {\r
+               echo htmlspecialchars($databases->f['datname']), "<br>\n";\r
+               if ($data->hasTables())\r
+                       echo "&nbsp;&nbsp;<a href=\"tables.php?database=", \r
+                               urlencode($databases->f['datname']), "\" target=detail>Tables</a><br>\n";\r
+               if ($data->hasViews())\r
+                       echo "&nbsp;&nbsp;<a href=\"views.php\" target=detail>Views</a><br>\n";\r
+               if ($data->hasSequences())\r
+                       echo "&nbsp;&nbsp;<a href=\"sequences.php\" target=detail>Sequences</a><br>\n";\r
+               if ($data->hasFunctions())\r
+                       echo "&nbsp;&nbsp;<a href=\"functions.php\" target=detail>Functions</a><br>\n";\r
+               if ($data->hasTriggers())\r
+                       echo "&nbsp;&nbsp;<a href=\"triggers.php\" target=detail>Triggers</a><br>\n";\r
+               if ($data->hasOperators())\r
+                       echo "&nbsp;&nbsp;<a href=\"operators.php\" target=detail>Operators</a><br>\n";\r
+               if ($data->hasTypes())\r
+                       echo "&nbsp;&nbsp;<a href=\"types.php\" target=detail>Types</a><br>\n";\r
+               if ($data->hasAggregates())\r
+                       echo "&nbsp;&nbsp;<a href=\"aggregates.php\" target=detail>Aggregates</a><br>\n";\r
+               if ($data->hasRules())\r
+                       echo "&nbsp;&nbsp;<a href=\"rules.php\" target=detail>Rules</a><br>\n";\r
+               $databases->moveNext();\r
+       }\r
+\r
+?>\r
+</body>\r
+</html>\r
diff --git a/public_html/databases.php b/public_html/databases.php
new file mode 100755 (executable)
index 0000000..934d102
--- /dev/null
@@ -0,0 +1,23 @@
+<?php\r
+\r
+       /**\r
+        * List databases in a server\r
+        * @param $webdbServerID The ID of the current server\r
+        *\r
+        * $Id: databases.php,v 1.1 2002/02/11 09:33:08 chriskl Exp $\r
+        */\r
+\r
+       // Include application functions\r
+       include_once('../conf/config.inc');\r
+\r
+?>\r
+\r
+<html>\r
+<body>\r
+\r
+<h1><?= $appName ?></h1>\r
+\r
+<p><?= $appIntro ?></p>\r
+\r
+</body>\r
+</html>
\ No newline at end of file
diff --git a/public_html/index.php b/public_html/index.php
new file mode 100755 (executable)
index 0000000..956cde9
--- /dev/null
@@ -0,0 +1,31 @@
+<?php\r
+\r
+       /**\r
+        * Main access point to WebDB.\r
+        *\r
+        * $Id: index.php,v 1.1 2002/02/11 09:33:08 chriskl Exp $\r
+        */\r
+\r
+       // Include application functions\r
+       include_once('../conf/config.inc');\r
+\r
+?>\r
+\r
+<html>\r
+<head>\r
+<title><?= $appName ?></title>\r
+</head>\r
+\r
+<frameset rows="50, *" border="0" frameborder="0">\r
+       <frame src="topbar.php" name="topbar">\r
+       <frameset cols="<?= $guiLeftFrameWidth ?>,*" border="0" frameborder="0">\r
+         <frame src="browser.php" name="browser">\r
+         <frame src="intro.php" name="detail">\r
+       </frameset>\r
+</frameset>\r
+<noframes>\r
+<body>\r
+       <?= $strNoFrames ?>\r
+</body>\r
+</noframes>\r
+</html>
\ No newline at end of file
diff --git a/public_html/intro.php b/public_html/intro.php
new file mode 100755 (executable)
index 0000000..ffa2521
--- /dev/null
@@ -0,0 +1,22 @@
+<?php\r
+\r
+       /**\r
+        * Intro screen\r
+        *\r
+        * $Id: intro.php,v 1.1 2002/02/11 09:33:08 chriskl Exp $\r
+        */\r
+\r
+       // Include application functions\r
+       include_once('../conf/config.inc');\r
+\r
+?>\r
+\r
+<html>\r
+<body>\r
+\r
+<h1><?= $appName ?></h1>\r
+\r
+<p><?= $appIntro ?></p>\r
+\r
+</body>\r
+</html>
\ No newline at end of file
diff --git a/public_html/login.php b/public_html/login.php
new file mode 100755 (executable)
index 0000000..a8c0331
--- /dev/null
@@ -0,0 +1,68 @@
+<?php\r
+\r
+       /**\r
+        * Login screen\r
+        *\r
+        * $Id: login.php,v 1.1 2002/02/11 09:33:08 chriskl Exp $\r
+        */\r
+\r
+       // Include application functions\r
+       include_once('../conf/config.inc');\r
+\r
+?>\r
+\r
+<html>\r
+       <head>\r
+       <title><?= $appName ?> :: <?= $strLogin ?></title>\r
+       </head>\r
+       \r
+       <body>\r
+               <h1><?= $appName ?> <?= $appVersion ?></h1>\r
+               <table border="0" cellpadding="0" cellspacing="0" width="350">\r
+                       <tr height="115">\r
+                               <td height="115" align="center" valign="middle">\r
+                                       <table border="0" cellpadding="2" cellspacing="0">\r
+                                               <form action="<?= $PHP_SELF ?>" method="post" name="login_form">\r
+                                               <tr>\r
+                                                       <td class="form">Username:</td>\r
+                                                       <td><input type="text" name="formUsername" value="<?php isset($webdbUsername) ? htmlspecialchars($webdbUsername) : '' ?>" size="24"></td>\r
+                                               </tr>\r
+                                               <tr>\r
+                                                       <td class="form">Password:</td>\r
+                                                       <td><input type="password" name="formPassword" size="24"></td>\r
+                                               </tr>\r
+                                               <tr>\r
+                                                       <td class="form">Server:</td>\r
+                                                       <td><select name="formServer">\r
+                                                       <?php\r
+                                                               for ($i = 0; $i < sizeof($confServers); $i++) {\r
+                                                                       echo "<option value=\"{$i}\">", htmlspecialchars($confServers[$i]['desc']), ' (',\r
+                                                                               htmlspecialchars($confServers[$i]['type']), ")</option>\n";\r
+                                                               }\r
+                                                       ?>                                                      \r
+                                                       </select></td>\r
+                                               </tr>\r
+                                               <tr>\r
+                                                       <td colspan="2" align="right" valign="middle">\r
+                                                               <input type="submit" name="submitLogin" value="Login">\r
+                                                       </td>\r
+                                               </tr>\r
+                                               </form>\r
+                                       </table>\r
+                               </td>\r
+                       </tr>\r
+               <script language=javascript>\r
+                       var uname = document.login_form.set_username;\r
+                       var pword = document.login_form.set_password;\r
+                       if (uname.value == "") { \r
+                               uname.focus();\r
+                       } else {\r
+                               pword.focus();\r
+                       }\r
+               </script>\r
+               </table>        \r
+    </td>\r
+  </tr>\r
+</table>\r
+</body>\r
+</html>\r
diff --git a/public_html/topbar.php b/public_html/topbar.php
new file mode 100755 (executable)
index 0000000..aa23d19
--- /dev/null
@@ -0,0 +1,24 @@
+<?php\r
+\r
+       /**\r
+        * Top menu for WebDB\r
+        *\r
+        * $Id: topbar.php,v 1.1 2002/02/11 09:33:08 chriskl Exp $\r
+        */\r
+\r
+       // Include application functions\r
+       include_once('../conf/config.inc');\r
+\r
+?>\r
+\r
+<html>\r
+\r
+<p>\r
+<a href="">Refresh</a> | \r
+<a href="">Execute SQL</a> | \r
+<a href="">Advanced</a> | \r
+<a href="">Preferences</a> | \r
+<a href="">Logout</a>\r
+</p>\r
+\r
+</html>
\ No newline at end of file