<?php
class Database {   
	var $connection;
	var $result;
	var $pages;
  	var $total;
  	var $from;
  	var $to;
	
	function __construct(&$locator) {	
  		$this->config =& $locator->get('config');
		$this->cache  =& $locator->get('cache');
  	}		
	
  	function connect($server, $username, $password, $database) {
		if (!$this->connection = mysql_connect($server, $username, $password,3306)) {
      		exit('Error: Could not make a database connection using ' . $username . '@' . $server);
    	}

    	if (!mysql_select_db($database, $this->connection)) {
      		exit('Error: Could not connect to database ' . $database);
    	}
		
		mysql_query("set character set utf8"); 	  
  	}
    
  	function query($sql) {
		$this->result = mysql_query($sql);
    	
		if (!$this->result) {
      		exit('Error: ' . mysql_error() . '<br />Error No: ' . mysql_errno() . '<br />' . $sql);
    	} else {
      		return $this->result;
      		mysql_close();
    	}
  	}
	
	function parse() {
    	$args = func_get_args();

		$sql = array_shift($args);

		return vsprintf(str_replace('?', '%s', $sql), array_map('mysql_real_escape_string', $args));	
		
		mysql_close();
	}		

  	function getRow($sql) {
    	$this->query($sql);
		
    	$row = mysql_fetch_assoc($this->result);

    	mysql_free_result($this->result);

    	return $row;
    	
    	mysql_close();
  	}

  	function getRows($sql) {
		$this->query($sql);
	
		if (func_num_args()) {
    		$this->query(implode(func_get_args(), ', '));
		}
		
    	$rows = array();

    	while ($row = mysql_fetch_assoc($this->result)) {
			$rows[] = $row;
    	}

    	mysql_free_result($this->result);
	
    	return $rows;
    	
    	mysql_close();
  	}
	
	function countRows() {
    	$this->query(implode(func_get_args(), ', '));
		
		return mysql_num_rows($this->result);
		
		mysql_close();
	}
	
  	function countAffected() {
    	return mysql_affected_rows($this->connection);
    	
    	mysql_close();
  	}

  	function getLastId() {
    	return mysql_insert_id($this->connection);
    	
    	mysql_close();
  	}
		  
  	function cache($key, $sql) {
    	if ($this->config->get('config_cache_query')) {
      		if (!$result = $this->cache->get($key)) {
	    		$result = $this->getRows($sql);
        
				$this->cache->set($key, $result);
      		}
    	} else {
      		$result = $this->getRows($sql);
    	}
    	return ($result);
    	mysql_close();
  	}

	function splitQuery($sql, &$page = 1, $max_rows = 20) {	
 //   	$count = $this->getRow(preg_replace(array('/select(.*)from /As', '/order by (.*)/'), array('select count(*) as total from ', ''), $sql, 1));

    	$count['total']=$this->countRows($sql);  
 	    $pages = ceil($count['total'] / (int)$max_rows);    

    	if (!$page ) {
      		$page = 1;
    	}else if ( $page>$pages )
		{
			$page = 1;
		}

    	$offset = ((int)$max_rows * ($page - 1));

    	$sql .= " limit " . (int)$offset . ", " . (int)$max_rows;

		$this->pages = (int)(($pages > 0) ? $pages : 1);
    	$this->total = (int)$count['total']; 
    	$this->from  = (int)(($offset > 0 || $count['total'] == 0) ? $offset : 1);

    	if ($count['total'] < $max_rows) {
      		$this->to = (int)$count['total'];
    	}  elseif ($this->pages == $page) {
      		$this->to = (int)($offset + $max_rows - ($offset + $max_rows - $count['total']));
    	} else {
      		$this->to = (int)($offset + $max_rows);
    	}

    	return $sql;
    	
    	mysql_close();
  	}
  
  	function getPages() {
    	return $this->pages;
    	
    	mysql_close();
  	}
  
  	function getTotal() {
    	return $this->total;
    	
    	mysql_close();
  	}
  
  	function getFrom() {
    	return $this->from;
    	mysql_close();
  	}
   
  	function getTo() {
    	return $this->to;
    	mysql_close();
  	}	
	
	function import($sql) {
		foreach (explode(";\n", $sql) as $sql) {
    		$sql = trim($sql);
    		
			if ($sql) {
      			$result = mysql_query($sql);
      			mysql_close();
				if (!$result) {
        			exit('Error: ' . mysql_error() . '<br />Error No: ' . mysql_errno() . '<br />' . $sql);
      			}
    		}
  		}
	}
	
	function export() {
		$output = '';
		
		$list_tables = mysql_list_tables(DB_NAME);

		while ($row = mysql_fetch_row($list_tables)) {
			$output .= '#' . "\n" . '# TABLE STRUCTURE FOR: `' . $row[0] . "`\n" . '#' . "\n\n";
			
			$output .= 'DROP TABLE IF EXISTS `' . $row[0] . '`;' . "\n";
			
			$create_table = mysql_query("show create table `" . DB_NAME . "`.`" . $row[0] . "`");
			$table_sql    = mysql_fetch_row($create_table);
			
			$output .= trim($table_sql[1]) . ';' . "\n\n";
			
			$results = $this->getRows("select * from `" . $row[0] . "`");
				
			foreach ($results as $result) {
				$fields = '';
					
				foreach (array_keys($result) as $value) {
					$fields .= '`' . $value . '`, ';
				}
					
				$values = '';
					
				foreach (array_values($result) as $value) {
					$value = str_replace(array("\x00", "\x0a", "\x0d", "\x1a"), array('\0', '\n', '\r', '\Z'), $value);
					$value = str_replace(array("\n", "\r", "\t"), array('\n', '\r', '\t'), $value);
					$value = str_replace('\\', '\\\\',	$value);
					$value = str_replace('\'', '\\\'',	$value);
					$value = str_replace('\\\n', '\n',	$value);
					$value = str_replace('\\\r', '\r',	$value);
					$value = str_replace('\\\t', '\t',	$value);			
						
					$values .= '\'' . $value . '\', ';
				}
					
				$output .= 'INSERT INTO `' . $row[0] . '` (' . preg_replace('/, $/', '', $fields) . ') VALUES (' . preg_replace('/, $/', '', $values) . ');' . "\n";
			}
				
			$output .= "\n\n";
		}

		return $output;
		
		mysql_close();
	}	
}
?>
