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

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

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