File:  [Local Repository] / db / prgsrc / db.cgi
Revision 1.79: download - view: text, annotated - select for diffs - revision graph
Tue Nov 26 05:34:39 2002 UTC (21 years, 6 months ago) by roma7
Branches: MAIN
CVS tags: HEAD
fixed "text only" bug

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

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