<?php
class watermark {
	var $image;
	var $type;
	var $width;
	var $height;
	var $marked_image;
	var $sizes;
	var $position = "2";
	var $img_x;
	var $img_y;
	var $ornt;
	var $imageCreated = false;
	var $fixedColor = '';

	function watermark($res) {
		list($this->type, $this->image) = $this->_getImage($res);

		if (!$this->image) {
			$this->_die_error("PHP does`nt support ". $this->type ." images");
		}

		$this->width = imagesx($this->image);
		$this->height = imagesy($this->image);
		$gdinfo = gd_info();
		if (preg_match('/(\d)\.\d/', $gdinfo["GD Version"], $gdinfo))
		$this->gd_version = $gdinfo[1];
		else
		$this->gd_version = 0;
		unset($gdinfo);
	}


	function setType($type) {
		$this->type = $type;
	}

	function addWatermark($mark, $type = "TEXT") {

		if ($type == "TEXT") {
			if(C_WATERMARK_TEXT_OR) $this->ornt = (C_WATERMARK_TEXT_OR == '1') ? "H" : "V";
			else $this->ornt = ($this->width > $this->height) ? "H" : "V";
			$this->sizes = $this->_getTextSizes($mark);

			$this->_getOffsets();

			$chunk = $this->_getChunk();
			if (!$chunk) $this->_die_error("Could not extract chunk from image");

			$img_mark = $this->_createEmptyWatermark();
			$img_mark = $this->_addTextWatermark($mark, $img_mark, $chunk);

			imagedestroy($chunk);

			$this->_createMarkedImage($img_mark, $type, C_WATERMARK_TEXT_TRANSPARENCY);
		} elseif ($type == "IMAGE") {
			list($dummy, $mark) = $this->_getImage($mark);
			$this->sizes = $this->_getImageSizes($mark);

			$this->_getOffsets();

			$img_mark = $this->_createEmptyWatermark();
			$img_mark = $this->_addImageWatermark($mark, $img_mark);

			$this->_createMarkedImage($img_mark, $type, C_WATERMARK_TEXT_TRANSPARENCY);
		}
	}

	function getMarkedImage() {
		if ($this->imageCreated == false) {
			$this->addWatermark($this->version);
		}
		return $this->marked_image;
	}

	function setPosition($newposition) {
		$valid_positions = array('0','1','2','3','4','5','6','7','8','9');

		#$newposition = strtoupper($newposition);

		if (in_array($newposition, $valid_positions)) {
			if ($newposition == "9") {
				$newposition = $valid_positions[rand(0, sizeof($valid_positions) - 2)];
			}
			$this->position = $newposition;
			return true;
		}
		return false;
	}

	function setFixedColor($color) {
		$text_color = array();
		if (preg_match('/^#?([a-f0-9]{2})([a-f0-9]{2})([a-f0-9]{2})$/i', $color, $matches)) {
			$text_color["r"] = hexdec($matches[1]);
			$text_color["g"] = hexdec($matches[2]);
			$text_color["b"] = hexdec($matches[3]);
		} else {
			return false;
		}
		$this->fixedColor = $text_color;
		return true;
	}

	function _die_error($errmsg) {
		die($errmsg);
	}

	function _getTextSizes($text) {
		$act_scale = 0;
		$act_font = 0;

		$marklength = strlen($text);
		$scale = ($this->ornt == "H") ? $this->width : $this->height;
		$char_widthmax = intval(($scale / $marklength) - 0.5);

		for ($size = 5; $size >= 1; $size--) {
			$box_w = imagefontwidth($size);
			$box_h = imagefontheight($size);
			$box_spacer_w = 0;
			$box_spacer_h = 0;

			if ($this->ornt == "H") {
				$box_h *= 2;
				$box_w *= 1.75;
				$box_w *= $marklength;
				$box_w += intval($this->width * 0.05);
				$box_spacer_w = intval($this->width * 0.01);
				$box_spacer_h = intval($this->height * 0.01);
			} else {
				$box_w *= 3;
				$box_h *= 1.1;
				$box_h *= $marklength;
				$box_spacer_h = intval($this->height * 0.01);
				$box_spacer_w = intval($this->width * 0.01);
			}

			$box_scale = ($this->ornt == "H") ? $box_w + $box_spacer_w : $box_h + $box_spacer_h;

			if ($box_scale < $scale && $box_scale > $act_scale) { $act_font = $size; $act_scale = $box_scale; }
		}

		return array(	"fontsize"	=> $act_font,
		"box_w"		=> $box_w,
		"box_h"		=> $box_h,
		"spacer_w"	=> $box_spacer_w,
		"spacer_h"	=> $box_spacer_h
		);
	}

	function _getImageSizes($res) {

		if (@imagesx($res) > $this->width || @imagesy($res) > $this->height) {
			$box_h = $box_w = 0;
			$box_spacer_h = $box_spacer_w = 0;
			if (imagesx($res) > imagesy($res)) {
				$box_w = $this->width;
				$box_h = intval((imagesy($res) / (imagesx($res) / $this->width)) + 0.5);
				$box_spacer_h = intval(($this->height - $box_h) / 2);
			} else {
				$box_h = $this->height;
				$box_w = intval((imagesx($res) / (imagesy($res) / $this->height)) + 0.5);
				$box_spacer_w = intval(($this->width - $box_w) / 2);
			}
		} else {
			$box_spacer_h = $box_spacer_w = 0;
			$box_h = imagesy($res);
			$box_w = imagesx($res);
		}
		return array(
		"box_w"		=> $box_w,
		"box_h"		=> $box_h,
		"spacer_w"	=> $box_spacer_w,
		"spacer_h"	=> $box_spacer_h
		);
	}

	function _getChunk() {
		$chunk = imagecreatetruecolor($this->sizes["box_w"], $this->sizes["box_h"]);
		imagecopy(	$chunk,
		$this->image,
		0,
		0,
		$this->img_x,
		$this->img_y,
		$this->sizes["box_w"],
		$this->sizes["box_h"]
		);
		return $chunk;
	}

	function _createEmptyWatermark() {
		return imagecreatetruecolor($this->sizes["box_w"], $this->sizes["box_h"]);
	}

	function _addTextWatermark($mark, $img_mark, $chunk) {
		imagetruecolortopalette($chunk, true, 65535);
		$text_color = array("r" => 0, "g" => 0, "b" => 0);

		if (is_array($this->fixedColor)) {
			$text_color = $this->fixedColor;
		} else {
			for($x = 0; $x <= $this->sizes["box_w"]; $x++) {
				for ($y = 0; $y <= $this->sizes["box_h"]; $y++) {
					$colors = imagecolorsforindex($chunk, imagecolorat($chunk, $x, $y));
					$text_color["r"] += $colors["red"];
					$text_color["r"] /= 2;
					$text_color["g"] += $colors["green"];
					$text_color["g"] /= 2;
					$text_color["b"] += $colors["blue"];
					$text_color["b"] /= 2;
				}
			}
			$text_color["r"] = $text_color["r"] < 128 ? $text_color["r"] + 128 : $text_color["r"] - 128;
			$text_color["g"] = $text_color["g"] < 128 ? $text_color["g"] + 128 : $text_color["g"] - 128;
			$text_color["r"] = $text_color["r"] < 128 ? $text_color["r"] + 128 : $text_color["r"] - 128;
		}
		$mark_bg = imagecolorallocate(	$img_mark,
		($text_color["r"] > 128 ? 10 : 240),
		($text_color["g"] > 128 ? 10 : 240),
		($text_color["b"] > 128 ? 10 : 240));

		$mark_col = imagecolorallocate($img_mark, $text_color["r"], $text_color["g"], $text_color["b"]);

		imagefill($img_mark, 0, 0, $mark_bg);
		imagecolortransparent($img_mark, $mark_bg);

		if ($this->ornt == "H") {
			#ImageTTFText ($img_mark,22,20,100, 100,$mark_col,'tahoma','qweqwe') or die('error');
			imagestring($img_mark, 3, 1, 0, $mark, $mark_col);
			#imagechar($img_mark, 5, 1, 0, $mark, $mark_col);
		} else {
			imagestringup($img_mark, $this->sizes["fontsize"], 0, $this->sizes["box_h"] - 5, $mark, $mark_col);
		}

		return $img_mark;
	}

	function _addImageWatermark($mark, $img_mark) {
		$transparent_color_idx = imagecolortransparent($mark);
		if ($transparent_color_idx >= 0) $transparent_color = imagecolorsforindex($mark, imagecolortransparent($mark));
		imagecopy($img_mark, $mark, 0, 0, 0, 0, imagesx($mark), imagesy($mark));
		if ($transparent_color_idx >= 0) {
			$trans;
			if (function_exists("imagecolorallocatealpha")) {
				$trans = imagecolorallocatealpha($img_mark,$transparent_color["red"],$transparent_color["green"],$transparent_color["blue"],127);
			} else {
				$trans = imagecolorallocate($img_mark,$transparent_color["red"],$transparent_color["green"],$transparent_color["blue"]);
			}
			imagecolortransparent($img_mark, $trans);
		}

		return $img_mark;
	}

	function _createMarkedImage($img_mark, $type, $pct) {
		$this->marked_image = imagecreatetruecolor($this->width, $this->height);
		imagecopy($this->marked_image, $this->image, 0, 0, 0, 0, $this->width, $this->height);
		if ($type == 'TEXT') {
			imagecopymerge(
			$this->marked_image,
			$img_mark,
			$this->img_x,
			$this->img_y,
			0,
			0,
			$this->sizes["box_w"],
			$this->sizes["box_h"],
			$pct
			);
			$this->imageCreated = true;
		} elseif ($type == 'IMAGE') {
			if ($this->gd_version >= 2) { // GD2: Should be the easy way
			imagealphablending($this->marked_image, true);

			imagecopy(
			$this->marked_image,
			$img_mark,
			$this->img_x,
			$this->img_y,
			0,
			0,
			$this->sizes["box_w"],
			$this->sizes["box_h"]
			);
			} else {
				imagecopymerge(
				$this->marked_image,
				$img_mark,
				$this->img_x,
				$this->img_y,
				0,
				0,
				$this->sizes["box_w"],
				$this->sizes["box_h"],
				$pct
				);
			}

			$this->imageCreated = true;
		}
	}

	function _getOffsets() {

		$width_mark = $this->sizes["box_w"] + $this->sizes["spacer_w"];
		$height_mark = $this->sizes["box_h"] + $this->sizes["spacer_h"];
		$width_left = $this->width - $width_mark;
		$height_left = $this->height - $height_mark;

		switch ($this->position) {
			case '0':
			$this->img_x = $width_left >= 5 ? 5 : $width_left;
			$this->img_y = $height_left >= 5 ? 5 : $height_left;
			break;
			case '1':
			$this->img_x = intval(($this->width - $width_mark) / 2);
			$this->img_y = $height_left >= 5 ? 5 : $height_left;
			break;
			default:
			case '2':
			$this->img_x = $this->width - $width_mark;
			$this->img_y = $height_left >= 5 ? 5 : $height_left;
			break;
			case '3':
			$this->img_x = $width_left >= 5 ? 5 : $width_left;
			$this->img_y = intval(($this->height - $height_mark) / 2);
			break;
			case '4':
			$this->img_x = intval(($this->width - $width_mark) / 2);
			$this->img_y = intval(($this->height - $height_mark) / 2);
			break;
			case '5':
			$this->img_x = $this->width - $width_mark;
			$this->img_y = intval(($this->height - $height_mark) / 2);
			break;
			case '6':
			$this->img_x = $width_left >= 5 ? 5 : $width_left;
			$this->img_y = $this->height - $height_mark;
			break;
			case '7':
			$this->img_x = intval(($this->width - $width_mark) / 2);
			$this->img_y = $this->height - $height_mark;
			break;
			case '8':
			$this->img_x = $this->width - $width_mark;
			$this->img_y = $this->height - $height_mark;
			break;
		}
	}

	function _getImage($res) {
		$img;
		$type;

		if (intval(@imagesx($res)) > 0) {
			$img = $res;
		} else {
			$imginfo = getimagesize($res);

			switch($imginfo[2]) { // Determine type
			case 1:
			$type = "GIF";
			if (function_exists("imagecreatefromgif")) {
				$img = imagecreatefromgif($res);
			} else {
				die("Unsupported image type: $type");
			}
			break;
			case 2:
			$type = "JPG";
			if (function_exists("imagecreatefromjpeg")) {
				$img = imagecreatefromjpeg($res);
			} else {
				die("Unsupported image type: $type");
			}
			break;
			case 3:
			$type = "PNG";
			if (function_exists("imagecreatefrompng")) {
				$img = imagecreatefrompng($res);
			} else {
				die("Unsupported image type: $type");
			}
			break;
			}
		}

		return array($type, $img);
	}

}
?>
