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

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);
1.65    ! roma7    1029:        $qnum = $Question{'Number'}
        !          1030:                if ($qnum == 0);
1.1       boris    1031:        if (!$text) {
                   1032:                $output .= hr({width=>"50%"});
                   1033:                if ($title) {
                   1034:                        my (%Tour) = GetTournament($dbh, $Question{'ParentId'});
                   1035:                        my (%Tournament) = GetTournament($dbh, $Tour{'ParentId'});
1.54      roma7    1036:                        my $fname=$Tournament{'FileName'};
                   1037:                        $fname=~s/\.txt//;
1.1       boris    1038:                        $titles .=
                   1039:                                dd(img({src=>"/icons/folder.open.gif"}) . " " .
1.54      roma7    1040:                                         a({href=>url . "?tour=$fname"}, $Tournament{'Title'}, $Tournament{'PlayedAt'}));
1.1       boris    1041:                        $titles .=
                   1042:                                dl(dd(img({src=>"/icons/folder.open.gif"}) . " " .
1.65    ! roma7    1043:                                        a({href=>url . "?tour=$fname.$Tour{Number}#$qnum"}, $Tour{'Title'})));
1.1       boris    1044:                }
                   1045:                $output .= dl(strong($titles));
                   1046:        }
1.37      roma7    1047: 
1.65    ! roma7    1048: 
        !          1049:        $output.= "<a NAME=\"$qnum\">";
1.1       boris    1050: 
1.37      roma7    1051:        $output .=
1.1       boris    1052:                &PrintField("Вопрос $qnum", $Question{'Question'}, $text);
                   1053: 
                   1054:        if ($answer) {
1.37      roma7    1055:                $output .=
1.1       boris    1056:                        &PrintField("Ответ", $Question{'Answer'}, $text);
                   1057: 
                   1058:                if ($Question{'Authors'}) {
1.29      roma7    1059:                       my $q=$Question{'Authors'};
                   1060: 
1.47      roma7    1061: #                    my $sth=$dbh->prepare("select Authors.Id,Name, Surname, Nicks from Authors, A2Q
                   1062: #                                 where Authors.Id=Author And Question=$Id");
                   1063: #                      $sth->execute;
                   1064: #                      my ($AuthorId,$Name, $Surname,$other,$Nicks);
                   1065: 
                   1066: #                      while ((($AuthorId,$Name, $Surname,$Nicks)=$sth->fetchrow),$AuthorId)
                   1067: #                      {
                   1068: #                        my ($firstletter)=$Name=~m/^./g;
                   1069: #                         $Name=~s/\./\\\./g;
                   1070: #                          my $sha="(?:$Name\\s+$Surname)|(?:$Surname\\s+$Name)|(?:$firstletter\\.\\s*$Surname)|(?:$Surname\\s+$firstletter\\.)|(?:$Surname)|(?:$Name)";
                   1071: #                          if ($Nicks)
                   1072: #                          {
                   1073: #                            $Nicks=~s/^\|//;
                   1074: #                            foreach (split /\|/, $Nicks)
                   1075: #                            {
                   1076: #                              s/\s+/ /g;
                   1077: #                              s/\s+$//;
                   1078: #                              s/ /\\s+/g;
                   1079: #                              s/\./\\\./g;
                   1080: #                              if (s/>$//) {$sha="$sha|(?:$_)"}
                   1081: #                              else        {$sha="(?:$_)|$sha"}
                   1082: #                            }
                   1083: #                          }
                   1084: #                          $q=~s/($sha)/a({href=>url."?qofauthor=$AuthorId"},$1)/ei;
                   1085: #                      }
1.29      roma7    1086: 
                   1087:                        $output .= &PrintField("Автор(ы)", $q, $text);
                   1088: 
                   1089: #                        $output.= &PrintField("Другие вопросы", $other);
1.1       boris    1090:                }
                   1091: 
                   1092:                if ($Question{'Sources'}) {
                   1093:                        $output .= &PrintField("Источник(и)", $Question{'Sources'}, $text);
                   1094:                }
                   1095: 
                   1096:                if ($Question{'Comments'}) {
                   1097:                        $output .= &PrintField("Комментарии", $Question{'Comments'}, $text);
                   1098:                }
                   1099:        }
1.45      roma7    1100: #      $output.=br.a({href=> url."?metod=proxy&qid=$Id"}, 'Близкие вопросы').p
                   1101: #             if $answer;
1.1       boris    1102:        return $output;
                   1103: }
                   1104: 
                   1105: # Returns the total number of questions currently in the DB.
                   1106: sub GetQNum {
                   1107:        my ($dbh) = @_;
                   1108:        my ($sth) = $dbh->prepare("SELECT COUNT(*) FROM Questions");
                   1109:        $sth->execute;
1.54      roma7    1110:        my $tmp=($sth->fetchrow)[0];
                   1111:         $sth->finish;
                   1112:        return $tmp;
1.1       boris    1113: }
1.12      boris    1114: sub GetMaxQId {
                   1115:        my ($dbh) = @_;
                   1116:        my ($sth) = $dbh->prepare("SELECT MAX(QuestionId) FROM Questions");
                   1117:        $sth->execute;
1.54      roma7    1118:        my $tmp=($sth->fetchrow)[0];
                   1119:         $sth->finish;
                   1120:        return $tmp;
                   1121: 
1.12      boris    1122: }
1.1       boris    1123: 
                   1124: # Returns Id's of 12 random questions
                   1125: sub Get12Random {
                   1126:    my ($dbh, $type, $num) = @_;
                   1127:        my ($i, @questions, $q, $t, $sth);
1.12      boris    1128:        my ($qnum) = &GetMaxQId($dbh);
1.1       boris    1129:        my (%chosen);
                   1130:        srand;
1.37      roma7    1131: 
1.53      roma7    1132:        my $where=0;
                   1133:        my $r=int (rand(10000));
                   1134: 
                   1135:        foreach (split '', $type)
                   1136:         {
                   1137:           $where.= " OR (Type ='$_') OR (Type ='$_Д') ";
                   1138:        }
                   1139:         $where.= "OR (Type='ЧБ')" if ($type=~/Ч|Б/);
                   1140: 
                   1141:    $q="select QuestionId, QuestionId/$r-floor(QuestionId/$r) as val 
                   1142:        from Questions where $where order by val limit $num";
                   1143: 
                   1144: # Когда на куличках появится mysql >=3.23 надо заменить на order by rand();
                   1145: 
                   1146:    $sth=$dbh->prepare($q);
                   1147:    $sth->execute;
                   1148:    while (($i)=$sth->fetchrow)
                   1149:    {
                   1150:       push @questions,$i;
1.11      boris    1151:    }
1.54      roma7    1152:    $sth->finish;
1.53      roma7    1153:     for ($i=@questions; --$i;){ 
                   1154:        my $j=rand ($i+1); 
                   1155:        @questions[$i,$j]=@questions[$j,$i] unless $i==$j;
                   1156:     }
1.11      boris    1157:    return @questions;
1.1       boris    1158: }
                   1159: 
                   1160: sub Include_virtual {
                   1161:        my ($fn, $output) = (@_, '');
                   1162: 
                   1163:        open F , $fn
1.2       boris    1164:                or return; #die "Can't open the file $fn: $!\n";
1.37      roma7    1165: 
1.1       boris    1166:        while (<F>) {
                   1167:                if (/<!--#include/o) {
                   1168:                        s/<!--#include virtual="\/(.*)" -->/&Include_virtual($1)/e;
                   1169:                }
                   1170:                if (/<!--#exec/o) {
                   1171:                        s/<!--#exec.*cmd\s*=\s*"([^"]*)".*-->/`$1`/e;
                   1172:                }
                   1173:                $output .= $_;
                   1174:        }
                   1175:        return $output;
                   1176: }
                   1177: 
                   1178: sub PrintArchive {
                   1179:        my($dbh, $Id) = @_;
                   1180:        my ($output, @list, $i);
                   1181: 
                   1182:        my (%Tournament) = &GetTournament($dbh, $Id);
                   1183:        my (@Tours) = &GetTours($dbh, $Id);
1.37      roma7    1184: 
1.1       boris    1185:        if ($Tournament{'Type'} =~ /Г/ || $Id == 0) {
                   1186:                for ($i = 0; $i <= $#Tours; $i++) {
                   1187:                        push(@list ,&PrintArchive($dbh, $Tours[$i]));
                   1188:                }
                   1189:                return @list;
                   1190:        }
1.60      roma7    1191: #      return "$SRCPATH/$Tournament{'FileName'} ";
                   1192:        return "$TMPDIR/$Tournament{'FileName'} ";
1.1       boris    1193: }
                   1194: 
                   1195: sub PrintAll {
1.54      roma7    1196:        my ($dbh, $Id,$fname) = @_;
1.1       boris    1197:        my ($output, $list, $i);
                   1198: 
                   1199:        my (%Tournament) = &GetTournament($dbh, $Id);
                   1200:        my (@Tours) = &GetTours($dbh, $Id);
1.37      roma7    1201:        my ($New) = ($Id and $Tournament{'Type'} eq 'Ч' and
1.1       boris    1202:                &NewEnough($Tournament{"CreatedAt"})) ?
                   1203:                img({src=>"/znatoki/dimrub/db/new-sml.gif", alt=>"NEW!"}) : "";
                   1204: 
                   1205:        if ($Id == 0) {
                   1206:                $output = h3("Все турниры");
                   1207:        } else {
1.54      roma7    1208:                 my $textid;
                   1209:                 if ($textid=$Tournament{'FileName'})
                   1210:                 {
                   1211:                   $textid=~s/\.txt//;
                   1212:                 }
                   1213:                 elsif ($textid=$Tournament{'Number'})
                   1214:                 {
                   1215:                      $fname=~s/\.txt//;
                   1216:                      $textid="$fname.$textid";
                   1217:                 }
                   1218:                 else {$textid=$Tournament{'Id'}};
                   1219: 
                   1220: 
1.1       boris    1221:                $output .= dd(img({src=>"/icons/folder.gif", alt=>"[*]"}) .
1.54      roma7    1222:       " " . a({href=>url . "?tour=$textid&answer=0"},
1.6       boris    1223:       $Tournament{'Title'}) ." " . $Tournament{'PlayedAt'} . " $New");
1.1       boris    1224:        }
1.54      roma7    1225:        if ($Id == 0 or $Tournament{'Type'} =~ /Г/ or $Tournament{'Type'} eq '') {
1.1       boris    1226:                for ($i = 0; $i <= $#Tours; $i++) {
1.54      roma7    1227:                        $list .= &PrintAll($dbh, $Tours[$i],$Tournament{'FileName'});
1.1       boris    1228:                }
                   1229:                $output .= dl($list);
                   1230:        }
                   1231:        return $output;
                   1232: }
                   1233: 
                   1234: sub PrintDates {
                   1235:        my ($dbh) = @_;
1.37      roma7    1236:        my ($from) = param('from_year') . "-" . param('from_month') .
1.1       boris    1237:                "-" .  param('from_day');
                   1238:        my ($to) = param('to_year') . "-" . param('to_month') . "-" .  param('to_day');
                   1239:        $from = $dbh->quote($from);
                   1240:        $to = $dbh->quote($to);
                   1241:        my ($sth) = $dbh->prepare("
                   1242:                SELECT DISTINCT Id
                   1243:                FROM Tournaments
                   1244:                WHERE PlayedAt >= $from AND PlayedAt <= $to
                   1245:                AND Type = 'Ч'
                   1246:        ");
                   1247:        $sth->execute;
                   1248:        my (%Tournament, @array, $output, $list);
                   1249: 
                   1250:        $output = h3("Список турниров, проходивших между $from и $to.");
                   1251:        while (@array = $sth->fetchrow) {
                   1252:                next
                   1253:                        if (!$array[0]);
                   1254:                %Tournament = &GetTournament($dbh, $array[0]);
                   1255:       $list .= dd(img({src=>"/icons/folder.gif", alt=>"[*]"}) .
                   1256:       " " . a({href=>url . "?tour=$Tournament{'Id'}&answer=0"},
1.6       boris    1257:       $Tournament{'Title'}, $Tournament{'PlayedAt'}));
1.1       boris    1258:        }
1.49      roma7    1259:         $sth->finish;
1.1       boris    1260:        $output .= dl($list);
                   1261:        return $output;
                   1262: }
                   1263: 
1.29      roma7    1264: sub PrintQOfAuthor
                   1265: {
1.41      roma7    1266: 
1.29      roma7    1267:     my ($dbh, $id) = @_;
                   1268:    $id=$dbh->quote($id);
1.37      roma7    1269:     my $sth =  $dbh->prepare("SELECT  Name, Surname FROM Authors WHERE Id=$id");
1.29      roma7    1270:     $sth->execute;
                   1271:     my ($name,$surname)=$sth->fetchrow;
                   1272: 
1.37      roma7    1273:     $sth =  $dbh->prepare("SELECT Question FROM A2Q WHERE Author=$id");
1.29      roma7    1274:     $sth->execute;
                   1275:     my $q;
1.37      roma7    1276:     my @Questions;
1.29      roma7    1277:     while (($q)=$sth->fetchrow,$q)
1.36      roma7    1278:      {push @Questions,$q unless $forbidden{$q}}
1.49      roma7    1279:     $sth->finish;
1.29      roma7    1280: 
                   1281:     my ($output, $i, $suffix, $hits) = ('', 0, '', $#Questions + 1);
                   1282: 
                   1283:     if ($hits =~ /1.$/  || $hits =~ /[5-90]$/) {
                   1284:                $suffix = 'й';
                   1285:        } elsif ($hits =~ /1$/) {
                   1286:                $suffix = 'е';
                   1287:        } else {
1.37      roma7    1288:                $suffix = 'я';
1.29      roma7    1289:        }
1.41      roma7    1290:        print h2("Поиск в базе вопросов");
                   1291:        print printform;
1.37      roma7    1292:        print p({align=>"center"}, "Автор ".strong("$name $surname. ")
1.29      roma7    1293:        . " : $hits попадани$suffix.");
                   1294: 
                   1295: 
1.40      roma7    1296: #      for ($i = 0; $i <= $#Questions; $i++) {
                   1297: #              $output = &PrintQuestion($dbh, $Questions[$i], 1, $i + 1, 1);
                   1298: #              print $output;
                   1299: #      }
                   1300:         PrintList($dbh,\@Questions,'gdfgdfgdfgdfg');
1.29      roma7    1301: }
                   1302: 
                   1303: 
                   1304: sub PrintAuthors
                   1305: {
                   1306:      my ($dbh,$sort)=@_;
                   1307:      my($output,$out1,@array,$sth);
1.37      roma7    1308:      if ($sort eq 'surname')
1.29      roma7    1309:      {
1.37      roma7    1310:         $sth =
                   1311:              $dbh->prepare("SELECT Id, Name, Surname, QNumber FROM Authors order by Surname, Name");
                   1312:      }
                   1313:      elsif($sort eq 'name')
                   1314:      {
                   1315:         $sth =
                   1316:              $dbh->prepare("SELECT Id, Name, Surname, QNumber FROM Authors order by Name, Surname");
1.29      roma7    1317:      }
                   1318:      else
                   1319:      {
1.37      roma7    1320:         $sth =
                   1321:              $dbh->prepare("SELECT Id, Name, Surname, QNumber FROM Authors Order by QNumber DESC, Surname");
1.29      roma7    1322:      }
                   1323: 
1.37      roma7    1324:      $output.=h2("Авторы вопросов")."\n";
                   1325:      $output.="<TABLE>";
                   1326: 
                   1327: 
1.29      roma7    1328:      $sth->execute;
1.37      roma7    1329:      $output.=Tr(th[a({href=>url."?authors=name"},"Имя")
                   1330: .", ".
                   1331: a({href=>url."?authors=surname"},"фамилия")
                   1332:      , a({href=>url."?authors=kvo"},"Количество вопросов")]);
1.29      roma7    1333: 
                   1334:      $out1='';
                   1335: 
                   1336:      my $ar=$sth->fetchall_arrayref;
                   1337: 
1.54      roma7    1338:      $sth->finish;
1.29      roma7    1339: 
1.33      boris    1340: 
1.29      roma7    1341:     foreach my $arr(@$ar)
                   1342:      {
1.37      roma7    1343: 
1.29      roma7    1344:            my ($id,$name,$surname,$kvo)=@$arr;
1.37      roma7    1345:            if (!$name || !$surname) {#print "Opanki at $id\n"
                   1346:               } else
1.29      roma7    1347:            {
1.37      roma7    1348:              my $add=Tr(td([a({href=>url."?qofauthor=$id"},"$name $surname"), $kvo]))."\n";
1.29      roma7    1349:              print STDERR $add;
                   1350:              $output.=$add;
                   1351:            }
                   1352:      }
                   1353:      $output.="</TABLE>";
1.49      roma7    1354:      $sth->finish;
1.29      roma7    1355:      return $output;
                   1356: }
                   1357: 
                   1358: 
1.60      roma7    1359: sub WriteFile {
                   1360:   my ($dbh,$fname) = @_;
                   1361:   $fname=~s/\.txt$//;
                   1362:   $fname=~s/.*\/(\w+)/$1/;
                   1363:   my $query= "SELECT Id, Title, Copyright, Info, URL, 
                   1364:                       Editors, EnteredBy, PlayedAt, CreatedAt 
                   1365:                      from Tournaments where FileName=".$dbh->quote("$fname.txt");
                   1366:   my $sth=$dbh->prepare($query);
                   1367:   my (%Question,%editor,%qnumber,%copyright,%author,%vid,%tourtitle);
                   1368:   $sth->execute;
                   1369:   my ($Id, $Title, $Copyright, $Info, $URL, 
                   1370:    $Editors, $EnteredBy, $PlayedAt, $CreatedAt)=
                   1371:       $sth->fetchrow;
                   1372:   return -1 unless $Id;
                   1373:   open (OUT, ">$TMPDIR/$fname.txt");
                   1374:   print OUT "Чемпионат:\n$Title\n\n";
                   1375:   my $date=$PlayedAt;
                   1376:   my ($year,$month,$day)=split /-/, $date;
                   1377: #  $month=0,$date=0 if $year && $month==1 && $day==1;
                   1378:   my $pdate=sprintf("%02d-%3s-%4d",$day,$months[$month],$year);
                   1379: 
                   1380:   print OUT "Дата:\n$pdate\n\n" if $date;
                   1381: 
                   1382:   print OUT "URL:\n$URL\n\n" if $URL;
                   1383: 
                   1384:   print OUT "Инфо:\n$Info\n\n" if $Info;
                   1385: 
                   1386:   print OUT "Копирайт:\n$Copyright\n\n" if $Copyright;
                   1387: 
                   1388:   print OUT "Редактор:\n$Editors\n\n" if $Editors;
                   1389: 
                   1390: 
                   1391:   $query= "SELECT Id, Title, Copyright, Editors from Tournaments where ParentId=$Id order by Id";
                   1392:   $sth=$dbh->prepare($query);
                   1393:   $sth->execute;
                   1394:   my ($tourid,$tourtitle,$cright,$editor,@tours,$vid,$author,$tourauthor);
                   1395: 
                   1396: 
                   1397:   while (($tourid,$tourtitle,$cright,$editor)=$sth->fetchrow,$tourid)
                   1398:   {
                   1399: #    $text{$tourid}="Тур:\n$tourtitle\n\n";
                   1400:     $query= "SELECT * from Questions where ParentId=$tourid order by QuestionId";
                   1401:     my $sth1=$dbh->prepare($query);
                   1402:     $sth1->execute;
                   1403:     push(@tours,$tourid);
                   1404:     $tourtitle{$tourid}=$tourtitle;
                   1405:     $copyright{$tourid}=$cright;
                   1406:     $editor{$tourid}=$editor;
                   1407:     $vid='';
                   1408:     my $author='';
                   1409:     my $eqauthor=1;
                   1410:     my $qnumber=0;
                   1411:     my @arr;
                   1412:     while ( @arr=$sth1->fetchrow, $arr[0])
                   1413:     {
                   1414:        my($i, $name) = 0;
                   1415:        $qnumber++;
                   1416:        foreach $name (@{$sth1->{NAME}}) {
                   1417:                $arr[$i]=~s/^(.*?)\s*$/$1/;
                   1418:                $Question{$tourid}[$qnumber]{$name} = $arr[$i++];
                   1419:        }
                   1420:        if ($vid)
                   1421:         {
                   1422:           if ($vid ne $Question{$tourid}[$qnumber]{'Type'}) {print STDERR "Warning: Different types for Tournament $tourid\n"}
                   1423:         } else 
                   1424:         {
                   1425:             $vid=$Question{$tourid}[$qnumber]{'Type'};
                   1426:         } 
                   1427: 
                   1428:        if ($author)
                   1429:         {
                   1430:           if ($author ne $Question{$tourid}[$qnumber]{'Authors'})  
                   1431:           {
                   1432:              $eqauthor=0;
                   1433:           }
                   1434:         } else 
                   1435:         {
                   1436:             $author=$Question{$tourid}[$qnumber]{'Authors'};
                   1437:             $eqauthor=0 unless $author;
                   1438:         } 
                   1439:     }
                   1440:     $vid{$tourid}=$vid;
                   1441:     $qnumber{$tourid}=$qnumber;
                   1442:     $author{$tourid}=$eqauthor ? $author : '';
                   1443:   }
                   1444: 
                   1445: 
                   1446:   $vid='';
                   1447:   my $eqvid=1;
                   1448:   my $eqauthor=1;
                   1449:   foreach (@tours)
                   1450:   {
                   1451:      $vid||=$vid{$_};
                   1452:      if ($vid{$_} ne $vid)
                   1453:      {
                   1454:         $eqvid=0;
                   1455:      }
                   1456:      $author||=$author{$_};
                   1457:      if (!$author{$_} || ($author{$_} ne $author))
                   1458:      {
                   1459:         $eqauthor=0;
                   1460:      }
                   1461:   }
                   1462:   
                   1463:   print OUT "Вид:\n$vid\n\n" if $eqvid;
                   1464:   print OUT "Автор:\n$author\n\n" if $eqauthor;
                   1465: 
                   1466:   foreach my $tour(@tours)
                   1467:   {
                   1468:      print OUT "Тур:\n$tourtitle{$tour}\n\n";
                   1469:      print OUT "Вид:\n$vid{$tour}\n\n" if  !$eqvid;
                   1470:      print OUT "Копирайт:\n$copyright{$tour}\n\n" if $copyright{$tour} && ($copyright{$tour} ne $Copyright);
                   1471:      print OUT "Редактор:\n$editor{$tour}\n\n" if $editor{$tour} && ($editor{$tour} ne $Editors);
                   1472:      $tourauthor=0;
                   1473:      if (!$eqauthor && $author{$tour})
                   1474:      { 
                   1475:        print OUT "Автор:\n$author{$tour}\n\n";
                   1476:        $tourauthor=1;
                   1477:      }
                   1478:      foreach my $q(1..$qnumber{$tour})
                   1479:      {
                   1480:         print OUT "Вопрос $q:\n".$Question{$tour}[$q]{'Question'}."\n\n";
                   1481:        print OUT  "Ответ:\n".$Question{$tour}[$q]{'Answer'}."\n\n";
                   1482:        print OUT  "Автор:\n".$Question{$tour}[$q]{'Authors'}."\n\n" 
                   1483:                if !$tourauthor && !$eqauthor && $Question{$tour}[$q]{'Authors'};
                   1484:        print OUT  "Комментарий:\n".$Question{$tour}[$q]{'Comments'}."\n\n" 
                   1485:                if $Question{$tour}[$q]{'Comments'};
                   1486:        print OUT "Источник:\n".$Question{$tour}[$q]{'Sources'}."\n\n" 
                   1487:                if $Question{$tour}[$q]{'Sources'};
                   1488:        print OUT "Рейтинг:\n".$Question{$tour}[$q]{'Rating'}."\n\n" 
                   1489:                if $Question{$tour}[$q]{'Rating'};
                   1490: 
                   1491:      }
                   1492:   }
                   1493: 
                   1494:   close OUT;
                   1495: 
                   1496: 
                   1497: 
                   1498: }
                   1499: 
1.37      roma7    1500: 
1.1       boris    1501: MAIN:
                   1502: {
                   1503:        setlocale(LC_CTYPE,'russian');
                   1504:        my($i, $tour);
                   1505:        my($text) = (param('text')) ? 1 : 0;
1.36      roma7    1506: 
1.1       boris    1507:        my($dbh) = DBI->connect("DBI:mysql:chgk", "piataev", "")
                   1508:                or do {
                   1509:                        print h1("Временные проблемы") . "База данных временно не
                   1510:                        работает. Заходите попозже.";
                   1511:                        print &Include_virtual("../dimrub/db/reklama.html");
                   1512:                    print end_html;
                   1513:                        die "Can't connect to DB chgk\n";
                   1514:                };
1.11      boris    1515:        if (!param('comp') and !param('sqldump') and !$text) {
1.1       boris    1516:           print header;
                   1517:           print start_html(-"title"=>'Database of the questions',
                   1518:                   -author=>'dimrub@icomverse.com',
                   1519:                   -bgcolor=>'#fff0e0',
                   1520:                                  -vlink=>'#800020');
                   1521:                print &Include_virtual("../dimrub/db/reklama.html");
                   1522:        }
1.22      roma7    1523: 
1.41      roma7    1524: 
1.22      roma7    1525: if ($^O =~ /win/i) {
                   1526:        $thislocale = "Russian_Russia.20866";
                   1527: } else {
                   1528:        $thislocale = "ru_RU.KOI8-R";
                   1529: }
                   1530: POSIX::setlocale( &POSIX::LC_ALL, $thislocale );
                   1531: 
                   1532: if ((uc 'а') ne 'А') {print "Koi8-r locale not installed!\n"};
                   1533: 
1.1       boris    1534: 
                   1535:        if ($text) {
                   1536:                print header('text/plain');
                   1537:        }
1.36      roma7    1538: 
1.37      roma7    1539:         if (param('hideequal')) {
1.36      roma7    1540:                   my ($sth)=  $dbh -> prepare("select first, second FROM equalto");
                   1541:                   $sth -> execute;
                   1542:                   while ( my  ($first, $second)=$sth -> fetchrow)
                   1543:                   {
                   1544:                        $forbidden{$first}=1;
                   1545:                   }
                   1546:                   $sth->finish;
1.37      roma7    1547:         }
1.36      roma7    1548: 
1.1       boris    1549: 
                   1550:        if (param('rand')) {
1.7       boris    1551:                my ($type, $qnum) = ('', 12);
1.53      roma7    1552:                $type.=$TypeName{$_} foreach param('type');
                   1553: #              $type .= 'Б' if (param('brain'));
                   1554: #              $type .= 'Ч' if (param('chgk'));
1.37      roma7    1555:                $qnum = param('qnum') if (param('qnum') =~ /^\d+$/);
1.7       boris    1556:                $qnum = 0 if (!$type);
1.52      roma7    1557:                my $Email;
                   1558:                if (($Email=param('email')) && -x $SENDMAIL &&
                   1559:                open(F, "| $SENDMAIL $Email")) {
1.1       boris    1560:                        my ($mime_type) = $text ? "plain" : "html";
                   1561:                        print F <<EOT;
                   1562: To: $Email
1.52      roma7    1563: From: olegstepanov\@mail.ru
1.1       boris    1564: Subject: Sluchajnij Paket Voprosov "Chto? Gde? Kogda?"
                   1565: MIME-Version: 1.0
                   1566: Content-type: text/$mime_type; charset="koi8-r"
                   1567: 
                   1568: EOT
                   1569:                        print F &PrintRandom($dbh, $type, $qnum, $text);
                   1570:                        close F;
1.52      roma7    1571:                        print "Пакет случайно выбранных вопросов послан по адресу $Email. Нажмите
1.1       boris    1572:                        на <B>Reload</B> для получения еще одного пакета";
                   1573:                } else {
                   1574:                        print &PrintRandom($dbh, $type, $qnum, $text);
                   1575:                }
1.37      roma7    1576:        }
1.29      roma7    1577:          elsif (param('authors')){
                   1578:                 print &PrintAuthors($dbh,param('authors'));
                   1579:         }
                   1580:           elsif (param('qofauthor')){
                   1581:                 &PrintQOfAuthor($dbh,param('qofauthor'));
                   1582:         }
1.54      roma7    1583:           elsif (param('sstr')||param('was')) {
                   1584:                &PrintSearch($dbh, param('sstr'), param('metod'),param('was'));
                   1585:                $dbh->do("delete from lastqueries where
1.57      roma7    1586:                       (TO_DAYS(NOW()) - TO_DAYS(t) >= 2) OR
                   1587:                           (time_to_sec(now())-time_to_sec(t) >3600)")
1.40      roma7    1588:        } 
                   1589:          elsif (param('qid')) {
                   1590:              my $qid=param('qid');
                   1591:               my $query="SELECT Question, Answer from Questions where QuestionId=$qid";
                   1592: print $query if $printqueries;
                   1593:              my $sth=$dbh->prepare($query);
                   1594:              $sth->execute;
                   1595:              my $sstr= join ' ',$sth->fetchrow;
1.49      roma7    1596:               $sth->finish;
1.41      roma7    1597:              $searchin{'Question'}=1;
                   1598:              $searchin{'Answer'}=1;
                   1599:       $sstr=~tr/ёЁ/еЕ/;
1.40      roma7    1600: $sstr=~s/[^йцукенгшщзхъфывапролджэячсмитьбюЙЦУКЕНГШЩЗХЪФЫВАПРОЛДЖЭЯЧСМИТЬБЮa-zA-Z0-9]/ /gi;
                   1601: #              print &PrintQuestion($dbh,$qid, 1, '!');
                   1602:              &PrintSearch($dbh, $sstr, 'proxy');
                   1603:        }
                   1604: 
                   1605:           elsif (param('all')) {
1.1       boris    1606:                print &PrintAll($dbh, 0);
                   1607:        } elsif (param('from_year') && param('to_year')) {
1.37      roma7    1608:                print &PrintDates($dbh);
1.1       boris    1609:        } elsif (param('comp')) {
1.9       boris    1610:            print header(
                   1611:                         -'Content-Type' => 'application/x-zip-compressed; name="db.zip"',
                   1612:                         -'Content-Disposition' => 'attachment; filename="db.zip"'
                   1613:                         );
                   1614:            $tour = (param('tour')) ? param('tour') : 0;
                   1615:            my (@files) = &PrintArchive($dbh, $tour);
1.60      roma7    1616:            WriteFile($dbh,$_) foreach @files;
1.9       boris    1617:            open F, "$ZIP -j - $SRCPATH/COPYRIGHT @files |";
                   1618:            print (<F>);
                   1619:            close F;
                   1620:            $dbh->disconnect;
                   1621:            exit;
                   1622:        } elsif (param('sqldump')) {
                   1623:            print header(
                   1624:                         -'Content-Type' => 'application/x-zip-compressed; name="dump.zip"',
                   1625:                         -'Content-Disposition' => 'attachment; filename="dump.zip"'
                   1626:                         );
1.10      boris    1627:            open F, "$ZIP -j - $DUMPFILE |";
1.9       boris    1628:            print (<F>);
                   1629:            close F;
                   1630:            $dbh->disconnect;
                   1631:            exit;
                   1632: 
1.1       boris    1633:        } else {
                   1634:                $tour = (param('tour')) ? param('tour') : 0;
1.54      roma7    1635:                my $sth;
1.1       boris    1636:                if ($tour !~ /^[0-9]*$/) {
1.54      roma7    1637:                    if ($tour=~/\./)
                   1638:                    {
                   1639:                        my ($fname,$n)= split /\./ , $tour;
                   1640: 
                   1641:                        $sth = $dbh->prepare(
                   1642:                        "SELECT t2.Id FROM Tournaments as t1, 
                   1643:                         Tournaments as t2 
                   1644:                        WHERE t1.FileName = '$fname.txt'
                   1645:                         AND t1.Id=t2.ParentId AND t2.Number=$n");
                   1646:                    }   
                   1647:                    else 
                   1648:                        {
                   1649:                           $sth = $dbh->prepare("SELECT Id FROM Tournaments
                   1650:                                     WHERE FileName = '$tour.txt'");
                   1651:                        }
                   1652:                    $sth->execute;
                   1653:                    $tour = ($sth->fetchrow)[0];
                   1654:                     $sth->finish;
1.1       boris    1655:                }
1.65    ! roma7    1656:                my $QuestionNumber=0;
        !          1657:                if (my $qnum=param('qnumber')){
        !          1658:                  my ($sth) = $dbh->prepare("SELECT QuestionId FROM Questions
        !          1659:                     WHERE ParentId=$tour AND Number=$qnum");
        !          1660:                  $sth->execute;
        !          1661:                  $QuestionNumber=($sth->fetchrow)[0]||0;
        !          1662:                }
        !          1663:                if ($QuestionNumber) {
        !          1664: 
        !          1665:                  print &PrintQuestion($dbh, $QuestionNumber, param('answer'), 0, 1);
        !          1666:                } else  {
        !          1667:                   print &PrintTournament($dbh, $tour, param('answer'));
        !          1668:                }
1.1       boris    1669:        }
                   1670:        if (!$text) {
                   1671:                print &Include_virtual("../dimrub/db/footer.html");
                   1672:                print end_html;
                   1673:        }
                   1674:        $dbh->disconnect;
                   1675: }

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