{
open (DATA, ">>$file") or die "Can't create File: $file\n";
close(DATA);
}
}
sub generate_random_string
{
ref(my $self = shift) or croak "instance variable needed";
my $length = shift;
# generate a new code
my $code = "";
for(my $i=0; $i < $length; $i++)
{
my $char;
my $list = int(rand 4) +1;
if ($list == 1)
{ # choose a number 1/4 of the time
$char = int(rand 7)+50;
} else { # choose a letter 3/4 of the time
$char = int(rand 25)+97;
}
$char = chr($char);
$code .= $char;
}
return $code;
}
sub _save_code
{
ref(my $self = shift) or croak "instance variable needed";
my $code = shift;
my $md5 = shift;
my $database_file = File::Spec->catfile($self->data_folder(),'codes.txt');
# set a variable with the current time
my $current_time = time;
# create database file if it doesn't already exist
$self->_touch_file($database_file);
# clean expired codes and images
open (DATA, "<$database_file") or die "Can't open File: $database_file\n";
flock DATA, 1; # read lock
my @data=<DATA>;
close(DATA);
my $new_data = "";
foreach my $line (@data)
{
$line =~ s/\n//;
my ($data_time,$data_code) = split(/::/,$line);
if ( (($current_time - $data_time) > ($self->expire())) ||
($data_code eq $md5) )
{ # remove expired captcha, or a dup
my $png_file = File::Spec->catfile($self->output_folder(),$data_code . ".png");
unlink($png_file) or carp("Can't remove png file [$png_file]\n");
} else {
$new_data .= $line."\n";
}
}
# save the code to database
warn "open File: $database_file\n" if($self->debug() >= 2);
open(DATA,">$database_file") or die "Can't open File: $database_file\n";
flock DATA, 2; # write lock
warn "-->>" . $new_data . "\n" if($self->debug() >= 2);
warn "-->>" . $current_time . "::" . $md5."\n" if($self->debug() >= 2);
print DATA $new_data;
print DATA $current_time."::".$md5."\n";
close(DATA);
warn "Close File: $database_file\n" if($self->debug() >= 2);
}
sub create_image_file
{
ref(my $self = shift) or croak "instance variable needed";
my $code = shift;
my $md5 = shift;
my $length = length($code);
my $im_width = $self->width();
# create a new image and color
my $im = new GD::Image(($im_width * $length),$self->height());
my $black = $im->colorAllocate(0,0,0);
# copy the character images into the code graphic
for(my $i=0; $i < $length; $i++)
{
my $letter = substr($code,$i,1);
my $letter_png = File::Spec->catfile($self->images_folder(),$letter . ".png");
my $source = new GD::Image($letter_png);
$im->copy($source,($i*($self->width()),0,0,0,$self->width(),$self->height()));
my $a = int(rand (int(($self->width())/14)))+0;
my $b = int(rand (int(($self->height())/12)))+0;
my $c = int(rand (int(($self->width())/3)))-(int(($self->width())/5));
my $d = int(rand (int(($self->height())/3)))-(int(($self->height())/5));
=4= |