Project

General

Profile

Paste
Download (12.7 KB) Statistics
| Branch: | Revision:

root / drupal7 / sites / all / modules / honeypot / honeypot.module @ 2c8c2b87

1
<?php
2

    
3
/**
4
 * @file
5
 * Honeypot module, for deterring spam bots from completing Drupal forms.
6
 */
7

    
8
/**
9
 * Implements hook_menu().
10
 */
11
function honeypot_menu() {
12
  $items['admin/config/content/honeypot'] = array(
13
    'title' => 'Honeypot configuration',
14
    'description' => 'Configure Honeypot spam prevention and the forms on which Honeypot will be used.',
15
    'page callback' => 'drupal_get_form',
16
    'page arguments' => array('honeypot_admin_form'),
17
    'access arguments' => array('administer honeypot'),
18
    'file' => 'honeypot.admin.inc',
19
  );
20

    
21
  return $items;
22
}
23

    
24
/**
25
 * Implements hook_permission().
26
 */
27
function honeypot_permission() {
28
  return array(
29
    'administer honeypot' => array(
30
      'title' => t('Administer Honeypot'),
31
      'description' => t('Administer Honeypot-protected forms and settings'),
32
    ),
33
    'bypass honeypot protection' => array(
34
      'title' => t('Bypass Honeypot protection'),
35
      'description' => t('Bypass Honeypot form protection.'),
36
    ),
37
  );
38
}
39

    
40
/**
41
 * Implements of hook_cron().
42
 */
43
function honeypot_cron() {
44
  // Delete {honeypot_user} entries older than the value of honeypot_expire.
45
  db_delete('honeypot_user')
46
    ->condition('timestamp', time() - variable_get('honeypot_expire', 300), '<')
47
    ->execute();
48
}
49

    
50
/**
51
 * Implements hook_form_alter().
52
 *
53
 * Add Honeypot features to forms enabled in the Honeypot admin interface.
54
 */
55
function honeypot_form_alter(&$form, &$form_state, $form_id) {
56
  // Don't use for maintenance mode forms (install, update, etc.).
57
  if (defined('MAINTENANCE_MODE')) {
58
    return;
59
  }
60

    
61
  $unprotected_forms = array(
62
    'user_login',
63
    'user_login_block',
64
    'search_form',
65
    'search_block_form',
66
    'views_exposed_form',
67
    'honeypot_admin_form',
68
  );
69

    
70
  // If configured to protect all forms, add protection to every form.
71
  if (variable_get('honeypot_protect_all_forms', 0) && !in_array($form_id, $unprotected_forms)) {
72
    // Don't protect system forms - only admins should have access, and system
73
    // forms may be programmatically submitted by drush and other modules.
74
    if (strpos($form_id, 'system_') === FALSE && strpos($form_id, 'search_') === FALSE && strpos($form_id, 'views_exposed_form_') === FALSE) {
75
      honeypot_add_form_protection($form, $form_state, array('honeypot', 'time_restriction'));
76
    }
77
  }
78

    
79
  // Otherwise add form protection to admin-configured forms.
80
  elseif ($forms_to_protect = honeypot_get_protected_forms()) {
81
    foreach ($forms_to_protect as $protect_form_id) {
82
      // For most forms, do a straight check on the form ID.
83
      if ($form_id == $protect_form_id) {
84
        honeypot_add_form_protection($form, $form_state, array('honeypot', 'time_restriction'));
85
      }
86
      // For webforms use a special check for variable form ID.
87
      elseif ($protect_form_id == 'webforms' && (strpos($form_id, 'webform_client_form') !== FALSE)) {
88
        honeypot_add_form_protection($form, $form_state, array('honeypot', 'time_restriction'));
89
      }
90
    }
91
  }
92
}
93

    
94
/**
95
 * Implements hook_trigger_info().
96
 */
97
function honeypot_trigger_info() {
98
  return array(
99
    'honeypot' => array(
100
      'honeypot_reject' => array(
101
        'label' => t('Honeypot rejection'),
102
      ),
103
    ),
104
  );
105
}
106

    
107
/**
108
 * Implements hook_rules_event_info()
109
 */
110
function honeypot_rules_event_info() {
111
  return array(
112
    'honeypot_reject' => array(
113
      'label' => t('Honeypot rejection'),
114
      'group' => t('Honeypot'),
115
      'variables' => array(
116
        'form_id' => array(
117
          'type' => 'text',
118
          'label' => t('Form ID of the form the user was disallowed from submitting.'),
119
        ),
120
        // Don't provide 'uid' in context because it is available as
121
        // site:current-user:uid.
122
        'type' => array(
123
          'type' => 'text',
124
          'label' => t('String indicating the reason the submission was blocked.'),
125
        ),
126
      ),
127
    ),
128
  );
129
}
130

    
131
/**
132
 * Build an array of all the protected forms on the site, by form_id.
133
 *
134
 * @todo - Add in API call/hook to allow modules to add to this array.
135
 */
136
function honeypot_get_protected_forms() {
137
  $forms = &drupal_static(__FUNCTION__);
138

    
139
  // If the data isn't already in memory, get from cache or look it up fresh.
140
  if (!isset($forms)) {
141
    if ($cache = cache_get('honeypot_protected_forms')) {
142
      $forms = $cache->data;
143
    }
144
    else {
145
      $forms = array();
146
      // Look up all the honeypot forms in the variables table.
147
      $result = db_query("SELECT name FROM {variable} WHERE name LIKE 'honeypot_form_%'")->fetchCol();
148
      // Add each form that's enabled to the $forms array.
149
      foreach ($result as $variable) {
150
        if (variable_get($variable, 0)) {
151
          $forms[] = substr($variable, 14);
152
        }
153
      }
154

    
155
      // Save the cached data.
156
      cache_set('honeypot_protected_forms', $forms, 'cache');
157
    }
158
  }
159

    
160
  return $forms;
161
}
162

    
163
/**
164
 * Form builder function to add different types of protection to forms.
165
 *
166
 * @param array $options
167
 *   Array of options to be added to form. Currently accepts 'honeypot' and
168
 *   'time_restriction'.
169
 *
170
 * @return array
171
 *   Returns elements to be placed in a form's elements array to prevent spam.
172
 */
173
function honeypot_add_form_protection(&$form, &$form_state, $options = array()) {
174
  global $user;
175

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

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

    
184
  // Build the honeypot element.
185
  if (in_array('honeypot', $options)) {
186
    // Get the element name (default is generic 'url').
187
    $honeypot_element = variable_get('honeypot_element_name', 'url');
188

    
189
    // Add 'autocomplete="off"' if configured.
190
    $attributes = array();
191
    if (variable_get('honeypot_autocomplete_attribute', 1)) {
192
      $attributes = array('autocomplete' => 'off');
193
    }
194

    
195
    // Build the honeypot element.
196
    $honeypot_class = $honeypot_element . '-textfield';
197
    $form[$honeypot_element] = array(
198
      '#type' => 'textfield',
199
      '#title' => t('Leave this field blank'),
200
      '#size' => 20,
201
      '#weight' => 100,
202
      '#attributes' => $attributes,
203
      '#element_validate' => array('_honeypot_honeypot_validate'),
204
      '#prefix' => '<div class="' . $honeypot_class . '">',
205
      '#suffix' => '</div>',
206
      // Hide honeypot using CSS.
207
      '#attached' => array(
208
        'css' => array(
209
          'data' => variable_get('file_public_path', conf_path() . '/files') . '/honeypot/honeypot.css',
210
        ),
211
      ),
212
    );
213
  }
214

    
215
  // Build the time restriction element (if it's not disabled).
216
  if (in_array('time_restriction', $options) && variable_get('honeypot_time_limit', 5) != 0) {
217
    // Set the current time in a hidden value to be checked later.
218
    $form['honeypot_time'] = array(
219
      '#type' => 'hidden',
220
      '#title' => t('Timestamp'),
221
      '#default_value' => time(),
222
      '#element_validate' => array('_honeypot_time_restriction_validate'),
223
    );
224

    
225
    // Disable page caching to make sure timestamp isn't cached.
226
    if (user_is_anonymous()) {
227
      $GLOBALS['conf']['cache'] = 0;
228
    }
229
  }
230

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

    
237
/**
238
 * Validate honeypot field.
239
 */
240
function _honeypot_honeypot_validate($element, &$form_state) {
241
  // Get the honeypot field value.
242
  $honeypot_value = $element['#value'];
243

    
244
  // Make sure it's empty.
245
  if (!empty($honeypot_value)) {
246
    _honeypot_log($form_state['values']['form_id'], 'honeypot');
247
    form_set_error('', t('There was a problem with your form submission. Please refresh the page and try again.'));
248
  }
249
}
250

    
251
/**
252
 * Validate honeypot's time restriction field.
253
 */
254
function _honeypot_time_restriction_validate($element, &$form_state) {
255
  // Don't do anything if the triggering element is a preview button.
256
  if ($form_state['triggering_element']['#value'] == t('Preview')) {
257
    return;
258
  }
259

    
260
  // Get the time value.
261
  $honeypot_time = $form_state['values']['honeypot_time'];
262

    
263
  // Get the honeypot_time_limit.
264
  $time_limit = honeypot_get_time_limit($form_state['values']);
265

    
266
  // Make sure current time - (time_limit + form time value) is greater than 0.
267
  // If not, throw an error.
268
  if (time() < ($honeypot_time + $time_limit)) {
269
    _honeypot_log($form_state['values']['form_id'], 'honeypot_time');
270
    // Get the time limit again, since it increases after first failure.
271
    $time_limit = honeypot_get_time_limit($form_state['values']);
272
    $form_state['values']['honeypot_time'] = time();
273
    form_set_error('', t('There was a problem with your form submission. Please wait @limit seconds and try again.', array('@limit' => $time_limit)));
274
  }
275
}
276

    
277
/**
278
 * Log blocked form submissions.
279
 *
280
 * @param string $form_id
281
 *   Form ID for the form on which submission was blocked.
282
 * @param string $type
283
 *   String indicating the reason the submission was blocked. Allowed values:
284
 *     - honeypot: If honeypot field was filled in.
285
 *     - honeypot_time: If form was completed before the configured time limit.
286
 */
287
function _honeypot_log($form_id, $type) {
288
  honeypot_log_failure($form_id, $type);
289
  if (variable_get('honeypot_log', 0)) {
290
    $variables = array(
291
      '%form'  => $form_id,
292
      '@cause' => ($type == 'honeypot') ? t('submission of a value in the honeypot field') : t('submission of the form in less than minimum required time'),
293
    );
294
    watchdog('honeypot', 'Blocked submission of %form due to @cause.', $variables);
295
  }
296
}
297

    
298
/**
299
 * Look up the time limit for the current user.
300
 *
301
 * @param array $form_values
302
 *   Array of form values (optional).
303
 */
304
function honeypot_get_time_limit($form_values = array()) {
305
  global $user;
306
  $honeypot_time_limit = variable_get('honeypot_time_limit', 5);
307

    
308
  // Only calculate time limit if honeypot_time_limit has a value > 0.
309
  if ($honeypot_time_limit) {
310
    // Get value from {honeypot_user} table for authenticated users.
311
    if ($user->uid) {
312
      $number = db_query("SELECT COUNT(*) FROM {honeypot_user} WHERE uid = :uid", array(':uid' => $user->uid))->fetchField();
313
    }
314
    // Get value from {flood} table for anonymous users.
315
    else {
316
      $number = db_query("SELECT COUNT(*) FROM {flood} WHERE event = :event AND identifier = :hostname AND timestamp > :time", array(
317
        ':event' => 'honeypot',
318
        ':hostname' => ip_address(),
319
        ':time' => time() - variable_get('honeypot_expire', 300),
320
      ))->fetchField();
321
    }
322
    // Don't add more than 30 days' worth of extra time.
323
    $honeypot_time_limit = (int) min($honeypot_time_limit + exp($number) - 1, 2592000);
324
    $additions = module_invoke_all('honeypot_time_limit', $honeypot_time_limit, $form_values, $number);
325
    if (count($additions)) {
326
      $honeypot_time_limit += array_sum($additions);
327
    }
328
  }
329
  return $honeypot_time_limit;
330
}
331

    
332
/**
333
 * Log the failed submision with timestamp.
334
 *
335
 * @param string $form_id
336
 *   Form ID for the rejected form submission.
337
 * @param string $type
338
 *   String indicating the reason the submission was blocked. Allowed values:
339
 *     - honeypot: If honeypot field was filled in.
340
 *     - honeypot_time: If form was completed before the configured time limit.
341
 */
342
function honeypot_log_failure($form_id, $type) {
343
  global $user;
344

    
345
  // Log failed submissions for authenticated users.
346
  if ($user->uid) {
347
    db_insert('honeypot_user')
348
      ->fields(array(
349
        'uid' => $user->uid,
350
        'timestamp' => time(),
351
      ))
352
      ->execute();
353
  }
354
  // Register flood event for anonymous users.
355
  else {
356
    flood_register_event('honeypot');
357
  }
358

    
359
  // Allow other modules to react to honeypot rejections.
360
  module_invoke_all('honeypot_reject', $form_id, $user->uid, $type);
361

    
362
  // Trigger honeypot_reject action.
363
  if (module_exists('trigger')) {
364
    $aids = trigger_get_assigned_actions('honeypot_reject');
365
    $context = array(
366
      'group' => 'honeypot',
367
      'hook' => 'honeypot_reject',
368
      'form_id' => $form_id,
369
      // Do not provide $user in context because it is available as a global.
370
      'type' => $type,
371
    );
372
    // Honeypot does not act on any specific object.
373
    $object = NULL;
374
    actions_do(array_keys($aids), $object, $context);
375
  }
376

    
377
  // Trigger rules honeypot_reject event.
378
  if (module_exists('rules')) {
379
    rules_invoke_event('honeypot_reject', $form_id, $type);
380
  }
381
}
382

    
383
/**
384
 * Create CSS file for Honeypot.
385
 */
386
function honeypot_create_css($element_name) {
387
  $path = 'public://honeypot';
388

    
389
  if (!file_prepare_directory($path, FILE_CREATE_DIRECTORY)) {
390
    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');
391
  }
392
  else {
393
    $filename = $path . '/honeypot.css';
394
    $data = '.' . $element_name . '-textfield { display: none !important; }';
395
    file_unmanaged_save_data($data, $filename, FILE_EXISTS_REPLACE);
396
  }
397
}