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

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

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