source: sipes/modules_contrib/captcha/captcha.inc @ ef72343

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

se actualizo el modulo

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