File:  [Local Repository] / db / prgsrc / db.cgi
Revision 1.116: download - view: text, annotated - select for diffs - revision graph
Mon Apr 28 22:49:50 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: print "shablon=$shablon".p;
  749: 	$first=$first-($first-1)%$outputkvo;
  750:         my $fkvo=param('fkvo')||($#$Questions+1);
  751: 	my $last=$first+$outputkvo-1;
  752: 	$last=$fkvo if $fkvo<$last;
  753:         my($f,$l);
  754:         my $nav='';
  755:         my $qs=query_string;
  756: 	$qs=~s/\;/\&/g;
  757:         $qs=~s/\&first\=[^\&]+//g;
  758:         my $sstr=param('sstr')||'';
  759:         $qs=~s/sstr=[^\&]+/sstr=$sstr/;
  760:         if ($usewas) {
  761:         	$qs=~s/\&was=[^\&]+//;
  762:         	$qs.="&was=$was" if $was;
  763:         	$qs.="&fkvo=$fkvo" if $was;
  764:         }
  765:         if ($first>$outputkvo*3+1)
  766:         {
  767:            $nav.=
  768:             ("&nbsp;"x4).
  769:             a({href=>$url."?".$qs."\&first=1"},"<<").("&nbsp;"x4).
  770:             a({href=>($url."?".$qs."\&first=".($first-$outputkvo))},"<").("&nbsp;"x4)
  771: 	}
  772:         else {$nav.='&nbsp;'x15;}
  773: 
  774:      my ($fprint,$lprint);
  775:      my $llprint=$fkvo- ($fkvo)%$outputkvo+1; #
  776:      if ($fkvo<=$outputkvo*7)
  777:      {         $fprint=1;
  778:                $lprint=$llprint;
  779:      }
  780:      elsif ($first>$outputkvo*3 && $fkvo-$first>$outputkvo*3)
  781:      {
  782:        $fprint=$first-$outputkvo*3;
  783:        $lprint=$first+$outputkvo*3;
  784:      } 
  785:      elsif  ($first<=$outputkvo*3)
  786:      {
  787:         $fprint=1; $lprint=6*$outputkvo+1;
  788:      }
  789:      else
  790:      { 
  791:            $lprint=$llprint;
  792:            $fprint=$lprint-$outputkvo*6
  793:      }
  794:          
  795: #        my $fprint=($first>$outputkvo*3) ? $first-$outputkvo*3 : 1;
  796: #        my $lprint=$#$Questions+1-$fprint>$outputkvo*7 ? $outputkvo*7 :$#$Questions+1;
  797: #        if ($lprint-$fprint<$outputkvo*6 && $fprint>1)
  798: #        {
  799: #            $fprint=$lprint-$outputkvo*6;
  800: #            $fprint=1 if ($fprint<=0) 
  801: #        }
  802: 
  803: 
  804: 
  805:         for($f=$fprint; $f<=$lprint; $f+=$outputkvo)
  806: 	{
  807: #	  next if $first-$f>$outputkvo*3;
  808: 	  $l=$f+$outputkvo-1;
  809: 	  $l=$fkvo if $l>$fkvo+1;
  810: 	  if ($f==$first) {$nav.="[$f-$l] ";}
  811: 	  else {
  812:                   $nav.= "[".a({href=>($url."?".$qs."\&first=$f")},"$f-$l")."] ";}
  813: 	}
  814:         if ($lprint+$outputkvo<$fkvo)
  815:         {
  816:            $nav.=
  817:             ("&nbsp;"x4).
  818:             a({href=>($url."?".$qs."\&first=".($first+$outputkvo))},">").("&nbsp;"x4).
  819:             a({href=>$url."?".$qs."\&first=$llprint"},">>").("&nbsp;"x4)
  820:         }
  821: 	$Output.= "$nav".br."\n";
  822: 	my @q=@$Questions[$first-1..$last-1];
  823: 	my %q=();
  824: 	my $sth=SelectQuestions($dbh,\@q,1);
  825: 	my $qq;
  826: 	my @Q;
  827: 	for (0..$#q) {
  828: 	        %{$Q[$_]}=();
  829: 		fetchquestion($sth,$Q[$_],1);
  830: 		$q{$Q[$_]{'QuestionId'}}=$Q[$_];
  831: 	}
  832: 
  833: 	for (my $i = $first; $i <= $last; $i++) {
  834: 		my $q=$q{$$Questions[$i-1]};
  835: 	        my $output;
  836: 		$output = &PrintQuestion($dbh, $q, 1, 0, 1,0,1  );
  837: #                if (param('metod') && (param('metod') eq 'rus' || param('metod') eq 'proxy'))
  838:                 {
  839: 	             $output=~s/\b($shablon)\b/\<strong\>$1\<\/strong\>/gi;
  840: 	             $output=~s/($shablon)/\<strong\>$1\<\/strong\>/gi;
  841: 		}
  842: 		$Output.= $output;
  843: 	}
  844: 	$sth->finish;
  845: 
  846: 	$Output.= "$nav".br."\n";
  847: 	return $Output;
  848: }
  849: 
  850: sub PrintSearch {
  851:         my $Output='';
  852: 	my ($dbh, $sstr, $metod,$was) = @_;
  853: 	my $t=time;
  854: 	$Output.= printform;
  855: 	my @allnf;
  856: 	my @Questions;
  857: 	$was=0 if $metod eq 'proxy';
  858: 	if ($usewas && $was && ($metod ne 'proxy'))
  859: 	{
  860: 	  my $sth=$dbh->prepare ("select sstr,questions,allnf from lastqueries where id=".param('was'));
  861:           $sth->execute;
  862:           my ($q,$nf);
  863: 	  ($sstr, $q,$nf)=($sth->fetchrow);
  864:           @Questions=unpack 'L*',$q; 
  865:           @allnf=unpack 'L*',$nf;        
  866:           $sth->finish;
  867:         }  
  868:         if (!$was || ($metod eq 'proxy') || (param('first')+$outputkvo>$cashednumber))
  869:         {
  870:              @Questions=&Search($dbh, \$sstr,$metod,$all,\@allnf);
  871:              $cashednumber=$#Questions if $cashednumber>$#Questions;
  872:              my $tmp=$dbh->quote(pack("L*",@Questions[0..$cashednumber]));
  873:              my $qsstr=$dbh->quote($sstr);
  874:              my $nf=$dbh->quote(pack("L*", @allnf));
  875:              my $ss=200;
  876:              if ($usewas) {
  877:              	do 
  878:              		{
  879:                			$was=int rand(32000);
  880:              		}
  881:              	while (--$ss && (!$dbh->do ("insert into lastqueries (id,sstr,questions,allnf) 
  882:                          values ($was, $qsstr,$tmp,$nf)")));
  883:              	$Output.= "Something is wrong...".br unless $ss;
  884:  	      }
  885:         }
  886: 
  887: 
  888: 
  889: 	$Output.= p. "Время поиска: " . (time-$t) ." сек.".p;
  890: 	my ($output, $i, $suffix, $hits) = ('', 0, '', $#Questions + 1);
  891: 
  892:         my $shablon;
  893:         $metod='rus' if $metod eq 'proxy';
  894:         if ($metod eq 'rus')
  895:         {
  896:            my $where='0';
  897:            $where.= " or w2=$_ " foreach @allnf;
  898:            my $query="select w1 from nests where $where";
  899:            my $sth=$dbh->prepare($query);
  900: 
  901: 	   $sth->execute;
  902: 	   my @shablon;
  903: 	   while (my @arr = $sth->fetchrow)
  904: 	   {
  905: 	     push @shablon,"(?:$arr[0])";
  906: 	   }
  907: 	   $sth->finish;
  908:            $shablon= join "|", @shablon;
  909:            $shablon=~s/[её]/\[ЕЁ\]/gi;
  910: #           $shablon=~s/([йцукенгшщзхъфывапролджэячсмитьбюЙЦУКЕНГШЩЗХЪФЫВАПРОЛДЖЭЯЧСМИТЬБЮ])/&NoCase($1)/ge;
  911:            $shablon=qr/$shablon/i;
  912: 
  913:         }
  914: 
  915:         $hits=param("fkvo")||$hits;
  916: 
  917: 	if ($hits =~ /1.$/  || $hits =~ /[5-90]$/) {
  918: 		$suffix = 'й';
  919: 	} elsif ($hits =~ /1$/) {
  920: 		$suffix = 'е';
  921: 	} else {
  922: 		$suffix = 'я';
  923: 	}
  924: 
  925: 	$Output.= p({align=>"center"}, "Результаты поиска на " . strong($sstr)
  926: 	. " : $hits попадани$suffix.");
  927: 
  928: 	if (param('word')) {
  929: 		$sstr = '[ 	\.\,:;]' . $sstr . '[  \.\,:\;]';
  930: 	}
  931: 
  932: #	$sstr =~ s/(.)/&NoCase($1)/ge;
  933: 
  934: 	my @sar;
  935: 	if ($metod ne 'rus') 
  936: 	{
  937: 	  my $ss=$sstr;
  938: 	  (@sar) = split(' ', $ss);
  939: 	  s/(\W)/\\$1/g foreach (@sar);
  940: 	  $shablon=join "|",@sar;
  941: 	}
  942: 	$Output.=PrintList($dbh,\@Questions,$shablon,$was);
  943: 	return $Output;
  944: }
  945: 
  946: sub PrintRandom {
  947:    my ($dbh, $type, $num, $text) = @_;
  948:    my $razd=param('razd');
  949:    my %q;
  950:    my $answer=$razd?0:1;
  951:    my @answers;
  952:    my (@Questions) = &Get12Random($dbh, $type, $num);
  953: 	my ($output, $i) = ('', 0);
  954: 
  955: 	if ($text) {
  956: 		$output .= "	$num случайных вопросов.\n\n";
  957: 	} else {
  958: 		$output .=
  959: 			h2({align=>"center"}, "$num случайных вопросов.");
  960: 	}
  961: 	my $sth=SelectQuestions($dbh,\@Questions,0);
  962: 	for ($i = 0; $i <= $#Questions; $i++) {
  963: 		fetchquestion($sth,\%q,0);
  964: 		$output .=
  965: 			&PrintQuestion($dbh, \%q, $answer, $i + 1, 0, $text,1);
  966: 			push @answers, $q{'Answer'};
  967: 	}
  968: 	$sth->finish;
  969: 	unless ($answer )
  970:         { 
  971:          $output.=$text?"\n".('-'x 20)."\nОтветы\n~~~~~~\n\n":h2('Ответы');
  972:          $sth=SelectQuestions($dbh,\@Questions,0);
  973:          for ($i = 0; $i <= $#Questions; $i++) {
  974: #                fetchquestion($sth,\%q,0);
  975: #		$output .=
  976: #			&PrintQuestion($dbh, \%q, -1, $i + 1, 0, $text,1);
  977:                 $output.=$text?("Ответ ". ($i+1).": $answers[$i]\n\n"):
  978: 			b("Ответ ". ($i+1).": "). $answers[$i].p;
  979: 	 }
  980:         }
  981: 
  982: 	return $output;
  983: }
  984: 
  985: sub PrintEditor {
  986:        my $t=shift; #ссылка на Хэш с полями
  987:        my $ed=$$t{'Editors'}||'';
  988:        my $edname=($ed=~/\,/ ) ? "Редакторы"  : "Редактор" ;
  989:        return $ed? h4({align=>"center"},"$edname: $ed" ): '';
  990: }
  991: 
  992: sub PrintTournament {
  993:    my ($dbh, $Id, $answer) = @_;
  994: 	my (%Tournament, @Tours, $i, $list, $qnum, $imgsrc, $alt,
  995: 		$SingleTour);
  996: 	my ($output) = '';
  997: 
  998: 	%Tournament = &GetTournament($dbh, $Id) if ($Id);
  999: 
 1000: 	my ($URL) = $Tournament{'URL'};
 1001: 	$URL=~s/http:\/znatoki\/boris\/reports\//$newsurl/ if $url=~/kulichki/ || $url=~/db.chgk.info/;
 1002: 	$URL=~s/\/znatoki\/boris\/reports\//$newsurl/ if url=~/kulichki/ || $url=~/db.chgk.info/;
 1003: 	my ($Info) = $Tournament{'Info'};
 1004: 	my ($Copyright) = $Tournament{'Copyright'};
 1005: 	my $fname=$Tournament{'FileName'};
 1006: 	@Tours = &GetTours($dbh, $Id);
 1007: 	$list='';
 1008: 	my $textid;
 1009: 	if ($Id) {
 1010: 		for ($Tournament{'Type'}) {
 1011: 			/Г/ && do {
 1012: 				$output .= h2({align=>"center"},
 1013: 					      "Группа: $Tournament{'Title'} ",
 1014: 					      $Tournament{'PlayedAt'}||'') . p . "\n";
 1015: 				last;
 1016: 			};
 1017: 			/Ч/ && do {
 1018: 				return &PrintTour($dbh, $Tours[0], $answer)
 1019: 					if ($#Tours == 0);
 1020: 
 1021: 				my $title="Пакет: $Tournament{'Title'}";
 1022: 				if ($Tournament{'PlayedAt'}) {
 1023: 				    $title .= " $Tournament{'PlayedAt'}";
 1024: 				}
 1025: 
 1026: 				$output .= h2({align=>"center"},
 1027: 					"$title") . p . "\n";
 1028: 			       $output.=&PrintEditor(\%Tournament);
 1029: 				last;
 1030: 			};
 1031: 			/Т/ && do {
 1032: 				return &PrintTour($dbh, $Id, $answer);
 1033: 			};
 1034: 		}
 1035: 	} else {
 1036: 		my ($qnum) = GetQNum($dbh);
 1037: 		$output .= h2("Банк Вопросов: $qnum вопрос".&Suffix($qnum)) 
 1038:                           . p . "\n";
 1039: 	}
 1040: 
 1041: 	for ($i = 0; $i <= $#Tours; $i++) {
 1042: 		%Tournament = &GetTournament($dbh, $Tours[$i]);
 1043: 
 1044: 		if ($Tournament{'Type'} =~ /Ч/) {
 1045: 			$SingleTour = 0;
 1046: 			my (@Tours) = &GetTours($dbh, $Tournament{'Id'});
 1047: 			$SingleTour = 1
 1048: 				if ($#Tours == 0);
 1049: 		}
 1050: 		if ($Tournament{'QuestionsNum'} > 0) {
 1051: 			$qnum = " ($Tournament{'QuestionsNum'} вопрос" .
 1052: 				&Suffix($Tournament{'QuestionsNum'}) . ")\n";
 1053: 		} else {
 1054: 			$qnum = '';
 1055: 		}
 1056: 		if ($Tournament{'Type'} !~ /[ТЧ]/) {
 1057: 		    $SingleTour=0;
 1058: 			$imgsrc = "/icons/folder.gif";
 1059: 			$alt = "[*]";
 1060: 		} else {
 1061: 			$imgsrc = "/icons/folder.gif";
 1062: 			$alt = "[-]";
 1063: 		}
 1064: 
 1065: 		my $textid;
 1066: 		if ($textid=$Tournament{'FileName'})
 1067: 		{
 1068: 		   $textid=~s/\.txt//;
 1069: 		}
 1070: 		elsif ($textid=$Tournament{'Number'})
 1071: 		  {
 1072: 		      $fname=~s/\.txt//;
 1073: 		      $textid="$fname.$textid";
 1074: 		  }
 1075: 	       else {$textid=$Tournament{'Id'}};
 1076: 		
 1077: 
 1078: 		if ($SingleTour or ($Tournament{'Type'} =~ /Т/)) {
 1079: 			$list .= dd(img({src=>$imgsrc, alt=>$alt})
 1080: 				. " " . $Tournament{'Title'} . " " .
 1081: 				    ($Tournament{'PlayedAt'}||"") . $qnum) .
 1082: 				dl(
 1083: 					dd("["
 1084: 						. a({href=>tourhref($textid,0)},
 1085: 						"вопросы") . "] ["
 1086:                   . a({href=>tourhref($textid,1)},
 1087:                   "вопросы + ответы") . "]")
 1088: 				);
 1089: 		} else {
 1090: 			$list .= dd(#a({href=>
 1091: #                                 $url . "?tour=$textid&comp=1"},
 1092: #				img({src=>'/icons/compressed.gif', alt=>'[ZIP]', border=>1}))				.  
 1093: 				" " . 
 1094:                                 img({src=>$imgsrc, alt=>$alt})
 1095: 				. " " . a({href=>tourhref($textid,0,1)},
 1096: 				$Tournament{'Title'}. " ".
 1097: 					  ($Tournament{'PlayedAt'}||'')) . $qnum); 
 1098: 		}
 1099: 	}
 1100: 	$output .= dl($list);
 1101: 
 1102: 	if ($URL) {
 1103: 	        if ($url=~/zaba\.ru/ && $URL=~/^\//){$URL="http://info.chgk.info$URL"}
 1104: 		$output .=
 1105: 		p("Дополнительная информация об этом турнире - по адресу " .
 1106: 			a({-'href'=>$URL}, $URL));
 1107: 	}
 1108: 
 1109: 	if ($Copyright) {
 1110: 		$output .= p("Копирайт: " .   $Copyright);
 1111: 	}
 1112: 
 1113: 
 1114: 
 1115: 	if ($Info) {
 1116: 		$output .= p($Info);
 1117: 	}
 1118: 	return $output;
 1119: }
 1120: 
 1121: sub Suffix {
 1122: 	my ($qnum) = @_;
 1123: 	my ($suffix) = 'а' if $qnum =~ /[234]$/;
 1124:    $suffix = '' if $qnum =~ /1$/;
 1125:    $suffix = 'ов' if $qnum =~ /[567890]$/ || $qnum =~ /1.$/;
 1126: 	return $suffix;
 1127: }
 1128: 
 1129: sub IsTour {
 1130: 	my ($dbh, $Id,$n) = @_;
 1131: 
 1132: 	my ($sth) ;
 1133:         
 1134:         if (defined $n) 
 1135:         { $sth=$dbh->prepare ("select Id FROM Tournaments
 1136:                            WHERE ParentId=$Id AND Number=$n");
 1137:         }
 1138:         else
 1139:         {
 1140:           $sth=$dbh->prepare("SELECT Id FROM Tournaments
 1141: 		WHERE Id=$Id");
 1142: 	}
 1143: 	$sth->execute;
 1144:         my $a=($sth->fetchrow)[0];
 1145: 	$sth->finish;
 1146:  	return $a;
 1147: }
 1148: 
 1149: # Gets a DB handler (ofcourse) and a tour Id. Prints all the
 1150: # question of that tour, according to the options.
 1151: sub PrintTour {
 1152: 	my ($dbh, $Id, $answer) = @_;
 1153: 	my ($output, $q, $bottom, $field) = ('', 0, '', '');
 1154: 
 1155: 	my (%Tour) = &GetTournament($dbh, $Id);
 1156: 	my (@Tours) = &GetTours($dbh, $Tour{'ParentId'});
 1157: 	my (%Tournament) = &GetTournament($dbh, $Tour{'ParentId'});
 1158: 	my %q;
 1159: 
 1160: 	return 0
 1161: 		if ($Tour{'Type'} !~ /Т/);
 1162: 
 1163: 	my ($fname)=$Tournament{'FileName'};
 1164: 	$fname=~s/\.txt//;
 1165: 	my ($qnum) = $Tour{'QuestionsNum'};
 1166: 	my ($suffix) = &Suffix($qnum);
 1167: 
 1168: 	$output .= h2({align=>"center"}, $Tournament{"Title"},
 1169: 		      $Tournament{'PlayedAt'}||'',
 1170: 		      "<br>", $Tour{"Title"} .
 1171: 		" ($qnum вопрос$suffix)\n") . p;
 1172: 	$output .=&PrintEditor(\%Tour);
 1173: 
 1174: 	my (@Questions) = &GetTourQuestions($dbh, $Id);
 1175: 	my $sth=SelectQuestions($dbh,\@Questions,0);
 1176: 	for ($q = 0; $q <= $#Questions; $q++) {
 1177: 		fetchquestion($sth,\%q,0);
 1178: 		$output .= &PrintQuestion($dbh, \%q, $answer, 0,0,0,1);
 1179: 	}
 1180: 	$sth->finish;
 1181: 	$output .= hr({-'align'=>'center', -'width'=>'80%'});
 1182: 
 1183: 	if ($Tournament{'URL'}) {
 1184: 		$output .=
 1185: 		p("Дополнительная информация об этом турнире - по адресу " .
 1186: 			a({-'href'=>$Tournament{'URL'}}, $Tournament{'URL'}));
 1187: 	}
 1188: 
 1189: 	if ($Tournament{'Copyright'}) {
 1190: 		$output .= p("Копирайт: " .   $Tournament{'Copyright'});
 1191: 	}
 1192: 
 1193: 	if ($Tournament{'Info'}) {
 1194: 		$output .= p($Tournament{'Info'});
 1195: 	}
 1196: 
 1197: 	my $n=$Tour{'Number'};
 1198: 	if ($answer == 0) {
 1199: 		$bottom .=
 1200: 			"[" . a({href=>tourhref("$fname.$n",1)}, 
 1201:                          "ответы") .  "] " . br;
 1202: 	}
 1203: 	if ($n>1) {
 1204: 		$bottom .=
 1205: 			"[" . a({href=>tourhref("$fname.".($n-1),0)},
 1206: 			"предыдущий тур") . "] ";
 1207: 		$bottom .=
 1208: 			"[" . a({href=>tourhref("$fname.".($n-1),1)},
 1209: 			"предыдущий тур с ответами") . "] " . br;
 1210: 	}
 1211: 	if (&IsTour($dbh, $Tour{'ParentId'}, $n + 1)) {
 1212: 		$bottom .=
 1213: 			"[" . a({href=>tourhref("$fname.".($n+1),0)},
 1214: 			"следующий тур") . "] ";
 1215: 		$bottom .=
 1216: 			"[" . a({href=>tourhref("$fname.".($n+1),1)},
 1217: 			"следующий тур с ответами") . "] ";
 1218: 	}
 1219: 
 1220: 	$output .=
 1221: 		p({align=>"center"}, font({size=>-1}, $bottom));
 1222: 
 1223: 	return $output;
 1224: }
 1225: 
 1226: sub PrintField {
 1227: 	my ($header, $value, $text) = @_;
 1228: 	if ($text) {
 1229: 	    $value =~ s/<[\/\w]*?>//sg;
 1230: 	} else {
 1231: 	    $value =~ s/^\s+/<br>&nbsp;&nbsp;&nbsp;&nbsp;/mg;
 1232: 	    $value =~ s/^\|([^\n]*)/<pre>$1<\/pre>/mg;
 1233: 	    $value =~ s/\s+-+\s+/&nbsp;&#0150; /mg;
 1234: 	    $value =~ s/(http:\/\/\S+[^\s\)\(\,\.])/<a href="$1">$1<\/a>/g if $header !~ /^Авто/;
 1235: #	    $value =~ s/(http:\/\/(?:\w+.)+[\w\\\~]+(\?[^\s.]+)?)/<a href="$1">$1<\/a>/g if $header !~ /^Авто/;
 1236: #	    $value =~ s/(\s)"/$1&#147;/mg;
 1237: #	    $value =~ s/^"/&#147;/mg;
 1238: #	    $value =~ s/"/&#148;/mg;
 1239: 	}
 1240: 
 1241: 
 1242: 	return $text ? "$header:\n$value\n\n" :
 1243: 		strong("$header: ") . $value . p . "\n";
 1244: }
 1245: 
 1246: # Gets a DB handler (ofcourse) and a question Id. Prints
 1247: # that question, according to the options.
 1248: sub PrintQuestion {
 1249: 	my ($dbh, $Id, $answer, $qnum, $title, $text,$h) = @_;
 1250: 	my ($output, $titles) = ('', '');
 1251: 	my (%Question);
 1252: 	if ($h) {
 1253: 	  %Question=%$Id;
 1254: 	} else {
 1255: 		%Question = &GetQuestion($dbh, $Id);
 1256: 		if ($title) {
 1257: 			my (%Tour) = GetTournament($dbh, $Question{'ParentId'});
 1258: 			my (%Tournament) = GetTournament($dbh, $Tour{'ParentId'});
 1259: 			$Question{'FileName'}=$Tournament{'FileName'};
 1260: 			$Question{'Title'}=$Tournament{'Title'};
 1261: 			$Question{'PlayedAt'}=$Tournament{'PlayedAt'};
 1262: 			$Question{'TourNumber'}=$Tour{'Number'};
 1263: 			$Question{'TourTitle'}=$Tour{'Title'};
 1264: 		}
 1265: 
 1266:         }
 1267: 		$qnum = $Question{'Number'}
 1268: 		if ($qnum == 0);
 1269: 	if (!$text) {
 1270: 		$output .= hr({width=>"50%"}) if $answer>=0;
 1271: 		if ($title) {
 1272: 			my $fname=$Question{'FileName'};
 1273: 			$fname=~s/\.txt//;
 1274: 			$titles .=
 1275: 				dd(img({src=>"/icons/folder.open.gif"}) . " " .
 1276: 					 a({href=>tourhref($fname,0,1)}, 
 1277:                                $Question{'Title'}, $Question{'PlayedAt'}||''));
 1278: 			$titles .=
 1279: 				dl(dd(img({src=>"/icons/folder.open.gif"}) . " " .
 1280: 					a({href=>tourhref("$fname.$Question{'TourNumber'}#$qnum",1)}, 
 1281:                           $Question{'TourTitle'})));
 1282: 		}
 1283: 		$output .= dl(strong($titles));
 1284: 	}
 1285: 
 1286: 
 1287: 	$output.= "<a NAME=\"$qnum\">" unless $text;
 1288: 
 1289: 	if ($answer>=0) {$output .=
 1290: 		&PrintField("Вопрос $qnum", $Question{'Question'}, $text);}
 1291: 	else {$output .="$qnum. "}
 1292: 	if ($answer==1|| $answer==-1) {
 1293: 		$output .=
 1294: 			&PrintField("Ответ", $Question{'Answer'}, $text);
 1295: 
 1296: 		if ($Question{'Authors'} ) {
 1297:                       my $q=$Question{'Authors'};
 1298: ###АВТОРА!!
 1299: # 		      my $sth=$dbh->prepare("select Authors.CharId,Name, Surname, Nicks from Authors, A2Q
 1300: #                                  where Authors.Id=Author And Question=$Id");
 1301: #                       $sth->execute;
 1302: #                       my ($AuthorId,$Name, $Surname,$other,$Nicks);
 1303: #                      if (!$text) {
 1304: #                       while ((($AuthorId,$Name, $Surname,$Nicks)=$sth->fetchrow),$AuthorId)
 1305: #                       {
 1306: #                          my ($firstletter)=$Name=~m/^./g;
 1307: #                          $Name=~s/\./\\\./g;
 1308: #                          $Name=~s/ё/[её]/g;
 1309: #                          $Surname=~s/ё/[её]/g;
 1310: #                           my $sha="(?:$Name\\s+$Surname)|(?:$Surname\\s+$Name)|(?:$firstletter\\.\\s*$Surname)|(?:$Surname\\s+$firstletter\\.)|(?:$Surname)";
 1311: #                           if ($Nicks)
 1312: #                           {
 1313: #                             $Nicks=~s/^\|//;
 1314: #                             foreach (split /\|/, $Nicks)
 1315: #                             {
 1316: #                               s/\s+/ /g;
 1317: #                               s/\s+$//;
 1318: #                               s/ /\\s+/g;
 1319: #                               s/\./\\\./g;
 1320: #                               if (s/>$//) {$sha="$sha|(?:$_)"}
 1321: #                               else        {$sha="(?:$_)|$sha"}
 1322: #                             }
 1323: #                           }
 1324: #                           $q=~s/($sha)/a({href=>url."?qofauthor=$AuthorId"},$1)/ei;
 1325: #                           unless ($1) 
 1326: #                             {   
 1327: #                                 $q=~s/$Name/a({href=>url."?qofauthor=$AuthorId"},$1)/ei;
 1328: #                             }
 1329: #                       }
 1330: #                      }
 1331: 			$output .= &PrintField("Автор(ы)", $q, $text);
 1332: 
 1333: 		}
 1334: 
 1335: 		if ($Question{'Sources'}) {
 1336: 			$output .= &PrintField("Источник(и)", $Question{'Sources'}, $text);
 1337: 		}
 1338: 
 1339: 		if ($Question{'Comments'}) {
 1340: 			$output .= &PrintField("Комментарии", $Question{'Comments'}, $text);
 1341: 		}
 1342: 	}
 1343: 	elsif ($answer==2) {
 1344: 	  my $text=$Question{'Answer'};
 1345: 	  $text=~s/\n/<option>/mg;
 1346: 	  $output.="<select><option selected>Ответ:<option>$text</select>";
 1347: 	  $text=$Question{'Comments'}||'';
 1348: 	  if ($text) {
 1349:              $text=~s/\n/<option>/mg;
 1350: 	     $output.="<select><option selected>Комментарий:<option>$text</select>"
 1351: 	  }
 1352: 	} 
 1353: 	elsif ($answer==3) {
 1354:         $output.=  <<EOTT
 1355: 	  <div align=right STYLE="cursor:hand;" OnStart="toggle(document.all.HideShow$qnum);" OnClick="toggle(document.all.HideShow$qnum);">
 1356: 	  <font size=-2 color=red> Показать/убрать ответ</font></div>
 1357: 	  <span style="display:none" id=HideShow$qnum>
 1358: EOTT
 1359:           .&PrintField("Ответ", $Question{'Answer'}, $text);
 1360: 		if ($Question{'Authors'}) {
 1361: 			$output .= &PrintField("Автор(ы)", $Question{'Authors'}, $text);
 1362: 		}
 1363: 		if ($Question{'Sources'}) {
 1364: 			$output .= &PrintField("Источник(и)", $Question{'Sources'}, $text);
 1365: 		}
 1366: 
 1367: 		if ($Question{'Comments'}) {
 1368: 			$output .= &PrintField("Комментарии", $Question{'Comments'}, $text);
 1369: 		}
 1370: 
 1371: 
 1372: 
 1373: $output.="</span>"
 1374: 
 1375: 	}
 1376: 	$output=~s/\(pic: ([^\)]*)\)/<p><img src="\/znatoki\/images\/db\/$1"><p>/g unless $text;
 1377: 	$paramtour||=param("tour");
 1378: 	my $qid=$paramtour ? ($paramtour.".$Question{'Number'}" ): '';
 1379: 
 1380: 	$output.=br.a({href=> $url."?metod=proxy&
 1381: qid=$qid"}, 'Близкие вопросы').p
 1382:              if $answer>0 && !$text && $qid;
 1383: 	return $output;
 1384: }
 1385: 
 1386: # Returns the total number of questions currently in the DB.
 1387: sub GetQNum {
 1388: 	my ($dbh) = @_;
 1389: 	my ($sth) = $dbh->prepare("SELECT COUNT(*) FROM Questions");
 1390: 	$sth->execute;
 1391: 	my $tmp=($sth->fetchrow)[0];
 1392:         $sth->finish;
 1393:  	return $tmp;
 1394: }
 1395: sub GetMaxQId {
 1396: 	my ($dbh) = @_;
 1397: 	my ($sth) = $dbh->prepare("SELECT MAX(QuestionId) FROM Questions");
 1398: 	$sth->execute;
 1399: 	my $tmp=($sth->fetchrow)[0];
 1400:         $sth->finish;
 1401:  	return $tmp;
 1402: 
 1403: }
 1404: 
 1405: # Returns Id's of 12 random questions
 1406: sub Get12Random {
 1407:    my ($dbh, $type, $num) = @_;
 1408: 	my ($i, @questions, $q, $t, $sth);
 1409: 	my ($qnum) = &GetMaxQId($dbh);
 1410: 	my (%chosen);
 1411: 	srand;
 1412: 	my $where=0;
 1413: 	my $r=int (rand(10000));
 1414: 
 1415: 	foreach (split '', $type)
 1416:         {
 1417:  	   $where.= " OR (Type ='$_') OR (Type ='$_Д') ";
 1418:  	}
 1419:         $where.= "OR (Type='ЧБ')" if ($type=~/Ч|Б/);
 1420: 
 1421: #   $q="select QuestionId, QuestionId/$r-floor(QuestionId/$r) as val 
 1422: #       from Questions where $where order by val limit $num";
 1423: # Когда на куличках появится mysql >=3.23 надо заменить на order by rand();
 1424:    $q="select QuestionId from Questions where $where order by rand() limit $num";
 1425: 
 1426: 
 1427:    $sth=$dbh->prepare($q);
 1428:    $sth->execute;
 1429:    while (($i)=$sth->fetchrow)
 1430:    {
 1431:       push @questions,$i;
 1432:    }
 1433:    $sth->finish;
 1434:     for ($i=@questions; --$i;){ 
 1435:        my $j=rand ($i+1); 
 1436:        @questions[$i,$j]=@questions[$j,$i] unless $i==$j;
 1437:     }
 1438:    return @questions;
 1439: }
 1440: 
 1441: sub Include_virtual {
 1442: 	my ($fn, $output) = (@_, '');
 1443: 	return "<!--#include virtual=\"$fn\"-->" if ($opt_z);
 1444: 	open F , $fn
 1445: 		or return ""; #die "Can't open the file $fn: $!\n";
 1446: 
 1447: 	while (<F>) {
 1448: 		if (/<!--#include/o) {
 1449: 			s/<!--#include virtual="\/(.*)" -->/&Include_virtual($1)/e;
 1450: 		}
 1451: 		if (/<!--#exec/o) {
 1452: 			s/<!--#exec.*cmd\s*=\s*"([^"]*)".*-->/`$1`/e;
 1453: 		}
 1454: 		$output .= $_;
 1455: 	}
 1456: 	return $output||"";
 1457: }
 1458: 
 1459: sub PrintArchive {
 1460: 	my($dbh, $Id) = @_;
 1461: 	my ($output, @list, $i);
 1462: 
 1463: 	my (%Tournament) = &GetTournament($dbh, $Id);
 1464: 	my (@Tours) = &GetTours($dbh, $Id);
 1465: 	if ($Tournament{'Type'} =~ /Г/ || $Id == 0) {
 1466: 		for ($i = 0; $i <= $#Tours; $i++) {
 1467: 			push(@list ,&PrintArchive($dbh, $Tours[$i]));
 1468: 		}
 1469: 		return @list;
 1470: 	}
 1471: #	return "$SRCPATH/$Tournament{'FileName'} ";
 1472: 	return "$TMPDIR/$Tournament{'FileName'} ";
 1473: }
 1474: 
 1475: sub PrintAll {
 1476: 	my ($dbh, $Id,$fname) = @_;
 1477: 	my ($output, $list, $i);
 1478: 
 1479: 	my (%Tournament) = &GetTournament($dbh, $Id);
 1480: 	my (@Tours) = &GetTours($dbh, $Id);
 1481: 	my $SingleTour = $#Tours == 0;
 1482: 
 1483: 	my ($New) = ($Id and $Tournament{'Type'} eq 'Ч' and
 1484: 		&NewEnough($Tournament{"CreatedAt"})) ?
 1485: 		img({src=>"/znatoki/dimrub/db/new-sml.gif", alt=>"NEW!"}) : "";
 1486: 
 1487: 	if ($Id == 0) {
 1488: 		$output = h3("Все турниры");
 1489: 	} else {
 1490: 	         my $textid;
 1491: 		 if ($textid=$Tournament{'FileName'})
 1492: 		 {
 1493: 		   $textid=~s/\.txt//;
 1494: 		 }
 1495: 		 elsif ($textid=$Tournament{'Number'})
 1496: 		 {
 1497: 		      $fname=~s/\.txt//;
 1498: 		      $textid="$fname.$textid";
 1499: 		 }
 1500: 	         else {$textid=$Tournament{'Id'}};
 1501: 
 1502: 
 1503: 		$output .= dd(img({src=>"/icons/folder.gif", alt=>"[*]"}) .
 1504:       " " . a({href=>tourhref($textid,0,!$SingleTour)},
 1505:       $Tournament{'Title'}) ." " . ($Tournament{'PlayedAt'}||'') . " $New");
 1506: 	}
 1507: 	if ($Id == 0 or $Tournament{'Type'} =~ /Г/ or $Tournament{'Type'} eq '') {
 1508: 		for ($i = 0; $i <= $#Tours; $i++) {
 1509: 			$list .= &PrintAll($dbh, $Tours[$i],$Tournament{'FileName'});
 1510: 		}
 1511: 		$output .= dl($list);
 1512: 	}
 1513: 	return $output;
 1514: }
 1515: 
 1516: sub PrintDates {
 1517: 	my ($dbh) = @_;
 1518: 	my ($from) = param('from_year') . "-" . param('from_month') .
 1519: 		"-" .  param('from_day');
 1520: 	my ($to) = param('to_year') . "-" . param('to_month') . "-" .  param('to_day');
 1521: 	$from = $dbh->quote($from);
 1522: 	$to = $dbh->quote($to);
 1523: 	my ($sth) = $dbh->prepare("
 1524: 		SELECT DISTINCT Id
 1525: 		FROM Tournaments
 1526: 		WHERE PlayedAt >= $from AND PlayedAt <= $to
 1527: 		AND Type = 'Ч'
 1528: 	");
 1529: 	$sth->execute;
 1530: 	my (%Tournament, @array, $output, $list);
 1531: 
 1532: 	$output = h3("Список турниров, проходивших между $from и $to.");
 1533: 	while (@array = $sth->fetchrow) {
 1534: 		next
 1535: 			if (!$array[0]);
 1536: 		%Tournament = &GetTournament($dbh, $array[0]);
 1537:       $list .= dd(img({src=>"/icons/folder.gif", alt=>"[*]"}) .
 1538:       " " . a({href=>tourhref($Tournament{'FileName'},0,1)},
 1539:       $Tournament{'Title'}, $Tournament{'PlayedAt'}||''));
 1540: 	}
 1541:         $sth->finish;
 1542: 	$output .= dl($list);
 1543: 	return $output;
 1544: }
 1545: 
 1546: sub PrintQOfAuthor
 1547: {
 1548: 
 1549:     my ($dbh, $id) = @_;
 1550:     my $Output='';
 1551:     unless ($id=~/^\d+$/) {
 1552:       $id=$dbh->quote($id);
 1553:       my $sth =  $dbh->prepare("SELECT Id FROM Authors WHERE CharId=$id");
 1554:       $sth->execute;
 1555:       ($id)=$sth->fetchrow;
 1556:       $sth->finish;
 1557:     }
 1558:     $id=$dbh->quote($id);
 1559: 
 1560:     my $sth =  $dbh->prepare("SELECT  Name, Surname FROM Authors WHERE Id=$id");
 1561:     $sth->execute;
 1562:     my ($name,$surname)=$sth->fetchrow;
 1563: 
 1564:     $sth =  $dbh->prepare("SELECT Question FROM A2Q WHERE Author=$id");
 1565:     $sth->execute;
 1566:     my $q;
 1567:     my @Questions;
 1568:     while (($q)=$sth->fetchrow,$q)
 1569:      {push @Questions,$q unless $forbidden{$q}}
 1570:     $sth->finish;
 1571: 
 1572:     my ($output, $i, $suffix, $hits) = ('', 0, '', $#Questions + 1);
 1573: 
 1574:     if ($hits =~ /1.$/  || $hits =~ /[5-90]$/) {
 1575: 		$suffix = 'й';
 1576: 	} elsif ($hits =~ /1$/) {
 1577: 		$suffix = 'е';
 1578: 	} else {
 1579: 		$suffix = 'я';
 1580: 	}
 1581: 	$Output.= printform;
 1582: 	$Output.= p({align=>"center"}, "Автор ".strong("$name $surname. ")
 1583: 	. " : $hits попадани$suffix.");
 1584: 
 1585: 
 1586: #	for ($i = 0; $i <= $#Questions; $i++) {
 1587: #		$output = &PrintQuestion($dbh, $Questions[$i], 1, $i + 1, 1);
 1588: #		print $output;
 1589: #	}
 1590:         $Output.=PrintList($dbh,\@Questions,'gdfgdfgdfgdfg');
 1591: }
 1592: 
 1593: 
 1594: sub PrintAuthors
 1595: {
 1596:      my ($dbh,$sort)=@_;
 1597:      my($output,$out1,@array,$sth);
 1598:      if ($sort eq 'surname')
 1599:      {
 1600:         $sth =
 1601:              $dbh->prepare("SELECT Id, Name, Surname, QNumber FROM Authors order by Surname, Name");
 1602:      }
 1603:      elsif($sort eq 'name')
 1604:      {
 1605:         $sth =
 1606:              $dbh->prepare("SELECT Id, Name, Surname, QNumber FROM Authors order by Name, Surname");
 1607:      }
 1608:      else
 1609:      {
 1610:         $sth =
 1611:              $dbh->prepare("SELECT Id, Name, Surname, QNumber FROM Authors Order by QNumber DESC, Surname");
 1612:      }
 1613: 
 1614:      $output.=h2("Авторы вопросов")."\n";
 1615:      $output.="<TABLE>";
 1616: 
 1617: 
 1618:      $sth->execute;
 1619:      $output.=Tr(th[a({href=>$url."?authors=name"},"Имя")
 1620: .", ".
 1621: a({href=>$url."?authors=surname"},"фамилия")
 1622:      , a({href=>$url."?authors=kvo"},"Количество вопросов")]);
 1623: 
 1624:      $out1='';
 1625: 
 1626:      my $ar=$sth->fetchall_arrayref;
 1627: 
 1628:      $sth->finish;
 1629: 
 1630: 
 1631:     foreach my $arr(@$ar)
 1632:      {
 1633: 
 1634:            my ($id,$name,$surname,$kvo)=@$arr;
 1635:            if (!$name || !$surname) {
 1636:               } else
 1637:            {
 1638:              my $add=Tr(td([a({href=>$url."?qofauthor=$id"},"$name $surname"), $kvo]))."\n";
 1639:              $output.=$add;
 1640:            }
 1641:      }
 1642:      $output.="</TABLE>";
 1643:      $sth->finish;
 1644:      return $output;
 1645: }
 1646: 
 1647: 
 1648: sub WriteFile {
 1649:   my ($dbh,$fname) = @_;
 1650:   $fname=~s/\s+$//;
 1651:   $fname=~s/^\s+//;
 1652:   $fname=~s/\.txt$//;
 1653:   $fname=~s/.*\/(\w+)/$1/;
 1654: 
 1655:   my $query= "SELECT Id, Title, Copyright, Info, URL, 
 1656:                       Editors, EnteredBy, PlayedAt, CreatedAt 
 1657:                      from Tournaments where FileName=
 1658:                      '$fname' OR FileName=".$dbh->quote("$fname.txt");
 1659:   my $sth=$dbh->prepare($query);
 1660:   my (%Question,%editor,%qnumber,%copyright,%author,%vid,%tourtitle);
 1661:   $sth->execute;
 1662:   my ($Id, $Title, $Copyright, $Info, $URL, 
 1663:    $Editors, $EnteredBy, $PlayedAt, $CreatedAt)=
 1664:       $sth->fetchrow;
 1665:   return -1 unless $Id;
 1666:   open (OUT, ">$TMPDIR/$fname.txt") || print STDERR "Error in $fname.txt\n";
 1667:   print OUT "Чемпионат:\n$Title\n\n";
 1668:   my $date=$PlayedAt||'00-00-00';
 1669:   my ($year,$month,$day)=split /-/, $date;
 1670: #  $month=0,$date=0 if $year && $month==1 && $day==1;
 1671:   my $pdate=sprintf("%02d-%3s-%4d",$day,$months[$month],$year);
 1672: 
 1673:   print OUT "Дата:\n$pdate\n\n" if $date;
 1674: 
 1675:   print OUT "URL:\n$URL\n\n" if $URL;
 1676: 
 1677:   print OUT "Инфо:\n$Info\n\n" if $Info;
 1678: 
 1679:   print OUT "Копирайт:\n$Copyright\n\n" if $Copyright;
 1680: 
 1681:   print OUT "Редактор:\n$Editors\n\n" if $Editors;
 1682: 
 1683: 
 1684:   $query= "SELECT Id, Title, Copyright, Editors from Tournaments where ParentId=$Id order by Id";
 1685:   $sth=$dbh->prepare($query);
 1686:   $sth->execute;
 1687:   my ($tourid,$tourtitle,$cright,$editor,@tours,$vid,$author,$tourauthor);
 1688: 
 1689: 
 1690:   while (($tourid,$tourtitle,$cright,$editor)=$sth->fetchrow,$tourid)
 1691:   {
 1692: #    $text{$tourid}="Тур:\n$tourtitle\n\n";
 1693:     $query= "SELECT * from Questions where ParentId=$tourid order by QuestionId";
 1694:     my $sth1=$dbh->prepare($query);
 1695:     $sth1->execute;
 1696:     push(@tours,$tourid);
 1697:     $tourtitle{$tourid}=$tourtitle;
 1698:     $copyright{$tourid}=$cright;
 1699:     $editor{$tourid}=$editor;
 1700:     $vid='';
 1701:     my $author='';
 1702:     my $eqauthor=1;
 1703:     my $qnumber=0;
 1704:     my @arr;
 1705:     while ( (@arr=$sth1->fetchrow), $arr[0])
 1706:     {
 1707: 	my($i, $name);
 1708: 	$i=0;
 1709: 	$qnumber++;
 1710: 	foreach $name (@{$sth1->{NAME}}) {
 1711: 	        if ($arr[$i]) {
 1712:   	           $arr[$i]=~s/^(.*?)\s*$/$1/;
 1713: 		   $Question{$tourid}[$qnumber]{$name} = $arr[$i];
 1714: 		} else {
 1715:   	            $Question{$tourid}[$qnumber]{$name} = 
 1716:                    ''}
 1717:                 $i++;
 1718: 	}
 1719: 	if ($vid)
 1720:         {
 1721:           if ($vid ne $Question{$tourid}[$qnumber]{'Type'}) {print STDERR "Warning: Different types for Tournament $tourid\n"}
 1722:         } else 
 1723:         {
 1724:             $vid=$Question{$tourid}[$qnumber]{'Type'};
 1725:         } 
 1726: 
 1727: 	if ($author)
 1728:         {
 1729:           if ($author ne $Question{$tourid}[$qnumber]{'Authors'})  
 1730:           {
 1731:              $eqauthor=0;
 1732:           }
 1733:         } else 
 1734:         {
 1735:             $author=$Question{$tourid}[$qnumber]{'Authors'};
 1736:             $eqauthor=0 unless $author;
 1737:         } 
 1738:     }
 1739:     $vid{$tourid}=$vid;
 1740:     $qnumber{$tourid}=$qnumber;
 1741:     $author{$tourid}=$eqauthor ? $author : '';
 1742:   }
 1743: 
 1744: 
 1745:   $vid='';
 1746:   my $eqvid=1;
 1747:   my $eqauthor=1;
 1748:   foreach (@tours)
 1749:   {
 1750:      $vid||=$vid{$_};
 1751:      if ($vid{$_} ne $vid)
 1752:      {
 1753:         $eqvid=0;
 1754:      }
 1755:      $author||=$author{$_};
 1756:      if (!$author{$_} || ($author{$_} ne $author))
 1757:      {
 1758:         $eqauthor=0;
 1759:      }
 1760:   }
 1761:   
 1762:   print OUT "Вид:\n$vid\n\n" if $eqvid;
 1763:   print OUT "Автор:\n$author\n\n" if $eqauthor;
 1764: 
 1765:   foreach my $tour(@tours)
 1766:   {
 1767:      print OUT "Тур:\n$tourtitle{$tour}\n\n";
 1768:      print OUT "Вид:\n$vid{$tour}\n\n" if  !$eqvid;
 1769:      print OUT "Копирайт:\n$copyright{$tour}\n\n" if $copyright{$tour} && ($copyright{$tour} ne $Copyright);
 1770:      print OUT "Редактор:\n$editor{$tour}\n\n" if $editor{$tour} && ($editor{$tour} ne $Editors);
 1771:      $tourauthor=0;
 1772:      if (!$eqauthor && $author{$tour})
 1773:      { 
 1774:        print OUT "Автор:\n$author{$tour}\n\n";
 1775:        $tourauthor=1;
 1776:      }
 1777:      foreach my $q(1..$qnumber{$tour})
 1778:      {
 1779:         print OUT "Вопрос $q:\n".$Question{$tour}[$q]{'Question'}."\n\n";
 1780: 	print OUT  "Ответ:\n".$Question{$tour}[$q]{'Answer'}."\n\n";
 1781: 	print OUT  "Автор:\n".$Question{$tour}[$q]{'Authors'}."\n\n" 
 1782:                if !$tourauthor && !$eqauthor && $Question{$tour}[$q]{'Authors'};
 1783: 	print OUT  "Комментарий:\n".$Question{$tour}[$q]{'Comments'}."\n\n" 
 1784:                if $Question{$tour}[$q]{'Comments'};
 1785: 	print OUT "Источник:\n".$Question{$tour}[$q]{'Sources'}."\n\n" 
 1786:                if $Question{$tour}[$q]{'Sources'};
 1787: 	print OUT "Рейтинг:\n".$Question{$tour}[$q]{'Rating'}."\n\n" 
 1788:                if $Question{$tour}[$q]{'Rating'};
 1789: 
 1790:      }
 1791:   }
 1792: 
 1793:   close OUT;
 1794: 
 1795: 
 1796: 
 1797: }
 1798: 
 1799: sub Bottom
 1800: {
 1801: 	my $output.=&Include_virtual("$footer")||"";
 1802: 	$output.=p."<center><font size=-2>Обновление: ".&Include_virtual("$datefooter")."</center></font>";
 1803: 	$output.=<<EEE
 1804: <SCRIPT LANGUAGE="JavaScript">
 1805: function toggle(e) {
 1806:   if (e.style.display == "none") {
 1807:      e.style.display="";
 1808:   } else {
 1809:      e.style.display = "none";
 1810:  }
 1811: }
 1812: </SCRIPT>
 1813: EEE
 1814: ;
 1815: 	$output.=end_html;
 1816: 	return $output;
 1817: }
 1818: 
 1819: 
 1820: MAIN:
 1821: {
 1822:         
 1823: 	setlocale(LC_CTYPE,'russian');
 1824: 	POSIX::setlocale( &POSIX::LC_ALL, $thislocale );
 1825: 	my($i, $tour);
 1826: 	my($text) = (param('text')) ? 1 : 0;
 1827: 	if (param('qid') && (param('qid')=~/^\d+$/)) {
 1828: 	   my $destination='http://db.chgk.info/search.html';
 1829: #		print header (-'Content-Type' => 'text/html',
 1830: #                -'Location:'=> 'http:\\db.chgk.info');
 1831: 		Redirect($destination);
 1832:                 exit
 1833: 	}
 1834: 
 1835: 	if ($text) {
 1836: 		print header('text/plain');
 1837: 	} else {print header;}
 1838: 	my($dbh) = DBI->connect("DBI:mysql:chgk", "piataev", "")
 1839: 		or do {
 1840: 			print h1("Временные проблемы") . "База вопросов временно не
 1841: 			работает. Заходите попозже.";
 1842: 			print &Include_virtual("$reklama") if $url!~/localhost/;
 1843: 		    print end_html;
 1844: 			die "Can't connect to DB chgk\n";
 1845: 		};
 1846: 	  my $sstr=param('sstr');
 1847:           $opt_z||=param("makehtml");
 1848: 	  if (param('qid')) {
 1849: 	      my $sth;
 1850: 	      my $qid=param('qid');
 1851: #		if ($qid !~ /^[0-9]+$/) 
 1852:                 {
 1853:                     my ($fname,$t,$n)= split /\./ , $qid;
 1854:                     $n=$t,$t='' unless $n;
 1855:                     $t||=1;
 1856: 		    if ($t)
 1857: 		    {
 1858: 	                $sth = $dbh->prepare(
 1859:                        "SELECT t2.Id FROM Tournaments as t1, 
 1860:                         Tournaments as t2 
 1861: 			WHERE (t1.FileName = '$fname.txt' OR t1.FileName='$fname')
 1862:                         AND t1.Id=t2.ParentId AND t2.Number=$t");
 1863: 		    }	
 1864: #		    else 
 1865: #		        {
 1866: #                          $sth = $dbh->prepare("SELECT Id FROM Tournaments
 1867: #			             WHERE FileName = '$fname.txt' OR FileName = '$fname'" );
 1868: #			}
 1869: 		    $sth->execute;
 1870: 	            $tour = ($sth->fetchrow)[0];
 1871:                     $sth->finish;
 1872: 	            $sth = $dbh->prepare(
 1873:                        "SELECT QuestionId FROM 
 1874:                         Questions 
 1875: 			WHERE ParentId=$tour AND 
 1876:                         Questions.Number=$n");
 1877: 		        $sth->execute;
 1878: 	                $qid = ($sth->fetchrow)[0];
 1879:               	     my $query="SELECT Question, Answer from Questions where QuestionId=$qid";
 1880: 	      	     $sth=$dbh->prepare($query);
 1881: 	      	     $sth->execute;
 1882: 	      	     $sstr= join ' ',$sth->fetchrow;
 1883:               	     $sth->finish;
 1884: 	      	     $searchin{'Question'}=1;
 1885: 	      	     $searchin{'Answer'}=1;
 1886:               	     $sstr=~tr/ёЁ/еЕ/;
 1887:               	     $sstr=~s/[^йцукенгшщзхъфывапролджэячсмитьбюЙЦУКЕНГШЩЗХЪФЫВАПРОЛДЖЭЯЧСМИТЬБЮa-zA-Z0-9]/ /gi;
 1888:               	     $proxysstr=$sstr;
 1889:               	     $proxysstr=makeproxysstr($dbh,\$proxysstr);
 1890:               } 
 1891:               
 1892:  	}
 1893: 
 1894: 
 1895: 	if (!param('comp') and !param('sqldump') and !$text) {
 1896: 	   my $title="Результаты поиска на \"". ($proxysstr||$sstr) .'"' 
 1897:                                                     if ($proxysstr||$sstr);
 1898:            $title||="База вопросов";
 1899: 
 1900: 	   $globaloutput.=start_html(-"title"=>$title,
 1901: 	           -author=>'dimrub@icomverse.com',
 1902: 	           -bgcolor=>'#fff0e0',
 1903: 				  -vlink=>'#800020');
 1904: $globaloutput.="<style>
 1905: td	{font-size: x-small; font-family : sans-serif}
 1906: th	{font-size: x-small; font-family : sans-serif}
 1907: </style>\n";
 1908: 
 1909: 		$globaloutput.=&Include_virtual("$reklama")||'';
 1910: 	}
 1911: 
 1912:        if (!$opt_z && length ($qs)<=255 && $qs !~ /(sstr)|(rand)|(comp)|(all=)/i) {
 1913:         	my $sth=$dbh->prepare("SELECT page,times,t from hash where query=".$dbh->quote($qs));
 1914:         	$sth->execute();
 1915:         	my ($p,$times,$t)=$sth->fetchrow();
 1916:         	$sth->finish;
 1917:         	if ($p) {
 1918: 			print ".$p";
 1919: 			$dbh->disconnect;
 1920: 			exit ;
 1921: 		}
 1922:        }
 1923: 
 1924: 
 1925: 
 1926: 
 1927:         if (param('hideequal')) {
 1928: 	           my ($sth)=  $dbh -> prepare("select first, second FROM equalto");
 1929: 	           $sth -> execute;
 1930: 	           while ( my  ($first, $second)=$sth -> fetchrow)
 1931:                   {
 1932:                        $forbidden{$first}=1;
 1933:                   }
 1934:                   $sth->finish;
 1935:         }
 1936: 		$tour = (param('tour')) ? param('tour') : 0;
 1937: 		my $sth;
 1938: 		if ($tour !~ /^[0-9]*$/) {
 1939: 		    if ($tour=~/\./)
 1940: 		    {
 1941: 		        my ($fname,$n)= split /\./ , $tour;
 1942: 
 1943: 	                $sth = $dbh->prepare(
 1944:                        "SELECT t2.Id FROM Tournaments as t1, 
 1945:                         Tournaments as t2 
 1946: 			WHERE (t1.FileName = '$fname.txt' OR t1.FileName='$fname')
 1947:                         AND t1.Id=t2.ParentId AND t2.Number=$n");
 1948: 		    }	
 1949: 		    else 
 1950: 		        {
 1951:                           $sth = $dbh->prepare("SELECT Id FROM Tournaments
 1952: 			             WHERE FileName = '$tour.txt' OR 
 1953:                                        FileName = '$tour'");
 1954: 			}
 1955: 		    $sth->execute;
 1956: 	            $tour = ($sth->fetchrow)[0];
 1957:                     $sth->finish;
 1958: 		}
 1959: 
 1960: 
 1961: 	if (param('rand')) {
 1962: 		my ($type, $qnum) = ('', 12);
 1963: 		$type.=$TypeName{$_} foreach param('type');
 1964: #		$type .= 'Б' if (param('brain'));
 1965: #		$type .= 'Ч' if (param('chgk'));
 1966: 		$qnum = param('qnum') if (param('qnum') =~ /^\d+$/);
 1967: 		$qnum = 0 if (!$type);
 1968: 		my $Email;
 1969: 		if (($Email=param('email')) && -x $SENDMAIL &&
 1970: 		open(F, "| $SENDMAIL $Email")) {
 1971: 			my ($mime_type) = $text ? "plain" : "html";
 1972: 			print F <<EOT;
 1973: To: $Email
 1974: From: olegstepanov\@mail.ru
 1975: Subject: Sluchajnij Paket Voprosov "Chto? Gde? Kogda?"
 1976: MIME-Version: 1.0
 1977: Content-type: text/$mime_type; charset="koi8-r"
 1978: 
 1979: EOT
 1980: 			print F &PrintRandom($dbh, $type, $qnum, $text);
 1981: 			close F;
 1982: 			$globaloutput.= "Пакет случайно выбранных вопросов послан по адресу $Email. Нажмите
 1983: 			на <B>Reload</B> для получения еще одного пакета";
 1984: 		} else {
 1985: 			$globaloutput.= &PrintRandom($dbh, $type, $qnum, $text);
 1986: 		}
 1987: 	}
 1988: 	  elsif (param('authors')){
 1989:                 $globaloutput.= &PrintAuthors($dbh,param('authors'));
 1990:         }
 1991:           elsif (param('qofauthor')){
 1992:                 $globaloutput.= &PrintQOfAuthor($dbh,param('qofauthor'));
 1993:         }
 1994:           elsif (param('sstr')||param('was')) {
 1995: 		$globaloutput.=&PrintSearch($dbh, $sstr||' ', param('metod')||'',param('was'));
 1996: 		$dbh->do("delete from lastqueries where
 1997:                       (TO_DAYS(NOW()) - TO_DAYS(t) >= 2) OR
 1998: 		           (time_to_sec(now())-time_to_sec(t) >3600)") if $usewas && random(30)==0;
 1999: 	} 
 2000: 	  elsif (param('qid')) {
 2001:  	      $globaloutput.=&PrintSearch($dbh, $sstr||'', 'proxy');
 2002:  	}
 2003:  	elsif (param('getfile')){
 2004:            $globaloutput.=&writefile
 2005:  	} elsif (param('all')) {
 2006: 	   my $destination='http://db.chgk.info/all.html';
 2007: 		Redirect($destination);
 2008:                 exit;
 2009: #		$globaloutput.=&PrintAll($dbh, 0);
 2010: 	} elsif (param('from_year') && param('to_year')) {
 2011: 		$globaloutput.=&PrintDates($dbh);
 2012: 	} elsif (param('comp')) {
 2013:             $globaloutput.="Content-Type: application/octet-stream\n";
 2014:             $globaloutput.="Content-Type: application/force-download\n";
 2015:             $globaloutput.="Content-Type: application/download\n";
 2016:             $globaloutput.="Content-Type: application/x-zip-compressed; name=db.zip\n";
 2017:             $globaloutput.="Content-Disposition: attachment; filename=db.zip \n\n";
 2018: 	    $tour ||= 0;
 2019: 	    my (@files) = &PrintArchive($dbh, $tour);
 2020: 	    WriteFile($dbh,$_) foreach @files;
 2021: 	    open F, "$ZIP -j - @files |";
 2022: 	    binmode(F);
 2023: 	    binmode(STDOUT);
 2024: 	    $globaloutput.= join "",<F>;
 2025: 	    close F;
 2026: 	    $dbh->disconnect;
 2027: 	    exit;
 2028: 	} elsif (param('sqldump')) {
 2029: 	    print header(
 2030: 			 -'Content-Type' => 'application/x-zip-compressed; name="dump.zip"',
 2031: 			 -'Content-Disposition' => 'attachment; filename="dump.zip"'
 2032: 			 );
 2033: 	    open F, "$ZIP -j - $DUMPFILE |";
 2034: 	    print (<F>);
 2035: 	    close F;
 2036: 	    $dbh->disconnect;
 2037: 	    exit;
 2038: 
 2039: 	} 
 2040:         elsif (!$opt_z && !param("makehtml")) {
 2041: 		my $QuestionNumber=0;
 2042: 		my $qnum;
 2043: 		if ($qnum=param('qnumber')){
 2044:       	          my ($sth) = $dbh->prepare("SELECT QuestionId FROM Questions
 2045: 		     WHERE ParentId=$tour AND Number=$qnum");
 2046: 		  $sth->execute;
 2047: 		  $QuestionNumber=($sth->fetchrow)[0]||0;
 2048: 	        }
 2049: 	        if ($QuestionNumber) {
 2050: 		  $globaloutput.= &PrintQuestion($dbh, $QuestionNumber, $withanswers||0, $qnum, 1,0,0);
 2051: #                                        $dbh, $Id, $answer, $qnum, $title, $text
 2052: 		} else  {
 2053:   		   $globaloutput.=&PrintTournament($dbh, $tour, $withanswers);
 2054:   		}
 2055: 	}
 2056: 	else {
 2057: 	          $opt_z=1;
 2058: 	          $url="http://db.chgk.info/cgi-bin/db.cgi";
 2059: 	          open TS, "timestamp";
 2060: 	          my $d=$dbh->quote(<TS>);
 2061: 	          close TS;
 2062: 		  open FF, ">${realHTMLDIR}index.html" or die "ERROR! - ${HTMLDIR}index.html\n";
 2063: 		       my $o=$globaloutput;
 2064: 		       $o.=&PrintTournament($dbh, 0, 0);
 2065: 		       $o.=&Bottom;
 2066: 		       print FF $o;
 2067: 		  close FF;
 2068: 		  open FF, ">${realHTMLDIR}all.html" or die "ERROR! - ${HTMLDIR}all.html\n";
 2069: 		       $o=$globaloutput;
 2070: 		       $o.=&PrintAll($dbh,0);
 2071: 		       $o.=&Bottom;
 2072: 		       print FF $o;
 2073: 		       close FF;
 2074: 
 2075: 
 2076: #      	          my ($sth) = $dbh->prepare("SELECT t1.Id, t1.FileName, t1.Type, 
 2077: #			count(t2.Id) 
 2078: #                     FROM Tournaments as t1, Tournaments as t2
 2079: #		     WHERE t1.CreatedAt>$d AND t2.ParentId=t1.Id GROUP BY t1.Id");
 2080: my ($sth) = $dbh->prepare("SELECT t1.Id, t1.FileName, t1.Type, count(t2.Id)  FROM Tournaments as t1  LEFT JOIN Tournaments as t2 
 2081:  ON t2.ParentId=t1.id WHERE t1.CreatedAt>$d GROUP BY t1.Id");
 2082: 		  $sth->execute;
 2083: 		  my ($Id,$fname,$type,$c);
 2084: 		  while (($Id,$fname,$type,$c)=$sth->fetchrow,$Id) {
 2085: 		     next unless $fname;
 2086: 		     print "$fname\n";
 2087: 		     $fname=~s/\.txt$//;
 2088: 		     if ($type=~/Т/ || $c<=1)
 2089: 		     {
 2090: 		       open FF, ">$realHTMLDIR$fname-q.html" or die "ERROR! - $fname-q.html\n";
 2091: 		       my $o=$globaloutput;
 2092: 		       $paramtour=$fname;
 2093: 		       $o.=&PrintTournament($dbh, $Id, 0);
 2094: 		       $o.=&Bottom;
 2095: 		       print FF $o;
 2096: 		       close FF;
 2097: 		       open FF, ">$realHTMLDIR$fname-a.html";
 2098: 		       $o=$globaloutput;
 2099: 		       $o.=&PrintTournament($dbh, $Id, 1);
 2100: 		       $o.=&Bottom;
 2101: 		       print FF $o;
 2102: 		       close FF;
 2103: 		     }
 2104: 		     else {
 2105: 		       open FF, ">$realHTMLDIR$fname.html" or die "ERROR! - $fname-q.html\n";
 2106: 		       my $o=$globaloutput;
 2107: 		       $o.=&PrintTournament($dbh, $Id, 0);
 2108: 		       $o.=&Bottom;
 2109: 		       print FF $o;
 2110: 		       close FF;
 2111: 
 2112: 		     }
 2113:                   }
 2114:         }
 2115: 	if (!$text) {
 2116: 		$globaloutput.=&Bottom;
 2117: 	}
 2118:         if (!$opt_z){ 
 2119: 	  print $globaloutput;
 2120: 	  if (($qs!~ /(rand)|(sstr)|(comp)/i) && (length $qs<=255)) {
 2121: 		$globaloutput=  $dbh->quote($globaloutput);
 2122: 		$dbh->do("insert into hash (query,page) values (".
 2123: 		$dbh->quote($qs).
 2124:                     ",$globaloutput)");
 2125: 	  }
 2126: 	}
 2127: 
 2128: 	$dbh->disconnect;
 2129: }

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