--- db/prgsrc/db.cgi 2001/11/20 21:33:36 1.34 +++ db/prgsrc/db.cgi 2004/01/10 22:52:20 1.128 @@ -2,53 +2,167 @@ use DBI; use CGI ':all'; -use Text::Query; use strict; use Time::Local; use POSIX qw(locale_h); use locale; -#open STDERR, ">errors"; -my $printqueries=1; +use vars qw($opt_z); +use Getopt::Std; +getopts('z'); +$opt_z||=param("makehtml"); +my $timestamp="_timestamp.tmp"; +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"; + +my $datefooter="../dimrub/db/date"; + +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/piataev/public_html/dimrub/db/files/"; +} +my $usehtml=$opt_z||0; +$usehtml=1; +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 $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/) { + 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; +#} +my $thislocale; +if ($^O =~ /win/i) { + $thislocale = "Russian_Russia.20866"; +} else { + $thislocale = "ru_RU.KOI8-R"; +} +POSIX::setlocale( &POSIX::LC_ALL, $thislocale ); + +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', 'Ответ', + 'Comments', 'Комментарии', 'Authors', 'Автор', + 'Sources', 'Источник','old','Старый','rus','Новый', + 'chgk', 'ЧГК', 'brain', 'Брейн-ринг','game', 'Своя игра', + 'ehruditka', 'Эрудитка', 'beskrylka', 'Бескрылка', 'igp', 'Интернет' +); my %searchin; +my $rl=qr/[йцукенгшщзхъфывапролджэячсмитьбюё]/; +my $RL=qr/[ЙЦУКЕНГШЩЗХЪЭЖДЛОРПАВЫФЯЧСМИТЬБЮЁ]/; +my $RLrl=qr/(?:(?:${rl})|(?:${RL}))+/; +my $l=qr/(?:(?:${RLrl})|(?:[\w\-]))+/; +my $Ll=qr/(?:[A-Z])|(?:${RL})/; +my %metodchar=('rus',1,'old',2); -my $thislocale; + +$searchin{$_}=1 foreach param('searchin'); +my %TypeName=('children'=>'Д', 'game'=>'Я', 'igp'=>'И', + 'chgk'=>'Ч', 'brain'=>'Б', 'beskrylka'=>'Л','ehruditka'=>'Э'); -$searchin{'question'}=param('Question'); -$searchin{'answer'}=param('Answer'); -$searchin{'comment'}=param('Comment'); -$searchin{'authors'}=param('Authors'); -$searchin{'sources'}=param('Sources'); +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`; -chomp $PWD; -my ($SRCPATH) = "$PWD/../dimrub/src"; -my ($ZIP) = "/home/piataev/bin/zip"; +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 $DUMPFILE = "/tmp/chgkdump"; my ($SENDMAIL) = "/usr/sbin/sendmail"; +my ($TMPDIR) = "/var/tmp"; my ($TMSECS) = 30*24*60*60; -my (%RevMonths) = +my (%RevMonths) = ('Jan', '0', 'Feb', '1', 'Mar', '2', 'Apr', '3', 'May', '4', 'Jun', '5', 'Jul', '6', 'Aug', '7', 'Sep', '8', 'Oct', '9', 'Nov', '10', 'Dec', '11', 'Янв', '0', 'Фев', 1, 'Мар', 2, 'Апр', 3, 'Май', '4', - 'Июн', '5', 'Июл', 6, 'Авг', '7', 'Сен', '8', + 'Июн', '5', 'Июл', 6, 'Авг', '7', 'Сен', '8', 'Окт', '9', 'Ноя', '19', 'Дек', '11'); +my @months=('000','Jan',"Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct", + "Nov","Dec"); + # Determine whether the given time is within 2 months from now. sub NewEnough { my ($a) = @_; my ($year, $month, $day) = split('-', $a); - + $month=1 if ($month<=0); + $day=1 if ($day<=0); return (time - timelocal(0, 0, 0, $day, $month -1, $year) < $TMSECS); } # Reads one question from the DB. Gets DB handler and Question ID. + +sub Redirect { +my ($destination) = @_; +print header.< +EndOfHTML +; +=head + +print < +Redirection + +

Redirection

+

It appears that your browser cannot handle redirections +automatically. You can proceed to the randomly-selected page +by clicking here.

+ + +EndOfHTML +; +=cut +} + + + + sub GetTournament { my ($dbh, $Id) = @_; my (%Tournament, $field, @arr); @@ -63,10 +177,58 @@ sub GetTournament { foreach $name (@{$sth->{NAME}}) { $Tournament{$name} = $arr[$i++]; } - + $sth->finish; return %Tournament; } +sub fetchquestion { + my ($sth,$q,$WithTour)=@_; + if ($WithTour) { + ($$q{'QuestionId'}, $$q{'Question'},$$q{'Answer'},$$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{'Number'})= + $sth->fetchrow; + } +} + + + + +sub SelectQuestions { + my ($dbh,$q,$WithTour) = @_; + my %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 QuestionId, Questions.Question, Answer, 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, + Questions.Number from Questions + WHERE $where"; + } + + my $sth; + $sth=$dbh->prepare($query); + $sth->execute; + return $sth; +} + + # Reads one question from the DB. Gets DB handler and Question ID. sub GetQuestion { my ($dbh, $QuestionId) = @_; @@ -84,16 +246,41 @@ sub GetQuestion { $Question{$name} = $arr[$i++]; } + $sth->finish; return %Question; } +sub tourhref { + my ($t,$a,$gr)=@_; + my $res; + if ($usehtml) { + $res=$t; + $res.=$a?"-a":"-q" unless $gr; + $res.=".html"; + $res=~s/(\#\d+)(.*)$/$2$1/; + my $t=$res; + $t=~s/\#.*$//; + $res=~s/\.1// unless -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":""; + return $res; + } + +} + # Gets numbers of all the questions from the given tour. sub GetTourQuestions { my ($dbh, $ParentId) = @_; my (@arr, @Questions); - - my ($sth) = $dbh->prepare("SELECT QuestionId FROM Questions - WHERE ParentId=$ParentId ORDER BY QuestionId"); + my ($sth) = $dbh->prepare("SELECT QuestionId FROM Questions + WHERE ParentId=$ParentId order by Number"); $sth->execute; @@ -101,6 +288,7 @@ sub GetTourQuestions { push @Questions, $arr[0]; } + $sth->finish; return @Questions; } @@ -117,10 +305,156 @@ sub GetTours { while (@arr = $sth->fetchrow) { push @Tours, $arr[0]; } - + $sth->finish; return @Tours; } +sub count +{ + my ($dbh,$word)=@_; + $word=$dbh->quote(uc $word); + my $query="SELECT number from nests,nf where $word=w1 AND w2=nf.id"; + my $sth=$dbh->prepare($query); + $sth->execute; + my @a=$sth->fetchrow; + $sth->finish; + $a[0]||0; +} + + +sub printform +{ + + my $qnumber=(" "x10)."Выводить по + "; +#textfield(-name=>'kvo', +# -default=>6, +# -size=>3, +# -maxlength=>5)." вопросов"; + my $sstr=param('sstr'); + my @df=keys %searchin; + my %checked; + $checked{lc $_}="" foreach ('Question','Answer','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], + 'false',\%rusfieldname); + @df=param('type'); + @df=('chgk','brain','igp','game','ehruditka','beskrylka') unless @df; + $checked{lc $_}="checked" foreach @df; + my $all=param('all') && param('all') eq 'yes'; + + $checked{'all'}=$all?"checked":""; + $checked{'any'}=$all?"":"checked"; + $checked{lc param('metod')}="checked"; + $checked{'rus'}=1 unless $checked{'rus'} || $checked{'old'}; + +################################################# +return +< +

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

+ + + $qnumber +

+ + + + + + + + + + + + + +
Вариант поиска: + + Простой (старый) + + "Что? Где? Когда?" + + "Брейн-Ринг" + + "Интернет" +
+ "Своя игра" + + "Эрудитка" + + "Бескрылка" +
Расширенный (с учетом грамматики, в вопросах всех типов) +
Искать: + +Все слова + +Любое слово +
Поля для поиска: + +Вопрос + +Ответ
+
+Комментарии
+
+Автор
+
+Источник
+
+ + +EOT +.endform +.hr + +} + +sub proxy +{ + my ($dbh,$ptext,$allnf)=@_; + my $sstr=makeproxysstr($dbh,$ptext,$allnf); + return russearch($dbh,$sstr,0,$allnf); +} + +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; + $text=~s/(${RLrl})p/$1р/gom; + $text=~s/\s+/ /gmo; + $text=~s/[^йцукенгшщзхъфывапролджэячсмитьбюЙЦУКЕНГШЩЗХЪФЫВАПРОЛДЖЭЯЧСМИТЬБЮQWERTYUIOPASDFGHJKLZXCVBNM0-9]/ /g; + $text=uc $text; + my @list= $text=~m/(?:(?:${RLrl})+)|(?:[A-Za-z0-9]+)/gom; + + my (%c, %good,$sstr); + foreach (@list) + { + $c{$_}=count($dbh,$_)||10000; + } + my @words=sort {$c{$a}<=> $c{$b}} @list; + +# $good{$words[$_]}=1 foreach 0..4; + foreach (@words) + { + $good{$_}=1 if $c{$_}<200; + } + + $good{$words[$_]}=0 foreach 16..$#words; + + $sstr.=" $_" foreach grep {$good{$_}} @list; + $$ptext=$sstr; + return $sstr; +} + + sub russearch { my ($dbh, $sstr, $all,$allnf)=@_; my (@qw,@w,@tasks,$qw,@arr,$nf,$sth,@nf,$w,$where,$e,@where,%good,$i,%where,$from); @@ -137,19 +471,21 @@ sub russearch { my %relevance; my @blob; my %count; - + 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; + #----------- foreach $i (0..$#w) # заполняем массив @nf начальных форм # $nf[$i] -- ссылка на массив возможных # начальных форм словоформы $i - { + { $qw= $dbh->quote (uc $w[$i]); $query=" select distinct w2 from nests where w1=$qw"; -print "$query",br if $printqueries; $sth=$dbh -> prepare($query); $sth -> execute; @{$nf[$i]}=(); @@ -157,10 +493,11 @@ print "$query",br if $printqueries; { push (@{$nf[$i]},$arr[0]) } + $sth->finish; } - my @bad=grep {!$nf[$_]} 0..$#w; # @bad -- номера словоформ, + my @bad=grep {!@{$nf[$_]}} 0..$#w; # @bad -- номера словоформ, # которых нет в словаре if (@bad) #есть неопознанные словоформы @@ -179,7 +516,6 @@ print "$query",br if $printqueries; my $kvo=0; push @$allnf, @{$_} foreach @nf; -print "nf=@$allnf"; foreach $i (0..$#w) #запросы в базу... { @@ -189,30 +525,10 @@ print "nf=@$allnf"; - $_= " word2question.word=".$_. ' ' foreach @arr; + $_= " word2question.word=$_" foreach @arr; $_= " nf.id=".$_. ' ' foreach @arr1; - -# $_= " nests.w2=".$_. ' ' foreach @arr2; -# $query="select w1 from nests where". (join ' OR ', @arr2); -#print $query if $printqueries; -# $sth=$dbh -> prepare($query); -# $sth->execute; -# while (@ar=$sth->fetchrow) -# { -# $ar[0]=~s/(.)/&nocase($1)/ge; -# push(@sf,'(?:'.$ar[0].')'); -# } -# $selectshablon=join '|',@sf; - -#print $selectshablon,br if $printqueries; - -# $selectshablon=qr/$selectshablon/i; - - - - - $query="select questions from word2question where". (join ' OR ', @arr); -print "$query\n",br if $printqueries; +# @arr=(0) unless @arr; + $query="select questions from word2question where (". (join ' OR ', @arr).") AND length(questions)<80000"; $sth=$dbh -> prepare($query); $sth->execute; @@ -222,8 +538,8 @@ print "$query\n",br if $printqueries; { @blob=(@blob,unpack 'C*',$arr[0]); } + $sth->finish; $query="select number from nf where ".(join ' OR ', @arr1); -print "$query\n",br if $printqueries; $sth=$dbh -> prepare($query); $sth->execute; @@ -231,7 +547,7 @@ print "$query\n",br if $printqueries; { $frequence[$i]+=$arr[0]; } - + $sth->finish; if (@blob < 4) @@ -251,9 +567,10 @@ print "$query\n",br if $printqueries; { ($field,$lo,$hi,$wordnumber)=@blob[$ii..($ii+3)]; $ii+=4; - $number=$lo+$hi*256; - $field=$fieldname{$field}; - if ($searchin{lc $field}) + my $addnumber=($field >> 4) << 16; + $number=(($field >> 4) << 16)+($hi << 8) + $lo; + $field=$fieldname{$field & 0xF}; + if ($searchin{$field}) { push @{$tasksof{$i}{$number}}, $wordnumber; # дополнили в хэше, висящем на @@ -270,7 +587,6 @@ print "$query\n",br if $printqueries; } } #foreach $i -#print "keys tasksof", join ' ', keys %{$tasksof{0}}; #Ищем пересечение или объединение списков вопросов (значений %tasksof) foreach $sf (keys %tasksof) { @@ -280,7 +596,6 @@ print "$query\n",br if $printqueries; keys %count) ; -print "\n\$#tasks=",$#tasks,br if $printqueries; ############ Сортировка найденных вопросов foreach (keys %wordsof) @@ -290,14 +605,9 @@ foreach (keys %wordsof) @tasks=sort {$relevance{$b}<=>$relevance{$a}} @tasks; - ############ -print "tasks=@tasks"; -#print "$_ $relevance{$_} | " foreach @tasks; -#print br; -print "allnf=@$allnf",br if $printqueries; return @tasks; } @@ -348,85 +658,106 @@ if $$words{$first}; # Returns list of QuestionId's, that have the search string in them. sub Search { - my ($dbh, $sstr,$metod,$all,$allnf) = @_; + my ($dbh, $s,$metod,$all,$allnf) = @_; + my $sstr=$$s; my (@arr, @Questions, @fields); - my (@sar, $i, $sth,$where); - -# push @fields, 'Question'; - + my (@sar, $i, $sth,$where,$query); if ($metod eq 'rus') { my @tasks=russearch($dbh,$sstr,$all,$allnf); return @tasks } + elsif ($metod eq 'proxy') + { + my @task=proxy($dbh,$s,$allnf); + return @task + } + ###Simple and advanced query processing. Added by R7 - if ($metod eq 'simple' || $metod eq 'advanced') + if ($metod eq 'simple' || $metod eq 'advanced') { foreach (qw/Question Answer Sources Authors Comments/) { if (param($_)) { - push @fields, $_; + push @fields, $_; } } @fields=(qw/Question Answer Sources Authors Comments/) unless scalar @fields; my $fields=join ",", @fields; my $q=new Text::Query($sstr, - -parse => 'Text::Query::'. + -parse => 'Text::Query::'. (($metod eq 'simple') ? 'ParseSimple':'ParseAdvanced'), -solve => 'Text::Query::SolveSQL', -build => 'Text::Query::BuildSQLMySQL', -fields_searched => $fields); $where= $$q{'matchexp'}; - my $query= "SELECT Questionid FROM Questions + $query= "SELECT Questionid FROM Questions WHERE $where"; - print br."Query is: $query".br if $debug; $sth = $dbh->prepare($query); } else -###### +###### { - foreach (qw/Question Answer Sources Authors Comments/) { - if (param($_)) { +# foreach (qw/Question Answer Sources Authors Comments/) { + foreach (param('searchin')) { +# if (param($_)) { push @fields, "IFNULL($_, '')"; - } +# } } @sar = split " ", $sstr; for $i (0 .. $#sar) { $sar[$i] = $dbh->quote("%${sar[$i]}%"); } - + $_.=' ' foreach (@fields); # Это чтобы последнее слово поля + # не сливалось с первым словом + # следующего поля, R7 my($f) = "CONCAT(" . join(',', @fields) . ")"; if (param('all') eq 'yes') { $sstr = join " AND $f LIKE ", @sar; } else { $sstr = join " OR $f LIKE ", @sar; } + + my $query; + $query="SELECT QuestionId FROM Questions + WHERE ($f LIKE $sstr) AND (".&makewhere.") ORDER BY QuestionId"; -my $query="SELECT QuestionId FROM Questions - WHERE $f LIKE $sstr ORDER BY QuestionId"; -print $query if $printqueries; - $sth = $dbh->prepare($query) + $sth = $dbh->prepare($query) } #else -- processing old-style query (R7) $sth->execute; while (@arr = $sth->fetchrow) { - push @Questions, $arr[0]; + push @Questions, $arr[0] unless $forbidden{$arr[0]}; } - + $sth->finish; + return @Questions; } +sub makewhere { + my @type=param('type'); + my $type=''; + + $type .= ($_=$TypeName{$_}) foreach @type; + my $where=' 0 '; + foreach (@type) { + $where.= " OR (Type ='$_') OR (Type ='$_Д') OR (Type ='Д$_') "; + } + $where.= "OR (Type='ЧБ')" if ($type=~/Ч|Б/); + return $where; +} + # Substitute every letter by a pair (for case insensitive search). - my (@letters) = qw/аА бБ вВ гГ дД еЕ жЖ зЗ иИ йЙ кК лЛ мМ нН оО + my (@letters) = qw/аА бБ вВ гГ дД еЕ жЖ зЗ иИ йЙ кК лЛ мМ нН оО пП рР сС тТ уУ фФ хХ цЦ чЧ шШ щЩ ьЬ ыЫ эЭ юЮ яЯ/; - + sub NoCase { - my ($sstr) = shift; + my ($sstr) = shift; my ($res); if (($res) = grep(/$sstr/, @letters)) { @@ -436,21 +767,161 @@ sub NoCase { } } +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; + $last=$fkvo if $fkvo<$last; + my($f,$l); + my $nav=''; + my $qs=query_string; + $qs=~s/\;/\&/g; + $qs=~s/\&first\=[^\&]+//g; + my $sstr=param('sstr')||''; + $qs=~s/sstr=[^\&]+/sstr=$sstr/; + if ($usewas) { + $qs=~s/\&was=[^\&]+//; + $qs.="&was=$was" if $was; + $qs.="&fkvo=$fkvo" if $was; + } + if ($first>$outputkvo*3+1) + { + $nav.= + (" "x4). + a({href=>$url."?".$qs."\&first=1"},"<<").(" "x4). + a({href=>($url."?".$qs."\&first=".($first-$outputkvo))},"<").(" "x4) + } + else {$nav.=' 'x15;} + + my ($fprint,$lprint); + my $llprint=$fkvo- ($fkvo)%$outputkvo+1; # + if ($fkvo<=$outputkvo*7) + { $fprint=1; + $lprint=$llprint; + } + elsif ($first>$outputkvo*3 && $fkvo-$first>$outputkvo*3) + { + $fprint=$first-$outputkvo*3; + $lprint=$first+$outputkvo*3; + } + elsif ($first<=$outputkvo*3) + { + $fprint=1; $lprint=6*$outputkvo+1; + } + else + { + $lprint=$llprint; + $fprint=$lprint-$outputkvo*6 + } + +# my $fprint=($first>$outputkvo*3) ? $first-$outputkvo*3 : 1; +# my $lprint=$#$Questions+1-$fprint>$outputkvo*7 ? $outputkvo*7 :$#$Questions+1; +# if ($lprint-$fprint<$outputkvo*6 && $fprint>1) +# { +# $fprint=$lprint-$outputkvo*6; +# $fprint=1 if ($fprint<=0) +# } + + + + for($f=$fprint; $f<=$lprint; $f+=$outputkvo) + { +# next if $first-$f>$outputkvo*3; + $l=$f+$outputkvo-1; + $l=$fkvo if $l>$fkvo+1; + if ($f==$first) {$nav.="[$f-$l] ";} + else { + $nav.= "[".a({href=>($url."?".$qs."\&first=$f")},"$f-$l")."] ";} + } + if ($lprint+$outputkvo<$fkvo) + { + $nav.= + (" "x4). + a({href=>($url."?".$qs."\&first=".($first+$outputkvo))},">").(" "x4). + a({href=>$url."?".$qs."\&first=$llprint"},">>").(" "x4) + } + $Output.= "$nav".br."\n"; + 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++) { + 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=~s/\b($shablon)\b/\$1\<\/strong\>/gi; + $output=~s/($shablon)/\$1\<\/strong\>/gi; + } + $Output.= $output; + } + $sth->finish; + + $Output.= "$nav".br."\n"; + return $Output; +} + sub PrintSearch { - my ($dbh, $sstr, $metod) = @_; + my $Output=''; + my ($dbh, $sstr, $metod,$was) = @_; + my $t=time; + $Output.= printform; my @allnf; - my (@Questions) = &Search($dbh, $sstr,$metod,$all,\@allnf); + my @Questions; + $was=0 if $metod eq 'proxy'; + if ($usewas && $was && ($metod ne 'proxy')) + { + my $sth=$dbh->prepare ("select sstr,questions,allnf from lastqueries where id=".param('was')); + $sth->execute; + my ($q,$nf); + ($sstr, $q,$nf)=($sth->fetchrow); + @Questions=unpack 'L*',$q; + @allnf=unpack 'L*',$nf; + $sth->finish; + } + if (!$was || ($metod eq 'proxy') || (param('first')+$outputkvo>$cashednumber)) + { + @Questions=&Search($dbh, \$sstr,$metod,$all,\@allnf); + $cashednumber=$#Questions if $cashednumber>$#Questions; + my $tmp=$dbh->quote(pack("L*",@Questions[0..$cashednumber])); + my $qsstr=$dbh->quote($sstr); + my $nf=$dbh->quote(pack("L*", @allnf)); + my $ss=200; + if ($usewas) { + do + { + $was=int rand(32000); + } + while (--$ss && (!$dbh->do ("insert into lastqueries (id,sstr,questions,allnf) + values ($was, $qsstr,$tmp,$nf)"))); + $Output.= "Something is wrong...".br unless $ss; + } + } + + + + $Output.= p. "Время поиска: " . (time-$t) ." сек.".p; my ($output, $i, $suffix, $hits) = ('', 0, '', $#Questions + 1); my $shablon; - + $metod='rus' if $metod eq 'proxy'; if ($metod eq 'rus') { my $where='0'; $where.= " or w2=$_ " foreach @allnf; my $query="select w1 from nests where $where"; my $sth=$dbh->prepare($query); -print "$query" if $printqueries; $sth->execute; my @shablon; @@ -458,48 +929,51 @@ print "$query" if $printqueries; { push @shablon,"(?:$arr[0])"; } - $shablon= join "|", @shablon; + $sth->finish; + $shablon= join "|", @shablon; $shablon=~s/[её]/\[ЕЁ\]/gi; # $shablon=~s/([йцукенгшщзхъфывапролджэячсмитьбюЙЦУКЕНГШЩЗХЪФЫВАПРОЛДЖЭЯЧСМИТЬБЮ])/&NoCase($1)/ge; $shablon=qr/$shablon/i; - print "!$shablon!",br if $printqueries; - } + } + $hits=param("fkvo")||$hits; if ($hits =~ /1.$/ || $hits =~ /[5-90]$/) { $suffix = 'й'; } elsif ($hits =~ /1$/) { $suffix = 'е'; } else { - $suffix = 'я'; + $suffix = 'я'; } - - print p({align=>"center"}, "Результаты поиска на " . strong($sstr) + + $Output.= p({align=>"center"}, "Результаты поиска на " . strong($sstr) . " : $hits попадани$suffix."); if (param('word')) { $sstr = '[ \.\,:;]' . $sstr . '[ \.\,:\;]'; } - $sstr =~ s/(.)/&NoCase($1)/ge; +# $sstr =~ s/(.)/&NoCase($1)/ge; - my(@sar) = split(' ', $sstr); - for ($i = 0; $i <= $#Questions; $i++) { - $output = &PrintQuestion($dbh, $Questions[$i], 1, $i + 1, 1); - if (param('metod') eq 'rus') - { - $output=~s/\b($shablon)\b/\$1\<\/strong\>/gi; - } else { - foreach (@sar) { - $output =~ s/$_/$&<\/strong>/gs; - }} - print $output; + my @sar; + if ($metod ne 'rus') + { + my $ss=$sstr; + (@sar) = split(' ', $ss); + s/(\W)/\\$1/g foreach (@sar); + $shablon=join "|",@sar; } + $Output.=PrintList($dbh,\@Questions,$shablon,$was); + return $Output; } sub PrintRandom { my ($dbh, $type, $num, $text) = @_; + my $razd=param('razd'); + my %q; + my $answer=$razd?0:1; + my @answers; my (@Questions) = &Get12Random($dbh, $type, $num); my ($output, $i) = ('', 0); @@ -509,14 +983,35 @@ sub PrintRandom { $output .= h2({align=>"center"}, "$num случайных вопросов."); } - + my $sth=SelectQuestions($dbh,\@Questions,0); for ($i = 0; $i <= $#Questions; $i++) { - # Passing DB handler, question ID, print answer, question - # number, print title, print text/html - $output .= - &PrintQuestion($dbh, $Questions[$i], 1, $i + 1, 0, $text); + fetchquestion($sth,\%q,0); + $output .= + &PrintQuestion($dbh, \%q, $answer, $i + 1, 0, $text,1); + push @answers, $q{'Answer'}; } - return $output; + $sth->finish; + unless ($answer ) + { + $output.=$text?"\n".('-'x 20)."\nОтветы\n~~~~~~\n\n":h2('Ответы'); + $sth=SelectQuestions($dbh,\@Questions,0); + for ($i = 0; $i <= $#Questions; $i++) { +# fetchquestion($sth,\%q,0); +# $output .= +# &PrintQuestion($dbh, \%q, -1, $i + 1, 0, $text,1); + $output.=$text?("Ответ ". ($i+1).": $answers[$i]\n\n"): + b("Ответ ". ($i+1).": "). $answers[$i].p; + } + } + + return $output; +} + +sub PrintEditor { + my $t=shift; #ссылка на Хэш с полями + my $ed=$$t{'Editors'}||''; + my $edname=($ed=~/\,/ ) ? "Редакторы" : "Редактор" ; + return $ed? h4({align=>"center"},"$edname: $ed" ): ''; } sub PrintTournament { @@ -526,32 +1021,36 @@ sub PrintTournament { my ($output) = ''; %Tournament = &GetTournament($dbh, $Id) if ($Id); - - my ($URL) = $Tournament{'URL'}; + + 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'}; @Tours = &GetTours($dbh, $Id); - + $list=''; + my $textid; if ($Id) { for ($Tournament{'Type'}) { /Г/ && do { - $output .= h2({align=>"center"}, + $output .= h2({align=>"center"}, "Группа: $Tournament{'Title'} ", - "$Tournament{'PlayedAt'}") . p . "\n"; + $Tournament{'PlayedAt'}||'') . p . "\n"; last; }; /Ч/ && do { return &PrintTour($dbh, $Tours[0], $answer) if ($#Tours == 0); - + my $title="Пакет: $Tournament{'Title'}"; if ($Tournament{'PlayedAt'}) { $title .= " $Tournament{'PlayedAt'}"; } - $output .= h2({align=>"center"}, + $output .= h2({align=>"center"}, "$title") . p . "\n"; + $output.=&PrintEditor(\%Tournament); last; }; /Т/ && do { @@ -559,13 +1058,25 @@ sub PrintTournament { }; } } else { - my ($qnum) = GetQNum($dbh); - $output .= h2("Банк Вопросов: $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++) { + for ($i = 0; $i <= $#Tours; $i++) { %Tournament = &GetTournament($dbh, $Tours[$i]); - + if ($Tournament{'Type'} =~ /Ч/) { $SingleTour = 0; my (@Tours) = &GetTours($dbh, $Tournament{'Id'}); @@ -578,7 +1089,8 @@ sub PrintTournament { } else { $qnum = ''; } - if ($Tournament{'Type'} =~ /Г/) { + if ($Tournament{'Type'} !~ /[ТЧ]/) { + $SingleTour=0; $imgsrc = "/icons/folder.gif"; $alt = "[*]"; } else { @@ -586,31 +1098,47 @@ sub PrintTournament { $alt = "[-]"; } - if ($SingleTour or $Tournament{'Type'} =~ /Т/) { + my $textid; + if ($textid=$Tournament{'FileName'}) + { + $textid=~s/\.txt//; + } + elsif ($textid=$Tournament{'Number'}) + { + $fname=~s/\.txt//; + $textid="$fname.$textid"; + } + else {$textid=$Tournament{'Id'}}; + + + if ($SingleTour or ($Tournament{'Type'} =~ /Т/)) { $list .= dd(img({src=>$imgsrc, alt=>$alt}) . " " . $Tournament{'Title'} . " " . - $Tournament{'PlayedAt'} . $qnum) . + ($Tournament{'PlayedAt'}||"") . $qnum) . dl( dd("[" - . a({href=>url . "?tour=$Tournament{'Id'}&answer=0"}, + . a({href=>tourhref($textid,0)}, "вопросы") . "] [" - . a({href=>url . "?tour=$Tournament{'Id'}&answer=1"}, + . a({href=>tourhref($textid,1)}, "вопросы + ответы") . "]") ); } else { - $list .= dd(a({href=>url . "?tour=$Tournament{'Id'}&comp=1"}, - img({src=>'/icons/compressed.gif', alt=>'[ZIP]', border=>1})) - . " " . img({src=>$imgsrc, alt=>$alt}) - . " " . a({href=>url . "?tour=$Tournament{'Id'}&answer=0"}, - $Tournament{'Title'}. " ". - $Tournament{'PlayedAt'}) . $qnum); + $list .= dd(a({href=> + $url . "?tour=$textid&comp=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); } } $output .= dl($list); if ($URL) { + if ($url=~/zaba\.ru/ && $URL=~/^\//){$URL="http://info.chgk.info$URL"} $output .= - p("Дополнительная информация об этом турнире - по адресу " . + p("Дополнительная информация об этом турнире - по адресу " . a({-'href'=>$URL}, $URL)); } @@ -618,10 +1146,11 @@ sub PrintTournament { $output .= p("Копирайт: " . $Copyright); } + + if ($Info) { $output .= p($Info); } - return $output; } @@ -633,12 +1162,41 @@ 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) = @_; - my ($sth) = $dbh->prepare("SELECT Type FROM Tournaments + my ($dbh, $Id,$n) = @_; + + my ($sth) ; + + if (defined $n) + { $sth=$dbh->prepare ("select Id FROM Tournaments + WHERE ParentId=$Id AND Number=$n"); + } + else + { + $sth=$dbh->prepare("SELECT Id FROM Tournaments WHERE Id=$Id"); + } $sth->execute; - return ($sth->fetchrow)[0] =~ /Т/; + my $a=($sth->fetchrow)[0]; + $sth->finish; + return $a; } # Gets a DB handler (ofcourse) and a tour Id. Prints all the @@ -650,28 +1208,34 @@ sub PrintTour { my (%Tour) = &GetTournament($dbh, $Id); my (@Tours) = &GetTours($dbh, $Tour{'ParentId'}); my (%Tournament) = &GetTournament($dbh, $Tour{'ParentId'}); + my %q; return 0 if ($Tour{'Type'} !~ /Т/); + my ($fname)=$Tournament{'FileName'}; + $fname=~s/\.txt//; my ($qnum) = $Tour{'QuestionsNum'}; - my ($suffix) = &Suffix($qnum); - - $output .= h2({align=>"center"}, $Tournament{"Title"}, - $Tournament{'PlayedAt'}, - "
", $Tour{"Title"} . + my ($suffix) = &Suffix($qnum); + + $output .= h2({align=>"center"}, $Tournament{"Title"}, + $Tournament{'PlayedAt'}||'', + "
", $Tour{"Title"} . " ($qnum вопрос$suffix)\n") . p; + $output .=&PrintEditor(\%Tour); my (@Questions) = &GetTourQuestions($dbh, $Id); + my $sth=SelectQuestions($dbh,\@Questions,0); for ($q = 0; $q <= $#Questions; $q++) { - $output .= &PrintQuestion($dbh, $Questions[$q], $answer, 0); - } - + fetchquestion($sth,\%q,0); + $output .= &PrintQuestion($dbh, \%q, $answer, 0,0,0,1); + } + $sth->finish; $output .= hr({-'align'=>'center', -'width'=>'80%'}); if ($Tournament{'URL'}) { $output .= - p("Дополнительная информация об этом турнире - по адресу " . + p("Дополнительная информация об этом турнире - по адресу " . a({-'href'=>$Tournament{'URL'}}, $Tournament{'URL'})); } @@ -682,26 +1246,30 @@ sub PrintTour { if ($Tournament{'Info'}) { $output .= p($Tournament{'Info'}); } - + my $n=$Tour{'Number'}; if ($answer == 0) { - $bottom .= - "[" . a({href=>url . "?tour=$Id&answer=1"}, "ответы") . "] " . br; - } - if (&IsTour($dbh, $Id - 1)) { - $bottom .= - "[" . a({href=>url . "?tour=" . ($Id - 1) . "&answer=0"}, + my $nn=".$n"; + $nn="" if ($n==1 && !&IsTour($dbh, $Tour{'ParentId'}, $n + 1)); + + $bottom .= + "[" . a({href=>tourhref("$fname$nn",1)}, + "ответы") . "] " . br; + } + if ($n>1) { + $bottom .= + "[" . a({href=>tourhref("$fname.".($n-1),0)}, "предыдущий тур") . "] "; - $bottom .= - "[" . a({href=>url . "?tour=" . ($Id - 1) . "&answer=1"}, + $bottom .= + "[" . a({href=>tourhref("$fname.".($n-1),1)}, "предыдущий тур с ответами") . "] " . br; } - if (&IsTour($dbh, $Id + 1)) { - $bottom .= - "[" . a({href=>url . "?tour=" . ($Id + 1) . "&answer=0"}, + if (&IsTour($dbh, $Tour{'ParentId'}, $n + 1)) { + $bottom .= + "[" . a({href=>tourhref("$fname.".($n+1),0)}, "следующий тур") . "] "; - $bottom .= - "[" . a({href=>url . "?tour=" . ($Id + 1) . "&answer=1"}, + $bottom .= + "[" . a({href=>tourhref("$fname.".($n+1),1)}, "следующий тур с ответами") . "] "; } @@ -714,75 +1282,112 @@ sub PrintTour { sub PrintField { my ($header, $value, $text) = @_; if ($text) { - $value =~ s/<[\/\w]*>//sg; + $value =~ s/<[\/\w]*?>//sg; } else { $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/(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;
 	}
 
-	return $text ? "$header:\n$value\n\n" : 
+
+	return $text ? "$header:\n$value\n\n" :
 		strong("$header: ") . $value . p . "\n";
 }
 
-# Gets a DB handler (ofcourse) and a question Id. Prints 
+# Gets a DB handler (ofcourse) and a question Id. Prints
 # that question, according to the options.
 sub PrintQuestion {
-	my ($dbh, $Id, $answer, $qnum, $title, $text) = @_;
+	my ($dbh, $Id, $answer, $qnum, $title, $text,$h) = @_;
 	my ($output, $titles) = ('', '');
-
-	my (%Question) = &GetQuestion($dbh, $Id);
-	if (!$text) {
-		$output .= hr({width=>"50%"});
+	my (%Question);
+	if ($h) {
+	  %Question=%$Id;
+	} else {
+		%Question = &GetQuestion($dbh, $Id);
 		if ($title) {
 			my (%Tour) = GetTournament($dbh, $Question{'ParentId'});
 			my (%Tournament) = GetTournament($dbh, $Tour{'ParentId'});
+			$Question{'FileName'}=$Tournament{'FileName'};
+			$Question{'Title'}=$Tournament{'Title'};
+			$Question{'PlayedAt'}=$Tournament{'PlayedAt'};
+			$Question{'TourNumber'}=$Tour{'Number'};
+			$Question{'TourTitle'}=$Tour{'Title'};
+		}
+
+        }
+		$qnum = $Question{'Number'}
+		if ($qnum == 0);
+	if (!$text) {
+		$output .= hr({width=>"50%"}) if $answer>=0;
+		if ($title) {
+			my $fname=$Question{'FileName'};
+			$fname=~s/\.txt//;
 			$titles .=
 				dd(img({src=>"/icons/folder.open.gif"}) . " " .
-					 a({href=>url . "?tour=$Tournament{'Id'}"}, $Tournament{'Title'}, $Tournament{'PlayedAt'}));
+					 a({href=>tourhref($fname,0,1)}, 
+                               $Question{'Title'}, $Question{'PlayedAt'}||''));
 			$titles .=
 				dl(dd(img({src=>"/icons/folder.open.gif"}) . " " .
-					a({href=>url . "?tour=$Tour{'Id'}"}, $Tour{'Title'})));
+					a({href=>tourhref("$fname.$Question{'TourNumber'}#$qnum",1)}, 
+                          $Question{'TourTitle'})));
 		}
 		$output .= dl(strong($titles));
 	}
-	
-	$qnum = $Question{'Number'}
-		if ($qnum == 0);
 
-	$output .= 
-		&PrintField("Вопрос $qnum", $Question{'Question'}, $text);
 
-	if ($answer) {
-		$output .= 
+	$output.= "" unless $text;
+
+	if ($answer>=0) {$output .=
+		&PrintField("Вопрос $qnum", $Question{'Question'}, $text);}
+	else {$output .="$qnum. "}
+	if ($answer==1|| $answer==-1) {
+		$output .=
 			&PrintField("Ответ", $Question{'Answer'}, $text);
 
-		if ($Question{'Authors'}) {
+		if ($Question{'Authors'} ) {
                       my $q=$Question{'Authors'};
-
-		      my $sth=$dbh->prepare("select Authors.Id,Name, Surname, Nicks from Authors, A2Q
-                                 where Authors.Id=Author And Question=$Id");
-                      $sth->execute;
-                      my ($AuthorId,$Name, $Surname,$other,$Nicks);
-
-                      while ((($AuthorId,$Name, $Surname,$Nicks)=$sth->fetchrow),$AuthorId)
-                      {
-                        my ($firstletter)=$Name=~m/^./g;
-#		        $other.=a({href=>url."?qofauthor=$AuthorId"},"$Name $Surname").". ";
-                          my $sha="(?:$Name\\s+$Surname)|(?:$Surname\\s+$Name)|(?:$firstletter\\.\\s*$Surname)|(?:$Surname\\s+$firstletter\\.)|(?:$Surname)|(?:$Name)";
-                          $Nicks=~s/^\|//;
-                          foreach (split /\|/, $Nicks)
-                          {
-                              s/ /\\s+/;
-                              if (s/>$//) {$sha="$sha|(?:$_)"}
-                              else        {$sha="(?:$_)|$sha"}
-                          }
-#$output.=br."sha=$sha".br;
-                          $q=~s/($sha)/a({href=>url."?qofauthor=$AuthorId"},$1)/ei;
-                      }
-
+###АВТОРА!!
+# 		      my $sth=$dbh->prepare("select Authors.CharId,Name, Surname, Nicks from Authors, A2Q
+#                                  where Authors.Id=Author And Question=$Id");
+#                       $sth->execute;
+#                       my ($AuthorId,$Name, $Surname,$other,$Nicks);
+#                      if (!$text) {
+#                       while ((($AuthorId,$Name, $Surname,$Nicks)=$sth->fetchrow),$AuthorId)
+#                       {
+#                          my ($firstletter)=$Name=~m/^./g;
+#                          $Name=~s/\./\\\./g;
+#                          $Name=~s/ё/[её]/g;
+#                          $Surname=~s/ё/[её]/g;
+#                           my $sha="(?:$Name\\s+$Surname)|(?:$Surname\\s+$Name)|(?:$firstletter\\.\\s*$Surname)|(?:$Surname\\s+$firstletter\\.)|(?:$Surname)";
+#                           if ($Nicks)
+#                           {
+#                             $Nicks=~s/^\|//;
+#                             foreach (split /\|/, $Nicks)
+#                             {
+#                               s/\s+/ /g;
+#                               s/\s+$//;
+#                               s/ /\\s+/g;
+#                               s/\./\\\./g;
+#                               if (s/>$//) {$sha="$sha|(?:$_)"}
+#                               else        {$sha="(?:$_)|$sha"}
+#                             }
+#                           }
+#                           $q=~s/($sha)/a({href=>url."?qofauthor=$AuthorId"},$1)/ei;
+#                           unless ($1) 
+#                             {   
+#                                 $q=~s/$Name/a({href=>url."?qofauthor=$AuthorId"},$1)/ei;
+#                             }
+#                       }
+#                      }
 			$output .= &PrintField("Автор(ы)", $q, $text);
 
-#                        $output.= &PrintField("Другие вопросы", $other);
 		}
 
 		if ($Question{'Sources'}) {
@@ -793,21 +1398,76 @@ sub PrintQuestion {
 			$output .= &PrintField("Комментарии", $Question{'Comments'}, $text);
 		}
 	}
+	elsif ($answer==2) {
+	  my $text=$Question{'Answer'};
+	  $text=~s/\n/