* @license GNU General Public License, version 2 (GPL-2.0) * * For full copyright and license information, please see * the docs/CREDITS.txt file. * */ /** * @ignore */ if (!defined('IN_PHPBB')) { exit; } global $table_prefix; define('CAPTCHA_QUESTIONS_TABLE', $table_prefix . 'captcha_questions'); define('CAPTCHA_ANSWERS_TABLE', $table_prefix . 'captcha_answers'); define('CAPTCHA_QA_CONFIRM_TABLE', $table_prefix . 'qa_confirm'); /** * And now to something completely different. Let's make a captcha without extending the abstract class. * QA CAPTCHA sample implementation */ class phpbb_captcha_qa { var $confirm_id; var $answer; var $question_ids; var $question_text; var $question_lang; var $question_strict; var $attempts = 0; var $type; // dirty trick: 0 is false, but can still encode that the captcha is not yet validated var $solved = 0; /** * @param int $type as per the CAPTCHA API docs, the type */ function init($type) { global $config, $db, $user; // load our language file $user->add_lang('captcha_qa'); // read input $this->confirm_id = request_var('qa_confirm_id', ''); $this->answer = utf8_normalize_nfc(request_var('qa_answer', '', true)); $this->type = (int) $type; $this->question_lang = $user->lang_name; // we need all defined questions - shouldn't be too many, so we can just grab them // try the user's lang first $sql = 'SELECT question_id FROM ' . CAPTCHA_QUESTIONS_TABLE . " WHERE lang_iso = '" . $db->sql_escape($user->lang_name) . "'"; $result = $db->sql_query($sql, 3600); while ($row = $db->sql_fetchrow($result)) { $this->question_ids[$row['question_id']] = $row['question_id']; } $db->sql_freeresult($result); // fallback to the board default lang if (!sizeof($this->question_ids)) { $this->question_lang = $config['default_lang']; $sql = 'SELECT question_id FROM ' . CAPTCHA_QUESTIONS_TABLE . " WHERE lang_iso = '" . $db->sql_escape($config['default_lang']) . "'"; $result = $db->sql_query($sql, 7200); while ($row = $db->sql_fetchrow($result)) { $this->question_ids[$row['question_id']] = $row['question_id']; } $db->sql_freeresult($result); } // okay, if there is a confirm_id, we try to load that confirm's state. If not, we try to find one if (!$this->load_answer() && (!$this->load_confirm_id() || !$this->load_answer())) { // we have no valid confirm ID, better get ready to ask something $this->select_question(); } } /** * API function */ static public function get_instance() { $instance = new phpbb_captcha_qa(); return $instance; } /** * See if the captcha has created its tables. */ static public function is_installed() { global $db; $db_tool = new \phpbb\db\tools($db); return $db_tool->sql_table_exists(CAPTCHA_QUESTIONS_TABLE); } /** * 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 */ static public function is_available() { global $config, $db, $phpbb_root_path, $phpEx, $user; // load language file for pretty display in the ACP dropdown $user->add_lang('captcha_qa'); if (!self::is_installed()) { return false; } $sql = 'SELECT COUNT(question_id) AS question_count FROM ' . CAPTCHA_QUESTIONS_TABLE . " WHERE lang_iso = '" . $db->sql_escape($config['default_lang']) . "'"; $result = $db->sql_query($sql); $row = $db->sql_fetchrow($result); $db->sql_freeresult($result); return ((bool) $row['question_count']); } /** * API function */ function has_config() { return true; } /** * API function */ static public function get_name() { return 'CAPTCHA_QA'; } /** * API function */ function get_class_name() { return 'phpbb_captcha_qa'; } /** * API function - not needed as we don't display an image */ function execute_demo() { } /** * API function - not needed as we don't display an image */ function execute() { } /** * API function - send the question to the template */ function get_template() { global $template; if ($this->is_solved()) { return false; } else { $template->assign_vars(array( 'QA_CONFIRM_QUESTION' => $this->question_text, 'QA_CONFIRM_ID' => $this->confirm_id, 'S_CONFIRM_CODE' => true, 'S_TYPE' => $this->type, )); return 'captcha_qa.html'; } } /** * API function - we just display a mockup so that the captcha doesn't need to be installed */ function get_demo_template() { global $config, $db, $template; if ($this->is_available()) { $sql = 'SELECT question_text FROM ' . CAPTCHA_QUESTIONS_TABLE . " WHERE lang_iso = '" . $db->sql_escape($config['default_lang']) . "'"; $result = $db->sql_query_limit($sql, 1); if ($row = $db->sql_fetchrow($result)) { $template->assign_vars(array( 'QA_CONFIRM_QUESTION' => $row['question_text'], )); } $db->sql_freeresult($result); } return 'captcha_qa_acp_demo.html'; } /** * API function */ function get_hidden_fields() { $hidden_fields = array(); // this is required - otherwise we would forget about the captcha being already solved if ($this->solved) { $hidden_fields['qa_answer'] = $this->answer; } $hidden_fields['qa_confirm_id'] = $this->confirm_id; return $hidden_fields; } /** * API function */ function garbage_collect($type = 0) { global $db, $config; $sql = 'SELECT c.confirm_id FROM ' . CAPTCHA_QA_CONFIRM_TABLE . ' c LEFT JOIN ' . SESSIONS_TABLE . ' s ON (c.session_id = s.session_id) WHERE s.session_id IS NULL' . ((empty($type)) ? '' : ' AND c.confirm_type = ' . (int) $type); $result = $db->sql_query($sql); if ($row = $db->sql_fetchrow($result)) { $sql_in = array(); do { $sql_in[] = (string) $row['confirm_id']; } while ($row = $db->sql_fetchrow($result)); if (sizeof($sql_in)) { $sql = 'DELETE FROM ' . CAPTCHA_QA_CONFIRM_TABLE . ' WHERE ' . $db->sql_in_set('confirm_id', $sql_in); $db->sql_query($sql); } } $db->sql_freeresult($result); } /** * API function - we don't drop the tables here, as that would cause the loss of all entered questions. */ function uninstall() { $this->garbage_collect(0); } /** * API function - set up shop */ function install() { global $db; $db_tool = new \phpbb\db\tools($db); $tables = array(CAPTCHA_QUESTIONS_TABLE, CAPTCHA_ANSWERS_TABLE, CAPTCHA_QA_CONFIRM_TABLE); $schemas = array( CAPTCHA_QUESTIONS_TABLE => array ( 'COLUMNS' => array( 'question_id' => array('UINT', Null, 'auto_increment'), 'strict' => array('BOOL', 0), 'lang_id' => array('UINT', 0), 'lang_iso' => array('VCHAR:30', ''), 'question_text' => array('TEXT_UNI', ''), ), 'PRIMARY_KEY' => 'question_id', 'KEYS' => array( 'lang' => array('INDEX', 'lang_iso'), ), ), CAPTCHA_ANSWERS_TABLE => array ( 'COLUMNS' => array( 'question_id' => array('UINT', 0), 'answer_text' => array('STEXT_UNI', ''), ), 'KEYS' => array( 'qid' => array('INDEX', 'question_id'), ), ), CAPTCHA_QA_CONFIRM_TABLE => array ( 'COLUMNS' => array( 'session_id' => array('CHAR:32', ''), 'confirm_id' => array('CHAR:32', ''), 'lang_iso' => array('VCHAR:30', ''), 'question_id' => array('UINT', 0), 'attempts' => array('UINT', 0), 'confirm_type' => array('USINT', 0), ), 'KEYS' => array( 'session_id' => array('INDEX', 'session_id'), 'lookup' => array('INDEX', array('confirm_id', 'session_id', 'lang_iso')), ), 'PRIMARY_KEY' => 'confirm_id', ), ); foreach($schemas as $table => $schema) { if (!$db_tool->sql_table_exists($table)) { $db_tool->sql_create_table($table, $schema); } } } /** * API function - see what has to be done to validate */ function validate() { global $config, $db, $user; $error = ''; if (!sizeof($this->question_ids)) { return false; } if (!$this->confirm_id) { $error = $user->lang['CONFIRM_QUESTION_WRONG']; } else { if ($this->check_answer()) { $this->solved = true; } else { $error = $user->lang['CONFIRM_QUESTION_WRONG']; } } if (strlen($error)) { // okay, incorrect answer. Let's ask a new question. $this->new_attempt(); $this->solved = false; return $error; } else { return false; } } /** * Select a question */ function select_question() { global $db, $user; if (!sizeof($this->question_ids)) { return false; } $this->confirm_id = md5(unique_id($user->ip)); $this->question = (int) array_rand($this->question_ids); $sql = 'INSERT INTO ' . CAPTCHA_QA_CONFIRM_TABLE . ' ' . $db->sql_build_array('INSERT', array( 'confirm_id' => (string) $this->confirm_id, 'session_id' => (string) $user->session_id, 'lang_iso' => (string) $this->question_lang, 'confirm_type' => (int) $this->type, 'question_id' => (int) $this->question, )); $db->sql_query($sql); $this->load_answer(); } /** * New Question, if desired. */ function reselect_question() { global $db, $user; if (!sizeof($this->question_ids)) { return false; } $this->question = (int) array_rand($this->question_ids); $this->solved = 0; $sql = 'UPDATE ' . CAPTCHA_QA_CONFIRM_TABLE . ' SET question_id = ' . (int) $this->question . " WHERE confirm_id = '" . $db->sql_escape($this->confirm_id) . "' AND session_id = '" . $db->sql_escape($user->session_id) . "'"; $db->sql_query($sql); $this->load_answer(); } /** * Wrong answer, so we increase the attempts and use a different question. */ function new_attempt() { global $db, $user; // yah, I would prefer a stronger rand, but this should work $this->question = (int) array_rand($this->question_ids); $this->solved = 0; $sql = 'UPDATE ' . CAPTCHA_QA_CONFIRM_TABLE . ' SET question_id = ' . (int) $this->question . ", attempts = attempts + 1 WHERE confirm_id = '" . $db->sql_escape($this->confirm_id) . "' AND session_id = '" . $db->sql_escape($user->session_id) . "'"; $db->sql_query($sql); $this->load_answer(); } /** * See if there is already an entry for the current session. */ function load_confirm_id() { global $db, $user; $sql = 'SELECT confirm_id FROM ' . CAPTCHA_QA_CONFIRM_TABLE . " WHERE session_id = '" . $db->sql_escape($user->session_id) . "' AND lang_iso = '" . $db->sql_escape($this->question_lang) . "' AND confirm_type = " . $this->type; $result = $db->sql_query_limit($sql, 1); $row = $db->sql_fetchrow($result); $db->sql_freeresult($result); if ($row) { $this->confirm_id = $row['confirm_id']; return true; } return false; } /** * Look up everything we need and populate the instance variables. */ function load_answer() { global $db, $user; if (!strlen($this->confirm_id) || !sizeof($this->question_ids)) { return false; } $sql = 'SELECT con.question_id, attempts, question_text, strict FROM ' . CAPTCHA_QA_CONFIRM_TABLE . ' con, ' . CAPTCHA_QUESTIONS_TABLE . " qes WHERE con.question_id = qes.question_id AND confirm_id = '" . $db->sql_escape($this->confirm_id) . "' AND session_id = '" . $db->sql_escape($user->session_id) . "' AND qes.lang_iso = '" . $db->sql_escape($this->question_lang) . "' AND confirm_type = " . $this->type; $result = $db->sql_query($sql); $row = $db->sql_fetchrow($result); $db->sql_freeresult($result); if ($row) { $this->question = $row['question_id']; $this->attempts = $row['attempts']; $this->question_strict = $row['strict']; $this->question_text = $row['question_text']; return true; } return false; } /** * The actual validation */ function check_answer() { global $db; $answer = ($this->question_strict) ? utf8_normalize_nfc(request_var('qa_answer', '', true)) : utf8_clean_string(utf8_normalize_nfc(request_var('qa_answer', '', true))); $sql = 'SELECT answer_text FROM ' . CAPTCHA_ANSWERS_TABLE . ' WHERE question_id = ' . (int) $this->question; $result = $db->sql_query($sql); while ($row = $db->sql_fetchrow($result)) { $solution = ($this->question_strict) ? $row['answer_text'] : utf8_clean_string($row['answer_text']); if ($solution === $answer) { $this->solved = true; break; } } $db->sql_freeresult($result); return $this->solved; } /** * API function */ function get_attempt_count() { return $this->attempts; } /** * API function */ function reset() { global $db, $user; $sql = 'DELETE FROM ' . CAPTCHA_QA_CONFIRM_TABLE . " WHERE session_id = '" . $db->sql_escape($user->session_id) . "' AND confirm_type = " . (int) $this->type; $db->sql_query($sql); // we leave the class usable by generating a new question $this->select_question(); } /** * API function */ function is_solved() { if (request_var('qa_answer', false) && $this->solved === 0) { $this->validate(); } return (bool) $this->solved; } /** * API function - The ACP backend, this marks the end of the easy methods */ function acp_page($id, &$module) { global $db, $user, $auth, $template; global $config, $phpbb_root_path, $phpbb_admin_path, $phpEx; $user->add_lang('acp/board'); $user->add_lang('captcha_qa'); if (!self::is_installed()) { $this->install(); } $module->tpl_name = 'captcha_qa_acp'; $module->page_title = 'ACP_VC_SETTINGS'; $form_key = 'acp_captcha'; add_form_key($form_key); $submit = request_var('submit', false); $question_id = request_var('question_id', 0); $action = request_var('action', ''); // we have two pages, so users might want to navigate from one to the other $list_url = $module->u_action . "&configure=1&select_captcha=" . $this->get_class_name(); $template->assign_vars(array( 'U_ACTION' => $module->u_action, 'QUESTION_ID' => $question_id , 'CLASS' => $this->get_class_name(), )); // show the list? if (!$question_id && $action != 'add') { $this->acp_question_list($module); } else if ($question_id && $action == 'delete') { if ($this->get_class_name() !== $config['captcha_plugin'] || !$this->acp_is_last($question_id)) { if (confirm_box(true)) { $this->acp_delete_question($question_id); trigger_error($user->lang['QUESTION_DELETED'] . adm_back_link($list_url)); } else { confirm_box(false, $user->lang['CONFIRM_OPERATION'], build_hidden_fields(array( 'question_id' => $question_id, 'action' => $action, 'configure' => 1, 'select_captcha' => $this->get_class_name(), )) ); } } else { trigger_error($user->lang['QA_LAST_QUESTION'] . adm_back_link($list_url), E_USER_WARNING); } } else { // okay, show the editor $error = false; $input_question = request_var('question_text', '', true); $input_answers = request_var('answers', '', true); $input_lang = request_var('lang_iso', '', true); $input_strict = request_var('strict', false); $langs = $this->get_languages(); foreach ($langs as $lang => $entry) { $template->assign_block_vars('langs', array( 'ISO' => $lang, 'NAME' => $entry['name'], )); } $template->assign_vars(array( 'U_LIST' => $list_url, )); if ($question_id) { if ($question = $this->acp_get_question_data($question_id)) { $answers = (isset($input_answers[$lang])) ? $input_answers[$lang] : implode("\n", $question['answers']); $template->assign_vars(array( 'QUESTION_TEXT' => ($input_question) ? $input_question : $question['question_text'], 'LANG_ISO' => ($input_lang) ? $input_lang : $question['lang_iso'], 'STRICT' => (isset($_REQUEST['strict'])) ? $input_strict : $question['strict'], 'ANSWERS' => $answers, )); } else { trigger_error($user->lang['FORM_INVALID'] . adm_back_link($list_url)); } } else { $template->assign_vars(array( 'QUESTION_TEXT' => $input_question, 'LANG_ISO' => $input_lang, 'STRICT' => $input_strict, 'ANSWERS' => $input_answers, )); } if ($submit && check_form_key($form_key)) { $data = $this->acp_get_question_input(); if (!$this->validate_input($data)) { $template->assign_vars(array( 'S_ERROR' => true, )); } else { if ($question_id) { $this->acp_update_question($data, $question_id); } else { $this->acp_add_question($data); } add_log('admin', 'LOG_CONFIG_VISUAL'); trigger_error($user->lang['CONFIG_UPDATED'] . adm_back_link($list_url)); } } else if ($submit) { trigger_error($user->lang['FORM_INVALID'] . adm_back_link($list_url), E_USER_WARNING); } } } /** * This handles the list overview */ function acp_question_list(&$module) { global $db, $template; $sql = 'SELECT * FROM ' . CAPTCHA_QUESTIONS_TABLE; $result = $db->sql_query($sql); $template->assign_vars(array( 'S_LIST' => true, )); while ($row = $db->sql_fetchrow($result)) { $url = $module->u_action . "&question_id={$row['question_id']}&configure=1&select_captcha=" . $this->get_class_name() . '&'; $template->assign_block_vars('questions', array( 'QUESTION_TEXT' => $row['question_text'], 'QUESTION_ID' => $row['question_id'], 'QUESTION_LANG' => $row['lang_iso'], 'U_DELETE' => "{$url}action=delete", 'U_EDIT' => "{$url}action=edit", )); } $db->sql_freeresult($result); } /** * Grab a question and bring it into a format the editor understands */ function acp_get_question_data($question_id) { global $db; if ($question_id) { $sql = 'SELECT * FROM ' . CAPTCHA_QUESTIONS_TABLE . ' WHERE question_id = ' . $question_id; $result = $db->sql_query($sql); $question = $db->sql_fetchrow($result); $db->sql_freeresult($result); if (!$question) { return false; } $question['answers'] = array(); $sql = 'SELECT * FROM ' . CAPTCHA_ANSWERS_TABLE . ' WHERE question_id = ' . $question_id; $result = $db->sql_query($sql); while ($row = $db->sql_fetchrow($result)) { $question['answers'][] = $row['answer_text']; } $db->sql_freeresult($result); return $question; } } /** * Grab a question from input and bring it into a format the editor understands */ function acp_get_question_input() { $answers = utf8_normalize_nfc(request_var('answers', '', true)); $question = array( 'question_text' => request_var('question_text', '', true), 'strict' => request_var('strict', false), 'lang_iso' => request_var('lang_iso', ''), 'answers' => (strlen($answers)) ? explode("\n", $answers) : '', ); return $question; } /** * Update a question. * param mixed $data : an array as created from acp_get_question_input or acp_get_question_data */ function acp_update_question($data, $question_id) { global $db, $cache; // easier to delete all answers than to figure out which to update $sql = 'DELETE FROM ' . CAPTCHA_ANSWERS_TABLE . " WHERE question_id = $question_id"; $db->sql_query($sql); $langs = $this->get_languages(); $question_ary = $data; $question_ary['lang_id'] = $langs[$question_ary['lang_iso']]['id']; unset($question_ary['answers']); $sql = 'UPDATE ' . CAPTCHA_QUESTIONS_TABLE . ' SET ' . $db->sql_build_array('UPDATE', $question_ary) . " WHERE question_id = $question_id"; $db->sql_query($sql); $this->acp_insert_answers($data, $question_id); $cache->destroy('sql', CAPTCHA_QUESTIONS_TABLE); } /** * Insert a question. * param mixed $data : an array as created from acp_get_question_input or acp_get_question_data */ function acp_add_question($data) { global $db, $cache; $langs = $this->get_languages(); $question_ary = $data; $question_ary['lang_id'] = $langs[$data['lang_iso']]['id']; unset($question_ary['answers']); $sql = 'INSERT INTO ' . CAPTCHA_QUESTIONS_TABLE . ' ' . $db->sql_build_array('INSERT', $question_ary); $db->sql_query($sql); $question_id = $db->sql_nextid(); $this->acp_insert_answers($data, $question_id); $cache->destroy('sql', CAPTCHA_QUESTIONS_TABLE); } /** * Insert the answers. * param mixed $data : an array as created from acp_get_question_input or acp_get_question_data */ function acp_insert_answers($data, $question_id) { global $db, $cache; foreach ($data['answers'] as $answer) { $answer_ary = array( 'question_id' => $question_id, 'answer_text' => $answer, ); $sql = 'INSERT INTO ' . CAPTCHA_ANSWERS_TABLE . ' ' . $db->sql_build_array('INSERT', $answer_ary); $db->sql_query($sql); } $cache->destroy('sql', CAPTCHA_ANSWERS_TABLE); } /** * Delete a question. */ function acp_delete_question($question_id) { global $db, $cache; $tables = array(CAPTCHA_QUESTIONS_TABLE, CAPTCHA_ANSWERS_TABLE); foreach ($tables as $table) { $sql = "DELETE FROM $table WHERE question_id = $question_id"; $db->sql_query($sql); } $cache->destroy('sql', $tables); } /** * Check if the entered data can be inserted/used * param mixed $data : an array as created from acp_get_question_input or acp_get_question_data */ function validate_input($question_data) { $langs = $this->get_languages(); if (!isset($question_data['lang_iso']) || !isset($question_data['question_text']) || !isset($question_data['strict']) || !isset($question_data['answers'])) { return false; } if (!isset($langs[$question_data['lang_iso']]) || !strlen($question_data['question_text']) || !sizeof($question_data['answers']) || !is_array($question_data['answers'])) { return false; } return true; } /** * List the installed language packs */ function get_languages() { global $db; $sql = 'SELECT * FROM ' . LANG_TABLE; $result = $db->sql_query($sql); $langs = array(); while ($row = $db->sql_fetchrow($result)) { $langs[$row['lang_iso']] = array( 'name' => $row['lang_local_name'], 'id' => (int) $row['lang_id'], ); } $db->sql_freeresult($result); return $langs; } /** * See if there is a question other than the one we have */ function acp_is_last($question_id) { global $config, $db; if ($question_id) { $sql = 'SELECT question_id FROM ' . CAPTCHA_QUESTIONS_TABLE . " WHERE lang_iso = '" . $db->sql_escape($config['default_lang']) . "' AND question_id <> " . (int) $question_id; $result = $db->sql_query_limit($sql, 1); $question = $db->sql_fetchrow($result); $db->sql_freeresult($result); if (!$question) { return true; } return false; } } } 01' href='#n501'>501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469
package Xconfigurator; # $Id$

use diagnostics;
use strict;
use vars qw($in $install @window_managers @depths @monitorSize2resolution @hsyncranges %min_hsync4wres @vsyncranges %depths @resolutions @resolutions_laptop %serversdriver @svgaservers @accelservers @allbutfbservers @allservers %vgamodes %videomemory @ramdac_name @ramdac_id @clockchip_name @clockchip_id %keymap_translate %standard_monitors $XF86firstchunk_text $keyboardsection_start $keyboardsection_start_v4 $keyboardsection_part2 $keyboardsection_part3 $keyboardsection_part3_v4 $keyboardsection_end $pointersection_text $monitorsection_text1 $monitorsection_text2 $monitorsection_text3 $monitorsection_text4 $modelines_text_Trident_TG_96xx $modelines_text_ext $modelines_text $devicesection_text $devicesection_text_v4 $screensection_text1 %lines @options %xkb_options $good_default_monitor $low_default_monitor $layoutsection_v4 $modelines_text_apple);

use common qw(:common :file :functional :system);
use log;
use detect_devices;
use run_program;
use Xconfigurator_consts;
use any;
use modules;
use my_gtk qw(:helpers :wrappers);

my $tmpconfig = "/tmp/Xconfig";

my ($prefix, %monitors, %standard_monitors_);


sub xtest {
    my ($display) = @_;
    $::isStandalone ? 
      system("DISPLAY=$display /usr/X11R6/bin/xtest") == 0 : 
      c::Xtest($display);    
}

sub getVGAMode($) { $_[0]->{card}{vga_mode} || $vgamodes{"640x480x16"}; }

sub readCardsDB {
    my ($file) = @_;
    my ($card, %cards);

    my $F = common::openFileMaybeCompressed($file);

    my ($lineno, $cmd, $val) = 0;
    my $fs = {
        LINE => sub { push @{$card->{lines}}, $val unless $val eq "VideoRam" },
	NAME => sub {
	    $cards{$card->{type}} = $card if $card;
	    $card = { type => $val };
	},
	SEE => sub {
	    my $c = $cards{$val} or die "Error in database, invalid reference $val at line $lineno";

	    push @{$card->{lines}}, @{$c->{lines} || []};
	    add2hash($card->{flags}, $c->{flags});
	    add2hash($card, $c);
	},
	CHIPSET => sub {
	    $card->{chipset} = $val;
	    $card->{flags}{needChipset} = 1 if $val eq 'GeForce DDR';
	    $card->{flags}{needVideoRam} = 1 if member($val, qw(mgag10 mgag200 RIVA128 SiS6326));
	},
	SERVER => sub { $card->{server} = $val; },
	DRIVER => sub { $card->{driver} = $val; },
	RAMDAC => sub { $card->{ramdac} = $val; },
	DACSPEED => sub { $card->{dacspeed} = $val; },
	CLOCKCHIP => sub { $card->{clockchip} = $val; $card->{flags}{noclockprobe} = 1; },
	NOCLOCKPROBE => sub { $card->{flags}{noclockprobe} = 1 },
	UNSUPPORTED => sub { $card->{flags}{unsupported} = 1 },
	COMMENT => sub {},
    };

    local $_;
    while (<$F>) { $lineno++;
	s/\s+$//;
	/^#/ and next;
	/^$/ and next;
	/^END/ and last;

	($cmd, $val) = /(\S+)\s*(.*)/ or next; #log::l("bad line $lineno ($_)"), next;

	my $f = $fs->{$cmd};

	$f ? $f->() : log::l("unknown line $lineno ($_)");
    }
    \%cards;
}
sub readCardsNames {
    my $file = "$ENV{SHARE_PATH}/ldetect-lst/CardsNames";
    map { (split '=>')[0] } grep { !/^#/ } catMaybeCompressed($file);
}
sub cardName2RealName {
    my ($name) = @_;
    my $file = "$ENV{SHARE_PATH}/ldetect-lst/CardsNames";
    foreach (catMaybeCompressed($file)) {
	chop;
	next if /^#/;	  
	my ($name_, $real) = split '=>';
	return $real if $name eq $name_;
    }
    $name;
}
sub updateCardAccordingName {
    my ($card, $name) = @_;
    my $cards = readCardsDB("$ENV{SHARE_PATH}/ldetect-lst/Cards+");

    add2hash($card->{flags}, $cards->{$name}{flags});
    add2hash($card, $cards->{$name});
    $card;
}

sub readMonitorsDB {
    my ($file) = @_;

    %monitors and return;

    my $F = common::openFileMaybeCompressed($file);
    local $_;
    my $lineno = 0; while (<$F>) {
	$lineno++;
	s/\s+$//;
	/^#/ and next;
	/^$/ and next;

	my @fields = qw(vendor type eisa hsyncrange vsyncrange);
	my @l = split /\s*;\s*/;
	@l == @fields or log::l("bad line $lineno ($_)"), next;

	my %l; @l{@fields} = @l;
	if ($monitors{$l{type}}) {
	    my $i; for ($i = 0; $monitors{"$l{type} ($i)"}; $i++) {}
	    $l{type} = "$l{type} ($i)";
	}
	$monitors{"$l{vendor}|$l{type}"} = \%l;
    }
    while (my ($k, $v) = each %standard_monitors) {
	$monitors{'Generic|' . translate($k)} = $standard_monitors_{$k} = 
	  { hsyncrange => $v->[1], vsyncrange => $v->[2] };
    }
}

sub keepOnlyLegalModes {
    my ($card, $monitor) = @_;
    my $mem = 1024 * ($card->{memory} || ($card->{server} eq 'FBDev' ? 2048 : 32768)); #- limit to 2048x1536x64
    my $hsync = max(split(/[,-]/, $monitor->{hsyncrange}));

    while (my ($depth, $res) = each %{$card->{depth}}) {
	@$res = grep {
	    $mem >= product(@$_, $depth / 8) &&
	    $hsync >= ($min_hsync4wres{$_->[0]} || 0) &&
	    ($card->{server} ne 'FBDev' || $vgamodes{"$_->[0]x$_->[1]x$depth"})
	} @$res;
	delete $card->{depth}{$depth} if @$res == 0;
    }
}

sub cardConfigurationAuto() {
    my @cards;
    if (my @c = grep { $_->{driver} =~ /(Card|Server):/ } detect_devices::probeall(1)) {
	foreach my $i (0..$#c) {
	    local $_ = $c[$i]->{driver};
	    my $card = { identifier => ($c[$i]{description} . (@c > 1 && " $i")) };
	    $card->{type} = $1 if /Card:(.*)/;
	    $card->{server} = $1 if /Server:(.*)/;
	    $card->{flags}{needVideoRam} &&= /86c368/;
	    $card->{busid} = "PCI:$c[$i]{pci_bus}:$c[$i]{pci_device}:$c[$i]{pci_function}";
	    push @{$card->{lines}}, @{$lines{$card->{identifier}} || []};
	    push @cards, $card;
	}
    }
    #- take a default on sparc if nothing has been found.
    if (arch() =~ /^sparc/ && !@cards) {
        log::l("Using probe with /proc/fb as nothing has been found!");
	local $_ = cat_("/proc/fb");
	if (/Mach64/) { push @cards, { server => "Mach64" } }
	elsif (/Permedia2/) { push @cards, { server => "3DLabs" } }
	else { push @cards, { server => "Sun24" } }
    }
    #- special case for dual head card using only one busid.
    @cards = map { my $dup = $_->{identifier} =~ /MGA G450/ ? 2 : 1;
		   if ($dup > 1) {
		       my @result;
		       my $orig = $_;
		       foreach (1..$dup) {
			   my $card = {};
			   add2hash($card, $orig);
			   push @result, $card;
		       }
		       @result;
		   } else {
		       ($_);
		   }
	       } @cards;
    #- make sure no type are already used, duplicate both screen
    #- and rename type (because used as id).
    if (@cards > 1) {
	my $card = 1;
	foreach (@cards) {
	    updateCardAccordingName($_, $_->{type}) if $_->{type};
	    $_->{type} = "$_->{type} $card";
	    $card++;
	}
    }
    #- in case of only one cards, remove all busid reference, this will avoid
    #- need of change of it if the card is moved.
    #- on many PPC machines, card is on-board, busid is important, leave?
    @cards == 1 and delete $cards[0]{busid} if arch() !~ /ppc/;
    @cards;
}

sub cardConfiguration(;$$$) {
    my ($card, $noauto, $cardOptions) = @_;
    $card ||= {};

    updateCardAccordingName($card, $card->{type}) if $card->{type}; #- try to get info from given type
    undef $card->{type} unless $card->{server}; #- bad type as we can't find the server
    my @cards = cardConfigurationAuto();
    if (@cards > 1 && ($noauto || !$card->{server})) {#} && !$::isEmbedded) {
	my (%single_heads, @choices, $tc);
	my $configure_multi_head = sub {
	    add2hash($card, $cards[0]); #- assume good default.
	    delete $card->{cards} if $noauto;
	    $card->{cards} or $card->{cards} = \@cards;
	    $card->{force_xf4} = 1; #- force XF4 in such case.
	    $card->{Xinerama} = $_[0];
	};
	foreach (@cards) {
	    unless ($_->{driver} && !$_->{flags}{unsupported}) {
		log::l("found card \"$_->{identifier}\" not supported by XF4, disabling mutli-head support");
		$configure_multi_head = undef;
	    }
	    #- if more than one card use the same BusID, we have to use screen.
	    if ($single_heads{$_->{busid}}) {
		$single_heads{$_->{busid}}{screen} ||= 0;
		$_->{screen} = $single_heads{$_->{busid}}{screen} + 1;
	    }
	    $single_heads{$_->{busid}} = $_;
	}
	if ($configure_multi_head) {
	    push @choices, { text => _("Configure all heads independantly"), code => sub { $configure_multi_head->('') } };
	    push @choices, { text => _("Use Xinerama extension"), code => sub { $configure_multi_head->(1) } };
	}
	foreach (values %single_heads) {
	    push @choices, { text => _("Configure only card \"%s\" (%s)", $_->{identifier}, $_->{busid}),
			     code => sub { add2hash($card, $_); delete $card->{cards}; delete $card->{Xinerama} } };
	}
	$tc = $in->ask_from_listf(_("Multi-head configuration"),
_("Your system support multiple head configuration.
What do you want to do?"), sub { translate($_[0]{text}) }, \@choices) or return; #- no more die, CHECK with auto that return ''!
	$tc->{code} and $tc->{code}();
    } else {
	#- only one head found, configure it as before.
	add2hash($card, $cards[0]) unless $card->{server} || $noauto;
	delete $card->{cards}; delete $card->{Xinerama};
    }
    $card->{server} = 'FBDev' unless !$cardOptions->{allowFB} || $card->{server} || $card->{type} || $noauto;
    $card->{type} = cardName2RealName($in->ask_from_treelist(_("Graphic card"), _("Select a graphic card"), '|', ['Other|Unlisted', readCardsNames()])) unless $card->{type} || $card->{server};
    undef $card->{type}, $card->{server} = $in->ask_from_list(_("X server"), _("Choose a X server"), $cardOptions->{allowFB} ? \@allservers : \@allbutfbservers ) or return if $card->{type} eq 'Other|Unlisted';

    updateCardAccordingName($card, $card->{type}) if $card->{type};
    add2hash($card, { vendor => "Unknown", board => "Unknown" });

    foreach ($card, @{$card->{cards} || []}) {
	$_->{memory} = 4096,  delete $_->{depth} if $_->{driver} eq 'i810';
	$_->{memory} = 16384, delete $_->{depth} if $_->{chipset} =~ /PERMEDIA/ && $_->{memory} <= 1024;
    }
    #- 3D acceleration configuration for XFree 3.3 using Utah-GLX.
    $card->{Utah_glx} = ($card->{identifier} =~ /Matrox.* G[24][05]0/ || #- 8bpp does not work.
			 $card->{identifier} =~ /Riva.*128/ ||
			 $card->{identifier} =~ /Rage X[CL]/ ||
			 $card->{identifier} =~ /3D Rage (?:LT|Pro)/);