<?php
	
/**
 * class db is used for establishing connection to the database
 * 
 * 
 * @copyright RMplus d.o.o. 2009
 * @author Bostjan Kodric <bostjan.kodric@rmplus.si>
 * 
 */
//include_once("_dirinfo.php");
//include_once (PATH_TO_ROOT."CRM/class/class.sqlPrepare.php");




	class db
	{
	
		var $ErrorCode;
		public $SQLconnect;
		private $logging;
		private $DataBaseEngine;
		private $inTransaction = 0;
		private $SQLPrepare;
		public $logFile = "/var/www/warpit/_log/class.db.log";
	
		/**
		 * function establishes connection to mysql database
		 * 
		 *
		 * @return MySQL connection identifier
		 */
		
		function __construct($DatabaseEngine = "mysql")
		{
			$this->DataBaseEngine = $DatabaseEngine;
		}
	
		function ChangeDatabase($database) { 
			mysql_select_db($database,$this->SQLconnect);
		}

		/**
		 * database Initialization
		 *
		 * @param string $username
		 * @param string $password
		 * @param string $server
		 * @param string $setname
		 */
		function SetDatabaseConnection($username = "", $password = "", $server = "localhost",$setname = "utf8") 
		{ 
			
			switch ($this->DataBaseEngine) {
				case "mysql" : 
					$this->SQLconnect = mysql_connect($server,$username,$password);
					mysql_query("SET NAMES '".$setname."'");
					break;
				default :
					$this->SQLconnect = mysql_connect($server,$username,$password);
					mysql_query("SET NAMES '".$setname."'");
					break;

			}
			//nepravilno raz�irjanje razreda db. Potrebno dedovanje ...
			//komentirano: 23.12.2013, Sandi Jer�i� Info: 031-689-240 - Borut J., 031-763-569 Sandi J.
			//$this->SQLPrepare = new SQLprepare($this->SQLconnect);
		}
			
		/**
		 * function resets error code array
		 *
		 */
		function resetErrorCode() { unset($this->ErrorCode); }
	
		
		/**
		 * runs sql and returns query result object. 
		 * Same functionality as $result = mysql_query in MySql
		 *
		 * @param string $sql
		 * @return query object result
		 */
		
		function SQLexecute($sql)
		{
			//echo $sql."<-<hr>";
			$this->resetErrorCode();
			$this->ErrorCode['code'] = 0;
			//$sql = $this->SQLPrepare->prepareSQL($sql);
			
			if(ini_get('magic_quotes_gpc'))
				$sql = stripslashes($sql);
			/*
			if ($this->logging) {
				
				$lf = fopen($this->logFile,"a");
				fwrite($lf, date("Ymd\tH:i:s\t").$sql."\n"); 
			}
			mysql_query("INSERT INTO WarpitDevel_Logger._webcati_survey 
										SET 
											microTime = '".microtime()."',
											actionKey = 'MySQL',
											actionData = '".addslashes($sql)."'");
			*/
	
			//echo $sql."<Br>";
			$this->LogWrite($sql,true,"DB class (SQLexecute)");
			
		//	file_put_contents("/tmp/log.sql",$sql,FILE_APPEND);
			
			if ($result = mysql_query($sql,$this->SQLconnect)) 
				return $result;
			else 
			{
					//echo mysql_error();
					$this->ErrorCode['code'] = mysql_errno();
					$this->ErrorCode['text'] = mysql_error();
					$this->ErrorCode['json'] = "{success:false,error:'". addslashes( $this->ErrorCode['text'])."',sql:'".addslashes( $sql)."' }";
					//just in case :)
					if($this->inTransaction)
						$this->SQLcommit();
					mysql_query("UNLOCK TABLES",$this->SQLconnect);
					throw new Exception("Error:".$this->GetError().",SQL: $sql");
					
					return 0;
			} 
		}
		
		
		/**
		 * Gets the table, row or column value!
		 *
		 * @param unknown_type $table 
		 * @param unknown_type $row - if specified returns only one row...can be number for int or where statement
		 * @param unknown_type $column - if specified returns value of this column, otherwise row as assoc array!
		 * @param unknown_type $database
		 */
		public function get($table,$row=null,$column=null,$database=null)
		{
			if($database)
				$this->ChangeDatabase($database);

			$sel = $column ? $column : '*';
			if(strpos($sel,',')==0 && trim($sel) != '*' )
			//if column does not contains commas and is not select all
				$oneColumn = true;
			else 
				$oneColumn = false;
			$byId = is_numeric($row);
			$sql = "SELECT $sel FROM $table";
			if($row)
			{
				if(is_numeric($row))
					$sql.= " WHERE id = $row";
				else
					$sql .= " WHERE $row";
			}
			//echo $sql;
			$this->LogWrite($sql,true,"DB class (get)");
			
			$res = $this->SQLexecute($sql);
			if($oneColumn)
				while ($r = $this->fetchAssoc($res))
				{
					$ans[] = $r[$sel];
				}
			else
				while ($r = $this->fetchAssoc($res))
				{
					$ans[] = $r;
				}
			//if only one column is sought and one row is fetched we return the value
			if($byId)
				return $ans[0];
				
			return $ans;
			
		}
		/**
		 * Begins a transactions
		 *
		 */
		function SQLbegin()
		{
			mysql_query("START TRANSACTION", $this->SQLconnect);
			$this->inTransaction = 1;
			return mysql_query('BEGIN',$this->SQLconnect);
			
		}
	/**
		 * Commits a transactions
		 *
		 */
		function SQLcommit()
		{
			$this->inTransaction = 0;
			return mysql_query('COMMIT',$this->SQLconnect);
			
		}
	/**
		 * Rolls back a transactions
		 *
		 */
		function SQLrollback()
		{
			return mysql_query('ROLLBACK',$this->SQLconnect);
			
		}
		
		
		function IsError() { return $this->ErrorCode['code']; } 
		function GetError() { return $this->ErrorCode['text']; }
		function JsonError(){ return $this->ErrorCode['json']; }
		/**
		 * Function works as $record = mysql_fetch_assoc($result)
		 *
		 * @param database object $result
		 * @return actual record set
		 */
		function fetchAssoc(&$result) { return mysql_fetch_assoc($result); }			
		/**
		 * Function works as $record = mysql_fetch_array($result)
		 *
		 * @param database object $result
		 * @return actual record set
		 */
		function fetchArray(&$result) { return mysql_fetch_array($result); }
		/**
		 * Function works as $record = mysql_fetch_row($result)
		 *
		 * @param database object $result
		 * @return actual record set
		 */
		function fetchRow(&$result) { return mysql_fetch_row($result); }
		
		function affectedRows() { return mysql_affected_rows($this->SQLconnect); }
		
		
		/**
		 * Function reeturns last inserted id in database
		 *
		 * @return id of last inserted id
		 */
		function GetLastInsertId() {
			$sql = "SELECT LAST_INSERT_ID();";
			$result = $this->SQLexecute($sql);
			$zadetek = mysql_fetch_array($result);
			return $zadetek[0];	
		}
		
		/**
		 *  Function returns number on rows in result
		 * 
		 * @param query object $result
		 * @return integer number of records in result
		 */
		function NumRows($result) { return mysql_num_rows($result); }
	/**
		 *  Function returns number of fields in result
		 * 
		 * @param query object $result
		 * @return integer number of fields in result
		 */
		function NumFields($result) { return mysql_num_fields($result); }
		/**
		 *  Function returns name of field in result
		 * 
		 * @param query object $result
		 * @param index of field
		 * @return integer number of records in result
		 */
		function FieldName($result,$index) { return mysql_field_name($result, $index); }
	/**
		 *  Function returns name of field in result
		 * 
		 * @param query object $result
		 * @param index of field
		 * @return integer number of records in result
		 */
		function FieldType($result,$index) { return mysql_field_type($result, $index); }
		
		/**
		 *  Function returns name of fields in a table
		 * 	Optionly a filter can be sot to get e.g. only numeric fields!
		 * 
		 * @param query object $result
		 * @param index of field
		 * @return array of fields
		 */
		function GetFields($tableName,$params=null) { 
			if(is_array($params))
			{
				$filters = $params;
			}
			if(is_string($params))
			{
				$filters[] = $params;
			}
			$fields = array();
			$res = $this->SQLexecute("DESCRIBE $tableName");
			while ($row = $this->fetchAssoc($res))
			{ 
				if(is_array($filters))
				{	
					$type = $row['Type'];
					foreach ($filters as $filter)
						switch ($filter) {
							case 'int':
									if(strtoupper(substr($type,0,3)) == 'INT' || strtoupper(substr($type,0,7)) == 'TINYINT' || strtoupper(substr($type,0,8)) == 'SMALLINT' || strtoupper(substr($type,0,9)) == 'MEDIUMINT' || strtoupper(substr($type,0,6)) == 'BIGINT')
									{	$fields[] = $row['Field']; }
							break;
							
							default:
								;
							break;
						}
					
				}
				else
				{
					$fields[] = $row['Field'];
				}
			}
			return $fields;
		}
		
		function RenameTable($oldName,$newName){
			if(!$this->TableExists($oldName)) return true;
			
			$sql = "RENAME TABLE $oldName TO $newName";
			$this->SQLexecute($sql);
			if($this->IsError())
				return false;
			return true;
		}
		public function DropTable($tableName)
		{
			$sql = "DROP TABLE IF EXISTS $tableName";
			$this->SQLexecute($sql);
			
		}
		function getAutoIncVal($table)
		{
			$sql = "SHOW TABLE STATUS LIKE '$table'";
			$result = $this->SQLexecute($sql);
			$zadetek = mysql_fetch_array($result);
			return $zadetek['Auto_increment'];	
			
		}
		function describe($tableName,$database = null)
		{
			if($database)
				$this->ChangeDatabase($database);
			$res = $this->SQLexecute("DESCRIBE $tableName");
			while ($row = $this->fetchAssoc($res))
			{
				$name = $row['Field'];
				$data['field'] = $name;
				$data['type'] = $row['Type'];
				$data['default'] = $row['default'];
				$arr[$name] = $data;
			}
			return $arr;
		}
		function TableExists($tableName,$database = null)
		{
			if($database)
				$this->ChangeDatabase($database);
			$sql = "SHOW TABLES LIKE '$tableName'";
			$rs = $this->SQLexecute($sql);
			if($this->fetchRow($rs))
				return true;
			return false;
		}
		
		function setLogging($aParam) { $this->logging = $aParam;} 
		
		//setArray returns results in Array
		function getArray($sql){
			 $temp = array();
			
			 $temp_res = $this->SQLexecute($sql);
			 
			 while ($t = $this->fetchArray($temp_res)) {
			 	array_push($temp, $t);
			 }
			 return $temp;
		}


		
		/**
		 * set the time zone and return the date
		 *
		 * @return date in the "H:i:s:u [j.n.Y]" format
		 */
		protected function GetTime() {
			return date("H:i:s:u [j.n.Y]");
		}

		/**
		 * Write debug info to a log file
		 *
		 * @param string $strLog
		 */
		public function LogWrite($strLog,$execute=null,$title=null) {
			if (!$execute) return true;
			
			if (!(strlen(WARPIT_LOGS) >= 3)) return true;
			
			if ($title) $title = " - ".$title;
			$strLog = $this->GetTime().$title." - ".$strLog."\r\n";
			$str = (isset($_SESSION['id_user'])) ? $_SESSION['id_user'] : 'admin'; 
			if (file_put_contents(WARPIT_LOGS."WarpitLog_".$str.".txt", $strLog, FILE_APPEND | LOCK_EX)) {
				return true;
			} else {
				return false;
			}
		}
	

		
	}
?>
