source: sipes/modules_contrib/captcha/captcha.inc @ 1e95969

stableversion-3.0
Last change on this file since 1e95969 was 177a560, checked in by José Gregorio Puentes <jpuentes@…>, 8 años ago

se agrego el directorio de modulos contribuidos de drupal

  • Propiedad mode establecida a 100755
File size: 15.0 KB
Línea 
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 */
20function captcha_set_form_id_setting($form_id, $captcha_type) {
21  if ($captcha_type == 'none') {
22    db_query("DELETE FROM {captcha_points} WHERE form_id = '%s'", $form_id);
23    db_query("INSERT INTO {captcha_points} (form_id, module, captcha_type) VALUES ('%s', NULL, NULL)", $form_id);
24  }
25  elseif ($captcha_type == 'default') {
26    db_query("DELETE FROM {captcha_points} WHERE form_id = '%s'", $form_id);
27    db_query("INSERT INTO {captcha_points} (form_id, module, captcha_type) VALUES ('%s', NULL, '%s')", $form_id, 'default');
28  }
29  elseif ($captcha_type == NULL) {
30    db_query("DELETE FROM {captcha_points} WHERE form_id = '%s'", $form_id);
31  }
32  elseif (is_object($captcha_type) && isset($captcha_type->module) && isset($captcha_type->captcha_type)) {
33    db_query("DELETE FROM {captcha_points} WHERE form_id = '%s'", $form_id);
34    db_query("INSERT INTO {captcha_points} (form_id, module, captcha_type) VALUES ('%s', '%s', '%s')", $form_id, $captcha_type->module, $captcha_type->captcha_type);
35  }
36  elseif (is_string($captcha_type) && substr_count($captcha_type, '/') == 1) {
37    list($module, $type) = explode('/', $captcha_type);
38    db_query("DELETE FROM {captcha_points} WHERE form_id = '%s'", $form_id);
39    db_query("INSERT INTO {captcha_points} (form_id, module, captcha_type) VALUES ('%s', '%s', '%s')", $form_id, $module, $type);
40  }
41  else {
42    drupal_set_message(t('Failed to set a CAPTCHA type for form %form_id: could not interpret value "@captcha_type"',
43      array('%form_id' => $form_id, '@captcha_type' => (string)$captcha_type)), 'warning');
44  }
45}
46
47/**
48 * Get the CAPTCHA setting for a given form_id.
49 *
50 * @param $form_id the form_id to query for
51 * @param $symbolic flag to return as (symbolic) strings instead of object.
52 *
53 * @return NULL if no setting is known
54 *   or a captcha_point object with fields 'module' and 'captcha_type'.
55 *   If argument $symbolic is true, returns (symbolic) as 'none', 'default'
56 *   or in the form 'captcha/Math'.
57 */
58function captcha_get_form_id_setting($form_id, $symbolic=FALSE) {
59  if (module_exists('ctools')) {
60    ctools_include('export');
61    $captcha_point = array_pop(ctools_export_load_object('captcha_points', 'names', array($form_id)));
62  }
63  else {
64    $result = db_query("SELECT module, captcha_type FROM {captcha_points} WHERE form_id = '%s'", $form_id);
65    if (!$result) {
66      return NULL;
67    }
68    $captcha_point = db_fetch_object($result);
69  }
70
71  if (!$captcha_point) {
72    $captcha_point = NULL;
73  }
74  elseif ($captcha_point->captcha_type == 'default') {
75    if (!$symbolic) {
76      list($module, $type) = explode('/', variable_get('captcha_default_challenge', 'captcha/Math'));
77      $captcha_point->module = $module;
78      $captcha_point->captcha_type = $type;
79    }
80    else {
81      $captcha_point = 'default';
82    }
83  }
84  elseif ($captcha_point->module == NULL && $captcha_point->captcha_type == NULL && $symbolic) {
85    $captcha_point = 'none';
86  }
87  elseif ($symbolic) {
88    $captcha_point = $captcha_point->module .'/'. $captcha_point->captcha_type;
89  }
90  return $captcha_point;
91}
92
93/**
94 * Helper function to load all captcha points.
95 *
96 * @return array of all captcha_points
97 */
98function captcha_get_captcha_points() {
99  if (module_exists('ctools')) {
100    ctools_include('export');
101    $captcha_points = ctools_export_load_object('captcha_points', 'all');
102    ksort($captcha_points);
103  }
104  else {
105    $captcha_points = array();
106    $result = db_query("SELECT * FROM {captcha_points} ORDER BY form_id");
107    while ($captcha_point = db_fetch_object($result)) {
108      $captcha_points[] = $captcha_point;
109    }
110  }
111  return $captcha_points;
112}
113
114/**
115 * Helper function for generating a new CAPTCHA session.
116 *
117 * @param $form_id the form_id of the form to add a CAPTCHA to.
118 * @param $status the initial status of the CAPTHCA session.
119 * @return the session ID of the new CAPTCHA session.
120 */
121function _captcha_generate_captcha_session($form_id=NULL, $status=CAPTCHA_STATUS_UNSOLVED) {
122  global $user;
123  // Initialize solution with random data.
124  $solution = md5(mt_rand());
125  db_query("INSERT into {captcha_sessions} (uid, sid, ip_address, timestamp, form_id, solution, status, attempts) VALUES (%d, '%s', '%s', %d, '%s', '%s', %d, %d)", $user->uid, session_id(), ip_address(), time(), $form_id, $solution, $status, 0);
126  $captcha_sid = db_last_insert_id('captcha_sessions', 'csid');
127  return $captcha_sid;
128}
129
130/**
131 * Helper function for updating the solution in the CAPTCHA session table.
132 *
133 * @param $captcha_sid the CAPTCHA session ID to update.
134 * @param $solution the new solution to associate with the given CAPTCHA session.
135 */
136function _captcha_update_captcha_session($captcha_sid, $solution) {
137  db_query("UPDATE {captcha_sessions} SET timestamp=%d, solution='%s' WHERE csid=%d", time(), $solution, $captcha_sid);
138}
139
140/**
141 * Helper function for checking if CAPTCHA is required for user,
142 * based on the CAPTCHA persistence setting, the CAPTCHA session ID and
143 * user session info.
144 */
145function _captcha_required_for_user($captcha_sid, $form_id) {
146  // Get the CAPTCHA persistence setting.
147  $captcha_persistence = variable_get('captcha_persistence', CAPTCHA_PERSISTENCE_SKIP_ONCE_SUCCESSFUL_PER_FORM_INSTANCE);
148
149  // First check: should we always add a CAPTCHA?
150  if ($captcha_persistence == CAPTCHA_PERSISTENCE_SHOW_ALWAYS) {
151    return TRUE;
152  }
153
154  // Get the status of the current CAPTCHA session.
155  $captcha_session_status = db_result(db_query("SELECT status FROM {captcha_sessions} WHERE csid = %d", $captcha_sid));
156  // Second check: if the current session is already solved: omit further CAPTCHAs.
157  if ($captcha_session_status == CAPTCHA_STATUS_SOLVED) {
158    return FALSE;
159  }
160
161  // Third check: look at the persistence level (per form instance, per form or per user).
162  if ($captcha_persistence == CAPTCHA_PERSISTENCE_SKIP_ONCE_SUCCESSFUL_PER_FORM_INSTANCE) {
163    return TRUE;
164  }
165  else {
166    $captcha_success_form_ids = isset($_SESSION['captcha_success_form_ids']) ? (array)($_SESSION['captcha_success_form_ids']) : array();
167    switch ($captcha_persistence) {
168      case CAPTCHA_PERSISTENCE_SKIP_ONCE_SUCCESSFUL:
169        return (count($captcha_success_form_ids) == 0);
170      case CAPTCHA_PERSISTENCE_SKIP_ONCE_SUCCESSFUL_PER_FORM_TYPE:
171        return !isset($captcha_success_form_ids[$form_id]);
172    }
173  }
174
175  // We should never get to this point, but to be sure, we return TRUE.
176  return TRUE;
177}
178
179/**
180 * Get the CAPTCHA description as configured on the general CAPTCHA
181 * settings page.
182 *
183 * If the locale module is enabled, the description will be returned
184 * for the current language the page is rendered for. This language
185 * can optionally been overriden with the $lang_code argument.
186 *
187 * @param $lang_code an optional language code to get the descripion for.
188 * @return a string with (localized) CAPTCHA description.
189 */
190function _captcha_get_description($lang_code=NULL) {
191  // If no language code is given: use the language of the current page.
192  global $language;
193  $lang_code = isset($lang_code) ? $lang_code : $language->language;
194  // The hardcoded but localizable default.
195  $default = t('This question is for testing whether you are a human visitor and to prevent automated spam submissions.', array(), $lang_code);
196  // Look up the configured CAPTCHA description or fall back on the (localized) default.
197  if (module_exists('locale')) {
198    $description = variable_get("captcha_description_$lang_code", $default);
199  }
200  else {
201    $description = variable_get('captcha_description', $default);
202  }
203  return filter_xss_admin($description);
204}
205
206/**
207 * Parse or interpret the given captcha_type.
208 * @param $captcha_type string representation of the CAPTCHA type,
209 *      e.g. 'default', 'none', 'captcha/Math', 'image_captcha/Image'
210 * @return list($captcha_module, $captcha_type)
211 */
212function _captcha_parse_captcha_type($captcha_type) {
213  if ($captcha_type == 'none') {
214    return array(NULL, NULL);
215  }
216  if ($captcha_type == 'default') {
217    $captcha_type = variable_get('captcha_default_challenge', 'captcha/Math');
218  }
219  return explode('/', $captcha_type);
220}
221
222/**
223 * Helper function to get placement information for a given form_id.
224 * @param $form_id the form_id to get the placement information for.
225 * @param $form if a form corresponding to the given form_id, if there
226 *   is no placement info for the given form_id, this form is examined to
227 *   guess the placement.
228 * @return placement info array (@see _captcha_insert_captcha_element() for more
229 *   info about the fields 'path', 'key' and 'weight'.
230 */
231function _captcha_get_captcha_placement($form_id, $form) {
232  // Get CAPTCHA placement map from cache. Two levels of cache:
233  // static variable in this function and storage in the variables table.
234  static $placement_map = NULL;
235  // Try first level cache.
236  if ($placement_map === NULL) {
237    // If first level cache missed: try second level cache.
238    $placement_map = variable_get('captcha_placement_map_cache', NULL);
239
240    if ($placement_map === NULL) {
241      // If second level cache missed: start from a fresh placement map.
242      $placement_map = array();
243      // Prefill with some hard coded default entries.
244
245      // The comment form can have a 'Preview' button, or both a 'Submit' and 'Preview' button,
246      // which is tricky for automatic placement detection. Luckily, Drupal core sets their
247      // weight (19 and 20), so we just have to specify a slightly smaller weight.
248      $placement_map['comment_form'] = array('path' => array(), 'key' => NULL, 'weight' => 18.9);
249      // Additional note: the node forms also have the posibility to only show a 'Preview' button.
250      // However, the 'Submit' button is always present, but is just not rendered ('#access' = FALSE)
251      // in those cases. The the automatic button detection should be sufficient for node forms.
252
253      // $placement_map['user_login'] = array('path' => array(), 'key' => NULL, 'weight' => 1.9);
254      // TODO: also make the placement 'overridable' from the admin UI?
255    }
256  }
257
258  // Query the placement map.
259  if (array_key_exists($form_id, $placement_map)) {
260    $placement = $placement_map[$form_id];
261  }
262  // If no placement info is available in placement map:
263  // search the form for buttons and guess placement from it.
264  else {
265    $buttons = _captcha_search_buttons($form);
266    if (count($buttons)) {
267      // Pick first button.
268      // TODO: make this more sophisticated? Use cases needed.
269      $placement = $buttons[0];
270    }
271    else {
272      // Use NULL when no buttons were found.
273      $placement = NULL;
274    }
275
276    // Store calculated placement in caches.
277    $placement_map[$form_id] = $placement;
278    variable_set('captcha_placement_map_cache', $placement_map);
279  }
280
281  return $placement;
282}
283
284/**
285 * Helper function for searching the buttons in a form.
286 *
287 * @param $form the form to search button elements in
288 * @return an array of paths to the buttons.
289 *   A path is an array of keys leading to the button, the last
290 *   item in the path is the weight of the button element
291 *   (or NULL if undefined).
292 */
293function _captcha_search_buttons($form) {
294  $buttons = array();
295  foreach (element_children($form) as $key) {
296    // Look for submit or button type elements.
297    if (isset($form[$key]['#type']) && ($form[$key]['#type'] == 'submit' || $form[$key]['#type'] == 'button')) {
298      $weight = isset($form[$key]['#weight']) ? $form[$key]['#weight'] : NULL;
299      $buttons[] = array(
300        'path' => array(),
301        'key' => $key,
302        'weight' => $weight,
303      );
304    }
305    // Process children recurively.
306    $children_buttons = _captcha_search_buttons($form[$key]);
307    foreach ($children_buttons as $b) {
308      $b['path'] = array_merge(array($key), $b['path']);
309      $buttons[] = $b;
310    }
311  }
312  return $buttons;
313}
314
315/**
316 * Helper function to insert a CAPTCHA element in a form before a given form element.
317 * @param $form the form to add the CAPTCHA element to.
318 * @param $placement information where the CAPTCHA element should be inserted.
319 *   $placement should be an associative array with fields:
320 *     - 'path': path (array of path items) of the container in the form where the
321 *       CAPTCHA element should be inserted.
322 *     - 'key': the key of the element before which the CAPTCHA element
323 *       should be inserted. If the field 'key' is undefined or NULL, the CAPTCHA will
324 *       just be appended to the container.
325 *     - 'weight': if 'key' is not NULL: should be the weight of the element defined by 'key'.
326 *       If 'key' is NULL and weight is not NULL: set the weight property of the CAPTCHA element
327 *       to this value.
328 * @param $captcha_element the CAPTCHA element to insert.
329 */
330function _captcha_insert_captcha_element(&$form, $placement, $captcha_element) {
331  // Get path, target and target weight or use defaults if not available.
332  $target_key = isset($placement['key']) ? $placement['key'] : NULL;
333  $target_weight = isset($placement['weight']) ? $placement['weight'] : NULL;
334  $path = isset($placement['path']) ? $placement['path'] : array();
335
336  // Walk through the form along the path.
337  $form_stepper = &$form;
338  foreach ($path as $step) {
339    if (isset($form_stepper[$step])) {
340      $form_stepper = & $form_stepper[$step];
341    }
342    else {
343      // Given path is invalid: stop stepping and
344      // continue in best effort (append instead of insert).
345      $target_key = NULL;
346      break;
347    }
348  }
349
350  // If no target is available: just append the CAPTCHA element to the container.
351  if ($target_key == NULL || !array_key_exists($target_key, $form_stepper)) {
352    // Optionally, set weight of CAPTCHA element.
353    if ($target_weight != NULL) {
354      $captcha_element['#weight'] = $target_weight;
355    }
356    $form_stepper['captcha'] =  $captcha_element;
357  }
358  // If there is a target available: make sure the CAPTCHA element comes right before it.
359  else {
360    // If target has a weight: set weight of CAPTCHA element a bit smaller
361    // and just append the CAPTCHA: sorting will fix the ordering anyway.
362    if ($target_weight != NULL) {
363      $captcha_element['#weight'] = $target_weight - .1;
364      $form_stepper['captcha'] =  $captcha_element;
365    }
366    else {
367      // If we can't play with weights: insert the CAPTCHA element at the right position.
368      // Because PHP lacks a function for this (array_splice() comes close,
369      // but it does not preserve the key of the inserted element), we do it by hand:
370      // chop of the end, append the CAPTCHA element and put the end back.
371      $offset = array_search($target_key, array_keys($form_stepper));
372      $end = array_splice($form_stepper, $offset);
373      $form_stepper['captcha'] =  $captcha_element;
374      foreach($end as $k => $v) {
375        $form_stepper[$k] = $v;
376      }
377    }
378  }
379}
Nota: Vea TracBrowser para ayuda de uso del navegador del repositorio.