2011-08-25 22:50:59 +02:00
|
|
|
<?php
|
|
|
|
|
|
|
|
namespace Gregwar\CaptchaBundle\Validator;
|
|
|
|
|
|
|
|
use Symfony\Component\Form\FormValidatorInterface;
|
2012-04-26 04:54:51 +02:00
|
|
|
use Symfony\Component\HttpFoundation\Session\Session;
|
2011-08-25 22:50:59 +02:00
|
|
|
use Symfony\Component\Form\FormInterface;
|
|
|
|
use Symfony\Component\Form\FormError;
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Captcha validator
|
|
|
|
*
|
|
|
|
* @author Gregwar <g.passault@gmail.com>
|
|
|
|
*/
|
|
|
|
class CaptchaValidator implements FormValidatorInterface
|
|
|
|
{
|
|
|
|
/**
|
|
|
|
* Session
|
|
|
|
*/
|
|
|
|
private $session;
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Session key to store the code
|
|
|
|
*/
|
|
|
|
private $key;
|
|
|
|
|
2012-06-29 16:23:05 +02:00
|
|
|
/**
|
|
|
|
* Error message text for non-matching submissions
|
|
|
|
*/
|
|
|
|
private $invalidMessage;
|
|
|
|
|
|
|
|
public function __construct(Session $session, $key, $invalidMessage)
|
2011-08-25 22:50:59 +02:00
|
|
|
{
|
|
|
|
$this->session = $session;
|
|
|
|
$this->key = $key;
|
2012-06-29 16:23:05 +02:00
|
|
|
$this->invalidMessage = $invalidMessage;
|
2011-08-25 22:50:59 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
public function validate(FormInterface $form)
|
|
|
|
{
|
|
|
|
$code = $form->getData();
|
|
|
|
$excepted_code = $this->getExceptedCode();
|
|
|
|
|
|
|
|
if (!($code && $excepted_code && is_string($code) && is_string($excepted_code)
|
|
|
|
&& $this->niceize($code) == $this->niceize($excepted_code))) {
|
2012-06-29 16:23:05 +02:00
|
|
|
$form->addError(new FormError($this->invalidMessage));
|
2011-08-25 22:50:59 +02:00
|
|
|
}
|
2011-12-02 18:23:08 +01:00
|
|
|
|
|
|
|
$this->session->remove($this->key);
|
2011-12-02 19:26:31 +01:00
|
|
|
|
|
|
|
if ($this->session->has($this->key.'_fingerprint')) {
|
|
|
|
$this->session->remove($this->key.'_fingerprint');
|
|
|
|
}
|
2011-08-25 22:50:59 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Retrieve the excepted CAPTCHA code
|
|
|
|
*/
|
|
|
|
private function getExceptedCode()
|
|
|
|
{
|
|
|
|
if ($this->session->has($this->key)) {
|
|
|
|
return $this->session->get($this->key);
|
|
|
|
}
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Process the codes
|
|
|
|
*/
|
2012-06-29 16:23:05 +02:00
|
|
|
private function niceize($code)
|
2011-08-25 22:50:59 +02:00
|
|
|
{
|
2011-12-14 10:18:38 +01:00
|
|
|
return strtr(strtolower($code), 'oil', '01l');
|
2011-08-25 22:50:59 +02:00
|
|
|
}
|
|
|
|
}
|