Annotation of db/prgsrc/db.cgi, revision 1.103

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

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