ILIAS  release_4-3 Revision
 All Data Structures Namespaces Files Functions Variables Groups Pages
securimage.php
Go to the documentation of this file.
1 <?php
2 
3 // error_reporting(E_ALL); ini_set('display_errors', 1); // uncomment this line for debugging
4 
123 {
124  // All of the public variables below are securimage options
125  // They can be passed as an array to the Securimage constructor, set below,
126  // or set from securimage_show.php and securimage_play.php
127 
132  const SI_IMAGE_JPEG = 1;
137  const SI_IMAGE_PNG = 2;
142  const SI_IMAGE_GIF = 3;
143 
148  const SI_CAPTCHA_STRING = 0;
154 
159  public $image_width = 215;
164  public $image_height = 80;
170 
175  public $image_bg_color = '#ffffff';
180  public $text_color = '#707070';
185  public $line_color = '#707070';
190  public $noise_color = '#707070';
191 
201  public $use_transparent_text = false;
202 
207  public $code_length = 6;
212  public $case_sensitive = false;
217  public $charset = 'ABCDEFGHKLMNPRSTUVWYZabcdefghklmnprstuvwyz23456789';
222  public $expiry_time = 900;
223 
229  public $session_name = null;
230 
235  public $use_wordlist = false;
236 
241  public $perturbation = 0.75;
246  public $num_lines = 8;
251  public $noise_level = 0;
252 
257  public $image_signature = '';
262  public $signature_color = '#707070';
268 
273  public $use_sqlite_db = false;
274 
281 
297  public $namespace;
298 
303  public $ttf_file;
326  public $audio_path;
327 
328 
329 
330  protected $im;
331  protected $tmpimg;
332  protected $bgimg;
333  protected $iscale = 5;
334 
335  protected $securimage_path = null;
336 
337  protected $code;
338  protected $code_display;
339 
340  protected $captcha_code;
341  protected $sqlite_handle;
342 
343  protected $gdbgcolor;
344  protected $gdtextcolor;
345  protected $gdlinecolor;
346  protected $gdsignaturecolor;
347 
364  public function __construct($options = array())
365  {
366  $this->securimage_path = dirname(__FILE__);
367 
368  if (is_array($options) && sizeof($options) > 0) {
369  foreach($options as $prop => $val) {
370  $this->$prop = $val;
371  }
372  }
373 
374  $this->image_bg_color = $this->initColor($this->image_bg_color, '#ffffff');
375  $this->text_color = $this->initColor($this->text_color, '#616161');
376  $this->line_color = $this->initColor($this->line_color, '#616161');
377  $this->noise_color = $this->initColor($this->noise_color, '#616161');
378  $this->signature_color = $this->initColor($this->signature_color, '#616161');
379 
380  if ($this->ttf_file == null) {
381  $this->ttf_file = $this->securimage_path . '/AHGBold.ttf';
382  }
383 
384  $this->signature_font = $this->ttf_file;
385 
386  if ($this->wordlist_file == null) {
387  $this->wordlist_file = $this->securimage_path . '/words/words.txt';
388  }
389 
390  if ($this->sqlite_database == null) {
391  $this->sqlite_database = $this->securimage_path . '/database/securimage.sqlite';
392  }
393 
394  if ($this->audio_path == null) {
395  $this->audio_path = $this->securimage_path . '/audio/';
396  }
397 
398  if ($this->code_length == null || $this->code_length < 1) {
399  $this->code_length = 6;
400  }
401 
402  if ($this->perturbation == null || !is_numeric($this->perturbation)) {
403  $this->perturbation = 0.75;
404  }
405 
406  if ($this->namespace == null || !is_string($this->namespace)) {
407  $this->namespace = 'default';
408  }
409 
410  // Initialize session or attach to existing
411  if ( session_id() == '' ) { // no session has been started yet, which is needed for validation
412  if ($this->session_name != null && trim($this->session_name) != '') {
413  session_name(trim($this->session_name)); // set session name if provided
414  }
415  session_start();
416  }
417  }
418 
423  public static function getPath()
424  {
425  return dirname(__FILE__);
426  }
427 
441  public function show($background_image = '')
442  {
443  if($background_image != '' && is_readable($background_image)) {
444  $this->bgimg = $background_image;
445  }
446 
447  $this->doImage();
448  }
449 
463  public function check($code)
464  {
465  $this->code_entered = $code;
466  $this->validate();
467  return $this->correct_code;
468  }
469 
479  public function outputAudioFile()
480  {
481  $ext = 'wav'; // force wav - mp3 is insecure
482 
483  header("Content-Disposition: attachment; filename=\"securimage_audio.{$ext}\"");
484  header('Cache-Control: no-store, no-cache, must-revalidate');
485  header('Expires: Sun, 1 Jan 2000 12:00:00 GMT');
486  header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . 'GMT');
487  header('Content-type: audio/x-wav');
488 
489  $audio = $this->getAudibleCode($ext);
490 
491  header('Content-Length: ' . strlen($audio));
492 
493  echo $audio;
494  exit;
495  }
496 
500  protected function doImage()
501  {
502  if( ($this->use_transparent_text == true || $this->bgimg != '') && function_exists('imagecreatetruecolor')) {
503  $imagecreate = 'imagecreatetruecolor';
504  } else {
505  $imagecreate = 'imagecreate';
506  }
507 
508  $this->im = $imagecreate($this->image_width, $this->image_height);
509  $this->tmpimg = $imagecreate($this->image_width * $this->iscale, $this->image_height * $this->iscale);
510 
511  $this->allocateColors();
512  imagepalettecopy($this->tmpimg, $this->im);
513 
514  $this->setBackground();
515 
516  $this->createCode();
517 
518  if ($this->noise_level > 0) {
519  $this->drawNoise();
520  }
521 
522  $this->drawWord();
523 
524  if ($this->perturbation > 0 && is_readable($this->ttf_file)) {
525  $this->distortedCopy();
526  }
527 
528  if ($this->num_lines > 0) {
529  $this->drawLines();
530  }
531 
532  if (trim($this->image_signature) != '') {
533  $this->addSignature();
534  }
535 
536  $this->output();
537  }
538 
542  protected function allocateColors()
543  {
544  // allocate bg color first for imagecreate
545  $this->gdbgcolor = imagecolorallocate($this->im,
546  $this->image_bg_color->r,
547  $this->image_bg_color->g,
548  $this->image_bg_color->b);
549 
550  $alpha = intval($this->text_transparency_percentage / 100 * 127);
551 
552  if ($this->use_transparent_text == true) {
553  $this->gdtextcolor = imagecolorallocatealpha($this->im,
554  $this->text_color->r,
555  $this->text_color->g,
556  $this->text_color->b,
557  $alpha);
558  $this->gdlinecolor = imagecolorallocatealpha($this->im,
559  $this->line_color->r,
560  $this->line_color->g,
561  $this->line_color->b,
562  $alpha);
563  $this->gdnoisecolor = imagecolorallocatealpha($this->im,
564  $this->noise_color->r,
565  $this->noise_color->g,
566  $this->noise_color->b,
567  $alpha);
568  } else {
569  $this->gdtextcolor = imagecolorallocate($this->im,
570  $this->text_color->r,
571  $this->text_color->g,
572  $this->text_color->b);
573  $this->gdlinecolor = imagecolorallocate($this->im,
574  $this->line_color->r,
575  $this->line_color->g,
576  $this->line_color->b);
577  $this->gdnoisecolor = imagecolorallocate($this->im,
578  $this->noise_color->r,
579  $this->noise_color->g,
580  $this->noise_color->b);
581  }
582 
583  $this->gdsignaturecolor = imagecolorallocate($this->im,
584  $this->signature_color->r,
585  $this->signature_color->g,
586  $this->signature_color->b);
587 
588  }
589 
593  protected function setBackground()
594  {
595  // set background color of image by drawing a rectangle since imagecreatetruecolor doesn't set a bg color
596  imagefilledrectangle($this->im, 0, 0,
597  $this->image_width, $this->image_height,
598  $this->gdbgcolor);
599  imagefilledrectangle($this->tmpimg, 0, 0,
600  $this->image_width * $this->iscale, $this->image_height * $this->iscale,
601  $this->gdbgcolor);
602 
603  if ($this->bgimg == '') {
604  if ($this->background_directory != null &&
605  is_dir($this->background_directory) &&
606  is_readable($this->background_directory))
607  {
608  $img = $this->getBackgroundFromDirectory();
609  if ($img != false) {
610  $this->bgimg = $img;
611  }
612  }
613  }
614 
615  if ($this->bgimg == '') {
616  return;
617  }
618 
619  $dat = @getimagesize($this->bgimg);
620  if($dat == false) {
621  return;
622  }
623 
624  switch($dat[2]) {
625  case 1: $newim = @imagecreatefromgif($this->bgimg); break;
626  case 2: $newim = @imagecreatefromjpeg($this->bgimg); break;
627  case 3: $newim = @imagecreatefrompng($this->bgimg); break;
628  default: return;
629  }
630 
631  if(!$newim) return;
632 
633  imagecopyresized($this->im, $newim, 0, 0, 0, 0,
634  $this->image_width, $this->image_height,
635  imagesx($newim), imagesy($newim));
636  }
637 
641  protected function getBackgroundFromDirectory()
642  {
643  $images = array();
644 
645  if ( ($dh = opendir($this->background_directory)) !== false) {
646  while (($file = readdir($dh)) !== false) {
647  if (preg_match('/(jpg|gif|png)$/i', $file)) $images[] = $file;
648  }
649 
650  closedir($dh);
651 
652  if (sizeof($images) > 0) {
653  return rtrim($this->background_directory, '/') . '/' . $images[rand(0, sizeof($images)-1)];
654  }
655  }
656 
657  return false;
658  }
659 
663  protected function createCode()
664  {
665  $this->code = false;
666 
667  switch($this->captcha_type) {
668  case self::SI_CAPTCHA_MATHEMATIC:
669  {
670  $signs = array('+', '-', 'x');
671  $left = rand(1, 10);
672  $right = rand(1, 5);
673  $sign = $signs[rand(0, 2)];
674 
675  switch($sign) {
676  case 'x': $c = $left * $right; break;
677  case '-': $c = $left - $right; break;
678  default: $c = $left + $right; break;
679  }
680 
681  $this->code = $c;
682  $this->code_display = "$left $sign $right";
683  break;
684  }
685 
686  default:
687  {
688  if ($this->use_wordlist && is_readable($this->wordlist_file)) {
689  $this->code = $this->readCodeFromFile();
690  }
691 
692  if ($this->code == false) {
693  $this->code = $this->generateCode($this->code_length);
694  }
695 
696  $this->code_display = $this->code;
697  $this->code = ($this->case_sensitive) ? $this->code : strtolower($this->code);
698  } // default
699  }
700 
701  $this->saveData();
702  }
703 
707  protected function drawWord()
708  {
709  $width2 = $this->image_width * $this->iscale;
710  $height2 = $this->image_height * $this->iscale;
711 
712  if (!is_readable($this->ttf_file)) {
713  imagestring($this->im, 4, 10, ($this->image_height / 2) - 5, 'Failed to load TTF font file!', $this->gdtextcolor);
714  } else {
715  if ($this->perturbation > 0) {
716  $font_size = $height2 * .4;
717  $bb = imageftbbox($font_size, 0, $this->ttf_file, $this->code_display);
718  $tx = $bb[4] - $bb[0];
719  $ty = $bb[5] - $bb[1];
720  $x = floor($width2 / 2 - $tx / 2 - $bb[0]);
721  $y = round($height2 / 2 - $ty / 2 - $bb[1]);
722 
723  imagettftext($this->tmpimg, $font_size, 0, $x, $y, $this->gdtextcolor, $this->ttf_file, $this->code_display);
724  } else {
725  $font_size = $this->image_height * .4;
726  $bb = imageftbbox($font_size, 0, $this->ttf_file, $this->code_display);
727  $tx = $bb[4] - $bb[0];
728  $ty = $bb[5] - $bb[1];
729  $x = floor($this->image_width / 2 - $tx / 2 - $bb[0]);
730  $y = round($this->image_height / 2 - $ty / 2 - $bb[1]);
731 
732  imagettftext($this->im, $font_size, 0, $x, $y, $this->gdtextcolor, $this->ttf_file, $this->code_display);
733  }
734  }
735 
736  // DEBUG
737  //$this->im = $this->tmpimg;
738  //$this->output();
739 
740  }
741 
745  protected function distortedCopy()
746  {
747  $numpoles = 3; // distortion factor
748  // make array of poles AKA attractor points
749  for ($i = 0; $i < $numpoles; ++ $i) {
750  $px[$i] = rand($this->image_width * 0.2, $this->image_width * 0.8);
751  $py[$i] = rand($this->image_height * 0.2, $this->image_height * 0.8);
752  $rad[$i] = rand($this->image_height * 0.2, $this->image_height * 0.8);
753  $tmp = ((- $this->frand()) * 0.15) - .15;
754  $amp[$i] = $this->perturbation * $tmp;
755  }
756 
757  $bgCol = imagecolorat($this->tmpimg, 0, 0);
758  $width2 = $this->iscale * $this->image_width;
759  $height2 = $this->iscale * $this->image_height;
760  imagepalettecopy($this->im, $this->tmpimg); // copy palette to final image so text colors come across
761  // loop over $img pixels, take pixels from $tmpimg with distortion field
762  for ($ix = 0; $ix < $this->image_width; ++ $ix) {
763  for ($iy = 0; $iy < $this->image_height; ++ $iy) {
764  $x = $ix;
765  $y = $iy;
766  for ($i = 0; $i < $numpoles; ++ $i) {
767  $dx = $ix - $px[$i];
768  $dy = $iy - $py[$i];
769  if ($dx == 0 && $dy == 0) {
770  continue;
771  }
772  $r = sqrt($dx * $dx + $dy * $dy);
773  if ($r > $rad[$i]) {
774  continue;
775  }
776  $rscale = $amp[$i] * sin(3.14 * $r / $rad[$i]);
777  $x += $dx * $rscale;
778  $y += $dy * $rscale;
779  }
780  $c = $bgCol;
781  $x *= $this->iscale;
782  $y *= $this->iscale;
783  if ($x >= 0 && $x < $width2 && $y >= 0 && $y < $height2) {
784  $c = imagecolorat($this->tmpimg, $x, $y);
785  }
786  if ($c != $bgCol) { // only copy pixels of letters to preserve any background image
787  imagesetpixel($this->im, $ix, $iy, $c);
788  }
789  }
790  }
791  }
792 
796  protected function drawLines()
797  {
798  for ($line = 0; $line < $this->num_lines; ++ $line) {
799  $x = $this->image_width * (1 + $line) / ($this->num_lines + 1);
800  $x += (0.5 - $this->frand()) * $this->image_width / $this->num_lines;
801  $y = rand($this->image_height * 0.1, $this->image_height * 0.9);
802 
803  $theta = ($this->frand() - 0.5) * M_PI * 0.7;
804  $w = $this->image_width;
805  $len = rand($w * 0.4, $w * 0.7);
806  $lwid = rand(0, 2);
807 
808  $k = $this->frand() * 0.6 + 0.2;
809  $k = $k * $k * 0.5;
810  $phi = $this->frand() * 6.28;
811  $step = 0.5;
812  $dx = $step * cos($theta);
813  $dy = $step * sin($theta);
814  $n = $len / $step;
815  $amp = 1.5 * $this->frand() / ($k + 5.0 / $len);
816  $x0 = $x - 0.5 * $len * cos($theta);
817  $y0 = $y - 0.5 * $len * sin($theta);
818 
819  $ldx = round(- $dy * $lwid);
820  $ldy = round($dx * $lwid);
821 
822  for ($i = 0; $i < $n; ++ $i) {
823  $x = $x0 + $i * $dx + $amp * $dy * sin($k * $i * $step + $phi);
824  $y = $y0 + $i * $dy - $amp * $dx * sin($k * $i * $step + $phi);
825  imagefilledrectangle($this->im, $x, $y, $x + $lwid, $y + $lwid, $this->gdlinecolor);
826  }
827  }
828  }
829 
833  protected function drawNoise()
834  {
835  if ($this->noise_level > 10) {
836  $noise_level = 10;
837  } else {
839  }
840 
841  $t0 = microtime(true);
842 
843  $noise_level *= 125; // an arbitrary number that works well on a 1-10 scale
844 
845  $points = $this->image_width * $this->image_height * $this->iscale;
846  $height = $this->image_height * $this->iscale;
847  $width = $this->image_width * $this->iscale;
848  for ($i = 0; $i < $noise_level; ++$i) {
849  $x = rand(10, $width);
850  $y = rand(10, $height);
851  $size = rand(7, 10);
852  if ($x - $size <= 0 && $y - $size <= 0) continue; // dont cover 0,0 since it is used by imagedistortedcopy
853  imagefilledarc($this->tmpimg, $x, $y, $size, $size, 0, 360, $this->gdnoisecolor, IMG_ARC_PIE);
854  }
855 
856  $t1 = microtime(true);
857 
858  $t = $t1 - $t0;
859 
860  /*
861  // DEBUG
862  imagestring($this->tmpimg, 5, 25, 30, "$t", $this->gdnoisecolor);
863  header('content-type: image/png');
864  imagepng($this->tmpimg);
865  exit;
866  */
867  }
868 
872  protected function addSignature()
873  {
874  $bbox = imagettfbbox(10, 0, $this->signature_font, $this->image_signature);
875  $textlen = $bbox[2] - $bbox[0];
876  $x = $this->image_width - $textlen - 5;
877  $y = $this->image_height - 3;
878 
879  imagettftext($this->im, 10, 0, $x, $y, $this->gdsignaturecolor, $this->signature_font, $this->image_signature);
880  }
881 
885  protected function output()
886  {
887  header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
888  header("Last-Modified: " . gmdate("D, d M Y H:i:s") . "GMT");
889  header("Cache-Control: no-store, no-cache, must-revalidate");
890  header("Cache-Control: post-check=0, pre-check=0", false);
891  header("Pragma: no-cache");
892 
893  switch ($this->image_type) {
894  case self::SI_IMAGE_JPEG:
895  header("Content-Type: image/jpeg");
896  imagejpeg($this->im, null, 90);
897  break;
898  case self::SI_IMAGE_GIF:
899  header("Content-Type: image/gif");
900  imagegif($this->im);
901  break;
902  default:
903  header("Content-Type: image/png");
904  imagepng($this->im);
905  break;
906  }
907 
908  imagedestroy($this->im);
909  exit();
910  }
911 
916  protected function getAudibleCode($format = 'wav')
917  {
918  // override any format other than wav for now
919  // this is due to security issues with MP3 files
920  $format = 'wav';
921 
922  $letters = array();
923  $code = $this->getCode();
924 
925  if ($code == '') {
926  $this->createCode();
927  $code = $this->getCode();
928  }
929 
930  for($i = 0; $i < strlen($code); ++$i) {
931  $letters[] = $code{$i};
932  }
933 
934  if ($format == 'mp3') {
935  return $this->generateMP3($letters);
936  } else {
937  return $this->generateWAV($letters);
938  }
939  }
940 
944  protected function readCodeFromFile()
945  {
946  $fp = @fopen($this->wordlist_file, 'rb');
947  if (!$fp) return false;
948 
949  $fsize = filesize($this->wordlist_file);
950  if ($fsize < 128) return false; // too small of a list to be effective
951 
952  fseek($fp, rand(0, $fsize - 64), SEEK_SET); // seek to a random position of file from 0 to filesize-64
953  $data = fread($fp, 64); // read a chunk from our random position
954  fclose($fp);
955  $data = preg_replace("/\r?\n/", "\n", $data);
956 
957  $start = @strpos($data, "\n", rand(0, 56)) + 1; // random start position
958  $end = @strpos($data, "\n", $start); // find end of word
959 
960  if ($start === false) {
961  return false;
962  } else if ($end === false) {
963  $end = strlen($data);
964  }
965 
966  return strtolower(substr($data, $start, $end - $start)); // return a line of the file
967  }
968 
972  protected function generateCode()
973  {
974  $code = '';
975 
976  for($i = 1, $cslen = strlen($this->charset); $i <= $this->code_length; ++$i) {
977  $code .= $this->charset{rand(0, $cslen - 1)};
978  }
979 
980  //return 'testing'; // debug, set the code to given string
981 
982  return $code;
983  }
984 
989  protected function validate()
990  {
991  $code = $this->getCode();
992  // returns stored code, or an empty string if no stored code was found
993  // checks the session and sqlite database if enabled
994 
995  if ($this->case_sensitive == false && preg_match('/[A-Z]/', $code)) {
996  // case sensitive was set from securimage_show.php but not in class
997  // the code saved in the session has capitals so set case sensitive to true
998  $this->case_sensitive = true;
999  }
1000 
1001  $code_entered = trim( (($this->case_sensitive) ? $this->code_entered
1002  : strtolower($this->code_entered))
1003  );
1004  $this->correct_code = false;
1005 
1006  if ($code != '') {
1007  if ($code == $code_entered) {
1008  $this->correct_code = true;
1009  $_SESSION['securimage_code_value'][$this->namespace] = '';
1010  $_SESSION['securimage_code_ctime'][$this->namespace] = '';
1011  $this->clearCodeFromDatabase();
1012  }
1013  }
1014  }
1015 
1019  protected function getCode()
1020  {
1021  $code = '';
1022 
1023  if (isset($_SESSION['securimage_code_value'][$this->namespace]) &&
1024  trim($_SESSION['securimage_code_value'][$this->namespace]) != '') {
1025  if ($this->isCodeExpired(
1026  $_SESSION['securimage_code_ctime'][$this->namespace]) == false) {
1027  $code = $_SESSION['securimage_code_value'][$this->namespace];
1028  }
1029  } else if ($this->use_sqlite_db == true && function_exists('sqlite_open')) {
1030  // no code in session - may mean user has cookies turned off
1031  $this->openDatabase();
1032  $code = $this->getCodeFromDatabase();
1033  } else { /* no code stored in session or sqlite database, validation will fail */ }
1034 
1035  return $code;
1036  }
1037 
1041  protected function saveData()
1042  {
1043  $_SESSION['securimage_code_value'][$this->namespace] = $this->code;
1044  $_SESSION['securimage_code_ctime'][$this->namespace] = time();
1045 
1046  $this->saveCodeToDatabase();
1047  }
1048 
1052  protected function saveCodeToDatabase()
1053  {
1054  $success = false;
1055 
1056  $this->openDatabase();
1057 
1058  if ($this->use_sqlite_db && $this->sqlite_handle !== false) {
1059  $ip = $_SERVER['REMOTE_ADDR'];
1060  $time = time();
1061  $code = $_SESSION['securimage_code_value'][$this->namespace]; // if cookies are disabled the session still exists at this point
1062  $success = sqlite_query($this->sqlite_handle,
1063  "INSERT OR REPLACE INTO codes(ip, code, namespace, created)
1064  VALUES('$ip', '$code', '{$this->namespace}', $time)");
1065  }
1066 
1067  return $success !== false;
1068  }
1069 
1073  protected function openDatabase()
1074  {
1075  $this->sqlite_handle = false;
1076 
1077  if ($this->use_sqlite_db && function_exists('sqlite_open')) {
1078  $this->sqlite_handle = sqlite_open($this->sqlite_database, 0666, $error);
1079 
1080  if ($this->sqlite_handle !== false) {
1081  $res = sqlite_query($this->sqlite_handle, "PRAGMA table_info(codes)");
1082  if (sqlite_num_rows($res) == 0) {
1083  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)");
1084  }
1085  }
1086 
1087  return $this->sqlite_handle != false;
1088  }
1089 
1090  return $this->sqlite_handle;
1091  }
1092 
1096  protected function getCodeFromDatabase()
1097  {
1098  $code = '';
1099 
1100  if ($this->use_sqlite_db && $this->sqlite_handle !== false) {
1101  $ip = $_SERVER['REMOTE_ADDR'];
1102  $ns = sqlite_escape_string($this->namespace);
1103 
1104  $res = sqlite_query($this->sqlite_handle, "SELECT * FROM codes WHERE ip = '$ip' AND namespace = '$ns'");
1105  if ($res && sqlite_num_rows($res) > 0) {
1106  $res = sqlite_fetch_array($res);
1107 
1108  if ($this->isCodeExpired($res['created']) == false) {
1109  $code = $res['code'];
1110  }
1111  }
1112  }
1113  return $code;
1114  }
1115 
1119  protected function clearCodeFromDatabase()
1120  {
1121  if (is_resource($this->sqlite_handle)) {
1122  $ip = $_SERVER['REMOTE_ADDR'];
1123  $ns = sqlite_escape_string($this->namespace);
1124 
1125  sqlite_query($this->sqlite_handle, "DELETE FROM codes WHERE ip = '$ip' AND namespace = '$ns'");
1126  }
1127  }
1128 
1132  protected function purgeOldCodesFromDatabase()
1133  {
1134  if ($this->use_sqlite_db && $this->sqlite_handle !== false) {
1135  $now = time();
1136  $limit = (!is_numeric($this->expiry_time) || $this->expiry_time < 1) ? 86400 : $this->expiry_time;
1137 
1138  sqlite_query($this->sqlite_handle, "DELETE FROM codes WHERE $now - created > $limit");
1139  }
1140  }
1141 
1146  protected function isCodeExpired($creation_time)
1147  {
1148  $expired = true;
1149 
1150  if (!is_numeric($this->expiry_time) || $this->expiry_time < 1) {
1151  $expired = false;
1152  } else if (time() - $creation_time < $this->expiry_time) {
1153  $expired = false;
1154  }
1155 
1156  return $expired;
1157  }
1158 
1165  protected function generateMP3()
1166  {
1167  return false;
1168  }
1169 
1176  protected function generateWAV($letters)
1177  {
1178  $data_len = 0;
1179  $files = array();
1180  $out_data = '';
1181  $out_channels = 0;
1182  $out_samplert = 0;
1183  $out_bpersample = 0;
1184  $numSamples = 0;
1185  $removeChunks = array('LIST', 'DISP', 'NOTE');
1186 
1187  for ($i = 0; $i < sizeof($letters); ++$i) {
1188  $letter = $letters[$i];
1189  $filename = $this->audio_path . strtoupper($letter) . '.wav';
1190  $file = array();
1191  $data = @file_get_contents($filename);
1192 
1193  if ($data === false) {
1194  // echo "Failed to read $filename";
1195  return $this->audioError();
1196  }
1197 
1198  $header = substr($data, 0, 36);
1199  $info = unpack('NChunkID/VChunkSize/NFormat/NSubChunk1ID/'
1200  .'VSubChunk1Size/vAudioFormat/vNumChannels/'
1201  .'VSampleRate/VByteRate/vBlockAlign/vBitsPerSample',
1202  $header);
1203 
1204  $dataPos = strpos($data, 'data');
1205  $out_channels = $info['NumChannels'];
1206  $out_samplert = $info['SampleRate'];
1207  $out_bpersample = $info['BitsPerSample'];
1208 
1209  if ($dataPos === false) {
1210  // wav file with no data?
1211  // echo "Failed to find DATA segment in $filename";
1212  return $this->audioError();
1213  }
1214 
1215  if ($info['AudioFormat'] != 1) {
1216  // only work with PCM audio
1217  // echo "$filename was not PCM audio, only PCM is supported";
1218  return $this->audioError();
1219  }
1220 
1221  if ($info['SubChunk1Size'] != 16 && $info['SubChunk1Size'] != 18) {
1222  // probably unsupported extension
1223  // echo "Bad SubChunk1Size in $filename - Size was {$info['SubChunk1Size']}";
1224  return $this->audioError();
1225  }
1226 
1227  if ($info['SubChunk1Size'] > 16) {
1228  $header .= substr($data, 36, $info['SubChunk1Size'] - 16);
1229  }
1230 
1231  if ($i == 0) {
1232  // create the final file's header, size will be adjusted later
1233  $out_data = $header . 'data';
1234  }
1235 
1236  $removed = 0;
1237 
1238  foreach($removeChunks as $chunk) {
1239  $chunkPos = strpos($data, $chunk);
1240  if ($chunkPos !== false) {
1241  $listSize = unpack('VSize', substr($data, $chunkPos + 4, 4));
1242 
1243  $data = substr($data, 0, $chunkPos) .
1244  substr($data, $chunkPos + 8 + $listSize['Size']);
1245 
1246  $removed += $listSize['Size'] + 8;
1247  }
1248  }
1249 
1250  $dataSize = unpack('VSubchunk2Size', substr($data, $dataPos + 4, 4));
1251  $dataSize['Subchunk2Size'] -= $removed;
1252  $out_data .= substr($data, $dataPos + 8, $dataSize['Subchunk2Size'] * ($out_bpersample / 8));
1253  $numSamples += $dataSize['Subchunk2Size'];
1254  }
1255 
1256  $filesize = strlen($out_data);
1257  $chunkSize = $filesize - 8;
1258  $dataCSize = $numSamples;
1259 
1260  $out_data = substr_replace($out_data, pack('V', $chunkSize), 4, 4);
1261  $out_data = substr_replace($out_data, pack('V', $numSamples), 40 + ($info['SubChunk1Size'] - 16), 4);
1262 
1263  $this->scrambleAudioData($out_data, 'wav');
1264 
1265  return $out_data;
1266  }
1267 
1273  protected function scrambleAudioData(&$data, $format)
1274  {
1275  $start = strpos($data, 'data') + 4; // look for "data" indicator
1276  if ($start === false) $start = 44; // if not found assume 44 byte header
1277 
1278  $start += rand(1, 4); // randomize starting offset
1279  $datalen = strlen($data) - $start;
1280  $step = 1;
1281 
1282  for ($i = $start; $i < $datalen; $i += $step) {
1283  $ch = ord($data{$i});
1284  if ($ch == 0 || $ch == 255) continue;
1285 
1286  if ($ch < 16 || $ch > 239) {
1287  $ch += rand(-6, 6);
1288  } else {
1289  $ch += rand(-12, 12);
1290  }
1291 
1292  if ($ch < 0) $ch = 0; else if ($ch > 255) $ch = 255;
1293 
1294  $data{$i} = chr($ch);
1295 
1296  $step = rand(1,4);
1297  }
1298 
1299  return $data;
1300  }
1301 
1307  protected function audioError()
1308  {
1309  return @file_get_contents(dirname(__FILE__) . '/audio/error.wav');
1310  }
1311 
1312  function frand()
1313  {
1314  return 0.0001 * rand(0,9999);
1315  }
1316 
1322  protected function initColor($color, $default)
1323  {
1324  if ($color == null) {
1325  return new Securimage_Color($default);
1326  } else if (is_string($color)) {
1327  try {
1328  return new Securimage_Color($color);
1329  } catch(Exception $e) {
1330  return new Securimage_Color($default);
1331  }
1332  } else if (is_array($color) && sizeof($color) == 3) {
1333  return new Securimage_Color($color[0], $color[1], $color[2]);
1334  } else {
1335  return new Securimage_Color($default);
1336  }
1337  }
1338 }
1339 
1340 
1351 {
1352  public $r;
1353  public $g;
1354  public $b;
1355 
1367  public function __construct($color = '#ffffff')
1368  {
1369  $args = func_get_args();
1370 
1371  if (sizeof($args) == 0) {
1372  $this->r = 255;
1373  $this->g = 255;
1374  $this->b = 255;
1375  } else if (sizeof($args) == 1) {
1376  // set based on html code
1377  if (substr($color, 0, 1) == '#') {
1378  $color = substr($color, 1);
1379  }
1380 
1381  if (strlen($color) != 3 && strlen($color) != 6) {
1382  throw new InvalidArgumentException(
1383  'Invalid HTML color code passed to Securimage_Color'
1384  );
1385  }
1386 
1387  $this->constructHTML($color);
1388  } else if (sizeof($args) == 3) {
1389  $this->constructRGB($args[0], $args[1], $args[2]);
1390  } else {
1391  throw new InvalidArgumentException(
1392  'Securimage_Color constructor expects 0, 1 or 3 arguments; ' . sizeof($args) . ' given'
1393  );
1394  }
1395  }
1396 
1403  protected function constructRGB($red, $green, $blue)
1404  {
1405  if ($red < 0) $red = 0;
1406  if ($red > 255) $red = 255;
1407  if ($green < 0) $green = 0;
1408  if ($green > 255) $green = 255;
1409  if ($blue < 0) $blue = 0;
1410  if ($blue > 255) $blue = 255;
1411 
1412  $this->r = $red;
1413  $this->g = $green;
1414  $this->b = $blue;
1415  }
1416 
1421  protected function constructHTML($color)
1422  {
1423  if (strlen($color) == 3) {
1424  $red = str_repeat(substr($color, 0, 1), 2);
1425  $green = str_repeat(substr($color, 1, 1), 2);
1426  $blue = str_repeat(substr($color, 2, 1), 2);
1427  } else {
1428  $red = substr($color, 0, 2);
1429  $green = substr($color, 2, 2);
1430  $blue = substr($color, 4, 2);
1431  }
1432 
1433  $this->r = hexdec($red);
1434  $this->g = hexdec($green);
1435  $this->b = hexdec($blue);
1436  }
1437 }