source: sipes/modules_contrib/captcha/captcha.module @ 1e95969

stableversion-3.0
Last change on this file since 1e95969 was 177a560, checked in by José Gregorio Puentes <jpuentes@…>, 8 años ago

se agrego el directorio de modulos contribuidos de drupal

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