Projet

Général

Profil

Paste
Télécharger (33,7 ko) Statistiques
| Branche: | Révision:

root / drupal7 / sites / all / modules / captcha / captcha.module @ 6ae446a4

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
 * Constants for CAPTCHA persistence.
13
 * TODO: change these integers to strings because the CAPTCHA settings form saves them as strings in the variables table anyway?
14
 */
15

    
16
// Always add a CAPTCHA (even on every page of a multipage workflow).
17
define('CAPTCHA_PERSISTENCE_SHOW_ALWAYS', 0);
18
// Only one CAPTCHA has to be solved per form instance/multi-step workflow.
19
define('CAPTCHA_PERSISTENCE_SKIP_ONCE_SUCCESSFUL_PER_FORM_INSTANCE', 1);
20
// Once the user answered correctly for a CAPTCHA on a certain form type,
21
// no more CAPTCHAs will be offered anymore for that form.
22
define('CAPTCHA_PERSISTENCE_SKIP_ONCE_SUCCESSFUL_PER_FORM_TYPE', 2);
23
// Once the user answered correctly for a CAPTCHA on the site,
24
// no more CAPTCHAs will be offered anymore.
25
define('CAPTCHA_PERSISTENCE_SKIP_ONCE_SUCCESSFUL', 3);
26

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

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

    
34
/**
35
 * Implementation of hook_help().
36
 */
37
function captcha_help($path, $arg) {
38
  switch ($path) {
39
    case 'admin/help#captcha':
40
      $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>';
41
      $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.',
42
        array(
43
          '!performancesettings' => url('admin/config/development/performance'),
44
          '!contenttypes' => url('admin/structure/types'),
45
        )
46
      ) . '</p>';
47
      $output .= '<p>' . t('CAPTCHA is a trademark of Carnegie Mellon University.') . '</p>';
48
      return $output;
49

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

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

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

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

    
187
  // Prevent caching of the page with CAPTCHA elements.
188
  // This needs to be done even if the CAPTCHA will be ommitted later:
189
  // other untrusted users should not get a cached page when
190
  // the current untrusted user can skip the current CAPTCHA.
191
  drupal_page_is_cacheable(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
  $captcha_token = db_select('captcha_sessions', 'c')
220
    ->fields('c', array('token'))
221
    ->condition('csid', $captcha_sid)
222
    ->execute()
223
    ->fetchField();
224
  if (!isset($captcha_token) && !$form_state['submitted']) {
225
    // Additional one-time CAPTCHA token: store in database and send with form.
226
    $captcha_token = md5(mt_rand());
227
    db_update('captcha_sessions')
228
      ->fields(array('token' => $captcha_token))
229
      ->condition('csid', $captcha_sid)
230
      ->execute();
231
  }
232

    
233
  $element['captcha_token'] = array(
234
    '#type' => 'hidden',
235
    '#value' => $captcha_token,
236
  );
237

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

    
241
  // Store CAPTCHA information for further processing in
242
  // - $form_state['captcha_info'], which survives a form rebuild (e.g. node
243
  //   preview), useful in _captcha_get_posted_captcha_info().
244
  // - $element['#captcha_info'], for post processing functions that do not
245
  //   receive a $form_state argument (e.g. the pre_render callback).
246
  $form_state['captcha_info'] = array(
247
    'this_form_id' => $this_form_id,
248
    'posted_form_id' => $posted_form_id,
249
    'captcha_sid' => $captcha_sid,
250
    'module' => $captcha_type_module,
251
    'captcha_type' => $captcha_type_challenge,
252
  );
253
  $element['#captcha_info'] = array(
254
    'form_id' => $this_form_id,
255
    'captcha_sid' => $captcha_sid,
256
  );
257

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

    
277
    // Add a validation callback for the CAPTCHA form element (when not in admin mode).
278
    if (!$element['#captcha_admin_mode']) {
279
      $element['#element_validate'] = array('captcha_validate');
280
    }
281

    
282
    // Set a custom CAPTCHA validate function if requested.
283
    if (isset($captcha['captcha_validate'])) {
284
      $element['#captcha_validate'] = $captcha['captcha_validate'];
285
    }
286

    
287
    // Set the theme function.
288
    $element['#theme'] = 'captcha';
289

    
290
    // Add pre_render callback for additional CAPTCHA processing.
291
    if (!isset($element['#pre_render'])) {
292
      $element['#pre_render'] = array();
293
    }
294
    $element['#pre_render'][] = 'captcha_pre_render_process';
295

    
296
    // Store the solution in the #captcha_info array.
297
    $element['#captcha_info']['solution'] = $captcha['solution'];
298

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

    
302
  }
303

    
304
  return $element;
305
}
306

    
307
/**
308
 * Implementation of hook_captcha_default_points_alter().
309
 *
310
 * Provide some default captchas only if defaults are not already
311
 * provided by other modules.
312
 */
313
function captcha_captcha_default_points_alter(&$items) {
314
  $modules = array(
315
    'comment' => array(
316
    ),
317
    'contact' => array(
318
      'contact_site_form',
319
      'contact_personal_form'
320
    ),
321
    'forum' => array(
322
      'forum_node_form',
323
    ),
324
    'user' => array(
325
      'user_register_form',
326
      'user_pass',
327
      'user_login',
328
      'user_login_block',
329
    ),
330
  );
331
  // Add comment form_ids of all currently known node types.
332
  foreach (node_type_get_names() as $type => $name) {
333
    $modules['comment'][] = 'comment_node_' . $type . '_form';
334
  }
335

    
336
  foreach ($modules as $module => $form_ids) {
337
    // Only give defaults if the module exists.
338
    if (module_exists($module)) {
339
      foreach ($form_ids as $form_id) {
340
        // Ensure a default has not been provided already.
341
        if (!isset($items[$form_id])) {
342
          $captcha = new stdClass;
343
          $captcha->disabled = FALSE;
344
          $captcha->api_version = 1;
345
          $captcha->form_id = $form_id;
346
          $captcha->module = '';
347
          $captcha->captcha_type = 'default';
348
          $items[$form_id] = $captcha;
349
        }
350
      }
351
    }
352
  }
353
}
354

    
355
/**
356
 * Theme function for a CAPTCHA element.
357
 *
358
 * Render it in a fieldset if a description of the CAPTCHA
359
 * is available. Render it as is otherwise.
360
 */
361
function theme_captcha($variables) {
362
  $element = $variables['element'];
363
  if (!empty($element['#description']) && isset($element['captcha_widgets'])) {
364
    $fieldset = array(
365
      '#type' => 'fieldset',
366
      '#title' => t('CAPTCHA'),
367
      '#description' => $element['#description'],
368
      '#children' => drupal_render_children($element),
369
      '#attributes' => array('class' => array('captcha')),
370
    );
371
    return theme('fieldset', array('element' => $fieldset));
372
  }
373
  else {
374
    return '<div class="captcha">' . drupal_render_children($element) . '</div>';
375
  }
376
}
377

    
378
/**
379
 * Implements of hook_form_alter().
380
 *
381
 * This function adds a CAPTCHA to forms for untrusted users if needed and adds
382
 * CAPTCHA administration links for site administrators if this option is enabled.
383
 */
384
function captcha_form_alter(&$form, &$form_state, $form_id) {
385

    
386
  if (!user_access('skip CAPTCHA')) {
387
    // Visitor does not have permission to skip CAPTCHAs.
388
    module_load_include('inc', 'captcha');
389

    
390
    // Get CAPTCHA type and module for given form_id.
391
    $captcha_point = captcha_get_form_id_setting($form_id);
392
    if ($captcha_point && !empty($captcha_point->captcha_type)) {
393
      module_load_include('inc', 'captcha');
394
      // Build CAPTCHA form element.
395
      $captcha_element = array(
396
        '#type' => 'captcha',
397
        '#captcha_type' => $captcha_point->module . '/' . $captcha_point->captcha_type,
398
      );
399
      // Add a CAPTCHA description if required.
400
      if (variable_get('captcha_add_captcha_description', TRUE)) {
401
        $captcha_element['#description'] = _captcha_get_description();
402
      }
403

    
404
      // Get placement in form and insert in form.
405
      $captcha_placement = _captcha_get_captcha_placement($form_id, $form);
406
      _captcha_insert_captcha_element($form, $captcha_placement, $captcha_element);
407
    }
408
  }
409
  elseif (
410
    variable_get('captcha_administration_mode', FALSE)
411
    && user_access('administer CAPTCHA settings')
412
    && (arg(0) != 'admin' || variable_get('captcha_allow_on_admin_pages', FALSE))
413
  ) {
414
    // Add CAPTCHA administration tools.
415
    module_load_include('inc', 'captcha');
416

    
417
    $captcha_point = captcha_get_form_id_setting($form_id);
418
    // For administrators: show CAPTCHA info and offer link to configure it.
419
    $captcha_element = array(
420
      '#type' => 'fieldset',
421
      '#title' => t('CAPTCHA'),
422
      '#collapsible' => TRUE,
423
      '#collapsed' => TRUE,
424
      '#attributes' => array('class' => array('captcha-admin-links')),
425
    );
426
    if ($captcha_point !== NULL && $captcha_point->captcha_type) {
427
      $captcha_element['#title'] = t('CAPTCHA: challenge "@type" enabled', array('@type' => $captcha_point->captcha_type));
428
      $captcha_element['#description'] = t('Untrusted users will see a CAPTCHA here (<a href="@settings">general CAPTCHA settings</a>).',
429
        array('@settings' => url('admin/config/people/captcha'))
430
      );
431
      $captcha_element['challenge'] = array(
432
        '#type' => 'item',
433
        '#title' => t('Enabled challenge'),
434
        '#markup' => t('%type by module %module (<a href="@change">change</a>, <a href="@disable">disable</a>)', array(
435
          '%type' => $captcha_point->captcha_type,
436
          '%module' => $captcha_point->module,
437
          '@change' => url("admin/config/people/captcha/captcha/captcha_point/$form_id", array('query' => drupal_get_destination())),
438
          '@disable' => url("admin/config/people/captcha/captcha/captcha_point/$form_id/disable", array('query' => drupal_get_destination())),
439
        )),
440
      );
441
      // Add an example challenge with solution.
442
      // This does not work with the reCAPTCHA and Egglue challenges as
443
      // discussed in http://drupal.org/node/487032 and
444
      // http://drupal.org/node/525586. As a temporary workaround, we
445
      // blacklist the reCAPTCHA and Egglue challenges and do not show
446
      // an example challenge.
447
      // TODO: Once the issues mentioned above are fixed, this workaround
448
      // should be removed.
449
      if ($captcha_point->module != 'recaptcha' && $captcha_point->module != 'egglue_captcha') {
450
        $captcha_element['example'] = array(
451
          '#type' => 'fieldset',
452
          '#title' => t('Example'),
453
          '#description' => t('This is a pre-solved, non-blocking example of this challenge.'),
454
        );
455
        $captcha_element['example']['example_captcha'] = array(
456
          '#type' => 'captcha',
457
          '#captcha_type' => $captcha_point->module . '/' . $captcha_point->captcha_type,
458
          '#captcha_admin_mode' => TRUE,
459
        );
460
      }
461
    }
462
    else {
463
      $captcha_element['#title'] = t('CAPTCHA: no challenge enabled');
464
      $captcha_element['add_captcha'] = array(
465
        '#markup' => l(t('Place a CAPTCHA here for untrusted users.'), "admin/config/people/captcha/captcha/captcha_point/$form_id", array('query' => drupal_get_destination()))
466
      );
467

    
468
    }
469
    // Get placement in form and insert in form.
470
    $captcha_placement = _captcha_get_captcha_placement($form_id, $form);
471
    _captcha_insert_captcha_element($form, $captcha_placement, $captcha_element);
472

    
473
  }
474

    
475
  // Add a warning about caching on the Perfomance settings page.
476
  if ($form_id == 'system_performance_settings') {
477
    $icon = theme(
478
      'image',
479
      array(
480
        'path' => 'misc/watchdog-warning.png',
481
        'width' => 18,
482
        'height' => 18,
483
        'alt' => t('warning'),
484
        'title' => t('warning'),
485
      )
486
    );
487
    $form['caching']['captcha'] = array(
488
      '#type' => 'item',
489
      '#title' => t('CAPTCHA'),
490
      '#markup' => t(
491
        '!icon The CAPTCHA module will disable the caching of pages that contain a CAPTCHA element.',
492
        array(
493
          '!icon' => '<span class="icon">' . $icon . '</span>'
494
        )
495
      ),
496
      '#attributes' => array('class' => array('warning')),
497
    );
498
  }
499

    
500
}
501

    
502
/**
503
 * CAPTCHA validation function to tests strict equality.
504
 *
505
 * @param string $solution
506
 *   the solution of the test.
507
 *
508
 * @param string $response
509
 *   the response to the test.
510
 *
511
 * @return bool
512
 *   TRUE when equal (ignoring spaces), FALSE otherwise.
513
 */
514
function captcha_validate_strict_equality($solution, $response) {
515
  return $solution === $response;
516
}
517

    
518
/**
519
 * CAPTCHA validation function to tests case insensitive equality.
520
 *
521
 * @param string $solution
522
 *   the solution of the test.
523
 *
524
 * @param string $response
525
 *   the response to the test.
526
 *
527
 * @return bool
528
 *   TRUE when equal (ignoring spaces), FALSE otherwise.
529
 */
530
function captcha_validate_case_insensitive_equality($solution, $response) {
531
  return drupal_strtolower($solution) === drupal_strtolower($response);
532
}
533

    
534
/**
535
 * CAPTCHA validation function to tests equality while ignoring spaces.
536
 *
537
 * @param string $solution
538
 *   the solution of the test.
539
 *
540
 * @param string $response
541
 *   the response to the test.
542
 *
543
 * @return bool
544
 *   TRUE when equal (ignoring spaces), FALSE otherwise.
545
 */
546
function captcha_validate_ignore_spaces($solution, $response) {
547
  return preg_replace('/\s/', '', $solution) === preg_replace('/\s/', '', $response);
548
}
549

    
550
/**
551
 * CAPTCHA validation function to tests case insensitive equality while ignoring spaces.
552
 *
553
 * @param string $solution
554
 *   the solution of the test.
555
 *
556
 * @param string $response
557
 *   the response to the test.
558
 *
559
 * @return bool
560
 *   TRUE when equal (ignoring spaces), FALSE otherwise.
561
 */
562
function captcha_validate_case_insensitive_ignore_spaces($solution, $response) {
563
  return preg_replace('/\s/', '', drupal_strtolower($solution)) === preg_replace('/\s/', '', drupal_strtolower($response));
564
}
565

    
566
/**
567
 * Helper function for getting the posted CAPTCHA info (posted form_id and
568
 * CAPTCHA sessions ID) from a form in case it is posted.
569
 *
570
 * This function hides the form processing mess for several use cases an
571
 * browser bug workarounds.
572
 * For example: $element['#post'] can typically be used to get the posted
573
 * form_id and captcha_sid, but in the case of node preview situations
574
 * (with correct CAPTCHA response) that does not work and we can get them from
575
 * $form_state['clicked_button']['#post'].
576
 * However with Internet Explorer 7, the latter does not work either when
577
 * submitting the forms (with only one text field) with the enter key
578
 * (see http://drupal.org/node/534168), in which case we also have to check
579
 * $form_state['buttons']['button']['0']['#post'].
580
 *
581
 * @todo for Drupal 7 version: is this IE7 workaround still needed?
582
 *
583
 * @param array $element
584
 *   the CAPTCHA element.
585
 *
586
 * @param array $form_state
587
 *   the form state structure to extract the info from.
588
 *
589
 * @param string $this_form_id
590
 *   the form ID of the form we are currently processing
591
 *     (which is not necessarily the form that was posted).
592
 *
593
 * @return array
594
 *   an array with $posted_form_id and $post_captcha_sid (with NULL values
595
 *     if the values could not be found, e.g. for a fresh form).
596
 */
597
function _captcha_get_posted_captcha_info($element, $form_state, $this_form_id) {
598
  //Handle Ajax scenarios
599
  if (!empty($form_state['rebuild_info'])) {
600
    if (!empty($form_state['captcha_info']['posted_form_id'])) {
601
      $posted_form_id = $form_state['captcha_info']['posted_form_id'];
602
    }
603
    else {
604
      $posted_form_id = $form_state['input']['form_id'];
605
    }
606

    
607
    $posted_captcha_sid = $form_state['captcha_info']['captcha_sid'];
608
  }
609
  else if ($form_state['submitted'] && isset($form_state['captcha_info'])) {
610
    // We are handling (or rebuilding) an already submitted form,
611
    // so we already determined the posted form ID and CAPTCHA session ID
612
    // for this form (from before submitting). Reuse this info.
613
    $posted_form_id = $form_state['captcha_info']['posted_form_id'];
614
    $posted_captcha_sid = $form_state['captcha_info']['captcha_sid'];
615
  }
616
  else {
617
    // We have to determine the posted form ID and CAPTCHA session ID
618
    // from the post data.
619
    // Because we possibly use raw post data here,
620
    // we should be extra cautious and filter this data.
621
    $posted_form_id = isset($form_state['input']['form_id']) ? preg_replace("/[^a-z0-9_]/", "", (string) $form_state['input']['form_id']) : NULL;
622
    $posted_captcha_sid = isset($form_state['input']['captcha_sid']) ? (int) $form_state['input']['captcha_sid'] : NULL;
623
    $posted_captcha_token = !empty($form_state['input']['captcha_token']) ? preg_replace("/[^a-zA-Z0-9]/", "", (string) $form_state['input']['captcha_token']) : NULL;
624

    
625
    if ($posted_form_id == $this_form_id) {
626
      // Check if the posted CAPTCHA token is valid for the posted CAPTCHA
627
      // session ID. Note that we could just check the validity of the CAPTCHA
628
      // token and extract the CAPTCHA session ID from that (without looking at
629
      // the actual posted CAPTCHA session ID). However, here we check both
630
      // the posted CAPTCHA token and session ID: it is a bit more stringent
631
      // and the database query should also be more efficient (because there is
632
      // an index on the CAPTCHA session ID).
633
      if ($posted_captcha_sid != NULL) {
634
        $expected_captcha_token = db_query(
635
          "SELECT token FROM {captcha_sessions} WHERE csid = :csid",
636
          array(':csid' => $posted_captcha_sid)
637
        )->fetchField();
638

    
639
        if ($expected_captcha_token !== $posted_captcha_token) {
640
          drupal_set_message(t('CAPTCHA session reuse attack detected.'), 'error');
641
          // Invalidate the CAPTCHA session.
642
          $posted_captcha_sid = NULL;
643
        }
644

    
645
        // Invalidate CAPTCHA token to avoid reuse.
646
        db_update('captcha_sessions')
647
          ->fields(array('token' => NULL))
648
          ->condition('csid', $posted_captcha_sid)
649
          ->execute();
650
      }
651
    }
652
    else {
653
      // The CAPTCHA session ID is specific to the posted form.
654
      // Return NULL, so a new session will be generated for this other form.
655
      $posted_captcha_sid = NULL;
656
    }
657
  }
658
  return array($posted_form_id, $posted_captcha_sid);
659
}
660

    
661
/**
662
 * CAPTCHA validation handler.
663
 *
664
 * This function is placed in the main captcha.module file to make sure that
665
 * it is available (even for cached forms, which don't fire
666
 * captcha_form_alter(), and subsequently don't include additional include
667
 * files).
668
 */
669
function captcha_validate($element, &$form_state) {
670
  // If disable captcha mode is enabled, bypass captcha validation.
671
  if (variable_get('disable_captcha', FALSE)) {
672
    return;
673
  }
674

    
675
  $captcha_info = $form_state['captcha_info'];
676
  $form_id = $captcha_info['this_form_id'];
677

    
678
  // Get CAPTCHA response.
679
  $captcha_response = $form_state['values']['captcha_response'];
680

    
681
  // Get CAPTCHA session from CAPTCHA info
682
  // TODO: is this correct in all cases: see comment and code in previous revisions?
683
  $csid = $captcha_info['captcha_sid'];
684

    
685
  $solution = db_query(
686
    'SELECT solution FROM {captcha_sessions} WHERE csid = :csid',
687
    array(':csid' => $csid)
688
    )
689
    ->fetchField();
690

    
691
  // @todo: what is the result when there is no entry for the captcha_session? in D6 it was FALSE, what in D7?
692
  if ($solution === FALSE) {
693
    // Unknown challenge_id.
694
    // TODO: this probably never happens anymore now that there is detection
695
    // for CAPTCHA session reuse attacks in _captcha_get_posted_captcha_info().
696
    form_set_error('captcha', t('CAPTCHA validation error: unknown CAPTCHA session ID. Contact the site administrator if this problem persists.'));
697
    watchdog('CAPTCHA',
698
      'CAPTCHA validation error: unknown CAPTCHA session ID (%csid).',
699
      array('%csid' => var_export($csid, TRUE)),
700
      WATCHDOG_ERROR);
701
  }
702
  else {
703
    // Get CAPTCHA validate function or fall back on strict equality.
704
    $captcha_validate = $element['#captcha_validate'];
705
    if (!function_exists($captcha_validate)) {
706
      $captcha_validate = 'captcha_validate_strict_equality';
707
    }
708
    // Check the response with the CAPTCHA validation function.
709
    // Apart from the traditional expected $solution and received $response,
710
    // we also provide the CAPTCHA $element and $form_state arrays for more advanced use cases.
711
    if ($captcha_validate($solution, $captcha_response, $element, $form_state)) {
712
      // Correct answer.
713

    
714
      // Store form_id in session (but only if it is useful to do so, avoid setting stuff in session unnecessarily).
715
      $captcha_persistence = variable_get('captcha_persistence', CAPTCHA_PERSISTENCE_SKIP_ONCE_SUCCESSFUL_PER_FORM_INSTANCE);
716
      if ($captcha_persistence == CAPTCHA_PERSISTENCE_SKIP_ONCE_SUCCESSFUL || $captcha_persistence == CAPTCHA_PERSISTENCE_SKIP_ONCE_SUCCESSFUL_PER_FORM_TYPE) {
717
        $_SESSION['captcha_success_form_ids'][$form_id] = $form_id;
718
      }
719

    
720
      // Record success.
721
      db_update('captcha_sessions')
722
        ->condition('csid', $csid)
723
        ->fields(array('status' => CAPTCHA_STATUS_SOLVED))
724
        ->expression('attempts', 'attempts + 1')
725
        ->execute();
726
    }
727
    else {
728
      // Wrong answer.
729
      db_update('captcha_sessions')
730
        ->condition('csid', $csid)
731
        ->expression('attempts', 'attempts + 1')
732
        ->execute();
733
      // Set form error.
734
      form_set_error('captcha_response', t('The answer you entered for the CAPTCHA was not correct.'));
735
      // Update wrong response counter.
736
      if (variable_get('captcha_enable_stats', FALSE)) {
737
        variable_set('captcha_wrong_response_counter', variable_get('captcha_wrong_response_counter', 0) + 1);
738
      }
739
      // Log to watchdog if needed.
740
      if (variable_get('captcha_log_wrong_responses', FALSE)) {
741
        watchdog('CAPTCHA',
742
          '%form_id post blocked by CAPTCHA module: challenge %challenge (by module %module), user answered "@response", but the solution was "@solution".',
743
          array(
744
            '%form_id' => $form_id,
745
            '@response' => $captcha_response, '@solution' => $solution,
746
            '%challenge' => $captcha_info['captcha_type'], '%module' => $captcha_info['module'],
747
          ),
748
          WATCHDOG_NOTICE);
749
      }
750
    }
751
  }
752
}
753

    
754
/**
755
 * Pre-render callback for additional processing of a CAPTCHA form element.
756
 *
757
 * This encompasses tasks that should happen after the general FAPI processing
758
 * (building, submission and validation) but before rendering (e.g. storing the solution).
759
 *
760
 * @param array $element
761
 *   the CAPTCHA form element
762
 *
763
 * @return array
764
 *   the manipulated element
765
 */
766
function captcha_pre_render_process($element) {
767
  module_load_include('inc', 'captcha');
768

    
769
  // Get form and CAPTCHA information.
770
  $captcha_info = $element['#captcha_info'];
771
  $form_id = $captcha_info['form_id'];
772
  $captcha_sid = (int) ($captcha_info['captcha_sid']);
773
  // Check if CAPTCHA is still required.
774
  // This check is done in a first phase during the element processing
775
  // (@see captcha_process), but it is also done here for better support
776
  // of multi-page forms. Take previewing a node submission for example:
777
  // when the challenge is solved correctely on preview, the form is still
778
  // not completely submitted, but the CAPTCHA can be skipped.
779
  if (_captcha_required_for_user($captcha_sid, $form_id) || $element['#captcha_admin_mode'] || $element['#captcha_always']) {
780
    // Update captcha_sessions table: store the solution of the generated CAPTCHA.
781
    _captcha_update_captcha_session($captcha_sid, $captcha_info['solution']);
782

    
783
    // Handle the response field if it is available and if it is a textfield.
784
    if (isset($element['captcha_widgets']['captcha_response']['#type']) && $element['captcha_widgets']['captcha_response']['#type'] == 'textfield') {
785
      // Before rendering: presolve an admin mode challenge or
786
      // empty the value of the captcha_response form item.
787
      $value = $element['#captcha_admin_mode'] ? $captcha_info['solution'] : '';
788
      $element['captcha_widgets']['captcha_response']['#value'] = $value;
789
    }
790
  }
791
  else {
792
    // Remove CAPTCHA widgets from form.
793
    unset($element['captcha_widgets']);
794
  }
795

    
796
  return $element;
797
}
798

    
799
/**
800
 * Default implementation of hook_captcha().
801
 */
802
function captcha_captcha($op, $captcha_type = '') {
803
  switch ($op) {
804
    case 'list':
805
      return array('Math');
806

    
807
    case 'generate':
808
      if ($captcha_type == 'Math') {
809
        $result = array();
810
        $answer = mt_rand(1, 20);
811
        $x = mt_rand(1, $answer);
812
        $y = $answer - $x;
813
        $result['solution'] = "$answer";
814
        // Build challenge widget.
815
        // Note that we also use t() for the math challenge itself. This makes
816
        // it possible to 'rephrase' the challenge a bit through localization
817
        // or string overrides.
818
        $result['form']['captcha_response'] = array(
819
          '#type' => 'textfield',
820
          '#title' => t('Math question'),
821
          '#description' => t('Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.'),
822
          '#field_prefix' => t('@x + @y = ', array('@x' => $x, '@y' => $y)),
823
          '#size' => 4,
824
          '#maxlength' => 2,
825
          '#required' => TRUE,
826
        );
827
        return $result;
828
      }
829
      elseif ($captcha_type == 'Test') {
830
        // This challenge is not visible through the administrative interface
831
        // as it is not listed in captcha_captcha('list'),
832
        // but it is meant for debugging and testing purposes.
833
        // TODO for Drupal 7 version: This should be done with a mock module,
834
        // but Drupal 6 does not support this (mock modules can not be hidden).
835
        $result = array(
836
          'solution' => 'Test 123',
837
          'form' => array(),
838
        );
839
        $result['form']['captcha_response'] = array(
840
          '#type' => 'textfield',
841
          '#title' => t('Test one two three'),
842
          '#required' => TRUE,
843
        );
844
        return $result;
845
      }
846
      break;
847
  }
848
}
849

    
850
/**
851
 * Implements hook_modules_enabled().
852
 */
853
function captcha_modules_enabled() {
854
  // When new modules are enabled: clear the CAPTCHA placement cache, so that
855
  // new hook_captcha_placement_map hooks can be triggered.
856
  variable_del('captcha_placement_map_cache');
857
}