<?php
/**
 * @version $Id: database.inc.php v2.0 $
 * @package PBDigg
 * @copyright Copyright (C) 2007 - 2008 PBDigg.com. All Rights Reserved.
 * @license PBDigg is free software and use is subject to license terms
 */

if(!defined('IN_ADMIN') || !isset($_PBDEV['PHP_SELF']) || !preg_match('/[\/\\\\]admincp\.php$/i', $_PBDEV['PHP_SELF']))
{
	exit('Access Denied');
}
define('PB_CSCRIPT', 'database');
allowdo('setdb');
$baseurl = 'admincp.php?action=database&amp;type=';
require_once (PBDIGG_CP.'include/table.inc.php');

if ($type == 'export')
{
	if ($submitted)
	{
		if(!preg_match('/^[0-9a-zA-Z_]+$/i', $filename))
		{
			showMsg($a_message['dbbak_file_error'], $actionurl);
		}
		if (!$tablename)
		{
			showMsg($a_message['dbbak_chose_table'], $actionurl);
		}
		$volume = (int)$volume + 1;
		$sqlfilename = "dbak/{$filename}_{$volume}.sql";
		if (strpos($db_charset, '-') !== FALSE)
		{
			$db_charset = str_replace('-', '', $db_charset);
		}
		if($DB->db_version() > '4.1')
		{
			$DB->db_query("SET character_set_connection='$db_charset', character_set_results='$db_charset', character_set_client='binary'");
		}
		if ($volume == 1)
		{
			$DB->db_query("TRUNCATE TABLE {$db_prefix}scaches");
			$tablename = implode('|', $tablename);
			$sizelimit *= 1000;
		}
		$sqldump = '';
		$sizelimit = (int)$sizelimit;
		$tables = explode('|', $tablename);
		$tableid = $tableid ? ($tableid - 1) : 0;
		$startfrom = (int)$startfrom;
		for($i = $tableid; $i < count($tables) && strlen($sqldump) < $sizelimit; $i++)
		{
			$sqldump .= sqldumptable($tables[$i], $startfrom, strlen($sqldump));
			$startfrom = 0;
		}
		$tableid = $i;
		if(trim($sqldump))
		{
			$sqldump = "# PBDigg Database Bake File Vol.$volume\n".
				"# Version: ".$_PBENV['PB_VERSION'][0]."\n".
				"# Time: ".gdate($timestamp)."\n".
				"# PBDigg: http://www.pbdigg.com\n".
				"# --------------------------------------------------------\n\n\n".$sqldump;
			if (PWriteFile($sqlfilename, $sqldump, 'wb'))
			{
				redirect($a_message['dbbak_ing'], 'admincp.php?action=database&type=export&submitted=1&filename='.rawurlencode($filename).'&sizelimit='.$sizelimit.'&volume='.$volume.'&tableid='.$tableid.'&startfrom='.$startrow.'&tablename='.rawurlencode($tablename), 1);
			}
			else
			{
				showMsg($a_message['dbbak_failed'], $ationurl);
			}
		}
		else
		{
			showMsg($a_message['dbbak_success'], $baseurl.'import');
		}
	}
	else
	{
		$DB->db_query('SHOW TABLE STATUS');
		$pbtable = $othertable = $result = array();
		while ($result = $DB->db_fetch_array())
		{
			if (in_array(str_replace($db_prefix, 'pb_', $result['Name']), $pbtables))
			{
				$pbtable[] = array($result['Name'], $result['Rows'], getRealSize($result['Data_length']));
			}
			else
			{
				$othertable[] = array($result['Name'], $result['Rows'], getRealSize($result['Data_length']));
			}
		}
		unset($result);
		$filename = $db_prefix.gdate($timestamp, 'YmdHis').'_'.random(8);
		$TPL->assign('filename', $filename);
		$TPL->assign('pbtable', $pbtable);
		$TPL->assign('othertable', $othertable);
		$TPL->assign('showothertable', !empty($othertable));
	}
}
elseif ($type == 'import')
{
	if ($bakin)
	{
		if (!$sqlfile || !preg_match('/^[0-9a-zA-Z_]+\.sql$/i', $sqlfile))
		{
			showMsg($a_message['dbbak_file_error'], $actionurl);
		}
		$sqldump = '';
		$file = PBDIGG_CP.'dbak/'.$_GET['sqlfile'];
		if (file_exists($file) && ($fp = fopen($file, 'rb')))
		{
			$bakinfo = fread($fp, 200);
			rewind($fp);
			$detail = explode("\n", $bakinfo);
			$sqldump .= fread($fp, filesize($file));
			fclose($fp);
		}
		else
		{
			if($process)
			{
				$Cache->config();
				showMsg($a_message['import_success'], 'admincp.php?action=tool&type=cache');
			}
			else
			{
				redirect($a_message['import_failed'], $actionurl);
			}
		}
		if (substr($detail[1], 11) == $_PBENV['PB_VERSION'][0])
		{
			$sqlquery = splitsql($sqldump);
			unset($sqldump);
			foreach($sqlquery as $sql)
			{
				if(trim($sql) != '')
				{
					if(preg_match('/^CREATE/', $sql))
					{
						$extra = substr($sql, strrpos($sql,')') + 1);
						$tabletype = substr($extra, strpos($extra,'=') + 1);
						$tabletype = substr($tabletype, 0, (strpos($tabletype, ' ') ? strpos($tabletype, ' ') : strlen($tabletype)));
						$sql = str_replace($extra, '', $sql);
						if (strpos($db_charset, '-') !== FALSE)
						{
							$db_charset = str_replace('-', '', $db_charset);
						}
						if($DB->db_version() > '4.1')
						{
							$extra = $db_charset ? "ENGINE=$tabletype DEFAULT CHARSET=$db_charset;" : "ENGINE=$tabletype;";
						}
						else
						{
							$extra = "TYPE=$tabletype;";
						}
						$sql .= $extra;
					}
					$DB->db_query($sql);
				}
			}
			$vol_current = substr($detail[0], strpos($detail[0], '.') + 1);
			$vol_next = $vol_current + 1;
			list($file_current) = explode('.', $sqlfile);
			$file_next = substr($sqlfile, 0, strrpos($sqlfile, '_') + 1).$vol_next.'.sql';
			redirect(sprintf($a_message['volume_import_success'], $vol_current), 'admincp.php?action=database&type=import&bakin=1&sqlfile='.rawurlencode($file_next).'&process=ing', 1);
		}
		else
		{
			showMsg($a_message['bakfile_version_error'], $actionurl);
		}
	}
	else
	{
		//list bak file
		$bakfile = $bk = $file = array();
		$handle = opendir(PBDIGG_CP.'dbak');
		$filenum = 0;
		while (($file = readdir($handle)) !== FALSE)
		{
			if (preg_match("/^".$db_prefix."[0-9]{14}_[0-9a-zA-Z_]{8}_[\d]+\.sql$/i", $file))
			{
				$strlen = 24 + strlen($db_prefix);
				$fp = fopen(PBDIGG_CP.'dbak/'.$file, 'rb');
				$bakinfo = fread($fp, 200);
				fclose($fp);
				$detail = explode("\n", $bakinfo);
				$bk['filename'] = $file;
				$bk['version'] = substr($detail[1], 11);
				$bk['bakdate'] = substr($detail[2], 8);
				$bk['pre'] = substr($file, 0, strrpos($file, '_'));
				$bk['volume']= substr($file, $strlen, strrpos($file, '.') - $strlen);
				$filenum++;
				$bakfile[]= $bk;
			}
		}
		$actionurl = 'admincp.php?action=database&type=delfile';
		$TPL->assign('filenum', $filenum);
		$TPL->assign('bakfile', $bakfile);
	}
}
elseif ($type == 'optimize')
{
	if ($submitted)
	{
		@set_time_limit(0);
		$optDB = implode(',', $pbtables);
		if (isset($repair))
		{
			$DB->db_query("REPAIR TABLE $optDB EXTENDED");
		}
		if (isset($optimize))
		{
			$DB->db_query("OPTIMIZE TABLE $optDB EXTENDED");
		}
		redirect($a_message['optimize_success'], $actionurl);
	}
}
elseif ($type == 'checksqlfile')
{
	if (substr($sqlfile, strpos($sqlfile, '.') - 1, 1) != 1)
	{
		showMsg($a_message['first_vol_limit'], $baseurl.'import');
	}
	$file = PBDIGG_CP.'dbak/'.$sqlfile;
	if (file_exists($file))
	{
		$fp = @fopen($file, 'rb');
		$detail = explode("\n", fread($fp, 200));
		fclose($fp);
		if (substr($detail[1],11) != $_PBENV['PB_VERSION'][0])
		{
			showMsg($a_message['bakfile_version_error'], $baseurl.'import');
		}
	}
	else
	{
		showMsg($a_message['bakfile_not_exist'], $baseurl.'import');
	}
	$actionurl = 'admincp.php?action=database&type=import&sqlfile='.$sqlfile;
}
elseif ($type == 'delfile')
{
	if (empty($dbfile) || !is_array($dbfile))
	{
		showMsg($a_message['parameter_error'], $baseurl.'import');
	}
	foreach($dbfile as $key => $value)
	{
		if(preg_match('/\.sql$/', $value))
		{
			PDel(PBDIGG_CP."dbak/$value");
		}
	}
	redirect($a_message['del_success'], $baseurl.'import');
}
else
{
	$database = $result = array();
	if($db_prefix != 'pb_')
	{
	foreach($pbtables as $key => $value)
	{
		$pbtables[$key] = str_replace('pb_', $db_prefix, $value);
	}
	}
	$database['version'] = $DB->db_version();
	$DB->db_query('SHOW STATUS');
	while ($result = $DB->db_fetch_array())
	{
		if ((strpos(strtolower($result['Variable_name']), 'uptime')) !== FALSE)
		{
			$database['runtime'] = timespanFormat($result['Value']);
			break;
		}
	}
	$TPL->assign('database', $database);
	$DB->db_query('SHOW TABLE STATUS');
	$pbtable = $othertable = $result = array();
	$pbtablenum = $pbrownum = $pbtotalsize = $othertablenum = $otherrownum = $othertotalsize = 0;
	while ($result = $DB->db_fetch_array())
	{
		if (in_array($result['Name'], $pbtables))
		{
			$pbrownum += $result['Rows'];
			$pbtotalsize += ($result['Data_length'] + $result['Index_length'] + $result['Data_free']);
			$result['Type'] = isset($result['Type']) ? $result['Type'] : $result['Engine'];
			$pbtablenum++;
			$pbtable[] = array($result['Name'], $result['Type'], $result['Rows'], $result['Update_time'], getRealSize($result['Data_length']), getRealSize($result['Data_free']));
		}
		else
		{
			$otherrownum += $result['Rows'];
			$othertotalsize += ($result['Data_length'] + $result['Index_length'] + $result['Data_free']);
			$result['Type'] = isset($result['Type']) ? $result['Type'] : $result['Engine'];
			$othertablenum++;
			$othertable[] = array($result['Name'], $result['Type'], $result['Rows'], $result['Update_time'], getRealSize($result['Data_length']), getRealSize($result['Data_free']));
		}
	}
	$pbtableinfo = array($pbtablenum, $pbrownum, getRealSize($pbtotalsize));
	$othertableinfo = array($othertablenum, $otherrownum, getRealSize($othertotalsize));
	$TPL->assign('pbtableinfo', $pbtableinfo);
	$TPL->assign('othertableinfo', $othertableinfo);
	$TPL->assign('showothertable', ($othertablenum[0] > 0));
	$TPL->assign('pbtable', $pbtable);
	$TPL->assign('othertable', $othertable);
}

$TPL->assign('menu', $m_db);
?>
