Projet

Général

Profil

Paste
Télécharger (11,9 ko) Statistiques
| Branche: | Révision:

root / drupal7 / sites / all / modules / honeypot / honeypot.module @ 87dbc3bf

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
      // Look up all the honeypot forms in the variables table.
146
      $result = db_query("SELECT name FROM {variable} WHERE name LIKE 'honeypot_form_%'")->fetchCol();
147
      // Add each form that's enabled to the $forms array.
148
      foreach ($result as $variable) {
149
        if (variable_get($variable, 0)) {
150
          $forms[] = substr($variable, 14);
151
        }
152
      }
153

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

    
159
  return $forms;
160
}
161

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

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

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

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

    
188
    // Build the honeypot element.
189
    $honeypot_class = $honeypot_element . '-textfield';
190
    $form[$honeypot_element] = array(
191
      '#type' => 'textfield',
192
      '#title' => t('Leave this field blank'),
193
      '#size' => 20,
194
      '#weight' => 100,
195
      '#attributes' => array('autocomplete' => 'off'),
196
      '#element_validate' => array('_honeypot_honeypot_validate'),
197
      '#prefix' => '<div class="' . $honeypot_class . '">',
198
      '#suffix' => '</div>',
199
      // Hide honeypot.
200
      '#attached' => array(
201
        'css' => array(
202
          '.' . $honeypot_class . ' { display: none !important; }' => array('type' => 'inline'),
203
        ),
204
      ),
205
    );
206
  }
207

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

    
218
    // Disable page caching to make sure timestamp isn't cached.
219
    if (user_is_anonymous()) {
220
      $GLOBALS['conf']['cache'] = 0;
221
    }
222
  }
223

    
224
  // Allow other modules to react to addition of form protection.
225
  if (!empty($options)) {
226
    module_invoke_all('honeypot_add_form_protection', $options, $form);
227
  }
228
}
229

    
230
/**
231
 * Validate honeypot field.
232
 */
233
function _honeypot_honeypot_validate($element, &$form_state) {
234
  // Get the honeypot field value.
235
  $honeypot_value = $element['#value'];
236

    
237
  // Make sure it's empty.
238
  if (!empty($honeypot_value)) {
239
    _honeypot_log($form_state['values']['form_id'], 'honeypot');
240
    form_set_error('', t('There was a problem with your form submission. Please refresh the page and try again.'));
241
  }
242
}
243

    
244
/**
245
 * Validate honeypot's time restriction field.
246
 */
247
function _honeypot_time_restriction_validate($element, &$form_state) {
248
  // Don't do anything if the triggering element is a preview button.
249
  if ($form_state['triggering_element']['#value'] == t('Preview')) {
250
    return;
251
  }
252

    
253
  // Get the time value.
254
  $honeypot_time = $form_state['values']['honeypot_time'];
255

    
256
  // Get the honeypot_time_limit.
257
  $time_limit = honeypot_get_time_limit($form_state['values']);
258

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

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

    
291
/**
292
 * Look up the time limit for the current user.
293
 *
294
 * @param array $form_values
295
 *   Array of form values (optional).
296
 */
297
function honeypot_get_time_limit($form_values = array()) {
298
  global $user;
299
  $honeypot_time_limit = variable_get('honeypot_time_limit', 5);
300

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

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

    
338
  // Log failed submissions for authenticated users.
339
  if ($user->uid) {
340
    db_insert('honeypot_user')
341
      ->fields(array(
342
        'uid' => $user->uid,
343
        'timestamp' => time(),
344
      ))
345
      ->execute();
346
  }
347
  // Register flood event for anonymous users.
348
  else {
349
    flood_register_event('honeypot');
350
  }
351

    
352
  // Allow other modules to react to honeypot rejections.
353
  module_invoke_all('honeypot_reject', $form_id, $user->uid, $type);
354

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

    
370
  // Trigger rules honeypot_reject event.
371
  if (module_exists('rules')) {
372
    rules_invoke_event('honeypot_reject', $form_id, $type);
373
  }
374
}