View source
<?php
define('WORD_LIST_CAPTCHA_WORD_POOL1', 'green red blue yellow black white magenta cyan orange violet purple gold brown pink');
define('WORD_LIST_CAPTCHA_WORD_POOL2', 'bird elephant dog cat crocodile lion fish cow horse sheep frog beetle worm spider bat giraffe lizard goat monkey rabbit chimpanzee');
function word_list_captcha_help($path, $arg) {
switch ($path) {
case 'admin/config/people/captcha/word_list_captcha':
return '<p>' . t('The unrelated word CAPTCHA consists of a list of closely related words with one non-related word, which the user has to select. To generate this list, two word pools are needed: one for the related words and one for the non-related word.') . '</p>';
}
}
function _word_list_captcha_get_word_list_captcha($list_size) {
if (mt_rand(0, 1)) {
$normal_words = _text_captcha_word_pool_get_content('word_list_captcha_word_pool_1', NULL, WORD_LIST_CAPTCHA_WORD_POOL1, TRUE);
$other_words = _text_captcha_word_pool_get_content('word_list_captcha_word_pool_2', NULL, WORD_LIST_CAPTCHA_WORD_POOL2, TRUE);
}
else {
$normal_words = _text_captcha_word_pool_get_content('word_list_captcha_word_pool_2', NULL, WORD_LIST_CAPTCHA_WORD_POOL2, TRUE);
$other_words = _text_captcha_word_pool_get_content('word_list_captcha_word_pool_1', NULL, WORD_LIST_CAPTCHA_WORD_POOL1, TRUE);
}
shuffle($normal_words);
$word_list = array_slice($normal_words, 0, $list_size - 1);
$wrong_word = $other_words[array_rand($other_words)];
$word_list[] = $wrong_word;
shuffle($word_list);
return [
$word_list,
$wrong_word,
];
}
function word_list_captcha_captcha($op, $captcha_type = '') {
$config = \Drupal::config('word_list_captcha.settings');
switch ($op) {
case 'list':
return [
'Pick the unrelated word',
];
case 'generate':
if ($captcha_type == 'Pick the unrelated word') {
$list_size = $config
->get('word_list_captcha_list_size');
list($word_list, $wrong_word) = _word_list_captcha_get_word_list_captcha($list_size);
$options = [];
foreach ($word_list as $word) {
$options[$word] = $word;
}
$captcha = [];
$captcha['solution'] = $wrong_word;
$captcha['form']['captcha_response'] = [
'#type' => 'radios',
'#title' => t('Which word does not belong to the list?'),
'#options' => $options,
'#attributes' => [
'class' => [
'text-captcha-word-list-radios',
],
],
'#DANGEROUS_SKIP_CHECK' => TRUE,
'#required' => TRUE,
'#cache' => [
'max-age' => 0,
],
];
\Drupal::service('page_cache_kill_switch')
->trigger();
$captcha['form']['captcha_response']['#attached']['library'][] = 'text_captcha/base';
return $captcha;
}
}
}