Projet

Général

Profil

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

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

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
    '#default_value' => '',
161
    // CAPTCHA in admin mode: presolve the CAPTCHA and always show it (despite previous successful responses).
162
    '#captcha_admin_mode' => FALSE,
163
    // The default CAPTCHA validation function.
164
    // TODO: should this be a single string or an array of strings (combined in OR fashion)?
165
    '#captcha_validate' => 'captcha_validate_strict_equality',
166
  );
167
  // Override the default CAPTCHA validation function for case insensitive validation.
168
  // TODO: shouldn't this be done somewhere else, e.g. in form_alter?
169
  if (CAPTCHA_DEFAULT_VALIDATION_CASE_INSENSITIVE == variable_get('captcha_default_validation', CAPTCHA_DEFAULT_VALIDATION_CASE_INSENSITIVE)) {
170
    $captcha_element['#captcha_validate'] = 'captcha_validate_case_insensitive_equality';
171
  }
172
  return array('captcha' => $captcha_element);
173
}
174

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

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

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

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

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

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

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

    
218
  $captcha_token = db_select('captcha_sessions', 'c')
219
    ->fields('c', array('token'))
220
    ->condition('csid', $captcha_sid)
221
    ->execute()
222
    ->fetchField();
223
  if (!isset($captcha_token) && !$form_state['submitted']) {
224
    // Additional one-time CAPTCHA token: store in database and send with form.
225
    $captcha_token = md5(mt_rand());
226
    db_update('captcha_sessions')
227
      ->fields(array('token' => $captcha_token))
228
      ->condition('csid', $captcha_sid)
229
      ->execute();
230
  }
231

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

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

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

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

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

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

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

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

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

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

    
301
  }
302

    
303
  return $element;
304
}
305

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

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

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

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

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

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

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

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

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

    
472
  }
473

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

    
499
}
500

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

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

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

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

    
565
/**
566
 * Helper function for getting the posted CAPTCHA info (posted form_id and
567
 * CAPTCHA sessions ID) from a form in case it is posted.
568
 *
569
 * This function hides the form processing mess for several use cases an
570
 * browser bug workarounds.
571
 * For example: $element['#post'] can typically be used to get the posted
572
 * form_id and captcha_sid, but in the case of node preview situations
573
 * (with correct CAPTCHA response) that does not work and we can get them from
574
 * $form_state['clicked_button']['#post'].
575
 * However with Internet Explorer 7, the latter does not work either when
576
 * submitting the forms (with only one text field) with the enter key
577
 * (see http://drupal.org/node/534168), in which case we also have to check
578
 * $form_state['buttons']['button']['0']['#post'].
579
 *
580
 * @todo for Drupal 7 version: is this IE7 workaround still needed?
581
 *
582
 * @param array $element
583
 *   the CAPTCHA element.
584
 *
585
 * @param array $form_state
586
 *   the form state structure to extract the info from.
587
 *
588
 * @param string $this_form_id
589
 *   the form ID of the form we are currently processing
590
 *     (which is not necessarily the form that was posted).
591
 *
592
 * @return array
593
 *   an array with $posted_form_id and $post_captcha_sid (with NULL values
594
 *     if the values could not be found, e.g. for a fresh form).
595
 */
596
function _captcha_get_posted_captcha_info($element, $form_state, $this_form_id) {
597
  if ($form_state['submitted'] && isset($form_state['captcha_info'])) {
598
    // We are handling (or rebuilding) an already submitted form,
599
    // so we already determined the posted form ID and CAPTCHA session ID
600
    // for this form (from before submitting). Reuse this info.
601
    $posted_form_id = $form_state['captcha_info']['posted_form_id'];
602
    $posted_captcha_sid = $form_state['captcha_info']['captcha_sid'];
603
  }
604
  else {
605
    // We have to determine the posted form ID and CAPTCHA session ID
606
    // from the post data.
607
    // Because we possibly use raw post data here,
608
    // we should be extra cautious and filter this data.
609
    $posted_form_id = isset($form_state['input']['form_id']) ? preg_replace("/[^a-z0-9_]/", "", (string) $form_state['input']['form_id']) : NULL;
610
    $posted_captcha_sid = isset($form_state['input']['captcha_sid']) ? (int) $form_state['input']['captcha_sid'] : NULL;
611
    $posted_captcha_token = !empty($form_state['input']['captcha_token']) ? preg_replace("/[^a-zA-Z0-9]/", "", (string) $form_state['input']['captcha_token']) : NULL;
612

    
613
    if ($posted_form_id == $this_form_id) {
614
      // Check if the posted CAPTCHA token is valid for the posted CAPTCHA
615
      // session ID. Note that we could just check the validity of the CAPTCHA
616
      // token and extract the CAPTCHA session ID from that (without looking at
617
      // the actual posted CAPTCHA session ID). However, here we check both
618
      // the posted CAPTCHA token and session ID: it is a bit more stringent
619
      // and the database query should also be more efficient (because there is
620
      // an index on the CAPTCHA session ID).
621
      if ($posted_captcha_sid != NULL) {
622
        $expected_captcha_token = db_query(
623
          "SELECT token FROM {captcha_sessions} WHERE csid = :csid",
624
          array(':csid' => $posted_captcha_sid)
625
        )->fetchField();
626

    
627
        if ($expected_captcha_token !== $posted_captcha_token) {
628
          drupal_set_message(t('CAPTCHA session reuse attack detected.'), 'error');
629
          // Invalidate the CAPTCHA session.
630
          $posted_captcha_sid = NULL;
631
        }
632

    
633
        // Invalidate CAPTCHA token to avoid reuse.
634
        db_update('captcha_sessions')
635
          ->fields(array('token' => NULL))
636
          ->condition('csid', $posted_captcha_sid)
637
          ->execute();
638
      }
639
    }
640
    else {
641
      // The CAPTCHA session ID is specific to the posted form.
642
      // Return NULL, so a new session will be generated for this other form.
643
      $posted_captcha_sid = NULL;
644
    }
645
  }
646
  return array($posted_form_id, $posted_captcha_sid);
647
}
648

    
649
/**
650
 * CAPTCHA validation handler.
651
 *
652
 * This function is placed in the main captcha.module file to make sure that
653
 * it is available (even for cached forms, which don't fire
654
 * captcha_form_alter(), and subsequently don't include additional include
655
 * files).
656
 */
657
function captcha_validate($element, &$form_state) {
658
  // If disable captcha mode is enabled, bypass captcha validation.
659
  if (variable_get('disable_captcha', FALSE)) {
660
    return;
661
  }
662

    
663
  $captcha_info = $form_state['captcha_info'];
664
  $form_id = $captcha_info['this_form_id'];
665

    
666
  // Get CAPTCHA response.
667
  $captcha_response = $form_state['values']['captcha_response'];
668

    
669
  // Get CAPTCHA session from CAPTCHA info
670
  // TODO: is this correct in all cases: see comment and code in previous revisions?
671
  $csid = $captcha_info['captcha_sid'];
672

    
673
  $solution = db_query(
674
    'SELECT solution FROM {captcha_sessions} WHERE csid = :csid',
675
    array(':csid' => $csid)
676
    )
677
    ->fetchField();
678

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

    
702
      // Store form_id in session (but only if it is useful to do so, avoid setting stuff in session unnecessarily).
703
      $captcha_persistence = variable_get('captcha_persistence', CAPTCHA_PERSISTENCE_SKIP_ONCE_SUCCESSFUL_PER_FORM_INSTANCE);
704
      if ($captcha_persistence == CAPTCHA_PERSISTENCE_SKIP_ONCE_SUCCESSFUL || $captcha_persistence == CAPTCHA_PERSISTENCE_SKIP_ONCE_SUCCESSFUL_PER_FORM_TYPE) {
705
        $_SESSION['captcha_success_form_ids'][$form_id] = $form_id;
706
      }
707

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

    
742
/**
743
 * Pre-render callback for additional processing of a CAPTCHA form element.
744
 *
745
 * This encompasses tasks that should happen after the general FAPI processing
746
 * (building, submission and validation) but before rendering (e.g. storing the solution).
747
 *
748
 * @param array $element
749
 *   the CAPTCHA form element
750
 *
751
 * @return array
752
 *   the manipulated element
753
 */
754
function captcha_pre_render_process($element) {
755
  module_load_include('inc', 'captcha');
756

    
757
  // Get form and CAPTCHA information.
758
  $captcha_info = $element['#captcha_info'];
759
  $form_id = $captcha_info['form_id'];
760
  $captcha_sid = (int) ($captcha_info['captcha_sid']);
761
  // Check if CAPTCHA is still required.
762
  // This check is done in a first phase during the element processing
763
  // (@see captcha_process), but it is also done here for better support
764
  // of multi-page forms. Take previewing a node submission for example:
765
  // when the challenge is solved correctely on preview, the form is still
766
  // not completely submitted, but the CAPTCHA can be skipped.
767
  if (_captcha_required_for_user($captcha_sid, $form_id) || $element['#captcha_admin_mode']) {
768
    // Update captcha_sessions table: store the solution of the generated CAPTCHA.
769
    _captcha_update_captcha_session($captcha_sid, $captcha_info['solution']);
770

    
771
    // Handle the response field if it is available and if it is a textfield.
772
    if (isset($element['captcha_widgets']['captcha_response']['#type']) && $element['captcha_widgets']['captcha_response']['#type'] == 'textfield') {
773
      // Before rendering: presolve an admin mode challenge or
774
      // empty the value of the captcha_response form item.
775
      $value = $element['#captcha_admin_mode'] ? $captcha_info['solution'] : '';
776
      $element['captcha_widgets']['captcha_response']['#value'] = $value;
777
    }
778
  }
779
  else {
780
    // Remove CAPTCHA widgets from form.
781
    unset($element['captcha_widgets']);
782
  }
783

    
784
  return $element;
785
}
786

    
787
/**
788
 * Default implementation of hook_captcha().
789
 */
790
function captcha_captcha($op, $captcha_type = '') {
791
  switch ($op) {
792
    case 'list':
793
      return array('Math');
794

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

    
838
/**
839
 * Implements hook_modules_enabled().
840
 */
841
function captcha_modules_enabled() {
842
  // When new modules are enabled: clear the CAPTCHA placement cache, so that
843
  // new hook_captcha_placement_map hooks can be triggered.
844
  variable_del('captcha_placement_map_cache');
845
}