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

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

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