<?php
/**
* @version 1.0.0
* @package RStickets! 1.0.0
* @copyright (C) 2007-2008 www.rsjoomla.com
* @license GPL, http://www.gnu.org/copyleft/gpl.html
*/

defined('_JEXEC') or die('Restricted access');

class rst_captcha
{
	function rst_captcha_generate_font()
	{
		$font = '/plugins/fonts/monofont.ttf';
		return $font;
	}
	
	function rst_captcha_generate_code($chars=6)
	{
		$possible = 'bBcCdDfFgGhHjJkKmMnNpPqQrRsStTvVwWxXyYzZ23456789';
		$count = strlen($possible) - 1;
		$code = '';
		for ($i=0;$i<$chars;$i++)
			$code .= substr($possible, mt_rand(0, $count), 1);
		
		unset($_SESSION['RST_CAPTCHA_Code']);
		return $code;
	}
	
	function rst_captcha_generate_image($width,$height,$chars=6,$dots=1,$lines=1)
	{
		if(!function_exists('imagecreate'))
		{
			rst_disable_captcha();
			header('Location:'.RST_FRONTEND_REL_PATH.'/img/nogd.gif');
			exit();
		}
		
		if(!function_exists('imagettfbbox'))
		{
			rst_disable_captcha();
			header('Location:'.RST_FRONTEND_REL_PATH.'/img/nofreetype.gif');
			exit();
		}
		
		$code = $this->rst_captcha_generate_code($chars);
		$font = $this->rst_captcha_generate_font();
		
		$font_size = $height * 0.80;
		$image = @imagecreate($width, $height) or die('imagecreate() function error');
		
		$background_color = imagecolorallocate($image, 255, 255, 255);
		$text_color = imagecolorallocate($image, 0, 100, 20);
		$noise_color = imagecolorallocate($image, 0, 153, 38);
		
		if ($dots == 1)
			for ($i=0; $i<($width*$height)/3; $i++)
				imagefilledellipse($image, mt_rand(0,$width), mt_rand(0,$height), 1, 1, $noise_color);
		
		if ($lines == 1)
			for ($i=0; $i<($width*$height)/150; $i++)
				imageline($image, mt_rand(0,$width), mt_rand(0,$height), mt_rand(0,$width), mt_rand(0,$height), $noise_color);
		
		$textbox = imagettfbbox($font_size, 0, RST_FRONTEND_ABS_PATH.$font, $code) or die('imagettfbbox() function error');
		$x = ($width - $textbox[4])/2;
		$y = ($height - $textbox[5])/2;
		imagettftext($image, $font_size, 0, $x, $y, $text_color, RST_FRONTEND_ABS_PATH.$font, $code) or die('imagettftext() function error');
		
		header('Content-Type: image/jpeg');
		imagejpeg($image);
		imagedestroy($image);
		$_SESSION['RST_CAPTCHA_Code'] = $code;
	}
}
?>