File:  [Local Repository] / db / prgsrc / db.cgi
Revision 1.72: download - view: text, annotated - select for diffs - revision graph
Sun Aug 4 11:25:10 2002 UTC (21 years, 9 months ago) by roma7
Branches: MAIN
CVS tags: HEAD
Zip & Types

    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: 
  537: 	  my($f) = "CONCAT(" . join(',', @fields) . ")";
  538: 	  if (param('all') eq 'yes') {
  539: 		$sstr = join " AND $f LIKE ", @sar;
  540: 	  } else {
  541: 		$sstr = join " OR $f LIKE ", @sar;
  542:     	  }
  543:     	  
  544:    my $query;
  545:                $query="SELECT QuestionId FROM Questions
  546: 		WHERE ($f LIKE $sstr) AND (".&makewhere.") ORDER BY QuestionId";
  547: 
  548: 
  549: print $query if $printqueries;
  550: 	  $sth = $dbh->prepare($query)
  551: 	} #else -- processing old-style query (R7)
  552: 
  553: 	$sth->execute;
  554: 	while (@arr = $sth->fetchrow) {
  555: 		push @Questions, $arr[0] unless $forbidden{$arr[0]};
  556: 	}
  557:         $sth->finish;
  558: print "@Questions" if $printqueries;
  559:         
  560: 	return @Questions;
  561: }
  562: 
  563: sub makewhere {
  564:       my @type=param('type');    
  565:       my $type='';
  566: 
  567:       $type .= ($_=$TypeName{$_}) foreach @type;
  568:       my $where=' 0 ';
  569:       foreach (@type) {
  570:  	     $where.= " OR (Type ='$_') OR (Type ='$_Д') ";
  571:       } 
  572:       $where.= "OR (Type='ЧБ')" if ($type=~/Ч|Б/);
  573:       return $where;
  574: }
  575: 
  576:  # Substitute every letter by a pair (for case insensitive search).
  577:  my (@letters) = qw/аА бБ вВ гГ дД еЕ жЖ зЗ иИ йЙ кК лЛ мМ нН оО
  578:  пП рР сС тТ уУ фФ хХ цЦ чЧ шШ щЩ ьЬ ыЫ эЭ юЮ яЯ/;
  579: 
  580: sub NoCase {
  581: 	my ($sstr) = shift;                   	
  582: 	my ($res);
  583: 
  584: 	if (($res) = grep(/$sstr/, @letters)) {
  585: 		return "[$res]";
  586: 	} else {
  587: 		return $sstr;
  588: 	}
  589: }
  590: 
  591: sub PrintList {
  592:    my ($dbh,$Questions,$shablon,$was)=@_;
  593: 
  594: 	my $first=param('first') ||1;
  595: 	my $kvo=param('kvo') ||150;
  596: 
  597: 	$first=$first-($first-1)%$kvo;
  598: 	my $last=$first+$kvo-1;
  599: 	$last=scalar @$Questions if scalar @$Questions <$last;
  600:         my($f,$l);
  601:         my $nav='';
  602:         my $qs=query_string;
  603: 	$qs=~s/\;/\&/g;
  604:         $qs=~s/\&first\=[^\&]+//g;
  605:         my $sstr=param('sstr')||'';
  606:         $qs=~s/sstr=[^\&]+/sstr=$sstr/;
  607:         $qs=~s/\&was=[^\&]+//;
  608:         $qs.="&was=$was"||'';
  609:         if ($first>$kvo*3+1)
  610:         {
  611:            $nav.=
  612:             ("&nbsp;"x4).
  613:             a({href=>url."?".$qs."\&first=1"},"<<").("&nbsp;"x4).
  614:             a({href=>(url."?".$qs."\&first=".($first-$kvo))},"<").("&nbsp;"x4)
  615: 	        }
  616: 
  617:         else {$nav.='&nbsp;'x15;}
  618: 
  619:      my ($fprint,$lprint);
  620:      my $llprint=$#$Questions- ($#$Questions+1)%$kvo+2;
  621:      if ($#$Questions+1<=$kvo*7)
  622:      {         $fprint=1;
  623:                $lprint=$llprint;
  624:      }
  625:      elsif ($first>$kvo*3 && $#$Questions+1-$first>$kvo*3)
  626:      {
  627:        $fprint=$first-$kvo*3;
  628:        $lprint=$first+$kvo*3;
  629:      } 
  630:      elsif  ($first<=$kvo*3)
  631:      {
  632:         $fprint=1; $lprint=6*$kvo+1;
  633:      }
  634:      else
  635:      { 
  636:            $lprint=$llprint;
  637:            $fprint=$lprint-$kvo*6
  638:      }
  639:          
  640: #        my $fprint=($first>$kvo*3) ? $first-$kvo*3 : 1;
  641: #        my $lprint=$#$Questions+1-$fprint>$kvo*7 ? $kvo*7 :$#$Questions+1;
  642: #        if ($lprint-$fprint<$kvo*6 && $fprint>1)
  643: #        {
  644: #            $fprint=$lprint-$kvo*6;
  645: #            $fprint=1 if ($fprint<=0) 
  646: #        }
  647: 
  648: 
  649: 
  650:         for($f=$fprint; $f<=$lprint; $f+=$kvo)
  651: 	{
  652: #	  next if $first-$f>$kvo*3;
  653: 	  $l=$f+$kvo-1;
  654: 	  $l=$#$Questions+1 if $l>$#$Questions+1;
  655: 	  if ($f==$first) {$nav.="[$f-$l] ";}
  656: 	  else {
  657:                   $nav.= "[".a({href=>(url."?".$qs."\&first=$f")},"$f-$l")."] ";}
  658: 	}
  659:         if ($lprint+$kvo<$#$Questions)
  660:         {
  661:            $nav.=
  662:             ("&nbsp;"x4).
  663:             a({href=>(url."?".$qs."\&first=".($first+$kvo))},">").("&nbsp;"x4).
  664:             a({href=>url."?".$qs."\&first=$llprint"},">>").("&nbsp;"x4)
  665:         }
  666: 
  667: 
  668: 	print "$nav".br."\n";
  669: 	for (my $i = $first; $i <= $last; $i++) {
  670: 		my $output = &PrintQuestion($dbh, $$Questions[$i-1], 1, 0, 1);
  671:                 if (param('metod') && (param('metod') eq 'rus' || param('metod') eq 'proxy'))
  672:                 {
  673: 	             $output=~s/\b($shablon)\b/\<strong\>$1\<\/strong\>/gi;
  674: 	        } else {
  675: 	             $output=~s/($shablon)/\<strong\>$1\<\/strong\>/gi;
  676: 		}
  677: 		print $output;
  678: 	}
  679: 
  680: 
  681: 	print "$nav".br."\n";
  682: 
  683: }
  684: 
  685: sub PrintSearch {
  686: 	my ($dbh, $sstr, $metod,$was) = @_;
  687: 	my $t=time;
  688: 	print h2("Поиск в базе вопросов");
  689: 	print printform;
  690: 	my @allnf;
  691: 	my @Questions;
  692: 	if ($was)
  693: 	{
  694: 	  my $sth=$dbh->prepare ("select sstr,questions,allnf from lastqueries where id=".param('was'));
  695:           $sth->execute;
  696:           my ($q,$nf);
  697: 	  ($sstr, $q,$nf)=($sth->fetchrow);
  698:           @Questions=unpack 'L*',$q; 
  699:           @allnf=unpack 'L*',$nf;        
  700:           $sth->finish;
  701:         } else 
  702:         {
  703:              @Questions=&Search($dbh, \$sstr,$metod,$all,\@allnf);
  704:              my $tmp=$dbh->quote(pack("L*",@Questions));
  705:              my $qsstr=$dbh->quote($sstr);
  706:              my $nf=$dbh->quote(pack("L*", @allnf));
  707:              my $ss=200;
  708:              do 
  709:              {
  710:                $was=int rand(32000);
  711:              }
  712:              while (--$ss && (!$dbh->do ("insert into lastqueries (id,sstr,questions,allnf) 
  713:                          values ($was, $qsstr,$tmp,$nf)")));
  714:              print "Something is wrong...".br unless $ss;
  715:         }
  716: 
  717: 
  718: 
  719: 	print p. "Время поиска: " . (time-$t) ." сек.".p;
  720: 	my ($output, $i, $suffix, $hits) = ('', 0, '', $#Questions + 1);
  721: 
  722:         my $shablon;
  723:         $metod='rus' if $metod eq 'proxy';
  724:         if ($metod eq 'rus')
  725:         {
  726:            my $where='0';
  727:            $where.= " or w2=$_ " foreach @allnf;
  728:            my $query="select w1 from nests where $where";
  729:            my $sth=$dbh->prepare($query);
  730: print "$query" if $printqueries;
  731: 
  732: 	   $sth->execute;
  733: 	   my @shablon;
  734: 	   while (my @arr = $sth->fetchrow)
  735: 	   {
  736: 	     push @shablon,"(?:$arr[0])";
  737: 	   }
  738: 	   $sth->finish;
  739:            $shablon= join "|", @shablon;
  740:            $shablon=~s/[её]/\[ЕЁ\]/gi;
  741: #           $shablon=~s/([йцукенгшщзхъфывапролджэячсмитьбюЙЦУКЕНГШЩЗХЪФЫВАПРОЛДЖЭЯЧСМИТЬБЮ])/&NoCase($1)/ge;
  742:            $shablon=qr/$shablon/i;
  743:            print "!$shablon!",br if $printqueries;
  744: 
  745:         }
  746: 
  747: 
  748: 
  749: 	if ($hits =~ /1.$/  || $hits =~ /[5-90]$/) {
  750: 		$suffix = 'й';
  751: 	} elsif ($hits =~ /1$/) {
  752: 		$suffix = 'е';
  753: 	} else {
  754: 		$suffix = 'я';
  755: 	}
  756: 
  757: 	print p({align=>"center"}, "Результаты поиска на " . strong($sstr)
  758: 	. " : $hits попадани$suffix.");
  759: 
  760: 	if (param('word')) {
  761: 		$sstr = '[ 	\.\,:;]' . $sstr . '[  \.\,:\;]';
  762: 	}
  763: 
  764: 	$sstr =~ s/(.)/&NoCase($1)/ge;
  765: 
  766: 	my @sar;
  767: 	if ($metod ne 'rus') 
  768: 	{
  769: 	  (@sar) = split(' ', $sstr);
  770: 	  $shablon=join "|",@sar;
  771: 	}
  772: 	PrintList($dbh,\@Questions,$shablon,$was);
  773: }
  774: 
  775: sub PrintRandom {
  776:    my ($dbh, $type, $num, $text) = @_;
  777:    my (@Questions) = &Get12Random($dbh, $type, $num);
  778: 	my ($output, $i) = ('', 0);
  779: 
  780: 	if ($text) {
  781: 		$output .= "	$num случайных вопросов.\n\n";
  782: 	} else {
  783: 		$output .=
  784: 			h2({align=>"center"}, "$num случайных вопросов.");
  785: 	}
  786: 
  787: 	for ($i = 0; $i <= $#Questions; $i++) {
  788: 		# Passing DB handler, question ID, print answer, question
  789: 		# number, print title, print text/html
  790: 		$output .=
  791: 			&PrintQuestion($dbh, $Questions[$i], 1, $i + 1, 0, $text);
  792: 	}
  793: 	return $output;
  794: }
  795: 
  796: sub PrintEditor {
  797:        my $t=shift; #ссылка на Хэш с полями
  798:        my $ed=$$t{'Editors'}||'';
  799:        my $edname=($ed=~/\,/ ) ? "Редакторы"  : "Редактор" ;
  800:        return $ed? h4({align=>"center"},"$edname: $ed" ): '';
  801: }
  802: 
  803: sub PrintTournament {
  804:    my ($dbh, $Id, $answer) = @_;
  805: 	my (%Tournament, @Tours, $i, $list, $qnum, $imgsrc, $alt,
  806: 		$SingleTour);
  807: 	my ($output) = '';
  808: 
  809: 	%Tournament = &GetTournament($dbh, $Id) if ($Id);
  810: 
  811: 	my ($URL) = $Tournament{'URL'};
  812: 	my ($Info) = $Tournament{'Info'};
  813: 	my ($Copyright) = $Tournament{'Copyright'};
  814: 	my $fname=$Tournament{'FileName'};
  815: 	@Tours = &GetTours($dbh, $Id);
  816: 	$list='';
  817: 	my $textid;
  818: 	if ($Id) {
  819: 		for ($Tournament{'Type'}) {
  820: 			/Г/ && do {
  821: 				$output .= h2({align=>"center"},
  822: 					      "Группа: $Tournament{'Title'} ",
  823: 					      "$Tournament{'PlayedAt'}") . p . "\n";
  824: 				last;
  825: 			};
  826: 			/Ч/ && do {
  827: 				return &PrintTour($dbh, $Tours[0], $answer)
  828: 					if ($#Tours == 0);
  829: 
  830: 				my $title="Пакет: $Tournament{'Title'}";
  831: 				if ($Tournament{'PlayedAt'}) {
  832: 				    $title .= " $Tournament{'PlayedAt'}";
  833: 				}
  834: 
  835: 				$output .= h2({align=>"center"},
  836: 					"$title") . p . "\n";
  837: 			       $output.=&PrintEditor(\%Tournament);
  838: 				last;
  839: 			};
  840: 			/Т/ && do {
  841: 				return &PrintTour($dbh, $Id, $answer);
  842: 			};
  843: 		}
  844: 	} else {
  845: 		my ($qnum) = GetQNum($dbh);
  846: 		$output .= h2("Банк Вопросов: $qnum вопрос".&Suffix($qnum)) 
  847:                           . p . "\n";
  848: 	}
  849: 
  850: 	for ($i = 0; $i <= $#Tours; $i++) {
  851: 		%Tournament = &GetTournament($dbh, $Tours[$i]);
  852: 
  853: 		if ($Tournament{'Type'} =~ /Ч/) {
  854: 			$SingleTour = 0;
  855: 			my (@Tours) = &GetTours($dbh, $Tournament{'Id'});
  856: 			$SingleTour = 1
  857: 				if ($#Tours == 0);
  858: 		}
  859: 		if ($Tournament{'QuestionsNum'} > 0) {
  860: 			$qnum = " ($Tournament{'QuestionsNum'} вопрос" .
  861: 				&Suffix($Tournament{'QuestionsNum'}) . ")\n";
  862: 		} else {
  863: 			$qnum = '';
  864: 		}
  865: 		if ($Tournament{'Type'} =~ /Г/) {
  866: 		    $SingleTour=0;
  867: 			$imgsrc = "/icons/folder.gif";
  868: 			$alt = "[*]";
  869: 		} else {
  870: 			$imgsrc = "/icons/folder.gif";
  871: 			$alt = "[-]";
  872: 		}
  873: 
  874: 		my $textid;
  875: 		if ($textid=$Tournament{'FileName'})
  876: 		{
  877: 		   $textid=~s/\.txt//;
  878: 		}
  879: 		elsif ($textid=$Tournament{'Number'})
  880: 		  {
  881: 		      $fname=~s/\.txt//;
  882: 		      $textid="$fname.$textid";
  883: 		  }
  884: 	       else {$textid=$Tournament{'Id'}};
  885: 		
  886: 
  887: 		if ($SingleTour or $Tournament{'Type'} =~ /Т/) {
  888: 			$list .= dd(img({src=>$imgsrc, alt=>$alt})
  889: 				. " " . $Tournament{'Title'} . " " .
  890: 				    $Tournament{'PlayedAt'} . $qnum) .
  891: 				dl(
  892: 					dd("["
  893: 						. a({href=>url .  "?tour=$textid&answer=0"},
  894: 						"вопросы") . "] ["
  895:                   . a({href=>url .  "?tour=$textid&answer=1"},
  896:                   "вопросы + ответы") . "]")
  897: 				);
  898: 		} else {
  899: 			$list .= dd(a({href=>url . "?tour=$textid&comp=1"},
  900: 				img({src=>'/icons/compressed.gif', alt=>'[ZIP]', border=>1})). " " . 
  901:                                 img({src=>$imgsrc, alt=>$alt})
  902: 				. " " . a({href=>url . "?tour=$textid&answer=0"},
  903: 				$Tournament{'Title'}. " ".
  904: 					  $Tournament{'PlayedAt'}) . $qnum);
  905: 		}
  906: 	}
  907: 	$output .= dl($list);
  908: 
  909: 	if ($URL) {
  910: 	        if (url=~/zaba\.ru/ && $URL=~/^\//){$URL="http://info.chgk.info$URL"}
  911: 		$output .=
  912: 		p("Дополнительная информация об этом турнире - по адресу " .
  913: 			a({-'href'=>$URL}, $URL));
  914: 	}
  915: 
  916: 	if ($Copyright) {
  917: 		$output .= p("Копирайт: " .   $Copyright);
  918: 	}
  919: 
  920: 
  921: 
  922: 	if ($Info) {
  923: 		$output .= p($Info);
  924: 	}
  925: 	return $output;
  926: }
  927: 
  928: sub Suffix {
  929: 	my ($qnum) = @_;
  930: 	my ($suffix) = 'а' if $qnum =~ /[234]$/;
  931:    $suffix = '' if $qnum =~ /1$/;
  932:    $suffix = 'ов' if $qnum =~ /[567890]$/ || $qnum =~ /1.$/;
  933: 	return $suffix;
  934: }
  935: 
  936: sub IsTour {
  937: 	my ($dbh, $Id,$n) = @_;
  938: 
  939: 	my ($sth) ;
  940:         
  941:         if (defined $n) 
  942:         { $sth=$dbh->prepare ("select Id FROM Tournaments
  943:                            WHERE ParentId=$Id AND Number=$n");
  944:         }
  945:         else
  946:         {
  947:           $sth=$dbh->prepare("SELECT Id FROM Tournaments
  948: 		WHERE Id=$Id");
  949: 	}
  950: 	$sth->execute;
  951:         my $a=($sth->fetchrow)[0];
  952: 	$sth->finish;
  953:  	return $a;
  954: }
  955: 
  956: # Gets a DB handler (ofcourse) and a tour Id. Prints all the
  957: # question of that tour, according to the options.
  958: sub PrintTour {
  959: 	my ($dbh, $Id, $answer) = @_;
  960: 	my ($output, $q, $bottom, $field) = ('', 0, '', '');
  961: 
  962: 	my (%Tour) = &GetTournament($dbh, $Id);
  963: 	my (@Tours) = &GetTours($dbh, $Tour{'ParentId'});
  964: 	my (%Tournament) = &GetTournament($dbh, $Tour{'ParentId'});
  965: 
  966: 	return 0
  967: 		if ($Tour{'Type'} !~ /Т/);
  968: 
  969: 	my ($fname)=$Tournament{'FileName'};
  970: 	$fname=~s/\.txt//;
  971: 	my ($qnum) = $Tour{'QuestionsNum'};
  972: 	my ($suffix) = &Suffix($qnum);
  973: 
  974: 	$output .= h2({align=>"center"}, $Tournament{"Title"},
  975: 		      $Tournament{'PlayedAt'},
  976: 		      "<br>", $Tour{"Title"} .
  977: 		" ($qnum вопрос$suffix)\n") . p;
  978: 	$output .=&PrintEditor(\%Tour);
  979: 
  980: 	my (@Questions) = &GetTourQuestions($dbh, $Id);
  981: 	for ($q = 0; $q <= $#Questions; $q++) {
  982: 		$output .= &PrintQuestion($dbh, $Questions[$q], $answer, 0);
  983: 	}
  984: 
  985: 	$output .= hr({-'align'=>'center', -'width'=>'80%'});
  986: 
  987: 	if ($Tournament{'URL'}) {
  988: 		$output .=
  989: 		p("Дополнительная информация об этом турнире - по адресу " .
  990: 			a({-'href'=>$Tournament{'URL'}}, $Tournament{'URL'}));
  991: 	}
  992: 
  993: 	if ($Tournament{'Copyright'}) {
  994: 		$output .= p("Копирайт: " .   $Tournament{'Copyright'});
  995: 	}
  996: 
  997: 	if ($Tournament{'Info'}) {
  998: 		$output .= p($Tournament{'Info'});
  999: 	}
 1000: 
 1001: 	my $n=$Tour{'Number'};
 1002: 	if ($answer == 0) {
 1003: 		$bottom .=
 1004: 			"[" . a({href=>url . "?tour=$fname.$n&answer=1"}, "ответы") .  "] " . br;
 1005: 	}
 1006: 	if ($n>1) {
 1007: 		$bottom .=
 1008: 			"[" . a({href=>url . "?tour=$fname." . ($n - 1) . "&answer=0"},
 1009: 			"предыдущий тур") . "] ";
 1010: 		$bottom .=
 1011: 			"[" . a({href=>url . "?tour=$fname." . ($n - 1) . "&answer=1"},
 1012: 			"предыдущий тур с ответами") . "] " . br;
 1013: 	}
 1014: 	if (&IsTour($dbh, $Tour{'ParentId'}, $n + 1)) {
 1015: 		$bottom .=
 1016: 			"[" . a({href=>url . "?tour=$fname." . ($n + 1) . "&answer=0"},
 1017: 			"следующий тур") . "] ";
 1018: 		$bottom .=
 1019: 			"[" . a({href=>url . "?tour=$fname." . ($n + 1) . "&answer=1"},
 1020: 			"следующий тур с ответами") . "] ";
 1021: 	}
 1022: 
 1023: 	$output .=
 1024: 		p({align=>"center"}, font({size=>-1}, $bottom));
 1025: 
 1026: 	return $output;
 1027: }
 1028: 
 1029: sub PrintField {
 1030: 	my ($header, $value, $text) = @_;
 1031: 	if ($text) {
 1032: 	    $value =~ s/<[\/\w]*?>//sg;
 1033: 	} else {
 1034: 	    $value =~ s/^\s+/<br>&nbsp;&nbsp;&nbsp;&nbsp;/mg;
 1035: 	    $value =~ s/^\|([^\n]*)/<pre>$1<\/pre>/mg;
 1036: 	    $value =~ s/\s+-+\s+/&nbsp;&#0150; /mg;
 1037: #	    $value =~ s/(\s)"/$1&#147;/mg;
 1038: #	    $value =~ s/^"/&#147;/mg;
 1039: #	    $value =~ s/"/&#148;/mg;
 1040: 	}
 1041: 
 1042: 
 1043: 	return $text ? "$header:\n$value\n\n" :
 1044: 		strong("$header: ") . $value . p . "\n";
 1045: }
 1046: 
 1047: # Gets a DB handler (ofcourse) and a question Id. Prints
 1048: # that question, according to the options.
 1049: sub PrintQuestion {
 1050: 	my ($dbh, $Id, $answer, $qnum, $title, $text) = @_;
 1051: 	my ($output, $titles) = ('', '');
 1052: 	my (%Question) = &GetQuestion($dbh, $Id);
 1053: 	$qnum = $Question{'Number'}
 1054: 		if ($qnum == 0);
 1055: 	if (!$text) {
 1056: 		$output .= hr({width=>"50%"});
 1057: 		if ($title) {
 1058: 			my (%Tour) = GetTournament($dbh, $Question{'ParentId'});
 1059: 			my (%Tournament) = GetTournament($dbh, $Tour{'ParentId'});
 1060: 			my $fname=$Tournament{'FileName'};
 1061: 			$fname=~s/\.txt//;
 1062: 			$titles .=
 1063: 				dd(img({src=>"/icons/folder.open.gif"}) . " " .
 1064: 					 a({href=>url . "?tour=$fname"}, $Tournament{'Title'}, $Tournament{'PlayedAt'}));
 1065: 			$titles .=
 1066: 				dl(dd(img({src=>"/icons/folder.open.gif"}) . " " .
 1067: 					a({href=>url . "?tour=$fname.$Tour{Number}#$qnum"}, $Tour{'Title'})));
 1068: 		}
 1069: 		$output .= dl(strong($titles));
 1070: 	}
 1071: 
 1072: 
 1073: 	$output.= "<a NAME=\"$qnum\">";
 1074: 
 1075: 	$output .=
 1076: 		&PrintField("Вопрос $qnum", $Question{'Question'}, $text);
 1077: 
 1078: 	if ($answer==1) {
 1079: 		$output .=
 1080: 			&PrintField("Ответ", $Question{'Answer'}, $text);
 1081: 
 1082: 		if ($Question{'Authors'}) {
 1083:                       my $q=$Question{'Authors'};
 1084: ###АВТОРА!!
 1085:  		      my $sth=$dbh->prepare("select Authors.Id,Name, Surname, Nicks from Authors, A2Q
 1086:                                   where Authors.Id=Author And Question=$Id");
 1087:                        $sth->execute;
 1088:                        my ($AuthorId,$Name, $Surname,$other,$Nicks);
 1089: 
 1090:                        while ((($AuthorId,$Name, $Surname,$Nicks)=$sth->fetchrow),$AuthorId)
 1091:                        {
 1092:                          my ($firstletter)=$Name=~m/^./g;
 1093:                           $Name=~s/\./\\\./g;
 1094:                            my $sha="(?:$Name\\s+$Surname)|(?:$Surname\\s+$Name)|(?:$firstletter\\.\\s*$Surname)|(?:$Surname\\s+$firstletter\\.)|(?:$Surname)|(?:$Name)";
 1095:                            if ($Nicks)
 1096:                            {
 1097:                              $Nicks=~s/^\|//;
 1098:                              foreach (split /\|/, $Nicks)
 1099:                              {
 1100:                                s/\s+/ /g;
 1101:                                s/\s+$//;
 1102:                                s/ /\\s+/g;
 1103:                                s/\./\\\./g;
 1104:                                if (s/>$//) {$sha="$sha|(?:$_)"}
 1105:                                else        {$sha="(?:$_)|$sha"}
 1106:                              }
 1107:                            }
 1108:                            $q=~s/($sha)/a({href=>url."?qofauthor=$AuthorId"},$1)/ei;
 1109:                        }
 1110:  
 1111: 			$output .= &PrintField("Автор(ы)", $q, $text);
 1112: 
 1113: 		}
 1114: 
 1115: 		if ($Question{'Sources'}) {
 1116: 			$output .= &PrintField("Источник(и)", $Question{'Sources'}, $text);
 1117: 		}
 1118: 
 1119: 		if ($Question{'Comments'}) {
 1120: 			$output .= &PrintField("Комментарии", $Question{'Comments'}, $text);
 1121: 		}
 1122: 	}
 1123: 	elsif ($answer==2) {
 1124: 	  my $text=$Question{'Answer'};
 1125: 	  $text=~s/\n/<option>/mg;
 1126: 	  $output.="<select><option selected>Ответ:<option>$text</select>";
 1127: 	  $text=$Question{'Comments'}||'';
 1128: 	  if ($text) {
 1129:              $text=~s/\n/<option>/mg;
 1130: 	     $output.="<select><option selected>Комментарий:<option>$text</select>"
 1131: 	  }
 1132: 	} 
 1133: 	elsif ($answer==3) {
 1134:         $output.=  <<EOTT
 1135: 	  <div align=right STYLE="cursor:hand;" OnStart="toggle(document.all.HideShow$qnum);" OnClick="toggle(document.all.HideShow$qnum);">
 1136: 	  <font size=-2 color=red> Показать/убрать ответ</font></div>
 1137: 	  <span style="display:none" id=HideShow$qnum>
 1138: EOTT
 1139:           .&PrintField("Ответ", $Question{'Answer'}, $text);
 1140: 		if ($Question{'Authors'}) {
 1141: 			$output .= &PrintField("Автор(ы)", $Question{'Authors'}, $text);
 1142: 		}
 1143: 		if ($Question{'Sources'}) {
 1144: 			$output .= &PrintField("Источник(и)", $Question{'Sources'}, $text);
 1145: 		}
 1146: 
 1147: 		if ($Question{'Comments'}) {
 1148: 			$output .= &PrintField("Комментарии", $Question{'Comments'}, $text);
 1149: 		}
 1150: 
 1151: 
 1152: $output.="</span>"
 1153: 
 1154: 	}
 1155: 	$output.=br.a({href=> url."?metod=proxy&qid=$Id"}, 'Близкие вопросы').p
 1156:              if $answer;
 1157: 	return $output;
 1158: }
 1159: 
 1160: # Returns the total number of questions currently in the DB.
 1161: sub GetQNum {
 1162: 	my ($dbh) = @_;
 1163: 	my ($sth) = $dbh->prepare("SELECT COUNT(*) FROM Questions");
 1164: 	$sth->execute;
 1165: 	my $tmp=($sth->fetchrow)[0];
 1166:         $sth->finish;
 1167:  	return $tmp;
 1168: }
 1169: sub GetMaxQId {
 1170: 	my ($dbh) = @_;
 1171: 	my ($sth) = $dbh->prepare("SELECT MAX(QuestionId) FROM Questions");
 1172: 	$sth->execute;
 1173: 	my $tmp=($sth->fetchrow)[0];
 1174:         $sth->finish;
 1175:  	return $tmp;
 1176: 
 1177: }
 1178: 
 1179: # Returns Id's of 12 random questions
 1180: sub Get12Random {
 1181:    my ($dbh, $type, $num) = @_;
 1182: 	my ($i, @questions, $q, $t, $sth);
 1183: 	my ($qnum) = &GetMaxQId($dbh);
 1184: 	my (%chosen);
 1185: 	srand;
 1186: 	my $where=0;
 1187: 	my $r=int (rand(10000));
 1188: 
 1189: 	foreach (split '', $type)
 1190:         {
 1191:  	   $where.= " OR (Type ='$_') OR (Type ='$_Д') ";
 1192:  	}
 1193:         $where.= "OR (Type='ЧБ')" if ($type=~/Ч|Б/);
 1194: 
 1195:    $q="select QuestionId, QuestionId/$r-floor(QuestionId/$r) as val 
 1196:        from Questions where $where order by val limit $num";
 1197: # Когда на куличках появится mysql >=3.23 надо заменить на order by rand();
 1198: 
 1199:    $sth=$dbh->prepare($q);
 1200:    $sth->execute;
 1201:    while (($i)=$sth->fetchrow)
 1202:    {
 1203:       push @questions,$i;
 1204:    }
 1205:    $sth->finish;
 1206:     for ($i=@questions; --$i;){ 
 1207:        my $j=rand ($i+1); 
 1208:        @questions[$i,$j]=@questions[$j,$i] unless $i==$j;
 1209:     }
 1210:    return @questions;
 1211: }
 1212: 
 1213: sub Include_virtual {
 1214: 	my ($fn, $output) = (@_, '');
 1215: 
 1216: 	open F , $fn
 1217: 		or return; #die "Can't open the file $fn: $!\n";
 1218: 
 1219: 	while (<F>) {
 1220: 		if (/<!--#include/o) {
 1221: 			s/<!--#include virtual="\/(.*)" -->/&Include_virtual($1)/e;
 1222: 		}
 1223: 		if (/<!--#exec/o) {
 1224: 			s/<!--#exec.*cmd\s*=\s*"([^"]*)".*-->/`$1`/e;
 1225: 		}
 1226: 		$output .= $_;
 1227: 	}
 1228: 	return $output;
 1229: }
 1230: 
 1231: sub PrintArchive {
 1232: 	my($dbh, $Id) = @_;
 1233: 	my ($output, @list, $i);
 1234: 
 1235: 	my (%Tournament) = &GetTournament($dbh, $Id);
 1236: 	my (@Tours) = &GetTours($dbh, $Id);
 1237: 	if ($Tournament{'Type'} =~ /Г/ || $Id == 0) {
 1238: 		for ($i = 0; $i <= $#Tours; $i++) {
 1239: 			push(@list ,&PrintArchive($dbh, $Tours[$i]));
 1240: 		}
 1241: 		return @list;
 1242: 	}
 1243: #	return "$SRCPATH/$Tournament{'FileName'} ";
 1244: 	return "$TMPDIR/$Tournament{'FileName'} ";
 1245: }
 1246: 
 1247: sub PrintAll {
 1248: 	my ($dbh, $Id,$fname) = @_;
 1249: 	my ($output, $list, $i);
 1250: 
 1251: 	my (%Tournament) = &GetTournament($dbh, $Id);
 1252: 	my (@Tours) = &GetTours($dbh, $Id);
 1253: 	my ($New) = ($Id and $Tournament{'Type'} eq 'Ч' and
 1254: 		&NewEnough($Tournament{"CreatedAt"})) ?
 1255: 		img({src=>"/znatoki/dimrub/db/new-sml.gif", alt=>"NEW!"}) : "";
 1256: 
 1257: 	if ($Id == 0) {
 1258: 		$output = h3("Все турниры");
 1259: 	} else {
 1260: 	         my $textid;
 1261: 		 if ($textid=$Tournament{'FileName'})
 1262: 		 {
 1263: 		   $textid=~s/\.txt//;
 1264: 		 }
 1265: 		 elsif ($textid=$Tournament{'Number'})
 1266: 		 {
 1267: 		      $fname=~s/\.txt//;
 1268: 		      $textid="$fname.$textid";
 1269: 		 }
 1270: 	         else {$textid=$Tournament{'Id'}};
 1271: 
 1272: 
 1273: 		$output .= dd(img({src=>"/icons/folder.gif", alt=>"[*]"}) .
 1274:       " " . a({href=>url . "?tour=$textid&answer=0"},
 1275:       $Tournament{'Title'}) ." " . $Tournament{'PlayedAt'} . " $New");
 1276: 	}
 1277: 	if ($Id == 0 or $Tournament{'Type'} =~ /Г/ or $Tournament{'Type'} eq '') {
 1278: 		for ($i = 0; $i <= $#Tours; $i++) {
 1279: 			$list .= &PrintAll($dbh, $Tours[$i],$Tournament{'FileName'});
 1280: 		}
 1281: 		$output .= dl($list);
 1282: 	}
 1283: 	return $output;
 1284: }
 1285: 
 1286: sub PrintDates {
 1287: 	my ($dbh) = @_;
 1288: 	my ($from) = param('from_year') . "-" . param('from_month') .
 1289: 		"-" .  param('from_day');
 1290: 	my ($to) = param('to_year') . "-" . param('to_month') . "-" .  param('to_day');
 1291: 	$from = $dbh->quote($from);
 1292: 	$to = $dbh->quote($to);
 1293: 	my ($sth) = $dbh->prepare("
 1294: 		SELECT DISTINCT Id
 1295: 		FROM Tournaments
 1296: 		WHERE PlayedAt >= $from AND PlayedAt <= $to
 1297: 		AND Type = 'Ч'
 1298: 	");
 1299: 	$sth->execute;
 1300: 	my (%Tournament, @array, $output, $list);
 1301: 
 1302: 	$output = h3("Список турниров, проходивших между $from и $to.");
 1303: 	while (@array = $sth->fetchrow) {
 1304: 		next
 1305: 			if (!$array[0]);
 1306: 		%Tournament = &GetTournament($dbh, $array[0]);
 1307:       $list .= dd(img({src=>"/icons/folder.gif", alt=>"[*]"}) .
 1308:       " " . a({href=>url . "?tour=$Tournament{'Id'}&answer=0"},
 1309:       $Tournament{'Title'}, $Tournament{'PlayedAt'}));
 1310: 	}
 1311:         $sth->finish;
 1312: 	$output .= dl($list);
 1313: 	return $output;
 1314: }
 1315: 
 1316: sub PrintQOfAuthor
 1317: {
 1318: 
 1319:     my ($dbh, $id) = @_;
 1320:    $id=$dbh->quote($id);
 1321:     my $sth =  $dbh->prepare("SELECT  Name, Surname FROM Authors WHERE Id=$id");
 1322:     $sth->execute;
 1323:     my ($name,$surname)=$sth->fetchrow;
 1324: 
 1325:     $sth =  $dbh->prepare("SELECT Question FROM A2Q WHERE Author=$id");
 1326:     $sth->execute;
 1327:     my $q;
 1328:     my @Questions;
 1329:     while (($q)=$sth->fetchrow,$q)
 1330:      {push @Questions,$q unless $forbidden{$q}}
 1331:     $sth->finish;
 1332: 
 1333:     my ($output, $i, $suffix, $hits) = ('', 0, '', $#Questions + 1);
 1334: 
 1335:     if ($hits =~ /1.$/  || $hits =~ /[5-90]$/) {
 1336: 		$suffix = 'й';
 1337: 	} elsif ($hits =~ /1$/) {
 1338: 		$suffix = 'е';
 1339: 	} else {
 1340: 		$suffix = 'я';
 1341: 	}
 1342: 	print h2("Поиск в базе вопросов");
 1343: 	print printform;
 1344: 	print p({align=>"center"}, "Автор ".strong("$name $surname. ")
 1345: 	. " : $hits попадани$suffix.");
 1346: 
 1347: 
 1348: #	for ($i = 0; $i <= $#Questions; $i++) {
 1349: #		$output = &PrintQuestion($dbh, $Questions[$i], 1, $i + 1, 1);
 1350: #		print $output;
 1351: #	}
 1352:         PrintList($dbh,\@Questions,'gdfgdfgdfgdfg');
 1353: }
 1354: 
 1355: 
 1356: sub PrintAuthors
 1357: {
 1358:      my ($dbh,$sort)=@_;
 1359:      my($output,$out1,@array,$sth);
 1360:      if ($sort eq 'surname')
 1361:      {
 1362:         $sth =
 1363:              $dbh->prepare("SELECT Id, Name, Surname, QNumber FROM Authors order by Surname, Name");
 1364:      }
 1365:      elsif($sort eq 'name')
 1366:      {
 1367:         $sth =
 1368:              $dbh->prepare("SELECT Id, Name, Surname, QNumber FROM Authors order by Name, Surname");
 1369:      }
 1370:      else
 1371:      {
 1372:         $sth =
 1373:              $dbh->prepare("SELECT Id, Name, Surname, QNumber FROM Authors Order by QNumber DESC, Surname");
 1374:      }
 1375: 
 1376:      $output.=h2("Авторы вопросов")."\n";
 1377:      $output.="<TABLE>";
 1378: 
 1379: 
 1380:      $sth->execute;
 1381:      $output.=Tr(th[a({href=>url."?authors=name"},"Имя")
 1382: .", ".
 1383: a({href=>url."?authors=surname"},"фамилия")
 1384:      , a({href=>url."?authors=kvo"},"Количество вопросов")]);
 1385: 
 1386:      $out1='';
 1387: 
 1388:      my $ar=$sth->fetchall_arrayref;
 1389: 
 1390:      $sth->finish;
 1391: 
 1392: 
 1393:     foreach my $arr(@$ar)
 1394:      {
 1395: 
 1396:            my ($id,$name,$surname,$kvo)=@$arr;
 1397:            if (!$name || !$surname) {#print "Opanki at $id\n"
 1398:               } else
 1399:            {
 1400:              my $add=Tr(td([a({href=>url."?qofauthor=$id"},"$name $surname"), $kvo]))."\n";
 1401:              print STDERR $add;
 1402:              $output.=$add;
 1403:            }
 1404:      }
 1405:      $output.="</TABLE>";
 1406:      $sth->finish;
 1407:      return $output;
 1408: }
 1409: 
 1410: 
 1411: sub WriteFile {
 1412:   my ($dbh,$fname) = @_;
 1413:   $fname=~s/\s+$//;
 1414:   $fname=~s/^\s+//;
 1415:   $fname=~s/\.txt$//;
 1416:   $fname=~s/.*\/(\w+)/$1/;
 1417: 
 1418:   my $query= "SELECT Id, Title, Copyright, Info, URL, 
 1419:                       Editors, EnteredBy, PlayedAt, CreatedAt 
 1420:                      from Tournaments where FileName=".$dbh->quote("$fname.txt");
 1421:   my $sth=$dbh->prepare($query);
 1422:   my (%Question,%editor,%qnumber,%copyright,%author,%vid,%tourtitle);
 1423:   $sth->execute;
 1424:   my ($Id, $Title, $Copyright, $Info, $URL, 
 1425:    $Editors, $EnteredBy, $PlayedAt, $CreatedAt)=
 1426:       $sth->fetchrow;
 1427:   return -1 unless $Id;
 1428:   open (OUT, ">$TMPDIR/$fname.txt") || print STDERR "Error in $fname.txt\n";
 1429:   print OUT "Чемпионат:\n$Title\n\n";
 1430:   my $date=$PlayedAt;
 1431:   my ($year,$month,$day)=split /-/, $date;
 1432: #  $month=0,$date=0 if $year && $month==1 && $day==1;
 1433:   my $pdate=sprintf("%02d-%3s-%4d",$day,$months[$month],$year);
 1434: 
 1435:   print OUT "Дата:\n$pdate\n\n" if $date;
 1436: 
 1437:   print OUT "URL:\n$URL\n\n" if $URL;
 1438: 
 1439:   print OUT "Инфо:\n$Info\n\n" if $Info;
 1440: 
 1441:   print OUT "Копирайт:\n$Copyright\n\n" if $Copyright;
 1442: 
 1443:   print OUT "Редактор:\n$Editors\n\n" if $Editors;
 1444: 
 1445: 
 1446:   $query= "SELECT Id, Title, Copyright, Editors from Tournaments where ParentId=$Id order by Id";
 1447:   $sth=$dbh->prepare($query);
 1448:   $sth->execute;
 1449:   my ($tourid,$tourtitle,$cright,$editor,@tours,$vid,$author,$tourauthor);
 1450: 
 1451: 
 1452:   while (($tourid,$tourtitle,$cright,$editor)=$sth->fetchrow,$tourid)
 1453:   {
 1454: #    $text{$tourid}="Тур:\n$tourtitle\n\n";
 1455:     $query= "SELECT * from Questions where ParentId=$tourid order by QuestionId";
 1456:     my $sth1=$dbh->prepare($query);
 1457:     $sth1->execute;
 1458:     push(@tours,$tourid);
 1459:     $tourtitle{$tourid}=$tourtitle;
 1460:     $copyright{$tourid}=$cright;
 1461:     $editor{$tourid}=$editor;
 1462:     $vid='';
 1463:     my $author='';
 1464:     my $eqauthor=1;
 1465:     my $qnumber=0;
 1466:     my @arr;
 1467:     while ( (@arr=$sth1->fetchrow), $arr[0])
 1468:     {
 1469: 	my($i, $name);
 1470: 	$i=0;
 1471: 	$qnumber++;
 1472: 	foreach $name (@{$sth1->{NAME}}) {
 1473: 	        if ($arr[$i]) {
 1474:   	           $arr[$i]=~s/^(.*?)\s*$/$1/;
 1475: 		   $Question{$tourid}[$qnumber]{$name} = $arr[$i];
 1476: 		} else {
 1477:   	            $Question{$tourid}[$qnumber]{$name} = 
 1478:                    ''}
 1479:                 $i++;
 1480: 	}
 1481: 	if ($vid)
 1482:         {
 1483:           if ($vid ne $Question{$tourid}[$qnumber]{'Type'}) {print STDERR "Warning: Different types for Tournament $tourid\n"}
 1484:         } else 
 1485:         {
 1486:             $vid=$Question{$tourid}[$qnumber]{'Type'};
 1487:         } 
 1488: 
 1489: 	if ($author)
 1490:         {
 1491:           if ($author ne $Question{$tourid}[$qnumber]{'Authors'})  
 1492:           {
 1493:              $eqauthor=0;
 1494:           }
 1495:         } else 
 1496:         {
 1497:             $author=$Question{$tourid}[$qnumber]{'Authors'};
 1498:             $eqauthor=0 unless $author;
 1499:         } 
 1500:     }
 1501:     $vid{$tourid}=$vid;
 1502:     $qnumber{$tourid}=$qnumber;
 1503:     $author{$tourid}=$eqauthor ? $author : '';
 1504:   }
 1505: 
 1506: 
 1507:   $vid='';
 1508:   my $eqvid=1;
 1509:   my $eqauthor=1;
 1510:   foreach (@tours)
 1511:   {
 1512:      $vid||=$vid{$_};
 1513:      if ($vid{$_} ne $vid)
 1514:      {
 1515:         $eqvid=0;
 1516:      }
 1517:      $author||=$author{$_};
 1518:      if (!$author{$_} || ($author{$_} ne $author))
 1519:      {
 1520:         $eqauthor=0;
 1521:      }
 1522:   }
 1523:   
 1524:   print OUT "Вид:\n$vid\n\n" if $eqvid;
 1525:   print OUT "Автор:\n$author\n\n" if $eqauthor;
 1526: 
 1527:   foreach my $tour(@tours)
 1528:   {
 1529:      print OUT "Тур:\n$tourtitle{$tour}\n\n";
 1530:      print OUT "Вид:\n$vid{$tour}\n\n" if  !$eqvid;
 1531:      print OUT "Копирайт:\n$copyright{$tour}\n\n" if $copyright{$tour} && ($copyright{$tour} ne $Copyright);
 1532:      print OUT "Редактор:\n$editor{$tour}\n\n" if $editor{$tour} && ($editor{$tour} ne $Editors);
 1533:      $tourauthor=0;
 1534:      if (!$eqauthor && $author{$tour})
 1535:      { 
 1536:        print OUT "Автор:\n$author{$tour}\n\n";
 1537:        $tourauthor=1;
 1538:      }
 1539:      foreach my $q(1..$qnumber{$tour})
 1540:      {
 1541:         print OUT "Вопрос $q:\n".$Question{$tour}[$q]{'Question'}."\n\n";
 1542: 	print OUT  "Ответ:\n".$Question{$tour}[$q]{'Answer'}."\n\n";
 1543: 	print OUT  "Автор:\n".$Question{$tour}[$q]{'Authors'}."\n\n" 
 1544:                if !$tourauthor && !$eqauthor && $Question{$tour}[$q]{'Authors'};
 1545: 	print OUT  "Комментарий:\n".$Question{$tour}[$q]{'Comments'}."\n\n" 
 1546:                if $Question{$tour}[$q]{'Comments'};
 1547: 	print OUT "Источник:\n".$Question{$tour}[$q]{'Sources'}."\n\n" 
 1548:                if $Question{$tour}[$q]{'Sources'};
 1549: 	print OUT "Рейтинг:\n".$Question{$tour}[$q]{'Rating'}."\n\n" 
 1550:                if $Question{$tour}[$q]{'Rating'};
 1551: 
 1552:      }
 1553:   }
 1554: 
 1555:   close OUT;
 1556: 
 1557: 
 1558: 
 1559: }
 1560: 
 1561: 
 1562: MAIN:
 1563: {
 1564: 	setlocale(LC_CTYPE,'russian');
 1565: 	my($i, $tour);
 1566: 	my($text) = (param('text')) ? 1 : 0;
 1567: 
 1568: 	my($dbh) = DBI->connect("DBI:mysql:chgk", "piataev", "")
 1569: 		or do {
 1570: 			print h1("Временные проблемы") . "База данных временно не
 1571: 			работает. Заходите попозже.";
 1572: 			print &Include_virtual("../dimrub/db/reklama.html");
 1573: 		    print end_html;
 1574: 			die "Can't connect to DB chgk\n";
 1575: 		};
 1576: 	if (!param('comp') and !param('sqldump') and !$text) {
 1577: 	   print header;
 1578: 	   print start_html(-"title"=>'Database of the questions',
 1579: 	           -author=>'dimrub@icomverse.com',
 1580: 	           -bgcolor=>'#fff0e0',
 1581: 				  -vlink=>'#800020');
 1582: 		print &Include_virtual("../dimrub/db/reklama.html");
 1583: 	}
 1584: 
 1585: 
 1586: if ($^O =~ /win/i) {
 1587: 	$thislocale = "Russian_Russia.20866";
 1588: } else {
 1589: 	$thislocale = "ru_RU.KOI8-R";
 1590: }
 1591: POSIX::setlocale( &POSIX::LC_ALL, $thislocale );
 1592: 
 1593: if ((uc 'а') ne 'А') {print "Koi8-r locale not installed!\n"};
 1594: 
 1595: 
 1596: 	if ($text) {
 1597: 		print header('text/plain');
 1598: 	}
 1599: 
 1600:         if (param('hideequal')) {
 1601: 	           my ($sth)=  $dbh -> prepare("select first, second FROM equalto");
 1602: 	           $sth -> execute;
 1603: 	           while ( my  ($first, $second)=$sth -> fetchrow)
 1604:                   {
 1605:                        $forbidden{$first}=1;
 1606:                   }
 1607:                   $sth->finish;
 1608:         }
 1609: 		$tour = (param('tour')) ? param('tour') : 0;
 1610: 		my $sth;
 1611: 		if ($tour !~ /^[0-9]*$/) {
 1612: 		    if ($tour=~/\./)
 1613: 		    {
 1614: 		        my ($fname,$n)= split /\./ , $tour;
 1615: 
 1616: 	                $sth = $dbh->prepare(
 1617:                        "SELECT t2.Id FROM Tournaments as t1, 
 1618:                         Tournaments as t2 
 1619: 			WHERE t1.FileName = '$fname.txt'
 1620:                         AND t1.Id=t2.ParentId AND t2.Number=$n");
 1621: 		    }	
 1622: 		    else 
 1623: 		        {
 1624:                           $sth = $dbh->prepare("SELECT Id FROM Tournaments
 1625: 			             WHERE FileName = '$tour.txt'");
 1626: 			}
 1627: 		    $sth->execute;
 1628: 	            $tour = ($sth->fetchrow)[0];
 1629:                     $sth->finish;
 1630: 		}
 1631: 
 1632: 
 1633: 	if (param('rand')) {
 1634: 		my ($type, $qnum) = ('', 12);
 1635: 		$type.=$TypeName{$_} foreach param('type');
 1636: #		$type .= 'Б' if (param('brain'));
 1637: #		$type .= 'Ч' if (param('chgk'));
 1638: 		$qnum = param('qnum') if (param('qnum') =~ /^\d+$/);
 1639: 		$qnum = 0 if (!$type);
 1640: 		my $Email;
 1641: 		if (($Email=param('email')) && -x $SENDMAIL &&
 1642: 		open(F, "| $SENDMAIL $Email")) {
 1643: 			my ($mime_type) = $text ? "plain" : "html";
 1644: 			print F <<EOT;
 1645: To: $Email
 1646: From: olegstepanov\@mail.ru
 1647: Subject: Sluchajnij Paket Voprosov "Chto? Gde? Kogda?"
 1648: MIME-Version: 1.0
 1649: Content-type: text/$mime_type; charset="koi8-r"
 1650: 
 1651: EOT
 1652: 			print F &PrintRandom($dbh, $type, $qnum, $text);
 1653: 			close F;
 1654: 			print "Пакет случайно выбранных вопросов послан по адресу $Email. Нажмите
 1655: 			на <B>Reload</B> для получения еще одного пакета";
 1656: 		} else {
 1657: 			print &PrintRandom($dbh, $type, $qnum, $text);
 1658: 		}
 1659: 	}
 1660: 	  elsif (param('authors')){
 1661:                 print &PrintAuthors($dbh,param('authors'));
 1662:         }
 1663:           elsif (param('qofauthor')){
 1664:                 &PrintQOfAuthor($dbh,param('qofauthor'));
 1665:         }
 1666:           elsif (param('sstr')||param('was')) {
 1667: 		&PrintSearch($dbh, param('sstr'), param('metod'),param('was'));
 1668: 		$dbh->do("delete from lastqueries where
 1669:                       (TO_DAYS(NOW()) - TO_DAYS(t) >= 2) OR
 1670: 		           (time_to_sec(now())-time_to_sec(t) >3600)")
 1671: 	} 
 1672: 	  elsif (param('qid')) {
 1673: 	      my $qid=param('qid');
 1674:               my $query="SELECT Question, Answer from Questions where QuestionId=$qid";
 1675: print $query if $printqueries;
 1676: 	      my $sth=$dbh->prepare($query);
 1677: 	      $sth->execute;
 1678: 	      my $sstr= join ' ',$sth->fetchrow;
 1679:               $sth->finish;
 1680: 	      $searchin{'Question'}=1;
 1681: 	      $searchin{'Answer'}=1;
 1682:       $sstr=~tr/ёЁ/еЕ/;
 1683: $sstr=~s/[^йцукенгшщзхъфывапролджэячсмитьбюЙЦУКЕНГШЩЗХЪФЫВАПРОЛДЖЭЯЧСМИТЬБЮa-zA-Z0-9]/ /gi;
 1684: #              print &PrintQuestion($dbh,$qid, 1, '!');
 1685:  	      &PrintSearch($dbh, $sstr, 'proxy');
 1686:  	}
 1687:  	elsif (param('getfile')){
 1688:           print &writefile
 1689:  	} elsif (param('all')) {
 1690: 		print &PrintAll($dbh, 0);
 1691: 	} elsif (param('from_year') && param('to_year')) {
 1692: 		print &PrintDates($dbh);
 1693: 	} elsif (param('comp')) {
 1694:             print "Content-Type: application/octet-stream\n";
 1695:             print "Content-Type: application/force-download\n";
 1696:             print "Content-Type: application/download\n";
 1697:             print "Content-Type: application/x-zip-compressed; name=db.zip\n";
 1698:             print "Content-Disposition: attachment; filename=db.zip \n\n";
 1699: #	    print header(
 1700: #			 -'Content-Type' => 'application/x-zip-compressed; name="db.zip"',
 1701: #			 -'Content-Type' => 'application/zip',
 1702: #			 -'Content-Disposition' => 'attachment; filename="db.zip"'
 1703: #			 );
 1704: 	    $tour ||= 0;
 1705: 	    my (@files) = &PrintArchive($dbh, $tour);
 1706: 	    WriteFile($dbh,$_) foreach @files;
 1707: #	    open F, "$ZIP -j - $SRCPATH/COPYRIGHT @files |";
 1708: 	    open F, "$ZIP -j - @files |";
 1709: 	    binmode(F);
 1710: 	    binmode(STDOUT);
 1711: 	    print (<F>);
 1712: 	    close F;
 1713: 	    $dbh->disconnect;
 1714: 	    exit;
 1715: 	} elsif (param('sqldump')) {
 1716: 	    print header(
 1717: 			 -'Content-Type' => 'application/x-zip-compressed; name="dump.zip"',
 1718: 			 -'Content-Disposition' => 'attachment; filename="dump.zip"'
 1719: 			 );
 1720: 	    open F, "$ZIP -j - $DUMPFILE |";
 1721: 	    print (<F>);
 1722: 	    close F;
 1723: 	    $dbh->disconnect;
 1724: 	    exit;
 1725: 
 1726: 	} else {
 1727: 		my $QuestionNumber=0;
 1728: 		my $qnum;
 1729: 		if ($qnum=param('qnumber')){
 1730:       	          my ($sth) = $dbh->prepare("SELECT QuestionId FROM Questions
 1731: 		     WHERE ParentId=$tour AND Number=$qnum");
 1732: 		  $sth->execute;
 1733: 		  $QuestionNumber=($sth->fetchrow)[0]||0;
 1734: 	        }
 1735: 	        if ($QuestionNumber) {
 1736: 		  print &PrintQuestion($dbh, $QuestionNumber, param('answer')||0, $qnum, 1);
 1737: #                                        $dbh, $Id, $answer, $qnum, $title, $text
 1738: 		} else  {
 1739:   		   print &PrintTournament($dbh, $tour, param('answer'));
 1740:   		}
 1741: 	}
 1742: 	if (!$text) {
 1743: 		print &Include_virtual("../dimrub/db/footer.html");
 1744: print <<EEE
 1745:   <SCRIPT LANGUAGE="JavaScript">
 1746: function toggle(e) {
 1747:   if (e.style.display == "none") {
 1748:      e.style.display="";
 1749:   } else {
 1750:      e.style.display = "none";
 1751:  }
 1752: }
 1753: </SCRIPT>
 1754: EEE
 1755: ;
 1756: 		print end_html;
 1757: 	}
 1758: 	$dbh->disconnect;
 1759: }

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