You are here

function captcha_pre_render in CAPTCHA 5.3

Same name and namespace in other branches
  1. 6 captcha.module \captcha_pre_render()

Implementation of form #pre_render.

The main purpose of this function is to store the solution of the CAPTCHA in the $_SESSION variable.

1 string reference to 'captcha_pre_render'
captcha_form_alter in ./captcha.module
Implementation of hook_form_alter().

File

./captcha.module, line 682
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.

Code

function captcha_pre_render($form_id, &$form) {

  // 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;
  }

  // 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 (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'] = '';
}