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

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

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