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

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

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