File:  [Local Repository] / db / prgsrc / db.cgi
Revision 1.163: download - view: text, annotated - select for diffs - revision graph
Wed Oct 13 12:39:05 2010 UTC (13 years, 7 months ago) by roma7
Branches: MAIN
CVS tags: HEAD
remove redirect

    1: #!/usr/bin/perl -w
    2: 
    3: use DBI;
    4: use CGI ':all';
    5: #use strict;
    6: use Encode;
    7: my @softfields=("От Олега Степанова");
    8: use Time::Local;
    9: use Data::Dumper "Dumper";
   10: use URI::Escape;
   11: my $proxyredirect=1;
   12: use POSIX qw(locale_h);
   13: use locale;
   14: my $maxQuestions = 3000;
   15: 
   16: use vars qw($opt_z);
   17: use Getopt::Std;
   18: #my ($dbuser,$dbname,$dbpass,$dbhost);
   19: eval {require "dbdefs.pl";} ;
   20: my $url=url||'';
   21: my @used_stop=();
   22: my $showNearQuestions=0;
   23: $dbuser||="piataev";
   24: $dbname||="chgk";
   25: $dbpass||="";
   26: $dbhost||="localhost";
   27: getopts('z');
   28: $opt_z||=param("makehtml");
   29: my $timestamp="_timestamp.tmp";
   30: my $usehash=0;
   31: my $paramtour;
   32: my $withanswers=param('answer')||param('answers');
   33: open STDERR, ">/var/tmp/errors1";
   34: my $newsurl='http://news.chgk.info/';
   35: my $reklama="../dimrub/db/reklama.html";
   36: my $footer="../dimrub/db/footer.html";
   37: $footer="../../chgk/footer.html" if $url=~/zaba/;
   38: $reklama="../../chgk/reklama.html" if $url=~/zaba/;
   39: my $datefooter="../dimrub/db/date";
   40: $datefooter="../../chgk/date" if $url=~/zaba/;
   41: 
   42: my $fname;
   43: $reklama="../reklama.html" if $opt_z;
   44: $footer="../footer.html" if $opt_z;
   45: $datefooter="../date" if $opt_z;
   46: my $HTMLDIR="/znatoki/dimrub/db/baza/";
   47: $HTMLDIR="/files/";
   48: my $realHTMLDIR;
   49: if ($^O =~ /win/i) {
   50:  $realHTMLDIR="/html/znatoki/baza/";
   51: } else 
   52: {
   53:   $realHTMLDIR="/home/znatoki/chgk-db/public_html/dimrub/db/files/";
   54: }
   55: 
   56: 
   57: my $usehtml=$opt_z||0;
   58: $usehtml=1;
   59: $usehtml=0 if $url=~/zaba/ || $url=~/localhost/;
   60: 
   61: my $usewas=0;
   62: my $cashednumber=500;
   63: my $outputnumber=10;
   64: my ($proxyptext,$proxysstr);
   65: my $printqueries=0;
   66: my $qs=query_string;
   67: my $globaloutput;
   68: my %forbidden=();
   69: my $debug=0; #added by R7
   70: my $metod=param('metod')||'';
   71: my $outputkvo=param('kvo') ||$outputnumber;
   72: $outputkvo=100 if $outputkvo>100;
   73: 
   74: if (param('debug')) {$debug=1; $printqueries=1}
   75: *STDERR=*STDOUT if $debug;
   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'},$$q{'PlayedAt2'}) = 
  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||=0;
  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,t2.PlayedAt2
  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="/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;
  718: 	     @tasks = russearch($dbh,$sstr,$all,$allnf);
  719: 	     
  720: 	    
  721: 	     return @tasks
  722: 	}
  723: 	elsif ($metod eq 'proxy')
  724: 	{
  725: 	  my @task=proxy($dbh,$s,$allnf);
  726: 	  return @task
  727: 	}
  728: 
  729: 
  730: 
  731: ###Simple and advanced query processing. Added by R7
  732: 	if ($metod eq 'simple' || $metod eq 'advanced')
  733: 	{
  734:           foreach (qw/Question Answer PassCriteria Sources Authors Comments/) {
  735: 		if (param($_)) {
  736: 			push @fields, $_;
  737: 		}
  738: 	   }
  739: 
  740: 	   @fields=(qw/Question Answer PassCriteria Sources Authors Comments/) unless scalar @fields;
  741: 	   my $fields=join ",", @fields;
  742:            my $q=new Text::Query($sstr,
  743:                  -parse => 'Text::Query::'.
  744:                    (($metod eq 'simple') ? 'ParseSimple':'ParseAdvanced'),
  745:                  -solve => 'Text::Query::SolveSQL',
  746:                  -build => 'Text::Query::BuildSQLMySQL',
  747:                  -fields_searched => $fields);
  748: 
  749:            $where=	$$q{'matchexp'};
  750:            $query= "SELECT Questionid FROM Questions
  751:                 WHERE $where";
  752: 
  753:            $sth = $dbh->prepare($query);
  754:          } else
  755: ######
  756:          {
  757: 
  758: 	  foreach (param('searchin')) {
  759: #		if (param($_)) {
  760: 			push @fields, "IFNULL($_, '')";
  761: #		}
  762: 	  }
  763: 	  @sar = split " ", $sstr;
  764: 	  for $i (0 .. $#sar) {
  765: 		$sar[$i] = $dbh->quote("%${sar[$i]}%");
  766: 	  }
  767: 	  $_.=' ' foreach (@fields); # Это чтобы последнее слово поля
  768: 	                             # не сливалось с первым словом
  769: 	                             # следующего поля, R7
  770: 	  my($f) = "CONCAT(" . join(',', @fields) . ")";
  771: 	  if (param('all') eq 'yes') {
  772: 		$sstr = join " AND $f LIKE ", @sar;
  773: 	  } else {
  774: 		$sstr = join " OR $f LIKE ", @sar;
  775:     	  }
  776:     	  
  777:    my $query;
  778:                $query="SELECT QuestionId FROM Questions
  779: 		WHERE ($f LIKE $sstr) AND (".&makewhere.") ORDER BY QuestionId LIMIT $maxQuestions";
  780: 
  781: 
  782: 	  $sth = $dbh->prepare($query)
  783: 	} #else -- processing old-style query (R7)
  784: 
  785: 	$sth->execute;
  786: 	while (@arr = $sth->fetchrow) {
  787: 		push @Questions, $arr[0] unless $forbidden{$arr[0]};
  788: 	}
  789:         $sth->finish;
  790:         
  791: 	return @Questions;
  792: }
  793: 
  794: sub makewhere {
  795:       my @type=param('type');    
  796:       my $type='';
  797: 
  798:       $type .= ($_=$TypeName{$_}) foreach @type;
  799:       my $where=' 0 ';
  800:       foreach (@type) {
  801:  	     $where.= " OR (Type ='$_') OR (Type ='$_Д') OR (Type ='Д$_') ";
  802:       } 
  803:       $where.= "OR (Type='ЧБ')" if ($type=~/Ч|Б/);
  804:       return $where;
  805: }
  806: 
  807:  # Substitute every letter by a pair (for case insensitive search).
  808:  my (@letters) = qw/аА бБ вВ гГ дД еЕ жЖ зЗ иИ йЙ кК лЛ мМ нН оО
  809:  пП рР сС тТ уУ фФ хХ цЦ чЧ шШ щЩ ьЬ ыЫ эЭ юЮ яЯ/;
  810: 
  811: sub NoCase {
  812: 	my ($sstr) = shift;                   	
  813: 	my ($res);
  814: 
  815: 	if (($res) = grep(/$sstr/, @letters)) {
  816: 		return "[$res]";
  817: 	} else {
  818: 		return $sstr;
  819: 	}
  820: }
  821: 
  822: sub PrintList {
  823:    my ($dbh,$Questions,$shablon,$was)=@_;
  824: 	my $total_found  = $totalfound||$#$Questions+1;
  825:         my $Output;
  826: 	my $first=param('first') ||1;
  827: 	$first=$first-($first-1)%$outputkvo;
  828:         my $fkvo=param('fkvo')||$total_found;
  829: 	my $last=$first+$outputkvo-1;
  830: 	$last=$fkvo if $fkvo<$last;
  831:         my($f,$l);
  832:         my $nav='';
  833:         my $qs=query_string;
  834: 	$qs=~s/\;/\&/g;
  835:         $qs=~s/\&first\=[^\&]+//g;
  836:         my $sstr=param('sstr')||'';
  837:         $qs=~s/sstr=[^\&]+/sstr=$sstr/;
  838:         if ($usewas) {
  839:         	$qs=~s/\&was=[^\&]+//;
  840:         	$qs.="&was=$was" if $was;
  841:         	$qs.="&fkvo=$fkvo" if $was;
  842:         }
  843:         if ($first>$outputkvo*3+1)
  844:         {
  845:            $nav.=
  846:             ("&nbsp;"x4).
  847:             a({href=>$url."?".$qs."\&first=1"},"<<").("&nbsp;"x4).
  848:             a({href=>($url."?".$qs."\&first=".($first-$outputkvo))},"<").("&nbsp;"x4)
  849: 	}
  850:         else {$nav.='&nbsp;'x15;}
  851: 
  852:      my ($fprint,$lprint);
  853:      my $llprint=$fkvo- ($fkvo-1)%$outputkvo; #
  854:      if ($fkvo<=$outputkvo*7)
  855:      {         $fprint=1;
  856:                $lprint=$llprint+($fkvo)%$outputkvo;
  857:      }
  858:      elsif ($first>$outputkvo*3 && $fkvo-$first>$outputkvo*3)
  859:      {
  860:        $fprint=$first-$outputkvo*3;
  861:        $lprint=$first+$outputkvo*3;
  862:      } 
  863:      elsif  ($first<=$outputkvo*3)
  864:      {
  865:         $fprint=1; $lprint=6*$outputkvo+1;
  866:      }
  867:      else
  868:      { 
  869:            $lprint=$fkvo;
  870:            $fprint=$lprint-($lprint-1)%$outputkvo-$outputkvo*6;
  871:      }
  872:          
  873: #        my $fprint=($first>$outputkvo*3) ? $first-$outputkvo*3 : 1;
  874: #        my $lprint=$#$Questions+1-$fprint>$outputkvo*7 ? $outputkvo*7 :$#$Questions+1;
  875: #        if ($lprint-$fprint<$outputkvo*6 && $fprint>1)
  876: #        {
  877: #            $fprint=$lprint-$outputkvo*6;
  878: #            $fprint=1 if ($fprint<=0) 
  879: #        }
  880: 
  881: 
  882:         for($f=$fprint; $f<=$lprint; $f+=$outputkvo)
  883: 	{
  884: #	  next if $first-$f>$outputkvo*3;
  885: 	  $l=$f+$outputkvo-1;
  886: 	  $l=$fkvo if $l>$fkvo+1;
  887: 	  if ($f==$first) {$nav.="[$f-$l] ";}
  888: 	  else {
  889:                   $nav.= "[".a({href=>($url."?".$qs."\&first=$f")},"$f-$l")."] ";}
  890: 	}
  891:         if ($lprint+$outputkvo<$fkvo)
  892:         {
  893:     	    my $reminder = ($llprint-1)%$outputkvo;
  894:     	    my $newlprint = $llprint-$reminder;
  895: #    	    $newlprint +=$outputkvo if $reminder!=$outputkvo-1;
  896:            $nav.=
  897:             ("&nbsp;"x4).
  898:             a({href=>($url."?".$qs."\&first=".($first+$outputkvo))},">").("&nbsp;"x4).
  899:             a({href=>$url."?".$qs."\&first=$newlprint"},">>").("&nbsp;"x4)
  900:         }
  901: 	$Output.= "$nav".br."\n";
  902: 	my @q;
  903: 	if ($totalfound) {
  904: 	    @q = @$Questions;
  905: 	} else {
  906: 	    @q=@$Questions[$first-1..$last-1];
  907: 	}
  908: 	my %q=();
  909: 	my $sth=SelectQuestions($dbh,\@q,1);
  910: 	my $qq;
  911: 	my @Q;
  912: 	for (0..$#q) {
  913: 	        %{$Q[$_]}=();
  914: 		fetchquestion($sth,$Q[$_],1);
  915: 		$q{$Q[$_]{'QuestionId'}}=$Q[$_];
  916: 	}
  917: 
  918: 	for my $i(0..$#q) {
  919: 		my $q=$q{$q[$i]};
  920: 	        my $output;
  921: 		$output = &PrintQuestion($dbh, $q, 1, 0, 1,$text,1  );
  922: #                if (param('metod') && (param('metod') eq 'rus' || param('metod') eq 'proxy'))
  923:                 {
  924: 	             $output=~s/\b($shablon)\b/\<strong\>$1\<\/strong\>/gi;
  925: 	             $output=~s/($shablon)/\<strong\>$1\<\/strong\>/gi;
  926: 	             $output=~s/(href="[^"]*?)(?:<.*?>)+([^"]*?)(?:<\/.*?>)+([^"]*?")/!1 $1$2$3 2!/g;#!!!!
  927: 		}
  928: 
  929: 		$Output.= $output;
  930: 	}
  931: 	$sth->finish;
  932: 
  933: 	$Output.= "$nav".br."\n";
  934: 	return $Output;
  935: }
  936: 
  937: sub PrintSearch {
  938:         my $Output='';
  939: 	my ($dbh, $sstr, $metod,$was) = @_;
  940: 	my $t=time;
  941: 	$Output.= printform;
  942: 	my @allnf;
  943: 	my @Questions;
  944: 	$was=0 if $metod eq 'proxy';
  945: 	if ($usewas && $was && ($metod ne 'proxy'))
  946: 	{
  947: 	  my $sth=$dbh->prepare ("select sstr,questions,allnf from lastqueries where id=".param('was'));
  948:           $sth->execute;
  949:           my ($q,$nf);
  950: 	  ($sstr, $q,$nf)=($sth->fetchrow);
  951:           @Questions=unpack 'L*',$q; 
  952:           @allnf=unpack 'L*',$nf;        
  953:           $sth->finish;
  954:         }  
  955:         if (!$was || ($metod eq 'proxy') || (param('first')+$outputkvo>$cashednumber))
  956:         {
  957:              @Questions=&Search($dbh, \$sstr,$metod,$all,\@allnf);
  958:              $cashednumber=$#Questions if $cashednumber>$#Questions;
  959:              my $tmp=$dbh->quote(pack("L*",@Questions[0..$cashednumber]));
  960:              my $qsstr=$dbh->quote($sstr);
  961:              my $nf=$dbh->quote(pack("L*", @allnf));
  962:              my $ss=200;
  963:              if ($usewas) {
  964:              	do 
  965:              		{
  966:                			$was=int rand(32000);
  967:              		}
  968:              	while (--$ss && (!$dbh->do ("insert into lastqueries (id,sstr,questions,allnf) 
  969:                          values ($was, $qsstr,$tmp,$nf)")));
  970:              	$Output.= "Something is wrong...".br."\n" unless $ss;
  971:  	      }
  972:         }
  973: 
  974: 
  975: 
  976: 	$Output.= p. "Время поиска: " . (time-$t) ." сек.".p;
  977: 	$_="\"$_\"" foreach @used_stop;
  978: 	$Output.= p. (join ', ',@used_stop) ." ignored".p if @used_stop;
  979: 	my ($output, $i, $suffix, $hits) = ('', 0, '', $#Questions + 1);
  980: 
  981:         my $shablon;
  982:         $metod='rus' if $metod eq 'proxy';
  983:         if ($metod eq 'rus')
  984:         {
  985:            my $where='0';
  986:            $where.= " or w2=$_ " foreach @allnf;
  987:            my $query="select w1 from nests where $where";
  988:            my $sth=$dbh->prepare($query);
  989: 
  990: 	   $sth->execute;
  991: 	   my @shablon;
  992: 	   while (my @arr = $sth->fetchrow)
  993: 	   {
  994: 	     push @shablon,"(?:$arr[0])";
  995: 	   }
  996: 	   $sth->finish;
  997:            $shablon= join "|", @shablon;
  998:            $shablon=~s/[её]/\[ЕЁ\]/gi;
  999: #           $shablon=~s/([йцукенгшщзхъфывапролджэячсмитьбюЙЦУКЕНГШЩЗХЪФЫВАПРОЛДЖЭЯЧСМИТЬБЮ])/&NoCase($1)/ge;
 1000:            $shablon=qr/$shablon/i;
 1001: 
 1002:         }
 1003: 
 1004:         $hits=param("fkvo")||$hits;
 1005: 
 1006: 	if ($hits =~ /1.$/  || $hits =~ /[5-90]$/) {
 1007: 		$suffix = 'й';
 1008: 	} elsif ($hits =~ /1$/) {
 1009: 		$suffix = 'е';
 1010: 	} else {
 1011: 		$suffix = 'я';
 1012: 	}
 1013: 
 1014: 	$hits = 'очень много' if ($hits==$maxQuestions);
 1015: 
 1016: 	$Output.= p({align=>"center"}, "Результаты поиска на " . strong($sstr)
 1017: 	. " : $hits попадани$suffix.");
 1018: 
 1019: 	if (param('word')) {
 1020: 		$sstr = '[ 	\.\,:;]' . $sstr . '[  \.\,:\;]';
 1021: 	}
 1022: 
 1023: #	$sstr =~ s/(.)/&NoCase($1)/ge;
 1024: 
 1025: 	my @sar;
 1026: 	if ($metod ne 'rus') 
 1027: 	{
 1028: 	  my $ss=$sstr;
 1029: 	  (@sar) = split(' ', $ss);
 1030: 	  s/(\W)/\\$1/g foreach (@sar);
 1031: 	  $shablon=join "|",@sar;
 1032: 	}
 1033: 	$Output.=PrintList($dbh,\@Questions,$shablon,$was);
 1034: 	return $Output;
 1035: }
 1036: 
 1037: sub PrintRandom {
 1038:    my ($dbh, $type, $num, $text) = @_;
 1039:    my $razd=param('razd');
 1040:    my %q;
 1041:    my $answer=$razd?0:1;
 1042:    my @answers;
 1043: #my $t=time;
 1044:    my (@Questions) = &Get12Random($dbh, $type, $num);
 1045: 
 1046: 	my ($output, $i) = ('', 0);
 1047: #$output.="time=".(time-$t).p;
 1048: 	if ($text) {
 1049: 		$output .= "	$num случайных вопросов.\n\n";
 1050: 	} else {
 1051: 		$output .=
 1052: 			h2({align=>"center"}, "$num случайных вопросов.");
 1053: 	}
 1054: 	my $sth=SelectQuestions($dbh,\@Questions,0);
 1055: 	for ($i = 0; $i <= $#Questions; $i++) {
 1056: 		fetchquestion($sth,\%q,0);
 1057: 		$output .=
 1058: 			&PrintQuestion($dbh, \%q, $answer, $i + 1, 0, $text,1);
 1059: 			push @answers, $q{'Answer'};
 1060: 	}
 1061: 	$sth->finish;
 1062: 	unless ($answer )
 1063:         { 
 1064:          $output.=$text?"\n".('-'x 20)."\nОтветы\n~~~~~~\n\n":h2('Ответы');
 1065:          $sth=SelectQuestions($dbh,\@Questions,0);
 1066:          for ($i = 0; $i <= $#Questions; $i++) {
 1067: #                fetchquestion($sth,\%q,0);
 1068: #		$output .=
 1069: #			&PrintQuestion($dbh, \%q, -1, $i + 1, 0, $text,1);
 1070:                 $output.=$text?("Ответ ". ($i+1).": $answers[$i]\n\n"):
 1071: 			b("Ответ ". ($i+1).": "). $answers[$i].p;
 1072: 	 }
 1073:         }
 1074: 
 1075: 	return $output;
 1076: }
 1077: 
 1078: sub PrintEditor {
 1079:        my $t=shift; #ссылка на Хэш с полями
 1080:        my $ed=$$t{'Editors'}||'';
 1081:        my $edname=($ed=~/\,/ ) ? "Редакторы"  : "Редактор" ;
 1082:        return $ed? h4({align=>"center"},"$edname: $ed" ): '';
 1083: }
 1084: 
 1085: sub PrintTournament {
 1086:    my ($dbh, $Id, $answer) = @_;
 1087: 	my (%Tournament, @Tours, $i, $list, $qnum, $imgsrc, $alt,
 1088: 		$SingleTour);
 1089: 	my ($output) = '';
 1090: 
 1091: 	%Tournament = &GetTournament($dbh, $Id) if ($Id);
 1092: 
 1093: 	my ($URL) = $Tournament{'URL'}||'';
 1094: 	$URL=~s/http:\/znatoki\/boris\/reports\//$newsurl/ if $url=~/kulichki/ || $url=~/db.chgk.info/;
 1095: 	$URL=~s/\/znatoki\/boris\/reports\//$newsurl/ if url=~/kulichki/ || $url=~/db.chgk.info/;
 1096: 	my ($Info) = $Tournament{'Info'};
 1097: 	my ($Copyright) = $Tournament{'Copyright'};
 1098: 	my $fname=$Tournament{'FileName'};
 1099: 	@Tours = &GetTours($dbh, $Id);
 1100: 	$list='';
 1101: 	my $textid;
 1102: 	my $isGroup;
 1103: 	if ($Id) {
 1104: 		for ($Tournament{'Type'}) {
 1105: 			/Г/ && do {
 1106: 				$output .= h2({align=>"center"},
 1107: 					      "Группа: $Tournament{'Title'} ",
 1108: 					      $Tournament{'PlayedAt'}||'') . 
 1109: 					      ($Tournament{'PlayedAt2'}?'&nbsp;&ndash; '.
 1110: 					        $Tournament{'PlayedAt2'}:'') . 
 1111: 					      
 1112: 					      p . "\n";
 1113: 					      $isGroup=1;
 1114: 				last;
 1115: 			};
 1116: 			/Ч/ && do {
 1117: 				return &PrintTour($dbh, $Tours[0], $answer)
 1118: 					if ($#Tours == 0);
 1119: 
 1120: 				my $title="Пакет: $Tournament{'Title'}";
 1121: 				if ($Tournament{'PlayedAt'}) {
 1122: 				    $title .= " $Tournament{'PlayedAt'}";
 1123: 				}
 1124: 
 1125: 				if ($Tournament{'PlayedAt2'}) {
 1126: 				    $title .= '&nbsp;&ndash; '.$Tournament{'PlayedAt2'};
 1127: 				}
 1128: 
 1129: 				$output .= h2({align=>"center"},
 1130: 					"$title") . p . "\n";
 1131: 			       $output.=&PrintEditor(\%Tournament);
 1132: 				last;
 1133: 			};
 1134: 			/Т/ && do {
 1135: 				return &PrintTour($dbh, $Id, $answer);
 1136: 			};
 1137: 		}
 1138: 	} else {
 1139: 		my ($qnum) = GetQNum($dbh,0);
 1140: 		my ($qnum1) = GetQNum($dbh,1);
 1141: 		$output .= h2("База вопросов").
 1142:                  h3("$qnum запис".&Suffix2($qnum).
 1143:                  " (уникальных $qnum1)");
 1144: 
 1145: #		 h4("<table>".
 1146: #		 Tr(td("Из них:"), td("Вопросов ЧГК: ".countz($dbh,'Ч'))).		 
 1147: #		 Tr(td("&nbsp;"), td("Вопросов для брейна: ".countz($dbh,'Б'))).		 
 1148: #		 Tr(td("&nbsp;"), td("Вопросов для ЧГК и брейна: ".countz($dbh,'ЧБ'))).		 
 1149: #		 Tr(td("&nbsp;"), td("Интернет-вопросов: ".countz($dbh,'И'))).		 
 1150: #		 Tr(td("&nbsp;"), td("Бескрылок: ".countz($dbh,'Л'))).
 1151: #		 Tr(td("&nbsp;"),td("Заданий для Своей Игры: ".countz($dbh,'Я'))).
 1152: #		 Tr(td("&nbsp;"),td("Эрудиток: ".countz($dbh,'Э'))))."</table>"
 1153: 	}
 1154: 
 1155: 	for ($i = 0; $i <= $#Tours; $i++) {
 1156: 		%Tournament = &GetTournament($dbh, $Tours[$i]);
 1157: 
 1158: 		if ($Tournament{'Type'} =~ /Ч/) {
 1159: 			$SingleTour = 0;
 1160: 			my (@Tours) = &GetTours($dbh, $Tournament{'Id'});
 1161: 			$SingleTour = 1
 1162: 				if ($#Tours == 0);
 1163: 		}
 1164: 		if ($Tournament{'QuestionsNum'} > 0) {
 1165: 			$qnum = " ($Tournament{'QuestionsNum'} вопрос" .
 1166: 				&Suffix($Tournament{'QuestionsNum'}) . ")\n";
 1167: 		} else {
 1168: 			$qnum = '';
 1169: 		}
 1170: 		if ($Tournament{'Type'} !~ /[ТЧ]/) {
 1171: 		    $SingleTour=0;
 1172: 			$imgsrc = "/icons/folder.gif";
 1173: 			$alt = "[*]";
 1174: 		} else {
 1175: 			$imgsrc = "/icons/folder.gif";
 1176: 			$alt = "[-]";
 1177: 		}
 1178: 
 1179: 		my $textid;
 1180: 		if ($textid=$Tournament{'FileName'})
 1181: 		{
 1182: 		   $textid=~s/\.txt//;
 1183: 		}
 1184: 		elsif ($textid=$Tournament{'Number'})
 1185: 		  {
 1186: 		      $fname=~s/\.txt//;
 1187: 		      $textid="$fname.$textid";
 1188: 		  }
 1189: 	       else {$textid=$Tournament{'Id'}};
 1190: 		
 1191: 
 1192: 		if ($SingleTour or ($Tournament{'Type'} =~ /Т/)) {
 1193: 			$list .= dd(img({src=>$imgsrc, alt=>$alt})
 1194: 				. " " . $Tournament{'Title'} . " " .
 1195: 				    ($Tournament{'PlayedAt'}||"") . 
 1196: 				    ($Tournament{'PlayedAt2'}?'&nbsp;&ndash; '.$Tournament{'PlayedAt2'}:"") .
 1197: 				    $qnum) .
 1198: 				dl(
 1199: 					dd("["
 1200: 						. a({href=>tourhref($textid,0)},
 1201: 						"вопросы") . "] ["
 1202:                   . a({href=>tourhref($textid,1)},
 1203:                   "вопросы + ответы") . "]")
 1204: 				);
 1205: 		} else {
 1206: 			$list .= dd(a({href=>
 1207:                                  $url . "?tour=$textid&comp=1"},
 1208: 				img({src=>'/icons/compressed.gif', alt=>'[ZIP]', border=>1}))				.  
 1209: 				" " . 
 1210:                                 img({src=>$imgsrc, alt=>$alt})
 1211: 				. " " . a({href=>tourhref($textid,0,1)},
 1212: 				$Tournament{'Title'}. " ".
 1213: 					  ($Tournament{'PlayedAt'}||'')) .
 1214: 					  ($Tournament{'PlayedAt2'}?'&nbsp;&ndash '. $Tournament{'PlayedAt2'}:''). $qnum); 
 1215: 		}
 1216: 	}
 1217: 	$output .= dl($list);
 1218: 
 1219: 	if ($URL) {
 1220: 	        if ($url=~/zaba\.ru/ && $URL=~/^\//){$URL="http://info.chgk.info$URL"}
 1221: 		$output .=
 1222: 		p("Дополнительная информация об этом турнире - по адресу " .
 1223: 			a({-'href'=>$URL}, $URL));
 1224: 	}
 1225: 	if ($Copyright) {
 1226: 		$output .= p("Копирайт: " .   $Copyright);
 1227: 	}
 1228: 
 1229: 
 1230: 
 1231: 	if ($Info) {
 1232: 		$output .= p($Info);
 1233: 	}
 1234: 
 1235: 
 1236: 
 1237: 	$output.=p("<a href='/dbxml.php?tour=".param('tour')."'>XML</a>");
 1238: 
 1239: 		if ($textid=$fname)
 1240: 		{
 1241: 		   $textid=~s/\.txt//;
 1242: 		}
 1243: 	if (!$isGroup) {
 1244:   	    $output .= center("<font size='-1'>[".
 1245: 	     a({href=>"/v2/tour/$textid/print", target=>'_blank'}, 'версия для печати')."] [".
 1246: 	     a({href=>"/v2/tour/$textid/fb2", target=>'_blank'}, 'fb2')."]"."</font>");
 1247:         }
 1248: 	
 1249: 	return $output;
 1250: }
 1251: 
 1252: sub Suffix {
 1253: 	my ($qnum) = @_;
 1254: 	my ($suffix) = 'а' if $qnum =~ /[234]$/;
 1255:    $suffix = '' if $qnum =~ /1$/;
 1256:    $suffix = 'ов' if $qnum =~ /[567890]$/ || $qnum =~ /1.$/;
 1257: 	return $suffix;
 1258: }
 1259: 
 1260: 
 1261: sub Suffix1 {
 1262: 	my ($qnum) = @_;
 1263: 	my ($suffix) = 'я' if $qnum =~ /[234]$/;
 1264:        $suffix = 'е' if $qnum =~ /1$/;
 1265:        $suffix = 'й' if $qnum =~ /[567890]$/ || $qnum =~ /1.$/;
 1266: 	return $suffix;
 1267: }
 1268: 
 1269: sub Suffix2 {
 1270: 	my ($qnum) = @_;
 1271: 	my ($suffix) = 'и' if $qnum =~ /[234]$/;
 1272:        $suffix = 'ь' if $qnum =~ /1$/;
 1273:        $suffix = 'ей' if $qnum =~ /[567890]$/ || $qnum =~ /1.$/;
 1274: 	return $suffix;
 1275: }
 1276: 
 1277: sub IsTour {
 1278: 	my ($dbh, $Id,$n) = @_;
 1279: 
 1280: 	my ($sth) ;
 1281:         
 1282:         if (defined $n) 
 1283:         { $sth=$dbh->prepare ("select Id FROM Tournaments
 1284:                            WHERE ParentId=$Id AND Number=$n");
 1285:         }
 1286:         else
 1287:         {
 1288:           $sth=$dbh->prepare("SELECT Id FROM Tournaments
 1289: 		WHERE Id=$Id");
 1290: 	}
 1291: 	$sth->execute;
 1292:         my $a=($sth->fetchrow)[0];
 1293: 	$sth->finish;
 1294:  	return $a;
 1295: }
 1296: 
 1297: # Gets a DB handler (ofcourse) and a tour Id. Prints all the
 1298: # question of that tour, according to the options.
 1299: sub PrintTour {
 1300: 	my ($dbh, $Id, $answer) = @_;
 1301: 	my ($output, $q, $bottom, $field) = ('', 0, '', '');
 1302: 
 1303: 	my (%Tour) = &GetTournament($dbh, $Id);
 1304: 	my (@Tours) = &GetTours($dbh, $Tour{'ParentId'});
 1305: 	my (%Tournament) = &GetTournament($dbh, $Tour{'ParentId'});
 1306: 	my %q;
 1307: 
 1308: 	return 0
 1309: 		if ($Tour{'Type'} !~ /Т/);
 1310: 
 1311: 	my ($fname)=$Tournament{'FileName'};
 1312: 	$fname=~s/\.txt//;
 1313: 	my ($qnum) = $Tour{'QuestionsNum'};
 1314: 	my ($suffix) = &Suffix($qnum);
 1315: 
 1316: 	$output .= h2({align=>"center"}, $Tournament{"Title"},
 1317: 		      $Tournament{'PlayedAt'}||'',
 1318: 		      $Tournament{'PlayedAt2'}?'&nbsp;&ndash; '.$Tournament{'PlayedAt2'}:'',
 1319: 		      "<br>\n", $Tour{"Title"} .
 1320: 		" ($qnum вопрос$suffix)\n") . p;
 1321: 	$output .=&PrintEditor(\%Tour);
 1322: 
 1323: 	my (@Questions) = &GetTourQuestions($dbh, $Id);
 1324: 	my $sth=SelectQuestions($dbh,\@Questions,0);
 1325: 	for ($q = 0; $q <= $#Questions; $q++) {
 1326: 		fetchquestion($sth,\%q,0);
 1327: 		$output .= &PrintQuestion($dbh, \%q, $answer, 0,0,$text,1);
 1328: 	}
 1329: 	$sth->finish;
 1330: 	$output .= hr({-'align'=>'center', -'width'=>'80%'});
 1331: 
 1332: 	if ($Tournament{'URL'}) {
 1333: 	    $URL = $Tournament{'URL'};
 1334: 	    $URL=~s/http:\/znatoki\/boris\/reports\//$newsurl/ if $url=~/kulichki/ || $url=~/db.chgk.info/;
 1335: 	    $URL=~s/\/znatoki\/boris\/reports\//$newsurl/ if url=~/kulichki/ || $url=~/db.chgk.info/;
 1336: 
 1337: 	    $output .=
 1338: 	    p("Дополнительная информация об этом турнире - по адресу " .
 1339: 			a({-'href'=>$URL}, $URL));
 1340: 	}
 1341: 
 1342: 	if ($Tournament{'Copyright'}) {
 1343: 		$output .= p("Копирайт: " .   $Tournament{'Copyright'});
 1344: 	}
 1345: 
 1346: 	if ($Tournament{'Info'}  ) {
 1347: 		$output .= p($Tournament{'Info'});
 1348: 	}
 1349: 
 1350: 	if ($Tour{'Info'} && ($Tournament{'Info'} ne $Tour{'Info'})) {
 1351: 		$output .= "!!".p($Tour{'Info'});
 1352: 	}
 1353: 
 1354: 	$output.=p("<a href='/dbxml.php?tour=".param('tour')."'>XML</a>");
 1355: 
 1356: 	my $n=$Tour{'Number'};
 1357: 	if ($answer == 0) {
 1358: 	        my $nn=".$n";
 1359: 	        $nn="" if ($n==1 && !&IsTour($dbh, $Tour{'ParentId'}, $n + 1));
 1360: 	        
 1361: 		$bottom .=
 1362: 			"[" . a({href=>tourhref("$fname$nn",1)}, 
 1363:                          "ответы") .  "] " 
 1364: 	}
 1365: 	$bottom .= "[".a({href=>"/v2/tour/$fname/print", target=>'_blank'}, 'версия для печати')."] [".
 1366: 	  a({href=>"/v2/tour/$fname/fb2/", target=>'_blank'}, 'fb2')."]".br;
 1367: 	
 1368: #	$bottom .= "[".a({href=>'/v2/print/'.$fname.'.'.$Tour{'Number'}, target=>'_blank'}, 'версия для печати')."]".br;
 1369: 	
 1370: 	if ($n>1) {
 1371: 		$bottom .=
 1372: 			"[" . a({href=>tourhref("$fname.".($n-1),0)},
 1373: 			"предыдущий тур") . "] ";
 1374: 		$bottom .=
 1375: 			"[" . a({href=>tourhref("$fname.".($n-1),1)},
 1376: 			"предыдущий тур с ответами") . "] " . br."\n";
 1377: 	}
 1378: 	
 1379: 	if (&IsTour($dbh, $Tour{'ParentId'}, $n + 1)) {
 1380: 		$bottom .=
 1381: 			"[" . a({href=>tourhref("$fname.".($n+1),0)},
 1382: 			"следующий тур") . "] ";
 1383: 		$bottom .=
 1384: 			"[" . a({href=>tourhref("$fname.".($n+1),1)},
 1385: 			"следующий тур с ответами") . "] ";
 1386: 	}
 1387: 
 1388: 	$output .=
 1389: 		p({align=>"center"}, font({size=>-1}, $bottom));
 1390: 
 1391: 	return $output;
 1392: }
 1393: 
 1394: 
 1395: sub escapeUrl {
 1396: 	my $uri = shift;
 1397: 	$uri=~s/<.*?>//g;
 1398: 	$uri =~ s/([Ю-Ъю-ъ]+)/URI::Escape::uri_escape_utf8(decode("koi8-r",$1))/eg;
 1399: 	return $uri;	
 1400: }
 1401: 
 1402: sub PrintField {
 1403: 	my ($header, $value, $text) = @_;
 1404: 	if ($text) {
 1405: 	    $value =~ s/<[\/\w]*?>//sg;
 1406: 	} else {
 1407: 	    if ($header=~/Комментар/)
 1408: 	    {
 1409: 		$value=~s/^\s*$_[\.:]/p."\n".strong("$_").":\n"/me foreach @softfields;
 1410: 	    }
 1411: 
 1412: 	    $value =~ s/^\s+/<br>\n&nbsp;&nbsp;&nbsp;&nbsp;/mg;
 1413: 	    $value =~ s/(\s+)-+(\s+)/$1&#0150;$2/mg;
 1414: 	    $value =~ s/\s+\&#0150/&nbsp;\&#0150/mg 
 1415: 			if $value !~ /^\|/;
 1416: 	    $value =~ s/^\|([^\n]*)/<pre>$1<\/pre>/mg;
 1417: 
 1418: 	    $value =~ s/(http:\/\/\S+[^\s\)\(\,\.\]])/a({href=>escapeUrl($1)},$1)/egm if $header !~ /^Авто/;#!!!
 1419: 
 1420: 	    $value =~ s/\.\.\.\]/!!!ZAKR!!!/g;
 1421: 	    $value =~ s/пропущено\]/!!!PROP!!!/g;
 1422: 	    $value =~ s/пропущены\]/!!!PROP2!!!/g;
 1423: 	    $value =~ s/\[Раздаточный материал:(.*?)\]\s*\n/<div class='razdatka'><div class='razdatka_header'>Раздаточный материал<\/div> $1<\/div>\n$2/sm;
 1424: 	    $value =~ s/<раздатка>(.*?)<\/раздатка>/<div class='razdatka'><div class='razdatka_header'>Раздаточный материал<\/div> $1<\/div>\n/sm;
 1425: 	    $value =~ s/!!!ZAKR!!!/\.\.\.\]/g;
 1426: 	    $value =~ s/!!!PROP!!!/пропущено\]/g;
 1427: 	    $value =~ s/!!!PROP2!!!/пропущены\]/g;
 1428: 
 1429: 
 1430: #	    $value =~ s/(http:\/\/\S+[^\s\)\(\,\.])/make/eg if $header !~ /^Авто/;#!!!
 1431: #	    $value =~ s/(http:\/\/\S+[^\s\)\(\,\.])/<a href="$1">$1<\/a>/g if $header !~ /^Авто/;
 1432: #	    $value =~ s/(http:\/\/(?:\w+.)+[\w\\\~]+(\?[^\s.]+)?)/<a href="$1">$1<\/a>/g if $header !~ /^Авто/;
 1433: #	    $value =~ s/(\s)"/$1&#147;/mg;
 1434: #	    $value =~ s/^"/&#147;/mg;
 1435: #	    $value =~ s/"/&#148;/mg;
 1436: 	}
 1437: 
 1438: 	if ($value=~/^\s*(<p.*?>)?\s*<strong/) {
 1439: 		return $text ? "$value\n\n" :
 1440: 			$value . p . "\n";
 1441: 	}
 1442: 	return $text ? "$header:\n$value\n\n" :
 1443: 		strong("$header: ") . "\n".$value . p . "\n";
 1444: }
 1445: 
 1446: # Gets a DB handler (ofcourse) and a question Id. Prints
 1447: # that question, according to the options.
 1448: sub PrintQuestion {
 1449: 	my ($dbh, $Id, $answer, $qnum, $title, $text,$h) = @_;
 1450: 	my ($output, $titles) = ('', '');
 1451: 	my $fname;
 1452: 	my (%Question);
 1453: 	if ($h) {
 1454: 	  %Question=%$Id;
 1455: 	} else {
 1456: 		%Question = &GetQuestion($dbh, $Id);
 1457: 		if ($title) {
 1458: 			my (%Tour) = GetTournament($dbh, $Question{'ParentId'});
 1459: 			my (%Tournament) = GetTournament($dbh, $Tour{'ParentId'});
 1460: 			$Question{'FileName'}=$Tournament{'FileName'};
 1461: 			$Question{'Title'}=$Tournament{'Title'};
 1462: 			$Question{'PlayedAt'}=$Tournament{'PlayedAt'};
 1463: 			$Question{'PlayedAt2'}=$Tournament{'PlayedAt2'};			
 1464: 			$Question{'TourNumber'}=$Tour{'Number'};
 1465: 			$Question{'TourTitle'}=$Tour{'Title'};
 1466: 		}
 1467: 
 1468:         }
 1469: 		$qnum = $Question{'Number'}
 1470: 		if ($qnum == 0);
 1471: 	if (!$text) {
 1472: 		$output .= hr({width=>"50%"}) if $answer>=0;
 1473: 		if ($title) {
 1474: 			$fname=$Question{'FileName'};
 1475: 			$fname=~s/\.txt//;
 1476: 			$titles .=
 1477: 				dd(img({src=>"/icons/folder.open.gif"}) . " " .
 1478: 					 a({href=>tourhref($fname,0,1)}, 
 1479:                                $Question{'Title'}, $Question{'PlayedAt'}||'',
 1480:                                $Question{'PlayedAt2'}?'&nbsp;&ndash; '.$Question{'PlayedAt2'}:''));
 1481: 			$titles .=
 1482: 				dl(dd(img({src=>"/icons/folder.open.gif"}) . " " .
 1483: 					a({href=>tourhref("$fname.$Question{'TourNumber'}#$qnum",1)}, 
 1484:                           $Question{'TourTitle'})));
 1485: 		}
 1486: 		$output .= dl(strong($titles));
 1487: 	}
 1488: 
 1489: 
 1490: 	$output.= "<a NAME=\"$qnum\">" unless $text;
 1491: 
 1492: 	if ($answer>=0) {$output .=
 1493: 		&PrintField("Вопрос $qnum", $Question{'Question'}, $text);}
 1494: 	else {$output .="$qnum. "}
 1495: 	if ($answer==1|| $answer==-1) {
 1496: 		$output .=
 1497: 			&PrintField("Ответ", $Question{'Answer'}, $text);
 1498: 		if ($Question{'PassCriteria'} ) {
 1499: 		  $output .=
 1500: 			&PrintField("Зачёт", $Question{'PassCriteria'}, $text);
 1501:                 }
 1502: 
 1503: 		if ($Question{'Authors'} ) {
 1504:                       my $q=$Question{'Authors'};
 1505: ###АВТОРА!!
 1506: # 		      my $sth=$dbh->prepare("select Authors.CharId,Name, Surname, Nicks from Authors, A2Q
 1507: #                                  where Authors.Id=Author And Question=$Id");
 1508: #                       $sth->execute;
 1509: #                       my ($AuthorId,$Name, $Surname,$other,$Nicks);
 1510: #                      if (!$text) {
 1511: #                       while ((($AuthorId,$Name, $Surname,$Nicks)=$sth->fetchrow),$AuthorId)
 1512: #                       {
 1513: #                          my ($firstletter)=$Name=~m/^./g;
 1514: #                          $Name=~s/\./\\\./g;
 1515: #                          $Name=~s/ё/[её]/g;
 1516: #                          $Surname=~s/ё/[её]/g;
 1517: #                           my $sha="(?:$Name\\s+$Surname)|(?:$Surname\\s+$Name)|(?:$firstletter\\.\\s*$Surname)|(?:$Surname\\s+$firstletter\\.)|(?:$Surname)";
 1518: #                           if ($Nicks)
 1519: #                           {
 1520: #                             $Nicks=~s/^\|//;
 1521: #                             foreach (split /\|/, $Nicks)
 1522: #                             {
 1523: #                               s/\s+/ /g;
 1524: #                               s/\s+$//;
 1525: #                               s/ /\\s+/g;
 1526: #                               s/\./\\\./g;
 1527: #                               if (s/>$//) {$sha="$sha|(?:$_)"}
 1528: #                               else        {$sha="(?:$_)|$sha"}
 1529: #                             }
 1530: #                           }
 1531: #                           $q=~s/($sha)/a({href=>url."?qofauthor=$AuthorId"},$1)/ei;
 1532: #                           unless ($1) 
 1533: #                             {   
 1534: #                                 $q=~s/$Name/a({href=>url."?qofauthor=$AuthorId"},$1)/ei;
 1535: #                             }
 1536: #                       }
 1537: #                      }
 1538: 			$output .= &PrintField("Автор(ы)", $q, $text);
 1539: 
 1540: 		}
 1541: 
 1542: 		if ($Question{'Sources'}) {
 1543: 			$output .= &PrintField("Источник(и)", $Question{'Sources'}, $text);
 1544: 		}
 1545: 
 1546: 		if ($Question{'Comments'}) {
 1547: 			$output .= &PrintField("Комментарии", $Question{'Comments'}, $text);
 1548: 		}
 1549: 	}
 1550: 	elsif ($answer==2) {
 1551: 	  my $text=$Question{'Answer'};
 1552: 	  $text=~s/\n/<option>/mg;
 1553: 	  $output.="<select><option selected>Ответ:<option>$text</select>";
 1554: 	  $text=$Question{'Comments'}||'';
 1555: 	  if ($text) {
 1556:              $text=~s/\n/<option>/mg;
 1557: 	     $output.="<select><option selected>Комментарий:<option>$text</select>"
 1558: 	  }
 1559: 	} 
 1560: 	elsif ($answer==3) {
 1561:         $output.=  <<EOTT
 1562: 	  <div align=right STYLE="cursor:hand;" OnStart="toggle(document.all.HideShow$qnum);" OnClick="toggle(document.all.HideShow$qnum);">
 1563: 	  <font size=-2 color=red> Показать/убрать ответ</font></div>
 1564: 	  <span style="display:none" id=HideShow$qnum>
 1565: EOTT
 1566:           .&PrintField("Ответ", $Question{'Answer'}, $text);
 1567: 		if ($Question{'Authors'}) {
 1568: 			$output .= &PrintField("Автор(ы)", $Question{'Authors'}, $text);
 1569: 		}
 1570: 		if ($Question{'PassCriteria'}) {
 1571: 			$output .= &PrintField("Зачёт", $Question{'PassCriteria'}, $text);
 1572: 		}
 1573: 
 1574: 		if ($Question{'Sources'}) {
 1575: 			$output .= &PrintField("Источник(и)", $Question{'Sources'}, $text);
 1576: 		}
 1577: 
 1578: 		if ($Question{'Comments'}) {
 1579: 			$output .= &PrintField("Комментарии", $Question{'Comments'}, $text);
 1580: 		}
 1581: 
 1582: 
 1583: 
 1584: $output.="</span>"
 1585: 
 1586: 	}
 1587: 	$output=~s/\(pic: ([^\)]*)\)/<p><img src="\/znatoki\/images\/db\/$1"><\/p>/g unless $text;
 1588: 	$output=~s/\(aud: ([^\)]*)\)/<embed type="application\/x-shockwave-flash" src="http:\/\/www.google.com\/reader\/ui\/3247397568-audio-player.swf?audioUrl=\/znatoki\/sounds\/db\/$1"  allowscriptaccess="never" width="400" height="27" quality="best" bgcolor="#ff0000" wmode="window" flashvars="playerMode=embedded" \/>/g unless $text;
 1589: 
 1590: 	$output=~s/⌡/\&iuml;/g;
 1591: 	$output=~s/⌠/\&Iuml;/g;
 1592: 
 1593: 	$paramtour||=param("tour");
 1594: 	$fname=$fname.".$Question{'TourNumber'}" if $fname && $Question{'TourNumber'};
 1595: $fname||=param('tour');
 1596: 	my $qid=$fname ? ($fname.".$Question{'Number'}" ): '';
 1597: 
 1598: 	$output.=br."\n".a({href=> "/search/"."?metod=proxy&
 1599: qid=$qid"}, 'Близкие вопросы').p
 1600:              if $answer>0 && !$text && $qid && $showNearQuestions;
 1601: 	return $output;
 1602: }
 1603: 
 1604: # Returns the total number of questions currently in the DB.
 1605: sub GetQNum {
 1606: 	my ($dbh,$x) = @_;
 1607: 	my ($sth) = $dbh->prepare("SELECT COUNT(*) FROM Questions");
 1608: 	$sth->execute;
 1609: 	my $tmp=($sth->fetchrow)[0];
 1610:         $sth->finish;
 1611: 	($sth)=  $dbh -> prepare("select distinct count(first) FROM equalto");
 1612: 	           $sth -> execute;
 1613: 	my ($c)=$sth->fetchrow;
 1614: 
 1615: #	           $i++  while ( my  ($first, $second)=$sth -> fetchrow)
 1616: #                  {
 1617: #                       $forbidden{$first}=1;
 1618: #                  }
 1619:                   $sth->finish;
 1620: 
 1621:  	return $tmp-($x?$c:0);
 1622: }
 1623: sub GetMaxQId {
 1624: 	my ($dbh) = @_;
 1625: 	my ($sth) = $dbh->prepare("SELECT MAX(QuestionId) FROM Questions");
 1626: 	$sth->execute;
 1627: 	my $tmp=($sth->fetchrow)[0];
 1628:         $sth->finish;
 1629:  	return $tmp;
 1630: 
 1631: }
 1632: 
 1633: # Returns Id's of 12 random questions
 1634: sub Get12Random {
 1635:    my ($dbh, $type, $num) = @_;
 1636: 	my ($i, @questions, $q, $t, $sth);
 1637: 	my ($qnum) = &GetMaxQId($dbh);
 1638: 	my (%chosen);
 1639: 	srand;
 1640: 	my $where=0;
 1641: 	my $r=int (rand(10000));
 1642: 	my $w1=$r<5000? "QuestionId<50000 ":"QuestionId>=50000";
 1643: 	$w1=1 if $url=~/zaba/;
 1644: 	$w1=1 if $type!~/Ч/;
 1645: 	foreach (split '', $type)
 1646:         {
 1647:  	   $where.= " OR (Type ='$_') OR (Type ='$_Д') ";
 1648:  	}
 1649:         $where.= "OR (Type='ЧБ')" if ($type=~/Ч|Б/);
 1650: 
 1651: #   $q="select QuestionId, QuestionId/$r-floor(QuestionId/$r) as val 
 1652: #       from Questions where $where order by val limit $num";
 1653: # Когда на куличках появится mysql >=3.23 надо заменить на order by rand();
 1654:    $q="select QuestionId from Questions where ($w1) AND ($where) order by rand() limit $num";
 1655: 
 1656: 
 1657:    $sth=$dbh->prepare($q);
 1658:    $sth->execute;
 1659:    while (($i)=$sth->fetchrow)
 1660:    {
 1661:       push @questions,$i;
 1662:    }
 1663:    $sth->finish;
 1664:     for ($i=@questions; --$i;){ 
 1665:        my $j=rand ($i+1); 
 1666:        @questions[$i,$j]=@questions[$j,$i] unless $i==$j;
 1667:     }
 1668:    return @questions;
 1669: }
 1670: 
 1671: sub Include_virtual {
 1672: 	my ($fn, $output) = (@_, '');
 1673: 	return "\n<!--#include virtual=\"$fn\"-->\n" if ($opt_z);
 1674: 	open F , $fn
 1675: 		or return ""; #die "Can't open the file $fn: $!\n";
 1676: 
 1677: 	while (<F>) {
 1678: 		if (/<!--#include/o) {
 1679: 			s/<!--#include virtual="\/?([^\/].*)" -->/&Include_virtual($1)/e;
 1680: 		}
 1681: 		if (/<!--#exec/o) {
 1682: 			s/<!--#exec.*cmd\s*=\s*"([^"]*)".*-->/`$1`/e;
 1683: 		}
 1684: 		$output .= $_;
 1685: 	}
 1686: 	return $output||"";
 1687: }
 1688: 
 1689: sub PrintArchive {
 1690: 	my($dbh, $Id) = @_;
 1691: 	my ($output, @list, $i);
 1692: 
 1693: 	my (%Tournament) = &GetTournament($dbh, $Id);
 1694: 	my (@Tours) = &GetTours($dbh, $Id);
 1695: 	if ($Tournament{'Type'} =~ /Г/ || $Id == 0) {
 1696: 		for ($i = 0; $i <= $#Tours; $i++) {
 1697: 			push(@list ,&PrintArchive($dbh, $Tours[$i]));
 1698: 		}
 1699: 		return @list;
 1700: 	}
 1701: #	return "$SRCPATH/$Tournament{'FileName'} ";
 1702: 	return "$TMPDIR/$Tournament{'FileName'} ";
 1703: }
 1704: 
 1705: sub PrintAll {
 1706: 	my ($dbh, $Id,$fname) = @_;
 1707: 	my ($output, $list, $i);
 1708: 
 1709: 	my (%Tournament) = &GetTournament($dbh, $Id);
 1710: 	my (@Tours) = &GetTours($dbh, $Id);
 1711: 	my $SingleTour = $#Tours == 0;
 1712: 
 1713: 	my ($New) = ($Id and $Tournament{'Type'} eq 'Ч' and
 1714: 		&NewEnough($Tournament{"CreatedAt"})) ?
 1715: 		img({src=>"/znatoki/dimrub/db/new-sml.gif", alt=>"NEW!"}) : "";
 1716: 
 1717: 	if ($Id == 0) {
 1718: 		$output = h3("Все турниры");
 1719: 	} else {
 1720: 	         my $textid;
 1721: 		 if ($textid=$Tournament{'FileName'})
 1722: 		 {
 1723: 		   $textid=~s/\.txt//;
 1724: 		 }
 1725: 		 elsif ($textid=$Tournament{'Number'})
 1726: 		 {
 1727: 		      $fname=~s/\.txt//;
 1728: 		      $textid="$fname.$textid";
 1729: 		 }
 1730: 	         else {$textid=$Tournament{'Id'}};
 1731: 
 1732: 
 1733: 		$output .= dd(img({src=>"/icons/folder.gif", alt=>"[*]"}) .
 1734:       " " . a({href=>tourhref($textid,0,!$SingleTour)},
 1735:       $Tournament{'Title'}) ." " . ($Tournament{'PlayedAt'}||'') . 
 1736:       ($Tournament{'PlayedAt2'}?'&nbsp;&ndash; '.$Tournament{'PlayedAt2'}:'') . 
 1737:       " $New");
 1738: 	}
 1739: 	if ($Id == 0 or $Tournament{'Type'} =~ /Г/ or $Tournament{'Type'} eq '') {
 1740: 		for ($i = 0; $i <= $#Tours; $i++) {
 1741: 			$list .= &PrintAll($dbh, $Tours[$i],$Tournament{'FileName'});
 1742: 		}
 1743: 		$output .= dl($list);
 1744: 	}
 1745: 	return $output;
 1746: }
 1747: 
 1748: sub PrintDates {
 1749: 	my ($dbh) = @_;
 1750: 	my ($from) = param('from_year') . "-" . param('from_month') .
 1751: 		"-" .  param('from_day');
 1752: 	my ($to) = param('to_year') . "-" . param('to_month') . "-" .  param('to_day');
 1753: 	$from = $dbh->quote($from);
 1754: 	$to = $dbh->quote($to);
 1755: 	my ($sth) = $dbh->prepare("
 1756: 		SELECT DISTINCT Id
 1757: 		FROM Tournaments
 1758: 		WHERE PlayedAt >= $from AND PlayedAt <= $to
 1759: 		AND Type = 'Ч'
 1760: 	");
 1761: 	$sth->execute;
 1762: 	my (%Tournament, @array, $output, $list);
 1763: 
 1764: 	$output = h3("Список турниров, проходивших между $from и $to.");
 1765: 	while (@array = $sth->fetchrow) {
 1766: 		next
 1767: 			if (!$array[0]);
 1768: 		%Tournament = &GetTournament($dbh, $array[0]);
 1769: 	         my $textid;
 1770: 		 if ($textid=$Tournament{'FileName'})
 1771: 		 {
 1772: 		   $textid=~s/\.txt//;
 1773: 		 }
 1774: 		 elsif ($textid=$Tournament{'Number'})
 1775: 		 {
 1776: 		      $fname=~s/\.txt//;
 1777: 		      $textid="$fname.$textid";
 1778: 		 }
 1779: 	         else {$textid=$Tournament{'Id'}};
 1780:       $list .= dd(img({src=>"/icons/folder.gif", alt=>"[*]"}) .
 1781:       " " . a({href=>tourhref($textid,0,1)},
 1782:       $Tournament{'Title'}, $Tournament{'PlayedAt'}||'', 
 1783:       $Tournament{'PlayedAt2'}?'&nbsp;&ndash; '.$Tournament{'PlayedAt2'}:''));
 1784: 	}
 1785:         $sth->finish;
 1786: 	$output .= dl($list);
 1787: 	return $output;
 1788: }
 1789: 
 1790: sub PrintQOfAuthor
 1791: {
 1792: 
 1793:     my ($dbh, $id) = @_;
 1794:     my $Output='';
 1795:     unless ($id=~/^\d+$/) {
 1796:       $id=$dbh->quote($id);
 1797:       my $sth =  $dbh->prepare("SELECT Id FROM Authors WHERE CharId=$id");
 1798:       $sth->execute;
 1799:       ($id)=$sth->fetchrow;
 1800:       $sth->finish;
 1801:     }
 1802:     $id=$dbh->quote($id);
 1803: 
 1804:     my $sth =  $dbh->prepare("SELECT  Name, Surname FROM Authors WHERE Id=$id");
 1805:     $sth->execute;
 1806:     my ($name,$surname)=$sth->fetchrow;
 1807: 
 1808:     $sth =  $dbh->prepare("SELECT Question FROM A2Q WHERE Author=$id");
 1809:     $sth->execute;
 1810:     my $q;
 1811:     my @Questions;
 1812:     while (($q)=$sth->fetchrow,$q)
 1813:      {push @Questions,$q unless $forbidden{$q}}
 1814:     $sth->finish;
 1815: 
 1816:     my ($output, $i, $suffix, $hits) = ('', 0, '', $#Questions + 1);
 1817: 
 1818:     if ($hits =~ /1.$/  || $hits =~ /[5-90]$/) {
 1819: 		$suffix = 'й';
 1820: 	} elsif ($hits =~ /1$/) {
 1821: 		$suffix = 'е';
 1822: 	} else {
 1823: 		$suffix = 'я';
 1824: 	}
 1825: 	$Output.= printform;
 1826: 	$Output.= p({align=>"center"}, "Автор ".strong("$name $surname ")
 1827: 	. " : $hits попадани$suffix.");
 1828: 
 1829: 
 1830: #	for ($i = 0; $i <= $#Questions; $i++) {
 1831: #		$output = &PrintQuestion($dbh, $Questions[$i], 1, $i + 1, 1);
 1832: #		print $output;
 1833: #	}
 1834:         $Output.=PrintList($dbh,\@Questions,'gdfgdfgdfgdfg');
 1835: }
 1836: 
 1837: 
 1838: sub PrintAuthors
 1839: {
 1840:      my ($dbh,$sort)=@_;
 1841:      my($output,$out1,@array,$sth);
 1842:      if ($sort eq 'surname')
 1843:      {
 1844:         $sth =
 1845:              $dbh->prepare("SELECT Id, Name, Surname, QNumber FROM Authors order by Surname, Name");
 1846:      }
 1847:      elsif($sort eq 'name')
 1848:      {
 1849:         $sth =
 1850:              $dbh->prepare("SELECT Id, Name, Surname, QNumber FROM Authors order by Name, Surname");
 1851:      }
 1852:      else
 1853:      {
 1854:         $sth =
 1855:              $dbh->prepare("SELECT Id, Name, Surname, QNumber FROM Authors Order by QNumber DESC, Surname");
 1856:      }
 1857: 
 1858:      $output.=h2("Авторы вопросов")."\n";
 1859:      $output.="<TABLE>";
 1860: 
 1861: 
 1862:      $sth->execute;
 1863:      $output.=Tr(th[a({href=>$url."?authors=name"},"Имя")
 1864: .", ".
 1865: a({href=>$url."?authors=surname"},"фамилия")
 1866:      , a({href=>$url."?authors=kvo"},"Количество вопросов")]);
 1867: 
 1868:      $out1='';
 1869: 
 1870:      my $ar=$sth->fetchall_arrayref;
 1871: 
 1872:      $sth->finish;
 1873: 
 1874: 
 1875:     foreach my $arr(@$ar)
 1876:      {
 1877: 
 1878:            my ($id,$name,$surname,$kvo)=@$arr;
 1879:            if (!$name || !$surname) {
 1880:               } else
 1881:            {
 1882:              my $add=Tr(td([a({href=>$url."?qofauthor=$id"},"$name $surname"), $kvo]))."\n";
 1883:              $output.=$add;
 1884:            }
 1885:      }
 1886:      $output.="</TABLE>";
 1887:      $sth->finish;
 1888:      return $output;
 1889: }
 1890: 
 1891: 
 1892: sub WriteFile {
 1893:   my ($dbh,$fname) = @_;
 1894:   $fname=~s/\s+$//;
 1895:   $fname=~s/^\s+//;
 1896:   $fname=~s/\.txt$//;
 1897:   $fname=~s/.*\/(\w+)/$1/;
 1898: 
 1899:   my $query= "SELECT Id, Title, Copyright, Info, URL, 
 1900:                       Editors, EnteredBy, PlayedAt, CreatedAt, PlayedAt2
 1901:                      from Tournaments where FileName=
 1902:                      '$fname' OR FileName=".$dbh->quote("$fname.txt");
 1903:   my $sth=$dbh->prepare($query);
 1904:   my (%Question,%editor,%qnumber,%copyright,%author,%vid,%tourtitle);
 1905:   $sth->execute;
 1906:   my ($Id, $Title, $Copyright, $Info, $URL, 
 1907:    $Editors, $EnteredBy, $PlayedAt, $CreatedAt, $PlayedAt2)=
 1908:       $sth->fetchrow;
 1909:   return -1 unless $Id;
 1910:   open (OUT, ">$TMPDIR/$fname.txt") || print STDERR "Error in $fname.txt\n";
 1911:   print OUT "Чемпионат:\n$Title\n\n";
 1912:   my $date=$PlayedAt||'00-00-00';
 1913:   my ($year,$month,$day)=split /-/, $date;
 1914: #  $month=0,$date=0 if $year && $month==1 && $day==1;
 1915:   my $pdate=sprintf("%02d-%3s-%4d",$day,$months[$month],$year);
 1916:   if ($PlayedAt2) {
 1917:     my ($year,$month,$day)=split /-/, $date;
 1918:     $pdate .= sprintf(" - %02d-%3s-%4d",$day,$months[$month],$year);    
 1919:   }
 1920: 
 1921:   print OUT "Дата:\n$pdate\n\n" if $date;
 1922: 
 1923:   print OUT "URL:\n$URL\n\n" if $URL;
 1924: 
 1925:   print OUT "Инфо:\n$Info\n\n" if $Info;
 1926: 
 1927:   print OUT "Копирайт:\n$Copyright\n\n" if $Copyright;
 1928: 
 1929:   print OUT "Редактор:\n$Editors\n\n" if $Editors;
 1930: 
 1931: 
 1932:   $query= "SELECT Id, Title, Copyright, Editors from Tournaments where ParentId=$Id order by Id";
 1933:   $sth=$dbh->prepare($query);
 1934:   $sth->execute;
 1935:   my ($tourid,$tourtitle,$cright,$editor,@tours,$vid,$author,$tourauthor);
 1936: 
 1937: 
 1938:   while (($tourid,$tourtitle,$cright,$editor)=$sth->fetchrow,$tourid)
 1939:   {
 1940: #    $text{$tourid}="Тур:\n$tourtitle\n\n";
 1941:     $query= "SELECT * from Questions where ParentId=$tourid order by QuestionId";
 1942:     my $sth1=$dbh->prepare($query);
 1943:     $sth1->execute;
 1944:     push(@tours,$tourid);
 1945:     $tourtitle{$tourid}=$tourtitle;
 1946:     $copyright{$tourid}=$cright;
 1947:     $editor{$tourid}=$editor;
 1948:     $vid='';
 1949:     my $author='';
 1950:     my $eqauthor=1;
 1951:     my $qnumber=0;
 1952:     my @arr;
 1953:     while ( (@arr=$sth1->fetchrow), $arr[0])
 1954:     {
 1955: 	my($i, $name);
 1956: 	$i=0;
 1957: 	$qnumber++;
 1958: 	foreach $name (@{$sth1->{NAME}}) {
 1959: 	        if ($arr[$i]) {
 1960:   	           $arr[$i]=~s/^(.*?)\s*$/$1/;
 1961: 		   $Question{$tourid}[$qnumber]{$name} = $arr[$i];
 1962: 		} else {
 1963:   	            $Question{$tourid}[$qnumber]{$name} = 
 1964:                    ''}
 1965:                 $i++;
 1966: 	}
 1967: 	if ($vid)
 1968:         {
 1969:           if ($vid ne $Question{$tourid}[$qnumber]{'Type'}) {print STDERR "Warning: Different types for Tournament $tourid\n"}
 1970:         } else 
 1971:         {
 1972:             $vid=$Question{$tourid}[$qnumber]{'Type'};
 1973:         } 
 1974: 
 1975: 	if ($author)
 1976:         {
 1977:           if ($author ne $Question{$tourid}[$qnumber]{'Authors'})  
 1978:           {
 1979:              $eqauthor=0;
 1980:           }
 1981:         } else 
 1982:         {
 1983:             $author=$Question{$tourid}[$qnumber]{'Authors'};
 1984:             $eqauthor=0 unless $author;
 1985:         } 
 1986:     }
 1987:     $vid{$tourid}=$vid;
 1988:     $qnumber{$tourid}=$qnumber;
 1989:     $author{$tourid}=$eqauthor ? $author : '';
 1990:   }
 1991: 
 1992: 
 1993:   $vid='';
 1994:   my $eqvid=1;
 1995:   my $eqauthor=1;
 1996:   foreach (@tours)
 1997:   {
 1998:      $vid||=$vid{$_};
 1999:      if ($vid{$_} ne $vid)
 2000:      {
 2001:         $eqvid=0;
 2002:      }
 2003:      $author||=$author{$_};
 2004:      if (!$author{$_} || ($author{$_} ne $author))
 2005:      {
 2006:         $eqauthor=0;
 2007:      }
 2008:   }
 2009:   
 2010:   print OUT "Вид:\n$vid\n\n" if $eqvid;
 2011:   print OUT "Автор:\n$author\n\n" if $eqauthor;
 2012: 
 2013:   foreach my $tour(@tours)
 2014:   {
 2015:      print OUT "Тур:\n$tourtitle{$tour}\n\n";
 2016:      print OUT "Вид:\n$vid{$tour}\n\n" if  !$eqvid;
 2017:      print OUT "Копирайт:\n$copyright{$tour}\n\n" if $copyright{$tour} && ($copyright{$tour} ne $Copyright);
 2018:      print OUT "Редактор:\n$editor{$tour}\n\n" if $editor{$tour} && ($editor{$tour} ne $Editors);
 2019:      $tourauthor=0;
 2020:      if (!$eqauthor && $author{$tour})
 2021:      { 
 2022:        print OUT "Автор:\n$author{$tour}\n\n";
 2023:        $tourauthor=1;
 2024:      }
 2025:      foreach my $q(1..$qnumber{$tour})
 2026:      {
 2027:         print OUT "Вопрос $q:\n".$Question{$tour}[$q]{'Question'}."\n\n";
 2028: 	print OUT  "Ответ:\n".$Question{$tour}[$q]{'Answer'}."\n\n";
 2029: 	print OUT  "Зачёт:\n".$Question{$tour}[$q]{'PassCriteria'}."\n\n";
 2030: 	print OUT  "Автор:\n".$Question{$tour}[$q]{'Authors'}."\n\n" 
 2031:                if !$tourauthor && !$eqauthor && $Question{$tour}[$q]{'Authors'};
 2032: 	print OUT  "Комментарий:\n".$Question{$tour}[$q]{'Comments'}."\n\n" 
 2033:                if $Question{$tour}[$q]{'Comments'};
 2034: 	print OUT "Источник:\n".$Question{$tour}[$q]{'Sources'}."\n\n" 
 2035:                if $Question{$tour}[$q]{'Sources'};
 2036: 	print OUT "Рейтинг:\n".$Question{$tour}[$q]{'Rating'}."\n\n" 
 2037:                if $Question{$tour}[$q]{'Rating'};
 2038: 
 2039:      }
 2040:   }
 2041: 
 2042:   close OUT;
 2043: 
 2044: 
 2045: 
 2046: }
 2047: 
 2048: sub Bottom
 2049: {
 2050: 	my $output.=&Include_virtual("$footer")||"";
 2051: 	$output.=p."<center><font size=-2>Обновление: ".&Include_virtual("$datefooter")."</center></font>";
 2052: 	$output.=<<EEE
 2053: <SCRIPT LANGUAGE="JavaScript">
 2054: function toggle(e) {
 2055:   if (e.style.display == "none") {
 2056:      e.style.display="";
 2057:   } else {
 2058:      e.style.display = "none";
 2059:  }
 2060: }
 2061: </SCRIPT>
 2062: EEE
 2063: ;
 2064: 	$output.=end_html;
 2065: 	return $output;
 2066: }
 2067: 
 2068: 
 2069: MAIN:
 2070: {
 2071:         
 2072: 	setlocale(LC_CTYPE,'russian');
 2073: 	POSIX::setlocale( &POSIX::LC_ALL, $thislocale );
 2074: 	my($i, $tour);
 2075: 	my($text) = (param('text')) ? 1 : 0;
 2076: 	$tour = (param('tour')) ? param('tour') : 0;
 2077: 	my $texttour=$tour;
 2078: 	my ($sth,$dbh);
 2079: 	my($dsn) = "DBI:mysql:database=$dbname;host=$dbhost";
 2080:         $dbh = DBI->connect($dsn, $dbuser, $dbpass)
 2081: #	$dbh = DBI->connect("DBI:mysql:$dbname", $username, $dbpass)
 2082: 		or do {
 2083: 			print header.h1("Временные проблемы") . "База вопросов временно не
 2084: 			работает. Заходите попозже.";
 2085: 			print &Include_virtual("$reklama") if $url!~/localhost/;
 2086: 		    print end_html;
 2087: 			die "Can't connect to DB chgk\n";
 2088: 		};
 2089:         $dbh->do("set names koi8r");
 2090: 
 2091: 	if (param('qid') && (param('qid')=~/^\d+$/) || $tour && $tour=~/^\d+$/) {
 2092: #	   my $destination='http://chgk.zaba.ru/search.html';
 2093: #		print header (-'Content-Type' => 'text/html',
 2094: #                -'Location:'=> 'http:\\db.chgk.info');
 2095: 		Redirect($destination);
 2096:                 exit
 2097: 	}
 2098: 
 2099: 	if (0 && $tour && !param('qnumber') && (!param('answers')||(param('answers')<=1)))
 2100: 	{       
 2101: 	        my $n=param('tour');
 2102: 	        $n=~s/.txt$//;        
 2103: 		my $gr=($n=~/^[A-Z]/) || (-e "$realHTMLDIR$n.html");
 2104: 		my $destination=tourhref($tour,param('answers')||0,$gr);
 2105: 		my $d=$destination;
 2106: 		$d=~s/$HTMLDIR/$realHTMLDIR/;
 2107: #		print header.$destination;
 2108: #                print header."$d|".(-e "$realHTMLDIR$n.html");
 2109:                 if (-e $d) {
 2110: 			Redirect($destination);
 2111: 			exit
 2112: 		}
 2113: 		$d=~s/\.\d+//;
 2114: 		$destination=~s/\.\d+//;
 2115:                 if (-e $d) {
 2116: 			Redirect($destination);
 2117: 			exit
 2118: 		}
 2119: 
 2120: 	}
 2121: 
 2122: 	if ($tour !~ /^[0-9]*$/) {	    
 2123: 		    if ($tour=~/\./)
 2124: 		    {
 2125: 		        my ($fname,$n)= split /\./ , $tour;
 2126: 
 2127: 	                $sth = $dbh->prepare(
 2128:                        "SELECT t2.Id FROM Tournaments as t1, 
 2129:                         Tournaments as t2 
 2130: 			WHERE (t1.FileName = '$fname.txt' OR t1.FileName='$fname')
 2131:                         AND t1.Id=t2.ParentId AND t2.Number=$n");
 2132: 		    }	
 2133: 		    else 
 2134: 		        {
 2135:                           $sth = $dbh->prepare("SELECT Id FROM Tournaments
 2136: 			             WHERE FileName = '$tour.txt' OR 
 2137:                                        FileName = '$tour'");
 2138: 			}
 2139: 		    $sth->execute;
 2140: 	            $tour = ($sth->fetchrow)[0];
 2141:                     $sth->finish;
 2142: 	}
 2143: 
 2144: 
 2145: 	if ($text && !param ('comp')) {
 2146: 		print header('text/plain');
 2147: 	} elsif (!param('comp')) {
 2148: 		print header(-charset =>'koi8-r')}
 2149: 	  my $sstr=param('sstr');
 2150:           $opt_z||=param("makehtml");
 2151: 	  if (param('qid')) {
 2152: 	      my $sth;
 2153: 	      my $qid=param('qid');
 2154: #		if ($qid !~ /^[0-9]+$/) 
 2155:                 {
 2156:                     my ($fname,$t,$n)= split /\./ , $qid;
 2157:                     $n=$t,$t='' unless $n;
 2158:                     $t||=1;
 2159: 		    if ($t)
 2160: 		    {
 2161: 	                $sth = $dbh->prepare(
 2162:                        "SELECT t2.Id FROM Tournaments as t1, 
 2163:                         Tournaments as t2 
 2164: 			WHERE (t1.FileName = '$fname.txt' OR t1.FileName='$fname')
 2165:                         AND t1.Id=t2.ParentId AND t2.Number=$t");
 2166: 		    }	
 2167: #		    else 
 2168: #		        {
 2169: #                          $sth = $dbh->prepare("SELECT Id FROM Tournaments
 2170: #			             WHERE FileName = '$fname.txt' OR FileName = '$fname'" );
 2171: #			}
 2172: 		    $sth->execute;
 2173: 	            $tour = ($sth->fetchrow)[0];
 2174:                     $sth->finish;
 2175: 	            $sth = $dbh->prepare(
 2176:                        "SELECT QuestionId FROM 
 2177:                         Questions 
 2178: 			WHERE ParentId=$tour AND 
 2179:                         Questions.Number=$n");
 2180: 		        $sth->execute;
 2181: 	                $qid = ($sth->fetchrow)[0];
 2182:               	     my $query="SELECT Question, Answer from Questions where QuestionId=$qid";
 2183: 	      	     $sth=$dbh->prepare($query);
 2184: 	      	     $sth->execute;
 2185: 	      	     $sstr= join ' ',$sth->fetchrow;
 2186:               	     $sth->finish;
 2187: 	      	     $searchin{'Question'}=1;
 2188: 	      	     $searchin{'Answer'}=1;
 2189:               	     $sstr=~tr/ёЁ/еЕ/;
 2190:               	     $sstr=~s/[^йцукенгшщзхъфывапролджэячсмитьбюЙЦУКЕНГШЩЗХЪФЫВАПРОЛДЖЭЯЧСМИТЬБЮa-zA-Z0-9]/ /gi;
 2191:               	     $proxysstr=$sstr;
 2192:               	     $proxysstr=makeproxysstr($dbh,\$proxysstr);
 2193:               } 
 2194:               
 2195:  	}
 2196: 
 2197: 
 2198: 	if (!param('comp') and !param('sqldump') and !$text) {
 2199: 	   my $title="Результаты поиска на \"". ($proxysstr||$sstr) .'"' 
 2200:                                                     if ($proxysstr||$sstr);
 2201:            $title||="База вопросов";
 2202: 	   $globaloutput.=start_html(-"title"=>$title,
 2203: 	           -author=>'dimrub@icomverse.com',
 2204: 	           -bgcolor=>'#fff0e0',
 2205: 				  -vlink=>'#800020');#}
 2206: $globaloutput.="<style>
 2207: td	{font-size: x-small; font-family : sans-serif}
 2208: th	{font-size: x-small; font-family : sans-serif}
 2209: div.razdatka { 
 2210:     background-color:#EEEEFF;
 2211:     padding:4px;
 2212:     border:1px solid black;
 2213: }
 2214: 
 2215: div.razdatka_header {font-style:italic;}
 2216: 
 2217: </style>\n";
 2218: 
 2219: 		$globaloutput.=&Include_virtual("$reklama")||'';
 2220: 	}
 2221: 
 2222:        if ($usehash && !$opt_z && length ($qs)<=255 && $qs !~ /(sstr)|(rand)|(comp)|(all=)/i) {
 2223:         	my $sth=$dbh->prepare("SELECT page,times,t from hash where query=".$dbh->quote($qs));
 2224:         	$sth->execute();
 2225:         	my ($p,$times,$t)=$sth->fetchrow();
 2226:         	$sth->finish;
 2227:         	if ($p) {
 2228: 			print ".$p";
 2229: 			$dbh->disconnect;
 2230: 			exit ;
 2231: 		}
 2232:        }
 2233: 
 2234: 
 2235: 
 2236: 
 2237:         if (param('hideequal')) {
 2238: 	           my ($sth)=  $dbh -> prepare("select first, second FROM equalto");
 2239: 	           $sth -> execute;
 2240: 	           while ( my  ($first, $second)=$sth -> fetchrow)
 2241:                   {
 2242:                        $forbidden{$first}=1;
 2243:                   }
 2244:                   $sth->finish;
 2245:         }
 2246: 
 2247: 
 2248: 
 2249: 	if (param('rand')) {
 2250: 		my ($type, $qnum) = ('', 12);
 2251: 		$type.=$TypeName{$_} foreach param('type');
 2252: #		$type .= 'Б' if (param('brain'));
 2253: #		$type .= 'Ч' if (param('chgk'));
 2254: 		$qnum = param('qnum') if (param('qnum') =~ /^\d+$/);
 2255: 		$qnum = 0 if (!$type);
 2256: 		my $Email;
 2257: 		if (($Email=param('email')) && -x $SENDMAIL &&
 2258: 		open(F, "| $SENDMAIL $Email")) {
 2259: 			my ($mime_type) = $text ? "plain" : "html";
 2260: 			print F <<EOT;
 2261: To: $Email
 2262: From: olegstepanov\@mail.ru
 2263: Subject: Sluchajnij Paket Voprosov "Chto? Gde? Kogda?"
 2264: MIME-Version: 1.0
 2265: Content-type: text/$mime_type; charset="koi8-r"
 2266: 
 2267: EOT
 2268: 			print F &PrintRandom($dbh, $type, $qnum, $text);
 2269: 			close F;
 2270: 			$globaloutput.= "Пакет случайно выбранных вопросов послан по адресу $Email. Нажмите
 2271: 			на <B>Reload</B> для получения еще одного пакета";
 2272: 		} else {
 2273: 			$globaloutput.= &PrintRandom($dbh, $type, $qnum, $text);
 2274: 		}
 2275: 	}
 2276: 	  elsif (param('authors')){
 2277:                 $globaloutput.= &PrintAuthors($dbh,param('authors'));
 2278:         }
 2279:           elsif (param('qofauthor')){
 2280:                 $globaloutput.= &PrintQOfAuthor($dbh,param('qofauthor'));
 2281:         }
 2282:           elsif (param('sstr')||param('was')) {
 2283: 		$globaloutput.=&PrintSearch($dbh, $sstr||' ', param('metod')||'',param('was'));
 2284: 		$dbh->do("delete from lastqueries where
 2285:                       (TO_DAYS(NOW()) - TO_DAYS(t) >= 2) OR
 2286: 		           (time_to_sec(now())-time_to_sec(t) >3600)") if $usewas && random(30)==0;
 2287: 	} 
 2288: 	  elsif (param('qid')) {
 2289:  	      $globaloutput.=&PrintSearch($dbh, $sstr||'', 'proxy');
 2290:  	}
 2291:  	elsif (param('getfile')){
 2292:            $globaloutput.=&writefile
 2293:  	} elsif (param('all')) {
 2294: #	   my $destination='http://db.chgk.info/all.html';
 2295: #		Redirect($destination);
 2296: #                exit;
 2297: 		$globaloutput.=&PrintAll($dbh, 0);
 2298: 	} elsif (param('from_year') && param('to_year')) {
 2299: 		$globaloutput.=&PrintDates($dbh);
 2300: 	} elsif (param('comp')) {
 2301:             print "Content-Type: application/octet-stream\n";
 2302:             print  "Content-Type: application/force-download\n";
 2303:             print  "Content-Type: application/download\n";
 2304:             print  "Content-Type: application/x-zip-compressed; name=$texttour.zip\n";
 2305:             print "Content-Disposition: attachment; filename=$texttour.zip \n\n";
 2306: 	    $tour ||= 0;
 2307: 	    my (@files) = &PrintArchive($dbh, $tour);
 2308: 	    WriteFile($dbh,$_) foreach @files;
 2309: 	    open F, "$ZIP -j - @files |";
 2310: 	    binmode(F);
 2311: 	    binmode(STDOUT);
 2312: 	    print join "",<F>;
 2313: 	    close F;
 2314: 	    $dbh->disconnect;
 2315: 	    exit;
 2316: 	} elsif (param('sqldump')) {
 2317: 	    print header(
 2318: 			 -'Content-Type' => 'application/x-zip-compressed; name="dump.zip"',
 2319: 			 -'Content-Disposition' => 'attachment; filename="dump.zip"'
 2320: 			 );
 2321: 	    open F, "$ZIP -j - $DUMPFILE |";
 2322: 	    print (<F>);
 2323: 	    close F;
 2324: 	    $dbh->disconnect;
 2325: 	    exit;
 2326: 
 2327: 	} 
 2328:         elsif (!$opt_z && !param("makehtml")) {
 2329: 		my $QuestionNumber=0;
 2330: 		my $qnum;
 2331: 		if ($qnum=param('qnumber')){
 2332:       	          my ($sth) = $dbh->prepare("SELECT QuestionId FROM Questions
 2333: 		     WHERE ParentId=$tour AND Number=$qnum");
 2334: 		  $sth->execute;
 2335: 		  $QuestionNumber=($sth->fetchrow)[0]||0;
 2336: 	        }
 2337: 	        if ($QuestionNumber) {
 2338: 		  $globaloutput.= &PrintQuestion($dbh, $QuestionNumber, $withanswers||0, $qnum, 1,$text,0);
 2339: #                                        $dbh, $Id, $answer, $qnum, $title, $text
 2340: 		} else  {
 2341:   		   $globaloutput.=&PrintTournament($dbh, $tour, $withanswers);
 2342:   		}
 2343: 	}
 2344: 	else {
 2345: 	          $opt_z=1;
 2346: 	          $url="http://db.chgk.info/cgi-bin/db.cgi";
 2347: 	          open TS, $timestamp;
 2348: 	          my $d=$dbh->quote(<TS>);
 2349: 	          close TS;
 2350: 		  open FF, ">${realHTMLDIR}index.html" or die "ERROR! - ${HTMLDIR}index.html\n";
 2351: 		       my $o=$globaloutput;
 2352: 		       $o.=&PrintTournament($dbh, 0, 0);
 2353: 		       $o.=&Bottom;
 2354: 		       print FF $o;
 2355: 		  close FF;
 2356: 		  open FF, ">${realHTMLDIR}all.html" or die "ERROR! - ${HTMLDIR}all.html\n";
 2357: 		       $o=$globaloutput;
 2358: 		       $o.=&PrintAll($dbh,0);
 2359: 		       $o.=&Bottom;
 2360: 		       print FF $o;
 2361: 		       close FF;
 2362: 
 2363: 
 2364: #      	          my ($sth) = $dbh->prepare("SELECT t1.Id, t1.FileName, t1.Type, 
 2365: #			count(t2.Id) 
 2366: #                     FROM Tournaments as t1, Tournaments as t2
 2367: #		     WHERE t1.CreatedAt>$d AND t2.ParentId=t1.Id GROUP BY t1.Id");
 2368: my ($sth) = $dbh->prepare("SELECT t1.Id, t1.FileName, t1.Type, count(t2.Id)  FROM Tournaments as t1  LEFT JOIN Tournaments as t2 
 2369:  ON t2.ParentId=t1.id WHERE t1.CreatedAt>=$d GROUP BY t1.Id");
 2370: 		  $sth->execute;
 2371: 		  my ($Id,$fname,$type,$c);
 2372: 		  while (($Id,$fname,$type,$c)=$sth->fetchrow,$Id) {
 2373: 		     next unless $fname;
 2374: 		     print "$fname\n";
 2375: 		     $fname=~s/\.txt$//;
 2376: 		     if ($type=~/Т/ || $c<=1)
 2377: 		     {
 2378: 		       open FF, ">$realHTMLDIR$fname-q.html" or die "ERROR! - $fname-q.html\n";
 2379: 		       my $o=$globaloutput;
 2380: 		       $paramtour=$fname;
 2381: 		       $o.=&PrintTournament($dbh, $Id, 0);
 2382: 		       $o.=&Bottom;
 2383: 		       print FF $o;
 2384: 		       close FF;
 2385: 		       open FF, ">$realHTMLDIR$fname-a.html";
 2386: 		       $o=$globaloutput;
 2387: 		       $o.=&PrintTournament($dbh, $Id, 1);
 2388: 		       $o.=&Bottom;
 2389: 		       print FF $o;
 2390: 		       close FF;
 2391: 		     }
 2392: 		     else {
 2393: 		       open FF, ">$realHTMLDIR$fname.html" or die "ERROR! - $fname-q.html\n";
 2394: 		       my $o=$globaloutput;
 2395: 		       $o.=&PrintTournament($dbh, $Id, 0);
 2396: 		       $o.=&Bottom;
 2397: 		       print FF $o;
 2398: 		       close FF;
 2399: 
 2400: 		     }
 2401:                   }
 2402:         }
 2403: 	if (!$text) {
 2404: 		$globaloutput.=&Bottom;
 2405: 	}
 2406:         if (!$opt_z){ 
 2407: 	  print $globaloutput;
 2408: 	  if (($qs!~ /(rand)|(sstr)|(comp)/i) && (length $qs<=255) && $usehash) {
 2409: 		$globaloutput=  $dbh->quote($globaloutput);
 2410: 		$dbh->do("insert into hash (query,page) values (".
 2411: 		$dbh->quote($qs).
 2412:                     ",$globaloutput)");
 2413: 	  }
 2414: 	}
 2415: 
 2416: 	$dbh->disconnect;
 2417: }

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