<?php

/**
 * display thumbnail
 * input:
 *    $_GET['file_id']
 *    $_GET['thumbnail'] 1: thumbnail image
 *
 */
require_once 'include/common.inc.php';
require_once XOOPS_TRUST_PATH . '/libs/xoonips/class/core/BeanFactory.class.php';
require_once XOOPS_TRUST_PATH . '/libs/xoonips/class/core/Request.class.php';
require_once XOOPS_TRUST_PATH . '/libs/xoonips/class/core/File.class.php';
require_once XOOPS_TRUST_PATH . '/libs/xoonips/class/core/Utils.class.php';

function imageError($code, $msg = '') {
	switch ($code) {
		case 403:
			header('HTTP/1.0 403 Forbidden');
			echo 'HTTP/1.0 403 Forbidden';
			break;
		case 404:
			header('HTTP/1.0 404 Not Found');
			echo 'HTTP/1.0 404 Not Found';
			break;
		case 500:
			header('HTTP/1.0 500 Internal Server Error');
			echo $msg;
			break;
	}
	exit();
}

// get form data
$request = new Xoonips_Request();
$fileID = $request->getParameter('file_id');
if (empty($fileID)) {
	imageError(404);
}

// get config
$dirname = Xoonips_Utils::getDirname();
$trustDirname = Xoonips_Utils::getTrustDirname();
$configBean = Xoonips_BeanFactory::getBean('ConfigBean', $dirname, $trustDirname);
$upload_dir = $configBean->getConfig('upload_dir');
$magic_file_path = $configBean->getConfig('magic_file_path');

// get file info
$fileBean = Xoonips_BeanFactory::getBean('ItemFileBean', $dirname, $trustDirname);
$fileInfo = $fileBean->getFile($fileID);

if (!$fileInfo) {
	imageError(404);
}

$file_name = $fileInfo['original_file_name'];
$mime_type = $fileInfo['mime_type'];
$file_size = $fileInfo['file_size'];

if (isset($fileInfo['item_id']) && empty($fileInfo['item_id'])) {
	$file_path = $upload_dir . '/' . $fileID;
} else {
	$file_path = $upload_dir . '/item/' . $fileInfo['item_id'] . '/' . $fileID;
}

if (!is_readable($file_path)) {
	imageError(404);
}

// buffer clear
Xoonips_Utils::allBufferClear();

// If character's code changes automatic, it becomes invalid.
if (function_exists('mb_http_output')) {
	mb_http_output('pass');
}

// output image
$thumbnail = $request->getParameter('thumbnail');
if (!empty($thumbnail)) {
	$thumabnailFile = $file_path . '_thumbnail';
	if (file_exists($thumabnailFile)) {
		if (!is_readable($thumabnailFile )) {
			imageError(404);
		}
		$imicon = imagecreatefrompng($thumabnailFile);
		header('Content-Type: image/png');
		imagepng($imicon);
		imagedestroy($imicon);
		exit();
	} else {
		// thumbnail doesn't available.
		$finfo = finfo_open(FILEINFO_NONE, $magic_file_path);
		$mime_type = finfo_file($finfo, $file_path);
		finfo_close($finfo);
		$image_type = 'unknown';
		if (preg_match('/^([^\\/]*)\\/(.*)$/', $mime_type, $matches)) {
			if ($matches[1] == 'audio' || $matches[1] == 'image'
					|| $matches[1] == 'video' || $matches[1] == 'text') {
				$image_type = $matches[1];
			} elseif ($matches[1] == 'application') {
				$types = array(
					'text' => array(
	                	'pdf',
                		'xml',
                		'msword',
                		'vnd.ms-excel'
					),
					'image' => array(
	                	'vnd.ms-powerpoint',
    	            	'postscript'
					),
					'audio' => array(
	                	'vnd.rn-realmedia'
	                )
				);
				if (in_array($matches[2], $types['text'])) {
					$image_type = 'text';
				} elseif (in_array($matches[2], $types['image'])) {
					$image_type = 'image';
				} elseif (in_array($matches[2], $types['audio'])) {
					$image_type = 'audio';
				} else {
					$image_type = 'application';
				}
			}
		}
		$image_file = XOOPS_ROOT_PATH . '/modules/' . $dirname . '/images/thumbnail_' . $image_type. ' . png';
		// create image resource
		$width = 100;
		$height = 100;
		$im = imagecreatetruecolor($width, $height);
		// label setting
		$f = 2;
		// font number
		$lp = 5;
		// label padding
		$fw = imagefontwidth($f);
		// font width
		$fh = imagefontheight($f);
		// font height
		$fmaxlen = ($width - $lp * 2) / $fw;
		// max label length
		$labels = explode(',', $label);
		$label = $labels[0];
		$llen = strlen($label);
		if ($llen > $fmaxlen) {
			$label = substr($label, 0, $fmaxlen - 3);
			$label .= '...';
			$llen = strlen($label);
		}
		$lx = ($widht - $llen * $fw) / 2;
		$ly = $height - $fh - $lp;
		// change alpha attributes and create transparent color
		imageantialias($im, true);
		imagealphablending($im, false);
		imagesavealpha($im, true);
		$transparent = imagecolorallocatealpha($im, 255, 255, 255, 0);
		$col_white = imagecolorallocate($im, 255, 255, 255);
		$col_gray = imagecolorallocate($im, 127, 127, 127);
		$col_black = imagecolorallocate($im, 0, 0, 0);
		// fill all area with transparent color
		imagefill($im, 0, 0, $col_white);
		imagealphablending($im, true);
		$imicon = imagecreatefrompng($image_file);
		imagecopy($im, $imicon, $widht / 2 - 48 / 2, $height / 2 - 48 / 2, 0, 0, 48, 48);
		imagepolygon($im, array(0, 0, $width - 1, 0, $width - 1, $height - 1, 0, $height - 1), 4, $col_gray);
		if (strlen($label) != 0) {
			imagestring($im, $f, $lx, $ly, $label, $col_black);
		}
		header('Content-Type: image/png');
		imagepng($im);
		imagedestroy($imicon);
		imagedestroy($im);
		exit();
	}
} else {
	$strip_mime_types = explode(';', $mime_type);
	$strip_mime_type = trim($strip_mime_types[0]);
	$show_mime_types = array(
	    'image/jpeg',
	    'image/png',
	   	'image/gif',
	   	'text/plain'
	);
	if (in_array($strip_mime_type, $show_mime_types)) {
		// acceptable to show directly in the browser
		header("Content-Type: $mime_type");
		header("Content-Length: $file_size");
		readfile($file_path);
		exit();
	} else {
		$xoonipsFile = new Xoonips_File($dirname, $trustDirname);
		$xoonipsFile->downloadFile($file_path, $file_name, $mime_type);
		exit();
	}
}

