Projet

Général

Profil

Paste
Télécharger (31,2 ko) Statistiques
| Branche: | Révision:

root / drupal7 / sites / all / modules / captcha / captcha.module @ a2baadd1

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).
18
define('CAPTCHA_PERSISTENCE_SHOW_ALWAYS', 0);
19
// Only one CAPTCHA has to be solved per form instance/multi-step workflow.
20
define('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.
23
define('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.
26
define('CAPTCHA_PERSISTENCE_SKIP_ONCE_SUCCESSFUL', 3);
27

    
28
define('CAPTCHA_STATUS_UNSOLVED', 0);
29
define('CAPTCHA_STATUS_SOLVED', 1);
30
define('CAPTCHA_STATUS_EXAMPLE', 2);
31

    
32
define('CAPTCHA_DEFAULT_VALIDATION_CASE_SENSITIVE', 0);
33
define('CAPTCHA_DEFAULT_VALIDATION_CASE_INSENSITIVE', 1);
34

    
35
/**
36
 * Implementation of hook_help().
37
 */
38
function 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 <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.',
43
        array(
44
          '!performancesettings' => url('admin/config/development/performance'),
45
          '!contenttypes' => url('admin/structure/types'),
46
        )
47
      ) . '</p>';
48
      $output .= '<p>' . t('CAPTCHA is a trademark of Carnegie Mellon University.') . '</p>';
49
      return $output;
50
    case 'admin/config/people/captcha':
51
    case 'admin/config/people/captcha/captcha':
52
    case 'admin/config/people/captcha/captcha/settings':
53
      $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>';
54
      $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>';
55
      return $output;
56
  }
57
}
58

    
59
/**
60
 * Implementation of hook_menu().
61
 */
62
function captcha_menu() {
63
  $items = array();
64
  // main configuration page of the basic CAPTCHA module
65
  $items['admin/config/people/captcha'] = array(
66
    'title' => 'CAPTCHA',
67
    'description' => 'Administer how and where CAPTCHAs are used.',
68
    'file' => 'captcha.admin.inc',
69
    'page callback' => 'drupal_get_form',
70
    'page arguments' => array('captcha_admin_settings'),
71
    'access arguments' => array('administer CAPTCHA settings'),
72
    'type' => MENU_NORMAL_ITEM,
73
  );
74
  // the default local task (needed when other modules want to offer
75
  // alternative CAPTCHA types and their own configuration page as local task)
76
  $items['admin/config/people/captcha/captcha'] = array(
77
    'title' => 'CAPTCHA',
78
    'access arguments' => array('administer CAPTCHA settings'),
79
    'type' => MENU_DEFAULT_LOCAL_TASK,
80
    'weight' => -20,
81
  );
82
  $items['admin/config/people/captcha/captcha/settings'] = array(
83
    'title' => 'General settings',
84
    'access arguments' => array('administer CAPTCHA settings'),
85
    'type' => MENU_DEFAULT_LOCAL_TASK,
86
    'weight' => 0,
87
  );
88
  $items['admin/config/people/captcha/captcha/examples'] = array(
89
    'title' => 'Examples',
90
    'description' => 'An overview of the available challenge types with examples.',
91
    'file' => 'captcha.admin.inc',
92
    'page callback' => 'drupal_get_form',
93
    'page arguments' => array('captcha_examples', 6, 7),
94
    'access arguments' => array('administer CAPTCHA settings'),
95
    'type' => MENU_LOCAL_TASK,
96
    'weight' => 5,
97
  );
98
  $items['admin/config/people/captcha/captcha/captcha_point'] = array(
99
    'title' => 'CAPTCHA point administration',
100
    'file' => 'captcha.admin.inc',
101
    'page callback' => 'captcha_point_admin',
102
    'page arguments' => array(6, 7),
103
    'access arguments' => array('administer CAPTCHA settings'),
104
    'type' => MENU_CALLBACK,
105
  );
106
  return $items;
107
}
108

    
109
/**
110
 * Implementation of hook_permission().
111
 */
112
function captcha_permission() {
113
  return array(
114
    'administer CAPTCHA settings' => array(
115
      'title' => t('Administer CAPTCHA settings'),
116
    ),
117
    'skip CAPTCHA' => array(
118
      'title' => t('Skip CAPTCHA'),
119
      'description' => t('Users with this permission will not be offered a CAPTCHA.'),
120
    ),
121
  );
122
}
123

    
124
/**
125
 * Implementation of hook_theme().
126
 */
127
function captcha_theme() {
128
  return array(
129
    'captcha_admin_settings_captcha_points' => array(
130
      'render element' => 'form',
131
    ),
132
    'captcha' => array(
133
      'render element' => 'element',
134
    ),
135
  );
136
}
137

    
138
/**
139
 * Implementation of hook_cron().
140
 *
141
 * Remove old entries from captcha_sessions table.
142
 */
143
function captcha_cron() {
144
  // Remove challenges older than 1 day.
145
  db_delete('captcha_sessions')
146
    ->condition('timestamp', REQUEST_TIME - 60*60*24, '<')
147
    ->execute();
148
}
149

    
150

    
151
/**
152
 * Implementation of hook_element_info().
153
 */
154
function captcha_element_info() {
155
  // Define the CAPTCHA form element with default properties.
156
  $captcha_element = array(
157
    '#input' => TRUE,
158
    '#process' => array('captcha_element_process'),
159
    // The type of challenge: e.g. 'default', 'none', 'captcha/Math', 'image_captcha/Image', ...
160
    '#captcha_type' => 'default',
161
    '#default_value' => '',
162
    // CAPTCHA in admin mode: presolve the CAPTCHA and always show it (despite previous successful responses).
163
    '#captcha_admin_mode' => FALSE,
164
    // The default CAPTCHA validation function.
165
    // TODO: should this be a single string or an array of strings (combined in OR fashion)?
166
    '#captcha_validate' => 'captcha_validate_strict_equality',
167
  );
168
  // Override the default CAPTCHA validation function for case insensitive validation.
169
  // TODO: shouldn't this be done somewhere else, e.g. in form_alter?
170
  if (CAPTCHA_DEFAULT_VALIDATION_CASE_INSENSITIVE == variable_get('captcha_default_validation', CAPTCHA_DEFAULT_VALIDATION_CASE_INSENSITIVE)) {
171
    $captcha_element['#captcha_validate'] = 'captcha_validate_case_insensitive_equality';
172
  }
173
  return array('captcha' => $captcha_element);
174
}
175

    
176
/**
177
 * Process callback for CAPTCHA form element.
178
 */
179
function captcha_element_process($element, &$form_state, $complete_form) {
180

    
181
  module_load_include('inc', 'captcha');
182

    
183
  // Add Javascript for general CAPTCHA functionality.
184
  drupal_add_js(drupal_get_path('module', 'captcha') . '/captcha.js');
185

    
186
  // Prevent caching of the page with CAPTCHA elements.
187
  // This needs to be done even if the CAPTCHA will be ommitted later:
188
  // other untrusted users should not get a cached page when
189
  // the current untrusted user can skip the current CAPTCHA.
190
  global $conf;
191
  $conf['cache'] = FALSE;
192

    
193
  // Get the form ID of the form we are currently processing (which is not
194
  // necessary the same form that is submitted (if any).
195
  $this_form_id = $complete_form['form_id']['#value'];
196

    
197
  // Get the CAPTCHA session ID.
198
  // If there is a submitted form: try to retrieve and reuse the
199
  // CAPTCHA session ID from the posted data.
200
  list($posted_form_id, $posted_captcha_sid) = _captcha_get_posted_captcha_info($element, $form_state, $this_form_id);
201
  if ($this_form_id == $posted_form_id && isset($posted_captcha_sid)) {
202
    $captcha_sid = $posted_captcha_sid;
203
  }
204
  else {
205
    // Generate a new CAPTCHA session if we could not reuse one from a posted form.
206
    $captcha_sid = _captcha_generate_captcha_session($this_form_id, CAPTCHA_STATUS_UNSOLVED);
207
  }
208

    
209
  // Store CAPTCHA session ID as hidden field.
210
  // Strictly speaking, it is not necessary to send the CAPTCHA session id
211
  // with the form, as the one time CAPTCHA token (see lower) is enough.
212
  // However, we still send it along, because it can help debugging
213
  // problems on live sites with only access to the markup.
214
  $element['captcha_sid'] = array(
215
    '#type' => 'hidden',
216
    '#value' => $captcha_sid,
217
  );
218

    
219
  // Additional one time CAPTCHA token: store in database and send with form.
220
  $captcha_token = md5(mt_rand());
221
  db_update('captcha_sessions')
222
    ->fields(array('token' => $captcha_token))
223
    ->condition('csid', $captcha_sid)
224
    ->execute();
225
  $element['captcha_token'] = array(
226
    '#type' => 'hidden',
227
    '#value' => $captcha_token,
228
  );
229

    
230
  // Get implementing module and challenge for CAPTCHA.
231
  list($captcha_type_module, $captcha_type_challenge) = _captcha_parse_captcha_type($element['#captcha_type']);
232

    
233
  // Store CAPTCHA information for further processing in
234
  // - $form_state['captcha_info'], which survives a form rebuild (e.g. node
235
  //   preview), useful in _captcha_get_posted_captcha_info().
236
  // - $element['#captcha_info'], for post processing functions that do not
237
  //   receive a $form_state argument (e.g. the pre_render callback).
238
  $form_state['captcha_info'] = array(
239
    'this_form_id' => $this_form_id,
240
    'posted_form_id' => $posted_form_id,
241
    'captcha_sid' => $captcha_sid,
242
    'module' => $captcha_type_module,
243
    'captcha_type' => $captcha_type_challenge,
244
  );
245
  $element['#captcha_info'] = array(
246
    'form_id' => $this_form_id,
247
    'captcha_sid' => $captcha_sid,
248
  );
249

    
250

    
251
  if (_captcha_required_for_user($captcha_sid, $this_form_id) || $element['#captcha_admin_mode']) {
252
    // Generate a CAPTCHA and its solution
253
    // (note that the CAPTCHA session ID is given as third argument).
254
    $captcha = module_invoke($captcha_type_module, 'captcha', 'generate', $captcha_type_challenge, $captcha_sid);
255
    if (!isset($captcha['form']) || !isset($captcha['solution'])) {
256
      // The selected module did not return what we expected: log about it and quit.
257
      watchdog('CAPTCHA',
258
        'CAPTCHA problem: unexpected result from hook_captcha() of module %module when trying to retrieve challenge type %type for form %form_id.',
259
        array('%type' => $captcha_type_challenge, '%module' => $captcha_type_module, '%form_id' => $this_form_id),
260
        WATCHDOG_ERROR);
261
      return $element;
262
    }
263
    // Add form elements from challenge as children to CAPTCHA form element.
264
    $element['captcha_widgets'] = $captcha['form'];
265

    
266
    // Add a validation callback for the CAPTCHA form element (when not in admin mode).
267
    if (!$element['#captcha_admin_mode']) {
268
      $element['#element_validate'] = array('captcha_validate');
269
    }
270

    
271
    // Set a custom CAPTCHA validate function if requested.
272
    if (isset($captcha['captcha_validate'])) {
273
      $element['#captcha_validate'] = $captcha['captcha_validate'];
274
    }
275

    
276
    // Set the theme function.
277
    $element['#theme'] = 'captcha';
278

    
279
    // Add pre_render callback for additional CAPTCHA processing.
280
    if (!isset($element['#pre_render'])) {
281
      $element['#pre_render'] = array();
282
    }
283
    $element['#pre_render'][] = 'captcha_pre_render_process';
284

    
285
    // Store the solution in the #captcha_info array.
286
    $element['#captcha_info']['solution'] = $captcha['solution'];
287

    
288
    // Make sure we can use a top level form value $form_state['values']['captcha_response'], even if the form has #tree=true.
289
    $element['#tree'] = FALSE;
290

    
291
  }
292

    
293
  return $element;
294
}
295

    
296

    
297
/**
298
 * Theme function for a CAPTCHA element.
299
 *
300
 * Render it in a fieldset if a description of the CAPTCHA
301
 * is available. Render it as is otherwise.
302
 */
303
function theme_captcha($variables) {
304
  $element = $variables['element'];
305
  if (!empty($element['#description']) && isset($element['captcha_widgets'])) {
306
    $fieldset = array(
307
      '#type' => 'fieldset',
308
      '#title' => t('CAPTCHA'),
309
      '#description' => $element['#description'],
310
      '#children' => drupal_render_children($element),
311
      '#attributes' => array('class' => array('captcha')),
312
    );
313
    return theme('fieldset', array('element' => $fieldset));
314
  }
315
  else {
316
    return '<div class="captcha">' . drupal_render_children($element) . '</div>';
317
  }
318
}
319

    
320

    
321
/**
322
 * Implementation of hook_form_alter().
323
 *
324
 * This function adds a CAPTCHA to forms for untrusted users if needed and adds
325
 * CAPTCHA administration links for site administrators if this option is enabled.
326
 */
327
function captcha_form_alter(&$form, &$form_state, $form_id) {
328

    
329
  if (!user_access('skip CAPTCHA')) {
330
    // Visitor does not have permission to skip CAPTCHAs.
331
    module_load_include('inc', 'captcha');
332

    
333
    // Get CAPTCHA type and module for given form_id.
334
    $captcha_point = captcha_get_form_id_setting($form_id);
335
    if ($captcha_point && $captcha_point->captcha_type) {
336
      module_load_include('inc', 'captcha');
337
      // Build CAPTCHA form element.
338
      $captcha_element = array(
339
        '#type' => 'captcha',
340
        '#captcha_type' => $captcha_point->module . '/' . $captcha_point->captcha_type,
341
      );
342
      // Add a CAPTCHA description if required.
343
      if (variable_get('captcha_add_captcha_description', TRUE)) {
344
        $captcha_element['#description'] = _captcha_get_description();
345
      }
346

    
347
      // Get placement in form and insert in form.
348
      $captcha_placement = _captcha_get_captcha_placement($form_id, $form);
349
      _captcha_insert_captcha_element($form, $captcha_placement, $captcha_element);
350
    }
351
  }
352
  else if (
353
  variable_get('captcha_administration_mode', FALSE)
354
  && user_access('administer CAPTCHA settings')
355
  && (arg(0) != 'admin' || variable_get('captcha_allow_on_admin_pages', FALSE))
356
  ) {
357
    // Add CAPTCHA administration tools.
358
    module_load_include('inc', 'captcha');
359

    
360
    $captcha_point = captcha_get_form_id_setting($form_id);
361
    // For administrators: show CAPTCHA info and offer link to configure it
362
    $captcha_element = array(
363
      '#type' => 'fieldset',
364
      '#title' => t('CAPTCHA'),
365
      '#collapsible' => TRUE,
366
      '#collapsed' => TRUE,
367
      '#attributes' => array('class' => array('captcha-admin-links')),
368
    );
369
    if ($captcha_point !== NULL && $captcha_point->captcha_type) {
370
      $captcha_element['#title'] = t('CAPTCHA: challenge "@type" enabled', array('@type' => $captcha_point->captcha_type));
371
      $captcha_element['#description'] = t('Untrusted users will see a CAPTCHA here (<a href="@settings">general CAPTCHA settings</a>).',
372
        array('@settings' => url('admin/config/people/captcha'))
373
      );
374
      $captcha_element['challenge'] = array(
375
        '#type' => 'item',
376
        '#title' => t('Enabled challenge'),
377
        '#markup' => t('%type by module %module (<a href="@change">change</a>, <a href="@disable">disable</a>)', array(
378
          '%type' => $captcha_point->captcha_type,
379
          '%module' => $captcha_point->module,
380
          '@change' => url("admin/config/people/captcha/captcha/captcha_point/$form_id", array('query' => drupal_get_destination())),
381
          '@disable' => url("admin/config/people/captcha/captcha/captcha_point/$form_id/disable", array('query' => drupal_get_destination())),
382
        )),
383
      );
384
      // Add an example challenge with solution.
385
      // This does not work with the reCAPTCHA and Egglue challenges as
386
      // discussed in http://drupal.org/node/487032 and
387
      // http://drupal.org/node/525586. As a temporary workaround, we
388
      // blacklist the reCAPTCHA and Egglue challenges and do not show
389
      // an example challenge.
390
      // TODO: Once the issues mentioned above are fixed, this workaround
391
      // should be removed.
392
      if ($captcha_point->module != 'recaptcha' && $captcha_point->module != 'egglue_captcha') {
393
        $captcha_element['example'] = array(
394
          '#type' => 'fieldset',
395
          '#title' => t('Example'),
396
          '#description' => t('This is a pre-solved, non-blocking example of this challenge.'),
397
        );
398
        $captcha_element['example']['example_captcha'] = array(
399
          '#type' => 'captcha',
400
          '#captcha_type' => $captcha_point->module . '/' . $captcha_point->captcha_type,
401
          '#captcha_admin_mode' => TRUE,
402
        );
403
      }
404
    }
405
    else {
406
      $captcha_element['#title'] = t('CAPTCHA: no challenge enabled');
407
      $captcha_element['add_captcha'] = array(
408
        '#markup' => l(t('Place a CAPTCHA here for untrusted users.'), "admin/config/people/captcha/captcha/captcha_point/$form_id", array('query' => drupal_get_destination()))
409
      );
410

    
411
    }
412
    // Get placement in form and insert in form.
413
    $captcha_placement = _captcha_get_captcha_placement($form_id, $form);
414
    _captcha_insert_captcha_element($form, $captcha_placement, $captcha_element);
415

    
416
  }
417

    
418
  // Add a warning about caching on the Perfomance settings page.
419
  if ($form_id == 'system_performance_settings') {
420
    $icon = theme('image', array('path' => 'misc/watchdog-warning.png', 'width' => 18, 'height' => 18, 'alt' => t('warning'), 'title' => t('warning')));
421
    $form['caching']['captcha'] = array(
422
      '#type' => 'item',
423
      '#title' => t('CAPTCHA'),
424
      '#markup' => t('!icon The CAPTCHA module will disable the caching of pages that contain a CAPTCHA element.', array(
425
        '!icon' => '<span class="icon">' . $icon . '</span>')
426
      ),
427
      '#attributes' => array('class' => array('warning')),
428
    );
429
  }
430

    
431
}
432

    
433
/**
434
 * CAPTCHA validation function to tests strict equality.
435
 * @param $solution the solution of the test.
436
 * @param $response the response to the test.
437
 * @return TRUE when strictly equal, FALSE otherwise.
438
 */
439
function captcha_validate_strict_equality($solution, $response) {
440
  return $solution === $response;
441
}
442

    
443
/**
444
 * CAPTCHA validation function to tests case insensitive equality.
445
 * @param $solution the solution of the test.
446
 * @param $response the response to the test.
447
 * @return TRUE when case insensitive equal, FALSE otherwise.
448
 */
449
function captcha_validate_case_insensitive_equality($solution, $response) {
450
  return drupal_strtolower($solution) === drupal_strtolower($response);
451
}
452

    
453
/**
454
 * CAPTCHA validation function to tests equality while ignoring spaces.
455
 * @param $solution the solution of the test.
456
 * @param $response the response to the test.
457
 * @return TRUE when equal (ignoring spaces), FALSE otherwise.
458
 */
459
function captcha_validate_ignore_spaces($solution, $response) {
460
  return preg_replace('/\s/', '', $solution) === preg_replace('/\s/', '', $response);
461
}
462

    
463
/**
464
 * CAPTCHA validation function to tests case insensitive equality while ignoring spaces.
465
 * @param $solution the solution of the test.
466
 * @param $response the response to the test.
467
 * @return TRUE when equal (ignoring spaces), FALSE otherwise.
468
 */
469
function captcha_validate_case_insensitive_ignore_spaces($solution, $response) {
470
  return preg_replace('/\s/', '', drupal_strtolower($solution)) === preg_replace('/\s/', '', drupal_strtolower($response));
471
}
472

    
473
/**
474
 * Helper function for getting the posted CAPTCHA info (posted form_id and
475
 * CAPTCHA sessions ID) from a form in case it is posted.
476
 *
477
 * This function hides the form processing mess for several use cases an
478
 * browser bug workarounds.
479
 * For example: $element['#post'] can typically be used to get the posted
480
 * form_id and captcha_sid, but in the case of node preview situations
481
 * (with correct CAPTCHA response) that does not work and we can get them from
482
 * $form_state['clicked_button']['#post'].
483
 * However with Internet Explorer 7, the latter does not work either when
484
 * submitting the forms (with only one text field) with the enter key
485
 * (see http://drupal.org/node/534168), in which case we also have to check
486
 * $form_state['buttons']['button']['0']['#post'].
487
 *
488
 * @todo for Drupal 7 version: is this IE7 workaround still needed?
489
 *
490
 * @param $element the CAPTCHA element.
491
 * @param $form_state the form state structure to extract the info from.
492
 * @param $this_form_id the form ID of the form we are currently processing
493
 *     (which is not necessarily the form that was posted).
494
 *
495
 * @return an array with $posted_form_id and $post_captcha_sid (with NULL values
496
 *     if the values could not be found, e.g. for a fresh form).
497
 */
498
function _captcha_get_posted_captcha_info($element, $form_state, $this_form_id) {
499
  if ($form_state['submitted'] && isset($form_state['captcha_info'])) {
500
    // We are handling (or rebuilding) an already submitted form,
501
    // so we already determined the posted form ID and CAPTCHA session ID
502
    // for this form (from before submitting). Reuse this info.
503
    $posted_form_id = $form_state['captcha_info']['posted_form_id'];
504
    $posted_captcha_sid = $form_state['captcha_info']['captcha_sid'];
505
  }
506
  else {
507
    // We have to determine the posted form ID and CAPTCHA session ID
508
    // from the post data.
509
    // Because we possibly use raw post data here,
510
    // we should be extra cautious and filter this data.
511
    $posted_form_id = isset($form_state['input']['form_id']) ?
512
      preg_replace("/[^a-z0-9_]/", "", (string) $form_state['input']['form_id'])
513
      : NULL;
514
    $posted_captcha_sid = isset($form_state['input']['captcha_sid']) ?
515
      (int) $form_state['input']['captcha_sid']
516
      : NULL;
517
    $posted_captcha_token = isset($form_state['input']['captcha_token']) ?
518
      preg_replace("/[^a-zA-Z0-9]/", "", (string) $form_state['input']['captcha_token'])
519
      : NULL;
520

    
521
    if ($posted_form_id == $this_form_id) {
522
      // Check if the posted CAPTCHA token is valid for the posted CAPTCHA
523
      // session ID. Note that we could just check the validity of the CAPTCHA
524
      // token and extract the CAPTCHA session ID from that (without looking at
525
      // the actual posted CAPTCHA session ID). However, here we check both
526
      // the posted CAPTCHA token and session ID: it is a bit more stringent
527
      // and the database query should also be more efficient (because there is
528
      // an index on the CAPTCHA session ID).
529
      if ($posted_captcha_sid != NULL) {
530
        $expected_captcha_token = db_query(
531
          "SELECT token FROM {captcha_sessions} WHERE csid = :csid",
532
          array(':csid' => $posted_captcha_sid)
533
        )->fetchField();
534
        if ($expected_captcha_token !== $posted_captcha_token) {
535
          drupal_set_message(t('CAPTCHA session reuse attack detected.'), 'error');
536
          // Invalidate the CAPTCHA session.
537
          $posted_captcha_sid = NULL;
538
        }
539
        // Invalidate CAPTCHA token to avoid reuse.
540
        db_update('captcha_sessions')
541
          ->fields(array('token' => NULL))
542
          ->condition('csid', $posted_captcha_sid);
543
      }
544
    }
545
    else {
546
      // The CAPTCHA session ID is specific to the posted form.
547
      // Return NULL, so a new session will be generated for this other form.
548
      $posted_captcha_sid = NULL;
549
    }
550
  }
551
  return array($posted_form_id, $posted_captcha_sid);
552
}
553

    
554
/**
555
 * CAPTCHA validation handler.
556
 *
557
 * This function is placed in the main captcha.module file to make sure that
558
 * it is available (even for cached forms, which don't fire
559
 * captcha_form_alter(), and subsequently don't include additional include
560
 * files).
561
 */
562
function captcha_validate($element, &$form_state) {
563

    
564
  $captcha_info = $form_state['captcha_info'];
565
  $form_id = $captcha_info['this_form_id'];
566

    
567
  // Get CAPTCHA response.
568
  $captcha_response = $form_state['values']['captcha_response'];
569

    
570
  // Get CAPTCHA session from CAPTCHA info
571
  // TODO: is this correct in all cases: see comment and code in previous revisions?
572
  $csid = $captcha_info['captcha_sid'];
573

    
574
  $solution = db_query(
575
    'SELECT solution FROM {captcha_sessions} WHERE csid = :csid',
576
    array(':csid' => $csid)
577
    )
578
    ->fetchField();
579

    
580
  // @todo: what is the result when there is no entry for the captcha_session? in D6 it was FALSE, what in D7?
581
  if ($solution === FALSE) {
582
    // Unknown challenge_id.
583
    // TODO: this probably never happens anymore now that there is detection
584
    // for CAPTCHA session reuse attacks in _captcha_get_posted_captcha_info().
585
    form_set_error('captcha', t('CAPTCHA validation error: unknown CAPTCHA session ID. Contact the site administrator if this problem persists.'));
586
    watchdog('CAPTCHA',
587
      'CAPTCHA validation error: unknown CAPTCHA session ID (%csid).',
588
      array('%csid' => var_export($csid, TRUE)),
589
      WATCHDOG_ERROR);
590
  }
591
  else {
592
    // Get CAPTCHA validate function or fall back on strict equality.
593
    $captcha_validate = $element['#captcha_validate'];
594
    if (!function_exists($captcha_validate)) {
595
       $captcha_validate = 'captcha_validate_strict_equality';
596
    }
597
    // Check the response with the CAPTCHA validation function.
598
    // Apart from the traditional expected $solution and received $response,
599
    // we also provide the CAPTCHA $element and $form_state arrays for more advanced use cases.
600
    if ($captcha_validate($solution, $captcha_response, $element, $form_state)) {
601
      // Correct answer.
602

    
603
      // Store form_id in session (but only if it is useful to do so, avoid setting stuff in session unnecessarily).
604
      $captcha_persistence = variable_get('captcha_persistence', CAPTCHA_PERSISTENCE_SKIP_ONCE_SUCCESSFUL_PER_FORM_INSTANCE);
605
      if ($captcha_persistence == CAPTCHA_PERSISTENCE_SKIP_ONCE_SUCCESSFUL || $captcha_persistence == CAPTCHA_PERSISTENCE_SKIP_ONCE_SUCCESSFUL_PER_FORM_TYPE) {
606
        $_SESSION['captcha_success_form_ids'][$form_id] = $form_id;
607
      }
608

    
609
      // Record success.
610
      db_update('captcha_sessions')
611
        ->condition('csid', $csid)
612
        ->fields(array('status' => CAPTCHA_STATUS_SOLVED))
613
        ->expression('attempts', 'attempts + 1')
614
        ->execute();
615
    }
616
    else {
617
      // Wrong answer.
618
      db_update('captcha_sessions')
619
        ->condition('csid', $csid)
620
        ->expression('attempts', 'attempts + 1')
621
        ->execute();
622
      // set form error
623
      form_set_error('captcha_response', t('The answer you entered for the CAPTCHA was not correct.'));
624
      // update wrong response counter
625
      if (variable_get('captcha_enable_stats', FALSE)) {
626
        variable_set('captcha_wrong_response_counter', variable_get('captcha_wrong_response_counter', 0) + 1);
627
      }
628
      // log to watchdog if needed
629
      if (variable_get('captcha_log_wrong_responses', FALSE)) {
630
        watchdog('CAPTCHA',
631
          '%form_id post blocked by CAPTCHA module: challenge %challenge (by module %module), user answered "@response", but the solution was "@solution".',
632
          array('%form_id' => $form_id,
633
            '@response' => $captcha_response, '@solution' => $solution,
634
            '%challenge' => $captcha_info['captcha_type'], '%module' => $captcha_info['module'],
635
          ),
636
          WATCHDOG_NOTICE);
637
      }
638
    }
639
  }
640
}
641

    
642
/**
643
 * Pre-render callback for additional processing of a CAPTCHA form element.
644
 *
645
 * This encompasses tasks that should happen after the general FAPI processing
646
 * (building, submission and validation) but before rendering (e.g. storing the solution).
647
 *
648
 * @param $element the CAPTCHA form element
649
 * @return the manipulated element
650
 */
651
function captcha_pre_render_process($element) {
652
  module_load_include('inc', 'captcha');
653

    
654
  // Get form and CAPTCHA information.
655
  $captcha_info = $element['#captcha_info'];
656
  $form_id = $captcha_info['form_id'];
657
  $captcha_sid = (int)($captcha_info['captcha_sid']);
658
  // Check if CAPTCHA is still required.
659
  // This check is done in a first phase during the element processing
660
  // (@see captcha_process), but it is also done here for better support
661
  // of multi-page forms. Take previewing a node submission for example:
662
  // when the challenge is solved correctely on preview, the form is still
663
  // not completely submitted, but the CAPTCHA can be skipped.
664
  if (_captcha_required_for_user($captcha_sid, $form_id) || $element['#captcha_admin_mode']) {
665
    // Update captcha_sessions table: store the solution of the generated CAPTCHA.
666
    _captcha_update_captcha_session($captcha_sid, $captcha_info['solution']);
667

    
668
    // Handle the response field if it is available and if it is a textfield.
669
    if (isset($element['captcha_widgets']['captcha_response']['#type']) && $element['captcha_widgets']['captcha_response']['#type'] == 'textfield') {
670
      // Before rendering: presolve an admin mode challenge or
671
      // empty the value of the captcha_response form item.
672
      $value = $element['#captcha_admin_mode'] ? $captcha_info['solution'] : '';
673
      $element['captcha_widgets']['captcha_response']['#value'] = $value;
674
    }
675
  }
676
  else {
677
    // Remove CAPTCHA widgets from form.
678
    unset($element['captcha_widgets']);
679
  }
680

    
681
  return $element;
682
}
683

    
684
/**
685
 * Default implementation of hook_captcha().
686
 */
687
function captcha_captcha($op, $captcha_type = '') {
688
  switch ($op) {
689
    case 'list':
690
      return array('Math');
691
      break;
692

    
693
    case 'generate':
694
      if ($captcha_type == 'Math') {
695
        $result = array();
696
        $answer = mt_rand(1, 20);
697
        $x = mt_rand(1, $answer);
698
        $y = $answer - $x;
699
        $result['solution'] = "$answer";
700
        // Build challenge widget.
701
        // Note that we also use t() for the math challenge itself. This makes
702
        // it possible to 'rephrase' the challenge a bit through localization
703
        // or string overrides.
704
        $result['form']['captcha_response'] = array(
705
          '#type' => 'textfield',
706
          '#title' => t('Math question'),
707
          '#description' => t('Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.'),
708
          '#field_prefix' => t('@x + @y = ', array('@x' => $x, '@y' => $y)),
709
          '#size' => 4,
710
          '#maxlength' => 2,
711
          '#required' => TRUE,
712
        );
713
        return $result;
714
      }
715
      elseif ($captcha_type == 'Test') {
716
        // This challenge is not visible through the administrative interface
717
        // as it is not listed in captcha_captcha('list'),
718
        // but it is meant for debugging and testing purposes.
719
        // TODO for Drupal 7 version: This should be done with a mock module,
720
        // but Drupal 6 does not support this (mock modules can not be hidden).
721
        $result = array(
722
          'solution' => 'Test 123',
723
          'form' => array(),
724
        );
725
        $result['form']['captcha_response'] = array(
726
          '#type' => 'textfield',
727
          '#title' => t('Test one two three'),
728
          '#required' => TRUE,
729
        );
730
        return $result;
731
      }
732
      break;
733
  }
734
}
735

    
736
/**
737
 * Implements hook_modules_enabled.
738
 */
739
function captcha_modules_enabled() {
740
  // When new modules are enabled: clear the CAPTCHA placement cache, so that
741
  // new hook_captcha_placement_map hooks can be triggered.
742
  variable_del('captcha_placement_map_cache');
743
}