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

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

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