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

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