File:  [Local Repository] / db / prgsrc / db.cgi
Revision 1.39: download - view: text, annotated - select for diffs - revision graph
Mon Dec 3 02:28:56 2001 UTC (22 years, 5 months ago) by roma7
Branches: MAIN
CVS tags: HEAD
Postavil metod "Post" i zavyol tablitsu queries dlya khraneniya zaprosov

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

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