Projet

Général

Profil

Paste
Télécharger (16,9 ko) Statistiques
| Branche: | Révision:

root / drupal7 / sites / all / modules / captcha / captcha.inc @ a8cee257

1
<?php
2

    
3
/**
4
 * @file
5
 * General CAPTCHA functionality and helper functions.
6
 */
7

    
8
/**
9
 * Helper function for adding/updating a CAPTCHA point.
10
 *
11
 * @param string $form_id
12
 *   the form ID to configure.
13
 *
14
 * @param string $captcha_type
15
 *   the setting for the given form_id, can be:
16
 *   - 'none' to disable CAPTCHA,
17
 *   - 'default' to use the default challenge type
18
 *   - NULL to remove the entry for the CAPTCHA type
19
 *   - something of the form 'image_captcha/Image'
20
 *   - an object with attributes $captcha_type->module and $captcha_type->captcha_type
21
 */
22
function captcha_set_form_id_setting($form_id, $captcha_type) {
23
  // Handle 'none'.
24
  if ($captcha_type == 'none') {
25
    db_merge('captcha_points')
26
      ->key(array('form_id' => $form_id))
27
      ->fields(array('module' => NULL, 'captcha_type' => NULL))
28
      ->execute();
29
  }
30
  // Handle 'default'.
31
  elseif ($captcha_type == 'default') {
32
    db_merge('captcha_points')
33
      ->key(array('form_id' => $form_id))
34
      ->fields(array('module' => NULL, 'captcha_type' => 'default'))
35
      ->execute();
36
  }
37
  // Handle NULL.
38
  elseif ($captcha_type == NULL) {
39
    db_delete('captcha_points')->condition('form_id', $form_id)->execute();
40
  }
41
  // Handle a captcha_type object.
42
  elseif (is_object($captcha_type) && !empty($captcha_type->module) && !empty($captcha_type->captcha_type)) {
43
    db_merge('captcha_points')
44
      ->key(array('form_id' => $form_id))
45
      ->fields(array('module' => $captcha_type->module, 'captcha_type' => $captcha_type->captcha_type))
46
      ->execute();
47
  }
48
  // Handle a captcha_type string.
49
  elseif (is_string($captcha_type) && substr_count($captcha_type, '/') == 1) {
50
    list($module, $type) = explode('/', $captcha_type);
51
    db_merge('captcha_points')
52
      ->key(array('form_id' => $form_id))
53
      ->fields(array('module' => $module, 'captcha_type' => $type))
54
      ->execute();
55
  }
56
  else {
57
    drupal_set_message(
58
      t('Failed to set a CAPTCHA type for form %form_id: could not interpret value "@captcha_type"',
59
      array(
60
        '%form_id' => $form_id,
61
        '@captcha_type' => (string) $captcha_type,
62
      )
63
      ),
64
      'warning'
65
    );
66
  }
67
}
68

    
69
/**
70
 * Get the CAPTCHA setting for a given form_id.
71
 *
72
 * @param string $form_id
73
 *   the form_id to query for
74
 *
75
 * @param bool $symbolic
76
 *   flag to return as (symbolic) strings instead of object.
77
 *
78
 * @return NULL
79
 *   if no setting is known
80
 *   or a captcha_point object with fields 'module' and 'captcha_type'.
81
 *   If argument $symbolic is true, returns (symbolic) as 'none', 'default'
82
 *   or in the form 'captcha/Math'.
83
 */
84
function captcha_get_form_id_setting($form_id, $symbolic = FALSE) {
85
  // Fetch setting from database.
86
  if (module_exists('ctools')) {
87
    ctools_include('export');
88
    $object = ctools_export_load_object('captcha_points', 'names', array($form_id));
89
    $captcha_point = array_pop($object);
90
  }
91
  else {
92
    $result = db_query("SELECT module, captcha_type FROM {captcha_points} WHERE form_id = :form_id",
93
      array(':form_id' =>  $form_id));
94
    $captcha_point = $result->fetchObject();
95
  }
96

    
97
  // If no setting is available in database for the given form,
98
  // but 'captcha_default_challenge_on_nonlisted_forms' is enabled, pick the default type anyway.
99
  if (!$captcha_point && variable_get('captcha_default_challenge_on_nonlisted_forms', FALSE)) {
100
    $captcha_point = (object) array('captcha_type' => 'default');
101
  }
102

    
103
  // Handle (default) settings and symbolic mode.
104
  if (!$captcha_point) {
105
    $captcha_point = NULL;
106
  }
107
  elseif (!empty($captcha_point->captcha_type) && $captcha_point->captcha_type == 'default') {
108
    if (!$symbolic) {
109
      list($module, $type) = explode('/', variable_get('captcha_default_challenge', 'captcha/Math'));
110
      $captcha_point->module = $module;
111
      $captcha_point->captcha_type = $type;
112
    }
113
    else {
114
      $captcha_point = 'default';
115
    }
116
  }
117
  elseif (empty($captcha_point->module) && empty($captcha_point->captcha_type) && $symbolic) {
118
    $captcha_point = 'none';
119
  }
120
  elseif ($symbolic) {
121
    $captcha_point = $captcha_point->module . '/' . $captcha_point->captcha_type;
122
  }
123

    
124
  return $captcha_point;
125
}
126

    
127
/**
128
 * Helper function to load all captcha points.
129
 *
130
 * @return array of all captcha_points
131
 */
132
function captcha_get_captcha_points() {
133
  if (module_exists('ctools')) {
134
    ctools_include('export');
135
    $captcha_points = ctools_export_load_object('captcha_points', 'all');
136
  }
137
  else {
138
    $captcha_points = array();
139
    $result = db_select('captcha_points', 'cp')->fields('cp')->orderBy('form_id')->execute();
140
    foreach ($result as $captcha_point) {
141
      $captcha_points[] = $captcha_point;
142
    }
143
  }
144
  return $captcha_points;
145
}
146

    
147
/**
148
 * Helper function for generating a new CAPTCHA session.
149
 *
150
 * @param string $form_id
151
 *   the form_id of the form to add a CAPTCHA to.
152
 *
153
 * @param int $status
154
 *   the initial status of the CAPTHCA session.
155
 *
156
 * @return int
157
 *   the session ID of the new CAPTCHA session.
158
 */
159
function _captcha_generate_captcha_session($form_id = NULL, $status = CAPTCHA_STATUS_UNSOLVED) {
160
  global $user;
161
  // Initialize solution with random data.
162
  $solution = md5(mt_rand());
163
  // Insert an entry and thankfully receive the value of the autoincrement field 'csid'.
164
  $captcha_sid = db_insert('captcha_sessions')
165
  ->fields(array(
166
    'uid' => $user->uid,
167
    'sid' => session_id(),
168
    'ip_address' => ip_address(),
169
    'timestamp' => REQUEST_TIME,
170
    'form_id' => $form_id,
171
    'solution' => $solution,
172
    'status' => $status,
173
    'attempts' => 0,
174
  ))
175
  ->execute();
176
  return $captcha_sid;
177
}
178

    
179
/**
180
 * Helper function for updating the solution in the CAPTCHA session table.
181
 *
182
 * @param int $captcha_sid
183
 *   the CAPTCHA session ID to update.
184
 *
185
 * @param string $solution
186
 *   the new solution to associate with the given CAPTCHA session.
187
 */
188
function _captcha_update_captcha_session($captcha_sid, $solution) {
189
  db_update('captcha_sessions')
190
    ->condition('csid', $captcha_sid)
191
    ->fields(array(
192
      'timestamp' => REQUEST_TIME,
193
      'solution' => $solution,
194
    ))
195
    ->execute();
196
}
197

    
198
/**
199
 * Helper function for checking if CAPTCHA is required for user.
200
 *
201
 * Based on the CAPTCHA persistence setting, the CAPTCHA session ID and
202
 * user session info.
203
 */
204
function _captcha_required_for_user($captcha_sid, $form_id) {
205
  // Get the CAPTCHA persistence setting.
206
  $captcha_persistence = variable_get('captcha_persistence', CAPTCHA_PERSISTENCE_SKIP_ONCE_SUCCESSFUL_PER_FORM_INSTANCE);
207

    
208
  // First check: should we always add a CAPTCHA?
209
  if ($captcha_persistence == CAPTCHA_PERSISTENCE_SHOW_ALWAYS) {
210
    return TRUE;
211
  }
212

    
213
  // Get the status of the current CAPTCHA session.
214
  $captcha_session_status = db_query('SELECT status FROM {captcha_sessions} WHERE csid = :csid', array(':csid' => $captcha_sid))->fetchField();
215
  // Second check: if the current session is already solved: omit further CAPTCHAs.
216
  if ($captcha_session_status == CAPTCHA_STATUS_SOLVED) {
217
    return FALSE;
218
  }
219

    
220
  // Third check: look at the persistence level (per form instance, per form or per user).
221
  if ($captcha_persistence == CAPTCHA_PERSISTENCE_SKIP_ONCE_SUCCESSFUL_PER_FORM_INSTANCE) {
222
    return TRUE;
223
  }
224
  else {
225
    $captcha_success_form_ids = isset($_SESSION['captcha_success_form_ids']) ? (array) ($_SESSION['captcha_success_form_ids']) : array();
226
    switch ($captcha_persistence) {
227
      case CAPTCHA_PERSISTENCE_SKIP_ONCE_SUCCESSFUL:
228
        return (count($captcha_success_form_ids) == 0);
229

    
230
      case CAPTCHA_PERSISTENCE_SKIP_ONCE_SUCCESSFUL_PER_FORM_TYPE:
231
        return !isset($captcha_success_form_ids[$form_id]);
232
    }
233
  }
234

    
235
  // We should never get to this point, but to be sure, we return TRUE.
236
  return TRUE;
237
}
238

    
239

    
240
/**
241
 * Get the CAPTCHA description as configured on the general CAPTCHA settings page.
242
 *
243
 * If the locale module is enabled, the description will be returned
244
 * for the current language the page is rendered for. This language
245
 * can optionally been overridden with the $lang_code argument.
246
 *
247
 * @param string|null $lang_code
248
 *   an optional language code to get the description for.
249
 *
250
 * @return string
251
 *   String with (localized) CAPTCHA description.
252
 */
253
function _captcha_get_description($lang_code = NULL) {
254
  // If no language code is given: use the language of the current page.
255
  global $language;
256
  $lang_code = isset($lang_code) ? $lang_code : $language->language;
257
  // The hardcoded but localizable default.
258
  $default = t('This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.', array(), array('langcode' => $lang_code));
259
  // Look up the configured CAPTCHA description or fall back on the (localized) default.
260
  if (module_exists('locale')) {
261
    $description = variable_get("captcha_description_$lang_code", $default);
262
  }
263
  else {
264
    $description = variable_get('captcha_description', $default);
265
  }
266
  return filter_xss_admin($description);
267
}
268

    
269
/**
270
 * Get the error message as configured on the general CAPTCHA settings page.
271
 *
272
 * If the locale module is enabled, the error message will be returned
273
 * for the current language the page is rendered for. This language
274
 * can optionally been overridden with the $lang_code argument.
275
 *
276
 * @param string|null $lang_code
277
 *   an optional language code to get the description for.
278
 *
279
 * @return string
280
 *   String with (localized) error message.
281
 */
282
function _captcha_get_error_message($lang_code = NULL) {
283
  // If no language code is given: use the language of the current page.
284
  global $language;
285
  $lang_code = isset($lang_code) ? $lang_code : $language->language;
286
  // The hardcoded but localizable default.
287
  $default = t('The answer you entered for the CAPTCHA was not correct.', array(), array('langcode' => $lang_code));
288
  // Look up the configured error message or fall back on the (localized) default.
289
  if (module_exists('locale')) {
290
    $message = variable_get('captcha_error_message_' . $lang_code, $default);
291
  }
292
  else {
293
    $message = variable_get('captcha_error_message', $default);
294
  }
295
  return filter_xss_admin($message);
296
}
297

    
298
/**
299
 * Parse or interpret the given captcha_type.
300
 *
301
 * @param string $captcha_type
302
 *   string representation of the CAPTCHA type,
303
 *      e.g. 'default', 'none', 'captcha/Math', 'image_captcha/Image'
304
 *
305
 * @return array
306
 *   list($captcha_module, $captcha_type)
307
 */
308
function _captcha_parse_captcha_type($captcha_type) {
309
  if ($captcha_type == 'none') {
310
    return array(NULL, NULL);
311
  }
312
  if ($captcha_type == 'default') {
313
    $captcha_type = variable_get('captcha_default_challenge', 'captcha/Math');
314
  }
315
  return explode('/', $captcha_type);
316
}
317

    
318
/**
319
 * Helper function to get placement information for a given form_id.
320
 *
321
 * @param string $form_id
322
 *   the form_id to get the placement information for.
323
 *
324
 * @param array $form
325
 *   if a form corresponding to the given form_id, if there
326
 *   is no placement info for the given form_id, this form is examined to
327
 *   guess the placement.
328
 *
329
 * @return array
330
 *   placement info array (@see _captcha_insert_captcha_element() for more
331
 *   info about the fields 'path', 'key' and 'weight'.
332
 */
333
function _captcha_get_captcha_placement($form_id, $form) {
334
  // Get CAPTCHA placement map from cache. Two levels of cache:
335
  // static variable in this function and storage in the variables table.
336
  static $placement_map = NULL;
337
  // Try first level cache.
338
  if ($placement_map === NULL) {
339
    // If first level cache missed: try second level cache.
340
    $placement_map = variable_get('captcha_placement_map_cache', NULL);
341

    
342
    if ($placement_map === NULL) {
343
      // If second level cache missed: initialize the placement map
344
      // and let other modules hook into this with the hook_captcha_placement_map hook.
345
      // By default however, probably all Drupal core forms are already correctly
346
      // handled with the best effort guess based on the 'actions' element (see below).
347
      $placement_map = module_invoke_all('captcha_placement_map');
348
    }
349
  }
350

    
351
  // Query the placement map.
352
  if (array_key_exists($form_id, $placement_map)) {
353
    $placement = $placement_map[$form_id];
354
  }
355
  // If no placement info is available in placement map: make a best effort guess.
356
  else {
357
    // If there is an "actions" button group, a good placement is just before that.
358
    if (isset($form['actions']) && isset($form['actions']['#type']) && $form['actions']['#type'] === 'actions') {
359
      $placement = array(
360
        'path' => array(),
361
        'key' => 'actions',
362
        // #type 'actions' defaults to 100.
363
        'weight' => (isset($form['actions']['#weight']) ? $form['actions']['#weight'] - 1 : 99),
364
      );
365
    }
366
    else {
367
      // Search the form for buttons and guess placement from it.
368
      $buttons = _captcha_search_buttons($form);
369
      if (count($buttons)) {
370
        // Pick first button.
371
        // TODO: make this more sofisticated? Use cases needed.
372
        $placement = (isset($buttons[count($buttons) - 1])) ? $buttons[count($buttons) - 1] : $buttons[0];
373
      }
374
      else {
375
        // Use NULL when no buttons were found.
376
        $placement = NULL;
377
      }
378
    }
379

    
380
    // Store calculated placement in cache.
381
    $placement_map[$form_id] = $placement;
382
    variable_set('captcha_placement_map_cache', $placement_map);
383
  }
384

    
385
  return $placement;
386
}
387

    
388
/**
389
 * Helper function for searching the buttons in a form.
390
 *
391
 * @param array $form
392
 *   the form to search button elements in
393
 *
394
 * @return array
395
 *   an array of paths to the buttons.
396
 *   A path is an array of keys leading to the button, the last
397
 *   item in the path is the weight of the button element
398
 *   (or NULL if undefined).
399
 */
400
function _captcha_search_buttons($form) {
401
  $buttons = array();
402
  foreach (element_children($form) as $key) {
403
    // Look for submit or button type elements.
404
    if (isset($form[$key]['#type']) && ($form[$key]['#type'] == 'submit' || $form[$key]['#type'] == 'button')) {
405
      $weight = isset($form[$key]['#weight']) ? $form[$key]['#weight'] : NULL;
406
      $buttons[] = array(
407
        'path' => array(),
408
        'key' => $key,
409
        'weight' => $weight,
410
      );
411
    }
412
    // Process children recurively.
413
    $children_buttons = _captcha_search_buttons($form[$key]);
414
    foreach ($children_buttons as $b) {
415
      $b['path'] = array_merge(array($key), $b['path']);
416
      $buttons[] = $b;
417
    }
418
  }
419
  return $buttons;
420
}
421

    
422
/**
423
 * Helper function to insert a CAPTCHA element in a form before a given form element.
424
 *
425
 * @param array $form
426
 *   the form to add the CAPTCHA element to.
427
 *
428
 * @param array $placement
429
 *   information where the CAPTCHA element should be inserted.
430
 *   $placement should be an associative array with fields:
431
 *     - 'path': path (array of path items) of the container in the form where the
432
 *       CAPTCHA element should be inserted.
433
 *     - 'key': the key of the element before which the CAPTCHA element
434
 *       should be inserted. If the field 'key' is undefined or NULL, the CAPTCHA will
435
 *       just be appended in the container.
436
 *     - 'weight': if 'key' is not NULL: should be the weight of the element defined by 'key'.
437
 *       If 'key' is NULL and weight is not NULL: set the weight property of the CAPTCHA element
438
 *       to this value.
439
 *
440
 * @param array $captcha_element
441
 *   the CAPTCHA element to insert.
442
 */
443
function _captcha_insert_captcha_element(&$form, $placement, $captcha_element) {
444
  // Get path, target and target weight or use defaults if not available.
445
  $target_key = isset($placement['key']) ? $placement['key'] : NULL;
446
  $target_weight = isset($placement['weight']) ? $placement['weight'] : NULL;
447
  $path = isset($placement['path']) ? $placement['path'] : array();
448

    
449
  // Walk through the form along the path.
450
  $form_stepper = &$form;
451
  foreach ($path as $step) {
452
    if (isset($form_stepper[$step])) {
453
      $form_stepper = & $form_stepper[$step];
454
    }
455
    else {
456
      // Given path is invalid: stop stepping and
457
      // continue in best effort (append instead of insert).
458
      $target_key = NULL;
459
      break;
460
    }
461
  }
462

    
463
  // If no target is available: just append the CAPTCHA element to the container.
464
  if ($target_key == NULL || !array_key_exists($target_key, $form_stepper)) {
465
    // Optionally, set weight of CAPTCHA element.
466
    if ($target_weight != NULL) {
467
      $captcha_element['#weight'] = $target_weight;
468
    }
469
    $form_stepper['captcha'] = $captcha_element;
470
  }
471
  // If there is a target available: make sure the CAPTCHA element comes right before it.
472
  else {
473
    // If target has a weight: set weight of CAPTCHA element a bit smaller
474
    // and just append the CAPTCHA: sorting will fix the ordering anyway.
475
    if ($target_weight != NULL) {
476
      $captcha_element['#weight'] = $target_weight - .1;
477
      $form_stepper['captcha'] = $captcha_element;
478
    }
479
    else {
480
      // If we can't play with weights: insert the CAPTCHA element at the right position.
481
      // Because PHP lacks a function for this (array_splice() comes close,
482
      // but it does not preserve the key of the inserted element), we do it by hand:
483
      // chop of the end, append the CAPTCHA element and put the end back.
484
      $offset = array_search($target_key, array_keys($form_stepper));
485
      $end = array_splice($form_stepper, $offset);
486
      $form_stepper['captcha'] = $captcha_element;
487
      foreach ($end as $k => $v) {
488
        $form_stepper[$k] = $v;
489
      }
490
    }
491
  }
492
}