<?php
/**
* This file generates a CAPTCHA string, writes it into the $_SESSION['captcha'] and renders a fresh CAPTCHA graphic file to the browser.
* MAY BE NEED TO REGENRATE SESSTION EACH 3 TIMES USER ENTERS WRONG PARAMS
*/
/* check if PHP GD extension is loaded */
if (!extension_loaded('gd')) {
	error_log("Install GD module for this PHP server");
	die("It looks like GD is not installed");
}
/* Start the session... */
session_start();
/* target captcha string length */
$iCaptchaLength = rand(4,6);
/* following letters are excluded from captcha: I, O, Q, S, 0, 1, 5 */
$str_choice = 'abcdefghjklmnprtuvwxyz2346789';
$str_captcha = '';
/* create target captcha with letters coming from $str_choice */
for($i=0; $i < $iCaptchaLength; $i++) {
	do{$ipos = rand(0, strlen($str_choice) - 1);
	/* checks that each letter is used only once */
	}while(stripos($str_captcha, $str_choice[$ipos]) !== false);
	$str_captcha .= $str_choice[$ipos];
}
/* write the generated captcha into a SESSION variable */
$_SESSION['captcha'] = $str_captcha;
/* begin to create the image with PHP's GD tools */
$im = imagecreatetruecolor(140, 40);
$bg = imagecolorallocate($im, 255, 255, 255);
$black = imagecolorallocate($im, 0, 0, 0);
imagefill($im, 0, 0, $bg);
/* background color fill red - for tests */
// imagefilledrectangle($im, 0, 0, 299, 99, 0xFF0000);
/* create background with 1000 short lines */
// for($i=0;$i<1000;$i++){
	// $lines = imagecolorallocate($im, rand(200, 220), rand(200, 220), rand(200, 220));
	// $start_x = rand(0,150);
	// $start_y = rand(0,70);
	// $end_x = $start_x + rand(0,5);
	// $end_y = $start_y + rand(0,5);
	// imageline($im, $start_x, $start_y, $end_x, $end_y, $lines);
// }
/*  TODO: put the font path into the configure */
for($i=0;$i < $iCaptchaLength;$i++){
	$text_color = imagecolorallocate($im, rand(0, 50), rand(0, 50), rand(0, 50));
	/* font-path relative to this file */
	/* ( resource $image , float $size , float $angle , int $x , int $y , int $color , string $fontfile , string $text [, array $extrainfo ] ) */
	imagefttext($im, 28, rand(-10, 10), 10 + ($i * 22) + rand(-3, +3), 20 + rand(5, 5), $text_color, 'fonts/AngelicWar.ttf', $str_captcha[$i]);
}
// imageline(the image, start X, start y, $end_x, $end_y, $lines)/
// imageLine($im, rand(8,12), rand(8,18), rand(90,110), rand(8,18), $black);
/* send http-header to prevent image caching (so we always see a fresh captcha image) */
header('Content-type: image/png');
header('Pragma: no-cache');
header('Cache-Control: no-store, no-cache, proxy-revalidate');
/* send image to browser and destroy image from PHP "cache" */
imagepng($im);
imagedestroy($im);