<?php
	require_once(dirname(__FILE__).'/init.php');

	if (FrontendAccess()) {
		/*********************************************
		* 	Return an attachment for a question      *
		*********************************************/
		if (isset($_GET['data'])) {
			$data = $_GET['data'];
			$arrData = explode('|', base64_decode($data));
			$questId = $arrData[0];
			$filename = $arrData[1];

			// Security measures
			$attachments_dir = dirname(__FILE__).DIRECTORY_SEPARATOR.'attachments';
			$file = sprintf('%s'.DIRECTORY_SEPARATOR.'%d'.DIRECTORY_SEPARATOR.'%s', $attachments_dir, $questId, $filename);
			$dir_of_file = dirname(realpath($file));
			
			if (is_numeric($questId) && $dir_of_file == $attachments_dir.DIRECTORY_SEPARATOR.$questId) {
				header('Pragma: public');
				header('Expires: 0');
				header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
				header('Content-Type: application/force-download');
				header('Content-Type: application/octet-stream');
				header('Content-Type: application/download');
				header('Content-Disposition: attachment; filename="'.$filename.'";');
				header('Content-Transfer-Encoding: binary');
				header('Content-Length: '.filesize($file));
				readfile_chunked($file,false);
				die();
			}
		}
	}
	
	header('Location: index.php');
	
	/**
	* readfile_chunked
	*
	* Read the file in chunks to preserve memory. 
	*/
	function readfile_chunked($filename,$retbytes=true) {
		$chunksize = 1*(1024*1024); // how many bytes per chunk
		$buffer = '';
		$cnt = 0;

		$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;
	}
?>