<?php
/*
Plugin Name: wp-image-resize
Plugin URI: http://totalinnovation.it
Description: manage image resize direct on template file
Version: 1.0
Author: Total innovation
Author URI: http://totalinnovation.it
License: GPL2
*/

require_once(dirname(__FILE__)."/wideimage/WideImage.php");

define("WPIR_CACHE_PATH",dirname(dirname(dirname(__FILE__)))."/cache-images");
define("WPIR_IMAGE_PATH",get_bloginfo('url')."/wp-content/cache-images");

register_activation_hook( __FILE__, "wpir_register_activation_hook" );

function wpir_register_activation_hook() {
	global $wpdb;
	
	## prepare database
	$sql = "DROP TABLE wp_image_resize";
	$wpdb->query($sql);	
	$sql = "
		CREATE TABLE IF NOT EXISTS `wp_image_resize` (
			`id` int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
			`src` varchar(255) NOT NULL,
			`width` int(11) NOT NULL,
			`height` int(11) NOT NULL,
			`act` varchar(20) NOT NULL,
			`filename` varchar(255) NOT NULL
		) COMMENT=''
	";
	$wpdb->query($sql);	
	
	## prepare cache directory
		mkdir(WPIR_CACHE_PATH,0777);
}

function wpir_filename($src,$act,$w,$h) {
	$info = pathinfo($src);
	$ext = $info["extension"];
	return md5($src)."-".$act."-".$w."-".$h.'.'.$ext;
}

function wpir_create_cache_file($src,$act,$w,$h) {
	$file = wpir_filename($src,$act,$w,$h);
	$image = WideImage::load($src);

	if ($act == 'crop') {
		$image = $image->resize($w, $h, 'outside');		
		$image = $image->crop('center', 'center', $w, $h);		
	}		
	
	$cache = WPIR_CACHE_PATH."/".$file;	
	$image->saveToFile($cache);		
	return $file;
}

function wpir_load_file_from_db($src,$act,$w,$h) {
	global $wpdb;
	$sql = "SELECT filename FROM wp_image_resize WHERE act='{$act}' AND height='{$h}' AND width='{$w}' AND src='{$src}' LIMIT 1";
	$row = $wpdb->get_row($sql);
	if ($row) {
		return $row->filename;
	} else {
		return "";
	}
}

function wpir_save_file_on_db($src,$file,$act,$w,$h) {
	global $wpdb;
	$sql = "INSERT INTO wp_image_resize (act,height,width,src,filename) VALUES ('{$act}','{$h}','{$w}','{$src}','{$file}')";
	$row = $wpdb->query($sql);
}

require_once(dirname(__FILE__)."/template-functions.php");
