<?php

	class db
	{
		
		var $link = null;
		private 
			$queries,
			$total_time = 0;
		
		function db()
		{
			if(true)
			{
				$this->link = mysql_pconnect(SQL_HOST,SQL_USER,SQL_PASS) or die ("<pre>Ospravedlňte prosím dočasný výpadok. Dúfame, že prevádzka bude čoskoro obnovená.</pre>");
			}
			else 
			{
//				$this->link = mysql_connect("mysql","peterpech","kj545sdfsadca") or die ("<pre>Ospravedlňte prosím dočasný výpadok. Dúfame, že prevádzka bude čoskoro obnovená.</pre>");
			}
			$db = mysql_select_db(SQL_DATABASE, $this->link) or die ("Nepodarilo sa otvorit databazu");
			$this->queries = array();
		}
		
		function WriteLogTxT($message)
		{
			$filename = "log/global.txt";
			$time = date("d.m.Y H:i:s");
			if(!file_exists($filename))
			{
				$fp = fOpen($filename, "w");
				fPuts($fp, $time.": ".$message."\n");
				fClose($fp);
				chmod($filename, 0204);
			}
			else 
			{
				$fp = fOpen($filename, "a");
				fPuts($fp, $time.": ".$message."\n");
				fClose($fp);
			}
		}
		
		function WriteLog($message)
		{
			$time = date("d.m.Y H:i:s");
			$message = addslashes($message);
			$message .= ' '.$_SERVER['PHP_SELF'].'?'.$_SERVER['QUERY_STRING'];
			$query = "INSERT into mobile_logs (time, message) VALUES ('$time', '$message')";
			mysql_query($query, $this->link);
//			db::WriteLogTxT($message);
//			mail('pesto@peterpech.com', '4mobile db error', $message);
		}
		
		function ExecuteQuery($query)
		{
			$this->queries[] = $query;
			$tmp_time = fnExec_time();
			if(mysql_query($query, $this->link)) 
			{
				$x = round(fnExec_time() - $tmp_time, 5);
				$this->total_time += $x;
				$this->queries[sizeof($this->queries)-1] .= ' | '.$x;
				return true;
			}
			else 
			{
				db::WriteLog(mysql_error().' '.$query);
				return false;
			}
		}
		
		function GetAffectedRows()
		{
			return mysql_affected_rows();
		}
		
		function GetResult($query)
		{
			$this->queries[] = $query;
			$tmp_time = fnExec_time();
			$result = mysql_query($query, $this->link);
			$x = round(fnExec_time() - $tmp_time, 5);
				$this->total_time += $x;
				$this->queries[sizeof($this->queries)-1] .= ' | '.$x;
			if($result)
			{
				return $result;
			}
			else return null;
		}
		
		function GetRow($table, $id, $fields)
		{
			$query = "SELECT $fields FROM $table WHERE ID='$id' limit 0, 1";
			$this->queries[] = $query;
			$tmp_time = fnExec_time();
			$result = mysql_query($query, $this->link) or db::WriteLog(mysql_error().' '.$query.' '.$_SERVER['PHP_SELF']);
			$x = round(fnExec_time() - $tmp_time, 5);
				$this->total_time += $x;
				$this->queries[sizeof($this->queries)-1] .= ' | '.$x;
			if($result)
			{
				$row = mysql_fetch_assoc($result);
				return $row;
			}
			else return null;
		}
		
		function GetRow2($table, $fields, $where, $what)
		{
			$query = "SELECT $fields FROM $table WHERE $where='$what' limit 0, 1";
			$this->queries[] = $query;
			$tmp_time = fnExec_time();
			$result = mysql_query($query, $this->link) or db::WriteLog(mysql_error().' '.$query.' '.$_SERVER['PHP_SELF']);
			$x = round(fnExec_time() - $tmp_time, 5);
				$this->total_time += $x;
				$this->queries[sizeof($this->queries)-1] .= ' | '.$x;
			if($result)
			{
				$row = mysql_fetch_assoc($result);
				return $row;
			}
			else return null;
		}
		
		function GetArray($query)
		{
			$result = db::GetResult($query);
			$res = array();
			if($result)
			{
				while($row = mysql_fetch_assoc($result))
				{
					$res[] = $row;
				}
			}
			return $res;
		}
		
		function GetOne($table, $id, $field)
		{
			$query = "SELECT $field FROM $table WHERE ID='$id' limit 0, 1";
			$this->queries[] = $query;
			$tmp_time = fnExec_time();
			$result = mysql_query($query, $this->link) or db::WriteLog(mysql_error().' '.$query.' '.$_SERVER['PHP_SELF']);
			$x = round(fnExec_time() - $tmp_time, 5);
				$this->total_time += $x;
				$this->queries[sizeof($this->queries)-1] .= ' | '.$x;
			if($result)
			{
				$row = mysql_fetch_array($result);
				return $row[$field];
			}
			else return null;
		}
		
		function GetOne3($query)
		{
			$this->queries[] = $query;
			$tmp_time = fnExec_time();
			$result = mysql_query($query, $this->link) or db::WriteLog(mysql_error().' '.$query.' '.$_SERVER['PHP_SELF']);
			$x = round(fnExec_time() - $tmp_time, 5);
				$this->total_time += $x;
				$this->queries[sizeof($this->queries)-1] .= ' | '.$x;
			if($result)
			{
				$row = mysql_fetch_array($result);
				return $row[0];
			}
			else return null;
		}
		
		function GetNums($query)
		{
			$this->queries[] = $query;
			$tmp_time = fnExec_time();
			$result = mysql_query($query, $this->link) or db::WriteLog(mysql_error().' '.$query.' '.$_SERVER['PHP_SELF']);
			$x = round(fnExec_time() - $tmp_time, 5);
				$this->total_time += $x;
				$this->queries[sizeof($this->queries)-1] .= ' | '.$x;
			if($result)
			{
				return mysql_num_rows($result);
			}
			else return 0;
		}
		
		function GetLimit($query)
		{
			global $nastranu, $i, $module;
			$exceptions = array('gbook', 'bazar', 'forum');
			$this->queries[] = $query;
			$tmp_time = fnExec_time();
			
			if (!isset($nastranu)) $nastranu = 30;
			$result = mysql_query($query, $this->link) or db::WriteLog(mysql_error().' '.$query.' '.$_SERVER['PHP_SELF']);
			$x = round(fnExec_time() - $tmp_time, 5);
				$this->total_time += $x;
				$this->queries[sizeof($this->queries)-1] .= ' | '.$x;
			if($result)
			{
				$max = mysql_num_rows($result);
				mysql_free_result($result);
				$stranok = floor($max/$nastranu);
				if($max%$nastranu>0) $stranok+=1;
				$lim = ($i-1) * $nastranu;
				$result = array($lim, $max, $stranok);
				return $result;
			}
			else return null;
		}
		
		function Increment($table, $column, $id, $count)
		{
			if($table<>'' && $column<>'' && $id<>'')
			{
				$query = "UPDATE $table SET $column = $column + $count WHERE ID='$id' limit 1";
//				error_log($query."\n", 3, $_SERVER['DOCUMENT_ROOT'].'/lib/log/'.date('j-m-y').'-increment.log');
				return db::ExecuteQuery($query);
			}
			else
			{
				db::WriteLog('chyba tabula alebo daco');
				return false;
			}
		}
		
		function Max_ID($table)
		{
			$query = "SELECT max(ID) as max from $table";
			$result = db::GetResult($query);
			if($result)
			{
				$row = mysql_fetch_array($result);
				return $row['max'];
			}
			else return 0;
		}
		
		function Max($table, $column)
		{
			$query = "SELECT max($column) as max from $table";
			$result = db::GetResult($query);
			if($result)
			{
				$row = mysql_fetch_array($result);
				return $row['max'];
			}
			else return 0;
		}
		
		function GetOne2($table, $column, $where, $what)
		{
			if($table!='' && $column!='' && $where!='' && $what!='')
			{
				$query = "SELECT $column FROM $table WHERE $where = '$what' limit 0, 1";
				$result = db::GetResult($query);
				if($result)
				{
					$row = mysql_fetch_array($result);
					return $row[$column];
				}
				else return 0;
			}
			else return 0;
		}
		
		function showAllQueries()
		{
			if(fnIsAdmin())
			{
				$i = 0;
				echo "<pre style='border: black solid 2px; margin:5px; padding: 5px; background:#FFFFEE; color:#000066; font-size:12px; text-align:left;'>";
				echo "<b>QUERIES</b><br />";
				foreach($this->queries as $query)
				{
					$i++;
					echo "[$i]: $query<br/>";
				}
				echo "</pre>";
				dump($this->total_time);
			}
		}
	}
	
	class db_structure
	{
		function db_structure()
		{
			@set_time_limit(3600);	
			$this->link = mysql_connect(SQL_HOST,SQL_USER,SQL_PASS) or die ("Nepodarilo sa pripojit");
			$db = mysql_select_db(SQL_DATABASE, $this->link) or die ("Nepodarilo sa otvorit databazu");
		}
		
		function dump($var)
		{
			echo "<pre>";
			print_r($var);
			echo "</pre>";
		}
		
		function fnGetDbs()
		{
			$result = mysql_list_dbs();
			$dbs = array();
			while($row = mysql_fetch_row($result))
			{
				$dbs[] = $row[0];
			}
			return $dbs;
		}
		
		function fnGetTables($dbase)
		{
			$query = "SHOW TABLES FROM `$dbase`";
			$result = mysql_query($query);
			$tables = array();
			while($row = mysql_fetch_array($result))
			{
				$tables[] = $row[0];
			}
			return $tables;
		}
		
		function fnGetTableStructure($dbase, $table)
		{
			mysql_select_db($dbase);
			$query = "DESCRIBE $table";
			$result = mysql_query($query);
			$cols = array();
			while($row = mysql_fetch_assoc($result))
			{
				$cols[] = $row;
			}
			return $cols;
		}
		
		function fnGetTableCols($dbase, $table)
		{
			mysql_select_db($dbase);
			$query = "DESCRIBE $table";
			$result = mysql_query($query);
			$rows = array();
			while($row = mysql_fetch_assoc($result))
			{
				$rows[] = $row['Field'];
			}
			return $rows;
		}
		
		function fnArrayToPhpStr($array)
		{
			$i = 0;
			$str = '';
			if(is_array($array))
			{
				foreach($array as $value)
				{
					$str .= "'".addslashes(htmlspecialchars($value))."'";
					$i++;
					if($i<sizeof($array))
					{
						$str .= ', ';
					}
				}
				return $str;
			}
			else return false;
		}
		
		function fnDumpTableByInserts($dbase, $table)
		{
			$buffer = '';
			mysql_select_db($dbase);
			$query = "SELECT * FROM $table";
			$result = mysql_query($query);
			if($result)
			{
				while($row = mysql_fetch_assoc($result))
				{
					$buffer .= "INSERT INTO '$table' (".db_structure::fnArrayToPhpStr(db_structure::fnGetTableCols($dbase, $table)).") VALUES (".db_structure::fnArrayToPhpStr($row).");";
					$buffer .= "\n";
				}
				return $buffer;
			}
			else return false;
		}
		
		function fnDumpDbaseByInserts($dbase)
		{
			$buffer = '';
			
			$ttd = array //tables to dump
			(
				'mobile_address_book',
				'mobile_anketa',
				'mobile_bazar',
				'mobile_counter',
				'mobile_dload_dnes',
				'mobile_game_types',
				'mobile_games',
				'mobile_gbook',
				'mobile_img_cat',
				'mobile_img_res',
				'mobile_logged_users',
				'mobile_logs',
				'mobile_melody',
				'mobile_moj_mobil',
				'mobile_navstev_dnes',
				'mobile_news',
				'mobile_phorum_main_topics',
				'mobile_phorum_posts',
				'mobile_phorum_topics',
				'mobile_posta',
				'mobile_posta_inbox',
				'mobile_posta_sent',
				'mobile_pozadia',
				'mobile_reklama',
				'mobile_reklama_bottom',
				'mobile_reklama_left',
				'mobile_themes',
				'mobile_users',
				'mobile_video',
				'mobile_visits_logs',
			);
			$tables = db_structure::fnGetTables($dbase);
			if(is_array($tables))
			{
				foreach($tables as $table)
				{
					if(in_array($table, $ttd))
					{
						$buffer .= "\n\n// ************************  TABLE NAME: ".$table." ************************\n\n";
						$buffer .= db_structure::fnDumpTableByInserts($dbase, $table);
						$buffer .= "\n\n// ************************  END OF TABLE: ".$table." **********************\n\n";
					}
				}
				return $buffer;
			}
			else return false;
		}
		
		function fnDumpServerByInserts()
		{
			$buffer = '';
			$dbs = db_structure::fnGetDbs();
			if(is_array($dbs))
			{
				foreach($dbs as $dbase)
				{
					$buffer .= "\n\n//########################## DATABASE: ".$dbase." ##########################\n\n";
					$buffer .= db_structure::fnDumpDbaseByInserts($dbase)."\n";
					$buffer .= "\n\n//########################## END OF DATABASE: ".$dbase." ###################\n\n";
				}
				return $buffer;
			}
			else return false;
		}
		
		function fnDumpServerByInsertsToFile($filename)
		{
			$buffer = db_structure::fnDumpServerByInserts();
			$fp = fopen($filename, 'w');
			if($fp)
			{
				fputs($fp, $buffer);
				fclose($fp);
				return true;
			}
			else return false;
		}
		
		function fnDumpDbaseByInsertsToFile($filename, $dbase)
		{
			$buffer = db_structure::fnDumpDbaseByInserts($dbase);
			$fp = fopen($filename, 'w');
			if($fp)
			{
				fputs($fp, $buffer);
				fclose($fp);
				return true;
			}
			else return false;
		}
		
		function fnDumpTableByInsertsToFile($filename, $dbase, $table)
		{
			$buffer = db_structure::fnDumpTableByInserts($dbase, $table);
			$fp = fopen($filename, 'w');
			if($fp)
			{
				fputs($fp, $buffer);
				fclose($fp);
				return true;
			}
			else return false;
		}
		
		function fnSendMail($komu, $dump)
		{
			$subject = "Mysql Server Dump";
		   	$headers = "From:mysql <ugly@motherfucker.com>\n";
		   	$headers .= "Content-Type: text/html; charset=iso-8859-2\n";
		   	if(mail($komu, $subject, $dump, $headers))
		   	{
		   		return true;
		   	}
		   	else 
		   	{
		   		return false;	
		   	}
		}
		
		function fnDumpServerByInsertsToMail($mail_addr)
		{
			$buffer = db_structure::fnDumpServerByInserts();
			return db_structure::fnSendMail($mail_addr, $buffer);			
		}
		
		function fnDumpDbaseByInsertsToMail($mail_addr, $dbase)
		{
			$buffer = db_structure::fnDumpDbaseByInserts($dbase);
			return db_structure::fnSendMail($mail_addr, $buffer);			
		}
		
		function fnDumpTableByInsertsToMail($mail_addr, $dbase, $table)
		{
			$buffer = db_structure::fnDumpTableByInserts($dbase, $table);
			return db_structure::fnSendMail($mail_addr, $buffer);			
		}
	}
	
?>