<?php
/*
=====================================================
 DataLife Engine - by SoftNews Media Group 
-----------------------------------------------------
 http://dle-news.ru/
-----------------------------------------------------
 Copyright (c) 2004,2010 SoftNews Media Group
=====================================================
 Данный код защищен авторскими правами
=====================================================
 Файл: download.php
-----------------------------------------------------
 Назначение: Скачивание файлов
=====================================================
*/
@session_start ();

define ( 'DATALIFEENGINE', true );
define ( 'FILE_DIR', '../uploads/files/' );
define ( 'ROOT_DIR', '..' );
define ( 'ENGINE_DIR', ROOT_DIR . '/engine' );

@error_reporting ( E_ALL ^ E_NOTICE );
@ini_set ( 'display_errors', true );
@ini_set ( 'html_errors', false );
@ini_set ( 'error_reporting', E_ALL ^ E_NOTICE );

require ENGINE_DIR . '/data/config.php';

if ($config['http_home_url'] == "") {
	
	$config['http_home_url'] = explode ( "engine/download.php", $_SERVER['PHP_SELF'] );
	$config['http_home_url'] = reset ( $config['http_home_url'] );
	$config['http_home_url'] = "http://" . $_SERVER['HTTP_HOST'] . $config['http_home_url'];

}

require_once ENGINE_DIR . '/classes/mysql.php';
require_once ENGINE_DIR . '/data/dbconfig.php';
require_once ENGINE_DIR . '/modules/functions.php';
require_once ENGINE_DIR . '/modules/sitelogin.php';
require_once ENGINE_DIR . '/classes/download.class.php';

function reset_url($url) {
	$value = str_replace ( "http://", "", $url );
	$value = str_replace ( "https://", "", $value );
	$value = str_replace ( "www.", "", $value );
	$value = explode ( "/", $value );
	$value = reset ( $value );
	return $value;
}

$sub = $_GET['sub'];

if( @preg_match( "/[\||\'|\<|\>|\"|\?|\$|\@|\/|\\\|\&\~\*\+]/", $sub ) ) 
	$sub = "";

///////////////// mangachan mod. если 5 id то это сабы, и выдаем сабы
/*
if( $_GET['id'] == 5 )
{	
	$real_pa = $sub;
	$row['name'] = explode("/", $real_pa);
	$row['name'] = end($row['name']);
//	$real_pa = substr( FILE_DIR . $real_pa, 2, strlen(FILE_DIR . $real_pa) );
//	$real_pa = str_replace("/uploads/files/", "", $real_pa);

	if ( !strstr($row['name'], "__hchan.live.") )
	{
		$row['name'] = str_replace(".srt", "__hchan.live.srt", $row['name']);
		$row['name'] = str_replace(".ass", "__hchan.live.ass", $row['name']);	
		$row['name'] = str_replace(".ssa", "__hchan.live.ssa", $row['name']);
	}

	header( "Pragma: public" );
	header( "Expires: 0" );
	header( "Cache-Control:" );
	header( "Cache-Control: public" );
	header( "Content-Description: File Transfer" );
	header( "Content-Transfer-Encoding: binary" );
	header( "Content-Type: text/plain; name={$row['name']}"  );
	header( 'Content-Disposition: attachment; filename="' . substr($row['name'], 11) . '";' );
	header("X-Accel-Redirect: " . $real_pa); 

	return;	
}
*/
////////////// закончили мод

////////// hentaichan mod. если вместо id указано не id, а link и ссылка, то увеличиваем счетчик и редиректим
/*
if($_GET['link'])
{
	$nid = $_GET['nid'];
	$db->query ( "UPDATE " . PREFIX . "_files SET dcount=dcount+1 WHERE news_id ='$nid'" );
	$ssilka = $_GET['link'];
	$link = "Location: $ssilka";	
	header($link);
}
*/
///////// закончили мод

//################# Определение групп пользователей
$user_group = get_vars ( "usergroup" );

if (! $user_group) {
	
	$user_group = array ();
	
	$db->query ( "SELECT * FROM " . USERPREFIX . "_usergroups ORDER BY id ASC" );
	
	while ( $row = $db->get_row () ) {
		
		$user_group[$row['id']] = array ();
		
		foreach ( $row as $key => $value ) {
			$user_group[$row['id']][$key] = $value;
		}
	
	}
	
	set_vars ( "usergroup", $user_group );
	$db->free ();

}

if (! $is_logged) {
	$member_id['user_group'] = 5;
}

if (! $user_group[$member_id['user_group']]['allow_files'])
	die ( "Access denied 1" );

if ($config['files_antileech']) {

	$_SERVER['HTTP_REFERER'] = reset_url ( $_SERVER['HTTP_REFERER'] );
	$_SERVER['HTTP_HOST'] = reset_url ( $_SERVER['HTTP_HOST'] );

	///////// hentaichan mod. делаем, чтобы с dl.hchan.live загрузка тоже прокатывала

	if ( $_SERVER['HTTP_HOST'] == "dl.imgschan.xyz")
		$_SERVER['HTTP_HOST'] = "hchan.live";
	if ( $_SERVER['HTTP_HOST'] == "dl.hentai-chan.pro")
		$_SERVER['HTTP_HOST'] = "hchan.live";
	if ( $_SERVER['HTTP_HOST'] == "dl2.hentai-chan.pro")
		$_SERVER['HTTP_HOST'] = "hchan.live";
	if ( $_SERVER['HTTP_HOST'] == "dl.hentai-chan.pro")
		$_SERVER['HTTP_HOST'] = "hchan.live";
	if ( $_SERVER['HTTP_HOST'] == "dl.hchan.pro")
		$_SERVER['HTTP_HOST'] = "hchan.live";
	if ( $_SERVER['HTTP_HOST'] == "dl.hchan.me")
		$_SERVER['HTTP_HOST'] = "hchan.live";
	if ( $_SERVER['HTTP_HOST'] == "exhentai-dono.me")
		$_SERVER['HTTP_HOST'] = "hchan.live";

	//////// закончили мод	
    if($_SERVER['HTTP_REFERER'] == 'exhentai-dono.me' || $_SERVER['HTTP_REFERER'] == 'hentaichan.live' || $_SERVER['HTTP_REFERER'] == 'y.hentaichan.live' || $_SERVER['HTTP_REFERER'] == 'xxxx.hentaichan.live') {
        ;
    }
	else if ($_SERVER['HTTP_HOST'] != $_SERVER['HTTP_REFERER']) {
//		@header ( 'Location: ' . $config['http_home_url'] );
//		die ( "Access denied!!!<br /><br />Please visit <a href=\"{$config['http_home_url']}\">{$config['http_home_url']}</a>" );
	}

}

$id = intval ( $_REQUEST['id'] );

if ($_REQUEST['area'] == "static")
	$row = $db->super_query ( "SELECT a.name, a.onserver, b.category FROM " . PREFIX . "_static_files a, " . PREFIX . "_post b WHERE a.id ='$id'" );
else
	$row = $db->super_query ( "SELECT a.name, a.onserver, a.news_id, b.category FROM " . PREFIX . "_files a, " . PREFIX . "_post b WHERE a.id ='$id'  AND a.news_id = b.id " );

if (! $row) {
	header("Location: /");
	die ( "Access denied 2" );
}

$config['files_max_speed'] = intval ( $config['files_max_speed'] );

////////// hentaichan mod. если троеточие в назваии, то хитро поступаем
//$row['onserver'] = str_replace( "\\", "/", $row['onserver'] );
//$row['onserver'] = str_replace( "..", "__", $row['onserver'] );
//$row['onserver'] = str_replace( "./", "_/", $row['onserver'] );
$r_o_t = $row['onserver'];
$row['onserver'] = str_replace( "\\", "/", $row['onserver'] );
$row['onserver'] = str_replace( "./", "_/", $row['onserver'] );
if ( !file_exists(FILE_DIR . $row['onserver']) && strstr($row['onserver'], "...") )
	$row['onserver'] = str_replace( "..", "__", $row['onserver'] );

if ( !file_exists(FILE_DIR . $row['onserver']) && strstr($r_o_t, "...") )
	$row['onserver'] = $r_o_t;

//if( $row['onserver'] == "1426751465_palco-nagashima-kekkon-wa-jinsei-no______-rrrerrrussian.zip" )
//	$row['onserver'] = "1426751465_palco-nagashima-kekkon-wa-jinsei-no......-rrrerrrussian.zip";

/////////// hentaichan mod. для архивов, которых нет на сервере физически, создаем временный архив из папки в галереи
$tempflag = false;
if ( !file_exists(FILE_DIR . $row['onserver']) )
{
set_time_limit(30800);
	/// смотрим, манга, игра, или видео это
	$category = $row['category'];
	if ($category == 2)
		$cat = "manga";
	else if ( $category == 8)
		$cat = "games";
	else if ( $category == 9)
		$cat = "video";

	$name_dir = substr( $row["onserver"], 0, -4 );
	$upload_path = ROOT_DIR . "/$cat/" . substr( $row["name"], 0, 1 ) . "/" . $name_dir . "/"; // тут лежит картиночная папка нужной мангой
///// отключаем создание темповых архивов, т.к. они почему то не удаляются. 
/*
	$tempflag = true;
	$filetemp = tempnam($_SERVER['DOCUMENT_ROOT']."/tmp", "zip");	
*/
	$filetemp = FILE_DIR . $row['onserver'];
/////////

	if ( !stristr($filetemp, ".zip") )
	{
		$filetemp = $filetemp . ".zip";
		$row['onserver'] = $row['onserver'] . ".zip";
		$row['name'] = $row['name'] . ".zip";
	}

	$zip = new ZipArchive;
	$zip->open($filetemp, ZIPARCHIVE::CREATE | ZIPARCHIVE::OVERWRITE);
	if ($handle = opendir($upload_path)) {
	    while (false !== ($pics = readdir($handle))) 
		{
			if ( $pics != ".." AND $pics != "." AND $pics != "thumbs"  )
			{
				$zip->addFile($upload_path.$pics, $pics);
			}
	    }
	    closedir($handle);
	}
	else echo "error";
	$zip->addFile(ROOT_DIR . "/manga/" . "hchan.live.txt", "hchan.live.txt");
	$zip->close();

/*
///////////// если не используем встроенный обработчик файлов, то сами можем
	if ($config['files_count'] == "yes" and ! $file->range)
		$db->query ( "UPDATE " . PREFIX . "_files SET dcount=dcount+1 WHERE id ='$id'" );
	$db->close ();

	$save_name = explode(".",$row["name"]);
	$save_name = $save_name[0];
	header('Content-Type: application/zip');
	header('Content-Length: ' . filesize($filetemp));
	header( "Content-Transfer-Encoding: binary" );
	$hh = "Content-Disposition: attachment; filename=$save_name";
	header($hh);

	readfile($filetemp);
	unlink($filetemp); 

	return;*/
}

if ( substr_count($row['name'], "__hchan.live") <= 0 )
{
//	$a = substr($row['name'], 0, -4);
//	$b = substr($row['name'], -4);
//	$row['name'] = $a . "__hchan.live" . $b;

    $ext = substr($row['name'], -3);
    if($ext == '001' || $ext == '002' || $ext == '003' || $ext == '004' || $ext == '005' || $ext == '006') {
    }
    else {
        if($row['news_id'] == 20523) {
        }
        else {
        	$row['name'] = str_replace(".zip", "__hchan.live.zip", $row['name']);
        	$row['name'] = str_replace(".7z", "__hchan.live.7z", $row['name']);	
            $row['name'] = str_replace(".rar", "__hchan.live.rar", $row['name']);
            $row['name'] = str_replace(".apk", "__hchan.live.apk", $row['name']);
        }
    }
}

/* hentaichan mod. убираем стандарный загрузк, делаем через nginx, счетчик тоже отключаем.
if ( $tempflag )
	$file = new download ( $filetemp, $row['name'], $config['files_force'], $config['files_max_speed'] );
else
///////// закончили мод
$file = new download ( FILE_DIR . $row['onserver'], $row['name'], $config['files_force'], $config['files_max_speed'] );


if ($_REQUEST['area'] == "static") {
	
	if ($config['files_count'] == "yes" and ! $file->range)
		$db->query ( "UPDATE " . PREFIX . "_static_files SET dcount=dcount+1 WHERE id ='$id'" );

} else {
	
	if ($config['files_count'] == "yes" and ! $file->range)
		$db->query ( "UPDATE " . PREFIX . "_files SET dcount=dcount+1 WHERE id ='$id'" );

}

$db->close ();

$file->download_file (); */

	if ($config['files_count'] == "yes" and ! $file->range)
		$db->query ( "UPDATE " . PREFIX . "_files SET dcount=dcount+1 WHERE id ='$id'" );

$real_pa = substr( FILE_DIR . $row['onserver'], 2, strlen(FILE_DIR . $row['onserver']) );

/*
if ( $row['category'] == 2 || $row['category'] == 8  || $row['category'] == 9 )
{
	header('HTTP/1.1 302 Moved Temporarily');
	$newurl = "Location: http://46.38.58.11{$real_pa}";
	header($newurl);
	return;
}
*/

$mainDomain = 'imgschan.xyz';


if ($row['category'] == 2) {
	$secured_stuff = "/uploads/files/{$row['onserver']}";
	$time  = time() + 86400; // 24 hours
	$hash = md5($time.$secured_stuff . " multichan", true);
	$hash = strtr( base64_encode($hash), array( '+' => '-', '/' => '_', '=' => '' ));

    if($_GET['id'] % 4 == 0) {
        $url    = "https://bigg2.{$mainDomain}" . "$secured_stuff" . "?hh={$hash}&expires={$time}&file={$row['name']}";
    }
    else if($_GET['id'] % 4 == 1) {
        if($_GET['id'] % 2 == 1) {
            $url    = "https://bigg2.{$mainDomain}" . "$secured_stuff" . "?hh={$hash}&expires={$time}&file={$row['name']}";
        }
        else {
            $url    = "https://bigg3.{$mainDomain}" . "$secured_stuff" . "?hh={$hash}&expires={$time}&file={$row['name']}";
        }
    }
    else if($_GET['id'] % 4 == 2) {
        $url    = "https://bigg3.{$mainDomain}" . "$secured_stuff" . "?hh={$hash}&expires={$time}&file={$row['name']}";
    }
    else if($_GET['id'] % 4 == 3) {
//        $url    = "https://bigg4.{$mainDomain}" . "$secured_stuff" . "?hh={$hash}&expires={$time}&file={$row['name']}";
        $url    = "https://bigg5.{$mainDomain}" . "$secured_stuff" . "?hh={$hash}&expires={$time}&file={$row['name']}";
    }
    else {
//        $url    = "https://bigg4.{$mainDomain}" . "$secured_stuff" . "?hh={$hash}&expires={$time}&file={$row['name']}";
        $url    = "https://bigg5.{$mainDomain}" . "$secured_stuff" . "?hh={$hash}&expires={$time}&file={$row['name']}";
        //die('Технические работы, архивы будут не доступны ближайщие 24-48 часов.');
    }

	$newurl = "Location:$url";
	header($newurl);
	return;
}
else {
	$secured_stuff = "/uploads/files/{$row['onserver']}";
	$time  = time() + 86400; // 24 hours
	$hash = md5($time.$secured_stuff . " multichan", true);
	$hash = strtr( base64_encode($hash), array( '+' => '-', '/' => '_', '=' => '' ));

    if($_GET['id'] == 37527 || $_GET['id'] == 48114 || $_GET['id'] == 48106 || $_GET['id'] == 48537) {
        $url = "https://bigg3.{$mainDomain}" . "$secured_stuff" . "?hh={$hash}&expires={$time}&file={$row['name']}";
    }
    else if($_GET['id'] % 4 == 0) {
        $url = "https://bigg6.{$mainDomain}" . "$secured_stuff" . "?hh={$hash}&expires={$time}&file={$row['name']}";
    }
    else if($_GET['id'] % 4 == 1) {
       $url = "https://bigg2.{$mainDomain}" . "$secured_stuff" . "?hh={$hash}&expires={$time}&file={$row['name']}";
    }
    else if($_GET['id'] % 4 == 2) {
       $url = "https://bigg3.{$mainDomain}" . "$secured_stuff" . "?hh={$hash}&expires={$time}&file={$row['name']}";
    }
    else if($_GET['id'] % 4 == 3) {
//        $url = "https://bigg4.{$mainDomain}" . "$secured_stuff" . "?hh={$hash}&expires={$time}&file={$row['name']}";
        $url = "https://bigg5.{$mainDomain}" . "$secured_stuff" . "?hh={$hash}&expires={$time}&file={$row['name']}";
    }
    else {
//        $url = "https://bigg4.{$mainDomain}" . "$secured_stuff" . "?hh={$hash}&expires={$time}&file={$row['name']}";
        $url = "https://bigg5.{$mainDomain}" . "$secured_stuff" . "?hh={$hash}&expires={$time}&file={$row['name']}";
        //die('Технические работы, архивы будут не доступны ближайщие 24-48 часов.');
    }

/*
    if($member_id['user_group'] == 1)
    	$url    = "http://big6.{$mainDomain}" . "$secured_stuff" . "?hh={$hash}&expires={$time}&file={$row['name']}";
    else 
    	$url    = "http://big.{$mainDomain}" . "$secured_stuff" . "?hh={$hash}&expires={$time}&file={$row['name']}";
*/

	$newurl = "Location:$url";
	header($newurl);
	return;
}

header( "Pragma: public" );
header( "Expires: 0" );
header( "Cache-Control:" );
header( "Cache-Control: public" );
header( "Content-Description: File Transfer" );
header( "Content-Transfer-Encoding: binary" );
if ( $row['category'] == 9 )
	header('Content-Type: video/x-flv');
else
	header( "Content-Type: application/zip"  );
if ( $row['category'] == 9 )
	header( 'Content-Disposition: attachment; filename="' . substr($row['name'], 11) . '";' );
else 
	header( 'Content-Disposition: attachment; filename="' . $row['name'] . '";' );
header("X-Accel-Redirect: " . $real_pa); 

/////////// hentaichan mod. не удаляем темповый архив, т.к. создаем его с в папке аплоадс с тем же именем, что и оригинальный файл
//unlink($filetemp);
/////////закончили мод
?>
