#918856 - CAPTCHA Session Reuse message on webforms
[project/captcha.git] / captcha.inc
CommitLineData
852813d1 1<?php
852813d1 2
852813d1 3/**
cdd89fd9
SL
4 * @file
5 * General CAPTCHA functionality and helper functions.
6 */
7
8/**
ec836876
SL
9 * Helper function for adding/updating a CAPTCHA point.
10 *
11 * @param $form_id the form ID to configure.
4d405648
SL
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'
a0583ff0 17 * - an object with attributes $captcha_type->module and $captcha_type->captcha_type
ec836876 18 * @return nothing
ec836876
SL
19 */
20function captcha_set_form_id_setting($form_id, $captcha_type) {
b473fc58 21 // Handle 'none'.
ec836876 22 if ($captcha_type == 'none') {
b473fc58
SL
23 db_merge('captcha_points')
24 ->key(array('form_id' => $form_id))
a0583ff0 25 ->fields(array('module' => NULL, 'captcha_type' => NULL))
b473fc58 26 ->execute();
ec836876 27 }
b473fc58 28 // Handle 'default'.
ec836876 29 elseif ($captcha_type == 'default') {
b473fc58
SL
30 db_merge('captcha_points')
31 ->key(array('form_id' => $form_id))
a0583ff0 32 ->fields(array('module' => NULL, 'captcha_type' => 'default'))
b473fc58 33 ->execute();
ec836876 34 }
b473fc58 35 // Handle NULL.
ec836876 36 elseif ($captcha_type == NULL) {
b473fc58 37 db_delete('captcha_points')->condition('form_id', $form_id)->execute();
ec836876 38 }
b473fc58 39 // Handle a captcha_type object.
a0583ff0 40 elseif (is_object($captcha_type) && isset($captcha_type->module) && isset($captcha_type->captcha_type)) {
b473fc58
SL
41 db_merge('captcha_points')
42 ->key(array('form_id' => $form_id))
a0583ff0 43 ->fields(array('module' => $captcha_type->module, 'captcha_type' => $captcha_type->captcha_type))
b473fc58 44 ->execute();
4d405648 45 }
b473fc58 46 // Handle a captcha_type string.
4d405648 47 elseif (is_string($captcha_type) && substr_count($captcha_type, '/') == 1) {
ec836876 48 list($module, $type) = explode('/', $captcha_type);
b473fc58
SL
49 db_merge('captcha_points')
50 ->key(array('form_id' => $form_id))
a0583ff0 51 ->fields(array('module' => $module, 'captcha_type' => $type))
b473fc58 52 ->execute();
ec836876
SL
53 }
54 else {
55 drupal_set_message(t('Failed to set a CAPTCHA type for form %form_id: could not interpret value "@captcha_type"',
4d405648 56 array('%form_id' => $form_id, '@captcha_type' => (string)$captcha_type)), 'warning');
ec836876
SL
57 }
58}
59
60/**
61 * Get the CAPTCHA setting for a given form_id.
62 *
df833c7e
SL
63 * @param $form_id the form_id to query for
64 * @param $symbolic flag to return as (symbolic) strings instead of object.
ec836876 65 *
df833c7e 66 * @return NULL if no setting is known
a0583ff0 67 * or a captcha_point object with fields 'module' and 'captcha_type'.
df833c7e
SL
68 * If argument $symbolic is true, returns (symbolic) as 'none', 'default'
69 * or in the form 'captcha/Math'.
ec836876 70 */
df833c7e 71function captcha_get_form_id_setting($form_id, $symbolic=FALSE) {
df806586 72 // Fetch setting from database.
a0583ff0 73 $result = db_query("SELECT module, captcha_type FROM {captcha_points} WHERE form_id = :form_id",
7212e5a3 74 array(':form_id' => $form_id));
b473fc58 75 $captcha_point = $result->fetchObject();
20f9ea92 76
df806586
SL
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');
ec836876 82 }
20f9ea92 83
df806586
SL
84 // Handle (default) settings and symbolic mode.
85 if (!$captcha_point) {
86 $captcha_point = NULL;
87 }
88 elseif ($captcha_point->captcha_type == 'default') {
df833c7e
SL
89 if (!$symbolic) {
90 list($module, $type) = explode('/', variable_get('captcha_default_challenge', 'captcha/Math'));
91 $captcha_point->module = $module;
a0583ff0 92 $captcha_point->captcha_type = $type;
df833c7e
SL
93 }
94 else {
95 $captcha_point = 'default';
96 }
97 }
a0583ff0 98 elseif ($captcha_point->module == NULL && $captcha_point->captcha_type == NULL && $symbolic) {
df833c7e
SL
99 $captcha_point = 'none';
100 }
101 elseif ($symbolic) {
a0583ff0 102 $captcha_point = $captcha_point->module . '/' . $captcha_point->captcha_type;
ec836876
SL
103 }
104 return $captcha_point;
105}
106
107
108/**
777c94d7
SL
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.
852813d1 114 */
777c94d7
SL
115function _captcha_generate_captcha_session($form_id=NULL, $status=CAPTCHA_STATUS_UNSOLVED) {
116 global $user;
511a109e
SL
117 // Initialize solution with random data.
118 $solution = md5(mt_rand());
b473fc58
SL
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,
511a109e 127 'solution' => $solution,
b473fc58
SL
128 'status' => $status,
129 'attempts' => 0,
130 ))
131 ->execute();
777c94d7
SL
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 */
141function _captcha_update_captcha_session($captcha_sid, $solution) {
b473fc58
SL
142 db_update('captcha_sessions')
143 ->condition('csid', $captcha_sid)
144 ->fields(array(
145 'timestamp' => REQUEST_TIME,
146 'solution' => $solution,
147 ))
148 ->execute();
777c94d7
SL
149}
150
151/**
152 * Helper function for checking if CAPTCHA is required for user,
c0bd33ae
SL
153 * based on the CAPTCHA persistence setting, the CAPTCHA session ID and
154 * user session info.
777c94d7
SL
155 */
156function _captcha_required_for_user($captcha_sid, $form_id) {
c0bd33ae
SL
157 // Get the CAPTCHA persistence setting.
158 $captcha_persistence = variable_get('captcha_persistence', CAPTCHA_PERSISTENCE_SKIP_ONCE_SUCCESSFUL_PER_FORM_INSTANCE);
852813d1 159
c0bd33ae
SL
160 // First check: should we always add a CAPTCHA?
161 if ($captcha_persistence == CAPTCHA_PERSISTENCE_SHOW_ALWAYS) {
162 return TRUE;
163 }
efd7ac42 164
c0bd33ae
SL
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;
777c94d7 170 }
852813d1 171
c0bd33ae
SL
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;
056c2aa1 188}
852813d1 189
c0bd33ae 190
777c94d7 191/**
0664c3a9
SL
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 *
782937d0
SL
199 * @param $lang_code an optional language code to get the descripion for.
200 * @return a string with (localized) CAPTCHA description.
777c94d7
SL
201 */
202function _captcha_get_description($lang_code=NULL) {
0664c3a9
SL
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.
d8729096 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));
0664c3a9 208 // Look up the configured CAPTCHA description or fall back on the (localized) default.
777c94d7 209 if (module_exists('locale')) {
777c94d7
SL
210 $description = variable_get("captcha_description_$lang_code", $default);
211 }
212 else {
213 $description = variable_get('captcha_description', $default);
214 }
3d031dea 215 return filter_xss_admin($description);
777c94d7
SL
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 */
224function _captcha_parse_captcha_type($captcha_type) {
225 if ($captcha_type == 'none') {
226 return array(NULL, NULL);
227 }
228 if ($captcha_type == 'default') {
ec836876 229 $captcha_type = variable_get('captcha_default_challenge', 'captcha/Math');
777c94d7
SL
230 }
231 return explode('/', $captcha_type);
232}
056c2aa1
SL
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 */
243function _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);
056c2aa1
SL
251
252 if ($placement_map === NULL) {
8055780f
SL
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');
056c2aa1 258 }
852813d1
SL
259 }
260
056c2aa1
SL
261 // Query the placement map.
262 if (array_key_exists($form_id, $placement_map)) {
263 $placement = $placement_map[$form_id];
264 }
855288c8 265 // If no placement info is available in placement map: make a best effort guess.
056c2aa1 266 else {
855288c8
SL
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 );
33b7718a
SL
275 }
276 else {
855288c8
SL
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 }
33b7718a
SL
288 }
289
855288c8 290 // Store calculated placement in cache.
056c2aa1
SL
291 $placement_map[$form_id] = $placement;
292 variable_set('captcha_placement_map_cache', $placement_map);
293 }
203adfed 294
056c2aa1
SL
295 return $placement;
296}
d2dfa333 297
056c2aa1
SL
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 */
307function _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;
d2dfa333 324 }
056c2aa1
SL
325 }
326 return $buttons;
327}
d2dfa333 328
056c2aa1
SL
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.
33b7718a
SL
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.
056c2aa1
SL
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
8055780f 338 * just be appended in the container.
056c2aa1
SL
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 */
344function _captcha_insert_captcha_element(&$form, $placement, $captcha_element) {
33b7718a
SL
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();
056c2aa1
SL
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];
d2dfa333
SL
355 }
356 else {
056c2aa1
SL
357 // Given path is invalid: stop stepping and
358 // continue in best effort (append instead of insert).
359 $target_key = NULL;
360 break;
d2dfa333 361 }
d2dfa333
SL
362 }
363
056c2aa1
SL
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;
cdd89fd9 388 foreach ($end as $k => $v) {
056c2aa1
SL
389 $form_stepper[$k] = $v;
390 }
391 }
392 }
d2dfa333
SL
393}
394