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

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:            {
1.134   ! roma7     619:                foreach (keys %{$tasksof{$sf}})
        !           620:                 {
        !           621:                     next if $forbidden{$_};
        !           622:                      $count{$_}++ 
        !           623:                 }
        !           624: 
1.22      roma7     625:            }
                    626:              @tasks= ($all ? (grep {$count{$_}==$kvo} keys %count) :
                    627:                              keys %count) ;
                    628: 
                    629: 
                    630: ############ Сортировка найденных вопросов
                    631: 
                    632: foreach (keys %wordsof)
                    633: {
                    634:   $relevance{$_}=&relevance($#w,$wordsof{$_},\@frequence) if $_
                    635: }
                    636: 
                    637: @tasks=sort {$relevance{$b}<=>$relevance{$a}} @tasks;
                    638: 
                    639: ############
                    640: 
                    641: 
                    642:         return  @tasks;
                    643: }
                    644: 
                    645: 
                    646: sub distance  {
                    647:                  # на входе -- номера словоформ и ссылки на
                    648:                  # списки вхождений. На выходе -- расстояние,
                    649:                  # вычисляемое по формуле min(|b-a-pb+pa|)
                    650:                  #                       pb,pa
                    651:                  # (pb и pa -- позиции слов b и a)
                    652:    my ($a,$b,$lista,$listb)=@_;
                    653:    my ($pa,$pb,$min,$curmin);
                    654:    $min=10000;
                    655:    foreach $pa (@$lista)
                    656:    {
                    657:      foreach $pb (@$listb)
                    658:      {
                    659:         $curmin=abs($b-$a-$pb+$pa);
                    660:         $min= $curmin if $curmin<$min;
                    661:      }
                    662:    }
                    663:    return $min;
                    664: 
                    665: }
                    666: 
                    667: sub relevance {
                    668:               # На входе -- количество искомых словоформ -1 и
                    669:               # ссылка на hash, ключи которого --
                    670:               # номера словоформ, а значения -- списки вхождений
                    671: 
                    672:        my ($n,$words,$frequence)=@_;
                    673:        my $relevance=0;
                    674:        my ($first,$second,$d);
                    675:        foreach $first (0..$n)
                    676:        {
                    677:          $relevance+=scalar @{$$words{$first}}+1000+1000/$$frequence[$first]
                    678: if $$words{$first};
                    679:          foreach $second ($first+1..$n)
                    680:          {
                    681:             $d=&distance($first,$second,$$words{$first},$$words{$second});
                    682:             $relevance+=($d>10?0:10-$d)*10;
                    683:          }
                    684:        }
                    685:        return $relevance;
                    686: }
                    687: 
                    688: 
1.1       boris     689: 
                    690: # Returns list of QuestionId's, that have the search string in them.
                    691: sub Search {
1.40      roma7     692:        my ($dbh, $s,$metod,$all,$allnf) = @_;
                    693:        my $sstr=$$s;
1.1       boris     694:        my (@arr, @Questions, @fields);
1.39      roma7     695:        my (@sar, $i, $sth,$where,$query);
1.22      roma7     696:        if ($metod eq 'rus')
                    697:        {
                    698:             my @tasks=russearch($dbh,$sstr,$all,$allnf);
                    699:             return @tasks
                    700:        }
1.40      roma7     701:        elsif ($metod eq 'proxy')
                    702:        {
                    703:          my @task=proxy($dbh,$s,$allnf);
                    704:          return @task
                    705:        }
                    706: 
1.22      roma7     707: 
                    708: 
1.14      roma7     709: ###Simple and advanced query processing. Added by R7
1.37      roma7     710:        if ($metod eq 'simple' || $metod eq 'advanced')
1.14      roma7     711:        {
1.29      roma7     712:           foreach (qw/Question Answer Sources Authors Comments/) {
1.14      roma7     713:                if (param($_)) {
1.37      roma7     714:                        push @fields, $_;
1.14      roma7     715:                }
1.29      roma7     716:           }
1.22      roma7     717: 
1.14      roma7     718:           @fields=(qw/Question Answer Sources Authors Comments/) unless scalar @fields;
                    719:           my $fields=join ",", @fields;
                    720:            my $q=new Text::Query($sstr,
1.37      roma7     721:                  -parse => 'Text::Query::'.
1.14      roma7     722:                    (($metod eq 'simple') ? 'ParseSimple':'ParseAdvanced'),
                    723:                  -solve => 'Text::Query::SolveSQL',
                    724:                  -build => 'Text::Query::BuildSQLMySQL',
                    725:                  -fields_searched => $fields);
                    726: 
                    727:            $where=     $$q{'matchexp'};
1.39      roma7     728:            $query= "SELECT Questionid FROM Questions
1.14      roma7     729:                 WHERE $where";
                    730: 
                    731:            $sth = $dbh->prepare($query);
                    732:          } else
1.37      roma7     733: ######
1.14      roma7     734:          {
                    735: 
1.41      roma7     736: #        foreach (qw/Question Answer Sources Authors Comments/) {
                    737:          foreach (param('searchin')) {
                    738: #              if (param($_)) {
1.1       boris     739:                        push @fields, "IFNULL($_, '')";
1.41      roma7     740: #              }
1.14      roma7     741:          }
                    742:          @sar = split " ", $sstr;
                    743:          for $i (0 .. $#sar) {
1.1       boris     744:                $sar[$i] = $dbh->quote("%${sar[$i]}%");
1.14      roma7     745:          }
1.75      roma7     746:          $_.=' ' foreach (@fields); # Это чтобы последнее слово поля
                    747:                                     # не сливалось с первым словом
                    748:                                     # следующего поля, R7
1.14      roma7     749:          my($f) = "CONCAT(" . join(',', @fields) . ")";
                    750:          if (param('all') eq 'yes') {
1.1       boris     751:                $sstr = join " AND $f LIKE ", @sar;
1.14      roma7     752:          } else {
1.1       boris     753:                $sstr = join " OR $f LIKE ", @sar;
1.14      roma7     754:          }
1.72      roma7     755:          
1.36      roma7     756:    my $query;
                    757:                $query="SELECT QuestionId FROM Questions
1.72      roma7     758:                WHERE ($f LIKE $sstr) AND (".&makewhere.") ORDER BY QuestionId";
1.37      roma7     759: 
1.21      roma7     760: 
1.22      roma7     761:          $sth = $dbh->prepare($query)
1.14      roma7     762:        } #else -- processing old-style query (R7)
                    763: 
1.1       boris     764:        $sth->execute;
                    765:        while (@arr = $sth->fetchrow) {
1.36      roma7     766:                push @Questions, $arr[0] unless $forbidden{$arr[0]};
1.1       boris     767:        }
1.49      roma7     768:         $sth->finish;
1.72      roma7     769:         
1.1       boris     770:        return @Questions;
                    771: }
                    772: 
1.72      roma7     773: sub makewhere {
                    774:       my @type=param('type');    
                    775:       my $type='';
                    776: 
                    777:       $type .= ($_=$TypeName{$_}) foreach @type;
                    778:       my $where=' 0 ';
                    779:       foreach (@type) {
1.128     boris     780:             $where.= " OR (Type ='$_') OR (Type ='$_Д') OR (Type ='Д$_') ";
1.72      roma7     781:       } 
                    782:       $where.= "OR (Type='ЧБ')" if ($type=~/Ч|Б/);
                    783:       return $where;
                    784: }
                    785: 
1.1       boris     786:  # Substitute every letter by a pair (for case insensitive search).
1.37      roma7     787:  my (@letters) = qw/аА бБ вВ гГ дД еЕ жЖ зЗ иИ йЙ кК лЛ мМ нН оО
1.1       boris     788:  пП рР сС тТ уУ фФ хХ цЦ чЧ шШ щЩ ьЬ ыЫ эЭ юЮ яЯ/;
1.37      roma7     789: 
1.1       boris     790: sub NoCase {
1.47      roma7     791:        my ($sstr) = shift;                     
1.1       boris     792:        my ($res);
                    793: 
                    794:        if (($res) = grep(/$sstr/, @letters)) {
                    795:                return "[$res]";
                    796:        } else {
                    797:                return $sstr;
                    798:        }
                    799: }
                    800: 
1.40      roma7     801: sub PrintList {
1.54      roma7     802:    my ($dbh,$Questions,$shablon,$was)=@_;
1.95      roma7     803:         my $Output;
1.40      roma7     804:        my $first=param('first') ||1;
1.95      roma7     805:        $first=$first-($first-1)%$outputkvo;
1.93      roma7     806:         my $fkvo=param('fkvo')||($#$Questions+1);
1.95      roma7     807:        my $last=$first+$outputkvo-1;
1.93      roma7     808:        $last=$fkvo if $fkvo<$last;
1.40      roma7     809:         my($f,$l);
                    810:         my $nav='';
1.41      roma7     811:         my $qs=query_string;
                    812:        $qs=~s/\;/\&/g;
                    813:         $qs=~s/\&first\=[^\&]+//g;
1.72      roma7     814:         my $sstr=param('sstr')||'';
1.51      roma7     815:         $qs=~s/sstr=[^\&]+/sstr=$sstr/;
1.95      roma7     816:         if ($usewas) {
                    817:                $qs=~s/\&was=[^\&]+//;
                    818:                $qs.="&was=$was" if $was;
                    819:                $qs.="&fkvo=$fkvo" if $was;
                    820:         }
                    821:         if ($first>$outputkvo*3+1)
1.41      roma7     822:         {
                    823:            $nav.=
                    824:             ("&nbsp;"x4).
1.100     roma7     825:             a({href=>$url."?".$qs."\&first=1"},"<<").("&nbsp;"x4).
                    826:             a({href=>($url."?".$qs."\&first=".($first-$outputkvo))},"<").("&nbsp;"x4)
1.93      roma7     827:        }
1.41      roma7     828:         else {$nav.='&nbsp;'x15;}
                    829: 
                    830:      my ($fprint,$lprint);
1.95      roma7     831:      my $llprint=$fkvo- ($fkvo)%$outputkvo+1; #
                    832:      if ($fkvo<=$outputkvo*7)
1.41      roma7     833:      {         $fprint=1;
                    834:                $lprint=$llprint;
                    835:      }
1.95      roma7     836:      elsif ($first>$outputkvo*3 && $fkvo-$first>$outputkvo*3)
1.41      roma7     837:      {
1.95      roma7     838:        $fprint=$first-$outputkvo*3;
                    839:        $lprint=$first+$outputkvo*3;
1.41      roma7     840:      } 
1.95      roma7     841:      elsif  ($first<=$outputkvo*3)
1.41      roma7     842:      {
1.95      roma7     843:         $fprint=1; $lprint=6*$outputkvo+1;
1.41      roma7     844:      }
                    845:      else
                    846:      { 
                    847:            $lprint=$llprint;
1.95      roma7     848:            $fprint=$lprint-$outputkvo*6
1.41      roma7     849:      }
                    850:          
1.95      roma7     851: #        my $fprint=($first>$outputkvo*3) ? $first-$outputkvo*3 : 1;
                    852: #        my $lprint=$#$Questions+1-$fprint>$outputkvo*7 ? $outputkvo*7 :$#$Questions+1;
                    853: #        if ($lprint-$fprint<$outputkvo*6 && $fprint>1)
1.41      roma7     854: #        {
1.95      roma7     855: #            $fprint=$lprint-$outputkvo*6;
1.41      roma7     856: #            $fprint=1 if ($fprint<=0) 
                    857: #        }
                    858: 
                    859: 
                    860: 
1.95      roma7     861:         for($f=$fprint; $f<=$lprint; $f+=$outputkvo)
1.40      roma7     862:        {
1.95      roma7     863: #        next if $first-$f>$outputkvo*3;
                    864:          $l=$f+$outputkvo-1;
1.93      roma7     865:          $l=$fkvo if $l>$fkvo+1;
1.40      roma7     866:          if ($f==$first) {$nav.="[$f-$l] ";}
                    867:          else {
1.100     roma7     868:                   $nav.= "[".a({href=>($url."?".$qs."\&first=$f")},"$f-$l")."] ";}
1.41      roma7     869:        }
1.95      roma7     870:         if ($lprint+$outputkvo<$fkvo)
1.41      roma7     871:         {
                    872:            $nav.=
                    873:             ("&nbsp;"x4).
1.100     roma7     874:             a({href=>($url."?".$qs."\&first=".($first+$outputkvo))},">").("&nbsp;"x4).
                    875:             a({href=>$url."?".$qs."\&first=$llprint"},">>").("&nbsp;"x4)
1.41      roma7     876:         }
1.95      roma7     877:        $Output.= "$nav".br."\n";
1.96      roma7     878:        my @q=@$Questions[$first-1..$last-1];
1.95      roma7     879:        my %q=();
                    880:        my $sth=SelectQuestions($dbh,\@q,1);
1.116     roma7     881:        my $qq;
                    882:        my @Q;
                    883:        for (0..$#q) {
                    884:                %{$Q[$_]}=();
                    885:                fetchquestion($sth,$Q[$_],1);
                    886:                $q{$Q[$_]{'QuestionId'}}=$Q[$_];
                    887:        }
                    888: 
1.40      roma7     889:        for (my $i = $first; $i <= $last; $i++) {
1.116     roma7     890:                my $q=$q{$$Questions[$i-1]};
1.95      roma7     891:                my $output;
1.116     roma7     892:                $output = &PrintQuestion($dbh, $q, 1, 0, 1,0,1  );
                    893: #                if (param('metod') && (param('metod') eq 'rus' || param('metod') eq 'proxy'))
1.40      roma7     894:                 {
                    895:                     $output=~s/\b($shablon)\b/\<strong\>$1\<\/strong\>/gi;
                    896:                     $output=~s/($shablon)/\<strong\>$1\<\/strong\>/gi;
                    897:                }
1.95      roma7     898:                $Output.= $output;
1.40      roma7     899:        }
1.95      roma7     900:        $sth->finish;
1.41      roma7     901: 
1.95      roma7     902:        $Output.= "$nav".br."\n";
                    903:        return $Output;
1.40      roma7     904: }
                    905: 
1.1       boris     906: sub PrintSearch {
1.95      roma7     907:         my $Output='';
1.54      roma7     908:        my ($dbh, $sstr, $metod,$was) = @_;
                    909:        my $t=time;
1.95      roma7     910:        $Output.= printform;
1.22      roma7     911:        my @allnf;
1.54      roma7     912:        my @Questions;
1.92      roma7     913:        $was=0 if $metod eq 'proxy';
1.95      roma7     914:        if ($usewas && $was && ($metod ne 'proxy'))
1.54      roma7     915:        {
                    916:          my $sth=$dbh->prepare ("select sstr,questions,allnf from lastqueries where id=".param('was'));
                    917:           $sth->execute;
                    918:           my ($q,$nf);
                    919:          ($sstr, $q,$nf)=($sth->fetchrow);
1.58      roma7     920:           @Questions=unpack 'L*',$q; 
                    921:           @allnf=unpack 'L*',$nf;        
1.54      roma7     922:           $sth->finish;
1.92      roma7     923:         }  
1.95      roma7     924:         if (!$was || ($metod eq 'proxy') || (param('first')+$outputkvo>$cashednumber))
1.54      roma7     925:         {
                    926:              @Questions=&Search($dbh, \$sstr,$metod,$all,\@allnf);
1.95      roma7     927:              $cashednumber=$#Questions if $cashednumber>$#Questions;
1.92      roma7     928:              my $tmp=$dbh->quote(pack("L*",@Questions[0..$cashednumber]));
1.54      roma7     929:              my $qsstr=$dbh->quote($sstr);
1.58      roma7     930:              my $nf=$dbh->quote(pack("L*", @allnf));
1.55      roma7     931:              my $ss=200;
1.95      roma7     932:              if ($usewas) {
                    933:                do 
                    934:                        {
                    935:                                        $was=int rand(32000);
                    936:                        }
                    937:                while (--$ss && (!$dbh->do ("insert into lastqueries (id,sstr,questions,allnf) 
1.55      roma7     938:                          values ($was, $qsstr,$tmp,$nf)")));
1.95      roma7     939:                $Output.= "Something is wrong...".br unless $ss;
                    940:              }
1.54      roma7     941:         }
1.55      roma7     942: 
1.54      roma7     943: 
                    944: 
1.95      roma7     945:        $Output.= p. "Время поиска: " . (time-$t) ." сек.".p;
1.1       boris     946:        my ($output, $i, $suffix, $hits) = ('', 0, '', $#Questions + 1);
                    947: 
1.22      roma7     948:         my $shablon;
1.40      roma7     949:         $metod='rus' if $metod eq 'proxy';
1.22      roma7     950:         if ($metod eq 'rus')
                    951:         {
                    952:            my $where='0';
                    953:            $where.= " or w2=$_ " foreach @allnf;
                    954:            my $query="select w1 from nests where $where";
                    955:            my $sth=$dbh->prepare($query);
                    956: 
                    957:           $sth->execute;
                    958:           my @shablon;
                    959:           while (my @arr = $sth->fetchrow)
                    960:           {
                    961:             push @shablon,"(?:$arr[0])";
                    962:           }
1.54      roma7     963:           $sth->finish;
1.37      roma7     964:            $shablon= join "|", @shablon;
1.22      roma7     965:            $shablon=~s/[её]/\[ЕЁ\]/gi;
                    966: #           $shablon=~s/([йцукенгшщзхъфывапролджэячсмитьбюЙЦУКЕНГШЩЗХЪФЫВАПРОЛДЖЭЯЧСМИТЬБЮ])/&NoCase($1)/ge;
                    967:            $shablon=qr/$shablon/i;
1.54      roma7     968: 
1.22      roma7     969:         }
                    970: 
1.92      roma7     971:         $hits=param("fkvo")||$hits;
1.22      roma7     972: 
1.1       boris     973:        if ($hits =~ /1.$/  || $hits =~ /[5-90]$/) {
                    974:                $suffix = 'й';
                    975:        } elsif ($hits =~ /1$/) {
                    976:                $suffix = 'е';
                    977:        } else {
1.37      roma7     978:                $suffix = 'я';
1.1       boris     979:        }
1.37      roma7     980: 
1.95      roma7     981:        $Output.= p({align=>"center"}, "Результаты поиска на " . strong($sstr)
1.1       boris     982:        . " : $hits попадани$suffix.");
                    983: 
                    984:        if (param('word')) {
                    985:                $sstr = '[      \.\,:;]' . $sstr . '[  \.\,:\;]';
                    986:        }
                    987: 
1.73      roma7     988: #      $sstr =~ s/(.)/&NoCase($1)/ge;
1.1       boris     989: 
1.40      roma7     990:        my @sar;
                    991:        if ($metod ne 'rus') 
                    992:        {
1.74      roma7     993:          my $ss=$sstr;
                    994:          (@sar) = split(' ', $ss);
                    995:          s/(\W)/\\$1/g foreach (@sar);
1.40      roma7     996:          $shablon=join "|",@sar;
1.1       boris     997:        }
1.95      roma7     998:        $Output.=PrintList($dbh,\@Questions,$shablon,$was);
                    999:        return $Output;
1.1       boris    1000: }
                   1001: 
                   1002: sub PrintRandom {
                   1003:    my ($dbh, $type, $num, $text) = @_;
1.80      roma7    1004:    my $razd=param('razd');
1.95      roma7    1005:    my %q;
1.80      roma7    1006:    my $answer=$razd?0:1;
1.95      roma7    1007:    my @answers;
1.129     roma7    1008: #my $t=time;
1.1       boris    1009:    my (@Questions) = &Get12Random($dbh, $type, $num);
1.129     roma7    1010: 
1.1       boris    1011:        my ($output, $i) = ('', 0);
1.129     roma7    1012: #$output.="time=".(time-$t).p;
1.1       boris    1013:        if ($text) {
                   1014:                $output .= "    $num случайных вопросов.\n\n";
                   1015:        } else {
                   1016:                $output .=
                   1017:                        h2({align=>"center"}, "$num случайных вопросов.");
                   1018:        }
1.95      roma7    1019:        my $sth=SelectQuestions($dbh,\@Questions,0);
1.1       boris    1020:        for ($i = 0; $i <= $#Questions; $i++) {
1.95      roma7    1021:                fetchquestion($sth,\%q,0);
1.37      roma7    1022:                $output .=
1.95      roma7    1023:                        &PrintQuestion($dbh, \%q, $answer, $i + 1, 0, $text,1);
                   1024:                        push @answers, $q{'Answer'};
1.1       boris    1025:        }
1.95      roma7    1026:        $sth->finish;
1.80      roma7    1027:        unless ($answer )
                   1028:         { 
                   1029:          $output.=$text?"\n".('-'x 20)."\nОтветы\n~~~~~~\n\n":h2('Ответы');
1.95      roma7    1030:          $sth=SelectQuestions($dbh,\@Questions,0);
1.80      roma7    1031:          for ($i = 0; $i <= $#Questions; $i++) {
1.95      roma7    1032: #                fetchquestion($sth,\%q,0);
                   1033: #              $output .=
                   1034: #                      &PrintQuestion($dbh, \%q, -1, $i + 1, 0, $text,1);
                   1035:                 $output.=$text?("Ответ ". ($i+1).": $answers[$i]\n\n"):
                   1036:                        b("Ответ ". ($i+1).": "). $answers[$i].p;
1.80      roma7    1037:         }
                   1038:         }
                   1039: 
1.37      roma7    1040:        return $output;
1.1       boris    1041: }
                   1042: 
1.53      roma7    1043: sub PrintEditor {
                   1044:        my $t=shift; #ссылка на Хэш с полями
1.70      roma7    1045:        my $ed=$$t{'Editors'}||'';
1.53      roma7    1046:        my $edname=($ed=~/\,/ ) ? "Редакторы"  : "Редактор" ;
1.54      roma7    1047:        return $ed? h4({align=>"center"},"$edname: $ed" ): '';
1.53      roma7    1048: }
                   1049: 
1.1       boris    1050: sub PrintTournament {
                   1051:    my ($dbh, $Id, $answer) = @_;
                   1052:        my (%Tournament, @Tours, $i, $list, $qnum, $imgsrc, $alt,
                   1053:                $SingleTour);
                   1054:        my ($output) = '';
                   1055: 
                   1056:        %Tournament = &GetTournament($dbh, $Id) if ($Id);
1.37      roma7    1057: 
1.118     roma7    1058:        my ($URL) = $Tournament{'URL'}||'';
1.116     roma7    1059:        $URL=~s/http:\/znatoki\/boris\/reports\//$newsurl/ if $url=~/kulichki/ || $url=~/db.chgk.info/;
                   1060:        $URL=~s/\/znatoki\/boris\/reports\//$newsurl/ if url=~/kulichki/ || $url=~/db.chgk.info/;
1.1       boris    1061:        my ($Info) = $Tournament{'Info'};
                   1062:        my ($Copyright) = $Tournament{'Copyright'};
1.54      roma7    1063:        my $fname=$Tournament{'FileName'};
1.1       boris    1064:        @Tours = &GetTours($dbh, $Id);
1.53      roma7    1065:        $list='';
1.54      roma7    1066:        my $textid;
1.1       boris    1067:        if ($Id) {
                   1068:                for ($Tournament{'Type'}) {
                   1069:                        /Г/ && do {
1.37      roma7    1070:                                $output .= h2({align=>"center"},
1.6       boris    1071:                                              "Группа: $Tournament{'Title'} ",
1.74      roma7    1072:                                              $Tournament{'PlayedAt'}||'') . p . "\n";
1.1       boris    1073:                                last;
                   1074:                        };
                   1075:                        /Ч/ && do {
                   1076:                                return &PrintTour($dbh, $Tours[0], $answer)
                   1077:                                        if ($#Tours == 0);
1.37      roma7    1078: 
1.6       boris    1079:                                my $title="Пакет: $Tournament{'Title'}";
                   1080:                                if ($Tournament{'PlayedAt'}) {
                   1081:                                    $title .= " $Tournament{'PlayedAt'}";
                   1082:                                }
1.1       boris    1083: 
1.37      roma7    1084:                                $output .= h2({align=>"center"},
1.6       boris    1085:                                        "$title") . p . "\n";
1.53      roma7    1086:                               $output.=&PrintEditor(\%Tournament);
1.1       boris    1087:                                last;
                   1088:                        };
                   1089:                        /Т/ && do {
                   1090:                                return &PrintTour($dbh, $Id, $answer);
                   1091:                        };
                   1092:                }
                   1093:        } else {
1.126     roma7    1094:                my ($qnum) = GetQNum($dbh,0);
                   1095:                my ($qnum1) = GetQNum($dbh,1);
                   1096:                $output .= h2("База вопросов").
                   1097:                  h3("$qnum запис".&Suffix2($qnum).
1.127     roma7    1098:                  " (уникальных $qnum1)");
1.126     roma7    1099: 
                   1100: #               h4("<table>".
                   1101: #               Tr(td("Из них:"), td("Вопросов ЧГК: ".countz($dbh,'Ч'))).               
                   1102: #               Tr(td("&nbsp;"), td("Вопросов для брейна: ".countz($dbh,'Б'))).                 
                   1103: #               Tr(td("&nbsp;"), td("Вопросов для ЧГК и брейна: ".countz($dbh,'ЧБ'))).          
                   1104: #               Tr(td("&nbsp;"), td("Интернет-вопросов: ".countz($dbh,'И'))).           
                   1105: #               Tr(td("&nbsp;"), td("Бескрылок: ".countz($dbh,'Л'))).
                   1106: #               Tr(td("&nbsp;"),td("Заданий для Своей Игры: ".countz($dbh,'Я'))).
                   1107: #               Tr(td("&nbsp;"),td("Эрудиток: ".countz($dbh,'Э'))))."</table>"
1.1       boris    1108:        }
                   1109: 
1.37      roma7    1110:        for ($i = 0; $i <= $#Tours; $i++) {
1.1       boris    1111:                %Tournament = &GetTournament($dbh, $Tours[$i]);
1.37      roma7    1112: 
1.1       boris    1113:                if ($Tournament{'Type'} =~ /Ч/) {
                   1114:                        $SingleTour = 0;
                   1115:                        my (@Tours) = &GetTours($dbh, $Tournament{'Id'});
                   1116:                        $SingleTour = 1
                   1117:                                if ($#Tours == 0);
                   1118:                }
                   1119:                if ($Tournament{'QuestionsNum'} > 0) {
                   1120:                        $qnum = " ($Tournament{'QuestionsNum'} вопрос" .
                   1121:                                &Suffix($Tournament{'QuestionsNum'}) . ")\n";
                   1122:                } else {
                   1123:                        $qnum = '';
                   1124:                }
1.100     roma7    1125:                if ($Tournament{'Type'} !~ /[ТЧ]/) {
1.63      boris    1126:                    $SingleTour=0;
1.1       boris    1127:                        $imgsrc = "/icons/folder.gif";
                   1128:                        $alt = "[*]";
                   1129:                } else {
                   1130:                        $imgsrc = "/icons/folder.gif";
                   1131:                        $alt = "[-]";
                   1132:                }
                   1133: 
1.54      roma7    1134:                my $textid;
                   1135:                if ($textid=$Tournament{'FileName'})
                   1136:                {
                   1137:                   $textid=~s/\.txt//;
                   1138:                }
                   1139:                elsif ($textid=$Tournament{'Number'})
                   1140:                  {
                   1141:                      $fname=~s/\.txt//;
                   1142:                      $textid="$fname.$textid";
                   1143:                  }
                   1144:               else {$textid=$Tournament{'Id'}};
                   1145:                
                   1146: 
1.103     roma7    1147:                if ($SingleTour or ($Tournament{'Type'} =~ /Т/)) {
1.1       boris    1148:                        $list .= dd(img({src=>$imgsrc, alt=>$alt})
1.6       boris    1149:                                . " " . $Tournament{'Title'} . " " .
1.103     roma7    1150:                                    ($Tournament{'PlayedAt'}||"") . $qnum) .
1.1       boris    1151:                                dl(
                   1152:                                        dd("["
1.100     roma7    1153:                                                . a({href=>tourhref($textid,0)},
1.1       boris    1154:                                                "вопросы") . "] ["
1.100     roma7    1155:                   . a({href=>tourhref($textid,1)},
1.1       boris    1156:                   "вопросы + ответы") . "]")
                   1157:                                );
                   1158:                } else {
1.118     roma7    1159:                        $list .= dd(a({href=>
                   1160:                                  $url . "?tour=$textid&comp=1"},
                   1161:                                img({src=>'/icons/compressed.gif', alt=>'[ZIP]', border=>1}))                           .  
1.116     roma7    1162:                                " " . 
1.59      roma7    1163:                                 img({src=>$imgsrc, alt=>$alt})
1.100     roma7    1164:                                . " " . a({href=>tourhref($textid,0,1)},
1.37      roma7    1165:                                $Tournament{'Title'}. " ".
1.103     roma7    1166:                                          ($Tournament{'PlayedAt'}||'')) . $qnum); 
1.1       boris    1167:                }
                   1168:        }
                   1169:        $output .= dl($list);
                   1170: 
                   1171:        if ($URL) {
1.100     roma7    1172:                if ($url=~/zaba\.ru/ && $URL=~/^\//){$URL="http://info.chgk.info$URL"}
1.1       boris    1173:                $output .=
1.37      roma7    1174:                p("Дополнительная информация об этом турнире - по адресу " .
1.1       boris    1175:                        a({-'href'=>$URL}, $URL));
                   1176:        }
                   1177: 
                   1178:        if ($Copyright) {
                   1179:                $output .= p("Копирайт: " .   $Copyright);
                   1180:        }
                   1181: 
1.53      roma7    1182: 
                   1183: 
1.1       boris    1184:        if ($Info) {
                   1185:                $output .= p($Info);
                   1186:        }
                   1187:        return $output;
                   1188: }
                   1189: 
                   1190: sub Suffix {
                   1191:        my ($qnum) = @_;
                   1192:        my ($suffix) = 'а' if $qnum =~ /[234]$/;
                   1193:    $suffix = '' if $qnum =~ /1$/;
                   1194:    $suffix = 'ов' if $qnum =~ /[567890]$/ || $qnum =~ /1.$/;
                   1195:        return $suffix;
                   1196: }
                   1197: 
1.126     roma7    1198: 
                   1199: sub Suffix1 {
                   1200:        my ($qnum) = @_;
                   1201:        my ($suffix) = 'я' if $qnum =~ /[234]$/;
                   1202:        $suffix = 'е' if $qnum =~ /1$/;
                   1203:        $suffix = 'й' if $qnum =~ /[567890]$/ || $qnum =~ /1.$/;
                   1204:        return $suffix;
                   1205: }
                   1206: 
                   1207: sub Suffix2 {
                   1208:        my ($qnum) = @_;
                   1209:        my ($suffix) = 'и' if $qnum =~ /[234]$/;
                   1210:        $suffix = 'ь' if $qnum =~ /1$/;
                   1211:        $suffix = 'ей' if $qnum =~ /[567890]$/ || $qnum =~ /1.$/;
                   1212:        return $suffix;
                   1213: }
                   1214: 
1.1       boris    1215: sub IsTour {
1.54      roma7    1216:        my ($dbh, $Id,$n) = @_;
                   1217: 
                   1218:        my ($sth) ;
                   1219:         
                   1220:         if (defined $n) 
                   1221:         { $sth=$dbh->prepare ("select Id FROM Tournaments
                   1222:                            WHERE ParentId=$Id AND Number=$n");
                   1223:         }
                   1224:         else
                   1225:         {
                   1226:           $sth=$dbh->prepare("SELECT Id FROM Tournaments
1.1       boris    1227:                WHERE Id=$Id");
1.54      roma7    1228:        }
1.1       boris    1229:        $sth->execute;
1.54      roma7    1230:         my $a=($sth->fetchrow)[0];
                   1231:        $sth->finish;
                   1232:        return $a;
1.1       boris    1233: }
                   1234: 
                   1235: # Gets a DB handler (ofcourse) and a tour Id. Prints all the
                   1236: # question of that tour, according to the options.
                   1237: sub PrintTour {
                   1238:        my ($dbh, $Id, $answer) = @_;
                   1239:        my ($output, $q, $bottom, $field) = ('', 0, '', '');
                   1240: 
                   1241:        my (%Tour) = &GetTournament($dbh, $Id);
                   1242:        my (@Tours) = &GetTours($dbh, $Tour{'ParentId'});
                   1243:        my (%Tournament) = &GetTournament($dbh, $Tour{'ParentId'});
1.95      roma7    1244:        my %q;
1.1       boris    1245: 
                   1246:        return 0
                   1247:                if ($Tour{'Type'} !~ /Т/);
                   1248: 
1.54      roma7    1249:        my ($fname)=$Tournament{'FileName'};
                   1250:        $fname=~s/\.txt//;
1.1       boris    1251:        my ($qnum) = $Tour{'QuestionsNum'};
1.37      roma7    1252:        my ($suffix) = &Suffix($qnum);
                   1253: 
                   1254:        $output .= h2({align=>"center"}, $Tournament{"Title"},
1.74      roma7    1255:                      $Tournament{'PlayedAt'}||'',
1.37      roma7    1256:                      "<br>", $Tour{"Title"} .
1.1       boris    1257:                " ($qnum вопрос$suffix)\n") . p;
1.53      roma7    1258:        $output .=&PrintEditor(\%Tour);
1.1       boris    1259: 
                   1260:        my (@Questions) = &GetTourQuestions($dbh, $Id);
1.95      roma7    1261:        my $sth=SelectQuestions($dbh,\@Questions,0);
1.1       boris    1262:        for ($q = 0; $q <= $#Questions; $q++) {
1.95      roma7    1263:                fetchquestion($sth,\%q,0);
                   1264:                $output .= &PrintQuestion($dbh, \%q, $answer, 0,0,0,1);
1.37      roma7    1265:        }
1.95      roma7    1266:        $sth->finish;
1.1       boris    1267:        $output .= hr({-'align'=>'center', -'width'=>'80%'});
                   1268: 
                   1269:        if ($Tournament{'URL'}) {
                   1270:                $output .=
1.37      roma7    1271:                p("Дополнительная информация об этом турнире - по адресу " .
1.1       boris    1272:                        a({-'href'=>$Tournament{'URL'}}, $Tournament{'URL'}));
                   1273:        }
                   1274: 
                   1275:        if ($Tournament{'Copyright'}) {
                   1276:                $output .= p("Копирайт: " .   $Tournament{'Copyright'});
                   1277:        }
                   1278: 
                   1279:        if ($Tournament{'Info'}) {
                   1280:                $output .= p($Tournament{'Info'});
                   1281:        }
1.37      roma7    1282: 
1.54      roma7    1283:        my $n=$Tour{'Number'};
1.1       boris    1284:        if ($answer == 0) {
1.121     roma7    1285:                my $nn=".$n";
                   1286:                $nn="" if ($n==1 && !&IsTour($dbh, $Tour{'ParentId'}, $n + 1));
                   1287:                
1.37      roma7    1288:                $bottom .=
1.121     roma7    1289:                        "[" . a({href=>tourhref("$fname$nn",1)}, 
1.100     roma7    1290:                          "ответы") .  "] " . br;
1.1       boris    1291:        }
1.54      roma7    1292:        if ($n>1) {
1.37      roma7    1293:                $bottom .=
1.100     roma7    1294:                        "[" . a({href=>tourhref("$fname.".($n-1),0)},
1.1       boris    1295:                        "предыдущий тур") . "] ";
1.37      roma7    1296:                $bottom .=
1.100     roma7    1297:                        "[" . a({href=>tourhref("$fname.".($n-1),1)},
1.1       boris    1298:                        "предыдущий тур с ответами") . "] " . br;
                   1299:        }
1.54      roma7    1300:        if (&IsTour($dbh, $Tour{'ParentId'}, $n + 1)) {
1.37      roma7    1301:                $bottom .=
1.100     roma7    1302:                        "[" . a({href=>tourhref("$fname.".($n+1),0)},
1.1       boris    1303:                        "следующий тур") . "] ";
1.37      roma7    1304:                $bottom .=
1.100     roma7    1305:                        "[" . a({href=>tourhref("$fname.".($n+1),1)},
1.1       boris    1306:                        "следующий тур с ответами") . "] ";
                   1307:        }
                   1308: 
                   1309:        $output .=
                   1310:                p({align=>"center"}, font({size=>-1}, $bottom));
                   1311: 
                   1312:        return $output;
                   1313: }
                   1314: 
                   1315: sub PrintField {
                   1316:        my ($header, $value, $text) = @_;
                   1317:        if ($text) {
1.59      roma7    1318:            $value =~ s/<[\/\w]*?>//sg;
1.5       boris    1319:        } else {
                   1320:            $value =~ s/^\s+/<br>&nbsp;&nbsp;&nbsp;&nbsp;/mg;
1.125     boris    1321:            $value =~ s/(\s+)-+(\s+)/$1&#0150;$2/mg;
                   1322:            $value =~ s/\s+\&#0150/&nbsp;\&#0150/mg 
                   1323:                        if $value !~ /^\|/;
1.5       boris    1324:            $value =~ s/^\|([^\n]*)/<pre>$1<\/pre>/mg;
1.79      roma7    1325:            $value =~ s/(http:\/\/\S+[^\s\)\(\,\.])/<a href="$1">$1<\/a>/g if $header !~ /^Авто/;
                   1326: #          $value =~ s/(http:\/\/(?:\w+.)+[\w\\\~]+(\?[^\s.]+)?)/<a href="$1">$1<\/a>/g if $header !~ /^Авто/;
1.61      roma7    1327: #          $value =~ s/(\s)"/$1&#147;/mg;
                   1328: #          $value =~ s/^"/&#147;/mg;
                   1329: #          $value =~ s/"/&#148;/mg;
1.1       boris    1330:        }
1.59      roma7    1331: 
1.29      roma7    1332: 
1.37      roma7    1333:        return $text ? "$header:\n$value\n\n" :
1.1       boris    1334:                strong("$header: ") . $value . p . "\n";
                   1335: }
                   1336: 
1.37      roma7    1337: # Gets a DB handler (ofcourse) and a question Id. Prints
1.1       boris    1338: # that question, according to the options.
                   1339: sub PrintQuestion {
1.95      roma7    1340:        my ($dbh, $Id, $answer, $qnum, $title, $text,$h) = @_;
1.1       boris    1341:        my ($output, $titles) = ('', '');
1.133     roma7    1342:        my $fname;
1.95      roma7    1343:        my (%Question);
                   1344:        if ($h) {
                   1345:          %Question=%$Id;
                   1346:        } else {
                   1347:                %Question = &GetQuestion($dbh, $Id);
                   1348:                if ($title) {
                   1349:                        my (%Tour) = GetTournament($dbh, $Question{'ParentId'});
                   1350:                        my (%Tournament) = GetTournament($dbh, $Tour{'ParentId'});
                   1351:                        $Question{'FileName'}=$Tournament{'FileName'};
                   1352:                        $Question{'Title'}=$Tournament{'Title'};
                   1353:                        $Question{'PlayedAt'}=$Tournament{'PlayedAt'};
                   1354:                        $Question{'TourNumber'}=$Tour{'Number'};
                   1355:                        $Question{'TourTitle'}=$Tour{'Title'};
                   1356:                }
                   1357: 
                   1358:         }
                   1359:                $qnum = $Question{'Number'}
1.65      roma7    1360:                if ($qnum == 0);
1.1       boris    1361:        if (!$text) {
1.80      roma7    1362:                $output .= hr({width=>"50%"}) if $answer>=0;
1.1       boris    1363:                if ($title) {
1.133     roma7    1364:                        $fname=$Question{'FileName'};
1.54      roma7    1365:                        $fname=~s/\.txt//;
1.1       boris    1366:                        $titles .=
                   1367:                                dd(img({src=>"/icons/folder.open.gif"}) . " " .
1.100     roma7    1368:                                         a({href=>tourhref($fname,0,1)}, 
                   1369:                                $Question{'Title'}, $Question{'PlayedAt'}||''));
1.1       boris    1370:                        $titles .=
                   1371:                                dl(dd(img({src=>"/icons/folder.open.gif"}) . " " .
1.100     roma7    1372:                                        a({href=>tourhref("$fname.$Question{'TourNumber'}#$qnum",1)}, 
                   1373:                           $Question{'TourTitle'})));
1.1       boris    1374:                }
                   1375:                $output .= dl(strong($titles));
                   1376:        }
1.37      roma7    1377: 
1.65      roma7    1378: 
1.79      roma7    1379:        $output.= "<a NAME=\"$qnum\">" unless $text;
1.1       boris    1380: 
1.80      roma7    1381:        if ($answer>=0) {$output .=
                   1382:                &PrintField("Вопрос $qnum", $Question{'Question'}, $text);}
                   1383:        else {$output .="$qnum. "}
                   1384:        if ($answer==1|| $answer==-1) {
1.37      roma7    1385:                $output .=
1.1       boris    1386:                        &PrintField("Ответ", $Question{'Answer'}, $text);
                   1387: 
1.79      roma7    1388:                if ($Question{'Authors'} ) {
1.29      roma7    1389:                       my $q=$Question{'Authors'};
1.70      roma7    1390: ###АВТОРА!!
1.95      roma7    1391: #                    my $sth=$dbh->prepare("select Authors.CharId,Name, Surname, Nicks from Authors, A2Q
                   1392: #                                  where Authors.Id=Author And Question=$Id");
                   1393: #                       $sth->execute;
                   1394: #                       my ($AuthorId,$Name, $Surname,$other,$Nicks);
                   1395: #                      if (!$text) {
                   1396: #                       while ((($AuthorId,$Name, $Surname,$Nicks)=$sth->fetchrow),$AuthorId)
                   1397: #                       {
                   1398: #                          my ($firstletter)=$Name=~m/^./g;
                   1399: #                          $Name=~s/\./\\\./g;
                   1400: #                          $Name=~s/ё/[её]/g;
                   1401: #                          $Surname=~s/ё/[её]/g;
                   1402: #                           my $sha="(?:$Name\\s+$Surname)|(?:$Surname\\s+$Name)|(?:$firstletter\\.\\s*$Surname)|(?:$Surname\\s+$firstletter\\.)|(?:$Surname)";
                   1403: #                           if ($Nicks)
                   1404: #                           {
                   1405: #                             $Nicks=~s/^\|//;
                   1406: #                             foreach (split /\|/, $Nicks)
                   1407: #                             {
                   1408: #                               s/\s+/ /g;
                   1409: #                               s/\s+$//;
                   1410: #                               s/ /\\s+/g;
                   1411: #                               s/\./\\\./g;
                   1412: #                               if (s/>$//) {$sha="$sha|(?:$_)"}
                   1413: #                               else        {$sha="(?:$_)|$sha"}
                   1414: #                             }
                   1415: #                           }
                   1416: #                           $q=~s/($sha)/a({href=>url."?qofauthor=$AuthorId"},$1)/ei;
                   1417: #                           unless ($1) 
                   1418: #                             {   
                   1419: #                                 $q=~s/$Name/a({href=>url."?qofauthor=$AuthorId"},$1)/ei;
                   1420: #                             }
                   1421: #                       }
                   1422: #                      }
1.29      roma7    1423:                        $output .= &PrintField("Автор(ы)", $q, $text);
                   1424: 
1.1       boris    1425:                }
                   1426: 
                   1427:                if ($Question{'Sources'}) {
                   1428:                        $output .= &PrintField("Источник(и)", $Question{'Sources'}, $text);
                   1429:                }
                   1430: 
                   1431:                if ($Question{'Comments'}) {
                   1432:                        $output .= &PrintField("Комментарии", $Question{'Comments'}, $text);
                   1433:                }
                   1434:        }
1.68      roma7    1435:        elsif ($answer==2) {
                   1436:          my $text=$Question{'Answer'};
                   1437:          $text=~s/\n/<option>/mg;
                   1438:          $output.="<select><option selected>Ответ:<option>$text</select>";
                   1439:          $text=$Question{'Comments'}||'';
                   1440:          if ($text) {
                   1441:              $text=~s/\n/<option>/mg;
                   1442:             $output.="<select><option selected>Комментарий:<option>$text</select>"
                   1443:          }
                   1444:        } 
                   1445:        elsif ($answer==3) {
                   1446:         $output.=  <<EOTT
                   1447:          <div align=right STYLE="cursor:hand;" OnStart="toggle(document.all.HideShow$qnum);" OnClick="toggle(document.all.HideShow$qnum);">
                   1448:          <font size=-2 color=red> Показать/убрать ответ</font></div>
                   1449:          <span style="display:none" id=HideShow$qnum>
                   1450: EOTT
                   1451:           .&PrintField("Ответ", $Question{'Answer'}, $text);
                   1452:                if ($Question{'Authors'}) {
                   1453:                        $output .= &PrintField("Автор(ы)", $Question{'Authors'}, $text);
                   1454:                }
                   1455:                if ($Question{'Sources'}) {
                   1456:                        $output .= &PrintField("Источник(и)", $Question{'Sources'}, $text);
                   1457:                }
                   1458: 
                   1459:                if ($Question{'Comments'}) {
                   1460:                        $output .= &PrintField("Комментарии", $Question{'Comments'}, $text);
                   1461:                }
                   1462: 
1.83      roma7    1463: 
1.68      roma7    1464: 
                   1465: $output.="</span>"
                   1466: 
                   1467:        }
1.83      roma7    1468:        $output=~s/\(pic: ([^\)]*)\)/<p><img src="\/znatoki\/images\/db\/$1"><p>/g unless $text;
1.116     roma7    1469:        $paramtour||=param("tour");
1.133     roma7    1470:        $fname=$fname.".$Question{'TourNumber'}" if $fname && $Question{'TourNumber'};
                   1471: $fname||=param('tour');
                   1472:        my $qid=$fname ? ($fname.".$Question{'Number'}" ): '';
1.87      roma7    1473: 
1.100     roma7    1474:        $output.=br.a({href=> $url."?metod=proxy&
1.87      roma7    1475: qid=$qid"}, 'Близкие вопросы').p
                   1476:              if $answer>0 && !$text && $qid;
1.1       boris    1477:        return $output;
                   1478: }
                   1479: 
                   1480: # Returns the total number of questions currently in the DB.
                   1481: sub GetQNum {
1.126     roma7    1482:        my ($dbh,$x) = @_;
1.1       boris    1483:        my ($sth) = $dbh->prepare("SELECT COUNT(*) FROM Questions");
                   1484:        $sth->execute;
1.54      roma7    1485:        my $tmp=($sth->fetchrow)[0];
                   1486:         $sth->finish;
1.126     roma7    1487:        ($sth)=  $dbh -> prepare("select distinct count(first) FROM equalto");
                   1488:                   $sth -> execute;
                   1489:        my ($c)=$sth->fetchrow;
                   1490: 
                   1491: #                 $i++  while ( my  ($first, $second)=$sth -> fetchrow)
                   1492: #                  {
                   1493: #                       $forbidden{$first}=1;
                   1494: #                  }
                   1495:                   $sth->finish;
                   1496: 
                   1497:        return $tmp-($x?$c:0);
1.1       boris    1498: }
1.12      boris    1499: sub GetMaxQId {
                   1500:        my ($dbh) = @_;
                   1501:        my ($sth) = $dbh->prepare("SELECT MAX(QuestionId) FROM Questions");
                   1502:        $sth->execute;
1.54      roma7    1503:        my $tmp=($sth->fetchrow)[0];
                   1504:         $sth->finish;
                   1505:        return $tmp;
                   1506: 
1.12      boris    1507: }
1.1       boris    1508: 
                   1509: # Returns Id's of 12 random questions
                   1510: sub Get12Random {
                   1511:    my ($dbh, $type, $num) = @_;
                   1512:        my ($i, @questions, $q, $t, $sth);
1.12      boris    1513:        my ($qnum) = &GetMaxQId($dbh);
1.1       boris    1514:        my (%chosen);
                   1515:        srand;
1.53      roma7    1516:        my $where=0;
                   1517:        my $r=int (rand(10000));
1.130     roma7    1518:        my $w1=$r<5000? "QuestionId<50000 ":"QuestionId>=50000";
                   1519:        $w1=1 if $url=~/zaba/;
1.129     roma7    1520:        $w1=1 if $type!~/Ч/;
1.53      roma7    1521:        foreach (split '', $type)
                   1522:         {
                   1523:           $where.= " OR (Type ='$_') OR (Type ='$_Д') ";
                   1524:        }
                   1525:         $where.= "OR (Type='ЧБ')" if ($type=~/Ч|Б/);
                   1526: 
1.95      roma7    1527: #   $q="select QuestionId, QuestionId/$r-floor(QuestionId/$r) as val 
                   1528: #       from Questions where $where order by val limit $num";
1.53      roma7    1529: # Когда на куличках появится mysql >=3.23 надо заменить на order by rand();
1.129     roma7    1530:    $q="select QuestionId from Questions where ($w1) AND ($where) order by rand() limit $num";
1.95      roma7    1531: 
1.53      roma7    1532: 
                   1533:    $sth=$dbh->prepare($q);
                   1534:    $sth->execute;
                   1535:    while (($i)=$sth->fetchrow)
                   1536:    {
                   1537:       push @questions,$i;
1.11      boris    1538:    }
1.54      roma7    1539:    $sth->finish;
1.53      roma7    1540:     for ($i=@questions; --$i;){ 
                   1541:        my $j=rand ($i+1); 
                   1542:        @questions[$i,$j]=@questions[$j,$i] unless $i==$j;
                   1543:     }
1.11      boris    1544:    return @questions;
1.1       boris    1545: }
                   1546: 
                   1547: sub Include_virtual {
                   1548:        my ($fn, $output) = (@_, '');
1.119     roma7    1549:        return "\n<!--#include virtual=\"$fn\"-->\n" if ($opt_z);
1.1       boris    1550:        open F , $fn
1.103     roma7    1551:                or return ""; #die "Can't open the file $fn: $!\n";
1.37      roma7    1552: 
1.1       boris    1553:        while (<F>) {
                   1554:                if (/<!--#include/o) {
1.119     roma7    1555:                        s/<!--#include virtual="\/?([^\/].*)" -->/&Include_virtual($1)/e;
1.1       boris    1556:                }
                   1557:                if (/<!--#exec/o) {
                   1558:                        s/<!--#exec.*cmd\s*=\s*"([^"]*)".*-->/`$1`/e;
                   1559:                }
                   1560:                $output .= $_;
                   1561:        }
1.103     roma7    1562:        return $output||"";
1.1       boris    1563: }
                   1564: 
                   1565: sub PrintArchive {
                   1566:        my($dbh, $Id) = @_;
                   1567:        my ($output, @list, $i);
                   1568: 
                   1569:        my (%Tournament) = &GetTournament($dbh, $Id);
                   1570:        my (@Tours) = &GetTours($dbh, $Id);
                   1571:        if ($Tournament{'Type'} =~ /Г/ || $Id == 0) {
                   1572:                for ($i = 0; $i <= $#Tours; $i++) {
                   1573:                        push(@list ,&PrintArchive($dbh, $Tours[$i]));
                   1574:                }
                   1575:                return @list;
                   1576:        }
1.60      roma7    1577: #      return "$SRCPATH/$Tournament{'FileName'} ";
                   1578:        return "$TMPDIR/$Tournament{'FileName'} ";
1.1       boris    1579: }
                   1580: 
                   1581: sub PrintAll {
1.54      roma7    1582:        my ($dbh, $Id,$fname) = @_;
1.1       boris    1583:        my ($output, $list, $i);
                   1584: 
                   1585:        my (%Tournament) = &GetTournament($dbh, $Id);
                   1586:        my (@Tours) = &GetTours($dbh, $Id);
1.107     roma7    1587:        my $SingleTour = $#Tours == 0;
                   1588: 
1.37      roma7    1589:        my ($New) = ($Id and $Tournament{'Type'} eq 'Ч' and
1.1       boris    1590:                &NewEnough($Tournament{"CreatedAt"})) ?
                   1591:                img({src=>"/znatoki/dimrub/db/new-sml.gif", alt=>"NEW!"}) : "";
                   1592: 
                   1593:        if ($Id == 0) {
                   1594:                $output = h3("Все турниры");
                   1595:        } else {
1.54      roma7    1596:                 my $textid;
                   1597:                 if ($textid=$Tournament{'FileName'})
                   1598:                 {
                   1599:                   $textid=~s/\.txt//;
                   1600:                 }
                   1601:                 elsif ($textid=$Tournament{'Number'})
                   1602:                 {
                   1603:                      $fname=~s/\.txt//;
                   1604:                      $textid="$fname.$textid";
                   1605:                 }
                   1606:                 else {$textid=$Tournament{'Id'}};
                   1607: 
                   1608: 
1.1       boris    1609:                $output .= dd(img({src=>"/icons/folder.gif", alt=>"[*]"}) .
1.107     roma7    1610:       " " . a({href=>tourhref($textid,0,!$SingleTour)},
1.74      roma7    1611:       $Tournament{'Title'}) ." " . ($Tournament{'PlayedAt'}||'') . " $New");
1.1       boris    1612:        }
1.54      roma7    1613:        if ($Id == 0 or $Tournament{'Type'} =~ /Г/ or $Tournament{'Type'} eq '') {
1.1       boris    1614:                for ($i = 0; $i <= $#Tours; $i++) {
1.54      roma7    1615:                        $list .= &PrintAll($dbh, $Tours[$i],$Tournament{'FileName'});
1.1       boris    1616:                }
                   1617:                $output .= dl($list);
                   1618:        }
                   1619:        return $output;
                   1620: }
                   1621: 
                   1622: sub PrintDates {
                   1623:        my ($dbh) = @_;
1.37      roma7    1624:        my ($from) = param('from_year') . "-" . param('from_month') .
1.1       boris    1625:                "-" .  param('from_day');
                   1626:        my ($to) = param('to_year') . "-" . param('to_month') . "-" .  param('to_day');
                   1627:        $from = $dbh->quote($from);
                   1628:        $to = $dbh->quote($to);
                   1629:        my ($sth) = $dbh->prepare("
                   1630:                SELECT DISTINCT Id
                   1631:                FROM Tournaments
                   1632:                WHERE PlayedAt >= $from AND PlayedAt <= $to
                   1633:                AND Type = 'Ч'
                   1634:        ");
                   1635:        $sth->execute;
                   1636:        my (%Tournament, @array, $output, $list);
                   1637: 
                   1638:        $output = h3("Список турниров, проходивших между $from и $to.");
                   1639:        while (@array = $sth->fetchrow) {
                   1640:                next
                   1641:                        if (!$array[0]);
                   1642:                %Tournament = &GetTournament($dbh, $array[0]);
1.123     roma7    1643:                 my $textid;
                   1644:                 if ($textid=$Tournament{'FileName'})
                   1645:                 {
                   1646:                   $textid=~s/\.txt//;
                   1647:                 }
                   1648:                 elsif ($textid=$Tournament{'Number'})
                   1649:                 {
                   1650:                      $fname=~s/\.txt//;
                   1651:                      $textid="$fname.$textid";
                   1652:                 }
                   1653:                 else {$textid=$Tournament{'Id'}};
1.1       boris    1654:       $list .= dd(img({src=>"/icons/folder.gif", alt=>"[*]"}) .
1.123     roma7    1655:       " " . a({href=>tourhref($textid,0,1)},
1.74      roma7    1656:       $Tournament{'Title'}, $Tournament{'PlayedAt'}||''));
1.1       boris    1657:        }
1.49      roma7    1658:         $sth->finish;
1.1       boris    1659:        $output .= dl($list);
                   1660:        return $output;
                   1661: }
                   1662: 
1.29      roma7    1663: sub PrintQOfAuthor
                   1664: {
1.41      roma7    1665: 
1.29      roma7    1666:     my ($dbh, $id) = @_;
1.95      roma7    1667:     my $Output='';
1.87      roma7    1668:     unless ($id=~/^\d+$/) {
                   1669:       $id=$dbh->quote($id);
                   1670:       my $sth =  $dbh->prepare("SELECT Id FROM Authors WHERE CharId=$id");
                   1671:       $sth->execute;
                   1672:       ($id)=$sth->fetchrow;
                   1673:       $sth->finish;
                   1674:     }
                   1675:     $id=$dbh->quote($id);
                   1676: 
1.37      roma7    1677:     my $sth =  $dbh->prepare("SELECT  Name, Surname FROM Authors WHERE Id=$id");
1.29      roma7    1678:     $sth->execute;
                   1679:     my ($name,$surname)=$sth->fetchrow;
                   1680: 
1.37      roma7    1681:     $sth =  $dbh->prepare("SELECT Question FROM A2Q WHERE Author=$id");
1.29      roma7    1682:     $sth->execute;
                   1683:     my $q;
1.37      roma7    1684:     my @Questions;
1.29      roma7    1685:     while (($q)=$sth->fetchrow,$q)
1.36      roma7    1686:      {push @Questions,$q unless $forbidden{$q}}
1.49      roma7    1687:     $sth->finish;
1.29      roma7    1688: 
                   1689:     my ($output, $i, $suffix, $hits) = ('', 0, '', $#Questions + 1);
                   1690: 
                   1691:     if ($hits =~ /1.$/  || $hits =~ /[5-90]$/) {
                   1692:                $suffix = 'й';
                   1693:        } elsif ($hits =~ /1$/) {
                   1694:                $suffix = 'е';
                   1695:        } else {
1.37      roma7    1696:                $suffix = 'я';
1.29      roma7    1697:        }
1.95      roma7    1698:        $Output.= printform;
                   1699:        $Output.= p({align=>"center"}, "Автор ".strong("$name $surname. ")
1.29      roma7    1700:        . " : $hits попадани$suffix.");
                   1701: 
                   1702: 
1.40      roma7    1703: #      for ($i = 0; $i <= $#Questions; $i++) {
                   1704: #              $output = &PrintQuestion($dbh, $Questions[$i], 1, $i + 1, 1);
                   1705: #              print $output;
                   1706: #      }
1.95      roma7    1707:         $Output.=PrintList($dbh,\@Questions,'gdfgdfgdfgdfg');
1.29      roma7    1708: }
                   1709: 
                   1710: 
                   1711: sub PrintAuthors
                   1712: {
                   1713:      my ($dbh,$sort)=@_;
                   1714:      my($output,$out1,@array,$sth);
1.37      roma7    1715:      if ($sort eq 'surname')
1.29      roma7    1716:      {
1.37      roma7    1717:         $sth =
                   1718:              $dbh->prepare("SELECT Id, Name, Surname, QNumber FROM Authors order by Surname, Name");
                   1719:      }
                   1720:      elsif($sort eq 'name')
                   1721:      {
                   1722:         $sth =
                   1723:              $dbh->prepare("SELECT Id, Name, Surname, QNumber FROM Authors order by Name, Surname");
1.29      roma7    1724:      }
                   1725:      else
                   1726:      {
1.37      roma7    1727:         $sth =
                   1728:              $dbh->prepare("SELECT Id, Name, Surname, QNumber FROM Authors Order by QNumber DESC, Surname");
1.29      roma7    1729:      }
                   1730: 
1.37      roma7    1731:      $output.=h2("Авторы вопросов")."\n";
                   1732:      $output.="<TABLE>";
                   1733: 
                   1734: 
1.29      roma7    1735:      $sth->execute;
1.100     roma7    1736:      $output.=Tr(th[a({href=>$url."?authors=name"},"Имя")
1.37      roma7    1737: .", ".
1.100     roma7    1738: a({href=>$url."?authors=surname"},"фамилия")
                   1739:      , a({href=>$url."?authors=kvo"},"Количество вопросов")]);
1.29      roma7    1740: 
                   1741:      $out1='';
                   1742: 
                   1743:      my $ar=$sth->fetchall_arrayref;
                   1744: 
1.54      roma7    1745:      $sth->finish;
1.29      roma7    1746: 
1.33      boris    1747: 
1.29      roma7    1748:     foreach my $arr(@$ar)
                   1749:      {
1.37      roma7    1750: 
1.29      roma7    1751:            my ($id,$name,$surname,$kvo)=@$arr;
1.95      roma7    1752:            if (!$name || !$surname) {
1.37      roma7    1753:               } else
1.29      roma7    1754:            {
1.100     roma7    1755:              my $add=Tr(td([a({href=>$url."?qofauthor=$id"},"$name $surname"), $kvo]))."\n";
1.29      roma7    1756:              $output.=$add;
                   1757:            }
                   1758:      }
                   1759:      $output.="</TABLE>";
1.49      roma7    1760:      $sth->finish;
1.29      roma7    1761:      return $output;
                   1762: }
                   1763: 
                   1764: 
1.60      roma7    1765: sub WriteFile {
                   1766:   my ($dbh,$fname) = @_;
1.72      roma7    1767:   $fname=~s/\s+$//;
                   1768:   $fname=~s/^\s+//;
1.60      roma7    1769:   $fname=~s/\.txt$//;
                   1770:   $fname=~s/.*\/(\w+)/$1/;
1.72      roma7    1771: 
1.60      roma7    1772:   my $query= "SELECT Id, Title, Copyright, Info, URL, 
                   1773:                       Editors, EnteredBy, PlayedAt, CreatedAt 
1.116     roma7    1774:                      from Tournaments where FileName=
                   1775:                      '$fname' OR FileName=".$dbh->quote("$fname.txt");
1.60      roma7    1776:   my $sth=$dbh->prepare($query);
                   1777:   my (%Question,%editor,%qnumber,%copyright,%author,%vid,%tourtitle);
                   1778:   $sth->execute;
                   1779:   my ($Id, $Title, $Copyright, $Info, $URL, 
                   1780:    $Editors, $EnteredBy, $PlayedAt, $CreatedAt)=
                   1781:       $sth->fetchrow;
                   1782:   return -1 unless $Id;
1.72      roma7    1783:   open (OUT, ">$TMPDIR/$fname.txt") || print STDERR "Error in $fname.txt\n";
1.60      roma7    1784:   print OUT "Чемпионат:\n$Title\n\n";
1.74      roma7    1785:   my $date=$PlayedAt||'00-00-00';
1.60      roma7    1786:   my ($year,$month,$day)=split /-/, $date;
                   1787: #  $month=0,$date=0 if $year && $month==1 && $day==1;
                   1788:   my $pdate=sprintf("%02d-%3s-%4d",$day,$months[$month],$year);
                   1789: 
                   1790:   print OUT "Дата:\n$pdate\n\n" if $date;
                   1791: 
                   1792:   print OUT "URL:\n$URL\n\n" if $URL;
                   1793: 
                   1794:   print OUT "Инфо:\n$Info\n\n" if $Info;
                   1795: 
                   1796:   print OUT "Копирайт:\n$Copyright\n\n" if $Copyright;
                   1797: 
                   1798:   print OUT "Редактор:\n$Editors\n\n" if $Editors;
                   1799: 
                   1800: 
                   1801:   $query= "SELECT Id, Title, Copyright, Editors from Tournaments where ParentId=$Id order by Id";
                   1802:   $sth=$dbh->prepare($query);
                   1803:   $sth->execute;
                   1804:   my ($tourid,$tourtitle,$cright,$editor,@tours,$vid,$author,$tourauthor);
                   1805: 
                   1806: 
                   1807:   while (($tourid,$tourtitle,$cright,$editor)=$sth->fetchrow,$tourid)
                   1808:   {
                   1809: #    $text{$tourid}="Тур:\n$tourtitle\n\n";
                   1810:     $query= "SELECT * from Questions where ParentId=$tourid order by QuestionId";
                   1811:     my $sth1=$dbh->prepare($query);
                   1812:     $sth1->execute;
                   1813:     push(@tours,$tourid);
                   1814:     $tourtitle{$tourid}=$tourtitle;
                   1815:     $copyright{$tourid}=$cright;
                   1816:     $editor{$tourid}=$editor;
                   1817:     $vid='';
                   1818:     my $author='';
                   1819:     my $eqauthor=1;
                   1820:     my $qnumber=0;
                   1821:     my @arr;
1.72      roma7    1822:     while ( (@arr=$sth1->fetchrow), $arr[0])
1.60      roma7    1823:     {
1.72      roma7    1824:        my($i, $name);
                   1825:        $i=0;
1.60      roma7    1826:        $qnumber++;
                   1827:        foreach $name (@{$sth1->{NAME}}) {
1.72      roma7    1828:                if ($arr[$i]) {
                   1829:                   $arr[$i]=~s/^(.*?)\s*$/$1/;
                   1830:                   $Question{$tourid}[$qnumber]{$name} = $arr[$i];
                   1831:                } else {
                   1832:                    $Question{$tourid}[$qnumber]{$name} = 
                   1833:                    ''}
                   1834:                 $i++;
1.60      roma7    1835:        }
                   1836:        if ($vid)
                   1837:         {
                   1838:           if ($vid ne $Question{$tourid}[$qnumber]{'Type'}) {print STDERR "Warning: Different types for Tournament $tourid\n"}
                   1839:         } else 
                   1840:         {
                   1841:             $vid=$Question{$tourid}[$qnumber]{'Type'};
                   1842:         } 
                   1843: 
                   1844:        if ($author)
                   1845:         {
                   1846:           if ($author ne $Question{$tourid}[$qnumber]{'Authors'})  
                   1847:           {
                   1848:              $eqauthor=0;
                   1849:           }
                   1850:         } else 
                   1851:         {
                   1852:             $author=$Question{$tourid}[$qnumber]{'Authors'};
                   1853:             $eqauthor=0 unless $author;
                   1854:         } 
                   1855:     }
                   1856:     $vid{$tourid}=$vid;
                   1857:     $qnumber{$tourid}=$qnumber;
                   1858:     $author{$tourid}=$eqauthor ? $author : '';
                   1859:   }
                   1860: 
                   1861: 
                   1862:   $vid='';
                   1863:   my $eqvid=1;
                   1864:   my $eqauthor=1;
                   1865:   foreach (@tours)
                   1866:   {
                   1867:      $vid||=$vid{$_};
                   1868:      if ($vid{$_} ne $vid)
                   1869:      {
                   1870:         $eqvid=0;
                   1871:      }
                   1872:      $author||=$author{$_};
                   1873:      if (!$author{$_} || ($author{$_} ne $author))
                   1874:      {
                   1875:         $eqauthor=0;
                   1876:      }
                   1877:   }
                   1878:   
                   1879:   print OUT "Вид:\n$vid\n\n" if $eqvid;
                   1880:   print OUT "Автор:\n$author\n\n" if $eqauthor;
                   1881: 
                   1882:   foreach my $tour(@tours)
                   1883:   {
                   1884:      print OUT "Тур:\n$tourtitle{$tour}\n\n";
                   1885:      print OUT "Вид:\n$vid{$tour}\n\n" if  !$eqvid;
                   1886:      print OUT "Копирайт:\n$copyright{$tour}\n\n" if $copyright{$tour} && ($copyright{$tour} ne $Copyright);
                   1887:      print OUT "Редактор:\n$editor{$tour}\n\n" if $editor{$tour} && ($editor{$tour} ne $Editors);
                   1888:      $tourauthor=0;
                   1889:      if (!$eqauthor && $author{$tour})
                   1890:      { 
                   1891:        print OUT "Автор:\n$author{$tour}\n\n";
                   1892:        $tourauthor=1;
                   1893:      }
                   1894:      foreach my $q(1..$qnumber{$tour})
                   1895:      {
                   1896:         print OUT "Вопрос $q:\n".$Question{$tour}[$q]{'Question'}."\n\n";
                   1897:        print OUT  "Ответ:\n".$Question{$tour}[$q]{'Answer'}."\n\n";
                   1898:        print OUT  "Автор:\n".$Question{$tour}[$q]{'Authors'}."\n\n" 
                   1899:                if !$tourauthor && !$eqauthor && $Question{$tour}[$q]{'Authors'};
                   1900:        print OUT  "Комментарий:\n".$Question{$tour}[$q]{'Comments'}."\n\n" 
                   1901:                if $Question{$tour}[$q]{'Comments'};
                   1902:        print OUT "Источник:\n".$Question{$tour}[$q]{'Sources'}."\n\n" 
                   1903:                if $Question{$tour}[$q]{'Sources'};
                   1904:        print OUT "Рейтинг:\n".$Question{$tour}[$q]{'Rating'}."\n\n" 
                   1905:                if $Question{$tour}[$q]{'Rating'};
                   1906: 
                   1907:      }
                   1908:   }
                   1909: 
                   1910:   close OUT;
                   1911: 
                   1912: 
                   1913: 
                   1914: }
                   1915: 
1.100     roma7    1916: sub Bottom
                   1917: {
1.116     roma7    1918:        my $output.=&Include_virtual("$footer")||"";
                   1919:        $output.=p."<center><font size=-2>Обновление: ".&Include_virtual("$datefooter")."</center></font>";
1.100     roma7    1920:        $output.=<<EEE
                   1921: <SCRIPT LANGUAGE="JavaScript">
                   1922: function toggle(e) {
                   1923:   if (e.style.display == "none") {
                   1924:      e.style.display="";
                   1925:   } else {
                   1926:      e.style.display = "none";
                   1927:  }
                   1928: }
                   1929: </SCRIPT>
                   1930: EEE
                   1931: ;
                   1932:        $output.=end_html;
                   1933:        return $output;
                   1934: }
                   1935: 
1.37      roma7    1936: 
1.1       boris    1937: MAIN:
                   1938: {
1.89      roma7    1939:         
1.1       boris    1940:        setlocale(LC_CTYPE,'russian');
1.116     roma7    1941:        POSIX::setlocale( &POSIX::LC_ALL, $thislocale );
1.1       boris    1942:        my($i, $tour);
                   1943:        my($text) = (param('text')) ? 1 : 0;
1.121     roma7    1944:        $tour = (param('tour')) ? param('tour') : 0;
                   1945:        my $texttour=$tour;
                   1946:        my ($sth,$dbh);
1.130     roma7    1947:        my($dsn) = "DBI:mysql:database=$dbname;host=$dbhost";
                   1948:         $dbh = DBI->connect($dsn, $dbuser, $dbpass) 
                   1949: #      $dbh = DBI->connect("DBI:mysql:$dbname", $username, $dbpass)
1.121     roma7    1950:                or do {
1.130     roma7    1951:                        print header.h1("Временные проблемы") . "База вопросов временно не
1.121     roma7    1952:                        работает. Заходите попозже.";
                   1953:                        print &Include_virtual("$reklama") if $url!~/localhost/;
                   1954:                    print end_html;
                   1955:                        die "Can't connect to DB chgk\n";
                   1956:                };
                   1957: 
                   1958: 
                   1959:        if (param('qid') && (param('qid')=~/^\d+$/) || $tour && $tour=~/^\d+$/) {
1.130     roma7    1960:           my $destination='http://chgk.zaba.ru/search.html';
1.95      roma7    1961: #              print header (-'Content-Type' => 'text/html',
                   1962: #                -'Location:'=> 'http:\\db.chgk.info');
                   1963:                Redirect($destination);
                   1964:                 exit
                   1965:        }
                   1966: 
1.125     boris    1967:        if ($tour && !param('qnumber') && (!param('answers')||(param('answers')<=1)))
1.121     roma7    1968:        {       
                   1969:                my $n=param('tour');
                   1970:                $n=~s/.txt$//;        
                   1971:                my $gr=($n=~/^[A-Z]/) || (-e "$realHTMLDIR$n.html");
                   1972:                my $destination=tourhref($tour,param('answers')||0,$gr);
                   1973:                my $d=$destination;
                   1974:                $d=~s/$HTMLDIR/$realHTMLDIR/;
                   1975: #              print header.$destination;
1.131     roma7    1976: #                print header."$d|".(-e "$realHTMLDIR$n.html");
1.121     roma7    1977:                 if (-e $d) {
                   1978:                        Redirect($destination);
                   1979:                        exit
                   1980:                }
                   1981:                $d=~s/\.\d+//;
                   1982:                $destination=~s/\.\d+//;
                   1983:                 if (-e $d) {
                   1984:                        Redirect($destination);
                   1985:                        exit
                   1986:                }
                   1987: 
                   1988:        }
                   1989: 
                   1990:        if ($tour !~ /^[0-9]*$/) {          
                   1991:                    if ($tour=~/\./)
                   1992:                    {
                   1993:                        my ($fname,$n)= split /\./ , $tour;
                   1994: 
                   1995:                        $sth = $dbh->prepare(
                   1996:                        "SELECT t2.Id FROM Tournaments as t1, 
                   1997:                         Tournaments as t2 
                   1998:                        WHERE (t1.FileName = '$fname.txt' OR t1.FileName='$fname')
                   1999:                         AND t1.Id=t2.ParentId AND t2.Number=$n");
                   2000:                    }   
                   2001:                    else 
                   2002:                        {
                   2003:                           $sth = $dbh->prepare("SELECT Id FROM Tournaments
                   2004:                                     WHERE FileName = '$tour.txt' OR 
                   2005:                                        FileName = '$tour'");
                   2006:                        }
                   2007:                    $sth->execute;
                   2008:                    $tour = ($sth->fetchrow)[0];
                   2009:                     $sth->finish;
                   2010:        }
                   2011: 
                   2012: 
1.118     roma7    2013:        if ($text && !param ('comp')) {
1.85      roma7    2014:                print header('text/plain');
1.130     roma7    2015:        } elsif (!param('comp')) {
                   2016:                print header(-charset =>'koi8-r')}
1.89      roma7    2017:          my $sstr=param('sstr');
1.116     roma7    2018:           $opt_z||=param("makehtml");
1.89      roma7    2019:          if (param('qid')) {
                   2020:              my $sth;
                   2021:              my $qid=param('qid');
1.95      roma7    2022: #              if ($qid !~ /^[0-9]+$/) 
                   2023:                 {
1.89      roma7    2024:                     my ($fname,$t,$n)= split /\./ , $qid;
                   2025:                     $n=$t,$t='' unless $n;
1.116     roma7    2026:                     $t||=1;
1.95      roma7    2027:                    if ($t)
1.89      roma7    2028:                    {
                   2029:                        $sth = $dbh->prepare(
                   2030:                        "SELECT t2.Id FROM Tournaments as t1, 
                   2031:                         Tournaments as t2 
1.116     roma7    2032:                        WHERE (t1.FileName = '$fname.txt' OR t1.FileName='$fname')
1.89      roma7    2033:                         AND t1.Id=t2.ParentId AND t2.Number=$t");
                   2034:                    }   
1.116     roma7    2035: #                  else 
                   2036: #                      {
                   2037: #                          $sth = $dbh->prepare("SELECT Id FROM Tournaments
                   2038: #                                   WHERE FileName = '$fname.txt' OR FileName = '$fname'" );
                   2039: #                      }
1.89      roma7    2040:                    $sth->execute;
                   2041:                    $tour = ($sth->fetchrow)[0];
                   2042:                     $sth->finish;
                   2043:                    $sth = $dbh->prepare(
                   2044:                        "SELECT QuestionId FROM 
                   2045:                         Questions 
                   2046:                        WHERE ParentId=$tour AND 
                   2047:                         Questions.Number=$n");
                   2048:                        $sth->execute;
                   2049:                        $qid = ($sth->fetchrow)[0];
1.95      roma7    2050:                     my $query="SELECT Question, Answer from Questions where QuestionId=$qid";
                   2051:                     $sth=$dbh->prepare($query);
                   2052:                     $sth->execute;
                   2053:                     $sstr= join ' ',$sth->fetchrow;
                   2054:                     $sth->finish;
                   2055:                     $searchin{'Question'}=1;
                   2056:                     $searchin{'Answer'}=1;
                   2057:                     $sstr=~tr/ёЁ/еЕ/;
                   2058:                     $sstr=~s/[^йцукенгшщзхъфывапролджэячсмитьбюЙЦУКЕНГШЩЗХЪФЫВАПРОЛДЖЭЯЧСМИТЬБЮa-zA-Z0-9]/ /gi;
                   2059:                     $proxysstr=$sstr;
                   2060:                     $proxysstr=makeproxysstr($dbh,\$proxysstr);
                   2061:               } 
                   2062:               
1.89      roma7    2063:        }
                   2064: 
                   2065: 
1.11      boris    2066:        if (!param('comp') and !param('sqldump') and !$text) {
1.89      roma7    2067:           my $title="Результаты поиска на \"". ($proxysstr||$sstr) .'"' 
                   2068:                                                     if ($proxysstr||$sstr);
                   2069:            $title||="База вопросов";
1.95      roma7    2070:           $globaloutput.=start_html(-"title"=>$title,
1.1       boris    2071:                   -author=>'dimrub@icomverse.com',
                   2072:                   -bgcolor=>'#fff0e0',
1.132     roma7    2073:                                  -vlink=>'#800020');#}
1.95      roma7    2074: $globaloutput.="<style>
1.85      roma7    2075: td     {font-size: x-small; font-family : sans-serif}
                   2076: th     {font-size: x-small; font-family : sans-serif}
1.84      roma7    2077: </style>\n";
                   2078: 
1.113     roma7    2079:                $globaloutput.=&Include_virtual("$reklama")||'';
1.1       boris    2080:        }
1.22      roma7    2081: 
1.130     roma7    2082:        if ($usehash && !$opt_z && length ($qs)<=255 && $qs !~ /(sstr)|(rand)|(comp)|(all=)/i) {
1.95      roma7    2083:                my $sth=$dbh->prepare("SELECT page,times,t from hash where query=".$dbh->quote($qs));
                   2084:                $sth->execute();
                   2085:                my ($p,$times,$t)=$sth->fetchrow();
                   2086:                $sth->finish;
                   2087:                if ($p) {
                   2088:                        print ".$p";
                   2089:                        $dbh->disconnect;
                   2090:                        exit ;
                   2091:                }
                   2092:        }
                   2093: 
1.41      roma7    2094: 
1.22      roma7    2095: 
1.36      roma7    2096: 
1.37      roma7    2097:         if (param('hideequal')) {
1.36      roma7    2098:                   my ($sth)=  $dbh -> prepare("select first, second FROM equalto");
                   2099:                   $sth -> execute;
                   2100:                   while ( my  ($first, $second)=$sth -> fetchrow)
                   2101:                   {
                   2102:                        $forbidden{$first}=1;
                   2103:                   }
                   2104:                   $sth->finish;
1.37      roma7    2105:         }
1.134   ! roma7    2106: 
1.36      roma7    2107: 
1.1       boris    2108: 
                   2109:        if (param('rand')) {
1.7       boris    2110:                my ($type, $qnum) = ('', 12);
1.53      roma7    2111:                $type.=$TypeName{$_} foreach param('type');
                   2112: #              $type .= 'Б' if (param('brain'));
                   2113: #              $type .= 'Ч' if (param('chgk'));
1.37      roma7    2114:                $qnum = param('qnum') if (param('qnum') =~ /^\d+$/);
1.7       boris    2115:                $qnum = 0 if (!$type);
1.52      roma7    2116:                my $Email;
                   2117:                if (($Email=param('email')) && -x $SENDMAIL &&
                   2118:                open(F, "| $SENDMAIL $Email")) {
1.1       boris    2119:                        my ($mime_type) = $text ? "plain" : "html";
                   2120:                        print F <<EOT;
                   2121: To: $Email
1.52      roma7    2122: From: olegstepanov\@mail.ru
1.1       boris    2123: Subject: Sluchajnij Paket Voprosov "Chto? Gde? Kogda?"
                   2124: MIME-Version: 1.0
                   2125: Content-type: text/$mime_type; charset="koi8-r"
                   2126: 
                   2127: EOT
                   2128:                        print F &PrintRandom($dbh, $type, $qnum, $text);
                   2129:                        close F;
1.95      roma7    2130:                        $globaloutput.= "Пакет случайно выбранных вопросов послан по адресу $Email. Нажмите
1.1       boris    2131:                        на <B>Reload</B> для получения еще одного пакета";
                   2132:                } else {
1.95      roma7    2133:                        $globaloutput.= &PrintRandom($dbh, $type, $qnum, $text);
1.1       boris    2134:                }
1.37      roma7    2135:        }
1.29      roma7    2136:          elsif (param('authors')){
1.95      roma7    2137:                 $globaloutput.= &PrintAuthors($dbh,param('authors'));
1.29      roma7    2138:         }
                   2139:           elsif (param('qofauthor')){
1.95      roma7    2140:                 $globaloutput.= &PrintQOfAuthor($dbh,param('qofauthor'));
1.29      roma7    2141:         }
1.54      roma7    2142:           elsif (param('sstr')||param('was')) {
1.95      roma7    2143:                $globaloutput.=&PrintSearch($dbh, $sstr||' ', param('metod')||'',param('was'));
1.54      roma7    2144:                $dbh->do("delete from lastqueries where
1.57      roma7    2145:                       (TO_DAYS(NOW()) - TO_DAYS(t) >= 2) OR
1.95      roma7    2146:                           (time_to_sec(now())-time_to_sec(t) >3600)") if $usewas && random(30)==0;
1.40      roma7    2147:        } 
                   2148:          elsif (param('qid')) {
1.95      roma7    2149:              $globaloutput.=&PrintSearch($dbh, $sstr||'', 'proxy');
1.40      roma7    2150:        }
1.72      roma7    2151:        elsif (param('getfile')){
1.95      roma7    2152:            $globaloutput.=&writefile
1.72      roma7    2153:        } elsif (param('all')) {
1.118     roma7    2154: #         my $destination='http://db.chgk.info/all.html';
                   2155: #              Redirect($destination);
                   2156: #                exit;
                   2157:                $globaloutput.=&PrintAll($dbh, 0);
1.1       boris    2158:        } elsif (param('from_year') && param('to_year')) {
1.95      roma7    2159:                $globaloutput.=&PrintDates($dbh);
1.1       boris    2160:        } elsif (param('comp')) {
1.118     roma7    2161:             print "Content-Type: application/octet-stream\n";
                   2162:             print  "Content-Type: application/force-download\n";
                   2163:             print  "Content-Type: application/download\n";
1.119     roma7    2164:             print  "Content-Type: application/x-zip-compressed; name=$texttour.zip\n";
                   2165:             print "Content-Disposition: attachment; filename=$texttour.zip \n\n";
1.72      roma7    2166:            $tour ||= 0;
1.9       boris    2167:            my (@files) = &PrintArchive($dbh, $tour);
1.60      roma7    2168:            WriteFile($dbh,$_) foreach @files;
1.72      roma7    2169:            open F, "$ZIP -j - @files |";
                   2170:            binmode(F);
                   2171:            binmode(STDOUT);
1.118     roma7    2172:            print join "",<F>;
1.9       boris    2173:            close F;
                   2174:            $dbh->disconnect;
                   2175:            exit;
                   2176:        } elsif (param('sqldump')) {
                   2177:            print header(
                   2178:                         -'Content-Type' => 'application/x-zip-compressed; name="dump.zip"',
                   2179:                         -'Content-Disposition' => 'attachment; filename="dump.zip"'
                   2180:                         );
1.10      boris    2181:            open F, "$ZIP -j - $DUMPFILE |";
1.9       boris    2182:            print (<F>);
                   2183:            close F;
                   2184:            $dbh->disconnect;
                   2185:            exit;
                   2186: 
1.100     roma7    2187:        } 
1.116     roma7    2188:         elsif (!$opt_z && !param("makehtml")) {
1.65      roma7    2189:                my $QuestionNumber=0;
1.66      roma7    2190:                my $qnum;
                   2191:                if ($qnum=param('qnumber')){
1.65      roma7    2192:                  my ($sth) = $dbh->prepare("SELECT QuestionId FROM Questions
                   2193:                     WHERE ParentId=$tour AND Number=$qnum");
                   2194:                  $sth->execute;
                   2195:                  $QuestionNumber=($sth->fetchrow)[0]||0;
                   2196:                }
                   2197:                if ($QuestionNumber) {
1.114     roma7    2198:                  $globaloutput.= &PrintQuestion($dbh, $QuestionNumber, $withanswers||0, $qnum, 1,0,0);
1.66      roma7    2199: #                                        $dbh, $Id, $answer, $qnum, $title, $text
1.65      roma7    2200:                } else  {
1.114     roma7    2201:                   $globaloutput.=&PrintTournament($dbh, $tour, $withanswers);
1.65      roma7    2202:                }
1.1       boris    2203:        }
1.100     roma7    2204:        else {
1.116     roma7    2205:                  $opt_z=1;
                   2206:                  $url="http://db.chgk.info/cgi-bin/db.cgi";
1.121     roma7    2207:                  open TS, $timestamp;
1.100     roma7    2208:                  my $d=$dbh->quote(<TS>);
                   2209:                  close TS;
1.103     roma7    2210:                  open FF, ">${realHTMLDIR}index.html" or die "ERROR! - ${HTMLDIR}index.html\n";
                   2211:                       my $o=$globaloutput;
                   2212:                       $o.=&PrintTournament($dbh, 0, 0);
                   2213:                       $o.=&Bottom;
                   2214:                       print FF $o;
                   2215:                  close FF;
                   2216:                  open FF, ">${realHTMLDIR}all.html" or die "ERROR! - ${HTMLDIR}all.html\n";
                   2217:                       $o=$globaloutput;
                   2218:                       $o.=&PrintAll($dbh,0);
                   2219:                       $o.=&Bottom;
                   2220:                       print FF $o;
                   2221:                       close FF;
                   2222: 
                   2223: 
                   2224: #                        my ($sth) = $dbh->prepare("SELECT t1.Id, t1.FileName, t1.Type, 
                   2225: #                      count(t2.Id) 
                   2226: #                     FROM Tournaments as t1, Tournaments as t2
                   2227: #                   WHERE t1.CreatedAt>$d AND t2.ParentId=t1.Id GROUP BY t1.Id");
                   2228: 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    2229:  ON t2.ParentId=t1.id WHERE t1.CreatedAt>=$d GROUP BY t1.Id");
1.100     roma7    2230:                  $sth->execute;
                   2231:                  my ($Id,$fname,$type,$c);
                   2232:                  while (($Id,$fname,$type,$c)=$sth->fetchrow,$Id) {
1.103     roma7    2233:                     next unless $fname;
1.100     roma7    2234:                     print "$fname\n";
                   2235:                     $fname=~s/\.txt$//;
                   2236:                     if ($type=~/Т/ || $c<=1)
                   2237:                     {
1.110     roma7    2238:                       open FF, ">$realHTMLDIR$fname-q.html" or die "ERROR! - $fname-q.html\n";
1.100     roma7    2239:                       my $o=$globaloutput;
1.116     roma7    2240:                       $paramtour=$fname;
1.100     roma7    2241:                       $o.=&PrintTournament($dbh, $Id, 0);
                   2242:                       $o.=&Bottom;
                   2243:                       print FF $o;
                   2244:                       close FF;
                   2245:                       open FF, ">$realHTMLDIR$fname-a.html";
                   2246:                       $o=$globaloutput;
                   2247:                       $o.=&PrintTournament($dbh, $Id, 1);
                   2248:                       $o.=&Bottom;
                   2249:                       print FF $o;
                   2250:                       close FF;
                   2251:                     }
                   2252:                     else {
1.110     roma7    2253:                       open FF, ">$realHTMLDIR$fname.html" or die "ERROR! - $fname-q.html\n";
1.100     roma7    2254:                       my $o=$globaloutput;
                   2255:                       $o.=&PrintTournament($dbh, $Id, 0);
                   2256:                       $o.=&Bottom;
                   2257:                       print FF $o;
                   2258:                       close FF;
                   2259: 
                   2260:                     }
                   2261:                   }
                   2262:         }
1.1       boris    2263:        if (!$text) {
1.100     roma7    2264:                $globaloutput.=&Bottom;
1.95      roma7    2265:        }
1.100     roma7    2266:         if (!$opt_z){ 
                   2267:          print $globaloutput;
1.130     roma7    2268:          if (($qs!~ /(rand)|(sstr)|(comp)/i) && (length $qs<=255) && $usehash) {
1.95      roma7    2269:                $globaloutput=  $dbh->quote($globaloutput);
                   2270:                $dbh->do("insert into hash (query,page) values (".
                   2271:                $dbh->quote($qs).
                   2272:                     ",$globaloutput)");
1.100     roma7    2273:          }
1.1       boris    2274:        }
1.95      roma7    2275: 
1.1       boris    2276:        $dbh->disconnect;
                   2277: }

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