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

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

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