You are here

function lost_character_captcha_captcha in CAPTCHA Pack 8

Same name and namespace in other branches
  1. 5 text_captcha/lost_character_captcha/lost_character_captcha.module \lost_character_captcha_captcha()
  2. 6 text_captcha/lost_character_captcha/lost_character_captcha.module \lost_character_captcha_captcha()
  3. 7 text_captcha/lost_character_captcha/lost_character_captcha.module \lost_character_captcha_captcha()

Implements hook_captcha().

File

text_captcha/modules/lost_character_captcha/lost_character_captcha.module, line 39
Contains general functionality of the module.

Code

function lost_character_captcha_captcha($op, $captcha_type = '') {
  $config = \Drupal::config('lost_character_captcha.settings');
  switch ($op) {
    case 'list':
      return [
        "Lost characters",
      ];
    case 'generate':
      if ($captcha_type == "Lost characters") {

        // Get the word pool.
        $words = _text_captcha_word_pool_get_content('lost_character_captcha_word_pool', NULL, LOST_CHARACTER_CAPTCHA_DEFAULT_WORD_POOL, TRUE);

        // Pick a random word.
        $word = $words[array_rand($words)];

        // Split in characters.
        $characters = _text_captcha_utf8_split($word);

        // Lose characters.
        $lost = [];
        $lose_quantity = $config
          ->get('lost_character_captcha_quantity');
        for ($i = 0; $i < $lose_quantity; $i++) {

          // Pick a random character.
          $n = array_rand($characters);
          while ($characters[$n] == LOST_CHARACTER_CAPTCHA_HINTER) {
            $n = array_rand($characters);
          }

          // Save it for building the solution.
          $lost[] = $characters[$n];

          // And lose it in the given word.
          if ($config
            ->get('lost_character_captcha_enable_hint')) {
            $characters[$n] = LOST_CHARACTER_CAPTCHA_HINTER;
          }
          else {
            unset($characters[$n]);
          }
        }

        // Build the CAPTCHA.
        sort($lost);
        $given_word = implode('', $characters);
        $solution = implode('', $lost);
        if ($lose_quantity == 1) {
          $title = t('Enter the missing character from the following word');
        }
        else {
          $title = t('Enter the @num missing characters from the following word', [
            '@num' => $lose_quantity,
          ]);
        }
        $captcha = [];
        $captcha['solution'] = $solution;
        $captcha['form']['captcha_response'] = [
          '#type' => 'textfield',
          '#title' => $title,
          '#field_prefix' => "{$given_word}: ",
          '#size' => 3,
          '#maxlength' => 3,
          '#required' => TRUE,
          '#process' => [
            'lost_character_process',
          ],
          '#cache' => [
            'max-age' => 0,
          ],
        ];
        \Drupal::service('page_cache_kill_switch')
          ->trigger();
        return $captcha;
      }
  }
}