File:  [Local Repository] / db / prgsrc / db.cgi
Revision 1.40: download - view: text, annotated - select for diffs - revision graph
Mon Dec 3 13:57:20 2001 UTC (22 years, 5 months ago) by roma7
Branches: MAIN
CVS tags: HEAD
Poisk blizkikh voprosov

    1: #!/perl/bin/perl -w
    2: 
    3: use DBI;
    4: use CGI ':all';
    5: use Text::Query;
    6: use strict;
    7: use Time::Local;
    8: use POSIX qw(locale_h);
    9: use locale;
   10: #open STDERR, ">errors1";
   11: my $printqueries=0;
   12: my %forbidden=();
   13: my $debug=0; #added by R7
   14: my %fieldname= (0,'Question', 1, 'Answer', 2, 'Comments', 3, 'Authors', 4, 'Sources');
   15: my %searchin;
   16: my $rl=qr/[йцукенгшщзхъфывапролджэячсмитьбюё]/;
   17: my $RL=qr/[ЙЦУКЕНГШЩЗХЪЭЖДЛОРПАВЫФЯЧСМИТЬБЮЁ]/;
   18: my $RLrl=qr/(?:(?:${rl})|(?:${RL}))+/;
   19: my $l=qr/(?:(?:${RLrl})|(?:[\w\-]))+/;
   20: my $Ll=qr/(?:[A-Z])|(?:${RL})/;
   21: 
   22: 
   23: 
   24: my $thislocale;
   25: 
   26: 
   27: $searchin{'question'}=param('Question');
   28: $searchin{'answer'}=param('Answer');
   29: $searchin{'comments'}=param('Comments');
   30: $searchin{'authors'}=param('Authors');
   31: $searchin{'sources'}=param('Sources');
   32: my $all=param('all');
   33: $all=0 if lc $all eq 'no';
   34: my ($PWD) = `pwd`;
   35: chomp $PWD;
   36: my ($SRCPATH) = "$PWD/../dimrub/src";
   37: my ($ZIP) = "/home/piataev/bin/zip";
   38: my $DUMPFILE = "/tmp/chgkdump";
   39: my ($SENDMAIL) = "/usr/sbin/sendmail";
   40: my ($TMSECS) = 30*24*60*60;
   41: my (%RevMonths) =
   42: 	('Jan', '0', 'Feb', '1', 'Mar', '2', 'Apr', '3', 'May', '4', 'Jun', '5',
   43: 	'Jul', '6', 'Aug', '7', 'Sep', '8', 'Oct', '9', 'Nov', '10',
   44: 	'Dec', '11',
   45: 	 'Янв', '0', 'Фев', 1, 'Мар', 2, 'Апр', 3, 'Май', '4',
   46: 	 'Июн', '5', 'Июл', 6, 'Авг', '7', 'Сен', '8',
   47: 	 'Окт', '9', 'Ноя', '19', 'Дек', '11');
   48: 
   49: # Determine whether the given time is within 2 months from now.
   50: sub NewEnough {
   51: 	my ($a) = @_;
   52: 	my ($year, $month, $day) = split('-', $a);
   53: 
   54: 	return (time - timelocal(0, 0, 0, $day, $month -1, $year) < $TMSECS);
   55: }
   56: 
   57: # Reads one question from the DB. Gets DB handler and Question ID.
   58: sub GetTournament {
   59: 	my ($dbh, $Id) = @_;
   60: 	my (%Tournament, $field, @arr);
   61: 
   62: 	return %Tournament if ($Id == 0);
   63: 
   64: 	my ($sth) = $dbh->prepare("SELECT * FROM Tournaments WHERE Id=$Id");
   65: 	$sth->execute;
   66: 
   67: 	@arr = $sth->fetchrow;
   68: 	my($i, $name) = 0;
   69: 	foreach $name (@{$sth->{NAME}}) {
   70: 		$Tournament{$name} = $arr[$i++];
   71: 	}
   72: 
   73: 	return %Tournament;
   74: }
   75: 
   76: # Reads one question from the DB. Gets DB handler and Question ID.
   77: sub GetQuestion {
   78: 	my ($dbh, $QuestionId) = @_;
   79: 	my (%Question, $field, @arr);
   80: 
   81: 	my($sth) = $dbh->prepare("
   82: 		SELECT * FROM Questions WHERE QuestionId=$QuestionId
   83: 	");
   84: 
   85: 	$sth->execute;
   86: 
   87: 	@arr = $sth->fetchrow;
   88: 	my($i, $name) = 0;
   89: 	foreach $name (@{$sth->{NAME}}) {
   90: 		$Question{$name} = $arr[$i++];
   91: 	}
   92: 
   93: 	return %Question;
   94: }
   95: 
   96: # Gets numbers of all the questions from the given tour.
   97: sub GetTourQuestions {
   98: 	my ($dbh, $ParentId) = @_;
   99: 	my (@arr, @Questions);
  100: 
  101: 	my ($sth) = $dbh->prepare("SELECT QuestionId FROM Questions
  102: 		WHERE ParentId=$ParentId ORDER BY QuestionId");
  103: 
  104: 	$sth->execute;
  105: 
  106: 	while (@arr = $sth->fetchrow) {
  107: 		push @Questions, $arr[0];
  108: 	}
  109: 
  110: 	return @Questions;
  111: }
  112: 
  113: # Returns list of children of the given tournament.
  114: sub GetTours {
  115: 	my ($dbh, $ParentId) = @_;
  116: 	my (@arr, @Tours);
  117: 
  118: 	my ($sth) = $dbh->prepare("SELECT Id FROM Tournaments
  119: 		WHERE ParentId=$ParentId ORDER BY Id");
  120: 
  121: 	$sth->execute;
  122: 
  123: 	while (@arr = $sth->fetchrow) {
  124: 		push @Tours, $arr[0];
  125: 	}
  126: 
  127: 	return @Tours;
  128: }
  129: 
  130: sub count
  131: {
  132:   my ($dbh,$word)=@_; 
  133: print "timeb=".time.br if $debug;
  134:   $word=$dbh->quote(uc $word);
  135:   my $query="SELECT number from nests,nf where $word=w1 AND w2=nf.id";
  136:   my $sth=$dbh->prepare($query);
  137:   $sth->execute;
  138:   my @a=$sth->fetchrow;
  139: print "timee0=".time.br if $debug;
  140:   $a[0]||0;
  141: }
  142: 
  143: 
  144: sub proxy
  145: {
  146: #print "time0=".time.br if $debug;
  147:       my ($dbh,$ptext,$allnf)=@_;
  148:       my $text=$$ptext;
  149:       $text=~tr/ёЁ/еЕ/;
  150:       $text=~s/(${RLrl})p(${RLrl})/$1p$2/gom;
  151:       $text=~s/p(${RLrl})/р$1/gom;
  152:       $text=~s/(${RLrl})p/$1р/gom;
  153:       $text=~s/\s+/ /gmo;
  154:       $text=~s/[^йцукенгшщзхъфывапролджэячсмитьбюЙЦУКЕНГШЩЗХЪФЫВАПРОЛДЖЭЯЧСМИТЬБЮQWERTYUIOPASDFGHJKLZXCVBNM]/ /g;
  155:       $text=uc $text;
  156:       my @list= $text=~m/(?:(?:${RLrl})+)|(?:[A-Za-z0-9]+)/gom;
  157:       my (%c, %good,$sstr);
  158:       foreach (@list)
  159:       {
  160:            $c{$_}=count($dbh,$_)||10000;
  161:       }
  162:       my @words=sort {$c{$a}<=> $c{$b}} @list;
  163: 
  164: #      $good{$words[$_]}=1 foreach 0..4;
  165: 
  166:       foreach (@words)
  167:       {
  168:          $good{$_}=1 if $c{$_}<200;
  169:       }
  170: 
  171: #      foreach (@list)
  172: #      {
  173: #        if ($good{$_})
  174: #        {
  175: #           $good{$_}=0;
  176: #           $sstr.=" $_";
  177: #        }
  178: #      }
  179:       $sstr.=" $_" foreach grep {$good{$_}} @list;
  180: print "time05=".time.br if $debug;
  181:       $$ptext=$sstr;
  182:       return russearch($dbh,$sstr,0,$allnf);
  183: }
  184: 
  185: 
  186: sub russearch {
  187:             my ($dbh, $sstr, $all,$allnf)=@_;
  188:             my (@qw,@w,@tasks,$qw,@arr,$nf,$sth,@nf,$w,$where,$e,@where,%good,$i,%where,$from);
  189:             my($number,@good,$t,$task,@rho,$rank,%rank,$r2,$r1,$word,$n,@last,$good,@words,%number,$taskid);
  190:             my ($hi, $lo, $wordnumber,$query,$blob,$field,$sf,$ii);
  191:             my @frequence;
  192:             my (@arr1,@ar,@sf,@arr2);
  193: 	    my %tasks;
  194: 	    my $tasks;
  195: 	    my @verybad;
  196: 	    my %nf;
  197:             my %tasksof;
  198:             my %wordsof;
  199:             my %relevance;
  200:             my @blob;
  201:             my %count;
  202: 
  203: $sstr=~tr/йцукенгшщзхъфывапролджэячсмитьбю/ЙЦУКЕНГШЩЗХЪФЫВАПРОЛДЖЭЯЧСМИТЬБЮ/;
  204:     	    @qw=@w =split (' ', uc $sstr);
  205: 
  206: #-----------
  207:             foreach $i (0..$#w) # заполняем массив @nf начальных форм
  208:                            # $nf[$i] -- ссылка на массив возможных
  209:                            # начальных форм словоформы $i
  210:             {
  211:                 $qw= $dbh->quote (uc $w[$i]);
  212:                 $query="  select distinct w2 from nests
  213:                                 where w1=$qw";
  214: print "$query",br if $printqueries;
  215:                 $sth=$dbh -> prepare($query);
  216: 	        $sth -> execute;
  217: 	        @{$nf[$i]}=();
  218: 	        while (@arr = $sth->fetchrow)
  219: 	        {
  220: 	           push (@{$nf[$i]},$arr[0])
  221: 	        }
  222:             }
  223: 
  224: 
  225:             my @bad=grep {!@{$nf[$_]}} 0..$#w; # @bad -- номера словоформ,
  226:                                            # которых нет в словаре
  227: 
  228:             if (@bad) #есть неопознанные словоформы
  229:             {
  230:                require  "cw.pl";
  231:                foreach $i(@bad)
  232:                {
  233:                  if (@arr=checkword($dbh,$w[$i]))
  234:                    {push (@{$nf[$i]}, @arr);}
  235:                  else
  236:                    {push (@verybad,$i);}
  237:                }
  238:             }
  239:             return () if ($all && @verybad);
  240: 
  241: 
  242:             my $kvo=0;
  243:             push @$allnf, @{$_} foreach @nf;
  244: 	    print "nf=@$allnf" if $printqueries;
  245: 
  246:             foreach $i (0..$#w) #запросы в базу...
  247:             {
  248:               @arr=@{$nf[$i]} if $nf[$i];
  249:               @arr2=@arr1=@arr;
  250: 
  251: 
  252: 
  253: 
  254:               $_= " word2question.word=".$_. ' ' foreach @arr;
  255:               $_= " nf.id=".$_. ' ' foreach @arr1;
  256: #              @arr=(0) unless @arr;
  257:               $query="select questions from word2question where". (join ' OR ', @arr);
  258: print STDERR "!$query\n",br if $printqueries;
  259: 
  260:     	      $sth=$dbh -> prepare($query);
  261:               $sth->execute;
  262: 
  263:               @blob=();
  264:               while (@arr=$sth->fetchrow)
  265:               {
  266:                 @blob=(@blob,unpack 'C*',$arr[0]);
  267:               }
  268:               $query="select number from nf where ".(join ' OR ', @arr1);
  269: print "$query\n",br if $printqueries;
  270:     	      $sth=$dbh -> prepare($query);
  271:               $sth->execute;
  272: 
  273:               while (@arr=$sth->fetchrow)
  274:               {
  275:                 $frequence[$i]+=$arr[0];
  276:               }
  277: 
  278: 
  279: 
  280:               if (@blob < 4)
  281:               {
  282:                  $tasksof{$i}=undef;
  283:               } else
  284:               {
  285:                  $kvo++;
  286:                  $ii=0;
  287:                  while ($ii<$#blob)  # создаём хэш %tasksof, ключи которого --
  288:                              # номера искомых словоформ, а значения --
  289:                              # списки вопросов, в которых есть соответствующа
  290:                              # словоформа.
  291:                              # Каждый список в свою очередь также оформлен в
  292:                              # виде хэша, ключи которого -- номера вопросов,
  293:                              # а значения -- списки номеров вхождений. Вот.
  294:                  {
  295:                     ($field,$lo,$hi,$wordnumber)=@blob[$ii..($ii+3)];
  296:                     $ii+=4;
  297:                     $number=$lo+$hi*256;
  298:                     $field=$fieldname{$field};
  299:                     if ($searchin{lc $field})
  300:                     {
  301:                       push @{$tasksof{$i}{$number}}, $wordnumber;
  302:                                       # дополнили в хэше, висящем на
  303:                                       # словоформе $i в %tasksof список
  304:                                       # вхождений $i в вопрос $number.
  305:                       push @{$wordsof{$number}{$i}}, $wordnumber;
  306:                                       # дополнили в хэше, висящем на
  307:                                       # вопросе $number в %wordsof список
  308:                                       # вхождений $i в вопрос $number.
  309: 
  310: 
  311:                     }
  312:                  }  #while ($ii<$#blob)
  313:                }
  314:             }    #foreach $i
  315: 
  316: #print "keys tasksof", join ' ', keys %{$tasksof{0}};
  317: #Ищем пересечение или объединение списков вопросов (значений %tasksof)
  318:        	    foreach $sf (keys %tasksof)
  319:            {
  320:               $count{$_}++ foreach keys %{$tasksof{$sf}};
  321:            }
  322:              @tasks= ($all ? (grep {$count{$_}==$kvo} keys %count) :
  323:                              keys %count) ;
  324: 
  325: 
  326: print "\n\$#tasks=",$#tasks,br if $printqueries;
  327: ############ Сортировка найденных вопросов
  328: 
  329: foreach (keys %wordsof)
  330: {
  331:   $relevance{$_}=&relevance($#w,$wordsof{$_},\@frequence) if $_
  332: }
  333: 
  334: @tasks=sort {$relevance{$b}<=>$relevance{$a}} @tasks;
  335: 
  336: 
  337: ############
  338: 
  339: print "tasks=@tasks" if $printqueries;
  340: 
  341: #print "$_ $relevance{$_} | " foreach @tasks;
  342: #print br;
  343: print "allnf=@$allnf",br if $printqueries;
  344:         return  @tasks;
  345: }
  346: 
  347: 
  348: sub distance  {
  349:                  # на входе -- номера словоформ и ссылки на
  350:                  # списки вхождений. На выходе -- расстояние,
  351:                  # вычисляемое по формуле min(|b-a-pb+pa|)
  352:                  #                       pb,pa
  353:                  # (pb и pa -- позиции слов b и a)
  354:    my ($a,$b,$lista,$listb)=@_;
  355:    my ($pa,$pb,$min,$curmin);
  356:    $min=10000;
  357:    foreach $pa (@$lista)
  358:    {
  359:      foreach $pb (@$listb)
  360:      {
  361:         $curmin=abs($b-$a-$pb+$pa);
  362:         $min= $curmin if $curmin<$min;
  363:      }
  364:    }
  365:    return $min;
  366: 
  367: }
  368: 
  369: sub relevance {
  370:               # На входе -- количество искомых словоформ -1 и
  371:               # ссылка на hash, ключи которого --
  372:               # номера словоформ, а значения -- списки вхождений
  373: 
  374:        my ($n,$words,$frequence)=@_;
  375:        my $relevance=0;
  376:        my ($first,$second,$d);
  377:        foreach $first (0..$n)
  378:        {
  379:          $relevance+=scalar @{$$words{$first}}+1000+1000/$$frequence[$first]
  380: if $$words{$first};
  381:          foreach $second ($first+1..$n)
  382:          {
  383:             $d=&distance($first,$second,$$words{$first},$$words{$second});
  384:             $relevance+=($d>10?0:10-$d)*10;
  385:          }
  386:        }
  387:        return $relevance;
  388: }
  389: 
  390: 
  391: 
  392: # Returns list of QuestionId's, that have the search string in them.
  393: sub Search {
  394: 	my ($dbh, $s,$metod,$all,$allnf) = @_;
  395: 	my $sstr=$$s;
  396: 	my (@arr, @Questions, @fields);
  397: 	my (@sar, $i, $sth,$where,$query);
  398: 	my $ip=$ENV{'REMOTE_ADDR'};
  399: 
  400:         $ip=$dbh->quote($ip);
  401: 	$query=
  402:           "INSERT into queries (query,metod,searchin,ip)
  403:                     values (". $dbh->quote($sstr).', '.
  404:                     $dbh->quote($metod) . ', ' .
  405:                     $dbh->quote(join ' ', grep $searchin{$_}, keys %searchin)  . 
  406:               ", $ip)";
  407: print $query if $printqueries;
  408:         $dbh -> do ($query);
  409: 	if ($metod eq 'rus')
  410: 	{
  411: 	     my @tasks=russearch($dbh,$sstr,$all,$allnf);
  412: 	     return @tasks
  413: 	}
  414: 	elsif ($metod eq 'proxy')
  415: 	{
  416: #	  $searchin{'question'}=1;
  417: #	  $searchin{'answer'}=1;
  418: 	  my @task=proxy($dbh,$s,$allnf);
  419: #	  $$s=$sstr;
  420: 	  return @task
  421: 	}
  422: 
  423: 
  424: 
  425: ###Simple and advanced query processing. Added by R7
  426: 	if ($metod eq 'simple' || $metod eq 'advanced')
  427: 	{
  428:           foreach (qw/Question Answer Sources Authors Comments/) {
  429: 		if (param($_)) {
  430: 			push @fields, $_;
  431: 		}
  432: 	   }
  433: 
  434: 	   @fields=(qw/Question Answer Sources Authors Comments/) unless scalar @fields;
  435: 	   my $fields=join ",", @fields;
  436:            my $q=new Text::Query($sstr,
  437:                  -parse => 'Text::Query::'.
  438:                    (($metod eq 'simple') ? 'ParseSimple':'ParseAdvanced'),
  439:                  -solve => 'Text::Query::SolveSQL',
  440:                  -build => 'Text::Query::BuildSQLMySQL',
  441:                  -fields_searched => $fields);
  442: 
  443:            $where=	$$q{'matchexp'};
  444:            $query= "SELECT Questionid FROM Questions
  445:                 WHERE $where";
  446:            print br."Query is: $query".br if $debug;
  447: 
  448:            $sth = $dbh->prepare($query);
  449:          } else
  450: ######
  451:          {
  452: 
  453: 	  foreach (qw/Question Answer Sources Authors Comments/) {
  454: 		if (param($_)) {
  455: 			push @fields, "IFNULL($_, '')";
  456: 		}
  457: 	  }
  458: 	  @sar = split " ", $sstr;
  459: 	  for $i (0 .. $#sar) {
  460: 		$sar[$i] = $dbh->quote("%${sar[$i]}%");
  461: 	  }
  462: 
  463: 	  my($f) = "CONCAT(" . join(',', @fields) . ")";
  464: 	  if (param('all') eq 'yes') {
  465: 		$sstr = join " AND $f LIKE ", @sar;
  466: 	  } else {
  467: 		$sstr = join " OR $f LIKE ", @sar;
  468:     	  }
  469: 
  470:    my $query;
  471:                $query="SELECT QuestionId FROM Questions
  472: 		WHERE $f LIKE $sstr ORDER BY QuestionId";
  473: 
  474: 
  475: print $query if $printqueries;
  476: 	  $sth = $dbh->prepare($query)
  477: 	} #else -- processing old-style query (R7)
  478: 
  479: 	$sth->execute;
  480: 	while (@arr = $sth->fetchrow) {
  481: 		push @Questions, $arr[0] unless $forbidden{$arr[0]};
  482: 	}
  483: 
  484: print "@Questions" if $printqueries;
  485: 	return @Questions;
  486: }
  487: 
  488:  # Substitute every letter by a pair (for case insensitive search).
  489:  my (@letters) = qw/аА бБ вВ гГ дД еЕ жЖ зЗ иИ йЙ кК лЛ мМ нН оО
  490:  пП рР сС тТ уУ фФ хХ цЦ чЧ шШ щЩ ьЬ ыЫ эЭ юЮ яЯ/;
  491: 
  492: sub NoCase {
  493: 	my ($sstr) = shift;
  494: 	my ($res);
  495: 
  496: 	if (($res) = grep(/$sstr/, @letters)) {
  497: 		return "[$res]";
  498: 	} else {
  499: 		return $sstr;
  500: 	}
  501: }
  502: 
  503: sub PrintList {
  504:    my ($dbh,$Questions,$shablon)=@_;
  505: 
  506: 	my $first=param('first') ||1;
  507: 	my $kvo=param('kvo') ||30;
  508: 
  509: 	$first=$first-($first-1)%$kvo;
  510: 	my $last=$first+$kvo-1;
  511: 	$last=scalar @$Questions if scalar @$Questions <$last;
  512:         my($f,$l);
  513:         my $nav='';
  514: 
  515:         for($f=1; $f<=@$Questions; $f+=$kvo)
  516: 	{
  517: 	  $l=$f+$kvo-1;
  518: 	  $l=$#$Questions+1 if $l>$#$Questions+1;
  519: 	  if ($f==$first) {$nav.="[$f-$l] ";}
  520: 	  else {
  521:             	  my $qs=query_string;
  522: 	          $qs=~s/\;/\&/g;
  523:                   $qs=~s/\&first\=[^\&]+//g;
  524: 	          $qs.="\&first=$f";
  525: 
  526:                   $nav.= "[".a({href=>(url."?".$qs)},"$f-$l")."] ";}
  527: 	}
  528: 	print "$nav".br."\n";
  529: 	for (my $i = $first; $i <= $last; $i++) {
  530: 		my $output = &PrintQuestion($dbh, $$Questions[$i-1], 1, $i, 1);
  531:                 if (param('metod') eq 'rus' || param('metod') eq 'proxy')
  532:                 {
  533: 	             $output=~s/\b($shablon)\b/\<strong\>$1\<\/strong\>/gi;
  534: 	        } else {
  535: 	             $output=~s/($shablon)/\<strong\>$1\<\/strong\>/gi;
  536: 		}
  537: 		print $output;
  538: 	}
  539: 	print "$nav".br."\n";
  540: 
  541: }
  542: 
  543: sub PrintSearch {
  544: 	my ($dbh, $sstr, $metod) = @_;
  545: 
  546: 	my @allnf;
  547:         my (@Questions) = &Search($dbh, \$sstr,$metod,$all,\@allnf);
  548: 	my ($output, $i, $suffix, $hits) = ('', 0, '', $#Questions + 1);
  549: 
  550:         my $shablon;
  551:         $metod='rus' if $metod eq 'proxy';
  552:         if ($metod eq 'rus')
  553:         {
  554:            my $where='0';
  555:            $where.= " or w2=$_ " foreach @allnf;
  556:            my $query="select w1 from nests where $where";
  557:            my $sth=$dbh->prepare($query);
  558: print "$query" if $printqueries;
  559: 
  560: 	   $sth->execute;
  561: 	   my @shablon;
  562: 	   while (my @arr = $sth->fetchrow)
  563: 	   {
  564: 	     push @shablon,"(?:$arr[0])";
  565: 	   }
  566:            $shablon= join "|", @shablon;
  567:            $shablon=~s/[её]/\[ЕЁ\]/gi;
  568: #           $shablon=~s/([йцукенгшщзхъфывапролджэячсмитьбюЙЦУКЕНГШЩЗХЪФЫВАПРОЛДЖЭЯЧСМИТЬБЮ])/&NoCase($1)/ge;
  569:            $shablon=qr/$shablon/i;
  570:            print "!$shablon!",br if $printqueries;
  571:         }
  572: 
  573: 
  574: 
  575: 	if ($hits =~ /1.$/  || $hits =~ /[5-90]$/) {
  576: 		$suffix = 'й';
  577: 	} elsif ($hits =~ /1$/) {
  578: 		$suffix = 'е';
  579: 	} else {
  580: 		$suffix = 'я';
  581: 	}
  582: 
  583: 	print p({align=>"center"}, "Результаты поиска на " . strong($sstr)
  584: 	. " : $hits попадани$suffix.");
  585: 
  586: 	if (param('word')) {
  587: 		$sstr = '[ 	\.\,:;]' . $sstr . '[  \.\,:\;]';
  588: 	}
  589: 
  590: 	$sstr =~ s/(.)/&NoCase($1)/ge;
  591: 
  592: 	my @sar;
  593: 	if ($metod ne 'rus') 
  594: 	{
  595: 	  (@sar) = split(' ', $sstr);
  596: 	  $shablon=join "|",@sar;
  597: 	}
  598: 	PrintList($dbh,\@Questions,$shablon);
  599: }
  600: 
  601: sub PrintRandom {
  602:    my ($dbh, $type, $num, $text) = @_;
  603:    my (@Questions) = &Get12Random($dbh, $type, $num);
  604: 	my ($output, $i) = ('', 0);
  605: 
  606: 	if ($text) {
  607: 		$output .= "	$num случайных вопросов.\n\n";
  608: 	} else {
  609: 		$output .=
  610: 			h2({align=>"center"}, "$num случайных вопросов.");
  611: 	}
  612: 
  613: 	for ($i = 0; $i <= $#Questions; $i++) {
  614: 		# Passing DB handler, question ID, print answer, question
  615: 		# number, print title, print text/html
  616: 		$output .=
  617: 			&PrintQuestion($dbh, $Questions[$i], 1, $i + 1, 0, $text);
  618: 	}
  619: 	return $output;
  620: }
  621: 
  622: sub PrintTournament {
  623:    my ($dbh, $Id, $answer) = @_;
  624: 	my (%Tournament, @Tours, $i, $list, $qnum, $imgsrc, $alt,
  625: 		$SingleTour);
  626: 	my ($output) = '';
  627: 
  628: 	%Tournament = &GetTournament($dbh, $Id) if ($Id);
  629: 
  630: 	my ($URL) = $Tournament{'URL'};
  631: 	my ($Info) = $Tournament{'Info'};
  632: 	my ($Copyright) = $Tournament{'Copyright'};
  633: 
  634: 	@Tours = &GetTours($dbh, $Id);
  635: 
  636: 	if ($Id) {
  637: 		for ($Tournament{'Type'}) {
  638: 			/Г/ && do {
  639: 				$output .= h2({align=>"center"},
  640: 					      "Группа: $Tournament{'Title'} ",
  641: 					      "$Tournament{'PlayedAt'}") . p . "\n";
  642: 				last;
  643: 			};
  644: 			/Ч/ && do {
  645: 				return &PrintTour($dbh, $Tours[0], $answer)
  646: 					if ($#Tours == 0);
  647: 
  648: 				my $title="Пакет: $Tournament{'Title'}";
  649: 				if ($Tournament{'PlayedAt'}) {
  650: 				    $title .= " $Tournament{'PlayedAt'}";
  651: 				}
  652: 
  653: 				$output .= h2({align=>"center"},
  654: 					"$title") . p . "\n";
  655: 				last;
  656: 			};
  657: 			/Т/ && do {
  658: 				return &PrintTour($dbh, $Id, $answer);
  659: 			};
  660: 		}
  661: 	} else {
  662: 		my ($qnum) = GetQNum($dbh);
  663: 		$output .= h2("Банк Вопросов: $qnum вопросов") . p . "\n";
  664: 	}
  665: 
  666: 	for ($i = 0; $i <= $#Tours; $i++) {
  667: 		%Tournament = &GetTournament($dbh, $Tours[$i]);
  668: 
  669: 		if ($Tournament{'Type'} =~ /Ч/) {
  670: 			$SingleTour = 0;
  671: 			my (@Tours) = &GetTours($dbh, $Tournament{'Id'});
  672: 			$SingleTour = 1
  673: 				if ($#Tours == 0);
  674: 		}
  675: 		if ($Tournament{'QuestionsNum'} > 0) {
  676: 			$qnum = " ($Tournament{'QuestionsNum'} вопрос" .
  677: 				&Suffix($Tournament{'QuestionsNum'}) . ")\n";
  678: 		} else {
  679: 			$qnum = '';
  680: 		}
  681: 		if ($Tournament{'Type'} =~ /Г/) {
  682: 			$imgsrc = "/icons/folder.gif";
  683: 			$alt = "[*]";
  684: 		} else {
  685: 			$imgsrc = "/icons/folder.gif";
  686: 			$alt = "[-]";
  687: 		}
  688: 
  689: 		if ($SingleTour or $Tournament{'Type'} =~ /Т/) {
  690: 			$list .= dd(img({src=>$imgsrc, alt=>$alt})
  691: 				. " " . $Tournament{'Title'} . " " .
  692: 				    $Tournament{'PlayedAt'} . $qnum) .
  693: 				dl(
  694: 					dd("["
  695: 						. a({href=>url .  "?tour=$Tournament{'Id'}&answer=0"},
  696: 						"вопросы") . "] ["
  697:                   . a({href=>url .  "?tour=$Tournament{'Id'}&answer=1"},
  698:                   "вопросы + ответы") . "]")
  699: 				);
  700: 		} else {
  701: 			$list .= dd(a({href=>url . "?tour=$Tournament{'Id'}&comp=1"},
  702: 				img({src=>'/icons/compressed.gif', alt=>'[ZIP]', border=>1}))
  703: 				. " " . img({src=>$imgsrc, alt=>$alt})
  704: 				. " " . a({href=>url . "?tour=$Tournament{'Id'}&answer=0"},
  705: 				$Tournament{'Title'}. " ".
  706: 					  $Tournament{'PlayedAt'}) . $qnum);
  707: 		}
  708: 	}
  709: 	$output .= dl($list);
  710: 
  711: 	if ($URL) {
  712: 		$output .=
  713: 		p("Дополнительная информация об этом турнире - по адресу " .
  714: 			a({-'href'=>$URL}, $URL));
  715: 	}
  716: 
  717: 	if ($Copyright) {
  718: 		$output .= p("Копирайт: " .   $Copyright);
  719: 	}
  720: 
  721: 	if ($Info) {
  722: 		$output .= p($Info);
  723: 	}
  724: 
  725: 	return $output;
  726: }
  727: 
  728: sub Suffix {
  729: 	my ($qnum) = @_;
  730: 	my ($suffix) = 'а' if $qnum =~ /[234]$/;
  731:    $suffix = '' if $qnum =~ /1$/;
  732:    $suffix = 'ов' if $qnum =~ /[567890]$/ || $qnum =~ /1.$/;
  733: 	return $suffix;
  734: }
  735: 
  736: sub IsTour {
  737: 	my ($dbh, $Id) = @_;
  738: 	my ($sth) = $dbh->prepare("SELECT Type FROM Tournaments
  739: 		WHERE Id=$Id");
  740: 	$sth->execute;
  741: 	return ($sth->fetchrow)[0] =~ /Т/;
  742: }
  743: 
  744: # Gets a DB handler (ofcourse) and a tour Id. Prints all the
  745: # question of that tour, according to the options.
  746: sub PrintTour {
  747: 	my ($dbh, $Id, $answer) = @_;
  748: 	my ($output, $q, $bottom, $field) = ('', 0, '', '');
  749: 
  750: 	my (%Tour) = &GetTournament($dbh, $Id);
  751: 	my (@Tours) = &GetTours($dbh, $Tour{'ParentId'});
  752: 	my (%Tournament) = &GetTournament($dbh, $Tour{'ParentId'});
  753: 
  754: 	return 0
  755: 		if ($Tour{'Type'} !~ /Т/);
  756: 
  757: 	my ($qnum) = $Tour{'QuestionsNum'};
  758: 	my ($suffix) = &Suffix($qnum);
  759: 
  760: 	$output .= h2({align=>"center"}, $Tournament{"Title"},
  761: 		      $Tournament{'PlayedAt'},
  762: 		      "<br>", $Tour{"Title"} .
  763: 		" ($qnum вопрос$suffix)\n") . p;
  764: 
  765: 	my (@Questions) = &GetTourQuestions($dbh, $Id);
  766: 	for ($q = 0; $q <= $#Questions; $q++) {
  767: 		$output .= &PrintQuestion($dbh, $Questions[$q], $answer, 0);
  768: 	}
  769: 
  770: 	$output .= hr({-'align'=>'center', -'width'=>'80%'});
  771: 
  772: 	if ($Tournament{'URL'}) {
  773: 		$output .=
  774: 		p("Дополнительная информация об этом турнире - по адресу " .
  775: 			a({-'href'=>$Tournament{'URL'}}, $Tournament{'URL'}));
  776: 	}
  777: 
  778: 	if ($Tournament{'Copyright'}) {
  779: 		$output .= p("Копирайт: " .   $Tournament{'Copyright'});
  780: 	}
  781: 
  782: 	if ($Tournament{'Info'}) {
  783: 		$output .= p($Tournament{'Info'});
  784: 	}
  785: 
  786: 
  787: 	if ($answer == 0) {
  788: 		$bottom .=
  789: 			"[" . a({href=>url . "?tour=$Id&answer=1"}, "ответы") .  "] " . br;
  790: 	}
  791: 	if (&IsTour($dbh, $Id - 1)) {
  792: 		$bottom .=
  793: 			"[" . a({href=>url . "?tour=" . ($Id - 1) . "&answer=0"},
  794: 			"предыдущий тур") . "] ";
  795: 		$bottom .=
  796: 			"[" . a({href=>url . "?tour=" . ($Id - 1) . "&answer=1"},
  797: 			"предыдущий тур с ответами") . "] " . br;
  798: 	}
  799: 	if (&IsTour($dbh, $Id + 1)) {
  800: 		$bottom .=
  801: 			"[" . a({href=>url . "?tour=" . ($Id + 1) . "&answer=0"},
  802: 			"следующий тур") . "] ";
  803: 		$bottom .=
  804: 			"[" . a({href=>url . "?tour=" . ($Id + 1) . "&answer=1"},
  805: 			"следующий тур с ответами") . "] ";
  806: 	}
  807: 
  808: 	$output .=
  809: 		p({align=>"center"}, font({size=>-1}, $bottom));
  810: 
  811: 	return $output;
  812: }
  813: 
  814: sub PrintField {
  815: 	my ($header, $value, $text) = @_;
  816: 	if ($text) {
  817: 	    $value =~ s/<[\/\w]*>//sg;
  818: 	} else {
  819: 	    $value =~ s/^\s+/<br>&nbsp;&nbsp;&nbsp;&nbsp;/mg;
  820: 	    $value =~ s/^\|([^\n]*)/<pre>$1<\/pre>/mg;
  821: 	}
  822: 
  823: 	return $text ? "$header:\n$value\n\n" :
  824: 		strong("$header: ") . $value . p . "\n";
  825: }
  826: 
  827: # Gets a DB handler (ofcourse) and a question Id. Prints
  828: # that question, according to the options.
  829: sub PrintQuestion {
  830: 	my ($dbh, $Id, $answer, $qnum, $title, $text) = @_;
  831: 	my ($output, $titles) = ('', '');
  832: 	my (%Question) = &GetQuestion($dbh, $Id);
  833: 	if (!$text) {
  834: 		$output .= hr({width=>"50%"});
  835: 		if ($title) {
  836: 			my (%Tour) = GetTournament($dbh, $Question{'ParentId'});
  837: 			my (%Tournament) = GetTournament($dbh, $Tour{'ParentId'});
  838: 			$titles .=
  839: 				dd(img({src=>"/icons/folder.open.gif"}) . " " .
  840: 					 a({href=>url . "?tour=$Tournament{'Id'}"}, $Tournament{'Title'}, $Tournament{'PlayedAt'}));
  841: 			$titles .=
  842: 				dl(dd(img({src=>"/icons/folder.open.gif"}) . " " .
  843: 					a({href=>url . "?tour=$Tour{'Id'}"}, $Tour{'Title'})));
  844: 		}
  845: 		$output .= dl(strong($titles));
  846: 	}
  847: 
  848: 	$qnum = $Question{'Number'}
  849: 		if ($qnum == 0);
  850: 
  851: 	$output .=
  852: 		&PrintField("Вопрос $qnum", $Question{'Question'}, $text);
  853: 
  854: 	if ($answer) {
  855: 		$output .=
  856: 			&PrintField("Ответ", $Question{'Answer'}, $text);
  857: 
  858: 		if ($Question{'Authors'}) {
  859:                       my $q=$Question{'Authors'};
  860: 
  861: 		      my $sth=$dbh->prepare("select Authors.Id,Name, Surname, Nicks from Authors, A2Q
  862:                                  where Authors.Id=Author And Question=$Id");
  863:                       $sth->execute;
  864:                       my ($AuthorId,$Name, $Surname,$other,$Nicks);
  865: 
  866:                       while ((($AuthorId,$Name, $Surname,$Nicks)=$sth->fetchrow),$AuthorId)
  867:                       {
  868:                         my ($firstletter)=$Name=~m/^./g;
  869:                          $Name=~s/\./\\\./g;
  870:                           my $sha="(?:$Name\\s+$Surname)|(?:$Surname\\s+$Name)|(?:$firstletter\\.\\s*$Surname)|(?:$Surname\\s+$firstletter\\.)|(?:$Surname)|(?:$Name)";
  871:                           if ($Nicks)
  872:                           {
  873:                             $Nicks=~s/^\|//;
  874:                             foreach (split /\|/, $Nicks)
  875:                             {
  876:                               s/\s+/ /g;
  877:                               s/\s+$//;
  878:                               s/ /\\s+/g;
  879:                               s/\./\\\./g;
  880:                               if (s/>$//) {$sha="$sha|(?:$_)"}
  881:                               else        {$sha="(?:$_)|$sha"}
  882:                             }
  883:                           }
  884:                           $q=~s/($sha)/a({href=>url."?qofauthor=$AuthorId"},$1)/ei;
  885:                       }
  886: 
  887: 			$output .= &PrintField("Автор(ы)", $q, $text);
  888: 
  889: #                        $output.= &PrintField("Другие вопросы", $other);
  890: 		}
  891: 
  892: 		if ($Question{'Sources'}) {
  893: 			$output .= &PrintField("Источник(и)", $Question{'Sources'}, $text);
  894: 		}
  895: 
  896: 		if ($Question{'Comments'}) {
  897: 			$output .= &PrintField("Комментарии", $Question{'Comments'}, $text);
  898: 		}
  899: 	}
  900: 	$output.=br.a({href=> url."?metod=proxy&qid=$Id"}, 'Близкие вопросы').p
  901:              if $answer;
  902: 	return $output;
  903: }
  904: 
  905: # Returns the total number of questions currently in the DB.
  906: sub GetQNum {
  907: 	my ($dbh) = @_;
  908: 	my ($sth) = $dbh->prepare("SELECT COUNT(*) FROM Questions");
  909: 	$sth->execute;
  910:  	return ($sth->fetchrow)[0];
  911: }
  912: sub GetMaxQId {
  913: 	my ($dbh) = @_;
  914: 	my ($sth) = $dbh->prepare("SELECT MAX(QuestionId) FROM Questions");
  915: 	$sth->execute;
  916:  	return ($sth->fetchrow)[0];
  917: }
  918: 
  919: # Returns Id's of 12 random questions
  920: sub Get12Random {
  921:    my ($dbh, $type, $num) = @_;
  922: 	my ($i, @questions, $q, $t, $sth);
  923: 	my ($qnum) = &GetMaxQId($dbh);
  924: 	my (%chosen);
  925: 	srand;
  926: 
  927:    for ($i = 0; $i < $num; $i++) {
  928:        do {
  929: 	   $q = int(rand($qnum));
  930: 	   $sth = $dbh->prepare("SELECT Type FROM Questions
  931: 				WHERE QuestionId=$q");
  932: 	   $sth->execute;
  933: 	   $t = ($sth->fetchrow)[0];
  934:        } until !$chosen{$q} && $t && $type =~ /[$t]/;
  935:        $chosen{$q} = 'y';
  936:        push @questions, $q;
  937:    }
  938:    return @questions;
  939: }
  940: 
  941: sub Include_virtual {
  942: 	my ($fn, $output) = (@_, '');
  943: 
  944: 	open F , $fn
  945: 		or return; #die "Can't open the file $fn: $!\n";
  946: 
  947: 	while (<F>) {
  948: 		if (/<!--#include/o) {
  949: 			s/<!--#include virtual="\/(.*)" -->/&Include_virtual($1)/e;
  950: 		}
  951: 		if (/<!--#exec/o) {
  952: 			s/<!--#exec.*cmd\s*=\s*"([^"]*)".*-->/`$1`/e;
  953: 		}
  954: 		$output .= $_;
  955: 	}
  956: 	return $output;
  957: }
  958: 
  959: sub PrintArchive {
  960: 	my($dbh, $Id) = @_;
  961: 	my ($output, @list, $i);
  962: 
  963: 	my (%Tournament) = &GetTournament($dbh, $Id);
  964: 	my (@Tours) = &GetTours($dbh, $Id);
  965: 
  966: 	if ($Tournament{'Type'} =~ /Г/ || $Id == 0) {
  967: 		for ($i = 0; $i <= $#Tours; $i++) {
  968: 			push(@list ,&PrintArchive($dbh, $Tours[$i]));
  969: 		}
  970: 		return @list;
  971: 	}
  972: 	return "$SRCPATH/$Tournament{'FileName'} ";
  973: }
  974: 
  975: sub PrintAll {
  976: 	my ($dbh, $Id) = @_;
  977: 	my ($output, $list, $i);
  978: 
  979: 	my (%Tournament) = &GetTournament($dbh, $Id);
  980: 	my (@Tours) = &GetTours($dbh, $Id);
  981: 	my ($New) = ($Id and $Tournament{'Type'} eq 'Ч' and
  982: 		&NewEnough($Tournament{"CreatedAt"})) ?
  983: 		img({src=>"/znatoki/dimrub/db/new-sml.gif", alt=>"NEW!"}) : "";
  984: 
  985: 	if ($Id == 0) {
  986: 		$output = h3("Все турниры");
  987: 	} else {
  988: 		$output .= dd(img({src=>"/icons/folder.gif", alt=>"[*]"}) .
  989:       " " . a({href=>url . "?tour=$Tournament{'Id'}&answer=0"},
  990:       $Tournament{'Title'}) ." " . $Tournament{'PlayedAt'} . " $New");
  991: 	}
  992: 	if ($Id == 0 or $Tournament{'Type'} =~ /Г/) {
  993: 		for ($i = 0; $i <= $#Tours; $i++) {
  994: 			$list .= &PrintAll($dbh, $Tours[$i]);
  995: 		}
  996: 		$output .= dl($list);
  997: 	}
  998: 	return $output;
  999: }
 1000: 
 1001: sub PrintDates {
 1002: 	my ($dbh) = @_;
 1003: 	my ($from) = param('from_year') . "-" . param('from_month') .
 1004: 		"-" .  param('from_day');
 1005: 	my ($to) = param('to_year') . "-" . param('to_month') . "-" .  param('to_day');
 1006: 	$from = $dbh->quote($from);
 1007: 	$to = $dbh->quote($to);
 1008: 	my ($sth) = $dbh->prepare("
 1009: 		SELECT DISTINCT Id
 1010: 		FROM Tournaments
 1011: 		WHERE PlayedAt >= $from AND PlayedAt <= $to
 1012: 		AND Type = 'Ч'
 1013: 	");
 1014: 	$sth->execute;
 1015: 	my (%Tournament, @array, $output, $list);
 1016: 
 1017: 	$output = h3("Список турниров, проходивших между $from и $to.");
 1018: 	while (@array = $sth->fetchrow) {
 1019: 		next
 1020: 			if (!$array[0]);
 1021: 		%Tournament = &GetTournament($dbh, $array[0]);
 1022:       $list .= dd(img({src=>"/icons/folder.gif", alt=>"[*]"}) .
 1023:       " " . a({href=>url . "?tour=$Tournament{'Id'}&answer=0"},
 1024:       $Tournament{'Title'}, $Tournament{'PlayedAt'}));
 1025: 	}
 1026: 	$output .= dl($list);
 1027: 	return $output;
 1028: }
 1029: 
 1030: sub PrintQOfAuthor
 1031: {
 1032:     my ($dbh, $id) = @_;
 1033:    $id=$dbh->quote($id);
 1034:     my $sth =  $dbh->prepare("SELECT  Name, Surname FROM Authors WHERE Id=$id");
 1035:     $sth->execute;
 1036:     my ($name,$surname)=$sth->fetchrow;
 1037: 
 1038:     $sth =  $dbh->prepare("SELECT Question FROM A2Q WHERE Author=$id");
 1039:     $sth->execute;
 1040:     my $q;
 1041:     my @Questions;
 1042:     while (($q)=$sth->fetchrow,$q)
 1043:      {push @Questions,$q unless $forbidden{$q}}
 1044: 
 1045:     my ($output, $i, $suffix, $hits) = ('', 0, '', $#Questions + 1);
 1046: 
 1047:     if ($hits =~ /1.$/  || $hits =~ /[5-90]$/) {
 1048: 		$suffix = 'й';
 1049: 	} elsif ($hits =~ /1$/) {
 1050: 		$suffix = 'е';
 1051: 	} else {
 1052: 		$suffix = 'я';
 1053: 	}
 1054: 
 1055: 	print p({align=>"center"}, "Автор ".strong("$name $surname. ")
 1056: 	. " : $hits попадани$suffix.");
 1057: 
 1058: 
 1059: #	for ($i = 0; $i <= $#Questions; $i++) {
 1060: #		$output = &PrintQuestion($dbh, $Questions[$i], 1, $i + 1, 1);
 1061: #		print $output;
 1062: #	}
 1063:         PrintList($dbh,\@Questions,'gdfgdfgdfgdfg');
 1064: }
 1065: 
 1066: 
 1067: sub PrintAuthors
 1068: {
 1069:      my ($dbh,$sort)=@_;
 1070:      my($output,$out1,@array,$sth);
 1071:      if ($sort eq 'surname')
 1072:      {
 1073:         $sth =
 1074:              $dbh->prepare("SELECT Id, Name, Surname, QNumber FROM Authors order by Surname, Name");
 1075:      }
 1076:      elsif($sort eq 'name')
 1077:      {
 1078:         $sth =
 1079:              $dbh->prepare("SELECT Id, Name, Surname, QNumber FROM Authors order by Name, Surname");
 1080:      }
 1081:      else
 1082:      {
 1083:         $sth =
 1084:              $dbh->prepare("SELECT Id, Name, Surname, QNumber FROM Authors Order by QNumber DESC, Surname");
 1085:      }
 1086: 
 1087:      $output.=h2("Авторы вопросов")."\n";
 1088:      $output.="<TABLE>";
 1089: 
 1090: 
 1091:      $sth->execute;
 1092:      $output.=Tr(th[a({href=>url."?authors=name"},"Имя")
 1093: .", ".
 1094: a({href=>url."?authors=surname"},"фамилия")
 1095:      , a({href=>url."?authors=kvo"},"Количество вопросов")]);
 1096: 
 1097:      $out1='';
 1098: 
 1099:      my $ar=$sth->fetchall_arrayref;
 1100: 
 1101: 
 1102: 
 1103:     foreach my $arr(@$ar)
 1104:      {
 1105: 
 1106:            my ($id,$name,$surname,$kvo)=@$arr;
 1107:            if (!$name || !$surname) {#print "Opanki at $id\n"
 1108:               } else
 1109:            {
 1110:              my $add=Tr(td([a({href=>url."?qofauthor=$id"},"$name $surname"), $kvo]))."\n";
 1111:              print STDERR $add;
 1112:              $output.=$add;
 1113:            }
 1114:      }
 1115:      $output.="</TABLE>";
 1116:      return $output;
 1117: }
 1118: 
 1119: 
 1120: 
 1121: MAIN:
 1122: {
 1123: 	setlocale(LC_CTYPE,'russian');
 1124: 	my($i, $tour);
 1125: 	my($text) = (param('text')) ? 1 : 0;
 1126: 
 1127: 	my($dbh) = DBI->connect("DBI:mysql:chgk", "piataev", "")
 1128: 		or do {
 1129: 			print h1("Временные проблемы") . "База данных временно не
 1130: 			работает. Заходите попозже.";
 1131: 			print &Include_virtual("../dimrub/db/reklama.html");
 1132: 		    print end_html;
 1133: 			die "Can't connect to DB chgk\n";
 1134: 		};
 1135: 	if (!param('comp') and !param('sqldump') and !$text) {
 1136: 	   print header;
 1137: 	   print start_html(-"title"=>'Database of the questions',
 1138: 	           -author=>'dimrub@icomverse.com',
 1139: 	           -bgcolor=>'#fff0e0',
 1140: 				  -vlink=>'#800020');
 1141: 		print &Include_virtual("../dimrub/db/reklama.html");
 1142: 	}
 1143: 
 1144: if ($^O =~ /win/i) {
 1145: 	$thislocale = "Russian_Russia.20866";
 1146: } else {
 1147: 	$thislocale = "ru_RU.KOI8-R";
 1148: }
 1149: POSIX::setlocale( &POSIX::LC_ALL, $thislocale );
 1150: 
 1151: if ((uc 'а') ne 'А') {print "Koi8-r locale not installed!\n"};
 1152: 
 1153: 
 1154: 	if ($text) {
 1155: 		print header('text/plain');
 1156: 	}
 1157: 
 1158:         if (param('hideequal')) {
 1159: 	           my ($sth)=  $dbh -> prepare("select first, second FROM equalto");
 1160: 	           $sth -> execute;
 1161: 	           while ( my  ($first, $second)=$sth -> fetchrow)
 1162:                   {
 1163:                        $forbidden{$first}=1;
 1164:                   }
 1165:                   $sth->finish;
 1166:         }
 1167: 
 1168: 
 1169: 	if (param('rand')) {
 1170: 		my ($type, $qnum) = ('', 12);
 1171: 		$type .= 'Б' if (param('brain'));
 1172: 		$type .= 'Ч' if (param('chgk'));
 1173: 		$qnum = param('qnum') if (param('qnum') =~ /^\d+$/);
 1174: 		$qnum = 0 if (!$type);
 1175: 		if (param('email') && -x $SENDMAIL &&
 1176: 		open(F, "| $SENDMAIL -t -n")) {
 1177: 			my ($Email) = param('email');
 1178: 			my ($mime_type) = $text ? "plain" : "html";
 1179: 			print F <<EOT;
 1180: To: $Email
 1181: From: olegstemanov\@mail.ru
 1182: Subject: Sluchajnij Paket Voprosov "Chto? Gde? Kogda?"
 1183: MIME-Version: 1.0
 1184: Content-type: text/$mime_type; charset="koi8-r"
 1185: 
 1186: EOT
 1187: 			print F &PrintRandom($dbh, $type, $qnum, $text);
 1188: 			close F;
 1189: 			print "Пакет случайно выбранных вопросов послан. Нажмите
 1190: 			на <B>Reload</B> для получения еще одного пакета";
 1191: 		} else {
 1192: 			print &PrintRandom($dbh, $type, $qnum, $text);
 1193: 		}
 1194: 	}
 1195: 	  elsif (param('authors')){
 1196:                 print &PrintAuthors($dbh,param('authors'));
 1197:         }
 1198:           elsif (param('qofauthor')){
 1199:                 &PrintQOfAuthor($dbh,param('qofauthor'));
 1200:         }
 1201:           elsif (param('sstr')) {
 1202: 		&PrintSearch($dbh, param('sstr'), param('metod'));
 1203: 	} 
 1204: 	  elsif (param('qid')) {
 1205: 	      my $qid=param('qid');
 1206:               my $query="SELECT Question, Answer from Questions where QuestionId=$qid";
 1207: print $query if $printqueries;
 1208: 	      my $sth=$dbh->prepare($query);
 1209: 	      $sth->execute;
 1210: 	      my $sstr= join ' ',$sth->fetchrow;
 1211: 	      $searchin{'question'}=1;
 1212: 	      $searchin{'answer'}=1;
 1213: $sstr=~s/[^йцукенгшщзхъфывапролджэячсмитьбюЙЦУКЕНГШЩЗХЪФЫВАПРОЛДЖЭЯЧСМИТЬБЮa-zA-Z0-9]/ /gi;
 1214: #              print &PrintQuestion($dbh,$qid, 1, '!');
 1215:  	      &PrintSearch($dbh, $sstr, 'proxy');
 1216:  	}
 1217: 
 1218:           elsif (param('all')) {
 1219: 		print &PrintAll($dbh, 0);
 1220: 	} elsif (param('from_year') && param('to_year')) {
 1221: 		print &PrintDates($dbh);
 1222: 	} elsif (param('comp')) {
 1223: 	    print header(
 1224: 			 -'Content-Type' => 'application/x-zip-compressed; name="db.zip"',
 1225: 			 -'Content-Disposition' => 'attachment; filename="db.zip"'
 1226: 			 );
 1227: 	    $tour = (param('tour')) ? param('tour') : 0;
 1228: 	    my (@files) = &PrintArchive($dbh, $tour);
 1229: 	    open F, "$ZIP -j - $SRCPATH/COPYRIGHT @files |";
 1230: 	    print (<F>);
 1231: 	    close F;
 1232: 	    $dbh->disconnect;
 1233: 	    exit;
 1234: 	} elsif (param('sqldump')) {
 1235: 	    print header(
 1236: 			 -'Content-Type' => 'application/x-zip-compressed; name="dump.zip"',
 1237: 			 -'Content-Disposition' => 'attachment; filename="dump.zip"'
 1238: 			 );
 1239: 	    open F, "$ZIP -j - $DUMPFILE |";
 1240: 	    print (<F>);
 1241: 	    close F;
 1242: 	    $dbh->disconnect;
 1243: 	    exit;
 1244: 
 1245: 	} else {
 1246: 		$tour = (param('tour')) ? param('tour') : 0;
 1247: 		if ($tour !~ /^[0-9]*$/) {
 1248: 			my ($sth) = $dbh->prepare("SELECT Id FROM Tournaments
 1249: 			WHERE FileName = '$tour.txt'");
 1250: 			$sth->execute;
 1251: 			$tour = ($sth->fetchrow)[0];
 1252: 		}
 1253: 		print &PrintTournament($dbh, $tour, param('answer'));
 1254: 	}
 1255: 	if (!$text) {
 1256: 		print &Include_virtual("../dimrub/db/footer.html");
 1257: 		print end_html;
 1258: 	}
 1259: 	$dbh->disconnect;
 1260: }

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