File:  [Local Repository] / db / prgsrc / db.cgi
Revision 1.147: download - view: text, annotated - select for diffs - revision graph
Sun Mar 2 05:25:30 2008 UTC (16 years, 2 months ago) by boris
Branches: MAIN
CVS tags: HEAD
added "set names koi8r"

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

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