# Copyright (c) 2003, James Seng. (http://james.seng.cc/)
# This code is released under the Artistic License.

package MT::SCode;
use strict;

###############################
#                             #
# Define the follow variables #
#                             #
###############################

# tmp directory
# Notice the '/' at the end . You need to have that '/'
# ie, my $tmpdir = "/tmp/captcha' wont work. You need '/tmp/captcha/'
my $tmpdir = "/tmp/"; 

# the length of the security code
my $scode_length = 6;

# max number of temp files
my $scode_maxtmp = 50;

###########################
#                         #
# Do not modify from here #
#                         #
###########################

sub scode_len {
    return $scode_length;
}

sub scode_tmp {
    return $scode_maxtmp;
}

sub scode_generate {
    return int rand( (10**($scode_length)) - (10**($scode_length-1)) ) +
                      10**($scode_length-1);
}

sub scode_create {
    my $code = shift;

    return if (-e $tmpdir.$code);

  	my $scode = scode_generate();
    if ($code>0 && $code<=$scode_maxtmp) {
        open(OUTFILE,">${tmpdir}${code}");
        print OUTFILE $scode;
        close(OUTFILE);
    }
    return $scode;
}

sub scode_delete {
    my $code = shift;

    if ($code>0 && $code<=$scode_maxtmp) {
        unlink $tmpdir.$code;
    }
}

sub scode_get {
    my $code = shift;

    srand time;

    if (!$code) {
      return 999999;
    }

    # Random number back...if have not initialized
    if ($code<=0 || $code>$scode_maxtmp || !-e $tmpdir.$code ) {
        return scode_create();
    }

    open(INFILE, $tmpdir.$code);
    my $scode = <INFILE>;
    close(INFILE);

    $scode =~ s/\D//g;
    return $scode;
}

1;
