Projet

Général

Profil

Paste
Télécharger (10,4 ko) Statistiques
| Branche: | Révision:

root / htmltest / sites / all / modules / honeypot / honeypot.module @ a5572547

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
 * Build an array of all the protected forms on the site, by form_id.
96
 *
97
 * @todo - Add in API call/hook to allow modules to add to this array.
98
 */
99
function honeypot_get_protected_forms() {
100
  $forms = &drupal_static(__FUNCTION__);
101

    
102
  // If the data isn't already in memory, get from cache or look it up fresh.
103
  if (!isset($forms)) {
104
    if ($cache = cache_get('honeypot_protected_forms')) {
105
      $forms = $cache->data;
106
    }
107
    else {
108
      // Look up all the honeypot forms in the variables table.
109
      $result = db_query("SELECT name FROM {variable} WHERE name LIKE 'honeypot_form_%'")->fetchCol();
110
      // Add each form that's enabled to the $forms array.
111
      foreach ($result as $variable) {
112
        if (variable_get($variable, 0)) {
113
          $forms[] = substr($variable, 14);
114
        }
115
      }
116

    
117
      // Save the cached data.
118
      cache_set('honeypot_protected_forms', $forms, 'cache');
119
    }
120
  }
121

    
122
  return $forms;
123
}
124

    
125
/**
126
 * Form builder function to add different types of protection to forms.
127
 *
128
 * @param array $options
129
 *   Array of options to be added to form. Currently accepts 'honeypot' and
130
 *   'time_restriction'.
131
 *
132
 * @return array
133
 *   Returns elements to be placed in a form's elements array to prevent spam.
134
 */
135
function honeypot_add_form_protection(&$form, &$form_state, $options = array()) {
136
  global $user;
137

    
138
  // Allow other modules to alter the protections applied to this form.
139
  drupal_alter('honeypot_form_protections', $options, $form);
140

    
141
  // Don't add any protections if the user can bypass the Honeypot.
142
  if (user_access('bypass honeypot protection')) {
143
    return;
144
  }
145

    
146
  // Build the honeypot element.
147
  if (in_array('honeypot', $options)) {
148
    // Get the element name (default is generic 'url').
149
    $honeypot_element = variable_get('honeypot_element_name', 'url');
150

    
151
    // Build the honeypot element.
152
    $honeypot_class = $honeypot_element . '-textfield';
153
    $form[$honeypot_element] = array(
154
      '#type' => 'textfield',
155
      '#title' => t('Leave this field blank'),
156
      '#size' => 20,
157
      '#weight' => 100,
158
      '#attributes' => array('autocomplete' => 'off'),
159
      '#element_validate' => array('_honeypot_honeypot_validate'),
160
      '#prefix' => '<div class="' . $honeypot_class . '">',
161
      '#suffix' => '</div>',
162
      // Hide honeypot.
163
      '#attached' => array(
164
        'css' => array(
165
          '.' . $honeypot_class . ' { display: none !important; }' => array('type' => 'inline'),
166
        ),
167
      ),
168
    );
169
  }
170

    
171
  // Build the time restriction element (if it's not disabled).
172
  if (in_array('time_restriction', $options) && variable_get('honeypot_time_limit', 5) != 0) {
173
    // Set the current time in a hidden value to be checked later.
174
    $form['honeypot_time'] = array(
175
      '#type' => 'hidden',
176
      '#title' => t('Timestamp'),
177
      '#default_value' => time(),
178
      '#element_validate' => array('_honeypot_time_restriction_validate'),
179
    );
180

    
181
    // Disable page caching to make sure timestamp isn't cached.
182
    if (user_is_anonymous()) {
183
      $GLOBALS['conf']['cache'] = 0;
184
    }
185
  }
186

    
187
  // Allow other modules to react to addition of form protection.
188
  if (!empty($options)) {
189
    module_invoke_all('honeypot_add_form_protection', $options, $form);
190
  }
191
}
192

    
193
/**
194
 * Validate honeypot field.
195
 */
196
function _honeypot_honeypot_validate($element, &$form_state) {
197
  // Get the honeypot field value.
198
  $honeypot_value = $element['#value'];
199

    
200
  // Make sure it's empty.
201
  if (!empty($honeypot_value)) {
202
    _honeypot_log($form_state['values']['form_id'], 'honeypot');
203
    form_set_error('', t('There was a problem with your form submission. Please refresh the page and try again.'));
204
  }
205
}
206

    
207
/**
208
 * Validate honeypot's time restriction field.
209
 */
210
function _honeypot_time_restriction_validate($element, &$form_state) {
211
  // Don't do anything if the triggering element is a preview button.
212
  if ($form_state['triggering_element']['#value'] == t('Preview')) {
213
    return;
214
  }
215

    
216
  // Get the time value.
217
  $honeypot_time = $form_state['values']['honeypot_time'];
218

    
219
  // Get the honeypot_time_limit.
220
  $time_limit = honeypot_get_time_limit($form_state['values']);
221

    
222
  // Make sure current time - (time_limit + form time value) is greater than 0.
223
  // If not, throw an error.
224
  if (time() < ($honeypot_time + $time_limit)) {
225
    _honeypot_log($form_state['values']['form_id'], 'honeypot_time');
226
    $time_limit = honeypot_get_time_limit();
227
    $form_state['values']['honeypot_time'] = time();
228
    form_set_error('', t('There was a problem with your form submission. Please wait @limit seconds and try again.', array('@limit' => $time_limit)));
229
  }
230
}
231

    
232
/**
233
 * Log blocked form submissions.
234
 *
235
 * @param string $form_id
236
 *   Form ID for the form on which submission was blocked.
237
 * @param string $type
238
 *   String indicating the reason the submission was blocked. Allowed values:
239
 *     - honeypot: If honeypot field was filled in.
240
 *     - honeypot_time: If form was completed before the configured time limit.
241
 */
242
function _honeypot_log($form_id, $type) {
243
  honeypot_log_failure($form_id, $type);
244
  if (variable_get('honeypot_log', 0)) {
245
    $variables = array(
246
      '%form'  => $form_id,
247
      '@cause' => ($type == 'honeypot') ? t('submission of a value in the honeypot field') : t('submission of the form in less than minimum required time'),
248
    );
249
    watchdog('honeypot', 'Blocked submission of %form due to @cause.', $variables);
250
  }
251
}
252

    
253
/**
254
 * Look up the time limit for the current user.
255
 *
256
 * @param array $form_values
257
 *   Array of form values (optional).
258
 */
259
function honeypot_get_time_limit($form_values = array()) {
260
  global $user;
261
  $honeypot_time_limit = variable_get('honeypot_time_limit', 5);
262

    
263
  // Only calculate time limit if honeypot_time_limit has a value > 0.
264
  if ($honeypot_time_limit) {
265
    // Get value from {honeypot_user} table for authenticated users.
266
    if ($user->uid) {
267
      $number = db_query("SELECT COUNT(*) FROM {honeypot_user} WHERE uid = :uid", array(':uid' => $user->uid))->fetchField();
268
    }
269
    // Get value from {flood} table for anonymous users.
270
    else {
271
      $number = db_query("SELECT COUNT(*) FROM {flood} WHERE event = :event AND identifier = :hostname AND timestamp > :time", array(
272
        ':event' => 'honeypot',
273
        ':hostname' => ip_address(),
274
        ':time' => time() - variable_get('honeypot_expire', 300),
275
      ))->fetchField();
276
    }
277
    // Don't add more than 30 days' worth of extra time.
278
    $honeypot_time_limit = $honeypot_time_limit + (int) min($honeypot_time_limit + exp($number), 2592000);
279
    $additions = module_invoke_all('honeypot_time_limit', $honeypot_time_limit, $form_values, $number);
280
    if (count($additions)) {
281
      $honeypot_time_limit += array_sum($additions);
282
    }
283
  }
284
  return $honeypot_time_limit;
285
}
286

    
287
/**
288
 * Log the failed submision with timestamp.
289
 *
290
 * @param string $form_id
291
 *   Form ID for the rejected form submission.
292
 * @param string $type
293
 *   String indicating the reason the submission was blocked. Allowed values:
294
 *     - honeypot: If honeypot field was filled in.
295
 *     - honeypot_time: If form was completed before the configured time limit.
296
 */
297
function honeypot_log_failure($form_id, $type) {
298
  global $user;
299

    
300
  // Log failed submissions for authenticated users.
301
  if ($user->uid) {
302
    db_insert('honeypot_user')
303
      ->fields(array(
304
        'uid' => $user->uid,
305
        'timestamp' => time(),
306
      ))
307
      ->execute();
308
  }
309
  // Register flood event for anonymous users.
310
  else {
311
    flood_register_event('honeypot');
312
  }
313

    
314
  // Allow other modules to react to honeypot rejections.
315
  module_invoke_all('honeypot_reject', $form_id, $user->uid, $type);
316
}