Diff for /db/prgsrc/db.cgi between versions 1.42 and 1.149

version 1.42, 2001/12/05 00:17:52 version 1.149, 2008/11/09 20:02:36
Line 2 Line 2
   
 use DBI;  use DBI;
 use CGI ':all';  use CGI ':all';
 use Text::Query;  #use strict;
 use strict;  my @softfields=("ïÔ ïÌÅÇÁ óÔÅÐÁÎÏ×Á");
 use Time::Local;  use Time::Local;
   my $proxyredirect=1;
 use POSIX qw(locale_h);  use POSIX qw(locale_h);
 use locale;  use locale;
 #open STDERR, ">errors1";  use vars qw($opt_z);
   use Getopt::Std;
   #my ($dbuser,$dbname,$dbpass,$dbhost);
   eval {require "dbdefs.pl";} ;
   my $url=url||'';
   my @used_stop=();
   my $showNearQuestions=0;
   $dbuser||="piataev";
   $dbname||="chgk";
   $dbpass||="";
   $dbhost||="localhost";
   getopts('z');
   $opt_z||=param("makehtml");
   my $timestamp="_timestamp.tmp";
   my $usehash=0;
   my $paramtour;
   my $withanswers=param('answer')||param('answers');
   open STDERR, ">/var/tmp/errors1";
   my $newsurl='http://news.chgk.info/';
   my $reklama="../dimrub/db/reklama.html";
   my $footer="../dimrub/db/footer.html";
   $footer="../../chgk/footer.html" if $url=~/zaba/;
   $reklama="../../chgk/reklama.html" if $url=~/zaba/;
   my $datefooter="../dimrub/db/date";
   $datefooter="../../chgk/date" if $url=~/zaba/;
   
   my $fname;
   $reklama="../reklama.html" if $opt_z;
   $footer="../footer.html" if $opt_z;
   $datefooter="../date" if $opt_z;
   my $HTMLDIR="/znatoki/dimrub/db/baza/";
   $HTMLDIR="/files/";
   my $realHTMLDIR;
   if ($^O =~ /win/i) {
    $realHTMLDIR="/html/znatoki/baza/";
   } else 
   {
     $realHTMLDIR="/home/znatoki/chgk-db/public_html/dimrub/db/files/";
   }
   
   
   my $usehtml=$opt_z||0;
   $usehtml=1;
   $usehtml=0 if $url=~/zaba/ || $url=~/localhost/;
   
   my $usewas=0;
   my $cashednumber=500;
   my $outputnumber=10;
   my ($proxyptext,$proxysstr);
 my $printqueries=0;  my $printqueries=0;
   my $qs=query_string;
   my $globaloutput;
 my %forbidden=();  my %forbidden=();
 my $debug=0; #added by R7  my $debug=0; #added by R7
 my %fieldname= (0,'Question', 1, 'Answer', 2, 'Comments', 3, 'Authors', 4, 'Sources');  my $metod=param('metod')||'';
 my %rusfieldname=('Question','÷ÏÐÒÏÓ', 'Answer', 'ïÔ×ÅÔ',   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/ && $url !~ /zaba/ && $url !~ /question\.chgk\.info/ ) {
      my $u="http://db.chgk.info/cgi-bin/db.cgi?$qs";
      Redirect ($u);
      exit;
   }
   
   if ($proxyredirect && $metod=~/proxy/ && $url !~ /localhost/ && $url !~ /bilbo/ && $url !~ /zaba/) {
      my $u="http://chgk.zaba.ru/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, 'PassCriteria', 3, 'Comments', 4, 'Authors', 5, 'Sources');
   my %rusfieldname=('Question','÷ÏÐÒÏÓ', 'Answer', 'ïÔ×ÅÔ', 'PassCriteria','úÁÞ£Ô',
                   'Comments', 'ëÏÍÍÅÎÔÁÒÉÉ', 'Authors', 'á×ÔÏÒ',                     'Comments', 'ëÏÍÍÅÎÔÁÒÉÉ', 'Authors', 'á×ÔÏÒ', 
                   'Sources', 'éÓÔÏÞÎÉË','old','óÔÁÒÙÊ','rus','îÏ×ÙÊ');                    'Sources', 'éÓÔÏÞÎÉË','old','óÔÁÒÙÊ','rus','îÏ×ÙÊ',
                     'chgk', 'þçë', 'brain', 'âÒÅÊÎ-ÒÉÎÇ','game', 'ó×ÏÑ ÉÇÒÁ', 
                     'ehruditka', 'üÒÕÄÉÔËÁ', 'beskrylka', 'âÅÓËÒÙÌËÁ', 'igp', 'éÎÔÅÒÎÅÔ'
   );
 my %searchin;  my %searchin;
 my $rl=qr/[ÊÃÕËÅÎÇÛÝÚÈßÆÙ×ÁÐÒÏÌÄÖÜÑÞÓÍÉÔØÂÀ£]/;  my $rl=qr/[ÊÃÕËÅÎÇÛÝÚÈßÆÙ×ÁÐÒÏÌÄÖÜÑÞÓÍÉÔØÂÀ£]/;
 my $RL=qr/[êãõëåîçûýúèÿüöäìïòðá÷ùæñþóíéôøâà³]/;  my $RL=qr/[êãõëåîçûýúèÿüöäìïòðá÷ùæñþóíéôøâà³]/;
 my $RLrl=qr/(?:(?:${rl})|(?:${RL}))+/;  my $RLrl=qr/(?:(?:${rl})|(?:${RL}))+/;
 my $l=qr/(?:(?:${RLrl})|(?:[\w\-]))+/;  my $l=qr/(?:(?:${RLrl})|(?:[\w\-]))+/;
 my $Ll=qr/(?:[A-Z])|(?:${RL})/;  my $Ll=qr/(?:[A-Z])|(?:${RL})/;
   my %metodchar=('rus',1,'old',2);
   
   
   
   
 my $thislocale;  
   
 $searchin{$_}=1 foreach param('searchin');  $searchin{$_}=1 foreach param('searchin');
 #$searchin{'Question'}=param('Question');  my %TypeName=('children'=>'ä', 'game'=>'ñ', 'igp'=>'é',
 #$searchin{'Answer'}=param('Answer');                'chgk'=>'þ', 'brain'=>'â', 'beskrylka'=>'ì','ehruditka'=>'ü');
 #$searchin{'Comments'}=param('Comments');  
 #$searchin{'Authors'}=param('Authors');  
 #$searchin{'Sources'}=param('Sources');  sub countz {
     my ($dbh,$type)=@_;
     
     my $sth=$dbh->prepare("select count(*) from Questions where Type LIKE '%$type%'");
     $sth->execute();
     my ($tmp)=$sth->fetchrow();
     return $tmp;
   }
   
 my $all=param('all');  my $all=param('all');
 $all=0 if lc $all eq 'no';  $all=0 if lc $all eq 'no';
 my ($PWD) = `pwd`;  my ($PWD) = `pwd` if $^O!~/win/i;
 chomp $PWD;  chomp $PWD if $PWD;
 my ($SRCPATH) = "$PWD/../dimrub/src";  my ($SRCPATH) = "/home/db-chgk/public_html/dimrub/src";
 my ($ZIP) = "/home/piataev/bin/zip";  my ($ZIP) = "/usr/bin/zip";
 my $DUMPFILE = "/tmp/chgkdump";  my $DUMPFILE = "/tmp/chgkdump";
 my ($SENDMAIL) = "/usr/sbin/sendmail";  my ($SENDMAIL) = "/usr/sbin/sendmail";
   my ($TMPDIR) = "/var/tmp";
 my ($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',
Line 49  my (%RevMonths) = Line 144  my (%RevMonths) =
          'ñÎ×', '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 header.<<EndOfHTML;
   <head><meta http-equiv="refresh" content="0; URL=$destination"></head>
   EndOfHTML
   ;
   =head
   
   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
   ;
   =cut
   }
   
   
   
   
 sub GetTournament {  sub GetTournament {
         my ($dbh, $Id) = @_;          my ($dbh, $Id) = @_;
         my (%Tournament, $field, @arr);          my (%Tournament, $field, @arr);
Line 73  sub GetTournament { Line 202  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{'QuestionId'}, $$q{'Question'},$$q{'Answer'},$$q{'PassCriteria'},$$q{'Comments'},$$q{'Authors'},$$q{'Sources'},
                   $$q{'Number'}, 
                   $$q{'Title'}, $$q{'TourTitle'}, $$q{'FileName'},$$q{'PlayedAt'},$$q{'TourNumber'}) = 
                   $sth->fetchrow;
           } else {
                   ($$q{'QuestionId'}, $$q{'Question'},$$q{'Answer'},$$q{'PassCriteria'},$$q{'Comments'},$$q{'Authors'},$$q{'Sources'},
                   $$q{'Number'})= 
                   $sth->fetchrow;
           }
   }
   
   
   
   
   sub SelectQuestions {
           my ($dbh,$q,$WithTour) = @_;
           my %q=();
   #       $_ = "QuestionId=$_" foreach @$q;
   #       my $where=join " OR ",@$q;
           my $where=join ',',@$q;
           $where &&= "QuestionId IN (".(join ',',$where).")";
           $where||=1;
           $where="($where) AND Questions.ParentId=t1.Id AND t1.ParentId=t2.Id" 
                   if $WithTour;
   
           my $query;
           if ($WithTour) {
                   $query="SELECT QuestionId, Questions.Question, Answer, PassCriteria, Comments, Authors, Sources,
                           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 QuestionId, Questions.Question, Answer, PassCriteria, Comments, Authors, Sources,
                           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 94  sub GetQuestion { Line 271  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=~s/\-q$//;
           $res=~s/\-a$//;
           $res.=$a?"-a":"-q" unless $gr;
           $res.=".html";
           $res=~s/(\#\d+)(.*)$/$2$1/;
           my $t=$res;
           $t=~s/\#.*$//;
   #       $res=~s/\.1// unless $gr ||$res=~/\.\d+$/;#-e "$realHTMLDIR$t";
           $t=$res;
           $t=~s/\#.*$//;
   #       $res=~s/\.html/-q\.html/ unless -e "$realHTMLDIR$t";
           $res="$HTMLDIR$res" unless $opt_z;
           return $res;
      } else {
           $res=$url;
           $res.=$a?"?answers=1&":"?";
           $res.="tour=$t";
   
           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 QuestionId");                  WHERE ParentId=$ParentId order by Number");
   
         $sth->execute;          $sth->execute;
   
Line 111  sub GetTourQuestions { Line 316  sub GetTourQuestions {
                 push @Questions, $arr[0];                  push @Questions, $arr[0];
         }          }
   
           $sth->finish;
         return @Questions;          return @Questions;
 }  }
   
Line 127  sub GetTours { Line 333  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  sub count
 {  {
   my ($dbh,$word)=@_;     my ($dbh,$word)=@_; 
 print "timeb=".time.br if $debug;  
   $word=$dbh->quote(uc $word);    $word=$dbh->quote(uc $word);
   my $query="SELECT number from nests,nf where $word=w1 AND w2=nf.id";    my $query="SELECT number from nests,nf where $word=w1 AND w2=nf.id";
   my $sth=$dbh->prepare($query);    my $sth=$dbh->prepare($query);
   $sth->execute;    $sth->execute;
   my @a=$sth->fetchrow;    my @a=$sth->fetchrow;
 print "timee0=".time.br if $debug;    $sth->finish;
   $a[0]||0;    $a[0]||0;
 }  }
   
Line 148  print "timee0=".time.br if $debug; Line 353  print "timee0=".time.br if $debug;
 sub printform  sub printform
 {  {
   
   my $submit=submit(-value=>'ðÏÉÓË');    my $qnumber=("&nbsp;"x10)."÷Ù×ÏÄÉÔØ ÐÏ 
   my $inputstring=textfield(-name=>'sstr',    <input type=\"text\" name=\"kvo\" value=$outputkvo size=\"3\" maxlength=\"5\">";
                          -default=>param('sstr')||'',  #textfield(-name=>'kvo',
                          -size=>50);  #                         -default=>6,
   my $fields=checkbox_group('searchin',['Question','Answer','Comments','Authors','Sources'], [grep $searchin{$_}, keys %searchin],  #                         -size=>3,
   #                         -maxlength=>5)." ×ÏÐÒÏÓÏ×";
     my $sstr=param('sstr');
     my @df=keys %searchin;
     my %checked;
     $checked{lc $_}="" foreach ('Question','Answer','PassCriteria','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','PassCriteria','Comments','Authors','Sources'], [@df],
              'false',\%rusfieldname);               'false',\%rusfieldname);
     @df=param('type');
   my $metod=radio_group(-name=>'metod',-values=>['old','rus'],    @df=('chgk','brain','igp','game','ehruditka','beskrylka') unless @df;
                        -default=>(param('metod')||'rus'),    $checked{lc $_}="checked" foreach @df;
                        -labels=>\%rusfieldname);    my $all=param('all') && param('all') eq 'yes';
   my $all=radio_group(-name=>'all',-values=>['yes','no'],  
                        -default=>(param('all')||'no'),    $checked{'all'}=$all?"checked":"";
                        -labels=>{'yes'=>'÷ÓÅ','no'=>'ìÀÂÏÅ'});    $checked{'any'}=$all?"":"checked";
     $checked{lc param('metod')}="checked";
     $checked{'rus'}=1 unless $checked{'rus'} || $checked{'old'};
   
 #################################################  #################################################
 return   start_form(-method=>'get',  return   
                        -action=>url,  <<EOT
                        -enctype=>  <form method="get" enctype="application/x-www-form-urlencoded"
                 "application/x-www-form-urlencoded"  action="/znatoki/cgi-bin/db.cgi">
 ).br.  <h2>ðÏÉÓË × ÂÁÚÅ ×ÏÐÒÏÓÏ×</h2>
 table(Tr  
 (  <input type="text" name="sstr" value="$sstr" size="30" maxlength="50"> 
   td({-valign=>'TOP'},$inputstring.$submit.p."íÅÔÏÄ: $metod".p."óÌÏ×Á: $all"),  <input type="submit" value="ðÏÉÓË"> $qnumber
   td({-valign=>'TOP'},('&nbsp;'x 8).'ðÏÌÑ:'),  <p>
   td({-valign=>'TOP'},$fields)  
 )   <table border="1" cellpadding=4 cellspacing=0>
 )  <tr>
    <th align="left" rowspan=3 width="20%"> ÷ÁÒÉÁÎÔ ÐÏÉÓËÁ:
 #$fields.  </td><td rowspan=2 colspan=3>
 #$inputstring.$submit.br.$metod.$all  <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=6><input type="radio" $checked{'rus'} name="metod" value="rus"> òÁÓÛÉÒÅÎÎÙÊ (Ó ÕÞÅÔÏÍ ÇÒÁÍÍÁÔÉËÉ, × ×ÏÐÒÏÓÁÈ ×ÓÅÈ ÔÉÐÏ×)
   </td>
   </tr><tr>
   <th align="left">éÓËÁÔØ:
   </td><td colspan=3>
   <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="PassCriteria" $checked{'passcriteria'}>úÁÞ£Ô<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>
   <!--p><i>åÓÌÉ ÐÒÉ ÐÏÐÙÔËÅ ÐÏÉÓËÁ ×ÙÄÁ£ÔÓÑ ÓÏÏÂÝÅÎÉÅ ÏÂ ÏÛÉÂËÅ, 
   ÐÏÐÒÏÂÕÊÔÅ ×ÏÓÐÏÌØÚÏ×ÁÔØÓÑ 
   <a href="http://chgk.zaba.ru/search.html">ÚÅÒËÁÌÏÍ ÂÁÚÙ</a></i-->
   </center>
   
   EOT
 .endform  .endform
 .hr  .hr
   
 }  }
   
 sub proxy  sub proxy
 {  {     
 #print "time0=".time.br if $debug;  
       my ($dbh,$ptext,$allnf)=@_;        my ($dbh,$ptext,$allnf)=@_;
         my $sstr=makeproxysstr($dbh,$ptext,$allnf);
         return russearch($dbh,$sstr,0,$allnf);
   }
   
   sub makeproxysstr {
         my ($dbh,$ptext)=@_;
       my $text=$$ptext;        my $text=$$ptext;
         POSIX::setlocale( &POSIX::LC_ALL, $thislocale );
       $text=~tr/£³/Åå/;        $text=~tr/£³/Åå/;
       $text=~s/(${RLrl})p(${RLrl})/$1p$2/gom;        $text=~s/(${RLrl})p(${RLrl})/$1p$2/gom;
       $text=~s/p(${RLrl})/Ò$1/gom;        $text=~s/p(${RLrl})/Ò$1/gom;
       $text=~s/(${RLrl})p/$1Ò/gom;        $text=~s/(${RLrl})p/$1Ò/gom;
       $text=~s/\s+/ /gmo;        $text=~s/\s+/ /gmo;
       $text=~s/[^ÊÃÕËÅÎÇÛÝÚÈßÆÙ×ÁÐÒÏÌÄÖÜÑÞÓÍÉÔØÂÀêãõëåîçûýúèÿæù÷áðòïìäöüñþóíéôøâàQWERTYUIOPASDFGHJKLZXCVBNM]/ /g;        $text=~s/[^ÊÃÕËÅÎÇÛÝÚÈßÆÙ×ÁÐÒÏÌÄÖÜÑÞÓÍÉÔØÂÀêãõëåîçûýúèÿæù÷áðòïìäöüñþóíéôøâàQWERTYUIOPASDFGHJKLZXCVBNM0-9]/ /g;
       $text=uc $text;        $text=uc $text;
       my @list= $text=~m/(?:(?:${RLrl})+)|(?:[A-Za-z0-9]+)/gom;        my @list= $text=~m/(?:(?:${RLrl})+)|(?:[A-Za-z0-9]+)/gom;
   
       my (%c, %good,$sstr);        my (%c, %good,$sstr);
       foreach (@list)        foreach (@list)
       {        {
Line 204  sub proxy Line 475  sub proxy
       my @words=sort {$c{$a}<=> $c{$b}} @list;        my @words=sort {$c{$a}<=> $c{$b}} @list;
   
 #      $good{$words[$_]}=1 foreach 0..4;  #      $good{$words[$_]}=1 foreach 0..4;
   
       foreach (@words)        foreach (@words)
       {        {
          $good{$_}=1 if $c{$_}<200;           $good{$_}=1 if $c{$_}<200 && length $_>2;
       }        }
   
       $good{$words[$_]}=0 foreach 16..$#words;        $good{$words[$_]}=0 foreach 16..$#words;
   
 #      foreach (@list)  
 #      {  
 #        if ($good{$_})  
 #        {  
 #           $good{$_}=0;  
 #           $sstr.=" $_";  
 #        }  
 #      }  
       $sstr.=" $_" foreach grep {$good{$_}} @list;        $sstr.=" $_" foreach grep {$good{$_}} @list;
 print "time05=".time.br if $debug;  
       $$ptext=$sstr;        $$ptext=$sstr;
       return russearch($dbh,$sstr,0,$allnf);        return $sstr;
 }  }
   
   
Line 243  sub russearch { Line 504  sub russearch {
             my %relevance;              my %relevance;
             my @blob;              my @blob;
             my %count;              my %count;
               my %stop_word;
           POSIX::setlocale( &POSIX::LC_ALL, $thislocale );
 $sstr=~tr/ÊÃÕËÅÎÇÛÝÚÈßÆÙ×ÁÐÒÏÌÄÖÜÑÞÓÍÉÔØÂÀ/êãõëåîçûýúèÿæù÷áðòïìäöüñþóíéôøâà/;  $sstr=~tr/ÊÃÕËÅÎÇÛÝÚÈßÆÙ×ÁÐÒÏÌÄÖÜÑÞÓÍÉÔØÂÀ/êãõëåîçûýúèÿæù÷áðòïìäöüñþóíéôøâà/;
             @qw=@w =split (' ', uc $sstr);  #           @qw=@w =split (' ', uc $sstr);
               my $ts=uc $sstr;
               @qw=@w= $ts=~m/(?:(?:${RLrl})+)|(?:[A-Za-z0-9]+)/gom;
               $query="select nf.word from nf  where number>=50000";
               $sth=$dbh->prepare($query);
               $sth->execute();
               %stop_word=();
               while (@arr = $sth->fetchrow)
                   {
                      $stop_word{$arr[0]}=1;
                   }
                   $sth->finish;
               
   
 #-----------  #-----------
             foreach $i (0..$#w) # ÚÁÐÏÌÎÑÅÍ ÍÁÓÓÉ× @nf ÎÁÞÁÌØÎÙÈ ÆÏÒÍ              foreach $i (0..$#w) # ÚÁÐÏÌÎÑÅÍ ÍÁÓÓÉ× @nf ÎÁÞÁÌØÎÙÈ ÆÏÒÍ
                            # $nf[$i] -- ÓÓÙÌËÁ ÎÁ ÍÁÓÓÉ× ×ÏÚÍÏÖÎÙÈ                             # $nf[$i] -- ÓÓÙÌËÁ ÎÁ ÍÁÓÓÉ× ×ÏÚÍÏÖÎÙÈ
                            # ÎÁÞÁÌØÎÙÈ ÆÏÒÍ ÓÌÏ×ÏÆÏÒÍÙ $i                             # ÎÁÞÁÌØÎÙÈ ÆÏÒÍ ÓÌÏ×ÏÆÏÒÍÙ $i
             {              {
                   (push @used_stop, uc $w[$i]),next if $stop_word{uc $w[$i]};
                 $qw= $dbh->quote (uc $w[$i]);                  $qw= $dbh->quote (uc $w[$i]);
   
                 $query="  select distinct w2 from nests                  $query="  select distinct w2 from nests
                                 where w1=$qw";                                  where w1=$qw";
 print "$query",br if $printqueries;  
                 $sth=$dbh -> prepare($query);                  $sth=$dbh -> prepare($query);
                 $sth -> execute;                  $sth -> execute;
                 @{$nf[$i]}=();                  @{$nf[$i]}=();
Line 263  print "$query",br if $printqueries; Line 538  print "$query",br if $printqueries;
                 {                  {
                    push (@{$nf[$i]},$arr[0])                     push (@{$nf[$i]},$arr[0])
                 }                  }
                   $sth->finish;
             }              }
   
   
Line 285  print "$query",br if $printqueries; Line 561  print "$query",br if $printqueries;
   
             my $kvo=0;              my $kvo=0;
             push @$allnf, @{$_} foreach @nf;              push @$allnf, @{$_} foreach @nf;
             print "nf=@$allnf" if $printqueries;  
   
             foreach $i (0..$#w) #ÚÁÐÒÏÓÙ × ÂÁÚÕ...              foreach $i (0..$#w) #ÚÁÐÒÏÓÙ × ÂÁÚÕ...
             {              {
Line 295  print "$query",br if $printqueries; Line 570  print "$query",br if $printqueries;
   
   
   
               $_= " word2question.word=".$_. ' ' foreach @arr;                $_= " word2question.word=$_" foreach @arr;
               $_= " nf.id=".$_. ' ' foreach @arr1;                $_= " nf.id=".$_. ' ' foreach @arr1;
 #              @arr=(0) unless @arr;  #              @arr=(0) unless @arr;
               $query="select questions from word2question where". (join ' OR ', @arr);                $query="select questions from word2question where (". (join ' OR ', @arr).") ";
 print STDERR "!$query\n",br if $printqueries;  
   
               $sth=$dbh -> prepare($query);                $sth=$dbh -> prepare($query);
               $sth->execute;                $sth->execute;
Line 309  print STDERR "!$query\n",br if $printque Line 583  print STDERR "!$query\n",br if $printque
               {                {
                 @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 318  print "$query\n",br if $printqueries; Line 592  print "$query\n",br if $printqueries;
               {                {
                 $frequence[$i]+=$arr[0];                  $frequence[$i]+=$arr[0];
               }                }
                 $sth->finish;
   
   
               if (@blob < 4)                if (@blob < 4)
Line 338  print "$query\n",br if $printqueries; Line 612  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;
                       $field=$fieldname{$field & 0xF};
                     if ($searchin{$field})                      if ($searchin{$field})
                     {                      {
                       push @{$tasksof{$i}{$number}}, $wordnumber;                        push @{$tasksof{$i}{$number}}, $wordnumber;
Line 357  print "$query\n",br if $printqueries; Line 632  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)
            {             {
               $count{$_}++ foreach keys %{$tasksof{$sf}};                  foreach (keys %{$tasksof{$sf}})
                   {
                        next if $forbidden{$_};
                        $count{$_}++ 
                   }
   
            }             }
              @tasks= ($all ? (grep {$count{$_}==$kvo} keys %count) :               @tasks= ($all ? (grep {$count{$_}==$kvo} keys %count) :
                              keys %count) ;                               keys %count) ;
   
   
 print "\n\$#tasks=",$#tasks,br if $printqueries;  
 ############ óÏÒÔÉÒÏ×ËÁ ÎÁÊÄÅÎÎÙÈ ×ÏÐÒÏÓÏ×  ############ óÏÒÔÉÒÏ×ËÁ ÎÁÊÄÅÎÎÙÈ ×ÏÐÒÏÓÏ×
   
 foreach (keys %wordsof)  foreach (keys %wordsof)
Line 377  foreach (keys %wordsof) Line 655  foreach (keys %wordsof)
   
 @tasks=sort {$relevance{$b}<=>$relevance{$a}} @tasks;  @tasks=sort {$relevance{$b}<=>$relevance{$a}} @tasks;
   
   
 ############  ############
   
 print "tasks=@tasks" if $printqueries;  
   
 #print "$_ $relevance{$_} | " foreach @tasks;  
 #print br;  
 print "allnf=@$allnf",br if $printqueries;  
         return  @tasks;          return  @tasks;
 }  }
   
Line 439  sub Search { Line 712  sub Search {
         my $sstr=$$s;          my $sstr=$$s;
         my (@arr, @Questions, @fields);          my (@arr, @Questions, @fields);
         my (@sar, $i, $sth,$where,$query);          my (@sar, $i, $sth,$where,$query);
         my $ip=$ENV{'REMOTE_ADDR'};  
   
         $ip=$dbh->quote($ip);  
         $query=  
           "INSERT into queries (query,metod,searchin,ip)  
                     values (". $dbh->quote($sstr).', '.  
                     $dbh->quote($metod) . ', ' .  
                     $dbh->quote(join ' ', grep $searchin{$_}, keys %searchin)  .   
               ", $ip)";  
 print $query if $printqueries;  
         $dbh -> do ($query);  
         if ($metod eq 'rus')          if ($metod eq 'rus')
         {          {
              my @tasks=russearch($dbh,$sstr,$all,$allnf);               my @tasks=russearch($dbh,$sstr,$all,$allnf);
Line 457  print $query if $printqueries; Line 719  print $query if $printqueries;
         }          }
         elsif ($metod eq 'proxy')          elsif ($metod eq 'proxy')
         {          {
 #         $searchin{'question'}=1;  
 #         $searchin{'answer'}=1;  
           my @task=proxy($dbh,$s,$allnf);            my @task=proxy($dbh,$s,$allnf);
 #         $$s=$sstr;  
           return @task            return @task
         }          }
   
Line 469  print $query if $printqueries; Line 728  print $query if $printqueries;
 ###Simple and advanced query processing. Added by R7  ###Simple and advanced query processing. Added by R7
         if ($metod eq 'simple' || $metod eq 'advanced')          if ($metod eq 'simple' || $metod eq 'advanced')
         {          {
           foreach (qw/Question Answer Sources Authors Comments/) {            foreach (qw/Question Answer PassCriteria Sources Authors Comments/) {
                 if (param($_)) {                  if (param($_)) {
                         push @fields, $_;                          push @fields, $_;
                 }                  }
            }             }
   
            @fields=(qw/Question Answer Sources Authors Comments/) unless scalar @fields;             @fields=(qw/Question Answer PassCriteria Sources Authors Comments/) unless scalar @fields;
            my $fields=join ",", @fields;             my $fields=join ",", @fields;
            my $q=new Text::Query($sstr,             my $q=new Text::Query($sstr,
                  -parse => 'Text::Query::'.                   -parse => 'Text::Query::'.
Line 487  print $query if $printqueries; Line 746  print $query if $printqueries;
            $where=      $$q{'matchexp'};             $where=      $$q{'matchexp'};
            $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 (param('searchin')) {            foreach (param('searchin')) {
 #               if (param($_)) {  #               if (param($_)) {
                         push @fields, "IFNULL($_, '')";                          push @fields, "IFNULL($_, '')";
Line 504  print $query if $printqueries; Line 761  print $query if $printqueries;
           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;     my $query;
                $query="SELECT QuestionId FROM Questions                 $query="SELECT QuestionId FROM Questions
                 WHERE $f LIKE $sstr ORDER BY QuestionId";                  WHERE ($f LIKE $sstr) AND (".&makewhere.") 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)
   
Line 525  print $query if $printqueries; Line 783  print $query if $printqueries;
         while (@arr = $sth->fetchrow) {          while (@arr = $sth->fetchrow) {
                 push @Questions, $arr[0] unless $forbidden{$arr[0]};                  push @Questions, $arr[0] unless $forbidden{$arr[0]};
         }          }
           $sth->finish;
 print "@Questions" if $printqueries;          
         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 ='$_ä') 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 546  sub NoCase { Line 817  sub NoCase {
 }  }
   
 sub PrintList {  sub PrintList {
    my ($dbh,$Questions,$shablon)=@_;     my ($dbh,$Questions,$shablon,$was)=@_;
           my $Output;
         my $first=param('first') ||1;          my $first=param('first') ||1;
         my $kvo=param('kvo') ||30;          $first=$first-($first-1)%$outputkvo;
           my $fkvo=param('fkvo')||($#$Questions+1);
         $first=$first-($first-1)%$kvo;          my $last=$first+$outputkvo-1;
         my $last=$first+$kvo-1;          $last=$fkvo if $fkvo<$last;
         $last=scalar @$Questions if scalar @$Questions <$last;  
         my($f,$l);          my($f,$l);
         my $nav='';          my $nav='';
         my $qs=query_string;          my $qs=query_string;
         $qs=~s/\;/\&/g;          $qs=~s/\;/\&/g;
         $qs=~s/\&first\=[^\&]+//g;          $qs=~s/\&first\=[^\&]+//g;
           my $sstr=param('sstr')||'';
           $qs=~s/sstr=[^\&]+/sstr=$sstr/;
         if ($first>$kvo*3+1)          if ($usewas) {
                   $qs=~s/\&was=[^\&]+//;
                   $qs.="&was=$was" if $was;
                   $qs.="&fkvo=$fkvo" if $was;
           }
           if ($first>$outputkvo*3+1)
         {          {
            $nav.=             $nav.=
             ("&nbsp;"x4).              ("&nbsp;"x4).
             a({href=>url."?".$qs."\&first=1"},"<<").("&nbsp;"x4).              a({href=>$url."?".$qs."\&first=1"},"<<").("&nbsp;"x4).
             a({href=>(url."?".$qs."\&first=".($first-$kvo))},"<").("&nbsp;"x4)              a({href=>($url."?".$qs."\&first=".($first-$outputkvo))},"<").("&nbsp;"x4)
         }          }
   
         else {$nav.='&nbsp;'x15;}          else {$nav.='&nbsp;'x15;}
   
      my ($fprint,$lprint);       my ($fprint,$lprint);
      my $llprint=$#$Questions- ($#$Questions+1)%$kvo+2;       my $llprint=$fkvo- ($fkvo)%$outputkvo+1; #
      if ($#$Questions+1<=$kvo*7)       if ($fkvo<=$outputkvo*7)
      {         $fprint=1;       {         $fprint=1;
                $lprint=$llprint;                 $lprint=$llprint;
      }       }
      elsif ($first>$kvo*3 && $#$Questions+1-$first>$kvo*3)       elsif ($first>$outputkvo*3 && $fkvo-$first>$outputkvo*3)
      {       {
        $fprint=$first-$kvo*3;         $fprint=$first-$outputkvo*3;
        $lprint=$first+$kvo*3;         $lprint=$first+$outputkvo*3;
      }        } 
      elsif  ($first<=$kvo*3)       elsif  ($first<=$outputkvo*3)
      {       {
         $fprint=1; $lprint=6*$kvo+1;          $fprint=1; $lprint=6*$outputkvo+1;
      }       }
      else       else
      {        { 
            $lprint=$llprint;             $lprint=$llprint;
            $fprint=$lprint-$kvo*6             $fprint=$lprint-$outputkvo*6
      }       }
                     
 #        my $fprint=($first>$kvo*3) ? $first-$kvo*3 : 1;  #        my $fprint=($first>$outputkvo*3) ? $first-$outputkvo*3 : 1;
 #        my $lprint=$#$Questions+1-$fprint>$kvo*7 ? $kvo*7 :$#$Questions+1;  #        my $lprint=$#$Questions+1-$fprint>$outputkvo*7 ? $outputkvo*7 :$#$Questions+1;
 #        if ($lprint-$fprint<$kvo*6 && $fprint>1)  #        if ($lprint-$fprint<$outputkvo*6 && $fprint>1)
 #        {  #        {
 #            $fprint=$lprint-$kvo*6;  #            $fprint=$lprint-$outputkvo*6;
 #            $fprint=1 if ($fprint<=0)   #            $fprint=1 if ($fprint<=0) 
 #        }  #        }
   
   
   
         for($f=$fprint; $f<=$lprint; $f+=$kvo)          for($f=$fprint; $f<=$lprint; $f+=$outputkvo)
         {          {
 #         next if $first-$f>$kvo*3;  #         next if $first-$f>$outputkvo*3;
           $l=$f+$kvo-1;            $l=$f+$outputkvo-1;
           $l=$#$Questions+1 if $l>$#$Questions+1;            $l=$fkvo if $l>$fkvo+1;
           if ($f==$first) {$nav.="[$f-$l] ";}            if ($f==$first) {$nav.="[$f-$l] ";}
           else {            else {
                   $nav.= "[".a({href=>(url."?".$qs."\&first=$f")},"$f-$l")."] ";}                    $nav.= "[".a({href=>($url."?".$qs."\&first=$f")},"$f-$l")."] ";}
         }          }
         if ($lprint+$kvo<$#$Questions)          if ($lprint+$outputkvo<$fkvo)
         {          {
            $nav.=             $nav.=
             ("&nbsp;"x4).              ("&nbsp;"x4).
             a({href=>(url."?".$qs."\&first=".($first+$kvo))},">").("&nbsp;"x4).              a({href=>($url."?".$qs."\&first=".($first+$outputkvo))},">").("&nbsp;"x4).
             a({href=>url."?".$qs."\&first=$llprint"},">>").("&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);
           my $qq;
           my @Q;
           for (0..$#q) {
                   %{$Q[$_]}=();
                   fetchquestion($sth,$Q[$_],1);
                   $q{$Q[$_]{'QuestionId'}}=$Q[$_];
           }
   
   
         print "$nav".br."\n";  
         for (my $i = $first; $i <= $last; $i++) {          for (my $i = $first; $i <= $last; $i++) {
                 my $output = &PrintQuestion($dbh, $$Questions[$i-1], 1, $i, 1);                  my $q=$q{$$Questions[$i-1]};
                 if (param('metod') eq 'rus' || param('metod') eq 'proxy')                  my $output;
                   $output = &PrintQuestion($dbh, $q, 1, 0, 1,$text,1  );
   #                if (param('metod') && (param('metod') eq 'rus' || param('metod') eq 'proxy'))
                 {                  {
                      $output=~s/\b($shablon)\b/\<strong\>$1\<\/strong\>/gi;                       $output=~s/\b($shablon)\b/\<strong\>$1\<\/strong\>/gi;
                 } else {  
                      $output=~s/($shablon)/\<strong\>$1\<\/strong\>/gi;                       $output=~s/($shablon)/\<strong\>$1\<\/strong\>/gi;
                 }                  }
                 print $output;                  $Output.= $output;
         }          }
           $sth->finish;
   
           $Output.= "$nav".br."\n";
         print "$nav".br."\n";          return $Output;
   
 }  }
   
 sub PrintSearch {  sub PrintSearch {
         my ($dbh, $sstr, $metod) = @_;          my $Output='';
         print h2("ðÏÉÓË × ÂÁÚÅ ×ÏÐÒÏÓÏ×");          my ($dbh, $sstr, $metod,$was) = @_;
         print printform;          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;
           $_="\"$_\"" foreach @used_stop;
           $Output.= p. (join ', ',@used_stop) ." ignored".p if @used_stop;
         my ($output, $i, $suffix, $hits) = ('', 0, '', $#Questions + 1);          my ($output, $i, $suffix, $hits) = ('', 0, '', $#Questions + 1);
   
         my $shablon;          my $shablon;
Line 653  sub PrintSearch { Line 973  sub PrintSearch {
            $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 661  print "$query" if $printqueries; Line 980  print "$query" if $printqueries;
            {             {
              push @shablon,"(?:$arr[0])";               push @shablon,"(?:$arr[0])";
            }             }
              $sth->finish;
            $shablon= join "|", @shablon;             $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 = 'Ê';
Line 678  print "$query" if $printqueries; Line 998  print "$query" if $printqueries;
                 $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;          my @sar;
         if ($metod ne 'rus')           if ($metod ne 'rus') 
         {          {
           (@sar) = split(' ', $sstr);            my $ss=$sstr;
             (@sar) = split(' ', $ss);
             s/(\W)/\\$1/g foreach (@sar);
           $shablon=join "|",@sar;            $shablon=join "|",@sar;
         }          }
         PrintList($dbh,\@Questions,$shablon);          $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 $t=time;
    my (@Questions) = &Get12Random($dbh, $type, $num);     my (@Questions) = &Get12Random($dbh, $type, $num);
         my ($output, $i) = ('', 0);  
   
           my ($output, $i) = ('', 0);
   #$output.="time=".(time-$t).p;
         if ($text) {          if ($text) {
                 $output .= "    $num ÓÌÕÞÁÊÎÙÈ ×ÏÐÒÏÓÏ×.\n\n";                  $output .= "    $num ÓÌÕÞÁÊÎÙÈ ×ÏÐÒÏÓÏ×.\n\n";
         } else {          } else {
                 $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, $Questions[$i], 1, $i + 1, 0, $text);                          &PrintQuestion($dbh, \%q, $answer, $i + 1, 0, $text,1);
                           push @answers, $q{'Answer'};
         }          }
           $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;          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 {
    my ($dbh, $Id, $answer) = @_;     my ($dbh, $Id, $answer) = @_;
         my (%Tournament, @Tours, $i, $list, $qnum, $imgsrc, $alt,          my (%Tournament, @Tours, $i, $list, $qnum, $imgsrc, $alt,
Line 725  sub PrintTournament { Line 1075  sub PrintTournament {
   
         %Tournament = &GetTournament($dbh, $Id) if ($Id);          %Tournament = &GetTournament($dbh, $Id) if ($Id);
   
         my ($URL) = $Tournament{'URL'};          my ($URL) = $Tournament{'URL'}||'';
           $URL=~s/http:\/znatoki\/boris\/reports\//$newsurl/ if $url=~/kulichki/ || $url=~/db.chgk.info/;
           $URL=~s/\/znatoki\/boris\/reports\//$newsurl/ if url=~/kulichki/ || $url=~/db.chgk.info/;
         my ($Info) = $Tournament{'Info'};          my ($Info) = $Tournament{'Info'};
         my ($Copyright) = $Tournament{'Copyright'};          my ($Copyright) = $Tournament{'Copyright'};
           my $fname=$Tournament{'FileName'};
         @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 {
Line 750  sub PrintTournament { Line 1103  sub PrintTournament {
   
                                 $output .= h2({align=>"center"},                                  $output .= h2({align=>"center"},
                                         "$title") . p . "\n";                                          "$title") . p . "\n";
                                  $output.=&PrintEditor(\%Tournament);
                                 last;                                  last;
                         };                          };
                         /ô/ && do {                          /ô/ && do {
Line 757  sub PrintTournament { Line 1111  sub PrintTournament {
                         };                          };
                 }                  }
         } else {          } else {
                 my ($qnum) = GetQNum($dbh);                  my ($qnum) = GetQNum($dbh,0);
                 $output .= h2("âÁÎË ÷ÏÐÒÏÓÏ×: $qnum ×ÏÐÒÏÓÏ×") . p . "\n";                  my ($qnum1) = GetQNum($dbh,1);
                   $output .= h2("âÁÚÁ ×ÏÐÒÏÓÏ×").
                    h3("$qnum ÚÁÐÉÓ".&Suffix2($qnum).
                    " (ÕÎÉËÁÌØÎÙÈ $qnum1)");
   
   #                h4("<table>".
   #                Tr(td("éÚ ÎÉÈ:"), td("÷ÏÐÒÏÓÏ× þçë: ".countz($dbh,'þ'))).               
   #                Tr(td("&nbsp;"), td("÷ÏÐÒÏÓÏ× ÄÌÑ ÂÒÅÊÎÁ: ".countz($dbh,'â'))).                 
   #                Tr(td("&nbsp;"), td("÷ÏÐÒÏÓÏ× ÄÌÑ þçë É ÂÒÅÊÎÁ: ".countz($dbh,'þâ'))).          
   #                Tr(td("&nbsp;"), td("éÎÔÅÒÎÅÔ-×ÏÐÒÏÓÏ×: ".countz($dbh,'é'))).           
   #                Tr(td("&nbsp;"), td("âÅÓËÒÙÌÏË: ".countz($dbh,'ì'))).
   #                Tr(td("&nbsp;"),td("úÁÄÁÎÉÊ ÄÌÑ ó×ÏÅÊ éÇÒÙ: ".countz($dbh,'ñ'))).
   #                Tr(td("&nbsp;"),td("üÒÕÄÉÔÏË: ".countz($dbh,'ü'))))."</table>"
         }          }
   
         for ($i = 0; $i <= $#Tours; $i++) {          for ($i = 0; $i <= $#Tours; $i++) {
Line 776  sub PrintTournament { Line 1142  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 784  sub PrintTournament { Line 1151  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"},                                  " " . 
                                   img({src=>$imgsrc, alt=>$alt})
                                   . " " . a({href=>tourhref($textid,0,1)},
                                 $Tournament{'Title'}. " ".                                  $Tournament{'Title'}. " ".
                                           $Tournament{'PlayedAt'}) . $qnum);                                            ($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));
         }          }
   
         if ($Copyright) {          if ($Copyright) {
                 $output .= p("ëÏÐÉÒÁÊÔ: " .   $Copyright);                  $output .= p("ëÏÐÉÒÁÊÔ: " .   $Copyright);
         }          }
   
   
   
         if ($Info) {          if ($Info) {
                 $output .= p($Info);                  $output .= p($Info);
         }          }
   
           $output.=p("<a href='/dbxml.php?tour=".param('tour')."'>XML</a>");
           
           
         return $output;          return $output;
 }  }
   
Line 831  sub Suffix { Line 1218  sub Suffix {
         return $suffix;          return $suffix;
 }  }
   
   
   sub Suffix1 {
           my ($qnum) = @_;
           my ($suffix) = 'Ñ' if $qnum =~ /[234]$/;
          $suffix = 'Å' if $qnum =~ /1$/;
          $suffix = 'Ê' if $qnum =~ /[567890]$/ || $qnum =~ /1.$/;
           return $suffix;
   }
   
   sub Suffix2 {
           my ($qnum) = @_;
           my ($suffix) = 'É' if $qnum =~ /[234]$/;
          $suffix = 'Ø' if $qnum =~ /1$/;
          $suffix = 'ÅÊ' if $qnum =~ /[567890]$/ || $qnum =~ /1.$/;
           return $suffix;
   }
   
 sub IsTour {  sub IsTour {
         my ($dbh, $Id) = @_;          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 848  sub PrintTour { Line 1264  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,$text,1);
         }          }
           $sth->finish;
         $output .= hr({-'align'=>'center', -'width'=>'80%'});          $output .= hr({-'align'=>'center', -'width'=>'80%'});
   
         if ($Tournament{'URL'}) {          if ($Tournament{'URL'}) {
Line 881  sub PrintTour { Line 1303  sub PrintTour {
                 $output .= p($Tournament{'Info'});                  $output .= p($Tournament{'Info'});
         }          }
   
           if ($Tour{'Info'}) {
                   $output .= p($Tour{'Info'});
           }
   
   
           $output.=p("<a href='/dbxml.php?tour=".param('tour')."'>XML</a>");
   
           my $n=$Tour{'Number'};
         if ($answer == 0) {          if ($answer == 0) {
                   my $nn=".$n";
                   $nn="" if ($n==1 && !&IsTour($dbh, $Tour{'ParentId'}, $n + 1));
                   
                 $bottom .=                  $bottom .=
                         "[" . a({href=>url . "?tour=$Id&answer=1"}, "ÏÔ×ÅÔÙ") .  "] " . br;                          "[" . a({href=>tourhref("$fname$nn",1)}, 
                            "ÏÔ×ÅÔÙ") .  "] " . br;
         }          }
         if (&IsTour($dbh, $Id - 1)) {          if ($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)},
                         "ÐÒÅÄÙÄÕÝÉÊ ÔÕÒ Ó ÏÔ×ÅÔÁÍÉ") . "] " . 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 912  sub PrintTour { Line 1345  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 {
               if ($header=~/ëÏÍÍÅÎÔÁÒ/)
               {
                   $value=~s/^\s*$_[\.:]/p."\n".strong("$_").":"/me foreach @softfields;
               }
   
             $value =~ s/^\s+/<br>&nbsp;&nbsp;&nbsp;&nbsp;/mg;              $value =~ s/^\s+/<br>&nbsp;&nbsp;&nbsp;&nbsp;/mg;
               $value =~ s/(\s+)-+(\s+)/$1&#0150;$2/mg;
               $value =~ s/\s+\&#0150/&nbsp;\&#0150/mg 
                           if $value !~ /^\|/;
             $value =~ s/^\|([^\n]*)/<pre>$1<\/pre>/mg;              $value =~ s/^\|([^\n]*)/<pre>$1<\/pre>/mg;
               $value =~ s/(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;
         }          }
   
           if ($value=~/^\s*(<p.*?>)?\s*<strong/) {
                   return $text ? "$value\n\n" :
                           $value . p . "\n";
           }
         return $text ? "$header:\n$value\n\n" :          return $text ? "$header:\n$value\n\n" :
                 strong("$header: ") . $value . p . "\n";                  strong("$header: ") . $value . p . "\n";
 }  }
Line 925  sub PrintField { Line 1375  sub PrintField {
 # 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) = &GetQuestion($dbh, $Id);          my $fname;
         if (!$text) {          my (%Question);
                 $output .= hr({width=>"50%"});          if ($h) {
             %Question=%$Id;
           } 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) {
                           $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 .=          $output.= "<a NAME=\"$qnum\">" unless $text;
                 &PrintField("÷ÏÐÒÏÓ $qnum", $Question{'Question'}, $text);  
   
         if ($answer) {          if ($answer>=0) {$output .=
                   &PrintField("÷ÏÐÒÏÓ $qnum", $Question{'Question'}, $text);}
           else {$output .="$qnum. "}
           if ($answer==1|| $answer==-1) {
                 $output .=                  $output .=
                         &PrintField("ïÔ×ÅÔ", $Question{'Answer'}, $text);                          &PrintField("ïÔ×ÅÔ", $Question{'Answer'}, $text);
                   if ($Question{'PassCriteria'} ) {
                     $output .=
                           &PrintField("úÁÞ£Ô", $Question{'PassCriteria'}, $text);
                   }
   
                 if ($Question{'Authors'}) {                  if ($Question{'Authors'} ) {
                       my $q=$Question{'Authors'};                        my $q=$Question{'Authors'};
   ###á÷ôïòá!!
   #                     my $sth=$dbh->prepare("select Authors.CharId,Name, Surname, Nicks from Authors, A2Q
   #                                  where Authors.Id=Author And Question=$Id");
   #                       $sth->execute;
   #                       my ($AuthorId,$Name, $Surname,$other,$Nicks);
   #                      if (!$text) {
   #                       while ((($AuthorId,$Name, $Surname,$Nicks)=$sth->fetchrow),$AuthorId)
   #                       {
   #                          my ($firstletter)=$Name=~m/^./g;
   #                          $Name=~s/\./\\\./g;
   #                          $Name=~s/£/[Å£]/g;
   #                          $Surname=~s/£/[Å£]/g;
   #                           my $sha="(?:$Name\\s+$Surname)|(?:$Surname\\s+$Name)|(?:$firstletter\\.\\s*$Surname)|(?:$Surname\\s+$firstletter\\.)|(?:$Surname)";
   #                           if ($Nicks)
   #                           {
   #                             $Nicks=~s/^\|//;
   #                             foreach (split /\|/, $Nicks)
   #                             {
   #                               s/\s+/ /g;
   #                               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);
   
                       my $sth=$dbh->prepare("select Authors.Id,Name, Surname, Nicks from Authors, A2Q                  }
                                  where Authors.Id=Author And Question=$Id");  
                       $sth->execute;  
                       my ($AuthorId,$Name, $Surname,$other,$Nicks);  
   
                       while ((($AuthorId,$Name, $Surname,$Nicks)=$sth->fetchrow),$AuthorId)  
                       {  
                         my ($firstletter)=$Name=~m/^./g;  
                          $Name=~s/\./\\\./g;  
                           my $sha="(?:$Name\\s+$Surname)|(?:$Surname\\s+$Name)|(?:$firstletter\\.\\s*$Surname)|(?:$Surname\\s+$firstletter\\.)|(?:$Surname)|(?:$Name)";  
                           if ($Nicks)  
                           {  
                             $Nicks=~s/^\|//;  
                             foreach (split /\|/, $Nicks)  
                             {  
                               s/\s+/ /g;  
                               s/\s+$//;  
                               s/ /\\s+/g;  
                               s/\./\\\./g;  
                               if (s/>$//) {$sha="$sha|(?:$_)"}  
                               else        {$sha="(?:$_)|$sha"}  
                             }  
                           }  
                           $q=~s/($sha)/a({href=>url."?qofauthor=$AuthorId"},$1)/ei;  
                       }  
   
                         $output .= &PrintField("á×ÔÏÒ(Ù)", $q, $text);                  if ($Question{'Sources'}) {
                           $output .= &PrintField("éÓÔÏÞÎÉË(É)", $Question{'Sources'}, $text);
                   }
   
 #                        $output.= &PrintField("äÒÕÇÉÅ ×ÏÐÒÏÓÙ", $other);                  if ($Question{'Comments'}) {
                           $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{'PassCriteria'}) {
                           $output .= &PrintField("úÁÞ£Ô", $Question{'PassCriteria'}, $text);
                 }                  }
   
                 if ($Question{'Sources'}) {                  if ($Question{'Sources'}) {
Line 994  sub PrintQuestion { Line 1505  sub PrintQuestion {
                 if ($Question{'Comments'}) {                  if ($Question{'Comments'}) {
                         $output .= &PrintField("ëÏÍÍÅÎÔÁÒÉÉ", $Question{'Comments'}, $text);                          $output .= &PrintField("ëÏÍÍÅÎÔÁÒÉÉ", $Question{'Comments'}, $text);
                 }                  }
   
   
   
   $output.="</span>"
   
         }          }
         $output.=br.a({href=> url."?metod=proxy&qid=$Id"}, 'âÌÉÚËÉÅ ×ÏÐÒÏÓÙ').p          $output=~s/\(pic: ([^\)]*)\)/<p><img src="\/znatoki\/images\/db\/$1"><p>/g unless $text;
              if $answer;          $output=~s/\(aud: ([^\)]*)\)/<p><embed src="\/znatoki\/sounds\/db\/$1"><\/embed><p>/g unless $text;
   
           $output=~s/›/\&iuml;/g;
           $output=~s/“/\&Iuml;/g;
   
           $paramtour||=param("tour");
           $fname=$fname.".$Question{'TourNumber'}" if $fname && $Question{'TourNumber'};
   $fname||=param('tour');
           my $qid=$fname ? ($fname.".$Question{'Number'}" ): '';
   
           $output.=br.a({href=> "/search/"."?metod=proxy&
   qid=$qid"}, 'âÌÉÚËÉÅ ×ÏÐÒÏÓÙ').p
                if $answer>0 && !$text && $qid && $showNearQuestions;
         return $output;          return $output;
 }  }
   
 # Returns the total number of questions currently in the DB.  # Returns the total number of questions currently in the DB.
 sub GetQNum {  sub GetQNum {
         my ($dbh) = @_;          my ($dbh,$x) = @_;
         my ($sth) = $dbh->prepare("SELECT COUNT(*) FROM Questions");          my ($sth) = $dbh->prepare("SELECT COUNT(*) FROM Questions");
         $sth->execute;          $sth->execute;
         return ($sth->fetchrow)[0];          my $tmp=($sth->fetchrow)[0];
           $sth->finish;
           ($sth)=  $dbh -> prepare("select distinct count(first) FROM equalto");
                      $sth -> execute;
           my ($c)=$sth->fetchrow;
   
   #                  $i++  while ( my  ($first, $second)=$sth -> fetchrow)
   #                  {
   #                       $forbidden{$first}=1;
   #                  }
                     $sth->finish;
   
           return $tmp-($x?$c:0);
 }  }
 sub GetMaxQId {  sub GetMaxQId {
         my ($dbh) = @_;          my ($dbh) = @_;
         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 1021  sub Get12Random { Line 1564  sub Get12Random {
         my ($qnum) = &GetMaxQId($dbh);          my ($qnum) = &GetMaxQId($dbh);
         my (%chosen);          my (%chosen);
         srand;          srand;
           my $where=0;
           my $r=int (rand(10000));
           my $w1=$r<5000? "QuestionId<50000 ":"QuestionId>=50000";
           $w1=1 if $url=~/zaba/;
           $w1=1 if $type!~/þ/;
           foreach (split '', $type)
           {
              $where.= " OR (Type ='$_') OR (Type ='$_ä') ";
           }
           $where.= "OR (Type='þâ')" if ($type=~/þ|â/);
   
    for ($i = 0; $i < $num; $i++) {  #   $q="select QuestionId, QuestionId/$r-floor(QuestionId/$r) as val 
        do {  #       from Questions where $where order by val limit $num";
            $q = int(rand($qnum));  # ëÏÇÄÁ ÎÁ ËÕÌÉÞËÁÈ ÐÏÑ×ÉÔÓÑ mysql >=3.23 ÎÁÄÏ ÚÁÍÅÎÉÔØ ÎÁ order by rand();
            $sth = $dbh->prepare("SELECT Type FROM Questions     $q="select QuestionId from Questions where ($w1) AND ($where) order by rand() limit $num";
                                 WHERE QuestionId=$q");  
            $sth->execute;  
            $t = ($sth->fetchrow)[0];     $sth=$dbh->prepare($q);
        } until !$chosen{$q} && $t && $type =~ /[$t]/;     $sth->execute;
        $chosen{$q} = 'y';     while (($i)=$sth->fetchrow)
        push @questions, $q;     {
         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 "\n<!--#include virtual=\"$fn\"-->\n" if ($opt_z);
         open F , $fn          open F , $fn
                 or return; #die "Can't open the file $fn: $!\n";                  or return ""; #die "Can't open the file $fn: $!\n";
   
         while (<F>) {          while (<F>) {
                 if (/<!--#include/o) {                  if (/<!--#include/o) {
                         s/<!--#include virtual="\/(.*)" -->/&Include_virtual($1)/e;                          s/<!--#include virtual="\/?([^\/].*)" -->/&Include_virtual($1)/e;
                 }                  }
                 if (/<!--#exec/o) {                  if (/<!--#exec/o) {
                         s/<!--#exec.*cmd\s*=\s*"([^"]*)".*-->/`$1`/e;                          s/<!--#exec.*cmd\s*=\s*"([^"]*)".*-->/`$1`/e;
                 }                  }
                 $output .= $_;                  $output .= $_;
         }          }
         return $output;          return $output||"";
 }  }
   
 sub PrintArchive {  sub PrintArchive {
Line 1060  sub PrintArchive { Line 1619  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 $SingleTour = $#Tours == 0;
   
         my ($New) = ($Id and $Tournament{'Type'} eq 'þ' and          my ($New) = ($Id and $Tournament{'Type'} eq 'þ' and
                 &NewEnough($Tournament{"CreatedAt"})) ?                  &NewEnough($Tournament{"CreatedAt"})) ?
                 img({src=>"/znatoki/dimrub/db/new-sml.gif", alt=>"NEW!"}) : "";                  img({src=>"/znatoki/dimrub/db/new-sml.gif", alt=>"NEW!"}) : "";
Line 1083  sub PrintAll { Line 1644  sub PrintAll {
         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 1117  sub PrintDates { Line 1691  sub PrintDates {
                 next                  next
                         if (!$array[0]);                          if (!$array[0]);
                 %Tournament = &GetTournament($dbh, $array[0]);                  %Tournament = &GetTournament($dbh, $array[0]);
                    my $textid;
                    if ($textid=$Tournament{'FileName'})
                    {
                      $textid=~s/\.txt//;
                    }
                    elsif ($textid=$Tournament{'Number'})
                    {
                         $fname=~s/\.txt//;
                         $textid="$fname.$textid";
                    }
                    else {$textid=$Tournament{'Id'}};
       $list .= dd(img({src=>"/icons/folder.gif", alt=>"[*]"}) .        $list .= dd(img({src=>"/icons/folder.gif", alt=>"[*]"}) .
       " " . a({href=>url . "?tour=$Tournament{'Id'}&answer=0"},        " " . a({href=>tourhref($textid,0,1)},
       $Tournament{'Title'}, $Tournament{'PlayedAt'}));        $Tournament{'Title'}, $Tournament{'PlayedAt'}||''));
         }          }
           $sth->finish;
         $output .= dl($list);          $output .= dl($list);
         return $output;          return $output;
 }  }
Line 1129  sub PrintQOfAuthor Line 1715  sub PrintQOfAuthor
 {  {
   
     my ($dbh, $id) = @_;      my ($dbh, $id) = @_;
    $id=$dbh->quote($id);      my $Output='';
       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");      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;
Line 1140  sub PrintQOfAuthor Line 1735  sub PrintQOfAuthor
     my @Questions;      my @Questions;
     while (($q)=$sth->fetchrow,$q)      while (($q)=$sth->fetchrow,$q)
      {push @Questions,$q unless $forbidden{$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 1150  sub PrintQOfAuthor Line 1746  sub PrintQOfAuthor
         } else {          } else {
                 $suffix = 'Ñ';                  $suffix = 'Ñ';
         }          }
         print h2("ðÏÉÓË × ÂÁÚÅ ×ÏÐÒÏÓÏ×");          $Output.= printform;
         print printform;          $Output.= p({align=>"center"}, "á×ÔÏÒ ".strong("$name $surname ")
         print p({align=>"center"}, "á×ÔÏÒ ".strong("$name $surname. ")  
         . " : $hits ÐÏÐÁÄÁÎÉ$suffix.");          . " : $hits ÐÏÐÁÄÁÎÉ$suffix.");
   
   
Line 1160  sub PrintQOfAuthor Line 1755  sub PrintQOfAuthor
 #               $output = &PrintQuestion($dbh, $Questions[$i], 1, $i + 1, 1);  #               $output = &PrintQuestion($dbh, $Questions[$i], 1, $i + 1, 1);
 #               print $output;  #               print $output;
 #       }  #       }
         PrintList($dbh,\@Questions,'gdfgdfgdfgdfg');          $Output.=PrintList($dbh,\@Questions,'gdfgdfgdfgdfg');
 }  }
   
   
Line 1189  sub PrintAuthors Line 1784  sub PrintAuthors
   
   
      $sth->execute;       $sth->execute;
      $output.=Tr(th[a({href=>url."?authors=name"},"éÍÑ")       $output.=Tr(th[a({href=>$url."?authors=name"},"éÍÑ")
 .", ".  .", ".
 a({href=>url."?authors=surname"},"ÆÁÍÉÌÉÑ")  a({href=>$url."?authors=surname"},"ÆÁÍÉÌÉÑ")
      , a({href=>url."?authors=kvo"},"ëÏÌÉÞÅÓÔ×Ï ×ÏÐÒÏÓÏ×")]);       , 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"             if (!$name || !$surname) {
               } else                } else
            {             {
              my $add=Tr(td([a({href=>url."?qofauthor=$id"},"$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=
                        '$fname' OR 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]{'PassCriteria'}."\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("$footer")||"";
           $output.=p."<center><font size=-2>ïÂÎÏ×ÌÅÎÉÅ: ".&Include_virtual("$datefooter")."</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');
           POSIX::setlocale( &POSIX::LC_ALL, $thislocale );
         my($i, $tour);          my($i, $tour);
         my($text) = (param('text')) ? 1 : 0;          my($text) = (param('text')) ? 1 : 0;
           $tour = (param('tour')) ? param('tour') : 0;
         my($dbh) = DBI->connect("DBI:mysql:chgk", "piataev", "")          my $texttour=$tour;
           my ($sth,$dbh);
           my($dsn) = "DBI:mysql:database=$dbname;host=$dbhost";
           $dbh = DBI->connect($dsn, $dbuser, $dbpass)
   #       $dbh = DBI->connect("DBI:mysql:$dbname", $username, $dbpass)
                 or do {                  or do {
                         print h1("÷ÒÅÍÅÎÎÙÅ ÐÒÏÂÌÅÍÙ") . "âÁÚÁ ÄÁÎÎÙÈ ×ÒÅÍÅÎÎÏ ÎÅ                          print header.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";
                 };                  };
         if (!param('comp') and !param('sqldump') and !$text) {          $dbh->do("set names koi8r");
            print header;  
            print start_html(-"title"=>'Database of the questions',  
                    -author=>'dimrub@icomverse.com',  
                    -bgcolor=>'#fff0e0',  
                                   -vlink=>'#800020');  
                 print &Include_virtual("../dimrub/db/reklama.html");  
         }  
   
   #       if (param('qid') && (param('qid')=~/^\d+$/) || $tour && $tour=~/^\d+$/) {
   #          my $destination='http://chgk.zaba.ru/search.html';
   #               print header (-'Content-Type' => 'text/html',
   #                -'Location:'=> 'http:\\db.chgk.info');
   #               Redirect($destination);
   #                exit
   #       }
   
 if ($^O =~ /win/i) {          if (0 && $tour && !param('qnumber') && (!param('answers')||(param('answers')<=1)))
         $thislocale = "Russian_Russia.20866";          {       
 } else {                  my $n=param('tour');
         $thislocale = "ru_RU.KOI8-R";                  $n=~s/.txt$//;        
 }                  my $gr=($n=~/^[A-Z]/) || (-e "$realHTMLDIR$n.html");
 POSIX::setlocale( &POSIX::LC_ALL, $thislocale );                  my $destination=tourhref($tour,param('answers')||0,$gr);
                   my $d=$destination;
                   $d=~s/$HTMLDIR/$realHTMLDIR/;
   #               print header.$destination;
   #                print header."$d|".(-e "$realHTMLDIR$n.html");
                   if (-e $d) {
                           Redirect($destination);
                           exit
                   }
                   $d=~s/\.\d+//;
                   $destination=~s/\.\d+//;
                   if (-e $d) {
                           Redirect($destination);
                           exit
                   }
   
 if ((uc 'Á') ne 'á') {print "Koi8-r locale not installed!\n"};          }
   
           if ($tour !~ /^[0-9]*$/) {          
                       if ($tour=~/\./)
                       {
                           my ($fname,$n)= split /\./ , $tour;
   
                           $sth = $dbh->prepare(
                          "SELECT t2.Id FROM Tournaments as t1, 
                           Tournaments as t2 
                           WHERE (t1.FileName = '$fname.txt' OR t1.FileName='$fname')
                           AND t1.Id=t2.ParentId AND t2.Number=$n");
                       }   
                       else 
                           {
                             $sth = $dbh->prepare("SELECT Id FROM Tournaments
                                        WHERE FileName = '$tour.txt' OR 
                                          FileName = '$tour'");
                           }
                       $sth->execute;
                       $tour = ($sth->fetchrow)[0];
                       $sth->finish;
           }
   
         if ($text) {  
           if ($text && !param ('comp')) {
                 print header('text/plain');                  print header('text/plain');
         }          } elsif (!param('comp')) {
                   print header(-charset =>'koi8-r')}
             my $sstr=param('sstr');
             $opt_z||=param("makehtml");
             if (param('qid')) {
                 my $sth;
                 my $qid=param('qid');
   #               if ($qid !~ /^[0-9]+$/) 
                   {
                       my ($fname,$t,$n)= split /\./ , $qid;
                       $n=$t,$t='' unless $n;
                       $t||=1;
                       if ($t)
                       {
                           $sth = $dbh->prepare(
                          "SELECT t2.Id FROM Tournaments as t1, 
                           Tournaments as t2 
                           WHERE (t1.FileName = '$fname.txt' OR t1.FileName='$fname')
                           AND t1.Id=t2.ParentId AND t2.Number=$t");
                       }   
   #                   else 
   #                       {
   #                          $sth = $dbh->prepare("SELECT Id FROM Tournaments
   #                                    WHERE FileName = '$fname.txt' OR FileName = '$fname'" );
   #                       }
                       $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) {
              my $title="òÅÚÕÌØÔÁÔÙ ÐÏÉÓËÁ ÎÁ \"". ($proxysstr||$sstr) .'"' 
                                                       if ($proxysstr||$sstr);
              $title||="âÁÚÁ ×ÏÐÒÏÓÏ×";
              $globaloutput.=start_html(-"title"=>$title,
                      -author=>'dimrub@icomverse.com',
                      -bgcolor=>'#fff0e0',
                                     -vlink=>'#800020');#}
   $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 ($usehash && !$opt_z && length ($qs)<=255 && $qs !~ /(sstr)|(rand)|(comp)|(all=)/i) {
                   my $sth=$dbh->prepare("SELECT page,times,t from hash where query=".$dbh->quote($qs));
                   $sth->execute();
                   my ($p,$times,$t)=$sth->fetchrow();
                   $sth->finish;
                   if ($p) {
                           print ".$p";
                           $dbh->disconnect;
                           exit ;
                   }
          }
   
   
   
   
         if (param('hideequal')) {          if (param('hideequal')) {
                    my ($sth)=  $dbh -> prepare("select first, second FROM equalto");                     my ($sth)=  $dbh -> prepare("select first, second FROM equalto");
Line 1267  if ((uc 'Á') ne 'á') {print "Koi8-r loca Line 2157  if ((uc 'Á') ne 'á') {print "Koi8-r loca
         }          }
   
   
   
         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'));
   #               $type .= 'þ' if (param('chgk'));
                 $qnum = param('qnum') if (param('qnum') =~ /^\d+$/);                  $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 1287  Content-type: text/$mime_type; charset=" Line 2179  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'));
                   $dbh->do("delete from lastqueries where
                         (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')) {            elsif (param('qid')) {
               my $qid=param('qid');                $globaloutput.=&PrintSearch($dbh, $sstr||'', 'proxy');
               my $query="SELECT Question, Answer from Questions where QuestionId=$qid";  
 print $query if $printqueries;  
               my $sth=$dbh->prepare($query);  
               $sth->execute;  
               my $sstr= join ' ',$sth->fetchrow;  
               $searchin{'Question'}=1;  
               $searchin{'Answer'}=1;  
       $sstr=~tr/£³/Åå/;  
 $sstr=~s/[^ÊÃÕËÅÎÇÛÝÚÈßÆÙ×ÁÐÒÏÌÄÖÜÑÞÓÍÉÔØÂÀêãõëåîçûýúèÿæù÷áðòïìäöüñþóíéôøâàa-zA-Z0-9]/ /gi;  
 #              print &PrintQuestion($dbh,$qid, 1, '!');  
               &PrintSearch($dbh, $sstr, 'proxy');  
         }          }
           elsif (param('getfile')){
           elsif (param('all')) {             $globaloutput.=&writefile
                 print &PrintAll($dbh, 0);          } 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(              print "Content-Type: application/octet-stream\n";
                          -'Content-Type' => 'application/x-zip-compressed; name="db.zip"',              print  "Content-Type: application/force-download\n";
                          -'Content-Disposition' => 'attachment; filename="db.zip"'              print  "Content-Type: application/download\n";
                          );              print  "Content-Type: application/x-zip-compressed; name=$texttour.zip\n";
             $tour = (param('tour')) ? param('tour') : 0;              print "Content-Disposition: attachment; filename=$texttour.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);
               print join "",<F>;
             close F;              close F;
             $dbh->disconnect;              $dbh->disconnect;
             exit;              exit;
Line 1344  $sstr=~s/[^ÊÃÕËÅÎÇÛÝÚÈßÆÙ×ÁÐÒÏÌÄÖÜÑÞÓÍÉÔ Line 2236  $sstr=~s/[^ÊÃÕËÅÎÇÛÝÚÈßÆÙ×ÁÐÒÏÌÄÖÜÑÞÓÍÉÔ
             $dbh->disconnect;              $dbh->disconnect;
             exit;              exit;
   
         } else {          } 
                 $tour = (param('tour')) ? param('tour') : 0;          elsif (!$opt_z && !param("makehtml")) {
                 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, $withanswers||0, $qnum, 1,$text,0);
   #                                        $dbh, $Id, $answer, $qnum, $title, $text
                   } else  {
                      $globaloutput.=&PrintTournament($dbh, $tour, $withanswers);
                   }
           }
           else {
                     $opt_z=1;
                     $url="http://db.chgk.info/cgi-bin/db.cgi";
                     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;
                          $paramtour=$fname;
                          $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) && $usehash) {
                   $globaloutput=  $dbh->quote($globaloutput);
                   $dbh->do("insert into hash (query,page) values (".
                   $dbh->quote($qs).
                       ",$globaloutput)");
             }
         }          }
   
         $dbh->disconnect;          $dbh->disconnect;
 }  }

Removed from v.1.42  
changed lines
  Added in v.1.149


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