honeypot.module 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  1. <?php
  2. /**
  3. * @file
  4. * Honeypot module, for deterring spam bots from completing Drupal forms.
  5. */
  6. /**
  7. * Implements hook_menu().
  8. */
  9. function honeypot_menu() {
  10. $items['admin/config/content/honeypot'] = array(
  11. 'title' => 'Honeypot configuration',
  12. 'description' => 'Configure Honeypot spam prevention and the forms on which Honeypot will be used.',
  13. 'page callback' => 'drupal_get_form',
  14. 'page arguments' => array('honeypot_admin_form'),
  15. 'access arguments' => array('administer honeypot'),
  16. 'file' => 'honeypot.admin.inc',
  17. );
  18. return $items;
  19. }
  20. /**
  21. * Implements hook_permission().
  22. */
  23. function honeypot_permission() {
  24. return array(
  25. 'administer honeypot' => array(
  26. 'title' => t('Administer Honeypot'),
  27. 'description' => t('Administer Honeypot-protected forms and settings'),
  28. ),
  29. 'bypass honeypot protection' => array(
  30. 'title' => t('Bypass Honeypot protection'),
  31. 'description' => t('Bypass Honeypot form protection.'),
  32. ),
  33. );
  34. }
  35. /**
  36. * Implements of hook_cron().
  37. */
  38. function honeypot_cron() {
  39. // Delete {honeypot_user} entries older than the value of honeypot_expire.
  40. db_delete('honeypot_user')
  41. ->condition('timestamp', time() - variable_get('honeypot_expire', 300), '<')
  42. ->execute();
  43. }
  44. /**
  45. * Implements hook_form_alter().
  46. *
  47. * Add Honeypot features to forms enabled in the Honeypot admin interface.
  48. */
  49. function honeypot_form_alter(&$form, &$form_state, $form_id) {
  50. // Don't use for maintenance mode forms (install, update, etc.).
  51. if (defined('MAINTENANCE_MODE')) {
  52. return;
  53. }
  54. $unprotected_forms = array(
  55. 'user_login',
  56. 'user_login_block',
  57. 'search_form',
  58. 'search_block_form',
  59. 'views_exposed_form',
  60. 'honeypot_admin_form',
  61. );
  62. // If configured to protect all forms, add protection to every form.
  63. if (variable_get('honeypot_protect_all_forms', 0) && !in_array($form_id, $unprotected_forms)) {
  64. // Don't protect system forms - only admins should have access, and system
  65. // forms may be programmatically submitted by drush and other modules.
  66. if (strpos($form_id, 'system_') === FALSE && strpos($form_id, 'search_') === FALSE && strpos($form_id, 'views_exposed_form_') === FALSE) {
  67. honeypot_add_form_protection($form, $form_state, array('honeypot', 'time_restriction'));
  68. }
  69. }
  70. // Otherwise add form protection to admin-configured forms.
  71. elseif ($forms_to_protect = honeypot_get_protected_forms()) {
  72. foreach ($forms_to_protect as $protect_form_id) {
  73. // For most forms, do a straight check on the form ID.
  74. if ($form_id == $protect_form_id) {
  75. honeypot_add_form_protection($form, $form_state, array('honeypot', 'time_restriction'));
  76. }
  77. // For webforms use a special check for variable form ID.
  78. elseif ($protect_form_id == 'webforms' && (strpos($form_id, 'webform_client_form') !== FALSE)) {
  79. honeypot_add_form_protection($form, $form_state, array('honeypot', 'time_restriction'));
  80. }
  81. }
  82. }
  83. }
  84. /**
  85. * Implements hook_trigger_info().
  86. */
  87. function honeypot_trigger_info() {
  88. return array(
  89. 'honeypot' => array(
  90. 'honeypot_reject' => array(
  91. 'label' => t('Honeypot rejection'),
  92. ),
  93. ),
  94. );
  95. }
  96. /**
  97. * Implements hook_rules_event_info()
  98. */
  99. function honeypot_rules_event_info() {
  100. return array(
  101. 'honeypot_reject' => array(
  102. 'label' => t('Honeypot rejection'),
  103. 'group' => t('Honeypot'),
  104. 'variables' => array(
  105. 'form_id' => array(
  106. 'type' => 'text',
  107. 'label' => t('Form ID of the form the user was disallowed from submitting.'),
  108. ),
  109. // Don't provide 'uid' in context because it is available as
  110. // site:current-user:uid.
  111. 'type' => array(
  112. 'type' => 'text',
  113. 'label' => t('String indicating the reason the submission was blocked.'),
  114. ),
  115. ),
  116. ),
  117. );
  118. }
  119. /**
  120. * Build an array of all the protected forms on the site, by form_id.
  121. *
  122. * @todo - Add in API call/hook to allow modules to add to this array.
  123. */
  124. function honeypot_get_protected_forms() {
  125. $forms = &drupal_static(__FUNCTION__);
  126. // If the data isn't already in memory, get from cache or look it up fresh.
  127. if (!isset($forms)) {
  128. if ($cache = cache_get('honeypot_protected_forms')) {
  129. $forms = $cache->data;
  130. }
  131. else {
  132. // Look up all the honeypot forms in the variables table.
  133. $result = db_query("SELECT name FROM {variable} WHERE name LIKE 'honeypot_form_%'")->fetchCol();
  134. // Add each form that's enabled to the $forms array.
  135. foreach ($result as $variable) {
  136. if (variable_get($variable, 0)) {
  137. $forms[] = substr($variable, 14);
  138. }
  139. }
  140. // Save the cached data.
  141. cache_set('honeypot_protected_forms', $forms, 'cache');
  142. }
  143. }
  144. return $forms;
  145. }
  146. /**
  147. * Form builder function to add different types of protection to forms.
  148. *
  149. * @param array $options
  150. * Array of options to be added to form. Currently accepts 'honeypot' and
  151. * 'time_restriction'.
  152. *
  153. * @return array
  154. * Returns elements to be placed in a form's elements array to prevent spam.
  155. */
  156. function honeypot_add_form_protection(&$form, &$form_state, $options = array()) {
  157. global $user;
  158. // Allow other modules to alter the protections applied to this form.
  159. drupal_alter('honeypot_form_protections', $options, $form);
  160. // Don't add any protections if the user can bypass the Honeypot.
  161. if (user_access('bypass honeypot protection')) {
  162. return;
  163. }
  164. // Build the honeypot element.
  165. if (in_array('honeypot', $options)) {
  166. // Get the element name (default is generic 'url').
  167. $honeypot_element = variable_get('honeypot_element_name', 'url');
  168. // Build the honeypot element.
  169. $honeypot_class = $honeypot_element . '-textfield';
  170. $form[$honeypot_element] = array(
  171. '#type' => 'textfield',
  172. '#title' => t('Leave this field blank'),
  173. '#size' => 20,
  174. '#weight' => 100,
  175. '#attributes' => array('autocomplete' => 'off'),
  176. '#element_validate' => array('_honeypot_honeypot_validate'),
  177. '#prefix' => '<div class="' . $honeypot_class . '">',
  178. '#suffix' => '</div>',
  179. // Hide honeypot.
  180. '#attached' => array(
  181. 'css' => array(
  182. '.' . $honeypot_class . ' { display: none !important; }' => array('type' => 'inline'),
  183. ),
  184. ),
  185. );
  186. }
  187. // Build the time restriction element (if it's not disabled).
  188. if (in_array('time_restriction', $options) && variable_get('honeypot_time_limit', 5) != 0) {
  189. // Set the current time in a hidden value to be checked later.
  190. $form['honeypot_time'] = array(
  191. '#type' => 'hidden',
  192. '#title' => t('Timestamp'),
  193. '#default_value' => time(),
  194. '#element_validate' => array('_honeypot_time_restriction_validate'),
  195. );
  196. // Disable page caching to make sure timestamp isn't cached.
  197. if (user_is_anonymous()) {
  198. $GLOBALS['conf']['cache'] = 0;
  199. }
  200. }
  201. // Allow other modules to react to addition of form protection.
  202. if (!empty($options)) {
  203. module_invoke_all('honeypot_add_form_protection', $options, $form);
  204. }
  205. }
  206. /**
  207. * Validate honeypot field.
  208. */
  209. function _honeypot_honeypot_validate($element, &$form_state) {
  210. // Get the honeypot field value.
  211. $honeypot_value = $element['#value'];
  212. // Make sure it's empty.
  213. if (!empty($honeypot_value)) {
  214. _honeypot_log($form_state['values']['form_id'], 'honeypot');
  215. form_set_error('', t('There was a problem with your form submission. Please refresh the page and try again.'));
  216. }
  217. }
  218. /**
  219. * Validate honeypot's time restriction field.
  220. */
  221. function _honeypot_time_restriction_validate($element, &$form_state) {
  222. // Don't do anything if the triggering element is a preview button.
  223. if ($form_state['triggering_element']['#value'] == t('Preview')) {
  224. return;
  225. }
  226. // Get the time value.
  227. $honeypot_time = $form_state['values']['honeypot_time'];
  228. // Get the honeypot_time_limit.
  229. $time_limit = honeypot_get_time_limit($form_state['values']);
  230. // Make sure current time - (time_limit + form time value) is greater than 0.
  231. // If not, throw an error.
  232. if (time() < ($honeypot_time + $time_limit)) {
  233. _honeypot_log($form_state['values']['form_id'], 'honeypot_time');
  234. // Get the time limit again, since it increases after first failure.
  235. $time_limit = honeypot_get_time_limit($form_state['values']);
  236. $form_state['values']['honeypot_time'] = time();
  237. form_set_error('', t('There was a problem with your form submission. Please wait @limit seconds and try again.', array('@limit' => $time_limit)));
  238. }
  239. }
  240. /**
  241. * Log blocked form submissions.
  242. *
  243. * @param string $form_id
  244. * Form ID for the form on which submission was blocked.
  245. * @param string $type
  246. * String indicating the reason the submission was blocked. Allowed values:
  247. * - honeypot: If honeypot field was filled in.
  248. * - honeypot_time: If form was completed before the configured time limit.
  249. */
  250. function _honeypot_log($form_id, $type) {
  251. honeypot_log_failure($form_id, $type);
  252. if (variable_get('honeypot_log', 0)) {
  253. $variables = array(
  254. '%form' => $form_id,
  255. '@cause' => ($type == 'honeypot') ? t('submission of a value in the honeypot field') : t('submission of the form in less than minimum required time'),
  256. );
  257. watchdog('honeypot', 'Blocked submission of %form due to @cause.', $variables);
  258. }
  259. }
  260. /**
  261. * Look up the time limit for the current user.
  262. *
  263. * @param array $form_values
  264. * Array of form values (optional).
  265. */
  266. function honeypot_get_time_limit($form_values = array()) {
  267. global $user;
  268. $honeypot_time_limit = variable_get('honeypot_time_limit', 5);
  269. // Only calculate time limit if honeypot_time_limit has a value > 0.
  270. if ($honeypot_time_limit) {
  271. // Get value from {honeypot_user} table for authenticated users.
  272. if ($user->uid) {
  273. $number = db_query("SELECT COUNT(*) FROM {honeypot_user} WHERE uid = :uid", array(':uid' => $user->uid))->fetchField();
  274. }
  275. // Get value from {flood} table for anonymous users.
  276. else {
  277. $number = db_query("SELECT COUNT(*) FROM {flood} WHERE event = :event AND identifier = :hostname AND timestamp > :time", array(
  278. ':event' => 'honeypot',
  279. ':hostname' => ip_address(),
  280. ':time' => time() - variable_get('honeypot_expire', 300),
  281. ))->fetchField();
  282. }
  283. // Don't add more than 30 days' worth of extra time.
  284. $honeypot_time_limit = (int) min($honeypot_time_limit + exp($number) - 1, 2592000);
  285. $additions = module_invoke_all('honeypot_time_limit', $honeypot_time_limit, $form_values, $number);
  286. if (count($additions)) {
  287. $honeypot_time_limit += array_sum($additions);
  288. }
  289. }
  290. return $honeypot_time_limit;
  291. }
  292. /**
  293. * Log the failed submision with timestamp.
  294. *
  295. * @param string $form_id
  296. * Form ID for the rejected form submission.
  297. * @param string $type
  298. * String indicating the reason the submission was blocked. Allowed values:
  299. * - honeypot: If honeypot field was filled in.
  300. * - honeypot_time: If form was completed before the configured time limit.
  301. */
  302. function honeypot_log_failure($form_id, $type) {
  303. global $user;
  304. // Log failed submissions for authenticated users.
  305. if ($user->uid) {
  306. db_insert('honeypot_user')
  307. ->fields(array(
  308. 'uid' => $user->uid,
  309. 'timestamp' => time(),
  310. ))
  311. ->execute();
  312. }
  313. // Register flood event for anonymous users.
  314. else {
  315. flood_register_event('honeypot');
  316. }
  317. // Allow other modules to react to honeypot rejections.
  318. module_invoke_all('honeypot_reject', $form_id, $user->uid, $type);
  319. // Trigger honeypot_reject action.
  320. if (module_exists('trigger')) {
  321. $aids = trigger_get_assigned_actions('honeypot_reject');
  322. $context = array(
  323. 'group' => 'honeypot',
  324. 'hook' => 'honeypot_reject',
  325. 'form_id' => $form_id,
  326. // Do not provide $user in context because it is available as a global.
  327. 'type' => $type,
  328. );
  329. // Honeypot does not act on any specific object.
  330. $object = NULL;
  331. actions_do(array_keys($aids), $object, $context);
  332. }
  333. // Trigger rules honeypot_reject event.
  334. if (module_exists('rules')) {
  335. rules_invoke_event('honeypot_reject', $form_id, $type);
  336. }
  337. }