<?php if (!defined('PmWiki')) exit();
/* PDFThumb: Display thumbnails of PDFs
* @author Michael Eager <eager at eagercon dot com>
* @license http://www.gnu.org/licenses/gpl.html GNU General Public License
*
* Requires ImageMagick or Poppler.
* Incompatible with Hg
*
* PDF: link displays thumbnail of PDF with link.  If the file does not exist,
* displays a link to upload the file.  The file name is use as the caption.
*
* Configuration options (defaults shown):
*   $PDFThumb['size'] = 100;  // Largest dimension for thumbnail width/height
*   $PDFThumb['caption'] = TRUE; // Display caption
*   $PDFThumb['converter'] = "Poppler"; // Use PDFtoPPM for conversion
*       (If not set, or set to other value, use ImageMagick.)
*
* (:pdfthumb <option> ...:) sets page-specific options:
*   options may not have spaces
*	size=200	// Set thumbnail max width/height
*	caption		// Display captions
*	nocaption	// Do not display captions
*	regen		// Regenerate thumbnails
*
* Note:  Generating thumbnails may take a long time and exceed PHPs time limit.
*/
$RecipeInfo['PDFThumb']['Version'] = '2025-04-1f';

# Linking
SDV($LinkFunctions['PDF:'],'PDFThumb1');
SDV($IMap['PDF:'],'$1');

# Default values
SDVA($PDFThumb, array(
  'size' => 200,
  'caption' => TRUE,
  'regen' => FALSE,
  'converter' => 'Poppler',
));

Markup('pdfthumb', '<links', '/^\\(:pdfthumb\s*(.*?):\\)/i', "PDFThumbOpts");
function PDFThumbOpts($m) {
	global $PDFThumb;
	extract($GLOBALS['MarkupToHTML']);
	global $PDFT_override;
	$args = ParseArgs($m[1]);
	if (isset($args['size'])) SetProperty($pagename, "PDF-size", $args['size']);
	if (array_key_exists('', $args)) {
		if (array_search("caption", $args[''])) SetProperty($pagename, "PDF-caption", TRUE);
		if (array_search("nocaption", $args[''])) SetProperty($pagename, "PDF-caption", FALSE);
		if (array_search("regen", $args[''])) SetProperty($pagename, "PDF-regen", TRUE);
	}
}

function PDFThumb1($pagename,$imap,$path,$title,$txt,$fmt=NULL) {
	return genPDFThumb($pagename, $path, null);
}

Markup('pdf', '<links', "/(?>\\[\\[PDF:\\s*([^|\\]]*)\\|?\\s*([^\\]]*)\\]\\])/", "PDFThumb2");
function PDFThumb2($m) {
	extract($GLOBALS["MarkupToHTML"]);
	return genPDFThumb($pagename, $m[1], ($m[2] ? $m[2] : $m[1]));
}

function genPDFThumb($pagename, $path, $title) {
	global $EnableUpload, $UploadFileFmt, $UploadUrlFmt, $UploadDir, $UploadPrefixFmt, $PDFThumb;
	$out = '';
	$path = trim($path);
	$ext = strtolower(substr ($path, -4));
	$path = substr_replace($path, $ext, -4);
	preg_match('/\\.([^.]+)$/',$path,$match);
	$ext=@$match[1];
	if (!(($ext=='pdf')OR($ext=='PDF')))
		return "<i>$path</i>: ".XL('IMGbadtype');
	$pathThumb = str_replace(array('.pdf','.PDF'), array('.jpg','.jpg'),$path);
	$upname = MakeUploadName($pagename,$path); //eliminate non alphanum chars
	$upnameThumb = MakeUploadName($pagename,$pathThumb);

	$flpth = FmtPageName("$UploadFileFmt/$upname",$pagename);
	$flpthThumb = FmtPageName("$UploadFileFmt/$upnameThumb",$pagename);

	$pageurl = FmtPageName('$PageUrl', $pagename);
	$uploaddir = FmtPageName("$UploadDir$UploadPrefixFmt", $pagename);
	$uploadurl = FmtPageName(
		IsEnabled($EnableDirectDownload, 1) ?
			"$UploadUrlFmt$UploadPrefixFmt/" :
			"\$PageUrl?action=download&amp;upname=",
		$pagename );

	# If file doesn't exist, insert link to upload it
	if (!file_exists($flpth)) {
		$aopt = "href='$pageurl?upname=$upname&amp;action=upload'";
		$out = Keep("<a $aopt style='color:red'>Upload $upname</a>");
		return $out;
	}

	# If thumbnail doesn't exist or regen was requested, create it
	$regen = PageTextVar($pagename, 'PDF-regen');
	if ($regen || !file_exists($flpthThumb)) {
		$out = CreatePDFThumbnail($flpth, $flpthThumb);
		if ($out != "") { return $out; }
	}

	$url = PUE("$uploadurl$path");

	$thumb = Url_Attach ($pagename, $upnameThumb);
	$out .= "<div id='pdfimage'><a class='urllink' href='$url'><img src='$thumb' border='0' alt=''></a>";
	$docaption = PageTextVar($pagename, 'PDF-caption');
	$size = PageTextVar($pagename, 'PDF-size');
	if (!isset($caption)) $caption = $PDFThumb['caption'];
	if ($caption) {
		if (is_null($title)) $title = $path;
		$out .= "<div class='pdfcaption'>";
		$out .= "<a href='$url'><small>$title</small></a>";
		$out .= "</div>"; }
	$out .= "</div>\n";

	return Keep($out);
}

function CreatePDFThumbnail($PDF, $Thumb) {
	extract($GLOBALS['MarkupToHTML']);
	global $PCache, $PDFThumb;
	if (mime_content_type($PDF) != 'application/pdf')
		return "Invalid file type";

	if (file_exists($Thumb)) unlink($Thumb);

	$thumb_size = PageTextVar($pagename, 'PDF-size');
	if (empty($thumb_size)) $thumb_size = $PDFThumb['size'];

	if ($PDFThumb['converter'] == 'Poppler') {
		$cmd = "pdftoppm -l 1 -scale-to $thumb_size " .
		       "-jpeg '$PDF' > '$Thumb'";
		exec ($cmd);
	} else {
		$img = new Imagick();
		$img->setResolution(300, 300);     //set the resolution of the resulting jpeg
		$img->readImage($PDF."[0]");

		// Calculate thumbnail height/width using PDF page size ratio
		$height = $img->getImageHeight();
		$width = $img->getImageWidth();
		if ($height == 0) $height = 1;
		if ($width == 0) $width = 1;
		$thumb_sizeR = round($thumb_size*(min($width,$height)/max($width,$height)));
		if ($height == $width) $img->thumbnailimage($thumb_size,$thumb_size);
		else if ($height < $width) $img->thumbnailimage($thumb_size,$thumb_sizeR);
		else $img->thumbnailimage($thumb_sizeR,$thumb_size);

		$img->setImageBackgroundColor('white');
		$img = $img->flattenImages();
		$img->setimageformat('jpeg');

		$img->writeimage($Thumb);
		$img->clear();
		$img->destroy();
	}

	chmod($Thumb, 0666);	// Allow deleting jpeg

	if (file_exists($Thumb)) return "";
	return "Create PDF Failed";
}