<?php
#############################################
# 0JXRgdC70Lgg0YLRiyDRh9C40YLQsNC10YjRjCDRj #
# dGC0L4g0YHQvtC+0LHRidC10L3QuNC1LCDQt9C90L #
# DRh9C40YIg0YLRiyDQvdC10LzQvdC+0LPQviDQt9C #
# 90LDQtdGI0YwgUEhQIQ== #
#__---------------------------------------__#
#__ 0JrQu9C40Log0JrQu9GD0LE= __#
# --------------------------------------- #
# 0JDQstGC0L7RgCA6IE1vcmdhbg== #
# SUNRIDog0L3QtSDRgdC60LDQttGDIHhE #
# #
#############################################
require '../inc/start.php';
require '../inc/regvars.php';
require '../inc/db.php';
require '../inc/config.php';
require '../inc/funct.php';
require '../inc/antidos.php';
require '../inc/gzip.php';
require '../inc/header.php';
only_reg('/aut.php?',true);
if($user_prof['admin']<3){location('menu/index.php');}
$mode = (!empty($_GET['mode'])) ? $_GET['mode'] : '';
if($mode!='load')
{
$title = 'Бэкап БД';
require '../inc/head.php';
echo '<div class="sec">
Бэкап БД
</div><div class="vstavka">
';
}
switch($mode)
{
####################
####################
default:
$array_types = array('MyISAM','ISAM','HEAP','InnoDB');
$tbl_count=0;
$db_size=0;
$result=query("SHOW TABLE STATUS FROM `$db[db]`");
while($row=mysql_fetch_array($result)){
if (!isset($row['Type'])) $row['Type'] = '';
if (!isset($row['Engine'])) $row['Engine'] = '';
if(in_array($row['Type'],$array_types) || in_array($row['Engine'],$array_types))
{
$tbl_count++;
$db_size+=$row['Data_length']+$row['Index_length'];
}
}
echo '<div class="ad">Размер базы данных : <b>'.formatsize($db_size).'</b></div>
<div class="ad">Количество таблиц : <b>'.$tbl_count.postfix($tbl_count,'таблиц','таблица','таблица').'</b></div>
<br />
<form action="backup.php?mode=backup" method="POST" name="backupf">
Вы можете <br />
<input name="all" type="radio" value="1" checked="checked">сделать бэкап всех таблиц<br />
либо<br />
<input name="all" type="radio" value="0">выбрать таблицы для бэкапа : <br />';
if($web_brows==true)
{
echo '
<script type="text/javascript">
<!--
function select(selected){for(i=0;i<document.backupf.elements["tables[]"].length;i++){document.backupf.elements["tables[]"].options[i].selected = selected;}}
function selectCore(){for(i=0;i<document.backupf.elements["tables[]"].length;i++){document.backupf.elements["tables[]"].options[i].selected = (document.backupf.elements["tables[]"].options[i].text).match("^'.$db['prefix'].'");}}
-->
</script>
';
echo '
( <a href="javascript:void(0)" OnClick="javascript:select(true)">все</a> | <a href="javascript:void(0)" OnClick="javascript:select(false)">отмена</a> | <a href="javascript:void(0)" OnClick="javascript:selectCore()">ядро</a> )<br />';
}
echo '<select size="7" name="tables[]" multiple="yes">
';
$tables = mysql_list_tables($db['db']);
while($table = mysql_fetch_array($tables))
{
echo ' <option value="'.$table[0].'">'.$table[0].'</option>
';
}
echo '</select><br />
Имя файла : <br />
<input name="name_backup" type="text" value="backup_'.formatdate(0,'G-i_d_m_Y').'" maxlength="100"><br />
Режим : <br />
<select size="1" name="mode">
<option value="0">Структура</option>
<option value="1" selected="selected">Структура+Данные</option>
<option value="2">Данные</option>
</select><br />
Секретный код : <br />
<input name="secret_code" type="password"><br />
<input type="submit" value="Бэкап">
</form>
';
break;
####################
####################
case 'backup':
$secret_code = my_md5(obr($_POST['secret_code'],'string'));
if($secret_code == $config['secret_code'])
{
$name = obr($_POST['name_backup'],'string',100);
if($name!='' && preg_match('|^([a-z0-9_\-]*)$|iu',$name))
{
$mode = obr($_POST['mode'],'integer',1);
if($mode>=0 && $mode<=2)
{
$all = $_POST['all'];
if($all == 1)
{
$res_tables = mysql_list_tables($db['db']);
while($res_table = mysql_fetch_array($res_tables))$tselect[] = $res_table[0];
}
else
{
$tselect = $_POST['tables'];
}
$count_tselect = count($tselect);
if($count_tselect>0 || $all == 1)
{
function fput($name,$data)
{
$fp = fopen($name,'a+');
fwrite($fp,$data);
fclose($fp);
}
$result = '-- --
-- Click Club by Morgan
-- --
-- Хост '.gethostbyaddr($_remote_host).'
-- Время создания '.formatdate(0,'G:i:s d M y',false,false).'
-- Версия сервера: '.mysql_get_server_info().'
-- Версия клиента: '.mysql_get_client_info().'
-- Версия PHP: '.phpversion().'
--
-- БД `'.$db['db'].'`
';
$rand_filename = 'rand_'.rand(1,99999);
mkdir('data/'.$rand_filename,0777);
file_put_contents('data/'.$rand_filename.'/start.sql',$result);
for($i = 0;$i < $count_tselect;$i ++)
{
query("OPTIMIZE TABLE `$tselect[$i]`");
//-------------
//------------- Структура
//-------------
$res_fields = query("SHOW FIELDS FROM `$tselect[$i]`");
$count_fields = mysql_num_rows($res_fields);
echo 'Таблица <b>'.$tselect[$i].'</b>(<b>'.$count_fields.'</b>'.postfix($count_fields,'полей','поля','поле').')<br />
';
//
$result_table = '
-- -----------------------------------------------
-- ---------
-- Таблица '.$tselect[$i].'
-- ---------
';
fput('data/'.$rand_filename.'/table_'.$tselect[$i].'.sql',$result_table);
//-- Лист столбцов
$list_fields = '';
if($mode==0 || $mode==1)
{
$result_table = '
--
-- Структура
--
CREATE TABLE `'.$tselect[$i].'` (
';
//-- Первичный ключ
$primary_keys = '';
//-- Структура , столбцы
for($j=0;$j<$count_fields;$j++)
{
$field = mysql_fetch_array($res_fields);
$result_field = ' `'.$field['Field'].'` '.$field['Type'].' ';
$list_fields .= ',`'.$field['Field'].'`';
if($field['Null']=='NO'){$result_field .= 'NOT NULL';}else{$result_field .= 'NULL';}
if(!empty($field['Extra']))$result_field .= ' '.$field['Extra'];
if($field['Key']=='PRI')$primary_keys .= ',`'.$field['Field'].'`';
$result_table .= $result_field .= ',
';
#array_dump($field);
}
if($primary_keys!='')
{
$result_table .= ' PRIMARY KEY ('.(substr($primary_keys,1)).'),';
}
$result_table = substr($result_table,0,strrpos($result_table,','));
$inftable = mysql_fetch_array(query("SHOW TABLE STATUS WHERE `Name`='$tselect[$i]'"));
$result_table .= '
) ENGINE='.$inftable['Engine'].' DEFAULT COLLATE='.$inftable['Collation'].' '.(!empty($inftable['Auto_increment']) ? ' AUTO_INCREMENT='.$inftable['Auto_increment'] : '').';
';
fput('data/'.$rand_filename.'/table_'.$tselect[$i].'.sql',"\r\n".$result_table);
}
if($mode==1 || $mode==2)
{
//-------------
//------------- Дамп
//-------------
$res_records = query("SELECT * FROM `$tselect[$i]`");
$count_records = mysql_num_rows($res_records);
if($count_records>0)
{
$result_table = '
--
-- Данные
--
';
fput('data/'.$rand_filename.'/table_'.$tselect[$i].'.sql',"\r\n".$result_table);
if(empty($list_fields))
{
while($fldontbl = mysql_fetch_array($res_fields))
{
$list_fields .= ','.$fldontbl['Field'];
}
}
$list_fields = '('.substr($list_fields,1).')';
$result_record = null;
$ir = 0;
while($record = mysql_fetch_array($res_records))
{
$result_record_r_d = null;
$ir ++;
for($r=0;$r<$count_fields;$r++)
{
if(is_numeric($record[$r])){ $result_record_r_d .= ','.$record[$r];}
else{ $result_record_r_d .= ',0x'.bin2hex($record[$r]); }
}
$result_record_r = 'INSERT INTO `'.$tselect[$i].'` '.$list_fields.' VALUES ('.substr($result_record_r_d,1).');
';
$result_record .= $result_record_r;
# $result_table .= $result_record;
if(is_integer($ir / 1000))
{
# echo $ir.'<br/ >';
fput('data/'.$rand_filename.'/table_'.$tselect[$i].'.sql',"\r\n".$result_record);
$result_record = null;
}
}
}
}
#file_put_contents('data/'.$rand_filename.'/table_'.$tselect[$i].'.tmp',$result_table);
#$result .= $result_table;
}
#$fp = fopen('data/'.$name.'.sql.gz','w+');
#fwrite($fp,gzencode($result,9));
#fclose($fp);
#file_put_contents('data/'.$name.'.sql.gz',gzencode(file_get_contents('data/'.$rand_filename.'.tmp')));
#unlink('data/'.$rand_filename.'.tmp');
/*
//===== Грузим ZIP
require '../inc/zip.lib.php';
$zip = new createZip();
$zip -> addFile(file_get_contents('data/'.$rand_filename.'/start.tmp'),'start.sql');
unlink('data/'.$rand_filename.'/start.tmp');
for($i = 0;$i < $count_tselect;$i ++)
{
$zip -> addFIle(gzencode(file_get_contents('data/'.$rand_filename.'/table_'.$tselect[$i].'.tmp')),'table_'.$tselect[$i].'.sql.gz');
unlink('data/'.$rand_filename.'/table_'.$tselect[$i].'.tmp');
}
rmdir('data/'.$rand_filename);
file_put_contents('data/'.$name.'.zip',$zip -> getZippedFile());
//======
*/
require '../inc/pclzip.lib.php';
$pclzip_tmp_dir = 'data/'.$rand_filename;
$zip = new PclZip('data/'.$name.'.zip');
$added_files = array('data/'.$rand_filename.'/start.sql');
for($i = 0;$i < $count_tselect;$i ++)
{
$added_files[] = 'data/'.$rand_filename.'/table_'.$tselect[$i].'.sql';
}
$zip -> create($added_files,PCLZIP_OPT_REMOVE_ALL_PATH);
unlink('data/'.$rand_filename.'/start.sql');
for($i = 0;$i < $count_tselect;$i ++)
{
unlink('data/'.$rand_filename.'/table_'.$tselect[$i].'.sql');
}
rmdir('data/'.$rand_filename);
#$zip = null;
echo '<br />
Бэкап успешно создан!<br />
Он находиться по адресу <b>data/'.$name.'.zip</b><br />
Размер <b>'.formatsize(filesize('data/'.$name.'.zip')).'</b><br />
<form action="backup.php?mode=load" method="POST">
<input name="file" type="hidden" value="'.$name.'">
<input type="submit" value="Скачать >>>">
</form>
';
// -- Удаляем старые файлы (больше месяца)
$od = opendir('data');
while(false !== ($rd = readdir($od)))
{
if(strtolower(pathinfo($rd,PATHINFO_EXTENSION)) == 'zip' && ($sitetime - filemtime('data/'.$rd)) > 2592000)
{
chmod('data/'.$rd,0777);
unlink('data/'.$rd);
}
# echo strtolower(pathinfo($rd,PATHINFO_EXTENSION));
}
}else{echo 'Выберите хотя бы одну таблицу!<br />
<a href="backup.php?"><<<Назад</a><br />';}
}else{echo 'Выберите режим!<br />
<a href="backup.php?"><<<Назад</a><br />';}
}else{echo 'Введите имя!<br />
<a href="backup.php?"><<<Назад</a><br />';}
}else{echo 'Код введен не верно!<br />
<a href="backup.php?"><<<Назад</a><br />';}
break;
####################
####################
case 'load':
if(!empty($_POST['file']))
{
$file = obr($_POST['file'],'string',100);
if(!empty($file) && preg_match('|^([a-z0-9_-]*)$|iu',$file) && file_exists('data/'.$file.'.zip'))
{
header('HTTP/1.0 200 OK');
header('Cache-Control: public, must-revalidate, max-age=0');
header('Pragma: cache');
$etag = md5($file['filename']);
$etag = substr($etag, 0, 4) . '-' . substr($etag, 5, 5) . '-' . substr($etag, 10, 8);
header('ETag: "' . $etag . '"');
header('Keep-Alive: timeout=15, max=50');
header('Connection: Keep-Alive');
header('Accept-Ranges: bytes');
header('Content-Length: '.filesize('data/'.$file.'.zip'));
header('Content-Type: application/x-gzip');
header('Content-Disposition: attachment;filename='.$file.'.zip');
readfile('data/'.$file.'.zip');
exit;
# $fp = gzopen('data/'.$file.'.gz','rb');
# $bfile = gzread($fp,filesize('data/'.$file.'.gz'));
# gzpassthru($fp);
# gzclose($fp);
}else{location('admin/backup.php');}
}else{location('admin/backup.php');}
break;
}
echo '<hr/>';
echo '..<a href="/admin/index.php?">Админ панель</a><br />';
echo '.<a href="/menu/index.php?">Кабинет</a><br />';
require '../inc/foot.php';
################################################
# 0KHQutGA0LjQv9GCINC90LUg0L/QsNCx0LvQuNC6IQ== #
# 0KHRgtCw0LLRgNC+0L/QvtC70YwsIDIwMDkg0LMu #
################################################
?>