You are here

function _captcha_get_captcha_placement in CAPTCHA 8

Same name and namespace in other branches
  1. 6.2 captcha.inc \_captcha_get_captcha_placement()
  2. 7 captcha.inc \_captcha_get_captcha_placement()

Helper function to get placement information for a given form_id.

1 call to _captcha_get_captcha_placement()
captcha_form_alter in ./captcha.module
Implements hook_form_alter().

File

./captcha.inc, line 216
General CAPTCHA functionality and helper functions.

Code

function _captcha_get_captcha_placement($form_id, $form) {

  // Get CAPTCHA placement map from cache. Two levels of cache:
  // static variable in this function and storage in the variables table.
  static $placement_map = NULL;
  $write_cache = FALSE;

  // Try first level cache.
  if ($placement_map === NULL) {

    // If first level cache missed: try second level cache.
    if ($cache = \Drupal::cache()
      ->get('captcha_placement_map_cache')) {
      $placement_map = $cache->data;
    }
    else {

      // If second level cache missed: initialize the placement map
      // and let other modules hook into this with the
      // hook_captcha_placement_map hook.
      // By default however, probably all Drupal core forms
      // are already correctly handled with the best effort guess
      // based on the 'actions' element (see below).
      $placement_map = \Drupal::moduleHandler()
        ->invokeAll('captcha_placement_map');
      $write_cache = TRUE;
    }
  }

  // Query the placement map.
  if (array_key_exists($form_id, $placement_map)) {
    $placement = $placement_map[$form_id];
  }
  else {

    // If there is an "actions" button group, a good placement
    // is just before that.
    if (isset($form['actions']) && isset($form['actions']['#type']) && $form['actions']['#type'] === 'actions') {
      $placement = [
        'path' => [],
        'key' => 'actions',
        // #type 'actions' defaults to 100.
        'weight' => isset($form['actions']['#weight']) ? $form['actions']['#weight'] - 1 : 99,
      ];
    }
    else {

      // Search the form for buttons and guess placement from it.
      $buttons = _captcha_search_buttons($form);
      if (count($buttons)) {

        // Pick first button.
        // TODO: make this more sofisticated? Use cases needed.
        $placement = isset($buttons[count($buttons) - 1]) ? $buttons[count($buttons) - 1] : $buttons[0];
      }
      else {

        // Use NULL when no buttons were found.
        $placement = NULL;
      }
    }

    // Store calculated placement in cache.
    $placement_map[$form_id] = $placement;
    $write_cache = TRUE;
  }
  if ($write_cache) {
    \Drupal::cache()
      ->set('captcha_placement_map_cache', $placement_map);
  }
  return $placement;
}