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

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

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