--- db/prgsrc/db.cgi 2002/11/10 16:10:53 1.78 +++ db/prgsrc/db.cgi 2004/03/17 10:26:31 1.132 @@ -2,17 +2,96 @@ use DBI; use CGI ':all'; -use strict; +#use strict; use Time::Local; +my $proxyredirect=1; use POSIX qw(locale_h); use locale; +use vars qw($opt_z); +use Getopt::Std; +#my ($dbuser,$dbname,$dbpass,$dbhost); +require "dbdefs.pl"; +my $url=url||''; +$dbuser||="piataev"; +$dbname||="chgk"; +$dbpass||=""; +$dbhost||="localhost"; +getopts('z'); +$opt_z||=param("makehtml"); +my $timestamp="_timestamp.tmp"; +my $usehash=0; +my $paramtour; +my $withanswers=param('answer')||param('answers'); open STDERR, ">/var/tmp/errors1"; my $newsurl='http://news.chgk.info/'; +my $reklama="../dimrub/db/reklama.html"; +my $footer="../dimrub/db/footer.html"; +$footer="../../chgk/footer.html" if $url=~/zaba/; +$reklama="../../chgk/reklama.html" if $url=~/zaba/; +my $datefooter="../dimrub/db/date"; +$datefooter="../../chgk/date" if $url=~/zaba/; + +my $fname; +$reklama="../reklama.html" if $opt_z; +$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; +$usehtml=0 if $url=~/zaba/; + +my $usewas=0; +my $cashednumber=500; +my $outputnumber=10; +my ($proxyptext,$proxysstr); my $printqueries=0; +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/ && $url !~ /zaba/) { + my $u="http://db.chgk.info/cgi-bin/db.cgi?$qs"; + Redirect ($u); + exit; +} + +if ($proxyredirect && $metod=~/proxy/ && $url !~ /localhost/ && $url !~ /bilbo/ && $url !~ /zaba/) { + my $u="http://chgk.zaba.ru/cgi-bin/db.cgi?$qs"; + Redirect ($u); + exit; +} + +#if (!param('sstr') && param('all')) { +# my $destination='http://db.chgk.info/all.html'; +# Redirect($destination); +# 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', 'Автор', @@ -30,18 +109,25 @@ my %metodchar=('rus',1,'old',2); -my $thislocale; $searchin{$_}=1 foreach param('searchin'); my %TypeName=('children'=>'Д', 'game'=>'Я', 'igp'=>'И', '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`; -chomp $PWD; +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"; @@ -63,11 +149,42 @@ my @months=('000','Jan',"Feb","Mar","Apr 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); @@ -86,6 +203,54 @@ sub GetTournament { 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) = @_; @@ -107,11 +272,36 @@ sub GetQuestion { 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.=$a?"?answers=1&":"?"; + $res.="tour=$t"; + + 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 Number"); @@ -145,13 +335,11 @@ sub GetTours { 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; $sth->finish; $a[0]||0; } @@ -160,61 +348,109 @@ print "timee0=".time.br if $debug; sub printform { - my $submit=submit(-value=>'Поиск'); - my $inputstring=textfield(-name=>'sstr', - -default=>param('sstr')||'', - -size=>30, - -maxlength=>50); - my $qnumber="Выводить по".br. textfield(-name=>'kvo', - -default=>param('kvo')||'150', - -size=>3, - -maxlength=>5). br."вопросов"; - + 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'; - my $types=checkbox_group('type',['chgk','brain','igp','game','ehruditka','beskrylka'], [@df], - 'false',\%rusfieldname); - my $metod=radio_group(-name=>'metod',-values=>['old','rus'], - -default=>(param('metod')||'rus'), - -labels=>\%rusfieldname); - my $all=radio_group(-name=>'all',-values=>['yes','no'], - -default=>(param('all')||'no'), - -labels=>{'yes'=>'Все','no'=>'Любое'}); + $checked{'all'}=$all?"checked":""; + $checked{'any'}=$all?"":"checked"; + $checked{lc param('metod')}="checked"; + $checked{'rus'}=1 unless $checked{'rus'} || $checked{'old'}; ################################################# -return start_form(-method=>'get', - -action=>url, - -enctype=> - "application/x-www-form-urlencoded" -).br. -table(Tr -( - td({-valign=>'TOP'},$inputstring.$submit.p."Метод: $metod".p."Слова: $all"), - td({-valign=>'TOP'},(' 'x 8).'Поля:'), - td({-valign=>'TOP'},$fields), - td({-valign=>'TOP'},(' 'x 1).'Типы:'), - td({-valign=>'TOP'},$types), td(" "x5), - td({-valign=>'TOP'},$qnumber) -) -) - -#$fields. -#$inputstring.$submit.br.$metod.$all +return +< +

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

+ + + $qnumber +

+ + + + + + + + + + + + + +
Вариант поиска: + + Простой (старый) + + "Что? Где? Когда?" + + "Брейн-Ринг" + + "Интернет" +
+ "Своя игра" + + "Эрудитка" + + "Бескрылка" +
Расширенный (с учетом грамматики, в вопросах всех типов) +
Искать: + +Все слова + +Любое слово +
Поля для поиска: + +Вопрос + +Ответ
+
+Комментарии
+
+Автор
+
+Источник
+
+

Если при попытке поиска выдаётся сообщение об ошибке, +попробуйте воспользоваться +зеркалом базы + + +EOT .endform .hr } sub proxy -{ -#print "time0=".time.br if $debug; +{ 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; @@ -223,6 +459,7 @@ sub proxy $text=~s/[^йцукенгшщзхъфывапролджэячсмитьбюЙЦУКЕНГШЩЗХЪФЫВАПРОЛДЖЭЯЧСМИТЬБЮQWERTYUIOPASDFGHJKLZXCVBNM0-9]/ /g; $text=uc $text; my @list= $text=~m/(?:(?:${RLrl})+)|(?:[A-Za-z0-9]+)/gom; + my (%c, %good,$sstr); foreach (@list) { @@ -231,26 +468,16 @@ sub proxy 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; -# 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); + return $sstr; } @@ -270,9 +497,12 @@ 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 начальных форм @@ -282,7 +512,6 @@ $sstr=~tr/йцукенгшщзхъфывапролджэячсмить $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]}=(); @@ -313,7 +542,6 @@ print "$query",br if $printqueries; my $kvo=0; push @$allnf, @{$_} foreach @nf; - print "nf=@$allnf" if $printqueries; foreach $i (0..$#w) #запросы в базу... { @@ -323,11 +551,10 @@ print "$query",br if $printqueries; - $_= " word2question.word=".$_. ' ' foreach @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; + $query="select questions from word2question where (". (join ' OR ', @arr).") AND length(questions)<80000"; $sth=$dbh -> prepare($query); $sth->execute; @@ -339,7 +566,6 @@ print STDERR "!$query\n",br if $printque } $sth->finish; $query="select number from nf where ".(join ' OR ', @arr1); -print "$query\n",br if $printqueries; $sth=$dbh -> prepare($query); $sth->execute; @@ -387,7 +613,6 @@ print "$query\n",br if $printqueries; } } #foreach $i -#print "keys tasksof", join ' ', keys %{$tasksof{0}}; #Ищем пересечение или объединение списков вопросов (значений %tasksof) foreach $sf (keys %tasksof) { @@ -397,7 +622,6 @@ print "$query\n",br if $printqueries; keys %count) ; -print "\n\$#tasks=",$#tasks,br if $printqueries; ############ Сортировка найденных вопросов foreach (keys %wordsof) @@ -407,14 +631,9 @@ foreach (keys %wordsof) @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; } @@ -469,17 +688,6 @@ sub Search { my $sstr=$$s; my (@arr, @Questions, @fields); 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); @@ -487,10 +695,7 @@ sub Search { } elsif ($metod eq 'proxy') { -# $searchin{'question'}=1; -# $searchin{'answer'}=1; my @task=proxy($dbh,$s,$allnf); -# $$s=$sstr; return @task } @@ -517,7 +722,6 @@ sub Search { $where= $$q{'matchexp'}; $query= "SELECT Questionid FROM Questions WHERE $where"; - print br."Query is: $query".br if $debug; $sth = $dbh->prepare($query); } else @@ -549,7 +753,6 @@ sub Search { WHERE ($f LIKE $sstr) AND (".&makewhere.") ORDER BY QuestionId"; -print $query if $printqueries; $sth = $dbh->prepare($query) } #else -- processing old-style query (R7) @@ -558,7 +761,6 @@ print $query if $printqueries; push @Questions, $arr[0] unless $forbidden{$arr[0]}; } $sth->finish; -print "@Questions" if $printqueries; return @Questions; } @@ -570,7 +772,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; @@ -593,13 +795,12 @@ sub NoCase { sub PrintList { my ($dbh,$Questions,$shablon,$was)=@_; - + my $Output; my $first=param('first') ||1; - my $kvo=param('kvo') ||150; - - $first=$first-($first-1)%$kvo; - my $last=$first+$kvo-1; - $last=scalar @$Questions if scalar @$Questions <$last; + $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; @@ -607,92 +808,105 @@ sub PrintList { $qs=~s/\&first\=[^\&]+//g; my $sstr=param('sstr')||''; $qs=~s/sstr=[^\&]+/sstr=$sstr/; - $qs=~s/\&was=[^\&]+//; - $qs.="&was=$was"||''; - if ($first>$kvo*3+1) + 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-$kvo))},"<").(" "x4) - } - + a({href=>$url."?".$qs."\&first=1"},"<<").(" "x4). + a({href=>($url."?".$qs."\&first=".($first-$outputkvo))},"<").(" "x4) + } else {$nav.=' 'x15;} my ($fprint,$lprint); - my $llprint=$#$Questions- ($#$Questions+1)%$kvo+2; - if ($#$Questions+1<=$kvo*7) + my $llprint=$fkvo- ($fkvo)%$outputkvo+1; # + if ($fkvo<=$outputkvo*7) { $fprint=1; $lprint=$llprint; } - elsif ($first>$kvo*3 && $#$Questions+1-$first>$kvo*3) + elsif ($first>$outputkvo*3 && $fkvo-$first>$outputkvo*3) { - $fprint=$first-$kvo*3; - $lprint=$first+$kvo*3; + $fprint=$first-$outputkvo*3; + $lprint=$first+$outputkvo*3; } - elsif ($first<=$kvo*3) + elsif ($first<=$outputkvo*3) { - $fprint=1; $lprint=6*$kvo+1; + $fprint=1; $lprint=6*$outputkvo+1; } else { $lprint=$llprint; - $fprint=$lprint-$kvo*6 + $fprint=$lprint-$outputkvo*6 } -# my $fprint=($first>$kvo*3) ? $first-$kvo*3 : 1; -# my $lprint=$#$Questions+1-$fprint>$kvo*7 ? $kvo*7 :$#$Questions+1; -# if ($lprint-$fprint<$kvo*6 && $fprint>1) +# 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-$kvo*6; +# $fprint=$lprint-$outputkvo*6; # $fprint=1 if ($fprint<=0) # } - for($f=$fprint; $f<=$lprint; $f+=$kvo) + for($f=$fprint; $f<=$lprint; $f+=$outputkvo) { -# next if $first-$f>$kvo*3; - $l=$f+$kvo-1; - $l=$#$Questions+1 if $l>$#$Questions+1; +# 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")."] ";} + $nav.= "[".a({href=>($url."?".$qs."\&first=$f")},"$f-$l")."] ";} } - if ($lprint+$kvo<$#$Questions) + if ($lprint+$outputkvo<$fkvo) { $nav.= (" "x4). - a({href=>(url."?".$qs."\&first=".($first+$kvo))},">").(" "x4). - a({href=>url."?".$qs."\&first=$llprint"},">>").(" "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[$_]; + } - - print "$nav".br."\n"; for (my $i = $first; $i <= $last; $i++) { - my $output = &PrintQuestion($dbh, $$Questions[$i-1], 1, 0, 1); - if (param('metod') && (param('metod') eq 'rus' || param('metod') eq 'proxy')) + 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; - } else { $output=~s/($shablon)/\$1\<\/strong\>/gi; } - print $output; + $Output.= $output; } + $sth->finish; - - print "$nav".br."\n"; - + $Output.= "$nav".br."\n"; + return $Output; } sub PrintSearch { + my $Output=''; my ($dbh, $sstr, $metod,$was) = @_; my $t=time; - print h2("Поиск в базе вопросов"); - print printform; + $Output.= printform; my @allnf; my @Questions; - if ($was) + $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; @@ -701,25 +915,29 @@ sub PrintSearch { @Questions=unpack 'L*',$q; @allnf=unpack 'L*',$nf; $sth->finish; - } else + } + if (!$was || ($metod eq 'proxy') || (param('first')+$outputkvo>$cashednumber)) { @Questions=&Search($dbh, \$sstr,$metod,$all,\@allnf); - my $tmp=$dbh->quote(pack("L*",@Questions)); + $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; - do - { - $was=int rand(32000); - } - while (--$ss && (!$dbh->do ("insert into lastqueries (id,sstr,questions,allnf) + if ($usewas) { + do + { + $was=int rand(32000); + } + while (--$ss && (!$dbh->do ("insert into lastqueries (id,sstr,questions,allnf) values ($was, $qsstr,$tmp,$nf)"))); - print "Something is wrong...".br unless $ss; + $Output.= "Something is wrong...".br unless $ss; + } } - print p. "Время поиска: " . (time-$t) ." сек.".p; + $Output.= p. "Время поиска: " . (time-$t) ." сек.".p; my ($output, $i, $suffix, $hits) = ('', 0, '', $#Questions + 1); my $shablon; @@ -730,7 +948,6 @@ sub PrintSearch { $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; @@ -743,11 +960,10 @@ print "$query" if $printqueries; $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 = 'й'; @@ -757,7 +973,7 @@ print "$query" if $printqueries; $suffix = 'я'; } - print p({align=>"center"}, "Результаты поиска на " . strong($sstr) + $Output.= p({align=>"center"}, "Результаты поиска на " . strong($sstr) . " : $hits попадани$suffix."); if (param('word')) { @@ -774,27 +990,48 @@ print "$query" if $printqueries; s/(\W)/\\$1/g foreach (@sar); $shablon=join "|",@sar; } - PrintList($dbh,\@Questions,$shablon,$was); + $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 $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 { $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 + fetchquestion($sth,\%q,0); $output .= - &PrintQuestion($dbh, $Questions[$i], 1, $i + 1, 0, $text); + &PrintQuestion($dbh, \%q, $answer, $i + 1, 0, $text,1); + push @answers, $q{'Answer'}; } + $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; } @@ -813,9 +1050,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'}; @@ -849,9 +1086,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++) { @@ -869,7 +1117,7 @@ sub PrintTournament { } else { $qnum = ''; } - if ($Tournament{'Type'} =~ /Г/) { + if ($Tournament{'Type'} !~ /[ТЧ]/) { $SingleTour=0; $imgsrc = "/icons/folder.gif"; $alt = "[*]"; @@ -891,30 +1139,32 @@ sub PrintTournament { else {$textid=$Tournament{'Id'}}; - if ($SingleTour or $Tournament{'Type'} =~ /Т/) { + 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=$textid&answer=0"}, + . a({href=>tourhref($textid,0)}, "вопросы") . "] [" - . a({href=>url . "?tour=$textid&answer=1"}, + . a({href=>tourhref($textid,1)}, "вопросы + ответы") . "]") ); } else { - $list .= dd(a({href=>url . "?tour=$textid&comp=1"}, - img({src=>'/icons/compressed.gif', alt=>'[ZIP]', border=>1})). " " . + $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=>url . "?tour=$textid&answer=0"}, + . " " . a({href=>tourhref($textid,0,1)}, $Tournament{'Title'}. " ". - $Tournament{'PlayedAt'}||'') . $qnum); + ($Tournament{'PlayedAt'}||'')) . $qnum); } } $output .= dl($list); if ($URL) { - if (url=~/zaba\.ru/ && $URL=~/^\//){$URL="http://info.chgk.info$URL"} + if ($url=~/zaba\.ru/ && $URL=~/^\//){$URL="http://info.chgk.info$URL"} $output .= p("Дополнительная информация об этом турнире - по адресу " . a({-'href'=>$URL}, $URL)); @@ -940,6 +1190,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) = @_; @@ -969,6 +1236,7 @@ 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'} !~ /Т/); @@ -985,10 +1253,12 @@ sub PrintTour { $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'}) { @@ -1007,23 +1277,27 @@ sub PrintTour { my $n=$Tour{'Number'}; if ($answer == 0) { + my $nn=".$n"; + $nn="" if ($n==1 && !&IsTour($dbh, $Tour{'ParentId'}, $n + 1)); + $bottom .= - "[" . a({href=>url . "?tour=$fname.$n&answer=1"}, "ответы") . "] " . br; + "[" . a({href=>tourhref("$fname$nn",1)}, + "ответы") . "] " . br; } if ($n>1) { $bottom .= - "[" . a({href=>url . "?tour=$fname." . ($n - 1) . "&answer=0"}, + "[" . a({href=>tourhref("$fname.".($n-1),0)}, "предыдущий тур") . "] "; $bottom .= - "[" . a({href=>url . "?tour=$fname." . ($n - 1) . "&answer=1"}, + "[" . a({href=>tourhref("$fname.".($n-1),1)}, "предыдущий тур с ответами") . "] " . br; } if (&IsTour($dbh, $Tour{'ParentId'}, $n + 1)) { $bottom .= - "[" . a({href=>url . "?tour=$fname." . ($n + 1) . "&answer=0"}, + "[" . a({href=>tourhref("$fname.".($n+1),0)}, "следующий тур") . "] "; $bottom .= - "[" . a({href=>url . "?tour=$fname." . ($n + 1) . "&answer=1"}, + "[" . a({href=>tourhref("$fname.".($n+1),1)}, "следующий тур с ответами") . "] "; } @@ -1039,8 +1313,12 @@ sub PrintField { $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/\s+-+\s+/ – /mg;
+	    $value =~ s/(http:\/\/\S+[^\s\)\(\,\.])/$1<\/a>/g if $header !~ /^Авто/;
+#	    $value =~ s/(http:\/\/(?:\w+.)+[\w\\\~]+(\?[^\s.]+)?)/$1<\/a>/g if $header !~ /^Авто/;
 #	    $value =~ s/(\s)"/$1“/mg;
 #	    $value =~ s/^"/“/mg;
 #	    $value =~ s/"/”/mg;
@@ -1054,68 +1332,88 @@ sub PrintField {
 # 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);
-	$qnum = $Question{'Number'}
-		if ($qnum == 0);
-	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'});
-			my $fname=$Tournament{'FileName'};
-return "" if $fname=~/mgp0203/;
+			$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=$fname"}, $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=$fname.$Tour{Number}#$qnum"}, $Tour{'Title'})));
+					a({href=>tourhref("$fname.$Question{'TourNumber'}#$qnum",1)}, 
+                          $Question{'TourTitle'})));
 		}
 		$output .= dl(strong($titles));
 	}
 
 
-	$output.= "";
-
-	$output .=
-		&PrintField("Вопрос $qnum", $Question{'Question'}, $text);
+	$output.= "" unless $text;
 
-	if ($answer==1) {
+	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;
-                          $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;
-                       }
- 
+# 		      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);
 
 		}
@@ -1157,22 +1455,38 @@ EOTT
 		}
 
 
+
 $output.=""
 
 	}
-	$output.=br.a({href=> url."?metod=proxy&qid=$Id"}, 'Близкие вопросы').p
-             if $answer;
+	$output=~s/\(pic: ([^\)]*)\)/

/g unless $text; + $paramtour||=param("tour"); + my $qid=$paramtour ? ($paramtour.".$Question{'Number'}" ): ''; + + $output.=br.a({href=> $url."?metod=proxy& +qid=$qid"}, 'Близкие вопросы').p + if $answer>0 && !$text && $qid; 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) = @_; @@ -1193,16 +1507,20 @@ 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 ='$_Д') "; } $where.= "OR (Type='ЧБ')" if ($type=~/Ч|Б/); - $q="select QuestionId, QuestionId/$r-floor(QuestionId/$r) as val - from Questions where $where order by val limit $num"; +# $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 ($w1) AND ($where) order by rand() limit $num"; + $sth=$dbh->prepare($q); $sth->execute; @@ -1220,20 +1538,20 @@ 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"; + or return ""; #die "Can't open the file $fn: $!\n"; while () { if (//&Include_virtual($1)/e; + s//&Include_virtual($1)/e; } if (//`$1`/e; } $output .= $_; } - return $output; + return $output||""; } sub PrintArchive { @@ -1258,6 +1576,8 @@ sub PrintAll { my (%Tournament) = &GetTournament($dbh, $Id); my (@Tours) = &GetTours($dbh, $Id); + my $SingleTour = $#Tours == 0; + my ($New) = ($Id and $Tournament{'Type'} eq 'Ч' and &NewEnough($Tournament{"CreatedAt"})) ? img({src=>"/znatoki/dimrub/db/new-sml.gif", alt=>"NEW!"}) : ""; @@ -1279,7 +1599,7 @@ sub PrintAll { $output .= dd(img({src=>"/icons/folder.gif", alt=>"[*]"}) . - " " . a({href=>url . "?tour=$textid&answer=0"}, + " " . a({href=>tourhref($textid,0,!$SingleTour)}, $Tournament{'Title'}) ." " . ($Tournament{'PlayedAt'}||'') . " $New"); } if ($Id == 0 or $Tournament{'Type'} =~ /Г/ or $Tournament{'Type'} eq '') { @@ -1312,8 +1632,19 @@ 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=>url . "?tour=$Tournament{'Id'}&answer=0"}, + " " . a({href=>tourhref($textid,0,1)}, $Tournament{'Title'}, $Tournament{'PlayedAt'}||'')); } $sth->finish; @@ -1325,7 +1656,16 @@ sub PrintQOfAuthor { my ($dbh, $id) = @_; - $id=$dbh->quote($id); + my $Output=''; + unless ($id=~/^\d+$/) { + $id=$dbh->quote($id); + my $sth = $dbh->prepare("SELECT Id FROM Authors WHERE CharId=$id"); + $sth->execute; + ($id)=$sth->fetchrow; + $sth->finish; + } + $id=$dbh->quote($id); + my $sth = $dbh->prepare("SELECT Name, Surname FROM Authors WHERE Id=$id"); $sth->execute; my ($name,$surname)=$sth->fetchrow; @@ -1347,9 +1687,8 @@ sub PrintQOfAuthor } else { $suffix = 'я'; } - print h2("Поиск в базе вопросов"); - print printform; - print p({align=>"center"}, "Автор ".strong("$name $surname. ") + $Output.= printform; + $Output.= p({align=>"center"}, "Автор ".strong("$name $surname. ") . " : $hits попадани$suffix."); @@ -1357,7 +1696,7 @@ sub PrintQOfAuthor # $output = &PrintQuestion($dbh, $Questions[$i], 1, $i + 1, 1); # print $output; # } - PrintList($dbh,\@Questions,'gdfgdfgdfgdfg'); + $Output.=PrintList($dbh,\@Questions,'gdfgdfgdfgdfg'); } @@ -1386,10 +1725,10 @@ sub PrintAuthors $sth->execute; - $output.=Tr(th[a({href=>url."?authors=name"},"Имя") + $output.=Tr(th[a({href=>$url."?authors=name"},"Имя") .", ". -a({href=>url."?authors=surname"},"фамилия") - , a({href=>url."?authors=kvo"},"Количество вопросов")]); +a({href=>$url."?authors=surname"},"фамилия") + , a({href=>$url."?authors=kvo"},"Количество вопросов")]); $out1=''; @@ -1402,11 +1741,10 @@ a({href=>url."?authors=surname"},"фамили { my ($id,$name,$surname,$kvo)=@$arr; - if (!$name || !$surname) {#print "Opanki at $id\n" + if (!$name || !$surname) { } else { - my $add=Tr(td([a({href=>url."?qofauthor=$id"},"$name $surname"), $kvo]))."\n"; - print STDERR $add; + my $add=Tr(td([a({href=>$url."?qofauthor=$id"},"$name $surname"), $kvo]))."\n"; $output.=$add; } } @@ -1425,7 +1763,8 @@ sub WriteFile { my $query= "SELECT Id, Title, Copyright, Info, URL, Editors, EnteredBy, PlayedAt, CreatedAt - from Tournaments where FileName=".$dbh->quote("$fname.txt"); + 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; @@ -1566,57 +1905,81 @@ sub WriteFile { } +sub Bottom +{ + my $output.=&Include_virtual("$footer")||""; + $output.=p."

Обновление: ".&Include_virtual("$datefooter")."
"; + $output.=< +function toggle(e) { + if (e.style.display == "none") { + e.style.display=""; + } else { + e.style.display = "none"; + } +} + +EEE +; + $output.=end_html; + return $output; +} + MAIN: { + setlocale(LC_CTYPE,'russian'); + POSIX::setlocale( &POSIX::LC_ALL, $thislocale ); my($i, $tour); my($text) = (param('text')) ? 1 : 0; - - my($dbh) = DBI->connect("DBI:mysql:chgk", "piataev", "") + $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 h1("Временные проблемы") . "База данных временно не + print header.h1("Временные проблемы") . "База вопросов временно не работает. Заходите попозже."; - print &Include_virtual("../dimrub/db/reklama.html"); + print &Include_virtual("$reklama") if $url!~/localhost/; print end_html; die "Can't connect to DB chgk\n"; }; - if (!param('comp') and !param('sqldump') and !$text) { - print header; - print start_html(-"title"=>'Database of the questions', - -author=>'dimrub@icomverse.com', - -bgcolor=>'#fff0e0', - -vlink=>'#800020'); - 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 (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 ($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 ($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; - } - $tour = (param('tour')) ? param('tour') : 0; - my $sth; - if ($tour !~ /^[0-9]*$/) { + if ($tour !~ /^[0-9]*$/) { if ($tour=~/\./) { my ($fname,$n)= split /\./ , $tour; @@ -1624,18 +1987,114 @@ if ((uc 'а') ne 'А') {print "Koi8-r loca $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=$n"); } else { $sth = $dbh->prepare("SELECT Id FROM Tournaments - WHERE FileName = '$tour.txt'"); + WHERE FileName = '$tour.txt' OR + FileName = '$tour'"); } $sth->execute; $tour = ($sth->fetchrow)[0]; $sth->finish; + } + + + if ($text && !param ('comp')) { + print header('text/plain'); + } 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'); +# if ($qid !~ /^[0-9]+$/) + { + 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' 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' OR FileName = '$fname'" ); +# } + $sth->execute; + $tour = ($sth->fetchrow)[0]; + $sth->finish; + $sth = $dbh->prepare( + "SELECT QuestionId FROM + Questions + WHERE ParentId=$tour AND + Questions.Number=$n"); + $sth->execute; + $qid = ($sth->fetchrow)[0]; + my $query="SELECT Question, Answer from Questions where QuestionId=$qid"; + $sth=$dbh->prepare($query); + $sth->execute; + $sstr= join ' ',$sth->fetchrow; + $sth->finish; + $searchin{'Question'}=1; + $searchin{'Answer'}=1; + $sstr=~tr/ёЁ/еЕ/; + $sstr=~s/[^йцукенгшщзхъфывапролджэячсмитьбюЙЦУКЕНГШЩЗХЪФЫВАПРОЛДЖЭЯЧСМИТЬБЮa-zA-Z0-9]/ /gi; + $proxysstr=$sstr; + $proxysstr=makeproxysstr($dbh,\$proxysstr); + } + + } + + + if (!param('comp') and !param('sqldump') and !$text) { + my $title="Результаты поиска на \"". ($proxysstr||$sstr) .'"' + if ($proxysstr||$sstr); + $title||="База вопросов"; + $globaloutput.=start_html(-"title"=>$title, + -author=>'dimrub@icomverse.com', + -bgcolor=>'#fff0e0', + -vlink=>'#800020');#} +$globaloutput.="\n"; + + $globaloutput.=&Include_virtual("$reklama")||''; + } + + 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(); + $sth->finish; + if ($p) { + print ".$p"; + $dbh->disconnect; + exit ; } + } + + + + + 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')) { @@ -1659,64 +2118,49 @@ Content-type: text/$mime_type; charset=" EOT print F &PrintRandom($dbh, $type, $qnum, $text); close F; - print "Пакет случайно выбранных вопросов послан по адресу $Email. Нажмите + $globaloutput.= "Пакет случайно выбранных вопросов послан по адресу $Email. Нажмите на Reload для получения еще одного пакета"; } else { - print &PrintRandom($dbh, $type, $qnum, $text); + $globaloutput.= &PrintRandom($dbh, $type, $qnum, $text); } } elsif (param('authors')){ - print &PrintAuthors($dbh,param('authors')); + $globaloutput.= &PrintAuthors($dbh,param('authors')); } elsif (param('qofauthor')){ - &PrintQOfAuthor($dbh,param('qofauthor')); + $globaloutput.= &PrintQOfAuthor($dbh,param('qofauthor')); } elsif (param('sstr')||param('was')) { - &PrintSearch($dbh, param('sstr'), param('metod'),param('was')); + $globaloutput.=&PrintSearch($dbh, $sstr||' ', param('metod')||'',param('was')); $dbh->do("delete from lastqueries where (TO_DAYS(NOW()) - TO_DAYS(t) >= 2) OR - (time_to_sec(now())-time_to_sec(t) >3600)") + (time_to_sec(now())-time_to_sec(t) >3600)") if $usewas && random(30)==0; } elsif (param('qid')) { - my $qid=param('qid'); - my $query="SELECT Question, Answer from Questions where QuestionId=$qid"; -print $query if $printqueries; - my $sth=$dbh->prepare($query); - $sth->execute; - my $sstr= join ' ',$sth->fetchrow; - $sth->finish; - $searchin{'Question'}=1; - $searchin{'Answer'}=1; - $sstr=~tr/ёЁ/еЕ/; -$sstr=~s/[^йцукенгшщзхъфывапролджэячсмитьбюЙЦУКЕНГШЩЗХЪФЫВАПРОЛДЖЭЯЧСМИТЬБЮa-zA-Z0-9]/ /gi; -# print &PrintQuestion($dbh,$qid, 1, '!'); - &PrintSearch($dbh, $sstr, 'proxy'); + $globaloutput.=&PrintSearch($dbh, $sstr||'', 'proxy'); } elsif (param('getfile')){ - print &writefile + $globaloutput.=&writefile } elsif (param('all')) { - print &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')) { - print &PrintDates($dbh); + $globaloutput.=&PrintDates($dbh); } elsif (param('comp')) { 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=db.zip\n"; - print "Content-Disposition: attachment; filename=db.zip \n\n"; -# print header( -# -'Content-Type' => 'application/x-zip-compressed; name="db.zip"', -# -'Content-Type' => 'application/zip', -# -'Content-Disposition' => 'attachment; filename="db.zip"' -# ); + 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 - $SRCPATH/COPYRIGHT @files |"; open F, "$ZIP -j - @files |"; binmode(F); binmode(STDOUT); - print (); + print join "",; close F; $dbh->disconnect; exit; @@ -1731,7 +2175,8 @@ $sstr=~s/[^йцукенгшщзхъфывапролджэячсмит $dbh->disconnect; exit; - } else { + } + elsif (!$opt_z && !param("makehtml")) { my $QuestionNumber=0; my $qnum; if ($qnum=param('qnumber')){ @@ -1741,27 +2186,83 @@ $sstr=~s/[^йцукенгшщзхъфывапролджэячсмит $QuestionNumber=($sth->fetchrow)[0]||0; } if ($QuestionNumber) { - print &PrintQuestion($dbh, $QuestionNumber, param('answer')||0, $qnum, 1); + $globaloutput.= &PrintQuestion($dbh, $QuestionNumber, $withanswers||0, $qnum, 1,0,0); # $dbh, $Id, $answer, $qnum, $title, $text } else { - print &PrintTournament($dbh, $tour, param('answer')); + $globaloutput.=&PrintTournament($dbh, $tour, $withanswers); } } + else { + $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"; + my $o=$globaloutput; + $o.=&PrintTournament($dbh, 0, 0); + $o.=&Bottom; + print FF $o; + close FF; + open FF, ">${realHTMLDIR}all.html" or die "ERROR! - ${HTMLDIR}all.html\n"; + $o=$globaloutput; + $o.=&PrintAll($dbh,0); + $o.=&Bottom; + print FF $o; + close FF; + + +# my ($sth) = $dbh->prepare("SELECT t1.Id, t1.FileName, t1.Type, +# count(t2.Id) +# 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"); + $sth->execute; + my ($Id,$fname,$type,$c); + while (($Id,$fname,$type,$c)=$sth->fetchrow,$Id) { + next unless $fname; + print "$fname\n"; + $fname=~s/\.txt$//; + if ($type=~/Т/ || $c<=1) + { + 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; + close FF; + open FF, ">$realHTMLDIR$fname-a.html"; + $o=$globaloutput; + $o.=&PrintTournament($dbh, $Id, 1); + $o.=&Bottom; + print FF $o; + close FF; + } + else { + open FF, ">$realHTMLDIR$fname.html" or die "ERROR! - $fname-q.html\n"; + my $o=$globaloutput; + $o.=&PrintTournament($dbh, $Id, 0); + $o.=&Bottom; + print FF $o; + close FF; + + } + } + } if (!$text) { - print &Include_virtual("../dimrub/db/footer.html"); -print < -function toggle(e) { - if (e.style.display == "none") { - e.style.display=""; - } else { - e.style.display = "none"; - } -} - -EEE -; - print end_html; + $globaloutput.=&Bottom; } + if (!$opt_z){ + print $globaloutput; + 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). + ",$globaloutput)"); + } + } + $dbh->disconnect; }