<?php
class mysql {

	var $con;
  var $debug_time;
  var $debug;
  var $count = false;

	function __construct( $db = array() )
  {
		$default = array(
			'host' => 'localhost',
			'user' => 'root',
			'pass' => '',
			'db' => 'test'
		);

		$db   = array_merge( $default , $db );
		$this -> con = mysql_connect( $db['host'] , $db['user'] , $db['pass'] , true ) or die ( 'Error connecting to MySQL' );
		mysql_select_db( $db['db'] , $this -> con ) or die( 'Database ' . $db['db'] . ' does not exist!' );
	}

  function insert( $table = null , $array_of_values = array() , $debug = false )
  {
		if ( $table === null || empty( $array_of_values ) || !is_array( $array_of_values ) )
      return false;

    $fields = array();
    $values = array();

		foreach ( $array_of_values as $id => $value )
    {
			$fields[] = $id;
			if ( is_array( $value ) && !empty( $value[0] ) )
        $values[] = $value[0];
			else
        $values[] = "'" . $value . "'";
		}
		$s = "INSERT INTO $table (".implode(',',$fields).') VALUES ('.implode(',',$values).')';
		if ( mysql_query( $s , $this -> con ) )
      return mysql_insert_id( $this -> con );
    else if ( $debug )
      die( mysql_error() );
		return false;
	}

  function query( $sql , $cache = false , $debug = false , $field = false )
  {
    if ( $cache === true )
      $cache = 60 * 60;

    if ( $this -> debug_time )
      $t_start = $this -> getmicrotime();

    if ( !$sql )
      return false;

    $key = md5( $sql );

    if ( !$cache || !$value = $this -> fetch ( $key )  )
    {
      $result = mysql_query( $sql , $this -> con );
      if ( $debug && !$result )
        die ( mysql_error() );
      else if ( $result )
      {
        if ( mysql_num_rows( $result ) )
        {
          while ( $row = mysql_fetch_assoc( $result ) )
          {
            if ( $field )
              $value[] = $row[$field];
            else
              $value[] = $row;
          }
          if ( $cache )
            $this -> store( $key , $value , $cache );
          $out = $value;
        }
        else
          $out = false;
      }
      else
        $out = false;
    } else
      $out = $value;

    if ( $this -> debug_time )
    {
      $t_diff = round( microtime(true) - $t_start , 6 );
      $debug_txt = '<p style=\'font-size:11px; padding: 10px; margin: 0px; font-family: verdana;';
        if ( $this -> count )
          $debug_txt .= 'background:#e6e6e6;';
        $this -> count = !$this -> count;
      $debug_txt .= '\'>';
        if ( $cache )
          $debug_txt .= '<b>CACHE</b>';
        else
          $debug_txt .= '<b>MYSQL</b>';
      $debug_txt .= ': ' . $sql . ' w czasie <b>' . $t_diff . '</b>s</p>';
      $this -> debug .= '<script type="text/javascript">
              debug = window.open( "" ,"Debuger" ,"toolbar = no,height = 500px , width = 1000px" );
              debug.document.writeln("' . str_replace( '"' , '&#039;' , $debug_txt ) . '");
            </script>';
    }
    return $out;
  }

  function delete( $table = null , $conditions = 'FALSE' )
  {
		if ( $table === null )
      return false;
		return $this -> execute( "DELETE FROM $table WHERE $conditions" ) or die( mysql_error() );
	}

  function update( $options , $debug = false )
  {
    $sql = "UPDATE {$options['table']} SET {$options['fields']} WHERE {$options['condition']}";
		return $this -> execute( $sql , $debug );
	}

  function execute( $sql = '' , $debug = false )
  {
    if ( $this -> debug_time )
      $t_start = $this -> getmicrotime();

		if ( $res = mysql_query( $sql , $this -> con ) )
      $out = $res;
		else
    {
      if ( $debug )
        die ( mysql_error() );
      $out = false;
    }

    if ( $this -> debug_time )
    {
      $t_diff = round( microtime(true) - $t_start , 6 );
      $debug_txt = '<p style=\'font-size:11px; padding: 10px; margin: 0px; font-family: verdana;';
        if ( $this -> count )
          $debug_txt .= 'background:#e6e6e6;';
        $this -> count = !$this -> count;
      $debug_txt .= '\'>';
      $debug_txt .= '<b>MYSQL</b>';
      $debug_txt .= ': ' . $sql . ' w czasie <b>' . $t_diff . '</b>s</p>';
      $this -> debug .= '<script type="text/javascript">
              debug = window.open( "" ,"Debuger" ,"toolbar = no,height = 500px , width = 1000px" );
              debug.document.writeln("' . str_replace( '"' , '&#039;' , $debug_txt ) . '");
            </script>';
    }
    return $out;
	}

  function select( $options , $cache = false , $debug = false , $to_array = false )
  {
		$default = array (
			'table' => '',
			'fields' => '*',
			'condition' => '',
			'order' => '',
			'limit' => ''
		);

		$options  = array_merge( $default , $options );

		$sql      = "SELECT {$options['fields']} FROM {$options['table']}";
    if ( $options['condition'] !== '' )
      $sql .= " WHERE {$options['condition']}";
    if ( $options['order'] !== '' )
      $sql .= " ORDER BY {$options['order']}";
    if ( $options['limit'] !== '' )
      $sql .= " LIMIT {$options['limit']}";

    if ( $to_array )
      $field = $options['fields'];
    else
      $field = false;
		return $this -> query( $sql , $cache , $debug , $field );
	}

  function select_array( $options , $cache = false , $debug = false )
  {
    $result = $this -> select( $options , $cache , $debug , true );
    return $result;
  }

  function row( $options , $cache = false , $debug = false )
  {
		$default = array (
			'table' => '',
			'fields' => '*',
			'condition' => '1',
			'order' => '1',
      'limit' => '1',
		);

		$options = array_merge( $default , $options );

		$sql    = "SELECT {$options['fields']} FROM {$options['table']} WHERE {$options['condition']} ORDER BY {$options['order']} LIMIT {$options['limit']}";
		$result = $this -> query( $sql , $cache , $debug );
		if ( empty( $result[0] ) )
      return false;
		return $result[0];
	}

  function get( $options , $cache = false , $debug = false )
  {
		$default = array (
			'table' => '',
			'fields' => '*',
			'condition' => '1',
			'order' => '1',
      'limit' => '1'
		);

		$options = array_merge( $default , $options );

    $result = $this -> row( $options ,
                            $cache ,
                            $debug
                          );

    if ( $result[$options['fields']] === '' )
      return false;
		return $result[$options['fields']];
	}

  public function sec( $string ) {
    if ( get_magic_quotes_gpc() )
      $string = stripslashes( $string );
    if ( phpversion() >= '4.3.0' )
      $string = mysql_real_escape_string( $string );
    else
      $string = mysql_escape_string( $string );
    return $string;
  }

  private function store( $key , $data , $ttl )
	{
		$h = fopen( $this -> getFileName( $key ) , 'w' );
		if ( !$h )
			throw new Exception( 'Could not write to cache' );
		$data = base64_encode( serialize( array( time() + $ttl , $data ) ) );
		if ( fwrite( $h , $data ) === false )
			throw new Exception('Could not write to cache');
		fclose($h);
	}

	private function getFileName( $key )
	{
		$md5 = md5( $key );
		$dir = 'temp/' . $md5[0] . '/' . $md5[1] . '/';
		if ( !is_dir( $dir ) )
			mkdir( $dir , 0770 , true );
		return $dir . 's_cache' . $md5;
	}

	private function fetch( $key )
	{
		$filename = $this -> getFileName( $key );
			if ( !file_exists( $filename ) || !is_readable( $filename ) )
		return false;

		$data = base64_decode( file_get_contents( $filename ) );

		$data = @unserialize( $data );
		if ( !$data )
		{
			unlink( $filename );
			return false;
		}
		if ( time() > $data[0] )
		{
			unlink($filename);
			return false;
		}
		return $data[1];
	}

  public function pre( $data )
  {
    echo '<pre>' . print_r( $data , true ) . '</pre>';
  }

  public function dump( $data )
  {
    if ( !$data )
      return false;
    echo "<style>table.dump { font-family:Arial; font-size:8pt; } table.dump td , table.dump th { padding: 5px 10px; }</style>";
    echo "<table class=\"dump\" border=\"1\" cellpadding=\"1\" cellspacing=\"0\">\n";
    echo "<tr>";
    echo "<th>Lp.</th>";
    foreach( $data[0] as $key => $val )
    {
      echo "<th><b>";
      echo $key;
      echo "</b></th>";
    }
    echo "</tr>\n";
    $row_cnt = 0;
    foreach( $data as $row )
    {
      $row_cnt++;
      echo "<tr align='center'>";
      echo "<td>".$row_cnt."</td>";
      foreach ( $row as $val )
      {
        echo "<td>";
        echo $val;
        echo "</td>";
      }
      echo"</tr>\n";
    }
    echo "</table>\n";
  }

  private function getmicrotime()
  {
    list( $usec , $sec ) = explode( " " , microtime() );
    return ( (float)$usec + (float)$sec );
  }

  public function debug() {
    $this -> debug_time = !$this -> debug_time;
  }
}
?>
