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

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

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