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

class Documents extends MY_Controller
{
	public function index($url)
	{
		$this->load->model("document");
		$user 	= get_user();
		$doc 	= new Document();
		$doc->loadByURL($url);
		$path 	= DOCUMENT_PATH . "/" . $doc->filename;

		if($doc->document_id && $doc->published && file_exists($path))
		{
			if(!$this->acl->checkDocument($doc->document_id, Mainframe::user(), "read"))
			{
				if($site->login_page_id)
				{
					header("Location: $login_url");
					exit();
				}
				else
				{
					// Not authorized
					show_error("You are not authorized to view this document.", 403, "Access Denied");
				}
			}

			$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: inline; filename=\"" . addslashes(basename($path)) . "\"", true);
		    	exit;
		    }

			header("Content-Type: " . $mimetype);
			header("Content-Length: " . filesize($path));
			header('Content-Disposition: ' . ($doc->content_disposition ? $doc->content_disposition : 'inline') . '; filename="' . addslashes($doc->title) . '.' . $pathinfo['extension'] . '"');

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

	public function cover($id, $width=800, $height=600)
	{
		$this->load->model("document");
		$user 	= get_user();
		$doc 	= new Document();
		$doc->load($id);
		$path 	= DOCUMENT_PATH . "/" . $doc->filename;

		if($doc->document_id && file_exists($path))
		{
			if(!$this->acl->checkDocument($doc->document_id, Mainframe::user(), "read"))
			{
				if($site->login_page_id)
				{
					header("Location: $login_url");
					exit();
				}
				else
				{
					// Not authorized
					show_error("You are not authorized to view this document.", 403, "Access Denied");
				}
			}
		}
		else
		{
			show_404();
		}

		if(class_exists("Imagick") && preg_match('/\.pdf$/i', $doc->filename))
		{
			$temp = ABSOLUTE_PATH . "/images/documents/" . str_ireplace(".pdf", $width . "x" . $height . ".jpg", $doc->filename);

			if(file_exists($temp))
			{
				$thumb = Mainframe::thumbnail($temp, $width, $height, false, Mainframe::site()->webp ? IMAGETYPE_WEBP : null);
				header("Location: " . $thumb, 302);
				exit();
			}
			else
			{
				$im = new Imagick();
				$im->setResolution(72, 72);
				$im->readImage($path . '[0]');
				$im->setImageFormat('jpg');
				$im->setImageCompressionQuality(80);
				$im->scaleImage($width * 2, $height * 2, true);

				file_put_contents($temp, $im->getImageBlob());
				$thumb = Mainframe::thumbnail($temp, $width, $height, false, Mainframe::site()->webp ? IMAGETYPE_WEBP : null);

				header("Location: " . $thumb, 302);
				exit();
			}
		}
		else
		{
			// Output a blank image
			$im = imagecreatetruecolor(1, 1);
			imagealphablending($im, false);
			$col = imagecolorallocatealpha($im, 255, 255, 255, 127);
			imagefilledrectangle($im, 0, 0, 1, 1, $col);
			imagealphablending($im, true);
			imagesavealpha($im, true);
			header('Content-Type: image/png');
			imagepng($im, null, 9, PNG_NO_FILTER);
		}
	}
}
