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

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

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