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

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

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