--- db/prgsrc/db.cgi 2003/08/29 21:52:25 1.124 +++ db/prgsrc/db.cgi 2006/09/24 19:53:59 1.143 @@ -2,23 +2,36 @@ use DBI; use CGI ':all'; -use strict; +#use strict; +my @softfields=("От Олега Степанова"); use Time::Local; +my $proxyredirect=1; use POSIX qw(locale_h); use locale; use vars qw($opt_z); use Getopt::Std; +#my ($dbuser,$dbname,$dbpass,$dbhost); +eval {require "dbdefs.pl";} ; +my $url=url||''; +my @used_stop=(); +$dbuser||="piataev"; +$dbname||="chgk"; +$dbpass||=""; +$dbhost||="localhost"; getopts('z'); $opt_z||=param("makehtml"); my $timestamp="_timestamp.tmp"; +my $usehash=0; my $paramtour; my $withanswers=param('answer')||param('answers'); open STDERR, ">/var/tmp/errors1"; my $newsurl='http://news.chgk.info/'; my $reklama="../dimrub/db/reklama.html"; my $footer="../dimrub/db/footer.html"; - +$footer="../../chgk/footer.html" if $url=~/zaba/; +$reklama="../../chgk/reklama.html" if $url=~/zaba/; my $datefooter="../dimrub/db/date"; +$datefooter="../../chgk/date" if $url=~/zaba/; my $fname; $reklama="../reklama.html" if $opt_z; @@ -31,30 +44,41 @@ if ($^O =~ /win/i) { $realHTMLDIR="/html/znatoki/baza/"; } else { - $realHTMLDIR="/home/piataev/public_html/dimrub/db/files/"; + $realHTMLDIR="/home/znatoki/chgk-db/public_html/dimrub/db/files/"; } + + my $usehtml=$opt_z||0; $usehtml=1; +$usehtml=0 if $url=~/zaba/ || $url=~/localhost/; + my $usewas=0; my $cashednumber=500; my $outputnumber=10; my ($proxyptext,$proxysstr); my $printqueries=0; -my $url=url||''; my $qs=query_string; my $globaloutput; my %forbidden=(); my $debug=0; #added by R7 +my $metod=param('metod')||''; my $outputkvo=param('kvo') ||$outputnumber; $outputkvo=100 if $outputkvo>100; if (param('debug')) {$debug=1; $printqueries=1} *STDERR=*STDOUT if $debug; -if ($url !~ /db\.chgk\.info/ && $url !~ /localhost/ && $url !~ /bilbo/) { +if ($url !~ /db\.chgk\.info/ && $url !~ /localhost/ && $url !~ /bilbo/ && $url !~ /zaba/ && $url !~ /question\.chgk\.info/ ) { my $u="http://db.chgk.info/cgi-bin/db.cgi?$qs"; Redirect ($u); exit; } + +if ($proxyredirect && $metod=~/proxy/ && $url !~ /localhost/ && $url !~ /bilbo/ && $url !~ /zaba/) { + my $u="http://chgk.zaba.ru/cgi-bin/db.cgi?$qs"; + Redirect ($u); + exit; +} + #if (!param('sstr') && param('all')) { # my $destination='http://db.chgk.info/all.html'; # Redirect($destination); @@ -70,8 +94,8 @@ POSIX::setlocale( &POSIX::LC_ALL, $thisl if ((uc 'а') ne 'А') {print STDERR "Koi8-r locale not installed!\n"}; -my %fieldname= (0,'Question', 1, 'Answer', 2, 'Comments', 3, 'Authors', 4, 'Sources'); -my %rusfieldname=('Question','Вопрос', 'Answer', 'Ответ', +my %fieldname= (0,'Question', 1, 'Answer', 2, 'PassCriteria', 3, 'Comments', 4, 'Authors', 5, 'Sources'); +my %rusfieldname=('Question','Вопрос', 'Answer', 'Ответ', 'PassCriteria','Зачёт', 'Comments', 'Комментарии', 'Authors', 'Автор', 'Sources', 'Источник','old','Старый','rus','Новый', 'chgk', 'ЧГК', 'brain', 'Брейн-ринг','game', 'Своя игра', @@ -93,13 +117,21 @@ my %TypeName=('children'=>'Д', 'game'=>' 'chgk'=>'Ч', 'brain'=>'Б', 'beskrylka'=>'Л','ehruditka'=>'Э'); +sub countz { + my ($dbh,$type)=@_; + + my $sth=$dbh->prepare("select count(*) from Questions where Type LIKE '%$type%'"); + $sth->execute(); + my ($tmp)=$sth->fetchrow(); + return $tmp; +} my $all=param('all'); $all=0 if lc $all eq 'no'; my ($PWD) = `pwd` if $^O!~/win/i; chomp $PWD if $PWD; -my ($SRCPATH) = "/home/piataev/public_html/dimrub/src"; -my ($ZIP) = "/usr/local/bin/zip"; +my ($SRCPATH) = "/home/db-chgk/public_html/dimrub/src"; +my ($ZIP) = "/usr/bin/zip"; my $DUMPFILE = "/tmp/chgkdump"; my ($SENDMAIL) = "/usr/sbin/sendmail"; my ($TMPDIR) = "/var/tmp"; @@ -176,12 +208,12 @@ sub GetTournament { sub fetchquestion { my ($sth,$q,$WithTour)=@_; if ($WithTour) { - ($$q{'QuestionId'}, $$q{'Question'},$$q{'Answer'},$$q{'Comments'},$$q{'Authors'},$$q{'Sources'}, + ($$q{'QuestionId'}, $$q{'Question'},$$q{'Answer'},$$q{'PassCriteria'},$$q{'Comments'},$$q{'Authors'},$$q{'Sources'}, $$q{'Number'}, $$q{'Title'}, $$q{'TourTitle'}, $$q{'FileName'},$$q{'PlayedAt'},$$q{'TourNumber'}) = $sth->fetchrow; } else { - ($$q{'QuestionId'}, $$q{'Question'},$$q{'Answer'},$$q{'Comments'},$$q{'Authors'},$$q{'Sources'}, + ($$q{'QuestionId'}, $$q{'Question'},$$q{'Answer'},$$q{'PassCriteria'},$$q{'Comments'},$$q{'Authors'},$$q{'Sources'}, $$q{'Number'})= $sth->fetchrow; } @@ -203,13 +235,13 @@ sub SelectQuestions { my $query; if ($WithTour) { - $query="SELECT QuestionId, Questions.Question, Answer, Comments, Authors, Sources, + $query="SELECT QuestionId, Questions.Question, Answer, PassCriteria, Comments, Authors, Sources, Questions.Number , t2.Title, t1.Title, t2.FileName, t2.PlayedAt,t1.Number from Questions,Tournaments as t1, Tournaments as t2 WHERE $where"; } else { - $query="SELECT QuestionId, Questions.Question, Answer, Comments, Authors, Sources, + $query="SELECT QuestionId, Questions.Question, Answer, PassCriteria, Comments, Authors, Sources, Questions.Number from Questions WHERE $where"; } @@ -260,8 +292,9 @@ sub tourhref { return $res; } else { $res=$url; - $res.="?tour=$t"; - $res.=$a?"&answers=1":""; + $res.=$a?"?answers=1&":"?"; + $res.="tour=$t"; + return $res; } @@ -326,11 +359,11 @@ sub printform my $sstr=param('sstr'); my @df=keys %searchin; my %checked; - $checked{lc $_}="" foreach ('Question','Answer','Comments','Authors','Sources','old','rus', + $checked{lc $_}="" foreach ('Question','Answer','PassCriteria','Comments','Authors','Sources','old','rus', 'chgk','brain','igp','game','ehruditka','beskrylka'); @df=('Question', 'Answer') unless @df; $checked{lc $_}="checked" foreach @df; - my $fields=checkbox_group('searchin',['Question','Answer','Comments','Authors','Sources'], [@df], + my $fields=checkbox_group('searchin',['Question','Answer','PassCriteria','Comments','Authors','Sources'], [@df], 'false',\%rusfieldname); @df=param('type'); @df=('chgk','brain','igp','game','ehruditka','beskrylka') unless @df; @@ -356,7 +389,7 @@ action="/znatoki/cgi-bin/db.cgi"> -
Вариант поиска: - + Простой (старый)  "Что? Где? Когда?" @@ -374,11 +407,11 @@ action="/znatoki/cgi-bin/db.cgi">  "Бескрылка"
Расширенный (с учетом грамматики, в вопросах всех типов) + Расширенный (с учетом грамматики, в вопросах всех типов)
Искать: - + Все слова Любое слово @@ -390,6 +423,8 @@ action="/znatoki/cgi-bin/db.cgi"> Ответ
+Зачёт
+
Комментарии
Автор
@@ -398,6 +433,9 @@ action="/znatoki/cgi-bin/db.cgi">
+ EOT @@ -436,7 +474,7 @@ sub makeproxysstr { # $good{$words[$_]}=1 foreach 0..4; foreach (@words) { - $good{$_}=1 if $c{$_}<200; + $good{$_}=1 if $c{$_}<200 && length $_>2; } $good{$words[$_]}=0 foreach 16..$#words; @@ -463,19 +501,31 @@ sub russearch { my %relevance; my @blob; my %count; + my %stop_word; POSIX::setlocale( &POSIX::LC_ALL, $thislocale ); $sstr=~tr/йцукенгшщзхъфывапролджэячсмитьбю/ЙЦУКЕНГШЩЗХЪФЫВАПРОЛДЖЭЯЧСМИТЬБЮ/; # @qw=@w =split (' ', uc $sstr); my $ts=uc $sstr; @qw=@w= $ts=~m/(?:(?:${RLrl})+)|(?:[A-Za-z0-9]+)/gom; - + $query="select nf.word from nf where number>=50000"; + $sth=$dbh->prepare($query); + $sth->execute(); + %stop_word=(); + while (@arr = $sth->fetchrow) + { + $stop_word{$arr[0]}=1; + } + $sth->finish; + #----------- foreach $i (0..$#w) # заполняем массив @nf начальных форм # $nf[$i] -- ссылка на массив возможных # начальных форм словоформы $i { + (push @used_stop, uc $w[$i]),next if $stop_word{uc $w[$i]}; $qw= $dbh->quote (uc $w[$i]); + $query=" select distinct w2 from nests where w1=$qw"; $sth=$dbh -> prepare($query); @@ -520,7 +570,7 @@ $sstr=~tr/йцукенгшщзхъфывапролджэячсмить $_= " word2question.word=$_" foreach @arr; $_= " nf.id=".$_. ' ' foreach @arr1; # @arr=(0) unless @arr; - $query="select questions from word2question where (". (join ' OR ', @arr).") AND length(questions)<80000"; + $query="select questions from word2question where (". (join ' OR ', @arr).") "; $sth=$dbh -> prepare($query); $sth->execute; @@ -582,7 +632,12 @@ $sstr=~tr/йцукенгшщзхъфывапролджэячсмить #Ищем пересечение или объединение списков вопросов (значений %tasksof) foreach $sf (keys %tasksof) { - $count{$_}++ foreach keys %{$tasksof{$sf}}; + foreach (keys %{$tasksof{$sf}}) + { + next if $forbidden{$_}; + $count{$_}++ + } + } @tasks= ($all ? (grep {$count{$_}==$kvo} keys %count) : keys %count) ; @@ -670,13 +725,13 @@ sub Search { ###Simple and advanced query processing. Added by R7 if ($metod eq 'simple' || $metod eq 'advanced') { - foreach (qw/Question Answer Sources Authors Comments/) { + foreach (qw/Question Answer PassCriteria Sources Authors Comments/) { if (param($_)) { push @fields, $_; } } - @fields=(qw/Question Answer Sources Authors Comments/) unless scalar @fields; + @fields=(qw/Question Answer PassCriteria Sources Authors Comments/) unless scalar @fields; my $fields=join ",", @fields; my $q=new Text::Query($sstr, -parse => 'Text::Query::'. @@ -694,7 +749,6 @@ sub Search { ###### { -# foreach (qw/Question Answer Sources Authors Comments/) { foreach (param('searchin')) { # if (param($_)) { push @fields, "IFNULL($_, '')"; @@ -738,7 +792,7 @@ sub makewhere { $type .= ($_=$TypeName{$_}) foreach @type; my $where=' 0 '; foreach (@type) { - $where.= " OR (Type ='$_') OR (Type ='$_Д') "; + $where.= " OR (Type ='$_') OR (Type ='$_Д') OR (Type ='Д$_') "; } $where.= "OR (Type='ЧБ')" if ($type=~/Ч|Б/); return $where; @@ -850,7 +904,7 @@ sub PrintList { for (my $i = $first; $i <= $last; $i++) { my $q=$q{$$Questions[$i-1]}; my $output; - $output = &PrintQuestion($dbh, $q, 1, 0, 1,0,1 ); + $output = &PrintQuestion($dbh, $q, 1, 0, 1,$text,1 ); # if (param('metod') && (param('metod') eq 'rus' || param('metod') eq 'proxy')) { $output=~s/\b($shablon)\b/\$1\<\/strong\>/gi; @@ -904,6 +958,8 @@ sub PrintSearch { $Output.= p. "Время поиска: " . (time-$t) ." сек.".p; + $_="\"$_\"" foreach @used_stop; + $Output.= p. (join ', ',@used_stop) ." ignored".p if @used_stop; my ($output, $i, $suffix, $hits) = ('', 0, '', $#Questions + 1); my $shablon; @@ -966,9 +1022,11 @@ sub PrintRandom { my %q; my $answer=$razd?0:1; my @answers; +#my $t=time; my (@Questions) = &Get12Random($dbh, $type, $num); - my ($output, $i) = ('', 0); + my ($output, $i) = ('', 0); +#$output.="time=".(time-$t).p; if ($text) { $output .= " $num случайных вопросов.\n\n"; } else { @@ -1050,9 +1108,20 @@ sub PrintTournament { }; } } else { - my ($qnum) = GetQNum($dbh); - $output .= h2("Банк Вопросов: $qnum вопрос".&Suffix($qnum)) - . p . "\n"; + my ($qnum) = GetQNum($dbh,0); + my ($qnum1) = GetQNum($dbh,1); + $output .= h2("База вопросов"). + h3("$qnum запис".&Suffix2($qnum). + " (уникальных $qnum1)"); + +# h4("". +# Tr(td("Из них:"), td("Вопросов ЧГК: ".countz($dbh,'Ч'))). +# Tr(td(" "), td("Вопросов для брейна: ".countz($dbh,'Б'))). +# Tr(td(" "), td("Вопросов для ЧГК и брейна: ".countz($dbh,'ЧБ'))). +# Tr(td(" "), td("Интернет-вопросов: ".countz($dbh,'И'))). +# Tr(td(" "), td("Бескрылок: ".countz($dbh,'Л'))). +# Tr(td(" "),td("Заданий для Своей Игры: ".countz($dbh,'Я'))). +# Tr(td(" "),td("Эрудиток: ".countz($dbh,'Э'))))."
" } for ($i = 0; $i <= $#Tours; $i++) { @@ -1143,6 +1212,23 @@ sub Suffix { return $suffix; } + +sub Suffix1 { + my ($qnum) = @_; + my ($suffix) = 'я' if $qnum =~ /[234]$/; + $suffix = 'е' if $qnum =~ /1$/; + $suffix = 'й' if $qnum =~ /[567890]$/ || $qnum =~ /1.$/; + return $suffix; +} + +sub Suffix2 { + my ($qnum) = @_; + my ($suffix) = 'и' if $qnum =~ /[234]$/; + $suffix = 'ь' if $qnum =~ /1$/; + $suffix = 'ей' if $qnum =~ /[567890]$/ || $qnum =~ /1.$/; + return $suffix; +} + sub IsTour { my ($dbh, $Id,$n) = @_; @@ -1192,7 +1278,7 @@ sub PrintTour { my $sth=SelectQuestions($dbh,\@Questions,0); for ($q = 0; $q <= $#Questions; $q++) { fetchquestion($sth,\%q,0); - $output .= &PrintQuestion($dbh, \%q, $answer, 0,0,0,1); + $output .= &PrintQuestion($dbh, \%q, $answer, 0,0,$text,1); } $sth->finish; $output .= hr({-'align'=>'center', -'width'=>'80%'}); @@ -1248,9 +1334,16 @@ sub PrintField { if ($text) { $value =~ s/<[\/\w]*?>//sg; } else { + if ($header=~/Комментар/) + { + $value=~s/^\s*$_[\.:]/p."\n".strong("$_").":"/me foreach @softfields; + } + $value =~ s/^\s+/
    /mg; + $value =~ s/(\s+)-+(\s+)/$1–$2/mg; + $value =~ s/\s+\–/ \–/mg + if $value !~ /^\|/; $value =~ s/^\|([^\n]*)/
$1<\/pre>/mg;
-	    $value =~ s/\s+-+\s+/ – /mg;
 	    $value =~ s/(http:\/\/\S+[^\s\)\(\,\.])/$1<\/a>/g if $header !~ /^Авто/;
 #	    $value =~ s/(http:\/\/(?:\w+.)+[\w\\\~]+(\?[^\s.]+)?)/$1<\/a>/g if $header !~ /^Авто/;
 #	    $value =~ s/(\s)"/$1“/mg;
@@ -1258,7 +1351,10 @@ sub PrintField {
 #	    $value =~ s/"/”/mg;
 	}
 
-
+	if ($value=~/^\s*()?\s*"50%"}) if $answer>=0;
 		if ($title) {
-			my $fname=$Question{'FileName'};
+			$fname=$Question{'FileName'};
 			$fname=~s/\.txt//;
 			$titles .=
 				dd(img({src=>"/icons/folder.open.gif"}) . " " .
@@ -1312,6 +1409,10 @@ sub PrintQuestion {
 	if ($answer==1|| $answer==-1) {
 		$output .=
 			&PrintField("Ответ", $Question{'Answer'}, $text);
+		if ($Question{'PassCriteria'} ) {
+		  $output .=
+			&PrintField("Зачёт", $Question{'PassCriteria'}, $text);
+                }
 
 		if ($Question{'Authors'} ) {
                       my $q=$Question{'Authors'};
@@ -1380,6 +1481,10 @@ EOTT
 		if ($Question{'Authors'}) {
 			$output .= &PrintField("Автор(ы)", $Question{'Authors'}, $text);
 		}
+		if ($Question{'PassCriteria'}) {
+			$output .= &PrintField("Зачёт", $Question{'PassCriteria'}, $text);
+		}
+
 		if ($Question{'Sources'}) {
 			$output .= &PrintField("Источник(и)", $Question{'Sources'}, $text);
 		}
@@ -1394,8 +1499,13 @@ $output.=""
 
 	}
 	$output=~s/\(pic: ([^\)]*)\)/

/g unless $text; + $output=~s/⌡/\ï/g; + $output=~s/⌠/\Ï/g; + $paramtour||=param("tour"); - my $qid=$paramtour ? ($paramtour.".$Question{'Number'}" ): ''; + $fname=$fname.".$Question{'TourNumber'}" if $fname && $Question{'TourNumber'}; +$fname||=param('tour'); + my $qid=$fname ? ($fname.".$Question{'Number'}" ): ''; $output.=br.a({href=> $url."?metod=proxy& qid=$qid"}, 'Близкие вопросы').p @@ -1405,12 +1515,22 @@ qid=$qid"}, 'Близкие вопросы').p # Returns the total number of questions currently in the DB. sub GetQNum { - my ($dbh) = @_; + my ($dbh,$x) = @_; my ($sth) = $dbh->prepare("SELECT COUNT(*) FROM Questions"); $sth->execute; my $tmp=($sth->fetchrow)[0]; $sth->finish; - return $tmp; + ($sth)= $dbh -> prepare("select distinct count(first) FROM equalto"); + $sth -> execute; + my ($c)=$sth->fetchrow; + +# $i++ while ( my ($first, $second)=$sth -> fetchrow) +# { +# $forbidden{$first}=1; +# } + $sth->finish; + + return $tmp-($x?$c:0); } sub GetMaxQId { my ($dbh) = @_; @@ -1431,7 +1551,9 @@ sub Get12Random { srand; my $where=0; my $r=int (rand(10000)); - + my $w1=$r<5000? "QuestionId<50000 ":"QuestionId>=50000"; + $w1=1 if $url=~/zaba/; + $w1=1 if $type!~/Ч/; foreach (split '', $type) { $where.= " OR (Type ='$_') OR (Type ='$_Д') "; @@ -1441,7 +1563,7 @@ sub Get12Random { # $q="select QuestionId, QuestionId/$r-floor(QuestionId/$r) as val # from Questions where $where order by val limit $num"; # Когда на куличках появится mysql >=3.23 надо заменить на order by rand(); - $q="select QuestionId from Questions where $where order by rand() limit $num"; + $q="select QuestionId from Questions where ($w1) AND ($where) order by rand() limit $num"; $sth=$dbh->prepare($q); @@ -1610,7 +1732,7 @@ sub PrintQOfAuthor $suffix = 'я'; } $Output.= printform; - $Output.= p({align=>"center"}, "Автор ".strong("$name $surname. ") + $Output.= p({align=>"center"}, "Автор ".strong("$name $surname ") . " : $hits попадани$suffix."); @@ -1809,6 +1931,7 @@ sub WriteFile { { print OUT "Вопрос $q:\n".$Question{$tour}[$q]{'Question'}."\n\n"; print OUT "Ответ:\n".$Question{$tour}[$q]{'Answer'}."\n\n"; + print OUT "Зачёт:\n".$Question{$tour}[$q]{'PassCriteria'}."\n\n"; print OUT "Автор:\n".$Question{$tour}[$q]{'Authors'}."\n\n" if !$tourauthor && !$eqauthor && $Question{$tour}[$q]{'Authors'}; print OUT "Комментарий:\n".$Question{$tour}[$q]{'Comments'}."\n\n" @@ -1858,9 +1981,11 @@ MAIN: $tour = (param('tour')) ? param('tour') : 0; my $texttour=$tour; my ($sth,$dbh); - $dbh = DBI->connect("DBI:mysql:chgk", "piataev", "") + my($dsn) = "DBI:mysql:database=$dbname;host=$dbhost"; + $dbh = DBI->connect($dsn, $dbuser, $dbpass) +# $dbh = DBI->connect("DBI:mysql:$dbname", $username, $dbpass) or do { - print h1("Временные проблемы") . "База вопросов временно не + print header.h1("Временные проблемы") . "База вопросов временно не работает. Заходите попозже."; print &Include_virtual("$reklama") if $url!~/localhost/; print end_html; @@ -1869,14 +1994,14 @@ MAIN: if (param('qid') && (param('qid')=~/^\d+$/) || $tour && $tour=~/^\d+$/) { - my $destination='http://db.chgk.info/search.html'; +# my $destination='http://chgk.zaba.ru/search.html'; # print header (-'Content-Type' => 'text/html', # -'Location:'=> 'http:\\db.chgk.info'); Redirect($destination); exit } - if ($tour && (!param('answers')||!param('answers')<=1)) + if ($tour && !param('qnumber') && (!param('answers')||(param('answers')<=1))) { my $n=param('tour'); $n=~s/.txt$//; @@ -1885,14 +2010,13 @@ MAIN: my $d=$destination; $d=~s/$HTMLDIR/$realHTMLDIR/; # print header.$destination; - print header."$d|".(-e "$realHTMLDIR$n.html"); +# print header."$d|".(-e "$realHTMLDIR$n.html"); if (-e $d) { Redirect($destination); exit } $d=~s/\.\d+//; $destination=~s/\.\d+//; -print br.br.$d; if (-e $d) { Redirect($destination); exit @@ -1925,7 +2049,8 @@ print br.br.$d; if ($text && !param ('comp')) { print header('text/plain'); - } elsif (!param('comp')) {print header;} + } elsif (!param('comp')) { + print header(-charset =>'koi8-r')} my $sstr=param('sstr'); $opt_z||=param("makehtml"); if (param('qid')) { @@ -1979,11 +2104,10 @@ print br.br.$d; my $title="Результаты поиска на \"". ($proxysstr||$sstr) .'"' if ($proxysstr||$sstr); $title||="База вопросов"; - $globaloutput.=start_html(-"title"=>$title, -author=>'dimrub@icomverse.com', -bgcolor=>'#fff0e0', - -vlink=>'#800020'); + -vlink=>'#800020');#} $globaloutput.="