File:  [Local Repository] / db / prgsrc / db.cgi
Revision 1.47: download - view: text, annotated - select for diffs - revision graph
Mon Dec 10 20:37:23 2001 UTC (22 years, 5 months ago) by roma7
Branches: MAIN
CVS tags: HEAD
*** empty log message ***

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

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