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

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

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