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

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

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