Projet

Général

Profil

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

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

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
  $result = db_query("SELECT module, captcha_type FROM {captcha_points} WHERE form_id = :form_id", array(':form_id' => $form_id));
87
  $captcha_point = $result->fetchObject();
88

    
89
  // If no setting is available in database for the given form,
90
  // but 'captcha_default_challenge_on_nonlisted_forms' is enabled, pick the default type anyway.
91
  if (!$captcha_point && variable_get('captcha_default_challenge_on_nonlisted_forms', FALSE)) {
92
    $captcha_point = (object) array('captcha_type' => 'default');
93
  }
94

    
95
  // Handle (default) settings and symbolic mode.
96
  if (!$captcha_point) {
97
    $captcha_point = NULL;
98
  }
99
  elseif ($captcha_point->captcha_type == 'default') {
100
    if (!$symbolic) {
101
      list($module, $type) = explode('/', variable_get('captcha_default_challenge', 'captcha/Math'));
102
      $captcha_point->module = $module;
103
      $captcha_point->captcha_type = $type;
104
    }
105
    else {
106
      $captcha_point = 'default';
107
    }
108
  }
109
  elseif ($captcha_point->module == NULL && $captcha_point->captcha_type == NULL && $symbolic) {
110
    $captcha_point = 'none';
111
  }
112
  elseif ($symbolic) {
113
    $captcha_point = $captcha_point->module . '/' . $captcha_point->captcha_type;
114
  }
115
  return $captcha_point;
116
}
117

    
118
/**
119
 * Helper function for generating a new CAPTCHA session.
120
 *
121
 * @param string $form_id
122
 *   the form_id of the form to add a CAPTCHA to.
123
 *
124
 * @param int $status
125
 *   the initial status of the CAPTHCA session.
126
 *
127
 * @return int
128
 *   the session ID of the new CAPTCHA session.
129
 */
130
function _captcha_generate_captcha_session($form_id = NULL, $status = CAPTCHA_STATUS_UNSOLVED) {
131
  global $user;
132
  // Initialize solution with random data.
133
  $solution = md5(mt_rand());
134
  // Insert an entry and thankfully receive the value of the autoincrement field 'csid'.
135
  $captcha_sid = db_insert('captcha_sessions')
136
  ->fields(array(
137
    'uid' => $user->uid,
138
    'sid' => session_id(),
139
    'ip_address' => ip_address(),
140
    'timestamp' => REQUEST_TIME,
141
    'form_id' => $form_id,
142
    'solution' => $solution,
143
    'status' => $status,
144
    'attempts' => 0,
145
  ))
146
  ->execute();
147
  return $captcha_sid;
148
}
149

    
150
/**
151
 * Helper function for updating the solution in the CAPTCHA session table.
152
 *
153
 * @param int $captcha_sid
154
 *   the CAPTCHA session ID to update.
155
 *
156
 * @param string $solution
157
 *   the new solution to associate with the given CAPTCHA session.
158
 */
159
function _captcha_update_captcha_session($captcha_sid, $solution) {
160
  db_update('captcha_sessions')
161
    ->condition('csid', $captcha_sid)
162
    ->fields(array(
163
      'timestamp' => REQUEST_TIME,
164
      'solution' => $solution,
165
    ))
166
    ->execute();
167
}
168

    
169
/**
170
 * Helper function for checking if CAPTCHA is required for user.
171
 *
172
 * Based on the CAPTCHA persistence setting, the CAPTCHA session ID and
173
 * user session info.
174
 */
175
function _captcha_required_for_user($captcha_sid, $form_id) {
176
  // Get the CAPTCHA persistence setting.
177
  $captcha_persistence = variable_get('captcha_persistence', CAPTCHA_PERSISTENCE_SKIP_ONCE_SUCCESSFUL_PER_FORM_INSTANCE);
178

    
179
  // First check: should we always add a CAPTCHA?
180
  if ($captcha_persistence == CAPTCHA_PERSISTENCE_SHOW_ALWAYS) {
181
    return TRUE;
182
  }
183

    
184
  // Get the status of the current CAPTCHA session.
185
  $captcha_session_status = db_query('SELECT status FROM {captcha_sessions} WHERE csid = :csid', array(':csid' => $captcha_sid))->fetchField();
186
  // Second check: if the current session is already solved: omit further CAPTCHAs.
187
  if ($captcha_session_status == CAPTCHA_STATUS_SOLVED) {
188
    return FALSE;
189
  }
190

    
191
  // Third check: look at the persistence level (per form instance, per form or per user).
192
  if ($captcha_persistence == CAPTCHA_PERSISTENCE_SKIP_ONCE_SUCCESSFUL_PER_FORM_INSTANCE) {
193
    return TRUE;
194
  }
195
  else {
196
    $captcha_success_form_ids = isset($_SESSION['captcha_success_form_ids']) ? (array) ($_SESSION['captcha_success_form_ids']) : array();
197
    switch ($captcha_persistence) {
198
      case CAPTCHA_PERSISTENCE_SKIP_ONCE_SUCCESSFUL:
199
        return (count($captcha_success_form_ids) == 0);
200

    
201
      case CAPTCHA_PERSISTENCE_SKIP_ONCE_SUCCESSFUL_PER_FORM_TYPE:
202
        return !isset($captcha_success_form_ids[$form_id]);
203
    }
204
  }
205

    
206
  // We should never get to this point, but to be sure, we return TRUE.
207
  return TRUE;
208
}
209

    
210

    
211
/**
212
 * Get the CAPTCHA description as configured on the general CAPTCHA settings page.
213
 *
214
 * If the locale module is enabled, the description will be returned
215
 * for the current language the page is rendered for. This language
216
 * can optionally been overridden with the $lang_code argument.
217
 *
218
 * @param string|null $lang_code
219
 *   an optional language code to get the description for.
220
 *
221
 * @return string
222
 *   String with (localized) CAPTCHA description.
223
 */
224
function _captcha_get_description($lang_code = NULL) {
225
  // If no language code is given: use the language of the current page.
226
  global $language;
227
  $lang_code = isset($lang_code) ? $lang_code : $language->language;
228
  // The hardcoded but localizable default.
229
  $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));
230
  // Look up the configured CAPTCHA description or fall back on the (localized) default.
231
  if (module_exists('locale')) {
232
    $description = variable_get("captcha_description_$lang_code", $default);
233
  }
234
  else {
235
    $description = variable_get('captcha_description', $default);
236
  }
237
  return filter_xss_admin($description);
238
}
239

    
240
/**
241
 * Parse or interpret the given captcha_type.
242
 *
243
 * @param string $captcha_type
244
 *   string representation of the CAPTCHA type,
245
 *      e.g. 'default', 'none', 'captcha/Math', 'image_captcha/Image'
246
 *
247
 * @return array
248
 *   list($captcha_module, $captcha_type)
249
 */
250
function _captcha_parse_captcha_type($captcha_type) {
251
  if ($captcha_type == 'none') {
252
    return array(NULL, NULL);
253
  }
254
  if ($captcha_type == 'default') {
255
    $captcha_type = variable_get('captcha_default_challenge', 'captcha/Math');
256
  }
257
  return explode('/', $captcha_type);
258
}
259

    
260
/**
261
 * Helper function to get placement information for a given form_id.
262
 *
263
 * @param string $form_id
264
 *   the form_id to get the placement information for.
265
 *
266
 * @param array $form
267
 *   if a form corresponding to the given form_id, if there
268
 *   is no placement info for the given form_id, this form is examined to
269
 *   guess the placement.
270
 *
271
 * @return array
272
 *   placement info array (@see _captcha_insert_captcha_element() for more
273
 *   info about the fields 'path', 'key' and 'weight'.
274
 */
275
function _captcha_get_captcha_placement($form_id, $form) {
276
  // Get CAPTCHA placement map from cache. Two levels of cache:
277
  // static variable in this function and storage in the variables table.
278
  static $placement_map = NULL;
279
  // Try first level cache.
280
  if ($placement_map === NULL) {
281
    // If first level cache missed: try second level cache.
282
    $placement_map = variable_get('captcha_placement_map_cache', NULL);
283

    
284
    if ($placement_map === NULL) {
285
      // If second level cache missed: initialize the placement map
286
      // and let other modules hook into this with the hook_captcha_placement_map hook.
287
      // By default however, probably all Drupal core forms are already correctly
288
      // handled with the best effort guess based on the 'actions' element (see below).
289
      $placement_map = module_invoke_all('captcha_placement_map');
290
    }
291
  }
292

    
293
  // Query the placement map.
294
  if (array_key_exists($form_id, $placement_map)) {
295
    $placement = $placement_map[$form_id];
296
  }
297
  // If no placement info is available in placement map: make a best effort guess.
298
  else {
299
    // If there is an "actions" button group, a good placement is just before that.
300
    if (isset($form['actions']) && isset($form['actions']['#type']) && $form['actions']['#type'] === 'actions') {
301
      $placement = array(
302
        'path' => array(),
303
        'key' => 'actions',
304
        // #type 'actions' defaults to 100.
305
        'weight' => (isset($form['actions']['#weight']) ? $form['actions']['#weight'] - 1 : 99),
306
      );
307
    }
308
    else {
309
      // Search the form for buttons and guess placement from it.
310
      $buttons = _captcha_search_buttons($form);
311
      if (count($buttons)) {
312
        // Pick first button.
313
        // TODO: make this more sofisticated? Use cases needed.
314
        $placement = $buttons[0];
315
      }
316
      else {
317
        // Use NULL when no buttons were found.
318
        $placement = NULL;
319
      }
320
    }
321

    
322
    // Store calculated placement in cache.
323
    $placement_map[$form_id] = $placement;
324
    variable_set('captcha_placement_map_cache', $placement_map);
325
  }
326

    
327
  return $placement;
328
}
329

    
330
/**
331
 * Helper function for searching the buttons in a form.
332
 *
333
 * @param array $form
334
 *   the form to search button elements in
335
 *
336
 * @return array
337
 *   an array of paths to the buttons.
338
 *   A path is an array of keys leading to the button, the last
339
 *   item in the path is the weight of the button element
340
 *   (or NULL if undefined).
341
 */
342
function _captcha_search_buttons($form) {
343
  $buttons = array();
344
  foreach (element_children($form) as $key) {
345
    // Look for submit or button type elements.
346
    if (isset($form[$key]['#type']) && ($form[$key]['#type'] == 'submit' || $form[$key]['#type'] == 'button')) {
347
      $weight = isset($form[$key]['#weight']) ? $form[$key]['#weight'] : NULL;
348
      $buttons[] = array(
349
        'path' => array(),
350
        'key' => $key,
351
        'weight' => $weight,
352
      );
353
    }
354
    // Process children recurively.
355
    $children_buttons = _captcha_search_buttons($form[$key]);
356
    foreach ($children_buttons as $b) {
357
      $b['path'] = array_merge(array($key), $b['path']);
358
      $buttons[] = $b;
359
    }
360
  }
361
  return $buttons;
362
}
363

    
364
/**
365
 * Helper function to insert a CAPTCHA element in a form before a given form element.
366
 *
367
 * @param array $form
368
 *   the form to add the CAPTCHA element to.
369
 *
370
 * @param array $placement
371
 *   information where the CAPTCHA element should be inserted.
372
 *   $placement should be an associative array with fields:
373
 *     - 'path': path (array of path items) of the container in the form where the
374
 *       CAPTCHA element should be inserted.
375
 *     - 'key': the key of the element before which the CAPTCHA element
376
 *       should be inserted. If the field 'key' is undefined or NULL, the CAPTCHA will
377
 *       just be appended in the container.
378
 *     - 'weight': if 'key' is not NULL: should be the weight of the element defined by 'key'.
379
 *       If 'key' is NULL and weight is not NULL: set the weight property of the CAPTCHA element
380
 *       to this value.
381
 *
382
 * @param array $captcha_element
383
 *   the CAPTCHA element to insert.
384
 */
385
function _captcha_insert_captcha_element(&$form, $placement, $captcha_element) {
386
  // Get path, target and target weight or use defaults if not available.
387
  $target_key = isset($placement['key']) ? $placement['key'] : NULL;
388
  $target_weight = isset($placement['weight']) ? $placement['weight'] : NULL;
389
  $path = isset($placement['path']) ? $placement['path'] : array();
390

    
391
  // Walk through the form along the path.
392
  $form_stepper = &$form;
393
  foreach ($path as $step) {
394
    if (isset($form_stepper[$step])) {
395
      $form_stepper = & $form_stepper[$step];
396
    }
397
    else {
398
      // Given path is invalid: stop stepping and
399
      // continue in best effort (append instead of insert).
400
      $target_key = NULL;
401
      break;
402
    }
403
  }
404

    
405
  // If no target is available: just append the CAPTCHA element to the container.
406
  if ($target_key == NULL || !array_key_exists($target_key, $form_stepper)) {
407
    // Optionally, set weight of CAPTCHA element.
408
    if ($target_weight != NULL) {
409
      $captcha_element['#weight'] = $target_weight;
410
    }
411
    $form_stepper['captcha'] = $captcha_element;
412
  }
413
  // If there is a target available: make sure the CAPTCHA element comes right before it.
414
  else {
415
    // If target has a weight: set weight of CAPTCHA element a bit smaller
416
    // and just append the CAPTCHA: sorting will fix the ordering anyway.
417
    if ($target_weight != NULL) {
418
      $captcha_element['#weight'] = $target_weight - .1;
419
      $form_stepper['captcha'] = $captcha_element;
420
    }
421
    else {
422
      // If we can't play with weights: insert the CAPTCHA element at the right position.
423
      // Because PHP lacks a function for this (array_splice() comes close,
424
      // but it does not preserve the key of the inserted element), we do it by hand:
425
      // chop of the end, append the CAPTCHA element and put the end back.
426
      $offset = array_search($target_key, array_keys($form_stepper));
427
      $end = array_splice($form_stepper, $offset);
428
      $form_stepper['captcha'] = $captcha_element;
429
      foreach ($end as $k => $v) {
430
        $form_stepper[$k] = $v;
431
      }
432
    }
433
  }
434
}