File:  [Local Repository] / db / prgsrc / db.cgi
Revision 1.99: download - view: text, annotated - select for diffs - revision graph
Sat Apr 19 22:50:06 2003 UTC (21 years, 1 month ago) by roma7
Branches: MAIN
CVS tags: HEAD
'Comments'error fixed

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

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