File:  [Local Repository] / db / prgsrc / db.cgi
Revision 1.103: download - view: text, annotated - select for diffs - revision graph
Sun Apr 20 11:35:05 2003 UTC (21 years, 1 month ago) by roma7
Branches: MAIN
CVS tags: HEAD
htmling once again

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

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