<?php if (!defined('PmWiki')) exit();

/*	=== Attache-ImageSizer ===
 *	Copyright 2010 Eemeli Aro <eemeli@gmail.com>
 *
 *	Automatically resize uploaded images using ImageMagick
 *
 *	Developed and tested using the PmWiki 2.2.x series.
 *
 *	To install, add the following line to your configuration file :
		include_once("$FarmD/cookbook/attache-imagesizer.php");
 *
 *	For more information, please see the online documentation at
 *		http://www.pmwiki.org/wiki/Cookbook/Attache-ImageSizer
 *
 *	This program is free software; you can redistribute it and/or
 *	modify it under the terms of the GNU General Public License,
 *	Version 2, as published by the Free Software Foundation.
 *	http://www.gnu.org/copyleft/gpl.html
 */

$RecipeInfo['Attache-ImageSizer']['Version'] = '2010-05-04';

SDV($HandleActions['download'], 'HandleDownload');
SDV($ImgSizer['HandleDownloadFunction'], $HandleActions['download']);
$HandleActions['download'] = 'HandleImageDownload';

## If FALSE, no image found. Modifies $filepath and $opt.
function ImageSizerParseName(&$filepath, &$opt) {
	global $ImgSizer;
	SDV($ImgSizer['separator'], '--');
	$pat = '/^(.*?)'.preg_quote($ImgSizer['separator']).'([a-z])(\w*)(\.[^.]+)$/';
	while (!file_exists($filepath)) {
		if (preg_match($pat, $filepath, $m)) {
			if (preg_match('/^[0-9_]/', $m[3])) {
				$opt[$m[2]] = ($m[3][0] == '_') ? substr($m[3], 1) : str_replace('_', '.', $m[3]);
			} else {
				$opt['fmt'] = $m[2].$m[3];
			}
			$filepath = $m[1].$m[4];
		} else return FALSE;
	}
	return TRUE;
}

function HandleImageDownload($pagename, $auth='read') {
	global $WorkDir, $ImgExtPattern, $UploadFileFmt, $UploadExts, $DownloadDisposition, $ImgSizer;

	## use default HandleDownload for non-images
	$upname = MakeUploadName($pagename, @$_REQUEST['upname']);
	$is_img = preg_match("/^(.*?)($ImgExtPattern)$/", $upname, $imgname);
	if (!$is_img) {
		$ImgSizer['HandleDownloadFunction']($pagename, $auth);
		exit();
	}

	UploadAuth($pagename, $auth);

	SDVA($ImgSizer, array(
		'default-opt' => array('fmt' => 'default', 'w' => '500', 'h' => '500'),
		'convert-cmd' => 'convert',
		'convert-fmt' => array('default' => "-resize '%wx%h>'", 'thumb' => "-resize '50x50>'", 'orig' => ''),
		'cache-dir' => $WorkDir
	));

	## read formatting options from defaults & file name
	$ImgSizer['opt'] = $ImgSizer['default-opt'];
	$filepath = FmtPageName("$UploadFileFmt/$upname", $pagename);
	if (!ImageSizerParseName($filepath, $ImgSizer['opt']) || !isset($ImgSizer['convert-fmt'][$ImgSizer['opt']['fmt']])) {
		header("HTTP/1.0 404 Not Found");
		Abort("?requested file not found");
	}

	$fmt = trim($ImgSizer['convert-fmt'][$ImgSizer['opt']['fmt']]);
	if (empty($fmt)) {
		$cachefilepath = $filepath;
	} else {
		$copt = preg_replace('/%([a-z])/e', "\$ImgSizer['opt']['$1']", $fmt);
		$convert = "{$ImgSizer['convert-cmd']} '$filepath' $copt";
		$cachefilepath = "{$ImgSizer['cache-dir']}/img_" . md5($convert) . ',cache';
		if (!file_exists($cachefilepath) || (filemtime($cachefilepath) < filemtime($filepath))) {
			mkdirp($ImgSizer['cache-dir']);
			$status = shell_exec("$convert '$cachefilepath' 2>&1");
			if ($status) {
				header("HTTP/1.0 500 Internal Server Error");
				Abort("?image conversion error: $status");
			}
			fixperms($cachefilepath, 0444);
		}
	}

	## file read & delivery based on HandleDownload
	SDV($DownloadDisposition, 'inline');
	$ext = substr($imgname[2], 1);
	if (!empty($UploadExts[$ext])) header("Content-Type: {$UploadExts[$ext]}");
	header('Content-Length: ' . filesize($cachefilepath));
	header("Content-disposition: $DownloadDisposition; filename=\"$upname\"");
	$fp = fopen($cachefilepath, 'rb');
	if ($fp) {
		while (!feof($fp)) echo fread($fp, 4096);
		fclose($fp);
	}
	exit();
}


SDV($LinkFunctions['Attach:'], 'LinkUpload');
SDV($ImgSizer['LinkUploadFunction'], $LinkFunctions['Attach:']);
$LinkFunctions['Attach:'] = 'LinkUploadImage';

## based on LinkUpload
function LinkUploadImage($pagename, $imap, $path, $alt, $txt, $fmt=NULL) {
  global $FmtV, $UploadFileFmt, $LinkUploadCreateFmt, $UploadUrlFmt,
    $UploadPrefixFmt, $EnableDirectDownload, $ImgExtPattern, $ImgSizer;
  if (preg_match('!^(.*)/([^/]+)$!', $path, $match)) {
    $pagename = MakePageName($pagename, $match[1]);
    $path = $match[2];
  }
  $upname = MakeUploadName($pagename, $path);
  $is_img = preg_match("/^(.*?)($ImgExtPattern)$/", $upname);
  if (!$is_img)
    return $ImgSizer['LinkUploadFunction']($pagename, $imap, $path, $alt, $txt, $fmt);
  $filepath = FmtPageName("$UploadFileFmt/$upname", $pagename);
  $FmtV['$LinkUpload'] =
    FmtPageName("\$PageUrl?action=upload&amp;upname=$upname", $pagename);
  $FmtV['$LinkText'] = $txt;
  if (!ImageSizerParseName($filepath, $opt))
    return FmtPageName($LinkUploadCreateFmt, $pagename);
  $path = PUE(FmtPageName(IsEnabled($EnableDirectDownload, 1)
                            ? "$UploadUrlFmt$UploadPrefixFmt/$upname"
                            : "{\$PageUrl}?action=download&amp;upname=$upname",
                          $pagename));
  return LinkIMap($pagename, $imap, $path, $alt, $txt, $fmt);
}