File:  [Local Repository] / db / prgsrc / db.cgi
Revision 1.75: download - view: text, annotated - select for diffs - revision graph
Sun Oct 6 23:12:22 2002 UTC (21 years, 8 months ago) by roma7
Branches: MAIN
CVS tags: HEAD
*** empty log message ***

    1: #!/usr/bin/perl -w
    2: 
    3: use  DBI;
    4: use CGI ':all';
    5: use strict;
    6: use Time::Local;
    7: use POSIX qw(locale_h);
    8: use locale;
    9: open STDERR, ">/var/tmp/errors1";
   10: my $printqueries=0;
   11: my %forbidden=();
   12: my $debug=0; #added by R7
   13: if (param('debug')) {$debug=1; $printqueries=1}
   14: *STDERR=*STDOUT if $debug;
   15: my %fieldname= (0,'Question', 1, 'Answer', 2, 'Comments', 3, 'Authors', 4, 'Sources');
   16: my %rusfieldname=('Question','Вопрос', 'Answer', 'Ответ', 
   17:                   'Comments', 'Комментарии', 'Authors', 'Автор', 
   18:                   'Sources', 'Источник','old','Старый','rus','Новый',
   19:                   'chgk', 'ЧГК', 'brain', 'Брейн-ринг','game', 'Своя игра', 
   20:                   'ehruditka', 'Эрудитка', 'beskrylka', 'Бескрылка'
   21: );
   22: my %searchin;
   23: my $rl=qr/[йцукенгшщзхъфывапролджэячсмитьбюё]/;
   24: my $RL=qr/[ЙЦУКЕНГШЩЗХЪЭЖДЛОРПАВЫФЯЧСМИТЬБЮЁ]/;
   25: my $RLrl=qr/(?:(?:${rl})|(?:${RL}))+/;
   26: my $l=qr/(?:(?:${RLrl})|(?:[\w\-]))+/;
   27: my $Ll=qr/(?:[A-Z])|(?:${RL})/;
   28: my %metodchar=('rus',1,'old',2);
   29: 
   30: 
   31: 
   32: my $thislocale;
   33: 
   34: $searchin{$_}=1 foreach param('searchin');
   35: my %TypeName=('children'=>'Д', 'game'=>'И',
   36:               'chgk'=>'Ч', 'brain'=>'Б', 'beskrylka'=>'Л','ehruditka'=>'Э');
   37: 
   38: 
   39: 
   40: my $all=param('all');
   41: $all=0 if lc $all eq 'no';
   42: my ($PWD) = `pwd`;
   43: chomp $PWD;
   44: my ($SRCPATH) = "/home/piataev/public_html/dimrub/src";
   45: my ($ZIP) = "/usr/local/bin/zip";
   46: my $DUMPFILE = "/tmp/chgkdump";
   47: my ($SENDMAIL) = "/usr/sbin/sendmail";
   48: my ($TMPDIR) = "/var/tmp";
   49: my ($TMSECS) = 30*24*60*60;
   50: my (%RevMonths) =
   51: 	('Jan', '0', 'Feb', '1', 'Mar', '2', 'Apr', '3', 'May', '4', 'Jun', '5',
   52: 	'Jul', '6', 'Aug', '7', 'Sep', '8', 'Oct', '9', 'Nov', '10',
   53: 	'Dec', '11',
   54: 	 'Янв', '0', 'Фев', 1, 'Мар', 2, 'Апр', 3, 'Май', '4',
   55: 	 'Июн', '5', 'Июл', 6, 'Авг', '7', 'Сен', '8',
   56: 	 'Окт', '9', 'Ноя', '19', 'Дек', '11');
   57: my @months=('000','Jan',"Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct",
   58:           "Nov","Dec");
   59: 
   60: 
   61: # Determine whether the given time is within 2 months from now.
   62: sub NewEnough {
   63: 	my ($a) = @_;
   64: 	my ($year, $month, $day) = split('-', $a);
   65: 
   66: 	return (time - timelocal(0, 0, 0, $day, $month -1, $year) < $TMSECS);
   67: }
   68: 
   69: # Reads one question from the DB. Gets DB handler and Question ID.
   70: sub GetTournament {
   71: 	my ($dbh, $Id) = @_;
   72: 	my (%Tournament, $field, @arr);
   73: 
   74: 	return %Tournament if ($Id == 0);
   75: 
   76: 	my ($sth) = $dbh->prepare("SELECT * FROM Tournaments WHERE Id=$Id");
   77: 	$sth->execute;
   78: 
   79: 	@arr = $sth->fetchrow;
   80: 	my($i, $name) = 0;
   81: 	foreach $name (@{$sth->{NAME}}) {
   82: 		$Tournament{$name} = $arr[$i++];
   83: 	}
   84:         $sth->finish;
   85: 	return %Tournament;
   86: }
   87: 
   88: # Reads one question from the DB. Gets DB handler and Question ID.
   89: sub GetQuestion {
   90: 	my ($dbh, $QuestionId) = @_;
   91: 	my (%Question, $field, @arr);
   92: 
   93: 	my($sth) = $dbh->prepare("
   94: 		SELECT * FROM Questions WHERE QuestionId=$QuestionId
   95: 	");
   96: 
   97: 	$sth->execute;
   98: 
   99: 	@arr = $sth->fetchrow;
  100: 	my($i, $name) = 0;
  101: 	foreach $name (@{$sth->{NAME}}) {
  102: 		$Question{$name} = $arr[$i++];
  103: 	}
  104: 
  105:         $sth->finish;
  106: 	return %Question;
  107: }
  108: 
  109: # Gets numbers of all the questions from the given tour.
  110: sub GetTourQuestions {
  111: 	my ($dbh, $ParentId) = @_;
  112: 	my (@arr, @Questions);
  113: 
  114: 	my ($sth) = $dbh->prepare("SELECT QuestionId FROM Questions
  115: 		WHERE ParentId=$ParentId order by Number");
  116: 
  117: 	$sth->execute;
  118: 
  119: 	while (@arr = $sth->fetchrow) {
  120: 		push @Questions, $arr[0];
  121: 	}
  122: 
  123:         $sth->finish;
  124: 	return @Questions;
  125: }
  126: 
  127: # Returns list of children of the given tournament.
  128: sub GetTours {
  129: 	my ($dbh, $ParentId) = @_;
  130: 	my (@arr, @Tours);
  131: 
  132: 	my ($sth) = $dbh->prepare("SELECT Id FROM Tournaments
  133: 		WHERE ParentId=$ParentId ORDER BY Id");
  134: 
  135: 	$sth->execute;
  136: 
  137: 	while (@arr = $sth->fetchrow) {
  138: 		push @Tours, $arr[0];
  139: 	}
  140:         $sth->finish;
  141: 	return @Tours;
  142: }
  143: 
  144: sub count
  145: {
  146:   my ($dbh,$word)=@_; 
  147: print "timeb=".time.br if $debug;
  148:   $word=$dbh->quote(uc $word);
  149:   my $query="SELECT number from nests,nf where $word=w1 AND w2=nf.id";
  150:   my $sth=$dbh->prepare($query);
  151:   $sth->execute;
  152:   my @a=$sth->fetchrow;
  153: print "timee0=".time.br if $debug;
  154:   $sth->finish;
  155:   $a[0]||0;
  156: }
  157: 
  158: 
  159: sub printform
  160: {
  161: 
  162:   my $submit=submit(-value=>'Поиск');
  163:   my $inputstring=textfield(-name=>'sstr',
  164:                          -default=>param('sstr')||'',
  165:                          -size=>30,
  166:                          -maxlength=>50);
  167:   my $qnumber="Выводить по".br. textfield(-name=>'kvo',
  168:                          -default=>param('kvo')||'150',
  169:                          -size=>3,
  170:                          -maxlength=>5). br."вопросов";
  171: 
  172:   my @df=keys %searchin;
  173:   @df=('Question', 'Answer') unless @df;
  174:   my $fields=checkbox_group('searchin',['Question','Answer','Comments','Authors','Sources'], [@df],
  175:              'false',\%rusfieldname);
  176:   @df=param('type');
  177:   @df=('chgk','brain','game','ehruditka','beskrylka') unless @df;
  178: 
  179:   my $types=checkbox_group('type',['chgk','brain','game','ehruditka','beskrylka'], [@df],
  180:              'false',\%rusfieldname);
  181:   my $metod=radio_group(-name=>'metod',-values=>['old','rus'],
  182:                        -default=>(param('metod')||'rus'),
  183:                        -labels=>\%rusfieldname);
  184:   my $all=radio_group(-name=>'all',-values=>['yes','no'],
  185:                        -default=>(param('all')||'no'),
  186:                        -labels=>{'yes'=>'Все','no'=>'Любое'});
  187: 
  188: #################################################
  189: return   start_form(-method=>'get',
  190:                        -action=>url,
  191:                        -enctype=>
  192:                 "application/x-www-form-urlencoded"
  193: ).br.
  194: table(Tr
  195: (
  196:   td({-valign=>'TOP'},$inputstring.$submit.p."Метод: $metod".p."Слова: $all"),
  197:   td({-valign=>'TOP'},('&nbsp;'x 8).'Поля:'),
  198:   td({-valign=>'TOP'},$fields), 
  199:   td({-valign=>'TOP'},('&nbsp;'x 1).'Типы:'),
  200:   td({-valign=>'TOP'},$types), td("&nbsp;"x5),
  201:   td({-valign=>'TOP'},$qnumber)
  202: ) 
  203: )
  204:  
  205: #$fields.
  206: #$inputstring.$submit.br.$metod.$all
  207: .endform
  208: .hr
  209: 
  210: }
  211: 
  212: sub proxy
  213: {
  214: #print "time0=".time.br if $debug;
  215:       my ($dbh,$ptext,$allnf)=@_;
  216:       my $text=$$ptext;
  217:       $text=~tr/ёЁ/еЕ/;
  218:       $text=~s/(${RLrl})p(${RLrl})/$1p$2/gom;
  219:       $text=~s/p(${RLrl})/р$1/gom;
  220:       $text=~s/(${RLrl})p/$1р/gom;
  221:       $text=~s/\s+/ /gmo;
  222:       $text=~s/[^йцукенгшщзхъфывапролджэячсмитьбюЙЦУКЕНГШЩЗХЪФЫВАПРОЛДЖЭЯЧСМИТЬБЮQWERTYUIOPASDFGHJKLZXCVBNM0-9]/ /g;
  223:       $text=uc $text;
  224:       my @list= $text=~m/(?:(?:${RLrl})+)|(?:[A-Za-z0-9]+)/gom;
  225:       my (%c, %good,$sstr);
  226:       foreach (@list)
  227:       {
  228:            $c{$_}=count($dbh,$_)||10000;
  229:       }
  230:       my @words=sort {$c{$a}<=> $c{$b}} @list;
  231: 
  232: #      $good{$words[$_]}=1 foreach 0..4;
  233: 
  234:       foreach (@words)
  235:       {
  236:          $good{$_}=1 if $c{$_}<200;
  237:       }
  238: 
  239:       $good{$words[$_]}=0 foreach 16..$#words;
  240: 
  241: #      foreach (@list)
  242: #      {
  243: #        if ($good{$_})
  244: #        {
  245: #           $good{$_}=0;
  246: #           $sstr.=" $_";
  247: #        }
  248: #      }
  249:       $sstr.=" $_" foreach grep {$good{$_}} @list;
  250: print "time05=".time.br if $debug;
  251:       $$ptext=$sstr;
  252:       return russearch($dbh,$sstr,0,$allnf);
  253: }
  254: 
  255: 
  256: sub russearch {
  257:             my ($dbh, $sstr, $all,$allnf)=@_;
  258:             my (@qw,@w,@tasks,$qw,@arr,$nf,$sth,@nf,$w,$where,$e,@where,%good,$i,%where,$from);
  259:             my($number,@good,$t,$task,@rho,$rank,%rank,$r2,$r1,$word,$n,@last,$good,@words,%number,$taskid);
  260:             my ($hi, $lo, $wordnumber,$query,$blob,$field,$sf,$ii);
  261:             my @frequence;
  262:             my (@arr1,@ar,@sf,@arr2);
  263: 	    my %tasks;
  264: 	    my $tasks;
  265: 	    my @verybad;
  266: 	    my %nf;
  267:             my %tasksof;
  268:             my %wordsof;
  269:             my %relevance;
  270:             my @blob;
  271:             my %count;
  272: 
  273: $sstr=~tr/йцукенгшщзхъфывапролджэячсмитьбю/ЙЦУКЕНГШЩЗХЪФЫВАПРОЛДЖЭЯЧСМИТЬБЮ/;
  274:     	    @qw=@w =split (' ', uc $sstr);
  275: 
  276: #-----------
  277:             foreach $i (0..$#w) # заполняем массив @nf начальных форм
  278:                            # $nf[$i] -- ссылка на массив возможных
  279:                            # начальных форм словоформы $i
  280:             {
  281:                 $qw= $dbh->quote (uc $w[$i]);
  282:                 $query="  select distinct w2 from nests
  283:                                 where w1=$qw";
  284: print "$query",br if $printqueries;
  285:                 $sth=$dbh -> prepare($query);
  286: 	        $sth -> execute;
  287: 	        @{$nf[$i]}=();
  288: 	        while (@arr = $sth->fetchrow)
  289: 	        {
  290: 	           push (@{$nf[$i]},$arr[0])
  291: 	        }
  292:                 $sth->finish;
  293:             }
  294: 
  295: 
  296:             my @bad=grep {!@{$nf[$_]}} 0..$#w; # @bad -- номера словоформ,
  297:                                            # которых нет в словаре
  298: 
  299:             if (@bad) #есть неопознанные словоформы
  300:             {
  301:                require  "cw.pl";
  302:                foreach $i(@bad)
  303:                {
  304:                  if (@arr=checkword($dbh,$w[$i]))
  305:                    {push (@{$nf[$i]}, @arr);}
  306:                  else
  307:                    {push (@verybad,$i);}
  308:                }
  309:             }
  310:             return () if ($all && @verybad);
  311: 
  312: 
  313:             my $kvo=0;
  314:             push @$allnf, @{$_} foreach @nf;
  315: 	    print "nf=@$allnf" if $printqueries;
  316: 
  317:             foreach $i (0..$#w) #запросы в базу...
  318:             {
  319:               @arr=@{$nf[$i]} if $nf[$i];
  320:               @arr2=@arr1=@arr;
  321: 
  322: 
  323: 
  324: 
  325:               $_= " word2question.word=".$_. ' ' foreach @arr;
  326:               $_= " nf.id=".$_. ' ' foreach @arr1;
  327: #              @arr=(0) unless @arr;
  328:               $query="select questions from word2question where". (join ' OR ', @arr);
  329: print STDERR "!$query\n",br if $printqueries;
  330: 
  331:     	      $sth=$dbh -> prepare($query);
  332:               $sth->execute;
  333: 
  334:               @blob=();
  335:               while (@arr=$sth->fetchrow)
  336:               {
  337:                 @blob=(@blob,unpack 'C*',$arr[0]);
  338:               }
  339:               $sth->finish;
  340:               $query="select number from nf where ".(join ' OR ', @arr1);
  341: print "$query\n",br if $printqueries;
  342:     	      $sth=$dbh -> prepare($query);
  343:               $sth->execute;
  344: 
  345:               while (@arr=$sth->fetchrow)
  346:               {
  347:                 $frequence[$i]+=$arr[0];
  348:               }
  349:               $sth->finish;
  350: 
  351: 
  352:               if (@blob < 4)
  353:               {
  354:                  $tasksof{$i}=undef;
  355:               } else
  356:               {
  357:                  $kvo++;
  358:                  $ii=0;
  359:                  while ($ii<$#blob)  # создаём хэш %tasksof, ключи которого --
  360:                              # номера искомых словоформ, а значения --
  361:                              # списки вопросов, в которых есть соответствующа
  362:                              # словоформа.
  363:                              # Каждый список в свою очередь также оформлен в
  364:                              # виде хэша, ключи которого -- номера вопросов,
  365:                              # а значения -- списки номеров вхождений. Вот.
  366:                  {
  367:                     ($field,$lo,$hi,$wordnumber)=@blob[$ii..($ii+3)];
  368:                     $ii+=4;
  369:                     my $addnumber=($field >> 4) << 16;
  370:                     $number=(($field >> 4) << 16)+($hi << 8) + $lo;
  371:                     $field=$fieldname{$field & 0xF};
  372:                     if ($searchin{$field})
  373:                     {
  374:                       push @{$tasksof{$i}{$number}}, $wordnumber;
  375:                                       # дополнили в хэше, висящем на
  376:                                       # словоформе $i в %tasksof список
  377:                                       # вхождений $i в вопрос $number.
  378:                       push @{$wordsof{$number}{$i}}, $wordnumber;
  379:                                       # дополнили в хэше, висящем на
  380:                                       # вопросе $number в %wordsof список
  381:                                       # вхождений $i в вопрос $number.
  382: 
  383: 
  384:                     }
  385:                  }  #while ($ii<$#blob)
  386:                }
  387:             }    #foreach $i
  388: 
  389: #print "keys tasksof", join ' ', keys %{$tasksof{0}};
  390: #Ищем пересечение или объединение списков вопросов (значений %tasksof)
  391:        	    foreach $sf (keys %tasksof)
  392:            {
  393:               $count{$_}++ foreach keys %{$tasksof{$sf}};
  394:            }
  395:              @tasks= ($all ? (grep {$count{$_}==$kvo} keys %count) :
  396:                              keys %count) ;
  397: 
  398: 
  399: print "\n\$#tasks=",$#tasks,br if $printqueries;
  400: ############ Сортировка найденных вопросов
  401: 
  402: foreach (keys %wordsof)
  403: {
  404:   $relevance{$_}=&relevance($#w,$wordsof{$_},\@frequence) if $_
  405: }
  406: 
  407: @tasks=sort {$relevance{$b}<=>$relevance{$a}} @tasks;
  408: 
  409: 
  410: ############
  411: 
  412: print "tasks=@tasks" if $printqueries;
  413: 
  414: #print "$_ $relevance{$_} | " foreach @tasks;
  415: #print br;
  416: print "allnf=@$allnf",br if $printqueries;
  417:         return  @tasks;
  418: }
  419: 
  420: 
  421: sub distance  {
  422:                  # на входе -- номера словоформ и ссылки на
  423:                  # списки вхождений. На выходе -- расстояние,
  424:                  # вычисляемое по формуле min(|b-a-pb+pa|)
  425:                  #                       pb,pa
  426:                  # (pb и pa -- позиции слов b и a)
  427:    my ($a,$b,$lista,$listb)=@_;
  428:    my ($pa,$pb,$min,$curmin);
  429:    $min=10000;
  430:    foreach $pa (@$lista)
  431:    {
  432:      foreach $pb (@$listb)
  433:      {
  434:         $curmin=abs($b-$a-$pb+$pa);
  435:         $min= $curmin if $curmin<$min;
  436:      }
  437:    }
  438:    return $min;
  439: 
  440: }
  441: 
  442: sub relevance {
  443:               # На входе -- количество искомых словоформ -1 и
  444:               # ссылка на hash, ключи которого --
  445:               # номера словоформ, а значения -- списки вхождений
  446: 
  447:        my ($n,$words,$frequence)=@_;
  448:        my $relevance=0;
  449:        my ($first,$second,$d);
  450:        foreach $first (0..$n)
  451:        {
  452:          $relevance+=scalar @{$$words{$first}}+1000+1000/$$frequence[$first]
  453: if $$words{$first};
  454:          foreach $second ($first+1..$n)
  455:          {
  456:             $d=&distance($first,$second,$$words{$first},$$words{$second});
  457:             $relevance+=($d>10?0:10-$d)*10;
  458:          }
  459:        }
  460:        return $relevance;
  461: }
  462: 
  463: 
  464: 
  465: # Returns list of QuestionId's, that have the search string in them.
  466: sub Search {
  467: 	my ($dbh, $s,$metod,$all,$allnf) = @_;
  468: 	my $sstr=$$s;
  469: 	my (@arr, @Questions, @fields);
  470: 	my (@sar, $i, $sth,$where,$query);
  471: #	my $ip=$ENV{'REMOTE_ADDR'};
  472: 
  473: #        $ip=$dbh->quote($ip);
  474: #	$query=
  475: #          "INSERT into queries (query,metod,searchin,ip)
  476: #                    values (". $dbh->quote($sstr).', '.
  477: #                    $dbh->quote($metod) . ', ' .
  478: #                    $dbh->quote(join ' ', grep $searchin{$_}, keys %searchin)  . 
  479: #              ", $ip)";
  480: #print $query if $printqueries;
  481: #        $dbh -> do ($query);
  482: 	if ($metod eq 'rus')
  483: 	{
  484: 	     my @tasks=russearch($dbh,$sstr,$all,$allnf);
  485: 	     return @tasks
  486: 	}
  487: 	elsif ($metod eq 'proxy')
  488: 	{
  489: #	  $searchin{'question'}=1;
  490: #	  $searchin{'answer'}=1;
  491: 	  my @task=proxy($dbh,$s,$allnf);
  492: #	  $$s=$sstr;
  493: 	  return @task
  494: 	}
  495: 
  496: 
  497: 
  498: ###Simple and advanced query processing. Added by R7
  499: 	if ($metod eq 'simple' || $metod eq 'advanced')
  500: 	{
  501:           foreach (qw/Question Answer Sources Authors Comments/) {
  502: 		if (param($_)) {
  503: 			push @fields, $_;
  504: 		}
  505: 	   }
  506: 
  507: 	   @fields=(qw/Question Answer Sources Authors Comments/) unless scalar @fields;
  508: 	   my $fields=join ",", @fields;
  509:            my $q=new Text::Query($sstr,
  510:                  -parse => 'Text::Query::'.
  511:                    (($metod eq 'simple') ? 'ParseSimple':'ParseAdvanced'),
  512:                  -solve => 'Text::Query::SolveSQL',
  513:                  -build => 'Text::Query::BuildSQLMySQL',
  514:                  -fields_searched => $fields);
  515: 
  516:            $where=	$$q{'matchexp'};
  517:            $query= "SELECT Questionid FROM Questions
  518:                 WHERE $where";
  519:            print br."Query is: $query".br if $debug;
  520: 
  521:            $sth = $dbh->prepare($query);
  522:          } else
  523: ######
  524:          {
  525: 
  526: #	  foreach (qw/Question Answer Sources Authors Comments/) {
  527: 	  foreach (param('searchin')) {
  528: #		if (param($_)) {
  529: 			push @fields, "IFNULL($_, '')";
  530: #		}
  531: 	  }
  532: 	  @sar = split " ", $sstr;
  533: 	  for $i (0 .. $#sar) {
  534: 		$sar[$i] = $dbh->quote("%${sar[$i]}%");
  535: 	  }
  536: 	  $_.=' ' foreach (@fields); # Это чтобы последнее слово поля
  537: 	                             # не сливалось с первым словом
  538: 	                             # следующего поля, R7
  539: 	  my($f) = "CONCAT(" . join(',', @fields) . ")";
  540: 	  if (param('all') eq 'yes') {
  541: 		$sstr = join " AND $f LIKE ", @sar;
  542: 	  } else {
  543: 		$sstr = join " OR $f LIKE ", @sar;
  544:     	  }
  545:     	  
  546:    my $query;
  547:                $query="SELECT QuestionId FROM Questions
  548: 		WHERE ($f LIKE $sstr) AND (".&makewhere.") ORDER BY QuestionId";
  549: 
  550: 
  551: print $query if $printqueries;
  552: 	  $sth = $dbh->prepare($query)
  553: 	} #else -- processing old-style query (R7)
  554: 
  555: 	$sth->execute;
  556: 	while (@arr = $sth->fetchrow) {
  557: 		push @Questions, $arr[0] unless $forbidden{$arr[0]};
  558: 	}
  559:         $sth->finish;
  560: print "@Questions" if $printqueries;
  561:         
  562: 	return @Questions;
  563: }
  564: 
  565: sub makewhere {
  566:       my @type=param('type');    
  567:       my $type='';
  568: 
  569:       $type .= ($_=$TypeName{$_}) foreach @type;
  570:       my $where=' 0 ';
  571:       foreach (@type) {
  572:  	     $where.= " OR (Type ='$_') OR (Type ='$_Д') ";
  573:       } 
  574:       $where.= "OR (Type='ЧБ')" if ($type=~/Ч|Б/);
  575:       return $where;
  576: }
  577: 
  578:  # Substitute every letter by a pair (for case insensitive search).
  579:  my (@letters) = qw/аА бБ вВ гГ дД еЕ жЖ зЗ иИ йЙ кК лЛ мМ нН оО
  580:  пП рР сС тТ уУ фФ хХ цЦ чЧ шШ щЩ ьЬ ыЫ эЭ юЮ яЯ/;
  581: 
  582: sub NoCase {
  583: 	my ($sstr) = shift;                   	
  584: 	my ($res);
  585: 
  586: 	if (($res) = grep(/$sstr/, @letters)) {
  587: 		return "[$res]";
  588: 	} else {
  589: 		return $sstr;
  590: 	}
  591: }
  592: 
  593: sub PrintList {
  594:    my ($dbh,$Questions,$shablon,$was)=@_;
  595: 
  596: 	my $first=param('first') ||1;
  597: 	my $kvo=param('kvo') ||150;
  598: 
  599: 	$first=$first-($first-1)%$kvo;
  600: 	my $last=$first+$kvo-1;
  601: 	$last=scalar @$Questions if scalar @$Questions <$last;
  602:         my($f,$l);
  603:         my $nav='';
  604:         my $qs=query_string;
  605: 	$qs=~s/\;/\&/g;
  606:         $qs=~s/\&first\=[^\&]+//g;
  607:         my $sstr=param('sstr')||'';
  608:         $qs=~s/sstr=[^\&]+/sstr=$sstr/;
  609:         $qs=~s/\&was=[^\&]+//;
  610:         $qs.="&was=$was"||'';
  611:         if ($first>$kvo*3+1)
  612:         {
  613:            $nav.=
  614:             ("&nbsp;"x4).
  615:             a({href=>url."?".$qs."\&first=1"},"<<").("&nbsp;"x4).
  616:             a({href=>(url."?".$qs."\&first=".($first-$kvo))},"<").("&nbsp;"x4)
  617: 	        }
  618: 
  619:         else {$nav.='&nbsp;'x15;}
  620: 
  621:      my ($fprint,$lprint);
  622:      my $llprint=$#$Questions- ($#$Questions+1)%$kvo+2;
  623:      if ($#$Questions+1<=$kvo*7)
  624:      {         $fprint=1;
  625:                $lprint=$llprint;
  626:      }
  627:      elsif ($first>$kvo*3 && $#$Questions+1-$first>$kvo*3)
  628:      {
  629:        $fprint=$first-$kvo*3;
  630:        $lprint=$first+$kvo*3;
  631:      } 
  632:      elsif  ($first<=$kvo*3)
  633:      {
  634:         $fprint=1; $lprint=6*$kvo+1;
  635:      }
  636:      else
  637:      { 
  638:            $lprint=$llprint;
  639:            $fprint=$lprint-$kvo*6
  640:      }
  641:          
  642: #        my $fprint=($first>$kvo*3) ? $first-$kvo*3 : 1;
  643: #        my $lprint=$#$Questions+1-$fprint>$kvo*7 ? $kvo*7 :$#$Questions+1;
  644: #        if ($lprint-$fprint<$kvo*6 && $fprint>1)
  645: #        {
  646: #            $fprint=$lprint-$kvo*6;
  647: #            $fprint=1 if ($fprint<=0) 
  648: #        }
  649: 
  650: 
  651: 
  652:         for($f=$fprint; $f<=$lprint; $f+=$kvo)
  653: 	{
  654: #	  next if $first-$f>$kvo*3;
  655: 	  $l=$f+$kvo-1;
  656: 	  $l=$#$Questions+1 if $l>$#$Questions+1;
  657: 	  if ($f==$first) {$nav.="[$f-$l] ";}
  658: 	  else {
  659:                   $nav.= "[".a({href=>(url."?".$qs."\&first=$f")},"$f-$l")."] ";}
  660: 	}
  661:         if ($lprint+$kvo<$#$Questions)
  662:         {
  663:            $nav.=
  664:             ("&nbsp;"x4).
  665:             a({href=>(url."?".$qs."\&first=".($first+$kvo))},">").("&nbsp;"x4).
  666:             a({href=>url."?".$qs."\&first=$llprint"},">>").("&nbsp;"x4)
  667:         }
  668: 
  669: 
  670: 	print "$nav".br."\n";
  671: 	for (my $i = $first; $i <= $last; $i++) {
  672: 		my $output = &PrintQuestion($dbh, $$Questions[$i-1], 1, 0, 1);
  673:                 if (param('metod') && (param('metod') eq 'rus' || param('metod') eq 'proxy'))
  674:                 {
  675: 	             $output=~s/\b($shablon)\b/\<strong\>$1\<\/strong\>/gi;
  676: 	        } else {
  677: 	             $output=~s/($shablon)/\<strong\>$1\<\/strong\>/gi;
  678: 		}
  679: 		print $output;
  680: 	}
  681: 
  682: 
  683: 	print "$nav".br."\n";
  684: 
  685: }
  686: 
  687: sub PrintSearch {
  688: 	my ($dbh, $sstr, $metod,$was) = @_;
  689: 	my $t=time;
  690: 	print h2("Поиск в базе вопросов");
  691: 	print printform;
  692: 	my @allnf;
  693: 	my @Questions;
  694: 	if ($was)
  695: 	{
  696: 	  my $sth=$dbh->prepare ("select sstr,questions,allnf from lastqueries where id=".param('was'));
  697:           $sth->execute;
  698:           my ($q,$nf);
  699: 	  ($sstr, $q,$nf)=($sth->fetchrow);
  700:           @Questions=unpack 'L*',$q; 
  701:           @allnf=unpack 'L*',$nf;        
  702:           $sth->finish;
  703:         } else 
  704:         {
  705:              @Questions=&Search($dbh, \$sstr,$metod,$all,\@allnf);
  706:              my $tmp=$dbh->quote(pack("L*",@Questions));
  707:              my $qsstr=$dbh->quote($sstr);
  708:              my $nf=$dbh->quote(pack("L*", @allnf));
  709:              my $ss=200;
  710:              do 
  711:              {
  712:                $was=int rand(32000);
  713:              }
  714:              while (--$ss && (!$dbh->do ("insert into lastqueries (id,sstr,questions,allnf) 
  715:                          values ($was, $qsstr,$tmp,$nf)")));
  716:              print "Something is wrong...".br unless $ss;
  717:         }
  718: 
  719: 
  720: 
  721: 	print p. "Время поиска: " . (time-$t) ." сек.".p;
  722: 	my ($output, $i, $suffix, $hits) = ('', 0, '', $#Questions + 1);
  723: 
  724:         my $shablon;
  725:         $metod='rus' if $metod eq 'proxy';
  726:         if ($metod eq 'rus')
  727:         {
  728:            my $where='0';
  729:            $where.= " or w2=$_ " foreach @allnf;
  730:            my $query="select w1 from nests where $where";
  731:            my $sth=$dbh->prepare($query);
  732: print "$query" if $printqueries;
  733: 
  734: 	   $sth->execute;
  735: 	   my @shablon;
  736: 	   while (my @arr = $sth->fetchrow)
  737: 	   {
  738: 	     push @shablon,"(?:$arr[0])";
  739: 	   }
  740: 	   $sth->finish;
  741:            $shablon= join "|", @shablon;
  742:            $shablon=~s/[её]/\[ЕЁ\]/gi;
  743: #           $shablon=~s/([йцукенгшщзхъфывапролджэячсмитьбюЙЦУКЕНГШЩЗХЪФЫВАПРОЛДЖЭЯЧСМИТЬБЮ])/&NoCase($1)/ge;
  744:            $shablon=qr/$shablon/i;
  745:            print "!$shablon!",br if $printqueries;
  746: 
  747:         }
  748: 
  749: 
  750: 
  751: 	if ($hits =~ /1.$/  || $hits =~ /[5-90]$/) {
  752: 		$suffix = 'й';
  753: 	} elsif ($hits =~ /1$/) {
  754: 		$suffix = 'е';
  755: 	} else {
  756: 		$suffix = 'я';
  757: 	}
  758: 
  759: 	print p({align=>"center"}, "Результаты поиска на " . strong($sstr)
  760: 	. " : $hits попадани$suffix.");
  761: 
  762: 	if (param('word')) {
  763: 		$sstr = '[ 	\.\,:;]' . $sstr . '[  \.\,:\;]';
  764: 	}
  765: 
  766: #	$sstr =~ s/(.)/&NoCase($1)/ge;
  767: 
  768: 	my @sar;
  769: 	if ($metod ne 'rus') 
  770: 	{
  771: 	  my $ss=$sstr;
  772: 	  (@sar) = split(' ', $ss);
  773: 	  s/(\W)/\\$1/g foreach (@sar);
  774: 	  $shablon=join "|",@sar;
  775: 	}
  776: 	PrintList($dbh,\@Questions,$shablon,$was);
  777: }
  778: 
  779: sub PrintRandom {
  780:    my ($dbh, $type, $num, $text) = @_;
  781:    my (@Questions) = &Get12Random($dbh, $type, $num);
  782: 	my ($output, $i) = ('', 0);
  783: 
  784: 	if ($text) {
  785: 		$output .= "	$num случайных вопросов.\n\n";
  786: 	} else {
  787: 		$output .=
  788: 			h2({align=>"center"}, "$num случайных вопросов.");
  789: 	}
  790: 
  791: 	for ($i = 0; $i <= $#Questions; $i++) {
  792: 		# Passing DB handler, question ID, print answer, question
  793: 		# number, print title, print text/html
  794: 		$output .=
  795: 			&PrintQuestion($dbh, $Questions[$i], 1, $i + 1, 0, $text);
  796: 	}
  797: 	return $output;
  798: }
  799: 
  800: sub PrintEditor {
  801:        my $t=shift; #ссылка на Хэш с полями
  802:        my $ed=$$t{'Editors'}||'';
  803:        my $edname=($ed=~/\,/ ) ? "Редакторы"  : "Редактор" ;
  804:        return $ed? h4({align=>"center"},"$edname: $ed" ): '';
  805: }
  806: 
  807: sub PrintTournament {
  808:    my ($dbh, $Id, $answer) = @_;
  809: 	my (%Tournament, @Tours, $i, $list, $qnum, $imgsrc, $alt,
  810: 		$SingleTour);
  811: 	my ($output) = '';
  812: 
  813: 	%Tournament = &GetTournament($dbh, $Id) if ($Id);
  814: 
  815: 	my ($URL) = $Tournament{'URL'};
  816: 	my ($Info) = $Tournament{'Info'};
  817: 	my ($Copyright) = $Tournament{'Copyright'};
  818: 	my $fname=$Tournament{'FileName'};
  819: 	@Tours = &GetTours($dbh, $Id);
  820: 	$list='';
  821: 	my $textid;
  822: 	if ($Id) {
  823: 		for ($Tournament{'Type'}) {
  824: 			/Г/ && do {
  825: 				$output .= h2({align=>"center"},
  826: 					      "Группа: $Tournament{'Title'} ",
  827: 					      $Tournament{'PlayedAt'}||'') . p . "\n";
  828: 				last;
  829: 			};
  830: 			/Ч/ && do {
  831: 				return &PrintTour($dbh, $Tours[0], $answer)
  832: 					if ($#Tours == 0);
  833: 
  834: 				my $title="Пакет: $Tournament{'Title'}";
  835: 				if ($Tournament{'PlayedAt'}) {
  836: 				    $title .= " $Tournament{'PlayedAt'}";
  837: 				}
  838: 
  839: 				$output .= h2({align=>"center"},
  840: 					"$title") . p . "\n";
  841: 			       $output.=&PrintEditor(\%Tournament);
  842: 				last;
  843: 			};
  844: 			/Т/ && do {
  845: 				return &PrintTour($dbh, $Id, $answer);
  846: 			};
  847: 		}
  848: 	} else {
  849: 		my ($qnum) = GetQNum($dbh);
  850: 		$output .= h2("Банк Вопросов: $qnum вопрос".&Suffix($qnum)) 
  851:                           . p . "\n";
  852: 	}
  853: 
  854: 	for ($i = 0; $i <= $#Tours; $i++) {
  855: 		%Tournament = &GetTournament($dbh, $Tours[$i]);
  856: 
  857: 		if ($Tournament{'Type'} =~ /Ч/) {
  858: 			$SingleTour = 0;
  859: 			my (@Tours) = &GetTours($dbh, $Tournament{'Id'});
  860: 			$SingleTour = 1
  861: 				if ($#Tours == 0);
  862: 		}
  863: 		if ($Tournament{'QuestionsNum'} > 0) {
  864: 			$qnum = " ($Tournament{'QuestionsNum'} вопрос" .
  865: 				&Suffix($Tournament{'QuestionsNum'}) . ")\n";
  866: 		} else {
  867: 			$qnum = '';
  868: 		}
  869: 		if ($Tournament{'Type'} =~ /Г/) {
  870: 		    $SingleTour=0;
  871: 			$imgsrc = "/icons/folder.gif";
  872: 			$alt = "[*]";
  873: 		} else {
  874: 			$imgsrc = "/icons/folder.gif";
  875: 			$alt = "[-]";
  876: 		}
  877: 
  878: 		my $textid;
  879: 		if ($textid=$Tournament{'FileName'})
  880: 		{
  881: 		   $textid=~s/\.txt//;
  882: 		}
  883: 		elsif ($textid=$Tournament{'Number'})
  884: 		  {
  885: 		      $fname=~s/\.txt//;
  886: 		      $textid="$fname.$textid";
  887: 		  }
  888: 	       else {$textid=$Tournament{'Id'}};
  889: 		
  890: 
  891: 		if ($SingleTour or $Tournament{'Type'} =~ /Т/) {
  892: 			$list .= dd(img({src=>$imgsrc, alt=>$alt})
  893: 				. " " . $Tournament{'Title'} . " " .
  894: 				    $Tournament{'PlayedAt'} . $qnum) .
  895: 				dl(
  896: 					dd("["
  897: 						. a({href=>url .  "?tour=$textid&answer=0"},
  898: 						"вопросы") . "] ["
  899:                   . a({href=>url .  "?tour=$textid&answer=1"},
  900:                   "вопросы + ответы") . "]")
  901: 				);
  902: 		} else {
  903: 			$list .= dd(a({href=>url . "?tour=$textid&comp=1"},
  904: 				img({src=>'/icons/compressed.gif', alt=>'[ZIP]', border=>1})). " " . 
  905:                                 img({src=>$imgsrc, alt=>$alt})
  906: 				. " " . a({href=>url . "?tour=$textid&answer=0"},
  907: 				$Tournament{'Title'}. " ".
  908: 					  $Tournament{'PlayedAt'}||'') . $qnum);
  909: 		}
  910: 	}
  911: 	$output .= dl($list);
  912: 
  913: 	if ($URL) {
  914: 	        if (url=~/zaba\.ru/ && $URL=~/^\//){$URL="http://info.chgk.info$URL"}
  915: 		$output .=
  916: 		p("Дополнительная информация об этом турнире - по адресу " .
  917: 			a({-'href'=>$URL}, $URL));
  918: 	}
  919: 
  920: 	if ($Copyright) {
  921: 		$output .= p("Копирайт: " .   $Copyright);
  922: 	}
  923: 
  924: 
  925: 
  926: 	if ($Info) {
  927: 		$output .= p($Info);
  928: 	}
  929: 	return $output;
  930: }
  931: 
  932: sub Suffix {
  933: 	my ($qnum) = @_;
  934: 	my ($suffix) = 'а' if $qnum =~ /[234]$/;
  935:    $suffix = '' if $qnum =~ /1$/;
  936:    $suffix = 'ов' if $qnum =~ /[567890]$/ || $qnum =~ /1.$/;
  937: 	return $suffix;
  938: }
  939: 
  940: sub IsTour {
  941: 	my ($dbh, $Id,$n) = @_;
  942: 
  943: 	my ($sth) ;
  944:         
  945:         if (defined $n) 
  946:         { $sth=$dbh->prepare ("select Id FROM Tournaments
  947:                            WHERE ParentId=$Id AND Number=$n");
  948:         }
  949:         else
  950:         {
  951:           $sth=$dbh->prepare("SELECT Id FROM Tournaments
  952: 		WHERE Id=$Id");
  953: 	}
  954: 	$sth->execute;
  955:         my $a=($sth->fetchrow)[0];
  956: 	$sth->finish;
  957:  	return $a;
  958: }
  959: 
  960: # Gets a DB handler (ofcourse) and a tour Id. Prints all the
  961: # question of that tour, according to the options.
  962: sub PrintTour {
  963: 	my ($dbh, $Id, $answer) = @_;
  964: 	my ($output, $q, $bottom, $field) = ('', 0, '', '');
  965: 
  966: 	my (%Tour) = &GetTournament($dbh, $Id);
  967: 	my (@Tours) = &GetTours($dbh, $Tour{'ParentId'});
  968: 	my (%Tournament) = &GetTournament($dbh, $Tour{'ParentId'});
  969: 
  970: 	return 0
  971: 		if ($Tour{'Type'} !~ /Т/);
  972: 
  973: 	my ($fname)=$Tournament{'FileName'};
  974: 	$fname=~s/\.txt//;
  975: 	my ($qnum) = $Tour{'QuestionsNum'};
  976: 	my ($suffix) = &Suffix($qnum);
  977: 
  978: 	$output .= h2({align=>"center"}, $Tournament{"Title"},
  979: 		      $Tournament{'PlayedAt'}||'',
  980: 		      "<br>", $Tour{"Title"} .
  981: 		" ($qnum вопрос$suffix)\n") . p;
  982: 	$output .=&PrintEditor(\%Tour);
  983: 
  984: 	my (@Questions) = &GetTourQuestions($dbh, $Id);
  985: 	for ($q = 0; $q <= $#Questions; $q++) {
  986: 		$output .= &PrintQuestion($dbh, $Questions[$q], $answer, 0);
  987: 	}
  988: 
  989: 	$output .= hr({-'align'=>'center', -'width'=>'80%'});
  990: 
  991: 	if ($Tournament{'URL'}) {
  992: 		$output .=
  993: 		p("Дополнительная информация об этом турнире - по адресу " .
  994: 			a({-'href'=>$Tournament{'URL'}}, $Tournament{'URL'}));
  995: 	}
  996: 
  997: 	if ($Tournament{'Copyright'}) {
  998: 		$output .= p("Копирайт: " .   $Tournament{'Copyright'});
  999: 	}
 1000: 
 1001: 	if ($Tournament{'Info'}) {
 1002: 		$output .= p($Tournament{'Info'});
 1003: 	}
 1004: 
 1005: 	my $n=$Tour{'Number'};
 1006: 	if ($answer == 0) {
 1007: 		$bottom .=
 1008: 			"[" . a({href=>url . "?tour=$fname.$n&answer=1"}, "ответы") .  "] " . br;
 1009: 	}
 1010: 	if ($n>1) {
 1011: 		$bottom .=
 1012: 			"[" . a({href=>url . "?tour=$fname." . ($n - 1) . "&answer=0"},
 1013: 			"предыдущий тур") . "] ";
 1014: 		$bottom .=
 1015: 			"[" . a({href=>url . "?tour=$fname." . ($n - 1) . "&answer=1"},
 1016: 			"предыдущий тур с ответами") . "] " . br;
 1017: 	}
 1018: 	if (&IsTour($dbh, $Tour{'ParentId'}, $n + 1)) {
 1019: 		$bottom .=
 1020: 			"[" . a({href=>url . "?tour=$fname." . ($n + 1) . "&answer=0"},
 1021: 			"следующий тур") . "] ";
 1022: 		$bottom .=
 1023: 			"[" . a({href=>url . "?tour=$fname." . ($n + 1) . "&answer=1"},
 1024: 			"следующий тур с ответами") . "] ";
 1025: 	}
 1026: 
 1027: 	$output .=
 1028: 		p({align=>"center"}, font({size=>-1}, $bottom));
 1029: 
 1030: 	return $output;
 1031: }
 1032: 
 1033: sub PrintField {
 1034: 	my ($header, $value, $text) = @_;
 1035: 	if ($text) {
 1036: 	    $value =~ s/<[\/\w]*?>//sg;
 1037: 	} else {
 1038: 	    $value =~ s/^\s+/<br>&nbsp;&nbsp;&nbsp;&nbsp;/mg;
 1039: 	    $value =~ s/^\|([^\n]*)/<pre>$1<\/pre>/mg;
 1040: 	    $value =~ s/\s+-+\s+/&nbsp;&#0150; /mg;
 1041: #	    $value =~ s/(\s)"/$1&#147;/mg;
 1042: #	    $value =~ s/^"/&#147;/mg;
 1043: #	    $value =~ s/"/&#148;/mg;
 1044: 	}
 1045: 
 1046: 
 1047: 	return $text ? "$header:\n$value\n\n" :
 1048: 		strong("$header: ") . $value . p . "\n";
 1049: }
 1050: 
 1051: # Gets a DB handler (ofcourse) and a question Id. Prints
 1052: # that question, according to the options.
 1053: sub PrintQuestion {
 1054: 	my ($dbh, $Id, $answer, $qnum, $title, $text) = @_;
 1055: 	my ($output, $titles) = ('', '');
 1056: 	my (%Question) = &GetQuestion($dbh, $Id);
 1057: 	$qnum = $Question{'Number'}
 1058: 		if ($qnum == 0);
 1059: 	if (!$text) {
 1060: 		$output .= hr({width=>"50%"});
 1061: 		if ($title) {
 1062: 			my (%Tour) = GetTournament($dbh, $Question{'ParentId'});
 1063: 			my (%Tournament) = GetTournament($dbh, $Tour{'ParentId'});
 1064: 			my $fname=$Tournament{'FileName'};
 1065: 			$fname=~s/\.txt//;
 1066: 			$titles .=
 1067: 				dd(img({src=>"/icons/folder.open.gif"}) . " " .
 1068: 					 a({href=>url . "?tour=$fname"}, $Tournament{'Title'}, $Tournament{'PlayedAt'}||''));
 1069: 			$titles .=
 1070: 				dl(dd(img({src=>"/icons/folder.open.gif"}) . " " .
 1071: 					a({href=>url . "?tour=$fname.$Tour{Number}#$qnum"}, $Tour{'Title'})));
 1072: 		}
 1073: 		$output .= dl(strong($titles));
 1074: 	}
 1075: 
 1076: 
 1077: 	$output.= "<a NAME=\"$qnum\">";
 1078: 
 1079: 	$output .=
 1080: 		&PrintField("Вопрос $qnum", $Question{'Question'}, $text);
 1081: 
 1082: 	if ($answer==1) {
 1083: 		$output .=
 1084: 			&PrintField("Ответ", $Question{'Answer'}, $text);
 1085: 
 1086: 		if ($Question{'Authors'}) {
 1087:                       my $q=$Question{'Authors'};
 1088: ###АВТОРА!!
 1089:  		      my $sth=$dbh->prepare("select Authors.Id,Name, Surname, Nicks from Authors, A2Q
 1090:                                   where Authors.Id=Author And Question=$Id");
 1091:                        $sth->execute;
 1092:                        my ($AuthorId,$Name, $Surname,$other,$Nicks);
 1093: 
 1094:                        while ((($AuthorId,$Name, $Surname,$Nicks)=$sth->fetchrow),$AuthorId)
 1095:                        {
 1096:                          my ($firstletter)=$Name=~m/^./g;
 1097:                           $Name=~s/\./\\\./g;
 1098:                            my $sha="(?:$Name\\s+$Surname)|(?:$Surname\\s+$Name)|(?:$firstletter\\.\\s*$Surname)|(?:$Surname\\s+$firstletter\\.)|(?:$Surname)|(?:$Name)";
 1099:                            if ($Nicks)
 1100:                            {
 1101:                              $Nicks=~s/^\|//;
 1102:                              foreach (split /\|/, $Nicks)
 1103:                              {
 1104:                                s/\s+/ /g;
 1105:                                s/\s+$//;
 1106:                                s/ /\\s+/g;
 1107:                                s/\./\\\./g;
 1108:                                if (s/>$//) {$sha="$sha|(?:$_)"}
 1109:                                else        {$sha="(?:$_)|$sha"}
 1110:                              }
 1111:                            }
 1112:                            $q=~s/($sha)/a({href=>url."?qofauthor=$AuthorId"},$1)/ei;
 1113:                        }
 1114:  
 1115: 			$output .= &PrintField("Автор(ы)", $q, $text);
 1116: 
 1117: 		}
 1118: 
 1119: 		if ($Question{'Sources'}) {
 1120: 			$output .= &PrintField("Источник(и)", $Question{'Sources'}, $text);
 1121: 		}
 1122: 
 1123: 		if ($Question{'Comments'}) {
 1124: 			$output .= &PrintField("Комментарии", $Question{'Comments'}, $text);
 1125: 		}
 1126: 	}
 1127: 	elsif ($answer==2) {
 1128: 	  my $text=$Question{'Answer'};
 1129: 	  $text=~s/\n/<option>/mg;
 1130: 	  $output.="<select><option selected>Ответ:<option>$text</select>";
 1131: 	  $text=$Question{'Comments'}||'';
 1132: 	  if ($text) {
 1133:              $text=~s/\n/<option>/mg;
 1134: 	     $output.="<select><option selected>Комментарий:<option>$text</select>"
 1135: 	  }
 1136: 	} 
 1137: 	elsif ($answer==3) {
 1138:         $output.=  <<EOTT
 1139: 	  <div align=right STYLE="cursor:hand;" OnStart="toggle(document.all.HideShow$qnum);" OnClick="toggle(document.all.HideShow$qnum);">
 1140: 	  <font size=-2 color=red> Показать/убрать ответ</font></div>
 1141: 	  <span style="display:none" id=HideShow$qnum>
 1142: EOTT
 1143:           .&PrintField("Ответ", $Question{'Answer'}, $text);
 1144: 		if ($Question{'Authors'}) {
 1145: 			$output .= &PrintField("Автор(ы)", $Question{'Authors'}, $text);
 1146: 		}
 1147: 		if ($Question{'Sources'}) {
 1148: 			$output .= &PrintField("Источник(и)", $Question{'Sources'}, $text);
 1149: 		}
 1150: 
 1151: 		if ($Question{'Comments'}) {
 1152: 			$output .= &PrintField("Комментарии", $Question{'Comments'}, $text);
 1153: 		}
 1154: 
 1155: 
 1156: $output.="</span>"
 1157: 
 1158: 	}
 1159: 	$output.=br.a({href=> url."?metod=proxy&qid=$Id"}, 'Близкие вопросы').p
 1160:              if $answer;
 1161: 	return $output;
 1162: }
 1163: 
 1164: # Returns the total number of questions currently in the DB.
 1165: sub GetQNum {
 1166: 	my ($dbh) = @_;
 1167: 	my ($sth) = $dbh->prepare("SELECT COUNT(*) FROM Questions");
 1168: 	$sth->execute;
 1169: 	my $tmp=($sth->fetchrow)[0];
 1170:         $sth->finish;
 1171:  	return $tmp;
 1172: }
 1173: sub GetMaxQId {
 1174: 	my ($dbh) = @_;
 1175: 	my ($sth) = $dbh->prepare("SELECT MAX(QuestionId) FROM Questions");
 1176: 	$sth->execute;
 1177: 	my $tmp=($sth->fetchrow)[0];
 1178:         $sth->finish;
 1179:  	return $tmp;
 1180: 
 1181: }
 1182: 
 1183: # Returns Id's of 12 random questions
 1184: sub Get12Random {
 1185:    my ($dbh, $type, $num) = @_;
 1186: 	my ($i, @questions, $q, $t, $sth);
 1187: 	my ($qnum) = &GetMaxQId($dbh);
 1188: 	my (%chosen);
 1189: 	srand;
 1190: 	my $where=0;
 1191: 	my $r=int (rand(10000));
 1192: 
 1193: 	foreach (split '', $type)
 1194:         {
 1195:  	   $where.= " OR (Type ='$_') OR (Type ='$_Д') ";
 1196:  	}
 1197:         $where.= "OR (Type='ЧБ')" if ($type=~/Ч|Б/);
 1198: 
 1199:    $q="select QuestionId, QuestionId/$r-floor(QuestionId/$r) as val 
 1200:        from Questions where $where order by val limit $num";
 1201: # Когда на куличках появится mysql >=3.23 надо заменить на order by rand();
 1202: 
 1203:    $sth=$dbh->prepare($q);
 1204:    $sth->execute;
 1205:    while (($i)=$sth->fetchrow)
 1206:    {
 1207:       push @questions,$i;
 1208:    }
 1209:    $sth->finish;
 1210:     for ($i=@questions; --$i;){ 
 1211:        my $j=rand ($i+1); 
 1212:        @questions[$i,$j]=@questions[$j,$i] unless $i==$j;
 1213:     }
 1214:    return @questions;
 1215: }
 1216: 
 1217: sub Include_virtual {
 1218: 	my ($fn, $output) = (@_, '');
 1219: 
 1220: 	open F , $fn
 1221: 		or return; #die "Can't open the file $fn: $!\n";
 1222: 
 1223: 	while (<F>) {
 1224: 		if (/<!--#include/o) {
 1225: 			s/<!--#include virtual="\/(.*)" -->/&Include_virtual($1)/e;
 1226: 		}
 1227: 		if (/<!--#exec/o) {
 1228: 			s/<!--#exec.*cmd\s*=\s*"([^"]*)".*-->/`$1`/e;
 1229: 		}
 1230: 		$output .= $_;
 1231: 	}
 1232: 	return $output;
 1233: }
 1234: 
 1235: sub PrintArchive {
 1236: 	my($dbh, $Id) = @_;
 1237: 	my ($output, @list, $i);
 1238: 
 1239: 	my (%Tournament) = &GetTournament($dbh, $Id);
 1240: 	my (@Tours) = &GetTours($dbh, $Id);
 1241: 	if ($Tournament{'Type'} =~ /Г/ || $Id == 0) {
 1242: 		for ($i = 0; $i <= $#Tours; $i++) {
 1243: 			push(@list ,&PrintArchive($dbh, $Tours[$i]));
 1244: 		}
 1245: 		return @list;
 1246: 	}
 1247: #	return "$SRCPATH/$Tournament{'FileName'} ";
 1248: 	return "$TMPDIR/$Tournament{'FileName'} ";
 1249: }
 1250: 
 1251: sub PrintAll {
 1252: 	my ($dbh, $Id,$fname) = @_;
 1253: 	my ($output, $list, $i);
 1254: 
 1255: 	my (%Tournament) = &GetTournament($dbh, $Id);
 1256: 	my (@Tours) = &GetTours($dbh, $Id);
 1257: 	my ($New) = ($Id and $Tournament{'Type'} eq 'Ч' and
 1258: 		&NewEnough($Tournament{"CreatedAt"})) ?
 1259: 		img({src=>"/znatoki/dimrub/db/new-sml.gif", alt=>"NEW!"}) : "";
 1260: 
 1261: 	if ($Id == 0) {
 1262: 		$output = h3("Все турниры");
 1263: 	} else {
 1264: 	         my $textid;
 1265: 		 if ($textid=$Tournament{'FileName'})
 1266: 		 {
 1267: 		   $textid=~s/\.txt//;
 1268: 		 }
 1269: 		 elsif ($textid=$Tournament{'Number'})
 1270: 		 {
 1271: 		      $fname=~s/\.txt//;
 1272: 		      $textid="$fname.$textid";
 1273: 		 }
 1274: 	         else {$textid=$Tournament{'Id'}};
 1275: 
 1276: 
 1277: 		$output .= dd(img({src=>"/icons/folder.gif", alt=>"[*]"}) .
 1278:       " " . a({href=>url . "?tour=$textid&answer=0"},
 1279:       $Tournament{'Title'}) ." " . ($Tournament{'PlayedAt'}||'') . " $New");
 1280: 	}
 1281: 	if ($Id == 0 or $Tournament{'Type'} =~ /Г/ or $Tournament{'Type'} eq '') {
 1282: 		for ($i = 0; $i <= $#Tours; $i++) {
 1283: 			$list .= &PrintAll($dbh, $Tours[$i],$Tournament{'FileName'});
 1284: 		}
 1285: 		$output .= dl($list);
 1286: 	}
 1287: 	return $output;
 1288: }
 1289: 
 1290: sub PrintDates {
 1291: 	my ($dbh) = @_;
 1292: 	my ($from) = param('from_year') . "-" . param('from_month') .
 1293: 		"-" .  param('from_day');
 1294: 	my ($to) = param('to_year') . "-" . param('to_month') . "-" .  param('to_day');
 1295: 	$from = $dbh->quote($from);
 1296: 	$to = $dbh->quote($to);
 1297: 	my ($sth) = $dbh->prepare("
 1298: 		SELECT DISTINCT Id
 1299: 		FROM Tournaments
 1300: 		WHERE PlayedAt >= $from AND PlayedAt <= $to
 1301: 		AND Type = 'Ч'
 1302: 	");
 1303: 	$sth->execute;
 1304: 	my (%Tournament, @array, $output, $list);
 1305: 
 1306: 	$output = h3("Список турниров, проходивших между $from и $to.");
 1307: 	while (@array = $sth->fetchrow) {
 1308: 		next
 1309: 			if (!$array[0]);
 1310: 		%Tournament = &GetTournament($dbh, $array[0]);
 1311:       $list .= dd(img({src=>"/icons/folder.gif", alt=>"[*]"}) .
 1312:       " " . a({href=>url . "?tour=$Tournament{'Id'}&answer=0"},
 1313:       $Tournament{'Title'}, $Tournament{'PlayedAt'}||''));
 1314: 	}
 1315:         $sth->finish;
 1316: 	$output .= dl($list);
 1317: 	return $output;
 1318: }
 1319: 
 1320: sub PrintQOfAuthor
 1321: {
 1322: 
 1323:     my ($dbh, $id) = @_;
 1324:    $id=$dbh->quote($id);
 1325:     my $sth =  $dbh->prepare("SELECT  Name, Surname FROM Authors WHERE Id=$id");
 1326:     $sth->execute;
 1327:     my ($name,$surname)=$sth->fetchrow;
 1328: 
 1329:     $sth =  $dbh->prepare("SELECT Question FROM A2Q WHERE Author=$id");
 1330:     $sth->execute;
 1331:     my $q;
 1332:     my @Questions;
 1333:     while (($q)=$sth->fetchrow,$q)
 1334:      {push @Questions,$q unless $forbidden{$q}}
 1335:     $sth->finish;
 1336: 
 1337:     my ($output, $i, $suffix, $hits) = ('', 0, '', $#Questions + 1);
 1338: 
 1339:     if ($hits =~ /1.$/  || $hits =~ /[5-90]$/) {
 1340: 		$suffix = 'й';
 1341: 	} elsif ($hits =~ /1$/) {
 1342: 		$suffix = 'е';
 1343: 	} else {
 1344: 		$suffix = 'я';
 1345: 	}
 1346: 	print h2("Поиск в базе вопросов");
 1347: 	print printform;
 1348: 	print p({align=>"center"}, "Автор ".strong("$name $surname. ")
 1349: 	. " : $hits попадани$suffix.");
 1350: 
 1351: 
 1352: #	for ($i = 0; $i <= $#Questions; $i++) {
 1353: #		$output = &PrintQuestion($dbh, $Questions[$i], 1, $i + 1, 1);
 1354: #		print $output;
 1355: #	}
 1356:         PrintList($dbh,\@Questions,'gdfgdfgdfgdfg');
 1357: }
 1358: 
 1359: 
 1360: sub PrintAuthors
 1361: {
 1362:      my ($dbh,$sort)=@_;
 1363:      my($output,$out1,@array,$sth);
 1364:      if ($sort eq 'surname')
 1365:      {
 1366:         $sth =
 1367:              $dbh->prepare("SELECT Id, Name, Surname, QNumber FROM Authors order by Surname, Name");
 1368:      }
 1369:      elsif($sort eq 'name')
 1370:      {
 1371:         $sth =
 1372:              $dbh->prepare("SELECT Id, Name, Surname, QNumber FROM Authors order by Name, Surname");
 1373:      }
 1374:      else
 1375:      {
 1376:         $sth =
 1377:              $dbh->prepare("SELECT Id, Name, Surname, QNumber FROM Authors Order by QNumber DESC, Surname");
 1378:      }
 1379: 
 1380:      $output.=h2("Авторы вопросов")."\n";
 1381:      $output.="<TABLE>";
 1382: 
 1383: 
 1384:      $sth->execute;
 1385:      $output.=Tr(th[a({href=>url."?authors=name"},"Имя")
 1386: .", ".
 1387: a({href=>url."?authors=surname"},"фамилия")
 1388:      , a({href=>url."?authors=kvo"},"Количество вопросов")]);
 1389: 
 1390:      $out1='';
 1391: 
 1392:      my $ar=$sth->fetchall_arrayref;
 1393: 
 1394:      $sth->finish;
 1395: 
 1396: 
 1397:     foreach my $arr(@$ar)
 1398:      {
 1399: 
 1400:            my ($id,$name,$surname,$kvo)=@$arr;
 1401:            if (!$name || !$surname) {#print "Opanki at $id\n"
 1402:               } else
 1403:            {
 1404:              my $add=Tr(td([a({href=>url."?qofauthor=$id"},"$name $surname"), $kvo]))."\n";
 1405:              print STDERR $add;
 1406:              $output.=$add;
 1407:            }
 1408:      }
 1409:      $output.="</TABLE>";
 1410:      $sth->finish;
 1411:      return $output;
 1412: }
 1413: 
 1414: 
 1415: sub WriteFile {
 1416:   my ($dbh,$fname) = @_;
 1417:   $fname=~s/\s+$//;
 1418:   $fname=~s/^\s+//;
 1419:   $fname=~s/\.txt$//;
 1420:   $fname=~s/.*\/(\w+)/$1/;
 1421: 
 1422:   my $query= "SELECT Id, Title, Copyright, Info, URL, 
 1423:                       Editors, EnteredBy, PlayedAt, CreatedAt 
 1424:                      from Tournaments where FileName=".$dbh->quote("$fname.txt");
 1425:   my $sth=$dbh->prepare($query);
 1426:   my (%Question,%editor,%qnumber,%copyright,%author,%vid,%tourtitle);
 1427:   $sth->execute;
 1428:   my ($Id, $Title, $Copyright, $Info, $URL, 
 1429:    $Editors, $EnteredBy, $PlayedAt, $CreatedAt)=
 1430:       $sth->fetchrow;
 1431:   return -1 unless $Id;
 1432:   open (OUT, ">$TMPDIR/$fname.txt") || print STDERR "Error in $fname.txt\n";
 1433:   print OUT "Чемпионат:\n$Title\n\n";
 1434:   my $date=$PlayedAt||'00-00-00';
 1435:   my ($year,$month,$day)=split /-/, $date;
 1436: #  $month=0,$date=0 if $year && $month==1 && $day==1;
 1437:   my $pdate=sprintf("%02d-%3s-%4d",$day,$months[$month],$year);
 1438: 
 1439:   print OUT "Дата:\n$pdate\n\n" if $date;
 1440: 
 1441:   print OUT "URL:\n$URL\n\n" if $URL;
 1442: 
 1443:   print OUT "Инфо:\n$Info\n\n" if $Info;
 1444: 
 1445:   print OUT "Копирайт:\n$Copyright\n\n" if $Copyright;
 1446: 
 1447:   print OUT "Редактор:\n$Editors\n\n" if $Editors;
 1448: 
 1449: 
 1450:   $query= "SELECT Id, Title, Copyright, Editors from Tournaments where ParentId=$Id order by Id";
 1451:   $sth=$dbh->prepare($query);
 1452:   $sth->execute;
 1453:   my ($tourid,$tourtitle,$cright,$editor,@tours,$vid,$author,$tourauthor);
 1454: 
 1455: 
 1456:   while (($tourid,$tourtitle,$cright,$editor)=$sth->fetchrow,$tourid)
 1457:   {
 1458: #    $text{$tourid}="Тур:\n$tourtitle\n\n";
 1459:     $query= "SELECT * from Questions where ParentId=$tourid order by QuestionId";
 1460:     my $sth1=$dbh->prepare($query);
 1461:     $sth1->execute;
 1462:     push(@tours,$tourid);
 1463:     $tourtitle{$tourid}=$tourtitle;
 1464:     $copyright{$tourid}=$cright;
 1465:     $editor{$tourid}=$editor;
 1466:     $vid='';
 1467:     my $author='';
 1468:     my $eqauthor=1;
 1469:     my $qnumber=0;
 1470:     my @arr;
 1471:     while ( (@arr=$sth1->fetchrow), $arr[0])
 1472:     {
 1473: 	my($i, $name);
 1474: 	$i=0;
 1475: 	$qnumber++;
 1476: 	foreach $name (@{$sth1->{NAME}}) {
 1477: 	        if ($arr[$i]) {
 1478:   	           $arr[$i]=~s/^(.*?)\s*$/$1/;
 1479: 		   $Question{$tourid}[$qnumber]{$name} = $arr[$i];
 1480: 		} else {
 1481:   	            $Question{$tourid}[$qnumber]{$name} = 
 1482:                    ''}
 1483:                 $i++;
 1484: 	}
 1485: 	if ($vid)
 1486:         {
 1487:           if ($vid ne $Question{$tourid}[$qnumber]{'Type'}) {print STDERR "Warning: Different types for Tournament $tourid\n"}
 1488:         } else 
 1489:         {
 1490:             $vid=$Question{$tourid}[$qnumber]{'Type'};
 1491:         } 
 1492: 
 1493: 	if ($author)
 1494:         {
 1495:           if ($author ne $Question{$tourid}[$qnumber]{'Authors'})  
 1496:           {
 1497:              $eqauthor=0;
 1498:           }
 1499:         } else 
 1500:         {
 1501:             $author=$Question{$tourid}[$qnumber]{'Authors'};
 1502:             $eqauthor=0 unless $author;
 1503:         } 
 1504:     }
 1505:     $vid{$tourid}=$vid;
 1506:     $qnumber{$tourid}=$qnumber;
 1507:     $author{$tourid}=$eqauthor ? $author : '';
 1508:   }
 1509: 
 1510: 
 1511:   $vid='';
 1512:   my $eqvid=1;
 1513:   my $eqauthor=1;
 1514:   foreach (@tours)
 1515:   {
 1516:      $vid||=$vid{$_};
 1517:      if ($vid{$_} ne $vid)
 1518:      {
 1519:         $eqvid=0;
 1520:      }
 1521:      $author||=$author{$_};
 1522:      if (!$author{$_} || ($author{$_} ne $author))
 1523:      {
 1524:         $eqauthor=0;
 1525:      }
 1526:   }
 1527:   
 1528:   print OUT "Вид:\n$vid\n\n" if $eqvid;
 1529:   print OUT "Автор:\n$author\n\n" if $eqauthor;
 1530: 
 1531:   foreach my $tour(@tours)
 1532:   {
 1533:      print OUT "Тур:\n$tourtitle{$tour}\n\n";
 1534:      print OUT "Вид:\n$vid{$tour}\n\n" if  !$eqvid;
 1535:      print OUT "Копирайт:\n$copyright{$tour}\n\n" if $copyright{$tour} && ($copyright{$tour} ne $Copyright);
 1536:      print OUT "Редактор:\n$editor{$tour}\n\n" if $editor{$tour} && ($editor{$tour} ne $Editors);
 1537:      $tourauthor=0;
 1538:      if (!$eqauthor && $author{$tour})
 1539:      { 
 1540:        print OUT "Автор:\n$author{$tour}\n\n";
 1541:        $tourauthor=1;
 1542:      }
 1543:      foreach my $q(1..$qnumber{$tour})
 1544:      {
 1545:         print OUT "Вопрос $q:\n".$Question{$tour}[$q]{'Question'}."\n\n";
 1546: 	print OUT  "Ответ:\n".$Question{$tour}[$q]{'Answer'}."\n\n";
 1547: 	print OUT  "Автор:\n".$Question{$tour}[$q]{'Authors'}."\n\n" 
 1548:                if !$tourauthor && !$eqauthor && $Question{$tour}[$q]{'Authors'};
 1549: 	print OUT  "Комментарий:\n".$Question{$tour}[$q]{'Comments'}."\n\n" 
 1550:                if $Question{$tour}[$q]{'Comments'};
 1551: 	print OUT "Источник:\n".$Question{$tour}[$q]{'Sources'}."\n\n" 
 1552:                if $Question{$tour}[$q]{'Sources'};
 1553: 	print OUT "Рейтинг:\n".$Question{$tour}[$q]{'Rating'}."\n\n" 
 1554:                if $Question{$tour}[$q]{'Rating'};
 1555: 
 1556:      }
 1557:   }
 1558: 
 1559:   close OUT;
 1560: 
 1561: 
 1562: 
 1563: }
 1564: 
 1565: 
 1566: MAIN:
 1567: {
 1568: 	setlocale(LC_CTYPE,'russian');
 1569: 	my($i, $tour);
 1570: 	my($text) = (param('text')) ? 1 : 0;
 1571: 
 1572: 	my($dbh) = DBI->connect("DBI:mysql:chgk", "piataev", "")
 1573: 		or do {
 1574: 			print h1("Временные проблемы") . "База данных временно не
 1575: 			работает. Заходите попозже.";
 1576: 			print &Include_virtual("../dimrub/db/reklama.html");
 1577: 		    print end_html;
 1578: 			die "Can't connect to DB chgk\n";
 1579: 		};
 1580: 	if (!param('comp') and !param('sqldump') and !$text) {
 1581: 	   print header;
 1582: 	   print start_html(-"title"=>'Database of the questions',
 1583: 	           -author=>'dimrub@icomverse.com',
 1584: 	           -bgcolor=>'#fff0e0',
 1585: 				  -vlink=>'#800020');
 1586: 		print &Include_virtual("../dimrub/db/reklama.html");
 1587: 	}
 1588: 
 1589: 
 1590: if ($^O =~ /win/i) {
 1591: 	$thislocale = "Russian_Russia.20866";
 1592: } else {
 1593: 	$thislocale = "ru_RU.KOI8-R";
 1594: }
 1595: POSIX::setlocale( &POSIX::LC_ALL, $thislocale );
 1596: 
 1597: if ((uc 'а') ne 'А') {print "Koi8-r locale not installed!\n"};
 1598: 
 1599: 
 1600: 	if ($text) {
 1601: 		print header('text/plain');
 1602: 	}
 1603: 
 1604:         if (param('hideequal')) {
 1605: 	           my ($sth)=  $dbh -> prepare("select first, second FROM equalto");
 1606: 	           $sth -> execute;
 1607: 	           while ( my  ($first, $second)=$sth -> fetchrow)
 1608:                   {
 1609:                        $forbidden{$first}=1;
 1610:                   }
 1611:                   $sth->finish;
 1612:         }
 1613: 		$tour = (param('tour')) ? param('tour') : 0;
 1614: 		my $sth;
 1615: 		if ($tour !~ /^[0-9]*$/) {
 1616: 		    if ($tour=~/\./)
 1617: 		    {
 1618: 		        my ($fname,$n)= split /\./ , $tour;
 1619: 
 1620: 	                $sth = $dbh->prepare(
 1621:                        "SELECT t2.Id FROM Tournaments as t1, 
 1622:                         Tournaments as t2 
 1623: 			WHERE t1.FileName = '$fname.txt'
 1624:                         AND t1.Id=t2.ParentId AND t2.Number=$n");
 1625: 		    }	
 1626: 		    else 
 1627: 		        {
 1628:                           $sth = $dbh->prepare("SELECT Id FROM Tournaments
 1629: 			             WHERE FileName = '$tour.txt'");
 1630: 			}
 1631: 		    $sth->execute;
 1632: 	            $tour = ($sth->fetchrow)[0];
 1633:                     $sth->finish;
 1634: 		}
 1635: 
 1636: 
 1637: 	if (param('rand')) {
 1638: 		my ($type, $qnum) = ('', 12);
 1639: 		$type.=$TypeName{$_} foreach param('type');
 1640: #		$type .= 'Б' if (param('brain'));
 1641: #		$type .= 'Ч' if (param('chgk'));
 1642: 		$qnum = param('qnum') if (param('qnum') =~ /^\d+$/);
 1643: 		$qnum = 0 if (!$type);
 1644: 		my $Email;
 1645: 		if (($Email=param('email')) && -x $SENDMAIL &&
 1646: 		open(F, "| $SENDMAIL $Email")) {
 1647: 			my ($mime_type) = $text ? "plain" : "html";
 1648: 			print F <<EOT;
 1649: To: $Email
 1650: From: olegstepanov\@mail.ru
 1651: Subject: Sluchajnij Paket Voprosov "Chto? Gde? Kogda?"
 1652: MIME-Version: 1.0
 1653: Content-type: text/$mime_type; charset="koi8-r"
 1654: 
 1655: EOT
 1656: 			print F &PrintRandom($dbh, $type, $qnum, $text);
 1657: 			close F;
 1658: 			print "Пакет случайно выбранных вопросов послан по адресу $Email. Нажмите
 1659: 			на <B>Reload</B> для получения еще одного пакета";
 1660: 		} else {
 1661: 			print &PrintRandom($dbh, $type, $qnum, $text);
 1662: 		}
 1663: 	}
 1664: 	  elsif (param('authors')){
 1665:                 print &PrintAuthors($dbh,param('authors'));
 1666:         }
 1667:           elsif (param('qofauthor')){
 1668:                 &PrintQOfAuthor($dbh,param('qofauthor'));
 1669:         }
 1670:           elsif (param('sstr')||param('was')) {
 1671: 		&PrintSearch($dbh, param('sstr'), param('metod'),param('was'));
 1672: 		$dbh->do("delete from lastqueries where
 1673:                       (TO_DAYS(NOW()) - TO_DAYS(t) >= 2) OR
 1674: 		           (time_to_sec(now())-time_to_sec(t) >3600)")
 1675: 	} 
 1676: 	  elsif (param('qid')) {
 1677: 	      my $qid=param('qid');
 1678:               my $query="SELECT Question, Answer from Questions where QuestionId=$qid";
 1679: print $query if $printqueries;
 1680: 	      my $sth=$dbh->prepare($query);
 1681: 	      $sth->execute;
 1682: 	      my $sstr= join ' ',$sth->fetchrow;
 1683:               $sth->finish;
 1684: 	      $searchin{'Question'}=1;
 1685: 	      $searchin{'Answer'}=1;
 1686:       $sstr=~tr/ёЁ/еЕ/;
 1687: $sstr=~s/[^йцукенгшщзхъфывапролджэячсмитьбюЙЦУКЕНГШЩЗХЪФЫВАПРОЛДЖЭЯЧСМИТЬБЮa-zA-Z0-9]/ /gi;
 1688: #              print &PrintQuestion($dbh,$qid, 1, '!');
 1689:  	      &PrintSearch($dbh, $sstr, 'proxy');
 1690:  	}
 1691:  	elsif (param('getfile')){
 1692:           print &writefile
 1693:  	} elsif (param('all')) {
 1694: 		print &PrintAll($dbh, 0);
 1695: 	} elsif (param('from_year') && param('to_year')) {
 1696: 		print &PrintDates($dbh);
 1697: 	} elsif (param('comp')) {
 1698:             print "Content-Type: application/octet-stream\n";
 1699:             print "Content-Type: application/force-download\n";
 1700:             print "Content-Type: application/download\n";
 1701:             print "Content-Type: application/x-zip-compressed; name=db.zip\n";
 1702:             print "Content-Disposition: attachment; filename=db.zip \n\n";
 1703: #	    print header(
 1704: #			 -'Content-Type' => 'application/x-zip-compressed; name="db.zip"',
 1705: #			 -'Content-Type' => 'application/zip',
 1706: #			 -'Content-Disposition' => 'attachment; filename="db.zip"'
 1707: #			 );
 1708: 	    $tour ||= 0;
 1709: 	    my (@files) = &PrintArchive($dbh, $tour);
 1710: 	    WriteFile($dbh,$_) foreach @files;
 1711: #	    open F, "$ZIP -j - $SRCPATH/COPYRIGHT @files |";
 1712: 	    open F, "$ZIP -j - @files |";
 1713: 	    binmode(F);
 1714: 	    binmode(STDOUT);
 1715: 	    print (<F>);
 1716: 	    close F;
 1717: 	    $dbh->disconnect;
 1718: 	    exit;
 1719: 	} elsif (param('sqldump')) {
 1720: 	    print header(
 1721: 			 -'Content-Type' => 'application/x-zip-compressed; name="dump.zip"',
 1722: 			 -'Content-Disposition' => 'attachment; filename="dump.zip"'
 1723: 			 );
 1724: 	    open F, "$ZIP -j - $DUMPFILE |";
 1725: 	    print (<F>);
 1726: 	    close F;
 1727: 	    $dbh->disconnect;
 1728: 	    exit;
 1729: 
 1730: 	} else {
 1731: 		my $QuestionNumber=0;
 1732: 		my $qnum;
 1733: 		if ($qnum=param('qnumber')){
 1734:       	          my ($sth) = $dbh->prepare("SELECT QuestionId FROM Questions
 1735: 		     WHERE ParentId=$tour AND Number=$qnum");
 1736: 		  $sth->execute;
 1737: 		  $QuestionNumber=($sth->fetchrow)[0]||0;
 1738: 	        }
 1739: 	        if ($QuestionNumber) {
 1740: 		  print &PrintQuestion($dbh, $QuestionNumber, param('answer')||0, $qnum, 1);
 1741: #                                        $dbh, $Id, $answer, $qnum, $title, $text
 1742: 		} else  {
 1743:   		   print &PrintTournament($dbh, $tour, param('answer'));
 1744:   		}
 1745: 	}
 1746: 	if (!$text) {
 1747: 		print &Include_virtual("../dimrub/db/footer.html");
 1748: print <<EEE
 1749:   <SCRIPT LANGUAGE="JavaScript">
 1750: function toggle(e) {
 1751:   if (e.style.display == "none") {
 1752:      e.style.display="";
 1753:   } else {
 1754:      e.style.display = "none";
 1755:  }
 1756: }
 1757: </SCRIPT>
 1758: EEE
 1759: ;
 1760: 		print end_html;
 1761: 	}
 1762: 	$dbh->disconnect;
 1763: }

FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>