6 * @copyright (c) 2006, 2008 phpBB Group
7 * @license http://opensource.org/licenses/gpl-license.php GNU Public License
14 if (!defined('IN_PHPBB'))
21 define('CAPTCHA_QUESTIONS_TABLE', $table_prefix . 'captcha_questions');
22 define('CAPTCHA_ANSWERS_TABLE', $table_prefix . 'captcha_answers');
23 define('CAPTCHA_QA_CONFIRM_TABLE', $table_prefix . 'qa_confirm');
26 * And now to something completely different. Let's make a captcha without extending the abstract class.
27 * QA CAPTCHA sample implementation
31 class phpbb_captcha_qa
41 // dirty trick: 0 is false, but can still encode that the captcha is not yet validated
45 * @param int $type as per the CAPTCHA API docs, the type
49 global $config, $db, $user;
51 // load our language file
52 $user->add_lang('captcha_qa');
55 $this->confirm_id = request_var('qa_confirm_id', '');
56 $this->answer = utf8_normalize_nfc(request_var('qa_answer', '', true));
58 $this->type = (int) $type;
59 $this->question_lang = $user->lang_name;
61 // we need all defined questions - shouldn't be too many, so we can just grab them
62 // try the user's lang first
63 $sql = 'SELECT question_id
64 FROM ' . CAPTCHA_QUESTIONS_TABLE . "
65 WHERE lang_iso = '" . $db->sql_escape($user->lang_name) . "'";
66 $result = $db->sql_query($sql, 3600);
68 while ($row = $db->sql_fetchrow($result))
70 $this->question_ids[$row['question_id']] = $row['question_id'];
72 $db->sql_freeresult($result);
74 // fallback to the board default lang
75 if (!sizeof($this->question_ids))
77 $this->question_lang = $config['default_lang'];
79 $sql = 'SELECT question_id
80 FROM ' . CAPTCHA_QUESTIONS_TABLE . "
81 WHERE lang_iso = '" . $db->sql_escape($config['default_lang']) . "'";
82 $result = $db->sql_query($sql, 7200);
84 while ($row = $db->sql_fetchrow($result))
86 $this->question_ids[$row['question_id']] = $row['question_id'];
88 $db->sql_freeresult($result);
91 // okay, if there is a confirm_id, we try to load that confirm's state. If not, we try to find one
92 if (!$this->load_answer() && (!$this->load_confirm_id() || !$this->load_answer()))
94 // we have no valid confirm ID, better get ready to ask something
95 $this->select_question();
102 function &get_instance()
104 $instance =& new phpbb_captcha_qa();
110 * See if the captcha has created its tables.
112 function is_installed()
114 global $db, $phpbb_root_path, $phpEx;
116 if (!class_exists('phpbb_db_tools'))
118 include("$phpbb_root_path/includes/db/db_tools.$phpEx");
120 $db_tool = new phpbb_db_tools($db);
122 return $db_tool->sql_table_exists(CAPTCHA_QUESTIONS_TABLE);
126 * API function - for the captcha to be available, it must have installed itself and there has to be at least one question in the board's default lang
128 function is_available()
130 global $config, $db, $phpbb_root_path, $phpEx, $user;
132 // load language file for pretty display in the ACP dropdown
133 $user->add_lang('captcha_qa');
135 if (!phpbb_captcha_qa::is_installed())
140 $sql = 'SELECT COUNT(question_id) AS question_count
141 FROM ' . CAPTCHA_QUESTIONS_TABLE . "
142 WHERE lang_iso = '" . $db->sql_escape($config['default_lang']) . "'";
143 $result = $db->sql_query($sql);
144 $row = $db->sql_fetchrow($result);
145 $db->sql_freeresult($result);
147 return ((bool) $row['question_count']);
153 function has_config()
169 function get_class_name()
171 return 'phpbb_captcha_qa';
175 * API function - not needed as we don't display an image
177 function execute_demo()
182 * API function - not needed as we don't display an image
189 * API function - send the question to the template
191 function get_template()
195 if ($this->is_solved())
201 $template->assign_vars(array(
202 'QA_CONFIRM_QUESTION' => $this->question_text,
203 'QA_CONFIRM_ID' => $this->confirm_id,
204 'S_CONFIRM_CODE' => true,
205 'S_TYPE' => $this->type,
208 return 'captcha_qa.html';
213 * API function - we just display a mockup so that the captcha doesn't need to be installed
215 function get_demo_template()
217 global $config, $db, $template;
219 if ($this->is_available())
221 $sql = 'SELECT question_text
222 FROM ' . CAPTCHA_QUESTIONS_TABLE . "
223 WHERE lang_iso = '" . $db->sql_escape($config['default_lang']) . "'";
224 $result = $db->sql_query_limit($sql, 1);
225 if ($row = $db->sql_fetchrow($result))
227 $template->assign_vars(array(
228 'QA_CONFIRM_QUESTION' => $row['question_text'],
231 $db->sql_freeresult($result);
233 return 'captcha_qa_acp_demo.html';
239 function get_hidden_fields()
241 $hidden_fields = array();
243 // this is required - otherwise we would forget about the captcha being already solved
246 $hidden_fields['qa_answer'] = $this->answer;
248 $hidden_fields['qa_confirm_id'] = $this->confirm_id;
250 return $hidden_fields;
256 function garbage_collect($type = 0)
260 $sql = 'SELECT c.confirm_id
261 FROM ' . CAPTCHA_QA_CONFIRM_TABLE . ' c
262 LEFT JOIN ' . SESSIONS_TABLE . ' s
263 ON (c.session_id = s.session_id)
264 WHERE s.session_id IS NULL' .
265 ((empty($type)) ? '' : ' AND c.confirm_type = ' . (int) $type);
266 $result = $db->sql_query($sql);
268 if ($row = $db->sql_fetchrow($result))
274 $sql_in[] = (string) $row['confirm_id'];
276 while ($row = $db->sql_fetchrow($result));
280 $sql = 'DELETE FROM ' . CAPTCHA_QA_CONFIRM_TABLE . '
281 WHERE ' . $db->sql_in_set('confirm_id', $sql_in);
282 $db->sql_query($sql);
285 $db->sql_freeresult($result);
289 * API function - we don't drop the tables here, as that would cause the loss of all entered questions.
293 $this->garbage_collect(0);
297 * API function - set up shop
301 global $db, $phpbb_root_path, $phpEx;
303 if (!class_exists('phpbb_db_tools'))
305 include("$phpbb_root_path/includes/db/db_tools.$phpEx");
307 $db_tool = new phpbb_db_tools($db);
309 $tables = array(CAPTCHA_QUESTIONS_TABLE, CAPTCHA_ANSWERS_TABLE, CAPTCHA_QA_CONFIRM_TABLE);
312 CAPTCHA_QUESTIONS_TABLE => array (
314 'question_id' => array('UINT', Null, 'auto_increment'),
315 'strict' => array('BOOL', 0),
316 'lang_id' => array('UINT', 0),
317 'lang_iso' => array('VCHAR:30', ''),
318 'question_text' => array('TEXT_UNI', ''),
320 'PRIMARY_KEY' => 'question_id',
322 'lang' => array('INDEX', 'lang_iso'),
325 CAPTCHA_ANSWERS_TABLE => array (
327 'question_id' => array('UINT', 0),
328 'answer_text' => array('STEXT_UNI', ''),
331 'qid' => array('INDEX', 'question_id'),
334 CAPTCHA_QA_CONFIRM_TABLE => array (
336 'session_id' => array('CHAR:32', ''),
337 'confirm_id' => array('CHAR:32', ''),
338 'lang_iso' => array('VCHAR:30', ''),
339 'question_id' => array('UINT', 0),
340 'attempts' => array('UINT', 0),
341 'confirm_type' => array('USINT', 0),
344 'session_id' => array('INDEX', 'session_id'),
345 'lookup' => array('INDEX', array('confirm_id', 'session_id', 'lang_iso')),
347 'PRIMARY_KEY' => 'confirm_id',
351 foreach($schemas as $table => $schema)
353 if (!$db_tool->sql_table_exists($table))
355 $db_tool->sql_create_table($table, $schema);
361 * API function - see what has to be done to validate
365 global $config, $db, $user;
369 if (!sizeof($this->question_ids))
374 if (!$this->confirm_id)
376 $error = $user->lang['CONFIRM_QUESTION_WRONG'];
380 if ($this->check_answer())
382 // $this->delete_code(); commented out to allow posting.php to repeat the question
383 $this->solved = true;
387 $error = $user->lang['CONFIRM_QUESTION_WRONG'];
393 // okay, incorrect answer. Let's ask a new question.
394 $this->new_attempt();
395 $this->solved = false;
408 function select_question()
412 if (!sizeof($this->question_ids))
416 $this->confirm_id = md5(unique_id($user->ip));
417 $this->question = (int) array_rand($this->question_ids);
419 $sql = 'INSERT INTO ' . CAPTCHA_QA_CONFIRM_TABLE . ' ' . $db->sql_build_array('INSERT', array(
420 'confirm_id' => (string) $this->confirm_id,
421 'session_id' => (string) $user->session_id,
422 'lang_iso' => (string) $this->question_lang,
423 'confirm_type' => (int) $this->type,
424 'question_id' => (int) $this->question,
426 $db->sql_query($sql);
428 $this->load_answer();
432 * New Question, if desired.
434 function reselect_question()
438 if (!sizeof($this->question_ids))
443 $this->question = (int) array_rand($this->question_ids);
446 $sql = 'UPDATE ' . CAPTCHA_QA_CONFIRM_TABLE . '
447 SET question_id = ' . (int) $this->question . "
448 WHERE confirm_id = '" . $db->sql_escape($this->confirm_id) . "'
449 AND session_id = '" . $db->sql_escape($user->session_id) . "'";
450 $db->sql_query($sql);
452 $this->load_answer();
456 * Wrong answer, so we increase the attempts and use a different question.
458 function new_attempt()
462 // yah, I would prefer a stronger rand, but this should work
463 $this->question = (int) array_rand($this->question_ids);
466 $sql = 'UPDATE ' . CAPTCHA_QA_CONFIRM_TABLE . '
467 SET question_id = ' . (int) $this->question . ",
468 attempts = attempts + 1
469 WHERE confirm_id = '" . $db->sql_escape($this->confirm_id) . "'
470 AND session_id = '" . $db->sql_escape($user->session_id) . "'";
471 $db->sql_query($sql);
473 $this->load_answer();
478 * See if there is already an entry for the current session.
480 function load_confirm_id()
484 $sql = 'SELECT confirm_id
485 FROM ' . CAPTCHA_QA_CONFIRM_TABLE . "
487 session_id = '" . $db->sql_escape($user->session_id) . "'
488 AND lang_iso = '" . $db->sql_escape($this->question_lang) . "'
489 AND confirm_type = " . $this->type;
490 $result = $db->sql_query_limit($sql, 1);
491 $row = $db->sql_fetchrow($result);
492 $db->sql_freeresult($result);
496 $this->confirm_id = $row['confirm_id'];
503 * Look up everything we need and populate the instance variables.
505 function load_answer()
509 if (!strlen($this->confirm_id) || !sizeof($this->question_ids))
514 $sql = 'SELECT con.question_id, attempts, question_text, strict
515 FROM ' . CAPTCHA_QA_CONFIRM_TABLE . ' con, ' . CAPTCHA_QUESTIONS_TABLE . " qes
516 WHERE con.question_id = qes.question_id
517 AND confirm_id = '" . $db->sql_escape($this->confirm_id) . "'
518 AND session_id = '" . $db->sql_escape($user->session_id) . "'
519 AND qes.lang_iso = '" . $db->sql_escape($this->question_lang) . "'
520 AND confirm_type = " . $this->type;
521 $result = $db->sql_query($sql);
522 $row = $db->sql_fetchrow($result);
523 $db->sql_freeresult($result);
527 $this->question = $row['question_id'];
529 $this->attempts = $row['attempts'];
530 $this->question_strict = $row['strict'];
531 $this->question_text = $row['question_text'];
540 * The actual validation
542 function check_answer()
546 $answer = ($this->question_strict) ? utf8_normalize_nfc(request_var('qa_answer', '', true)) : utf8_clean_string(utf8_normalize_nfc(request_var('qa_answer', '', true)));
548 $sql = 'SELECT answer_text
549 FROM ' . CAPTCHA_ANSWERS_TABLE . '
550 WHERE question_id = ' . (int) $this->question;
551 $result = $db->sql_query($sql);
553 while ($row = $db->sql_fetchrow($result))
555 $solution = ($this->question_strict) ? $row['answer_text'] : utf8_clean_string($row['answer_text']);
557 if ($solution === $answer)
559 $this->solved = true;
564 $db->sql_freeresult($result);
566 return $this->solved;
570 * API function - clean the entry
572 function delete_code()
576 $sql = 'DELETE FROM ' . CAPTCHA_QA_CONFIRM_TABLE . "
577 WHERE confirm_id = '" . $db->sql_escape($confirm_id) . "'
578 AND session_id = '" . $db->sql_escape($user->session_id) . "'
579 AND confirm_type = " . $this->type;
580 $db->sql_query($sql);
586 function get_attempt_count()
588 return $this->attempts;
598 $sql = 'DELETE FROM ' . CAPTCHA_QA_CONFIRM_TABLE . "
599 WHERE session_id = '" . $db->sql_escape($user->session_id) . "'
600 AND confirm_type = " . (int) $this->type;
601 $db->sql_query($sql);
603 // we leave the class usable by generating a new question
604 $this->select_question();
612 if (request_var('qa_answer', false) && $this->solved === 0)
617 return (bool) $this->solved;
621 * API function - The ACP backend, this marks the end of the easy methods
623 function acp_page($id, &$module)
625 global $db, $user, $auth, $template;
626 global $config, $phpbb_root_path, $phpbb_admin_path, $phpEx;
628 $user->add_lang('acp/board');
629 $user->add_lang('captcha_qa');
631 if (!$this->is_installed())
636 $module->tpl_name = 'captcha_qa_acp';
637 $module->page_title = 'ACP_VC_SETTINGS';
638 $form_key = 'acp_captcha';
639 add_form_key($form_key);
641 $submit = request_var('submit', false);
642 $question_id = request_var('question_id', 0);
643 $action = request_var('action', '');
645 // we have two pages, so users might want to navigate from one to the other
646 $list_url = $module->u_action . "&configure=1&select_captcha=" . $this->get_class_name();
648 $template->assign_vars(array(
649 'U_ACTION' => $module->u_action,
650 'QUESTION_ID' => $question_id ,
651 'CLASS' => $this->get_class_name(),
655 if (!$question_id && $action != 'add')
657 $this->acp_question_list($module);
659 else if ($question_id && $action == 'delete')
661 if ($this->get_class_name() !== $config['captcha_plugin'] || !$this->acp_is_last($question_id))
663 if (confirm_box(true))
665 $this->acp_delete_question($question_id);
667 trigger_error($user->lang['QUESTION_DELETED'] . adm_back_link($list_url));
671 confirm_box(false, $user->lang['CONFIRM_OPERATION'], build_hidden_fields(array(
672 'question_id' => $question_id,
675 'select_captcha' => $this->get_class_name(),
682 trigger_error($user->lang['QA_LAST_QUESTION'] . adm_back_link($list_url), E_USER_WARNING);
687 // okay, show the editor
689 $input_question = request_var('question_text', '', true);
690 $input_answers = request_var('answers', '', true);
691 $input_lang = request_var('lang_iso', '', true);
692 $input_strict = request_var('strict', false);
693 $langs = $this->get_languages();
695 foreach ($langs as $lang => $entry)
697 $template->assign_block_vars('langs', array(
699 'NAME' => $entry['name'],
703 $template->assign_vars(array(
704 'U_LIST' => $list_url,
709 if ($question = $this->acp_get_question_data($question_id))
711 $answers = (isset($input_answers[$lang])) ? $input_answers[$lang] : implode("\n", $question['answers']);
713 $template->assign_vars(array(
714 'QUESTION_TEXT' => ($input_question) ? $input_question : $question['question_text'],
715 'LANG_ISO' => ($input_lang) ? $input_lang : $question['lang_iso'],
716 'STRICT' => (isset($_REQUEST['strict'])) ? $input_strict : $question['strict'],
717 'ANSWERS' => $answers,
722 trigger_error($user->lang['FORM_INVALID'] . adm_back_link($list_url));
727 $template->assign_vars(array(
728 'QUESTION_TEXT' => $input_question,
729 'LANG_ISO' => $input_lang,
730 'STRICT' => $input_strict,
731 'ANSWERS' => $input_answers,
735 if ($submit && check_form_key($form_key))
737 $data = $this->acp_get_question_input();
739 if (!$this->validate_input($data))
741 $template->assign_vars(array(
749 $this->acp_update_question($data, $question_id);
753 $this->acp_add_question($data);
756 add_log('admin', 'LOG_CONFIG_VISUAL');
757 trigger_error($user->lang['CONFIG_UPDATED'] . adm_back_link($list_url));
762 trigger_error($user->lang['FORM_INVALID'] . adm_back_link($list_url), E_USER_WARNING);
768 * This handles the list overview
770 function acp_question_list(&$module)
772 global $db, $template;
775 FROM ' . CAPTCHA_QUESTIONS_TABLE;
776 $result = $db->sql_query($sql);
778 $template->assign_vars(array(
782 while ($row = $db->sql_fetchrow($result))
784 $url = $module->u_action . "&question_id={$row['question_id']}&configure=1&select_captcha=" . $this->get_class_name() . '&';
786 $template->assign_block_vars('questions', array(
787 'QUESTION_TEXT' => $row['question_text'],
788 'QUESTION_ID' => $row['question_id'],
789 'QUESTION_LANG' => $row['lang_iso'],
790 'U_DELETE' => "{$url}action=delete",
791 'U_EDIT' => "{$url}action=edit",
794 $db->sql_freeresult($result);
798 * Grab a question and bring it into a format the editor understands
800 function acp_get_question_data($question_id)
807 FROM ' . CAPTCHA_QUESTIONS_TABLE . '
808 WHERE question_id = ' . $question_id;
809 $result = $db->sql_query($sql);
810 $question = $db->sql_fetchrow($result);
811 $db->sql_freeresult($result);
818 $question['answers'] = array();
821 FROM ' . CAPTCHA_ANSWERS_TABLE . '
822 WHERE question_id = ' . $question_id;
823 $result = $db->sql_query($sql);
825 while ($row = $db->sql_fetchrow($result))
827 $question['answers'][] = $row['answer_text'];
829 $db->sql_freeresult($result);
836 * Grab a question from input and bring it into a format the editor understands
838 function acp_get_question_input()
840 $answers = utf8_normalize_nfc(request_var('answers', '', true));
842 'question_text' => request_var('question_text', '', true),
843 'strict' => request_var('strict', false),
844 'lang_iso' => request_var('lang_iso', ''),
845 'answers' => (strlen($answers)) ? explode("\n", $answers) : '',
853 * param mixed $data : an array as created from acp_get_question_input or acp_get_question_data
855 function acp_update_question($data, $question_id)
859 // easier to delete all answers than to figure out which to update
860 $sql = 'DELETE FROM ' . CAPTCHA_ANSWERS_TABLE . " WHERE question_id = $question_id";
861 $db->sql_query($sql);
863 $langs = $this->get_languages();
864 $question_ary = $data;
865 $question_ary['lang_id'] = $langs[$question_ary['lang_iso']]['id'];
866 unset($question_ary['answers']);
868 $sql = 'UPDATE ' . CAPTCHA_QUESTIONS_TABLE . '
869 SET ' . $db->sql_build_array('UPDATE', $question_ary) . "
870 WHERE question_id = $question_id";
871 $db->sql_query($sql);
873 $this->acp_insert_answers($data, $question_id);
875 $cache->destroy('sql', CAPTCHA_QUESTIONS_TABLE);
880 * param mixed $data : an array as created from acp_get_question_input or acp_get_question_data
882 function acp_add_question($data)
886 $langs = $this->get_languages();
887 $question_ary = $data;
889 $question_ary['lang_id'] = $langs[$data['lang_iso']]['id'];
890 unset($question_ary['answers']);
892 $sql = 'INSERT INTO ' . CAPTCHA_QUESTIONS_TABLE . ' ' . $db->sql_build_array('INSERT', $question_ary);
893 $db->sql_query($sql);
895 $question_id = $db->sql_nextid();
897 $this->acp_insert_answers($data, $question_id);
899 $cache->destroy('sql', CAPTCHA_QUESTIONS_TABLE);
903 * Insert the answers.
904 * param mixed $data : an array as created from acp_get_question_input or acp_get_question_data
906 function acp_insert_answers($data, $question_id)
910 foreach ($data['answers'] as $answer)
913 'question_id' => $question_id,
914 'answer_text' => $answer,
917 $sql = 'INSERT INTO ' . CAPTCHA_ANSWERS_TABLE . ' ' . $db->sql_build_array('INSERT', $answer_ary);
918 $db->sql_query($sql);
921 $cache->destroy('sql', CAPTCHA_ANSWERS_TABLE);
927 function acp_delete_question($question_id)
931 $tables = array(CAPTCHA_QUESTIONS_TABLE, CAPTCHA_ANSWERS_TABLE);
933 foreach ($tables as $table)
935 $sql = "DELETE FROM $table
936 WHERE question_id = $question_id";
937 $db->sql_query($sql);
940 $cache->destroy('sql', $tables);
944 * Check if the entered data can be inserted/used
945 * param mixed $data : an array as created from acp_get_question_input or acp_get_question_data
947 function validate_input($question_data)
949 $langs = $this->get_languages();
951 if (!isset($question_data['lang_iso']) ||
952 !isset($question_data['question_text']) ||
953 !isset($question_data['strict']) ||
954 !isset($question_data['answers']))
959 if (!isset($langs[$question_data['lang_iso']]) ||
960 !strlen($question_data['question_text']) ||
961 !sizeof($question_data['answers']) ||
962 !is_array($question_data['answers']))
971 * List the installed language packs
973 function get_languages()
979 $result = $db->sql_query($sql);
982 while ($row = $db->sql_fetchrow($result))
984 $langs[$row['lang_iso']] = array(
985 'name' => $row['lang_local_name'],
986 'id' => (int) $row['lang_id'],
989 $db->sql_freeresult($result);
997 * See if there is a question other than the one we have
999 function acp_is_last($question_id)
1001 global $config, $db;
1005 $sql = 'SELECT question_id
1006 FROM ' . CAPTCHA_QUESTIONS_TABLE . "
1007 WHERE lang_iso = '" . $db->sql_escape($config['default_lang']) . "'
1008 AND question_id <> " . (int) $question_id;
1009 $result = $db->sql_query_limit($sql, 1);
1010 $question = $db->sql_fetchrow($result);
1011 $db->sql_freeresult($result);