Projet

Général

Profil

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

root / drupal7 / sites / all / modules / captcha / captcha.inc @ 66b5cbf6

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

    
60
/**
61
 * Get the CAPTCHA setting for a given form_id.
62
 *
63
 * @param $form_id the form_id to query for
64
 * @param $symbolic flag to return as (symbolic) strings instead of object.
65
 *
66
 * @return NULL if no setting is known
67
 *   or a captcha_point object with fields 'module' and 'captcha_type'.
68
 *   If argument $symbolic is true, returns (symbolic) as 'none', 'default'
69
 *   or in the form 'captcha/Math'.
70
 */
71
function captcha_get_form_id_setting($form_id, $symbolic=FALSE) {
72
  // Fetch setting from database.
73
  $result = db_query("SELECT module, captcha_type FROM {captcha_points} WHERE form_id = :form_id",
74
    array(':form_id' =>  $form_id));
75
  $captcha_point = $result->fetchObject();
76

    
77
  // If no setting is available in database for the given form,
78
  // but 'captcha_default_challenge_on_nonlisted_forms' is enabled, pick the default type anyway
79
  if (!$captcha_point && variable_get('captcha_default_challenge_on_nonlisted_forms', FALSE))
80
  {
81
    $captcha_point = (object) array('captcha_type' => 'default');
82
  }
83

    
84
  // Handle (default) settings and symbolic mode.
85
  if (!$captcha_point) {
86
    $captcha_point = NULL;
87
  }
88
  elseif ($captcha_point->captcha_type == 'default') {
89
    if (!$symbolic) {
90
      list($module, $type) = explode('/', variable_get('captcha_default_challenge', 'captcha/Math'));
91
      $captcha_point->module = $module;
92
      $captcha_point->captcha_type = $type;
93
    }
94
    else {
95
      $captcha_point = 'default';
96
    }
97
  }
98
  elseif ($captcha_point->module == NULL && $captcha_point->captcha_type == NULL && $symbolic) {
99
    $captcha_point = 'none';
100
  }
101
  elseif ($symbolic) {
102
    $captcha_point = $captcha_point->module . '/' . $captcha_point->captcha_type;
103
  }
104
  return $captcha_point;
105
}
106

    
107

    
108
/**
109
 * Helper function for generating a new CAPTCHA session.
110
 *
111
 * @param $form_id the form_id of the form to add a CAPTCHA to.
112
 * @param $status the initial status of the CAPTHCA session.
113
 * @return the session ID of the new CAPTCHA session.
114
 */
115
function _captcha_generate_captcha_session($form_id=NULL, $status=CAPTCHA_STATUS_UNSOLVED) {
116
  global $user;
117
  // Initialize solution with random data.
118
  $solution = md5(mt_rand());
119
  // Insert an entry and thankfully receive the value of the autoincrement field 'csid'.
120
  $captcha_sid = db_insert('captcha_sessions')
121
  ->fields(array(
122
    'uid' => $user->uid,
123
    'sid' => session_id(),
124
    'ip_address' => ip_address(),
125
    'timestamp' => REQUEST_TIME,
126
    'form_id' => $form_id,
127
    'solution' => $solution,
128
    'status' => $status,
129
    'attempts' => 0,
130
  ))
131
  ->execute();
132
  return $captcha_sid;
133
}
134

    
135
/**
136
 * Helper function for updating the solution in the CAPTCHA session table.
137
 *
138
 * @param $captcha_sid the CAPTCHA session ID to update.
139
 * @param $solution the new solution to associate with the given CAPTCHA session.
140
 */
141
function _captcha_update_captcha_session($captcha_sid, $solution) {
142
  db_update('captcha_sessions')
143
    ->condition('csid', $captcha_sid)
144
    ->fields(array(
145
      'timestamp' => REQUEST_TIME,
146
      'solution' => $solution,
147
    ))
148
    ->execute();
149
}
150

    
151
/**
152
 * Helper function for checking if CAPTCHA is required for user,
153
 * based on the CAPTCHA persistence setting, the CAPTCHA session ID and
154
 * user session info.
155
 */
156
function _captcha_required_for_user($captcha_sid, $form_id) {
157
  // Get the CAPTCHA persistence setting.
158
  $captcha_persistence = variable_get('captcha_persistence', CAPTCHA_PERSISTENCE_SKIP_ONCE_SUCCESSFUL_PER_FORM_INSTANCE);
159

    
160
  // First check: should we always add a CAPTCHA?
161
  if ($captcha_persistence == CAPTCHA_PERSISTENCE_SHOW_ALWAYS) {
162
    return TRUE;
163
  }
164

    
165
  // Get the status of the current CAPTCHA session.
166
  $captcha_session_status = db_query('SELECT status FROM {captcha_sessions} WHERE csid = :csid', array(':csid' => $captcha_sid))->fetchField();
167
  // Second check: if the current session is already solved: omit further CAPTCHAs.
168
  if ($captcha_session_status == CAPTCHA_STATUS_SOLVED) {
169
    return FALSE;
170
  }
171

    
172
  // Third check: look at the persistence level (per form instance, per form or per user).
173
  if ($captcha_persistence == CAPTCHA_PERSISTENCE_SKIP_ONCE_SUCCESSFUL_PER_FORM_INSTANCE) {
174
    return TRUE;
175
  }
176
  else {
177
    $captcha_success_form_ids = isset($_SESSION['captcha_success_form_ids']) ? (array)($_SESSION['captcha_success_form_ids']) : array();
178
    switch ($captcha_persistence) {
179
      case CAPTCHA_PERSISTENCE_SKIP_ONCE_SUCCESSFUL:
180
        return (count($captcha_success_form_ids) == 0);
181
      case CAPTCHA_PERSISTENCE_SKIP_ONCE_SUCCESSFUL_PER_FORM_TYPE:
182
        return !isset($captcha_success_form_ids[$form_id]);
183
    }
184
  }
185

    
186
  // We should never get to this point, but to be sure, we return TRUE.
187
  return TRUE;
188
}
189

    
190

    
191
/**
192
 * Get the CAPTCHA description as configured on the general CAPTCHA
193
 * settings page.
194
 *
195
 * If the locale module is enabled, the description will be returned
196
 * for the current language the page is rendered for. This language
197
 * can optionally been overriden with the $lang_code argument.
198
 *
199
 * @param $lang_code an optional language code to get the descripion for.
200
 * @return a string with (localized) CAPTCHA description.
201
 */
202
function _captcha_get_description($lang_code=NULL) {
203
  // If no language code is given: use the language of the current page.
204
  global $language;
205
  $lang_code = isset($lang_code) ? $lang_code : $language->language;
206
  // The hardcoded but localizable default.
207
  $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));
208
  // Look up the configured CAPTCHA description or fall back on the (localized) default.
209
  if (module_exists('locale')) {
210
    $description = variable_get("captcha_description_$lang_code", $default);
211
  }
212
  else {
213
    $description = variable_get('captcha_description', $default);
214
  }
215
  return filter_xss_admin($description);
216
}
217

    
218
/**
219
 * Parse or interpret the given captcha_type.
220
 * @param $captcha_type string representation of the CAPTCHA type,
221
 *      e.g. 'default', 'none', 'captcha/Math', 'image_captcha/Image'
222
 * @return list($captcha_module, $captcha_type)
223
 */
224
function _captcha_parse_captcha_type($captcha_type) {
225
  if ($captcha_type == 'none') {
226
    return array(NULL, NULL);
227
  }
228
  if ($captcha_type == 'default') {
229
    $captcha_type = variable_get('captcha_default_challenge', 'captcha/Math');
230
  }
231
  return explode('/', $captcha_type);
232
}
233

    
234
/**
235
 * Helper function to get placement information for a given form_id.
236
 * @param $form_id the form_id to get the placement information for.
237
 * @param $form if a form corresponding to the given form_id, if there
238
 *   is no placement info for the given form_id, this form is examined to
239
 *   guess the placement.
240
 * @return placement info array (@see _captcha_insert_captcha_element() for more
241
 *   info about the fields 'path', 'key' and 'weight'.
242
 */
243
function _captcha_get_captcha_placement($form_id, $form) {
244
  // Get CAPTCHA placement map from cache. Two levels of cache:
245
  // static variable in this function and storage in the variables table.
246
  static $placement_map = NULL;
247
  // Try first level cache.
248
  if ($placement_map === NULL) {
249
    // If first level cache missed: try second level cache.
250
    $placement_map = variable_get('captcha_placement_map_cache', NULL);
251

    
252
    if ($placement_map === NULL) {
253
      // If second level cache missed: initialize the placement map
254
      // and let other modules hook into this with the hook_captcha_placement_map hook.
255
      // By default however, probably all Drupal core forms are already correctly
256
      // handled with the best effort guess based on the 'actions' element (see below).
257
      $placement_map = module_invoke_all('captcha_placement_map');
258
    }
259
  }
260

    
261
  // Query the placement map.
262
  if (array_key_exists($form_id, $placement_map)) {
263
    $placement = $placement_map[$form_id];
264
  }
265
  // If no placement info is available in placement map: make a best effort guess.
266
  else {
267
    // If there is an "actions" button group, a good placement is just before that.
268
    if (isset($form['actions']) && isset($form['actions']['#type']) && $form['actions']['#type'] === 'actions') {
269
      $placement = array(
270
        'path' => array(),
271
        'key' => 'actions',
272
        // #type 'actions' defaults to 100.
273
        'weight' => (isset($form['actions']['#weight']) ? $form['actions']['#weight'] - 1 : 99),
274
      );
275
    }
276
    else {
277
      // Search the form for buttons and guess placement from it.
278
      $buttons = _captcha_search_buttons($form);
279
      if (count($buttons)) {
280
        // Pick first button.
281
        // TODO: make this more sofisticated? Use cases needed.
282
        $placement = $buttons[0];
283
      }
284
      else {
285
        // Use NULL when no buttons were found.
286
        $placement = NULL;
287
      }
288
    }
289

    
290
    // Store calculated placement in cache.
291
    $placement_map[$form_id] = $placement;
292
    variable_set('captcha_placement_map_cache', $placement_map);
293
  }
294

    
295
  return $placement;
296
}
297

    
298
/**
299
 * Helper function for searching the buttons in a form.
300
 *
301
 * @param $form the form to search button elements in
302
 * @return an array of paths to the buttons.
303
 *   A path is an array of keys leading to the button, the last
304
 *   item in the path is the weight of the button element
305
 *   (or NULL if undefined).
306
 */
307
function _captcha_search_buttons($form) {
308
  $buttons = array();
309
  foreach (element_children($form) as $key) {
310
    // Look for submit or button type elements.
311
    if (isset($form[$key]['#type']) && ($form[$key]['#type'] == 'submit' || $form[$key]['#type'] == 'button')) {
312
      $weight = isset($form[$key]['#weight']) ? $form[$key]['#weight'] : NULL;
313
      $buttons[] = array(
314
        'path' => array(),
315
        'key' => $key,
316
        'weight' => $weight,
317
      );
318
    }
319
    // Process children recurively.
320
    $children_buttons = _captcha_search_buttons($form[$key]);
321
    foreach ($children_buttons as $b) {
322
      $b['path'] = array_merge(array($key), $b['path']);
323
      $buttons[] = $b;
324
    }
325
  }
326
  return $buttons;
327
}
328

    
329
/**
330
 * Helper function to insert a CAPTCHA element in a form before a given form element.
331
 * @param $form the form to add the CAPTCHA element to.
332
 * @param $placement information where the CAPTCHA element should be inserted.
333
 *   $placement should be an associative array with fields:
334
 *     - 'path': path (array of path items) of the container in the form where the
335
 *       CAPTCHA element should be inserted.
336
 *     - 'key': the key of the element before which the CAPTCHA element
337
 *       should be inserted. If the field 'key' is undefined or NULL, the CAPTCHA will
338
 *       just be appended in the container.
339
 *     - 'weight': if 'key' is not NULL: should be the weight of the element defined by 'key'.
340
 *       If 'key' is NULL and weight is not NULL: set the weight property of the CAPTCHA element
341
 *       to this value.
342
 * @param $captcha_element the CAPTCHA element to insert.
343
 */
344
function _captcha_insert_captcha_element(&$form, $placement, $captcha_element) {
345
  // Get path, target and target weight or use defaults if not available.
346
  $target_key = isset($placement['key']) ? $placement['key'] : NULL;
347
  $target_weight = isset($placement['weight']) ? $placement['weight'] : NULL;
348
  $path = isset($placement['path']) ? $placement['path'] : array();
349

    
350
  // Walk through the form along the path.
351
  $form_stepper = &$form;
352
  foreach ($path as $step) {
353
    if (isset($form_stepper[$step])) {
354
      $form_stepper = & $form_stepper[$step];
355
    }
356
    else {
357
      // Given path is invalid: stop stepping and
358
      // continue in best effort (append instead of insert).
359
      $target_key = NULL;
360
      break;
361
    }
362
  }
363

    
364
  // If no target is available: just append the CAPTCHA element to the container.
365
  if ($target_key == NULL || !array_key_exists($target_key, $form_stepper)) {
366
    // Optionally, set weight of CAPTCHA element.
367
    if ($target_weight != NULL) {
368
      $captcha_element['#weight'] = $target_weight;
369
    }
370
    $form_stepper['captcha'] =  $captcha_element;
371
  }
372
  // If there is a target available: make sure the CAPTCHA element comes right before it.
373
  else {
374
    // If target has a weight: set weight of CAPTCHA element a bit smaller
375
    // and just append the CAPTCHA: sorting will fix the ordering anyway.
376
    if ($target_weight != NULL) {
377
      $captcha_element['#weight'] = $target_weight - .1;
378
      $form_stepper['captcha'] =  $captcha_element;
379
    }
380
    else {
381
      // If we can't play with weights: insert the CAPTCHA element at the right position.
382
      // Because PHP lacks a function for this (array_splice() comes close,
383
      // but it does not preserve the key of the inserted element), we do it by hand:
384
      // chop of the end, append the CAPTCHA element and put the end back.
385
      $offset = array_search($target_key, array_keys($form_stepper));
386
      $end = array_splice($form_stepper, $offset);
387
      $form_stepper['captcha'] =  $captcha_element;
388
      foreach ($end as $k => $v) {
389
        $form_stepper[$k] = $v;
390
      }
391
    }
392
  }
393
}
394