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

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

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