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

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

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