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

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

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