<?php
$title->SetTitle('Маркет - Просмотр архива');
///Подключаем шапку
$title->GetHeader();

$id = isset($_GET['id']) ? abs((int)$_GET['id']) : false;
if (empty($id)) {
header ('location: /');
exit;
}
$query = DB :: $dbs -> query ("SELECT * FROM `magazin_file` WHERE `id`= ?", [$id]);
if ($query -> rowCount () == 0) {
header ('location: /');
exit;
}
$file = $query -> fetch ();
$pr = DB :: $dbs -> queryFetch ("SELECT * FROM `magazin_pr` WHERE `id`= ?", [$file['id_pr']]);
$r = DB :: $dbs -> queryFetch ("SELECT * FROM magazin_r WHERE id = ?", [$file['id_r']]);

echo '<div class="container-fluid page_header"><div class="container"><div class="row"><div class="col-xs-12 col-sm-8 col-md-9 col-lg-9"><h1>Маркет - Просмотр архива ' . $file['name'].' </h1><ol class="breadcrumb" xmlns:v="http://'.homeurl.'/#"><li typeof="v:Breadcrumb"><a href="/" rel="v:url" property="v:title">'.homeurl.'</a></li><li typeof="v:Breadcrumb"><a href="/market" rel="v:url" property="v:title">Маркет</a></li><li typeof="v:Breadcrumb"><a href="/market/kat/'.$r['id'].'" rel="v:url" property="v:title">' . $r['name'].'</a></li><li typeof="v:Breadcrumb"><a href="/market/dir/'.$pr['id'].'" rel="v:url" property="v:title">' . $pr['name'].'</a></li><li class="active" typeof="v:Breadcrumb"><span property="v:title">' . $file['name'].'</span></li></ol></div></div></div></div>';
echo'<div class="container page_body"><div class="row"><div class="col-xs-12 page_content col-lg-9"><div class="navbar page_content_navbar collapse hidden-lg"><div class="container-fluid"><div class="navbar-collapse"></div></div></div><div class="text_box hidden-lg pr_block_small hidden"></div><div class="container-fluid cols_table">';


echo'<div class="catSides"><a href="/market"><i class="md-format-list-bulleted"></i> Маркет</a> - Просмотр архива ' . $file['name'].'</div>';

if ($b['level']<4) {
header('location:/');
die();
}
require_once('../market/lib/pclzip.lib.php');
/* не трогать функции */
function win_to_utf($str){
if(function_exists('mb_convert_encoding')) return mb_convert_encoding($str, 'utf-8', 'windows-1251');
if (function_exists('iconv')) return iconv('windows-1251', 'utf-8', $str);
$win1251utf8 = array(
"xC0"=>"А","xC1"=>"Б","xC2"=>"В","xC3"=>"Г","xC4"=>"Д","xC5"=>"Е","xA8"=>"Ё","xC6"=>"Ж","xC7"=>"З","xC8"=>"И","xC9"=>"Й","xCA"=>"К","xCB"=>"Л","xCC"=>"М",
"xCD"=>"Н","xCE"=>"О","xCF"=>"П","xD0"=>"Р","xD1"=>"С","xD2"=>"Т","xD3"=>"У","xD4"=>"Ф","xD5"=>"Х","xD6"=>"Ц","xD7"=>"Ч","xD8"=>"Ш","xD9"=>"Щ","xDA"=>"Ъ",
"xDB"=>"Ы","xDC"=>"Ь","xDD"=>"Э","xDE"=>"Ю","xDF"=>"Я","xE0"=>"а","xE1"=>"б","xE2"=>"в","xE3"=>"г","xE4"=>"д","xE5"=>"е","xB8"=>"ё","xE6"=>"ж","xE7"=>"з",
"xE8"=>"и","xE9"=>"й","xEA"=>"к","xEB"=>"л","xEC"=>"м","xED"=>"н","xEE"=>"о","xEF"=>"п","xF0"=>"р","xF1"=>"с","xF2"=>"т","xF3"=>"у","xF4"=>"ф","xF5"=>"х",
"xF6"=>"ц","xF7"=>"ч","xF8"=>"ш","xF9"=>"щ","xFA"=>"ъ","xFB"=>"ы","xFC"=>"ь","xFD"=>"э","xFE"=>"ю","xFF"=>"я");
return strtr($str, $win1251utf8);
}
function is_utf($str)
{
$c = 0;
$b = 0;
$bits = 0;
$len = strlen($str);
for($i = 0; $i < $len; $i++)
{
$c = ord($str[$i]);
if($c > 128) {
if (($c >= 254)) return false;
elseif ($c >= 252) $bits = 6;
elseif ($c >= 248) $bits = 5;
elseif ($c >= 240) $bits = 4;
elseif ($c >= 224) $bits = 3;
elseif ($c >= 192) $bits = 2;
else return false;
if (($i + $bits) > $len) return false;
while ($bits > 1) {
$i++;
$b = ord($str[$i]);
if ($b < 128 || $b > 191) return false;
$bits--;
}
}
}
return true;
}
/* Подсвечиваем код */
function hightlight($code) {
$code = stripslashes($code);
if(!strpos($code,"<?") && substr($code,0,2)!="<?"){
$code="<?php
".trim($code)."
?>";}
$code = trim($code);
$code=highlight_string($code,true);
return '<div class="citat">'.$code.'</div>';
}
//---------------//
$onpage = 10;
$id = abs(intval($_GET['id']));
$page = abs(intval($_GET['page']));
$start = abs(intval($_GET['start']));
$act = (isset($_GET['act']) && $_GET['act'] == 'preview') ? htmlspecialchars($_GET['act']) : NULL;
$d = DB::$dbs->queryFetch("SELECT * FROM `magazin_file` WHERE `id` = ?",[$id]);
$di = ROOT.'files/mag_file/'.$d['file'];
if (!file_exists($di)) {
header('location:/');
exit();
}
/* Получаем каталог */
$filename = pathinfo($di);
$ext = strtolower($filename['extension']);
if ($ext != 'zip') die('Файл не является ZIP архивом');
$dir = $filename['dirname'] . '/';
$back = DB::$dbs->queryFetch("SELECT * FROM `magazin_file` WHERE `file` = ?",[$dir]);
/* Содержимоe */
if (!$act){
$zip = new PclZip($di);
if (!$list = $zip->listContent()) die('Ошибка: '.$zip->errorInfo(true));
for($i = 0; $i < sizeof($list); ++$i){
for(reset($list[$i]); $key = key($list[$i]); next($list[$i]))
{
$zfilesize = strstr($listcontent, '--size');
$zfilesize = str_replace('--size:', '', $zfilesize);
$zfilesize = str_replace($zfilesize, $zfilesize . '|', $zfilesize);
$sizelist .= $zfilesize;
$listcontent = "[$i]--$key:" . $list[$i][$key];
$zfile = strstr($listcontent, '--filename');
$zfile = str_replace('--filename:', '', $zfile);
$zfile = str_replace($zfile, $zfile . '|', $zfile);
$savelist .= $zfile;
}
}
$sizefiles2 = explode('|', $sizelist);

$sizelist2 = array_sum($sizefiles2);
$obkb = round($sizelist2 / 1024, 2);
$preview = $savelist;

$preview = explode('|', $preview);

$count = count($preview) - 1;
echo'<div class="row text_box">Всего файлов: ' .$count . '<br/>Вес распакованного архива: ' . $obkb . ' kb</div>';
if (!isset($page)) $page = 1;
$n = 0;
$pages = ceil($count / $onpage);
if (!$pages) $pages = 1;
if ($page) $n = ($onpage * $page) - $onpage;
if ($count == 0) echo 'Пусто...';
$sizefiles = explode('|', $sizelist);
$selectfile = explode('|', $savelist);

$open = htmlspecialchars($_GET['open']);
for ($i = 1; $i <= $onpage; ++$i)
{
if (empty($selectfile[$n]))
{
$n++;
continue;
}

$path = $selectfile[$n];
$fname = $path;
#$zdir = preg_replace('/[/]?[^/]*$/', '', $path);
echo '<div class="row text_box"><a href="?act=preview&id='.$id.'&open='.$path.'"><i class="md-file-download"></i> ' . $fname.'</a>';
if ($sizefiles[$n] != 0) echo ' (' . round($sizefiles[$n] / 1024, 2) . 'kb)';
echo '<br/>';
echo'</a></div>';
$n++;
}
echo '<div class="row text_box">';
echo 'Страницы: ';
$asd = $page - 2;
$asd2 = $page + 3;
if ($asd < $count && $asd > 0 && $page > 3) echo '<a href="/market/zip/'.$id.'?page=1">1</a> ... ';
for($i = $asd; $i < $asd2; $i++)
{
if ($i < $count && $i > 0)
{
if ($i > $pages) break;
if ($page == $i) echo '<b>[' . $i . ']</b> ';
else echo '<a href="/market/zip/'.$id.'?page='.$i.'">' . $i . '</a> ';
}
}
if ($i <= $pages)
{
if ($asd2 < $count) echo ' ... <a href="/market/zip/'.$id.'?page='.$pages.'">' . $pages . '</a>';
}
echo '</div>';
}
/* Просмотр файла */
if ($act == 'preview')
{
$open = htmlspecialchars(trim($_GET['open']));
if (strpos($open , '..') !== false or strpos($open , './') !== false)
{
echo 'В хакера решил поиграть?';
///Подключаем футер
$title->GetFooter();
exit();
}

$zip = new PclZip($di);
$content = $zip->extract(PCLZIP_OPT_BY_NAME, $open, PCLZIP_OPT_EXTRACT_AS_STRING);
$content = $content[0]['content'];
$preview2 = explode("n", $content);
$count = count($preview2);
echo '<div class="row text_box"><b>Файл: ' . $open . '</b></div>';
$eX = strtolower(strrchr($open, '.'));

$php = ['.php', '.pl', '.js', '.jsp', '.html', '.xhtml', '.xml', '.wml', '.asp', '.aspx'];
$txt = ['.txt', '.sql', '.dat', '.css', '.ini', '.function', '.htaccess', '.tpl'];
$img = ['.gif', '.jpg', '.jpeg', '.png', '.bmp', '.wbmp', '.ico', '.swf'];

if (empty($content)) die('<div class="error">Файл пуст.</div>');

if (isset($_GET['img'])){
$ext = strtolower(substr($open, strrpos($open, '.') + 1));

ob_end_clean();
ob_clean();

header("Content-type: image/$ext");
header("Content-Length: " . strlen($content));
header('Content-Disposition: inline; filename="' . $open . '"');

echo $content;
///Подключаем футер
$title->GetFooter();
exit();
}

if (in_array($eX, $php))
{
echo  (!empty($content) ? '<div class="row text_box">Строк: ' . $count . '</div>' : '');
if (is_utf($content)) echo '<div class="row text_box">' . hightlight($content).'</div>';
else echo ' <div class="row text_box">' . hightlight(win_to_utf($content)). '</div>';
}
elseif (in_array($eX, $txt))
{
$content = htmlspecialchars($content);
echo  (!empty($content) ? '<div class="row text_box">Строк: ' . $count . '</div>' : '');
if ($content) echo '<div class="row text_box">' . nl2br($content) . '</div>';
else echo '<div class="row text_box">' . win_to_utf(nl2br($content)) . '</div>';
}
elseif (in_array($eX, $img)){
echo '<div class="row text_box"><img src="/market/zip/preview/'.$id.'?open='.$open.'&amp;img" alt=""/></div>';
}
else
{
die('Невозможно прочесть файл!');
}
}
echo '<ul class="nav nav-pills nav-stacked"><li><a href="/market/file/'.$id.'"><i class="md-apps"></i>  Вернуться к файлу</a></ul>';
if (isset($_GET['act'])) echo '<ul class="nav nav-pills nav-stacked"><li><a href="/market/zip/'.$id.'"><i class="md-apps"></i>  К просмотру архива</a></ul>';
?>