File:  [Local Repository] / db / prgsrc / db.cgi
Revision 1.156: download - view: text, annotated - select for diffs - revision graph
Sun Jan 10 19:19:44 2010 UTC (14 years, 4 months ago) by roma7
Branches: MAIN
CVS tags: HEAD
Razdatka fix

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

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