You are here

function honeypot_add_form_protection in Honeypot 6

Same name and namespace in other branches
  1. 8 honeypot.module \honeypot_add_form_protection()
  2. 7 honeypot.module \honeypot_add_form_protection()
  3. 2.0.x honeypot.module \honeypot_add_form_protection()

Form builder function to add different types of protection to forms.

Parameters

array $options: Array of options to be added to form. Currently accepts 'honeypot' and 'time_restriction'.

1 call to honeypot_add_form_protection()
honeypot_form_alter in ./honeypot.module
Implementation of hook_form_alter().

File

./honeypot.module, line 125
Honeypot module, for deterring spam bots from completing Drupal forms.

Code

function honeypot_add_form_protection(&$form, &$form_state, $options = array()) {
  global $user;

  // Allow other modules to alter the protections applied to this form.
  drupal_alter('honeypot_form_protections', $options, $form);

  // Don't add any protections if the user can bypass the Honeypot.
  if (user_access('bypass honeypot protection')) {
    return;
  }

  // Build the honeypot element.
  if (in_array('honeypot', $options)) {

    // Get the element name (default is generic 'url').
    $honeypot_element = variable_get('honeypot_element_name', 'url');

    // Build the honeypot element.
    $form[$honeypot_element] = array(
      '#type' => 'textfield',
      '#title' => t('Leave this field blank'),
      '#size' => 20,
      '#weight' => 100,
      '#element_validate' => array(
        '_honeypot_honeypot_validate',
      ),
      '#prefix' => '<div class="honeypot-textfield">',
      '#suffix' => '</div>',
    );
    $form['#pre_render'][] = '_honeypot_form_add_css';
  }

  // Build the time restriction element (if it's not disabled).
  if (in_array('time_restriction', $options) && variable_get('honeypot_time_limit', 5) != 0) {

    // Set the current time in a hidden value to be checked later.
    $form['honeypot_time'] = array(
      '#type' => 'hidden',
      '#title' => t('Timestamp'),
      '#default_value' => time(),
      '#element_validate' => array(
        '_honeypot_time_restriction_validate',
      ),
    );

    // Disable page caching to make sure timestamp isn't cached.
    if (user_is_anonymous()) {
      $GLOBALS['conf']['cache'] = CACHE_DISABLED;

      // Pressflow in CACHE_EXTERNAL caching mode additionally requires marking
      // this request as non-cacheable to bypass external caches (like Varnish).
      if (function_exists('drupal_page_is_cacheable')) {
        drupal_set_header('Cache-Control', 'no-cache, must-revalidate, post-check=0, pre-check=0', FALSE);
      }
    }
  }

  // Allow other modules to react to addition of form protection.
  if (!empty($options)) {
    module_invoke_all('honeypot_add_form_protection', $options, $form);
  }
}