File:  [Local Repository] / db / prgsrc / db.cgi
Revision 1.117: download - view: text, annotated - select for diffs - revision graph
Tue Apr 29 22:21:26 2003 UTC (21 years, 1 month ago) by roma7
Branches: MAIN
CVS tags: HEAD
*** empty log message ***

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

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