Captcha.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. <?php
  2. /**
  3. *
  4. * Cube Framework $Id$ Mb+q3NGklhDEfLjdI7KJHpjTTrjH4c3asnT1dGhtIZU=
  5. *
  6. * @link http://codecu.be/framework
  7. * @copyright Copyright (c) 2014 CodeCube SRL
  8. * @license http://codecu.be/framework/license Commercial License
  9. *
  10. * @version 1.2
  11. */
  12. /**
  13. * captcha element validator class
  14. */
  15. namespace Cube\Validate;
  16. use Cube\Controller\Front,
  17. Cube\Session;
  18. class Captcha extends AbstractValidate
  19. {
  20. const SESSION_NAMESPACE = 'Captcha';
  21. protected $_message = "The captcha code is not valid.";
  22. /**
  23. *
  24. * session object
  25. *
  26. * @var \Cube\Session
  27. */
  28. protected $_session;
  29. /**
  30. *
  31. * get session object
  32. *
  33. * @return \Cube\Session
  34. */
  35. public function getSession()
  36. {
  37. if (!($this->_session instanceof Session)) {
  38. $this->setSession();
  39. }
  40. return $this->_session;
  41. }
  42. /**
  43. *
  44. * set session object
  45. *
  46. * @param \Cube\Session $session
  47. *
  48. * @return $this
  49. */
  50. public function setSession(Session $session = null)
  51. {
  52. if ($session === null) {
  53. $session = Front::getInstance()->getBootstrap()->getResource('session');
  54. }
  55. if (!($session instanceof Session)) {
  56. $session = new Session();
  57. $session->setNamespace(self::SESSION_NAMESPACE);
  58. }
  59. $this->_session = $session;
  60. return $this;
  61. }
  62. /**
  63. *
  64. * checks for a valid captcha code, and resets the code if valid
  65. *
  66. * @return bool return true if the validation is successful
  67. */
  68. public function isValid()
  69. {
  70. $name = $this->getName();
  71. $value = $this->getValue();
  72. $codes = (array) $this->getSession()->get($name);
  73. if (($key = array_search($value, $codes)) !== false) {
  74. unset($codes[$key]);
  75. $this->getSession()->set($name, $codes);
  76. return true;
  77. }
  78. else {
  79. return false;
  80. }
  81. }
  82. }