<?php
/**
 * svgImage Plugin
 * 
 * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
 * @author     i-net software <tools@inetsoftware.de>
 * @author     Gerry Weissbach <gweissbach@inetsoftware.de>
 */

// must be run within Dokuwiki
if(!defined('DOKU_INC')) die();

if(!defined('DOKU_PLUGIN')) define('DOKU_PLUGIN',DOKU_INC.'lib/plugins/');
require_once(DOKU_PLUGIN.'action.php');

class action_plugin_svgimg extends DokuWiki_Action_Plugin {

	var $functions = null;

    function getInfo(){
			return confToHash(dirname(__FILE__).'/info.txt');
    }

	function register(&$controller) {

		$controller->register_hook('MEDIA_SENDFILE', 'BEFORE', $this, 'svgimg__convert');
	}

	function svgimg__convert(&$event, $args) {

		/* Filename for reflect Image */
		$data = $event->data;
		$ext = $data['ext'];
		if ( strtolower($ext) != 'svg' ) { return false; }
		if (!$functions=& plugin_load('helper', 'svgimg')) return false;

		// get Output Format
		$ext = empty( $_REQUEST['return_type'] ) ? $this->getConf('return_type') : (in_array( hsc($_REQUEST['return_type']), array('png', 'jpg', 'jpeg') ) ? hsc($_REQUEST['return_type']) : $this->getConf('return_type'));
		$data['mime'] = "image/$ext";
		
		// get width and height
		if ( $data['width'] == 0 ) { $data['width'] = null; }
		if ( $data['height'] == 0 ) { $data['height'] = null; }

		// get Background-Color
		$data['background'] = $functions->_calc_bgcolor($_REQUEST['bgc']);

		// check the CacheFile
		$cacheFile = $functions->_get_cache_file($data, $ext);
		$mtime = @filemtime($cacheFile); // 0 if not exists
		if( ($mtime == 0) ||                           // cache does not exist
			($data['cache'] != -1 && $mtime < time()-$data['cache']) ) {   // 'recache' and cache has expired
			// Create Image
			if ( $functions->create_svg_image( $data, $ext, $cacheFile) ) {

				// If all done, ok.
				// If all done, ok.
			} else {
				$event->preventDefault();
				msg('Could not transfrom svg to output format.', -1);
			}
		}

		$data['file'] = $cacheFile;
		$event->data = $data;
	}


}