<?php
define('IN_CARD', true);
define('CURR_PAGE', 'text_on_image');

include('include/lib.inc.php');
// Load functions for image watermarking
include("include/class/watermark_text.class.php");

function im_wordwrap($txt,$font,$size,$width) { 
   $sep=array(' ','-'); // separators 
   $res=array(); 
   $buf=''; 
   // main function loop 
   for($i=0;$i<strlen($txt);$i++) { 
       $l=$txt[$i]; 
       if ($l=='^') { 
           $res[]=$buf; 
           $buf=''; 
           continue; 
       } 
       $t=$buf.$l; 
       $bbox=imagettfbbox($size,0,$font,$t); 
       $left=($bbox[0]>$bbox[6])?$bbox[6]:$bbox[0]; // determine most far points 
       $right=($bbox[2]>$bbox[4])?$bbox[2]:$bbox[4]; // idem 
       $w=$right-$left; // get total width 
       if ($w>$width) { 
           if ($buf=='') return false; // FATAL: 1 letter is smallest than the pixel width - avoid infinite loop 
           // we can assume that everything present in $buf currently is inside our limits 
           // find a separator in string 
           $fp=false; 
           foreach($sep as $s) { 
               $p=strrpos($buf,$s); 
               if (($p!==false) and ($p>$fp)) $fp=$p; 
           } 
           if ($fp===false) { 
               // let's break here ! 
               $res[]=$buf; 
               $buf=''; 
               $i--; // dececrase $i to retry this letter 
               continue; 
           } 
           // $fp+1 -> we put the separator char at the end of the prev. line =p 
           $res[]=substr($buf,0,$fp+1); 
           $buf=substr($buf,$fp+1); 
           $i--; 
           continue; 
       } 
       $buf.=$l; 
   } 
   if ($buf!='') $res[]=$buf; 
   return $res; 
}

function im_width($txt,$font,$size) { 
       $bbox=imagettfbbox($size,0,$font,$txt); 
       $left=($bbox[0]>$bbox[6])?$bbox[6]:$bbox[0]; // determine most far points 
       $right=($bbox[2]>$bbox[4])?$bbox[2]:$bbox[4]; // idem 
       $w=$right-$left; // get total width  
   return $w; 
}

function make_newpicname($size=5) {
	
//	$pool = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
	$pool = 'abcdefghijklmnopqrstuvwxyz';
	$pool .= '0123456789';
	mt_srand ((double) microtime() * 1000000);
	$unique_id = '';
	for ($i=0; $i<$size; $i++) {
		$unique_id .= substr($pool, (mt_rand()%(strlen($pool))), 1);
	}
	$unique_id = time().'-'.$unique_id;
	return $unique_id;
}

include(ROOT_DIR.'include/page_header.php');

$query = "SELECT * FROM ". TBL_ECARD_TEXT ." WHERE card_id=$id ";
$result = $DB_site->query($query);
$row = $DB_site->fetch_array($result);

#################################################################################
# Watermark Image using Text script usage example
# For updates visit http://www.zubrag.com/scripts/
#################################################################################
// Watermark all the "jpg" files from images folder
// and save watermarked images into destination folder
$filename = $cfg['path_images'] . $row['card_image'];

$width = $row['text_width'];

// Watermark text color, Hex format. Must start from #
$color = $row['font_color'];

// Font name. Case sensitive (i.e. Arial not equals arial)
$font = 'font/' . $row['font_face'];

// Font size
$font_size = $row['font_size'];

// Tex align
$align = $row['text_align'];

// Tex valign
$valign = $row['text_valign'];

// Vertical offset in pixels, from the bottom
$offset_y = $row['text_y'];

// Horizontal offset in pixels, from the right
$offset_x = $row['text_x'];

// Angle for text rotation. For example 0 - horizontal, 90 - vertical
$angle = $row['font_angle'];

// Shadow? true or false
$drop_shadow = true;

// Shadow color, Hex format. Must start from #
// This may help to make watermark text more distinguishable from image background
$shadow_color = $row['shadow_color'];

// 1 - save as file on the server, 2 - output to browser, 3 - do both
$mode = 1;

// Save watermarked images to this folder, must end with slash.
$destination_folder = $cfg['dir_temp_images'];

// Watermark text
$text = (isset($text)) ? safe_text($text) : safe_text($row['default_text']);
//$text = im_wordwrap($text,$font,$font_size,$width);
if (im_width($text, $font, $font_size) > $width) {
	$max_reduce = intval($font_size / 2);
	while ((im_width($text, $font, $font_size) > $width) and ($max_reduce > 0)) {
    	$font_size--;
		$max_reduce--;
		if($valign == "bottom") {
			$offset_y++;
		}
		else {
			$offset_y--;
		}
	}
	if (im_width($text, $font, $font_size) > $width) {
		message_die(GENERAL_ERROR,"Il testo è troppo lungo");
	}
}

// Horizontal offset in pixels, from the right
// $offset_x = $row['text_x'] - (im_width($text,$font,$font_size)) / 2;
#################################################################################
#     END OF SETTINGS
#################################################################################

// Where to save watermarked image
$file_type 	= get_file_extension(basename($filename));
$picdate = date('Y-m-d-H-i-s');
$picdate = make_newpicname();
if($file_type == 'gif') {
	$pic_name = $picdate . '.gif';
}
elseif($file_type == 'jpg' || $file_type=='jpeg') {
	$pic_name = $picdate . '.jpg';
}
else {
	$pic_name ='';
}
if($pic_name == "$picdate." || empty($pic_name)) {
	message_die(CRITICAL_ERROR,$msg['upload_error_file_ext']);
}
$pic_name = "maked_" . $pic_name;
$imgdestpath = $destination_folder . $pic_name;

// create class instance
$img = new Watermark_Text($filename);

// shadow params
$img->setShadow($drop_shadow, $shadow_color);

// font params
$img->setFont($font, $font_size);

// Determine image size
$size = getimagesize($filename);
$size_x = $size[0];
$size_y = $size[1];

// Apply watermark
if(preg_match("[\n]", $text)) {
	$text2 = explode("\n", $text);
	if($valign == "bottom") {
		$num = count($text2) - 1;
		$text3 = array();
		while($num >= 0) {
			$text3[] = $text2[$num];
			$num--;
		}
		$text2 = $text3;
	}
	$count = 0;
	foreach ($text2 as $text3) {
		if($count == 0) {
			$img->ApplyWatermark($text3, $color, $angle, $offset_x, $offset_y, $align, $valign);
		}
		else {
			$offset_y = $offset_y + $font_size*1.4;
			$img->ApplyWatermark($text3, $color, $angle, $offset_x, $offset_y, $align, $valign);
		}
		$count++; 
	}
}
else {
	$img->ApplyWatermark($text, $color, $angle, $offset_x, $offset_y, $align, $valign);
}

//	$img->ApplyCopyright();

// Save on server
$img->SaveAsFile($imgdestpath);

// Output to browser
//$img->Output();

// release resources
$img->Free();

$t->set_file(array('body' => 'page_text_on_image.html'));
text_on_image_cat();
card_cat();

$FORM_HIDDEN_FIELDS = $HTML_site->form_hidden(array(
	'id' => $id
));
$_img = empty($row['card_thm'])? $row['card_image'] : $row['card_thm'];
$resize = resize($cfg['path_images'] . $_img, $cfg['thm_size']);
$_img = preg_match("[.jpg]", $_img)? '<img src="' . $cfg['url_site'] . 'tnp.php?image=' . $cfg['path_images'] . $_img . '&tnsize=' . $cfg['thm_size'] . '" border="0">' : '<img src="' . $cfg['url_images'] . $_img . '" ' . $resize . ' border="0">';
$attribute = get_file_w_h($row['card_image']);
$t->set_var(array(
	'U_COMPOSE_CARD' => $cfg['url_site'].'text_on_image.php?id=' . $row['card_id'],
	'U_CARD_THUMB' => $cfg['url_images']. $row['card_thm'],
	'HTML_THUMBNAIL' => $_img,
	'CARD_ID' => $row['card_id'],
	'ICON_NEW' => gethml_newbutton($row['card_date']),
	'DEFAULT_TEXT' => safe_text(nl2br(cut_string($row['default_text'], 60))),
	'THM_SIZE' => $cfg['thm_size'],
	'FORM_HIDDEN_FIELDS' => $FORM_HIDDEN_FIELDS,
	'TEXT' => $text,
	'IMG' => 'immagini/temp/' . basename($imgdestpath),
	'MSG_CREATE_ECARD' => "<a href='create.php?f=temp/". $pic_name . "'>". $msg['upload_create_ecard'] ."<a>"
));

$t->set_block('body','prev_card','prev_cards');
$sql_prev = "SELECT * FROM ". TBL_ECARD_TEXT ." WHERE card_id < '$id' and cat_id='$row[cat_id]' ORDER BY card_id DESC LIMIT 1 ";
$result_prev = $DB_site->query($sql_prev);
while ($row_prev = $DB_site->fetch_array($result_prev)) {
	$_img = empty($row_prev['card_thm'])? $row_prev['card_image'] : $row_prev['card_thm'];
	$resize = resize($cfg['path_images'] . $_img, $cfg['thm_size']);
	$_img = preg_match("[.jpg]", $_img)? '<img src="' . $cfg['url_site'] . 'tnp.php?image=' . $cfg['path_images'] . $_img . '&tnsize=' . $cfg['thm_size'] . '" border="0">' : '<img src="' . $cfg['url_images'] . $_img . '" ' . $resize . ' border="0">';
	$attribute = get_file_w_h($row_prev['card_image']);
	$t->set_var(array(
		'PREV_U_COMPOSE_CARD' => $cfg['url_site'].'text_on_image.php?id=' . $row_prev['card_id'],
		'PREV_U_CARD_THUMB' => $cfg['url_images']. $row['card_thm'],
		'PREV_HTML_THUMBNAIL' => $_img,
		'PREV_CARD_ID' => $row_prev['card_id'],
		'PREV_ICON_NEW' => gethml_newbutton($row['card_date']),
		'PREV_DEFAULT_TEXT' => safe_text(nl2br(cut_string($row_prev['default_text'], 60))),
		'PREV_THM_SIZE' => $cfg['thm_size']
	));
	$t->parse('prev_cards', 'prev_card', true);
	$i++;
}

$t->set_block('body','next_card','next_cards');
$sql_next = "SELECT * FROM ". TBL_ECARD_TEXT ." WHERE card_id > '$id' and cat_id='$row[cat_id]' ORDER BY card_id ASC LIMIT 1 ";
$result_next = $DB_site->query($sql_next);
while ($row_next = $DB_site->fetch_array($result_next)) {
	$_img = empty($row_next['card_thm'])? $row_next['card_image'] : $row_next['card_thm'];
	$resize = resize($cfg['path_images'] . $_img, $cfg['thm_size']);
	$_img = preg_match("[.jpg]", $_img)? '<img src="' . $cfg['url_site'] . 'tnp.php?image=' . $cfg['path_images'] . $_img . '&tnsize=' . $cfg['thm_size'] . '" border="0">' : '<img src="' . $cfg['url_images'] . $_img . '" ' . $resize . ' border="0">';
	$attribute = get_file_w_h($row_next['card_image']);
	$t->set_var(array(
		'NEXT_U_COMPOSE_CARD' => $cfg['url_site'].'text_on_image.php?id=' . $row_next['card_id'],
		'NEXT_U_CARD_THUMB' => $cfg['url_images']. $row_next['card_thm'],
		'NEXT_HTML_THUMBNAIL' => $_img,
		'NEXT_CARD_ID' => $row_next['card_id'],
		'NEXT_ICON_NEW' => gethml_newbutton($row_next['card_date']),
		'NEXT_DEFAULT_TEXT' => safe_text(nl2br(cut_string($row_next['default_text'], 60))),
		'NEXT_THM_SIZE' => $cfg['thm_size']
	));
	$t->parse('next_cards', 'next_card', true);
	$i++;
}

$t->parse('body', 'body');
$t->p('body');
include(ROOT_DIR.'include/page_footer.php');
?>