src/Security/Controller/captchaController.php line 362

Open in your IDE?
  1. <?php
  2. namespace App\Security\Controller;
  3. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  4. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
  5. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
  6. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
  7. use Symfony\Component\Security\Core\SecurityContext;
  8. use Symfony\Component\HttpFoundation\Response;
  9. use Symfony\Component\HttpFoundation\Request;
  10. use App\Entity\SeguridadUsuario;
  11. use App\Repository\SeguridadUsuarioRepository;
  12. /**
  13. *
  14. * captcha controller.
  15. */
  16. class captchaController extends AbstractController
  17. {
  18.     /** Width of the image */
  19.     public $width  300;
  20.     /** Height of the image */
  21.     public $height 70;
  22.     /** Dictionary word file (empty for randnom text) */
  23.     public $wordsFile 'words/en.php';
  24.     /**
  25.      * Path for resource files (fonts, words, etc.)
  26.      *
  27.      * "resources" by default. For security reasons, is better move this
  28.      * directory to another location outise the web server
  29.      *
  30.      */
  31.     public $resourcesPath 'resources';
  32.     /** Min word length (for non-dictionary random text generation) */
  33.     public $minWordLength 5;
  34.     /**
  35.      * Max word length (for non-dictionary random text generation)
  36.      * 
  37.      * Used for dictionary words indicating the word-length
  38.      * for font-size modification purposes
  39.      */
  40.     public $maxWordLength 8;
  41.     /** Sessionname to store the original text */
  42.     public $session_var 'captcha';
  43.     /** Background color in RGB-array */
  44.     public $backgroundColor = array(255255255);
  45.     /** Foreground colors in RGB-array */
  46.     public $colors = array(
  47.         array(27,78,181), // blue
  48.         array(22,163,35), // green
  49.         array(214,36,7),  // red
  50.     );
  51.     /** Shadow color in RGB-array or null */
  52.     public $shadowColor null//array(0, 0, 0);
  53.     /**
  54.      * Font configuration
  55.      *
  56.      * - font: TTF file
  57.      * - spacing: relative pixel space between character
  58.      * - minSize: min font size
  59.      * - maxSize: max font size
  60.      */
  61.     public $fonts = array(
  62.         'Antykwa'  => array('spacing' => -3'minSize' => 27'maxSize' => 30'font' => 'AntykwaBold.ttf'),
  63.         'Candice'  => array('spacing' =>-1.5,'minSize' => 28'maxSize' => 31'font' => 'Candice.ttf'),
  64. //        'DingDong' => array('spacing' => -2, 'minSize' => 24, 'maxSize' => 30, 'font' => 'Ding-DongDaddyO.ttf'),
  65.         'Duality'  => array('spacing' => -2'minSize' => 30'maxSize' => 38'font' => 'Duality.ttf'),
  66. //        'Heineken' => array('spacing' => -2, 'minSize' => 24, 'maxSize' => 34, 'font' => 'Heineken.ttf'),
  67.         'Jura'     => array('spacing' => -2'minSize' => 28'maxSize' => 32'font' => 'Jura.ttf'),
  68.         'StayPuft' => array('spacing' =>-1.5,'minSize' => 28'maxSize' => 32'font' => 'StayPuft.ttf'),
  69.         'Times'    => array('spacing' => -2'minSize' => 28'maxSize' => 34'font' => 'TimesNewRomanBold.ttf'),
  70.         'VeraSans' => array('spacing' => -1'minSize' => 20'maxSize' => 28'font' => 'VeraSansBold.ttf'),
  71.     );
  72.     /** Wave configuracion in X and Y axes */
  73.     public $Yperiod    12;
  74.     public $Yamplitude 14;
  75.     public $Xperiod    11;
  76.     public $Xamplitude 5;
  77.     /** letter rotation clockwise */
  78.     public $maxRotation 8;
  79.     /**
  80.      * Internal image size factor (for better image quality)
  81.      * 1: low, 2: medium, 3: high
  82.      */
  83.     public $scale 2;
  84.     /** 
  85.      * Blur effect for better image quality (but slower image processing).
  86.      * Better image results with scale=3
  87.      */
  88.     public $blur false;
  89.     /** Debug? */
  90.     public $debug false;
  91.     
  92.     /** Image format: jpeg or png */
  93.     public $imageFormat 'jpeg';
  94.     /** GD image */
  95.     public $im;
  96.     
  97.     public function __construct($config = array()) 
  98.     {
  99.     }
  100.     public function writeAction(Request $request
  101.     {
  102.         putenv('GDFONTPATH=' realpath('.'));        
  103.         $this->wordsFile 'words/'.$request->getLocale().'.php';
  104.     
  105. //        $this->backgroundColor = array(136, 0, 6);
  106.         $this->backgroundColor = array(255255255);
  107.         $this->colors = array(
  108.             array(0,0,0), 
  109.             //array(188,161,236), 
  110.             //array(145,225,168),  
  111.         );
  112.     
  113.         return $this->CreateImage($request);
  114.     }
  115.     public function CreateImage($request
  116.     {
  117.         $ini microtime(true);
  118.         /** Initialization */
  119.         $this->ImageAllocate();
  120.         
  121.         /** Text insertion */
  122.         $text $this->GetCaptchaText();
  123.         $fontcfg  $this->fonts[array_rand($this->fonts)];
  124.         $this->WriteText($text$fontcfg);
  125.         //$_SESSION[$this->session_var] = $text;
  126.         $session $request->getSession();
  127.         $session->set('captcha_codigo'$text);
  128.         /** Transformations */
  129.         $this->WaveImage();
  130.         if ($this->blur && function_exists('imagefilter')) {
  131.             imagefilter($this->imIMG_FILTER_GAUSSIAN_BLUR);
  132.         }
  133.         $this->ReduceImage();
  134.         if ($this->debug) {
  135.             imagestring($this->im11$this->height-8,
  136.                 "$text {$fontcfg['font']} ".round((microtime(true)-$ini)*1000)."ms",
  137.                 $this->GdFgColor
  138.             );
  139.         }
  140.         /** Output */
  141.         return $this->WriteImage();
  142.         $this->Cleanup();
  143.     }
  144.     /**
  145.      * Creates the image resources
  146.      */
  147.     protected function ImageAllocate() 
  148.     {
  149.         // Cleanup
  150.         if (!empty($this->im)) {
  151.             imagedestroy($this->im);
  152.         }
  153.         $this->im imagecreatetruecolor($this->width*$this->scale$this->height*$this->scale);
  154.         // Background color
  155.         $this->GdBgColor imagecolorallocate($this->im,
  156.             $this->backgroundColor[0],
  157.             $this->backgroundColor[1],
  158.             $this->backgroundColor[2]
  159.         );
  160.         imagefilledrectangle($this->im00$this->width*$this->scale$this->height*$this->scale$this->GdBgColor);
  161.         // Foreground color
  162.         $color           $this->colors[mt_rand(0sizeof($this->colors)-1)];
  163.         $this->GdFgColor imagecolorallocate($this->im$color[0], $color[1], $color[2]);
  164.         // Shadow color
  165.         if (!empty($this->shadowColor) && is_array($this->shadowColor) && sizeof($this->shadowColor) >= 3) {
  166.             $this->GdShadowColor imagecolorallocate($this->im,
  167.                 $this->shadowColor[0],
  168.                 $this->shadowColor[1],
  169.                 $this->shadowColor[2]
  170.             );
  171.         }
  172.     }
  173.     /**
  174.      * Text generation
  175.      *
  176.      * @return string Text
  177.      */
  178.     protected function GetCaptchaText() 
  179.     {
  180.         $text $this->GetDictionaryCaptchaText();
  181.         if (!$text) {
  182.             $text $this->GetRandomCaptchaText();
  183.         }
  184.         return $text;
  185.     }
  186.     /**
  187.      * Random text generation
  188.      *
  189.      * @return string Text
  190.      */
  191.     protected function GetRandomCaptchaText($length null
  192.     {
  193.         if (empty($length)) {
  194.             $length rand($this->minWordLength$this->maxWordLength);
  195.         }
  196.         $words  "abcdefghijlmnopqrstvwyz";
  197.         $vocals "aeiou";
  198.         $text  "";
  199.         $vocal rand(01);
  200.         for ($i=0$i<$length$i++) 
  201.         {
  202.             if ($vocal
  203.             {
  204.                 $text .= substr($vocalsmt_rand(04), 1);
  205.             }
  206.             else
  207.             {
  208.                 $text .= substr($wordsmt_rand(022), 1);
  209.             }
  210.             $vocal = !$vocal;
  211.         }
  212.         return $text;
  213.     }
  214.     /**
  215.      * Random dictionary word generation
  216.      *
  217.      * @param boolean $extended Add extended "fake" words
  218.      * @return string Word
  219.      */
  220.     function GetDictionaryCaptchaText($extended false
  221.     {
  222.         if (empty($this->wordsFile)) 
  223.         {
  224.             return false;
  225.         }
  226.         // Full path of words file
  227.         if (substr($this->wordsFile01) == '/'
  228.         {
  229.             $wordsfile $this->wordsFile;
  230.         }
  231.         else
  232.         {
  233.             $wordsfile $this->resourcesPath.'/'.$this->wordsFile;
  234.         }
  235.         $fp     fopen($wordsfile"r");
  236.         $length fgets($fp);
  237.         $length strlen($length);
  238.         if (!$length
  239.         {
  240.             return false;
  241.         }
  242.         $fsize=filesize($wordsfile);
  243.         $line rand(1, ($fsize/$length)-2);
  244.         if (fseek($fp$length*$line) == -1
  245.         {
  246.             return false;
  247.         }
  248.         $text trim(fgets($fp));
  249.         fclose($fp);
  250.         /** Change ramdom volcals */
  251.         if ($extended)
  252.         {
  253.             $text   preg_split('//'$text, -1PREG_SPLIT_NO_EMPTY);
  254.             $vocals = array('a''e''i''o''u');
  255.             foreach ($text as $i => $char
  256.             {
  257.                 if (mt_rand(01) && in_array($char$vocals)) 
  258.                 {
  259.                     $text[$i] = $vocals[mt_rand(04)];
  260.                 }
  261.             }
  262.             $text implode(''$text);
  263.         }
  264.         return $text;
  265.     }
  266.     /**
  267.      * Text insertion
  268.      */
  269.     protected function WriteText($text$fontcfg = array()) {
  270.         if (empty($fontcfg)) {
  271.             // Select the font configuration
  272.             $fontcfg  $this->fonts[array_rand($this->fonts)];
  273.         }
  274.         // Full path of font file
  275.         $fontfile $this->resourcesPath.'/fonts/'.$fontcfg['font'];
  276.         /** Increase font-size for shortest words: 9% for each glyp missing */
  277.         $lettersMissing $this->maxWordLength-strlen($text);
  278.         $fontSizefactor 1+($lettersMissing*0.09);
  279.         // Text generation (char by char)
  280.         $x      20*$this->scale;
  281.         $y      round(($this->height*27/40)*$this->scale);
  282.         $length strlen($text);
  283.         for ($i=0$i<$length$i++) {
  284.             $degree   rand($this->maxRotation*-1$this->maxRotation);
  285.             $fontsize rand($fontcfg['minSize'], $fontcfg['maxSize'])*$this->scale*$fontSizefactor;
  286.             $letter   substr($text$i1);
  287.             if ($this->shadowColor) {
  288.                 $coords imagettftext($this->im$fontsize$degree,
  289.                     $x+$this->scale$y+$this->scale,
  290.                     $this->GdShadowColor$fontfile$letter);
  291.             }
  292.             $coords imagettftext($this->im$fontsize$degree,
  293.                 $x$y,
  294.                 $this->GdFgColor$fontfile$letter);
  295.             $x += ($coords[2]-$x) + ($fontcfg['spacing']*$this->scale);
  296.         }
  297.     }
  298.     /**
  299.      * Wave filter
  300.      */
  301.     protected function WaveImage() {
  302.         // X-axis wave generation
  303.         $xp $this->scale*$this->Xperiod*rand(1,3);
  304.         $k rand(0100);
  305.         for ($i 0$i < ($this->width*$this->scale); $i++) {
  306.             imagecopy($this->im$this->im,
  307.                 $i-1sin($k+$i/$xp) * ($this->scale*$this->Xamplitude),
  308.                 $i01$this->height*$this->scale);
  309.         }
  310.         // Y-axis wave generation
  311.         $k rand(0100);
  312.         $yp $this->scale*$this->Yperiod*rand(1,2);
  313.         for ($i 0$i < ($this->height*$this->scale); $i++) {
  314.             imagecopy($this->im$this->im,
  315.                 sin($k+$i/$yp) * ($this->scale*$this->Yamplitude), $i-1,
  316.                 0$i$this->width*$this->scale1);
  317.         }
  318.     }
  319.     /**
  320.      * Reduce the image to the final size
  321.      */
  322.     protected function ReduceImage() {
  323.         // Reduzco el tama�o de la imagen
  324.         $imResampled imagecreatetruecolor($this->width$this->height);
  325.         imagecopyresampled($imResampled$this->im,
  326.             0000,
  327.             $this->width$this->height,
  328.             $this->width*$this->scale$this->height*$this->scale
  329.         );
  330.         imagedestroy($this->im);
  331.         $this->im $imResampled;
  332.     }
  333.     /**
  334.      * File generation
  335.      */
  336.     protected function WriteImage() {
  337.         
  338.          
  339.          //$response = new Response();
  340.          //$response->headers->set('Content-type', 'image/jpeg');
  341.          ///imagepng($this->im);
  342.                     
  343.                 ob_start();
  344.                 imagepng($this->im);
  345.                 $imagevariable ob_get_contents();
  346.                 ob_end_clean();
  347.                 $response = new Response();
  348.                 $response->headers->set('Content-type''image/jpeg');
  349.                 return $response->setContent($imagevariable); 
  350.         
  351.         /*
  352.         
  353.         if ($this->imageFormat == 'png' && function_exists('imagepng')) {            
  354.             header("Content-type: image/png");
  355.             imagepng($this->im);
  356.         } else {
  357.             header("Content-type: image/jpeg");
  358.             imagejpeg($this->im, null, 80);
  359.             
  360.         }*/
  361.     }
  362.     /**
  363.      * Cleanup
  364.      */
  365.     protected function Cleanup() {
  366.         imagedestroy($this->im);
  367.     }
  368.    
  369.     
  370.     
  371.     
  372.     
  373.     public function writeSimpleAction(Request $request) {
  374.         $dir 'fonts/';
  375.         $session $request->getSession();
  376.         $codigo '';
  377.         for ($i 0$i 5$i++) {
  378.                 $codigo .= chr(rand(97122));
  379.         }
  380.         $session->set('captcha_codigo'$codigo);
  381.         $image imagecreatetruecolor(14040);
  382.         // random number 1 or 2
  383.         $num rand(1,2);
  384.         if($num==1)
  385.         {
  386.                 $font "Capture it 2.ttf"// font style
  387.         }
  388.         else
  389.         {
  390.                 $font "Molot.otf";// font style
  391.         }
  392.         // random number 1 or 2
  393.         $num2 rand(1,2);
  394.         if($num2==1)
  395.         {
  396.                 $color imagecolorallocate($image113193217);// color
  397.         }
  398.         else
  399.         {
  400.                 $color imagecolorallocate($image16319782);// color
  401.         }
  402.         $white imagecolorallocate($image13606); // background color white
  403.         imagefilledrectangle($image,0,0,399,99,$white);
  404.         imagettftext ($image260534$color$dir.$font$codigo);
  405.         ob_start();
  406.         imagepng($image);
  407.         $imagevariable ob_get_contents();
  408.         ob_end_clean();
  409.         $response = new Response();
  410.         $response->headers->set('Content-type''image/jpeg');
  411.         return $response->setContent($imagevariable); 
  412.     }
  413.     
  414. }
  415. ?>