source: sipes/modules_contrib/captcha/captcha.admin.inc

stableversion-3.0
Last change on this file 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: 22.0 KB
Línea 
1<?php
2
3/**
4 * @file
5 * Functionality and helper functions for CAPTCHA administration.
6 */
7
8/**
9 * Return an array with the available CAPTCHA types, for use as options array
10 * for a select form elements.
11 *
12 * @param $add_special_options if true: also add a 'none' and 'default' option
13 *
14 * @return an associative array mapping "$module/$type" to
15 *   "$type (from module $module)" with $module the module name implementing the CAPTCHA
16 *   and $type the name of the CAPTCHA type.
17 */
18function _captcha_available_challenge_types($add_special_options=TRUE) {
19  if ($add_special_options) {
20    $captcha_types['none'] = '['. t('none') .']';
21    $captcha_types['default'] = '['. t('default challenge type') .']';
22  }
23  // We do our own version of Drupal's module_invoke_all() here because
24  // we want to build an array with custom keys and values.
25  foreach (module_implements('captcha') as $module) {
26    $result = call_user_func_array($module .'_captcha', array('list'));
27    if (is_array($result)) {
28      foreach ($result as $type) {
29        $captcha_types["$module/$type"] = t('@type (from module @module)', array('@type' => $type, '@module' => $module));
30      }
31    }
32  }
33  return $captcha_types;
34}
35
36/**
37 * Form builder function for the general CAPTCHA configuration
38 */
39function captcha_admin_settings(&$form_state) {
40  module_load_include('inc', 'captcha');
41
42  // Use javascript for some added usability on admin form.
43  drupal_add_js(drupal_get_path('module', 'captcha') .'/captcha.js');
44
45  // Configuration of which forms to protect, with what challenge.
46  $form['captcha_form_protection'] = array(
47    '#type' => 'fieldset',
48    '#title' => t('Form protection'),
49    '#description' => t('Select the challenge type you want for each of the listed forms (identified by their so called <em>form_id</em>\'s). You can easily add arbitrary forms with textfield at the bottom of the table or with the help of the \'%CAPTCHA_admin_links\' option below.',
50      array('%CAPTCHA_admin_links' => t('Add CAPTCHA administration links to forms'))
51      ),
52  );
53  $form['captcha_form_protection']['captcha_default_challenge'] = array(
54    '#type' => 'select',
55    '#title' => t('Default challenge type'),
56    '#description' => t('Select the default challenge type for CAPTCHAs. This can be overriden for each form if desired.'),
57    '#options' => _captcha_available_challenge_types(FALSE),
58    '#default_value' => variable_get('captcha_default_challenge', 'captcha/Math'),
59  );
60  // List known form_ids.
61  $form['captcha_form_protection']['captcha_form_id_overview'] = array(
62    '#theme' => 'captcha_admin_settings_captcha_points',
63    '#tree' => TRUE,
64  );
65  $form['captcha_form_protection']['captcha_form_id_overview']['captcha_captcha_points'] = array();
66  $captcha_type_options = _captcha_available_challenge_types();
67
68  $captcha_points = captcha_get_captcha_points();
69  foreach ($captcha_points as $captcha_point) {
70    $elem = array();
71    $elem['form_id'] = array(
72      '#value' => $captcha_point->form_id,
73    );
74    // Select widget for CAPTCHA type.
75    if (isset($captcha_point->module) && $captcha_point->module) {
76      $captcha_type = $captcha_point->module .'/'. $captcha_point->captcha_type;
77    }
78    elseif (isset($captcha_point->captcha_type) && ($captcha_point->captcha_type == 'default')) {
79      $captcha_type = 'default';
80    }
81    else {
82      $captcha_type = 'none';
83    }
84    $elem['captcha_type'] = array(
85      '#type' => 'select',
86      '#default_value' => $captcha_type,
87      '#options' => $captcha_type_options,
88    );
89    // Additional operations.
90    $ops = array();
91    if (module_exists('ctools') && $captcha_point->export_type & EXPORT_IN_CODE) {
92      if ($captcha_point->export_type & EXPORT_IN_DATABASE) {
93        $ops[] = l(t('revert'), "admin/user/captcha/captcha/captcha_point/{$captcha_point->form_id}/delete");
94      }
95      // TODO Disable exported points.
96    }
97    else {
98      $ops[] = l(t('delete'), "admin/user/captcha/captcha/captcha_point/{$captcha_point->form_id}/delete");
99    }
100    $elem['operations'] = array('#value' => implode(", ", $ops));
101
102    $form['captcha_form_protection']['captcha_form_id_overview']['captcha_captcha_points'][$captcha_point->form_id] = $elem;
103  }
104
105  // Form items for new form_id.
106  $form['captcha_form_protection']['captcha_form_id_overview']['captcha_new_captcha_point'] = array();
107  // Textfield for form_id.
108  $form['captcha_form_protection']['captcha_form_id_overview']['captcha_new_captcha_point']['form_id'] = array(
109    '#type' => 'textfield',
110    '#size' => 16,
111  );
112  // Select widget for CAPTCHA type.
113  $form['captcha_form_protection']['captcha_form_id_overview']['captcha_new_captcha_point']['captcha_type'] = array(
114    '#type' => 'select',
115    '#default_value' => 'none',
116    '#options' => $captcha_type_options,
117  );
118
119  // Field for the CAPTCHA administration mode.
120  $form['captcha_form_protection']['captcha_administration_mode'] = array(
121    '#type' => 'checkbox',
122    '#title' => t('Add CAPTCHA administration links to forms'),
123    '#default_value' => variable_get('captcha_administration_mode', FALSE),
124    '#description' => t('This option makes it easy to manage CAPTCHA settings on forms. When enabled, users with the "%admincaptcha" permission will see a fieldset with CAPTCHA administration links on all forms, except on administrative pages.', array('%admincaptcha' => t('administer CAPTCHA settings'))),
125  );
126  // Field for the CAPTCHAs on admin pages.
127  $form['captcha_form_protection']['captcha_allow_on_admin_pages'] = array(
128    '#type' => 'checkbox',
129    '#title' => t('Allow CAPTCHAs and CAPTCHA administration links on administrative pages'),
130    '#default_value' => variable_get('captcha_allow_on_admin_pages', FALSE),
131    '#description' => t('This option makes it possible to add CAPTCHAs to forms on administrative pages. CAPTCHAs are disabled by default on administrative pages (which shouldn\'t be accessible to untrusted users normally) to avoid the related overhead. In some situations, e.g. in the case of demo sites, it can be usefull to allow CAPTCHAs on administrative pages.'),
132  );
133
134  // Button for flushing the CAPTCHA placement cache.
135  $form['captcha_form_protection']['captcha_placement_caching'] = array(
136    '#type' => 'item',
137    '#title' => t('CAPTCHA placement caching'),
138    '#description' => t('For efficiency, the positions of the CAPTCHA elements in each of the configured forms are cached. Most of the time, the structure of a form does not change and it would be a waste to recalculate the positions every time. Occasionally however, the form structure can change (e.g. during site building) and flushing the CAPTCHA placement cache can be required to fix the CAPTCHA placement.'),
139  );
140  $form['captcha_form_protection']['captcha_placement_caching']['captcha_placement_cache_flush'] = array(
141    '#type' => 'button',
142    '#value' => t('Flush the CAPTCHA placement cache'),
143    '#submit' => array('captcha_placement_cache_flush'),
144  );
145  // Handle the button for flushing the CAPTCHA placement cache.
146  // This is done here instead of in a submit handler because the button is
147  // not a submitting button.
148  if (isset($form_state['post']['op']) && $form_state['post']['op'] ==  t('Flush the CAPTCHA placement cache')) {
149    variable_del('captcha_placement_map_cache');
150    drupal_set_message(t('Flushed the CAPTCHA placement cache.'));
151  }
152
153
154  // Configuration option for adding a CAPTCHA description.
155  $form['captcha_add_captcha_description'] = array(
156    '#type' => 'checkbox',
157    '#title' => t('Add a description to the CAPTCHA'),
158    '#description' => t('Add a configurable description to explain the purpose of the CAPTCHA to the visitor.'),
159    '#default_value' => variable_get('captcha_add_captcha_description', TRUE),
160  );
161  // Textfield(s) for the CAPTCHA description.
162  if (module_exists('locale')) {
163    $langs = locale_language_list();
164    $form['captcha_descriptions'] = array(
165      '#type' => 'fieldset',
166      '#title' => t('CAPTCHA description'),
167      '#description' => t('Configurable description of the CAPTCHA. An empty entry will reset the description.'),
168      '#attributes' => array('id' => 'edit-captcha-description-wrapper'),
169    );
170    foreach ($langs as $lang_code => $lang_name) {
171      $form['captcha_descriptions']["captcha_description_$lang_code"] = array(
172        '#type' => 'textfield',
173        '#title' => t('For language %lang_name (code %lang_code)', array('%lang_name' => $lang_name, '%lang_code' => $lang_code)),
174        '#default_value' => _captcha_get_description($lang_code),
175        '#maxlength' => 256,
176      );
177    }
178  }
179  else {
180    $form['captcha_description'] = array(
181      '#type' => 'textfield',
182      '#title' => t('Challenge description'),
183      '#description' => t('Configurable description of the CAPTCHA. An empty entry will reset the description.'),
184      '#default_value' => _captcha_get_description(),
185      '#maxlength' => 256,
186    );
187  }
188
189  // Option for case sensitive/insensitive validation of the responses.
190  $form['captcha_default_validation'] = array(
191    '#type' => 'radios',
192    '#title' => t('Default CAPTCHA validation'),
193    '#description' => t('Define how the response should be processed by default. Note that the modules that provide the actual challenges can override or ignore this.'),
194    '#options' => array(
195      CAPTCHA_DEFAULT_VALIDATION_CASE_SENSITIVE => t('Case sensitive validation: the response has to exactly match the solution.'),
196      CAPTCHA_DEFAULT_VALIDATION_CASE_INSENSITIVE => t('Case insensitive validation: lowercase/uppercase errors are ignored.'),
197    ),
198    '#default_value' => variable_get('captcha_default_validation', CAPTCHA_DEFAULT_VALIDATION_CASE_INSENSITIVE),
199  );
200
201  // Field for CAPTCHA persistence.
202  // TODO for D7: Rethink/simplify the explanation and UI strings.
203  $form['captcha_persistence'] = array(
204    '#type' => 'radios',
205    '#title' => t('Persistence'),
206    '#default_value' => variable_get('captcha_persistence', CAPTCHA_PERSISTENCE_SKIP_ONCE_SUCCESSFUL_PER_FORM_INSTANCE),
207    '#options' => array(
208      CAPTCHA_PERSISTENCE_SHOW_ALWAYS =>
209        t('Always add a challenge.'),
210      CAPTCHA_PERSISTENCE_SKIP_ONCE_SUCCESSFUL_PER_FORM_INSTANCE =>
211        t('Omit challenges in a multi-step/preview workflow once the user successfully responds to a challenge.'),
212      CAPTCHA_PERSISTENCE_SKIP_ONCE_SUCCESSFUL_PER_FORM_TYPE =>
213        t('Omit challenges on a form type once the user successfully responds to a challenge on a form of that type.'),
214      CAPTCHA_PERSISTENCE_SKIP_ONCE_SUCCESSFUL =>
215        t('Omit challenges on all forms once the user successfully responds to any challenge on the site.'),
216    ),
217    '#description' => t('Define if challenges should be omitted during the rest of a session once the user successfully responds to a challenge.'),
218  );
219
220  // Option for logging wrong responses.
221  $form['captcha_log_wrong_responses'] = array(
222    '#type' => 'checkbox',
223    '#title' => t('Log wrong responses'),
224    '#description' => t('Report information about wrong responses to the !log.', array('!log' => l(t('log'), 'admin/reports/dblog'))),
225    '#default_value' => variable_get('captcha_log_wrong_responses', FALSE),
226  );
227
228  // Submit button.
229  $form['submit'] = array(
230    '#type' => 'submit',
231    '#value' => t('Save configuration'),
232  );
233
234  return $form;
235}
236
237/**
238 * Custom theme function for a table of (form_id -> CAPTCHA type) settings
239 */
240function theme_captcha_admin_settings_captcha_points($form) {
241  $header = array('form_id', t('Challenge type'), t('Operations'));
242  $rows = array();
243  // Existing CAPTCHA points.
244  foreach (element_children($form['captcha_captcha_points']) as $key) {
245    $row = array();
246    $row[] = drupal_render($form['captcha_captcha_points'][$key]['form_id']);
247    $row[] = drupal_render($form['captcha_captcha_points'][$key]['captcha_type']);
248    $row[] = drupal_render($form['captcha_captcha_points'][$key]['operations']);
249    $rows[] = $row;
250  }
251  // For new CAPTCHA point.
252  $row = array();
253  $row[] = drupal_render($form['captcha_new_captcha_point']['form_id']);
254  $row[] = drupal_render($form['captcha_new_captcha_point']['captcha_type']);
255  $row[] = '';
256  $rows[] = $row;
257
258  $output = theme('table', $header, $rows);
259  return $output;
260}
261
262/**
263 * Validation handler for captcha_admin_settings form.
264 */
265function captcha_admin_settings_validate($form, $form_state) {
266  $form_id = $form_state['values']['captcha_form_id_overview']['captcha_new_captcha_point']['form_id'];
267  if (!preg_match('/^[a-z0-9_]*$/', $form_id)) {
268    form_set_error('captcha_form_id_overview][captcha_new_captcha_point][form_id', t('Illegal form_id'));
269  }
270}
271
272/**
273 * Submission function for captcha_admin_settings form.
274 */
275function captcha_admin_settings_submit($form, &$form_state) {
276
277  variable_set('captcha_administration_mode', $form_state['values']['captcha_administration_mode']);
278  variable_set('captcha_allow_on_admin_pages', $form_state['values']['captcha_allow_on_admin_pages']);
279
280  variable_set('captcha_default_challenge', $form_state['values']['captcha_default_challenge']);
281
282  // Process CAPTCHA points
283  if (isset($form_state['values']['captcha_form_id_overview']['captcha_captcha_points'])) {
284    // Load existing data.
285    $captcha_points = captcha_get_captcha_points();
286
287    foreach ($form_state['values']['captcha_form_id_overview']['captcha_captcha_points'] as $captcha_point_form_id => $data) {
288
289      // If this is an in-code captcha point and its settings are unchanged,
290      // don't save to the database.
291      if (module_exists('ctools') && isset($captcha_points[$captcha_point_form_id])) {
292        // Parse module and captcha_type from submitted values.
293        $captcha_type = $data['captcha_type'];
294        if (is_string($captcha_type) && substr_count($captcha_type, '/') == 1) {
295          list($module, $subtype) = explode('/', $data['captcha_type']);
296        }
297        else {
298          $module = NULL;
299          $subtype = ($captcha_type === 'none') ? NULL : $captcha_type;
300        }
301
302        $point = $captcha_points[$captcha_point_form_id];
303        if ($point->export_type & EXPORT_IN_CODE && !($point->export_type & EXPORT_IN_DATABASE) &&
304        $point->module == $module && $point->captcha_type == $subtype) {
305          continue;
306        }
307      }
308
309      captcha_set_form_id_setting($captcha_point_form_id, $data['captcha_type']);
310    }
311  }
312
313  // Add new CAPTCHA point?
314  $captcha_point_form_id = $form_state['values']['captcha_form_id_overview']['captcha_new_captcha_point']['form_id'];
315  if (!empty($captcha_point_form_id)) {
316    $captcha_type = $form_state['values']['captcha_form_id_overview']['captcha_new_captcha_point']['captcha_type'];
317    captcha_set_form_id_setting($captcha_point_form_id, $captcha_type);
318    drupal_set_message(t('Added CAPTCHA point.'), 'status');
319  }
320
321  // CAPTCHA description stuff.
322  variable_set('captcha_add_captcha_description', $form_state['values']['captcha_add_captcha_description']);
323  // Save (or reset) the CAPTCHA descriptions.
324  if (module_exists('locale')) {
325    $langs = locale_language_list();
326    foreach ($langs as $lang_code => $lang_name) {
327      $description = $form_state['values']["captcha_description_$lang_code"];
328      if ($description) {
329        variable_set("captcha_description_$lang_code", $description);
330      }
331      else {
332        variable_del("captcha_description_$lang_code");
333        drupal_set_message(t('Reset of CAPTCHA description for language %language.', array('%language' => $lang_name)), 'status');
334      }
335    }
336  }
337  else {
338    $description = $form_state['values']['captcha_description'];
339    if ($description) {
340      variable_set('captcha_description', $description);
341    }
342    else {
343      variable_del('captcha_description');
344      drupal_set_message(t('Reset of CAPTCHA description.'), 'status');
345    }
346  }
347
348  variable_set('captcha_default_validation', $form_state['values']['captcha_default_validation']);
349  variable_set('captcha_persistence', $form_state['values']['captcha_persistence']);
350  variable_set('captcha_log_wrong_responses', $form_state['values']['captcha_log_wrong_responses']);
351
352  drupal_set_message(t('The CAPTCHA settings were saved.'), 'status');
353}
354
355
356/**
357 * Central handler for CAPTCHA point administration (adding, disabling, deleting)
358 */
359function captcha_point_admin($captcha_point_form_id=NULL, $op=NULL) {
360  module_load_include('inc', 'captcha');
361
362  // if $captcha_point_form_id and action $op given: do the action
363  if ($captcha_point_form_id) {
364    switch ($op) {
365      case 'disable':
366        return drupal_get_form('captcha_point_disable_confirm', $captcha_point_form_id, FALSE);
367      case 'delete':
368        return drupal_get_form('captcha_point_disable_confirm', $captcha_point_form_id, TRUE);
369    }
370    // return edit form for CAPTCHA point
371    return drupal_get_form('captcha_point_admin_form', $captcha_point_form_id);
372  }
373  // return add form for CAPTCHA point
374  return drupal_get_form('captcha_point_admin_form');
375}
376
377function captcha_point_admin_form($form_state, $captcha_point_form_id=NULL) {
378  $form = array();
379  $default_captcha_type = 'none';
380  if (isset($captcha_point_form_id)) {
381    // use given CAPTCHA point form_id
382    $form['captcha_point_form_id'] = array(
383      '#type' => 'textfield',
384      '#title' => t('Form ID'),
385      '#description' => t('The Drupal form_id of the form to add the CAPTCHA to.'),
386      '#value' => check_plain($captcha_point_form_id),
387      '#disabled' => TRUE,
388    );
389    $captcha_point = captcha_get_form_id_setting($captcha_point_form_id);
390    if ($captcha_point) {
391      $default_captcha_type = "{$captcha_point->module}/{$captcha_point->captcha_type}";
392    }
393  }
394  else {
395    // textfield for CAPTCHA point form_id
396    $form['captcha_point_form_id'] = array(
397      '#type' => 'textfield',
398      '#title' => t('Form ID'),
399      '#description' => t('The Drupal form_id of the form to add the CAPTCHA to.'),
400    );
401  }
402  // select widget for CAPTCHA type
403  $form['captcha_type'] = array(
404    '#type' => 'select',
405    '#title' => t('Challenge type'),
406    '#description' => t('The CAPTCHA type to use for this form'),
407    '#default_value' => $default_captcha_type,
408    '#options' => _captcha_available_challenge_types(),
409  );
410  // redirect to general CAPTCHA settings page after submission
411  $form['#redirect'] = 'admin/user/captcha';
412  // submit button
413  $form['submit'] = array(
414    '#type' => 'submit',
415    '#value' => t('Save'),
416  );
417  return $form;
418}
419
420
421/**
422 * validation function for captcha_point_admin_form
423 */
424function captcha_point_admin_form_validate($form, $form_state) {
425  if (!preg_match('/^[a-z0-9_]+$/', $form_state['values']['captcha_point_form_id'])) {
426    form_set_error('captcha_point_form_id', t('Illegal form_id'));
427  }
428}
429
430
431/**
432 * Submit function for captcha_point_admin_form.
433 */
434function captcha_point_admin_form_submit($form, $form_state) {
435  $captcha_point_form_id = $form_state['values']['captcha_point_form_id'];
436  $captcha_type = $form_state['values']['captcha_type'];
437  captcha_set_form_id_setting($captcha_point_form_id, $captcha_type);
438  drupal_set_message(t('Saved CAPTCHA point settings.'), 'status');
439}
440
441/**
442 * Confirm dialog for disabling/deleting a CAPTCHA point
443 */
444function captcha_point_disable_confirm(&$form_state, $captcha_point_form_id, $delete) {
445  $form = array();
446  $form['captcha_point_form_id'] = array(
447    '#type' => 'value',
448    '#value' => $captcha_point_form_id,
449  );
450  $form['captcha_point_delete'] = array(
451    '#type' => 'value',
452    '#value' => $delete,
453  );
454  if ($delete) {
455    $message = t('Are you sure you want to delete the CAPTCHA for form_id %form_id?', array('%form_id' => $captcha_point_form_id));
456    $yes = t('Delete');
457  }
458  else {
459    $message = t('Are you sure you want to disable the CAPTCHA for form_id %form_id?', array('%form_id' => $captcha_point_form_id));
460    $yes = t('Disable');
461  }
462  return confirm_form($form, $message, 'admin/user/captcha/captcha', '', $yes);
463}
464
465/**
466 * Submission handler of CAPTCHA point disabling/deleting confirm_form.
467 */
468function captcha_point_disable_confirm_submit($form, &$form_state) {
469  $captcha_point_form_id = $form_state['values']['captcha_point_form_id'];
470  $delete = $form_state['values']['captcha_point_delete'];
471  if ($delete) {
472    captcha_set_form_id_setting($captcha_point_form_id, NULL);
473    drupal_set_message(t('Deleted CAPTCHA for form %form_id.', array('%form_id' => $captcha_point_form_id)));
474  }
475  else {
476    captcha_set_form_id_setting($captcha_point_form_id, 'none');
477    drupal_set_message(t('Disabled CAPTCHA for form %form_id.', array('%form_id' => $captcha_point_form_id)));
478  }
479  $form_state['redirect'] = 'admin/user/captcha/captcha';
480}
481
482/**
483 * Helper function for generating an example challenge.
484 */
485function _captcha_generate_example_challenge($module, $type) {
486  return array(
487    '#type' => 'captcha',
488    '#captcha_type' => $module .'/'. $type,
489    '#captcha_admin_mode' => TRUE,
490  );
491}
492
493/**
494 * Funtion for generating a page with CAPTCHA examples.
495 *
496 * If the arguments $module and $challenge are not set, generate a list with
497 * examples of the available CAPTCHA types.
498 * If $module and $challenge are set, generate 10 examples of the concerning
499 * CAPTCHA.
500 */
501function captcha_examples($form_state, $module, $challenge) {
502  module_load_include('inc', 'captcha');
503
504  $form = array();
505  if ($module && $challenge) {
506    // Generate 10 example challenges.
507    for ($i=0; $i<10; $i++) {
508      $form["challenge_{$i}"] = _captcha_generate_example_challenge($module, $challenge);
509    }
510  }
511  else {
512    // generate a list with examples of the available CAPTCHA types
513    $form['info'] = array(
514      '#value' => t('This page gives an overview of all available challenge types, generated with their current settings.'),
515    );
516    foreach (module_implements('captcha') as $mkey => $module) {
517      $challenges = call_user_func_array($module .'_captcha', array('list'));
518      if ($challenges) {
519        foreach ($challenges as $ckey => $challenge) {
520          $form["captcha_{$mkey}_{$ckey}"] = array(
521            '#type' => 'fieldset',
522            '#title' => t('Challenge "%challenge" by module "%module"', array('%challenge' => $challenge, '%module' => $module)),
523            'challenge' => _captcha_generate_example_challenge($module, $challenge),
524            'more_examples' => array(
525              '#value' => l(t('10 more examples of this challenge.'), "admin/user/captcha/captcha/examples/$module/$challenge"),
526            ),
527          );
528        }
529      }
530    }
531  }
532  return $form;
533}
Nota: Vea TracBrowser para ayuda de uso del navegador del repositorio.