You are here

function captcha_questions_form_validate in Captcha Questions 8

Same name and namespace in other branches
  1. 7 captcha_questions.module \captcha_questions_form_validate()

Implements hook_form_validate().

1 string reference to 'captcha_questions_form_validate'
captcha_questions_form_alter in ./captcha_questions.module
Implements hook_form_alter().

File

./captcha_questions.module, line 57
Module file for the Captcha questions module.

Code

function captcha_questions_form_validate(&$form, FormStateInterface $form_state) {
  $ip = \Drupal::request()
    ->getClientIp();
  $form_id = $form_state
    ->getValue('form_id');
  $config = \Drupal::config('captcha_questions.settings');
  $question_asked = $config
    ->get('captcha_questions_question');
  $answers = $config
    ->get('captcha_questions_answers');
  $answer_given = $form_state
    ->getValue('captcha_questions_answer_given');

  // Comparison is done in lowercase, ensure answers are lowercase.
  $answers = array_map('strtolower', $answers);
  $answer_given = mb_strtolower($answer_given);

  // Check answer.
  if (in_array($answer_given, $answers) == FALSE) {

    // Log to watchdog if enabled.
    if ($config
      ->get('captcha_questions_watchdog')) {
      $message = t('Blocked submission of form with form_id @form_id. Answer given was %answer_given', [
        '@form_id' => $form_id,
        '%answer_given' => $form_state
          ->getValue('captcha_questions_answer_given'),
      ]);
      \Drupal::logger('captcha_questions')
        ->error($message);
    }

    // Log to dblog if enabled and module exists and enabled.
    $dblog_enabled = \Drupal::config('captcha_questions.settings')
      ->get('captcha_questions_dblog');
    $dblog_module_exists = \Drupal::moduleHandler()
      ->moduleExists('captcha_questions_dblog') ? TRUE : FALSE;
    if ($dblog_enabled && $dblog_module_exists) {
      \Drupal::database()
        ->insert('captcha_questions_dblog')
        ->fields([
        'timestamp' => \Drupal::time()
          ->getRequestTime(),
        'ip' => $ip,
        'form_id' => $form_id,
        'question_asked' => Html::escape($question_asked),
        'answer_given' => Html::escape($answer_given),
        'answer_correct' => implode(",", $answers),
      ])
        ->execute();
    }

    // Display error.
    $form_state
      ->setErrorByName('captcha_questions_answer_given', t('Invalid answer'));
  }
}