<?php
/**
* DB Connect is a simple tool to handle simple mysql connects, queries and other.
*
* @name DB Connect (MySQL)
* @verision 2.1.0
* @package Maris Engine
* @author Rashaud Teague <rashaud.teague@gmail.com>
* @since ??/??/2007
* @license GNU GPL
*/


class DB {
	/**
	* @var $username
	* Username in database admin.
	*/
	protected $username;
	
	
	/**
	* @var $servername
	* Servername for a database to connect to.
	*/
	protected $servername;
	
	
	/**
	* @var $pass
	* Username's password to log into the database connection.
	*/
	protected $pass;
	
	
	/**
	* @var $dbname
	* Name of the database that is to be connected to.
	*/
	protected $dbname;
	
	
	/**
	* @var $prefix
	* Prefix for data tables.
	*/
	protected $prefix;
	
	
	/**
	* @var $result
	* Holds the result of a query result.
	*/
	protected $result;
	
	
	/**
	* @var $sql
	* Initial SQL query string.
	*/
	public $sql;
	
	
	/**
	* @var $link
	* MySQL connection link.
	*/
	private $link;
	
	
	/**
	* @var $queries
	* The number of queries being run.
	*/
	public $queries = 0;
	
	
	/**
	* @var $db_tables
	* db tables array (default empty array...primarily for the use of db installations)
	*/
	public $db_tables = array();
	
	
	/**
	* void __construct([$config_file]) aka DB_connect
	*
	* Sets the database connection variables. First includes the "config.php" file to get
	* the values of the array variable $dbsettings. Executes the connect() function to connect
	* to the database.
	*
	* @param str $config_file
	*/
	
	public function __construct($config_file = 'config.php') {
		
		include $config_file;
		
		$this->servername = $dbsettings['servername'];
		$this->username = $dbsettings['username'];
		$this->pass = $dbsettings['password'];
		$this->dbname = $dbsettings['dbname'];
		$this->prefix = $dbsettings['prefix'];
	}
	
	
	/**
	* void connect()
	*
	* Takes the set connection variables then connects to the database. Exception is thrown to incase error.
	* This function is executed in the __construct function.
	*/
	
	public function connect() {
		$dbconn = @mysql_connect($this->servername, $this->username, $this->pass);
		
		if (!$dbconn) {
			$this->log_sql_errors('Could not perform DB connection: '.mysql_error());
		}
		
		$select = @mysql_select_db($this->dbname, $dbconn);
		
		if (!$select) {
			$this->log_sql_errors('Could not perform DB selection: '.mysql_error());
		}
		
		$this->link = $dbconn;
	}
	
	
	/**
	* void exe_sql($query [, $table])
	*
	* Executes the given query command
	* INSERT, SELECT, DELETE and so on...
	*
	* @param str $query
	* @param str $table
	*/
	
	public function exe_sql($query, $table = '') {
		
		if ($table != '') {
			$nquery = str_replace('{{table}}', $this->prefix. '_' .trim($table), $query);
		} else {
			$nquery = $query;
		}
		
		//save query to class
		$this->sql = $nquery;
		
		//check to see if we are connected still
		if (!mysql_ping($this->link)) {
			$this->log_sql_errors('Lost DB connection: ');
		}
		
		$result = mysql_query($nquery);
		
		if (!$result) {
			//do the basic SQL commands...
			if (preg_match("/^SELECT/", $query)) {
				
				$this->log_sql_errors('Could not perform SELECT: '.mysql_error());
				
			} elseif (preg_match("/^INSERT/", $query)) {
				
				$this->log_sql_errors('Could not perform INSERT: '.mysql_error());
				
			} elseif (preg_match("/^UPDATE/", $query)) {
				
				$this->log_sql_errors('Could not perform UPDATE: '.mysql_error());
				
			} elseif (preg_match("/^DELETE/", $query)) {
				
				$this->log_sql_errors('Could not perform DELETE: '.mysql_error());
				
			} else {
				
				$this->log_sql_errors('Could not perform DB operation: '.mysql_error());
				
			}
		}
		
		$this->result = $result;
		$this->queries += 1;
	}
	
	
	/**
	* void free()
	*
	* Frees memory from the sql execution
	*/
	
	public function free() {
		mysql_free_result($this->result);
	}
	
	
	/**
	* int get_num_queries()
	*
	* Simply returns the number of queries ran.
	*
	* @return int $this->queries
	*/
	
	public function get_num_queries() {
		return $this->queries;
	}
	
	
	/**
	* mixed result([$row])
	*
	* Gives a sql result.
	*
	* @example {-
	* $DB = new DB();
	* $DB->connect();
	*
	* //if you are counting the quantity of inserted data in a table
	* $query = "SELECT count(*) FROM yourtable";
	* $DB->exe_sql($query);
	* $count = $DB->result();
	* -}
	*
	* @param int $row
	*/
	
	public function result($row = 0) {
		
		$result = mysql_result($this->result, $row);
		
		return $result;
	}
	
	
	/**
	* mixed fetch_array()
	*
	* Fetches an array of results from the given query
	*
	* @example {-
	* $DB = new DB();
	* $DB->connect();
	*
	* $query = "SELECT * FROM yourtable";
	* $DB->exe_sql($query);
	* $row = $DB->fetch_array();
	* -} OR {-
	*
	* while ($row = $DB->fetch_array()) {
	* 	//...results $row[fieldName]; (just whatever the field name is you want to grab)
	* }
	*
	* @return bool,array
	*/
	
	public function fetch_array() {
		$row_query = mysql_fetch_array($this->result);
		
		if (!is_array($row_query)) {
			return false;
		}
		
		return $row_query;
	}
	
	
	/**
	* array fetch_object()
	*
	* Fetches an object/array of results from the given query
	*
	* @example {-
	* $DB = new DB();
	* $DB->connect();
	*
	* $query = "SELECT * FROM yourtable";
	* $DB->exe_sql($query);
	* $row = $DB->fetch_object();
	* -} OR {-
	*
	* while ($row = $DB->fetch_array()) {
	* 	//...results $row->fieldName; (just whatever the field name is you want to grab)
	* }
	*
	* @return array
	*/
	
	public function fetch_object() {
		$obj = mysql_fetch_object($this->result);
		
		return $obj;
	}
	
	/**
	* array fetch_row()
	*
	* Returns a numerical array that corresponds to the fetched row and moves the internal data pointer ahead
	*
	* @return array
	*/
	
	public function fetch_row() {
		$obj = mysql_fetch_row($this->result);
		
		return $obj;
	}
	
	
	/**
	* int last_id()
	*
	* Gets last inserted id.
	*
	* @return int
	*/
	
	public function last_id() {
		return mysql_insert_id();
	}
	
	
	/**
	* void debug_query([$str])
	*
	* Parses out a query string for better view when debugging a sql query.
	*
	* @param str $str
	*/
	
	public function debug_query($str = '') {
		$word_breaks = array(
		"/(SELECT)/ie",
		"/(INSERT)/ie",
		"/(UPDATE)/ie",
		"/(DELETE)/ie",
		"/(FROM)/ie",
		"/(VALUES)/ie",
		"/(SET)/ie",
		"/(WHERE)/ie",
		"/(AND)/ie",
		"/(OR)/ie",
		"/(LEFT\sJOIN)/ie",
		"/(LEFT\sOUTER\sJOIN)/ie",
		"/(RIGHT\sJOIN)/ie",
		"/(RIGHT\sOUTER\sJOIN)/ie",
		"/(INNER\sJOIN)/ie",
		"/(ON)/ie",
		"/(\()/",
		"/(\))/",
		);
		
		$replacements = array(
		'"".strtoupper("$1")."<br>"',
		'"<br>".strtoupper("$1")."<br>"',
		'"<br>".strtoupper("$1")."<br>"',
		'"<br>".strtoupper("$1")."<br>"',
		'"<br>".strtoupper("$1")."<br>"',
		'"<br>".strtoupper("$1").""',
		'"<br>".strtoupper("$1")."<br>"',
		'"<br>".strtoupper("$1")."<br>"',
		'"<br>".strtoupper("$1")."<br>"',
		'"<br>".strtoupper("$1")."<br>"',
		'"<br>".strtoupper("$1")."<br>"',
		'"<br>".strtoupper("$1")."<br>"',
		'"<br>".strtoupper("$1")."<br>"',
		'"<br>".strtoupper("$1")."<br>"',
		'"<br>".strtoupper("$1")."<br>"',
		'"<br>".strtoupper("$1")."<br>"',
		'<br>$1<blockquote>',
		'</blockquote>$1'
		);
		
		
		
		if ($query_str != '') {
			//foreach ($word_breaks as $breaks) {
			    //if (preg_match("/".$breaks."/i", $query_str)) {
			        $new_query = preg_replace($word_breaks, $replacements, $query_str);
			    //}
			//}
			
		} else {
			$new_query = preg_replace($word_breaks, $replacements, $this->sql);
		}
		
		print $new_query;
		die();
	}
	
	
	/**
	* int num_rows()
	* Gets the number of rows from the result_query.
	*
	* @example {-
	* $DB = new DB();
	* $DB->connect();
	*
	* $query = "SELECT * FROM yourtable";
	* $DB->exe_sql($query);
	* $row = $DB->num_rows();
	* -}
	*
	* @return int
	*/
	
	public function num_rows() {
		$num_query = mysql_num_rows($this->result);
		
		return $num_query;
	}
	
	
	/**
	* array fetch_field()
	*
	* Gets the number of rows from the result_query.
	*
	* @example {-
	* $DB = new DB();
	* $DB->connect();
	*
	* $query = "SELECT * FROM yourtable";
	* $DB->exe_sql($query);
	* $field = $DB->fetch_field();
	*
	* print $field->anyfieldname;
	* -}
	*
	* @return array
	*/
	
	public function fetch_field() {
		$field_row = mysql_fetch_field($this->result);
		
		return $field_row;
	}
	
	
	/**
	* void db_close()
	*
	* Closes the database.
	*/
	
	public function db_close() {
		mysql_close($this->link);
	}
	
	
	/**
	*void add_table($str)
	*
	* Add table names to a drop list.
	*/
	
	public function add_table($str) {
		$this->db_tables[] = $str;
	}
	
	
	/**
	* void drops()
	*
	* Drop all tables in the drop lists...great for uninstalling things.
	*/
	
	public function drops() {
		foreach ($this->db_tables as $thetables) {
			$result = mysql_query("DROP TABLE IF EXISTS `$thetables`");
		}
	}
	
	
	/**
	* void run_query($query [, $table])
	*
	* Runs a multi-line query.
	*
	* @example {-
	* $DB = new DB();
	* $DB->connect();
	*
	* $query = <<<HERE
	* INSERT INTO {{table}} VALUES('', '$val1');
	* INSERT INTO {{table}} VALUES('', '$val2');
	* INSERT INTO {{table}} VALUES('', '$val3');
	* HERE;
	*
	* [[After multiple lines of query commands]]
	*
	* $DB->run_query($multi_line_query_string, [$table]);
	* -}
	*
	* @param $query
	* @param $table
	*/
	
	public function run_query($query, $table = '') {
		$lines = preg_split("/[;]+/", $query);
		$queries = sizeof($lines);
		
		foreach ($lines as $command) {
			$command = trim($command);
			$command = str_replace("\\n", '', $command);
			if ($command != '') {
				if ($table != '') {
					$this->exe_sql($command, $table);
				} else {
					$this->exe_sql($command);
				}
			}
		}
	}
	
	public function log_sql_errors($error) {
		if ($error == '') {
			die('ERROR: Failed to log error.');
		}
		$error_file = 'mysql_error_log';
		$pFile = fopen($error_file, 'a');
		$error_date = date('M d Y H:i:s A', time());
		$error_line = ':BEGIN:'.$error.' file:'.__FILE__.' line:'.__LINE__.' '.$error_date.':END:'."\n";
		fputs($pFile, $error_line);
		fclose($pFile);
		
		die($error_line);
	}
}
?>