File:  [Local Repository] / db / prgsrc / db.cgi
Revision 1.96: download - view: text, annotated - select for diffs - revision graph
Thu Apr 10 00:05:04 2003 UTC (21 years, 1 month ago) by roma7
Branches: MAIN
CVS tags: HEAD
malen'koe ispravlenie vyvoda

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

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