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

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

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