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

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

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