<?php
/**
 * @version $Id: attachments.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
 */

define('PB_CSCRIPT', 'attachments');
require_once('include/common.inc.php');

if (empty ($aid) || !is_numeric($aid))
{
	showMsg($u_message['parameter_error']);
}
$aid = (int)$aid;
if ($pb_attoutlink)
{
	$url = parse_url($_PBENV['PB_URL']);
	$host = $url['host'];
	if (!preg_match('/[\d\.]{7,15}/i', $host))
	{
		$domain = 'com,net,org,gov,info,mobi,la,biz,jp,cn,tv,cc,nu,us,cn,ac,bj,sh,tj,cq,he,sx,nm,ln,jl,hl,js,zj,ah,fj,jx,sd,ha,hb,hn,gd,gx,hi,sc,gz,yn,xz,sn,gs,qh,nx,xj,tw,hk,mo';
		$realurl = array();
		$urlparse = explode('.', $host);
		$paramindex = count($urlparse) - 1;
		if ($paramindex)
		{
			while ($paramindex > 0)
			{
				$realurl[] = $urlparse[$paramindex];
				if (strpos($domain, $urlparse[$paramindex]) === FALSE)
				{
					break;
				}
				$paramindex--;
			}
		}
		else
		{
			$realurl = $urlparse;
		}
		$host = implode('.', array_reverse($realurl));
	}
	if (isset($_SERVER['HTTP_REFERER']) && strpos($_SERVER['HTTP_REFERER'], $host) === FALSE)
	{
		showMsg($u_message['attachment_download_denied']);
	}
}

$attdata = $DB->db_fetch_one_array("SELECT * FROM {$db_prefix}attachments WHERE aid = $aid");
if ($attdata)
{
	$DB->db_query("UPDATE {$db_prefix}attachments SET downloads = downloads + 1 WHERE aid = $aid");
	$attachmentpath = PBDIGG_ROOT.'attachments/'.$attdata['filepath'];
	$disposition = 'attachment';
	if ($attdata['isimg'])
	{
		$imginfo = @getimagesize($attachmentpath);
		if ($imginfo[2] && $imginfo['bits'])
		{
			$disposition = 'inline';
		}
		unset($imginfo);
	}
	if (file_exists($attachmentpath) && is_readable($attachmentpath))
	{
		ob_end_clean();
		$filesize = filesize($attachmentpath);
		header('Cache-control: max-age=31536000');
		header('Expires: '.gmdate('D, d M Y H:i:s', $timestamp + 31536000).' GMT');
		header('Last-Modified: '.gmdate('D, d M Y H:i:s', $attdata['uploaddate']).' GMT');
		header('Content-Encoding: none');
		header('Content-type: '.$attdata['filetype']);
		header('Content-Disposition: '.$disposition.'; filename='.urldecode($attdata['filename']));
		header('Content-Length: '.$filesize);
		@readfile($attachmentpath);
//		$fp = fopen($attachmentpath, 'rb');
//		@flock($fp, LOCK_EX);
//		$attachment = @fread($fp, $filesize);
//		@fclose($fp);
//		echo $attachment;
		exit;
	}
	else
	{
		showMsg($u_message['attachment_noexist']);
	}
}
else
{
	showMsg($u_message['attachment_norecord']);
}

?>
