--- db/prgsrc/db.cgi 2000/10/15 19:49:22 1.1 +++ db/prgsrc/db.cgi 2001/12/03 13:57:20 1.40 @@ -1,21 +1,50 @@ -#!/usr/bin/perl -w +#!/perl/bin/perl -w use DBI; use CGI ':all'; +use Text::Query; use strict; use Time::Local; use POSIX qw(locale_h); +use locale; +#open STDERR, ">errors1"; +my $printqueries=0; +my %forbidden=(); +my $debug=0; #added by R7 +my %fieldname= (0,'Question', 1, 'Answer', 2, 'Comments', 3, 'Authors', 4, 'Sources'); +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 $thislocale; + + +$searchin{'question'}=param('Question'); +$searchin{'answer'}=param('Answer'); +$searchin{'comments'}=param('Comments'); +$searchin{'authors'}=param('Authors'); +$searchin{'sources'}=param('Sources'); +my $all=param('all'); +$all=0 if lc $all eq 'no'; my ($PWD) = `pwd`; chomp $PWD; my ($SRCPATH) = "$PWD/../dimrub/src"; -my ($ZIP) = "/usr/local/bin/zip"; +my ($ZIP) = "/home/piataev/bin/zip"; +my $DUMPFILE = "/tmp/chgkdump"; my ($SENDMAIL) = "/usr/sbin/sendmail"; 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'); + 'Dec', '11', + 'Янв', '0', 'Фев', 1, 'Мар', 2, 'Апр', 3, 'Май', '4', + 'Июн', '5', 'Июл', 6, 'Авг', '7', 'Сен', '8', + 'Окт', '9', 'Ноя', '19', 'Дек', '11'); # Determine whether the given time is within 2 months from now. sub NewEnough { @@ -69,7 +98,7 @@ sub GetTourQuestions { my ($dbh, $ParentId) = @_; my (@arr, @Questions); - my ($sth) = $dbh->prepare("SELECT QuestionId FROM Questions + my ($sth) = $dbh->prepare("SELECT QuestionId FROM Questions WHERE ParentId=$ParentId ORDER BY QuestionId"); $sth->execute; @@ -98,47 +127,368 @@ sub GetTours { return @Tours; } +sub count +{ + my ($dbh,$word)=@_; +print "timeb=".time.br if $debug; + $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; +print "timee0=".time.br if $debug; + $a[0]||0; +} + + +sub proxy +{ +#print "time0=".time.br if $debug; + my ($dbh,$ptext,$allnf)=@_; + my $text=$$ptext; + $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/[^йцукенгшщзхъфывапролджэячсмитьбюЙЦУКЕНГШЩЗХЪФЫВАПРОЛДЖЭЯЧСМИТЬБЮQWERTYUIOPASDFGHJKLZXCVBNM]/ /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; + } + +# foreach (@list) +# { +# if ($good{$_}) +# { +# $good{$_}=0; +# $sstr.=" $_"; +# } +# } + $sstr.=" $_" foreach grep {$good{$_}} @list; +print "time05=".time.br if $debug; + $$ptext=$sstr; + return russearch($dbh,$sstr,0,$allnf); +} + + +sub russearch { + my ($dbh, $sstr, $all,$allnf)=@_; + my (@qw,@w,@tasks,$qw,@arr,$nf,$sth,@nf,$w,$where,$e,@where,%good,$i,%where,$from); + my($number,@good,$t,$task,@rho,$rank,%rank,$r2,$r1,$word,$n,@last,$good,@words,%number,$taskid); + my ($hi, $lo, $wordnumber,$query,$blob,$field,$sf,$ii); + my @frequence; + my (@arr1,@ar,@sf,@arr2); + my %tasks; + my $tasks; + my @verybad; + my %nf; + my %tasksof; + my %wordsof; + my %relevance; + my @blob; + my %count; + +$sstr=~tr/йцукенгшщзхъфывапролджэячсмитьбю/ЙЦУКЕНГШЩЗХЪФЫВАПРОЛДЖЭЯЧСМИТЬБЮ/; + @qw=@w =split (' ', uc $sstr); + +#----------- + 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]}=(); + while (@arr = $sth->fetchrow) + { + push (@{$nf[$i]},$arr[0]) + } + } + + + my @bad=grep {!@{$nf[$_]}} 0..$#w; # @bad -- номера словоформ, + # которых нет в словаре + + if (@bad) #есть неопознанные словоформы + { + require "cw.pl"; + foreach $i(@bad) + { + if (@arr=checkword($dbh,$w[$i])) + {push (@{$nf[$i]}, @arr);} + else + {push (@verybad,$i);} + } + } + return () if ($all && @verybad); + + + my $kvo=0; + push @$allnf, @{$_} foreach @nf; + print "nf=@$allnf" if $printqueries; + + foreach $i (0..$#w) #запросы в базу... + { + @arr=@{$nf[$i]} if $nf[$i]; + @arr2=@arr1=@arr; + + + + + $_= " word2question.word=".$_. ' ' foreach @arr; + $_= " nf.id=".$_. ' ' foreach @arr1; +# @arr=(0) unless @arr; + $query="select questions from word2question where". (join ' OR ', @arr); +print STDERR "!$query\n",br if $printqueries; + + $sth=$dbh -> prepare($query); + $sth->execute; + + @blob=(); + while (@arr=$sth->fetchrow) + { + @blob=(@blob,unpack 'C*',$arr[0]); + } + $query="select number from nf where ".(join ' OR ', @arr1); +print "$query\n",br if $printqueries; + $sth=$dbh -> prepare($query); + $sth->execute; + + while (@arr=$sth->fetchrow) + { + $frequence[$i]+=$arr[0]; + } + + + + if (@blob < 4) + { + $tasksof{$i}=undef; + } else + { + $kvo++; + $ii=0; + while ($ii<$#blob) # создаём хэш %tasksof, ключи которого -- + # номера искомых словоформ, а значения -- + # списки вопросов, в которых есть соответствующа + # словоформа. + # Каждый список в свою очередь также оформлен в + # виде хэша, ключи которого -- номера вопросов, + # а значения -- списки номеров вхождений. Вот. + { + ($field,$lo,$hi,$wordnumber)=@blob[$ii..($ii+3)]; + $ii+=4; + $number=$lo+$hi*256; + $field=$fieldname{$field}; + if ($searchin{lc $field}) + { + push @{$tasksof{$i}{$number}}, $wordnumber; + # дополнили в хэше, висящем на + # словоформе $i в %tasksof список + # вхождений $i в вопрос $number. + push @{$wordsof{$number}{$i}}, $wordnumber; + # дополнили в хэше, висящем на + # вопросе $number в %wordsof список + # вхождений $i в вопрос $number. + + + } + } #while ($ii<$#blob) + } + } #foreach $i + +#print "keys tasksof", join ' ', keys %{$tasksof{0}}; +#Ищем пересечение или объединение списков вопросов (значений %tasksof) + foreach $sf (keys %tasksof) + { + $count{$_}++ foreach keys %{$tasksof{$sf}}; + } + @tasks= ($all ? (grep {$count{$_}==$kvo} keys %count) : + keys %count) ; + + +print "\n\$#tasks=",$#tasks,br if $printqueries; +############ Сортировка найденных вопросов + +foreach (keys %wordsof) +{ + $relevance{$_}=&relevance($#w,$wordsof{$_},\@frequence) if $_ +} + +@tasks=sort {$relevance{$b}<=>$relevance{$a}} @tasks; + + +############ + +print "tasks=@tasks" if $printqueries; + +#print "$_ $relevance{$_} | " foreach @tasks; +#print br; +print "allnf=@$allnf",br if $printqueries; + return @tasks; +} + + +sub distance { + # на входе -- номера словоформ и ссылки на + # списки вхождений. На выходе -- расстояние, + # вычисляемое по формуле min(|b-a-pb+pa|) + # pb,pa + # (pb и pa -- позиции слов b и a) + my ($a,$b,$lista,$listb)=@_; + my ($pa,$pb,$min,$curmin); + $min=10000; + foreach $pa (@$lista) + { + foreach $pb (@$listb) + { + $curmin=abs($b-$a-$pb+$pa); + $min= $curmin if $curmin<$min; + } + } + return $min; + +} + +sub relevance { + # На входе -- количество искомых словоформ -1 и + # ссылка на hash, ключи которого -- + # номера словоформ, а значения -- списки вхождений + + my ($n,$words,$frequence)=@_; + my $relevance=0; + my ($first,$second,$d); + foreach $first (0..$n) + { + $relevance+=scalar @{$$words{$first}}+1000+1000/$$frequence[$first] +if $$words{$first}; + foreach $second ($first+1..$n) + { + $d=&distance($first,$second,$$words{$first},$$words{$second}); + $relevance+=($d>10?0:10-$d)*10; + } + } + return $relevance; +} + + # Returns list of QuestionId's, that have the search string in them. sub Search { - my ($dbh, $sstr) = @_; + my ($dbh, $s,$metod,$all,$allnf) = @_; + my $sstr=$$s; my (@arr, @Questions, @fields); - my (@sar, $i, $sth); + my (@sar, $i, $sth,$where,$query); + my $ip=$ENV{'REMOTE_ADDR'}; + + $ip=$dbh->quote($ip); + $query= + "INSERT into queries (query,metod,searchin,ip) + values (". $dbh->quote($sstr).', '. + $dbh->quote($metod) . ', ' . + $dbh->quote(join ' ', grep $searchin{$_}, keys %searchin) . + ", $ip)"; +print $query if $printqueries; + $dbh -> do ($query); + if ($metod eq 'rus') + { + my @tasks=russearch($dbh,$sstr,$all,$allnf); + return @tasks + } + elsif ($metod eq 'proxy') + { +# $searchin{'question'}=1; +# $searchin{'answer'}=1; + my @task=proxy($dbh,$s,$allnf); +# $$s=$sstr; + return @task + } + - push @fields, 'Question'; - foreach (qw/Answer Sources Authors Comments/) { + +###Simple and advanced query processing. Added by R7 + if ($metod eq 'simple' || $metod eq 'advanced') + { + foreach (qw/Question Answer Sources Authors Comments/) { if (param($_)) { - push @fields, "IFNULL($_, '')"; + push @fields, $_; } - } + } - @sar = split " ", $sstr; - for $i (0 .. $#sar) { + @fields=(qw/Question Answer Sources Authors Comments/) unless scalar @fields; + my $fields=join ",", @fields; + my $q=new Text::Query($sstr, + -parse => 'Text::Query::'. + (($metod eq 'simple') ? 'ParseSimple':'ParseAdvanced'), + -solve => 'Text::Query::SolveSQL', + -build => 'Text::Query::BuildSQLMySQL', + -fields_searched => $fields); + + $where= $$q{'matchexp'}; + $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($_)) { + push @fields, "IFNULL($_, '')"; + } + } + @sar = split " ", $sstr; + for $i (0 .. $#sar) { $sar[$i] = $dbh->quote("%${sar[$i]}%"); - } + } - my($f) = "CONCAT(" . join(',', @fields) . ")"; - if (param('all') eq 'yes') { + my($f) = "CONCAT(" . join(',', @fields) . ")"; + if (param('all') eq 'yes') { $sstr = join " AND $f LIKE ", @sar; - } else { + } else { $sstr = join " OR $f LIKE ", @sar; - } - - $sth = $dbh->prepare("SELECT QuestionId FROM Questions - WHERE $f LIKE $sstr ORDER BY QuestionId"); + } + + my $query; + $query="SELECT QuestionId FROM Questions + WHERE $f LIKE $sstr ORDER BY QuestionId"; + + +print $query if $printqueries; + $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]}; } - + +print "@Questions" if $printqueries; return @Questions; } # Substitute every letter by a pair (for case insensitive search). - my (@letters) = qw/аА бБ вВ гГ дД еЕ жЖ зЗ иИ йЙ кК лЛ мМ нН оО + my (@letters) = qw/аА бБ вВ гГ дД еЕ жЖ зЗ иИ йЙ кК лЛ мМ нН оО пП рР сС тТ уУ фФ хХ цЦ чЧ шШ щЩ ьЬ ыЫ эЭ юЮ яЯ/; - + sub NoCase { my ($sstr) = shift; my ($res); @@ -150,19 +500,86 @@ sub NoCase { } } +sub PrintList { + my ($dbh,$Questions,$shablon)=@_; + + my $first=param('first') ||1; + my $kvo=param('kvo') ||30; + + $first=$first-($first-1)%$kvo; + my $last=$first+$kvo-1; + $last=scalar @$Questions if scalar @$Questions <$last; + my($f,$l); + my $nav=''; + + for($f=1; $f<=@$Questions; $f+=$kvo) + { + $l=$f+$kvo-1; + $l=$#$Questions+1 if $l>$#$Questions+1; + if ($f==$first) {$nav.="[$f-$l] ";} + else { + my $qs=query_string; + $qs=~s/\;/\&/g; + $qs=~s/\&first\=[^\&]+//g; + $qs.="\&first=$f"; + + $nav.= "[".a({href=>(url."?".$qs)},"$f-$l")."] ";} + } + print "$nav".br."\n"; + for (my $i = $first; $i <= $last; $i++) { + my $output = &PrintQuestion($dbh, $$Questions[$i-1], 1, $i, 1); + if (param('metod') eq 'rus' || param('metod') eq 'proxy') + { + $output=~s/\b($shablon)\b/\$1\<\/strong\>/gi; + } else { + $output=~s/($shablon)/\$1\<\/strong\>/gi; + } + print $output; + } + print "$nav".br."\n"; + +} + sub PrintSearch { - my ($dbh, $sstr) = @_; - my (@Questions) = &Search($dbh, $sstr); + my ($dbh, $sstr, $metod) = @_; + + my @allnf; + my (@Questions) = &Search($dbh, \$sstr,$metod,$all,\@allnf); 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; + while (my @arr = $sth->fetchrow) + { + push @shablon,"(?:$arr[0])"; + } + $shablon= join "|", @shablon; + $shablon=~s/[её]/\[ЕЁ\]/gi; +# $shablon=~s/([йцукенгшщзхъфывапролджэячсмитьбюЙЦУКЕНГШЩЗХЪФЫВАПРОЛДЖЭЯЧСМИТЬБЮ])/&NoCase($1)/ge; + $shablon=qr/$shablon/i; + print "!$shablon!",br if $printqueries; + } + + + if ($hits =~ /1.$/ || $hits =~ /[5-90]$/) { $suffix = 'й'; } elsif ($hits =~ /1$/) { $suffix = 'е'; } else { - $suffix = 'я'; + $suffix = 'я'; } - + print p({align=>"center"}, "Результаты поиска на " . strong($sstr) . " : $hits попадани$suffix."); @@ -172,14 +589,13 @@ sub PrintSearch { $sstr =~ s/(.)/&NoCase($1)/ge; - my(@sar) = split(/\s/, $sstr); - for ($i = 0; $i <= $#Questions; $i++) { - $output = &PrintQuestion($dbh, $Questions[$i], 1, $i + 1, 1); - foreach (@sar) { - $output =~ s/$_/$&<\/strong>/gs; - } - print $output; + my @sar; + if ($metod ne 'rus') + { + (@sar) = split(' ', $sstr); + $shablon=join "|",@sar; } + PrintList($dbh,\@Questions,$shablon); } sub PrintRandom { @@ -197,10 +613,10 @@ sub PrintRandom { for ($i = 0; $i <= $#Questions; $i++) { # Passing DB handler, question ID, print answer, question # number, print title, print text/html - $output .= + $output .= &PrintQuestion($dbh, $Questions[$i], 1, $i + 1, 0, $text); } - return $output; + return $output; } sub PrintTournament { @@ -210,7 +626,7 @@ sub PrintTournament { my ($output) = ''; %Tournament = &GetTournament($dbh, $Id) if ($Id); - + my ($URL) = $Tournament{'URL'}; my ($Info) = $Tournament{'Info'}; my ($Copyright) = $Tournament{'Copyright'}; @@ -220,16 +636,22 @@ sub PrintTournament { if ($Id) { for ($Tournament{'Type'}) { /Г/ && do { - $output .= h2({align=>"center"}, - "Группа: $Tournament{'Title'}") . p . "\n"; + $output .= h2({align=>"center"}, + "Группа: $Tournament{'Title'} ", + "$Tournament{'PlayedAt'}") . p . "\n"; last; }; /Ч/ && do { return &PrintTour($dbh, $Tours[0], $answer) if ($#Tours == 0); - $output .= h2({align=>"center"}, - "Чемпионат: $Tournament{'Title'}") . p . "\n"; + my $title="Пакет: $Tournament{'Title'}"; + if ($Tournament{'PlayedAt'}) { + $title .= " $Tournament{'PlayedAt'}"; + } + + $output .= h2({align=>"center"}, + "$title") . p . "\n"; last; }; /Т/ && do { @@ -241,9 +663,9 @@ sub PrintTournament { $output .= h2("Банк Вопросов: $qnum вопросов") . p . "\n"; } - 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'}); @@ -266,7 +688,8 @@ sub PrintTournament { if ($SingleTour or $Tournament{'Type'} =~ /Т/) { $list .= dd(img({src=>$imgsrc, alt=>$alt}) - . " " . $Tournament{'Title'} . $qnum) . + . " " . $Tournament{'Title'} . " " . + $Tournament{'PlayedAt'} . $qnum) . dl( dd("[" . a({href=>url . "?tour=$Tournament{'Id'}&answer=0"}, @@ -275,18 +698,19 @@ sub PrintTournament { "вопросы + ответы") . "]") ); } else { - $list .= dd(a({href=>url . "?tour=$Tournament{'Id'}&comp=1"}, + $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'}) . $qnum); + . " " . img({src=>$imgsrc, alt=>$alt}) + . " " . a({href=>url . "?tour=$Tournament{'Id'}&answer=0"}, + $Tournament{'Title'}. " ". + $Tournament{'PlayedAt'}) . $qnum); } } $output .= dl($list); if ($URL) { $output .= - p("Дополнительная информация об этом турнире - по адресу " . + p("Дополнительная информация об этом турнире - по адресу " . a({-'href'=>$URL}, $URL)); } @@ -297,7 +721,7 @@ sub PrintTournament { if ($Info) { $output .= p($Info); } - + return $output; } @@ -311,7 +735,7 @@ sub Suffix { sub IsTour { my ($dbh, $Id) = @_; - my ($sth) = $dbh->prepare("SELECT Type FROM Tournaments + my ($sth) = $dbh->prepare("SELECT Type FROM Tournaments WHERE Id=$Id"); $sth->execute; return ($sth->fetchrow)[0] =~ /Т/; @@ -331,21 +755,23 @@ sub PrintTour { if ($Tour{'Type'} !~ /Т/); my ($qnum) = $Tour{'QuestionsNum'}; - my ($suffix) = &Suffix($qnum); - - $output .= h2({align=>"center"}, $Tour{"Title"} . + my ($suffix) = &Suffix($qnum); + + $output .= h2({align=>"center"}, $Tournament{"Title"}, + $Tournament{'PlayedAt'}, + "
", $Tour{"Title"} . " ($qnum вопрос$suffix)\n") . p; my (@Questions) = &GetTourQuestions($dbh, $Id); for ($q = 0; $q <= $#Questions; $q++) { $output .= &PrintQuestion($dbh, $Questions[$q], $answer, 0); - } + } $output .= hr({-'align'=>'center', -'width'=>'80%'}); if ($Tournament{'URL'}) { $output .= - p("Дополнительная информация об этом турнире - по адресу " . + p("Дополнительная информация об этом турнире - по адресу " . a({-'href'=>$Tournament{'URL'}}, $Tournament{'URL'})); } @@ -356,26 +782,26 @@ sub PrintTour { if ($Tournament{'Info'}) { $output .= p($Tournament{'Info'}); } - + if ($answer == 0) { - $bottom .= + $bottom .= "[" . a({href=>url . "?tour=$Id&answer=1"}, "ответы") . "] " . br; } if (&IsTour($dbh, $Id - 1)) { - $bottom .= - "[" . a({href=>url . "?tour=" . ($Id - 1) . "&answer=0"}, + $bottom .= + "[" . a({href=>url . "?tour=" . ($Id - 1) . "&answer=0"}, "предыдущий тур") . "] "; - $bottom .= - "[" . a({href=>url . "?tour=" . ($Id - 1) . "&answer=1"}, + $bottom .= + "[" . a({href=>url . "?tour=" . ($Id - 1) . "&answer=1"}, "предыдущий тур с ответами") . "] " . br; } if (&IsTour($dbh, $Id + 1)) { - $bottom .= - "[" . a({href=>url . "?tour=" . ($Id + 1) . "&answer=0"}, + $bottom .= + "[" . a({href=>url . "?tour=" . ($Id + 1) . "&answer=0"}, "следующий тур") . "] "; - $bottom .= - "[" . a({href=>url . "?tour=" . ($Id + 1) . "&answer=1"}, + $bottom .= + "[" . a({href=>url . "?tour=" . ($Id + 1) . "&answer=1"}, "следующий тур с ответами") . "] "; } @@ -388,18 +814,21 @@ 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/^\|([^\n]*)/
$1<\/pre>/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 ($output, $titles) = ('', '');
-
 	my (%Question) = &GetQuestion($dbh, $Id);
 	if (!$text) {
 		$output .= hr({width=>"50%"});
@@ -408,26 +837,56 @@ sub PrintQuestion {
 			my (%Tournament) = GetTournament($dbh, $Tour{'ParentId'});
 			$titles .=
 				dd(img({src=>"/icons/folder.open.gif"}) . " " .
-					 a({href=>url . "?tour=$Tournament{'Id'}"}, $Tournament{'Title'}));
+					 a({href=>url . "?tour=$Tournament{'Id'}"}, $Tournament{'Title'}, $Tournament{'PlayedAt'}));
 			$titles .=
 				dl(dd(img({src=>"/icons/folder.open.gif"}) . " " .
 					a({href=>url . "?tour=$Tour{'Id'}"}, $Tour{'Title'})));
 		}
 		$output .= dl(strong($titles));
 	}
-	
+
 	$qnum = $Question{'Number'}
 		if ($qnum == 0);
 
-	$output .= 
+	$output .=
 		&PrintField("Вопрос $qnum", $Question{'Question'}, $text);
 
 	if ($answer) {
-		$output .= 
+		$output .=
 			&PrintField("Ответ", $Question{'Answer'}, $text);
 
 		if ($Question{'Authors'}) {
-			$output .= &PrintField("Автор(ы)", $Question{'Authors'}, $text);
+                      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;
+                         $Name=~s/\./\\\./g;
+                          my $sha="(?:$Name\\s+$Surname)|(?:$Surname\\s+$Name)|(?:$firstletter\\.\\s*$Surname)|(?:$Surname\\s+$firstletter\\.)|(?:$Surname)|(?:$Name)";
+                          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;
+                      }
+
+			$output .= &PrintField("Автор(ы)", $q, $text);
+
+#                        $output.= &PrintField("Другие вопросы", $other);
 		}
 
 		if ($Question{'Sources'}) {
@@ -438,6 +897,8 @@ sub PrintQuestion {
 			$output .= &PrintField("Комментарии", $Question{'Comments'}, $text);
 		}
 	}
+	$output.=br.a({href=> url."?metod=proxy&qid=$Id"}, 'Близкие вопросы').p
+             if $answer;
 	return $output;
 }
 
@@ -448,35 +909,41 @@ sub GetQNum {
 	$sth->execute;
  	return ($sth->fetchrow)[0];
 }
+sub GetMaxQId {
+	my ($dbh) = @_;
+	my ($sth) = $dbh->prepare("SELECT MAX(QuestionId) FROM Questions");
+	$sth->execute;
+ 	return ($sth->fetchrow)[0];
+}
 
 # Returns Id's of 12 random questions
 sub Get12Random {
    my ($dbh, $type, $num) = @_;
 	my ($i, @questions, $q, $t, $sth);
-	my ($qnum) = &GetQNum($dbh);
+	my ($qnum) = &GetMaxQId($dbh);
 	my (%chosen);
 	srand;
-	
-	for ($i = 0; $i < $num; $i++) {
-		do {
-			$q = int(rand($qnum));
-			$sth = $dbh->prepare("SELECT Type FROM Questions
+
+   for ($i = 0; $i < $num; $i++) {
+       do {
+	   $q = int(rand($qnum));
+	   $sth = $dbh->prepare("SELECT Type FROM Questions
 				WHERE QuestionId=$q");
-			$sth->execute;
-			$t = ($sth->fetchrow)[0];
-		} until !$chosen{$q} && $t =~ /$type/;
-		$chosen{$q} = 'y';
-		push @questions, $q;
-	}
-	return @questions;
+	   $sth->execute;
+	   $t = ($sth->fetchrow)[0];
+       } until !$chosen{$q} && $t && $type =~ /[$t]/;
+       $chosen{$q} = 'y';
+       push @questions, $q;
+   }
+   return @questions;
 }
 
 sub Include_virtual {
 	my ($fn, $output) = (@_, '');
 
 	open F , $fn
-		or die "Can't open the file $fn: $!\n";
-	
+		or return; #die "Can't open the file $fn: $!\n";
+
 	while () {
 		if (//&Include_virtual($1)/e;
@@ -495,7 +962,7 @@ sub PrintArchive {
 
 	my (%Tournament) = &GetTournament($dbh, $Id);
 	my (@Tours) = &GetTours($dbh, $Id);
-	
+
 	if ($Tournament{'Type'} =~ /Г/ || $Id == 0) {
 		for ($i = 0; $i <= $#Tours; $i++) {
 			push(@list ,&PrintArchive($dbh, $Tours[$i]));
@@ -511,7 +978,7 @@ sub PrintAll {
 
 	my (%Tournament) = &GetTournament($dbh, $Id);
 	my (@Tours) = &GetTours($dbh, $Id);
-	my ($New) = ($Id and $Tournament{'Type'} eq 'Ч' and 
+	my ($New) = ($Id and $Tournament{'Type'} eq 'Ч' and
 		&NewEnough($Tournament{"CreatedAt"})) ?
 		img({src=>"/znatoki/dimrub/db/new-sml.gif", alt=>"NEW!"}) : "";
 
@@ -520,7 +987,7 @@ sub PrintAll {
 	} else {
 		$output .= dd(img({src=>"/icons/folder.gif", alt=>"[*]"}) .
       " " . a({href=>url . "?tour=$Tournament{'Id'}&answer=0"},
-      $Tournament{'Title'}) . " $New");
+      $Tournament{'Title'}) ." " . $Tournament{'PlayedAt'} . " $New");
 	}
 	if ($Id == 0 or $Tournament{'Type'} =~ /Г/) {
 		for ($i = 0; $i <= $#Tours; $i++) {
@@ -533,7 +1000,7 @@ sub PrintAll {
 
 sub PrintDates {
 	my ($dbh) = @_;
-	my ($from) = param('from_year') . "-" . param('from_month') . 
+	my ($from) = param('from_year') . "-" . param('from_month') .
 		"-" .  param('from_day');
 	my ($to) = param('to_year') . "-" . param('to_month') . "-" .  param('to_day');
 	$from = $dbh->quote($from);
@@ -554,17 +1021,109 @@ sub PrintDates {
 		%Tournament = &GetTournament($dbh, $array[0]);
       $list .= dd(img({src=>"/icons/folder.gif", alt=>"[*]"}) .
       " " . a({href=>url . "?tour=$Tournament{'Id'}&answer=0"},
-      $Tournament{'Title'}));
+      $Tournament{'Title'}, $Tournament{'PlayedAt'}));
 	}
 	$output .= dl($list);
 	return $output;
 }
 
+sub PrintQOfAuthor
+{
+    my ($dbh, $id) = @_;
+   $id=$dbh->quote($id);
+    my $sth =  $dbh->prepare("SELECT  Name, Surname FROM Authors WHERE Id=$id");
+    $sth->execute;
+    my ($name,$surname)=$sth->fetchrow;
+
+    $sth =  $dbh->prepare("SELECT Question FROM A2Q WHERE Author=$id");
+    $sth->execute;
+    my $q;
+    my @Questions;
+    while (($q)=$sth->fetchrow,$q)
+     {push @Questions,$q unless $forbidden{$q}}
+
+    my ($output, $i, $suffix, $hits) = ('', 0, '', $#Questions + 1);
+
+    if ($hits =~ /1.$/  || $hits =~ /[5-90]$/) {
+		$suffix = 'й';
+	} elsif ($hits =~ /1$/) {
+		$suffix = 'е';
+	} else {
+		$suffix = 'я';
+	}
+
+	print p({align=>"center"}, "Автор ".strong("$name $surname. ")
+	. " : $hits попадани$suffix.");
+
+
+#	for ($i = 0; $i <= $#Questions; $i++) {
+#		$output = &PrintQuestion($dbh, $Questions[$i], 1, $i + 1, 1);
+#		print $output;
+#	}
+        PrintList($dbh,\@Questions,'gdfgdfgdfgdfg');
+}
+
+
+sub PrintAuthors
+{
+     my ($dbh,$sort)=@_;
+     my($output,$out1,@array,$sth);
+     if ($sort eq 'surname')
+     {
+        $sth =
+             $dbh->prepare("SELECT Id, Name, Surname, QNumber FROM Authors order by Surname, Name");
+     }
+     elsif($sort eq 'name')
+     {
+        $sth =
+             $dbh->prepare("SELECT Id, Name, Surname, QNumber FROM Authors order by Name, Surname");
+     }
+     else
+     {
+        $sth =
+             $dbh->prepare("SELECT Id, Name, Surname, QNumber FROM Authors Order by QNumber DESC, Surname");
+     }
+
+     $output.=h2("Авторы вопросов")."\n";
+     $output.="";
+
+
+     $sth->execute;
+     $output.=Tr(th[a({href=>url."?authors=name"},"Имя")
+.", ".
+a({href=>url."?authors=surname"},"фамилия")
+     , a({href=>url."?authors=kvo"},"Количество вопросов")]);
+
+     $out1='';
+
+     my $ar=$sth->fetchall_arrayref;
+
+
+
+    foreach my $arr(@$ar)
+     {
+
+           my ($id,$name,$surname,$kvo)=@$arr;
+           if (!$name || !$surname) {#print "Opanki at $id\n"
+              } else
+           {
+             my $add=Tr(td([a({href=>url."?qofauthor=$id"},"$name $surname"), $kvo]))."\n";
+             print STDERR $add;
+             $output.=$add;
+           }
+     }
+     $output.="
"; + return $output; +} + + + MAIN: { setlocale(LC_CTYPE,'russian'); my($i, $tour); my($text) = (param('text')) ? 1 : 0; + my($dbh) = DBI->connect("DBI:mysql:chgk", "piataev", "") or do { print h1("Временные проблемы") . "База данных временно не @@ -573,7 +1132,7 @@ MAIN: print end_html; die "Can't connect to DB chgk\n"; }; - if (!param('comp') and !$text) { + if (!param('comp') and !param('sqldump') and !$text) { print header; print start_html(-"title"=>'Database of the questions', -author=>'dimrub@icomverse.com', @@ -582,21 +1141,44 @@ MAIN: print &Include_virtual("../dimrub/db/reklama.html"); } +if ($^O =~ /win/i) { + $thislocale = "Russian_Russia.20866"; +} else { + $thislocale = "ru_RU.KOI8-R"; +} +POSIX::setlocale( &POSIX::LC_ALL, $thislocale ); + +if ((uc 'а') ne 'А') {print "Koi8-r locale not installed!\n"}; + + if ($text) { print header('text/plain'); } + if (param('hideequal')) { + my ($sth)= $dbh -> prepare("select first, second FROM equalto"); + $sth -> execute; + while ( my ($first, $second)=$sth -> fetchrow) + { + $forbidden{$first}=1; + } + $sth->finish; + } + + if (param('rand')) { - my ($type, $qnum) = ('Ч', 12); - $type = 'Б' if (param('brain')); - $qnum = param('qnum') if (param('qnum') =~ /^\d+$/); - if (param('email') && -x $SENDMAIL && + my ($type, $qnum) = ('', 12); + $type .= 'Б' if (param('brain')); + $type .= 'Ч' if (param('chgk')); + $qnum = param('qnum') if (param('qnum') =~ /^\d+$/); + $qnum = 0 if (!$type); + if (param('email') && -x $SENDMAIL && open(F, "| $SENDMAIL -t -n")) { my ($Email) = param('email'); my ($mime_type) = $text ? "plain" : "html"; print F <prepare($query); + $sth->execute; + my $sstr= join ' ',$sth->fetchrow; + $searchin{'question'}=1; + $searchin{'answer'}=1; +$sstr=~s/[^йцукенгшщзхъфывапролджэячсмитьбюЙЦУКЕНГШЩЗХЪФЫВАПРОЛДЖЭЯЧСМИТЬБЮa-zA-Z0-9]/ /gi; +# print &PrintQuestion($dbh,$qid, 1, '!'); + &PrintSearch($dbh, $sstr, 'proxy'); + } + + elsif (param('all')) { print &PrintAll($dbh, 0); } elsif (param('from_year') && param('to_year')) { - print &PrintDates($dbh); + print &PrintDates($dbh); } elsif (param('comp')) { - print header( - -'Content-Type' => 'application/x-zip-compressed; name="db.zip"', - -'Content-Disposition' => 'attachment; filename="db.zip"' - ); - $tour = (param('tour')) ? param('tour') : 0; - my (@files) = &PrintArchive($dbh, $tour); - open F, "$ZIP -j - $SRCPATH/COPYRIGHT @files |"; - print (); - close F; - $dbh->disconnect; - exit; + print header( + -'Content-Type' => 'application/x-zip-compressed; name="db.zip"', + -'Content-Disposition' => 'attachment; filename="db.zip"' + ); + $tour = (param('tour')) ? param('tour') : 0; + my (@files) = &PrintArchive($dbh, $tour); + open F, "$ZIP -j - $SRCPATH/COPYRIGHT @files |"; + print (); + close F; + $dbh->disconnect; + exit; + } elsif (param('sqldump')) { + print header( + -'Content-Type' => 'application/x-zip-compressed; name="dump.zip"', + -'Content-Disposition' => 'attachment; filename="dump.zip"' + ); + open F, "$ZIP -j - $DUMPFILE |"; + print (); + close F; + $dbh->disconnect; + exit; + } else { $tour = (param('tour')) ? param('tour') : 0; if ($tour !~ /^[0-9]*$/) {