Annotation of db/prgsrc/db.cgi, revision 1.36
1.29 roma7 1: #!/usr/bin/perl -w
1.1 boris 2:
3: use DBI;
4: use CGI ':all';
1.15 roma7 5: use Text::Query;
1.1 boris 6: use strict;
7: use Time::Local;
8: use POSIX qw(locale_h);
1.22 roma7 9: use locale;
1.36 ! roma7 10: open STDERR, ">errors";
! 11: my $printqueries=1;
! 12: my %forbidden=();
! 13: my $debug=1; #added by R7
1.25 roma7 14: my %fieldname= (0,'Question', 1, 'Answer', 2, 'Comments', 3, 'Authors', 4, 'Sources');
1.22 roma7 15: my %searchin;
16:
17:
18:
19: my $thislocale;
20:
21:
1.23 roma7 22: $searchin{'question'}=param('Question');
23: $searchin{'answer'}=param('Answer');
24: $searchin{'comment'}=param('Comment');
1.25 roma7 25: $searchin{'authors'}=param('Authors');
26: $searchin{'sources'}=param('Sources');
1.22 roma7 27: my $all=param('all');
28: $all=0 if lc $all eq 'no';
1.1 boris 29: my ($PWD) = `pwd`;
30: chomp $PWD;
1.3 boris 31: my ($SRCPATH) = "$PWD/../dimrub/src";
1.8 boris 32: my ($ZIP) = "/home/piataev/bin/zip";
1.11 boris 33: my $DUMPFILE = "/tmp/chgkdump";
1.1 boris 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',
1.3 boris 39: 'Dec', '11',
40: 'Янв', '0', 'Фев', 1, 'Мар', 2, 'Апр', 3, 'Май', '4',
41: 'Июн', '5', 'Июл', 6, 'Авг', '7', 'Сен', '8',
42: 'Окт', '9', 'Ноя', '19', 'Дек', '11');
1.1 boris 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:
1.22 roma7 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:
1.29 roma7 163:
1.22 roma7 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:
1.29 roma7 180:
1.22 roma7 181: my $kvo=0;
182: push @$allnf, @{$_} foreach @nf;
1.35 boris 183: print "nf=@$allnf" if $printqueries;
1.22 roma7 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: {
1.25 roma7 234: ($field,$lo,$hi,$wordnumber)=@blob[$ii..($ii+3)];
1.22 roma7 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:
1.29 roma7 255: #print "keys tasksof", join ' ', keys %{$tasksof{0}};
1.22 roma7 256: #Ищем пересечение или объединение списков вопросов (значений %tasksof)
1.29 roma7 257: foreach $sf (keys %tasksof)
1.22 roma7 258: {
259: $count{$_}++ foreach keys %{$tasksof{$sf}};
260: }
261: @tasks= ($all ? (grep {$count{$_}==$kvo} keys %count) :
262: keys %count) ;
263:
264:
1.29 roma7 265: print "\n\$#tasks=",$#tasks,br if $printqueries;
1.22 roma7 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:
1.35 boris 278: print "tasks=@tasks" if $printqueries;
1.22 roma7 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:
1.1 boris 330:
331: # Returns list of QuestionId's, that have the search string in them.
332: sub Search {
1.22 roma7 333: my ($dbh, $sstr,$metod,$all,$allnf) = @_;
1.1 boris 334: my (@arr, @Questions, @fields);
1.14 roma7 335: my (@sar, $i, $sth,$where);
1.1 boris 336:
1.6 boris 337: # push @fields, 'Question';
1.14 roma7 338:
1.22 roma7 339: if ($metod eq 'rus')
340: {
341: my @tasks=russearch($dbh,$sstr,$all,$allnf);
342: return @tasks
343: }
344:
345:
1.14 roma7 346: ###Simple and advanced query processing. Added by R7
347: if ($metod eq 'simple' || $metod eq 'advanced')
348: {
1.29 roma7 349: foreach (qw/Question Answer Sources Authors Comments/) {
1.14 roma7 350: if (param($_)) {
351: push @fields, $_;
352: }
1.29 roma7 353: }
1.22 roma7 354:
1.14 roma7 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";
1.29 roma7 367: print br."Query is: $query".br if $debug;
1.14 roma7 368:
369: $sth = $dbh->prepare($query);
370: } else
371: ######
372: {
373:
374: foreach (qw/Question Answer Sources Authors Comments/) {
1.1 boris 375: if (param($_)) {
376: push @fields, "IFNULL($_, '')";
377: }
1.14 roma7 378: }
379: @sar = split " ", $sstr;
380: for $i (0 .. $#sar) {
1.1 boris 381: $sar[$i] = $dbh->quote("%${sar[$i]}%");
1.14 roma7 382: }
1.1 boris 383:
1.14 roma7 384: my($f) = "CONCAT(" . join(',', @fields) . ")";
385: if (param('all') eq 'yes') {
1.1 boris 386: $sstr = join " AND $f LIKE ", @sar;
1.14 roma7 387: } else {
1.1 boris 388: $sstr = join " OR $f LIKE ", @sar;
1.14 roma7 389: }
1.36 ! roma7 390:
! 391: my $query;
! 392: $query="SELECT QuestionId FROM Questions
! 393: WHERE $f LIKE $sstr ORDER BY QuestionId";
! 394:
1.21 roma7 395:
1.22 roma7 396: print $query if $printqueries;
397: $sth = $dbh->prepare($query)
1.1 boris 398:
1.14 roma7 399: } #else -- processing old-style query (R7)
400:
1.1 boris 401: $sth->execute;
402: while (@arr = $sth->fetchrow) {
1.36 ! roma7 403: push @Questions, $arr[0] unless $forbidden{$arr[0]};
1.1 boris 404: }
1.22 roma7 405:
1.1 boris 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 {
1.14 roma7 425: my ($dbh, $sstr, $metod) = @_;
1.22 roma7 426: my @allnf;
427: my (@Questions) = &Search($dbh, $sstr,$metod,$all,\@allnf);
1.1 boris 428: my ($output, $i, $suffix, $hits) = ('', 0, '', $#Questions + 1);
429:
1.22 roma7 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:
1.1 boris 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:
1.13 roma7 472: my(@sar) = split(' ', $sstr);
1.1 boris 473: for ($i = 0; $i <= $#Questions; $i++) {
474: $output = &PrintQuestion($dbh, $Questions[$i], 1, $i + 1, 1);
1.22 roma7 475: if (param('metod') eq 'rus')
476: {
477: $output=~s/\b($shablon)\b/\<strong\>$1\<\/strong\>/gi;
478: } else {
1.1 boris 479: foreach (@sar) {
480: $output =~ s/$_/<strong>$&<\/strong>/gs;
1.22 roma7 481: }}
1.1 boris 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"},
1.6 boris 525: "Группа: $Tournament{'Title'} ",
526: "$Tournament{'PlayedAt'}") . p . "\n";
1.1 boris 527: last;
528: };
529: /Ч/ && do {
530: return &PrintTour($dbh, $Tours[0], $answer)
531: if ($#Tours == 0);
1.6 boris 532:
533: my $title="Пакет: $Tournament{'Title'}";
534: if ($Tournament{'PlayedAt'}) {
535: $title .= " $Tournament{'PlayedAt'}";
536: }
1.1 boris 537:
538: $output .= h2({align=>"center"},
1.6 boris 539: "$title") . p . "\n";
1.1 boris 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})
1.6 boris 576: . " " . $Tournament{'Title'} . " " .
577: $Tournament{'PlayedAt'} . $qnum) .
1.1 boris 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"},
1.6 boris 590: $Tournament{'Title'}. " ".
591: $Tournament{'PlayedAt'}) . $qnum);
1.1 boris 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:
1.4 boris 645: $output .= h2({align=>"center"}, $Tournament{"Title"},
1.6 boris 646: $Tournament{'PlayedAt'},
1.4 boris 647: "<br>", $Tour{"Title"} .
1.1 boris 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) {
1.5 boris 702: $value =~ s/<[\/\w]*>//sg;
703: } else {
704: $value =~ s/^\s+/<br> /mg;
705: $value =~ s/^\|([^\n]*)/<pre>$1<\/pre>/mg;
1.1 boris 706: }
1.29 roma7 707:
1.1 boris 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"}) . " " .
1.6 boris 726: a({href=>url . "?tour=$Tournament{'Id'}"}, $Tournament{'Title'}, $Tournament{'PlayedAt'}));
1.1 boris 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'}) {
1.29 roma7 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").". ";
1.36 ! roma7 756: $Name=~s/\./\\\./g;
1.29 roma7 757: my $sha="(?:$Name\\s+$Surname)|(?:$Surname\\s+$Name)|(?:$firstletter\\.\\s*$Surname)|(?:$Surname\\s+$firstletter\\.)|(?:$Surname)|(?:$Name)";
758: $Nicks=~s/^\|//;
759: foreach (split /\|/, $Nicks)
760: {
1.36 ! roma7 761: s/\s+/ /g;
! 762: s/\s+$//;
! 763: s/ /\\s+/g;
! 764: s/\./\\\./g;
1.29 roma7 765: if (s/>$//) {$sha="$sha|(?:$_)"}
766: else {$sha="(?:$_)|$sha"}
767: }
768: $q=~s/($sha)/a({href=>url."?qofauthor=$AuthorId"},$1)/ei;
769: }
770:
771: $output .= &PrintField("Автор(ы)", $q, $text);
772:
773: # $output.= &PrintField("Другие вопросы", $other);
1.1 boris 774: }
775:
776: if ($Question{'Sources'}) {
777: $output .= &PrintField("Источник(и)", $Question{'Sources'}, $text);
778: }
779:
780: if ($Question{'Comments'}) {
781: $output .= &PrintField("Комментарии", $Question{'Comments'}, $text);
782: }
783: }
784: return $output;
785: }
786:
787: # Returns the total number of questions currently in the DB.
788: sub GetQNum {
789: my ($dbh) = @_;
790: my ($sth) = $dbh->prepare("SELECT COUNT(*) FROM Questions");
791: $sth->execute;
792: return ($sth->fetchrow)[0];
793: }
1.12 boris 794: sub GetMaxQId {
795: my ($dbh) = @_;
796: my ($sth) = $dbh->prepare("SELECT MAX(QuestionId) FROM Questions");
797: $sth->execute;
798: return ($sth->fetchrow)[0];
799: }
1.1 boris 800:
801: # Returns Id's of 12 random questions
802: sub Get12Random {
803: my ($dbh, $type, $num) = @_;
804: my ($i, @questions, $q, $t, $sth);
1.12 boris 805: my ($qnum) = &GetMaxQId($dbh);
1.1 boris 806: my (%chosen);
807: srand;
808:
1.11 boris 809: for ($i = 0; $i < $num; $i++) {
810: do {
811: $q = int(rand($qnum));
812: $sth = $dbh->prepare("SELECT Type FROM Questions
1.1 boris 813: WHERE QuestionId=$q");
1.11 boris 814: $sth->execute;
815: $t = ($sth->fetchrow)[0];
816: } until !$chosen{$q} && $t && $type =~ /[$t]/;
817: $chosen{$q} = 'y';
818: push @questions, $q;
819: }
820: return @questions;
1.1 boris 821: }
822:
823: sub Include_virtual {
824: my ($fn, $output) = (@_, '');
825:
826: open F , $fn
1.2 boris 827: or return; #die "Can't open the file $fn: $!\n";
1.1 boris 828:
829: while (<F>) {
830: if (/<!--#include/o) {
831: s/<!--#include virtual="\/(.*)" -->/&Include_virtual($1)/e;
832: }
833: if (/<!--#exec/o) {
834: s/<!--#exec.*cmd\s*=\s*"([^"]*)".*-->/`$1`/e;
835: }
836: $output .= $_;
837: }
838: return $output;
839: }
840:
841: sub PrintArchive {
842: my($dbh, $Id) = @_;
843: my ($output, @list, $i);
844:
845: my (%Tournament) = &GetTournament($dbh, $Id);
846: my (@Tours) = &GetTours($dbh, $Id);
847:
848: if ($Tournament{'Type'} =~ /Г/ || $Id == 0) {
849: for ($i = 0; $i <= $#Tours; $i++) {
850: push(@list ,&PrintArchive($dbh, $Tours[$i]));
851: }
852: return @list;
853: }
854: return "$SRCPATH/$Tournament{'FileName'} ";
855: }
856:
857: sub PrintAll {
858: my ($dbh, $Id) = @_;
859: my ($output, $list, $i);
860:
861: my (%Tournament) = &GetTournament($dbh, $Id);
862: my (@Tours) = &GetTours($dbh, $Id);
863: my ($New) = ($Id and $Tournament{'Type'} eq 'Ч' and
864: &NewEnough($Tournament{"CreatedAt"})) ?
865: img({src=>"/znatoki/dimrub/db/new-sml.gif", alt=>"NEW!"}) : "";
866:
867: if ($Id == 0) {
868: $output = h3("Все турниры");
869: } else {
870: $output .= dd(img({src=>"/icons/folder.gif", alt=>"[*]"}) .
871: " " . a({href=>url . "?tour=$Tournament{'Id'}&answer=0"},
1.6 boris 872: $Tournament{'Title'}) ." " . $Tournament{'PlayedAt'} . " $New");
1.1 boris 873: }
874: if ($Id == 0 or $Tournament{'Type'} =~ /Г/) {
875: for ($i = 0; $i <= $#Tours; $i++) {
876: $list .= &PrintAll($dbh, $Tours[$i]);
877: }
878: $output .= dl($list);
879: }
880: return $output;
881: }
882:
883: sub PrintDates {
884: my ($dbh) = @_;
885: my ($from) = param('from_year') . "-" . param('from_month') .
886: "-" . param('from_day');
887: my ($to) = param('to_year') . "-" . param('to_month') . "-" . param('to_day');
888: $from = $dbh->quote($from);
889: $to = $dbh->quote($to);
890: my ($sth) = $dbh->prepare("
891: SELECT DISTINCT Id
892: FROM Tournaments
893: WHERE PlayedAt >= $from AND PlayedAt <= $to
894: AND Type = 'Ч'
895: ");
896: $sth->execute;
897: my (%Tournament, @array, $output, $list);
898:
899: $output = h3("Список турниров, проходивших между $from и $to.");
900: while (@array = $sth->fetchrow) {
901: next
902: if (!$array[0]);
903: %Tournament = &GetTournament($dbh, $array[0]);
904: $list .= dd(img({src=>"/icons/folder.gif", alt=>"[*]"}) .
905: " " . a({href=>url . "?tour=$Tournament{'Id'}&answer=0"},
1.6 boris 906: $Tournament{'Title'}, $Tournament{'PlayedAt'}));
1.1 boris 907: }
908: $output .= dl($list);
909: return $output;
910: }
911:
1.29 roma7 912: sub PrintQOfAuthor
913: {
914: my ($dbh, $id) = @_;
915: $id=$dbh->quote($id);
916: my $sth = $dbh->prepare("SELECT Name, Surname FROM Authors WHERE Id=$id");
917: $sth->execute;
918: my ($name,$surname)=$sth->fetchrow;
919:
920: $sth = $dbh->prepare("SELECT Question FROM A2Q WHERE Author=$id");
921: $sth->execute;
922: my $q;
923: my @Questions;
924: while (($q)=$sth->fetchrow,$q)
1.36 ! roma7 925: {push @Questions,$q unless $forbidden{$q}}
1.29 roma7 926:
927: my ($output, $i, $suffix, $hits) = ('', 0, '', $#Questions + 1);
928:
929: if ($hits =~ /1.$/ || $hits =~ /[5-90]$/) {
930: $suffix = 'й';
931: } elsif ($hits =~ /1$/) {
932: $suffix = 'е';
933: } else {
934: $suffix = 'я';
935: }
936:
937: print p({align=>"center"}, "Автор ".strong("$name $surname. ")
938: . " : $hits попадани$suffix.");
939:
940:
941: for ($i = 0; $i <= $#Questions; $i++) {
942: $output = &PrintQuestion($dbh, $Questions[$i], 1, $i + 1, 1);
943: print $output;
944: }
945: }
946:
947:
948: sub PrintAuthors
949: {
950: my ($dbh,$sort)=@_;
951: my($output,$out1,@array,$sth);
952: if ($sort eq 'surname')
953: {
954: $sth =
955: $dbh->prepare("SELECT Id, Name, Surname, QNumber FROM Authors order by Surname");
956:
957: $output.="<TABLE><CAPTION>Алфавитный список авторов</CAPTION>";
958: }
959: else
960: {
961: $sth =
962: $dbh->prepare("SELECT Id, Name, Surname, QNumber FROM Authors Order by QNumber DESC");
963: $output.="<TABLE>";
964: }
965:
966: $sth->execute;
967: $output.=Tr(th["Фамилия, имя", "Количество вопросов"]);
968:
969: $out1='';
970:
971: my $ar=$sth->fetchall_arrayref;
972:
973:
1.33 boris 974: =head
975: foreach my $arr(@$ar)
976: {
977: $sth =
978: $dbh->prepare("SELECT count(*) FROM A2Q where Author=".$$arr[0]);
979: $sth->execute;
980:
981: my ($kvo)=$sth->fetchrow;
982:
983:
984:
985: push @$arr, $kvo;
986: }
987:
988: =cut
989:
990:
991: # sort { }@{$ar}
1.29 roma7 992:
993: foreach my $arr(@$ar)
994: {
995:
996: my ($id,$name,$surname,$kvo)=@$arr;
1.33 boris 997: if (!$name || !$surname) {print "Opanki at $id\n"} else
1.29 roma7 998: {
1.33 boris 999: print "!";
1000:
1001: my $add=Tr(td([a({href=>"/cgi-bin/db.cgi?qofauthor=$id"},'[Q] ')."$name $surname", $kvo]))."\n";
1.29 roma7 1002: print STDERR $add;
1003: $output.=$add;
1004: }
1005: }
1006: $output.="</TABLE>";
1007: return $output;
1008: }
1009:
1010:
1011:
1.1 boris 1012: MAIN:
1013: {
1014: setlocale(LC_CTYPE,'russian');
1015: my($i, $tour);
1016: my($text) = (param('text')) ? 1 : 0;
1.36 ! roma7 1017:
1.1 boris 1018: my($dbh) = DBI->connect("DBI:mysql:chgk", "piataev", "")
1019: or do {
1020: print h1("Временные проблемы") . "База данных временно не
1021: работает. Заходите попозже.";
1022: print &Include_virtual("../dimrub/db/reklama.html");
1023: print end_html;
1024: die "Can't connect to DB chgk\n";
1025: };
1.11 boris 1026: if (!param('comp') and !param('sqldump') and !$text) {
1.1 boris 1027: print header;
1028: print start_html(-"title"=>'Database of the questions',
1029: -author=>'dimrub@icomverse.com',
1030: -bgcolor=>'#fff0e0',
1031: -vlink=>'#800020');
1032: print &Include_virtual("../dimrub/db/reklama.html");
1033: }
1.22 roma7 1034:
1035: if ($^O =~ /win/i) {
1036: $thislocale = "Russian_Russia.20866";
1037: } else {
1038: $thislocale = "ru_RU.KOI8-R";
1039: }
1040: POSIX::setlocale( &POSIX::LC_ALL, $thislocale );
1041:
1042: if ((uc 'а') ne 'А') {print "Koi8-r locale not installed!\n"};
1043:
1.1 boris 1044:
1045: if ($text) {
1046: print header('text/plain');
1047: }
1.36 ! roma7 1048:
! 1049: if (param('showequal')) {
! 1050: my ($sth)= $dbh -> prepare("select first, second FROM equalto");
! 1051: $sth -> execute;
! 1052: while ( my ($first, $second)=$sth -> fetchrow)
! 1053: {
! 1054: $forbidden{$first}=1;
! 1055: }
! 1056: $sth->finish;
! 1057: }
! 1058:
1.1 boris 1059:
1060: if (param('rand')) {
1.7 boris 1061: my ($type, $qnum) = ('', 12);
1062: $type .= 'Б' if (param('brain'));
1063: $type .= 'Ч' if (param('chgk'));
1.1 boris 1064: $qnum = param('qnum') if (param('qnum') =~ /^\d+$/);
1.7 boris 1065: $qnum = 0 if (!$type);
1.1 boris 1066: if (param('email') && -x $SENDMAIL &&
1067: open(F, "| $SENDMAIL -t -n")) {
1068: my ($Email) = param('email');
1069: my ($mime_type) = $text ? "plain" : "html";
1070: print F <<EOT;
1071: To: $Email
1.8 boris 1072: From: olegstemanov\@mail.ru
1.1 boris 1073: Subject: Sluchajnij Paket Voprosov "Chto? Gde? Kogda?"
1074: MIME-Version: 1.0
1075: Content-type: text/$mime_type; charset="koi8-r"
1076:
1077: EOT
1078: print F &PrintRandom($dbh, $type, $qnum, $text);
1079: close F;
1080: print "Пакет случайно выбранных вопросов послан. Нажмите
1081: на <B>Reload</B> для получения еще одного пакета";
1082: } else {
1083: print &PrintRandom($dbh, $type, $qnum, $text);
1084: }
1.29 roma7 1085: }
1086: elsif (param('authors')){
1087: print &PrintAuthors($dbh,param('authors'));
1088: }
1089: elsif (param('qofauthor')){
1090: &PrintQOfAuthor($dbh,param('qofauthor'));
1091: }
1092: elsif (param('sstr')) {
1.14 roma7 1093: &PrintSearch($dbh, param('sstr'), param('metod'));
1.1 boris 1094: } elsif (param('all')) {
1095: print &PrintAll($dbh, 0);
1096: } elsif (param('from_year') && param('to_year')) {
1097: print &PrintDates($dbh);
1098: } elsif (param('comp')) {
1.9 boris 1099: print header(
1100: -'Content-Type' => 'application/x-zip-compressed; name="db.zip"',
1101: -'Content-Disposition' => 'attachment; filename="db.zip"'
1102: );
1103: $tour = (param('tour')) ? param('tour') : 0;
1104: my (@files) = &PrintArchive($dbh, $tour);
1105: open F, "$ZIP -j - $SRCPATH/COPYRIGHT @files |";
1106: print (<F>);
1107: close F;
1108: $dbh->disconnect;
1109: exit;
1110: } elsif (param('sqldump')) {
1111: print header(
1112: -'Content-Type' => 'application/x-zip-compressed; name="dump.zip"',
1113: -'Content-Disposition' => 'attachment; filename="dump.zip"'
1114: );
1.10 boris 1115: open F, "$ZIP -j - $DUMPFILE |";
1.9 boris 1116: print (<F>);
1117: close F;
1118: $dbh->disconnect;
1119: exit;
1120:
1.1 boris 1121: } else {
1122: $tour = (param('tour')) ? param('tour') : 0;
1123: if ($tour !~ /^[0-9]*$/) {
1124: my ($sth) = $dbh->prepare("SELECT Id FROM Tournaments
1125: WHERE FileName = '$tour.txt'");
1126: $sth->execute;
1127: $tour = ($sth->fetchrow)[0];
1128: }
1129: print &PrintTournament($dbh, $tour, param('answer'));
1130: }
1131: if (!$text) {
1132: print &Include_virtual("../dimrub/db/footer.html");
1133: print end_html;
1134: }
1135: $dbh->disconnect;
1136: }
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>