You are here

function _captcha_get_captcha_placement in CAPTCHA 7

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

Helper function to get placement information for a given form_id.

Parameters

string $form_id: the form_id to get the placement information for.

array $form: if a form corresponding to the given form_id, if there is no placement info for the given form_id, this form is examined to guess the placement.

Return value

array placement info array (@see _captcha_insert_captcha_element() for more info about the fields 'path', 'key' and 'weight'.

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

File

./captcha.inc, line 333
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;

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

    // If first level cache missed: try second level cache.
    $placement_map = variable_get('captcha_placement_map_cache', NULL);
    if ($placement_map === NULL) {

      // 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 = module_invoke_all('captcha_placement_map');
    }
  }

  // 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 = array(
        'path' => array(),
        '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;
    variable_set('captcha_placement_map_cache', $placement_map);
  }
  return $placement;
}