--- db/prgsrc/db.cgi 2003/04/20 12:21:13 1.109 +++ db/prgsrc/db.cgi 2010/01/10 19:19:44 1.156 @@ -2,49 +2,92 @@ use DBI; use CGI ':all'; -use strict; +#use strict; +use Encode; +my @softfields=("От Олега Степанова"); use Time::Local; +use Data::Dumper "Dumper"; +use URI::Escape; +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=(); +my $showNearQuestions=0; +$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 $HTMLDIR=""; +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; +$footer="../footer.html" if $opt_z; +$datefooter="../date" if $opt_z; +my $HTMLDIR="/znatoki/dimrub/db/baza/"; +$HTMLDIR="/files/"; my $realHTMLDIR; if ($^O =~ /win/i) { $realHTMLDIR="/html/znatoki/baza/"; } else { - $realHTMLDIR="/home/znatoki/public_html/dimrub/db/baza/"; + $realHTMLDIR="/home/znatoki/chgk-db/public_html/dimrub/db/files/"; } -my $usehtml=1; + + +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\// && $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 (!param('sstr') && param('all')) { - my $destination='http://db.chgk.info/all.html'; - Redirect($destination); - 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); +# exit; +#} my $thislocale; if ($^O =~ /win/i) { $thislocale = "Russian_Russia.20866"; @@ -55,8 +98,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', 'Своя игра', @@ -78,13 +121,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"; @@ -113,6 +164,12 @@ sub NewEnough { sub Redirect { my ($destination) = @_; +print header.< +EndOfHTML +; +=head + print <here< EndOfHTML ; +=cut } @@ -154,12 +212,12 @@ sub GetTournament { sub fetchquestion { my ($sth,$q,$WithTour)=@_; if ($WithTour) { - ($$q{'Question'},$$q{'Answer'},$$q{'Comments'},$$q{'Authors'}, + ($$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'}) = + $$q{'Title'}, $$q{'TourTitle'}, $$q{'FileName'},$$q{'PlayedAt'},$$q{'TourNumber'},$$q{'PlayedAt2'}) = $sth->fetchrow; } else { - ($$q{'Question'},$$q{'Answer'},$$q{'Comments'},$$q{'Authors'}, + ($$q{'QuestionId'}, $$q{'Question'},$$q{'Answer'},$$q{'PassCriteria'},$$q{'Comments'},$$q{'Authors'},$$q{'Sources'}, $$q{'Number'})= $sth->fetchrow; } @@ -167,24 +225,27 @@ sub fetchquestion { + sub SelectQuestions { my ($dbh,$q,$WithTour) = @_; my %q=(); - $_ = "QuestionId=$_" foreach @$q; - my $where=join " OR ",@$q; +# $_ = "QuestionId=$_" foreach @$q; +# my $where=join " OR ",@$q; + my $where=join ',',@$q; + $where &&= "QuestionId IN (".(join ',',$where).")"; $where||=1; $where="($where) AND Questions.ParentId=t1.Id AND t1.ParentId=t2.Id" if $WithTour; my $query; if ($WithTour) { - $query="SELECT Questions.Question, Answer, Comments, Authors, + $query="SELECT QuestionId, Questions.Question, Answer, PassCriteria, Comments, Authors, Sources, Questions.Number - , t2.Title, t1.Title, t2.FileName, t2.PlayedAt,t1.Number + , t2.Title, t1.Title, t2.FileName, t2.PlayedAt,t1.Number,t2.PlayedAt2 from Questions,Tournaments as t1, Tournaments as t2 WHERE $where"; } else { - $query="SELECT Questions.Question, Answer, Comments, Authors, + $query="SELECT QuestionId, Questions.Question, Answer, PassCriteria, Comments, Authors, Sources, Questions.Number from Questions WHERE $where"; } @@ -222,14 +283,24 @@ sub tourhref { my $res; if ($usehtml) { $res=$t; + $res=~s/\-q$//; + $res=~s/\-a$//; $res.=$a?"-a":"-q" unless $gr; $res.=".html"; $res=~s/(\#\d+)(.*)$/$2$1/; + my $t=$res; + $t=~s/\#.*$//; +# $res=~s/\.1// unless $gr ||$res=~/\.\d+$/;#-e "$realHTMLDIR$t"; + $t=$res; + $t=~s/\#.*$//; +# $res=~s/\.html/-q\.html/ unless -e "$realHTMLDIR$t"; + $res="$HTMLDIR$res" unless $opt_z; return $res; } else { $res=$url; - $res.="?tour=$t"; - $res.=$a?"?answers=1":""; + $res.=$a?"?answers=1&":"?"; + $res.="tour=$t"; + return $res; } @@ -294,11 +365,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; @@ -314,7 +385,7 @@ sub printform return < +action="/cgi-bin/db.cgi">

Поиск в базе вопросов

@@ -324,7 +395,7 @@ action="/znatoki/cgi-bin/db.cgi"> -
Вариант поиска: - + Простой (старый)  "Что? Где? Когда?" @@ -342,11 +413,11 @@ action="/znatoki/cgi-bin/db.cgi">  "Бескрылка"
Расширенный (с учетом грамматики, в вопросах всех типов) + Расширенный (с учетом грамматики, в вопросах всех типов)
Искать: - + Все слова Любое слово @@ -358,6 +429,8 @@ action="/znatoki/cgi-bin/db.cgi"> Ответ
+Зачёт
+
Комментарии
Автор
@@ -366,6 +439,9 @@ action="/znatoki/cgi-bin/db.cgi">
+ EOT @@ -384,6 +460,7 @@ sub proxy sub makeproxysstr { my ($dbh,$ptext)=@_; my $text=$$ptext; + POSIX::setlocale( &POSIX::LC_ALL, $thislocale ); $text=~tr/ёЁ/еЕ/; $text=~s/(${RLrl})p(${RLrl})/$1p$2/gom; $text=~s/p(${RLrl})/р$1/gom; @@ -392,6 +469,7 @@ sub makeproxysstr { $text=~s/[^йцукенгшщзхъфывапролджэячсмитьбюЙЦУКЕНГШЩЗХЪФЫВАПРОЛДЖЭЯЧСМИТЬБЮQWERTYUIOPASDFGHJKLZXCVBNM0-9]/ /g; $text=uc $text; my @list= $text=~m/(?:(?:${RLrl})+)|(?:[A-Za-z0-9]+)/gom; + my (%c, %good,$sstr); foreach (@list) { @@ -400,10 +478,9 @@ sub makeproxysstr { my @words=sort {$c{$a}<=> $c{$b}} @list; # $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; @@ -430,16 +507,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); +# @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); @@ -484,7 +576,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; @@ -546,7 +638,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) ; @@ -561,7 +658,6 @@ foreach (keys %wordsof) @tasks=sort {$relevance{$b}<=>$relevance{$a}} @tasks; - ############ @@ -621,7 +717,10 @@ sub Search { my (@sar, $i, $sth,$where,$query); if ($metod eq 'rus') { - my @tasks=russearch($dbh,$sstr,$all,$allnf); + my @tasks; + @tasks = russearch($dbh,$sstr,$all,$allnf); + + return @tasks } elsif ($metod eq 'proxy') @@ -635,13 +734,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::'. @@ -659,7 +758,6 @@ sub Search { ###### { -# foreach (qw/Question Answer Sources Authors Comments/) { foreach (param('searchin')) { # if (param($_)) { push @fields, "IFNULL($_, '')"; @@ -703,7 +801,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; @@ -728,7 +826,6 @@ sub PrintList { my ($dbh,$Questions,$shablon,$was)=@_; my $Output; my $first=param('first') ||1; - $first=$first-($first-1)%$outputkvo; my $fkvo=param('fkvo')||($#$Questions+1); my $last=$first+$outputkvo-1; @@ -805,16 +902,25 @@ sub PrintList { my @q=@$Questions[$first-1..$last-1]; my %q=(); my $sth=SelectQuestions($dbh,\@q,1); + my $qq; + my @Q; + for (0..$#q) { + %{$Q[$_]}=(); + fetchquestion($sth,$Q[$_],1); + $q{$Q[$_]{'QuestionId'}}=$Q[$_]; + } + for (my $i = $first; $i <= $last; $i++) { - fetchquestion($sth,\%q,1); + my $q=$q{$$Questions[$i-1]}; my $output; - $output = &PrintQuestion($dbh, \%q, 1, 0, 1,0,1 ); - if (param('metod') && (param('metod') eq 'rus' || param('metod') eq 'proxy')) + $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; - } else { $output=~s/($shablon)/\$1\<\/strong\>/gi; + $output=~s/(href="[^"]*?)(?:<.*?>)+([^"]*?)(?:<\/.*?>)+([^"]*?")/!1 $1$2$3 2!/g;#!!!! } + $Output.= $output; } $sth->finish; @@ -856,13 +962,15 @@ sub PrintSearch { } while (--$ss && (!$dbh->do ("insert into lastqueries (id,sstr,questions,allnf) values ($was, $qsstr,$tmp,$nf)"))); - $Output.= "Something is wrong...".br unless $ss; + $Output.= "Something is wrong...".br."\n" unless $ss; } } $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; @@ -925,9 +1033,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 { @@ -973,9 +1083,9 @@ sub PrintTournament { %Tournament = &GetTournament($dbh, $Id) if ($Id); - my ($URL) = $Tournament{'URL'}; - $URL=~s/http:\/znatoki\/boris\/reports\//$newsurl/ if $url=~/kulichki/; - $URL=~s/\/znatoki\/boris\/reports\//$newsurl/ if url=~/kulichki/;; + my ($URL) = $Tournament{'URL'}||''; + $URL=~s/http:\/znatoki\/boris\/reports\//$newsurl/ if $url=~/kulichki/ || $url=~/db.chgk.info/; + $URL=~s/\/znatoki\/boris\/reports\//$newsurl/ if url=~/kulichki/ || $url=~/db.chgk.info/; my ($Info) = $Tournament{'Info'}; my ($Copyright) = $Tournament{'Copyright'}; my $fname=$Tournament{'FileName'}; @@ -987,7 +1097,11 @@ sub PrintTournament { /Г/ && do { $output .= h2({align=>"center"}, "Группа: $Tournament{'Title'} ", - $Tournament{'PlayedAt'}||'') . p . "\n"; + $Tournament{'PlayedAt'}||'') . + ($Tournament{'PlayedAt2'}?' – '. + $Tournament{'PlayedAt2'}:'') . + + p . "\n"; last; }; /Ч/ && do { @@ -999,6 +1113,10 @@ sub PrintTournament { $title .= " $Tournament{'PlayedAt'}"; } + if ($Tournament{'PlayedAt2'}) { + $title .= ' – '.$Tournament{'PlayedAt2'}; + } + $output .= h2({align=>"center"}, "$title") . p . "\n"; $output.=&PrintEditor(\%Tournament); @@ -1009,9 +1127,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++) { @@ -1054,7 +1183,9 @@ sub PrintTournament { if ($SingleTour or ($Tournament{'Type'} =~ /Т/)) { $list .= dd(img({src=>$imgsrc, alt=>$alt}) . " " . $Tournament{'Title'} . " " . - ($Tournament{'PlayedAt'}||"") . $qnum) . + ($Tournament{'PlayedAt'}||"") . + ($Tournament{'PlayedAt2'}?' – '.$Tournament{'PlayedAt2'}:"") . + $qnum) . dl( dd("[" . a({href=>tourhref($textid,0)}, @@ -1065,12 +1196,13 @@ sub PrintTournament { } else { $list .= dd(a({href=> $url . "?tour=$textid&comp=1"}, - img({src=>'/icons/compressed.gif', alt=>'[ZIP]', border=>1})). - " " . + img({src=>'/icons/compressed.gif', alt=>'[ZIP]', border=>1})) . + " " . img({src=>$imgsrc, alt=>$alt}) . " " . a({href=>tourhref($textid,0,1)}, $Tournament{'Title'}. " ". - ($Tournament{'PlayedAt'}||'')) . $qnum); + ($Tournament{'PlayedAt'}||'')) . + ($Tournament{'PlayedAt2'}?' &ndash '. $Tournament{'PlayedAt2'}:''). $qnum); } } $output .= dl($list); @@ -1081,7 +1213,6 @@ sub PrintTournament { p("Дополнительная информация об этом турнире - по адресу " . a({-'href'=>$URL}, $URL)); } - if ($Copyright) { $output .= p("Копирайт: " . $Copyright); } @@ -1091,6 +1222,10 @@ sub PrintTournament { if ($Info) { $output .= p($Info); } + + $output.=p("XML"); + + return $output; } @@ -1102,6 +1237,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) = @_; @@ -1143,7 +1295,8 @@ sub PrintTour { $output .= h2({align=>"center"}, $Tournament{"Title"}, $Tournament{'PlayedAt'}||'', - "
", $Tour{"Title"} . + $Tournament{'PlayedAt2'}?' – '.$Tournament{'PlayedAt2'}:'', + "
\n", $Tour{"Title"} . " ($qnum вопрос$suffix)\n") . p; $output .=&PrintEditor(\%Tour); @@ -1151,30 +1304,43 @@ 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%'}); if ($Tournament{'URL'}) { - $output .= - p("Дополнительная информация об этом турнире - по адресу " . - a({-'href'=>$Tournament{'URL'}}, $Tournament{'URL'})); + $URL = $Tournament{'URL'}; + $URL=~s/http:\/znatoki\/boris\/reports\//$newsurl/ if $url=~/kulichki/ || $url=~/db.chgk.info/; + $URL=~s/\/znatoki\/boris\/reports\//$newsurl/ if url=~/kulichki/ || $url=~/db.chgk.info/; + + $output .= + p("Дополнительная информация об этом турнире - по адресу " . + a({-'href'=>$URL}, $URL)); } if ($Tournament{'Copyright'}) { $output .= p("Копирайт: " . $Tournament{'Copyright'}); } - if ($Tournament{'Info'}) { + if ($Tournament{'Info'} ) { $output .= p($Tournament{'Info'}); } + if ($Tour{'Info'} && ($Tournament{'Info'} ne $Tour{'Info'})) { + $output .= "!!".p($Tour{'Info'}); + } + + $output.=p("XML"); + my $n=$Tour{'Number'}; if ($answer == 0) { + my $nn=".$n"; + $nn="" if ($n==1 && !&IsTour($dbh, $Tour{'ParentId'}, $n + 1)); + $bottom .= - "[" . a({href=>tourhref($fname,1)}, - "ответы") . "] " . br; + "[" . a({href=>tourhref("$fname$nn",1)}, + "ответы") . "] " . br."\n"; } if ($n>1) { $bottom .= @@ -1182,7 +1348,7 @@ sub PrintTour { "предыдущий тур") . "] "; $bottom .= "[" . a({href=>tourhref("$fname.".($n-1),1)}, - "предыдущий тур с ответами") . "] " . br; + "предыдущий тур с ответами") . "] " . br."\n"; } if (&IsTour($dbh, $Tour{'ParentId'}, $n + 1)) { $bottom .= @@ -1199,24 +1365,54 @@ sub PrintTour { return $output; } + +sub escapeUrl { + my $uri = shift; + $uri=~s/<.*?>//g; + $uri =~ s/([Ю-Ъю-ъ]+)/URI::Escape::uri_escape_utf8(decode("koi8-r",$1))/eg; + return $uri; +} + sub PrintField { my ($header, $value, $text) = @_; if ($text) { $value =~ s/<[\/\w]*?>//sg; } else { - $value =~ s/^\s+/
    /mg; + if ($header=~/Комментар/) + { + $value=~s/^\s*$_[\.:]/p."\n".strong("$_").":\n"/me foreach @softfields; + } + + $value =~ s/^\s+/
\n    /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:\/\/\S+[^\s\)\(\,\.\]])/a({href=>escapeUrl($1)},$1)/egm if $header !~ /^Авто/;#!!!
+
+	    $value =~ s/\.\.\.\]/!!!ZAKR!!!/g;
+	    $value =~ s/пропущено\]/!!!PROP!!!/g;
+	    $value =~ s/пропущены\]/!!!PROP2!!!/g;
+	    $value =~ s/\[Раздаточный материал:(.*?)\]\s*\n/
Раздаточный материал<\/div> $1<\/div>\n$2/sm; + $value =~ s/!!!ZAKR!!!/\.\.\.\]/g; + $value =~ s/!!!PROP2!!!/пропущены\]/g; + + +# $value =~ s/(http:\/\/\S+[^\s\)\(\,\.])/make/eg if $header !~ /^Авто/;#!!! +# $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; # $value =~ s/^"/“/mg; # $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"}) . " " . a({href=>tourhref($fname,0,1)}, - $Question{'Title'}, $Question{'PlayedAt'}||'')); + $Question{'Title'}, $Question{'PlayedAt'}||'', + $Question{'PlayedAt2'}?' – '.$Question{'PlayedAt2'}:'')); $titles .= dl(dd(img({src=>"/icons/folder.open.gif"}) . " " . a({href=>tourhref("$fname.$Question{'TourNumber'}#$qnum",1)}, @@ -1268,6 +1467,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'}; @@ -1336,6 +1539,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); } @@ -1349,23 +1556,41 @@ EOTT $output.="" } - $output=~s/\(pic: ([^\)]*)\)/

/g unless $text; - my $qid=param('tour') ? (param('tour').".$Question{'Number'}" ): ''; + $output=~s/\(pic: ([^\)]*)\)/

<\/p>/g unless $text; + $output=~s/\(aud: ([^\)]*)\)//g unless $text; + + $output=~s/⌡/\ï/g; + $output=~s/⌠/\Ï/g; - $output.=br.a({href=> $url."?metod=proxy& + $paramtour||=param("tour"); + $fname=$fname.".$Question{'TourNumber'}" if $fname && $Question{'TourNumber'}; +$fname||=param('tour'); + my $qid=$fname ? ($fname.".$Question{'Number'}" ): ''; + + $output.=br."\n".a({href=> "/search/"."?metod=proxy& qid=$qid"}, 'Близкие вопросы').p - if $answer>0 && !$text && $qid; + if $answer>0 && !$text && $qid && $showNearQuestions; return $output; } # 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) = @_; @@ -1386,7 +1611,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 ='$_Д') "; @@ -1396,7 +1623,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); @@ -1415,13 +1642,13 @@ sub Get12Random { sub Include_virtual { my ($fn, $output) = (@_, ''); - + return "\n\n" if ($opt_z); open F , $fn or return ""; #die "Can't open the file $fn: $!\n"; while () { if (//&Include_virtual($1)/e; + s//&Include_virtual($1)/e; } if (//`$1`/e; @@ -1477,7 +1704,9 @@ sub PrintAll { $output .= dd(img({src=>"/icons/folder.gif", alt=>"[*]"}) . " " . a({href=>tourhref($textid,0,!$SingleTour)}, - $Tournament{'Title'}) ." " . ($Tournament{'PlayedAt'}||'') . " $New"); + $Tournament{'Title'}) ." " . ($Tournament{'PlayedAt'}||'') . + ($Tournament{'PlayedAt2'}?' – '.$Tournament{'PlayedAt2'}:'') . + " $New"); } if ($Id == 0 or $Tournament{'Type'} =~ /Г/ or $Tournament{'Type'} eq '') { for ($i = 0; $i <= $#Tours; $i++) { @@ -1509,9 +1738,21 @@ sub PrintDates { next if (!$array[0]); %Tournament = &GetTournament($dbh, $array[0]); + my $textid; + if ($textid=$Tournament{'FileName'}) + { + $textid=~s/\.txt//; + } + elsif ($textid=$Tournament{'Number'}) + { + $fname=~s/\.txt//; + $textid="$fname.$textid"; + } + else {$textid=$Tournament{'Id'}}; $list .= dd(img({src=>"/icons/folder.gif", alt=>"[*]"}) . - " " . a({href=>tourhref($Tournament{'FileName'},0,1)}, - $Tournament{'Title'}, $Tournament{'PlayedAt'}||'')); + " " . a({href=>tourhref($textid,0,1)}, + $Tournament{'Title'}, $Tournament{'PlayedAt'}||'', + $Tournament{'PlayedAt2'}?' – '.$Tournament{'PlayedAt2'}:'')); } $sth->finish; $output .= dl($list); @@ -1554,7 +1795,7 @@ sub PrintQOfAuthor $suffix = 'я'; } $Output.= printform; - $Output.= p({align=>"center"}, "Автор ".strong("$name $surname. ") + $Output.= p({align=>"center"}, "Автор ".strong("$name $surname ") . " : $hits попадани$suffix."); @@ -1628,13 +1869,14 @@ sub WriteFile { $fname=~s/.*\/(\w+)/$1/; my $query= "SELECT Id, Title, Copyright, Info, URL, - Editors, EnteredBy, PlayedAt, CreatedAt - from Tournaments where FileName=".$dbh->quote("$fname.txt"); + Editors, EnteredBy, PlayedAt, CreatedAt, PlayedAt2 + from Tournaments where FileName= + '$fname' OR FileName=".$dbh->quote("$fname.txt"); my $sth=$dbh->prepare($query); my (%Question,%editor,%qnumber,%copyright,%author,%vid,%tourtitle); $sth->execute; my ($Id, $Title, $Copyright, $Info, $URL, - $Editors, $EnteredBy, $PlayedAt, $CreatedAt)= + $Editors, $EnteredBy, $PlayedAt, $CreatedAt, $PlayedAt2)= $sth->fetchrow; return -1 unless $Id; open (OUT, ">$TMPDIR/$fname.txt") || print STDERR "Error in $fname.txt\n"; @@ -1643,6 +1885,10 @@ sub WriteFile { my ($year,$month,$day)=split /-/, $date; # $month=0,$date=0 if $year && $month==1 && $day==1; my $pdate=sprintf("%02d-%3s-%4d",$day,$months[$month],$year); + if ($PlayedAt2) { + my ($year,$month,$day)=split /-/, $date; + $pdate .= sprintf(" - %02d-%3s-%4d",$day,$months[$month],$year); + } print OUT "Дата:\n$pdate\n\n" if $date; @@ -1752,6 +1998,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" @@ -1772,8 +2019,8 @@ sub WriteFile { sub Bottom { - my $output.=&Include_virtual("../dimrub/db/footer.html")||""; - $output.=p."

Обновление: ".&Include_virtual("../dimrub/db/date")."
"; + my $output.=&Include_virtual("$footer")||""; + $output.=p."
Обновление: ".&Include_virtual("$datefooter")."
"; $output.=< function toggle(e) { @@ -1795,28 +2042,84 @@ MAIN: { setlocale(LC_CTYPE,'russian'); + POSIX::setlocale( &POSIX::LC_ALL, $thislocale ); my($i, $tour); my($text) = (param('text')) ? 1 : 0; - if (param('qid') && (param('qid')=~/^\d+$/)) { - my $destination='http://db.chgk.info/search.html'; + $tour = (param('tour')) ? param('tour') : 0; + my $texttour=$tour; + my ($sth,$dbh); + 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 header.h1("Временные проблемы") . "База вопросов временно не + работает. Заходите попозже."; + print &Include_virtual("$reklama") if $url!~/localhost/; + print end_html; + die "Can't connect to DB chgk\n"; + }; + $dbh->do("set names koi8r"); + + if (param('qid') && (param('qid')=~/^\d+$/) || $tour && $tour=~/^\d+$/) { +# my $destination='http://chgk.zaba.ru/search.html'; # print header (-'Content-Type' => 'text/html', # -'Location:'=> 'http:\\db.chgk.info'); Redirect($destination); exit } - if ($text) { + if (0 && $tour && !param('qnumber') && (!param('answers')||(param('answers')<=1))) + { + my $n=param('tour'); + $n=~s/.txt$//; + my $gr=($n=~/^[A-Z]/) || (-e "$realHTMLDIR$n.html"); + my $destination=tourhref($tour,param('answers')||0,$gr); + my $d=$destination; + $d=~s/$HTMLDIR/$realHTMLDIR/; +# print header.$destination; +# print header."$d|".(-e "$realHTMLDIR$n.html"); + if (-e $d) { + Redirect($destination); + exit + } + $d=~s/\.\d+//; + $destination=~s/\.\d+//; + if (-e $d) { + Redirect($destination); + exit + } + + } + + if ($tour !~ /^[0-9]*$/) { + if ($tour=~/\./) + { + my ($fname,$n)= split /\./ , $tour; + + $sth = $dbh->prepare( + "SELECT t2.Id FROM Tournaments as t1, + Tournaments as t2 + WHERE (t1.FileName = '$fname.txt' OR t1.FileName='$fname') + AND t1.Id=t2.ParentId AND t2.Number=$n"); + } + else + { + $sth = $dbh->prepare("SELECT Id FROM Tournaments + WHERE FileName = '$tour.txt' OR + FileName = '$tour'"); + } + $sth->execute; + $tour = ($sth->fetchrow)[0]; + $sth->finish; + } + + + if ($text && !param ('comp')) { print header('text/plain'); - } else {print header;} - my($dbh) = DBI->connect("DBI:mysql:chgk", "piataev", "") - or do { - print h1("Временные проблемы") . "База вопросов временно не - работает. Заходите попозже."; - print &Include_virtual("../dimrub/db/reklama.html") if $url!~/localhost/; - print end_html; - die "Can't connect to DB chgk\n"; - }; + } elsif (!param('comp')) { + print header(-charset =>'koi8-r')} my $sstr=param('sstr'); + $opt_z||=param("makehtml"); if (param('qid')) { my $sth; my $qid=param('qid'); @@ -1824,19 +2127,20 @@ MAIN: { my ($fname,$t,$n)= split /\./ , $qid; $n=$t,$t='' unless $n; + $t||=1; if ($t) { $sth = $dbh->prepare( "SELECT t2.Id FROM Tournaments as t1, Tournaments as t2 - WHERE t1.FileName = '$fname.txt' + WHERE (t1.FileName = '$fname.txt' OR t1.FileName='$fname') AND t1.Id=t2.ParentId AND t2.Number=$t"); } - else - { - $sth = $dbh->prepare("SELECT Id FROM Tournaments - WHERE FileName = '$fname.txt'"); - } +# else +# { +# $sth = $dbh->prepare("SELECT Id FROM Tournaments +# WHERE FileName = '$fname.txt' OR FileName = '$fname'" ); +# } $sth->execute; $tour = ($sth->fetchrow)[0]; $sth->finish; @@ -1867,20 +2171,27 @@ MAIN: my $title="Результаты поиска на \"". ($proxysstr||$sstr) .'"' if ($proxysstr||$sstr); $title||="База вопросов"; - $globaloutput.=start_html(-"title"=>$title, -author=>'dimrub@icomverse.com', -bgcolor=>'#fff0e0', - -vlink=>'#800020'); + -vlink=>'#800020');#} $globaloutput.="\n"; - $globaloutput.=&Include_virtual("../dimrub/db/reklama.html")||''; + $globaloutput.=&Include_virtual("$reklama")||''; } - if (length ($qs)<=255 && $qs !~ /(sstr)|(rand)|(comp)|(all=)/i) { + if ($usehash && !$opt_z && length ($qs)<=255 && $qs !~ /(sstr)|(rand)|(comp)|(all=)/i) { my $sth=$dbh->prepare("SELECT page,times,t from hash where query=".$dbh->quote($qs)); $sth->execute(); my ($p,$times,$t)=$sth->fetchrow(); @@ -1904,29 +2215,7 @@ th {font-size: x-small; font-family : sa } $sth->finish; } - $tour = (param('tour')) ? param('tour') : 0; - my $sth; - if ($tour !~ /^[0-9]*$/) { - if ($tour=~/\./) - { - my ($fname,$n)= split /\./ , $tour; - $sth = $dbh->prepare( - "SELECT t2.Id FROM Tournaments as t1, - Tournaments as t2 - WHERE t1.FileName = '$fname.txt' - AND t1.Id=t2.ParentId AND t2.Number=$n"); - } - else - { - $sth = $dbh->prepare("SELECT Id FROM Tournaments - WHERE FileName = '$tour.txt' OR - FileName = '$tour'"); - } - $sth->execute; - $tour = ($sth->fetchrow)[0]; - $sth->finish; - } if (param('rand')) { @@ -1974,25 +2263,25 @@ EOT elsif (param('getfile')){ $globaloutput.=&writefile } elsif (param('all')) { - my $destination='http://db.chgk.info/all.html'; - Redirect($destination); - exit; -# $globaloutput.=&PrintAll($dbh, 0); +# my $destination='http://db.chgk.info/all.html'; +# Redirect($destination); +# exit; + $globaloutput.=&PrintAll($dbh, 0); } elsif (param('from_year') && param('to_year')) { $globaloutput.=&PrintDates($dbh); } elsif (param('comp')) { - $globaloutput.="Content-Type: application/octet-stream\n"; - $globaloutput.="Content-Type: application/force-download\n"; - $globaloutput.="Content-Type: application/download\n"; - $globaloutput.="Content-Type: application/x-zip-compressed; name=db.zip\n"; - $globaloutput.="Content-Disposition: attachment; filename=db.zip \n\n"; + print "Content-Type: application/octet-stream\n"; + print "Content-Type: application/force-download\n"; + print "Content-Type: application/download\n"; + print "Content-Type: application/x-zip-compressed; name=$texttour.zip\n"; + print "Content-Disposition: attachment; filename=$texttour.zip \n\n"; $tour ||= 0; my (@files) = &PrintArchive($dbh, $tour); WriteFile($dbh,$_) foreach @files; open F, "$ZIP -j - @files |"; binmode(F); binmode(STDOUT); - $globaloutput.= join "",; + print join "",; close F; $dbh->disconnect; exit; @@ -2008,7 +2297,7 @@ EOT exit; } - elsif (!$opt_z) { + elsif (!$opt_z && !param("makehtml")) { my $QuestionNumber=0; my $qnum; if ($qnum=param('qnumber')){ @@ -2018,14 +2307,16 @@ EOT $QuestionNumber=($sth->fetchrow)[0]||0; } if ($QuestionNumber) { - $globaloutput.= &PrintQuestion($dbh, $QuestionNumber, param('answer')||0, $qnum, 1,0,0); + $globaloutput.= &PrintQuestion($dbh, $QuestionNumber, $withanswers||0, $qnum, 1,$text,0); # $dbh, $Id, $answer, $qnum, $title, $text } else { - $globaloutput.=&PrintTournament($dbh, $tour, param('answer')); + $globaloutput.=&PrintTournament($dbh, $tour, $withanswers); } } else { - open TS, "timestamp"; + $opt_z=1; + $url="http://db.chgk.info/cgi-bin/db.cgi"; + open TS, $timestamp; my $d=$dbh->quote(); close TS; open FF, ">${realHTMLDIR}index.html" or die "ERROR! - ${HTMLDIR}index.html\n"; @@ -2047,7 +2338,7 @@ EOT # FROM Tournaments as t1, Tournaments as t2 # WHERE t1.CreatedAt>$d AND t2.ParentId=t1.Id GROUP BY t1.Id"); my ($sth) = $dbh->prepare("SELECT t1.Id, t1.FileName, t1.Type, count(t2.Id) FROM Tournaments as t1 LEFT JOIN Tournaments as t2 - ON t2.ParentId=t1.id WHERE t1.CreatedAt>$d GROUP BY t1.Id"); + ON t2.ParentId=t1.id WHERE t1.CreatedAt>=$d GROUP BY t1.Id"); $sth->execute; my ($Id,$fname,$type,$c); while (($Id,$fname,$type,$c)=$sth->fetchrow,$Id) { @@ -2056,8 +2347,9 @@ my ($sth) = $dbh->prepare("SELECT t1.Id, $fname=~s/\.txt$//; if ($type=~/Т/ || $c<=1) { - open FF, ">$realHTMLDIR$fname-q.html" or die "ERROR! - $HTMLDIR$fname-q.html\n"; + open FF, ">$realHTMLDIR$fname-q.html" or die "ERROR! - $fname-q.html\n"; my $o=$globaloutput; + $paramtour=$fname; $o.=&PrintTournament($dbh, $Id, 0); $o.=&Bottom; print FF $o; @@ -2070,7 +2362,7 @@ my ($sth) = $dbh->prepare("SELECT t1.Id, close FF; } else { - open FF, ">$realHTMLDIR$fname.html" or die "ERROR! - $HTMLDIR$fname-q.html\n"; + open FF, ">$realHTMLDIR$fname.html" or die "ERROR! - $fname-q.html\n"; my $o=$globaloutput; $o.=&PrintTournament($dbh, $Id, 0); $o.=&Bottom; @@ -2085,7 +2377,7 @@ my ($sth) = $dbh->prepare("SELECT t1.Id, } if (!$opt_z){ print $globaloutput; - if (($qs!~ /(rand)|(sstr)|(comp)/i) && (length $qs<=255)) { + if (($qs!~ /(rand)|(sstr)|(comp)/i) && (length $qs<=255) && $usehash) { $globaloutput= $dbh->quote($globaloutput); $dbh->do("insert into hash (query,page) values (". $dbh->quote($qs).