You are here

riddler.module in Captcha Riddler 8

Same filename and directory in other branches
  1. 5 riddler.module
  2. 6 riddler.module
  3. 7 riddler.module

File

riddler.module
View source
<?php

use Drupal\Core\Routing\RouteMatchInterface;

/**
 * Implements hook_help().
 */
function riddler_help($route_name, RouteMatchInterface $route_match) {
  switch ($route_name) {
    case 'help.page.riddler':
      $output = '<p>' . t('Requires anonymous users completing forms to answer a simple question to counter spam.') . '</p>';
      return $output;
  }
}

/**
 * Implements hook_captcha().
 */
function riddler_captcha($op, $captcha_type = '', $captcha_sid = NULL) {
  $riddles = \Drupal::config('riddler.settings')
    ->get('riddles');
  switch ($op) {
    case 'list':
      return [
        'Riddler',
      ];
      break;
    case 'generate':
      if ($captcha_type == 'Riddler') {

        // Generate a CAPTCHA code.
        $key = array_rand($riddles);
        $riddle = $riddles[$key];

        // Build the result to return.
        $result = [];
        $result['solution'] = $riddle['response'];
        $result['form']['captcha_riddle'] = [
          '#markup' => '<p><strong>' . $riddle['question'] . '</strong></p>',
        ];
        $result['form']['captcha_response'] = [
          '#type' => 'textfield',
          '#title' => t('Answer the question here:'),
          '#weight' => 0,
          '#required' => TRUE,
          '#size' => 15,
          '#attributes' => [
            'autocomplete' => 'off',
          ],
          '#cache' => [
            'max-age' => 0,
          ],
        ];

        // Use custom validation so multiple answers can be tested.
        $result['captcha_validate'] = 'riddler_captcha_validate';
        \Drupal::service('page_cache_kill_switch')
          ->trigger();
        return $result;
      }
      break;
  }
}

/**
 * Custom validation for Riddler.
 */
function riddler_captcha_validate($solution, $captcha_response, $element, $form_state) {

  // There can be multiple possible answers, so explode solution.
  $solutions = explode(',', $solution);

  // Remove any stray spaces.
  $solutions = array_map('trim', $solutions);
  $isolutions = array_map('strtolower', $solutions);
  switch (\Drupal::config('captcha.settings')
    ->get('default_validation')) {
    case CAPTCHA_DEFAULT_VALIDATION_CASE_SENSITIVE:
      return in_array($captcha_response, $solutions);
      break;
    case CAPTCHA_DEFAULT_VALIDATION_CASE_INSENSITIVE:
      return in_array(strtolower($captcha_response), $isolutions);
      break;
  }

  // Just in case.
  return FALSE;
}

Functions

Namesort descending Description
riddler_captcha Implements hook_captcha().
riddler_captcha_validate Custom validation for Riddler.
riddler_help Implements hook_help().