You are here

function foo_captcha_captcha in CAPTCHA 8

Implements hook_captcha().

This documentation is for developers that want to implement their own challenge type and integrate it with the base CAPTCHA module.

=== Required: hook_captcha($op, $captcha_type='') ===

The hook_captcha() hook is the only required function if you want to integrate with the base CAPTCHA module.

Functionality depends on the first argument $op:

  • 'list': you should return an array of possible challenge types that your module implements.
  • 'generate': generate a challenge.

You should return an array that offers form elements and the solution of your challenge, defined by the second argument $captcha_type.

The returned array $captcha should have the following items:

  • $captcha['solution']: this is the solution of your challenge
  • $captcha['form']: an array of the form elements you want to add to the form.
  • $captcha['cacheable']: (optional) boolean indicating whether the captcha type is compatible with the form being cached. Defaults to FALSE. Note that if this TRUE, the 'captcha_validate' key must be set to a callback that ignores the solution.
  • $captcha['captcha_validate']: (optional) The name of a function to call to compare the solution with the given response. Defaults to captcha_validate_strict_equality().

There should be a key 'captcha_response' in this array, which points to the form element where the user enters the answer.

An optional additional argument $captcha_sid with the captcha session ID is available for more advanced challenges (e.g. the image CAPTCHA uses this argument, see image_captcha_captcha()) and it is used for every session.

Let's give a simple example to make this more clear.

We create the challenge 'Foo CAPTCHA', which requires the user to enter "foo" in a textfield.

File

./captcha.api.php, line 51
Hooks for the captcha module.

Code

function foo_captcha_captcha($op, $captcha_type = '') {
  switch ($op) {
    case 'list':
      return [
        'Foo CAPTCHA',
      ];
    case 'generate':
      if ($captcha_type == 'Foo CAPTCHA') {
        $captcha = [];
        $captcha['solution'] = 'foo';
        $captcha['form']['captcha_response'] = [
          '#type' => 'textfield',
          '#title' => t('Enter "foo"'),
          '#required' => TRUE,
        ];

        // The CAPTCHA module provides an option for case sensitive and case
        // insensitve validation of the responses. If this is not sufficient,
        // you can provide your own validation function with the
        // 'captcha_validate' field, illustrated by the following example:
        $captcha['captcha_validate'] = 'foo_captcha_custom_validation';
        return $captcha;
      }
      break;
  }
}