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

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

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