captcha.module

Tracking 7.x-1.x branch
  1. drupal
    1. 5 contributions/captcha/captcha.module
    2. 6 contributions/captcha/captcha.module
    3. 7 contributions/captcha/captcha.module

This module enables basic CAPTCHA functionality: administrators can add a CAPTCHA to desired forms that users without the 'skip CAPTCHA' permission (typically anonymous visitors) have to solve.

Functions & methods

NameDescription
captcha_captchaDefault implementation of hook_captcha().
captcha_cronImplementation of hook_cron().
captcha_element_infoImplementation of hook_element_info().
captcha_element_processProcess callback for CAPTCHA form element.
captcha_form_alterImplementation of hook_form_alter().
captcha_helpImplementation of hook_help().
captcha_menuImplementation of hook_menu().
captcha_modules_enabledImplements hook_modules_enabled.
captcha_permissionImplementation of hook_permission().
captcha_pre_render_processPre-render callback for additional processing of a CAPTCHA form element.
captcha_themeImplementation of hook_theme().
captcha_validateCAPTCHA validation handler.
captcha_validate_case_insensitive_equalityCAPTCHA validation function to tests case insensitive equality.
captcha_validate_case_insensitive_ignore_spacesCAPTCHA validation function to tests case insensitive equality while ignoring spaces.
captcha_validate_ignore_spacesCAPTCHA validation function to tests equality while ignoring spaces.
captcha_validate_strict_equalityCAPTCHA validation function to tests strict equality.
theme_captchaTheme function for a CAPTCHA element.
_captcha_get_posted_captcha_infoHelper function for getting the posted CAPTCHA info (posted form_id and CAPTCHA sessions ID) from a form in case it is posted.

Constants

NameDescription
CAPTCHA_DEFAULT_VALIDATION_CASE_INSENSITIVE
CAPTCHA_DEFAULT_VALIDATION_CASE_SENSITIVE
CAPTCHA_PERSISTENCE_SHOW_ALWAYS
CAPTCHA_PERSISTENCE_SKIP_ONCE_SUCCESSFUL
CAPTCHA_PERSISTENCE_SKIP_ONCE_SUCCESSFUL_PER_FORM_INSTANCE
CAPTCHA_PERSISTENCE_SKIP_ONCE_SUCCESSFUL_PER_FORM_TYPE
CAPTCHA_STATUS_EXAMPLE
CAPTCHA_STATUS_SOLVED
CAPTCHA_STATUS_UNSOLVED

File

View source
  1. <?php
  2. /**
  3. * @file
  4. * This module enables basic CAPTCHA functionality:
  5. * administrators can add a CAPTCHA to desired forms that users without
  6. * the 'skip CAPTCHA' permission (typically anonymous visitors) have
  7. * to solve.
  8. *
  9. */
  10. /**
  11. * Constants for CAPTCHA persistence.
  12. * TODO: change these integers to strings because the CAPTCHA settings form saves them as strings in the variables table anyway?
  13. */
  14. // Always add a CAPTCHA (even on every page of a multipage workflow).
  15. define('CAPTCHA_PERSISTENCE_SHOW_ALWAYS', 0);
  16. // Only one CAPTCHA has to be solved per form instance/multi-step workflow.
  17. define('CAPTCHA_PERSISTENCE_SKIP_ONCE_SUCCESSFUL_PER_FORM_INSTANCE', 1);
  18. // Once the user answered correctly for a CAPTCHA on a certain form type,
  19. // no more CAPTCHAs will be offered anymore for that form.
  20. define('CAPTCHA_PERSISTENCE_SKIP_ONCE_SUCCESSFUL_PER_FORM_TYPE', 2);
  21. // Once the user answered correctly for a CAPTCHA on the site,
  22. // no more CAPTCHAs will be offered anymore.
  23. define('CAPTCHA_PERSISTENCE_SKIP_ONCE_SUCCESSFUL', 3);
  24. define('CAPTCHA_STATUS_UNSOLVED', 0);
  25. define('CAPTCHA_STATUS_SOLVED', 1);
  26. define('CAPTCHA_STATUS_EXAMPLE', 2);
  27. define('CAPTCHA_DEFAULT_VALIDATION_CASE_SENSITIVE', 0);
  28. define('CAPTCHA_DEFAULT_VALIDATION_CASE_INSENSITIVE', 1);
  29. /**
  30. * Implementation of hook_help().
  31. */
  32. function captcha_help($path, $arg) {
  33. switch ($path) {
  34. case 'admin/help#captcha':
  35. $output = '<p>' . t('"CAPTCHA" is an acronym for "Completely Automated Public Turing test to tell Computers and Humans Apart". It is typically a challenge-response test to determine whether the user is human. The CAPTCHA module is a tool to fight automated submission by malicious users (spamming) of for example comments forms, user registration forms, guestbook forms, etc. You can extend the desired forms with an additional challenge, which should be easy for a human to solve correctly, but hard enough to keep automated scripts and spam bots out.') . '</p>';
  36. $output .= '<p>' . t('Note that the CAPTCHA module interacts with page caching (see <a href="!performancesettings">performance settings</a>). Because the challenge should be unique for each generated form, the caching of the page it appears on is prevented. Make sure that these forms do not appear on too many pages or you will lose much caching efficiency. For example, if you put a CAPTCHA on the user login block, which typically appears on each page for anonymous visitors, caching will practically be disabled. The comment submission forms are another example. In this case you should set the <em>Location of comment submission form</em> to <em>Display on separate page</em> in the comment settings of the relevant <a href="!contenttypes">content types</a> for better caching efficiency.',
  37. array(
  38. '!performancesettings' => url('admin/config/development/performance'),
  39. '!contenttypes' => url('admin/structure/types'),
  40. )
  41. ) . '</p>';
  42. $output .= '<p>' . t('CAPTCHA is a trademark of Carnegie Mellon University.') . '</p>';
  43. return $output;
  44. case 'admin/config/people/captcha':
  45. case 'admin/config/people/captcha/captcha':
  46. case 'admin/config/people/captcha/captcha/settings':
  47. $output = '<p>' . t('A CAPTCHA can be added to virtually each Drupal form. Some default forms are already provided in the form list, but arbitrary forms can be easily added and managed when the option <em>Add CAPTCHA administration links to forms</em> is enabled.') . '</p>';
  48. $output .= '<p>' . t('Users with the <em>Skip CAPTCHA</em> <a href="@perm">permission</a> won\'t be offered a challenge. Be sure to grant this permission to the trusted users (e.g. site administrators). If you want to test a protected form, be sure to do it as a user without the <em>Skip CAPTCHA</em> permission (e.g. as anonymous user).', array('@perm' => url('admin/people/permissions'))) . '</p>';
  49. return $output;
  50. }
  51. }
  52. /**
  53. * Implementation of hook_menu().
  54. */
  55. function captcha_menu() {
  56. $items = array();
  57. // main configuration page of the basic CAPTCHA module
  58. $items['admin/config/people/captcha'] = array(
  59. 'title' => 'CAPTCHA',
  60. 'description' => 'Administer how and where CAPTCHAs are used.',
  61. 'file' => 'captcha.admin.inc',
  62. 'page callback' => 'drupal_get_form',
  63. 'page arguments' => array('captcha_admin_settings'),
  64. 'access arguments' => array('administer CAPTCHA settings'),
  65. 'type' => MENU_NORMAL_ITEM,
  66. );
  67. // the default local task (needed when other modules want to offer
  68. // alternative CAPTCHA types and their own configuration page as local task)
  69. $items['admin/config/people/captcha/captcha'] = array(
  70. 'title' => 'CAPTCHA',
  71. 'access arguments' => array('administer CAPTCHA settings'),
  72. 'type' => MENU_DEFAULT_LOCAL_TASK,
  73. 'weight' => -20,
  74. );
  75. $items['admin/config/people/captcha/captcha/settings'] = array(
  76. 'title' => 'General settings',
  77. 'access arguments' => array('administer CAPTCHA settings'),
  78. 'type' => MENU_DEFAULT_LOCAL_TASK,
  79. 'weight' => 0,
  80. );
  81. $items['admin/config/people/captcha/captcha/examples'] = array(
  82. 'title' => 'Examples',
  83. 'description' => 'An overview of the available challenge types with examples.',
  84. 'file' => 'captcha.admin.inc',
  85. 'page callback' => 'drupal_get_form',
  86. 'page arguments' => array('captcha_examples', 6, 7),
  87. 'access arguments' => array('administer CAPTCHA settings'),
  88. 'type' => MENU_LOCAL_TASK,
  89. 'weight' => 5,
  90. );
  91. $items['admin/config/people/captcha/captcha/captcha_point'] = array(
  92. 'title' => 'CAPTCHA point administration',
  93. 'file' => 'captcha.admin.inc',
  94. 'page callback' => 'captcha_point_admin',
  95. 'page arguments' => array(6, 7),
  96. 'access arguments' => array('administer CAPTCHA settings'),
  97. 'type' => MENU_CALLBACK,
  98. );
  99. return $items;
  100. }
  101. /**
  102. * Implementation of hook_permission().
  103. */
  104. function captcha_permission() {
  105. return array(
  106. 'administer CAPTCHA settings' => array(
  107. 'title' => t('Administer CAPTCHA settings'),
  108. ),
  109. 'skip CAPTCHA' => array(
  110. 'title' => t('Skip CAPTCHA'),
  111. 'description' => t('Users with this permission will not be offered a CAPTCHA.'),
  112. ),
  113. );
  114. }
  115. /**
  116. * Implementation of hook_theme().
  117. */
  118. function captcha_theme() {
  119. return array(
  120. 'captcha_admin_settings_captcha_points' => array(
  121. 'render element' => 'form',
  122. ),
  123. 'captcha' => array(
  124. 'render element' => 'element',
  125. ),
  126. );
  127. }
  128. /**
  129. * Implementation of hook_cron().
  130. *
  131. * Remove old entries from captcha_sessions table.
  132. */
  133. function captcha_cron() {
  134. // Remove challenges older than 1 day.
  135. db_delete('captcha_sessions')
  136. ->condition('timestamp', REQUEST_TIME - 60*60*24, '<')
  137. ->execute();
  138. }
  139. /**
  140. * Implementation of hook_element_info().
  141. */
  142. function captcha_element_info() {
  143. // Define the CAPTCHA form element with default properties.
  144. $captcha_element = array(
  145. '#input' => TRUE,
  146. '#process' => array('captcha_element_process'),
  147. // The type of challenge: e.g. 'default', 'none', 'captcha/Math', 'image_captcha/Image', ...
  148. '#captcha_type' => 'default',
  149. '#default_value' => '',
  150. // CAPTCHA in admin mode: presolve the CAPTCHA and always show it (despite previous successful responses).
  151. '#captcha_admin_mode' => FALSE,
  152. // The default CAPTCHA validation function.
  153. // TODO: should this be a single string or an array of strings (combined in OR fashion)?
  154. '#captcha_validate' => 'captcha_validate_strict_equality',
  155. );
  156. // Override the default CAPTCHA validation function for case insensitive validation.
  157. // TODO: shouldn't this be done somewhere else, e.g. in form_alter?
  158. if (CAPTCHA_DEFAULT_VALIDATION_CASE_INSENSITIVE == variable_get('captcha_default_validation', CAPTCHA_DEFAULT_VALIDATION_CASE_INSENSITIVE)) {
  159. $captcha_element['#captcha_validate'] = 'captcha_validate_case_insensitive_equality';
  160. }
  161. return array('captcha' => $captcha_element);
  162. }
  163. /**
  164. * Process callback for CAPTCHA form element.
  165. */
  166. function captcha_element_process($element, &$form_state, $complete_form) {
  167. module_load_include('inc', 'captcha');
  168. // Add Javascript for general CAPTCHA functionality.
  169. drupal_add_js(drupal_get_path('module', 'captcha') . '/captcha.js');
  170. // Prevent caching of the page with CAPTCHA elements.
  171. // This needs to be done even if the CAPTCHA will be ommitted later:
  172. // other untrusted users should not get a cached page when
  173. // the current untrusted user can skip the current CAPTCHA.
  174. global $conf;
  175. $conf['cache'] = FALSE;
  176. // Get the form ID of the form we are currently processing (which is not
  177. // necessary the same form that is submitted (if any).
  178. $this_form_id = $complete_form['form_id']['#value'];
  179. // Get the CAPTCHA session ID.
  180. // If there is a submitted form: try to retrieve and reuse the
  181. // CAPTCHA session ID from the posted data.
  182. list($posted_form_id, $posted_captcha_sid) = _captcha_get_posted_captcha_info($element, $form_state, $this_form_id);
  183. if ($this_form_id == $posted_form_id && isset($posted_captcha_sid)) {
  184. $captcha_sid = $posted_captcha_sid;
  185. }
  186. else {
  187. // Generate a new CAPTCHA session if we could not reuse one from a posted form.
  188. $captcha_sid = _captcha_generate_captcha_session($this_form_id, CAPTCHA_STATUS_UNSOLVED);
  189. }
  190. // Store CAPTCHA session ID as hidden field.
  191. // Strictly speaking, it is not necessary to send the CAPTCHA session id
  192. // with the form, as the one time CAPTCHA token (see lower) is enough.
  193. // However, we still send it along, because it can help debugging
  194. // problems on live sites with only access to the markup.
  195. $element['captcha_sid'] = array(
  196. '#type' => 'hidden',
  197. '#value' => $captcha_sid,
  198. );
  199. // Additional one time CAPTCHA token: store in database and send with form.
  200. $captcha_token = md5(mt_rand());
  201. db_update('captcha_sessions')
  202. ->fields(array('token' => $captcha_token))
  203. ->condition('csid', $captcha_sid)
  204. ->execute();
  205. $element['captcha_token'] = array(
  206. '#type' => 'hidden',
  207. '#value' => $captcha_token,
  208. );
  209. // Get implementing module and challenge for CAPTCHA.
  210. list($captcha_type_module, $captcha_type_challenge) = _captcha_parse_captcha_type($element['#captcha_type']);
  211. // Store CAPTCHA information for further processing in
  212. // - $form_state['captcha_info'], which survives a form rebuild (e.g. node
  213. // preview), useful in _captcha_get_posted_captcha_info().
  214. // - $element['#captcha_info'], for post processing functions that do not
  215. // receive a $form_state argument (e.g. the pre_render callback).
  216. $form_state['captcha_info'] = array(
  217. 'this_form_id' => $this_form_id,
  218. 'posted_form_id' => $posted_form_id,
  219. 'captcha_sid' => $captcha_sid,
  220. 'module' => $captcha_type_module,
  221. 'captcha_type' => $captcha_type_challenge,
  222. );
  223. $element['#captcha_info'] = array(
  224. 'form_id' => $this_form_id,
  225. 'captcha_sid' => $captcha_sid,
  226. );
  227. if (_captcha_required_for_user($captcha_sid, $this_form_id) || $element['#captcha_admin_mode']) {
  228. // Generate a CAPTCHA and its solution
  229. // (note that the CAPTCHA session ID is given as third argument).
  230. $captcha = module_invoke($captcha_type_module, 'captcha', 'generate', $captcha_type_challenge, $captcha_sid);
  231. if (!isset($captcha['form']) || !isset($captcha['solution'])) {
  232. // The selected module did not return what we expected: log about it and quit.
  233. watchdog('CAPTCHA',
  234. 'CAPTCHA problem: unexpected result from hook_captcha() of module %module when trying to retrieve challenge type %type for form %form_id.',
  235. array('%type' => $captcha_type_challenge, '%module' => $captcha_type_module, '%form_id' => $this_form_id),
  236. WATCHDOG_ERROR);
  237. return $element;
  238. }
  239. // Add form elements from challenge as children to CAPTCHA form element.
  240. $element['captcha_widgets'] = $captcha['form'];
  241. // Add a validation callback for the CAPTCHA form element (when not in admin mode).
  242. if (!$element['#captcha_admin_mode']) {
  243. $element['#element_validate'] = array('captcha_validate');
  244. }
  245. // Set a custom CAPTCHA validate function if requested.
  246. if (isset($captcha['captcha_validate'])) {
  247. $element['#captcha_validate'] = $captcha['captcha_validate'];
  248. }
  249. // Set the theme function.
  250. $element['#theme'] = 'captcha';
  251. // Add pre_render callback for additional CAPTCHA processing.
  252. $element['#pre_render'] = array('captcha_pre_render_process');
  253. // Store the solution in the #captcha_info array.
  254. $element['#captcha_info']['solution'] = $captcha['solution'];
  255. // Make sure we can use a top level form value $form_state['values']['captcha_response'], even if the form has #tree=true.
  256. $element['#tree'] = FALSE;
  257. }
  258. return $element;
  259. }
  260. /**
  261. * Theme function for a CAPTCHA element.
  262. *
  263. * Render it in a fieldset if a description of the CAPTCHA
  264. * is available. Render it as is otherwise.
  265. */
  266. function theme_captcha($variables) {
  267. $element = $variables['element'];
  268. if (!empty($element['#description']) && isset($element['captcha_widgets'])) {
  269. $fieldset = array(
  270. '#type' => 'fieldset',
  271. '#title' => t('CAPTCHA'),
  272. '#description' => $element['#description'],
  273. '#children' => drupal_render_children($element),
  274. '#attributes' => array('class' => array('captcha')),
  275. );
  276. return theme('fieldset', array('element' => $fieldset));
  277. }
  278. else {
  279. return '<div class="captcha">' . drupal_render_children($element) . '</div>';
  280. }
  281. }
  282. /**
  283. * Implementation of hook_form_alter().
  284. *
  285. * This function adds a CAPTCHA to forms for untrusted users if needed and adds
  286. * CAPTCHA administration links for site administrators if this option is enabled.
  287. */
  288. function captcha_form_alter(&$form, &$form_state, $form_id) {
  289. if (!user_access('skip CAPTCHA')) {
  290. // Visitor does not have permission to skip CAPTCHAs.
  291. module_load_include('inc', 'captcha');
  292. // Get CAPTCHA type and module for given form_id.
  293. $captcha_point = captcha_get_form_id_setting($form_id);
  294. if ($captcha_point && $captcha_point->captcha_type) {
  295. module_load_include('inc', 'captcha');
  296. // Build CAPTCHA form element.
  297. $captcha_element = array(
  298. '#type' => 'captcha',
  299. '#captcha_type' => $captcha_point->module . '/' . $captcha_point->captcha_type,
  300. );
  301. // Add a CAPTCHA description if required.
  302. if (variable_get('captcha_add_captcha_description', TRUE)) {
  303. $captcha_element['#description'] = _captcha_get_description();
  304. }
  305. // Get placement in form and insert in form.
  306. $captcha_placement = _captcha_get_captcha_placement($form_id, $form);
  307. _captcha_insert_captcha_element($form, $captcha_placement, $captcha_element);
  308. }
  309. }
  310. else if (
  311. variable_get('captcha_administration_mode', FALSE)
  312. && user_access('administer CAPTCHA settings')
  313. && (arg(0) != 'admin' || variable_get('captcha_allow_on_admin_pages', FALSE))
  314. ) {
  315. // Add CAPTCHA administration tools.
  316. module_load_include('inc', 'captcha');
  317. $captcha_point = captcha_get_form_id_setting($form_id);
  318. // For administrators: show CAPTCHA info and offer link to configure it
  319. $captcha_element = array(
  320. '#type' => 'fieldset',
  321. '#title' => t('CAPTCHA'),
  322. '#collapsible' => TRUE,
  323. '#collapsed' => TRUE,
  324. '#attributes' => array('class' => array('captcha-admin-links')),
  325. );
  326. if ($captcha_point !== NULL && $captcha_point->captcha_type) {
  327. $captcha_element['#title'] = t('CAPTCHA: challenge "@type" enabled', array('@type' => $captcha_point->captcha_type));
  328. $captcha_element['#description'] = t('Untrusted users will see a CAPTCHA here (<a href="@settings">general CAPTCHA settings</a>).',
  329. array('@settings' => url('admin/config/people/captcha'))
  330. );
  331. $captcha_element['challenge'] = array(
  332. '#type' => 'item',
  333. '#title' => t('Enabled challenge'),
  334. '#markup' => t('%type by module %module (<a href="@change">change</a>, <a href="@disable">disable</a>)', array(
  335. '%type' => $captcha_point->captcha_type,
  336. '%module' => $captcha_point->module,
  337. '@change' => url("admin/config/people/captcha/captcha/captcha_point/$form_id", array('query' => drupal_get_destination())),
  338. '@disable' => url("admin/config/people/captcha/captcha/captcha_point/$form_id/disable", array('query' => drupal_get_destination())),
  339. )),
  340. );
  341. // Add an example challenge with solution.
  342. // This does not work with the reCAPTCHA and Egglue challenges as
  343. // discussed in http://drupal.org/node/487032 and
  344. // http://drupal.org/node/525586. As a temporary workaround, we
  345. // blacklist the reCAPTCHA and Egglue challenges and do not show
  346. // an example challenge.
  347. // TODO: Once the issues mentioned above are fixed, this workaround
  348. // should be removed.
  349. if ($captcha_point->module != 'recaptcha' && $captcha_point->module != 'egglue_captcha') {
  350. $captcha_element['example'] = array(
  351. '#type' => 'fieldset',
  352. '#title' => t('Example'),
  353. '#description' => t('This is a pre-solved, non-blocking example of this challenge.'),
  354. );
  355. $captcha_element['example']['example_captcha'] = array(
  356. '#type' => 'captcha',
  357. '#captcha_type' => $captcha_point->module . '/' . $captcha_point->captcha_type,
  358. '#captcha_admin_mode' => TRUE,
  359. );
  360. }
  361. }
  362. else {
  363. $captcha_element['#title'] = t('CAPTCHA: no challenge enabled');
  364. $captcha_element['add_captcha'] = array(
  365. '#markup' => l(t('Place a CAPTCHA here for untrusted users.'), "admin/config/people/captcha/captcha/captcha_point/$form_id", array('query' => drupal_get_destination()))
  366. );
  367. }
  368. // Get placement in form and insert in form.
  369. $captcha_placement = _captcha_get_captcha_placement($form_id, $form);
  370. _captcha_insert_captcha_element($form, $captcha_placement, $captcha_element);
  371. }
  372. // Add a warning about caching on the Perfomance settings page.
  373. if ($form_id == 'system_performance_settings') {
  374. $icon = theme('image', array('path' => 'misc/watchdog-warning.png', 'width' => 18, 'height' => 18, 'alt' => t('warning'), 'title' => t('warning')));
  375. $form['caching']['captcha'] = array(
  376. '#type' => 'item',
  377. '#title' => t('CAPTCHA'),
  378. '#markup' => t('!icon The CAPTCHA module will disable the caching of pages that contain a CAPTCHA element.', array(
  379. '!icon' => '<span class="icon">' . $icon . '</span>')
  380. ),
  381. '#attributes' => array('class' => array('warning')),
  382. );
  383. }
  384. }
  385. /**
  386. * CAPTCHA validation function to tests strict equality.
  387. * @param $solution the solution of the test.
  388. * @param $response the response to the test.
  389. * @return TRUE when strictly equal, FALSE otherwise.
  390. */
  391. function captcha_validate_strict_equality($solution, $response) {
  392. return $solution === $response;
  393. }
  394. /**
  395. * CAPTCHA validation function to tests case insensitive equality.
  396. * @param $solution the solution of the test.
  397. * @param $response the response to the test.
  398. * @return TRUE when case insensitive equal, FALSE otherwise.
  399. */
  400. function captcha_validate_case_insensitive_equality($solution, $response) {
  401. return drupal_strtolower($solution) === drupal_strtolower($response);
  402. }
  403. /**
  404. * CAPTCHA validation function to tests equality while ignoring spaces.
  405. * @param $solution the solution of the test.
  406. * @param $response the response to the test.
  407. * @return TRUE when equal (ignoring spaces), FALSE otherwise.
  408. */
  409. function captcha_validate_ignore_spaces($solution, $response) {
  410. return preg_replace('/\s/', '', $solution) === preg_replace('/\s/', '', $response);
  411. }
  412. /**
  413. * CAPTCHA validation function to tests case insensitive equality while ignoring spaces.
  414. * @param $solution the solution of the test.
  415. * @param $response the response to the test.
  416. * @return TRUE when equal (ignoring spaces), FALSE otherwise.
  417. */
  418. function captcha_validate_case_insensitive_ignore_spaces($solution, $response) {
  419. return preg_replace('/\s/', '', drupal_strtolower($solution)) === preg_replace('/\s/', '', drupal_strtolower($response));
  420. }
  421. /**
  422. * Helper function for getting the posted CAPTCHA info (posted form_id and
  423. * CAPTCHA sessions ID) from a form in case it is posted.
  424. *
  425. * This function hides the form processing mess for several use cases an
  426. * browser bug workarounds.
  427. * For example: $element['#post'] can typically be used to get the posted
  428. * form_id and captcha_sid, but in the case of node preview situations
  429. * (with correct CAPTCHA response) that does not work and we can get them from
  430. * $form_state['clicked_button']['#post'].
  431. * However with Internet Explorer 7, the latter does not work either when
  432. * submitting the forms (with only one text field) with the enter key
  433. * (see http://drupal.org/node/534168), in which case we also have to check
  434. * $form_state['buttons']['button']['0']['#post'].
  435. *
  436. * @todo for Drupal 7 version: is this IE7 workaround still needed?
  437. *
  438. * @param $element the CAPTCHA element.
  439. * @param $form_state the form state structure to extract the info from.
  440. * @param $this_form_id the form ID of the form we are currently processing
  441. * (which is not necessarily the form that was posted).
  442. *
  443. * @return an array with $posted_form_id and $post_captcha_sid (with NULL values
  444. * if the values could not be found, e.g. for a fresh form).
  445. */
  446. function _captcha_get_posted_captcha_info($element, $form_state, $this_form_id) {
  447. if ($form_state['submitted'] && isset($form_state['captcha_info'])) {
  448. // We are handling (or rebuilding) an already submitted form,
  449. // so we already determined the posted form ID and CAPTCHA session ID
  450. // for this form (from before submitting). Reuse this info.
  451. $posted_form_id = $form_state['captcha_info']['posted_form_id'];
  452. $posted_captcha_sid = $form_state['captcha_info']['captcha_sid'];
  453. }
  454. else {
  455. // We have to determine the posted form ID and CAPTCHA session ID
  456. // from the post data.
  457. // Because we possibly use raw post data here,
  458. // we should be extra cautious and filter this data.
  459. $posted_form_id = isset($form_state['input']['form_id']) ?
  460. preg_replace("/[^a-z0-9_]/", "", (string) $form_state['input']['form_id'])
  461. : NULL;
  462. $posted_captcha_sid = isset($form_state['input']['captcha_sid']) ?
  463. (int) $form_state['input']['captcha_sid']
  464. : NULL;
  465. $posted_captcha_token = isset($form_state['input']['captcha_token']) ?
  466. preg_replace("/[^a-zA-Z0-9]/", "", (string) $form_state['input']['captcha_token'])
  467. : NULL;
  468. if ($posted_form_id == $this_form_id) {
  469. // Check if the posted CAPTCHA token is valid for the posted CAPTCHA
  470. // session ID. Note that we could just check the validity of the CAPTCHA
  471. // token and extract the CAPTCHA session ID from that (without looking at
  472. // the actual posted CAPTCHA session ID). However, here we check both
  473. // the posted CAPTCHA token and session ID: it is a bit more stringent
  474. // and the database query should also be more efficient (because there is
  475. // an index on the CAPTCHA session ID).
  476. if ($posted_captcha_sid != NULL) {
  477. $expected_captcha_token = db_query(
  478. "SELECT token FROM {captcha_sessions} WHERE csid = :csid",
  479. array(':csid' => $posted_captcha_sid)
  480. )->fetchField();
  481. if ($expected_captcha_token !== $posted_captcha_token) {
  482. drupal_set_message(t('CAPTCHA session reuse attack detected.'), 'error');
  483. // Invalidate the CAPTCHA session.
  484. $posted_captcha_sid = NULL;
  485. }
  486. // Invalidate CAPTCHA token to avoid reuse.
  487. db_update('captcha_sessions')
  488. ->fields(array('token' => NULL))
  489. ->condition('csid', $posted_captcha_sid);
  490. }
  491. }
  492. else {
  493. // The CAPTCHA session ID is specific to the posted form.
  494. // Return NULL, so a new session will be generated for this other form.
  495. $posted_captcha_sid = NULL;
  496. }
  497. }
  498. return array($posted_form_id, $posted_captcha_sid);
  499. }
  500. /**
  501. * CAPTCHA validation handler.
  502. *
  503. * This function is placed in the main captcha.module file to make sure that
  504. * it is available (even for cached forms, which don't fire
  505. * captcha_form_alter(), and subsequently don't include additional include
  506. * files).
  507. */
  508. function captcha_validate($element, &$form_state) {
  509. $captcha_info = $form_state['captcha_info'];
  510. $form_id = $captcha_info['this_form_id'];
  511. // Get CAPTCHA response.
  512. $captcha_response = $form_state['values']['captcha_response'];
  513. // Get CAPTCHA session from CAPTCHA info
  514. // TODO: is this correct in all cases: see comment and code in previous revisions?
  515. $csid = $captcha_info['captcha_sid'];
  516. $solution = db_query(
  517. 'SELECT solution FROM {captcha_sessions} WHERE csid = :csid',
  518. array(':csid' => $csid)
  519. )
  520. ->fetchField();
  521. // @todo: what is the result when there is no entry for the captcha_session? in D6 it was FALSE, what in D7?
  522. if ($solution === FALSE) {
  523. // Unknown challenge_id.
  524. // TODO: this probably never happens anymore now that there is detection
  525. // for CAPTCHA session reuse attacks in _captcha_get_posted_captcha_info().
  526. form_set_error('captcha', t('CAPTCHA validation error: unknown CAPTCHA session ID. Contact the site administrator if this problem persists.'));
  527. watchdog('CAPTCHA',
  528. 'CAPTCHA validation error: unknown CAPTCHA session ID (%csid).',
  529. array('%csid' => var_export($csid, TRUE)),
  530. WATCHDOG_ERROR);
  531. }
  532. else {
  533. // Get CAPTCHA validate function or fall back on strict equality.
  534. $captcha_validate = $element['#captcha_validate'];
  535. if (!function_exists($captcha_validate)) {
  536. $captcha_validate = 'captcha_validate_strict_equality';
  537. }
  538. // Check the response with the CAPTCHA validation function.
  539. // Apart from the traditional expected $solution and received $response,
  540. // we also provide the CAPTCHA $element and $form_state arrays for more advanced use cases.
  541. if ($captcha_validate($solution, $captcha_response, $element, $form_state)) {
  542. // Correct answer.
  543. $_SESSION['captcha_success_form_ids'][$form_id] = $form_id;
  544. // Record success.
  545. db_update('captcha_sessions')
  546. ->condition('csid', $csid)
  547. ->fields(array('status' => CAPTCHA_STATUS_SOLVED))
  548. ->expression('attempts', 'attempts + 1')
  549. ->execute();
  550. }
  551. else {
  552. // Wrong answer.
  553. db_update('captcha_sessions')
  554. ->condition('csid', $csid)
  555. ->expression('attempts', 'attempts + 1')
  556. ->execute();
  557. // set form error
  558. form_set_error('captcha_response', t('The answer you entered for the CAPTCHA was not correct.'));
  559. // update wrong response counter
  560. variable_set('captcha_wrong_response_counter', variable_get('captcha_wrong_response_counter', 0) + 1);
  561. // log to watchdog if needed
  562. if (variable_get('captcha_log_wrong_responses', FALSE)) {
  563. watchdog('CAPTCHA',
  564. '%form_id post blocked by CAPTCHA module: challenge %challenge (by module %module), user answered "@response", but the solution was "@solution".',
  565. array('%form_id' => $form_id,
  566. '@response' => $captcha_response, '@solution' => $solution,
  567. '%challenge' => $captcha_info['captcha_type'], '%module' => $captcha_info['module'],
  568. ),
  569. WATCHDOG_NOTICE);
  570. }
  571. }
  572. }
  573. }
  574. /**
  575. * Pre-render callback for additional processing of a CAPTCHA form element.
  576. *
  577. * This encompasses tasks that should happen after the general FAPI processing
  578. * (building, submission and validation) but before rendering (e.g. storing the solution).
  579. *
  580. * @param $element the CAPTCHA form element
  581. * @return the manipulated element
  582. */
  583. function captcha_pre_render_process($element) {
  584. module_load_include('inc', 'captcha');
  585. // Get form and CAPTCHA information.
  586. $captcha_info = $element['#captcha_info'];
  587. $form_id = $captcha_info['form_id'];
  588. $captcha_sid = (int)($captcha_info['captcha_sid']);
  589. // Check if CAPTCHA is still required.
  590. // This check is done in a first phase during the element processing
  591. // (@see captcha_process), but it is also done here for better support
  592. // of multi-page forms. Take previewing a node submission for example:
  593. // when the challenge is solved correctely on preview, the form is still
  594. // not completely submitted, but the CAPTCHA can be skipped.
  595. if (_captcha_required_for_user($captcha_sid, $form_id) || $element['#captcha_admin_mode']) {
  596. // Update captcha_sessions table: store the solution of the generated CAPTCHA.
  597. _captcha_update_captcha_session($captcha_sid, $captcha_info['solution']);
  598. // Handle the response field if it is available and if it is a textfield.
  599. if (isset($element['captcha_widgets']['captcha_response']['#type']) && $element['captcha_widgets']['captcha_response']['#type'] == 'textfield') {
  600. // Before rendering: presolve an admin mode challenge or
  601. // empty the value of the captcha_response form item.
  602. $value = $element['#captcha_admin_mode'] ? $captcha_info['solution'] : '';
  603. $element['captcha_widgets']['captcha_response']['#value'] = $value;
  604. }
  605. }
  606. else {
  607. // Remove CAPTCHA widgets from form.
  608. unset($element['captcha_widgets']);
  609. }
  610. return $element;
  611. }
  612. /**
  613. * Default implementation of hook_captcha().
  614. */
  615. function captcha_captcha($op, $captcha_type = '') {
  616. switch ($op) {
  617. case 'list':
  618. return array('Math');
  619. break;
  620. case 'generate':
  621. if ($captcha_type == 'Math') {
  622. $result = array();
  623. $answer = mt_rand(1, 20);
  624. $x = mt_rand(1, $answer);
  625. $y = $answer - $x;
  626. $result['solution'] = "$answer";
  627. // Build challenge widget.
  628. // Note that we also use t() for the math challenge itself. This makes
  629. // it possible to 'rephrase' the challenge a bit through localization
  630. // or string overrides.
  631. $result['form']['captcha_response'] = array(
  632. '#type' => 'textfield',
  633. '#title' => t('Math question'),
  634. '#description' => t('Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.'),
  635. '#field_prefix' => t('@x + @y = ', array('@x' => $x, '@y' => $y)),
  636. '#size' => 4,
  637. '#maxlength' => 2,
  638. '#required' => TRUE,
  639. );
  640. return $result;
  641. }
  642. elseif ($captcha_type == 'Test') {
  643. // This challenge is not visible through the administrative interface
  644. // as it is not listed in captcha_captcha('list'),
  645. // but it is meant for debugging and testing purposes.
  646. // TODO for Drupal 7 version: This should be done with a mock module,
  647. // but Drupal 6 does not support this (mock modules can not be hidden).
  648. $result = array(
  649. 'solution' => 'Test 123',
  650. 'form' => array(),
  651. );
  652. $result['form']['captcha_response'] = array(
  653. '#type' => 'textfield',
  654. '#title' => t('Test one two three'),
  655. '#required' => TRUE,
  656. );
  657. return $result;
  658. }
  659. break;
  660. }
  661. }
  662. /**
  663. * Implements hook_modules_enabled.
  664. */
  665. function captcha_modules_enabled() {
  666. // When new modules are enabled: clear the CAPTCHA placement cache, so that
  667. // new hook_captcha_placement_map hooks can be triggered.
  668. variable_del('captcha_placement_map_cache');
  669. }