File:  [Local Repository] / db / prgsrc / db.cgi
Revision 1.37: download - view: text, annotated - select for diffs - revision graph
Mon Nov 26 10:31:49 2001 UTC (22 years, 5 months ago) by roma7
Branches: MAIN
CVS tags: HEAD
There were some bugs

    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, ">errors";
   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{'comment'}=param('Comment');
   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: 
  196:               $query="select questions from word2question where". (join ' OR ', @arr);
  197: print "$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);
  336: 
  337: #	push @fields, 'Question';
  338: 
  339: 	if ($metod eq 'rus')
  340: 	{
  341: 	     my @tasks=russearch($dbh,$sstr,$all,$allnf);
  342: 	     return @tasks
  343: 	}
  344: 
  345: 
  346: ###Simple and advanced query processing. Added by R7
  347: 	if ($metod eq 'simple' || $metod eq 'advanced')
  348: 	{
  349:           foreach (qw/Question Answer Sources Authors Comments/) {
  350: 		if (param($_)) {
  351: 			push @fields, $_;
  352: 		}
  353: 	   }
  354: 
  355: 	   @fields=(qw/Question Answer Sources Authors Comments/) unless scalar @fields;
  356: 	   my $fields=join ",", @fields;
  357:            my $q=new Text::Query($sstr,
  358:                  -parse => 'Text::Query::'.
  359:                    (($metod eq 'simple') ? 'ParseSimple':'ParseAdvanced'),
  360:                  -solve => 'Text::Query::SolveSQL',
  361:                  -build => 'Text::Query::BuildSQLMySQL',
  362:                  -fields_searched => $fields);
  363: 
  364:            $where=	$$q{'matchexp'};
  365:            my $query= "SELECT Questionid FROM Questions
  366:                 WHERE $where";
  367:            print br."Query is: $query".br if $debug;
  368: 
  369:            $sth = $dbh->prepare($query);
  370:          } else
  371: ######
  372:          {
  373: 
  374: 	  foreach (qw/Question Answer Sources Authors Comments/) {
  375: 		if (param($_)) {
  376: 			push @fields, "IFNULL($_, '')";
  377: 		}
  378: 	  }
  379: 	  @sar = split " ", $sstr;
  380: 	  for $i (0 .. $#sar) {
  381: 		$sar[$i] = $dbh->quote("%${sar[$i]}%");
  382: 	  }
  383: 
  384: 	  my($f) = "CONCAT(" . join(',', @fields) . ")";
  385: 	  if (param('all') eq 'yes') {
  386: 		$sstr = join " AND $f LIKE ", @sar;
  387: 	  } else {
  388: 		$sstr = join " OR $f LIKE ", @sar;
  389:     	  }
  390: 
  391:    my $query;
  392:                $query="SELECT QuestionId FROM Questions
  393: 		WHERE $f LIKE $sstr ORDER BY QuestionId";
  394: 
  395: 
  396: print $query if $printqueries;
  397: 	  $sth = $dbh->prepare($query)
  398: 
  399: 	} #else -- processing old-style query (R7)
  400: 
  401: 	$sth->execute;
  402: 	while (@arr = $sth->fetchrow) {
  403: 		push @Questions, $arr[0] unless $forbidden{$arr[0]};
  404: 	}
  405: 
  406: 	return @Questions;
  407: }
  408: 
  409:  # Substitute every letter by a pair (for case insensitive search).
  410:  my (@letters) = qw/аА бБ вВ гГ дД еЕ жЖ зЗ иИ йЙ кК лЛ мМ нН оО
  411:  пП рР сС тТ уУ фФ хХ цЦ чЧ шШ щЩ ьЬ ыЫ эЭ юЮ яЯ/;
  412: 
  413: sub NoCase {
  414: 	my ($sstr) = shift;
  415: 	my ($res);
  416: 
  417: 	if (($res) = grep(/$sstr/, @letters)) {
  418: 		return "[$res]";
  419: 	} else {
  420: 		return $sstr;
  421: 	}
  422: }
  423: 
  424: sub PrintSearch {
  425: 	my ($dbh, $sstr, $metod) = @_;
  426: 	my @allnf;
  427:         my (@Questions) = &Search($dbh, $sstr,$metod,$all,\@allnf);
  428: 	my ($output, $i, $suffix, $hits) = ('', 0, '', $#Questions + 1);
  429: 
  430:         my $shablon;
  431: 
  432:         if ($metod eq 'rus')
  433:         {
  434:            my $where='0';
  435:            $where.= " or w2=$_ " foreach @allnf;
  436:            my $query="select w1 from nests where $where";
  437:            my $sth=$dbh->prepare($query);
  438: print "$query" if $printqueries;
  439: 
  440: 	   $sth->execute;
  441: 	   my @shablon;
  442: 	   while (my @arr = $sth->fetchrow)
  443: 	   {
  444: 	     push @shablon,"(?:$arr[0])";
  445: 	   }
  446:            $shablon= join "|", @shablon;
  447:            $shablon=~s/[её]/\[ЕЁ\]/gi;
  448: #           $shablon=~s/([йцукенгшщзхъфывапролджэячсмитьбюЙЦУКЕНГШЩЗХЪФЫВАПРОЛДЖЭЯЧСМИТЬБЮ])/&NoCase($1)/ge;
  449:            $shablon=qr/$shablon/i;
  450:            print "!$shablon!",br if $printqueries;
  451:         }
  452: 
  453: 
  454: 
  455: 	if ($hits =~ /1.$/  || $hits =~ /[5-90]$/) {
  456: 		$suffix = 'й';
  457: 	} elsif ($hits =~ /1$/) {
  458: 		$suffix = 'е';
  459: 	} else {
  460: 		$suffix = 'я';
  461: 	}
  462: 
  463: 	print p({align=>"center"}, "Результаты поиска на " . strong($sstr)
  464: 	. " : $hits попадани$suffix.");
  465: 
  466: 	if (param('word')) {
  467: 		$sstr = '[ 	\.\,:;]' . $sstr . '[  \.\,:\;]';
  468: 	}
  469: 
  470: 	$sstr =~ s/(.)/&NoCase($1)/ge;
  471: 
  472: 	my(@sar) = split(' ', $sstr);
  473: 	for ($i = 0; $i <= $#Questions; $i++) {
  474: 		$output = &PrintQuestion($dbh, $Questions[$i], 1, $i + 1, 1);
  475:                 if (param('metod') eq 'rus')
  476:                 {
  477: 	             $output=~s/\b($shablon)\b/\<strong\>$1\<\/strong\>/gi;
  478: 	        } else {
  479: 		foreach  (@sar) {
  480: 			$output =~ s/$_/<strong>$&<\/strong>/gs;
  481: 		}}
  482: 		print $output;
  483: 	}
  484: }
  485: 
  486: sub PrintRandom {
  487:    my ($dbh, $type, $num, $text) = @_;
  488:    my (@Questions) = &Get12Random($dbh, $type, $num);
  489: 	my ($output, $i) = ('', 0);
  490: 
  491: 	if ($text) {
  492: 		$output .= "	$num случайных вопросов.\n\n";
  493: 	} else {
  494: 		$output .=
  495: 			h2({align=>"center"}, "$num случайных вопросов.");
  496: 	}
  497: 
  498: 	for ($i = 0; $i <= $#Questions; $i++) {
  499: 		# Passing DB handler, question ID, print answer, question
  500: 		# number, print title, print text/html
  501: 		$output .=
  502: 			&PrintQuestion($dbh, $Questions[$i], 1, $i + 1, 0, $text);
  503: 	}
  504: 	return $output;
  505: }
  506: 
  507: sub PrintTournament {
  508:    my ($dbh, $Id, $answer) = @_;
  509: 	my (%Tournament, @Tours, $i, $list, $qnum, $imgsrc, $alt,
  510: 		$SingleTour);
  511: 	my ($output) = '';
  512: 
  513: 	%Tournament = &GetTournament($dbh, $Id) if ($Id);
  514: 
  515: 	my ($URL) = $Tournament{'URL'};
  516: 	my ($Info) = $Tournament{'Info'};
  517: 	my ($Copyright) = $Tournament{'Copyright'};
  518: 
  519: 	@Tours = &GetTours($dbh, $Id);
  520: 
  521: 	if ($Id) {
  522: 		for ($Tournament{'Type'}) {
  523: 			/Г/ && do {
  524: 				$output .= h2({align=>"center"},
  525: 					      "Группа: $Tournament{'Title'} ",
  526: 					      "$Tournament{'PlayedAt'}") . p . "\n";
  527: 				last;
  528: 			};
  529: 			/Ч/ && do {
  530: 				return &PrintTour($dbh, $Tours[0], $answer)
  531: 					if ($#Tours == 0);
  532: 
  533: 				my $title="Пакет: $Tournament{'Title'}";
  534: 				if ($Tournament{'PlayedAt'}) {
  535: 				    $title .= " $Tournament{'PlayedAt'}";
  536: 				}
  537: 
  538: 				$output .= h2({align=>"center"},
  539: 					"$title") . p . "\n";
  540: 				last;
  541: 			};
  542: 			/Т/ && do {
  543: 				return &PrintTour($dbh, $Id, $answer);
  544: 			};
  545: 		}
  546: 	} else {
  547: 		my ($qnum) = GetQNum($dbh);
  548: 		$output .= h2("Банк Вопросов: $qnum вопросов") . p . "\n";
  549: 	}
  550: 
  551: 	for ($i = 0; $i <= $#Tours; $i++) {
  552: 		%Tournament = &GetTournament($dbh, $Tours[$i]);
  553: 
  554: 		if ($Tournament{'Type'} =~ /Ч/) {
  555: 			$SingleTour = 0;
  556: 			my (@Tours) = &GetTours($dbh, $Tournament{'Id'});
  557: 			$SingleTour = 1
  558: 				if ($#Tours == 0);
  559: 		}
  560: 		if ($Tournament{'QuestionsNum'} > 0) {
  561: 			$qnum = " ($Tournament{'QuestionsNum'} вопрос" .
  562: 				&Suffix($Tournament{'QuestionsNum'}) . ")\n";
  563: 		} else {
  564: 			$qnum = '';
  565: 		}
  566: 		if ($Tournament{'Type'} =~ /Г/) {
  567: 			$imgsrc = "/icons/folder.gif";
  568: 			$alt = "[*]";
  569: 		} else {
  570: 			$imgsrc = "/icons/folder.gif";
  571: 			$alt = "[-]";
  572: 		}
  573: 
  574: 		if ($SingleTour or $Tournament{'Type'} =~ /Т/) {
  575: 			$list .= dd(img({src=>$imgsrc, alt=>$alt})
  576: 				. " " . $Tournament{'Title'} . " " .
  577: 				    $Tournament{'PlayedAt'} . $qnum) .
  578: 				dl(
  579: 					dd("["
  580: 						. a({href=>url .  "?tour=$Tournament{'Id'}&answer=0"},
  581: 						"вопросы") . "] ["
  582:                   . a({href=>url .  "?tour=$Tournament{'Id'}&answer=1"},
  583:                   "вопросы + ответы") . "]")
  584: 				);
  585: 		} else {
  586: 			$list .= dd(a({href=>url . "?tour=$Tournament{'Id'}&comp=1"},
  587: 				img({src=>'/icons/compressed.gif', alt=>'[ZIP]', border=>1}))
  588: 				. " " . img({src=>$imgsrc, alt=>$alt})
  589: 				. " " . a({href=>url . "?tour=$Tournament{'Id'}&answer=0"},
  590: 				$Tournament{'Title'}. " ".
  591: 					  $Tournament{'PlayedAt'}) . $qnum);
  592: 		}
  593: 	}
  594: 	$output .= dl($list);
  595: 
  596: 	if ($URL) {
  597: 		$output .=
  598: 		p("Дополнительная информация об этом турнире - по адресу " .
  599: 			a({-'href'=>$URL}, $URL));
  600: 	}
  601: 
  602: 	if ($Copyright) {
  603: 		$output .= p("Копирайт: " .   $Copyright);
  604: 	}
  605: 
  606: 	if ($Info) {
  607: 		$output .= p($Info);
  608: 	}
  609: 
  610: 	return $output;
  611: }
  612: 
  613: sub Suffix {
  614: 	my ($qnum) = @_;
  615: 	my ($suffix) = 'а' if $qnum =~ /[234]$/;
  616:    $suffix = '' if $qnum =~ /1$/;
  617:    $suffix = 'ов' if $qnum =~ /[567890]$/ || $qnum =~ /1.$/;
  618: 	return $suffix;
  619: }
  620: 
  621: sub IsTour {
  622: 	my ($dbh, $Id) = @_;
  623: 	my ($sth) = $dbh->prepare("SELECT Type FROM Tournaments
  624: 		WHERE Id=$Id");
  625: 	$sth->execute;
  626: 	return ($sth->fetchrow)[0] =~ /Т/;
  627: }
  628: 
  629: # Gets a DB handler (ofcourse) and a tour Id. Prints all the
  630: # question of that tour, according to the options.
  631: sub PrintTour {
  632: 	my ($dbh, $Id, $answer) = @_;
  633: 	my ($output, $q, $bottom, $field) = ('', 0, '', '');
  634: 
  635: 	my (%Tour) = &GetTournament($dbh, $Id);
  636: 	my (@Tours) = &GetTours($dbh, $Tour{'ParentId'});
  637: 	my (%Tournament) = &GetTournament($dbh, $Tour{'ParentId'});
  638: 
  639: 	return 0
  640: 		if ($Tour{'Type'} !~ /Т/);
  641: 
  642: 	my ($qnum) = $Tour{'QuestionsNum'};
  643: 	my ($suffix) = &Suffix($qnum);
  644: 
  645: 	$output .= h2({align=>"center"}, $Tournament{"Title"},
  646: 		      $Tournament{'PlayedAt'},
  647: 		      "<br>", $Tour{"Title"} .
  648: 		" ($qnum вопрос$suffix)\n") . p;
  649: 
  650: 	my (@Questions) = &GetTourQuestions($dbh, $Id);
  651: 	for ($q = 0; $q <= $#Questions; $q++) {
  652: 		$output .= &PrintQuestion($dbh, $Questions[$q], $answer, 0);
  653: 	}
  654: 
  655: 	$output .= hr({-'align'=>'center', -'width'=>'80%'});
  656: 
  657: 	if ($Tournament{'URL'}) {
  658: 		$output .=
  659: 		p("Дополнительная информация об этом турнире - по адресу " .
  660: 			a({-'href'=>$Tournament{'URL'}}, $Tournament{'URL'}));
  661: 	}
  662: 
  663: 	if ($Tournament{'Copyright'}) {
  664: 		$output .= p("Копирайт: " .   $Tournament{'Copyright'});
  665: 	}
  666: 
  667: 	if ($Tournament{'Info'}) {
  668: 		$output .= p($Tournament{'Info'});
  669: 	}
  670: 
  671: 
  672: 	if ($answer == 0) {
  673: 		$bottom .=
  674: 			"[" . a({href=>url . "?tour=$Id&answer=1"}, "ответы") .  "] " . br;
  675: 	}
  676: 	if (&IsTour($dbh, $Id - 1)) {
  677: 		$bottom .=
  678: 			"[" . a({href=>url . "?tour=" . ($Id - 1) . "&answer=0"},
  679: 			"предыдущий тур") . "] ";
  680: 		$bottom .=
  681: 			"[" . a({href=>url . "?tour=" . ($Id - 1) . "&answer=1"},
  682: 			"предыдущий тур с ответами") . "] " . br;
  683: 	}
  684: 	if (&IsTour($dbh, $Id + 1)) {
  685: 		$bottom .=
  686: 			"[" . a({href=>url . "?tour=" . ($Id + 1) . "&answer=0"},
  687: 			"следующий тур") . "] ";
  688: 		$bottom .=
  689: 			"[" . a({href=>url . "?tour=" . ($Id + 1) . "&answer=1"},
  690: 			"следующий тур с ответами") . "] ";
  691: 	}
  692: 
  693: 	$output .=
  694: 		p({align=>"center"}, font({size=>-1}, $bottom));
  695: 
  696: 	return $output;
  697: }
  698: 
  699: sub PrintField {
  700: 	my ($header, $value, $text) = @_;
  701: 	if ($text) {
  702: 	    $value =~ s/<[\/\w]*>//sg;
  703: 	} else {
  704: 	    $value =~ s/^\s+/<br>&nbsp;&nbsp;&nbsp;&nbsp;/mg;
  705: 	    $value =~ s/^\|([^\n]*)/<pre>$1<\/pre>/mg;
  706: 	}
  707: 
  708: 	return $text ? "$header:\n$value\n\n" :
  709: 		strong("$header: ") . $value . p . "\n";
  710: }
  711: 
  712: # Gets a DB handler (ofcourse) and a question Id. Prints
  713: # that question, according to the options.
  714: sub PrintQuestion {
  715: 	my ($dbh, $Id, $answer, $qnum, $title, $text) = @_;
  716: 	my ($output, $titles) = ('', '');
  717: 
  718: 	my (%Question) = &GetQuestion($dbh, $Id);
  719: 	if (!$text) {
  720: 		$output .= hr({width=>"50%"});
  721: 		if ($title) {
  722: 			my (%Tour) = GetTournament($dbh, $Question{'ParentId'});
  723: 			my (%Tournament) = GetTournament($dbh, $Tour{'ParentId'});
  724: 			$titles .=
  725: 				dd(img({src=>"/icons/folder.open.gif"}) . " " .
  726: 					 a({href=>url . "?tour=$Tournament{'Id'}"}, $Tournament{'Title'}, $Tournament{'PlayedAt'}));
  727: 			$titles .=
  728: 				dl(dd(img({src=>"/icons/folder.open.gif"}) . " " .
  729: 					a({href=>url . "?tour=$Tour{'Id'}"}, $Tour{'Title'})));
  730: 		}
  731: 		$output .= dl(strong($titles));
  732: 	}
  733: 
  734: 	$qnum = $Question{'Number'}
  735: 		if ($qnum == 0);
  736: 
  737: 	$output .=
  738: 		&PrintField("Вопрос $qnum", $Question{'Question'}, $text);
  739: 
  740: 	if ($answer) {
  741: 		$output .=
  742: 			&PrintField("Ответ", $Question{'Answer'}, $text);
  743: 
  744: 		if ($Question{'Authors'}) {
  745:                       my $q=$Question{'Authors'};
  746: 
  747: 		      my $sth=$dbh->prepare("select Authors.Id,Name, Surname, Nicks from Authors, A2Q
  748:                                  where Authors.Id=Author And Question=$Id");
  749:                       $sth->execute;
  750:                       my ($AuthorId,$Name, $Surname,$other,$Nicks);
  751: 
  752:                       while ((($AuthorId,$Name, $Surname,$Nicks)=$sth->fetchrow),$AuthorId)
  753:                       {
  754:                         my ($firstletter)=$Name=~m/^./g;
  755: #		        $other.=a({href=>url."?qofauthor=$AuthorId"},"$Name $Surname").". ";
  756:                          $Name=~s/\./\\\./g;
  757:                           my $sha="(?:$Name\\s+$Surname)|(?:$Surname\\s+$Name)|(?:$firstletter\\.\\s*$Surname)|(?:$Surname\\s+$firstletter\\.)|(?:$Surname)|(?:$Name)";
  758:                           if ($Nicks)
  759:                           {
  760:                             $Nicks=~s/^\|//;
  761:                             foreach (split /\|/, $Nicks)
  762:                             {
  763:                               s/\s+/ /g;
  764:                               s/\s+$//;
  765:                               s/ /\\s+/g;
  766:                               s/\./\\\./g;
  767:                               if (s/>$//) {$sha="$sha|(?:$_)"}
  768:                               else        {$sha="(?:$_)|$sha"}
  769:                             }
  770:                           }
  771:                           $q=~s/($sha)/a({href=>url."?qofauthor=$AuthorId"},$1)/ei;
  772:                       }
  773: 
  774: 			$output .= &PrintField("Автор(ы)", $q, $text);
  775: 
  776: #                        $output.= &PrintField("Другие вопросы", $other);
  777: 		}
  778: 
  779: 		if ($Question{'Sources'}) {
  780: 			$output .= &PrintField("Источник(и)", $Question{'Sources'}, $text);
  781: 		}
  782: 
  783: 		if ($Question{'Comments'}) {
  784: 			$output .= &PrintField("Комментарии", $Question{'Comments'}, $text);
  785: 		}
  786: 	}
  787: 	return $output;
  788: }
  789: 
  790: # Returns the total number of questions currently in the DB.
  791: sub GetQNum {
  792: 	my ($dbh) = @_;
  793: 	my ($sth) = $dbh->prepare("SELECT COUNT(*) FROM Questions");
  794: 	$sth->execute;
  795:  	return ($sth->fetchrow)[0];
  796: }
  797: sub GetMaxQId {
  798: 	my ($dbh) = @_;
  799: 	my ($sth) = $dbh->prepare("SELECT MAX(QuestionId) FROM Questions");
  800: 	$sth->execute;
  801:  	return ($sth->fetchrow)[0];
  802: }
  803: 
  804: # Returns Id's of 12 random questions
  805: sub Get12Random {
  806:    my ($dbh, $type, $num) = @_;
  807: 	my ($i, @questions, $q, $t, $sth);
  808: 	my ($qnum) = &GetMaxQId($dbh);
  809: 	my (%chosen);
  810: 	srand;
  811: 
  812:    for ($i = 0; $i < $num; $i++) {
  813:        do {
  814: 	   $q = int(rand($qnum));
  815: 	   $sth = $dbh->prepare("SELECT Type FROM Questions
  816: 				WHERE QuestionId=$q");
  817: 	   $sth->execute;
  818: 	   $t = ($sth->fetchrow)[0];
  819:        } until !$chosen{$q} && $t && $type =~ /[$t]/;
  820:        $chosen{$q} = 'y';
  821:        push @questions, $q;
  822:    }
  823:    return @questions;
  824: }
  825: 
  826: sub Include_virtual {
  827: 	my ($fn, $output) = (@_, '');
  828: 
  829: 	open F , $fn
  830: 		or return; #die "Can't open the file $fn: $!\n";
  831: 
  832: 	while (<F>) {
  833: 		if (/<!--#include/o) {
  834: 			s/<!--#include virtual="\/(.*)" -->/&Include_virtual($1)/e;
  835: 		}
  836: 		if (/<!--#exec/o) {
  837: 			s/<!--#exec.*cmd\s*=\s*"([^"]*)".*-->/`$1`/e;
  838: 		}
  839: 		$output .= $_;
  840: 	}
  841: 	return $output;
  842: }
  843: 
  844: sub PrintArchive {
  845: 	my($dbh, $Id) = @_;
  846: 	my ($output, @list, $i);
  847: 
  848: 	my (%Tournament) = &GetTournament($dbh, $Id);
  849: 	my (@Tours) = &GetTours($dbh, $Id);
  850: 
  851: 	if ($Tournament{'Type'} =~ /Г/ || $Id == 0) {
  852: 		for ($i = 0; $i <= $#Tours; $i++) {
  853: 			push(@list ,&PrintArchive($dbh, $Tours[$i]));
  854: 		}
  855: 		return @list;
  856: 	}
  857: 	return "$SRCPATH/$Tournament{'FileName'} ";
  858: }
  859: 
  860: sub PrintAll {
  861: 	my ($dbh, $Id) = @_;
  862: 	my ($output, $list, $i);
  863: 
  864: 	my (%Tournament) = &GetTournament($dbh, $Id);
  865: 	my (@Tours) = &GetTours($dbh, $Id);
  866: 	my ($New) = ($Id and $Tournament{'Type'} eq 'Ч' and
  867: 		&NewEnough($Tournament{"CreatedAt"})) ?
  868: 		img({src=>"/znatoki/dimrub/db/new-sml.gif", alt=>"NEW!"}) : "";
  869: 
  870: 	if ($Id == 0) {
  871: 		$output = h3("Все турниры");
  872: 	} else {
  873: 		$output .= dd(img({src=>"/icons/folder.gif", alt=>"[*]"}) .
  874:       " " . a({href=>url . "?tour=$Tournament{'Id'}&answer=0"},
  875:       $Tournament{'Title'}) ." " . $Tournament{'PlayedAt'} . " $New");
  876: 	}
  877: 	if ($Id == 0 or $Tournament{'Type'} =~ /Г/) {
  878: 		for ($i = 0; $i <= $#Tours; $i++) {
  879: 			$list .= &PrintAll($dbh, $Tours[$i]);
  880: 		}
  881: 		$output .= dl($list);
  882: 	}
  883: 	return $output;
  884: }
  885: 
  886: sub PrintDates {
  887: 	my ($dbh) = @_;
  888: 	my ($from) = param('from_year') . "-" . param('from_month') .
  889: 		"-" .  param('from_day');
  890: 	my ($to) = param('to_year') . "-" . param('to_month') . "-" .  param('to_day');
  891: 	$from = $dbh->quote($from);
  892: 	$to = $dbh->quote($to);
  893: 	my ($sth) = $dbh->prepare("
  894: 		SELECT DISTINCT Id
  895: 		FROM Tournaments
  896: 		WHERE PlayedAt >= $from AND PlayedAt <= $to
  897: 		AND Type = 'Ч'
  898: 	");
  899: 	$sth->execute;
  900: 	my (%Tournament, @array, $output, $list);
  901: 
  902: 	$output = h3("Список турниров, проходивших между $from и $to.");
  903: 	while (@array = $sth->fetchrow) {
  904: 		next
  905: 			if (!$array[0]);
  906: 		%Tournament = &GetTournament($dbh, $array[0]);
  907:       $list .= dd(img({src=>"/icons/folder.gif", alt=>"[*]"}) .
  908:       " " . a({href=>url . "?tour=$Tournament{'Id'}&answer=0"},
  909:       $Tournament{'Title'}, $Tournament{'PlayedAt'}));
  910: 	}
  911: 	$output .= dl($list);
  912: 	return $output;
  913: }
  914: 
  915: sub PrintQOfAuthor
  916: {
  917:     my ($dbh, $id) = @_;
  918:    $id=$dbh->quote($id);
  919:     my $sth =  $dbh->prepare("SELECT  Name, Surname FROM Authors WHERE Id=$id");
  920:     $sth->execute;
  921:     my ($name,$surname)=$sth->fetchrow;
  922: 
  923:     $sth =  $dbh->prepare("SELECT Question FROM A2Q WHERE Author=$id");
  924:     $sth->execute;
  925:     my $q;
  926:     my @Questions;
  927:     while (($q)=$sth->fetchrow,$q)
  928:      {push @Questions,$q unless $forbidden{$q}}
  929: 
  930:     my ($output, $i, $suffix, $hits) = ('', 0, '', $#Questions + 1);
  931: 
  932:     if ($hits =~ /1.$/  || $hits =~ /[5-90]$/) {
  933: 		$suffix = 'й';
  934: 	} elsif ($hits =~ /1$/) {
  935: 		$suffix = 'е';
  936: 	} else {
  937: 		$suffix = 'я';
  938: 	}
  939: 
  940: 	print p({align=>"center"}, "Автор ".strong("$name $surname. ")
  941: 	. " : $hits попадани$suffix.");
  942: 
  943: 
  944: 	for ($i = 0; $i <= $#Questions; $i++) {
  945: 		$output = &PrintQuestion($dbh, $Questions[$i], 1, $i + 1, 1);
  946: 		print $output;
  947: 	}
  948: }
  949: 
  950: 
  951: sub PrintAuthors
  952: {
  953:      my ($dbh,$sort)=@_;
  954:      my($output,$out1,@array,$sth);
  955:      if ($sort eq 'surname')
  956:      {
  957:         $sth =
  958:              $dbh->prepare("SELECT Id, Name, Surname, QNumber FROM Authors order by Surname, Name");
  959:      }
  960:      elsif($sort eq 'name')
  961:      {
  962:         $sth =
  963:              $dbh->prepare("SELECT Id, Name, Surname, QNumber FROM Authors order by Name, Surname");
  964:      }
  965:      else
  966:      {
  967:         $sth =
  968:              $dbh->prepare("SELECT Id, Name, Surname, QNumber FROM Authors Order by QNumber DESC, Surname");
  969:      }
  970: 
  971:      $output.=h2("Авторы вопросов")."\n";
  972:      $output.="<TABLE>";
  973: 
  974: 
  975:      $sth->execute;
  976:      $output.=Tr(th[a({href=>url."?authors=name"},"Имя")
  977: .", ".
  978: a({href=>url."?authors=surname"},"фамилия")
  979:      , a({href=>url."?authors=kvo"},"Количество вопросов")]);
  980: 
  981:      $out1='';
  982: 
  983:      my $ar=$sth->fetchall_arrayref;
  984: 
  985: 
  986: 
  987:     foreach my $arr(@$ar)
  988:      {
  989: 
  990:            my ($id,$name,$surname,$kvo)=@$arr;
  991:            if (!$name || !$surname) {#print "Opanki at $id\n"
  992:               } else
  993:            {
  994:              my $add=Tr(td([a({href=>url."?qofauthor=$id"},"$name $surname"), $kvo]))."\n";
  995:              print STDERR $add;
  996:              $output.=$add;
  997:            }
  998:      }
  999:      $output.="</TABLE>";
 1000:      return $output;
 1001: }
 1002: 
 1003: 
 1004: 
 1005: MAIN:
 1006: {
 1007: 	setlocale(LC_CTYPE,'russian');
 1008: 	my($i, $tour);
 1009: 	my($text) = (param('text')) ? 1 : 0;
 1010: 
 1011: 	my($dbh) = DBI->connect("DBI:mysql:chgk", "piataev", "")
 1012: 		or do {
 1013: 			print h1("Временные проблемы") . "База данных временно не
 1014: 			работает. Заходите попозже.";
 1015: 			print &Include_virtual("../dimrub/db/reklama.html");
 1016: 		    print end_html;
 1017: 			die "Can't connect to DB chgk\n";
 1018: 		};
 1019: 	if (!param('comp') and !param('sqldump') and !$text) {
 1020: 	   print header;
 1021: 	   print start_html(-"title"=>'Database of the questions',
 1022: 	           -author=>'dimrub@icomverse.com',
 1023: 	           -bgcolor=>'#fff0e0',
 1024: 				  -vlink=>'#800020');
 1025: 		print &Include_virtual("../dimrub/db/reklama.html");
 1026: 	}
 1027: 
 1028: if ($^O =~ /win/i) {
 1029: 	$thislocale = "Russian_Russia.20866";
 1030: } else {
 1031: 	$thislocale = "ru_RU.KOI8-R";
 1032: }
 1033: POSIX::setlocale( &POSIX::LC_ALL, $thislocale );
 1034: 
 1035: if ((uc 'а') ne 'А') {print "Koi8-r locale not installed!\n"};
 1036: 
 1037: 
 1038: 	if ($text) {
 1039: 		print header('text/plain');
 1040: 	}
 1041: 
 1042:         if (param('hideequal')) {
 1043: 	           my ($sth)=  $dbh -> prepare("select first, second FROM equalto");
 1044: 	           $sth -> execute;
 1045: 	           while ( my  ($first, $second)=$sth -> fetchrow)
 1046:                   {
 1047:                        $forbidden{$first}=1;
 1048:                   }
 1049:                   $sth->finish;
 1050:         }
 1051: 
 1052: 
 1053: 	if (param('rand')) {
 1054: 		my ($type, $qnum) = ('', 12);
 1055: 		$type .= 'Б' if (param('brain'));
 1056: 		$type .= 'Ч' if (param('chgk'));
 1057: 		$qnum = param('qnum') if (param('qnum') =~ /^\d+$/);
 1058: 		$qnum = 0 if (!$type);
 1059: 		if (param('email') && -x $SENDMAIL &&
 1060: 		open(F, "| $SENDMAIL -t -n")) {
 1061: 			my ($Email) = param('email');
 1062: 			my ($mime_type) = $text ? "plain" : "html";
 1063: 			print F <<EOT;
 1064: To: $Email
 1065: From: olegstemanov\@mail.ru
 1066: Subject: Sluchajnij Paket Voprosov "Chto? Gde? Kogda?"
 1067: MIME-Version: 1.0
 1068: Content-type: text/$mime_type; charset="koi8-r"
 1069: 
 1070: EOT
 1071: 			print F &PrintRandom($dbh, $type, $qnum, $text);
 1072: 			close F;
 1073: 			print "Пакет случайно выбранных вопросов послан. Нажмите
 1074: 			на <B>Reload</B> для получения еще одного пакета";
 1075: 		} else {
 1076: 			print &PrintRandom($dbh, $type, $qnum, $text);
 1077: 		}
 1078: 	}
 1079: 	  elsif (param('authors')){
 1080:                 print &PrintAuthors($dbh,param('authors'));
 1081:         }
 1082:           elsif (param('qofauthor')){
 1083:                 &PrintQOfAuthor($dbh,param('qofauthor'));
 1084:         }
 1085:           elsif (param('sstr')) {
 1086: 		&PrintSearch($dbh, param('sstr'), param('metod'));
 1087: 	} elsif (param('all')) {
 1088: 		print &PrintAll($dbh, 0);
 1089: 	} elsif (param('from_year') && param('to_year')) {
 1090: 		print &PrintDates($dbh);
 1091: 	} elsif (param('comp')) {
 1092: 	    print header(
 1093: 			 -'Content-Type' => 'application/x-zip-compressed; name="db.zip"',
 1094: 			 -'Content-Disposition' => 'attachment; filename="db.zip"'
 1095: 			 );
 1096: 	    $tour = (param('tour')) ? param('tour') : 0;
 1097: 	    my (@files) = &PrintArchive($dbh, $tour);
 1098: 	    open F, "$ZIP -j - $SRCPATH/COPYRIGHT @files |";
 1099: 	    print (<F>);
 1100: 	    close F;
 1101: 	    $dbh->disconnect;
 1102: 	    exit;
 1103: 	} elsif (param('sqldump')) {
 1104: 	    print header(
 1105: 			 -'Content-Type' => 'application/x-zip-compressed; name="dump.zip"',
 1106: 			 -'Content-Disposition' => 'attachment; filename="dump.zip"'
 1107: 			 );
 1108: 	    open F, "$ZIP -j - $DUMPFILE |";
 1109: 	    print (<F>);
 1110: 	    close F;
 1111: 	    $dbh->disconnect;
 1112: 	    exit;
 1113: 
 1114: 	} else {
 1115: 		$tour = (param('tour')) ? param('tour') : 0;
 1116: 		if ($tour !~ /^[0-9]*$/) {
 1117: 			my ($sth) = $dbh->prepare("SELECT Id FROM Tournaments
 1118: 			WHERE FileName = '$tour.txt'");
 1119: 			$sth->execute;
 1120: 			$tour = ($sth->fetchrow)[0];
 1121: 		}
 1122: 		print &PrintTournament($dbh, $tour, param('answer'));
 1123: 	}
 1124: 	if (!$text) {
 1125: 		print &Include_virtual("../dimrub/db/footer.html");
 1126: 		print end_html;
 1127: 	}
 1128: 	$dbh->disconnect;
 1129: }

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