Projet

Général

Profil

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

root / drupal7 / sites / all / modules / captcha / captcha.inc @ 00c2605a

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) && isset($captcha_type->module) && isset($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 ($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 ($captcha_point->module == NULL && $captcha_point->captcha_type == NULL && $symbolic) {
118
    $captcha_point = 'none';
119
  }
120
  elseif ($symbolic) {
121
    $captcha_point = $captcha_point->module . '/' . $captcha_point->captcha_type;
122
  }
123
  return $captcha_point;
124
}
125

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

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

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

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

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

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

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

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

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

    
238

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

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

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

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

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

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

    
355
  return $placement;
356
}
357

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

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

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

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