<?php

/*
*	Copyright VeryIDE,2007-2010
*	http://www.veryide.com/
*	
*	验证码模块
*	$Id: captcha.php,v2 21:01 2010/3/4 Leilei $
*/

//载入依赖库以及配置
require("../include/global.php");

	error_reporting(0);
	set_magic_quotes_runtime(0);
	
	//关闭缓冲
	ob_end_clean();

	//p3p
	//header('P3P: CP="CAO PSA OUR"');
	//header('P3P: CP="CURa ADMa DEVa PSAo PSDo OUR BUS UNI PUR INT DEM STA PRE COM NAV OTC NOI DSP COR"');

	//@session_start();
	//session_register('VCODE');
	header("Content-type: image/png");
	
	//exit($Global["domain"]);

//////////////////////////////////

	//图片参数
	$width			= GetNumber("width",90);			//图片宽
	$height			= GetNumber("height",30);			//图片高
	$len			= GetNumber("len",4);				//生成几位验证码
	
	$bgcolor		= "#ffffff";						//背景色
	
	$noise			= true;								//生成杂点
	$noisenum		= GetNumber("noisenum",80);			//杂点数量
	
	$border			= false;							//边框
	$bordercolor	= "#000000";						//边框颜色
	
	//创建图片
	$image = imageCreate($width, $height);
	
	$back = getcolor($bgcolor);
	
	imageFilledRectangle($image, 0, 0, $width, $height, $back);
	
	$size = $width/$len;
	
	if($size>$height) $size = $height;
	
	$left = ($width-$len*($size+$size/10))/$size;

	//字体位置
	$self = realpath('.')."/../source/fonts/";
	if( !ini_get("safe_mode") ){
		putenv('GDFONTPATH=' . realpath('./../source/fonts/'));
	}

	//生成字符
	for ($i=0; $i<$len; $i++){
		$randtext = rand(0, 9);
		$code .= $randtext;
		$textColor = imageColorAllocate($image, rand(0, 100), rand(0, 100), rand(0, 100));
		$font = rand(1,4).".ttf"; 
		$randsize = rand($size-$size/10, $size+$size/10);
		$location = $left+($i*$size+$size/10);

		imagettftext($image, $randsize, rand(-18,18), $location, rand($size-$size/10, $size+$size/10), $textColor, $self.$font, $randtext); 
	}

	//生成杂点
	if($noise == true) setnoise();
	
	setcookie('VCODE',$code,time()+60*60*24*30,'/',($Global["domain"]?'.'.$Global["domain"]:''));
	//setcookie('VCODE',$code,time()+60*60*24*30,'/');

	//生成边框
	$bordercolor = getcolor($bordercolor);
	
	if($border==true) imageRectangle($image, 0, 0, $width-1, $height-1, $bordercolor);

	//输出图片
	imagePng($image);
	imagedestroy($image);

	//获得颜色
	function getcolor($color){
		 global $image;
		 $color = eregi_replace ("^#","",$color);
		 $r = $color[0].$color[1];
		 $r = hexdec ($r);
		 $b = $color[2].$color[3];
		 $b = hexdec ($b);
		 $g = $color[4].$color[5];
		 $g = hexdec ($g);
		 $color = imagecolorallocate ($image, $r, $b, $g); 
		 return $color;
	}

	//生成杂点
	function setnoise(){
		global $image, $width, $height, $back, $noisenum;
		for ($i=0; $i<$noisenum; $i++){
			$randColor = imageColorAllocate($image, rand(0, 255), rand(0, 255), rand(0, 255));  
			imageSetPixel($image, rand(0, $width), rand(0, $height), $randColor);
		} 
	}
?>