Diff for /db/prgsrc/db.cgi between versions 1.106 and 1.158

version 1.106, 2003/04/20 11:45:48 version 1.158, 2010/01/24 20:30:05
Line 2 Line 2
   
 use DBI;  use DBI;
 use CGI ':all';  use CGI ':all';
 use strict;  #use strict;
   use Encode;
   my @softfields=("От Олега Степанова");
 use Time::Local;  use Time::Local;
   use Data::Dumper "Dumper";
   use URI::Escape;
   my $proxyredirect=1;
 use POSIX qw(locale_h);  use POSIX qw(locale_h);
 use locale;  use locale;
 use vars qw($opt_z);  use vars qw($opt_z);
 use Getopt::Std;  use Getopt::Std;
   #my ($dbuser,$dbname,$dbpass,$dbhost);
   eval {require "dbdefs.pl";} ;
   my $url=url||'';
   my @used_stop=();
   my $showNearQuestions=0;
   $dbuser||="piataev";
   $dbname||="chgk";
   $dbpass||="";
   $dbhost||="localhost";
 getopts('z');  getopts('z');
   $opt_z||=param("makehtml");
   my $timestamp="_timestamp.tmp";
   my $usehash=0;
   my $paramtour;
   my $withanswers=param('answer')||param('answers');
 open STDERR, ">/var/tmp/errors1";  open STDERR, ">/var/tmp/errors1";
 my $newsurl='http://news.chgk.info/';  my $newsurl='http://news.chgk.info/';
 my $HTMLDIR="";  my $reklama="../dimrub/db/reklama.html";
   my $footer="../dimrub/db/footer.html";
   $footer="../../chgk/footer.html" if $url=~/zaba/;
   $reklama="../../chgk/reklama.html" if $url=~/zaba/;
   my $datefooter="../dimrub/db/date";
   $datefooter="../../chgk/date" if $url=~/zaba/;
   
   my $fname;
   $reklama="../reklama.html" if $opt_z;
   $footer="../footer.html" if $opt_z;
   $datefooter="../date" if $opt_z;
   my $HTMLDIR="/znatoki/dimrub/db/baza/";
   $HTMLDIR="/files/";
 my $realHTMLDIR;  my $realHTMLDIR;
 if ($^O =~ /win/i) {  if ($^O =~ /win/i) {
  $realHTMLDIR="/html/znatoki/baza/";   $realHTMLDIR="/html/znatoki/baza/";
 } else   } else 
 {  {
   $realHTMLDIR="/home/znatoki/public_html/dimrub/db/baza/";    $realHTMLDIR="/home/znatoki/chgk-db/public_html/dimrub/db/files/";
 }  }
 my $usehtml=1;  
   
   my $usehtml=$opt_z||0;
   $usehtml=1;
   $usehtml=0 if $url=~/zaba/ || $url=~/localhost/;
   
 my $usewas=0;  my $usewas=0;
 my $cashednumber=500;  my $cashednumber=500;
 my $outputnumber=10;  my $outputnumber=10;
 my ($proxyptext,$proxysstr);  my ($proxyptext,$proxysstr);
 my $printqueries=0;  my $printqueries=0;
 my $url=url||'';  
 my $qs=query_string;  my $qs=query_string;
 my $globaloutput;  my $globaloutput;
 my %forbidden=();  my %forbidden=();
 my $debug=0; #added by R7  my $debug=0; #added by R7
   my $metod=param('metod')||'';
 my $outputkvo=param('kvo') ||$outputnumber;  my $outputkvo=param('kvo') ||$outputnumber;
 $outputkvo=100 if $outputkvo>100;  $outputkvo=100 if $outputkvo>100;
   
 if (param('debug')) {$debug=1; $printqueries=1}  if (param('debug')) {$debug=1; $printqueries=1}
 *STDERR=*STDOUT if $debug;  *STDERR=*STDOUT if $debug;
 if ($url !~ /db\.chgk\.info/ && $url !~ /localhost/ ) {  if ($url!~ /\/\/db\// && $url !~ /db\.chgk\.info/ && $url !~ /localhost/ && $url !~ /bilbo/ && $url !~ /zaba/ && $url !~ /question\.chgk\.info/ ) {
    my $u="http://db.chgk.info/cgi-bin/db.cgi?$qs";     my $u="http://db.chgk.info/cgi-bin/db.cgi?$qs";
    Redirect ($u);     Redirect ($u);
    exit;     exit;
 }  }
 if (!param('sstr') && param('all')) {  
            my $destination='http://db.chgk.info/all.html';  if ($proxyredirect && $metod=~/proxy/ && $url !~ /localhost/ && $url !~ /bilbo/ && $url !~ /zaba/) {
                 Redirect($destination);     my $u="http://chgk.zaba.ru/cgi-bin/db.cgi?$qs";
                 exit;     Redirect ($u);
      exit;
 }  }
   
   #if (!param('sstr') && param('all')) {
   #          my $destination='http://db.chgk.info/all.html';
   #               Redirect($destination);
   #                exit;
   #}
 my $thislocale;  my $thislocale;
 if ($^O =~ /win/i) {  if ($^O =~ /win/i) {
         $thislocale = "Russian_Russia.20866";          $thislocale = "Russian_Russia.20866";
Line 55  POSIX::setlocale( &POSIX::LC_ALL, $thisl Line 98  POSIX::setlocale( &POSIX::LC_ALL, $thisl
   
 if ((uc 'а') ne 'А') {print STDERR "Koi8-r locale not installed!\n"};  if ((uc 'а') ne 'А') {print STDERR "Koi8-r locale not installed!\n"};
   
 my %fieldname= (0,'Question', 1, 'Answer', 2, 'Comments', 3, 'Authors', 4, 'Sources');  my %fieldname= (0,'Question', 1, 'Answer', 2, 'PassCriteria', 3, 'Comments', 4, 'Authors', 5, 'Sources');
 my %rusfieldname=('Question','Вопрос', 'Answer', 'Ответ',   my %rusfieldname=('Question','Вопрос', 'Answer', 'Ответ', 'PassCriteria','Зачёт',
                   'Comments', 'Комментарии', 'Authors', 'Автор',                     'Comments', 'Комментарии', 'Authors', 'Автор', 
                   'Sources', 'Источник','old','Старый','rus','Новый',                    'Sources', 'Источник','old','Старый','rus','Новый',
                   'chgk', 'ЧГК', 'brain', 'Брейн-ринг','game', 'Своя игра',                     'chgk', 'ЧГК', 'brain', 'Брейн-ринг','game', 'Своя игра', 
Line 78  my %TypeName=('children'=>'Д', 'game'=>' Line 121  my %TypeName=('children'=>'Д', 'game'=>'
               'chgk'=>'Ч', 'brain'=>'Б', 'beskrylka'=>'Л','ehruditka'=>'Э');                'chgk'=>'Ч', 'brain'=>'Б', 'beskrylka'=>'Л','ehruditka'=>'Э');
   
   
   sub countz {
     my ($dbh,$type)=@_;
     
     my $sth=$dbh->prepare("select count(*) from Questions where Type LIKE '%$type%'");
     $sth->execute();
     my ($tmp)=$sth->fetchrow();
     return $tmp;
   }
   
 my $all=param('all');  my $all=param('all');
 $all=0 if lc $all eq 'no';  $all=0 if lc $all eq 'no';
 my ($PWD) = `pwd` if $^O!~/win/i;  my ($PWD) = `pwd` if $^O!~/win/i;
 chomp $PWD if $PWD;  chomp $PWD if $PWD;
 my ($SRCPATH) = "/home/piataev/public_html/dimrub/src";  my ($SRCPATH) = "/home/db-chgk/public_html/dimrub/src";
 my ($ZIP) = "/usr/local/bin/zip";  my ($ZIP) = "/usr/bin/zip";
 my $DUMPFILE = "/tmp/chgkdump";  my $DUMPFILE = "/tmp/chgkdump";
 my ($SENDMAIL) = "/usr/sbin/sendmail";  my ($SENDMAIL) = "/usr/sbin/sendmail";
 my ($TMPDIR) = "/var/tmp";  my ($TMPDIR) = "/var/tmp";
Line 113  sub NewEnough { Line 164  sub NewEnough {
   
 sub Redirect {  sub Redirect {
 my ($destination) = @_;  my ($destination) = @_;
   print header.<<EndOfHTML;
   <head><meta http-equiv="refresh" content="0; URL=$destination"></head>
   EndOfHTML
   ;
   =head
   
 print <<EndOfHTML;  print <<EndOfHTML;
 Content-type: text/html  Content-type: text/html
 Location: $destination  Location: $destination
Line 128  by clicking <A HREF="$destination">here< Line 185  by clicking <A HREF="$destination">here<
 </HTML>  </HTML>
 EndOfHTML  EndOfHTML
 ;  ;
   =cut
 }  }
   
   
Line 154  sub GetTournament { Line 212  sub GetTournament {
 sub fetchquestion {  sub fetchquestion {
         my ($sth,$q,$WithTour)=@_;          my ($sth,$q,$WithTour)=@_;
         if ($WithTour) {          if ($WithTour) {
                 ($$q{'Question'},$$q{'Answer'},$$q{'Comments'},$$q{'Authors'},                  ($$q{'QuestionId'}, $$q{'Question'},$$q{'Answer'},$$q{'PassCriteria'},$$q{'Comments'},$$q{'Authors'},$$q{'Sources'},
                 $$q{'Number'},                   $$q{'Number'}, 
                 $$q{'Title'}, $$q{'TourTitle'}, $$q{'FileName'},$$q{'PlayedAt'},$$q{'TourNumber'}) =                   $$q{'Title'}, $$q{'TourTitle'}, $$q{'FileName'},$$q{'PlayedAt'},$$q{'TourNumber'},$$q{'PlayedAt2'}) = 
                 $sth->fetchrow;                  $sth->fetchrow;
         } else {          } else {
                 ($$q{'Question'},$$q{'Answer'},$$q{'Comments'},$$q{'Authors'},                  ($$q{'QuestionId'}, $$q{'Question'},$$q{'Answer'},$$q{'PassCriteria'},$$q{'Comments'},$$q{'Authors'},$$q{'Sources'},
                 $$q{'Number'})=                   $$q{'Number'})= 
                 $sth->fetchrow;                  $sth->fetchrow;
         }          }
Line 167  sub fetchquestion { Line 225  sub fetchquestion {
   
   
   
   
 sub SelectQuestions {  sub SelectQuestions {
         my ($dbh,$q,$WithTour) = @_;          my ($dbh,$q,$WithTour) = @_;
         my %q=();          my %q=();
         $_ = "QuestionId=$_" foreach @$q;  #       $_ = "QuestionId=$_" foreach @$q;
         my $where=join " OR ",@$q;  #       my $where=join " OR ",@$q;
           my $where=join ',',@$q;
           $where &&= "QuestionId IN (".(join ',',$where).")";
         $where||=1;          $where||=1;
         $where="($where) AND Questions.ParentId=t1.Id AND t1.ParentId=t2.Id"           $where="($where) AND Questions.ParentId=t1.Id AND t1.ParentId=t2.Id" 
                 if $WithTour;                  if $WithTour;
   
         my $query;          my $query;
         if ($WithTour) {          if ($WithTour) {
                 $query="SELECT Questions.Question, Answer, Comments, Authors,                  $query="SELECT QuestionId, Questions.Question, Answer, PassCriteria, Comments, Authors, Sources,
                         Questions.Number                          Questions.Number
                         , t2.Title, t1.Title, t2.FileName,  t2.PlayedAt,t1.Number                          , t2.Title, t1.Title, t2.FileName,  t2.PlayedAt,t1.Number,t2.PlayedAt2
                         from Questions,Tournaments as t1, Tournaments as t2                           from Questions,Tournaments as t1, Tournaments as t2 
                         WHERE $where";                          WHERE $where";
         } else {          } else {
                 $query="SELECT Questions.Question, Answer, Comments, Authors,                  $query="SELECT QuestionId, Questions.Question, Answer, PassCriteria, Comments, Authors, Sources,
                         Questions.Number from Questions                           Questions.Number from Questions 
                         WHERE $where";                          WHERE $where";
         }          }
Line 222  sub tourhref { Line 283  sub tourhref {
    my $res;     my $res;
    if ($usehtml) {     if ($usehtml) {
         $res=$t;          $res=$t;
           $res=~s/\-q$//;
           $res=~s/\-a$//;
         $res.=$a?"-a":"-q" unless $gr;          $res.=$a?"-a":"-q" unless $gr;
         $res.=".html";          $res.=".html";
           $res=~s/(\#\d+)(.*)$/$2$1/;
           my $t=$res;
           $t=~s/\#.*$//;
   #       $res=~s/\.1// unless $gr ||$res=~/\.\d+$/;#-e "$realHTMLDIR$t";
           $t=$res;
           $t=~s/\#.*$//;
   #       $res=~s/\.html/-q\.html/ unless -e "$realHTMLDIR$t";
           $res="$HTMLDIR$res" unless $opt_z;
         return $res;          return $res;
    } else {     } else {
         $res=$url;          $res=$url;
         $res.="?tour=$t";          $res.=$a?"?answers=1&":"?";
         $res.=$a?"?answers=1":"";          $res.="tour=$t";
   
         return $res;          return $res;
    }     }
   
Line 293  sub printform Line 365  sub printform
   my $sstr=param('sstr');    my $sstr=param('sstr');
   my @df=keys %searchin;    my @df=keys %searchin;
   my %checked;    my %checked;
   $checked{lc $_}="" foreach ('Question','Answer','Comments','Authors','Sources','old','rus',    $checked{lc $_}="" foreach ('Question','Answer','PassCriteria','Comments','Authors','Sources','old','rus',
       'chgk','brain','igp','game','ehruditka','beskrylka');        'chgk','brain','igp','game','ehruditka','beskrylka');
   @df=('Question', 'Answer') unless @df;    @df=('Question', 'Answer') unless @df;
   $checked{lc $_}="checked" foreach @df;    $checked{lc $_}="checked" foreach @df;
   my $fields=checkbox_group('searchin',['Question','Answer','Comments','Authors','Sources'], [@df],    my $fields=checkbox_group('searchin',['Question','Answer','PassCriteria','Comments','Authors','Sources'], [@df],
              'false',\%rusfieldname);               'false',\%rusfieldname);
   @df=param('type');    @df=param('type');
   @df=('chgk','brain','igp','game','ehruditka','beskrylka') unless @df;    @df=('chgk','brain','igp','game','ehruditka','beskrylka') unless @df;
Line 313  sub printform Line 385  sub printform
 return     return   
 <<EOT  <<EOT
 <form method="get" enctype="application/x-www-form-urlencoded"  <form method="get" enctype="application/x-www-form-urlencoded"
 action="/znatoki/cgi-bin/db.cgi">  action="/cgi-bin/db.cgi">
 <h2>Поиск в базе вопросов</h2>  <h2>Поиск в базе вопросов</h2>
   
 <input type="text" name="sstr" value="$sstr" size="30" maxlength="50">   <input type="text" name="sstr" value="$sstr" size="30" maxlength="50"> 
Line 323  action="/znatoki/cgi-bin/db.cgi"> Line 395  action="/znatoki/cgi-bin/db.cgi">
 <table border="1" cellpadding=4 cellspacing=0>  <table border="1" cellpadding=4 cellspacing=0>
 <tr>  <tr>
 <th align="left" rowspan=3 width="20%"> Вариант поиска:  <th align="left" rowspan=3 width="20%"> Вариант поиска:
 </td><td rowspan=2 colspan=2>  </td><td rowspan=2 colspan=3>
 <input type="radio" $checked{'old'} name="metod" value="old"> Простой (старый)  <input type="radio" $checked{'old'} name="metod" value="old"> Простой (старый)
 </td><td>  </td><td>
 <input type="checkbox" $checked{'chgk'} name="type" value="chgk">&nbsp;"Что?&nbsp;Где?&nbsp;Когда?"  <input type="checkbox" $checked{'chgk'} name="type" value="chgk">&nbsp;"Что?&nbsp;Где?&nbsp;Когда?"
Line 341  action="/znatoki/cgi-bin/db.cgi"> Line 413  action="/znatoki/cgi-bin/db.cgi">
 <input type="checkbox" $checked{'beskrylka'} name="type" value="beskrylka">&nbsp;"Бескрылка"  <input type="checkbox" $checked{'beskrylka'} name="type" value="beskrylka">&nbsp;"Бескрылка"
 </td>  </td>
 </tr><tr>  </tr><tr>
 <td colspan=5><input type="radio" $checked{'rus'} name="metod" value="rus"> Расширенный (с учетом грамматики, в вопросах всех типов)  <td colspan=6><input type="radio" $checked{'rus'} name="metod" value="rus"> Расширенный (с учетом грамматики, в вопросах всех типов)
 </td>  </td>
 </tr><tr>  </tr><tr>
 <th align="left">Искать:  <th align="left">Искать:
 </td><td colspan=2>  </td><td colspan=3>
 <input type="radio" $checked{'all'} name="all" value="yes">Все слова  <input type="radio" $checked{'all'} name="all" value="yes">Все слова
 </td><td colspan=3>  </td><td colspan=3>
 <input type="radio" $checked{'any'} name="all" value="no">Любое слово  <input type="radio" $checked{'any'} name="all" value="no">Любое слово
Line 357  action="/znatoki/cgi-bin/db.cgi"> Line 429  action="/znatoki/cgi-bin/db.cgi">
 </td><td width="15%">  </td><td width="15%">
 <input type="checkbox" name="searchin" value="Answer" $checked{'answer'}>Ответ<br>   <input type="checkbox" name="searchin" value="Answer" $checked{'answer'}>Ответ<br> 
 </td><td width="15%">  </td><td width="15%">
   <input type="checkbox" name="searchin" value="PassCriteria" $checked{'passcriteria'}>Зачёт<br> 
   </td><td width="15%">
 <input type="checkbox" name="searchin" value="Comments" $checked{'comments'}>Комментарии<br>   <input type="checkbox" name="searchin" value="Comments" $checked{'comments'}>Комментарии<br> 
 </td><td width="15%">  </td><td width="15%">
 <input type="checkbox" name="searchin" value="Authors" $checked{'authors'}>Автор<br>  <input type="checkbox" name="searchin" value="Authors" $checked{'authors'}>Автор<br>
Line 365  action="/znatoki/cgi-bin/db.cgi"> Line 439  action="/znatoki/cgi-bin/db.cgi">
 </td>  </td>
 </tr>  </tr>
 </table>  </table>
   <!--p><i>Если при попытке поиска выдаётся сообщение об ошибке, 
   попробуйте воспользоваться 
   <a href="http://chgk.zaba.ru/search.html">зеркалом базы</a></i-->
 </center>  </center>
   
 EOT  EOT
Line 383  sub proxy Line 460  sub proxy
 sub makeproxysstr {  sub makeproxysstr {
       my ($dbh,$ptext)=@_;        my ($dbh,$ptext)=@_;
       my $text=$$ptext;        my $text=$$ptext;
         POSIX::setlocale( &POSIX::LC_ALL, $thislocale );
       $text=~tr/ёЁ/еЕ/;        $text=~tr/ёЁ/еЕ/;
       $text=~s/(${RLrl})p(${RLrl})/$1p$2/gom;        $text=~s/(${RLrl})p(${RLrl})/$1p$2/gom;
       $text=~s/p(${RLrl})/р$1/gom;        $text=~s/p(${RLrl})/р$1/gom;
Line 391  sub makeproxysstr { Line 469  sub makeproxysstr {
       $text=~s/[^йцукенгшщзхъфывапролджэячсмитьбюЙЦУКЕНГШЩЗХЪФЫВАПРОЛДЖЭЯЧСМИТЬБЮQWERTYUIOPASDFGHJKLZXCVBNM0-9]/ /g;        $text=~s/[^йцукенгшщзхъфывапролджэячсмитьбюЙЦУКЕНГШЩЗХЪФЫВАПРОЛДЖЭЯЧСМИТЬБЮQWERTYUIOPASDFGHJKLZXCVBNM0-9]/ /g;
       $text=uc $text;        $text=uc $text;
       my @list= $text=~m/(?:(?:${RLrl})+)|(?:[A-Za-z0-9]+)/gom;        my @list= $text=~m/(?:(?:${RLrl})+)|(?:[A-Za-z0-9]+)/gom;
   
       my (%c, %good,$sstr);        my (%c, %good,$sstr);
       foreach (@list)        foreach (@list)
       {        {
Line 399  sub makeproxysstr { Line 478  sub makeproxysstr {
       my @words=sort {$c{$a}<=> $c{$b}} @list;        my @words=sort {$c{$a}<=> $c{$b}} @list;
   
 #      $good{$words[$_]}=1 foreach 0..4;  #      $good{$words[$_]}=1 foreach 0..4;
   
       foreach (@words)        foreach (@words)
       {        {
          $good{$_}=1 if $c{$_}<200;           $good{$_}=1 if $c{$_}<200 && length $_>2;
       }        }
   
       $good{$words[$_]}=0 foreach 16..$#words;        $good{$words[$_]}=0 foreach 16..$#words;
Line 429  sub russearch { Line 507  sub russearch {
             my %relevance;              my %relevance;
             my @blob;              my @blob;
             my %count;              my %count;
               my %stop_word;
           POSIX::setlocale( &POSIX::LC_ALL, $thislocale );
 $sstr=~tr/йцукенгшщзхъфывапролджэячсмитьбю/ЙЦУКЕНГШЩЗХЪФЫВАПРОЛДЖЭЯЧСМИТЬБЮ/;  $sstr=~tr/йцукенгшщзхъфывапролджэячсмитьбю/ЙЦУКЕНГШЩЗХЪФЫВАПРОЛДЖЭЯЧСМИТЬБЮ/;
             @qw=@w =split (' ', uc $sstr);  #           @qw=@w =split (' ', uc $sstr);
               my $ts=uc $sstr;
               @qw=@w= $ts=~m/(?:(?:${RLrl})+)|(?:[A-Za-z0-9]+)/gom;
               $query="select nf.word from nf  where number>=50000";
               $sth=$dbh->prepare($query);
               $sth->execute();
               %stop_word=();
               while (@arr = $sth->fetchrow)
                   {
                      $stop_word{$arr[0]}=1;
                   }
                   $sth->finish;
               
   
 #-----------  #-----------
             foreach $i (0..$#w) # заполняем массив @nf начальных форм              foreach $i (0..$#w) # заполняем массив @nf начальных форм
                            # $nf[$i] -- ссылка на массив возможных                             # $nf[$i] -- ссылка на массив возможных
                            # начальных форм словоформы $i                             # начальных форм словоформы $i
             {              {
                   (push @used_stop, uc $w[$i]),next if $stop_word{uc $w[$i]};
                 $qw= $dbh->quote (uc $w[$i]);                  $qw= $dbh->quote (uc $w[$i]);
   
                 $query="  select distinct w2 from nests                  $query="  select distinct w2 from nests
                                 where w1=$qw";                                  where w1=$qw";
                 $sth=$dbh -> prepare($query);                  $sth=$dbh -> prepare($query);
Line 483  $sstr=~tr/йцукенгшщзхъфывапролджэячсмить Line 576  $sstr=~tr/йцукенгшщзхъфывапролджэячсмить
               $_= " word2question.word=$_" foreach @arr;                $_= " word2question.word=$_" foreach @arr;
               $_= " nf.id=".$_. ' ' foreach @arr1;                $_= " nf.id=".$_. ' ' foreach @arr1;
 #              @arr=(0) unless @arr;  #              @arr=(0) unless @arr;
               $query="select questions from word2question where (". (join ' OR ', @arr).") AND length(questions)<80000";                $query="select questions from word2question where (". (join ' OR ', @arr).") ";
   
               $sth=$dbh -> prepare($query);                $sth=$dbh -> prepare($query);
               $sth->execute;                $sth->execute;
Line 545  $sstr=~tr/йцукенгшщзхъфывапролджэячсмить Line 638  $sstr=~tr/йцукенгшщзхъфывапролджэячсмить
 #Ищем пересечение или объединение списков вопросов (значений %tasksof)  #Ищем пересечение или объединение списков вопросов (значений %tasksof)
             foreach $sf (keys %tasksof)              foreach $sf (keys %tasksof)
            {             {
               $count{$_}++ foreach keys %{$tasksof{$sf}};                  foreach (keys %{$tasksof{$sf}})
                   {
                        next if $forbidden{$_};
                        $count{$_}++ 
                   }
   
            }             }
              @tasks= ($all ? (grep {$count{$_}==$kvo} keys %count) :               @tasks= ($all ? (grep {$count{$_}==$kvo} keys %count) :
                              keys %count) ;                               keys %count) ;
Line 560  foreach (keys %wordsof) Line 658  foreach (keys %wordsof)
   
 @tasks=sort {$relevance{$b}<=>$relevance{$a}} @tasks;  @tasks=sort {$relevance{$b}<=>$relevance{$a}} @tasks;
   
   
 ############  ############
   
   
Line 620  sub Search { Line 717  sub Search {
         my (@sar, $i, $sth,$where,$query);          my (@sar, $i, $sth,$where,$query);
         if ($metod eq 'rus')          if ($metod eq 'rus')
         {          {
              my @tasks=russearch($dbh,$sstr,$all,$allnf);               my @tasks;
                @tasks = russearch($dbh,$sstr,$all,$allnf);
                
               
              return @tasks               return @tasks
         }          }
         elsif ($metod eq 'proxy')          elsif ($metod eq 'proxy')
Line 634  sub Search { Line 734  sub Search {
 ###Simple and advanced query processing. Added by R7  ###Simple and advanced query processing. Added by R7
         if ($metod eq 'simple' || $metod eq 'advanced')          if ($metod eq 'simple' || $metod eq 'advanced')
         {          {
           foreach (qw/Question Answer Sources Authors Comments/) {            foreach (qw/Question Answer PassCriteria Sources Authors Comments/) {
                 if (param($_)) {                  if (param($_)) {
                         push @fields, $_;                          push @fields, $_;
                 }                  }
            }             }
   
            @fields=(qw/Question Answer Sources Authors Comments/) unless scalar @fields;             @fields=(qw/Question Answer PassCriteria Sources Authors Comments/) unless scalar @fields;
            my $fields=join ",", @fields;             my $fields=join ",", @fields;
            my $q=new Text::Query($sstr,             my $q=new Text::Query($sstr,
                  -parse => 'Text::Query::'.                   -parse => 'Text::Query::'.
Line 658  sub Search { Line 758  sub Search {
 ######  ######
          {           {
   
 #         foreach (qw/Question Answer Sources Authors Comments/) {  
           foreach (param('searchin')) {            foreach (param('searchin')) {
 #               if (param($_)) {  #               if (param($_)) {
                         push @fields, "IFNULL($_, '')";                          push @fields, "IFNULL($_, '')";
Line 702  sub makewhere { Line 801  sub makewhere {
       $type .= ($_=$TypeName{$_}) foreach @type;        $type .= ($_=$TypeName{$_}) foreach @type;
       my $where=' 0 ';        my $where=' 0 ';
       foreach (@type) {        foreach (@type) {
              $where.= " OR (Type ='$_') OR (Type ='$_Д') ";               $where.= " OR (Type ='$_') OR (Type ='$_Д') OR (Type ='Д$_') ";
       }         } 
       $where.= "OR (Type='ЧБ')" if ($type=~/Ч|Б/);        $where.= "OR (Type='ЧБ')" if ($type=~/Ч|Б/);
       return $where;        return $where;
Line 727  sub PrintList { Line 826  sub PrintList {
    my ($dbh,$Questions,$shablon,$was)=@_;     my ($dbh,$Questions,$shablon,$was)=@_;
         my $Output;          my $Output;
         my $first=param('first') ||1;          my $first=param('first') ||1;
   
         $first=$first-($first-1)%$outputkvo;          $first=$first-($first-1)%$outputkvo;
         my $fkvo=param('fkvo')||($#$Questions+1);          my $fkvo=param('fkvo')||($#$Questions+1);
         my $last=$first+$outputkvo-1;          my $last=$first+$outputkvo-1;
Line 804  sub PrintList { Line 902  sub PrintList {
         my @q=@$Questions[$first-1..$last-1];          my @q=@$Questions[$first-1..$last-1];
         my %q=();          my %q=();
         my $sth=SelectQuestions($dbh,\@q,1);          my $sth=SelectQuestions($dbh,\@q,1);
           my $qq;
           my @Q;
           for (0..$#q) {
                   %{$Q[$_]}=();
                   fetchquestion($sth,$Q[$_],1);
                   $q{$Q[$_]{'QuestionId'}}=$Q[$_];
           }
   
         for (my $i = $first; $i <= $last; $i++) {          for (my $i = $first; $i <= $last; $i++) {
                 fetchquestion($sth,\%q,1);                  my $q=$q{$$Questions[$i-1]};
                 my $output;                  my $output;
                 $output = &PrintQuestion($dbh, \%q, 1, 0, 1,0,1  );                  $output = &PrintQuestion($dbh, $q, 1, 0, 1,$text,1  );
                 if (param('metod') && (param('metod') eq 'rus' || param('metod') eq 'proxy'))  #                if (param('metod') && (param('metod') eq 'rus' || param('metod') eq 'proxy'))
                 {                  {
                      $output=~s/\b($shablon)\b/\<strong\>$1\<\/strong\>/gi;                       $output=~s/\b($shablon)\b/\<strong\>$1\<\/strong\>/gi;
                 } else {  
                      $output=~s/($shablon)/\<strong\>$1\<\/strong\>/gi;                       $output=~s/($shablon)/\<strong\>$1\<\/strong\>/gi;
                        $output=~s/(href="[^"]*?)(?:<.*?>)+([^"]*?)(?:<\/.*?>)+([^"]*?")/!1 $1$2$3 2!/g;#!!!!
                 }                  }
   
                 $Output.= $output;                  $Output.= $output;
         }          }
         $sth->finish;          $sth->finish;
Line 855  sub PrintSearch { Line 962  sub PrintSearch {
                         }                          }
                 while (--$ss && (!$dbh->do ("insert into lastqueries (id,sstr,questions,allnf)                   while (--$ss && (!$dbh->do ("insert into lastqueries (id,sstr,questions,allnf) 
                          values ($was, $qsstr,$tmp,$nf)")));                           values ($was, $qsstr,$tmp,$nf)")));
                 $Output.= "Something is wrong...".br unless $ss;                  $Output.= "Something is wrong...".br."\n" unless $ss;
               }                }
         }          }
   
   
   
         $Output.= p. "Время поиска: " . (time-$t) ." сек.".p;          $Output.= p. "Время поиска: " . (time-$t) ." сек.".p;
           $_="\"$_\"" foreach @used_stop;
           $Output.= p. (join ', ',@used_stop) ." ignored".p if @used_stop;
         my ($output, $i, $suffix, $hits) = ('', 0, '', $#Questions + 1);          my ($output, $i, $suffix, $hits) = ('', 0, '', $#Questions + 1);
   
         my $shablon;          my $shablon;
Line 924  sub PrintRandom { Line 1033  sub PrintRandom {
    my %q;     my %q;
    my $answer=$razd?0:1;     my $answer=$razd?0:1;
    my @answers;     my @answers;
   #my $t=time;
    my (@Questions) = &Get12Random($dbh, $type, $num);     my (@Questions) = &Get12Random($dbh, $type, $num);
         my ($output, $i) = ('', 0);  
   
           my ($output, $i) = ('', 0);
   #$output.="time=".(time-$t).p;
         if ($text) {          if ($text) {
                 $output .= "    $num случайных вопросов.\n\n";                  $output .= "    $num случайных вопросов.\n\n";
         } else {          } else {
Line 972  sub PrintTournament { Line 1083  sub PrintTournament {
   
         %Tournament = &GetTournament($dbh, $Id) if ($Id);          %Tournament = &GetTournament($dbh, $Id) if ($Id);
   
         my ($URL) = $Tournament{'URL'};          my ($URL) = $Tournament{'URL'}||'';
         $URL=~s/http:\/znatoki\/boris\/reports\//$newsurl/ if $url=~/kulichki/;          $URL=~s/http:\/znatoki\/boris\/reports\//$newsurl/ if $url=~/kulichki/ || $url=~/db.chgk.info/;
         $URL=~s/\/znatoki\/boris\/reports\//$newsurl/ if url=~/kulichki/;;          $URL=~s/\/znatoki\/boris\/reports\//$newsurl/ if url=~/kulichki/ || $url=~/db.chgk.info/;
         my ($Info) = $Tournament{'Info'};          my ($Info) = $Tournament{'Info'};
         my ($Copyright) = $Tournament{'Copyright'};          my ($Copyright) = $Tournament{'Copyright'};
         my $fname=$Tournament{'FileName'};          my $fname=$Tournament{'FileName'};
Line 986  sub PrintTournament { Line 1097  sub PrintTournament {
                         /Г/ && do {                          /Г/ && do {
                                 $output .= h2({align=>"center"},                                  $output .= h2({align=>"center"},
                                               "Группа: $Tournament{'Title'} ",                                                "Группа: $Tournament{'Title'} ",
                                               $Tournament{'PlayedAt'}||'') . p . "\n";                                                $Tournament{'PlayedAt'}||'') . 
                                                 ($Tournament{'PlayedAt2'}?'&nbsp;&ndash; '.
                                                   $Tournament{'PlayedAt2'}:'') . 
                                                 
                                                 p . "\n";
                                 last;                                  last;
                         };                          };
                         /Ч/ && do {                          /Ч/ && do {
Line 998  sub PrintTournament { Line 1113  sub PrintTournament {
                                     $title .= " $Tournament{'PlayedAt'}";                                      $title .= " $Tournament{'PlayedAt'}";
                                 }                                  }
   
                                   if ($Tournament{'PlayedAt2'}) {
                                       $title .= '&nbsp;&ndash; '.$Tournament{'PlayedAt2'};
                                   }
   
                                 $output .= h2({align=>"center"},                                  $output .= h2({align=>"center"},
                                         "$title") . p . "\n";                                          "$title") . p . "\n";
                                $output.=&PrintEditor(\%Tournament);                                 $output.=&PrintEditor(\%Tournament);
Line 1008  sub PrintTournament { Line 1127  sub PrintTournament {
                         };                          };
                 }                  }
         } else {          } else {
                 my ($qnum) = GetQNum($dbh);                  my ($qnum) = GetQNum($dbh,0);
                 $output .= h2("Банк Вопросов: $qnum вопрос".&Suffix($qnum))                   my ($qnum1) = GetQNum($dbh,1);
                           . p . "\n";                  $output .= h2("База вопросов").
                    h3("$qnum запис".&Suffix2($qnum).
                    " (уникальных $qnum1)");
   
   #                h4("<table>".
   #                Tr(td("Из них:"), td("Вопросов ЧГК: ".countz($dbh,'Ч'))).               
   #                Tr(td("&nbsp;"), td("Вопросов для брейна: ".countz($dbh,'Б'))).                 
   #                Tr(td("&nbsp;"), td("Вопросов для ЧГК и брейна: ".countz($dbh,'ЧБ'))).          
   #                Tr(td("&nbsp;"), td("Интернет-вопросов: ".countz($dbh,'И'))).           
   #                Tr(td("&nbsp;"), td("Бескрылок: ".countz($dbh,'Л'))).
   #                Tr(td("&nbsp;"),td("Заданий для Своей Игры: ".countz($dbh,'Я'))).
   #                Tr(td("&nbsp;"),td("Эрудиток: ".countz($dbh,'Э'))))."</table>"
         }          }
   
         for ($i = 0; $i <= $#Tours; $i++) {          for ($i = 0; $i <= $#Tours; $i++) {
Line 1053  sub PrintTournament { Line 1183  sub PrintTournament {
                 if ($SingleTour or ($Tournament{'Type'} =~ /Т/)) {                  if ($SingleTour or ($Tournament{'Type'} =~ /Т/)) {
                         $list .= dd(img({src=>$imgsrc, alt=>$alt})                          $list .= dd(img({src=>$imgsrc, alt=>$alt})
                                 . " " . $Tournament{'Title'} . " " .                                  . " " . $Tournament{'Title'} . " " .
                                     ($Tournament{'PlayedAt'}||"") . $qnum) .                                      ($Tournament{'PlayedAt'}||"") . 
                                       ($Tournament{'PlayedAt2'}?'&nbsp;&ndash; '.$Tournament{'PlayedAt2'}:"") .
                                       $qnum) .
                                 dl(                                  dl(
                                         dd("["                                          dd("["
                                                 . a({href=>tourhref($textid,0)},                                                  . a({href=>tourhref($textid,0)},
Line 1064  sub PrintTournament { Line 1196  sub PrintTournament {
                 } else {                  } else {
                         $list .= dd(a({href=>                          $list .= dd(a({href=>
                                  $url . "?tour=$textid&comp=1"},                                   $url . "?tour=$textid&comp=1"},
                                 img({src=>'/icons/compressed.gif', alt=>'[ZIP]', border=>1})).                                   img({src=>'/icons/compressed.gif', alt=>'[ZIP]', border=>1}))                           .  
                                 " " .                                   " " . 
                                 img({src=>$imgsrc, alt=>$alt})                                  img({src=>$imgsrc, alt=>$alt})
                                 . " " . a({href=>tourhref($textid,0,1)},                                  . " " . a({href=>tourhref($textid,0,1)},
                                 $Tournament{'Title'}. " ".                                  $Tournament{'Title'}. " ".
                                           ($Tournament{'PlayedAt'}||'')) . $qnum);                                             ($Tournament{'PlayedAt'}||'')) .
                                             ($Tournament{'PlayedAt2'}?'&nbsp;&ndash '. $Tournament{'PlayedAt2'}:''). $qnum); 
                 }                  }
         }          }
         $output .= dl($list);          $output .= dl($list);
Line 1080  sub PrintTournament { Line 1213  sub PrintTournament {
                 p("Дополнительная информация об этом турнире - по адресу " .                  p("Дополнительная информация об этом турнире - по адресу " .
                         a({-'href'=>$URL}, $URL));                          a({-'href'=>$URL}, $URL));
         }          }
   
         if ($Copyright) {          if ($Copyright) {
                 $output .= p("Копирайт: " .   $Copyright);                  $output .= p("Копирайт: " .   $Copyright);
         }          }
Line 1090  sub PrintTournament { Line 1222  sub PrintTournament {
         if ($Info) {          if ($Info) {
                 $output .= p($Info);                  $output .= p($Info);
         }          }
   
           $output.=p("<a href='/dbxml.php?tour=".param('tour')."'>XML</a>");
           
           
         return $output;          return $output;
 }  }
   
Line 1101  sub Suffix { Line 1237  sub Suffix {
         return $suffix;          return $suffix;
 }  }
   
   
   sub Suffix1 {
           my ($qnum) = @_;
           my ($suffix) = 'я' if $qnum =~ /[234]$/;
          $suffix = 'е' if $qnum =~ /1$/;
          $suffix = 'й' if $qnum =~ /[567890]$/ || $qnum =~ /1.$/;
           return $suffix;
   }
   
   sub Suffix2 {
           my ($qnum) = @_;
           my ($suffix) = 'и' if $qnum =~ /[234]$/;
          $suffix = 'ь' if $qnum =~ /1$/;
          $suffix = 'ей' if $qnum =~ /[567890]$/ || $qnum =~ /1.$/;
           return $suffix;
   }
   
 sub IsTour {  sub IsTour {
         my ($dbh, $Id,$n) = @_;          my ($dbh, $Id,$n) = @_;
   
Line 1142  sub PrintTour { Line 1295  sub PrintTour {
   
         $output .= h2({align=>"center"}, $Tournament{"Title"},          $output .= h2({align=>"center"}, $Tournament{"Title"},
                       $Tournament{'PlayedAt'}||'',                        $Tournament{'PlayedAt'}||'',
                       "<br>", $Tour{"Title"} .                        $Tournament{'PlayedAt2'}?'&nbsp;&ndash; '.$Tournament{'PlayedAt2'}:'',
                         "<br>\n", $Tour{"Title"} .
                 " ($qnum вопрос$suffix)\n") . p;                  " ($qnum вопрос$suffix)\n") . p;
         $output .=&PrintEditor(\%Tour);          $output .=&PrintEditor(\%Tour);
   
Line 1150  sub PrintTour { Line 1304  sub PrintTour {
         my $sth=SelectQuestions($dbh,\@Questions,0);          my $sth=SelectQuestions($dbh,\@Questions,0);
         for ($q = 0; $q <= $#Questions; $q++) {          for ($q = 0; $q <= $#Questions; $q++) {
                 fetchquestion($sth,\%q,0);                  fetchquestion($sth,\%q,0);
                 $output .= &PrintQuestion($dbh, \%q, $answer, 0,0,0,1);                  $output .= &PrintQuestion($dbh, \%q, $answer, 0,0,$text,1);
         }          }
         $sth->finish;          $sth->finish;
         $output .= hr({-'align'=>'center', -'width'=>'80%'});          $output .= hr({-'align'=>'center', -'width'=>'80%'});
   
         if ($Tournament{'URL'}) {          if ($Tournament{'URL'}) {
                 $output .=              $URL = $Tournament{'URL'};
                 p("Дополнительная информация об этом турнире - по адресу " .              $URL=~s/http:\/znatoki\/boris\/reports\//$newsurl/ if $url=~/kulichki/ || $url=~/db.chgk.info/;
                         a({-'href'=>$Tournament{'URL'}}, $Tournament{'URL'}));              $URL=~s/\/znatoki\/boris\/reports\//$newsurl/ if url=~/kulichki/ || $url=~/db.chgk.info/;
   
               $output .=
               p("Дополнительная информация об этом турнире - по адресу " .
                           a({-'href'=>$URL}, $URL));
         }          }
   
         if ($Tournament{'Copyright'}) {          if ($Tournament{'Copyright'}) {
                 $output .= p("Копирайт: " .   $Tournament{'Copyright'});                  $output .= p("Копирайт: " .   $Tournament{'Copyright'});
         }          }
   
         if ($Tournament{'Info'}) {          if ($Tournament{'Info'}  ) {
                 $output .= p($Tournament{'Info'});                  $output .= p($Tournament{'Info'});
         }          }
   
           if ($Tour{'Info'} && ($Tournament{'Info'} ne $Tour{'Info'})) {
                   $output .= "!!".p($Tour{'Info'});
           }
   
           $output.=p("<a href='/dbxml.php?tour=".param('tour')."'>XML</a>");
   
         my $n=$Tour{'Number'};          my $n=$Tour{'Number'};
         if ($answer == 0) {          if ($answer == 0) {
                   my $nn=".$n";
                   $nn="" if ($n==1 && !&IsTour($dbh, $Tour{'ParentId'}, $n + 1));
                   
                 $bottom .=                  $bottom .=
                         "[" . a({href=>tourhref($fname,1)},                           "[" . a({href=>tourhref("$fname$nn",1)}, 
                          "ответы") .  "] " . br;                           "ответы") .  "] " . br."\n";
         }          }
         if ($n>1) {          if ($n>1) {
                 $bottom .=                  $bottom .=
Line 1181  sub PrintTour { Line 1348  sub PrintTour {
                         "предыдущий тур") . "] ";                          "предыдущий тур") . "] ";
                 $bottom .=                  $bottom .=
                         "[" . a({href=>tourhref("$fname.".($n-1),1)},                          "[" . a({href=>tourhref("$fname.".($n-1),1)},
                         "предыдущий тур с ответами") . "] " . br;                          "предыдущий тур с ответами") . "] " . br."\n";
         }          }
         if (&IsTour($dbh, $Tour{'ParentId'}, $n + 1)) {          if (&IsTour($dbh, $Tour{'ParentId'}, $n + 1)) {
                 $bottom .=                  $bottom .=
Line 1198  sub PrintTour { Line 1365  sub PrintTour {
         return $output;          return $output;
 }  }
   
   
   sub escapeUrl {
           my $uri = shift;
           $uri=~s/<.*?>//g;
           $uri =~ s/([Ю-Ъю-ъ]+)/URI::Escape::uri_escape_utf8(decode("koi8-r",$1))/eg;
           return $uri;    
   }
   
 sub PrintField {  sub PrintField {
         my ($header, $value, $text) = @_;          my ($header, $value, $text) = @_;
         if ($text) {          if ($text) {
             $value =~ s/<[\/\w]*?>//sg;              $value =~ s/<[\/\w]*?>//sg;
         } else {          } else {
             $value =~ s/^\s+/<br>&nbsp;&nbsp;&nbsp;&nbsp;/mg;              if ($header=~/Комментар/)
               {
                   $value=~s/^\s*$_[\.:]/p."\n".strong("$_").":\n"/me foreach @softfields;
               }
   
               $value =~ s/^\s+/<br>\n&nbsp;&nbsp;&nbsp;&nbsp;/mg;
               $value =~ s/(\s+)-+(\s+)/$1&#0150;$2/mg;
               $value =~ s/\s+\&#0150/&nbsp;\&#0150/mg 
                           if $value !~ /^\|/;
             $value =~ s/^\|([^\n]*)/<pre>$1<\/pre>/mg;              $value =~ s/^\|([^\n]*)/<pre>$1<\/pre>/mg;
             $value =~ s/\s+-+\s+/&nbsp;&#0150; /mg;  
             $value =~ s/(http:\/\/\S+[^\s\)\(\,\.])/<a href="$1">$1<\/a>/g if $header !~ /^Авто/;              $value =~ s/(http:\/\/\S+[^\s\)\(\,\.\]])/a({href=>escapeUrl($1)},$1)/egm if $header !~ /^Авто/;#!!!
   
               $value =~ s/\.\.\.\]/!!!ZAKR!!!/g;
               $value =~ s/пропущено\]/!!!PROP!!!/g;
               $value =~ s/пропущены\]/!!!PROP2!!!/g;
               $value =~ s/\[Раздаточный материал:(.*?)\]\s*\n/<div class='razdatka'><div class='razdatka_header'>Раздаточный материал<\/div> $1<\/div>\n$2/sm;
               $value =~ s/<раздатка>(.*?)<\/раздатка>/<div class='razdatka'><div class='razdatka_header'>Раздаточный материал<\/div> $1<\/div>\n/sm;
               $value =~ s/!!!ZAKR!!!/\.\.\.\]/g;
               $value =~ s/!!!PROP!!!/пропущено\]/g;
               $value =~ s/!!!PROP2!!!/пропущены\]/g;
   
   
   #           $value =~ s/(http:\/\/\S+[^\s\)\(\,\.])/make/eg if $header !~ /^Авто/;#!!!
   #           $value =~ s/(http:\/\/\S+[^\s\)\(\,\.])/<a href="$1">$1<\/a>/g if $header !~ /^Авто/;
 #           $value =~ s/(http:\/\/(?:\w+.)+[\w\\\~]+(\?[^\s.]+)?)/<a href="$1">$1<\/a>/g if $header !~ /^Авто/;  #           $value =~ s/(http:\/\/(?:\w+.)+[\w\\\~]+(\?[^\s.]+)?)/<a href="$1">$1<\/a>/g if $header !~ /^Авто/;
 #           $value =~ s/(\s)"/$1&#147;/mg;  #           $value =~ s/(\s)"/$1&#147;/mg;
 #           $value =~ s/^"/&#147;/mg;  #           $value =~ s/^"/&#147;/mg;
 #           $value =~ s/"/&#148;/mg;  #           $value =~ s/"/&#148;/mg;
         }          }
   
           if ($value=~/^\s*(<p.*?>)?\s*<strong/) {
                   return $text ? "$value\n\n" :
                           $value . p . "\n";
           }
         return $text ? "$header:\n$value\n\n" :          return $text ? "$header:\n$value\n\n" :
                 strong("$header: ") . $value . p . "\n";                  strong("$header: ") . "\n".$value . p . "\n";
 }  }
   
 # Gets a DB handler (ofcourse) and a question Id. Prints  # Gets a DB handler (ofcourse) and a question Id. Prints
Line 1223  sub PrintField { Line 1422  sub PrintField {
 sub PrintQuestion {  sub PrintQuestion {
         my ($dbh, $Id, $answer, $qnum, $title, $text,$h) = @_;          my ($dbh, $Id, $answer, $qnum, $title, $text,$h) = @_;
         my ($output, $titles) = ('', '');          my ($output, $titles) = ('', '');
           my $fname;
         my (%Question);          my (%Question);
         if ($h) {          if ($h) {
           %Question=%$Id;            %Question=%$Id;
Line 1234  sub PrintQuestion { Line 1434  sub PrintQuestion {
                         $Question{'FileName'}=$Tournament{'FileName'};                          $Question{'FileName'}=$Tournament{'FileName'};
                         $Question{'Title'}=$Tournament{'Title'};                          $Question{'Title'}=$Tournament{'Title'};
                         $Question{'PlayedAt'}=$Tournament{'PlayedAt'};                          $Question{'PlayedAt'}=$Tournament{'PlayedAt'};
                           $Question{'PlayedAt2'}=$Tournament{'PlayedAt2'};                        
                         $Question{'TourNumber'}=$Tour{'Number'};                          $Question{'TourNumber'}=$Tour{'Number'};
                         $Question{'TourTitle'}=$Tour{'Title'};                          $Question{'TourTitle'}=$Tour{'Title'};
                 }                  }
Line 1244  sub PrintQuestion { Line 1445  sub PrintQuestion {
         if (!$text) {          if (!$text) {
                 $output .= hr({width=>"50%"}) if $answer>=0;                  $output .= hr({width=>"50%"}) if $answer>=0;
                 if ($title) {                  if ($title) {
                         my $fname=$Question{'FileName'};                          $fname=$Question{'FileName'};
                         $fname=~s/\.txt//;                          $fname=~s/\.txt//;
                         $titles .=                          $titles .=
                                 dd(img({src=>"/icons/folder.open.gif"}) . " " .                                  dd(img({src=>"/icons/folder.open.gif"}) . " " .
                                          a({href=>tourhref($fname,0,1)},                                            a({href=>tourhref($fname,0,1)}, 
                                $Question{'Title'}, $Question{'PlayedAt'}||''));                                 $Question{'Title'}, $Question{'PlayedAt'}||'',
                                  $Question{'PlayedAt2'}?'&nbsp;&ndash; '.$Question{'PlayedAt2'}:''));
                         $titles .=                          $titles .=
                                 dl(dd(img({src=>"/icons/folder.open.gif"}) . " " .                                  dl(dd(img({src=>"/icons/folder.open.gif"}) . " " .
                                         a({href=>tourhref("$fname.$Question{'TourNumber'}#$qnum",1)},                                           a({href=>tourhref("$fname.$Question{'TourNumber'}#$qnum",1)}, 
Line 1267  sub PrintQuestion { Line 1469  sub PrintQuestion {
         if ($answer==1|| $answer==-1) {          if ($answer==1|| $answer==-1) {
                 $output .=                  $output .=
                         &PrintField("Ответ", $Question{'Answer'}, $text);                          &PrintField("Ответ", $Question{'Answer'}, $text);
                   if ($Question{'PassCriteria'} ) {
                     $output .=
                           &PrintField("Зачёт", $Question{'PassCriteria'}, $text);
                   }
   
                 if ($Question{'Authors'} ) {                  if ($Question{'Authors'} ) {
                       my $q=$Question{'Authors'};                        my $q=$Question{'Authors'};
Line 1335  EOTT Line 1541  EOTT
                 if ($Question{'Authors'}) {                  if ($Question{'Authors'}) {
                         $output .= &PrintField("Автор(ы)", $Question{'Authors'}, $text);                          $output .= &PrintField("Автор(ы)", $Question{'Authors'}, $text);
                 }                  }
                   if ($Question{'PassCriteria'}) {
                           $output .= &PrintField("Зачёт", $Question{'PassCriteria'}, $text);
                   }
   
                 if ($Question{'Sources'}) {                  if ($Question{'Sources'}) {
                         $output .= &PrintField("Источник(и)", $Question{'Sources'}, $text);                          $output .= &PrintField("Источник(и)", $Question{'Sources'}, $text);
                 }                  }
Line 1348  EOTT Line 1558  EOTT
 $output.="</span>"  $output.="</span>"
   
         }          }
         $output=~s/\(pic: ([^\)]*)\)/<p><img src="\/znatoki\/images\/db\/$1"><p>/g unless $text;          $output=~s/\(pic: ([^\)]*)\)/<p><img src="\/znatoki\/images\/db\/$1"><\/p>/g unless $text;
         my $qid=param('tour') ? (param('tour').".$Question{'Number'}" ): '';          $output=~s/\(aud: ([^\)]*)\)/<embed type="application\/x-shockwave-flash" src="http:\/\/www.google.com\/reader\/ui\/3247397568-audio-player.swf?audioUrl=\/znatoki\/sounds\/db\/$1"  allowscriptaccess="never" width="400" height="27" quality="best" bgcolor="#ff0000" wmode="window" flashvars="playerMode=embedded" \/>/g unless $text;
   
           $output=~s/⌡/\&iuml;/g;
           $output=~s/⌠/\&Iuml;/g;
   
         $output.=br.a({href=> $url."?metod=proxy&          $paramtour||=param("tour");
           $fname=$fname.".$Question{'TourNumber'}" if $fname && $Question{'TourNumber'};
   $fname||=param('tour');
           my $qid=$fname ? ($fname.".$Question{'Number'}" ): '';
   
           $output.=br."\n".a({href=> "/search/"."?metod=proxy&
 qid=$qid"}, 'Близкие вопросы').p  qid=$qid"}, 'Близкие вопросы').p
              if $answer>0 && !$text && $qid;               if $answer>0 && !$text && $qid && $showNearQuestions;
         return $output;          return $output;
 }  }
   
 # Returns the total number of questions currently in the DB.  # Returns the total number of questions currently in the DB.
 sub GetQNum {  sub GetQNum {
         my ($dbh) = @_;          my ($dbh,$x) = @_;
         my ($sth) = $dbh->prepare("SELECT COUNT(*) FROM Questions");          my ($sth) = $dbh->prepare("SELECT COUNT(*) FROM Questions");
         $sth->execute;          $sth->execute;
         my $tmp=($sth->fetchrow)[0];          my $tmp=($sth->fetchrow)[0];
         $sth->finish;          $sth->finish;
         return $tmp;          ($sth)=  $dbh -> prepare("select distinct count(first) FROM equalto");
                      $sth -> execute;
           my ($c)=$sth->fetchrow;
   
   #                  $i++  while ( my  ($first, $second)=$sth -> fetchrow)
   #                  {
   #                       $forbidden{$first}=1;
   #                  }
                     $sth->finish;
   
           return $tmp-($x?$c:0);
 }  }
 sub GetMaxQId {  sub GetMaxQId {
         my ($dbh) = @_;          my ($dbh) = @_;
Line 1385  sub Get12Random { Line 1613  sub Get12Random {
         srand;          srand;
         my $where=0;          my $where=0;
         my $r=int (rand(10000));          my $r=int (rand(10000));
           my $w1=$r<5000? "QuestionId<50000 ":"QuestionId>=50000";
           $w1=1 if $url=~/zaba/;
           $w1=1 if $type!~/Ч/;
         foreach (split '', $type)          foreach (split '', $type)
         {          {
            $where.= " OR (Type ='$_') OR (Type ='$_Д') ";             $where.= " OR (Type ='$_') OR (Type ='$_Д') ";
Line 1395  sub Get12Random { Line 1625  sub Get12Random {
 #   $q="select QuestionId, QuestionId/$r-floor(QuestionId/$r) as val   #   $q="select QuestionId, QuestionId/$r-floor(QuestionId/$r) as val 
 #       from Questions where $where order by val limit $num";  #       from Questions where $where order by val limit $num";
 # Когда на куличках появится mysql >=3.23 надо заменить на order by rand();  # Когда на куличках появится mysql >=3.23 надо заменить на order by rand();
    $q="select QuestionId from Questions where $where order by rand() limit $num";     $q="select QuestionId from Questions where ($w1) AND ($where) order by rand() limit $num";
   
   
    $sth=$dbh->prepare($q);     $sth=$dbh->prepare($q);
Line 1414  sub Get12Random { Line 1644  sub Get12Random {
   
 sub Include_virtual {  sub Include_virtual {
         my ($fn, $output) = (@_, '');          my ($fn, $output) = (@_, '');
           return "\n<!--#include virtual=\"$fn\"-->\n" if ($opt_z);
         open F , $fn          open F , $fn
                 or return ""; #die "Can't open the file $fn: $!\n";                  or return ""; #die "Can't open the file $fn: $!\n";
   
         while (<F>) {          while (<F>) {
                 if (/<!--#include/o) {                  if (/<!--#include/o) {
                         s/<!--#include virtual="\/(.*)" -->/&Include_virtual($1)/e;                          s/<!--#include virtual="\/?([^\/].*)" -->/&Include_virtual($1)/e;
                 }                  }
                 if (/<!--#exec/o) {                  if (/<!--#exec/o) {
                         s/<!--#exec.*cmd\s*=\s*"([^"]*)".*-->/`$1`/e;                          s/<!--#exec.*cmd\s*=\s*"([^"]*)".*-->/`$1`/e;
Line 1452  sub PrintAll { Line 1682  sub PrintAll {
   
         my (%Tournament) = &GetTournament($dbh, $Id);          my (%Tournament) = &GetTournament($dbh, $Id);
         my (@Tours) = &GetTours($dbh, $Id);          my (@Tours) = &GetTours($dbh, $Id);
           my $SingleTour = $#Tours == 0;
   
         my ($New) = ($Id and $Tournament{'Type'} eq 'Ч' and          my ($New) = ($Id and $Tournament{'Type'} eq 'Ч' and
                 &NewEnough($Tournament{"CreatedAt"})) ?                  &NewEnough($Tournament{"CreatedAt"})) ?
                 img({src=>"/znatoki/dimrub/db/new-sml.gif", alt=>"NEW!"}) : "";                  img({src=>"/znatoki/dimrub/db/new-sml.gif", alt=>"NEW!"}) : "";
Line 1473  sub PrintAll { Line 1705  sub PrintAll {
   
   
                 $output .= dd(img({src=>"/icons/folder.gif", alt=>"[*]"}) .                  $output .= dd(img({src=>"/icons/folder.gif", alt=>"[*]"}) .
       " " . a({href=>tourhref($textid,0,1)},        " " . a({href=>tourhref($textid,0,!$SingleTour)},
       $Tournament{'Title'}) ." " . ($Tournament{'PlayedAt'}||'') . " $New");        $Tournament{'Title'}) ." " . ($Tournament{'PlayedAt'}||'') . 
         ($Tournament{'PlayedAt2'}?'&nbsp;&ndash; '.$Tournament{'PlayedAt2'}:'') . 
         " $New");
         }          }
         if ($Id == 0 or $Tournament{'Type'} =~ /Г/ or $Tournament{'Type'} eq '') {          if ($Id == 0 or $Tournament{'Type'} =~ /Г/ or $Tournament{'Type'} eq '') {
                 for ($i = 0; $i <= $#Tours; $i++) {                  for ($i = 0; $i <= $#Tours; $i++) {
Line 1506  sub PrintDates { Line 1740  sub PrintDates {
                 next                  next
                         if (!$array[0]);                          if (!$array[0]);
                 %Tournament = &GetTournament($dbh, $array[0]);                  %Tournament = &GetTournament($dbh, $array[0]);
                    my $textid;
                    if ($textid=$Tournament{'FileName'})
                    {
                      $textid=~s/\.txt//;
                    }
                    elsif ($textid=$Tournament{'Number'})
                    {
                         $fname=~s/\.txt//;
                         $textid="$fname.$textid";
                    }
                    else {$textid=$Tournament{'Id'}};
       $list .= dd(img({src=>"/icons/folder.gif", alt=>"[*]"}) .        $list .= dd(img({src=>"/icons/folder.gif", alt=>"[*]"}) .
       " " . a({href=>tourhref($Tournament{'FileName'},0,1)},        " " . a({href=>tourhref($textid,0,1)},
       $Tournament{'Title'}, $Tournament{'PlayedAt'}||''));        $Tournament{'Title'}, $Tournament{'PlayedAt'}||'', 
         $Tournament{'PlayedAt2'}?'&nbsp;&ndash; '.$Tournament{'PlayedAt2'}:''));
         }          }
         $sth->finish;          $sth->finish;
         $output .= dl($list);          $output .= dl($list);
Line 1551  sub PrintQOfAuthor Line 1797  sub PrintQOfAuthor
                 $suffix = 'я';                  $suffix = 'я';
         }          }
         $Output.= printform;          $Output.= printform;
         $Output.= p({align=>"center"}, "Автор ".strong("$name $surname. ")          $Output.= p({align=>"center"}, "Автор ".strong("$name $surname ")
         . " : $hits попадани$suffix.");          . " : $hits попадани$suffix.");
   
   
Line 1625  sub WriteFile { Line 1871  sub WriteFile {
   $fname=~s/.*\/(\w+)/$1/;    $fname=~s/.*\/(\w+)/$1/;
   
   my $query= "SELECT Id, Title, Copyright, Info, URL,     my $query= "SELECT Id, Title, Copyright, Info, URL, 
                       Editors, EnteredBy, PlayedAt, CreatedAt                         Editors, EnteredBy, PlayedAt, CreatedAt, PlayedAt2
                      from Tournaments where FileName=".$dbh->quote("$fname.txt");                       from Tournaments where FileName=
                        '$fname' OR FileName=".$dbh->quote("$fname.txt");
   my $sth=$dbh->prepare($query);    my $sth=$dbh->prepare($query);
   my (%Question,%editor,%qnumber,%copyright,%author,%vid,%tourtitle);    my (%Question,%editor,%qnumber,%copyright,%author,%vid,%tourtitle);
   $sth->execute;    $sth->execute;
   my ($Id, $Title, $Copyright, $Info, $URL,     my ($Id, $Title, $Copyright, $Info, $URL, 
    $Editors, $EnteredBy, $PlayedAt, $CreatedAt)=     $Editors, $EnteredBy, $PlayedAt, $CreatedAt, $PlayedAt2)=
       $sth->fetchrow;        $sth->fetchrow;
   return -1 unless $Id;    return -1 unless $Id;
   open (OUT, ">$TMPDIR/$fname.txt") || print STDERR "Error in $fname.txt\n";    open (OUT, ">$TMPDIR/$fname.txt") || print STDERR "Error in $fname.txt\n";
Line 1640  sub WriteFile { Line 1887  sub WriteFile {
   my ($year,$month,$day)=split /-/, $date;    my ($year,$month,$day)=split /-/, $date;
 #  $month=0,$date=0 if $year && $month==1 && $day==1;  #  $month=0,$date=0 if $year && $month==1 && $day==1;
   my $pdate=sprintf("%02d-%3s-%4d",$day,$months[$month],$year);    my $pdate=sprintf("%02d-%3s-%4d",$day,$months[$month],$year);
     if ($PlayedAt2) {
       my ($year,$month,$day)=split /-/, $date;
       $pdate .= sprintf(" - %02d-%3s-%4d",$day,$months[$month],$year);    
     }
   
   print OUT "Дата:\n$pdate\n\n" if $date;    print OUT "Дата:\n$pdate\n\n" if $date;
   
Line 1749  sub WriteFile { Line 2000  sub WriteFile {
      {       {
         print OUT "Вопрос $q:\n".$Question{$tour}[$q]{'Question'}."\n\n";          print OUT "Вопрос $q:\n".$Question{$tour}[$q]{'Question'}."\n\n";
         print OUT  "Ответ:\n".$Question{$tour}[$q]{'Answer'}."\n\n";          print OUT  "Ответ:\n".$Question{$tour}[$q]{'Answer'}."\n\n";
           print OUT  "Зачёт:\n".$Question{$tour}[$q]{'PassCriteria'}."\n\n";
         print OUT  "Автор:\n".$Question{$tour}[$q]{'Authors'}."\n\n"           print OUT  "Автор:\n".$Question{$tour}[$q]{'Authors'}."\n\n" 
                if !$tourauthor && !$eqauthor && $Question{$tour}[$q]{'Authors'};                 if !$tourauthor && !$eqauthor && $Question{$tour}[$q]{'Authors'};
         print OUT  "Комментарий:\n".$Question{$tour}[$q]{'Comments'}."\n\n"           print OUT  "Комментарий:\n".$Question{$tour}[$q]{'Comments'}."\n\n" 
Line 1769  sub WriteFile { Line 2021  sub WriteFile {
   
 sub Bottom  sub Bottom
 {  {
         my $output.=&Include_virtual("../dimrub/db/footer.html")||"";          my $output.=&Include_virtual("$footer")||"";
         $output.=p."<center><font size=-2>Обновление: ".&Include_virtual("../dimrub/db/date")."</center></font>";          $output.=p."<center><font size=-2>Обновление: ".&Include_virtual("$datefooter")."</center></font>";
         $output.=<<EEE          $output.=<<EEE
 <SCRIPT LANGUAGE="JavaScript">  <SCRIPT LANGUAGE="JavaScript">
 function toggle(e) {  function toggle(e) {
Line 1792  MAIN: Line 2044  MAIN:
 {  {
                   
         setlocale(LC_CTYPE,'russian');          setlocale(LC_CTYPE,'russian');
           POSIX::setlocale( &POSIX::LC_ALL, $thislocale );
         my($i, $tour);          my($i, $tour);
         my($text) = (param('text')) ? 1 : 0;          my($text) = (param('text')) ? 1 : 0;
         if (param('qid') && (param('qid')=~/^\d+$/)) {          $tour = (param('tour')) ? param('tour') : 0;
            my $destination='http://db.chgk.info/search.html';          my $texttour=$tour;
           my ($sth,$dbh);
           my($dsn) = "DBI:mysql:database=$dbname;host=$dbhost";
           $dbh = DBI->connect($dsn, $dbuser, $dbpass)
   #       $dbh = DBI->connect("DBI:mysql:$dbname", $username, $dbpass)
                   or do {
                           print header.h1("Временные проблемы") . "База вопросов временно не
                           работает. Заходите попозже.";
                           print &Include_virtual("$reklama") if $url!~/localhost/;
                       print end_html;
                           die "Can't connect to DB chgk\n";
                   };
           $dbh->do("set names koi8r");
   
           if (param('qid') && (param('qid')=~/^\d+$/) || $tour && $tour=~/^\d+$/) {
   #          my $destination='http://chgk.zaba.ru/search.html';
 #               print header (-'Content-Type' => 'text/html',  #               print header (-'Content-Type' => 'text/html',
 #                -'Location:'=> 'http:\\db.chgk.info');  #                -'Location:'=> 'http:\\db.chgk.info');
                 Redirect($destination);                  Redirect($destination);
                 exit                  exit
         }          }
   
         if ($text) {          if (0 && $tour && !param('qnumber') && (!param('answers')||(param('answers')<=1)))
           {       
                   my $n=param('tour');
                   $n=~s/.txt$//;        
                   my $gr=($n=~/^[A-Z]/) || (-e "$realHTMLDIR$n.html");
                   my $destination=tourhref($tour,param('answers')||0,$gr);
                   my $d=$destination;
                   $d=~s/$HTMLDIR/$realHTMLDIR/;
   #               print header.$destination;
   #                print header."$d|".(-e "$realHTMLDIR$n.html");
                   if (-e $d) {
                           Redirect($destination);
                           exit
                   }
                   $d=~s/\.\d+//;
                   $destination=~s/\.\d+//;
                   if (-e $d) {
                           Redirect($destination);
                           exit
                   }
   
           }
   
           if ($tour !~ /^[0-9]*$/) {          
                       if ($tour=~/\./)
                       {
                           my ($fname,$n)= split /\./ , $tour;
   
                           $sth = $dbh->prepare(
                          "SELECT t2.Id FROM Tournaments as t1, 
                           Tournaments as t2 
                           WHERE (t1.FileName = '$fname.txt' OR t1.FileName='$fname')
                           AND t1.Id=t2.ParentId AND t2.Number=$n");
                       }   
                       else 
                           {
                             $sth = $dbh->prepare("SELECT Id FROM Tournaments
                                        WHERE FileName = '$tour.txt' OR 
                                          FileName = '$tour'");
                           }
                       $sth->execute;
                       $tour = ($sth->fetchrow)[0];
                       $sth->finish;
           }
   
   
           if ($text && !param ('comp')) {
                 print header('text/plain');                  print header('text/plain');
         } else {print header;}          } elsif (!param('comp')) {
         my($dbh) = DBI->connect("DBI:mysql:chgk", "piataev", "")                  print header(-charset =>'koi8-r')}
                 or do {  
                         print h1("Временные проблемы") . "База вопросов временно не  
                         работает. Заходите попозже.";  
                         print &Include_virtual("../dimrub/db/reklama.html") if $url!~/localhost/;  
                     print end_html;  
                         die "Can't connect to DB chgk\n";  
                 };  
           my $sstr=param('sstr');            my $sstr=param('sstr');
             $opt_z||=param("makehtml");
           if (param('qid')) {            if (param('qid')) {
               my $sth;                my $sth;
               my $qid=param('qid');                my $qid=param('qid');
Line 1821  MAIN: Line 2129  MAIN:
                 {                  {
                     my ($fname,$t,$n)= split /\./ , $qid;                      my ($fname,$t,$n)= split /\./ , $qid;
                     $n=$t,$t='' unless $n;                      $n=$t,$t='' unless $n;
                       $t||=1;
                     if ($t)                      if ($t)
                     {                      {
                         $sth = $dbh->prepare(                          $sth = $dbh->prepare(
                        "SELECT t2.Id FROM Tournaments as t1,                          "SELECT t2.Id FROM Tournaments as t1, 
                         Tournaments as t2                           Tournaments as t2 
                         WHERE t1.FileName = '$fname.txt'                          WHERE (t1.FileName = '$fname.txt' OR t1.FileName='$fname')
                         AND t1.Id=t2.ParentId AND t2.Number=$t");                          AND t1.Id=t2.ParentId AND t2.Number=$t");
                     }                         }   
                     else   #                   else 
                         {  #                       {
                           $sth = $dbh->prepare("SELECT Id FROM Tournaments  #                          $sth = $dbh->prepare("SELECT Id FROM Tournaments
                                      WHERE FileName = '$fname.txt'");  #                                    WHERE FileName = '$fname.txt' OR FileName = '$fname'" );
                         }  #                       }
                     $sth->execute;                      $sth->execute;
                     $tour = ($sth->fetchrow)[0];                      $tour = ($sth->fetchrow)[0];
                     $sth->finish;                      $sth->finish;
Line 1864  MAIN: Line 2173  MAIN:
            my $title="Результаты поиска на \"". ($proxysstr||$sstr) .'"'              my $title="Результаты поиска на \"". ($proxysstr||$sstr) .'"' 
                                                     if ($proxysstr||$sstr);                                                      if ($proxysstr||$sstr);
            $title||="База вопросов";             $title||="База вопросов";
   
            $globaloutput.=start_html(-"title"=>$title,             $globaloutput.=start_html(-"title"=>$title,
                    -author=>'dimrub@icomverse.com',                     -author=>'dimrub@icomverse.com',
                    -bgcolor=>'#fff0e0',                     -bgcolor=>'#fff0e0',
                                   -vlink=>'#800020');                                    -vlink=>'#800020');#}
 $globaloutput.="<style>  $globaloutput.="<style>
 td      {font-size: x-small; font-family : sans-serif}  td      {font-size: x-small; font-family : sans-serif}
 th      {font-size: x-small; font-family : sans-serif}  th      {font-size: x-small; font-family : sans-serif}
   div.razdatka { 
       background-color:#EEEEFF;
       padding:4px;
       border:1px solid black;
   }
   
   div.razdatka_header {font-style:italic;}
   
 </style>\n";  </style>\n";
   
                 $globaloutput.=&Include_virtual("../dimrub/db/reklama.html")||'';                  $globaloutput.=&Include_virtual("$reklama")||'';
         }          }
   
        if (length ($qs)<=255 && $qs !~ /(sstr)|(rand)|(comp)|(all=)/i) {         if ($usehash && !$opt_z && length ($qs)<=255 && $qs !~ /(sstr)|(rand)|(comp)|(all=)/i) {
                 my $sth=$dbh->prepare("SELECT page,times,t from hash where query=".$dbh->quote($qs));                  my $sth=$dbh->prepare("SELECT page,times,t from hash where query=".$dbh->quote($qs));
                 $sth->execute();                  $sth->execute();
                 my ($p,$times,$t)=$sth->fetchrow();                  my ($p,$times,$t)=$sth->fetchrow();
Line 1901  th {font-size: x-small; font-family : sa Line 2217  th {font-size: x-small; font-family : sa
                   }                    }
                   $sth->finish;                    $sth->finish;
         }          }
                 $tour = (param('tour')) ? param('tour') : 0;  
                 my $sth;  
                 if ($tour !~ /^[0-9]*$/) {  
                     if ($tour=~/\./)  
                     {  
                         my ($fname,$n)= split /\./ , $tour;  
   
                         $sth = $dbh->prepare(  
                        "SELECT t2.Id FROM Tournaments as t1,   
                         Tournaments as t2   
                         WHERE t1.FileName = '$fname.txt'  
                         AND t1.Id=t2.ParentId AND t2.Number=$n");  
                     }     
                     else   
                         {  
                           $sth = $dbh->prepare("SELECT Id FROM Tournaments  
                                      WHERE FileName = '$tour.txt' OR   
                                        FileName = '$tour'");  
                         }  
                     $sth->execute;  
                     $tour = ($sth->fetchrow)[0];  
                     $sth->finish;  
                 }  
   
   
         if (param('rand')) {          if (param('rand')) {
Line 1971  EOT Line 2265  EOT
         elsif (param('getfile')){          elsif (param('getfile')){
            $globaloutput.=&writefile             $globaloutput.=&writefile
         } elsif (param('all')) {          } elsif (param('all')) {
            my $destination='http://db.chgk.info/all.html';  #          my $destination='http://db.chgk.info/all.html';
                 Redirect($destination);  #               Redirect($destination);
                 exit;  #                exit;
 #               $globaloutput.=&PrintAll($dbh, 0);                  $globaloutput.=&PrintAll($dbh, 0);
         } elsif (param('from_year') && param('to_year')) {          } elsif (param('from_year') && param('to_year')) {
                 $globaloutput.=&PrintDates($dbh);                  $globaloutput.=&PrintDates($dbh);
         } elsif (param('comp')) {          } elsif (param('comp')) {
             $globaloutput.="Content-Type: application/octet-stream\n";              print "Content-Type: application/octet-stream\n";
             $globaloutput.="Content-Type: application/force-download\n";              print  "Content-Type: application/force-download\n";
             $globaloutput.="Content-Type: application/download\n";              print  "Content-Type: application/download\n";
             $globaloutput.="Content-Type: application/x-zip-compressed; name=db.zip\n";              print  "Content-Type: application/x-zip-compressed; name=$texttour.zip\n";
             $globaloutput.="Content-Disposition: attachment; filename=db.zip \n\n";              print "Content-Disposition: attachment; filename=$texttour.zip \n\n";
             $tour ||= 0;              $tour ||= 0;
             my (@files) = &PrintArchive($dbh, $tour);              my (@files) = &PrintArchive($dbh, $tour);
             WriteFile($dbh,$_) foreach @files;              WriteFile($dbh,$_) foreach @files;
             open F, "$ZIP -j - @files |";              open F, "$ZIP -j - @files |";
             binmode(F);              binmode(F);
             binmode(STDOUT);              binmode(STDOUT);
             $globaloutput.= join "",<F>;              print join "",<F>;
             close F;              close F;
             $dbh->disconnect;              $dbh->disconnect;
             exit;              exit;
Line 2005  EOT Line 2299  EOT
             exit;              exit;
   
         }           } 
         elsif (!$opt_z) {          elsif (!$opt_z && !param("makehtml")) {
                 my $QuestionNumber=0;                  my $QuestionNumber=0;
                 my $qnum;                  my $qnum;
                 if ($qnum=param('qnumber')){                  if ($qnum=param('qnumber')){
Line 2015  EOT Line 2309  EOT
                   $QuestionNumber=($sth->fetchrow)[0]||0;                    $QuestionNumber=($sth->fetchrow)[0]||0;
                 }                  }
                 if ($QuestionNumber) {                  if ($QuestionNumber) {
                   $globaloutput.= &PrintQuestion($dbh, $QuestionNumber, param('answer')||0, $qnum, 1,0,0);                    $globaloutput.= &PrintQuestion($dbh, $QuestionNumber, $withanswers||0, $qnum, 1,$text,0);
 #                                        $dbh, $Id, $answer, $qnum, $title, $text  #                                        $dbh, $Id, $answer, $qnum, $title, $text
                 } else  {                  } else  {
                    $globaloutput.=&PrintTournament($dbh, $tour, param('answer'));                     $globaloutput.=&PrintTournament($dbh, $tour, $withanswers);
                 }                  }
         }          }
         else {          else {
                   open TS, "timestamp";                    $opt_z=1;
                     $url="http://db.chgk.info/cgi-bin/db.cgi";
                     open TS, $timestamp;
                   my $d=$dbh->quote(<TS>);                    my $d=$dbh->quote(<TS>);
                   close TS;                    close TS;
                   open FF, ">${realHTMLDIR}index.html" or die "ERROR! - ${HTMLDIR}index.html\n";                    open FF, ">${realHTMLDIR}index.html" or die "ERROR! - ${HTMLDIR}index.html\n";
Line 2044  EOT Line 2340  EOT
 #                     FROM Tournaments as t1, Tournaments as t2  #                     FROM Tournaments as t1, Tournaments as t2
 #                    WHERE t1.CreatedAt>$d AND t2.ParentId=t1.Id GROUP BY t1.Id");  #                    WHERE t1.CreatedAt>$d AND t2.ParentId=t1.Id GROUP BY t1.Id");
 my ($sth) = $dbh->prepare("SELECT t1.Id, t1.FileName, t1.Type, count(t2.Id)  FROM Tournaments as t1  LEFT JOIN Tournaments as t2   my ($sth) = $dbh->prepare("SELECT t1.Id, t1.FileName, t1.Type, count(t2.Id)  FROM Tournaments as t1  LEFT JOIN Tournaments as t2 
  ON t2.ParentId=t1.id WHERE t1.CreatedAt>$d GROUP BY t1.Id");   ON t2.ParentId=t1.id WHERE t1.CreatedAt>=$d GROUP BY t1.Id");
                   $sth->execute;                    $sth->execute;
                   my ($Id,$fname,$type,$c);                    my ($Id,$fname,$type,$c);
                   while (($Id,$fname,$type,$c)=$sth->fetchrow,$Id) {                    while (($Id,$fname,$type,$c)=$sth->fetchrow,$Id) {
Line 2053  my ($sth) = $dbh->prepare("SELECT t1.Id, Line 2349  my ($sth) = $dbh->prepare("SELECT t1.Id,
                      $fname=~s/\.txt$//;                       $fname=~s/\.txt$//;
                      if ($type=~/Т/ || $c<=1)                       if ($type=~/Т/ || $c<=1)
                      {                       {
                        open FF, ">$realHTMLDIR$fname-q.html" or die "ERROR! - $HTMLDIR$fname-q.html\n";                         open FF, ">$realHTMLDIR$fname-q.html" or die "ERROR! - $fname-q.html\n";
                        my $o=$globaloutput;                         my $o=$globaloutput;
                          $paramtour=$fname;
                        $o.=&PrintTournament($dbh, $Id, 0);                         $o.=&PrintTournament($dbh, $Id, 0);
                        $o.=&Bottom;                         $o.=&Bottom;
                        print FF $o;                         print FF $o;
Line 2067  my ($sth) = $dbh->prepare("SELECT t1.Id, Line 2364  my ($sth) = $dbh->prepare("SELECT t1.Id,
                        close FF;                         close FF;
                      }                       }
                      else {                       else {
                        open FF, ">$realHTMLDIR$fname.html" or die "ERROR! - $HTMLDIR$fname-q.html\n";                         open FF, ">$realHTMLDIR$fname.html" or die "ERROR! - $fname-q.html\n";
                        my $o=$globaloutput;                         my $o=$globaloutput;
                        $o.=&PrintTournament($dbh, $Id, 0);                         $o.=&PrintTournament($dbh, $Id, 0);
                        $o.=&Bottom;                         $o.=&Bottom;
Line 2082  my ($sth) = $dbh->prepare("SELECT t1.Id, Line 2379  my ($sth) = $dbh->prepare("SELECT t1.Id,
         }          }
         if (!$opt_z){           if (!$opt_z){ 
           print $globaloutput;            print $globaloutput;
           if (($qs!~ /(rand)|(sstr)|(comp)/i) && (length $qs<=255)) {            if (($qs!~ /(rand)|(sstr)|(comp)/i) && (length $qs<=255) && $usehash) {
                 $globaloutput=  $dbh->quote($globaloutput);                  $globaloutput=  $dbh->quote($globaloutput);
                 $dbh->do("insert into hash (query,page) values (".                  $dbh->do("insert into hash (query,page) values (".
                 $dbh->quote($qs).                  $dbh->quote($qs).

Removed from v.1.106  
changed lines
  Added in v.1.158


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