ILIAS  Release_4_4_x_branch Revision 61816
 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.
 getCode ($array=false, $returnExisting=false)
 Return the code from the session or sqlite database if used.
 createCode ()
 Generates the code or math problem and saves the value to the session.
 getRandomNoiseFile ()
 frand ()
 Return a random float between 0 and 0.9999.
 errorHandler ($errno, $errstr, $errfile= '', $errline=0, $errcontext=array())
 Error handler used when outputting captcha image or audio.

Static Public Member Functions

static getPath ()
 Return the absolute path to the Securimage directory.
static getCaptchaId ($new=true, array $options=array())
 Generate a new captcha ID or retrieve the current ID.
static checkByCaptchaId ($id, $value, array $options=array())
 Validate a captcha code input against a captcha ID.

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
const SI_CAPTCHA_WORDS = 2
const SI_DRIVER_MYSQL = 'mysql'
const SI_DRIVER_PGSQL = 'pgsql'
const SI_DRIVER_SQLITE3 = 'sqlite'
 $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 = 20
 $use_transparent_text = true
 $code_length = 6
 $case_sensitive = false
 $charset = 'ABCDEFGHKLMNPRSTUVWYZabcdefghklmnprstuvwyz23456789'
 $expiry_time = 900
 $session_name = null
 $use_wordlist = false
 $perturbation = 0.85
 $num_lines = 5
 $noise_level = 2
 $image_signature = ''
 $signature_color = '#707070'
 $signature_font
 $use_sqlite_db = false
 $use_database = false
 $database_driver = self::SI_DRIVER_SQLITE3
 $database_host = 'localhost'
 $database_user = ''
 $database_pass = ''
 $database_name = ''
 $database_table = 'captcha_codes'
 $database_file
 $captcha_type = self::SI_CAPTCHA_STRING
 $namespace
 $ttf_file
 $wordlist_file
 $background_directory
 $sqlite_database
 $audio_path
 $audio_noise_path
 $audio_use_noise
 $audio_mix_normalization = 0.6
 $degrade_audio
 $audio_gap_min = 0
 $audio_gap_max = 600
 $securimage_path = null
 $display_value

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.
 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 ()
 Gets the code and returns the binary audio file for the stored captcha code.
 readCodeFromFile ($numWords=1)
 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.
 saveData ()
 Save data to session namespace and database if used.
 saveCodeToDatabase ()
 Saves the code to the sqlite database.
 openDatabase ()
 Open sqlite database.
 getDsn ()
 checkTablesExist ()
 createDatabaseTables ()
 getCodeFromDatabase ()
 Get a code from the sqlite database for ip address/captchaId.
 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.
 generateWAV ($letters)
 Generate a wav file given the $letters in the code.
 audioError ()
 Return a wav file saying there was an error generating file.
 canSendHeaders ()
 Checks to see if headers can be sent and if any error has been output to the browser.
 initColor ($color, $default)
 Convert an html color code to a Securimage_Color.

Protected Attributes

 $im
 $tmpimg
 $bgimg
 $iscale = 5
 $code
 $code_display
 $captcha_code
 $no_exit
 $no_session
 $send_headers
 $pdo_conn
 $gdbgcolor
 $gdtextcolor
 $gdlinecolor
 $gdsignaturecolor

Static Protected Attributes

static $_captchaId = null

Detailed Description

Definition at line 165 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 629 of file securimage.php.

References $_captchaId, $options, $ttf_file, and initColor().

{
$this->securimage_path = dirname(__FILE__);
if (is_array($options) && sizeof($options) > 0) {
foreach($options as $prop => $val) {
if ($prop == 'captchaId') {
$this->use_database = true;
} else if ($prop == 'use_sqlite_db') {
trigger_error("The use_sqlite_db option is deprecated, use 'use_database' instead", E_USER_NOTICE);
} else {
$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 (is_null($this->ttf_file)) {
$this->ttf_file = $this->securimage_path . '/AHGBold.ttf';
}
$this->signature_font = $this->ttf_file;
if (is_null($this->wordlist_file)) {
$this->wordlist_file = $this->securimage_path . '/words/words.txt';
}
if (is_null($this->database_file)) {
$this->database_file = $this->securimage_path . '/database/securimage.sq3';
}
if (is_null($this->audio_path)) {
$this->audio_path = $this->securimage_path . '/audio/en/';
}
if (is_null($this->audio_noise_path)) {
$this->audio_noise_path = $this->securimage_path . '/audio/noise/';
}
if (is_null($this->audio_use_noise)) {
$this->audio_use_noise = true;
}
if (is_null($this->degrade_audio)) {
$this->degrade_audio = true;
}
if (is_null($this->code_length) || (int)$this->code_length < 1) {
$this->code_length = 6;
}
if (is_null($this->perturbation) || !is_numeric($this->perturbation)) {
$this->perturbation = 0.75;
}
if (is_null($this->namespace) || !is_string($this->namespace)) {
$this->namespace = 'default';
}
if (is_null($this->no_exit)) {
$this->no_exit = false;
}
if (is_null($this->no_session)) {
$this->no_session = false;
}
if (is_null($this->send_headers)) {
$this->send_headers = true;
}
if ($this->no_session != true) {
// Initialize session or attach to existing
if ( session_id() == '' ) { // no session has been started yet, which is needed for validation
if (!is_null($this->session_name) && 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 1353 of file securimage.php.

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 1015 of file securimage.php.

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 2031 of file securimage.php.

Referenced by outputAudioFile().

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

+ Here is the caller graph for this function:

Securimage::canSendHeaders ( )
protected

Checks to see if headers can be sent and if any error has been output to the browser.

Returns
bool true if headers haven't been sent and no output/errors will break audio/images, false if unsafe

Definition at line 2041 of file securimage.php.

Referenced by output(), and outputAudioFile().

{
if (headers_sent()) {
// output has been flushed and headers have already been sent
return false;
} else if (strlen((string)ob_get_contents()) > 0) {
// headers haven't been sent, but there is data in the buffer that will break image and audio data
return false;
}
return true;
}

+ 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 831 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:

static Securimage::checkByCaptchaId (   $id,
  $value,
array  $options = array() 
)
static

Validate a captcha code input against a captcha ID.

Parameters
string$idThe captcha ID to check
string$valueThe captcha value supplied by the user
array$optionsArray of options to construct Securimage with. Options must include database options if they are not set in securimage.php
See Also
Securimage::$database_driver
Returns
bool true if the code was valid for the given captcha ID, false if not or if database failed to open

Definition at line 763 of file securimage.php.

References $code, $options, and $si.

{
$opts = array('captchaId' => $id,
'no_session' => true,
'use_database' => true);
if (sizeof($options) > 0) $opts = array_merge($options, $opts);
$si = new self($opts);
if ($si->openDatabase()) {
$code = $si->getCodeFromDatabase();
if (is_array($code)) {
$si->code = $code['code'];
$si->code_display = $code['code_disp'];
}
if ($si->check($value)) {
$si->clearCodeFromDatabase();
return true;
} else {
return false;
}
} else {
return false;
}
}
Securimage::checkTablesExist ( )
protected

Definition at line 1701 of file securimage.php.

References $query, and $result.

Referenced by openDatabase().

{
$table = $this->pdo_conn->quote($this->database_table);
switch($this->database_driver) {
case self::SI_DRIVER_SQLITE3:
// query row count for sqlite, PRAGMA queries seem to return no
// rowCount using PDO even if there are rows returned
$query = "SELECT COUNT(id) FROM $table";
break;
case self::SI_DRIVER_MYSQL:
$query = "SHOW TABLES LIKE $table";
break;
case self::SI_DRIVER_PGSQL:
$query = "SELECT * FROM information_schema.columns WHERE table_name = $table;";
break;
}
$result = $this->pdo_conn->query($query);
if (!$result) {
$err = $this->pdo_conn->errorInfo();
if ($this->database_driver == self::SI_DRIVER_SQLITE3 &&
$err[1] === 1 && strpos($err[2], 'no such table') !== false)
{
return false;
}
throw new Exception("Failed to check tables: {$err[0]} - {$err[1]}: {$err[2]}");
} else if ($this->database_driver == self::SI_DRIVER_SQLITE3) {
// successful here regardless of row count for sqlite
return true;
} else if ($result->rowCount() == 0) {
return false;
} else {
return true;
}
}

+ Here is the caller graph for this function:

Securimage::clearCodeFromDatabase ( )
protected

Remove an entered code from the database.

Definition at line 1856 of file securimage.php.

References $_captchaId, $query, and $result.

Referenced by saveCodeToDatabase(), and validate().

{
if ($this->pdo_conn) {
$ip = $_SERVER['REMOTE_ADDR'];
$ns = $this->pdo_conn->quote($this->namespace);
if (empty($id)) {
$id = $ip; // if no captchaId set, IP address is captchaId.
}
$id = $this->pdo_conn->quote($id);
$query = sprintf("DELETE FROM %s WHERE id = %s AND namespace = %s",
$this->database_table, $id, $ns);
$result = $this->pdo_conn->query($query);
if (!$result) {
trigger_error("Failed to delete code from database.", E_USER_WARNING);
}
}
}

+ Here is the caller graph for this function:

Securimage::createCode ( )

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

Definition at line 1136 of file securimage.php.

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

Referenced by doImage(), and getAudibleCode().

{
$this->code = false;
switch($this->captcha_type) {
case self::SI_CAPTCHA_MATHEMATIC:
{
do {
$signs = array('+', '-', 'x');
$left = mt_rand(1, 10);
$right = mt_rand(1, 5);
$sign = $signs[mt_rand(0, 2)];
switch($sign) {
case 'x': $c = $left * $right; break;
case '-': $c = $left - $right; break;
default: $c = $left + $right; break;
}
} while ($c <= 0); // no negative #'s or 0
$this->code = $c;
$this->code_display = "$left $sign $right";
break;
}
case self::SI_CAPTCHA_WORDS:
$words = $this->readCodeFromFile(2);
$this->code = implode(' ', $words);
$this->code_display = $this->code;
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::createDatabaseTables ( )
protected

Definition at line 1743 of file securimage.php.

References $query, and $result.

Referenced by openDatabase().

{
$queries = array();
switch($this->database_driver) {
case self::SI_DRIVER_SQLITE3:
$queries[] = "CREATE TABLE \"{$this->database_table}\" (
id VARCHAR(40),
namespace VARCHAR(32) NOT NULL,
code VARCHAR(32) NOT NULL,
code_display VARCHAR(32) NOT NULL,
created INTEGER NOT NULL,
PRIMARY KEY(id, namespace)
)";
$queries[] = "CREATE INDEX ndx_created ON {$this->database_table} (created)";
break;
case self::SI_DRIVER_MYSQL:
$queries[] = "CREATE TABLE `{$this->database_table}` (
`id` VARCHAR(40) NOT NULL,
`namespace` VARCHAR(32) NOT NULL,
`code` VARCHAR(32) NOT NULL,
`code_display` VARCHAR(32) NOT NULL,
`created` INT NOT NULL,
PRIMARY KEY(id, namespace),
INDEX(created)
)";
break;
case self::SI_DRIVER_PGSQL:
$queries[] = "CREATE TABLE {$this->database_table} (
id character varying(40) NOT NULL,
namespace character varying(32) NOT NULL,
code character varying(32) NOT NULL,
code_display character varying(32) NOT NULL,
created integer NOT NULL,
CONSTRAINT pkey_id_namespace PRIMARY KEY (id, namespace)
)";
$queries[] = "CREATE INDEX ndx_created ON {$this->database_table} (created);";
break;
}
$this->pdo_conn->beginTransaction();
foreach($queries as $query) {
$result = $this->pdo_conn->query($query);
if (!$result) {
$err = $this->pdo_conn->errorInfo();
trigger_error("Failed to create table. {$err[1]}: {$err[2]}", E_USER_WARNING);
$this->pdo_conn->rollBack();
$this->pdo_conn = false;
return false;
}
}
$this->pdo_conn->commit();
return true;
}

+ 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 1226 of file securimage.php.

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

Referenced by doImage().

{
$numpoles = 3; // distortion factor
// make array of poles AKA attractor points
for ($i = 0; $i < $numpoles; ++ $i) {
$px[$i] = mt_rand($this->image_width * 0.2, $this->image_width * 0.8);
$py[$i] = mt_rand($this->image_height * 0.2, $this->image_height * 0.8);
$rad[$i] = mt_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 944 of file securimage.php.

References $case_sensitive, $code, $display_value, addSignature(), allocateColors(), createCode(), distortedCopy(), drawLines(), drawNoise(), drawWord(), getCaptchaId(), getCodeFromDatabase(), openDatabase(), output(), and setBackground().

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();
$code = '';
if ($this->getCaptchaId(false) !== null) {
// a captcha Id was supplied
// check to see if a display_value for the captcha image was set
if (is_string($this->display_value) && strlen($this->display_value) > 0) {
$this->code_display = $this->display_value;
$this->code = ($this->case_sensitive) ?
$this->display_value :
strtolower($this->display_value);
} else if ($this->openDatabase()) {
// no display_value, check the database for existing captchaId
// got back a result from the database with a valid code for captchaId
if (is_array($code)) {
$this->code = $code['code'];
$this->code_display = $code['code_disp'];
$code = $code['code'];
}
}
}
if ($code == '') {
// if the code was not set using display_value or was not found in
// the database, create a new code
$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 1277 of file securimage.php.

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

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 = mt_rand($this->image_height * 0.1, $this->image_height * 0.9);
$theta = ($this->frand() - 0.5) * M_PI * 0.7;
$len = mt_rand($w * 0.4, $w * 0.7);
$lwid = mt_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 1314 of file securimage.php.

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

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 = mt_rand(10, $width);
$y = mt_rand(10, $height);
$size = mt_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 1188 of file securimage.php.

References $iscale.

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::errorHandler (   $errno,
  $errstr,
  $errfile = '',
  $errline = 0,
  $errcontext = array() 
)

Error handler used when outputting captcha image or audio.

This error handler helps determine if any errors raised would prevent captcha image or audio from displaying. If they have no effect on the output buffer or headers, true is returned so the script can continue processing. See https://github.com/dapphp/securimage/issues/15

Parameters
int$errno
string$errstr
string$errfile
int$errline
array$errcontext
Returns
boolean true if handled, false if PHP should handle

Definition at line 2101 of file securimage.php.

{
// get the current error reporting level
$level = error_reporting();
// if error was supressed or $errno not set in current error level
if ($level == 0 || ($level & $errno) == 0) {
return true;
}
return false;
}
Securimage::frand ( )

Return a random float between 0 and 0.9999.

Returns
float Random float between 0 and 0.9999

Definition at line 2059 of file securimage.php.

Referenced by distortedCopy(), and drawLines().

{
return 0.0001 * mt_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 1499 of file securimage.php.

References $code, and $code_length.

Referenced by createCode().

{
$code = '';
if (function_exists('mb_strlen')) {
for($i = 1, $cslen = mb_strlen($this->charset); $i <= $this->code_length; ++$i) {
$code .= mb_substr($this->charset, mt_rand(0, $cslen - 1), 1, 'UTF-8');
}
} else {
for($i = 1, $cslen = strlen($this->charset); $i <= $this->code_length; ++$i) {
$code .= substr($this->charset, mt_rand(0, $cslen - 1), 1);
}
}
return $code;
}

+ 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 1920 of file securimage.php.

References $audio_mix_normalization, WavFile\FILTER_DEGRADE, WavFile\FILTER_MIX, WavFile\FILTER_NORMALIZE, and getRandomNoiseFile().

Referenced by getAudibleCode().

{
$wavCaptcha = new WavFile();
$first = true; // reading first wav file
foreach ($letters as $letter) {
$letter = strtoupper($letter);
try {
$l = new WavFile($this->audio_path . '/' . $letter . '.wav');
if ($first) {
// set sample rate, bits/sample, and # of channels for file based on first letter
$wavCaptcha->setSampleRate($l->getSampleRate())
->setBitsPerSample($l->getBitsPerSample())
->setNumChannels($l->getNumChannels());
$first = false;
}
// append letter to the captcha audio
$wavCaptcha->appendWav($l);
// random length of silence between $audio_gap_min and $audio_gap_max
if ($this->audio_gap_max > 0 && $this->audio_gap_max > $this->audio_gap_min) {
$wavCaptcha->insertSilence( mt_rand($this->audio_gap_min, $this->audio_gap_max) / 1000.0 );
}
} catch (Exception $ex) {
// failed to open file, or the wav file is broken or not supported
// 2 wav files were not compatible, different # channels, bits/sample, or sample rate
throw $ex;
}
}
/********* Set up audio filters *****************************/
$filters = array();
if ($this->audio_use_noise == true) {
// use background audio - find random file
$noiseFile = $this->getRandomNoiseFile();
if ($noiseFile !== false && is_readable($noiseFile)) {
try {
$wavNoise = new WavFile($noiseFile, false);
} catch(Exception $ex) {
throw $ex;
}
// start at a random offset from the beginning of the wavfile
// in order to add more randomness
$randOffset = 0;
if ($wavNoise->getNumBlocks() > 2 * $wavCaptcha->getNumBlocks()) {
$randBlock = mt_rand(0, $wavNoise->getNumBlocks() - $wavCaptcha->getNumBlocks());
$wavNoise->readWavData($randBlock * $wavNoise->getBlockAlign(), $wavCaptcha->getNumBlocks() * $wavNoise->getBlockAlign());
} else {
$wavNoise->readWavData();
$randOffset = mt_rand(0, $wavNoise->getNumBlocks() - 1);
}
$mixOpts = array('wav' => $wavNoise,
'loop' => true,
'blockOffset' => $randOffset);
$filters[WavFile::FILTER_MIX] = $mixOpts;
}
}
if ($this->degrade_audio == true) {
// add random noise.
// any noise level below 95% is intensely distorted and not pleasant to the ear
$filters[WavFile::FILTER_DEGRADE] = mt_rand(95, 98) / 100.0;
}
if (!empty($filters)) {
$wavCaptcha->filter($filters); // apply filters to captcha audio
}
return $wavCaptcha->__toString();
}

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

Securimage::getAudibleCode ( )
protected

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

Returns
The audio representation of the captcha in Wav format

Definition at line 1413 of file securimage.php.

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

Referenced by outputAudioFile().

{
$letters = array();
$code = $this->getCode(true, true);
if ($code['code'] == '') {
if (strlen($this->display_value) > 0) {
$code = array('code' => $this->display_value, 'display' => $this->display_value);
} else {
$this->createCode();
$code = $this->getCode(true);
}
}
if (preg_match('/(\d+) (\+|-|x) (\d+)/i', $code['display'], $eq)) {
$math = true;
$left = $eq[1];
$sign = str_replace(array('+', '-', 'x'), array('plus', 'minus', 'times'), $eq[2]);
$right = $eq[3];
$letters = array($left, $sign, $right);
} else {
$math = false;
$length = strlen($code['display']);
for($i = 0; $i < $length; ++$i) {
$letter = $code['display']{$i};
$letters[] = $letter;
}
}
try {
return $this->generateWAV($letters);
} catch(Exception $ex) {
throw $ex;
}
}

+ 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 1114 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[mt_rand(0, sizeof($images)-1)];
}
}
return false;
}

+ Here is the caller graph for this function:

static Securimage::getCaptchaId (   $new = true,
array  $options = array() 
)
static

Generate a new captcha ID or retrieve the current ID.

Parameters
$newbool If true, generates a new challenge and returns and ID
$optionsarray Additional options to be passed to Securimage. Must include database options if not set directly in securimage.php
Returns
null|string Returns null if no captcha id set and new was false, or string captcha ID

Definition at line 735 of file securimage.php.

References $_captchaId, $options, and $si.

Referenced by doImage(), and saveCodeToDatabase().

{
if (is_null($new) || (bool)$new == true) {
$id = sha1(uniqid($_SERVER['REMOTE_ADDR'], true));
$opts = array('no_session' => true,
'use_database' => true);
if (sizeof($options) > 0) $opts = array_merge($options, $opts);
$si = new self($opts);
$si->createCode();
return $id;
} else {
}
}

+ Here is the caller graph for this function:

Securimage::getCode (   $array = false,
  $returnExisting = false 
)

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

If none exists yet, an empty string is returned

Parameters
$arraybool True to receive an array containing the code and properties
Returns
array|string Array if $array = true, otherwise a string containing the code

Definition at line 899 of file securimage.php.

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

Referenced by getAudibleCode(), and validate().

{
$code = '';
$time = 0;
$disp = 'error';
if ($returnExisting && strlen($this->code) > 0) {
if ($array) {
return array('code' => $this->code,
'display' => $this->code_display,
'code_display' => $this->code_display,
'time' => 0);
} else {
return $this->code;
}
}
if ($this->no_session != true) {
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];
$time = $_SESSION['securimage_code_ctime'][$this->namespace];
$disp = $_SESSION['securimage_code_disp'] [$this->namespace];
}
}
}
if (empty($code) && $this->use_database) {
// 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 */ }
if ($array == true) {
return array('code' => $code, 'ctime' => $time, 'display' => $disp);
} else {
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/captchaId.

Returns
string|array Empty string if no code was found or has expired, otherwise returns the stored captcha code. If a captchaId is set, this returns an array with indices "code" and "code_disp"

Definition at line 1813 of file securimage.php.

References $_captchaId, $code, $namespace, $query, $result, $row, and isCodeExpired().

Referenced by doImage(), and getCode().

{
$code = '';
if ($this->use_database == true && $this->pdo_conn) {
if (Securimage::$_captchaId !== null) {
$query = "SELECT * FROM {$this->database_table} WHERE id = ?";
$stmt = $this->pdo_conn->prepare($query);
$result = $stmt->execute(array(Securimage::$_captchaId));
} else {
$ip = $_SERVER['REMOTE_ADDR'];
// ip is stored in id column when no captchaId
$query = "SELECT * FROM {$this->database_table} WHERE id = ? AND namespace = ?";
$stmt = $this->pdo_conn->prepare($query);
$result = $stmt->execute(array($ip, $ns));
}
if (!$result) {
$err = $this->pdo_conn->errorInfo();
trigger_error("Failed to select code from database. {$err[0]}: {$err[1]}", E_USER_WARNING);
} else {
if ( ($row = $stmt->fetch()) !== false ) {
if (false == $this->isCodeExpired($row['created'])) {
if (Securimage::$_captchaId !== null) {
// return an array when using captchaId
$code = array('code' => $row['code'],
'code_disp' => $row['code_display']);
} else {
$code = $row['code'];
}
}
}
}
}
return $code;
}

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

Securimage::getDsn ( )
protected

Definition at line 1680 of file securimage.php.

References $database_file.

Referenced by openDatabase().

{
$dsn = sprintf('%s:', $this->database_driver);
switch($this->database_driver) {
case self::SI_DRIVER_SQLITE3:
break;
case self::SI_DRIVER_MYSQL:
case self::SI_DRIVER_PGSQL:
$dsn .= sprintf('host=%s;dbname=%s',
$this->database_host,
$this->database_name);
break;
}
return $dsn;
}

+ 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 721 of file securimage.php.

{
return dirname(__FILE__);
}
Securimage::getRandomNoiseFile ( )

Definition at line 2001 of file securimage.php.

References $file.

Referenced by generateWAV().

{
$return = false;
if ( ($dh = opendir($this->audio_noise_path)) !== false ) {
$list = array();
while ( ($file = readdir($dh)) !== false ) {
if ($file == '.' || $file == '..') continue;
if (strtolower(substr($file, -4)) != '.wav') continue;
$list[] = $file;
}
closedir($dh);
if (sizeof($list) > 0) {
$file = $list[array_rand($list, 1)];
$return = $this->audio_noise_path . DIRECTORY_SEPARATOR . $file;
}
}
return $return;
}

+ Here is the caller graph for this function:

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 2069 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 1901 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 1623 of file securimage.php.

References $options, $pdo_conn, checkTablesExist(), createDatabaseTables(), getDsn(), and purgeOldCodesFromDatabase().

Referenced by doImage(), getCode(), and saveCodeToDatabase().

{
$this->pdo_conn = false;
if ($this->use_database) {
$pdo_extension = 'PDO_' . strtoupper($this->database_driver);
if (!extension_loaded($pdo_extension)) {
trigger_error("Database support is turned on in Securimage, but the chosen extension $pdo_extension is not loaded in PHP.", E_USER_WARNING);
return false;
}
}
if ($this->database_driver == self::SI_DRIVER_SQLITE3) {
if (!file_exists($this->database_file)) {
$fp = fopen($this->database_file, 'w+');
if (!$fp) {
$err = error_get_last();
trigger_error("Securimage failed to create SQLite3 database file '{$this->database_file}'. Reason: {$err['message']}", E_USER_WARNING);
return false;
}
fclose($fp);
chmod($this->database_file, 0666);
} else if (!is_writeable($this->database_file)) {
trigger_error("Securimage does not have read/write access to database file '{$this->database_file}. Make sure permissions are 0666 and writeable by user '" . get_current_user() . "'", E_USER_WARNING);
return false;
}
}
$dsn = $this->getDsn();
try {
$options = array();
$this->pdo_conn = new PDO($dsn, $this->database_user, $this->database_pass, $options);
} catch (PDOException $pdoex) {
trigger_error("Database connection failed: " . $pdoex->getMessage(), E_USER_WARNING);
return false;
}
try {
if (!$this->checkTablesExist()) {
// create tables...
}
} catch (Exception $ex) {
trigger_error($ex->getMessage(), E_USER_WARNING);
$this->pdo_conn = null;
return false;
}
if (mt_rand(0, 100) / 100.0 == 1.0) {
}
}

+ Here is the call graph for this function:

+ 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 1366 of file securimage.php.

References canSendHeaders(), and exit.

Referenced by doImage().

{
if ($this->canSendHeaders() || $this->send_headers == false) {
if ($this->send_headers) {
// only send the content-type headers if no headers have been output
// this will ease debugging on misconfigured servers where warnings
// may have been output which break the image and prevent easily viewing
// source to see the error.
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:
if ($this->send_headers) header("Content-Type: image/jpeg");
imagejpeg($this->im, null, 90);
break;
case self::SI_IMAGE_GIF:
if ($this->send_headers) header("Content-Type: image/gif");
imagegif($this->im);
break;
default:
if ($this->send_headers) header("Content-Type: image/png");
imagepng($this->im);
break;
}
} else {
echo '<hr /><strong>'
.'Failed to generate captcha image, content has already been '
.'output.<br />This is most likely due to misconfiguration or '
.'a PHP error was sent to the browser.</strong>';
}
imagedestroy($this->im);
restore_error_handler();
if (!$this->no_exit) exit;
}

+ Here is the call graph for this function:

+ 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 847 of file securimage.php.

References audioError(), canSendHeaders(), exit, and getAudibleCode().

{
set_error_handler(array(&$this, 'errorHandler'));
require_once dirname(__FILE__) . '/WavFile.php';
try {
$audio = $this->getAudibleCode();
} catch (Exception $ex) {
if (($fp = @fopen(dirname(__FILE__) . '/si.error_log', 'a+')) !== false) {
fwrite($fp, date('Y-m-d H:i:s') . ': Securimage audio error "' . $ex->getMessage() . '"' . "\n");
fclose($fp);
}
$audio = $this->audioError();
}
if ($this->canSendHeaders() || $this->send_headers == false) {
if ($this->send_headers) {
$uniq = md5(uniqid(microtime()));
header("Content-Disposition: attachment; filename=\"securimage_audio-{$uniq}.wav\"");
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');
if (extension_loaded('zlib')) {
ini_set('zlib.output_compression', true); // compress output if supported by browser
} else {
header('Content-Length: ' . strlen($audio));
}
}
echo $audio;
} else {
echo '<hr /><strong>'
.'Failed to generate audio file, content has already been '
.'output.<br />This is most likely due to misconfiguration or '
.'a PHP error was sent to the browser.</strong>';
}
restore_error_handler();
if (!$this->no_exit) exit;
}

+ Here is the call graph for this function:

Securimage::purgeOldCodesFromDatabase ( )
protected

Deletes old codes from sqlite database.

Definition at line 1882 of file securimage.php.

References $query, and $result.

Referenced by openDatabase().

{
if ($this->use_database && $this->pdo_conn) {
$now = time();
$limit = (!is_numeric($this->expiry_time) || $this->expiry_time < 1) ? 86400 : $this->expiry_time;
$query = sprintf("DELETE FROM %s WHERE %s - created > %s",
$this->database_table,
$this->pdo_conn->quote($now, PDO::PARAM_INT),
$this->pdo_conn->quote($limit, PDO::PARAM_INT));
$result = $this->pdo_conn->query($query);
}
}

+ Here is the caller graph for this function:

Securimage::readCodeFromFile (   $numWords = 1)
protected

Gets a captcha code from a wordlist.

Definition at line 1456 of file securimage.php.

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
if ((int)$numWords < 1 || (int)$numWords > 5) $numWords = 1;
$words = array();
$i = 0;
do {
fseek($fp, mt_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
$data = preg_replace("/\r?\n/", "\n", $data);
$start = @strpos($data, "\n", mt_rand(0, 56)) + 1; // random start position
$end = @strpos($data, "\n", $start); // find end of word
if ($start === false) {
// picked start position at end of file
continue;
} else if ($end === false) {
$end = strlen($data);
}
$word = strtolower(substr($data, $start, $end - $start)); // return a line of the file
$words[] = $word;
} while (++$i < $numWords);
fclose($fp);
if ($numWords < 2) {
return $words[0];
} else {
return $words;
}
}

+ Here is the caller graph for this function:

Securimage::saveCodeToDatabase ( )
protected

Saves the code to the sqlite database.

Definition at line 1584 of file securimage.php.

References $code, $code_display, $query, $success, clearCodeFromDatabase(), getCaptchaId(), and openDatabase().

Referenced by saveData().

{
$success = false;
$this->openDatabase();
if ($this->use_database && $this->pdo_conn) {
$id = $this->getCaptchaId(false);
$ip = $_SERVER['REMOTE_ADDR'];
if (empty($id)) {
$id = $ip;
}
$time = time();
$code_disp = $this->code_display;
// This is somewhat expensive in PDO Sqlite3 (when there is something to delete)
$query = "INSERT INTO {$this->database_table} ("
."id, code, code_display, namespace, created) "
."VALUES(?, ?, ?, ?, ?)";
$stmt = $this->pdo_conn->prepare($query);
$success = $stmt->execute(array($id, $code, $code_disp, $this->namespace, $time));
if (!$success) {
$err = $stmt->errorInfo();
trigger_error("Failed to insert code into database. {$err[1]}: {$err[2]}", E_USER_WARNING);
}
}
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 1562 of file securimage.php.

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

Referenced by createCode().

{
if ($this->no_session != true) {
if (isset($_SESSION['securimage_code_value']) && is_scalar($_SESSION['securimage_code_value'])) {
// fix for migration from v2 - v3
unset($_SESSION['securimage_code_value']);
unset($_SESSION['securimage_code_ctime']);
}
$_SESSION['securimage_code_disp'] [$this->namespace] = $this->code_display;
$_SESSION['securimage_code_value'][$this->namespace] = $this->code;
$_SESSION['securimage_code_ctime'][$this->namespace] = time();
}
if ($this->use_database) {
}
}

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

Securimage::setBackground ( )
protected

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

Definition at line 1066 of file securimage.php.

References $img, and getBackgroundFromDirectory().

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 807 of file securimage.php.

References doImage().

{
set_error_handler(array(&$this, 'errorHandler'));
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 1520 of file securimage.php.

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

Referenced by check().

{
if (!is_string($this->code) || strlen($this->code) == 0) {
$code = $this->getCode();
// returns stored code, or an empty string if no stored code was found
// checks the session and database if enabled
} else {
}
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 (strpos($code, ' ') !== false) {
// for multi word captchas, remove more than once space from input
$code_entered = preg_replace('/\s+/', ' ', $code_entered);
$code_entered = strtolower($code_entered);
}
if ($code == $code_entered) {
$this->correct_code = true;
if ($this->no_session != 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::$_captchaId = null
staticprotected
Securimage::$audio_gap_max = 600

Definition at line 533 of file securimage.php.

Securimage::$audio_gap_min = 0

Definition at line 526 of file securimage.php.

Securimage::$audio_mix_normalization = 0.6

Definition at line 511 of file securimage.php.

Referenced by generateWAV().

Securimage::$audio_noise_path

Definition at line 479 of file securimage.php.

Securimage::$audio_path

Definition at line 472 of file securimage.php.

Securimage::$audio_use_noise

Definition at line 489 of file securimage.php.

Securimage::$background_directory

Definition at line 458 of file securimage.php.

Securimage::$bgimg
protected

Definition at line 543 of file securimage.php.

Securimage::$captcha_code
protected

Definition at line 577 of file securimage.php.

Securimage::$captcha_type = self::SI_CAPTCHA_STRING

Definition at line 425 of file securimage.php.

Securimage::$case_sensitive = false

Definition at line 284 of file securimage.php.

Referenced by createCode(), and doImage().

Securimage::$charset = 'ABCDEFGHKLMNPRSTUVWYZabcdefghklmnprstuvwyz23456789'

Definition at line 289 of file securimage.php.

Securimage::$code_display
protected

Definition at line 560 of file securimage.php.

Referenced by saveCodeToDatabase(), and saveData().

Securimage::$code_length = 6

Definition at line 279 of file securimage.php.

Referenced by generateCode().

Securimage::$database_driver = self::SI_DRIVER_SQLITE3

Definition at line 367 of file securimage.php.

Securimage::$database_file

Definition at line 418 of file securimage.php.

Referenced by getDsn().

Securimage::$database_host = 'localhost'

Definition at line 376 of file securimage.php.

Securimage::$database_name = ''

Definition at line 400 of file securimage.php.

Securimage::$database_pass = ''

Definition at line 392 of file securimage.php.

Securimage::$database_table = 'captcha_codes'

Definition at line 409 of file securimage.php.

Securimage::$database_user = ''

Definition at line 384 of file securimage.php.

Securimage::$degrade_audio

Definition at line 519 of file securimage.php.

Securimage::$display_value

Definition at line 570 of file securimage.php.

Referenced by doImage().

Securimage::$expiry_time = 900

Definition at line 294 of file securimage.php.

Securimage::$gdbgcolor
protected

Definition at line 608 of file securimage.php.

Securimage::$gdlinecolor
protected

Definition at line 610 of file securimage.php.

Securimage::$gdsignaturecolor
protected

Definition at line 611 of file securimage.php.

Securimage::$gdtextcolor
protected

Definition at line 609 of file securimage.php.

Securimage::$im
protected

Definition at line 541 of file securimage.php.

Securimage::$image_bg_color = '#ffffff'

Definition at line 247 of file securimage.php.

Securimage::$image_height = 80

Definition at line 236 of file securimage.php.

Referenced by distortedCopy().

Securimage::$image_signature = ''

Definition at line 329 of file securimage.php.

Securimage::$image_type = self::SI_IMAGE_PNG

Definition at line 241 of file securimage.php.

Securimage::$image_width = 215

Definition at line 231 of file securimage.php.

Referenced by distortedCopy(), and drawLines().

Securimage::$iscale = 5
protected

Definition at line 544 of file securimage.php.

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

Securimage::$line_color = '#707070'

Definition at line 257 of file securimage.php.

Securimage::$namespace

Definition at line 442 of file securimage.php.

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

Securimage::$no_exit
protected

Definition at line 584 of file securimage.php.

Securimage::$no_session
protected

Definition at line 591 of file securimage.php.

Securimage::$noise_color = '#707070'

Definition at line 262 of file securimage.php.

Securimage::$noise_level = 2

Definition at line 323 of file securimage.php.

Referenced by drawNoise().

Securimage::$num_lines = 5

Definition at line 318 of file securimage.php.

Referenced by drawLines().

Securimage::$pdo_conn
protected

Definition at line 605 of file securimage.php.

Referenced by openDatabase().

Securimage::$perturbation = 0.85

Definition at line 313 of file securimage.php.

Securimage::$securimage_path = null

Definition at line 546 of file securimage.php.

Securimage::$send_headers
protected

Definition at line 598 of file securimage.php.

Securimage::$session_name = null

Definition at line 301 of file securimage.php.

Securimage::$signature_color = '#707070'

Definition at line 334 of file securimage.php.

Securimage::$signature_font

Definition at line 339 of file securimage.php.

Securimage::$sqlite_database

Definition at line 464 of file securimage.php.

Securimage::$text_color = '#707070'

Definition at line 252 of file securimage.php.

Securimage::$text_transparency_percentage = 20

Definition at line 268 of file securimage.php.

Securimage::$tmpimg
protected

Definition at line 542 of file securimage.php.

Securimage::$ttf_file

Definition at line 448 of file securimage.php.

Referenced by __construct().

Securimage::$use_database = false

Definition at line 358 of file securimage.php.

Securimage::$use_sqlite_db = false

Definition at line 348 of file securimage.php.

Securimage::$use_transparent_text = true

Definition at line 273 of file securimage.php.

Securimage::$use_wordlist = false

Definition at line 307 of file securimage.php.

Securimage::$wordlist_file

Definition at line 453 of file securimage.php.

const Securimage::SI_CAPTCHA_MATHEMATIC = 1

Definition at line 196 of file securimage.php.

const Securimage::SI_CAPTCHA_STRING = 0

Definition at line 191 of file securimage.php.

const Securimage::SI_CAPTCHA_WORDS = 2

Definition at line 201 of file securimage.php.

const Securimage::SI_DRIVER_MYSQL = 'mysql'

Definition at line 208 of file securimage.php.

const Securimage::SI_DRIVER_PGSQL = 'pgsql'

Definition at line 215 of file securimage.php.

const Securimage::SI_DRIVER_SQLITE3 = 'sqlite'

Definition at line 222 of file securimage.php.

const Securimage::SI_IMAGE_GIF = 3

Definition at line 185 of file securimage.php.

const Securimage::SI_IMAGE_JPEG = 1

Definition at line 175 of file securimage.php.

const Securimage::SI_IMAGE_PNG = 2

Definition at line 180 of file securimage.php.


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