<?php

require_once dirname(__FILE__) . '/../se-lib/bootstrap.php';

error_reporting(E_ALL & ~E_NOTICE);

//session_save_path("../session") ;
session_start();

date_default_timezone_set('Europe/Warsaw');// PHP 5 >= 5.1.0 required by date functions

if (file_exists(APP_PATH_ROOT . DS . 'config' . DS . '.config_'.$_SERVER['SERVER_NAME'].'.php')) {
	require APP_PATH_ROOT . DS . 'config' . DS . '.config_'.$_SERVER['SERVER_NAME'].'.php';
}

if (($function_init = V::get('function_init', '', $_GET))) {
	if (function_exists($function_init)) {
		$function_init();
	} else {
		header('HTTP/1.1 400: Bad Request');
		header('Warning: wrong ID L.' . __LINE__);
	}
} else {
	header('HTTP/1.1 400: Bad Request');
	header('Warning: wrong ID L.' . __LINE__);
}



function fun_SHOW_EXTERNAL_IMAGE() {
	$remote_table = V::get('tbl', '', $_REQUEST);
	$remote_id = V::get('id', '', $_REQUEST, 'int');
	$number = V::get('number', '', $_REQUEST, 'int');
	$imageResize = V::get('resize', '', $_REQUEST);
	$DBG = (V::get('DBG', 0, $_REQUEST, 'int') > 0);

	Lib::loadClass('DB_Image');

	if ($remote_id <= 0) {
		header('HTTP/1.1 400: Bad Request');
		header('Warning: wrong ID L.' . __LINE__);
		exit;
	}

	if (!DB_Image::tableIsAllowed($remote_table)) {
		header('HTTP/1.1 400: Bad Request');
		header('Warning: table not allowed L.' . __LINE__);
		exit;
	}

	$image_row = DB_Image::getImage($remote_table, $remote_id, $number);
	if (!$image_row) {
		header('HTTP/1.1 400: Bad Request');
		header('Warning: image not found in db L.' . __LINE__);
		exit;
	}

	$etag = md5($image_row->ID . $image_row->A_CREATE_DATE_TS);
	if (@strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) == $image_row->A_CREATE_DATE_TS
		|| trim($_SERVER['HTTP_IF_NONE_MATCH']) == $etag) {
		header("HTTP/1.1 304 Not Modified");
		exit;
	}
	$expire_date = mktime(0, 0, 0, date('m') + 3, date('d'), date('Y'));

	$maxWidth = 0;
	$maxHeight = 0;
	if ($imageResize) {
		list($maxWidth, $maxHeight) = explode('x', $imageResize, 2);
		$maxWidth = intval($maxWidth);
		$maxHeight = intval($maxHeight);
		if ($maxWidth <= 0 || $maxHeight <= 0) {
			header('HTTP/1.1 400: Bad Request');
			echo'ERROR wrong param resize (WxH)';
			exit;
		}
	}

	if (!$DBG) {
		header("Content-type: {$image_row->TYPE}");
		header("Cache-control: public");
		header("Pragma: public");// default 'no-cache'
		header("Etag: {$etag}");
		if (!$imageResize) {
			header("Content-length: {$image_row->SIZE}");
		}
		header("Expires: " . gmdate("D, d M Y H:i:s", $expire_date) . " GMT");
		header("Last-Modified: " . gmdate("D, d M Y H:i:s", $image_row->A_CREATE_DATE_TS) . " GMT");
	}
	if ($imageResize) {
		print DB_Image::resizeImageFromBlob($image_row->IMAGE, $image_row->TYPE, $maxWidth, $maxHeight);
	} else {
		print $image_row->IMAGE;
	}
	exit;
}
