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

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

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