You are here

function random_captcha_type_captcha in CAPTCHA Pack 8

Same name and namespace in other branches
  1. 5 random_captcha_type/random_captcha_type.module \random_captcha_type_captcha()
  2. 6 random_captcha_type/random_captcha_type.module \random_captcha_type_captcha()
  3. 7 random_captcha_type/random_captcha_type.module \random_captcha_type_captcha()

Implements hook_captcha().

File

random_captcha_type/random_captcha_type.module, line 21
Contains general functionality of the module.

Code

function random_captcha_type_captcha($op, $captcha_type = '', $captcha_sid = 0) {
  switch ($op) {
    case 'list':
      $enabled_types = _random_captcha_type_get_enabled_types();
      if (count($enabled_types) < 2) {
        return;
      }
      return [
        'Random CAPTCHA type',
      ];
    case 'generate':
      if ($captcha_type == 'Random CAPTCHA type') {
        if (isset($_POST['random_captcha_type'])) {

          // If this is a POST request, we're possibly in a validation phase
          // so the CAPTCHA type should be the same as in the originating form.
          $module_and_type = $_POST['random_captcha_type'];
        }
        else {

          // If not, just pick a random one.
          $types = _random_captcha_type_get_enabled_types();
          $module_and_type = $types[array_rand($types)];
        }
        list($module, $type) = explode('/', $module_and_type);

        // Call the generate CAPTCHA hook.
        $captcha = \Drupal::moduleHandler()
          ->invoke($module, 'captcha', [
          'generate',
          $type,
          $captcha_sid,
        ]);

        // Store the current CAPTCHA type so it can be recovered for
        // regenerating the form in the validation phase.
        $captcha['form']['random_captcha_type'] = [
          '#type' => 'hidden',
          '#value' => $module_and_type,
        ];
        return $captcha;
      }
  }
}