<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Download extends MY_Controller
{
	public function index()
	{
		$this->admin_login_required();
		$path = preg_replace('/^download/', ABSOLUTE_PATH, uri_string());

		if(file_exists($path))
		{
			if(is_file($path))
			{
				$mimes = array();

				$ch = curl_init("http://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types");
				curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
				curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
				$mimetypes = curl_exec($ch);
				curl_close($ch);

			    foreach(explode("\n", $mimetypes) as $x)
			        if(isset($x[0]) && $x[0] !== '#' && preg_match_all('#([^\s]+)#',$x,$out) && isset($out[1]) && ($c=count($out[1])) > 1)
			            for($i=1; $i<$c; $i++)
			                $mimes[$out[1][$i]] = $out[1][0];

			    $pathinfo = pathinfo($path);
				$mimetype = $mimes[$pathinfo['extension']];

				if(isset($_SERVER['MOD_XSENDFILE_ENABLED']) && $_SERVER['MOD_XSENDFILE_ENABLED'])
		    	{
			    	header("X-SendFile: $path", true);
			    	header("Content-Type: " . $mimetype, true);
			    	header("Content-Disposition: attachment; filename=\"" . addslashes(basename($path)) . "\"", true);
			    	exit;
			    }

				header("Content-Type: " . $mimetype);
				header("Content-Length: " . filesize($path));
				header('Content-Disposition: attachment; filename="' . addslashes(basename($path)) . '"');

				ob_end_flush();
				readfile($path);
			}
			else if(is_dir($path))
			{
				$zipfile 	= "/tmp/" . addslashes(basename($path)) . "_" . time() . ".zip";
				$zip 		= new PharData($zipfile, null, null, Phar::ZIP);

				$this->zipDir($path, $zip);

				if(isset($_SERVER['MOD_XSENDFILE_ENABLED']) && $_SERVER['MOD_XSENDFILE_ENABLED'])
		    	{
			    	header("X-SendFile: $zipfile", true);
			    	header("Content-Type: application/zip", true);
			    	header("Content-Disposition: attachment; filename=\"" . addslashes(basename($zipfile)) . "\"", true);
			    	exit;
			    }

				header("Content-Type: application/zip");
				header("Content-Length: " . filesize($zipfile));
				header('Content-Disposition: attachment; filename="' . addslashes(basename($zipfile)) . '"');

				ob_end_flush();
				readfile($zipfile);
			}
		}
		else
		{
			$this->fourOhFour();
			show_404();
		}
	}

	private function zipDir($path, &$zip)
	{
		$files = scandir($path);

		// Add all files in /templates/latex except other temp files.
		foreach($files as $file)
		{
			set_time_limit(30);

			if($file != "." && $file != ".." && $file != ".htaccess" && $file != "index.html" && $file != "thumbnails")
			{
				if(is_file($path . "/" . $file))
				{
					$zip->addFile($path . "/" . $file, $file);
				}
				else if(is_dir($path . "/" . $file))
				{
					$this->zipDir($path . "/" . $file, $zip);
				}
			}
		}
	}
}
