Issue #1002246: make 'captcha_wrong_response_counter' updating optional and disabled...
[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) {
a0583ff0 72 $result = db_query("SELECT module, captcha_type FROM {captcha_points} WHERE form_id = :form_id",
7212e5a3 73 array(':form_id' => $form_id));
b473fc58 74 $captcha_point = $result->fetchObject();
ec836876
SL
75 if (!$captcha_point) {
76 $captcha_point = NULL;
77 }
a0583ff0 78 elseif ($captcha_point->captcha_type == 'default') {
df833c7e
SL
79 if (!$symbolic) {
80 list($module, $type) = explode('/', variable_get('captcha_default_challenge', 'captcha/Math'));
81 $captcha_point->module = $module;
a0583ff0 82 $captcha_point->captcha_type = $type;
df833c7e
SL
83 }
84 else {
85 $captcha_point = 'default';
86 }
87 }
a0583ff0 88 elseif ($captcha_point->module == NULL && $captcha_point->captcha_type == NULL && $symbolic) {
df833c7e
SL
89 $captcha_point = 'none';
90 }
91 elseif ($symbolic) {
a0583ff0 92 $captcha_point = $captcha_point->module . '/' . $captcha_point->captcha_type;
ec836876
SL
93 }
94 return $captcha_point;
95}
96
97
98/**
777c94d7
SL
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.
852813d1 104 */
777c94d7
SL
105function _captcha_generate_captcha_session($form_id=NULL, $status=CAPTCHA_STATUS_UNSOLVED) {
106 global $user;
511a109e
SL
107 // Initialize solution with random data.
108 $solution = md5(mt_rand());
b473fc58
SL
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,
511a109e 117 'solution' => $solution,
b473fc58
SL
118 'status' => $status,
119 'attempts' => 0,
120 ))
121 ->execute();
777c94d7
SL
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 */
131function _captcha_update_captcha_session($captcha_sid, $solution) {
b473fc58
SL
132 db_update('captcha_sessions')
133 ->condition('csid', $captcha_sid)
134 ->fields(array(
135 'timestamp' => REQUEST_TIME,
136 'solution' => $solution,
137 ))
138 ->execute();
777c94d7
SL
139}
140
141/**
142 * Helper function for checking if CAPTCHA is required for user,
c0bd33ae
SL
143 * based on the CAPTCHA persistence setting, the CAPTCHA session ID and
144 * user session info.
777c94d7
SL
145 */
146function _captcha_required_for_user($captcha_sid, $form_id) {
c0bd33ae
SL
147 // Get the CAPTCHA persistence setting.
148 $captcha_persistence = variable_get('captcha_persistence', CAPTCHA_PERSISTENCE_SKIP_ONCE_SUCCESSFUL_PER_FORM_INSTANCE);
852813d1 149
c0bd33ae
SL
150 // First check: should we always add a CAPTCHA?
151 if ($captcha_persistence == CAPTCHA_PERSISTENCE_SHOW_ALWAYS) {
152 return TRUE;
153 }
efd7ac42 154
c0bd33ae
SL
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;
777c94d7 160 }
852813d1 161
c0bd33ae
SL
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;
056c2aa1 178}
852813d1 179
c0bd33ae 180
777c94d7 181/**
0664c3a9
SL
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 *
782937d0
SL
189 * @param $lang_code an optional language code to get the descripion for.
190 * @return a string with (localized) CAPTCHA description.
777c94d7
SL
191 */
192function _captcha_get_description($lang_code=NULL) {
0664c3a9
SL
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.
d8729096 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));
0664c3a9 198 // Look up the configured CAPTCHA description or fall back on the (localized) default.
777c94d7 199 if (module_exists('locale')) {
777c94d7
SL
200 $description = variable_get("captcha_description_$lang_code", $default);
201 }
202 else {
203 $description = variable_get('captcha_description', $default);
204 }
3d031dea 205 return filter_xss_admin($description);
777c94d7
SL
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 */
214function _captcha_parse_captcha_type($captcha_type) {
215 if ($captcha_type == 'none') {
216 return array(NULL, NULL);
217 }
218 if ($captcha_type == 'default') {
ec836876 219 $captcha_type = variable_get('captcha_default_challenge', 'captcha/Math');
777c94d7
SL
220 }
221 return explode('/', $captcha_type);
222}
056c2aa1
SL
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 */
233function _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);
056c2aa1
SL
241
242 if ($placement_map === NULL) {
8055780f
SL
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');
056c2aa1 248 }
852813d1
SL
249 }
250
056c2aa1
SL
251 // Query the placement map.
252 if (array_key_exists($form_id, $placement_map)) {
253 $placement = $placement_map[$form_id];
254 }
855288c8 255 // If no placement info is available in placement map: make a best effort guess.
056c2aa1 256 else {
855288c8
SL
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 );
33b7718a
SL
265 }
266 else {
855288c8
SL
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 }
33b7718a
SL
278 }
279
855288c8 280 // Store calculated placement in cache.
056c2aa1
SL
281 $placement_map[$form_id] = $placement;
282 variable_set('captcha_placement_map_cache', $placement_map);
283 }
203adfed 284
056c2aa1
SL
285 return $placement;
286}
d2dfa333 287
056c2aa1
SL
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 */
297function _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;
d2dfa333 314 }
056c2aa1
SL
315 }
316 return $buttons;
317}
d2dfa333 318
056c2aa1
SL
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.
33b7718a
SL
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.
056c2aa1
SL
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
8055780f 328 * just be appended in the container.
056c2aa1
SL
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 */
334function _captcha_insert_captcha_element(&$form, $placement, $captcha_element) {
33b7718a
SL
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();
056c2aa1
SL
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];
d2dfa333
SL
345 }
346 else {
056c2aa1
SL
347 // Given path is invalid: stop stepping and
348 // continue in best effort (append instead of insert).
349 $target_key = NULL;
350 break;
d2dfa333 351 }
d2dfa333
SL
352 }
353
056c2aa1
SL
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;
cdd89fd9 378 foreach ($end as $k => $v) {
056c2aa1
SL
379 $form_stepper[$k] = $v;
380 }
381 }
382 }
d2dfa333
SL
383}
384