<?php
if (!defined('IN_COPPERMINE')) die('Not in Coppermine...');
set_time_limit(0);

ini_set("display_errors","1");
error_reporting(E_ALL);

require('include/init.inc.php');

function findtype($file)
{
	$file = strtolower($file);
	$revfile = strrev($file);
	$type = strtolower( strrev(substr($revfile,0,strpos($revfile,"."))) );
	
	return $type;
} 

function readfile_chunked($filename,$retbytes=true)
{
	$chunksize = 1*(1024*1024); // how many bytes per chunk
	$buffer = '';
	$cnt =0;
	// $handle = fopen($filename, 'rb');
	$handle = fopen($filename, 'rb');
	if ($handle === false)
	{
		return false;
	}
	while (!feof($handle))
	{
		$buffer = fread($handle, $chunksize);
		echo $buffer;
		ob_flush();
		flush();
		if ($retbytes)
		{
			$cnt += strlen($buffer);
		}
	}
	$status = fclose($handle);
	if ($retbytes && $status)
	{
		return $cnt; // return num. bytes delivered like readfile() does.
	}
	return $status;
}

function display_error()
{
	readfile_chunked("./images/read_error48x48.gif");
	exit();
}

if (isset($_GET['pid']))
{
    $pid = $_GET ['pid'];
    $method = $_GET['method'];
    
	$result = cpg_db_query("SELECT filepath, filename FROM {$CONFIG['TABLE_PICTURES']} WHERE pid='$pid'");  
	$row = mysql_fetch_array($result);
	mysql_free_result($result);
    	mysql_close();
	$filepath = $row['filepath'];
	$filename = $row['filename'];
	
    if($method == "thumb")
    {
	    $file = $CONFIG['fullpath'] . $filepath . $CONFIG['thumb_pfx'] . $filename;
    }
    else if($method == "normal")
    {
	    $file = $CONFIG['fullpath'] . $filepath . $CONFIG['normal_pfx'] . $filename;
    }
    else if($method == "fullsize")
    {
	    $file = $CONFIG['fullpath'] . $filepath . $filename;
    }
    else if($method == "dl")
    {
	    $file = $CONFIG['fullpath'] . $filepath . $filename;
    }
    else
    {
	    display_error();
    }
   
	if(md5($file) != $_GET['pr'])
		display_error();
	
	if (file_exists($file) && $filepath != "" && $filename != "")
	{
		if($method == "dl")
		{
			$save_as_name = basename($file);
			ini_set('session.cache_limiter', '');
			
			header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
			header('Pragma: no-cache');
			header("Content-Type: application/octet-stream");
			header("Content-Disposition: disposition-type=attachment; filename=\"$save_as_name\"");
		}
		else
		{
			$filetype = findtype($filename);
			if ($filetype == "jpg")
			{
				header("Content-type: image/jpeg");
			}
			else if($filetype == "png")
			{
				header("Content-type: image/png");
			}
			else if($filetype == "gif")
			{
				header("Content-type: image/gif");
			}
		}
		readfile_chunked($file);
	}
	else
	{
		//File did not exist
		display_error();
	}
}
else
{
	//If no PID is set
	display_error();
}

?>