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

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

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