<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Captcha {

    protected $ci;
    public $im;

    public function __construct()
    {
        $this->ci =& get_instance(); 
    }
	
	function create_captcha($data = '', $img_path = '', $img_url = '', $font_path = '')
	{
		$backgrounds = array();
		for($i=1; $i<9; $i++){
			array_push($backgrounds, dirname(dirname(dirname(__FILE__))).'/captcha/backgrounds/'.$i.'.png');
		}
		
		$defaults = array(
			'word'		=> '', 
			'img_path'	=> '',
			'img_url'	=> '',
			'img_width'	=> '80',
			'img_height'	=> '50',
            'backgrounds' => $backgrounds,
            'font_path' => array(dirname(dirname(dirname(__FILE__))).'/captcha/fonts/times_new_yorker.ttf'),
            'color' => '#ff000',
            'expiration'	=> 900,
			'word_length'	=> 5,
            'angle_min' => 0,
            'angle_max' => 5,
			'font_size'	=> 28,
			'img_id'	=> '',
			'characters' => '23456789abcdefghjkmnpqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ',
			'colors'	=> array(
				'background'	=> array(255,255,255),
				'border'	=> array(153,102,102),
				'text'		=> array(204,153,153),
				'grid'		=> array(255,182,182)
			)
		);
		
		foreach ($defaults as $key => $val)
		{
			if ( ! is_array($data) && empty($$key))
			{
				$$key = $val;
			}
			else
			{
				$$key = isset($data[$key]) ? $data[$key] : $val;
			}
		}

		if ($img_path === '' OR $img_url === ''
			OR ! is_dir($img_path) OR ! is_really_writable($img_path)
			OR ! extension_loaded('gd'))
		{
			//die('something went wrong');
			return FALSE;
		}

		// -----------------------------------
		// Remove old images
		// -----------------------------------

		$now = microtime(TRUE);

		$current_dir = @opendir($img_path);
		while ($filename = @readdir($current_dir))
		{
			if (substr($filename, -4) === '.png' && (str_replace('.png', '', $filename) + $expiration) < $now)
			{
				@unlink($img_path.$filename);
			}
		}

		@closedir($current_dir);

		// -----------------------------------
		// Do we have a "word" yet?
		// -----------------------------------
        $word="";
        $length = $defaults['word_length'];
        while( strlen($word) < $length ) {
            $word .= substr($defaults['characters'], mt_rand() % (strlen($defaults['characters'])), 1);
        }

        //set image background
        $background = $defaults['backgrounds'][mt_rand(0, count($defaults['backgrounds']) -1)];
        list($bg_width, $bg_height, $bg_type, $bg_attr) = getimagesize($background);

		// -----------------------------------
		// Determine angle and position
		// -----------------------------------
		$angle = mt_rand( $defaults['angle_min'], $defaults['angle_max'] ) * (mt_rand(0, 1) == 1 ? -1 : 1);
        $font = $defaults['font_path'][mt_rand(0, count($defaults['font_path']) - 1)];
        $font_size =  $defaults['font_size'];
        $text_box_size = imagettfbbox($font_size, $angle, $font, $word);
        $box_width = abs($text_box_size[6] - $text_box_size[2]);
        $box_height = abs($text_box_size[5] - $text_box_size[1]);
        $text_pos_x_min = 0;
        $text_pos_x_max = ($bg_width) - ($box_width);
        $text_pos_x = mt_rand($text_pos_x_min, $text_pos_x_max);
        $text_pos_y_min = $box_height;
        $text_pos_y_max = ($bg_height) - ($box_height / 2);
        if ($text_pos_y_min > $text_pos_y_max) {
            $temp_text_pos_y = $text_pos_y_min;
            $text_pos_y_min = $text_pos_y_max;
            $text_pos_y_max = $temp_text_pos_y;
        }
        $text_pos_y = mt_rand($text_pos_y_min, $text_pos_y_max);

		// Create image
		// PHP.net recommends imagecreatetruecolor(), but it isn't always available

        $im = imagecreatefrompng($background);


		// -----------------------------------
		//  Assign colors
		// ----------------------------------

		$color = $this->hex2rgb($defaults['color']);
        $color = imagecolorallocate($im, $color['r'], $color['g'], $color['b']);

	    // -----------------------------------
		//  Write the text
		// -----------------------------------

		imagettftext($im, $font_size, $angle, $text_pos_x, $text_pos_y, $color, $font, $word);
		// -----------------------------------
		//  Generate the image
		// -----------------------------------
		$img_url = rtrim($img_url, '/').'/';

		/*if (function_exists('imagejpeg'))
		{
			$img_filename = $now.'.jpg';
			imagejpeg($im, $img_path.$img_filename);
		}
		else
        */
		
        if (function_exists('imagepng'))
		{
			$img_filename = $now.'.png';
			imagepng($im, $img_path.$img_filename);
		}
		else
		{
			return FALSE;
		}
			
		$img = '<img '.($img_id === '' ? '' : 'id="'.$img_id.'"').' src="'.$img_url.$img_filename.'" style="width: '.$img_width.'; height: '.$img_height .'; border: 0;" alt=" " />';
		ImageDestroy($im);
		return array('word' => $word, 'time' => $now ,'image' => $img, 'filename' => $img_filename, 'src'=> $img_url.$img_filename);
	}

    function hex2rgb($hex_str, $return_string = false, $separator = ',') {
        $hex_str = preg_replace("/[^0-9A-Fa-f]/", '', $hex_str); // Gets a proper hex string
        $rgb_array = array();
        if( strlen($hex_str) == 6 ) {
            $color_val = hexdec($hex_str);
            $rgb_array['r'] = 0xFF & ($color_val >> 0x10);
            $rgb_array['g'] = 0xFF & ($color_val >> 0x8);
            $rgb_array['b'] = 0xFF & $color_val;
        } elseif( strlen($hex_str) == 3 ) {
            $rgb_array['r'] = hexdec(str_repeat(substr($hex_str, 0, 1), 2));
            $rgb_array['g'] = hexdec(str_repeat(substr($hex_str, 1, 1), 2));
            $rgb_array['b'] = hexdec(str_repeat(substr($hex_str, 2, 1), 2));
        } else {
            return false;
        }
        return $return_string ? implode($separator, $rgb_array) : $rgb_array;
    }
    
    public function __get($var){
	return get_instance()->$var;
    }
}