File:  [Local Repository] / db / prgsrc / db.cgi
Revision 1.138: download - view: text, annotated - select for diffs - revision graph
Sun Nov 21 13:37:29 2004 UTC (19 years, 6 months ago) by roma7
Branches: MAIN
CVS tags: HEAD
Stop-word limit is 50000 now

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

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