'. t('"CAPTCHA" is an acronym for "Completely Automated Public Turing test to tell Computers and Humans Apart". It is typically a challenge-response test to determine whether the user is human. The CAPTCHA module is a tool to fight automated submission by malicious users (spamming) of for example comments forms, user registration forms, guestbook forms, etc. You can extend the desired forms with an additional challenge, which should be easy for a human to solve correctly, but hard enough to keep automated scripts and spam bots out.') .'
';
$output .= ''. t('Note that the CAPTCHA module interacts with page caching (see performance settings). Because the challenge should be unique for each generated form, the caching of the page it appears on is prevented. Make sure that these forms do not appear on too many pages or you will lose much caching efficiency. For example, if you put a CAPTCHA on the user login block, which typically appears on each page for anonymous visitors, caching will practically be disabled. The comment submission forms are another example. In this case you should set the "%commentlocation" to "%separatepage" in the comment settings of the relevant content types for better caching efficiency.' ,
array(
'!performancesettings' => url('admin/settings/performance'),
'%commentlocation' => t('Location of comment submission form'),
'%separatepage' => t('Display on separate page'),
'!contenttypes' => url('admin/content/types'),
)
) .'
';
$output .= ''. t('CAPTCHA is a trademark of Carnegie Mellon University.') .'
';
return $output;
case 'admin/user/captcha':
case 'admin/user/captcha/captcha':
case 'admin/user/captcha/captcha/settings':
$output = ''. t('A CAPTCHA can be added to virtually each Drupal form. Some default forms are already provided in the form list, but arbitrary forms can be easily added and managed when the option "%adminlinks" is enabled.',
array('%adminlinks' => t('Add CAPTCHA administration links to forms'))) .'
';
$output .= ''. t('Users with the "%skipcaptcha" permission won\'t be offered a challenge. Be sure to grant this permission to the trusted users (e.g. site administrators). If you want to test a protected form, be sure to do it as a user without the "%skipcaptcha" permission (e.g. as anonymous user).',
array('%skipcaptcha' => t('skip CAPTCHA'), '@perm' => url('admin/user/permissions'))) .'
';
return $output;
}
}
/**
* Implementation of hook_menu().
*/
function captcha_menu() {
$items = array();
// main configuration page of the basic CAPTCHA module
$items['admin/user/captcha'] = array(
'title' => 'CAPTCHA',
'description' => 'Administer how and where CAPTCHAs are used.',
'file' => 'captcha.admin.inc',
'page callback' => 'drupal_get_form',
'page arguments' => array('captcha_admin_settings'),
'access arguments' => array('administer CAPTCHA settings'),
'type' => MENU_NORMAL_ITEM,
);
// the default local task (needed when other modules want to offer
// alternative CAPTCHA types and their own configuration page as local task)
$items['admin/user/captcha/captcha'] = array(
'title' => 'CAPTCHA',
'access arguments' => array('administer CAPTCHA settings'),
'type' => MENU_DEFAULT_LOCAL_TASK,
'weight' => -20,
);
$items['admin/user/captcha/captcha/settings'] = array(
'title' => 'General settings',
'access arguments' => array('administer CAPTCHA settings'),
'type' => MENU_DEFAULT_LOCAL_TASK,
'weight' => 0,
);
$items['admin/user/captcha/captcha/examples'] = array(
'title' => 'Examples',
'description' => 'An overview of the available challenge types with examples.',
'file' => 'captcha.admin.inc',
'page callback' => 'drupal_get_form',
'page arguments' => array('captcha_examples', 5, 6),
'access arguments' => array('administer CAPTCHA settings'),
'type' => MENU_LOCAL_TASK,
'weight' => 5,
);
$items['admin/user/captcha/captcha/captcha_point'] = array(
'title' => 'CAPTCHA point administration',
'file' => 'captcha.admin.inc',
'page callback' => 'captcha_point_admin',
'page arguments' => array(5, 6),
'access arguments' => array('administer CAPTCHA settings'),
'type' => MENU_CALLBACK,
);
return $items;
}
/**
* Implementation of hook_perm().
*/
function captcha_perm() {
return array('administer CAPTCHA settings', 'skip CAPTCHA');
}
/**
* Implementation of hook_requirements().
*/
function captcha_requirements($phase) {
$requirements = array();
$t = get_t();
if ($phase == 'runtime') {
// show the wrong response counter in the status report
$requirements['captcha_wrong_response_counter'] = array(
'title' => $t('CAPTCHA'),
'value' => format_plural(
variable_get('captcha_wrong_response_counter', 0),
'Already 1 blocked form submission',
'Already @count blocked form submissions'
),
'severity' => REQUIREMENT_INFO,
);
}
return $requirements;
}
/**
* Implementation of hook_theme().
*/
function captcha_theme() {
return array(
'captcha_admin_settings_captcha_points' => array(
'arguments' => array('form' => NULL),
),
'captcha' => array(
'arguments' => array('element' => NULL),
),
);
}
/**
* Implementation of hook_cron().
*
* Remove old entries from captcha_sessions table.
*/
function captcha_cron() {
// remove challenges older than 1 day
db_query('DELETE FROM {captcha_sessions} WHERE timestamp < %d', time() - 60*60*24);
}
/**
* Implementation of hook_elements().
*/
function captcha_elements() {
// Define the CAPTCHA form element with default properties.
// Unfortunately we can't set the '#description' field here because
// Drupal's form API processes it in a weird way: '#description'
// becomes an array instead of a string (see _element_info() in form.inc).
return array('captcha' => array(
'#input' => TRUE,
'#process' => array('captcha_process'),
// The type of challenge: e.g. 'default', 'none', 'captcha/Math', 'image_captcha/Image', ...
'#captcha_type' => 'default',
'#default_value' => '',
// CAPTCHA in admin mode: presolve the CAPTCHA and always show it (despite previous successful responses).
'#captcha_admin_mode' => FALSE,
));
}
/**
* Process callback for CAPTCHA form element.
*/
function captcha_process($element, $edit, &$form_state, $complete_form) {
module_load_include('inc', 'captcha');
// Prevent caching of the page with CAPTCHA elements.
// This needs to be done even if the CAPTCHA will be ommitted later:
// other untrusted users should not get a cached page when
// the current untrusted user can skip the current CAPTCHA.
global $conf;
$conf['cache'] = FALSE;
// Retrieve CAPTCHA session ID from posted data or generate it, if not available.
$this_form_id = $complete_form['form_id']['#value'];
$posted_form_id = (isset($element['#post']['form_id']) ? $element['#post']['form_id'] : NULL);
if ($this_form_id == $posted_form_id && isset($element['#post']['captcha_sid'])) {
$captcha_sid = $element['#post']['captcha_sid'];
} else {
// Generate new CAPTCHA session.
$captcha_sid = _captcha_generate_captcha_session($this_form_id, CAPTCHA_STATUS_UNSOLVED);
}
// Store CAPTCHA session ID as hidden field.
$element['captcha_sid'] = array(
'#type' => 'hidden',
'#value' => $captcha_sid,
);
// Get implementing module and challenge for CAPTCHA.
list($captcha_type_module, $captcha_type_challenge) = _captcha_parse_captcha_type($element['#captcha_type']);
if (_captcha_required_for_user($captcha_sid, $this_form_id) || $element['#captcha_admin_mode']) {
// Generate a CAPTCHA and its solution (note that the CAPTCHA session ID
// is given as thrid argument.
$captcha = module_invoke($captcha_type_module, 'captcha', 'generate', $captcha_type_challenge, $captcha_sid);
if (!$captcha) {
// The selected module returned nothing, maybe it is disabled or it's wrong, we should watchdog that and then quit.
watchdog('CAPTCHA',
'CAPTCHA problem: hook_captcha() of module %module returned nothing when trying to retrieve challenge type %type for form %form_id.',
array('%type' => $captcha_type_challenge, '%module' => $captcha_type_module, '%form_id' => $this_form_id),
WATCHDOG_ERROR);
return $element;
}
// Add form elements from challenge as children to CAPTCHA form element.
$element['captcha_widgets'] = $captcha['form'];
// Add CAPTCHA description if required:
// #description is default (NULL) and a description is set in the admin interface.
if ($element['#description'] === NULL) {
$captcha_description = _captcha_get_description();
if ($captcha_description) {
$element['#description'] = $captcha_description;
}
}
if (!$element['#captcha_admin_mode']) {
// Add a validation callback for the CAPTCHA form element.
$element['#element_validate'] = array('captcha_validate');
}
// Add pre_render callback for additional CAPTCHA processing.
$element['#pre_render'] = array('captcha_pre_render_process');
}
// Store information for usage in the validation and pre_render phase.
$element['#captcha_info'] = array(
'form_id' => $this_form_id,
'module' => $captcha_type_module,
'type' => $captcha_type_challenge,
'captcha_sid' => $captcha_sid,
'solution' => $captcha['solution'],
'preprocess' => isset($captcha['preprocess'])? $captcha['preprocess'] : FALSE,
);
return $element;
}
/**
* Theme function for a CAPTCHA element.
*
* Render it in a fieldset if a description of the CAPTCHA
* is available. Render it as is otherwise.
*/
function theme_captcha($element) {
if (!empty($element['#description'])) {
$fieldset = array(
'#type' => 'fieldset',
'#title' => t('CAPTCHA'),
'#description' => $element['#description'],
'#children' => $element['#children'],
'#attributes' => array('class' => 'captcha'),
);
return theme('fieldset', $fieldset);
}
else {
return ''. $element['#children'] .'
';
}
}
/**
* Get the CAPTCHA setting for a given form_id.
*
* @param $form_id
* @return NULL if no setting is known or a captcha_point object with fields 'module' and 'type'.
*/
function captcha_get_form_id_setting($form_id) {
$result = db_query("SELECT module, type FROM {captcha_points} WHERE form_id = '%s'", $form_id);
if (!$result) {
return NULL;
}
$captcha_point = db_fetch_object($result);
return $captcha_point;
}
/**
* Helper function for adding/updating a CAPTCHA point.
*
* @param $form_id the form ID to configure.
* @param captcha_type the setting for the given form_id,
* can be 'none' to disable CAPTCHA or something of form 'image_captcha/Image'.
* @todo captcha_get_form_id_setting and captcha_set_form_id_setting use a different way to
* communicate the CAPTCHA type (object with fields and string respectively). Make this more symmetric?
*/
function captcha_set_form_id_setting($form_id, $captcha_type) {
db_query("DELETE FROM {captcha_points} WHERE form_id = '%s'", $form_id);
if ($captcha_type == 'none') {
db_query("INSERT INTO {captcha_points} (form_id, module, type) VALUES ('%s', NULL, NULL)", $form_id);
}
else {
list($module, $type) = explode('/', $captcha_type);
db_query("INSERT INTO {captcha_points} (form_id, module, type) VALUES ('%s', '%s', '%s')", $form_id, $module, $type);
}
}
/**
* Implementation of hook_form_alter().
*
* This function adds a CAPTCHA to forms for untrusted users if needed and adds
* CAPTCHA administration links for site administrators if this option is enabled.
*/
function captcha_form_alter(&$form, $form_state, $form_id) {
if (arg(0) != 'admin') {
if (!user_access('skip CAPTCHA')) {
// Visitor does not have permission to skip the CAPTCHA
// Get CAPTCHA type and module for given form_id.
$captcha_point = captcha_get_form_id_setting($form_id);
if ($captcha_point && $captcha_point->type) {
module_load_include('inc', 'captcha');
# Build CAPTCHA form element.
$captcha_element = array(
'#type' => 'captcha',
'#captcha_type' => $captcha_point->module .'/'. $captcha_point->type,
);
# Get placement in form and insert in form.
$captcha_placement = _captcha_get_captcha_placement($form_id, $form);
_captcha_insert_captcha_element($form, $captcha_placement, $captcha_element);
}
}
else if (user_access('administer CAPTCHA settings') && variable_get('captcha_administration_mode', FALSE)) {
$captcha_point = captcha_get_form_id_setting($form_id);
// For administrators: show CAPTCHA info and offer link to configure it
$captcha_element = array(
'#type' => 'fieldset',
'#title' => t('CAPTCHA'),
'#collapsible' => TRUE,
'#collapsed' => TRUE,
);
if ($captcha_point !== NULL && $captcha_point->type) {
$captcha_element['#title'] = t('CAPTCHA: challenge "@type" enabled', array('@type' => $captcha_point->type));
$captcha_element['#description'] = t('Untrusted users will see a CAPTCHA here (!settings).',
array('!settings' => l(t('general CAPTCHA settings'), 'admin/user/captcha'))
);
$captcha_element['challenge'] = array(
'#type' => 'item',
'#title' => t('Enabled challenge'),
'#value' => t('"@type" by module "@module" (!change, !disable)', array(
'@type' => $captcha_point->type,
'@module' => $captcha_point->module,
'!change' => l(t('change'), "admin/user/captcha/captcha/captcha_point/$form_id", array('query' => drupal_get_destination())),
'!disable' => l(t('disable'), "admin/user/captcha/captcha/captcha_point/$form_id/disable", array('query' => drupal_get_destination())),
)),
);
$captcha_element['example'] = array(
'#type' => 'fieldset',
'#title' => t('Example'),
'#description' => t('This is a pre-solved, non-blocking example of this challenge.'),
);
$captcha_element['example']['example_captcha'] = array(
'#type' => 'captcha',
'#captcha_type' => $captcha_point->module .'/'. $captcha_point->type,
'#captcha_admin_mode' => TRUE,
);
} else {
$captcha_element['#title'] = t('CAPTCHA: no challenge enabled');
$captcha_element['add_captcha'] = array(
'#value' => l(t('Place a CAPTCHA here for untrusted users.'), "admin/user/captcha/captcha/captcha_point/$form_id", array('query' => drupal_get_destination()))
);
}
# Get placement in form and insert in form.
module_load_include('inc', 'captcha');
$captcha_placement = _captcha_get_captcha_placement($form_id, $form);
_captcha_insert_captcha_element($form, $captcha_placement, $captcha_element);
}
}
}
/**
* CAPTCHA validation handler.
*
* This function is placed in the main captcha.module file to make sure that
* it is available (even for cached forms, which don't fire
* captcha_form_alter(), and subsequently don't include additional include
* files).
*/
function captcha_validate($element, &$form_state) {
// Get answer and preprocess if needed
$captcha_info = $element['#captcha_info'];
$form_id = $captcha_info['form_id'];
$captcha_response = $form_state['values']['captcha_response'];
if ($captcha_info['preprocess']) {
$captcha_response = module_invoke($captcha_info['module'], 'captcha', 'preprocess', $captcha_info['type'], $captcha_response);
}
// We use $form_state['clicked_button']['#post']['captcha_sid']
// instead of $form_state['values']['captcha_sid'] because the latter
// contains the captcha_sid associated to the 'newly' generated element,
// while the former contains the captcha_sid of the posted form.
// In most cases both will be the same because of presistence.
// However, they will differ when the lifespan of the CAPTCHA session
// does not equal the lifespan of a multipage form and then we have to
// pick the right one.
$csid = $form_state['clicked_button']['#post']['captcha_sid'];
$solution = db_result(db_query('SELECT solution FROM {captcha_sessions} WHERE csid = %d AND status = %d', $csid, CAPTCHA_STATUS_UNSOLVED));
if ($solution === FALSE) {
// Unknown challenge_id.
form_set_error('captcha', t('CAPTCHA test failed (unknown csid).'));
}
else {
// Check answer.
if ($captcha_response == $solution) {
// Correct answer.
$_SESSION['captcha_success_form_ids'][$form_id] = $form_id;
// Record success.
db_query("UPDATE {captcha_sessions} SET status=%d, attempts=attempts+1 WHERE csid=%d", CAPTCHA_STATUS_SOLVED, $csid);
}
else {
// Wrong answer.
db_query("UPDATE {captcha_sessions} SET attempts=attempts+1 WHERE csid=%d", $csid);
// set form error
form_set_error('captcha_response', t('The answer you entered for the CAPTCHA was not correct.'));
// update wrong response counter
variable_set('captcha_wrong_response_counter', variable_get('captcha_wrong_response_counter', 0) + 1);
// log to watchdog if needed
if (variable_get('captcha_log_wrong_responses', FALSE)) {
watchdog('CAPTCHA',
'%form_id post blocked by CAPTCHA module: challenge "%challenge" (by module "%module"), user answered "%response", but the solution was "%solution".',
array('%form_id' => $form_id,
'%response' => $captcha_response, '%solution' => $solution,
'%challenge' => $captcha_info['type'], '%module' => $captcha_info['module'],
),
WATCHDOG_NOTICE);
}
// If CAPTCHA was on a login form: stop validating, quit the current request
// and forward to the current page (like a reload) to prevent loging in.
// We do that because the log in procedure, which happens after
// captcha_validate(), does not check error conditions of extra form
// elements like the CAPTCHA.
if ($form_id == 'user_login' || $form_id == 'user_login_block') {
drupal_goto($_GET['q']);
}
}
}
}
/**
* Pre-render callback for additional processing of a CAPTCHA form element.
*
* This encompasses tasks that should happen after the general FAPI processing
* (building, submission and validation) but before rendering (e.g. storing the solution).
*
* @param $element the CAPTCHA form element
* @return the manipulated element
*/
function captcha_pre_render_process($element) {
// Get form and CAPTCHA information.
$captcha_info = $element['#captcha_info'];
$form_id = $captcha_info['form_id'];
$captcha_sid = (int)($captcha_info['captcha_sid']);
// Check if CAPTCHA is still required.
// This check is done in a first phase during the element processing
// (@see captcha_process), but it is also done here for better support
// of multi-page forms. Take previewing a node submission for example:
// when the challenge is solved correctely on preview, the form is still
// not completely submitted, but the CAPTCHA can be skipped.
if (_captcha_required_for_user($captcha_sid, $form_id) || $element['#captcha_admin_mode']) {
// Update captcha_sessions table: store the solution of the generated CAPTCHA.
_captcha_update_captcha_session($captcha_sid, $captcha_info['solution']);
if (!$element['#captcha_admin_mode']) {
// Empty the value of the captcha_response form item before rendering
$element['captcha_widgets']['captcha_response']['#value'] = '';
}
else {
$element['captcha_widgets']['captcha_response']['#value'] = $captcha_info['solution'];
}
}
else {
// Remove CAPTCHA widgets from form.
unset($element['captcha_widgets']);
}
return $element;
}
/**
* Default implementation of hook_captcha().
*/
function captcha_captcha($op, $captcha_type = '') {
switch ($op) {
case 'list':
return array('Math');
break;
case 'generate':
if ($captcha_type == 'Math') {
$result = array();
$answer = mt_rand(1, 20);
$x = mt_rand(1, $answer);
$y = $answer - $x;
$result['solution'] = "$answer";
// Build challenge widget.
// Note that we also use t() for the math challenge itself. This makes
// it possible to 'rephrase' the challenge a bit through localization
// or string overrides.
$result['form']['captcha_response'] = array(
'#type' => 'textfield',
'#title' => t('Math Question'),
'#description' => t('Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.'),
'#field_prefix' => t('@x + @y = ', array('@x' => $x, '@y' => $y)),
'#size' => 4,
'#maxlength' => 2,
'#required' => TRUE,
);
return $result;
}
break;
}
}