Index: trunk/phpgwapi/inc/adodb/adodb-datadict.inc.php
===================================================================
--- trunk/phpgwapi/inc/adodb/adodb-datadict.inc.php	(revision 2)
+++ trunk/phpgwapi/inc/adodb/adodb-datadict.inc.php	(revision 34)
@@ -2,5 +2,5 @@
 
 /**
-  V4.51 29 July 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
+  V4.94 23 Jan 2007  (c) 2000-2007 John Lim (jlim#natsoft.com.my). All rights reserved.
   Released under both BSD license and Lesser GPL library license. 
   Whenever there is any discrepancy between the two licenses, 
@@ -23,5 +23,5 @@
 function Lens_ParseTest()
 {
-$str = "`zcol ACOL` NUMBER(32,2) DEFAULT 'The \"cow\" (and Jim''s dog) jumps over the moon' PRIMARY, INTI INT AUTO DEFAULT 0";
+$str = "`zcol ACOL` NUMBER(32,2) DEFAULT 'The \"cow\" (and Jim''s dog) jumps over the moon' PRIMARY, INTI INT AUTO DEFAULT 0, zcol2\"afs ds";
 print "<p>$str</p>";
 $a= Lens_ParseArgs($str);
@@ -30,4 +30,5 @@
 print "</pre>";
 }
+
 
 if (!function_exists('ctype_alnum')) {
@@ -61,4 +62,5 @@
 	$max = strlen($args);
 	$quoted = false;
+	$tokarr = array();
 	
 	while ($pos < $max) {
@@ -154,4 +156,5 @@
 		$pos += 1;
 	}
+	if ($intoken) $tokens[$stmtno][] = implode('',$tokarr);
 	
 	return $tokens;
@@ -163,13 +166,17 @@
 	var $debug = false;
 	var $dropTable = 'DROP TABLE %s';
+	var $renameTable = 'RENAME TABLE %s TO %s'; 
 	var $dropIndex = 'DROP INDEX %s';
 	var $addCol = ' ADD';
 	var $alterCol = ' ALTER COLUMN';
 	var $dropCol = ' DROP COLUMN';
+	var $renameColumn = 'ALTER TABLE %s RENAME COLUMN %s TO %s';	// table, old-column, new-column, column-definitions (not used by default)
 	var $nameRegex = '\w';
+	var $nameRegexBrackets = 'a-zA-Z0-9_\(\)';
 	var $schema = false;
 	var $serverInfo = array();
 	var $autoIncrement = false;
 	var $dataProvider;
+	var $invalidResizeTypes4 = array('CLOB','BLOB','TEXT','DATE','TIME'); // for changetablesql
 	var $blobSize = 100; 	/// any varchar/char field this size or greater is treated as a blob
 							/// in other words, we use a text area for editting.
@@ -185,30 +192,142 @@
 	}
 	
-	function &MetaTables()
-	{
+	function MetaTables()
+	{
+		if (!$this->connection->IsConnected()) return array();
 		return $this->connection->MetaTables();
 	}
 	
-	function &MetaColumns($tab, $upper=true, $schema=false)
-	{
+	function MetaColumns($tab, $upper=true, $schema=false)
+	{
+		if (!$this->connection->IsConnected()) return array();
 		return $this->connection->MetaColumns($this->TableName($tab), $upper, $schema);
 	}
 	
-	function &MetaPrimaryKeys($tab,$owner=false,$intkey=false)
-	{
+	function MetaPrimaryKeys($tab,$owner=false,$intkey=false)
+	{
+		if (!$this->connection->IsConnected()) return array();
 		return $this->connection->MetaPrimaryKeys($this->TableName($tab), $owner, $intkey);
 	}
 	
-	function &MetaIndexes($table, $primary = false, $owner = false)
-	{
+	function MetaIndexes($table, $primary = false, $owner = false)
+	{
+		if (!$this->connection->IsConnected()) return array();
 		return $this->connection->MetaIndexes($this->TableName($table), $primary, $owner);
 	}
 	
+
 	function MetaType($t,$len=-1,$fieldobj=false)
-	{
-		return ADORecordSet::MetaType($t,$len,$fieldobj);
-	}
-	
-	function NameQuote($name = NULL)
+	{		
+		static $typeMap = array(
+		'VARCHAR' => 'C',
+		'VARCHAR2' => 'C',
+		'CHAR' => 'C',
+		'C' => 'C',
+		'STRING' => 'C',
+		'NCHAR' => 'C',
+		'NVARCHAR' => 'C',
+		'VARYING' => 'C',
+		'BPCHAR' => 'C',
+		'CHARACTER' => 'C',
+		'INTERVAL' => 'C',  # Postgres
+		'MACADDR' => 'C', # postgres
+		##
+		'LONGCHAR' => 'X',
+		'TEXT' => 'X',
+		'NTEXT' => 'X',
+		'M' => 'X',
+		'X' => 'X',
+		'CLOB' => 'X',
+		'NCLOB' => 'X',
+		'LVARCHAR' => 'X',
+		##
+		'BLOB' => 'B',
+		'IMAGE' => 'B',
+		'BINARY' => 'B',
+		'VARBINARY' => 'B',
+		'LONGBINARY' => 'B',
+		'B' => 'B',
+		##
+		'YEAR' => 'D', // mysql
+		'DATE' => 'D',
+		'D' => 'D',
+		##
+		'UNIQUEIDENTIFIER' => 'C', # MS SQL Server
+		##
+		'TIME' => 'T',
+		'TIMESTAMP' => 'T',
+		'DATETIME' => 'T',
+		'TIMESTAMPTZ' => 'T',
+		'T' => 'T',
+		'TIMESTAMP WITHOUT TIME ZONE' => 'T', // postgresql
+		##
+		'BOOL' => 'L',
+		'BOOLEAN' => 'L', 
+		'BIT' => 'L',
+		'L' => 'L',
+		##
+		'COUNTER' => 'R',
+		'R' => 'R',
+		'SERIAL' => 'R', // ifx
+		'INT IDENTITY' => 'R',
+		##
+		'INT' => 'I',
+		'INT2' => 'I',
+		'INT4' => 'I',
+		'INT8' => 'I',
+		'INTEGER' => 'I',
+		'INTEGER UNSIGNED' => 'I',
+		'SHORT' => 'I',
+		'TINYINT' => 'I',
+		'SMALLINT' => 'I',
+		'I' => 'I',
+		##
+		'LONG' => 'N', // interbase is numeric, oci8 is blob
+		'BIGINT' => 'N', // this is bigger than PHP 32-bit integers
+		'DECIMAL' => 'N',
+		'DEC' => 'N',
+		'REAL' => 'N',
+		'DOUBLE' => 'N',
+		'DOUBLE PRECISION' => 'N',
+		'SMALLFLOAT' => 'N',
+		'FLOAT' => 'N',
+		'NUMBER' => 'N',
+		'NUM' => 'N',
+		'NUMERIC' => 'N',
+		'MONEY' => 'N',
+		
+		## informix 9.2
+		'SQLINT' => 'I', 
+		'SQLSERIAL' => 'I', 
+		'SQLSMINT' => 'I', 
+		'SQLSMFLOAT' => 'N', 
+		'SQLFLOAT' => 'N', 
+		'SQLMONEY' => 'N', 
+		'SQLDECIMAL' => 'N', 
+		'SQLDATE' => 'D', 
+		'SQLVCHAR' => 'C', 
+		'SQLCHAR' => 'C', 
+		'SQLDTIME' => 'T', 
+		'SQLINTERVAL' => 'N', 
+		'SQLBYTES' => 'B', 
+		'SQLTEXT' => 'X',
+		 ## informix 10
+		"SQLINT8" => 'I8',
+		"SQLSERIAL8" => 'I8',
+		"SQLNCHAR" => 'C',
+		"SQLNVCHAR" => 'C',
+		"SQLLVARCHAR" => 'X',
+		"SQLBOOL" => 'L'
+		);
+		
+		if (!$this->connection->IsConnected()) {
+			$t = strtoupper($t);
+			if (isset($typeMap[$t])) return $typeMap[$t];
+			return 'N';
+		}
+		return $this->connection->MetaType($t,$len,$fieldobj);
+	}
+	
+	function NameQuote($name = NULL,$allowBrackets=false)
 	{
 		if (!is_string($name)) {
@@ -230,5 +349,7 @@
 		
 		// if name contains special characters, quote it
-		if ( !preg_match('/^[' . $this->nameRegex . ']+$/', $name) ) {
+		$regex = ($allowBrackets) ? $this->nameRegexBrackets : $this->nameRegex;
+		
+		if ( !preg_match('/^[' . $regex . ']+$/', $name) ) {
 			return $quote . $name . $quote;
 		}
@@ -265,5 +386,5 @@
 	}
 	
-	/*
+	/**
 	 	Returns the actual type given a character code.
 		
@@ -311,5 +432,6 @@
 		
 		foreach($flds as $key => $fld) {
-			$flds[$key] = $this->NameQuote($fld);
+			# some indexes can use partial fields, eg. index first 32 chars of "name" with NAME(32)
+			$flds[$key] = $this->NameQuote($fld,$allowBrackets=true);
 		}
 		
@@ -331,25 +453,87 @@
 		$tabname = $this->TableName ($tabname);
 		$sql = array();
-		list($lines,$pkey) = $this->_GenFields($flds);
+		list($lines,$pkey,$idxs) = $this->_GenFields($flds);
+		// genfields can return FALSE at times
+		if ($lines  == null) $lines = array();
 		$alter = 'ALTER TABLE ' . $tabname . $this->addCol . ' ';
 		foreach($lines as $v) {
 			$sql[] = $alter . $v;
 		}
+		if (is_array($idxs)) {
+			foreach($idxs as $idx => $idxdef) {
+				$sql_idxs = $this->CreateIndexSql($idx, $tabname, $idxdef['cols'], $idxdef['opts']);
+				$sql = array_merge($sql, $sql_idxs);
+			}
+		}
 		return $sql;
 	}
 	
-	function AlterColumnSQL($tabname, $flds)
+	/**
+	 * Change the definition of one column
+	 *
+	 * As some DBM's can't do that on there own, you need to supply the complete defintion of the new table,
+	 * to allow, recreating the table and copying the content over to the new table
+	 * @param string $tabname table-name
+	 * @param string $flds column-name and type for the changed column
+	 * @param string $tableflds='' complete defintion of the new table, eg. for postgres, default ''
+	 * @param array/string $tableoptions='' options for the new table see CreateTableSQL, default ''
+	 * @return array with SQL strings
+	 */
+	function AlterColumnSQL($tabname, $flds, $tableflds='',$tableoptions='')
 	{
 		$tabname = $this->TableName ($tabname);
 		$sql = array();
-		list($lines,$pkey) = $this->_GenFields($flds);
+		list($lines,$pkey,$idxs) = $this->_GenFields($flds);
+		// genfields can return FALSE at times
+		if ($lines == null) $lines = array();
 		$alter = 'ALTER TABLE ' . $tabname . $this->alterCol . ' ';
 		foreach($lines as $v) {
 			$sql[] = $alter . $v;
 		}
+		if (is_array($idxs)) {
+			foreach($idxs as $idx => $idxdef) {
+				$sql_idxs = $this->CreateIndexSql($idx, $tabname, $idxdef['cols'], $idxdef['opts']);
+				$sql = array_merge($sql, $sql_idxs);
+			}
+
+		}
 		return $sql;
 	}
 	
-	function DropColumnSQL($tabname, $flds)
+	/**
+	 * Rename one column
+	 *
+	 * Some DBM's can only do this together with changeing the type of the column (even if that stays the same, eg. mysql)
+	 * @param string $tabname table-name
+	 * @param string $oldcolumn column-name to be renamed
+	 * @param string $newcolumn new column-name
+	 * @param string $flds='' complete column-defintion-string like for AddColumnSQL, only used by mysql atm., default=''
+	 * @return array with SQL strings
+	 */
+	function RenameColumnSQL($tabname,$oldcolumn,$newcolumn,$flds='')
+	{
+		$tabname = $this->TableName ($tabname);
+		if ($flds) {
+			list($lines,$pkey,$idxs) = $this->_GenFields($flds);
+			// genfields can return FALSE at times
+			if ($lines == null) $lines = array();
+			list(,$first) = each($lines);
+			list(,$column_def) = split("[\t ]+",$first,2);
+		}
+		return array(sprintf($this->renameColumn,$tabname,$this->NameQuote($oldcolumn),$this->NameQuote($newcolumn),$column_def));
+	}
+		
+	/**
+	 * Drop one column
+	 *
+	 * Some DBM's can't do that on there own, you need to supply the complete defintion of the new table,
+	 * to allow, recreating the table and copying the content over to the new table
+	 * @param string $tabname table-name
+	 * @param string $flds column-name and type for the changed column
+	 * @param string $tableflds='' complete defintion of the new table, eg. for postgres, default ''
+	 * @param array/string $tableoptions='' options for the new table see CreateTableSQL, default ''
+	 * @return array with SQL strings
+	 */
+	function DropColumnSQL($tabname, $flds, $tableflds='',$tableoptions='')
 	{
 		$tabname = $this->TableName ($tabname);
@@ -368,12 +552,17 @@
 	}
 	
-	/*
+	function RenameTableSQL($tabname,$newname)
+	{
+		return array (sprintf($this->renameTable, $this->TableName($tabname),$this->TableName($newname)));
+	}	
+	
+	/**
 	 Generate the SQL to create table. Returns an array of sql strings.
 	*/
-	function CreateTableSQL($tabname, $flds, $tableoptions=false)
-	{
-		if (!$tableoptions) $tableoptions = array();
-		
-		list($lines,$pkey) = $this->_GenFields($flds);
+	function CreateTableSQL($tabname, $flds, $tableoptions=array())
+	{
+		list($lines,$pkey,$idxs) = $this->_GenFields($flds, true);
+		// genfields can return FALSE at times
+		if ($lines == null) $lines = array();
 		
 		$taboptions = $this->_Options($tableoptions);
@@ -381,11 +570,25 @@
 		$sql = $this->_TableSQL($tabname,$lines,$pkey,$taboptions);
 		
+		// ggiunta - 2006/10/12 - KLUDGE:
+        // if we are on autoincrement, and table options includes REPLACE, the
+        // autoincrement sequence has already been dropped on table creation sql, so
+        // we avoid passing REPLACE to trigger creation code. This prevents
+        // creating sql that double-drops the sequence
+        if ($this->autoIncrement && isset($taboptions['REPLACE']))
+        	unset($taboptions['REPLACE']);
 		$tsql = $this->_Triggers($tabname,$taboptions);
 		foreach($tsql as $s) $sql[] = $s;
 		
+		if (is_array($idxs)) {
+			foreach($idxs as $idx => $idxdef) {
+				$sql_idxs = $this->CreateIndexSql($idx, $tabname,  $idxdef['cols'], $idxdef['opts']);
+				$sql = array_merge($sql, $sql_idxs);
+			}
+		}
+
 		return $sql;
 	}
 	
-	function _GenFields($flds)
+	function _GenFields($flds,$widespacing=false)
 	{
 		if (is_string($flds)) {
@@ -399,4 +602,7 @@
 				foreach($f0 as $token) {
 					switch (strtoupper($token)) {
+					case 'INDEX':
+						$f1['INDEX'] = '';
+						// fall through intentionally
 					case 'CONSTRAINT':
 					case 'DEFAULT': 
@@ -410,4 +616,18 @@
 					}
 				}
+				// 'index' token without a name means single column index: name it after column
+				if (array_key_exists('INDEX', $f1) && $f1['INDEX'] == '') {
+					$f1['INDEX'] = isset($f0['NAME']) ? $f0['NAME'] : $f0[0];
+					// check if column name used to create an index name was quoted
+					if (($f1['INDEX'][0] == '"' || $f1['INDEX'][0] == "'" || $f1['INDEX'][0] == "`") &&
+						($f1['INDEX'][0] == substr($f1['INDEX'], -1))) {
+						$f1['INDEX'] = $f1['INDEX'][0].'idx_'.substr($f1['INDEX'], 1, -1).$f1['INDEX'][0];
+					}
+					else
+						$f1['INDEX'] = 'idx_'.$f1['INDEX'];
+				}
+				// reset it, so we don't get next field 1st token as INDEX...
+				$hasparam = false;
+
 				$flds[] = $f1;
 				
@@ -417,7 +637,8 @@
 		$lines = array();
 		$pkey = array();
+		$idxs = array();
 		foreach($flds as $fld) {
 			$fld = _array_change_key_case($fld);
-		
+			
 			$fname = false;
 			$fdefault = false;
@@ -433,4 +654,6 @@
 			$fnotnull = false;
 			$funsigned = false;
+			$findex = '';
+			$funiqueindex = false;
 			
 			//-----------------
@@ -458,5 +681,6 @@
 				case 'AUTO':	$fautoinc = true; $fnotnull = true; break;
 				case 'KEY':
-				case 'PRIMARY':	$fprimary = $v; $fnotnull = true; break;
+                // a primary key col can be non unique in itself (if key spans many cols...)
+				case 'PRIMARY':	$fprimary = $v; $fnotnull = true; /*$funiqueindex = true;*/ break;
 				case 'DEF':
 				case 'DEFAULT': $fdefault = $v; break;
@@ -466,4 +690,7 @@
 				case 'DEFTIMESTAMP': $fdefts = $v; break;
 				case 'CONSTRAINT': $fconstraint = $v; break;
+				// let INDEX keyword create a 'very standard' index on column
+				case 'INDEX': $findex = $v; break;
+				case 'UNIQUE': $funiqueindex = true; break;
 				} //switch
 			} // foreach $fld
@@ -495,4 +722,25 @@
 			if ($ty == 'X') $fdefault = false;
 			
+			// build list of indexes
+			if ($findex != '') {
+				if (array_key_exists($findex, $idxs)) {
+					$idxs[$findex]['cols'][] = ($fname);
+					if (in_array('UNIQUE', $idxs[$findex]['opts']) != $funiqueindex) {
+						if ($this->debug) ADOConnection::outp("Index $findex defined once UNIQUE and once not");
+					}
+					if ($funiqueindex && !in_array('UNIQUE', $idxs[$findex]['opts']))
+						$idxs[$findex]['opts'][] = 'UNIQUE';
+				}
+				else
+				{
+					$idxs[$findex] = array();
+					$idxs[$findex]['cols'] = array($fname);
+					if ($funiqueindex)
+						$idxs[$findex]['opts'] = array('UNIQUE');
+					else
+						$idxs[$findex]['opts'] = array();
+				}
+			}
+
 			//--------------------
 			// CONSTRUCT FIELD SQL
@@ -509,14 +757,36 @@
 					$fdefault = $this->connection->sysDate;
 				}
-			} else if (strlen($fdefault) && !$fnoquote)
+			} else if ($fdefault !== false && !$fnoquote) {
 				if ($ty == 'C' or $ty == 'X' or 
-					( substr($fdefault,0,1) != "'" && !is_numeric($fdefault)))
+					( substr($fdefault,0,1) != "'" && !is_numeric($fdefault))) {
+
+					if (($ty == 'D' || $ty == 'T') && strtolower($fdefault) != 'null') {
+						// convert default date into database-aware code
+						if ($ty == 'T')
+						{
+							$fdefault = $this->connection->DBTimeStamp($fdefault);
+						}
+						else
+						{
+							$fdefault = $this->connection->DBDate($fdefault);
+						}
+					}
+					else
 					if (strlen($fdefault) != 1 && substr($fdefault,0,1) == ' ' && substr($fdefault,strlen($fdefault)-1) == ' ') 
 						$fdefault = trim($fdefault);
 					else if (strtolower($fdefault) != 'null')
 						$fdefault = $this->connection->qstr($fdefault);
+				}
+			}
 			$suffix = $this->_CreateSuffix($fname,$ftype,$fnotnull,$fdefault,$fautoinc,$fconstraint,$funsigned);
 			
-			$fname = str_pad($fname,16);
+			// add index creation
+			if ($widespacing) $fname = str_pad($fname,24);
+			
+			 // check for field names appearing twice
+            if (array_key_exists($fid, $lines)) {
+            	 ADOConnection::outp("Field '$fname' defined twice");
+            }
+			
 			$lines[$fid] = $fname.' '.$ftype.$suffix;
 			
@@ -524,7 +794,8 @@
 		} // foreach $flds
 		
-		return array($lines,$pkey);
-	}
-	/*
+		return array($lines,$pkey,$idxs);
+	}
+
+	/**
 		 GENERATE THE SIZE PART OF THE DATATYPE
 			$ftype is the actual type
@@ -619,5 +890,5 @@
 	}
 	
-	/*
+	/**
 		GENERATE TRIGGERS IF NEEDED
 		used when table has auto-incrementing field that is emulated using triggers
@@ -628,5 +899,5 @@
 	}
 	
-	/*
+	/**
 		Sanitize options, so that array elements with no keys are promoted to keys
 	*/
@@ -642,6 +913,6 @@
 	}
 	
-	/*
-	"Florian Buzin [ easywe ]" <florian.buzin@easywe.de>
+	/**
+	"Florian Buzin [ easywe ]" <florian.buzin#easywe.de>
 	
 	This function changes/adds new fields to your table. You don't
@@ -650,17 +921,69 @@
 	function ChangeTableSQL($tablename, $flds, $tableoptions = false)
 	{
+	global $ADODB_FETCH_MODE;
+	
+		$save = $ADODB_FETCH_MODE;
+		$ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
+		if ($this->connection->fetchMode !== false) $savem = $this->connection->SetFetchMode(false);
+		
 		// check table exists
-		$cols = &$this->MetaColumns($tablename);
+		$save_handler = $this->connection->raiseErrorFn;
+		$this->connection->raiseErrorFn = '';
+		$cols = $this->MetaColumns($tablename);
+		$this->connection->raiseErrorFn = $save_handler;
+		
+		if (isset($savem)) $this->connection->SetFetchMode($savem);
+		$ADODB_FETCH_MODE = $save;
+		
 		if ( empty($cols)) { 
 			return $this->CreateTableSQL($tablename, $flds, $tableoptions);
 		}
 		
+		if (is_array($flds)) {
+		// Cycle through the update fields, comparing
+		// existing fields to fields to update.
+		// if the Metatype and size is exactly the
+		// same, ignore - by Mark Newham
+			$holdflds = array();
+			foreach($flds as $k=>$v) {
+				if ( isset($cols[$k]) && is_object($cols[$k]) ) {
+					// If already not allowing nulls, then don't change
+					$obj = $cols[$k];
+					if (isset($obj->not_null) && $obj->not_null)
+						$v = str_replace('NOT NULL','',$v);
+
+					$c = $cols[$k];
+					$ml = $c->max_length;
+					$mt = $this->MetaType($c->type,$ml);
+					if ($ml == -1) $ml = '';
+					if ($mt == 'X') $ml = $v['SIZE'];
+					if (($mt != $v['TYPE']) ||  $ml != $v['SIZE']) {
+						$holdflds[$k] = $v;
+					}
+				} else {
+					$holdflds[$k] = $v;
+				}		
+			}
+			$flds = $holdflds;
+		}
+	
+
 		// already exists, alter table instead
-		list($lines,$pkey) = $this->_GenFields($flds);
+		list($lines,$pkey,$idxs) = $this->_GenFields($flds);
+		// genfields can return FALSE at times
+		if ($lines == null) $lines = array();
 		$alter = 'ALTER TABLE ' . $this->TableName($tablename);
 		$sql = array();
-		
+
 		foreach ( $lines as $id => $v ) {
 			if ( isset($cols[$id]) && is_object($cols[$id]) ) {
+			
+				$flds = Lens_ParseArgs($v,',');
+				
+				//  We are trying to change the size of the field, if not allowed, simply ignore the request.
+				if ($flds && in_array(strtoupper(substr($flds[0][1],0,4)),$this->invalidResizeTypes4)) {
+					echo "<h3>$this->alterCol cannot be changed to $flds currently</h3>";
+					continue;	 
+	 			}
 				$sql[] = $alter . $this->alterCol . ' ' . $v;
 			} else {
