comparison sites/all/modules/captcha/captcha.inc @ 2:b74b41bb73f0

-- Google analytics module
author danieleb <danielebarchiesi@me.com>
date Thu, 22 Aug 2013 17:22:54 +0100
parents
children
comparison
equal deleted inserted replaced
1:67ce89da90df 2:b74b41bb73f0
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 $result = db_query("SELECT module, captcha_type FROM {captcha_points} WHERE form_id = :form_id",
73 array(':form_id' => $form_id));
74 $captcha_point = $result->fetchObject();
75 if (!$captcha_point) {
76 $captcha_point = NULL;
77 }
78 elseif ($captcha_point->captcha_type == 'default') {
79 if (!$symbolic) {
80 list($module, $type) = explode('/', variable_get('captcha_default_challenge', 'captcha/Math'));
81 $captcha_point->module = $module;
82 $captcha_point->captcha_type = $type;
83 }
84 else {
85 $captcha_point = 'default';
86 }
87 }
88 elseif ($captcha_point->module == NULL && $captcha_point->captcha_type == NULL && $symbolic) {
89 $captcha_point = 'none';
90 }
91 elseif ($symbolic) {
92 $captcha_point = $captcha_point->module . '/' . $captcha_point->captcha_type;
93 }
94 return $captcha_point;
95 }
96
97
98 /**
99 * Helper function for generating a new CAPTCHA session.
100 *
101 * @param $form_id the form_id of the form to add a CAPTCHA to.
102 * @param $status the initial status of the CAPTHCA session.
103 * @return the session ID of the new CAPTCHA session.
104 */
105 function _captcha_generate_captcha_session($form_id=NULL, $status=CAPTCHA_STATUS_UNSOLVED) {
106 global $user;
107 // Initialize solution with random data.
108 $solution = md5(mt_rand());
109 // Insert an entry and thankfully receive the value of the autoincrement field 'csid'.
110 $captcha_sid = db_insert('captcha_sessions')
111 ->fields(array(
112 'uid' => $user->uid,
113 'sid' => session_id(),
114 'ip_address' => ip_address(),
115 'timestamp' => REQUEST_TIME,
116 'form_id' => $form_id,
117 'solution' => $solution,
118 'status' => $status,
119 'attempts' => 0,
120 ))
121 ->execute();
122 return $captcha_sid;
123 }
124
125 /**
126 * Helper function for updating the solution in the CAPTCHA session table.
127 *
128 * @param $captcha_sid the CAPTCHA session ID to update.
129 * @param $solution the new solution to associate with the given CAPTCHA session.
130 */
131 function _captcha_update_captcha_session($captcha_sid, $solution) {
132 db_update('captcha_sessions')
133 ->condition('csid', $captcha_sid)
134 ->fields(array(
135 'timestamp' => REQUEST_TIME,
136 'solution' => $solution,
137 ))
138 ->execute();
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 */
146 function _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_query('SELECT status FROM {captcha_sessions} WHERE csid = :csid', array(':csid' => $captcha_sid))->fetchField();
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 /**
182 * Get the CAPTCHA description as configured on the general CAPTCHA
183 * settings page.
184 *
185 * If the locale module is enabled, the description will be returned
186 * for the current language the page is rendered for. This language
187 * can optionally been overriden with the $lang_code argument.
188 *
189 * @param $lang_code an optional language code to get the descripion for.
190 * @return a string with (localized) CAPTCHA description.
191 */
192 function _captcha_get_description($lang_code=NULL) {
193 // If no language code is given: use the language of the current page.
194 global $language;
195 $lang_code = isset($lang_code) ? $lang_code : $language->language;
196 // The hardcoded but localizable default.
197 $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));
198 // Look up the configured CAPTCHA description or fall back on the (localized) default.
199 if (module_exists('locale')) {
200 $description = variable_get("captcha_description_$lang_code", $default);
201 }
202 else {
203 $description = variable_get('captcha_description', $default);
204 }
205 return filter_xss_admin($description);
206 }
207
208 /**
209 * Parse or interpret the given captcha_type.
210 * @param $captcha_type string representation of the CAPTCHA type,
211 * e.g. 'default', 'none', 'captcha/Math', 'image_captcha/Image'
212 * @return list($captcha_module, $captcha_type)
213 */
214 function _captcha_parse_captcha_type($captcha_type) {
215 if ($captcha_type == 'none') {
216 return array(NULL, NULL);
217 }
218 if ($captcha_type == 'default') {
219 $captcha_type = variable_get('captcha_default_challenge', 'captcha/Math');
220 }
221 return explode('/', $captcha_type);
222 }
223
224 /**
225 * Helper function to get placement information for a given form_id.
226 * @param $form_id the form_id to get the placement information for.
227 * @param $form if a form corresponding to the given form_id, if there
228 * is no placement info for the given form_id, this form is examined to
229 * guess the placement.
230 * @return placement info array (@see _captcha_insert_captcha_element() for more
231 * info about the fields 'path', 'key' and 'weight'.
232 */
233 function _captcha_get_captcha_placement($form_id, $form) {
234 // Get CAPTCHA placement map from cache. Two levels of cache:
235 // static variable in this function and storage in the variables table.
236 static $placement_map = NULL;
237 // Try first level cache.
238 if ($placement_map === NULL) {
239 // If first level cache missed: try second level cache.
240 $placement_map = variable_get('captcha_placement_map_cache', NULL);
241
242 if ($placement_map === NULL) {
243 // If second level cache missed: initialize the placement map
244 // and let other modules hook into this with the hook_captcha_placement_map hook.
245 // By default however, probably all Drupal core forms are already correctly
246 // handled with the best effort guess based on the 'actions' element (see below).
247 $placement_map = module_invoke_all('captcha_placement_map');
248 }
249 }
250
251 // Query the placement map.
252 if (array_key_exists($form_id, $placement_map)) {
253 $placement = $placement_map[$form_id];
254 }
255 // If no placement info is available in placement map: make a best effort guess.
256 else {
257 // If there is an "actions" button group, a good placement is just before that.
258 if (isset($form['actions']) && isset($form['actions']['#type']) && $form['actions']['#type'] === 'actions') {
259 $placement = array(
260 'path' => array(),
261 'key' => 'actions',
262 // #type 'actions' defaults to 100.
263 'weight' => (isset($form['actions']['#weight']) ? $form['actions']['#weight'] - 1 : 99),
264 );
265 }
266 else {
267 // Search the form for buttons and guess placement from it.
268 $buttons = _captcha_search_buttons($form);
269 if (count($buttons)) {
270 // Pick first button.
271 // TODO: make this more sofisticated? Use cases needed.
272 $placement = $buttons[0];
273 }
274 else {
275 // Use NULL when no buttons were found.
276 $placement = NULL;
277 }
278 }
279
280 // Store calculated placement in cache.
281 $placement_map[$form_id] = $placement;
282 variable_set('captcha_placement_map_cache', $placement_map);
283 }
284
285 return $placement;
286 }
287
288 /**
289 * Helper function for searching the buttons in a form.
290 *
291 * @param $form the form to search button elements in
292 * @return an array of paths to the buttons.
293 * A path is an array of keys leading to the button, the last
294 * item in the path is the weight of the button element
295 * (or NULL if undefined).
296 */
297 function _captcha_search_buttons($form) {
298 $buttons = array();
299 foreach (element_children($form) as $key) {
300 // Look for submit or button type elements.
301 if (isset($form[$key]['#type']) && ($form[$key]['#type'] == 'submit' || $form[$key]['#type'] == 'button')) {
302 $weight = isset($form[$key]['#weight']) ? $form[$key]['#weight'] : NULL;
303 $buttons[] = array(
304 'path' => array(),
305 'key' => $key,
306 'weight' => $weight,
307 );
308 }
309 // Process children recurively.
310 $children_buttons = _captcha_search_buttons($form[$key]);
311 foreach ($children_buttons as $b) {
312 $b['path'] = array_merge(array($key), $b['path']);
313 $buttons[] = $b;
314 }
315 }
316 return $buttons;
317 }
318
319 /**
320 * Helper function to insert a CAPTCHA element in a form before a given form element.
321 * @param $form the form to add the CAPTCHA element to.
322 * @param $placement information where the CAPTCHA element should be inserted.
323 * $placement should be an associative array with fields:
324 * - 'path': path (array of path items) of the container in the form where the
325 * CAPTCHA element should be inserted.
326 * - 'key': the key of the element before which the CAPTCHA element
327 * should be inserted. If the field 'key' is undefined or NULL, the CAPTCHA will
328 * just be appended in the container.
329 * - 'weight': if 'key' is not NULL: should be the weight of the element defined by 'key'.
330 * If 'key' is NULL and weight is not NULL: set the weight property of the CAPTCHA element
331 * to this value.
332 * @param $captcha_element the CAPTCHA element to insert.
333 */
334 function _captcha_insert_captcha_element(&$form, $placement, $captcha_element) {
335 // Get path, target and target weight or use defaults if not available.
336 $target_key = isset($placement['key']) ? $placement['key'] : NULL;
337 $target_weight = isset($placement['weight']) ? $placement['weight'] : NULL;
338 $path = isset($placement['path']) ? $placement['path'] : array();
339
340 // Walk through the form along the path.
341 $form_stepper = &$form;
342 foreach ($path as $step) {
343 if (isset($form_stepper[$step])) {
344 $form_stepper = & $form_stepper[$step];
345 }
346 else {
347 // Given path is invalid: stop stepping and
348 // continue in best effort (append instead of insert).
349 $target_key = NULL;
350 break;
351 }
352 }
353
354 // If no target is available: just append the CAPTCHA element to the container.
355 if ($target_key == NULL || !array_key_exists($target_key, $form_stepper)) {
356 // Optionally, set weight of CAPTCHA element.
357 if ($target_weight != NULL) {
358 $captcha_element['#weight'] = $target_weight;
359 }
360 $form_stepper['captcha'] = $captcha_element;
361 }
362 // If there is a target available: make sure the CAPTCHA element comes right before it.
363 else {
364 // If target has a weight: set weight of CAPTCHA element a bit smaller
365 // and just append the CAPTCHA: sorting will fix the ordering anyway.
366 if ($target_weight != NULL) {
367 $captcha_element['#weight'] = $target_weight - .1;
368 $form_stepper['captcha'] = $captcha_element;
369 }
370 else {
371 // If we can't play with weights: insert the CAPTCHA element at the right position.
372 // Because PHP lacks a function for this (array_splice() comes close,
373 // but it does not preserve the key of the inserted element), we do it by hand:
374 // chop of the end, append the CAPTCHA element and put the end back.
375 $offset = array_search($target_key, array_keys($form_stepper));
376 $end = array_splice($form_stepper, $offset);
377 $form_stepper['captcha'] = $captcha_element;
378 foreach ($end as $k => $v) {
379 $form_stepper[$k] = $v;
380 }
381 }
382 }
383 }
384