<?php
 	/**
	* Database class for PostgreSQL
	* @author SH Online Dienst GmbH Boris Erdmann, Kristian Koehntopp
    * @author Dan Kuykendall, Michael Dean, Dave Hall and others
	* @copyright Copyright (C) 1998-2000 SH Online Dienst GmbH Boris Erdmann, Kristian Koehntopp
	* @copyright Portions Copyright (C) 2001-2004 Free Software Foundation, Inc. http://www.fsf.org/
	* @license http://www.fsf.org/licenses/lgpl.html GNU Lesser General Public License
	* @link http://www.sanisoft.com/phplib/manual/DB_sql.php
	* @package phpgwapi
	* @subpackage database
	* @version $Id: class.db_pgsql.inc.php,v 1.1.1.3.6.1 2004/09/27 10:06:57 kazuyan Exp $
	*/

	/**
	* Database class for PostgreSQL
	* 
	* @package phpgwapi
	* @subpackage database
	* @ignore
	*/
	class db extends db_
	{
		var $Seq_Table = 'db_sequence';

		// PostgreSQL changed somethings from 6.x -> 7.x
		var $db_version;

		function ifadd($add, $me)
		{
			if($add != '')
			{
				return ' ' . $me . $add;
			}
		}

		/**
		* Constructor
		*
		* @param $query SQL query
		*/
		function db($query = '')
		{
			$this->db_($query);
		}

		/**
		 * Connect to database
		 * 
		 * @param string $Database Database name
		 * @param string $Host Database host
		 * @param string $User Database user
		 * @param string $Password Database users password
		 * @return resource Database connection_id
		 */
		function connect($Database = '', $Host = '', $User = '', $Password = '')
		{
			/* Handle defaults */
			if ($Database == '')
			{
				$Database = $this->Database;
			}
			if ($Host == '')
			{
				$Host     = $this->Host;
			}
			if ($User == '')
			{
				$User     = $this->User;
			}
			if ($Password == '')
			{
				$Password = $this->Password;
			}

			if (! $this->Link_ID)
			{
				$cstr = 'dbname=' . $Database
					. $this->ifadd($Host, 'host=')
					. $this->ifadd($Port, 'port=')
					. $this->ifadd($User, 'user=')
					. $this->ifadd("'".$Password."'", 'password=');
				if ($GLOBALS['phpgw_info']['server']['db_persistent'])
				{
					$this->Link_ID=@pg_pconnect($cstr);
				}
				else
				{
					$this->Link_ID=@pg_connect($cstr);
				}

				if (! $this->Link_ID)
				{
					$this->halt('Link-ID == false, '.($GLOBALS['phpgw_info']['server']['db_persistent']?'p':'').'connect failed');
					return 0; 
				}
				else
				{
					$this->query("select version()",__LINE__,__FILE__);
					$this->next_record();

					$version          = $this->f('version');
					$parts            = explode(' ',$version);
					$this->db_version = $parts[1];
				}
			}
			return $this->Link_ID; 
		}

        /**
         * Convert a unix timestamp to a rdms specific timestamp
         *
         * @param int unix timestamp
         * @return string rdms specific timestamp
         */
		function to_timestamp($epoch)
		{
			$db_version = $this->db_version;
			if (floor($db_version) == 6)
			{
				return $this->to_timestamp_6($epoch);
			}
			else
			{
				return $this->to_timestamp_7($epoch);
			}
		}

        /**
         * Convert a rdms specific timestamp to a unix timestamp
         *
         * @param string rdms specific timestamp
         * @return int unix timestamp
         */
		function from_timestamp($timestamp)
		{
			if (floor($this->db_version) == 6)
			{
				return $this->from_timestamp_6($timestamp);
			}
			else
			{
				return $this->from_timestamp_7($timestamp);
			}
		}

        /**
         * Convert a unix timestamp to a rdms specific timestamp in PostgreSQL 6
         *
         * @param int unix timestamp
         * @return string rdms specific timestamp
		 * @access private
         */
		function to_timestamp_6($epoch)
		{

		}

        /**
         * Convert a rdms specific timestamp to a unix timestamp for PostgreSQL 6
         *
         * @param string rdms specific timestamp
         * @return int unix timestamp
		 * @access private
         */
		function from_timestamp_6($timestamp)
		{

		}

        /**
         * Convert a unix timestamp to a rdms specific timestamp in PostgreSQL 7
         *
         * @param int unix timestamp
         * @return string rdms specific timestamp
		 * @access private
         */
		function to_timestamp_7($epoch)
		{
			// This needs the GMT offset!
			if ($GLOBALS['phpgw_info']['server']['tz_offset'] > 0)
				$sign = '+';
			else
				$sign = '-';
			return date('Y-m-d H:i:s'.$sign.sprintf('%02d', abs($GLOBALS['phpgw_info']['server']['tz_offset'])),$epoch);
		}

        /**
         * Convert a rdms specific timestamp to a unix timestamp for PostgreSQL 6
         *
         * @param string rdms specific timestamp
         * @return int unix timestamp
		 * @access private
         */
		function from_timestamp_7($timestamp)
		{
			ereg('([0-9]{4})-([0-9]{2})-([0-9]{2}) ([0-9]{2}):([0-9]{2}):([0-9]{2})',$timestamp,$parts);
	
			return mktime($parts[4],$parts[5],$parts[6],$parts[2],$parts[3],$parts[1]);
		}

		/**
		 * Disconnect database connection
		 *
		 * This only affects systems not using persistant connections 
		 * @return integer 1: ok; 0: not possible/already closed
		 */
		function disconnect()
		{
			return @pg_close($this->Link_ID);
		}

        /**
         * Execute a query
         *
         * @param string $Query_String the query to be executed
         * @param mixed $line the line method was called from - use __LINE__
         * @param string $file the file method was called from - use __FILE__
         * @return integer Current result if sucesful and null if failed
         */
		function query($Query_String, $line = '', $file = '')
		{
			if ($Query_String == '')
			{
				return 0;
			}
			if (!$this->connect())
			{
				return 0; /* we already complained in connect() about that. */
			};
			# New query, discard previous result.
			if ($this->Query_ID)
			{
				$this->free();
			} 
			
			if ($this->Debug)
			{
				printf("Debug: query = %s<br>\n", $Query_String);
			} 

			$this->Query_ID = @pg_Exec($this->Link_ID, $Query_String);
			$this->Row   = 0;

			$this->Error = @pg_ErrorMessage($this->Link_ID);
			$this->Errno = ($this->Error == '') ? 0 : 1;
			if (! $this->Query_ID)
			{
				$this->halt('Invalid SQL: ' . $Query_String, $line, $file);
				return 0; 
			}
			# Will return nada if it fails. That's fine. 
			return $this->Query_ID;
		}

        /**
         * Execute a query with limited result set
         *
         * @param string $Query_String the query to be executed
         * @param integer $offset row to start from
         * @param mixed $line the line method was called from - use __LINE__
         * @param string $file the file method was called from - use __FILE__
         * @param int $num_rows number of rows to return (optional), if unset will use $GLOBALS['phpgw_info']['user']['preferences']['common']['maxmatchs']
         * @return integer Current result if sucesful and null if failed
         */
		function limit_query($Query_String, $offset, $line = '', $file = '', $num_rows = 0)
		{
			$offset		= intval($offset);
			$num_rows	= intval($num_rows);

			if ($num_rows == 0)
			{
				$maxmatches = $GLOBALS['phpgw_info']['user']['preferences']['common']['maxmatchs'];
				$num_rows = (isset($maxmatches)?intval($maxmatches):15);
			}

			if ($offset == 0)
			{
				$Query_String .= ' LIMIT ' . $num_rows;
			}
			else
			{
				$Query_String .= ' LIMIT ' . $num_rows . ' OFFSET ' . $offset;
			}

			if ($this->Debug)
			{
				printf("Debug: limit_query = %s<br>offset=%d, num_rows=%d<br>\n", $Query_String, $offset, $num_rows);
			}

			return $this->query($Query_String, $line, $file);
		}

		function free()
		{
			@pg_freeresult($this->Query_ID);
			$this->Query_ID = 0;
		}

        /**
         * Move to the next row in the results set
         *
         * @return boolean was another row found?
         */
		function next_record()
		{
			$this->Record = @pg_fetch_array($this->Query_ID, $this->Row++);

			if ($this->Link_ID)
			{ 
				$this->Error = pg_ErrorMessage($this->Link_ID);
				$this->Errno = ($this->Error == '') ? 0 : 1;
			}

			$stat = is_array($this->Record);
			if (!$stat && $this->Auto_Free)
			{
				pg_freeresult($this->Query_ID);
				$this->Query_ID = 0;
			}
			return $stat;
		}

        /**
         * Move to position in result set
         *
         * @param integer $pos Required row (optional), default first row
         * @return integer 1 if sucessful or 0 if not found
         */
		function seek($pos)
		{
			$this->Row = $pos;
		}

		function transaction_begin()
		{
			return $this->query('begin');
		}

        /**
         * Complete the transaction
         *
         * @return boolean True if sucessful, False if failed
         */
		function transaction_commit()
		{
			if (! $this->Errno)
			{
				return pg_Exec($this->Link_ID,'commit');
			}
			else
			{
				return False;
			}
		}

        /**
         * Rollback the current transaction
         *
         * @return boolean True if sucessful, False if failed
         */
		function transaction_abort()
		{
			return @pg_Exec($this->Link_ID,'rollback');
		}

        /**
         * Find the primary key of the last insertion on the current db connection
         *
         * @param string $table name of table the insert was performed on
         * @param string $field the autoincrement primary key of the table
         * @return integer The id, -1 if failed
         */
		function get_last_insert_id($table, $field)
		{
			if (!isset($table) || $table == '' || !isset($field) || $field == '')
			{
				return -1;
			}

			$oid = pg_getlastoid($this->Query_ID);
			if ($oid == -1)
			{
				return -1;
			}

			$result = @pg_Exec($this->Link_ID, "select $field from $table where oid=$oid");
			if (!$result)
			{
				return -1;
			}

			$Record = @pg_fetch_array($result, 0);
			@pg_freeresult($result);
			if (!is_array($Record)) /* OID not found? */
			{
				return -1;
			}

			return $Record[0];
		}

        /**
         * Lock a table
         *
         * @param string $table name of table to lock
         * @param string $mode type of lock required (optional), default write
         * @return boolean True if sucessful, False if failed
         */
		function lock($table, $mode = 'write')
		{
			$result = $this->transaction_begin();

			if ($mode == 'write')
			{
				if (is_array($table))
				{
					while ($t = each($table))
					{
						$result = pg_Exec($this->Link_ID,'lock table ' . $t[1] . ' in share mode');
					}
				}
				else
				{
					$result = pg_Exec($this->Link_ID, 'lock table ' . $table . ' in share mode');
				}
			}
			else
			{
				$result = 1;
			}

			return $result;
		}

        /**
         * Unlock a table
         *
         * @return boolean True if sucessful, False if failed
         */
		function unlock()
		{
			return $this->transaction_commit();
		}


        /**
         * Get the id for the next sequence
         *
         * @param string $seq_name Name of the sequence
         * @return integer sequence id
         */
		function nextid($seq_name)
		{
			$this->connect();

			if ($this->lock($this->Seq_Table))
			{
				/* get sequence number (locked) and increment */
				$q  = sprintf("select nextid from %s where seq_name = '%s'",
					$this->Seq_Table,
					$seq_name);
				$id  = @pg_Exec($this->Link_ID, $q);
				$res = @pg_Fetch_Array($id, 0);

				/* No current value, make one */
				if (!is_array($res))
				{
					$currentid = 0;
					$q = sprintf("insert into %s values('%s', %s)",
						$this->Seq_Table,
						$seq_name,
						$currentid);
					$id = @pg_Exec($this->Link_ID, $q);
				}
				else
				{
					$currentid = $res['nextid'];
				}
				$nextid = $currentid + 1;
				$q = sprintf("update %s set nextid = '%s' where seq_name = '%s'",
					$this->Seq_Table,
					$nextid,
					$seq_name);
				$id = @pg_Exec($this->Link_ID, $q);
				$this->unlock();
			}
			else
			{
				$this->halt('cannot lock ' . $this->Seq_Table . ' - has it been created?');
				return 0;
			}
			return $nextid;
		}

        /**
         * Get description of a table
         *
         * @param string $table name of table to describe
         * @param boolean $full optional, default False summary information, True full information
         * @return array Table meta data
         */
		function metadata($table)
		{
			$count = 0;
			$id    = 0;
			$res   = array();

			$this->connect();
			$id = pg_exec($this->Link_ID, "select * from $table");
			if ($id < 0)
			{
				$this->Error = pg_ErrorMessage($id);
				$this->Errno = 1;
				$this->halt('Metadata query failed.');
			}
			$count = pg_NumFields($id);

			for ($i=0; $i<$count; $i++)
			{
				$res[$i]['table'] = $table;
				$res[$i]['name']  = pg_FieldName  ($id, $i); 
				$res[$i]['type']  = pg_FieldType  ($id, $i);
				$res[$i]['len']   = pg_FieldSize  ($id, $i);
				$res[$i]['flags'] = '';
			}

			pg_FreeResult($id);
			return $res;
		}

        /**
         * Get the number of rows affected by last update
         *
         * @return integer number of affected rows
         */
		function affected_rows()
		{
			return pg_cmdtuples($this->Query_ID);
		}

        /**
         * Number of rows in current result set
         *
         * @return integer number of rows
         */
		function num_rows()
		{
			return pg_numrows($this->Query_ID);
		}

        /**
         * Number of fields in current row
         *
         * @return integer number of fields
         */
		function num_fields()
		{
			return pg_numfields($this->Query_ID);
		}

        /**
        * Error handler
        *
        * @param string $msg error message
        * @param integer $line line of calling method/function (optional)
        * @param string $file file of calling method/function (optional)
		* @access private
        */
		function halt($msg, $line = '', $file = '')
		{ 
			/* private: error handling */ 
			if ($this->Halt_On_Error == 'no')
			{
				$this->Error = @pg_ErrorMessage($this->Link_ID);
				$this->Errno = 1;
				return;
			}

			/* Just in case there is a table currently locked */
			$this->transaction_abort();


			if ($this->xmlrpc || $this->soap)
			{
				$s = sprintf("Database error: %s\n", $msg);
				$s .= sprintf("PostgreSQL Error: %s\n\n (%s)\n\n",$this->Errno,$this->Error);
			}
			else
			{
				$s = sprintf("<b>Database error:</b> %s<br>\n", $msg);
				$s .= sprintf("<b>PostgreSQL Error</b>: %s (%s)<br>\n",$this->Errno,$this->Error);
			}

			if ($file)
			{
				if ($this->xmlrpc || $this->soap)
				{
					$s .=	sprintf("File: %s\n",$file);
				}
				else
				{
					$s .=	sprintf("<br><b>File:</b> %s",$file);
				}
			}

			if ($line)
			{
				if ($this->xmlrpc || $this->soap)
				{
					$s .=	sprintf("Line: %s\n",$line);
				}
				else
				{
					$s .=	sprintf("<br><b>Line:</b> %s",$line);
				}
			}

			if ($this->Halt_On_Error == 'yes')
			{
				if (! $this->xmlrpc && ! $this->soap)
				{
					$s .= '<p><b>Session halted.</b>';
				}
			}

			if ($this->xmlrpc)
			{
				xmlrpcfault($s);
			}
			elseif ($this->soap)
			{

			}
			else
			{
				echo $s;
				$GLOBALS['phpgw']->common->phpgw_exit(True);
			}
		}

        /**
         * Get a list of table names in the current database
         *
         * @return array List of the tables
         */
		function table_names()
		{
			$return = array();
			$this->query("select relname from pg_class where relkind = 'r' and not relname like 'pg_%'");
			$i=0;
			while ($this->next_record())
			{
				$return[$i]['table_name']= $this->f(0);
				$return[$i]['tablespace_name']=$this->Database;
				$return[$i]['database']=$this->Database;
				$i++;
			}
			return $return;
		}

		function index_names()
		{
			$this->query("SELECT relname FROM pg_class WHERE NOT relname ~ 'pg_.*' AND relkind ='i' ORDER BY relname");
			$i=0;
			while ($this->next_record())
			{
				$return[$i]['index_name']= $this->f(0);
				$return[$i]['tablespace_name']=$this->Database;
				$return[$i]['database']=$this->Database;
				$i++;
			}
			return $return;
		}

        /**
         * Create a new database
         *
         * @param string $adminname Name of database administrator user (optional)
         * @param string $adminpasswd Password for the database administrator user (optional)
         */
		function create_database($adminname = '', $adminpasswd = '')
		{
			$currentUser = $this->User;
			$currentPassword = $this->Password;
			$currentDatabase = $this->Database;

			if ($adminname != "")
			{
				$this->User = $adminname;
				$this->Password = $adminpasswd;
				$this->Database = 'template1'; 
			}
			
			/*
			This doesn't work if the httpd server user doesn't have execute permissions on the createdb program
			*/ 
			/*
			if (! $this->Host)
			{
				system('createdb ' . $currentDatabase, $outval);
			}
			else
			{
				system('createdb -h ' . $this->Host . ' ' . $currentDatabase, $outval);
			}

			if($outval != 0) 
			{
				// either the rights are not available or the postmaster is not running .... 
				echo 'database creation failure <BR>';
				echo 'please setup the postreSQL database manually<BR>';
			}*/
			
			$this->query("CREATE DATABASE $currentDatabase");
			$this->query("grant all on $currentDatabase.* to $currentUser@localhost identified by '$currentPassword'"); 

			$this->User = $currentUser;
			$this->Password = $currentPassword;
			$this->Database = $currentDatabase;
			$this->connect();
			//return $return;
		}
	}

