CaptchaLib.php 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. <?php
  2. App::uses('Security', 'Utility');
  3. if (!defined('FORMAT_DB_DATE')) {
  4. define('FORMAT_DB_DATETIME', 'Y-m-d H:i:s');
  5. }
  6. /**
  7. * Main utility for captchas.
  8. * Used by captcha helper and behavior.
  9. */
  10. class CaptchaLib {
  11. public static $defaults = [
  12. 'dummyField' => 'homepage',
  13. 'method' => 'hash',
  14. 'type' => 'both',
  15. 'checkSession' => false,
  16. 'checkIp' => false,
  17. 'salt' => '',
  18. ];
  19. // what type of captcha
  20. public static $types = ['passive', 'active', 'both'];
  21. // what method to use
  22. public static $methods = ['hash', 'db', 'session'];
  23. /**
  24. * @param array $data:
  25. * - captcha_time, result/captcha
  26. * @param array $options:
  27. * - salt (required)
  28. * - checkSession, checkIp, hashType (all optional)
  29. * @return string
  30. */
  31. public static function buildHash($data, $options, $init = false) {
  32. if ($init) {
  33. $data['captcha_time'] = time();
  34. $data['captcha'] = $data['result'];
  35. }
  36. $hashValue = date(FORMAT_DB_DATETIME, (int)$data['captcha_time']) . '_';
  37. $hashValue .= ($options['checkSession']) ? session_id() . '_' : '';
  38. $hashValue .= ($options['checkIp']) ? env('REMOTE_ADDR') . '_' : '';
  39. if (empty($options['type']) || $options['type'] !== 'passive') {
  40. $hashValue .= $data['captcha'];
  41. }
  42. $type = isset($options['hashType']) ? $options['hashType'] : null;
  43. return Security::hash($hashValue, $type, $options['salt']);
  44. }
  45. }