Projet

Général

Profil

Paste
Télécharger (35,3 ko) Statistiques
| Branche: | Révision:

root / drupal7 / sites / all / modules / captcha / captcha.module @ 620f9137

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
  // Get the form ID of the form we are currently processing (which is not
188
  // necessary the same form that is submitted (if any).
189
  $this_form_id = $complete_form['form_id']['#value'];
190

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

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

    
213
  $captcha_token = db_select('captcha_sessions', 'c')
214
    ->fields('c', array('token'))
215
    ->condition('csid', $captcha_sid)
216
    ->execute()
217
    ->fetchField();
218
  if (!isset($captcha_token) && !$form_state['submitted']) {
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
  }
226

    
227
  $element['captcha_token'] = array(
228
    '#type' => 'hidden',
229
    '#value' => $captcha_token,
230
  );
231

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

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

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

    
271
    // Add a validation callback for the CAPTCHA form element (when not in admin mode).
272
    if (!$element['#captcha_admin_mode']) {
273
      $element['#element_validate'] = array('captcha_validate');
274
    }
275

    
276
    // Set a custom CAPTCHA validate function if requested.
277
    if (isset($captcha['captcha_validate'])) {
278
      $element['#captcha_validate'] = $captcha['captcha_validate'];
279
    }
280

    
281
    // Set the theme function.
282
    $element['#theme'] = 'captcha';
283

    
284
    // Add pre_render callback for additional CAPTCHA processing.
285
    if (!isset($element['#pre_render'])) {
286
      $element['#pre_render'] = array();
287
    }
288
    $element['#pre_render'][] = 'captcha_pre_render_process';
289

    
290
    // Store the solution in the #captcha_info array.
291
    $element['#captcha_info']['solution'] = $captcha['solution'];
292

    
293
    // Store if this captcha type is cacheable:
294
    // A cacheable captcha must not depend on the sid or solution, but be
295
    // independent - like for example recaptcha.
296
    $element['#captcha_info']['cacheable'] = !empty($captcha['cacheable']);
297

    
298
    if (!empty($element['#captcha_info']['cacheable']) && drupal_page_is_cacheable()) {
299
      // This is only used to avoid the re-use message.
300
      $element['captcha_cacheable'] = array(
301
        '#type' => 'hidden',
302
        '#value' => TRUE,
303
      );
304
    }
305

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

    
309
  }
310

    
311
  return $element;
312
}
313

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

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

    
362
/**
363
 * Theme function for a CAPTCHA element.
364
 *
365
 * Render it in a fieldset if a description of the CAPTCHA
366
 * is available. Render it as is otherwise.
367
 */
368
function theme_captcha($variables) {
369
  $element = $variables['element'];
370

    
371
  if (empty($element['#description']) && !empty($element['#attributes']['title'])) {
372
    // Fix for Bootstrap-based themes.
373
    $element['#description'] = $element['#attributes']['title'];
374
  }
375

    
376
  if (!empty($element['#description']) && isset($element['captcha_widgets'])) {
377
    $fieldset = array(
378
      '#type' => 'fieldset',
379
      '#title' => t('CAPTCHA'),
380
      '#description' => $element['#description'],
381
      '#children' => drupal_render_children($element),
382
      '#attributes' => array('class' => array('captcha')),
383
    );
384
    return theme('fieldset', array('element' => $fieldset));
385
  }
386
  else {
387
    return '<div class="captcha">' . drupal_render_children($element) . '</div>';
388
  }
389
}
390

    
391
/**
392
 * Implements of hook_form_alter().
393
 *
394
 * This function adds a CAPTCHA to forms for untrusted users if needed and adds
395
 * CAPTCHA administration links for site administrators if this option is enabled.
396
 */
397
function captcha_form_alter(&$form, &$form_state, $form_id) {
398

    
399
  // If user has skip CAPTCHA permission, doesn't do anything.
400
  if (!user_access('skip CAPTCHA')) {
401
    // Visitor does not have permission to skip CAPTCHAs.
402
    module_load_include('inc', 'captcha');
403

    
404
    // Get CAPTCHA type and module for given form_id.
405
    $captcha_point = captcha_get_form_id_setting($form_id);
406

    
407
    // If no captcha point found, check to see if there is a setting for the base form id
408
    if (!$captcha_point) {
409
      if (isset($form_state['build_info']['base_form_id'])) {
410
        $captcha_point = captcha_get_form_id_setting($form_state['build_info']['base_form_id']);
411
      }
412
    }
413

    
414
    if ($captcha_point && !empty($captcha_point->captcha_type)) {
415
      module_load_include('inc', 'captcha');
416
      // Build CAPTCHA form element.
417
      $captcha_element = array(
418
        '#type' => 'captcha',
419
        '#captcha_type' => $captcha_point->module . '/' . $captcha_point->captcha_type,
420
      );
421
      // Add a CAPTCHA description if required.
422
      if (variable_get('captcha_add_captcha_description', TRUE)) {
423
        $captcha_element['#description'] = _captcha_get_description();
424
      }
425

    
426
      // Get placement in form and insert in form.
427
      $captcha_placement = _captcha_get_captcha_placement($form_id, $form);
428
      _captcha_insert_captcha_element($form, $captcha_placement, $captcha_element);
429
    }
430
  }
431

    
432
  // If user has access to administer CAPTCHA settings and
433
  // 'Add CAPTCHA administration links to forms' is enabled, display the
434
  // helper widget.
435
  if (
436
    variable_get('captcha_administration_mode', FALSE)
437
    && user_access('administer CAPTCHA settings')
438
    && (arg(0) != 'admin' || variable_get('captcha_allow_on_admin_pages', FALSE))
439
  ) {
440
    // Add CAPTCHA administration tools.
441
    module_load_include('inc', 'captcha');
442

    
443
    $captcha_point = captcha_get_form_id_setting($form_id);
444
    // For administrators: show CAPTCHA info and offer link to configure it.
445
    $captcha_element = array(
446
      '#type' => 'fieldset',
447
      '#title' => t('CAPTCHA'),
448
      '#collapsible' => TRUE,
449
      '#collapsed' => TRUE,
450
      '#attributes' => array('class' => array('captcha-admin-links')),
451
    );
452

    
453
    if ($captcha_point !== NULL && $captcha_point->captcha_type) {
454
      $captcha_element['#title'] = t('CAPTCHA: challenge "@type" enabled', array('@type' => $captcha_point->captcha_type));
455
      $captcha_element['#description'] = t('Untrusted users will see a CAPTCHA here (<a href="@settings">general CAPTCHA settings</a>).',
456
        array('@settings' => url('admin/config/people/captcha'))
457
      );
458
      $captcha_element['challenge'] = array(
459
        '#type' => 'item',
460
        '#title' => t('Enabled challenge'),
461
        '#markup' => t('%type by module %module (<a href="@change">change</a>, <a href="@disable">disable</a>)', array(
462
          '%type' => $captcha_point->captcha_type,
463
          '%module' => $captcha_point->module,
464
          '@change' => url("admin/config/people/captcha/captcha/captcha_point/$form_id", array('query' => drupal_get_destination())),
465
          '@disable' => url("admin/config/people/captcha/captcha/captcha_point/$form_id/disable", array('query' => drupal_get_destination())),
466
        )),
467
      );
468

    
469
      // Add an example challenge with solution.
470
      // This does not work with the reCAPTCHA and Egglue challenges as
471
      // discussed in http://drupal.org/node/487032 and
472
      // http://drupal.org/node/525586. As a temporary workaround, we
473
      // blacklist the reCAPTCHA and Egglue challenges and do not show
474
      // an example challenge.
475
      // TODO: Once the issues mentioned above are fixed, this workaround
476
      // should be removed.
477
      if ($captcha_point->module != 'recaptcha' && $captcha_point->module != 'egglue_captcha') {
478
        $captcha_element['example'] = array(
479
          '#type' => 'fieldset',
480
          '#title' => t('Example'),
481
          '#description' => t('This is a pre-solved, non-blocking example of this challenge.'),
482
        );
483
        $captcha_element['example']['example_captcha'] = array(
484
          '#type' => 'captcha',
485
          '#captcha_type' => $captcha_point->module . '/' . $captcha_point->captcha_type,
486
          '#captcha_admin_mode' => TRUE,
487
        );
488
      }
489
    }
490
    else {
491
      $captcha_element['#title'] = t('CAPTCHA: no challenge enabled');
492
      $captcha_element['add_captcha'] = array(
493
        '#markup' => l(t('Place a CAPTCHA here for untrusted users.'), "admin/config/people/captcha/captcha/captcha_point/$form_id", array('query' => drupal_get_destination()))
494
      );
495
    }
496

    
497
    // Get placement in form and insert in form.
498
    $captcha_placement = _captcha_get_captcha_placement($form_id, $form);
499
    _captcha_insert_captcha_element($form, $captcha_placement, $captcha_element);
500
  }
501

    
502
  // Add a warning about caching on the Perfomance settings page.
503
  if ($form_id == 'system_performance_settings') {
504
    $icon = theme(
505
      'image',
506
      array(
507
        'path' => 'misc/watchdog-warning.png',
508
        'width' => 18,
509
        'height' => 18,
510
        'alt' => t('warning'),
511
        'title' => t('warning'),
512
      )
513
    );
514
    $form['caching']['captcha'] = array(
515
      '#type' => 'item',
516
      '#title' => t('CAPTCHA'),
517
      '#markup' => t(
518
        '!icon The CAPTCHA module will disable the caching of pages that contain a CAPTCHA element.',
519
        array(
520
          '!icon' => '<span class="icon">' . $icon . '</span>'
521
        )
522
      ),
523
      '#attributes' => array('class' => array('warning')),
524
    );
525
  }
526

    
527
}
528

    
529
/**
530
 * CAPTCHA validation function to tests strict equality.
531
 *
532
 * @param string $solution
533
 *   the solution of the test.
534
 *
535
 * @param string $response
536
 *   the response to the test.
537
 *
538
 * @return bool
539
 *   TRUE when equal (ignoring spaces), FALSE otherwise.
540
 */
541
function captcha_validate_strict_equality($solution, $response) {
542
  return $solution === $response;
543
}
544

    
545
/**
546
 * CAPTCHA validation function to tests case insensitive equality.
547
 *
548
 * @param string $solution
549
 *   the solution of the test.
550
 *
551
 * @param string $response
552
 *   the response to the test.
553
 *
554
 * @return bool
555
 *   TRUE when equal (ignoring spaces), FALSE otherwise.
556
 */
557
function captcha_validate_case_insensitive_equality($solution, $response) {
558
  return drupal_strtolower($solution) === drupal_strtolower($response);
559
}
560

    
561
/**
562
 * CAPTCHA validation function to tests equality while ignoring spaces.
563
 *
564
 * @param string $solution
565
 *   the solution of the test.
566
 *
567
 * @param string $response
568
 *   the response to the test.
569
 *
570
 * @return bool
571
 *   TRUE when equal (ignoring spaces), FALSE otherwise.
572
 */
573
function captcha_validate_ignore_spaces($solution, $response) {
574
  return preg_replace('/\s/', '', $solution) === preg_replace('/\s/', '', $response);
575
}
576

    
577
/**
578
 * CAPTCHA validation function to tests case insensitive equality while ignoring spaces.
579
 *
580
 * @param string $solution
581
 *   the solution of the test.
582
 *
583
 * @param string $response
584
 *   the response to the test.
585
 *
586
 * @return bool
587
 *   TRUE when equal (ignoring spaces), FALSE otherwise.
588
 */
589
function captcha_validate_case_insensitive_ignore_spaces($solution, $response) {
590
  return preg_replace('/\s/', '', drupal_strtolower($solution)) === preg_replace('/\s/', '', drupal_strtolower($response));
591
}
592

    
593
/**
594
 * Helper function for getting the posted CAPTCHA info (posted form_id and
595
 * CAPTCHA sessions ID) from a form in case it is posted.
596
 *
597
 * This function hides the form processing mess for several use cases an
598
 * browser bug workarounds.
599
 * For example: $element['#post'] can typically be used to get the posted
600
 * form_id and captcha_sid, but in the case of node preview situations
601
 * (with correct CAPTCHA response) that does not work and we can get them from
602
 * $form_state['clicked_button']['#post'].
603
 * However with Internet Explorer 7, the latter does not work either when
604
 * submitting the forms (with only one text field) with the enter key
605
 * (see http://drupal.org/node/534168), in which case we also have to check
606
 * $form_state['buttons']['button']['0']['#post'].
607
 *
608
 * @todo for Drupal 7 version: is this IE7 workaround still needed?
609
 *
610
 * @param array $element
611
 *   the CAPTCHA element.
612
 *
613
 * @param array $form_state
614
 *   the form state structure to extract the info from.
615
 *
616
 * @param string $this_form_id
617
 *   the form ID of the form we are currently processing
618
 *     (which is not necessarily the form that was posted).
619
 *
620
 * @return array
621
 *   an array with $posted_form_id and $post_captcha_sid (with NULL values
622
 *     if the values could not be found, e.g. for a fresh form).
623
 */
624
function _captcha_get_posted_captcha_info($element, $form_state, $this_form_id) {
625
  //Handle Ajax scenarios
626
  if (!empty($form_state['rebuild_info'])) {
627
    if (!empty($form_state['captcha_info']['posted_form_id'])) {
628
      $posted_form_id = $form_state['captcha_info']['posted_form_id'];
629
    }
630
    else {
631
      $posted_form_id = $form_state['input']['form_id'];
632
    }
633

    
634
    $posted_captcha_sid = $form_state['captcha_info']['captcha_sid'];
635
  }
636
  else if ($form_state['submitted'] && isset($form_state['captcha_info'])) {
637
    // We are handling (or rebuilding) an already submitted form,
638
    // so we already determined the posted form ID and CAPTCHA session ID
639
    // for this form (from before submitting). Reuse this info.
640
    $posted_form_id = $form_state['captcha_info']['posted_form_id'];
641
    $posted_captcha_sid = $form_state['captcha_info']['captcha_sid'];
642
  }
643
  else {
644
    // We have to determine the posted form ID and CAPTCHA session ID
645
    // from the post data.
646
    // Because we possibly use raw post data here,
647
    // we should be extra cautious and filter this data.
648
    $posted_form_id = isset($form_state['input']['form_id']) ? preg_replace("/[^a-z0-9_]/", "", (string) $form_state['input']['form_id']) : NULL;
649
    $posted_captcha_sid = isset($form_state['input']['captcha_sid']) ? (int) $form_state['input']['captcha_sid'] : NULL;
650
    $posted_captcha_token = !empty($form_state['input']['captcha_token']) ? preg_replace("/[^a-zA-Z0-9]/", "", (string) $form_state['input']['captcha_token']) : NULL;
651

    
652
    if ($posted_form_id == $this_form_id) {
653
      // Check if the posted CAPTCHA token is valid for the posted CAPTCHA
654
      // session ID. Note that we could just check the validity of the CAPTCHA
655
      // token and extract the CAPTCHA session ID from that (without looking at
656
      // the actual posted CAPTCHA session ID). However, here we check both
657
      // the posted CAPTCHA token and session ID: it is a bit more stringent
658
      // and the database query should also be more efficient (because there is
659
      // an index on the CAPTCHA session ID).
660
      if ($posted_captcha_sid != NULL) {
661
        $expected_captcha_token = db_query(
662
          "SELECT token FROM {captcha_sessions} WHERE csid = :csid",
663
          array(':csid' => $posted_captcha_sid)
664
        )->fetchField();
665

    
666
        if ($expected_captcha_token !== $posted_captcha_token) {
667
          if (empty($form_state['input']['captcha_cacheable'])) {
668
            drupal_set_message(t('CAPTCHA session reuse attack detected.'), 'error');
669
          }
670
          // Invalidate the CAPTCHA session.
671
          $posted_captcha_sid = NULL;
672
        }
673

    
674
        // Invalidate CAPTCHA token to avoid reuse.
675
        db_update('captcha_sessions')
676
          ->fields(array('token' => NULL))
677
          ->condition('csid', $posted_captcha_sid)
678
          ->execute();
679
      }
680
    }
681
    else {
682
      // The CAPTCHA session ID is specific to the posted form.
683
      // Return NULL, so a new session will be generated for this other form.
684
      $posted_captcha_sid = NULL;
685
    }
686
  }
687
  return array($posted_form_id, $posted_captcha_sid);
688
}
689

    
690
/**
691
 * CAPTCHA validation handler.
692
 *
693
 * This function is placed in the main captcha.module file to make sure that
694
 * it is available (even for cached forms, which don't fire
695
 * captcha_form_alter(), and subsequently don't include additional include
696
 * files).
697
 */
698
function captcha_validate($element, &$form_state) {
699
  // If disable captcha mode is enabled, bypass captcha validation.
700
  if (variable_get('disable_captcha', FALSE)) {
701
    return;
702
  }
703

    
704
  $captcha_info = $form_state['captcha_info'];
705
  $form_id = $captcha_info['this_form_id'];
706

    
707
  // Get CAPTCHA response.
708
  $captcha_response = $form_state['values']['captcha_response'];
709

    
710
  // Get CAPTCHA session from CAPTCHA info
711
  // TODO: is this correct in all cases: see comment and code in previous revisions?
712
  $csid = $captcha_info['captcha_sid'];
713

    
714
  $solution = db_query(
715
    'SELECT solution FROM {captcha_sessions} WHERE csid = :csid',
716
    array(':csid' => $csid)
717
    )
718
    ->fetchField();
719

    
720
  // @todo: what is the result when there is no entry for the captcha_session? in D6 it was FALSE, what in D7?
721
  if ($solution === FALSE) {
722
    // Unknown challenge_id.
723
    // TODO: this probably never happens anymore now that there is detection
724
    // for CAPTCHA session reuse attacks in _captcha_get_posted_captcha_info().
725
    form_set_error('captcha', t('CAPTCHA validation error: unknown CAPTCHA session ID. Contact the site administrator if this problem persists.'));
726
    watchdog('CAPTCHA',
727
      'CAPTCHA validation error: unknown CAPTCHA session ID (%csid).',
728
      array('%csid' => var_export($csid, TRUE)),
729
      WATCHDOG_ERROR);
730
  }
731
  else {
732
    // Get CAPTCHA validate function or fall back on strict equality.
733
    $captcha_validate = $element['#captcha_validate'];
734
    if (!function_exists($captcha_validate)) {
735
      $captcha_validate = 'captcha_validate_strict_equality';
736
    }
737
    // Check the response with the CAPTCHA validation function.
738
    // Apart from the traditional expected $solution and received $response,
739
    // we also provide the CAPTCHA $element and $form_state arrays for more advanced use cases.
740
    if ($captcha_validate($solution, $captcha_response, $element, $form_state)) {
741
      // Correct answer.
742

    
743
      // Store form_id in session (but only if it is useful to do so, avoid setting stuff in session unnecessarily).
744
      $captcha_persistence = variable_get('captcha_persistence', CAPTCHA_PERSISTENCE_SKIP_ONCE_SUCCESSFUL_PER_FORM_INSTANCE);
745
      if ($captcha_persistence == CAPTCHA_PERSISTENCE_SKIP_ONCE_SUCCESSFUL || $captcha_persistence == CAPTCHA_PERSISTENCE_SKIP_ONCE_SUCCESSFUL_PER_FORM_TYPE) {
746
        $_SESSION['captcha_success_form_ids'][$form_id] = $form_id;
747
      }
748

    
749
      // Record success.
750
      db_update('captcha_sessions')
751
        ->condition('csid', $csid)
752
        ->fields(array('status' => CAPTCHA_STATUS_SOLVED))
753
        ->expression('attempts', 'attempts + 1')
754
        ->execute();
755
    }
756
    else {
757
      // Wrong answer.
758
      db_update('captcha_sessions')
759
        ->condition('csid', $csid)
760
        ->expression('attempts', 'attempts + 1')
761
        ->execute();
762
      // Set form error.
763
      form_set_error('captcha_response', _captcha_get_error_message());
764
      // Update wrong response counter.
765
      if (variable_get('captcha_enable_stats', FALSE)) {
766
        variable_set('captcha_wrong_response_counter', variable_get('captcha_wrong_response_counter', 0) + 1);
767
      }
768
      // Log to watchdog if needed.
769
      if (variable_get('captcha_log_wrong_responses', FALSE)) {
770
        watchdog('CAPTCHA',
771
          '%form_id post blocked by CAPTCHA module: challenge %challenge (by module %module), user answered "@response", but the solution was "@solution".',
772
          array(
773
            '%form_id' => $form_id,
774
            '@response' => $captcha_response, '@solution' => $solution,
775
            '%challenge' => $captcha_info['captcha_type'], '%module' => $captcha_info['module'],
776
          ),
777
          WATCHDOG_NOTICE);
778
      }
779
    }
780
  }
781
}
782

    
783
/**
784
 * Pre-render callback for additional processing of a CAPTCHA form element.
785
 *
786
 * This encompasses tasks that should happen after the general FAPI processing
787
 * (building, submission and validation) but before rendering (e.g. storing the solution).
788
 *
789
 * @param array $element
790
 *   the CAPTCHA form element
791
 *
792
 * @return array
793
 *   the manipulated element
794
 */
795
function captcha_pre_render_process($element) {
796
  module_load_include('inc', 'captcha');
797

    
798
  // Get form and CAPTCHA information.
799
  $captcha_info = $element['#captcha_info'];
800
  $form_id = $captcha_info['form_id'];
801
  $captcha_sid = (int) ($captcha_info['captcha_sid']);
802
  // Check if CAPTCHA is still required.
803
  // This check is done in a first phase during the element processing
804
  // (@see captcha_process), but it is also done here for better support
805
  // of multi-page forms. Take previewing a node submission for example:
806
  // when the challenge is solved correctely on preview, the form is still
807
  // not completely submitted, but the CAPTCHA can be skipped.
808
  if (_captcha_required_for_user($captcha_sid, $form_id) || $element['#captcha_admin_mode'] || $element['#captcha_always']) {
809
    // Prevent caching of the page with CAPTCHA elements.
810
    // This needs to be done only if the captcha is actually displayed.
811
    // The captcha display will be skipped only in 2 cases:
812
    //   - The captcha sid has a solution already.
813
    //   - The user has a SESSION.
814
    // For a page to be cacheable, the user MUST not have a SESSION.
815
    // For a SID to be solved already, it must be a POST request as else
816
    // a new unsolved SID is generated.
817
    // Therefore it is fine to disable the cache at this late stage here.
818
    if (empty($captcha_info['cacheable'])) {
819
      // The cache is only disabled if the captcha itself is not cacheable.
820
      drupal_page_is_cacheable(FALSE);
821
    }
822

    
823
    // Update captcha_sessions table: store the solution of the generated CAPTCHA.
824
    _captcha_update_captcha_session($captcha_sid, $captcha_info['solution']);
825

    
826
    // Handle the response field if it is available and if it is a textfield.
827
    if (isset($element['captcha_widgets']['captcha_response']['#type']) && $element['captcha_widgets']['captcha_response']['#type'] == 'textfield') {
828
      // Before rendering: presolve an admin mode challenge or
829
      // empty the value of the captcha_response form item.
830
      $value = $element['#captcha_admin_mode'] ? $captcha_info['solution'] : '';
831
      $element['captcha_widgets']['captcha_response']['#value'] = $value;
832
    }
833
  }
834
  else {
835
    // Remove CAPTCHA widgets from form.
836
    unset($element['captcha_widgets']);
837
  }
838

    
839
  return $element;
840
}
841

    
842
/**
843
 * Default implementation of hook_captcha().
844
 */
845
function captcha_captcha($op, $captcha_type = '') {
846
  switch ($op) {
847
    case 'list':
848
      return array('Math');
849

    
850
    case 'generate':
851
      if ($captcha_type == 'Math') {
852
        $result = array();
853
        $answer = mt_rand(1, 20);
854
        $x = mt_rand(1, $answer);
855
        $y = $answer - $x;
856
        $result['solution'] = "$answer";
857
        // Build challenge widget.
858
        // Note that we also use t() for the math challenge itself. This makes
859
        // it possible to 'rephrase' the challenge a bit through localization
860
        // or string overrides.
861
        $result['form']['captcha_response'] = array(
862
          '#type' => 'textfield',
863
          '#title' => t('Math question'),
864
          '#description' => t('Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.'),
865
          '#field_prefix' => t('@x + @y = ', array('@x' => $x, '@y' => $y)),
866
          '#size' => 4,
867
          '#maxlength' => 2,
868
          '#required' => TRUE,
869
        );
870
        return $result;
871
      }
872
      elseif ($captcha_type == 'Test') {
873
        // This challenge is not visible through the administrative interface
874
        // as it is not listed in captcha_captcha('list'),
875
        // but it is meant for debugging and testing purposes.
876
        // TODO for Drupal 7 version: This should be done with a mock module,
877
        // but Drupal 6 does not support this (mock modules can not be hidden).
878
        $result = array(
879
          'solution' => 'Test 123',
880
          'form' => array(),
881
        );
882
        $result['form']['captcha_response'] = array(
883
          '#type' => 'textfield',
884
          '#title' => t('Test one two three'),
885
          '#required' => TRUE,
886
        );
887
        return $result;
888
      }
889
      break;
890
  }
891
}
892

    
893
/**
894
 * Implements hook_modules_enabled().
895
 */
896
function captcha_modules_enabled() {
897
  // When new modules are enabled: clear the CAPTCHA placement cache, so that
898
  // new hook_captcha_placement_map hooks can be triggered.
899
  variable_del('captcha_placement_map_cache');
900
}