File:  [Local Repository] / db / prgsrc / db.cgi
Revision 1.98: download - view: text, annotated - select for diffs - revision graph
Mon Apr 14 23:52:12 2003 UTC (21 years, 1 month ago) by roma7
Branches: MAIN
CVS tags: HEAD
db.cgi

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

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