Projet

Général

Profil

Paste
Télécharger (15,8 ko) Statistiques
| Branche: | Révision:

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

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
 * Parse or interpret the given captcha_type.
271
 *
272
 * @param string $captcha_type
273
 *   string representation of the CAPTCHA type,
274
 *      e.g. 'default', 'none', 'captcha/Math', 'image_captcha/Image'
275
 *
276
 * @return array
277
 *   list($captcha_module, $captcha_type)
278
 */
279
function _captcha_parse_captcha_type($captcha_type) {
280
  if ($captcha_type == 'none') {
281
    return array(NULL, NULL);
282
  }
283
  if ($captcha_type == 'default') {
284
    $captcha_type = variable_get('captcha_default_challenge', 'captcha/Math');
285
  }
286
  return explode('/', $captcha_type);
287
}
288

    
289
/**
290
 * Helper function to get placement information for a given form_id.
291
 *
292
 * @param string $form_id
293
 *   the form_id to get the placement information for.
294
 *
295
 * @param array $form
296
 *   if a form corresponding to the given form_id, if there
297
 *   is no placement info for the given form_id, this form is examined to
298
 *   guess the placement.
299
 *
300
 * @return array
301
 *   placement info array (@see _captcha_insert_captcha_element() for more
302
 *   info about the fields 'path', 'key' and 'weight'.
303
 */
304
function _captcha_get_captcha_placement($form_id, $form) {
305
  // Get CAPTCHA placement map from cache. Two levels of cache:
306
  // static variable in this function and storage in the variables table.
307
  static $placement_map = NULL;
308
  // Try first level cache.
309
  if ($placement_map === NULL) {
310
    // If first level cache missed: try second level cache.
311
    $placement_map = variable_get('captcha_placement_map_cache', NULL);
312

    
313
    if ($placement_map === NULL) {
314
      // If second level cache missed: initialize the placement map
315
      // and let other modules hook into this with the hook_captcha_placement_map hook.
316
      // By default however, probably all Drupal core forms are already correctly
317
      // handled with the best effort guess based on the 'actions' element (see below).
318
      $placement_map = module_invoke_all('captcha_placement_map');
319
    }
320
  }
321

    
322
  // Query the placement map.
323
  if (array_key_exists($form_id, $placement_map)) {
324
    $placement = $placement_map[$form_id];
325
  }
326
  // If no placement info is available in placement map: make a best effort guess.
327
  else {
328
    // If there is an "actions" button group, a good placement is just before that.
329
    if (isset($form['actions']) && isset($form['actions']['#type']) && $form['actions']['#type'] === 'actions') {
330
      $placement = array(
331
        'path' => array(),
332
        'key' => 'actions',
333
        // #type 'actions' defaults to 100.
334
        'weight' => (isset($form['actions']['#weight']) ? $form['actions']['#weight'] - 1 : 99),
335
      );
336
    }
337
    else {
338
      // Search the form for buttons and guess placement from it.
339
      $buttons = _captcha_search_buttons($form);
340
      if (count($buttons)) {
341
        // Pick first button.
342
        // TODO: make this more sofisticated? Use cases needed.
343
        $placement = $buttons[0];
344
      }
345
      else {
346
        // Use NULL when no buttons were found.
347
        $placement = NULL;
348
      }
349
    }
350

    
351
    // Store calculated placement in cache.
352
    $placement_map[$form_id] = $placement;
353
    variable_set('captcha_placement_map_cache', $placement_map);
354
  }
355

    
356
  return $placement;
357
}
358

    
359
/**
360
 * Helper function for searching the buttons in a form.
361
 *
362
 * @param array $form
363
 *   the form to search button elements in
364
 *
365
 * @return array
366
 *   an array of paths to the buttons.
367
 *   A path is an array of keys leading to the button, the last
368
 *   item in the path is the weight of the button element
369
 *   (or NULL if undefined).
370
 */
371
function _captcha_search_buttons($form) {
372
  $buttons = array();
373
  foreach (element_children($form) as $key) {
374
    // Look for submit or button type elements.
375
    if (isset($form[$key]['#type']) && ($form[$key]['#type'] == 'submit' || $form[$key]['#type'] == 'button')) {
376
      $weight = isset($form[$key]['#weight']) ? $form[$key]['#weight'] : NULL;
377
      $buttons[] = array(
378
        'path' => array(),
379
        'key' => $key,
380
        'weight' => $weight,
381
      );
382
    }
383
    // Process children recurively.
384
    $children_buttons = _captcha_search_buttons($form[$key]);
385
    foreach ($children_buttons as $b) {
386
      $b['path'] = array_merge(array($key), $b['path']);
387
      $buttons[] = $b;
388
    }
389
  }
390
  return $buttons;
391
}
392

    
393
/**
394
 * Helper function to insert a CAPTCHA element in a form before a given form element.
395
 *
396
 * @param array $form
397
 *   the form to add the CAPTCHA element to.
398
 *
399
 * @param array $placement
400
 *   information where the CAPTCHA element should be inserted.
401
 *   $placement should be an associative array with fields:
402
 *     - 'path': path (array of path items) of the container in the form where the
403
 *       CAPTCHA element should be inserted.
404
 *     - 'key': the key of the element before which the CAPTCHA element
405
 *       should be inserted. If the field 'key' is undefined or NULL, the CAPTCHA will
406
 *       just be appended in the container.
407
 *     - 'weight': if 'key' is not NULL: should be the weight of the element defined by 'key'.
408
 *       If 'key' is NULL and weight is not NULL: set the weight property of the CAPTCHA element
409
 *       to this value.
410
 *
411
 * @param array $captcha_element
412
 *   the CAPTCHA element to insert.
413
 */
414
function _captcha_insert_captcha_element(&$form, $placement, $captcha_element) {
415
  // Get path, target and target weight or use defaults if not available.
416
  $target_key = isset($placement['key']) ? $placement['key'] : NULL;
417
  $target_weight = isset($placement['weight']) ? $placement['weight'] : NULL;
418
  $path = isset($placement['path']) ? $placement['path'] : array();
419

    
420
  // Walk through the form along the path.
421
  $form_stepper = &$form;
422
  foreach ($path as $step) {
423
    if (isset($form_stepper[$step])) {
424
      $form_stepper = & $form_stepper[$step];
425
    }
426
    else {
427
      // Given path is invalid: stop stepping and
428
      // continue in best effort (append instead of insert).
429
      $target_key = NULL;
430
      break;
431
    }
432
  }
433

    
434
  // If no target is available: just append the CAPTCHA element to the container.
435
  if ($target_key == NULL || !array_key_exists($target_key, $form_stepper)) {
436
    // Optionally, set weight of CAPTCHA element.
437
    if ($target_weight != NULL) {
438
      $captcha_element['#weight'] = $target_weight;
439
    }
440
    $form_stepper['captcha'] = $captcha_element;
441
  }
442
  // If there is a target available: make sure the CAPTCHA element comes right before it.
443
  else {
444
    // If target has a weight: set weight of CAPTCHA element a bit smaller
445
    // and just append the CAPTCHA: sorting will fix the ordering anyway.
446
    if ($target_weight != NULL) {
447
      $captcha_element['#weight'] = $target_weight - .1;
448
      $form_stepper['captcha'] = $captcha_element;
449
    }
450
    else {
451
      // If we can't play with weights: insert the CAPTCHA element at the right position.
452
      // Because PHP lacks a function for this (array_splice() comes close,
453
      // but it does not preserve the key of the inserted element), we do it by hand:
454
      // chop of the end, append the CAPTCHA element and put the end back.
455
      $offset = array_search($target_key, array_keys($form_stepper));
456
      $end = array_splice($form_stepper, $offset);
457
      $form_stepper['captcha'] = $captcha_element;
458
      foreach ($end as $k => $v) {
459
        $form_stepper[$k] = $v;
460
      }
461
    }
462
  }
463
}