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

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