ILIAS  release_4-3 Revision
 All Data Structures Namespaces Files Functions Variables Groups Pages
Securimage Class Reference
+ Collaboration diagram for Securimage:

Public Member Functions

 __construct ($options=array())
 Create a new securimage object, pass options to set in the constructor.
 show ($background_image= '')
 Used to serve a captcha image to the browser.
 check ($code)
 Check a submitted code against the stored value.
 outputAudioFile ()
 Output a wav file of the captcha code to the browser.
 frand ()

Static Public Member Functions

static getPath ()
 Return the absolute path to the Securimage directory.

Data Fields

const SI_IMAGE_JPEG = 1
const SI_IMAGE_PNG = 2
const SI_IMAGE_GIF = 3
const SI_CAPTCHA_STRING = 0
const SI_CAPTCHA_MATHEMATIC = 1
 $image_width = 215
 $image_height = 80
 $image_type = self::SI_IMAGE_PNG
 $image_bg_color = '#ffffff'
 $text_color = '#707070'
 $line_color = '#707070'
 $noise_color = '#707070'
 $text_transparency_percentage = 50
 $use_transparent_text = false
 $code_length = 6
 $case_sensitive = false
 $charset = 'ABCDEFGHKLMNPRSTUVWYZabcdefghklmnprstuvwyz23456789'
 $expiry_time = 900
 $session_name = null
 $use_wordlist = false
 $perturbation = 0.75
 $num_lines = 8
 $noise_level = 0
 $image_signature = ''
 $signature_color = '#707070'
 $signature_font
 $use_sqlite_db = false
 $captcha_type = self::SI_CAPTCHA_STRING
 $namespace
 $ttf_file
 $wordlist_file
 $background_directory
 $sqlite_database
 $audio_path

Protected Member Functions

 doImage ()
 The main image drawing routing, responsible for constructing the entire image and serving it.
 allocateColors ()
 Allocate the colors to be used for the image.
 setBackground ()
 The the background color, or background image to be used.
 getBackgroundFromDirectory ()
 Scan the directory for a background image to use.
 createCode ()
 Generates the code or math problem and saves the value to the session.
 drawWord ()
 Draws the captcha code on the image.
 distortedCopy ()
 Copies the captcha image to the final image with distortion applied.
 drawLines ()
 Draws distorted lines on the image.
 drawNoise ()
 Draws random noise on the image.
 addSignature ()
 Print signature text on image.
 output ()
 Sends the appropriate image and cache headers and outputs image to the browser.
 getAudibleCode ($format= 'wav')
 Gets the code and returns the binary audio file for the stored captcha code.
 readCodeFromFile ()
 Gets a captcha code from a wordlist.
 generateCode ()
 Generates a random captcha code from the set character set.
 validate ()
 Checks the entered code against the value stored in the session or sqlite database, handles case sensitivity Also clears the stored codes if the code was entered correctly to prevent re-use.
 getCode ()
 Return the code from the session or sqlite database if used.
 saveData ()
 Save data to session namespace and database if used.
 saveCodeToDatabase ()
 Saves the code to the sqlite database.
 openDatabase ()
 Open sqlite database.
 getCodeFromDatabase ()
 Get a code from the sqlite database for ip address.
 clearCodeFromDatabase ()
 Remove an entered code from the database.
 purgeOldCodesFromDatabase ()
 Deletes old codes from sqlite database.
 isCodeExpired ($creation_time)
 Checks to see if the captcha code has expired and cannot be used.
 generateMP3 ()
 Generate an MP3 audio file of the captcha image.
 generateWAV ($letters)
 Generate a wav file given the $letters in the code.
 scrambleAudioData (&$data, $format)
 Randomizes the audio data to add noise and prevent binary recognition.
 audioError ()
 Return a wav file saying there was an error generating file.
 initColor ($color, $default)
 Convert an html color code to a Securimage_Color.

Protected Attributes

 $im
 $tmpimg
 $bgimg
 $iscale = 5
 $securimage_path = null
 $code
 $code_display
 $captcha_code
 $sqlite_handle
 $gdbgcolor
 $gdtextcolor
 $gdlinecolor
 $gdsignaturecolor

Detailed Description

Definition at line 122 of file securimage.php.

Constructor & Destructor Documentation

Securimage::__construct (   $options = array())

Create a new securimage object, pass options to set in the constructor.


This can be used to display a captcha, play an audible captcha, or validate an entry

Parameters
array$options $options = array( 'text_color' => new Securimage_Color('#013020'), 'code_length' => 5, 'num_lines' => 5, 'noise_level' => 3, 'font_file' => Securimage::getPath() . '/custom.ttf' );

$img = new Securimage($options);

Definition at line 364 of file securimage.php.

References $ttf_file, code_length, image_bg_color, initColor(), line_color, noise_color, perturbation, signature_color, and text_color.

{
$this->securimage_path = dirname(__FILE__);
if (is_array($options) && sizeof($options) > 0) {
foreach($options as $prop => $val) {
$this->$prop = $val;
}
}
$this->image_bg_color = $this->initColor($this->image_bg_color, '#ffffff');
$this->text_color = $this->initColor($this->text_color, '#616161');
$this->line_color = $this->initColor($this->line_color, '#616161');
$this->noise_color = $this->initColor($this->noise_color, '#616161');
$this->signature_color = $this->initColor($this->signature_color, '#616161');
if ($this->ttf_file == null) {
$this->ttf_file = $this->securimage_path . '/AHGBold.ttf';
}
$this->signature_font = $this->ttf_file;
if ($this->wordlist_file == null) {
$this->wordlist_file = $this->securimage_path . '/words/words.txt';
}
if ($this->sqlite_database == null) {
$this->sqlite_database = $this->securimage_path . '/database/securimage.sqlite';
}
if ($this->audio_path == null) {
$this->audio_path = $this->securimage_path . '/audio/';
}
if ($this->code_length == null || $this->code_length < 1) {
$this->code_length = 6;
}
if ($this->perturbation == null || !is_numeric($this->perturbation)) {
$this->perturbation = 0.75;
}
if ($this->namespace == null || !is_string($this->namespace)) {
$this->namespace = 'default';
}
// Initialize session or attach to existing
if ( session_id() == '' ) { // no session has been started yet, which is needed for validation
if ($this->session_name != null && trim($this->session_name) != '') {
session_name(trim($this->session_name)); // set session name if provided
}
session_start();
}
}

+ Here is the call graph for this function:

Member Function Documentation

Securimage::addSignature ( )
protected

Print signature text on image.

Definition at line 872 of file securimage.php.

References image_height, image_signature, and image_width.

Referenced by doImage().

{
$bbox = imagettfbbox(10, 0, $this->signature_font, $this->image_signature);
$textlen = $bbox[2] - $bbox[0];
$x = $this->image_width - $textlen - 5;
$y = $this->image_height - 3;
imagettftext($this->im, 10, 0, $x, $y, $this->gdsignaturecolor, $this->signature_font, $this->image_signature);
}

+ Here is the caller graph for this function:

Securimage::allocateColors ( )
protected

Allocate the colors to be used for the image.

Definition at line 542 of file securimage.php.

References image_bg_color, line_color, noise_color, signature_color, text_color, text_transparency_percentage, and use_transparent_text.

Referenced by doImage().

{
// allocate bg color first for imagecreate
$this->gdbgcolor = imagecolorallocate($this->im,
$this->image_bg_color->r,
$this->image_bg_color->g,
$this->image_bg_color->b);
$alpha = intval($this->text_transparency_percentage / 100 * 127);
if ($this->use_transparent_text == true) {
$this->gdtextcolor = imagecolorallocatealpha($this->im,
$this->text_color->r,
$this->text_color->g,
$this->text_color->b,
$alpha);
$this->gdlinecolor = imagecolorallocatealpha($this->im,
$this->line_color->r,
$this->line_color->g,
$this->line_color->b,
$alpha);
$this->gdnoisecolor = imagecolorallocatealpha($this->im,
$this->noise_color->r,
$this->noise_color->g,
$this->noise_color->b,
$alpha);
} else {
$this->gdtextcolor = imagecolorallocate($this->im,
$this->text_color->r,
$this->text_color->g,
$this->text_color->b);
$this->gdlinecolor = imagecolorallocate($this->im,
$this->line_color->r,
$this->line_color->g,
$this->line_color->b);
$this->gdnoisecolor = imagecolorallocate($this->im,
$this->noise_color->r,
$this->noise_color->g,
$this->noise_color->b);
}
$this->gdsignaturecolor = imagecolorallocate($this->im,
$this->signature_color->r,
$this->signature_color->g,
$this->signature_color->b);
}

+ Here is the caller graph for this function:

Securimage::audioError ( )
protected

Return a wav file saying there was an error generating file.

Returns
string The binary audio contents

Definition at line 1307 of file securimage.php.

Referenced by generateWAV().

{
return @file_get_contents(dirname(__FILE__) . '/audio/error.wav');
}

+ Here is the caller graph for this function:

Securimage::check (   $code)

Check a submitted code against the stored value.

Parameters
string$codeThe captcha code to check $code = $_POST['code']; $img = new Securimage(); if ($img->check($code) == true) { $captcha_valid = true; } else { $captcha_valid = false; }

Definition at line 463 of file securimage.php.

References $code, and validate().

{
$this->code_entered = $code;
$this->validate();
return $this->correct_code;
}

+ Here is the call graph for this function:

Securimage::clearCodeFromDatabase ( )
protected

Remove an entered code from the database.

Definition at line 1119 of file securimage.php.

Referenced by validate().

{
if (is_resource($this->sqlite_handle)) {
$ip = $_SERVER['REMOTE_ADDR'];
$ns = sqlite_escape_string($this->namespace);
sqlite_query($this->sqlite_handle, "DELETE FROM codes WHERE ip = '$ip' AND namespace = '$ns'");
}
}

+ Here is the caller graph for this function:

Securimage::createCode ( )
protected

Generates the code or math problem and saves the value to the session.

Definition at line 663 of file securimage.php.

References $case_sensitive, $code, code_length, generateCode(), readCodeFromFile(), saveData(), and use_wordlist.

Referenced by doImage(), and getAudibleCode().

{
$this->code = false;
switch($this->captcha_type) {
case self::SI_CAPTCHA_MATHEMATIC:
{
$signs = array('+', '-', 'x');
$left = rand(1, 10);
$right = rand(1, 5);
$sign = $signs[rand(0, 2)];
switch($sign) {
case 'x': $c = $left * $right; break;
case '-': $c = $left - $right; break;
default: $c = $left + $right; break;
}
$this->code = $c;
$this->code_display = "$left $sign $right";
break;
}
default:
{
if ($this->use_wordlist && is_readable($this->wordlist_file)) {
$this->code = $this->readCodeFromFile();
}
if ($this->code == false) {
$this->code = $this->generateCode($this->code_length);
}
$this->code_display = $this->code;
$this->code = ($this->case_sensitive) ? $this->code : strtolower($this->code);
} // default
}
$this->saveData();
}

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

Securimage::distortedCopy ( )
protected

Copies the captcha image to the final image with distortion applied.

Definition at line 745 of file securimage.php.

References $image_height, $image_width, $iscale, frand(), image_height, image_width, and perturbation.

Referenced by doImage().

{
$numpoles = 3; // distortion factor
// make array of poles AKA attractor points
for ($i = 0; $i < $numpoles; ++ $i) {
$px[$i] = rand($this->image_width * 0.2, $this->image_width * 0.8);
$py[$i] = rand($this->image_height * 0.2, $this->image_height * 0.8);
$rad[$i] = rand($this->image_height * 0.2, $this->image_height * 0.8);
$tmp = ((- $this->frand()) * 0.15) - .15;
$amp[$i] = $this->perturbation * $tmp;
}
$bgCol = imagecolorat($this->tmpimg, 0, 0);
$width2 = $this->iscale * $this->image_width;
$height2 = $this->iscale * $this->image_height;
imagepalettecopy($this->im, $this->tmpimg); // copy palette to final image so text colors come across
// loop over $img pixels, take pixels from $tmpimg with distortion field
for ($ix = 0; $ix < $this->image_width; ++ $ix) {
for ($iy = 0; $iy < $this->image_height; ++ $iy) {
$x = $ix;
$y = $iy;
for ($i = 0; $i < $numpoles; ++ $i) {
$dx = $ix - $px[$i];
$dy = $iy - $py[$i];
if ($dx == 0 && $dy == 0) {
continue;
}
$r = sqrt($dx * $dx + $dy * $dy);
if ($r > $rad[$i]) {
continue;
}
$rscale = $amp[$i] * sin(3.14 * $r / $rad[$i]);
$x += $dx * $rscale;
$y += $dy * $rscale;
}
$c = $bgCol;
if ($x >= 0 && $x < $width2 && $y >= 0 && $y < $height2) {
$c = imagecolorat($this->tmpimg, $x, $y);
}
if ($c != $bgCol) { // only copy pixels of letters to preserve any background image
imagesetpixel($this->im, $ix, $iy, $c);
}
}
}
}

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

Securimage::doImage ( )
protected

The main image drawing routing, responsible for constructing the entire image and serving it.

Definition at line 500 of file securimage.php.

References addSignature(), allocateColors(), createCode(), distortedCopy(), drawLines(), drawNoise(), drawWord(), image_height, image_signature, image_width, noise_level, num_lines, output(), perturbation, setBackground(), and use_transparent_text.

Referenced by show().

{
if( ($this->use_transparent_text == true || $this->bgimg != '') && function_exists('imagecreatetruecolor')) {
$imagecreate = 'imagecreatetruecolor';
} else {
$imagecreate = 'imagecreate';
}
$this->im = $imagecreate($this->image_width, $this->image_height);
$this->tmpimg = $imagecreate($this->image_width * $this->iscale, $this->image_height * $this->iscale);
$this->allocateColors();
imagepalettecopy($this->tmpimg, $this->im);
$this->setBackground();
$this->createCode();
if ($this->noise_level > 0) {
$this->drawNoise();
}
$this->drawWord();
if ($this->perturbation > 0 && is_readable($this->ttf_file)) {
$this->distortedCopy();
}
if ($this->num_lines > 0) {
$this->drawLines();
}
if (trim($this->image_signature) != '') {
$this->addSignature();
}
$this->output();
}

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

Securimage::drawLines ( )
protected

Draws distorted lines on the image.

Definition at line 796 of file securimage.php.

References $image_width, $n, $num_lines, frand(), image_height, and image_width.

Referenced by doImage().

{
for ($line = 0; $line < $this->num_lines; ++ $line) {
$x = $this->image_width * (1 + $line) / ($this->num_lines + 1);
$x += (0.5 - $this->frand()) * $this->image_width / $this->num_lines;
$y = rand($this->image_height * 0.1, $this->image_height * 0.9);
$theta = ($this->frand() - 0.5) * M_PI * 0.7;
$len = rand($w * 0.4, $w * 0.7);
$lwid = rand(0, 2);
$k = $this->frand() * 0.6 + 0.2;
$k = $k * $k * 0.5;
$phi = $this->frand() * 6.28;
$step = 0.5;
$dx = $step * cos($theta);
$dy = $step * sin($theta);
$n = $len / $step;
$amp = 1.5 * $this->frand() / ($k + 5.0 / $len);
$x0 = $x - 0.5 * $len * cos($theta);
$y0 = $y - 0.5 * $len * sin($theta);
$ldx = round(- $dy * $lwid);
$ldy = round($dx * $lwid);
for ($i = 0; $i < $n; ++ $i) {
$x = $x0 + $i * $dx + $amp * $dy * sin($k * $i * $step + $phi);
$y = $y0 + $i * $dy - $amp * $dx * sin($k * $i * $step + $phi);
imagefilledrectangle($this->im, $x, $y, $x + $lwid, $y + $lwid, $this->gdlinecolor);
}
}
}

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

Securimage::drawNoise ( )
protected

Draws random noise on the image.

Definition at line 833 of file securimage.php.

References $iscale, $noise_level, $size, $t, image_height, image_width, and noise_level.

Referenced by doImage().

{
if ($this->noise_level > 10) {
} else {
}
$t0 = microtime(true);
$noise_level *= 125; // an arbitrary number that works well on a 1-10 scale
$points = $this->image_width * $this->image_height * $this->iscale;
$height = $this->image_height * $this->iscale;
$width = $this->image_width * $this->iscale;
for ($i = 0; $i < $noise_level; ++$i) {
$x = rand(10, $width);
$y = rand(10, $height);
$size = rand(7, 10);
if ($x - $size <= 0 && $y - $size <= 0) continue; // dont cover 0,0 since it is used by imagedistortedcopy
imagefilledarc($this->tmpimg, $x, $y, $size, $size, 0, 360, $this->gdnoisecolor, IMG_ARC_PIE);
}
$t1 = microtime(true);
$t = $t1 - $t0;
/*
// DEBUG
imagestring($this->tmpimg, 5, 25, 30, "$t", $this->gdnoisecolor);
header('content-type: image/png');
imagepng($this->tmpimg);
exit;
*/
}

+ Here is the caller graph for this function:

Securimage::drawWord ( )
protected

Draws the captcha code on the image.

Definition at line 707 of file securimage.php.

References $iscale, image_height, image_width, and perturbation.

Referenced by doImage().

{
$width2 = $this->image_width * $this->iscale;
$height2 = $this->image_height * $this->iscale;
if (!is_readable($this->ttf_file)) {
imagestring($this->im, 4, 10, ($this->image_height / 2) - 5, 'Failed to load TTF font file!', $this->gdtextcolor);
} else {
if ($this->perturbation > 0) {
$font_size = $height2 * .4;
$bb = imageftbbox($font_size, 0, $this->ttf_file, $this->code_display);
$tx = $bb[4] - $bb[0];
$ty = $bb[5] - $bb[1];
$x = floor($width2 / 2 - $tx / 2 - $bb[0]);
$y = round($height2 / 2 - $ty / 2 - $bb[1]);
imagettftext($this->tmpimg, $font_size, 0, $x, $y, $this->gdtextcolor, $this->ttf_file, $this->code_display);
} else {
$font_size = $this->image_height * .4;
$bb = imageftbbox($font_size, 0, $this->ttf_file, $this->code_display);
$tx = $bb[4] - $bb[0];
$ty = $bb[5] - $bb[1];
$x = floor($this->image_width / 2 - $tx / 2 - $bb[0]);
$y = round($this->image_height / 2 - $ty / 2 - $bb[1]);
imagettftext($this->im, $font_size, 0, $x, $y, $this->gdtextcolor, $this->ttf_file, $this->code_display);
}
}
// DEBUG
//$this->im = $this->tmpimg;
//$this->output();
}

+ Here is the caller graph for this function:

Securimage::frand ( )

Definition at line 1312 of file securimage.php.

Referenced by distortedCopy(), and drawLines().

{
return 0.0001 * rand(0,9999);
}

+ Here is the caller graph for this function:

Securimage::generateCode ( )
protected

Generates a random captcha code from the set character set.

Definition at line 972 of file securimage.php.

References $code, and $code_length.

Referenced by createCode().

{
$code = '';
for($i = 1, $cslen = strlen($this->charset); $i <= $this->code_length; ++$i) {
$code .= $this->charset{rand(0, $cslen - 1)};
}
//return 'testing'; // debug, set the code to given string
return $code;
}

+ Here is the caller graph for this function:

Securimage::generateMP3 ( )
protected

Generate an MP3 audio file of the captcha image.

Deprecated:
3.0

Definition at line 1165 of file securimage.php.

Referenced by getAudibleCode().

{
return false;
}

+ Here is the caller graph for this function:

Securimage::generateWAV (   $letters)
protected

Generate a wav file given the $letters in the code.

Todo:
Add ability to merge 2 sound files together to have random background sounds
Parameters
array$letters
Returns
string The binary contents of the wav file

Definition at line 1176 of file securimage.php.

References $data, $file, $filename, audioError(), and scrambleAudioData().

Referenced by getAudibleCode().

{
$data_len = 0;
$files = array();
$out_data = '';
$out_channels = 0;
$out_samplert = 0;
$out_bpersample = 0;
$numSamples = 0;
$removeChunks = array('LIST', 'DISP', 'NOTE');
for ($i = 0; $i < sizeof($letters); ++$i) {
$letter = $letters[$i];
$filename = $this->audio_path . strtoupper($letter) . '.wav';
$file = array();
$data = @file_get_contents($filename);
if ($data === false) {
// echo "Failed to read $filename";
return $this->audioError();
}
$header = substr($data, 0, 36);
$info = unpack('NChunkID/VChunkSize/NFormat/NSubChunk1ID/'
.'VSubChunk1Size/vAudioFormat/vNumChannels/'
.'VSampleRate/VByteRate/vBlockAlign/vBitsPerSample',
$header);
$dataPos = strpos($data, 'data');
$out_channels = $info['NumChannels'];
$out_samplert = $info['SampleRate'];
$out_bpersample = $info['BitsPerSample'];
if ($dataPos === false) {
// wav file with no data?
// echo "Failed to find DATA segment in $filename";
return $this->audioError();
}
if ($info['AudioFormat'] != 1) {
// only work with PCM audio
// echo "$filename was not PCM audio, only PCM is supported";
return $this->audioError();
}
if ($info['SubChunk1Size'] != 16 && $info['SubChunk1Size'] != 18) {
// probably unsupported extension
// echo "Bad SubChunk1Size in $filename - Size was {$info['SubChunk1Size']}";
return $this->audioError();
}
if ($info['SubChunk1Size'] > 16) {
$header .= substr($data, 36, $info['SubChunk1Size'] - 16);
}
if ($i == 0) {
// create the final file's header, size will be adjusted later
$out_data = $header . 'data';
}
$removed = 0;
foreach($removeChunks as $chunk) {
$chunkPos = strpos($data, $chunk);
if ($chunkPos !== false) {
$listSize = unpack('VSize', substr($data, $chunkPos + 4, 4));
$data = substr($data, 0, $chunkPos) .
substr($data, $chunkPos + 8 + $listSize['Size']);
$removed += $listSize['Size'] + 8;
}
}
$dataSize = unpack('VSubchunk2Size', substr($data, $dataPos + 4, 4));
$dataSize['Subchunk2Size'] -= $removed;
$out_data .= substr($data, $dataPos + 8, $dataSize['Subchunk2Size'] * ($out_bpersample / 8));
$numSamples += $dataSize['Subchunk2Size'];
}
$filesize = strlen($out_data);
$chunkSize = $filesize - 8;
$dataCSize = $numSamples;
$out_data = substr_replace($out_data, pack('V', $chunkSize), 4, 4);
$out_data = substr_replace($out_data, pack('V', $numSamples), 40 + ($info['SubChunk1Size'] - 16), 4);
$this->scrambleAudioData($out_data, 'wav');
return $out_data;
}

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

Securimage::getAudibleCode (   $format = 'wav')
protected

Gets the code and returns the binary audio file for the stored captcha code.

Parameters
string$formatWAV only

Definition at line 916 of file securimage.php.

References $code, createCode(), generateMP3(), generateWAV(), and getCode().

Referenced by outputAudioFile().

{
// override any format other than wav for now
// this is due to security issues with MP3 files
$format = 'wav';
$letters = array();
$code = $this->getCode();
if ($code == '') {
$this->createCode();
$code = $this->getCode();
}
for($i = 0; $i < strlen($code); ++$i) {
$letters[] = $code{$i};
}
if ($format == 'mp3') {
return $this->generateMP3($letters);
} else {
return $this->generateWAV($letters);
}
}

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

Securimage::getBackgroundFromDirectory ( )
protected

Scan the directory for a background image to use.

Definition at line 641 of file securimage.php.

References $file.

Referenced by setBackground().

{
$images = array();
if ( ($dh = opendir($this->background_directory)) !== false) {
while (($file = readdir($dh)) !== false) {
if (preg_match('/(jpg|gif|png)$/i', $file)) $images[] = $file;
}
closedir($dh);
if (sizeof($images) > 0) {
return rtrim($this->background_directory, '/') . '/' . $images[rand(0, sizeof($images)-1)];
}
}
return false;
}

+ Here is the caller graph for this function:

Securimage::getCode ( )
protected

Return the code from the session or sqlite database if used.

If none exists yet, an empty string is returned

Definition at line 1019 of file securimage.php.

References $_SESSION, $code, $namespace, getCodeFromDatabase(), isCodeExpired(), and openDatabase().

Referenced by getAudibleCode(), and validate().

{
$code = '';
if (isset($_SESSION['securimage_code_value'][$this->namespace]) &&
trim($_SESSION['securimage_code_value'][$this->namespace]) != '') {
if ($this->isCodeExpired(
$_SESSION['securimage_code_ctime'][$this->namespace]) == false) {
$code = $_SESSION['securimage_code_value'][$this->namespace];
}
} else if ($this->use_sqlite_db == true && function_exists('sqlite_open')) {
// no code in session - may mean user has cookies turned off
$this->openDatabase();
} else { /* no code stored in session or sqlite database, validation will fail */ }
return $code;
}

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

Securimage::getCodeFromDatabase ( )
protected

Get a code from the sqlite database for ip address.

Definition at line 1096 of file securimage.php.

References $code, $res, and isCodeExpired().

Referenced by getCode().

{
$code = '';
if ($this->use_sqlite_db && $this->sqlite_handle !== false) {
$ip = $_SERVER['REMOTE_ADDR'];
$ns = sqlite_escape_string($this->namespace);
$res = sqlite_query($this->sqlite_handle, "SELECT * FROM codes WHERE ip = '$ip' AND namespace = '$ns'");
if ($res && sqlite_num_rows($res) > 0) {
$res = sqlite_fetch_array($res);
if ($this->isCodeExpired($res['created']) == false) {
$code = $res['code'];
}
}
}
return $code;
}

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

static Securimage::getPath ( )
static

Return the absolute path to the Securimage directory.

Returns
string The path to the securimage base directory

Definition at line 423 of file securimage.php.

{
return dirname(__FILE__);
}
Securimage::initColor (   $color,
  $default 
)
protected

Convert an html color code to a Securimage_Color.

Parameters
string$color
Securimage_Color$defaultThe defalt color to use if $color is invalid

Definition at line 1322 of file securimage.php.

Referenced by __construct().

{
if ($color == null) {
return new Securimage_Color($default);
} else if (is_string($color)) {
try {
return new Securimage_Color($color);
} catch(Exception $e) {
return new Securimage_Color($default);
}
} else if (is_array($color) && sizeof($color) == 3) {
return new Securimage_Color($color[0], $color[1], $color[2]);
} else {
return new Securimage_Color($default);
}
}

+ Here is the caller graph for this function:

Securimage::isCodeExpired (   $creation_time)
protected

Checks to see if the captcha code has expired and cannot be used.

Parameters
unknown_type$creation_time

Definition at line 1146 of file securimage.php.

Referenced by getCode(), and getCodeFromDatabase().

{
$expired = true;
if (!is_numeric($this->expiry_time) || $this->expiry_time < 1) {
$expired = false;
} else if (time() - $creation_time < $this->expiry_time) {
$expired = false;
}
return $expired;
}

+ Here is the caller graph for this function:

Securimage::openDatabase ( )
protected

Open sqlite database.

Definition at line 1073 of file securimage.php.

References $res, and $sqlite_handle.

Referenced by getCode(), and saveCodeToDatabase().

{
$this->sqlite_handle = false;
if ($this->use_sqlite_db && function_exists('sqlite_open')) {
$this->sqlite_handle = sqlite_open($this->sqlite_database, 0666, $error);
if ($this->sqlite_handle !== false) {
$res = sqlite_query($this->sqlite_handle, "PRAGMA table_info(codes)");
if (sqlite_num_rows($res) == 0) {
sqlite_query($this->sqlite_handle, "CREATE TABLE codes (ip VARCHAR(32) PRIMARY KEY, code VARCHAR(32) NOT NULL, namespace VARCHAR(32) NOT NULL, created INTEGER)");
}
}
return $this->sqlite_handle != false;
}
}

+ Here is the caller graph for this function:

Securimage::output ( )
protected

Sends the appropriate image and cache headers and outputs image to the browser.

Definition at line 885 of file securimage.php.

References exit.

Referenced by doImage().

{
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . "GMT");
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
switch ($this->image_type) {
case self::SI_IMAGE_JPEG:
header("Content-Type: image/jpeg");
imagejpeg($this->im, null, 90);
break;
case self::SI_IMAGE_GIF:
header("Content-Type: image/gif");
imagegif($this->im);
break;
default:
header("Content-Type: image/png");
imagepng($this->im);
break;
}
imagedestroy($this->im);
exit();
}

+ Here is the caller graph for this function:

Securimage::outputAudioFile ( )

Output a wav file of the captcha code to the browser.

$img = new Securimage(); $img->outputAudioFile(); // outputs a wav file to the browser exit;

Definition at line 479 of file securimage.php.

References exit, and getAudibleCode().

{
$ext = 'wav'; // force wav - mp3 is insecure
header("Content-Disposition: attachment; filename=\"securimage_audio.{$ext}\"");
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Expires: Sun, 1 Jan 2000 12:00:00 GMT');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . 'GMT');
header('Content-type: audio/x-wav');
$audio = $this->getAudibleCode($ext);
header('Content-Length: ' . strlen($audio));
echo $audio;
}

+ Here is the call graph for this function:

Securimage::purgeOldCodesFromDatabase ( )
protected

Deletes old codes from sqlite database.

Definition at line 1132 of file securimage.php.

{
if ($this->use_sqlite_db && $this->sqlite_handle !== false) {
$now = time();
$limit = (!is_numeric($this->expiry_time) || $this->expiry_time < 1) ? 86400 : $this->expiry_time;
sqlite_query($this->sqlite_handle, "DELETE FROM codes WHERE $now - created > $limit");
}
}
Securimage::readCodeFromFile ( )
protected

Gets a captcha code from a wordlist.

Definition at line 944 of file securimage.php.

References $data.

Referenced by createCode().

{
$fp = @fopen($this->wordlist_file, 'rb');
if (!$fp) return false;
$fsize = filesize($this->wordlist_file);
if ($fsize < 128) return false; // too small of a list to be effective
fseek($fp, rand(0, $fsize - 64), SEEK_SET); // seek to a random position of file from 0 to filesize-64
$data = fread($fp, 64); // read a chunk from our random position
fclose($fp);
$data = preg_replace("/\r?\n/", "\n", $data);
$start = @strpos($data, "\n", rand(0, 56)) + 1; // random start position
$end = @strpos($data, "\n", $start); // find end of word
if ($start === false) {
return false;
} else if ($end === false) {
$end = strlen($data);
}
return strtolower(substr($data, $start, $end - $start)); // return a line of the file
}

+ Here is the caller graph for this function:

Securimage::saveCodeToDatabase ( )
protected

Saves the code to the sqlite database.

Definition at line 1052 of file securimage.php.

References $_SESSION, $code, $namespace, $success, and openDatabase().

Referenced by saveData().

{
$success = false;
$this->openDatabase();
if ($this->use_sqlite_db && $this->sqlite_handle !== false) {
$ip = $_SERVER['REMOTE_ADDR'];
$time = time();
$code = $_SESSION['securimage_code_value'][$this->namespace]; // if cookies are disabled the session still exists at this point
$success = sqlite_query($this->sqlite_handle,
"INSERT OR REPLACE INTO codes(ip, code, namespace, created)
VALUES('$ip', '$code', '{$this->namespace}', $time)");
}
return $success !== false;
}

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

Securimage::saveData ( )
protected

Save data to session namespace and database if used.

Definition at line 1041 of file securimage.php.

References $_SESSION, $code, $namespace, and saveCodeToDatabase().

Referenced by createCode().

{
$_SESSION['securimage_code_value'][$this->namespace] = $this->code;
$_SESSION['securimage_code_ctime'][$this->namespace] = time();
}

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

Securimage::scrambleAudioData ( $data,
  $format 
)
protected

Randomizes the audio data to add noise and prevent binary recognition.

Parameters
string$dataThe binary audio file data
string$formatThe format of the sound file (wav only)

Definition at line 1273 of file securimage.php.

References $data.

Referenced by generateWAV().

{
$start = strpos($data, 'data') + 4; // look for "data" indicator
if ($start === false) $start = 44; // if not found assume 44 byte header
$start += rand(1, 4); // randomize starting offset
$datalen = strlen($data) - $start;
$step = 1;
for ($i = $start; $i < $datalen; $i += $step) {
$ch = ord($data{$i});
if ($ch == 0 || $ch == 255) continue;
if ($ch < 16 || $ch > 239) {
$ch += rand(-6, 6);
} else {
$ch += rand(-12, 12);
}
if ($ch < 0) $ch = 0; else if ($ch > 255) $ch = 255;
$data{$i} = chr($ch);
$step = rand(1,4);
}
return $data;
}

+ Here is the caller graph for this function:

Securimage::setBackground ( )
protected

The the background color, or background image to be used.

Definition at line 593 of file securimage.php.

References $img, getBackgroundFromDirectory(), image_height, and image_width.

Referenced by doImage().

{
// set background color of image by drawing a rectangle since imagecreatetruecolor doesn't set a bg color
imagefilledrectangle($this->im, 0, 0,
$this->image_width, $this->image_height,
$this->gdbgcolor);
imagefilledrectangle($this->tmpimg, 0, 0,
$this->image_width * $this->iscale, $this->image_height * $this->iscale,
$this->gdbgcolor);
if ($this->bgimg == '') {
if ($this->background_directory != null &&
is_dir($this->background_directory) &&
is_readable($this->background_directory))
{
if ($img != false) {
$this->bgimg = $img;
}
}
}
if ($this->bgimg == '') {
return;
}
$dat = @getimagesize($this->bgimg);
if($dat == false) {
return;
}
switch($dat[2]) {
case 1: $newim = @imagecreatefromgif($this->bgimg); break;
case 2: $newim = @imagecreatefromjpeg($this->bgimg); break;
case 3: $newim = @imagecreatefrompng($this->bgimg); break;
default: return;
}
if(!$newim) return;
imagecopyresized($this->im, $newim, 0, 0, 0, 0,
$this->image_width, $this->image_height,
imagesx($newim), imagesy($newim));
}

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

Securimage::show (   $background_image = '')

Used to serve a captcha image to the browser.

Parameters
string$background_imageThe path to the background image to use $img = new Securimage(); $img->code_length = 6; $img->num_lines = 5; $img->noise_level = 5;

$img->show(); // sends the image to browser exit;

Definition at line 441 of file securimage.php.

References doImage().

{
if($background_image != '' && is_readable($background_image)) {
$this->bgimg = $background_image;
}
$this->doImage();
}

+ Here is the call graph for this function:

Securimage::validate ( )
protected

Checks the entered code against the value stored in the session or sqlite database, handles case sensitivity Also clears the stored codes if the code was entered correctly to prevent re-use.

Definition at line 989 of file securimage.php.

References $_SESSION, $code, $namespace, clearCodeFromDatabase(), and getCode().

Referenced by check().

{
$code = $this->getCode();
// returns stored code, or an empty string if no stored code was found
// checks the session and sqlite database if enabled
if ($this->case_sensitive == false && preg_match('/[A-Z]/', $code)) {
// case sensitive was set from securimage_show.php but not in class
// the code saved in the session has capitals so set case sensitive to true
$this->case_sensitive = true;
}
$code_entered = trim( (($this->case_sensitive) ? $this->code_entered
: strtolower($this->code_entered))
);
$this->correct_code = false;
if ($code != '') {
if ($code == $code_entered) {
$this->correct_code = true;
$_SESSION['securimage_code_value'][$this->namespace] = '';
$_SESSION['securimage_code_ctime'][$this->namespace] = '';
}
}
}

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

Field Documentation

Securimage::$audio_path

Definition at line 326 of file securimage.php.

Securimage::$background_directory

Definition at line 313 of file securimage.php.

Securimage::$bgimg
protected

Definition at line 332 of file securimage.php.

Securimage::$captcha_code
protected

Definition at line 340 of file securimage.php.

Securimage::$captcha_type = self::SI_CAPTCHA_STRING

Definition at line 280 of file securimage.php.

Securimage::$case_sensitive = false

Definition at line 212 of file securimage.php.

Referenced by createCode().

Securimage::$charset = 'ABCDEFGHKLMNPRSTUVWYZabcdefghklmnprstuvwyz23456789'

Definition at line 217 of file securimage.php.

Securimage::$code
protected
Securimage::$code_display
protected

Definition at line 338 of file securimage.php.

Securimage::$code_length = 6

Definition at line 207 of file securimage.php.

Referenced by generateCode().

Securimage::$expiry_time = 900

Definition at line 222 of file securimage.php.

Securimage::$gdbgcolor
protected

Definition at line 343 of file securimage.php.

Securimage::$gdlinecolor
protected

Definition at line 345 of file securimage.php.

Securimage::$gdsignaturecolor
protected

Definition at line 346 of file securimage.php.

Securimage::$gdtextcolor
protected

Definition at line 344 of file securimage.php.

Securimage::$im
protected

Definition at line 330 of file securimage.php.

Securimage::$image_bg_color = '#ffffff'

Definition at line 175 of file securimage.php.

Securimage::$image_height = 80

Definition at line 164 of file securimage.php.

Referenced by distortedCopy().

Securimage::$image_signature = ''

Definition at line 257 of file securimage.php.

Securimage::$image_type = self::SI_IMAGE_PNG

Definition at line 169 of file securimage.php.

Securimage::$image_width = 215

Definition at line 159 of file securimage.php.

Referenced by distortedCopy(), and drawLines().

Securimage::$iscale = 5
protected

Definition at line 333 of file securimage.php.

Referenced by distortedCopy(), drawNoise(), and drawWord().

Securimage::$line_color = '#707070'

Definition at line 185 of file securimage.php.

Securimage::$namespace

Definition at line 297 of file securimage.php.

Referenced by getCode(), saveCodeToDatabase(), saveData(), and validate().

Securimage::$noise_color = '#707070'

Definition at line 190 of file securimage.php.

Securimage::$noise_level = 0

Definition at line 251 of file securimage.php.

Referenced by drawNoise().

Securimage::$num_lines = 8

Definition at line 246 of file securimage.php.

Referenced by drawLines().

Securimage::$perturbation = 0.75

Definition at line 241 of file securimage.php.

Securimage::$securimage_path = null
protected

Definition at line 335 of file securimage.php.

Securimage::$session_name = null

Definition at line 229 of file securimage.php.

Securimage::$signature_color = '#707070'

Definition at line 262 of file securimage.php.

Securimage::$signature_font

Definition at line 267 of file securimage.php.

Securimage::$sqlite_database

Definition at line 318 of file securimage.php.

Securimage::$sqlite_handle
protected

Definition at line 341 of file securimage.php.

Referenced by openDatabase().

Securimage::$text_color = '#707070'

Definition at line 180 of file securimage.php.

Securimage::$text_transparency_percentage = 50

Definition at line 196 of file securimage.php.

Securimage::$tmpimg
protected

Definition at line 331 of file securimage.php.

Securimage::$ttf_file

Definition at line 303 of file securimage.php.

Referenced by __construct().

Securimage::$use_sqlite_db = false

Definition at line 273 of file securimage.php.

Securimage::$use_transparent_text = false

Definition at line 201 of file securimage.php.

Securimage::$use_wordlist = false

Definition at line 235 of file securimage.php.

Securimage::$wordlist_file

Definition at line 308 of file securimage.php.

const Securimage::SI_CAPTCHA_MATHEMATIC = 1

Definition at line 153 of file securimage.php.

const Securimage::SI_CAPTCHA_STRING = 0

Definition at line 148 of file securimage.php.

const Securimage::SI_IMAGE_GIF = 3

Definition at line 142 of file securimage.php.

const Securimage::SI_IMAGE_JPEG = 1

Definition at line 132 of file securimage.php.

const Securimage::SI_IMAGE_PNG = 2

Definition at line 137 of file securimage.php.


The documentation for this class was generated from the following file: