You are here

function honeypot_form_alter in Honeypot 8

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

Implements hook_form_alter().

Add Honeypot features to forms enabled in the Honeypot admin interface.

File

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

Code

function honeypot_form_alter(&$form, FormStateInterface $form_state, $form_id) {

  // Don't use for maintenance mode forms (install, update, etc.).
  if (defined('MAINTENANCE_MODE')) {
    return;
  }

  // Add a tag to all forms, so that if they are cached and honeypot
  // configuration is changed, the cached forms are invalidated and honeypot
  // protection can be re-evaluated.
  $form['#cache']['tags'][] = 'config:honeypot.settings';

  // Get list of unprotected forms and setting for whether to protect all forms.
  $unprotected_forms = \Drupal::config('honeypot.settings')
    ->get('unprotected_forms');
  $protect_all_forms = \Drupal::config('honeypot.settings')
    ->get('protect_all_forms');

  // If configured to protect all forms, add protection to every form.
  if ($protect_all_forms && !in_array($form_id, $unprotected_forms)) {

    // Don't protect system forms - only admins should have access, and system
    // forms may be programmatically submitted by drush and other modules.
    if (preg_match('/[^a-zA-Z]system_/', $form_id) === 0 && preg_match('/[^a-zA-Z]search_/', $form_id) === 0 && preg_match('/[^a-zA-Z]views_exposed_form_/', $form_id) === 0) {
      honeypot_add_form_protection($form, $form_state, [
        'honeypot',
        'time_restriction',
      ]);
    }
  }
  elseif ($forms_to_protect = honeypot_get_protected_forms()) {
    foreach ($forms_to_protect as $protect_form_id) {

      // For most forms, do a straight check on the form ID.
      if ($form_id == $protect_form_id) {
        honeypot_add_form_protection($form, $form_state, [
          'honeypot',
          'time_restriction',
        ]);
      }
    }
  }
}