File:  [Local Repository] / db / prgsrc / db.cgi
Revision 1.137: download - view: text, annotated - select for diffs - revision graph
Mon Nov 8 02:23:18 2004 UTC (19 years, 6 months ago) by boris
Branches: MAIN
CVS tags: HEAD
Made absence of dbdefs.pl non-fatal

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

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