Diff for /db/prgsrc/db.cgi between versions 1.29 and 1.113

version 1.29, 2001/11/19 00:59:44 version 1.113, 2003/04/20 12:48:48
Line 2 Line 2
   
 use DBI;  use DBI;
 use CGI ':all';  use CGI ':all';
 use Text::Query;  
 use strict;  use strict;
 use Time::Local;  use Time::Local;
 use POSIX qw(locale_h);  use POSIX qw(locale_h);
 use locale;  use locale;
 open STDERR, ">errors";  use vars qw($opt_z);
 my $printqueries=1;  use Getopt::Std;
 my $debug=1; #added by R7  getopts('z');
   open STDERR, ">/var/tmp/errors1";
   my $newsurl='http://news.chgk.info/';
   my $reklama="../dimrub/db/reklama.html";
   $reklama="../reklama.html" if $opt_z;
   my $HTMLDIR="/znatoki/dimrub/db/baza/";
   my $realHTMLDIR;
   if ($^O =~ /win/i) {
    $realHTMLDIR="/html/znatoki/baza/";
   } else 
   {
     $realHTMLDIR="/home/znatoki/public_html/dimrub/db/baza/";
   }
   my $usehtml=1;
   my $usewas=0;
   my $cashednumber=500;
   my $outputnumber=10;
   my ($proxyptext,$proxysstr);
   my $printqueries=0;
   my $url=url||'';
   my $qs=query_string;
   my $globaloutput;
   my %forbidden=();
   my $debug=0; #added by R7
   my $outputkvo=param('kvo') ||$outputnumber;
   $outputkvo=100 if $outputkvo>100;
   
   if (param('debug')) {$debug=1; $printqueries=1}
   *STDERR=*STDOUT if $debug;
   if ($url !~ /db\.chgk\.info/ && $url !~ /localhost/ && $url !~ /bilbo/) {
      my $u="http://db.chgk.info/cgi-bin/db.cgi?$qs";
      Redirect ($u);
      exit;
   }
   if (!param('sstr') && param('all')) {
              my $destination='http://db.chgk.info/all.html';
                   Redirect($destination);
                   exit;
   }
   my $thislocale;
   if ($^O =~ /win/i) {
           $thislocale = "Russian_Russia.20866";
   } else {
           $thislocale = "ru_RU.KOI8-R";
   }
   POSIX::setlocale( &POSIX::LC_ALL, $thislocale );
   
   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, 'Comments', 3, 'Authors', 4, 'Sources');
   my %rusfieldname=('Question','Вопрос', 'Answer', 'Ответ', 
                     'Comments', 'Комментарии', 'Authors', 'Автор', 
                     'Sources', 'Источник','old','Старый','rus','Новый',
                     'chgk', 'ЧГК', 'brain', 'Брейн-ринг','game', 'Своя игра', 
                     'ehruditka', 'Эрудитка', 'beskrylka', 'Бескрылка', 'igp', 'Интернет'
   );
 my %searchin;  my %searchin;
   my $rl=qr/[йцукенгшщзхъфывапролджэячсмитьбюё]/;
   my $RL=qr/[ЙЦУКЕНГШЩЗХЪЭЖДЛОРПАВЫФЯЧСМИТЬБЮЁ]/;
   my $RLrl=qr/(?:(?:${rl})|(?:${RL}))+/;
   my $l=qr/(?:(?:${RLrl})|(?:[\w\-]))+/;
   my $Ll=qr/(?:[A-Z])|(?:${RL})/;
   my %metodchar=('rus',1,'old',2);
   
   
   
 my $thislocale;  
   $searchin{$_}=1 foreach param('searchin');
   my %TypeName=('children'=>'Д', 'game'=>'Я', 'igp'=>'И',
                 'chgk'=>'Ч', 'brain'=>'Б', 'beskrylka'=>'Л','ehruditka'=>'Э');
   
   
   
 $searchin{'question'}=param('Question');  
 $searchin{'answer'}=param('Answer');  
 $searchin{'comment'}=param('Comment');  
 $searchin{'authors'}=param('Authors');  
 $searchin{'sources'}=param('Sources');  
 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`;  my ($PWD) = `pwd` if $^O!~/win/i;
 chomp $PWD;  chomp $PWD if $PWD;
 my ($SRCPATH) = "$PWD/../dimrub/src";  my ($SRCPATH) = "/home/piataev/public_html/dimrub/src";
 my ($ZIP) = "/home/piataev/bin/zip";  my ($ZIP) = "/usr/local/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 ($TMSECS) = 30*24*60*60;  my ($TMSECS) = 30*24*60*60;
 my (%RevMonths) =   my (%RevMonths) =
         ('Jan', '0', 'Feb', '1', 'Mar', '2', 'Apr', '3', 'May', '4', 'Jun', '5',          ('Jan', '0', 'Feb', '1', 'Mar', '2', 'Apr', '3', 'May', '4', 'Jun', '5',
         'Jul', '6', 'Aug', '7', 'Sep', '8', 'Oct', '9', 'Nov', '10',          'Jul', '6', 'Aug', '7', 'Sep', '8', 'Oct', '9', 'Nov', '10',
         'Dec', '11',          'Dec', '11',
          'Янв', '0', 'Фев', 1, 'Мар', 2, 'Апр', 3, 'Май', '4',           'Янв', '0', 'Фев', 1, 'Мар', 2, 'Апр', 3, 'Май', '4',
          'Июн', '5', 'Июл', 6, 'Авг', '7', 'Сен', '8',            'Июн', '5', 'Июл', 6, 'Авг', '7', 'Сен', '8',
          'Окт', '9', 'Ноя', '19', 'Дек', '11');           'Окт', '9', 'Ноя', '19', 'Дек', '11');
   my @months=('000','Jan',"Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct",
             "Nov","Dec");
   
   
 # Determine whether the given time is within 2 months from now.  # Determine whether the given time is within 2 months from now.
 sub NewEnough {  sub NewEnough {
         my ($a) = @_;          my ($a) = @_;
         my ($year, $month, $day) = split('-', $a);          my ($year, $month, $day) = split('-', $a);
           $month=1 if ($month<=0);
           $day=1 if ($day<=0);
         return (time - timelocal(0, 0, 0, $day, $month -1, $year) < $TMSECS);          return (time - timelocal(0, 0, 0, $day, $month -1, $year) < $TMSECS);
 }  }
   
 # Reads one question from the DB. Gets DB handler and Question ID.  # Reads one question from the DB. Gets DB handler and Question ID.
   
   sub Redirect {
   my ($destination) = @_;
   print <<EndOfHTML;
   Content-type: text/html
   Location: $destination
   
   <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
   <HTML><HEAD><TITLE>Redirection</TITLE></HEAD>
   <BODY BGCOLOR="#FFFFFF">
   <H1>Redirection</H1>
   <P>It appears that your browser cannot handle redirections
   automatically. You can proceed to the randomly-selected page 
   by clicking <A HREF="$destination">here</A>.</P>
   </BODY>
   </HTML>
   EndOfHTML
   ;
   }
   
   
   
   
 sub GetTournament {  sub GetTournament {
         my ($dbh, $Id) = @_;          my ($dbh, $Id) = @_;
         my (%Tournament, $field, @arr);          my (%Tournament, $field, @arr);
Line 63  sub GetTournament { Line 149  sub GetTournament {
         foreach $name (@{$sth->{NAME}}) {          foreach $name (@{$sth->{NAME}}) {
                 $Tournament{$name} = $arr[$i++];                  $Tournament{$name} = $arr[$i++];
         }          }
           $sth->finish;
         return %Tournament;          return %Tournament;
 }  }
   
   sub fetchquestion {
           my ($sth,$q,$WithTour)=@_;
           if ($WithTour) {
                   ($$q{'Question'},$$q{'Answer'},$$q{'Comments'},$$q{'Authors'},
                   $$q{'Number'}, 
                   $$q{'Title'}, $$q{'TourTitle'}, $$q{'FileName'},$$q{'PlayedAt'},$$q{'TourNumber'}) = 
                   $sth->fetchrow;
           } else {
                   ($$q{'Question'},$$q{'Answer'},$$q{'Comments'},$$q{'Authors'},
                   $$q{'Number'})= 
                   $sth->fetchrow;
           }
   }
   
   
   
   sub SelectQuestions {
           my ($dbh,$q,$WithTour) = @_;
           my %q=();
           $_ = "QuestionId=$_" foreach @$q;
           my $where=join " OR ",@$q;
           $where||=1;
           $where="($where) AND Questions.ParentId=t1.Id AND t1.ParentId=t2.Id" 
                   if $WithTour;
   
           my $query;
           if ($WithTour) {
                   $query="SELECT Questions.Question, Answer, Comments, Authors,
                           Questions.Number
                           , t2.Title, t1.Title, t2.FileName,  t2.PlayedAt,t1.Number
                           from Questions,Tournaments as t1, Tournaments as t2 
                           WHERE $where";
           } else {
                   $query="SELECT Questions.Question, Answer, Comments, Authors,
                           Questions.Number from Questions 
                           WHERE $where";
           }
   
           my $sth;
           $sth=$dbh->prepare($query);
           $sth->execute;
           return $sth;
   }
   
   
 # Reads one question from the DB. Gets DB handler and Question ID.  # Reads one question from the DB. Gets DB handler and Question ID.
 sub GetQuestion {  sub GetQuestion {
         my ($dbh, $QuestionId) = @_;          my ($dbh, $QuestionId) = @_;
Line 84  sub GetQuestion { Line 215  sub GetQuestion {
                 $Question{$name} = $arr[$i++];                  $Question{$name} = $arr[$i++];
         }          }
   
           $sth->finish;
         return %Question;          return %Question;
 }  }
   
   sub tourhref {
      my ($t,$a,$gr)=@_;
      my $res;
      if ($usehtml) {
           $res=$t;
           $res.=$a?"-a":"-q" unless $gr;
           $res.=".html";
           $res=~s/(\#\d+)(.*)$/$2$1/;
           $res="$HTMLDIR$res" unless $opt_z;
           return $res;
      } else {
           $res=$url;
           $res.="?tour=$t";
           $res.=$a?"?answers=1":"";
           return $res;
      }
   
   }
   
 # Gets numbers of all the questions from the given tour.  # Gets numbers of all the questions from the given tour.
 sub GetTourQuestions {  sub GetTourQuestions {
         my ($dbh, $ParentId) = @_;          my ($dbh, $ParentId) = @_;
         my (@arr, @Questions);          my (@arr, @Questions);
           my ($sth) = $dbh->prepare("SELECT QuestionId FROM Questions
         my ($sth) = $dbh->prepare("SELECT QuestionId FROM Questions                   WHERE ParentId=$ParentId order by Number");
                 WHERE ParentId=$ParentId ORDER BY QuestionId");  
   
         $sth->execute;          $sth->execute;
   
Line 101  sub GetTourQuestions { Line 251  sub GetTourQuestions {
                 push @Questions, $arr[0];                  push @Questions, $arr[0];
         }          }
   
           $sth->finish;
         return @Questions;          return @Questions;
 }  }
   
Line 117  sub GetTours { Line 268  sub GetTours {
         while (@arr = $sth->fetchrow) {          while (@arr = $sth->fetchrow) {
                 push @Tours, $arr[0];                  push @Tours, $arr[0];
         }          }
           $sth->finish;
         return @Tours;          return @Tours;
 }  }
   
   sub count
   {
     my ($dbh,$word)=@_; 
     $word=$dbh->quote(uc $word);
     my $query="SELECT number from nests,nf where $word=w1 AND w2=nf.id";
     my $sth=$dbh->prepare($query);
     $sth->execute;
     my @a=$sth->fetchrow;
     $sth->finish;
     $a[0]||0;
   }
   
   
   sub printform
   {
   
     my $qnumber=("&nbsp;"x10)."Выводить по 
     <input type=\"text\" name=\"kvo\" value=$outputkvo size=\"3\" maxlength=\"5\">";
   #textfield(-name=>'kvo',
   #                         -default=>6,
   #                         -size=>3,
   #                         -maxlength=>5)." вопросов";
     my $sstr=param('sstr');
     my @df=keys %searchin;
     my %checked;
     $checked{lc $_}="" foreach ('Question','Answer','Comments','Authors','Sources','old','rus',
         'chgk','brain','igp','game','ehruditka','beskrylka');
     @df=('Question', 'Answer') unless @df;
     $checked{lc $_}="checked" foreach @df;
     my $fields=checkbox_group('searchin',['Question','Answer','Comments','Authors','Sources'], [@df],
                'false',\%rusfieldname);
     @df=param('type');
     @df=('chgk','brain','igp','game','ehruditka','beskrylka') unless @df;
     $checked{lc $_}="checked" foreach @df;
     my $all=param('all') && param('all') eq 'yes';
   
     $checked{'all'}=$all?"checked":"";
     $checked{'any'}=$all?"":"checked";
     $checked{lc param('metod')}="checked";
     $checked{'rus'}=1 unless $checked{'rus'} || $checked{'old'};
   
   #################################################
   return   
   <<EOT
   <form method="get" enctype="application/x-www-form-urlencoded"
   action="/znatoki/cgi-bin/db.cgi">
   <h2>Поиск в базе вопросов</h2>
   
   <input type="text" name="sstr" value="$sstr" size="30" maxlength="50"> 
   <input type="submit" value="Поиск"> $qnumber
   <p>
   
   <table border="1" cellpadding=4 cellspacing=0>
   <tr>
   <th align="left" rowspan=3 width="20%"> Вариант поиска:
   </td><td rowspan=2 colspan=2>
   <input type="radio" $checked{'old'} name="metod" value="old"> Простой (старый)
   </td><td>
   <input type="checkbox" $checked{'chgk'} name="type" value="chgk">&nbsp;"Что?&nbsp;Где?&nbsp;Когда?"
   </td><td><nobr>
   <input type="checkbox" $checked{'brain'} name="type" value="brain">&nbsp;"Брейн-Ринг"</nobr>
   </td><td>
   <input type="checkbox" $checked{'igp'} name="type" value="igp">&nbsp;"Интернет"
   </td>
   </tr><tr>
   <td>
   <input type="checkbox" $checked{'game'} name="type" value="game">&nbsp;"Своя&nbsp;игра"
   </td><td>
   <input type="checkbox"  $checked{'ehruditka'} name="type" value="ehruditka">&nbsp;"Эрудитка"
   </td><td>
   <input type="checkbox" $checked{'beskrylka'} name="type" value="beskrylka">&nbsp;"Бескрылка"
   </td>
   </tr><tr>
   <td colspan=5><input type="radio" $checked{'rus'} name="metod" value="rus"> Расширенный (с учетом грамматики, в вопросах всех типов)
   </td>
   </tr><tr>
   <th align="left">Искать:
   </td><td colspan=2>
   <input type="radio" $checked{'all'} name="all" value="yes">Все слова
   </td><td colspan=3>
   <input type="radio" $checked{'any'} name="all" value="no">Любое слово
   </td>
   </tr><tr>
   <th align="left">Поля для поиска:
   </td><td width="15%">
   <input type="checkbox" name="searchin" value="Question" $checked{'question'}>Вопрос
   </td><td width="15%">
   <input type="checkbox" name="searchin" value="Answer" $checked{'answer'}>Ответ<br> 
   </td><td width="15%">
   <input type="checkbox" name="searchin" value="Comments" $checked{'comments'}>Комментарии<br> 
   </td><td width="15%">
   <input type="checkbox" name="searchin" value="Authors" $checked{'authors'}>Автор<br>
   </td><td width="15%">
   <input type="checkbox" name="searchin" value="Sources" $checked{'sources'}>Источник<br>
   </td>
   </tr>
   </table>
   </center>
   
   EOT
   .endform
   .hr
   
   }
   
   sub proxy
   {     
         my ($dbh,$ptext,$allnf)=@_;
         my $sstr=makeproxysstr($dbh,$ptext,$allnf);
         return russearch($dbh,$sstr,0,$allnf);
   }
   
   sub makeproxysstr {
         my ($dbh,$ptext)=@_;
         my $text=$$ptext;
         $text=~tr/ёЁ/еЕ/;
         $text=~s/(${RLrl})p(${RLrl})/$1p$2/gom;
         $text=~s/p(${RLrl})/р$1/gom;
         $text=~s/(${RLrl})p/$1р/gom;
         $text=~s/\s+/ /gmo;
         $text=~s/[^йцукенгшщзхъфывапролджэячсмитьбюЙЦУКЕНГШЩЗХЪФЫВАПРОЛДЖЭЯЧСМИТЬБЮQWERTYUIOPASDFGHJKLZXCVBNM0-9]/ /g;
         $text=uc $text;
         my @list= $text=~m/(?:(?:${RLrl})+)|(?:[A-Za-z0-9]+)/gom;
         my (%c, %good,$sstr);
         foreach (@list)
         {
              $c{$_}=count($dbh,$_)||10000;
         }
         my @words=sort {$c{$a}<=> $c{$b}} @list;
   
   #      $good{$words[$_]}=1 foreach 0..4;
   
         foreach (@words)
         {
            $good{$_}=1 if $c{$_}<200;
         }
   
         $good{$words[$_]}=0 foreach 16..$#words;
   
         $sstr.=" $_" foreach grep {$good{$_}} @list;
         $$ptext=$sstr;
         return $sstr;
   }
   
   
 sub russearch {  sub russearch {
             my ($dbh, $sstr, $all,$allnf)=@_;              my ($dbh, $sstr, $all,$allnf)=@_;
             my (@qw,@w,@tasks,$qw,@arr,$nf,$sth,@nf,$w,$where,$e,@where,%good,$i,%where,$from);              my (@qw,@w,@tasks,$qw,@arr,$nf,$sth,@nf,$w,$where,$e,@where,%good,$i,%where,$from);
Line 145  $sstr=~tr/йцукенгшщзхъфывапролджэячсмить Line 441  $sstr=~tr/йцукенгшщзхъфывапролджэячсмить
             foreach $i (0..$#w) # заполняем массив @nf начальных форм              foreach $i (0..$#w) # заполняем массив @nf начальных форм
                            # $nf[$i] -- ссылка на массив возможных                             # $nf[$i] -- ссылка на массив возможных
                            # начальных форм словоформы $i                             # начальных форм словоформы $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";
 print "$query",br if $printqueries;  
                 $sth=$dbh -> prepare($query);                  $sth=$dbh -> prepare($query);
                 $sth -> execute;                  $sth -> execute;
                 @{$nf[$i]}=();                  @{$nf[$i]}=();
Line 157  print "$query",br if $printqueries; Line 452  print "$query",br if $printqueries;
                 {                  {
                    push (@{$nf[$i]},$arr[0])                     push (@{$nf[$i]},$arr[0])
                 }                  }
                   $sth->finish;
             }              }
   
   
             my @bad=grep {!$nf[$_]} 0..$#w; # @bad -- номера словоформ,              my @bad=grep {!@{$nf[$_]}} 0..$#w; # @bad -- номера словоформ,
                                            # которых нет в словаре                                             # которых нет в словаре
   
             if (@bad) #есть неопознанные словоформы              if (@bad) #есть неопознанные словоформы
Line 179  print "$query",br if $printqueries; Line 475  print "$query",br if $printqueries;
   
             my $kvo=0;              my $kvo=0;
             push @$allnf, @{$_} foreach @nf;              push @$allnf, @{$_} foreach @nf;
 print "nf=@$allnf";  
   
             foreach $i (0..$#w) #запросы в базу...              foreach $i (0..$#w) #запросы в базу...
             {              {
Line 189  print "nf=@$allnf"; Line 484  print "nf=@$allnf";
   
   
   
               $_= " word2question.word=".$_. ' ' foreach @arr;                $_= " word2question.word=$_" foreach @arr;
               $_= " nf.id=".$_. ' ' foreach @arr1;                $_= " nf.id=".$_. ' ' foreach @arr1;
   #              @arr=(0) unless @arr;
 #              $_= " nests.w2=".$_. ' ' foreach @arr2;                $query="select questions from word2question where (". (join ' OR ', @arr).") AND length(questions)<80000";
 #              $query="select w1 from nests where". (join ' OR ', @arr2);  
 #print $query if $printqueries;  
 #             $sth=$dbh -> prepare($query);  
 #              $sth->execute;  
 #              while (@ar=$sth->fetchrow)  
 #              {  
 #                 $ar[0]=~s/(.)/&nocase($1)/ge;  
 #                 push(@sf,'(?:'.$ar[0].')');  
 #              }  
 #              $selectshablon=join '|',@sf;  
   
 #print $selectshablon,br if $printqueries;  
   
 #              $selectshablon=qr/$selectshablon/i;  
   
   
   
   
               $query="select questions from word2question where". (join ' OR ', @arr);  
 print "$query\n",br if $printqueries;  
   
               $sth=$dbh -> prepare($query);                $sth=$dbh -> prepare($query);
               $sth->execute;                $sth->execute;
Line 222  print "$query\n",br if $printqueries; Line 497  print "$query\n",br if $printqueries;
               {                {
                 @blob=(@blob,unpack 'C*',$arr[0]);                  @blob=(@blob,unpack 'C*',$arr[0]);
               }                }
                 $sth->finish;
               $query="select number from nf where ".(join ' OR ', @arr1);                $query="select number from nf where ".(join ' OR ', @arr1);
 print "$query\n",br if $printqueries;  
               $sth=$dbh -> prepare($query);                $sth=$dbh -> prepare($query);
               $sth->execute;                $sth->execute;
   
Line 231  print "$query\n",br if $printqueries; Line 506  print "$query\n",br if $printqueries;
               {                {
                 $frequence[$i]+=$arr[0];                  $frequence[$i]+=$arr[0];
               }                }
                 $sth->finish;
   
   
               if (@blob < 4)                if (@blob < 4)
Line 251  print "$query\n",br if $printqueries; Line 526  print "$query\n",br if $printqueries;
                  {                   {
                     ($field,$lo,$hi,$wordnumber)=@blob[$ii..($ii+3)];                      ($field,$lo,$hi,$wordnumber)=@blob[$ii..($ii+3)];
                     $ii+=4;                      $ii+=4;
                     $number=$lo+$hi*256;                      my $addnumber=($field >> 4) << 16;
                     $field=$fieldname{$field};                      $number=(($field >> 4) << 16)+($hi << 8) + $lo;
                     if ($searchin{lc $field})                      $field=$fieldname{$field & 0xF};
                       if ($searchin{$field})
                     {                      {
                       push @{$tasksof{$i}{$number}}, $wordnumber;                        push @{$tasksof{$i}{$number}}, $wordnumber;
                                       # дополнили в хэше, висящем на                                        # дополнили в хэше, висящем на
Line 270  print "$query\n",br if $printqueries; Line 546  print "$query\n",br if $printqueries;
                }                 }
             }    #foreach $i              }    #foreach $i
   
 #print "keys tasksof", join ' ', keys %{$tasksof{0}};  
 #Ищем пересечение или объединение списков вопросов (значений %tasksof)  #Ищем пересечение или объединение списков вопросов (значений %tasksof)
             foreach $sf (keys %tasksof)              foreach $sf (keys %tasksof)
            {             {
Line 280  print "$query\n",br if $printqueries; Line 555  print "$query\n",br if $printqueries;
                              keys %count) ;                               keys %count) ;
   
   
 print "\n\$#tasks=",$#tasks,br if $printqueries;  
 ############ Сортировка найденных вопросов  ############ Сортировка найденных вопросов
   
 foreach (keys %wordsof)  foreach (keys %wordsof)
Line 293  foreach (keys %wordsof) Line 567  foreach (keys %wordsof)
   
 ############  ############
   
 print "tasks=@tasks";  
   
 #print "$_ $relevance{$_} | " foreach @tasks;  
 #print br;  
 print "allnf=@$allnf",br if $printqueries;  
         return  @tasks;          return  @tasks;
 }  }
   
Line 348  if $$words{$first}; Line 618  if $$words{$first};
   
 # Returns list of QuestionId's, that have the search string in them.  # Returns list of QuestionId's, that have the search string in them.
 sub Search {  sub Search {
         my ($dbh, $sstr,$metod,$all,$allnf) = @_;          my ($dbh, $s,$metod,$all,$allnf) = @_;
           my $sstr=$$s;
         my (@arr, @Questions, @fields);          my (@arr, @Questions, @fields);
         my (@sar, $i, $sth,$where);          my (@sar, $i, $sth,$where,$query);
   
 #       push @fields, 'Question';  
   
         if ($metod eq 'rus')          if ($metod eq 'rus')
         {          {
              my @tasks=russearch($dbh,$sstr,$all,$allnf);               my @tasks=russearch($dbh,$sstr,$all,$allnf);
              return @tasks               return @tasks
         }          }
           elsif ($metod eq 'proxy')
           {
             my @task=proxy($dbh,$s,$allnf);
             return @task
           }
   
   
   
 ###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 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 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::'.
                    (($metod eq 'simple') ? 'ParseSimple':'ParseAdvanced'),                     (($metod eq 'simple') ? 'ParseSimple':'ParseAdvanced'),
                  -solve => 'Text::Query::SolveSQL',                   -solve => 'Text::Query::SolveSQL',
                  -build => 'Text::Query::BuildSQLMySQL',                   -build => 'Text::Query::BuildSQLMySQL',
                  -fields_searched => $fields);                   -fields_searched => $fields);
   
            $where=      $$q{'matchexp'};             $where=      $$q{'matchexp'};
            my $query= "SELECT Questionid FROM Questions             $query= "SELECT Questionid FROM Questions
                 WHERE $where";                  WHERE $where";
            print br."Query is: $query".br if $debug;  
   
            $sth = $dbh->prepare($query);             $sth = $dbh->prepare($query);
          } else           } else
 ######     ######
          {           {
   
           foreach (qw/Question Answer Sources Authors Comments/) {  #         foreach (qw/Question Answer Sources Authors Comments/) {
                 if (param($_)) {            foreach (param('searchin')) {
   #               if (param($_)) {
                         push @fields, "IFNULL($_, '')";                          push @fields, "IFNULL($_, '')";
                 }  #               }
           }            }
           @sar = split " ", $sstr;            @sar = split " ", $sstr;
           for $i (0 .. $#sar) {            for $i (0 .. $#sar) {
                 $sar[$i] = $dbh->quote("%${sar[$i]}%");                  $sar[$i] = $dbh->quote("%${sar[$i]}%");
           }            }
             $_.=' ' foreach (@fields); # Это чтобы последнее слово поля
                                        # не сливалось с первым словом
                                        # следующего поля, R7
           my($f) = "CONCAT(" . join(',', @fields) . ")";            my($f) = "CONCAT(" . join(',', @fields) . ")";
           if (param('all') eq 'yes') {            if (param('all') eq 'yes') {
                 $sstr = join " AND $f LIKE ", @sar;                  $sstr = join " AND $f LIKE ", @sar;
           } else {            } else {
                 $sstr = join " OR $f LIKE ", @sar;                  $sstr = join " OR $f LIKE ", @sar;
           }            }
             
      my $query;
                  $query="SELECT QuestionId FROM Questions
                   WHERE ($f LIKE $sstr) AND (".&makewhere.") ORDER BY QuestionId";
   
 my $query="SELECT QuestionId FROM Questions  
                 WHERE $f LIKE $sstr ORDER BY QuestionId";  
 print $query if $printqueries;  
           $sth = $dbh->prepare($query)  
   
             $sth = $dbh->prepare($query)
         } #else -- processing old-style query (R7)          } #else -- processing old-style query (R7)
   
         $sth->execute;          $sth->execute;
         while (@arr = $sth->fetchrow) {          while (@arr = $sth->fetchrow) {
                 push @Questions, $arr[0];                  push @Questions, $arr[0] unless $forbidden{$arr[0]};
         }          }
                   $sth->finish;
           
         return @Questions;          return @Questions;
 }  }
   
   sub makewhere {
         my @type=param('type');    
         my $type='';
   
         $type .= ($_=$TypeName{$_}) foreach @type;
         my $where=' 0 ';
         foreach (@type) {
                $where.= " OR (Type ='$_') OR (Type ='$_Д') ";
         } 
         $where.= "OR (Type='ЧБ')" if ($type=~/Ч|Б/);
         return $where;
   }
   
  # Substitute every letter by a pair (for case insensitive search).   # Substitute every letter by a pair (for case insensitive search).
  my (@letters) = qw/аА бБ вВ гГ дД еЕ жЖ зЗ иИ йЙ кК лЛ мМ нН оО    my (@letters) = qw/аА бБ вВ гГ дД еЕ жЖ зЗ иИ йЙ кК лЛ мМ нН оО
  пП рР сС тТ уУ фФ хХ цЦ чЧ шШ щЩ ьЬ ыЫ эЭ юЮ яЯ/;   пП рР сС тТ уУ фФ хХ цЦ чЧ шШ щЩ ьЬ ыЫ эЭ юЮ яЯ/;
    
 sub NoCase {  sub NoCase {
         my ($sstr) = shift;          my ($sstr) = shift;                     
         my ($res);          my ($res);
   
         if (($res) = grep(/$sstr/, @letters)) {          if (($res) = grep(/$sstr/, @letters)) {
Line 436  sub NoCase { Line 727  sub NoCase {
         }          }
 }  }
   
   sub PrintList {
      my ($dbh,$Questions,$shablon,$was)=@_;
           my $Output;
           my $first=param('first') ||1;
   
           $first=$first-($first-1)%$outputkvo;
           my $fkvo=param('fkvo')||($#$Questions+1);
           my $last=$first+$outputkvo-1;
           $last=$fkvo if $fkvo<$last;
           my($f,$l);
           my $nav='';
           my $qs=query_string;
           $qs=~s/\;/\&/g;
           $qs=~s/\&first\=[^\&]+//g;
           my $sstr=param('sstr')||'';
           $qs=~s/sstr=[^\&]+/sstr=$sstr/;
           if ($usewas) {
                   $qs=~s/\&was=[^\&]+//;
                   $qs.="&was=$was" if $was;
                   $qs.="&fkvo=$fkvo" if $was;
           }
           if ($first>$outputkvo*3+1)
           {
              $nav.=
               ("&nbsp;"x4).
               a({href=>$url."?".$qs."\&first=1"},"<<").("&nbsp;"x4).
               a({href=>($url."?".$qs."\&first=".($first-$outputkvo))},"<").("&nbsp;"x4)
           }
           else {$nav.='&nbsp;'x15;}
   
        my ($fprint,$lprint);
        my $llprint=$fkvo- ($fkvo)%$outputkvo+1; #
        if ($fkvo<=$outputkvo*7)
        {         $fprint=1;
                  $lprint=$llprint;
        }
        elsif ($first>$outputkvo*3 && $fkvo-$first>$outputkvo*3)
        {
          $fprint=$first-$outputkvo*3;
          $lprint=$first+$outputkvo*3;
        } 
        elsif  ($first<=$outputkvo*3)
        {
           $fprint=1; $lprint=6*$outputkvo+1;
        }
        else
        { 
              $lprint=$llprint;
              $fprint=$lprint-$outputkvo*6
        }
            
   #        my $fprint=($first>$outputkvo*3) ? $first-$outputkvo*3 : 1;
   #        my $lprint=$#$Questions+1-$fprint>$outputkvo*7 ? $outputkvo*7 :$#$Questions+1;
   #        if ($lprint-$fprint<$outputkvo*6 && $fprint>1)
   #        {
   #            $fprint=$lprint-$outputkvo*6;
   #            $fprint=1 if ($fprint<=0) 
   #        }
   
   
   
           for($f=$fprint; $f<=$lprint; $f+=$outputkvo)
           {
   #         next if $first-$f>$outputkvo*3;
             $l=$f+$outputkvo-1;
             $l=$fkvo if $l>$fkvo+1;
             if ($f==$first) {$nav.="[$f-$l] ";}
             else {
                     $nav.= "[".a({href=>($url."?".$qs."\&first=$f")},"$f-$l")."] ";}
           }
           if ($lprint+$outputkvo<$fkvo)
           {
              $nav.=
               ("&nbsp;"x4).
               a({href=>($url."?".$qs."\&first=".($first+$outputkvo))},">").("&nbsp;"x4).
               a({href=>$url."?".$qs."\&first=$llprint"},">>").("&nbsp;"x4)
           }
           $Output.= "$nav".br."\n";
           my @q=@$Questions[$first-1..$last-1];
           my %q=();
           my $sth=SelectQuestions($dbh,\@q,1);
           for (my $i = $first; $i <= $last; $i++) {
                   fetchquestion($sth,\%q,1);
                   my $output;
                   $output = &PrintQuestion($dbh, \%q, 1, 0, 1,0,1  );
                   if (param('metod') && (param('metod') eq 'rus' || param('metod') eq 'proxy'))
                   {
                        $output=~s/\b($shablon)\b/\<strong\>$1\<\/strong\>/gi;
                   } else {
                        $output=~s/($shablon)/\<strong\>$1\<\/strong\>/gi;
                   }
                   $Output.= $output;
           }
           $sth->finish;
   
           $Output.= "$nav".br."\n";
           return $Output;
   }
   
 sub PrintSearch {  sub PrintSearch {
         my ($dbh, $sstr, $metod) = @_;          my $Output='';
           my ($dbh, $sstr, $metod,$was) = @_;
           my $t=time;
           $Output.= printform;
         my @allnf;          my @allnf;
         my (@Questions) = &Search($dbh, $sstr,$metod,$all,\@allnf);          my @Questions;
           $was=0 if $metod eq 'proxy';
           if ($usewas && $was && ($metod ne 'proxy'))
           {
             my $sth=$dbh->prepare ("select sstr,questions,allnf from lastqueries where id=".param('was'));
             $sth->execute;
             my ($q,$nf);
             ($sstr, $q,$nf)=($sth->fetchrow);
             @Questions=unpack 'L*',$q; 
             @allnf=unpack 'L*',$nf;        
             $sth->finish;
           }  
           if (!$was || ($metod eq 'proxy') || (param('first')+$outputkvo>$cashednumber))
           {
                @Questions=&Search($dbh, \$sstr,$metod,$all,\@allnf);
                $cashednumber=$#Questions if $cashednumber>$#Questions;
                my $tmp=$dbh->quote(pack("L*",@Questions[0..$cashednumber]));
                my $qsstr=$dbh->quote($sstr);
                my $nf=$dbh->quote(pack("L*", @allnf));
                my $ss=200;
                if ($usewas) {
                   do 
                           {
                                   $was=int rand(32000);
                           }
                   while (--$ss && (!$dbh->do ("insert into lastqueries (id,sstr,questions,allnf) 
                            values ($was, $qsstr,$tmp,$nf)")));
                   $Output.= "Something is wrong...".br unless $ss;
                 }
           }
   
   
   
           $Output.= p. "Время поиска: " . (time-$t) ." сек.".p;
         my ($output, $i, $suffix, $hits) = ('', 0, '', $#Questions + 1);          my ($output, $i, $suffix, $hits) = ('', 0, '', $#Questions + 1);
   
         my $shablon;          my $shablon;
           $metod='rus' if $metod eq 'proxy';
         if ($metod eq 'rus')          if ($metod eq 'rus')
         {          {
            my $where='0';             my $where='0';
            $where.= " or w2=$_ " foreach @allnf;             $where.= " or w2=$_ " foreach @allnf;
            my $query="select w1 from nests where $where";             my $query="select w1 from nests where $where";
            my $sth=$dbh->prepare($query);             my $sth=$dbh->prepare($query);
 print "$query" if $printqueries;  
   
            $sth->execute;             $sth->execute;
            my @shablon;             my @shablon;
Line 458  print "$query" if $printqueries; Line 883  print "$query" if $printqueries;
            {             {
              push @shablon,"(?:$arr[0])";               push @shablon,"(?:$arr[0])";
            }             }
            $shablon= join "|", @shablon;              $sth->finish;
              $shablon= join "|", @shablon;
            $shablon=~s/[её]/\[ЕЁ\]/gi;             $shablon=~s/[её]/\[ЕЁ\]/gi;
 #           $shablon=~s/([йцукенгшщзхъфывапролджэячсмитьбюЙЦУКЕНГШЩЗХЪФЫВАПРОЛДЖЭЯЧСМИТЬБЮ])/&NoCase($1)/ge;  #           $shablon=~s/([йцукенгшщзхъфывапролджэячсмитьбюЙЦУКЕНГШЩЗХЪФЫВАПРОЛДЖЭЯЧСМИТЬБЮ])/&NoCase($1)/ge;
            $shablon=qr/$shablon/i;             $shablon=qr/$shablon/i;
            print "!$shablon!",br if $printqueries;  
         }  
   
           }
   
           $hits=param("fkvo")||$hits;
   
         if ($hits =~ /1.$/  || $hits =~ /[5-90]$/) {          if ($hits =~ /1.$/  || $hits =~ /[5-90]$/) {
                 $suffix = 'й';                  $suffix = 'й';
         } elsif ($hits =~ /1$/) {          } elsif ($hits =~ /1$/) {
                 $suffix = 'е';                  $suffix = 'е';
         } else {          } else {
                 $suffix = 'я';                   $suffix = 'я';
         }          }
           
         print p({align=>"center"}, "Результаты поиска на " . strong($sstr)          $Output.= p({align=>"center"}, "Результаты поиска на " . strong($sstr)
         . " : $hits попадани$suffix.");          . " : $hits попадани$suffix.");
   
         if (param('word')) {          if (param('word')) {
                 $sstr = '[      \.\,:;]' . $sstr . '[  \.\,:\;]';                  $sstr = '[      \.\,:;]' . $sstr . '[  \.\,:\;]';
         }          }
   
         $sstr =~ s/(.)/&NoCase($1)/ge;  #       $sstr =~ s/(.)/&NoCase($1)/ge;
   
         my(@sar) = split(' ', $sstr);          my @sar;
         for ($i = 0; $i <= $#Questions; $i++) {          if ($metod ne 'rus') 
                 $output = &PrintQuestion($dbh, $Questions[$i], 1, $i + 1, 1);          {
                 if (param('metod') eq 'rus')            my $ss=$sstr;
                 {             (@sar) = split(' ', $ss);
                      $output=~s/\b($shablon)\b/\<strong\>$1\<\/strong\>/gi;            s/(\W)/\\$1/g foreach (@sar);
                 } else {            $shablon=join "|",@sar;
                 foreach  (@sar) {  
                         $output =~ s/$_/<strong>$&<\/strong>/gs;  
                 }}  
                 print $output;  
         }          }
           $Output.=PrintList($dbh,\@Questions,$shablon,$was);
           return $Output;
 }  }
   
 sub PrintRandom {  sub PrintRandom {
    my ($dbh, $type, $num, $text) = @_;     my ($dbh, $type, $num, $text) = @_;
      my $razd=param('razd');
      my %q;
      my $answer=$razd?0:1;
      my @answers;
    my (@Questions) = &Get12Random($dbh, $type, $num);     my (@Questions) = &Get12Random($dbh, $type, $num);
         my ($output, $i) = ('', 0);          my ($output, $i) = ('', 0);
   
Line 509  sub PrintRandom { Line 937  sub PrintRandom {
                 $output .=                  $output .=
                         h2({align=>"center"}, "$num случайных вопросов.");                          h2({align=>"center"}, "$num случайных вопросов.");
         }          }
           my $sth=SelectQuestions($dbh,\@Questions,0);
         for ($i = 0; $i <= $#Questions; $i++) {          for ($i = 0; $i <= $#Questions; $i++) {
                 # Passing DB handler, question ID, print answer, question                  fetchquestion($sth,\%q,0);
                 # number, print title, print text/html                  $output .=
                 $output .=                           &PrintQuestion($dbh, \%q, $answer, $i + 1, 0, $text,1);
                         &PrintQuestion($dbh, $Questions[$i], 1, $i + 1, 0, $text);                          push @answers, $q{'Answer'};
         }          }
         return $output;           $sth->finish;
           unless ($answer )
           { 
            $output.=$text?"\n".('-'x 20)."\nОтветы\n~~~~~~\n\n":h2('Ответы');
            $sth=SelectQuestions($dbh,\@Questions,0);
            for ($i = 0; $i <= $#Questions; $i++) {
   #                fetchquestion($sth,\%q,0);
   #               $output .=
   #                       &PrintQuestion($dbh, \%q, -1, $i + 1, 0, $text,1);
                   $output.=$text?("Ответ ". ($i+1).": $answers[$i]\n\n"):
                           b("Ответ ". ($i+1).": "). $answers[$i].p;
            }
           }
   
           return $output;
   }
   
   sub PrintEditor {
          my $t=shift; #ссылка на Хэш с полями
          my $ed=$$t{'Editors'}||'';
          my $edname=($ed=~/\,/ ) ? "Редакторы"  : "Редактор" ;
          return $ed? h4({align=>"center"},"$edname: $ed" ): '';
 }  }
   
 sub PrintTournament {  sub PrintTournament {
Line 526  sub PrintTournament { Line 975  sub PrintTournament {
         my ($output) = '';          my ($output) = '';
   
         %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/\/znatoki\/boris\/reports\//$newsurl/ if url=~/kulichki/;;
         my ($Info) = $Tournament{'Info'};          my ($Info) = $Tournament{'Info'};
         my ($Copyright) = $Tournament{'Copyright'};          my ($Copyright) = $Tournament{'Copyright'};
           my $fname=$Tournament{'FileName'};
         @Tours = &GetTours($dbh, $Id);          @Tours = &GetTours($dbh, $Id);
           $list='';
           my $textid;
         if ($Id) {          if ($Id) {
                 for ($Tournament{'Type'}) {                  for ($Tournament{'Type'}) {
                         /Г/ && do {                          /Г/ && do {
                                 $output .= h2({align=>"center"},                                   $output .= h2({align=>"center"},
                                               "Группа: $Tournament{'Title'} ",                                                "Группа: $Tournament{'Title'} ",
                                               "$Tournament{'PlayedAt'}") . p . "\n";                                                $Tournament{'PlayedAt'}||'') . p . "\n";
                                 last;                                  last;
                         };                          };
                         /Ч/ && do {                          /Ч/ && do {
                                 return &PrintTour($dbh, $Tours[0], $answer)                                  return &PrintTour($dbh, $Tours[0], $answer)
                                         if ($#Tours == 0);                                          if ($#Tours == 0);
                                   
                                 my $title="Пакет: $Tournament{'Title'}";                                  my $title="Пакет: $Tournament{'Title'}";
                                 if ($Tournament{'PlayedAt'}) {                                  if ($Tournament{'PlayedAt'}) {
                                     $title .= " $Tournament{'PlayedAt'}";                                      $title .= " $Tournament{'PlayedAt'}";
                                 }                                  }
   
                                 $output .= h2({align=>"center"},                                   $output .= h2({align=>"center"},
                                         "$title") . p . "\n";                                          "$title") . p . "\n";
                                  $output.=&PrintEditor(\%Tournament);
                                 last;                                  last;
                         };                          };
                         /Т/ && do {                          /Т/ && do {
Line 560  sub PrintTournament { Line 1013  sub PrintTournament {
                 }                  }
         } else {          } else {
                 my ($qnum) = GetQNum($dbh);                  my ($qnum) = GetQNum($dbh);
                 $output .= h2("Банк Вопросов: $qnum вопросов") . p . "\n";                  $output .= h2("Банк Вопросов: $qnum вопрос".&Suffix($qnum)) 
                             . p . "\n";
         }          }
   
         for ($i = 0; $i <= $#Tours; $i++) {           for ($i = 0; $i <= $#Tours; $i++) {
                 %Tournament = &GetTournament($dbh, $Tours[$i]);                  %Tournament = &GetTournament($dbh, $Tours[$i]);
                   
                 if ($Tournament{'Type'} =~ /Ч/) {                  if ($Tournament{'Type'} =~ /Ч/) {
                         $SingleTour = 0;                          $SingleTour = 0;
                         my (@Tours) = &GetTours($dbh, $Tournament{'Id'});                          my (@Tours) = &GetTours($dbh, $Tournament{'Id'});
Line 578  sub PrintTournament { Line 1032  sub PrintTournament {
                 } else {                  } else {
                         $qnum = '';                          $qnum = '';
                 }                  }
                 if ($Tournament{'Type'} =~ /Г/) {                  if ($Tournament{'Type'} !~ /[ТЧ]/) {
                       $SingleTour=0;
                         $imgsrc = "/icons/folder.gif";                          $imgsrc = "/icons/folder.gif";
                         $alt = "[*]";                          $alt = "[*]";
                 } else {                  } else {
Line 586  sub PrintTournament { Line 1041  sub PrintTournament {
                         $alt = "[-]";                          $alt = "[-]";
                 }                  }
   
                 if ($SingleTour or $Tournament{'Type'} =~ /Т/) {                  my $textid;
                   if ($textid=$Tournament{'FileName'})
                   {
                      $textid=~s/\.txt//;
                   }
                   elsif ($textid=$Tournament{'Number'})
                     {
                         $fname=~s/\.txt//;
                         $textid="$fname.$textid";
                     }
                  else {$textid=$Tournament{'Id'}};
                   
   
                   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'}||"") . $qnum) .
                                 dl(                                  dl(
                                         dd("["                                          dd("["
                                                 . a({href=>url .  "?tour=$Tournament{'Id'}&answer=0"},                                                  . a({href=>tourhref($textid,0)},
                                                 "вопросы") . "] ["                                                  "вопросы") . "] ["
                   . a({href=>url .  "?tour=$Tournament{'Id'}&answer=1"},                    . a({href=>tourhref($textid,1)},
                   "вопросы + ответы") . "]")                    "вопросы + ответы") . "]")
                                 );                                  );
                 } else {                  } else {
                         $list .= dd(a({href=>url . "?tour=$Tournament{'Id'}&comp=1"},                           $list .= dd(a({href=>
                                 img({src=>'/icons/compressed.gif', alt=>'[ZIP]', border=>1}))                                   $url . "?tour=$textid&comp=1"},
                                 . " " . img({src=>$imgsrc, alt=>$alt})                                   img({src=>'/icons/compressed.gif', alt=>'[ZIP]', border=>1})). 
                                 . " " . a({href=>url . "?tour=$Tournament{'Id'}&answer=0"},                                   " " . 
                                 $Tournament{'Title'}. " ".                                   img({src=>$imgsrc, alt=>$alt})
                                           $Tournament{'PlayedAt'}) . $qnum);                                  . " " . a({href=>tourhref($textid,0,1)},
                                   $Tournament{'Title'}. " ".
                                             ($Tournament{'PlayedAt'}||'')) . $qnum); 
                 }                  }
         }          }
         $output .= dl($list);          $output .= dl($list);
   
         if ($URL) {          if ($URL) {
                   if ($url=~/zaba\.ru/ && $URL=~/^\//){$URL="http://info.chgk.info$URL"}
                 $output .=                  $output .=
                 p("Дополнительная информация об этом турнире - по адресу " .                   p("Дополнительная информация об этом турнире - по адресу " .
                         a({-'href'=>$URL}, $URL));                          a({-'href'=>$URL}, $URL));
         }          }
   
Line 618  sub PrintTournament { Line 1089  sub PrintTournament {
                 $output .= p("Копирайт: " .   $Copyright);                  $output .= p("Копирайт: " .   $Copyright);
         }          }
   
   
   
         if ($Info) {          if ($Info) {
                 $output .= p($Info);                  $output .= p($Info);
         }          }
           
         return $output;          return $output;
 }  }
   
Line 634  sub Suffix { Line 1106  sub Suffix {
 }  }
   
 sub IsTour {  sub IsTour {
         my ($dbh, $Id) = @_;          my ($dbh, $Id,$n) = @_;
         my ($sth) = $dbh->prepare("SELECT Type FROM Tournaments   
           my ($sth) ;
           
           if (defined $n) 
           { $sth=$dbh->prepare ("select Id FROM Tournaments
                              WHERE ParentId=$Id AND Number=$n");
           }
           else
           {
             $sth=$dbh->prepare("SELECT Id FROM Tournaments
                 WHERE Id=$Id");                  WHERE Id=$Id");
           }
         $sth->execute;          $sth->execute;
         return ($sth->fetchrow)[0] =~ /Т/;          my $a=($sth->fetchrow)[0];
           $sth->finish;
           return $a;
 }  }
   
 # Gets a DB handler (ofcourse) and a tour Id. Prints all the  # Gets a DB handler (ofcourse) and a tour Id. Prints all the
Line 650  sub PrintTour { Line 1134  sub PrintTour {
         my (%Tour) = &GetTournament($dbh, $Id);          my (%Tour) = &GetTournament($dbh, $Id);
         my (@Tours) = &GetTours($dbh, $Tour{'ParentId'});          my (@Tours) = &GetTours($dbh, $Tour{'ParentId'});
         my (%Tournament) = &GetTournament($dbh, $Tour{'ParentId'});          my (%Tournament) = &GetTournament($dbh, $Tour{'ParentId'});
           my %q;
   
         return 0          return 0
                 if ($Tour{'Type'} !~ /Т/);                  if ($Tour{'Type'} !~ /Т/);
   
           my ($fname)=$Tournament{'FileName'};
           $fname=~s/\.txt//;
         my ($qnum) = $Tour{'QuestionsNum'};          my ($qnum) = $Tour{'QuestionsNum'};
         my ($suffix) = &Suffix($qnum);           my ($suffix) = &Suffix($qnum);
           
         $output .= h2({align=>"center"}, $Tournament{"Title"},           $output .= h2({align=>"center"}, $Tournament{"Title"},
                       $Tournament{'PlayedAt'},                        $Tournament{'PlayedAt'}||'',
                       "<br>", $Tour{"Title"} .                         "<br>", $Tour{"Title"} .
                 " ($qnum вопрос$suffix)\n") . p;                  " ($qnum вопрос$suffix)\n") . p;
           $output .=&PrintEditor(\%Tour);
   
         my (@Questions) = &GetTourQuestions($dbh, $Id);          my (@Questions) = &GetTourQuestions($dbh, $Id);
           my $sth=SelectQuestions($dbh,\@Questions,0);
         for ($q = 0; $q <= $#Questions; $q++) {          for ($q = 0; $q <= $#Questions; $q++) {
                 $output .= &PrintQuestion($dbh, $Questions[$q], $answer, 0);                  fetchquestion($sth,\%q,0);
         }                   $output .= &PrintQuestion($dbh, \%q, $answer, 0,0,0,1);
           }
           $sth->finish;
         $output .= hr({-'align'=>'center', -'width'=>'80%'});          $output .= hr({-'align'=>'center', -'width'=>'80%'});
   
         if ($Tournament{'URL'}) {          if ($Tournament{'URL'}) {
                 $output .=                  $output .=
                 p("Дополнительная информация об этом турнире - по адресу " .                   p("Дополнительная информация об этом турнире - по адресу " .
                         a({-'href'=>$Tournament{'URL'}}, $Tournament{'URL'}));                          a({-'href'=>$Tournament{'URL'}}, $Tournament{'URL'}));
         }          }
   
Line 682  sub PrintTour { Line 1172  sub PrintTour {
         if ($Tournament{'Info'}) {          if ($Tournament{'Info'}) {
                 $output .= p($Tournament{'Info'});                  $output .= p($Tournament{'Info'});
         }          }
           
   
           my $n=$Tour{'Number'};
         if ($answer == 0) {          if ($answer == 0) {
                 $bottom .=                   $bottom .=
                         "[" . a({href=>url . "?tour=$Id&answer=1"}, "ответы") .  "] " . br;                          "[" . a({href=>tourhref($fname,1)}, 
         }                           "ответы") .  "] " . br;
         if (&IsTour($dbh, $Id - 1)) {          }
                 $bottom .=           if ($n>1) {
                         "[" . a({href=>url . "?tour=" . ($Id - 1) . "&answer=0"},                   $bottom .=
                           "[" . a({href=>tourhref("$fname.".($n-1),0)},
                         "предыдущий тур") . "] ";                          "предыдущий тур") . "] ";
                 $bottom .=                   $bottom .=
                         "[" . a({href=>url . "?tour=" . ($Id - 1) . "&answer=1"},                           "[" . a({href=>tourhref("$fname.".($n-1),1)},
                         "предыдущий тур с ответами") . "] " . br;                          "предыдущий тур с ответами") . "] " . br;
         }          }
         if (&IsTour($dbh, $Id + 1)) {          if (&IsTour($dbh, $Tour{'ParentId'}, $n + 1)) {
                 $bottom .=                   $bottom .=
                         "[" . a({href=>url . "?tour=" . ($Id + 1) . "&answer=0"},                           "[" . a({href=>tourhref("$fname.".($n+1),0)},
                         "следующий тур") . "] ";                          "следующий тур") . "] ";
                 $bottom .=                   $bottom .=
                         "[" . a({href=>url . "?tour=" . ($Id + 1) . "&answer=1"},                           "[" . a({href=>tourhref("$fname.".($n+1),1)},
                         "следующий тур с ответами") . "] ";                          "следующий тур с ответами") . "] ";
         }          }
   
Line 714  sub PrintTour { Line 1205  sub PrintTour {
 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;              $value =~ s/^\s+/<br>&nbsp;&nbsp;&nbsp;&nbsp;/mg;
             $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:\/\/(?:\w+.)+[\w\\\~]+(\?[^\s.]+)?)/<a href="$1">$1<\/a>/g if $header !~ /^Авто/;
   #           $value =~ s/(\s)"/$1&#147;/mg;
   #           $value =~ s/^"/&#147;/mg;
   #           $value =~ s/"/&#148;/mg;
         }          }
   
         return $text ? "$header:\n$value\n\n" :   
           return $text ? "$header:\n$value\n\n" :
                 strong("$header: ") . $value . p . "\n";                  strong("$header: ") . $value . p . "\n";
 }  }
   
 # Gets a DB handler (ofcourse) and a question Id. Prints   # Gets a DB handler (ofcourse) and a question Id. Prints
 # that question, according to the options.  # that question, according to the options.
 sub PrintQuestion {  sub PrintQuestion {
         my ($dbh, $Id, $answer, $qnum, $title, $text) = @_;          my ($dbh, $Id, $answer, $qnum, $title, $text,$h) = @_;
         my ($output, $titles) = ('', '');          my ($output, $titles) = ('', '');
           my (%Question);
         my (%Question) = &GetQuestion($dbh, $Id);          if ($h) {
         if (!$text) {            %Question=%$Id;
                 $output .= hr({width=>"50%"});          } else {
                   %Question = &GetQuestion($dbh, $Id);
                 if ($title) {                  if ($title) {
                         my (%Tour) = GetTournament($dbh, $Question{'ParentId'});                          my (%Tour) = GetTournament($dbh, $Question{'ParentId'});
                         my (%Tournament) = GetTournament($dbh, $Tour{'ParentId'});                          my (%Tournament) = GetTournament($dbh, $Tour{'ParentId'});
                           $Question{'FileName'}=$Tournament{'FileName'};
                           $Question{'Title'}=$Tournament{'Title'};
                           $Question{'PlayedAt'}=$Tournament{'PlayedAt'};
                           $Question{'TourNumber'}=$Tour{'Number'};
                           $Question{'TourTitle'}=$Tour{'Title'};
                   }
   
           }
                   $qnum = $Question{'Number'}
                   if ($qnum == 0);
           if (!$text) {
                   $output .= hr({width=>"50%"}) if $answer>=0;
                   if ($title) {
                           my $fname=$Question{'FileName'};
                           $fname=~s/\.txt//;
                         $titles .=                          $titles .=
                                 dd(img({src=>"/icons/folder.open.gif"}) . " " .                                  dd(img({src=>"/icons/folder.open.gif"}) . " " .
                                          a({href=>url . "?tour=$Tournament{'Id'}"}, $Tournament{'Title'}, $Tournament{'PlayedAt'}));                                           a({href=>tourhref($fname,0,1)}, 
                                  $Question{'Title'}, $Question{'PlayedAt'}||''));
                         $titles .=                          $titles .=
                                 dl(dd(img({src=>"/icons/folder.open.gif"}) . " " .                                  dl(dd(img({src=>"/icons/folder.open.gif"}) . " " .
                                         a({href=>url . "?tour=$Tour{'Id'}"}, $Tour{'Title'})));                                          a({href=>tourhref("$fname.$Question{'TourNumber'}#$qnum",1)}, 
                             $Question{'TourTitle'})));
                 }                  }
                 $output .= dl(strong($titles));                  $output .= dl(strong($titles));
         }          }
           
         $qnum = $Question{'Number'}  
                 if ($qnum == 0);  
   
         $output .=   
                 &PrintField("Вопрос $qnum", $Question{'Question'}, $text);  
   
         if ($answer) {          $output.= "<a NAME=\"$qnum\">" unless $text;
                 $output .=   
           if ($answer>=0) {$output .=
                   &PrintField("Вопрос $qnum", $Question{'Question'}, $text);}
           else {$output .="$qnum. "}
           if ($answer==1|| $answer==-1) {
                   $output .=
                         &PrintField("Ответ", $Question{'Answer'}, $text);                          &PrintField("Ответ", $Question{'Answer'}, $text);
   
                 if ($Question{'Authors'}) {                  if ($Question{'Authors'} ) {
                       my $q=$Question{'Authors'};                        my $q=$Question{'Authors'};
   ###АВТОРА!!
                       my $sth=$dbh->prepare("select Authors.Id,Name, Surname, Nicks from Authors, A2Q  #                     my $sth=$dbh->prepare("select Authors.CharId,Name, Surname, Nicks from Authors, A2Q
                                  where Authors.Id=Author And Question=$Id");  #                                  where Authors.Id=Author And Question=$Id");
                       $sth->execute;  #                       $sth->execute;
                       my ($AuthorId,$Name, $Surname,$other,$Nicks);  #                       my ($AuthorId,$Name, $Surname,$other,$Nicks);
   #                      if (!$text) {
                       while ((($AuthorId,$Name, $Surname,$Nicks)=$sth->fetchrow),$AuthorId)  #                       while ((($AuthorId,$Name, $Surname,$Nicks)=$sth->fetchrow),$AuthorId)
                       {  #                       {
                         my ($firstletter)=$Name=~m/^./g;  #                          my ($firstletter)=$Name=~m/^./g;
 #                       $other.=a({href=>url."?qofauthor=$AuthorId"},"$Name $Surname").". ";  #                          $Name=~s/\./\\\./g;
                           my $sha="(?:$Name\\s+$Surname)|(?:$Surname\\s+$Name)|(?:$firstletter\\.\\s*$Surname)|(?:$Surname\\s+$firstletter\\.)|(?:$Surname)|(?:$Name)";  #                          $Name=~s/ё/[её]/g;
                           $Nicks=~s/^\|//;  #                          $Surname=~s/ё/[её]/g;
                           foreach (split /\|/, $Nicks)  #                           my $sha="(?:$Name\\s+$Surname)|(?:$Surname\\s+$Name)|(?:$firstletter\\.\\s*$Surname)|(?:$Surname\\s+$firstletter\\.)|(?:$Surname)";
                           {  #                           if ($Nicks)
                               s/ /\\s+/;  #                           {
                               if (s/>$//) {$sha="$sha|(?:$_)"}  #                             $Nicks=~s/^\|//;
                               else        {$sha="(?:$_)|$sha"}  #                             foreach (split /\|/, $Nicks)
                           }  #                             {
 #$output.=br."sha=$sha".br;  #                               s/\s+/ /g;
                           $q=~s/($sha)/a({href=>url."?qofauthor=$AuthorId"},$1)/ei;  #                               s/\s+$//;
                       }  #                               s/ /\\s+/g;
   #                               s/\./\\\./g;
   #                               if (s/>$//) {$sha="$sha|(?:$_)"}
   #                               else        {$sha="(?:$_)|$sha"}
   #                             }
   #                           }
   #                           $q=~s/($sha)/a({href=>url."?qofauthor=$AuthorId"},$1)/ei;
   #                           unless ($1) 
   #                             {   
   #                                 $q=~s/$Name/a({href=>url."?qofauthor=$AuthorId"},$1)/ei;
   #                             }
   #                       }
   #                      }
                         $output .= &PrintField("Автор(ы)", $q, $text);                          $output .= &PrintField("Автор(ы)", $q, $text);
   
 #                        $output.= &PrintField("Другие вопросы", $other);  
                 }                  }
   
                 if ($Question{'Sources'}) {                  if ($Question{'Sources'}) {
Line 793  sub PrintQuestion { Line 1319  sub PrintQuestion {
                         $output .= &PrintField("Комментарии", $Question{'Comments'}, $text);                          $output .= &PrintField("Комментарии", $Question{'Comments'}, $text);
                 }                  }
         }          }
           elsif ($answer==2) {
             my $text=$Question{'Answer'};
             $text=~s/\n/<option>/mg;
             $output.="<select><option selected>Ответ:<option>$text</select>";
             $text=$Question{'Comments'}||'';
             if ($text) {
                $text=~s/\n/<option>/mg;
                $output.="<select><option selected>Комментарий:<option>$text</select>"
             }
           } 
           elsif ($answer==3) {
           $output.=  <<EOTT
             <div align=right STYLE="cursor:hand;" OnStart="toggle(document.all.HideShow$qnum);" OnClick="toggle(document.all.HideShow$qnum);">
             <font size=-2 color=red> Показать/убрать ответ</font></div>
             <span style="display:none" id=HideShow$qnum>
   EOTT
             .&PrintField("Ответ", $Question{'Answer'}, $text);
                   if ($Question{'Authors'}) {
                           $output .= &PrintField("Автор(ы)", $Question{'Authors'}, $text);
                   }
                   if ($Question{'Sources'}) {
                           $output .= &PrintField("Источник(и)", $Question{'Sources'}, $text);
                   }
   
                   if ($Question{'Comments'}) {
                           $output .= &PrintField("Комментарии", $Question{'Comments'}, $text);
                   }
   
   
   
   $output.="</span>"
   
           }
           $output=~s/\(pic: ([^\)]*)\)/<p><img src="\/znatoki\/images\/db\/$1"><p>/g unless $text;
           my $qid=param('tour') ? (param('tour').".$Question{'Number'}" ): '';
   
           $output.=br.a({href=> $url."?metod=proxy&
   qid=$qid"}, 'Близкие вопросы').p
                if $answer>0 && !$text && $qid;
         return $output;          return $output;
 }  }
   
Line 801  sub GetQNum { Line 1366  sub GetQNum {
         my ($dbh) = @_;          my ($dbh) = @_;
         my ($sth) = $dbh->prepare("SELECT COUNT(*) FROM Questions");          my ($sth) = $dbh->prepare("SELECT COUNT(*) FROM Questions");
         $sth->execute;          $sth->execute;
         return ($sth->fetchrow)[0];          my $tmp=($sth->fetchrow)[0];
           $sth->finish;
           return $tmp;
 }  }
 sub GetMaxQId {  sub GetMaxQId {
         my ($dbh) = @_;          my ($dbh) = @_;
         my ($sth) = $dbh->prepare("SELECT MAX(QuestionId) FROM Questions");          my ($sth) = $dbh->prepare("SELECT MAX(QuestionId) FROM Questions");
         $sth->execute;          $sth->execute;
         return ($sth->fetchrow)[0];          my $tmp=($sth->fetchrow)[0];
           $sth->finish;
           return $tmp;
   
 }  }
   
 # Returns Id's of 12 random questions  # Returns Id's of 12 random questions
Line 817  sub Get12Random { Line 1387  sub Get12Random {
         my ($qnum) = &GetMaxQId($dbh);          my ($qnum) = &GetMaxQId($dbh);
         my (%chosen);          my (%chosen);
         srand;          srand;
                   my $where=0;
    for ($i = 0; $i < $num; $i++) {          my $r=int (rand(10000));
        do {  
            $q = int(rand($qnum));          foreach (split '', $type)
            $sth = $dbh->prepare("SELECT Type FROM Questions          {
                                 WHERE QuestionId=$q");             $where.= " OR (Type ='$_') OR (Type ='$_Д') ";
            $sth->execute;          }
            $t = ($sth->fetchrow)[0];          $where.= "OR (Type='ЧБ')" if ($type=~/Ч|Б/);
        } until !$chosen{$q} && $t && $type =~ /[$t]/;  
        $chosen{$q} = 'y';  #   $q="select QuestionId, QuestionId/$r-floor(QuestionId/$r) as val 
        push @questions, $q;  #       from Questions where $where order by val limit $num";
   # Когда на куличках появится mysql >=3.23 надо заменить на order by rand();
      $q="select QuestionId from Questions where $where order by rand() limit $num";
   
   
      $sth=$dbh->prepare($q);
      $sth->execute;
      while (($i)=$sth->fetchrow)
      {
         push @questions,$i;
    }     }
      $sth->finish;
       for ($i=@questions; --$i;){ 
          my $j=rand ($i+1); 
          @questions[$i,$j]=@questions[$j,$i] unless $i==$j;
       }
    return @questions;     return @questions;
 }  }
   
 sub Include_virtual {  sub Include_virtual {
         my ($fn, $output) = (@_, '');          my ($fn, $output) = (@_, '');
           return "<!--#include virtual=\"$fn\"-->" 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;
Line 847  sub Include_virtual { Line 1431  sub Include_virtual {
                 }                  }
                 $output .= $_;                  $output .= $_;
         }          }
         return $output;          return $output||"";
 }  }
   
 sub PrintArchive {  sub PrintArchive {
Line 856  sub PrintArchive { Line 1440  sub PrintArchive {
   
         my (%Tournament) = &GetTournament($dbh, $Id);          my (%Tournament) = &GetTournament($dbh, $Id);
         my (@Tours) = &GetTours($dbh, $Id);          my (@Tours) = &GetTours($dbh, $Id);
           
         if ($Tournament{'Type'} =~ /Г/ || $Id == 0) {          if ($Tournament{'Type'} =~ /Г/ || $Id == 0) {
                 for ($i = 0; $i <= $#Tours; $i++) {                  for ($i = 0; $i <= $#Tours; $i++) {
                         push(@list ,&PrintArchive($dbh, $Tours[$i]));                          push(@list ,&PrintArchive($dbh, $Tours[$i]));
                 }                  }
                 return @list;                  return @list;
         }          }
         return "$SRCPATH/$Tournament{'FileName'} ";  #       return "$SRCPATH/$Tournament{'FileName'} ";
           return "$TMPDIR/$Tournament{'FileName'} ";
 }  }
   
 sub PrintAll {  sub PrintAll {
         my ($dbh, $Id) = @_;          my ($dbh, $Id,$fname) = @_;
         my ($output, $list, $i);          my ($output, $list, $i);
   
         my (%Tournament) = &GetTournament($dbh, $Id);          my (%Tournament) = &GetTournament($dbh, $Id);
         my (@Tours) = &GetTours($dbh, $Id);          my (@Tours) = &GetTours($dbh, $Id);
         my ($New) = ($Id and $Tournament{'Type'} eq 'Ч' and           my $SingleTour = $#Tours == 0;
   
           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!"}) : "";
   
         if ($Id == 0) {          if ($Id == 0) {
                 $output = h3("Все турниры");                  $output = h3("Все турниры");
         } else {          } else {
                    my $textid;
                    if ($textid=$Tournament{'FileName'})
                    {
                      $textid=~s/\.txt//;
                    }
                    elsif ($textid=$Tournament{'Number'})
                    {
                         $fname=~s/\.txt//;
                         $textid="$fname.$textid";
                    }
                    else {$textid=$Tournament{'Id'}};
   
   
                 $output .= dd(img({src=>"/icons/folder.gif", alt=>"[*]"}) .                  $output .= dd(img({src=>"/icons/folder.gif", alt=>"[*]"}) .
       " " . a({href=>url . "?tour=$Tournament{'Id'}&answer=0"},        " " . a({href=>tourhref($textid,0,!$SingleTour)},
       $Tournament{'Title'}) ." " . $Tournament{'PlayedAt'} . " $New");        $Tournament{'Title'}) ." " . ($Tournament{'PlayedAt'}||'') . " $New");
         }          }
         if ($Id == 0 or $Tournament{'Type'} =~ /Г/) {          if ($Id == 0 or $Tournament{'Type'} =~ /Г/ or $Tournament{'Type'} eq '') {
                 for ($i = 0; $i <= $#Tours; $i++) {                  for ($i = 0; $i <= $#Tours; $i++) {
                         $list .= &PrintAll($dbh, $Tours[$i]);                          $list .= &PrintAll($dbh, $Tours[$i],$Tournament{'FileName'});
                 }                  }
                 $output .= dl($list);                  $output .= dl($list);
         }          }
Line 894  sub PrintAll { Line 1493  sub PrintAll {
   
 sub PrintDates {  sub PrintDates {
         my ($dbh) = @_;          my ($dbh) = @_;
         my ($from) = param('from_year') . "-" . param('from_month') .           my ($from) = param('from_year') . "-" . param('from_month') .
                 "-" .  param('from_day');                  "-" .  param('from_day');
         my ($to) = param('to_year') . "-" . param('to_month') . "-" .  param('to_day');          my ($to) = param('to_year') . "-" . param('to_month') . "-" .  param('to_day');
         $from = $dbh->quote($from);          $from = $dbh->quote($from);
Line 914  sub PrintDates { Line 1513  sub PrintDates {
                         if (!$array[0]);                          if (!$array[0]);
                 %Tournament = &GetTournament($dbh, $array[0]);                  %Tournament = &GetTournament($dbh, $array[0]);
       $list .= dd(img({src=>"/icons/folder.gif", alt=>"[*]"}) .        $list .= dd(img({src=>"/icons/folder.gif", alt=>"[*]"}) .
       " " . a({href=>url . "?tour=$Tournament{'Id'}&answer=0"},        " " . a({href=>tourhref($Tournament{'FileName'},0,1)},
       $Tournament{'Title'}, $Tournament{'PlayedAt'}));        $Tournament{'Title'}, $Tournament{'PlayedAt'}||''));
         }          }
           $sth->finish;
         $output .= dl($list);          $output .= dl($list);
         return $output;          return $output;
 }  }
   
 sub PrintQOfAuthor  sub PrintQOfAuthor
 {  {
   
     my ($dbh, $id) = @_;      my ($dbh, $id) = @_;
    $id=$dbh->quote($id);      my $Output='';
     my $sth =  $dbh->prepare("SELECT  Name, Surname FROM Authors WHERE Id=$id");          unless ($id=~/^\d+$/) {
         $id=$dbh->quote($id);
         my $sth =  $dbh->prepare("SELECT Id FROM Authors WHERE CharId=$id");
         $sth->execute;
         ($id)=$sth->fetchrow;
         $sth->finish;
       }
       $id=$dbh->quote($id);
   
       my $sth =  $dbh->prepare("SELECT  Name, Surname FROM Authors WHERE Id=$id");
     $sth->execute;      $sth->execute;
     my ($name,$surname)=$sth->fetchrow;      my ($name,$surname)=$sth->fetchrow;
   
     $sth =  $dbh->prepare("SELECT Question FROM A2Q WHERE Author=$id");          $sth =  $dbh->prepare("SELECT Question FROM A2Q WHERE Author=$id");
     $sth->execute;      $sth->execute;
     my $q;      my $q;
     my @Questions;            my @Questions;
     while (($q)=$sth->fetchrow,$q)      while (($q)=$sth->fetchrow,$q)
      {push @Questions,$q;}       {push @Questions,$q unless $forbidden{$q}}
       $sth->finish;
   
     my ($output, $i, $suffix, $hits) = ('', 0, '', $#Questions + 1);      my ($output, $i, $suffix, $hits) = ('', 0, '', $#Questions + 1);
   
Line 943  sub PrintQOfAuthor Line 1554  sub PrintQOfAuthor
         } elsif ($hits =~ /1$/) {          } elsif ($hits =~ /1$/) {
                 $suffix = 'е';                  $suffix = 'е';
         } else {          } else {
                 $suffix = 'я';                   $suffix = 'я';
         }          }
                   $Output.= printform;
         print p({align=>"center"}, "Автор ".strong("$name $surname. ")           $Output.= p({align=>"center"}, "Автор ".strong("$name $surname. ")
         . " : $hits попадани$suffix.");          . " : $hits попадани$suffix.");
   
   
         for ($i = 0; $i <= $#Questions; $i++) {  #       for ($i = 0; $i <= $#Questions; $i++) {
                 $output = &PrintQuestion($dbh, $Questions[$i], 1, $i + 1, 1);  #               $output = &PrintQuestion($dbh, $Questions[$i], 1, $i + 1, 1);
                 print $output;  #               print $output;
         }  #       }
           $Output.=PrintList($dbh,\@Questions,'gdfgdfgdfgdfg');
 }  }
   
   
Line 961  sub PrintAuthors Line 1573  sub PrintAuthors
 {  {
      my ($dbh,$sort)=@_;       my ($dbh,$sort)=@_;
      my($output,$out1,@array,$sth);       my($output,$out1,@array,$sth);
      if ($sort eq 'surname')        if ($sort eq 'surname')
      {       {
         $sth =           $sth =
              $dbh->prepare("SELECT Id, Name, Surname, QNumber FROM Authors order by Surname");               $dbh->prepare("SELECT Id, Name, Surname, QNumber FROM Authors order by Surname, Name");
                }
         $output.="<TABLE><CAPTION>Алфавитный список авторов</CAPTION>";       elsif($sort eq 'name')
        {
           $sth =
                $dbh->prepare("SELECT Id, Name, Surname, QNumber FROM Authors order by Name, Surname");
      }       }
      else       else
      {       {
         $sth =           $sth =
              $dbh->prepare("SELECT Id, Name, Surname, QNumber FROM Authors Order by QNumber DESC");                     $dbh->prepare("SELECT Id, Name, Surname, QNumber FROM Authors Order by QNumber DESC, Surname");
         $output.="<TABLE>";  
      }       }
   
        $output.=h2("Авторы вопросов")."\n";
        $output.="<TABLE>";
   
   
      $sth->execute;       $sth->execute;
      $output.=Tr(th["Фамилия, имя", "Количество вопросов"]);       $output.=Tr(th[a({href=>$url."?authors=name"},"Имя")
   .", ".
   a({href=>$url."?authors=surname"},"фамилия")
        , a({href=>$url."?authors=kvo"},"Количество вопросов")]);
   
      $out1='';       $out1='';
   
      my $ar=$sth->fetchall_arrayref;       my $ar=$sth->fetchall_arrayref;
   
        $sth->finish;
   
   
       
     foreach my $arr(@$ar)      foreach my $arr(@$ar)
      {       {
             
            my ($id,$name,$surname,$kvo)=@$arr;             my ($id,$name,$surname,$kvo)=@$arr;
            if (!$name || !$surname) {print "Opanki at $id\n"} else             if (!$name || !$surname) {
                 } else
            {             {
              my $add=Tr(td([a({href=>"/cgi-bin/db.cgi?qofauthor=$id"},'[Q] ')."$name $surname", $kvo]))."\n";               my $add=Tr(td([a({href=>$url."?qofauthor=$id"},"$name $surname"), $kvo]))."\n";
              print STDERR $add;  
              $output.=$add;               $output.=$add;
            }             }
      }       }
      $output.="</TABLE>";       $output.="</TABLE>";
        $sth->finish;
      return $output;       return $output;
 }  }
   
   
      sub WriteFile {
     my ($dbh,$fname) = @_;
     $fname=~s/\s+$//;
     $fname=~s/^\s+//;
     $fname=~s/\.txt$//;
     $fname=~s/.*\/(\w+)/$1/;
   
     my $query= "SELECT Id, Title, Copyright, Info, URL, 
                         Editors, EnteredBy, PlayedAt, CreatedAt 
                        from Tournaments where FileName=".$dbh->quote("$fname.txt");
     my $sth=$dbh->prepare($query);
     my (%Question,%editor,%qnumber,%copyright,%author,%vid,%tourtitle);
     $sth->execute;
     my ($Id, $Title, $Copyright, $Info, $URL, 
      $Editors, $EnteredBy, $PlayedAt, $CreatedAt)=
         $sth->fetchrow;
     return -1 unless $Id;
     open (OUT, ">$TMPDIR/$fname.txt") || print STDERR "Error in $fname.txt\n";
     print OUT "Чемпионат:\n$Title\n\n";
     my $date=$PlayedAt||'00-00-00';
     my ($year,$month,$day)=split /-/, $date;
   #  $month=0,$date=0 if $year && $month==1 && $day==1;
     my $pdate=sprintf("%02d-%3s-%4d",$day,$months[$month],$year);
   
     print OUT "Дата:\n$pdate\n\n" if $date;
   
     print OUT "URL:\n$URL\n\n" if $URL;
   
     print OUT "Инфо:\n$Info\n\n" if $Info;
   
     print OUT "Копирайт:\n$Copyright\n\n" if $Copyright;
   
     print OUT "Редактор:\n$Editors\n\n" if $Editors;
   
   
     $query= "SELECT Id, Title, Copyright, Editors from Tournaments where ParentId=$Id order by Id";
     $sth=$dbh->prepare($query);
     $sth->execute;
     my ($tourid,$tourtitle,$cright,$editor,@tours,$vid,$author,$tourauthor);
   
   
     while (($tourid,$tourtitle,$cright,$editor)=$sth->fetchrow,$tourid)
     {
   #    $text{$tourid}="Тур:\n$tourtitle\n\n";
       $query= "SELECT * from Questions where ParentId=$tourid order by QuestionId";
       my $sth1=$dbh->prepare($query);
       $sth1->execute;
       push(@tours,$tourid);
       $tourtitle{$tourid}=$tourtitle;
       $copyright{$tourid}=$cright;
       $editor{$tourid}=$editor;
       $vid='';
       my $author='';
       my $eqauthor=1;
       my $qnumber=0;
       my @arr;
       while ( (@arr=$sth1->fetchrow), $arr[0])
       {
           my($i, $name);
           $i=0;
           $qnumber++;
           foreach $name (@{$sth1->{NAME}}) {
                   if ($arr[$i]) {
                      $arr[$i]=~s/^(.*?)\s*$/$1/;
                      $Question{$tourid}[$qnumber]{$name} = $arr[$i];
                   } else {
                       $Question{$tourid}[$qnumber]{$name} = 
                      ''}
                   $i++;
           }
           if ($vid)
           {
             if ($vid ne $Question{$tourid}[$qnumber]{'Type'}) {print STDERR "Warning: Different types for Tournament $tourid\n"}
           } else 
           {
               $vid=$Question{$tourid}[$qnumber]{'Type'};
           } 
   
           if ($author)
           {
             if ($author ne $Question{$tourid}[$qnumber]{'Authors'})  
             {
                $eqauthor=0;
             }
           } else 
           {
               $author=$Question{$tourid}[$qnumber]{'Authors'};
               $eqauthor=0 unless $author;
           } 
       }
       $vid{$tourid}=$vid;
       $qnumber{$tourid}=$qnumber;
       $author{$tourid}=$eqauthor ? $author : '';
     }
   
   
     $vid='';
     my $eqvid=1;
     my $eqauthor=1;
     foreach (@tours)
     {
        $vid||=$vid{$_};
        if ($vid{$_} ne $vid)
        {
           $eqvid=0;
        }
        $author||=$author{$_};
        if (!$author{$_} || ($author{$_} ne $author))
        {
           $eqauthor=0;
        }
     }
     
     print OUT "Вид:\n$vid\n\n" if $eqvid;
     print OUT "Автор:\n$author\n\n" if $eqauthor;
   
     foreach my $tour(@tours)
     {
        print OUT "Тур:\n$tourtitle{$tour}\n\n";
        print OUT "Вид:\n$vid{$tour}\n\n" if  !$eqvid;
        print OUT "Копирайт:\n$copyright{$tour}\n\n" if $copyright{$tour} && ($copyright{$tour} ne $Copyright);
        print OUT "Редактор:\n$editor{$tour}\n\n" if $editor{$tour} && ($editor{$tour} ne $Editors);
        $tourauthor=0;
        if (!$eqauthor && $author{$tour})
        { 
          print OUT "Автор:\n$author{$tour}\n\n";
          $tourauthor=1;
        }
        foreach my $q(1..$qnumber{$tour})
        {
           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]{'Authors'}."\n\n" 
                  if !$tourauthor && !$eqauthor && $Question{$tour}[$q]{'Authors'};
           print OUT  "Комментарий:\n".$Question{$tour}[$q]{'Comments'}."\n\n" 
                  if $Question{$tour}[$q]{'Comments'};
           print OUT "Источник:\n".$Question{$tour}[$q]{'Sources'}."\n\n" 
                  if $Question{$tour}[$q]{'Sources'};
           print OUT "Рейтинг:\n".$Question{$tour}[$q]{'Rating'}."\n\n" 
                  if $Question{$tour}[$q]{'Rating'};
   
        }
     }
   
     close OUT;
   
   
   
   }
   
   sub Bottom
   {
           my $output.=&Include_virtual("../dimrub/db/footer.html")||"";
           $output.=p."<center><font size=-2>Обновление: ".&Include_virtual("../dimrub/db/date")."</center></font>";
           $output.=<<EEE
   <SCRIPT LANGUAGE="JavaScript">
   function toggle(e) {
     if (e.style.display == "none") {
        e.style.display="";
     } else {
        e.style.display = "none";
    }
   }
   </SCRIPT>
   EEE
   ;
           $output.=end_html;
           return $output;
   }
   
   
 MAIN:  MAIN:
 {  {
           
         setlocale(LC_CTYPE,'russian');          setlocale(LC_CTYPE,'russian');
         my($i, $tour);          my($i, $tour);
         my($text) = (param('text')) ? 1 : 0;          my($text) = (param('text')) ? 1 : 0;
           if (param('qid') && (param('qid')=~/^\d+$/)) {
              my $destination='http://db.chgk.info/search.html';
   #               print header (-'Content-Type' => 'text/html',
   #                -'Location:'=> 'http:\\db.chgk.info');
                   Redirect($destination);
                   exit
           }
   
           if ($text) {
                   print header('text/plain');
           } else {print header;}
         my($dbh) = DBI->connect("DBI:mysql:chgk", "piataev", "")          my($dbh) = DBI->connect("DBI:mysql:chgk", "piataev", "")
                 or do {                  or do {
                         print h1("Временные проблемы") . "База данных временно не                          print h1("Временные проблемы") . "База вопросов временно не
                         работает. Заходите попозже.";                          работает. Заходите попозже.";
                         print &Include_virtual("../dimrub/db/reklama.html");                          print &Include_virtual("$reklama") if $url!~/localhost/;
                     print end_html;                      print end_html;
                         die "Can't connect to DB chgk\n";                          die "Can't connect to DB chgk\n";
                 };                  };
             my $sstr=param('sstr');
             if (param('qid')) {
                 my $sth;
                 my $qid=param('qid');
   #               if ($qid !~ /^[0-9]+$/) 
                   {
                       my ($fname,$t,$n)= split /\./ , $qid;
                       $n=$t,$t='' unless $n;
                       if ($t)
                       {
                           $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=$t");
                       }   
                       else 
                           {
                             $sth = $dbh->prepare("SELECT Id FROM Tournaments
                                        WHERE FileName = '$fname.txt'");
                           }
                       $sth->execute;
                       $tour = ($sth->fetchrow)[0];
                       $sth->finish;
                       $sth = $dbh->prepare(
                          "SELECT QuestionId FROM 
                           Questions 
                           WHERE ParentId=$tour AND 
                           Questions.Number=$n");
                           $sth->execute;
                           $qid = ($sth->fetchrow)[0];
                        my $query="SELECT Question, Answer from Questions where QuestionId=$qid";
                        $sth=$dbh->prepare($query);
                        $sth->execute;
                        $sstr= join ' ',$sth->fetchrow;
                        $sth->finish;
                        $searchin{'Question'}=1;
                        $searchin{'Answer'}=1;
                        $sstr=~tr/ёЁ/еЕ/;
                        $sstr=~s/[^йцукенгшщзхъфывапролджэячсмитьбюЙЦУКЕНГШЩЗХЪФЫВАПРОЛДЖЭЯЧСМИТЬБЮa-zA-Z0-9]/ /gi;
                        $proxysstr=$sstr;
                        $proxysstr=makeproxysstr($dbh,\$proxysstr);
                 } 
                 
           }
   
   
         if (!param('comp') and !param('sqldump') and !$text) {          if (!param('comp') and !param('sqldump') and !$text) {
            print header;             my $title="Результаты поиска на \"". ($proxysstr||$sstr) .'"' 
            print start_html(-"title"=>'Database of the questions',                                                      if ($proxysstr||$sstr);
              $title||="База вопросов";
   
              $globaloutput.=start_html(-"title"=>$title,
                    -author=>'dimrub@icomverse.com',                     -author=>'dimrub@icomverse.com',
                    -bgcolor=>'#fff0e0',                     -bgcolor=>'#fff0e0',
                                   -vlink=>'#800020');                                    -vlink=>'#800020');
                 print &Include_virtual("../dimrub/db/reklama.html");  $globaloutput.="<style>
         }  td      {font-size: x-small; font-family : sans-serif}
   th      {font-size: x-small; font-family : sans-serif}
   </style>\n";
   
                   $globaloutput.=&Include_virtual("$reklama")||'';
           }
   
          if (length ($qs)<=255 && $qs !~ /(sstr)|(rand)|(comp)|(all=)/i) {
                   my $sth=$dbh->prepare("SELECT page,times,t from hash where query=".$dbh->quote($qs));
                   $sth->execute();
                   my ($p,$times,$t)=$sth->fetchrow();
                   $sth->finish;
                   if ($p) {
                           print ".$p";
                           $dbh->disconnect;
                           exit ;
                   }
          }
   
 if ($^O =~ /win/i) {  
         $thislocale = "Russian_Russia.20866";  
 } else {  
         $thislocale = "ru_RU.KOI8-R";  
 }  
 POSIX::setlocale( &POSIX::LC_ALL, $thislocale );  
   
 if ((uc 'а') ne 'А') {print "Koi8-r locale not installed!\n"};  
   
   
         if ($text) {          if (param('hideequal')) {
                 print header('text/plain');                     my ($sth)=  $dbh -> prepare("select first, second FROM equalto");
         }                     $sth -> execute;
                      while ( my  ($first, $second)=$sth -> fetchrow)
                     {
                          $forbidden{$first}=1;
                     }
                     $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')) {
                 my ($type, $qnum) = ('', 12);                  my ($type, $qnum) = ('', 12);
                 $type .= 'Б' if (param('brain'));                  $type.=$TypeName{$_} foreach param('type');
                 $type .= 'Ч' if (param('chgk'));  #               $type .= 'Б' if (param('brain'));
                 $qnum = param('qnum') if (param('qnum') =~ /^\d+$/);      #               $type .= 'Ч' if (param('chgk'));
                   $qnum = param('qnum') if (param('qnum') =~ /^\d+$/);
                 $qnum = 0 if (!$type);                  $qnum = 0 if (!$type);
                 if (param('email') && -x $SENDMAIL &&                   my $Email;
                 open(F, "| $SENDMAIL -t -n")) {                  if (($Email=param('email')) && -x $SENDMAIL &&
                         my ($Email) = param('email');                  open(F, "| $SENDMAIL $Email")) {
                         my ($mime_type) = $text ? "plain" : "html";                          my ($mime_type) = $text ? "plain" : "html";
                         print F <<EOT;                          print F <<EOT;
 To: $Email  To: $Email
 From: olegstemanov\@mail.ru  From: olegstepanov\@mail.ru
 Subject: Sluchajnij Paket Voprosov "Chto? Gde? Kogda?"  Subject: Sluchajnij Paket Voprosov "Chto? Gde? Kogda?"
 MIME-Version: 1.0  MIME-Version: 1.0
 Content-type: text/$mime_type; charset="koi8-r"  Content-type: text/$mime_type; charset="koi8-r"
Line 1057  Content-type: text/$mime_type; charset=" Line 1953  Content-type: text/$mime_type; charset="
 EOT  EOT
                         print F &PrintRandom($dbh, $type, $qnum, $text);                          print F &PrintRandom($dbh, $type, $qnum, $text);
                         close F;                          close F;
                         print "Пакет случайно выбранных вопросов послан. Нажмите                          $globaloutput.= "Пакет случайно выбранных вопросов послан по адресу $Email. Нажмите
                         на <B>Reload</B> для получения еще одного пакета";                          на <B>Reload</B> для получения еще одного пакета";
                 } else {                  } else {
                         print &PrintRandom($dbh, $type, $qnum, $text);                          $globaloutput.= &PrintRandom($dbh, $type, $qnum, $text);
                 }                  }
         }           }
           elsif (param('authors')){            elsif (param('authors')){
                 print &PrintAuthors($dbh,param('authors'));                  $globaloutput.= &PrintAuthors($dbh,param('authors'));
         }          }
           elsif (param('qofauthor')){            elsif (param('qofauthor')){
                 &PrintQOfAuthor($dbh,param('qofauthor'));                  $globaloutput.= &PrintQOfAuthor($dbh,param('qofauthor'));
         }          }
           elsif (param('sstr')) {            elsif (param('sstr')||param('was')) {
                 &PrintSearch($dbh, param('sstr'), param('metod'));                  $globaloutput.=&PrintSearch($dbh, $sstr||' ', param('metod')||'',param('was'));
         } elsif (param('all')) {                  $dbh->do("delete from lastqueries where
                 print &PrintAll($dbh, 0);                        (TO_DAYS(NOW()) - TO_DAYS(t) >= 2) OR
                              (time_to_sec(now())-time_to_sec(t) >3600)") if $usewas && random(30)==0;
           } 
             elsif (param('qid')) {
                 $globaloutput.=&PrintSearch($dbh, $sstr||'', 'proxy');
           }
           elsif (param('getfile')){
              $globaloutput.=&writefile
           } elsif (param('all')) {
              my $destination='http://db.chgk.info/all.html';
                   Redirect($destination);
                   exit;
   #               $globaloutput.=&PrintAll($dbh, 0);
         } elsif (param('from_year') && param('to_year')) {          } elsif (param('from_year') && param('to_year')) {
                 print &PrintDates($dbh);                          $globaloutput.=&PrintDates($dbh);
         } elsif (param('comp')) {          } elsif (param('comp')) {
             print header(              $globaloutput.="Content-Type: application/octet-stream\n";
                          -'Content-Type' => 'application/x-zip-compressed; name="db.zip"',              $globaloutput.="Content-Type: application/force-download\n";
                          -'Content-Disposition' => 'attachment; filename="db.zip"'              $globaloutput.="Content-Type: application/download\n";
                          );              $globaloutput.="Content-Type: application/x-zip-compressed; name=db.zip\n";
             $tour = (param('tour')) ? param('tour') : 0;              $globaloutput.="Content-Disposition: attachment; filename=db.zip \n\n";
               $tour ||= 0;
             my (@files) = &PrintArchive($dbh, $tour);              my (@files) = &PrintArchive($dbh, $tour);
             open F, "$ZIP -j - $SRCPATH/COPYRIGHT @files |";              WriteFile($dbh,$_) foreach @files;
             print (<F>);              open F, "$ZIP -j - @files |";
               binmode(F);
               binmode(STDOUT);
               $globaloutput.= join "",<F>;
             close F;              close F;
             $dbh->disconnect;              $dbh->disconnect;
             exit;              exit;
Line 1098  EOT Line 2010  EOT
             $dbh->disconnect;              $dbh->disconnect;
             exit;              exit;
   
         } else {          } 
                 $tour = (param('tour')) ? param('tour') : 0;          elsif (!$opt_z) {
                 if ($tour !~ /^[0-9]*$/) {                  my $QuestionNumber=0;
                         my ($sth) = $dbh->prepare("SELECT Id FROM Tournaments                  my $qnum;
                         WHERE FileName = '$tour.txt'");                  if ($qnum=param('qnumber')){
                         $sth->execute;                    my ($sth) = $dbh->prepare("SELECT QuestionId FROM Questions
                         $tour = ($sth->fetchrow)[0];                       WHERE ParentId=$tour AND Number=$qnum");
                 }                    $sth->execute;
                 print &PrintTournament($dbh, $tour, param('answer'));                    $QuestionNumber=($sth->fetchrow)[0]||0;
         }                  }
                   if ($QuestionNumber) {
                     $globaloutput.= &PrintQuestion($dbh, $QuestionNumber, param('answer')||0, $qnum, 1,0,0);
   #                                        $dbh, $Id, $answer, $qnum, $title, $text
                   } else  {
                      $globaloutput.=&PrintTournament($dbh, $tour, param('answer'));
                   }
           }
           else {
                     open TS, "timestamp";
                     my $d=$dbh->quote(<TS>);
                     close TS;
                     open FF, ">${realHTMLDIR}index.html" or die "ERROR! - ${HTMLDIR}index.html\n";
                          my $o=$globaloutput;
                          $o.=&PrintTournament($dbh, 0, 0);
                          $o.=&Bottom;
                          print FF $o;
                     close FF;
                     open FF, ">${realHTMLDIR}all.html" or die "ERROR! - ${HTMLDIR}all.html\n";
                          $o=$globaloutput;
                          $o.=&PrintAll($dbh,0);
                          $o.=&Bottom;
                          print FF $o;
                          close FF;
   
   
   #                 my ($sth) = $dbh->prepare("SELECT t1.Id, t1.FileName, t1.Type, 
   #                       count(t2.Id) 
   #                     FROM Tournaments as t1, Tournaments as t2
   #                    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 
    ON t2.ParentId=t1.id WHERE t1.CreatedAt>$d GROUP BY t1.Id");
                     $sth->execute;
                     my ($Id,$fname,$type,$c);
                     while (($Id,$fname,$type,$c)=$sth->fetchrow,$Id) {
                        next unless $fname;
                        print "$fname\n";
                        $fname=~s/\.txt$//;
                        if ($type=~/Т/ || $c<=1)
                        {
                          open FF, ">$realHTMLDIR$fname-q.html" or die "ERROR! - $fname-q.html\n";
                          my $o=$globaloutput;
                          $o.=&PrintTournament($dbh, $Id, 0);
                          $o.=&Bottom;
                          print FF $o;
                          close FF;
                          open FF, ">$realHTMLDIR$fname-a.html";
                          $o=$globaloutput;
                          $o.=&PrintTournament($dbh, $Id, 1);
                          $o.=&Bottom;
                          print FF $o;
                          close FF;
                        }
                        else {
                          open FF, ">$realHTMLDIR$fname.html" or die "ERROR! - $fname-q.html\n";
                          my $o=$globaloutput;
                          $o.=&PrintTournament($dbh, $Id, 0);
                          $o.=&Bottom;
                          print FF $o;
                          close FF;
   
                        }
                     }
           }
         if (!$text) {          if (!$text) {
                 print &Include_virtual("../dimrub/db/footer.html");                  $globaloutput.=&Bottom;
                 print end_html;          }
           if (!$opt_z){ 
             print $globaloutput;
             if (($qs!~ /(rand)|(sstr)|(comp)/i) && (length $qs<=255)) {
                   $globaloutput=  $dbh->quote($globaloutput);
                   $dbh->do("insert into hash (query,page) values (".
                   $dbh->quote($qs).
                       ",$globaloutput)");
             }
         }          }
   
         $dbh->disconnect;          $dbh->disconnect;
 }  }

Removed from v.1.29  
changed lines
  Added in v.1.113


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