You are here

captcha.module in CAPTCHA 6

Same filename and directory in other branches
  1. 8 captcha.module
  2. 5.3 captcha.module
  3. 6.2 captcha.module
  4. 7 captcha.module

This module enables basic CAPTCHA functionality: administrators can add a CAPTCHA to desired forms that users without the 'skip CAPTCHA' permission (typically anonymous visitors) have to solve.

File

captcha.module
View source
<?php

/**
 * @file
 * This module enables basic CAPTCHA functionality:
 * administrators can add a CAPTCHA to desired forms that users without
 * the 'skip CAPTCHA' permission (typically anonymous visitors) have
 * to solve.
 *
 */
define('CAPTCHA_UNSOLVED_CHALLENGES_MAX', 20);
define('CAPTCHA_PERSISTENCE_SHOW_ALWAYS', 1);
define('CAPTCHA_PERSISTENCE_SKIP_ONCE_SUCCESSFUL_PER_FORM', 2);
define('CAPTCHA_PERSISTENCE_SKIP_ONCE_SUCCESSFUL', 3);

/**
 * Implementation of hook_help().
 */
function captcha_help($path, $arg) {
  switch ($path) {
    case 'admin/help#captcha':
      $output = '<p>' . t('"CAPTCHA" is an acronym for "Completely Automated Public Turing test to tell Computers and Humans Apart". It is typically a challenge-response test to determine whether the user is human. The CAPTCHA module is a tool to fight automated submission by malicious users (spamming) of for example comments forms, user registration forms, guestbook forms, etc. You can extend the desired forms with an additional challenge, which should be easy for a human to solve correctly, but hard enough to keep automated scripts and spam bots out.') . '</p>';
      $output .= '<p>' . t('Note that the CAPTCHA module interacts with page caching (see <a href="!performancesettings">performance settings</a>). Because the challenge should be unique for each generated form, the caching of the page it appears on is prevented. Make sure that these forms do not appear on too many pages or you will lose much caching efficiency. For example, if you put a CAPTCHA on the user login block, which typically appears on each page for anonymous visitors, caching will practically be disabled. The comment submission forms are another example. In this case you should set the "%commentlocation" to "%separatepage" in the comment settings of the relevant <a href="!contenttypes">content types</a> for better caching efficiency.', array(
        '!performancesettings' => url('admin/settings/performance'),
        '%commentlocation' => t('Location of comment submission form'),
        '%separatepage' => t('Display on separate page'),
        '!contenttypes' => url('admin/content/types'),
      )) . '</p>';
      $output .= '<p>' . t('CAPTCHA is a trademark of Carnegie Mellon University.') . '</p>';
      return $output;
    case 'admin/user/captcha':
    case 'admin/user/captcha/captcha':
    case 'admin/user/captcha/captcha/settings':
      $output = '<p>' . t('A CAPTCHA can be added to virtually each Drupal form. Some default forms are already provided in the form list, but arbitrary forms can be easily added and managed when the option "%adminlinks" is enabled.', array(
        '%adminlinks' => t('Add CAPTCHA administration links to forms'),
      )) . '</p>';
      $output .= '<p>' . t('Users with the "%skipcaptcha" <a href="@perm">permission</a> won\'t be offered a challenge. Be sure to grant this permission to the trusted users (e.g. site administrators). If you want to test a protected form, be sure to do it as a user without the "%skipcaptcha" permission (e.g. as anonymous user).', array(
        '%skipcaptcha' => t('skip CAPTCHA'),
        '@perm' => url('admin/user/permissions'),
      )) . '</p>';
      return $output;
  }
}

/**
 * Implementation of hook_menu().
 */
function captcha_menu() {
  $items = array();

  // main configuration page of the basic CAPTCHA module
  $items['admin/user/captcha'] = array(
    'title' => 'CAPTCHA',
    'description' => 'Administer how and where CAPTCHAs are used.',
    'file' => 'captcha.admin.inc',
    'page callback' => 'drupal_get_form',
    'page arguments' => array(
      'captcha_admin_settings',
    ),
    'access arguments' => array(
      'administer CAPTCHA settings',
    ),
    'type' => MENU_NORMAL_ITEM,
  );

  // the default local task (needed when other modules want to offer
  // alternative CAPTCHA types and their own configuration page as local task)
  $items['admin/user/captcha/captcha'] = array(
    'title' => 'CAPTCHA',
    'access arguments' => array(
      'administer CAPTCHA settings',
    ),
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'weight' => -20,
  );
  $items['admin/user/captcha/captcha/settings'] = array(
    'title' => 'General settings',
    'access arguments' => array(
      'administer CAPTCHA settings',
    ),
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'weight' => 0,
  );
  $items['admin/user/captcha/captcha/examples'] = array(
    'title' => 'Examples',
    'description' => 'An overview of the available challenge types with examples.',
    'file' => 'captcha.admin.inc',
    'page callback' => 'drupal_get_form',
    'page arguments' => array(
      'captcha_examples',
      5,
      6,
    ),
    'access arguments' => array(
      'administer CAPTCHA settings',
    ),
    'type' => MENU_LOCAL_TASK,
    'weight' => 5,
  );
  $items['admin/user/captcha/captcha/captcha_point'] = array(
    'title' => 'CAPTCHA point administration',
    'file' => 'captcha.admin.inc',
    'page callback' => 'captcha_point_admin',
    'page arguments' => array(
      5,
      6,
    ),
    'access arguments' => array(
      'administer CAPTCHA settings',
    ),
    'type' => MENU_CALLBACK,
  );
  return $items;
}

/**
 * Implementation of hook_perm().
 */
function captcha_perm() {
  return array(
    'administer CAPTCHA settings',
    'skip CAPTCHA',
  );
}

/**
 * Implementation of hook_requirements().
 */
function captcha_requirements($phase) {
  $requirements = array();
  $t = get_t();
  if ($phase == 'runtime') {

    // show the wrong response counter in the status report
    $requirements['captcha_wrong_response_counter'] = array(
      'title' => $t('CAPTCHA'),
      'value' => $t('Already @counter blocked form submissions', array(
        '@counter' => variable_get('captcha_wrong_response_counter', 0),
      )),
      'severity' => REQUIREMENT_INFO,
    );

    // Check if there is an entry for uid=0 in the users table, this is required
    // to have working a $_SESSION variable for anonymous users.
    if (!db_result(db_query('SELECT COUNT(*) FROM {users} WHERE uid=%d', 0))) {
      $requirements['captcha_no_sessions_for_anonymous'] = array(
        'title' => $t('CAPTCHA'),
        'value' => $t('No sessions for anonymous users.'),
        'description' => $t('There is no entry for uid 0 in the %users table of the database. This disables persistent session data for anonymous users. Because the CAPTCHA module depends on this session data, CAPTCHAs will not work for anonymous users. Add a row for uid 0 to the %users table to resolve this.', array(
          '%users' => 'users',
        )),
        'severity' => REQUIREMENT_ERROR,
      );
    }
  }
  return $requirements;
}

/**
 * Implementation of hook_theme().
 */
function captcha_theme() {
  return array(
    'captcha_admin_settings_captcha_points' => array(
      'arguments' => array(
        'form' => NULL,
      ),
    ),
  );
}

/**
 * Get the description which appears above the CAPTCHA in forms.
 * If the locale module is enabled, an optional language code can be given
 */
function _captcha_get_description($lang_code = NULL) {
  $default = t('This question is for testing whether you are a human visitor and to prevent automated spam submissions.');
  if (module_exists('locale')) {
    if ($lang_code == NULL) {
      global $language;
      $lang_code = $language->language;
    }
    $description = variable_get("captcha_description_{$lang_code}", $default);
  }
  else {
    $description = variable_get('captcha_description', $default);
  }
  return $description;
}

/**
 * Helper function for checking if the CAPTCHA for the given form_id should
 * be skipped because of CAPTCHA persistence.
 */
function _captcha_persistence_skip($form_id) {
  switch (variable_get('captcha_persistence', CAPTCHA_PERSISTENCE_SHOW_ALWAYS)) {
    case CAPTCHA_PERSISTENCE_SKIP_ONCE_SUCCESSFUL:
      return isset($_SESSION['captcha']['success']) && $_SESSION['captcha']['success'] === TRUE;
    case CAPTCHA_PERSISTENCE_SKIP_ONCE_SUCCESSFUL_PER_FORM:
      return isset($_SESSION['captcha'][$form_id]['success']) && $_SESSION['captcha'][$form_id]['success'] === TRUE;
    default:
      return FALSE;
  }
}

/**
 * Implementation of hook_form_alter().
 *
 * This function adds a CAPTCHA to forms for untrusted users if needed and adds
 * CAPTCHA administration links for site administrators if this option is enabled.
 */
function captcha_form_alter(&$form, $form_state, $form_id) {
  if (!user_access('skip CAPTCHA')) {

    // Visitor does not have permission to skip the CAPTCHA
    // Get CAPTCHA type and module for this form. Return if no CAPTCHA was set.
    $result = db_query("SELECT module, type FROM {captcha_points} WHERE form_id = '%s'", $form_id);
    if (!$result) {
      return;
    }
    $captcha_point = db_fetch_object($result);
    if (!$captcha_point || !$captcha_point->type) {
      return;
    }

    // Prevent caching of the page with this CAPTCHA enabled form.
    // This needs to be done even if the CAPTCHA will be skipped (because of
    // persistence): other untrusted users should not get a cached page when
    // the current untrusted user can skip the current CAPTCHA.
    global $conf;
    $conf['cache'] = FALSE;

    // Do not present CAPTCHA if not CAPTCHA-persistent and user has already solved a CAPTCHA for this form
    if (_captcha_persistence_skip($form_id)) {
      return;
    }

    // Generate a CAPTCHA and its solution
    $captcha = module_invoke($captcha_point->module, 'captcha', 'generate', $captcha_point->type);
    if (!$captcha) {

      //The selected module returned nothing, maybe it is disabled or it's wrong, we should watchdog that and then quit.
      watchdog('CAPTCHA', 'CAPTCHA problem: hook_captcha() of module %module returned nothing when trying to retrieve challenge type %type for form %form_id.', array(
        '%type' => $captcha_point->type,
        '%module' => $captcha_point->module,
        '%form_id' => $form_id,
      ), WATCHDOG_ERROR);
      return;
    }

    // Add a CAPTCHA part to the form (depends on value of captcha_description)
    $captcha_description = _captcha_get_description();
    if ($captcha_description) {

      // $captcha_description is not empty: CAPTCHA part is a fieldset with description
      $form['captcha'] = array(
        '#type' => 'fieldset',
        '#title' => t('CAPTCHA'),
        '#description' => $captcha_description,
        '#attributes' => array(
          'class' => 'captcha',
        ),
      );
    }
    else {

      // $captcha_description is empty: CAPTCHA part is an empty markup form element
      $form['captcha'] = array(
        '#type' => 'markup',
        '#prefix' => '<div class="captcha">',
        '#suffix' => '</div>',
      );
    }

    // Add the form elements of the generated CAPTCHA to the form
    $form['captcha'] = array_merge($form['captcha'], $captcha['form']);

    // Store the solution of the generated CAPTCHA as an internal form value.
    // This will be stored later in $_SESSION during the pre_render phase.
    // It can't be saved at this point because hook_form_alter is not only run
    // before form rendering, but also before form validation (which happens
    // in a new (POST) request. Consequently the right CAPTCHA solution would be
    // overwritten just before validation. The pre_render functions are not run
    // before validation and are the right place to store the solution in $_SESSION.
    $form['captcha']['captcha_solution'] = array(
      '#type' => 'value',
      '#value' => $captcha['solution'],
    );

    // The CAPTCHA token is used to differentiate between different instances
    // of the same form. This makes it possible to request the same form a
    // couple of times before submitting them. The solution of the CAPTCHA of
    // each of these form instances will be stored at the pre_render phase in
    // $_SESSION['captcha'][$form_id][$captcha_token]
    $form['captcha']['captcha_token'] = array(
      '#type' => 'hidden',
      '#value' => md5(mt_rand()),
    );

    // other internal values needed for the validation phase
    $form['captcha']['captcha_info'] = array(
      '#type' => 'value',
      '#value' => array(
        'form_id' => $form_id,
        'preprocess' => isset($captcha['preprocess']) ? $captcha['preprocess'] : FALSE,
        'module' => $captcha_point->module,
        'type' => $captcha_point->type,
      ),
    );

    // Add pre_render function for additional CAPTCHA processing.
    $form['#pre_render'][] = 'captcha_pre_render';

    // Add pre_render function for placement of CAPTCHA formt element (above submit buttons).
    $form['#pre_render'][] = 'captcha_pre_render_place_captcha';

    // Add a validation function for the CAPTCHA form element.
    $form['captcha']['#element_validate'] = array(
      'captcha_validate',
    );
  }
  elseif (user_access('administer CAPTCHA settings') && variable_get('captcha_administration_mode', FALSE) && arg(0) != 'admin') {

    // For administrators: show CAPTCHA info and offer link to configure it
    $result = db_query("SELECT module, type FROM {captcha_points} WHERE form_id = '%s'", $form_id);
    if (!$result) {
      return;
    }
    $captcha_point = db_fetch_object($result);
    $form['captcha'] = array(
      '#type' => 'fieldset',
      '#title' => t('CAPTCHA'),
      '#collapsible' => TRUE,
      '#collapsed' => TRUE,
    );
    if ($captcha_point && $captcha_point->type) {
      $form['captcha']['#description'] = t('Untrusted users will see a CAPTCHA here (!settings).', array(
        '!settings' => l(t('general CAPTCHA settings'), 'admin/user/captcha'),
      ));
      $form['captcha']['challenge'] = array(
        '#type' => 'item',
        '#title' => t('Enabled challenge'),
        '#value' => t('"@type" by module "@module" (!change, !disable)', array(
          '@type' => $captcha_point->type,
          '@module' => $captcha_point->module,
          '!change' => l(t('change'), "admin/user/captcha/captcha/captcha_point/{$form_id}", array(
            'query' => drupal_get_destination(),
          )),
          '!disable' => l(t('disable'), "admin/user/captcha/captcha/captcha_point/{$form_id}/disable", array(
            'query' => drupal_get_destination(),
          )),
        )),
      );
    }
    else {
      $form['captcha']['add_captcha'] = array(
        '#value' => l(t('Place a CAPTCHA here for untrusted users.'), "admin/user/captcha/captcha/captcha_point/{$form_id}", array(
          'query' => drupal_get_destination(),
        )),
      );
    }

    // Add pre_render function for placement of CAPTCHA formt element (above submit buttons).
    $form['#pre_render'][] = 'captcha_pre_render_place_captcha';
  }
}

/**
 * Implementation of form #validate.
 */
function captcha_validate($form, &$form_state) {

  // Check if there is CAPTCHA data available in $_SESSION.
  // If not, the visitor has most likely disabled cookies.
  if (!isset($_SESSION['captcha'])) {
    form_set_error('captcha_response', t('Cookies should be enabled in your browser for CAPTCHA validation.'));
    return;
  }

  // Get answer and preprocess if needed
  $captcha_response = $form_state['values']['captcha_response'];
  $captcha_info = $form_state['values']['captcha_info'];
  if ($captcha_info['preprocess']) {
    $captcha_response = module_invoke($captcha_info['module'], 'captcha', 'preprocess', $captcha_info['type'], $captcha_response);
  }
  $form_id = $captcha_info['form_id'];

  // not that we use $form_state['clicked_button']['#post']['captcha_token']
  // here instead of $form_state['values']['captcha_token'], because the latter
  // contains the captcha_token of the new form, while the former contains
  // the captcha token of the posted form.
  $captcha_token = $form_state['clicked_button']['#post']['captcha_token'];

  // Check if captcha_token exists
  if (!isset($_SESSION['captcha'][$form_id][$captcha_token])) {
    form_set_error('captcha_token', t('Invalid CAPTCHA token.'));
  }
  elseif ($captcha_response === $_SESSION['captcha'][$form_id][$captcha_token]) {
    $_SESSION['captcha'][$form_id]['success'] = TRUE;
    $_SESSION['captcha']['success'] = TRUE;
  }
  else {

    // set form error
    form_set_error('captcha_response', t('The answer you entered for the CAPTCHA was not correct.'));

    // update wrong response counter
    variable_set('captcha_wrong_response_counter', variable_get('captcha_wrong_response_counter', 0) + 1);

    // log to watchdog if needed
    if (variable_get('captcha_log_wrong_responses', FALSE)) {
      watchdog('CAPTCHA', '%form_id post blocked by CAPTCHA module: challenge "%challenge" (by module "%module"), user answered "%response", but the solution was "%solution".', array(
        '%form_id' => $form_id,
        '%response' => $captcha_response,
        '%solution' => $_SESSION['captcha'][$form_id][$captcha_token],
        '%challenge' => $captcha_info['type'],
        '%module' => $captcha_info['module'],
      ), WATCHDOG_NOTICE);
    }

    // If CAPTCHA was on a login form: stop validating, quit the current request
    // and forward to the current page (like a reload) to prevent loging in.
    // We do that because the log in procedure, which happens after
    // captcha_validate(), does not check error conditions of extra form
    // elements like the CAPTCHA.
    if ($form_id == 'user_login' || $form_id == 'user_login_block') {
      drupal_goto($_GET['q']);
    }
  }

  // Unset the solution to prevent reuse of the same CAPTCHA solution
  // by a spammer that repeats posting a form without requesting
  // (and thus rendering) a new form. Note that a new CAPTCHA solution is only
  // set at the pre_render phase.
  unset($_SESSION['captcha'][$form_id][$captcha_token]);
}

/**
 * Implementation of form #pre_render.
 *
 * The main purpose of this function is to store the solution of the CAPTCHA
 * in the $_SESSION variable.
 */
function captcha_pre_render($form) {
  $form_id = $form['captcha']['captcha_info']['#value']['form_id'];

  // Unset the CAPTCHA if non-CAPTCHA persistent and the CAPTCHA has
  // already been successfully solved for this form.
  // This needs to be done in this pre_render phase when previewing for example
  // nodes and comments before submission.
  // On submission of such a forms for preview, captcha_form_alter() is called
  // *before* the CAPTCHA validation function (which sets
  // $_SESSION['captcha'][$form_id]['success'] to TRUE on a correctly answered
  // CAPTCHA). After this the form_values are entered in the generated form
  // and this form is presented with the preview.
  // This means that captcha_form_alter() can't know if the CAPTCHA was
  // correctly answered and consequently adds a CAPTCHA to the form.
  // The pre_render phase happens after the validation phase and makes it
  // possible to remove the CAPTCHA from the form after all.
  if (_captcha_persistence_skip($form_id)) {
    unset($form['captcha']);
    return $form;
  }

  // count the number of unsolved CAPTCHAs and unset the oldest if too many
  // minus 1 is needed because 'success' is also an item of $_SESSION['captcha'][$form_id]
  if (isset($_SESSION['captcha'][$form_id]) && count($_SESSION['captcha'][$form_id]) - 1 > CAPTCHA_UNSOLVED_CHALLENGES_MAX) {
    foreach (array_keys($_SESSION['captcha'][$form_id]) as $captcha_token) {
      if ($captcha_token != 'success') {
        unset($_SESSION['captcha'][$form_id][$captcha_token]);
        break;
      }
    }
  }

  // store the current CAPTCHA solution in $_SESSION
  $captcha_token = $form['captcha']['captcha_token']['#value'];
  $_SESSION['captcha'][$form_id][$captcha_token] = $form['captcha']['captcha_solution']['#value'];
  $_SESSION['captcha'][$form_id]['success'] = FALSE;

  // empty the value of the captcha_response form item before rendering
  $form['captcha']['captcha_response']['#value'] = '';
  return $form;
}

/**
 * Pre_render function to place the CAPTCHA form element just above the last submit button
 */
function captcha_pre_render_place_captcha($form) {

  // search the weights of the buttons in the form
  $button_weights = array();
  foreach (element_children($form) as $key) {
    if ($key == 'buttons' || isset($form[$key]['#type']) && ($form[$key]['#type'] == 'submit' || $form[$key]['#type'] == 'button')) {
      $button_weights[] = $form[$key]['#weight'];
    }
  }
  if ($button_weights) {

    // set the weight of the CAPTCHA element a tiny bit smaller than the lightest button weight
    // (note that the default resolution of #weight values is 1/1000 (see drupal/includes/form.inc))
    $first_button_weight = min($button_weights);
    $form['captcha']['#weight'] = $first_button_weight - 0.5 / 1000.0;

    // make sure the form gets sorted before rendering
    unset($form['#sorted']);
  }
  return $form;
}

/**
 * Default implementation of hook_captcha
 */
function captcha_captcha($op, $captcha_type = '') {
  switch ($op) {
    case 'list':
      return array(
        'Math',
      );
    case 'generate':
      if ($captcha_type == 'Math') {
        $result = array();
        $answer = mt_rand(1, 20);
        $x = mt_rand(1, $answer);
        $y = $answer - $x;
        $result['solution'] = "{$answer}";
        $result['form']['captcha_response'] = array(
          '#type' => 'textfield',
          '#title' => t('Math Question'),
          '#description' => t('Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.'),
          '#field_prefix' => t('@x + @y = ', array(
            '@x' => $x,
            '@y' => $y,
          )),
          '#size' => 4,
          '#maxlength' => 2,
          '#required' => TRUE,
        );
        return $result;
      }
  }
}

Functions

Namesort descending Description
captcha_captcha Default implementation of hook_captcha
captcha_form_alter Implementation of hook_form_alter().
captcha_help Implementation of hook_help().
captcha_menu Implementation of hook_menu().
captcha_perm Implementation of hook_perm().
captcha_pre_render Implementation of form #pre_render.
captcha_pre_render_place_captcha Pre_render function to place the CAPTCHA form element just above the last submit button
captcha_requirements Implementation of hook_requirements().
captcha_theme Implementation of hook_theme().
captcha_validate Implementation of form #validate.
_captcha_get_description Get the description which appears above the CAPTCHA in forms. If the locale module is enabled, an optional language code can be given
_captcha_persistence_skip Helper function for checking if the CAPTCHA for the given form_id should be skipped because of CAPTCHA persistence.

Constants

Namesort descending Description
CAPTCHA_PERSISTENCE_SHOW_ALWAYS
CAPTCHA_PERSISTENCE_SKIP_ONCE_SUCCESSFUL
CAPTCHA_PERSISTENCE_SKIP_ONCE_SUCCESSFUL_PER_FORM
CAPTCHA_UNSOLVED_CHALLENGES_MAX @file This module enables basic CAPTCHA functionality: administrators can add a CAPTCHA to desired forms that users without the 'skip CAPTCHA' permission (typically anonymous visitors) have to solve.