'Honeypot configuration',
'description' => 'Configure Honeypot spam prevention and the forms on which Honeypot will be used.',
'page callback' => 'drupal_get_form',
'page arguments' => array('honeypot_admin_form'),
'access arguments' => array('administer honeypot'),
'file' => 'honeypot.admin.inc',
);
return $items;
}
/**
* Implements hook_permission().
*/
function honeypot_permission() {
return array(
'administer honeypot' => array(
'title' => t('Administer Honeypot'),
'description' => t('Administer Honeypot-protected forms and settings'),
),
'bypass honeypot protection' => array(
'title' => t('Bypass Honeypot protection'),
'description' => t('Bypass Honeypot form protection.'),
),
);
}
/**
* Implements hook_cron().
*/
function honeypot_cron() {
// Delete {honeypot_user} entries older than the value of honeypot_expire.
db_delete('honeypot_user')
->condition('timestamp', REQUEST_TIME - variable_get('honeypot_expire', 300), '<')
->execute();
// Regenerate the honeypot css file if it does not exist or is outdated.
$honeypot_css = honeypot_get_css_file_path();
$honeypot_element_name = variable_get('honeypot_element_name', 'url');
if (!file_exists($honeypot_css) || !honeypot_check_css($honeypot_element_name)) {
honeypot_create_css($honeypot_element_name);
}
}
/**
* Implements hook_form_alter().
*
* Add Honeypot features to forms enabled in the Honeypot admin interface.
*/
function honeypot_form_alter(&$form, &$form_state, $form_id) {
// Don't use for maintenance mode forms (install, update, etc.).
if (defined('MAINTENANCE_MODE')) {
return;
}
$unprotected_forms = array(
'user_login',
'user_login_block',
'search_form',
'search_block_form',
'views_exposed_form',
'honeypot_admin_form',
);
// If configured to protect all forms, add protection to every form.
if (variable_get('honeypot_protect_all_forms', 0) && !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, array('honeypot', 'time_restriction'));
}
}
// Otherwise add form protection to admin-configured forms.
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, array('honeypot', 'time_restriction'));
}
// For webforms use a special check for variable form ID.
elseif ($protect_form_id == 'webforms' && (strpos($form_id, 'webform_client_form') !== FALSE)) {
honeypot_add_form_protection($form, $form_state, array('honeypot', 'time_restriction'));
}
}
}
}
/**
* Implements hook_trigger_info().
*/
function honeypot_trigger_info() {
return array(
'honeypot' => array(
'honeypot_reject' => array(
'label' => t('Honeypot rejection'),
),
),
);
}
/**
* Implements hook_rules_event_info().
*/
function honeypot_rules_event_info() {
return array(
'honeypot_reject' => array(
'label' => t('Honeypot rejection'),
'group' => t('Honeypot'),
'variables' => array(
'form_id' => array(
'type' => 'text',
'label' => t('Form ID of the form the user was disallowed from submitting.'),
),
// Don't provide 'uid' in context because it is available as
// site:current-user:uid.
'type' => array(
'type' => 'text',
'label' => t('String indicating the reason the submission was blocked.'),
),
),
),
);
}
/**
* Implements hook_library().
*/
function honeypot_library() {
$info = system_get_info('module', 'honeypot');
$version = $info['version'];
// Library for Honeypot JS.
$libraries['timestamp.js'] = array(
'title' => 'Javascript to support timelimit on cached pages.',
'version' => $version,
'js' => array(
array(
'type' => 'setting',
'data' => array(
'honeypot' => array(
'jsToken' => honeypot_get_signed_timestamp('js_token:' . mt_rand(0, 2147483647)),
),
),
),
drupal_get_path('module', 'honeypot') . '/js/honeypot.js' => array(
'group' => JS_LIBRARY,
'weight' => 3,
),
),
);
return $libraries;
}
/**
* Build an array of all the protected forms on the site, by form_id.
*
* @todo - Add in API call/hook to allow modules to add to this array.
*/
function honeypot_get_protected_forms() {
$forms = &drupal_static(__FUNCTION__);
// If the data isn't already in memory, get from cache or look it up fresh.
if (!isset($forms)) {
if ($cache = cache_get('honeypot_protected_forms')) {
$forms = $cache->data;
}
else {
$forms = array();
// Look up all the honeypot forms in the variables table.
$result = db_query("SELECT name FROM {variable} WHERE name LIKE 'honeypot_form_%'")->fetchCol();
// Add each form that's enabled to the $forms array.
foreach ($result as $variable) {
if (variable_get($variable, 0)) {
$forms[] = substr($variable, 14);
}
}
// Save the cached data.
cache_set('honeypot_protected_forms', $forms, 'cache');
}
}
return $forms;
}
/**
* Form builder function to add different types of protection to forms.
*
* @param array $options
* Array of options to be added to form. Currently accepts 'honeypot' and
* 'time_restriction'.
*
* @return array
* Returns elements to be placed in a form's elements array to prevent spam.
*/
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');
// Add 'autocomplete="off"' if configured.
$attributes = array();
if (variable_get('honeypot_autocomplete_attribute', 1)) {
$attributes = array('autocomplete' => 'off');
}
// Get the path to the honeypot css file.
$honeypot_css = honeypot_get_css_file_path();
// Build the honeypot element.
$honeypot_class = $honeypot_element . '-textfield';
$form[$honeypot_element] = array(
'#type' => 'textfield',
'#title' => t('Leave this field blank'),
'#size' => 20,
'#weight' => 100,
'#attributes' => $attributes,
'#element_validate' => array('_honeypot_honeypot_validate'),
'#prefix' => '
',
'#suffix' => '
',
// Hide honeypot using CSS.
'#attached' => array(
'css' => array(
'data' => $honeypot_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' => honeypot_get_signed_timestamp(REQUEST_TIME),
'#element_validate' => array('_honeypot_time_restriction_validate'),
);
// Disable page caching to make sure timestamp isn't cached.
if (user_is_anonymous() && drupal_page_is_cacheable()) {
// Use javascript implementation if this page should be cached.
if (variable_get('honeypot_use_js_for_cached_pages', FALSE)) {
$form['honeypot_time']['#default_value'] = 'no_js_available';
$form['honeypot_time']['#attached']['library'][] = array('honeypot', 'timestamp.js');
$form['#attributes']['class'][] = 'honeypot-timestamp-js';
}
else {
drupal_page_is_cacheable(FALSE);
}
}
}
// Allow other modules to react to addition of form protection.
if (!empty($options)) {
module_invoke_all('honeypot_add_form_protection', $options, $form);
}
}
/**
* Validate honeypot field.
*/
function _honeypot_honeypot_validate($element, &$form_state) {
// Get the honeypot field value.
$honeypot_value = $element['#value'];
// Make sure it's empty.
if (!empty($honeypot_value)) {
_honeypot_log($form_state['values']['form_id'], 'honeypot');
form_set_error('', t('There was a problem with your form submission. Please refresh the page and try again.'));
}
}
/**
* Validate honeypot's time restriction field.
*/
function _honeypot_time_restriction_validate(&$element, &$form_state) {
if (!empty($form_state['programmed'])) {
// Don't do anything if the form was submitted programmatically.
return;
}
// Don't do anything if the triggering element is a preview button.
if ($form_state['triggering_element']['#value'] == t('Preview')) {
return;
}
if ($form_state['values']['honeypot_time'] == 'no_js_available') {
// Set an error, but do not penalize the user as it might be a legitimate
// attempt.
form_set_error('', t('You seem to have javascript disabled. Please confirm your form submission.'));
if (variable_get('honeypot_log', 0)) {
$variables = array(
'%form' => $form_state['values']['form_id'],
);
watchdog('honeypot', 'User tried to submit form %form without javascript enabled.', $variables);
}
// Update the value in $form_state and $element.
$form_state['values']['honeypot_time'] = honeypot_get_signed_timestamp(REQUEST_TIME);
$element['#value'] = $form_state['values']['honeypot_time'];
return;
}
$honeypot_time = FALSE;
// Update the honeypot_time for JS requests and get the $honeypot_time value.
if (strpos($form_state['values']['honeypot_time'], 'js_token:') === 0) {
$interval = _honeypot_get_interval_from_signed_js_value($form_state['values']['honeypot_time']);
if ($interval) {
// Set correct value for timestamp validation.
$honeypot_time = REQUEST_TIME - $interval;
// Update form_state and element values so they're correct.
$form_state['values']['honeypot_time'] = honeypot_get_signed_timestamp($honeypot_time);
$element['#value'] = $form_state['values']['honeypot_time'];
}
}
// Otherwise just get the $honeypot_time value.
else {
// Get the time value.
$honeypot_time = honeypot_get_time_from_signed_timestamp($form_state['values']['honeypot_time']);
}
// Get the honeypot_time_limit.
$time_limit = honeypot_get_time_limit($form_state['values']);
// Make sure current time - (time_limit + form time value) is greater than 0.
// If not, throw an error.
if (!$honeypot_time || REQUEST_TIME < ($honeypot_time + $time_limit)) {
_honeypot_log($form_state['values']['form_id'], 'honeypot_time');
// Get the time limit again, since it increases after first failure.
$time_limit = honeypot_get_time_limit($form_state['values']);
// Update the honeypot_time value in the form state and element.
$form_state['values']['honeypot_time'] = honeypot_get_signed_timestamp(REQUEST_TIME);
$element['#value'] = $form_state['values']['honeypot_time'];
form_set_error('', t('There was a problem with your form submission. Please wait @limit seconds and try again.', array('@limit' => $time_limit)));
}
}
/**
* Returns an interval if the given javascript submitted value is valid.
*
* @param string $honeypot_time
* The signed interval as submitted via javascript.
*
* @return int|FALSE
* The interval in seconds if the token is valid, FALSE otherwise.
*/
function _honeypot_get_interval_from_signed_js_value($honeypot_time) {
$t = explode('|', $honeypot_time);
if (count($t) != 3) {
return FALSE;
}
$js_token = $t[0] . '|' . $t[1];
$token_check = honeypot_get_time_from_signed_timestamp($js_token);
if (!$token_check) {
return FALSE;
}
$interval = (int) $t[2];
if ($interval == 0) {
return FALSE;
}
return $interval;
}
/**
* Log blocked form submissions.
*
* @param string $form_id
* Form ID for the form on which submission was blocked.
* @param string $type
* String indicating the reason the submission was blocked. Allowed values:
* - honeypot: If honeypot field was filled in.
* - honeypot_time: If form was completed before the configured time limit.
*/
function _honeypot_log($form_id, $type) {
honeypot_log_failure($form_id, $type);
if (variable_get('honeypot_log', 0)) {
$variables = array(
'%form' => $form_id,
'@cause' => ($type == 'honeypot') ? t('submission of a value in the honeypot field') : t('submission of the form in less than minimum required time'),
);
watchdog('honeypot', 'Blocked submission of %form due to @cause.', $variables);
}
}
/**
* Look up the time limit for the current user.
*
* @param array $form_values
* Array of form values (optional).
*/
function honeypot_get_time_limit($form_values = array()) {
global $user;
$honeypot_time_limit = variable_get('honeypot_time_limit', 5);
// Only calculate time limit if honeypot_time_limit has a value > 0.
if ($honeypot_time_limit) {
$expire_time = variable_get('honeypot_expire', 300);
// Query the {honeypot_user} table to determine the number of failed
// submissions for the current user.
$query = db_select('honeypot_user', 'hs')
->condition('uid', $user->uid)
->condition('timestamp', REQUEST_TIME - $expire_time, '>');
// For anonymous users, take the hostname into account.
if ($user->uid === 0) {
$query->condition('hostname', ip_address());
}
$number = $query->countQuery()->execute()->fetchField();
// Don't add more than 30 days' worth of extra time.
$honeypot_time_limit = (int) min($honeypot_time_limit + exp($number) - 1, 2592000);
$additions = module_invoke_all('honeypot_time_limit', $honeypot_time_limit, $form_values, $number);
if (count($additions)) {
$honeypot_time_limit += array_sum($additions);
}
}
return $honeypot_time_limit;
}
/**
* Log the failed submision with timestamp and hostname.
*
* @param string $form_id
* Form ID for the rejected form submission.
* @param string $type
* String indicating the reason the submission was blocked. Allowed values:
* - honeypot: If honeypot field was filled in.
* - honeypot_time: If form was completed before the configured time limit.
*/
function honeypot_log_failure($form_id, $type) {
global $user;
db_insert('honeypot_user')
->fields(array(
'uid' => $user->uid,
'hostname' => ip_address(),
'timestamp' => REQUEST_TIME,
))
->execute();
// Allow other modules to react to honeypot rejections.
module_invoke_all('honeypot_reject', $form_id, $user->uid, $type);
// Trigger honeypot_reject action.
if (module_exists('trigger')) {
$aids = trigger_get_assigned_actions('honeypot_reject');
$context = array(
'group' => 'honeypot',
'hook' => 'honeypot_reject',
'form_id' => $form_id,
// Do not provide $user in context because it is available as a global.
'type' => $type,
);
// Honeypot does not act on any specific object.
$object = NULL;
actions_do(array_keys($aids), $object, $context);
}
// Trigger rules honeypot_reject event.
if (module_exists('rules')) {
rules_invoke_event('honeypot_reject', $form_id, $type);
}
}
/**
* Retrieve the location of the Honeypot CSS file.
*
* @return string
* The path to the honeypot.css file.
*/
function honeypot_get_css_file_path() {
return honeypot_file_default_scheme() . '://honeypot/honeypot.css';
}
/**
* Create CSS file to hide the Honeypot field.
*
* @param string $element_name
* The honeypot element class name (e.g. 'url').
*/
function honeypot_create_css($element_name) {
$path = honeypot_file_default_scheme() . '://honeypot';
if (!file_prepare_directory($path, FILE_CREATE_DIRECTORY)) {
drupal_set_message(t('Unable to create Honeypot CSS directory, %path. Check the permissions on your files directory.', array('%path' => file_uri_target($path))), 'error');
}
else {
$filename = $path . '/honeypot.css';
$data = '.' . $element_name . '-textfield { display: none !important; }';
file_unmanaged_save_data($data, $filename, FILE_EXISTS_REPLACE);
}
}
/**
* Check Honeypot's CSS file for a given Honeypot element name.
*
* This function assumes the Honeypot CSS file already exists.
*
* @param string $element_name
* The honeypot element class name (e.g. 'url').
*
* @return bool
* TRUE if CSS is has element class name, FALSE if not.
*/
function honeypot_check_css($element_name) {
$path = honeypot_get_css_file_path();
$handle = fopen($path, 'r');
$contents = fread($handle, filesize($path));
fclose($handle);
if (strpos($contents, $element_name) === 1) {
return TRUE;
}
return FALSE;
}
/**
* Sign the timestamp $time.
*
* @param mixed $time
* The timestamp to sign.
*
* @return string
* A signed timestamp in the form timestamp|HMAC.
*/
function honeypot_get_signed_timestamp($time) {
return $time . '|' . drupal_hmac_base64($time, drupal_get_private_key());
}
/**
* Validate a signed timestamp.
*
* @param string $signed_timestamp
* A timestamp concateneted with the signature
*
* @return int
* The timestamp if the signature is correct, 0 otherwise.
*/
function honeypot_get_time_from_signed_timestamp($signed_timestamp) {
$honeypot_time = 0;
// Fail fast if timestamp was forged or saved with an older Honeypot version.
if (strpos($signed_timestamp, '|') === FALSE) {
return $honeypot_time;
}
list($timestamp, $received_hmac) = explode('|', $signed_timestamp);
if ($timestamp && $received_hmac) {
$calculated_hmac = drupal_hmac_base64($timestamp, drupal_get_private_key());
// Prevent leaking timing information, compare second order hmacs.
$random_key = drupal_random_bytes(32);
if (drupal_hmac_base64($calculated_hmac, $random_key) === drupal_hmac_base64($received_hmac, $random_key)) {
$honeypot_time = $timestamp;
}
}
return $honeypot_time;
}
/**
* Gets the default file stream for honeypot.
*
* @return
* 'public', 'private' or any other file scheme defined as the default.
*
* @see file_default_scheme()
*/
function honeypot_file_default_scheme() {
return variable_get('honeypot_file_default_scheme', file_default_scheme());
}