--- db/prgsrc/db.cgi 2003/04/29 22:21:26 1.117 +++ db/prgsrc/db.cgi 2004/01/10 22:52:20 1.128 @@ -10,6 +10,7 @@ use vars qw($opt_z); use Getopt::Std; getopts('z'); $opt_z||=param("makehtml"); +my $timestamp="_timestamp.tmp"; my $paramtour; my $withanswers=param('answer')||param('answers'); open STDERR, ">/var/tmp/errors1"; @@ -24,15 +25,16 @@ $reklama="../reklama.html" if $opt_z; $footer="../footer.html" if $opt_z; $datefooter="../date" if $opt_z; my $HTMLDIR="/znatoki/dimrub/db/baza/"; -$HTMLDIR="/baza/"; +$HTMLDIR="/files/"; my $realHTMLDIR; if ($^O =~ /win/i) { $realHTMLDIR="/html/znatoki/baza/"; } else { - $realHTMLDIR="/home/piataev/public_html/dimrub/db/baza/"; + $realHTMLDIR="/home/piataev/public_html/dimrub/db/files/"; } my $usehtml=$opt_z||0; +$usehtml=1; my $usewas=0; my $cashednumber=500; my $outputnumber=10; @@ -53,11 +55,11 @@ if ($url !~ /db\.chgk\.info/ && $url !~ Redirect ($u); exit; } -if (!param('sstr') && param('all')) { - my $destination='http://db.chgk.info/all.html'; - Redirect($destination); - 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"; @@ -91,6 +93,14 @@ my %TypeName=('children'=>'Д', 'game'=>' 'chgk'=>'Ч', 'brain'=>'Б', 'beskrylka'=>'Л','ehruditka'=>'Э'); +sub countz { + my ($dbh,$type)=@_; + + my $sth=$dbh->prepare("select count(*) from Questions where Type LIKE '%$type%'"); + $sth->execute(); + my ($tmp)=$sth->fetchrow(); + return $tmp; +} my $all=param('all'); $all=0 if lc $all eq 'no'; @@ -126,6 +136,12 @@ sub NewEnough { sub Redirect { my ($destination) = @_; +print header.< +EndOfHTML +; +=head + print <here< EndOfHTML ; +=cut } @@ -167,12 +184,12 @@ sub GetTournament { sub fetchquestion { my ($sth,$q,$WithTour)=@_; if ($WithTour) { - ($$q{'QuestionId'}, $$q{'Question'},$$q{'Answer'},$$q{'Comments'},$$q{'Authors'}, + ($$q{'QuestionId'}, $$q{'Question'},$$q{'Answer'},$$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{'Comments'},$$q{'Authors'}, + ($$q{'QuestionId'}, $$q{'Question'},$$q{'Answer'},$$q{'Comments'},$$q{'Authors'},$$q{'Sources'}, $$q{'Number'})= $sth->fetchrow; } @@ -194,13 +211,13 @@ sub SelectQuestions { my $query; if ($WithTour) { - $query="SELECT QuestionId, Questions.Question, Answer, Comments, Authors, + $query="SELECT QuestionId, Questions.Question, Answer, 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, Comments, Authors, + $query="SELECT QuestionId, Questions.Question, Answer, Comments, Authors, Sources, Questions.Number from Questions WHERE $where"; } @@ -241,6 +258,12 @@ sub tourhref { $res.=$a?"-a":"-q" unless $gr; $res.=".html"; $res=~s/(\#\d+)(.*)$/$2$1/; + my $t=$res; + $t=~s/\#.*$//; + $res=~s/\.1// unless -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 { @@ -450,7 +473,10 @@ sub russearch { my %count; POSIX::setlocale( &POSIX::LC_ALL, $thislocale ); $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; + #----------- foreach $i (0..$#w) # заполняем массив @nf начальных форм @@ -720,7 +746,7 @@ sub makewhere { $type .= ($_=$TypeName{$_}) foreach @type; my $where=' 0 '; foreach (@type) { - $where.= " OR (Type ='$_') OR (Type ='$_Д') "; + $where.= " OR (Type ='$_') OR (Type ='$_Д') OR (Type ='Д$_') "; } $where.= "OR (Type='ЧБ')" if ($type=~/Ч|Б/); return $where; @@ -996,7 +1022,7 @@ sub PrintTournament { %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'}; @@ -1032,9 +1058,20 @@ sub PrintTournament { }; } } else { - my ($qnum) = GetQNum($dbh); - $output .= h2("Банк Вопросов: $qnum вопрос".&Suffix($qnum)) - . p . "\n"; + my ($qnum) = GetQNum($dbh,0); + my ($qnum1) = GetQNum($dbh,1); + $output .= h2("База вопросов"). + h3("$qnum запис".&Suffix2($qnum). + " (уникальных $qnum1)"); + +# h4("". +# Tr(td("Из них:"), td("Вопросов ЧГК: ".countz($dbh,'Ч'))). +# Tr(td(" "), td("Вопросов для брейна: ".countz($dbh,'Б'))). +# Tr(td(" "), td("Вопросов для ЧГК и брейна: ".countz($dbh,'ЧБ'))). +# Tr(td(" "), td("Интернет-вопросов: ".countz($dbh,'И'))). +# Tr(td(" "), td("Бескрылок: ".countz($dbh,'Л'))). +# Tr(td(" "),td("Заданий для Своей Игры: ".countz($dbh,'Я'))). +# Tr(td(" "),td("Эрудиток: ".countz($dbh,'Э'))))."
" } for ($i = 0; $i <= $#Tours; $i++) { @@ -1086,9 +1123,9 @@ sub PrintTournament { "вопросы + ответы") . "]") ); } else { - $list .= dd(#a({href=> -# $url . "?tour=$textid&comp=1"}, -# img({src=>'/icons/compressed.gif', alt=>'[ZIP]', border=>1})) . + $list .= dd(a({href=> + $url . "?tour=$textid&comp=1"}, + img({src=>'/icons/compressed.gif', alt=>'[ZIP]', border=>1})) . " " . img({src=>$imgsrc, alt=>$alt}) . " " . a({href=>tourhref($textid,0,1)}, @@ -1125,6 +1162,23 @@ sub 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 { my ($dbh, $Id,$n) = @_; @@ -1195,8 +1249,11 @@ sub PrintTour { my $n=$Tour{'Number'}; if ($answer == 0) { + my $nn=".$n"; + $nn="" if ($n==1 && !&IsTour($dbh, $Tour{'ParentId'}, $n + 1)); + $bottom .= - "[" . a({href=>tourhref("$fname.$n",1)}, + "[" . a({href=>tourhref("$fname$nn",1)}, "ответы") . "] " . br; } if ($n>1) { @@ -1228,8 +1285,10 @@ sub PrintField { $value =~ s/<[\/\w]*?>//sg; } else { $value =~ s/^\s+/
    /mg; + $value =~ s/(\s+)-+(\s+)/$1–$2/mg; + $value =~ s/\s+\–/ \–/mg + if $value !~ /^\|/; $value =~ s/^\|([^\n]*)/
$1<\/pre>/mg;
-	    $value =~ s/\s+-+\s+/ – /mg;
 	    $value =~ s/(http:\/\/\S+[^\s\)\(\,\.])/$1<\/a>/g if $header !~ /^Авто/;
 #	    $value =~ s/(http:\/\/(?:\w+.)+[\w\\\~]+(\?[^\s.]+)?)/$1<\/a>/g if $header !~ /^Авто/;
 #	    $value =~ s/(\s)"/$1“/mg;
@@ -1384,12 +1443,22 @@ qid=$qid"}, 'Близкие вопросы').p
 
 # Returns the total number of questions currently in the DB.
 sub GetQNum {
-	my ($dbh) = @_;
+	my ($dbh,$x) = @_;
 	my ($sth) = $dbh->prepare("SELECT COUNT(*) FROM Questions");
 	$sth->execute;
 	my $tmp=($sth->fetchrow)[0];
         $sth->finish;
- 	return $tmp;
+	($sth)=  $dbh -> prepare("select distinct count(first) FROM equalto");
+	           $sth -> execute;
+	my ($c)=$sth->fetchrow;
+
+#	           $i++  while ( my  ($first, $second)=$sth -> fetchrow)
+#                  {
+#                       $forbidden{$first}=1;
+#                  }
+                  $sth->finish;
+
+ 	return $tmp-($x?$c:0);
 }
 sub GetMaxQId {
 	my ($dbh) = @_;
@@ -1439,13 +1508,13 @@ sub Get12Random {
 
 sub Include_virtual {
 	my ($fn, $output) = (@_, '');
-	return "" if ($opt_z);
+	return "\n\n" if ($opt_z);
 	open F , $fn
 		or return ""; #die "Can't open the file $fn: $!\n";
 
 	while () {
 		if (//&Include_virtual($1)/e;
+			s//&Include_virtual($1)/e;
 		}
 		if (//`$1`/e;
@@ -1533,8 +1602,19 @@ sub PrintDates {
 		next
 			if (!$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=>"[*]"}) .
-      " " . a({href=>tourhref($Tournament{'FileName'},0,1)},
+      " " . a({href=>tourhref($textid,0,1)},
       $Tournament{'Title'}, $Tournament{'PlayedAt'}||''));
 	}
         $sth->finish;
@@ -1823,7 +1903,20 @@ MAIN:
 	POSIX::setlocale( &POSIX::LC_ALL, $thislocale );
 	my($i, $tour);
 	my($text) = (param('text')) ? 1 : 0;
-	if (param('qid') && (param('qid')=~/^\d+$/)) {
+	$tour = (param('tour')) ? param('tour') : 0;
+	my $texttour=$tour;
+	my ($sth,$dbh);
+	$dbh = DBI->connect("DBI:mysql:chgk", "piataev", "")
+		or do {
+			print h1("Временные проблемы") . "База вопросов временно не
+			работает. Заходите попозже.";
+			print &Include_virtual("$reklama") if $url!~/localhost/;
+		    print end_html;
+			die "Can't connect to DB chgk\n";
+		};
+
+
+	if (param('qid') && (param('qid')=~/^\d+$/) || $tour && $tour=~/^\d+$/) {
 	   my $destination='http://db.chgk.info/search.html';
 #		print header (-'Content-Type' => 'text/html',
 #                -'Location:'=> 'http:\\db.chgk.info');
@@ -1831,17 +1924,56 @@ MAIN:
                 exit
 	}
 
-	if ($text) {
+	if ($tour && !param('qnumber') && (!param('answers')||(param('answers')<=1)))
+	{       
+	        my $n=param('tour');
+	        $n=~s/.txt$//;        
+		my $gr=($n=~/^[A-Z]/) || (-e "$realHTMLDIR$n.html");
+		my $destination=tourhref($tour,param('answers')||0,$gr);
+		my $d=$destination;
+		$d=~s/$HTMLDIR/$realHTMLDIR/;
+#		print header.$destination;
+                print header."$d|".(-e "$realHTMLDIR$n.html");
+                if (-e $d) {
+			Redirect($destination);
+			exit
+		}
+		$d=~s/\.\d+//;
+		$destination=~s/\.\d+//;
+print br.br.$d;
+                if (-e $d) {
+			Redirect($destination);
+			exit
+		}
+
+	}
+
+	if ($tour !~ /^[0-9]*$/) {	    
+		    if ($tour=~/\./)
+		    {
+		        my ($fname,$n)= split /\./ , $tour;
+
+	                $sth = $dbh->prepare(
+                       "SELECT t2.Id FROM Tournaments as t1, 
+                        Tournaments as t2 
+			WHERE (t1.FileName = '$fname.txt' OR t1.FileName='$fname')
+                        AND t1.Id=t2.ParentId AND t2.Number=$n");
+		    }	
+		    else 
+		        {
+                          $sth = $dbh->prepare("SELECT Id FROM Tournaments
+			             WHERE FileName = '$tour.txt' OR 
+                                       FileName = '$tour'");
+			}
+		    $sth->execute;
+	            $tour = ($sth->fetchrow)[0];
+                    $sth->finish;
+	}
+
+
+	if ($text && !param ('comp')) {
 		print header('text/plain');
-	} else {print header;}
-	my($dbh) = DBI->connect("DBI:mysql:chgk", "piataev", "")
-		or do {
-			print h1("Временные проблемы") . "База вопросов временно не
-			работает. Заходите попозже.";
-			print &Include_virtual("$reklama") if $url!~/localhost/;
-		    print end_html;
-			die "Can't connect to DB chgk\n";
-		};
+	} elsif (!param('comp')) {print header;}
 	  my $sstr=param('sstr');
           $opt_z||=param("makehtml");
 	  if (param('qid')) {
@@ -1932,29 +2064,6 @@ th	{font-size: x-small; font-family : sa
                   }
                   $sth->finish;
         }
-		$tour = (param('tour')) ? param('tour') : 0;
-		my $sth;
-		if ($tour !~ /^[0-9]*$/) {
-		    if ($tour=~/\./)
-		    {
-		        my ($fname,$n)= split /\./ , $tour;
-
-	                $sth = $dbh->prepare(
-                       "SELECT t2.Id FROM Tournaments as t1, 
-                        Tournaments as t2 
-			WHERE (t1.FileName = '$fname.txt' 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 (param('rand')) {
@@ -2002,25 +2111,25 @@ EOT
  	elsif (param('getfile')){
            $globaloutput.=&writefile
  	} elsif (param('all')) {
-	   my $destination='http://db.chgk.info/all.html';
-		Redirect($destination);
-                exit;
-#		$globaloutput.=&PrintAll($dbh, 0);
+#	   my $destination='http://db.chgk.info/all.html';
+#		Redirect($destination);
+#                exit;
+		$globaloutput.=&PrintAll($dbh, 0);
 	} elsif (param('from_year') && param('to_year')) {
 		$globaloutput.=&PrintDates($dbh);
 	} elsif (param('comp')) {
-            $globaloutput.="Content-Type: application/octet-stream\n";
-            $globaloutput.="Content-Type: application/force-download\n";
-            $globaloutput.="Content-Type: application/download\n";
-            $globaloutput.="Content-Type: application/x-zip-compressed; name=db.zip\n";
-            $globaloutput.="Content-Disposition: attachment; filename=db.zip \n\n";
+            print "Content-Type: application/octet-stream\n";
+            print  "Content-Type: application/force-download\n";
+            print  "Content-Type: application/download\n";
+            print  "Content-Type: application/x-zip-compressed; name=$texttour.zip\n";
+            print "Content-Disposition: attachment; filename=$texttour.zip \n\n";
 	    $tour ||= 0;
 	    my (@files) = &PrintArchive($dbh, $tour);
 	    WriteFile($dbh,$_) foreach @files;
 	    open F, "$ZIP -j - @files |";
 	    binmode(F);
 	    binmode(STDOUT);
-	    $globaloutput.= join "",;
+	    print join "",;
 	    close F;
 	    $dbh->disconnect;
 	    exit;
@@ -2055,7 +2164,7 @@ EOT
 	else {
 	          $opt_z=1;
 	          $url="http://db.chgk.info/cgi-bin/db.cgi";
-	          open TS, "timestamp";
+	          open TS, $timestamp;
 	          my $d=$dbh->quote();
 	          close TS;
 		  open FF, ">${realHTMLDIR}index.html" or die "ERROR! - ${HTMLDIR}index.html\n";
@@ -2077,7 +2186,7 @@ EOT
 #                     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");
+ 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) {