1: #!/usr/bin/perl -w
2:
3: use DBI;
4: use CGI ':all';
5: use strict;
6: use Time::Local;
7: use POSIX qw(locale_h);
8: use locale;
9: open STDERR, ">/var/tmp/errors1";
10: my $printqueries=0;
11: my %forbidden=();
12: my $debug=0; #added by R7
13: if (param('debug')) {$debug=1; $printqueries=1}
14: *STDERR=*STDOUT if $debug;
15: my %fieldname= (0,'Question', 1, 'Answer', 2, 'Comments', 3, 'Authors', 4, 'Sources');
16: my %rusfieldname=('Question','Вопрос', 'Answer', 'Ответ',
17: 'Comments', 'Комментарии', 'Authors', 'Автор',
18: 'Sources', 'Источник','old','Старый','rus','Новый',
19: 'chgk', 'ЧГК', 'brain', 'Брейн-ринг','game', 'Своя игра',
20: 'ehruditka', 'Эрудитка', 'beskrylka', 'Бескрылка'
21: );
22: my %searchin;
23: my $rl=qr/[йцукенгшщзхъфывапролджэячсмитьбюё]/;
24: my $RL=qr/[ЙЦУКЕНГШЩЗХЪЭЖДЛОРПАВЫФЯЧСМИТЬБЮЁ]/;
25: my $RLrl=qr/(?:(?:${rl})|(?:${RL}))+/;
26: my $l=qr/(?:(?:${RLrl})|(?:[\w\-]))+/;
27: my $Ll=qr/(?:[A-Z])|(?:${RL})/;
28: my %metodchar=('rus',1,'old',2);
29:
30:
31:
32: my $thislocale;
33:
34: $searchin{$_}=1 foreach param('searchin');
35: my %TypeName=('children'=>'Д', 'game'=>'И',
36: 'chgk'=>'Ч', 'brain'=>'Б', 'beskrylka'=>'Л','ehruditka'=>'Э');
37:
38:
39:
40: my $all=param('all');
41: $all=0 if lc $all eq 'no';
42: my ($PWD) = `pwd`;
43: chomp $PWD;
44: my ($SRCPATH) = "/home/piataev/public_html/dimrub/src";
45: my ($ZIP) = "/usr/local/bin/zip";
46: my $DUMPFILE = "/tmp/chgkdump";
47: my ($SENDMAIL) = "/usr/sbin/sendmail";
48: my ($TMPDIR) = "/var/tmp";
49: my ($TMSECS) = 30*24*60*60;
50: my (%RevMonths) =
51: ('Jan', '0', 'Feb', '1', 'Mar', '2', 'Apr', '3', 'May', '4', 'Jun', '5',
52: 'Jul', '6', 'Aug', '7', 'Sep', '8', 'Oct', '9', 'Nov', '10',
53: 'Dec', '11',
54: 'Янв', '0', 'Фев', 1, 'Мар', 2, 'Апр', 3, 'Май', '4',
55: 'Июн', '5', 'Июл', 6, 'Авг', '7', 'Сен', '8',
56: 'Окт', '9', 'Ноя', '19', 'Дек', '11');
57: my @months=('000','Jan',"Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct",
58: "Nov","Dec");
59:
60:
61: # Determine whether the given time is within 2 months from now.
62: sub NewEnough {
63: my ($a) = @_;
64: my ($year, $month, $day) = split('-', $a);
65:
66: return (time - timelocal(0, 0, 0, $day, $month -1, $year) < $TMSECS);
67: }
68:
69: # Reads one question from the DB. Gets DB handler and Question ID.
70: sub GetTournament {
71: my ($dbh, $Id) = @_;
72: my (%Tournament, $field, @arr);
73:
74: return %Tournament if ($Id == 0);
75:
76: my ($sth) = $dbh->prepare("SELECT * FROM Tournaments WHERE Id=$Id");
77: $sth->execute;
78:
79: @arr = $sth->fetchrow;
80: my($i, $name) = 0;
81: foreach $name (@{$sth->{NAME}}) {
82: $Tournament{$name} = $arr[$i++];
83: }
84: $sth->finish;
85: return %Tournament;
86: }
87:
88: # Reads one question from the DB. Gets DB handler and Question ID.
89: sub GetQuestion {
90: my ($dbh, $QuestionId) = @_;
91: my (%Question, $field, @arr);
92:
93: my($sth) = $dbh->prepare("
94: SELECT * FROM Questions WHERE QuestionId=$QuestionId
95: ");
96:
97: $sth->execute;
98:
99: @arr = $sth->fetchrow;
100: my($i, $name) = 0;
101: foreach $name (@{$sth->{NAME}}) {
102: $Question{$name} = $arr[$i++];
103: }
104:
105: $sth->finish;
106: return %Question;
107: }
108:
109: # Gets numbers of all the questions from the given tour.
110: sub GetTourQuestions {
111: my ($dbh, $ParentId) = @_;
112: my (@arr, @Questions);
113:
114: my ($sth) = $dbh->prepare("SELECT QuestionId FROM Questions
115: WHERE ParentId=$ParentId order by Number");
116:
117: $sth->execute;
118:
119: while (@arr = $sth->fetchrow) {
120: push @Questions, $arr[0];
121: }
122:
123: $sth->finish;
124: return @Questions;
125: }
126:
127: # Returns list of children of the given tournament.
128: sub GetTours {
129: my ($dbh, $ParentId) = @_;
130: my (@arr, @Tours);
131:
132: my ($sth) = $dbh->prepare("SELECT Id FROM Tournaments
133: WHERE ParentId=$ParentId ORDER BY Id");
134:
135: $sth->execute;
136:
137: while (@arr = $sth->fetchrow) {
138: push @Tours, $arr[0];
139: }
140: $sth->finish;
141: return @Tours;
142: }
143:
144: sub count
145: {
146: my ($dbh,$word)=@_;
147: print "timeb=".time.br if $debug;
148: $word=$dbh->quote(uc $word);
149: my $query="SELECT number from nests,nf where $word=w1 AND w2=nf.id";
150: my $sth=$dbh->prepare($query);
151: $sth->execute;
152: my @a=$sth->fetchrow;
153: print "timee0=".time.br if $debug;
154: $sth->finish;
155: $a[0]||0;
156: }
157:
158:
159: sub printform
160: {
161:
162: my $submit=submit(-value=>'Поиск');
163: my $inputstring=textfield(-name=>'sstr',
164: -default=>param('sstr')||'',
165: -size=>30,
166: -maxlength=>50);
167: my $qnumber="Выводить по".br. textfield(-name=>'kvo',
168: -default=>param('kvo')||'150',
169: -size=>3,
170: -maxlength=>5). br."вопросов";
171:
172: my @df=keys %searchin;
173: @df=('Question', 'Answer') unless @df;
174: my $fields=checkbox_group('searchin',['Question','Answer','Comments','Authors','Sources'], [@df],
175: 'false',\%rusfieldname);
176: @df=param('type');
177: @df=('chgk','brain','game','ehruditka','beskrylka') unless @df;
178:
179: my $types=checkbox_group('type',['chgk','brain','game','ehruditka','beskrylka'], [@df],
180: 'false',\%rusfieldname);
181: my $metod=radio_group(-name=>'metod',-values=>['old','rus'],
182: -default=>(param('metod')||'rus'),
183: -labels=>\%rusfieldname);
184: my $all=radio_group(-name=>'all',-values=>['yes','no'],
185: -default=>(param('all')||'no'),
186: -labels=>{'yes'=>'Все','no'=>'Любое'});
187:
188: #################################################
189: return start_form(-method=>'get',
190: -action=>url,
191: -enctype=>
192: "application/x-www-form-urlencoded"
193: ).br.
194: table(Tr
195: (
196: td({-valign=>'TOP'},$inputstring.$submit.p."Метод: $metod".p."Слова: $all"),
197: td({-valign=>'TOP'},(' 'x 8).'Поля:'),
198: td({-valign=>'TOP'},$fields),
199: td({-valign=>'TOP'},(' 'x 1).'Типы:'),
200: td({-valign=>'TOP'},$types), td(" "x5),
201: td({-valign=>'TOP'},$qnumber)
202: )
203: )
204:
205: #$fields.
206: #$inputstring.$submit.br.$metod.$all
207: .endform
208: .hr
209:
210: }
211:
212: sub proxy
213: {
214: #print "time0=".time.br if $debug;
215: my ($dbh,$ptext,$allnf)=@_;
216: my $text=$$ptext;
217: $text=~tr/ёЁ/еЕ/;
218: $text=~s/(${RLrl})p(${RLrl})/$1p$2/gom;
219: $text=~s/p(${RLrl})/р$1/gom;
220: $text=~s/(${RLrl})p/$1р/gom;
221: $text=~s/\s+/ /gmo;
222: $text=~s/[^йцукенгшщзхъфывапролджэячсмитьбюЙЦУКЕНГШЩЗХЪФЫВАПРОЛДЖЭЯЧСМИТЬБЮQWERTYUIOPASDFGHJKLZXCVBNM0-9]/ /g;
223: $text=uc $text;
224: my @list= $text=~m/(?:(?:${RLrl})+)|(?:[A-Za-z0-9]+)/gom;
225: my (%c, %good,$sstr);
226: foreach (@list)
227: {
228: $c{$_}=count($dbh,$_)||10000;
229: }
230: my @words=sort {$c{$a}<=> $c{$b}} @list;
231:
232: # $good{$words[$_]}=1 foreach 0..4;
233:
234: foreach (@words)
235: {
236: $good{$_}=1 if $c{$_}<200;
237: }
238:
239: $good{$words[$_]}=0 foreach 16..$#words;
240:
241: # foreach (@list)
242: # {
243: # if ($good{$_})
244: # {
245: # $good{$_}=0;
246: # $sstr.=" $_";
247: # }
248: # }
249: $sstr.=" $_" foreach grep {$good{$_}} @list;
250: print "time05=".time.br if $debug;
251: $$ptext=$sstr;
252: return russearch($dbh,$sstr,0,$allnf);
253: }
254:
255:
256: sub russearch {
257: my ($dbh, $sstr, $all,$allnf)=@_;
258: my (@qw,@w,@tasks,$qw,@arr,$nf,$sth,@nf,$w,$where,$e,@where,%good,$i,%where,$from);
259: my($number,@good,$t,$task,@rho,$rank,%rank,$r2,$r1,$word,$n,@last,$good,@words,%number,$taskid);
260: my ($hi, $lo, $wordnumber,$query,$blob,$field,$sf,$ii);
261: my @frequence;
262: my (@arr1,@ar,@sf,@arr2);
263: my %tasks;
264: my $tasks;
265: my @verybad;
266: my %nf;
267: my %tasksof;
268: my %wordsof;
269: my %relevance;
270: my @blob;
271: my %count;
272:
273: $sstr=~tr/йцукенгшщзхъфывапролджэячсмитьбю/ЙЦУКЕНГШЩЗХЪФЫВАПРОЛДЖЭЯЧСМИТЬБЮ/;
274: @qw=@w =split (' ', uc $sstr);
275:
276: #-----------
277: foreach $i (0..$#w) # заполняем массив @nf начальных форм
278: # $nf[$i] -- ссылка на массив возможных
279: # начальных форм словоформы $i
280: {
281: $qw= $dbh->quote (uc $w[$i]);
282: $query=" select distinct w2 from nests
283: where w1=$qw";
284: print "$query",br if $printqueries;
285: $sth=$dbh -> prepare($query);
286: $sth -> execute;
287: @{$nf[$i]}=();
288: while (@arr = $sth->fetchrow)
289: {
290: push (@{$nf[$i]},$arr[0])
291: }
292: $sth->finish;
293: }
294:
295:
296: my @bad=grep {!@{$nf[$_]}} 0..$#w; # @bad -- номера словоформ,
297: # которых нет в словаре
298:
299: if (@bad) #есть неопознанные словоформы
300: {
301: require "cw.pl";
302: foreach $i(@bad)
303: {
304: if (@arr=checkword($dbh,$w[$i]))
305: {push (@{$nf[$i]}, @arr);}
306: else
307: {push (@verybad,$i);}
308: }
309: }
310: return () if ($all && @verybad);
311:
312:
313: my $kvo=0;
314: push @$allnf, @{$_} foreach @nf;
315: print "nf=@$allnf" if $printqueries;
316:
317: foreach $i (0..$#w) #запросы в базу...
318: {
319: @arr=@{$nf[$i]} if $nf[$i];
320: @arr2=@arr1=@arr;
321:
322:
323:
324:
325: $_= " word2question.word=".$_. ' ' foreach @arr;
326: $_= " nf.id=".$_. ' ' foreach @arr1;
327: # @arr=(0) unless @arr;
328: $query="select questions from word2question where". (join ' OR ', @arr);
329: print STDERR "!$query\n",br if $printqueries;
330:
331: $sth=$dbh -> prepare($query);
332: $sth->execute;
333:
334: @blob=();
335: while (@arr=$sth->fetchrow)
336: {
337: @blob=(@blob,unpack 'C*',$arr[0]);
338: }
339: $sth->finish;
340: $query="select number from nf where ".(join ' OR ', @arr1);
341: print "$query\n",br if $printqueries;
342: $sth=$dbh -> prepare($query);
343: $sth->execute;
344:
345: while (@arr=$sth->fetchrow)
346: {
347: $frequence[$i]+=$arr[0];
348: }
349: $sth->finish;
350:
351:
352: if (@blob < 4)
353: {
354: $tasksof{$i}=undef;
355: } else
356: {
357: $kvo++;
358: $ii=0;
359: while ($ii<$#blob) # создаём хэш %tasksof, ключи которого --
360: # номера искомых словоформ, а значения --
361: # списки вопросов, в которых есть соответствующа
362: # словоформа.
363: # Каждый список в свою очередь также оформлен в
364: # виде хэша, ключи которого -- номера вопросов,
365: # а значения -- списки номеров вхождений. Вот.
366: {
367: ($field,$lo,$hi,$wordnumber)=@blob[$ii..($ii+3)];
368: $ii+=4;
369: my $addnumber=($field >> 4) << 16;
370: $number=(($field >> 4) << 16)+($hi << 8) + $lo;
371: $field=$fieldname{$field & 0xF};
372: if ($searchin{$field})
373: {
374: push @{$tasksof{$i}{$number}}, $wordnumber;
375: # дополнили в хэше, висящем на
376: # словоформе $i в %tasksof список
377: # вхождений $i в вопрос $number.
378: push @{$wordsof{$number}{$i}}, $wordnumber;
379: # дополнили в хэше, висящем на
380: # вопросе $number в %wordsof список
381: # вхождений $i в вопрос $number.
382:
383:
384: }
385: } #while ($ii<$#blob)
386: }
387: } #foreach $i
388:
389: #print "keys tasksof", join ' ', keys %{$tasksof{0}};
390: #Ищем пересечение или объединение списков вопросов (значений %tasksof)
391: foreach $sf (keys %tasksof)
392: {
393: $count{$_}++ foreach keys %{$tasksof{$sf}};
394: }
395: @tasks= ($all ? (grep {$count{$_}==$kvo} keys %count) :
396: keys %count) ;
397:
398:
399: print "\n\$#tasks=",$#tasks,br if $printqueries;
400: ############ Сортировка найденных вопросов
401:
402: foreach (keys %wordsof)
403: {
404: $relevance{$_}=&relevance($#w,$wordsof{$_},\@frequence) if $_
405: }
406:
407: @tasks=sort {$relevance{$b}<=>$relevance{$a}} @tasks;
408:
409:
410: ############
411:
412: print "tasks=@tasks" if $printqueries;
413:
414: #print "$_ $relevance{$_} | " foreach @tasks;
415: #print br;
416: print "allnf=@$allnf",br if $printqueries;
417: return @tasks;
418: }
419:
420:
421: sub distance {
422: # на входе -- номера словоформ и ссылки на
423: # списки вхождений. На выходе -- расстояние,
424: # вычисляемое по формуле min(|b-a-pb+pa|)
425: # pb,pa
426: # (pb и pa -- позиции слов b и a)
427: my ($a,$b,$lista,$listb)=@_;
428: my ($pa,$pb,$min,$curmin);
429: $min=10000;
430: foreach $pa (@$lista)
431: {
432: foreach $pb (@$listb)
433: {
434: $curmin=abs($b-$a-$pb+$pa);
435: $min= $curmin if $curmin<$min;
436: }
437: }
438: return $min;
439:
440: }
441:
442: sub relevance {
443: # На входе -- количество искомых словоформ -1 и
444: # ссылка на hash, ключи которого --
445: # номера словоформ, а значения -- списки вхождений
446:
447: my ($n,$words,$frequence)=@_;
448: my $relevance=0;
449: my ($first,$second,$d);
450: foreach $first (0..$n)
451: {
452: $relevance+=scalar @{$$words{$first}}+1000+1000/$$frequence[$first]
453: if $$words{$first};
454: foreach $second ($first+1..$n)
455: {
456: $d=&distance($first,$second,$$words{$first},$$words{$second});
457: $relevance+=($d>10?0:10-$d)*10;
458: }
459: }
460: return $relevance;
461: }
462:
463:
464:
465: # Returns list of QuestionId's, that have the search string in them.
466: sub Search {
467: my ($dbh, $s,$metod,$all,$allnf) = @_;
468: my $sstr=$$s;
469: my (@arr, @Questions, @fields);
470: my (@sar, $i, $sth,$where,$query);
471: # my $ip=$ENV{'REMOTE_ADDR'};
472:
473: # $ip=$dbh->quote($ip);
474: # $query=
475: # "INSERT into queries (query,metod,searchin,ip)
476: # values (". $dbh->quote($sstr).', '.
477: # $dbh->quote($metod) . ', ' .
478: # $dbh->quote(join ' ', grep $searchin{$_}, keys %searchin) .
479: # ", $ip)";
480: #print $query if $printqueries;
481: # $dbh -> do ($query);
482: if ($metod eq 'rus')
483: {
484: my @tasks=russearch($dbh,$sstr,$all,$allnf);
485: return @tasks
486: }
487: elsif ($metod eq 'proxy')
488: {
489: # $searchin{'question'}=1;
490: # $searchin{'answer'}=1;
491: my @task=proxy($dbh,$s,$allnf);
492: # $$s=$sstr;
493: return @task
494: }
495:
496:
497:
498: ###Simple and advanced query processing. Added by R7
499: if ($metod eq 'simple' || $metod eq 'advanced')
500: {
501: foreach (qw/Question Answer Sources Authors Comments/) {
502: if (param($_)) {
503: push @fields, $_;
504: }
505: }
506:
507: @fields=(qw/Question Answer Sources Authors Comments/) unless scalar @fields;
508: my $fields=join ",", @fields;
509: my $q=new Text::Query($sstr,
510: -parse => 'Text::Query::'.
511: (($metod eq 'simple') ? 'ParseSimple':'ParseAdvanced'),
512: -solve => 'Text::Query::SolveSQL',
513: -build => 'Text::Query::BuildSQLMySQL',
514: -fields_searched => $fields);
515:
516: $where= $$q{'matchexp'};
517: $query= "SELECT Questionid FROM Questions
518: WHERE $where";
519: print br."Query is: $query".br if $debug;
520:
521: $sth = $dbh->prepare($query);
522: } else
523: ######
524: {
525:
526: # foreach (qw/Question Answer Sources Authors Comments/) {
527: foreach (param('searchin')) {
528: # if (param($_)) {
529: push @fields, "IFNULL($_, '')";
530: # }
531: }
532: @sar = split " ", $sstr;
533: for $i (0 .. $#sar) {
534: $sar[$i] = $dbh->quote("%${sar[$i]}%");
535: }
536:
537: my($f) = "CONCAT(" . join(',', @fields) . ")";
538: if (param('all') eq 'yes') {
539: $sstr = join " AND $f LIKE ", @sar;
540: } else {
541: $sstr = join " OR $f LIKE ", @sar;
542: }
543:
544: my $query;
545: $query="SELECT QuestionId FROM Questions
546: WHERE ($f LIKE $sstr) AND (".&makewhere.") ORDER BY QuestionId";
547:
548:
549: print $query if $printqueries;
550: $sth = $dbh->prepare($query)
551: } #else -- processing old-style query (R7)
552:
553: $sth->execute;
554: while (@arr = $sth->fetchrow) {
555: push @Questions, $arr[0] unless $forbidden{$arr[0]};
556: }
557: $sth->finish;
558: print "@Questions" if $printqueries;
559:
560: return @Questions;
561: }
562:
563: sub makewhere {
564: my @type=param('type');
565: my $type='';
566:
567: $type .= ($_=$TypeName{$_}) foreach @type;
568: my $where=' 0 ';
569: foreach (@type) {
570: $where.= " OR (Type ='$_') OR (Type ='$_Д') ";
571: }
572: $where.= "OR (Type='ЧБ')" if ($type=~/Ч|Б/);
573: return $where;
574: }
575:
576: # Substitute every letter by a pair (for case insensitive search).
577: my (@letters) = qw/аА бБ вВ гГ дД еЕ жЖ зЗ иИ йЙ кК лЛ мМ нН оО
578: пП рР сС тТ уУ фФ хХ цЦ чЧ шШ щЩ ьЬ ыЫ эЭ юЮ яЯ/;
579:
580: sub NoCase {
581: my ($sstr) = shift;
582: my ($res);
583:
584: if (($res) = grep(/$sstr/, @letters)) {
585: return "[$res]";
586: } else {
587: return $sstr;
588: }
589: }
590:
591: sub PrintList {
592: my ($dbh,$Questions,$shablon,$was)=@_;
593:
594: my $first=param('first') ||1;
595: my $kvo=param('kvo') ||150;
596:
597: $first=$first-($first-1)%$kvo;
598: my $last=$first+$kvo-1;
599: $last=scalar @$Questions if scalar @$Questions <$last;
600: my($f,$l);
601: my $nav='';
602: my $qs=query_string;
603: $qs=~s/\;/\&/g;
604: $qs=~s/\&first\=[^\&]+//g;
605: my $sstr=param('sstr')||'';
606: $qs=~s/sstr=[^\&]+/sstr=$sstr/;
607: $qs=~s/\&was=[^\&]+//;
608: $qs.="&was=$was"||'';
609: if ($first>$kvo*3+1)
610: {
611: $nav.=
612: (" "x4).
613: a({href=>url."?".$qs."\&first=1"},"<<").(" "x4).
614: a({href=>(url."?".$qs."\&first=".($first-$kvo))},"<").(" "x4)
615: }
616:
617: else {$nav.=' 'x15;}
618:
619: my ($fprint,$lprint);
620: my $llprint=$#$Questions- ($#$Questions+1)%$kvo+2;
621: if ($#$Questions+1<=$kvo*7)
622: { $fprint=1;
623: $lprint=$llprint;
624: }
625: elsif ($first>$kvo*3 && $#$Questions+1-$first>$kvo*3)
626: {
627: $fprint=$first-$kvo*3;
628: $lprint=$first+$kvo*3;
629: }
630: elsif ($first<=$kvo*3)
631: {
632: $fprint=1; $lprint=6*$kvo+1;
633: }
634: else
635: {
636: $lprint=$llprint;
637: $fprint=$lprint-$kvo*6
638: }
639:
640: # my $fprint=($first>$kvo*3) ? $first-$kvo*3 : 1;
641: # my $lprint=$#$Questions+1-$fprint>$kvo*7 ? $kvo*7 :$#$Questions+1;
642: # if ($lprint-$fprint<$kvo*6 && $fprint>1)
643: # {
644: # $fprint=$lprint-$kvo*6;
645: # $fprint=1 if ($fprint<=0)
646: # }
647:
648:
649:
650: for($f=$fprint; $f<=$lprint; $f+=$kvo)
651: {
652: # next if $first-$f>$kvo*3;
653: $l=$f+$kvo-1;
654: $l=$#$Questions+1 if $l>$#$Questions+1;
655: if ($f==$first) {$nav.="[$f-$l] ";}
656: else {
657: $nav.= "[".a({href=>(url."?".$qs."\&first=$f")},"$f-$l")."] ";}
658: }
659: if ($lprint+$kvo<$#$Questions)
660: {
661: $nav.=
662: (" "x4).
663: a({href=>(url."?".$qs."\&first=".($first+$kvo))},">").(" "x4).
664: a({href=>url."?".$qs."\&first=$llprint"},">>").(" "x4)
665: }
666:
667:
668: print "$nav".br."\n";
669: for (my $i = $first; $i <= $last; $i++) {
670: my $output = &PrintQuestion($dbh, $$Questions[$i-1], 1, 0, 1);
671: if (param('metod') && (param('metod') eq 'rus' || param('metod') eq 'proxy'))
672: {
673: $output=~s/\b($shablon)\b/\<strong\>$1\<\/strong\>/gi;
674: } else {
675: $output=~s/($shablon)/\<strong\>$1\<\/strong\>/gi;
676: }
677: print $output;
678: }
679:
680:
681: print "$nav".br."\n";
682:
683: }
684:
685: sub PrintSearch {
686: my ($dbh, $sstr, $metod,$was) = @_;
687: my $t=time;
688: print h2("Поиск в базе вопросов");
689: print printform;
690: my @allnf;
691: my @Questions;
692: if ($was)
693: {
694: my $sth=$dbh->prepare ("select sstr,questions,allnf from lastqueries where id=".param('was'));
695: $sth->execute;
696: my ($q,$nf);
697: ($sstr, $q,$nf)=($sth->fetchrow);
698: @Questions=unpack 'L*',$q;
699: @allnf=unpack 'L*',$nf;
700: $sth->finish;
701: } else
702: {
703: @Questions=&Search($dbh, \$sstr,$metod,$all,\@allnf);
704: my $tmp=$dbh->quote(pack("L*",@Questions));
705: my $qsstr=$dbh->quote($sstr);
706: my $nf=$dbh->quote(pack("L*", @allnf));
707: my $ss=200;
708: do
709: {
710: $was=int rand(32000);
711: }
712: while (--$ss && (!$dbh->do ("insert into lastqueries (id,sstr,questions,allnf)
713: values ($was, $qsstr,$tmp,$nf)")));
714: print "Something is wrong...".br unless $ss;
715: }
716:
717:
718:
719: print p. "Время поиска: " . (time-$t) ." сек.".p;
720: my ($output, $i, $suffix, $hits) = ('', 0, '', $#Questions + 1);
721:
722: my $shablon;
723: $metod='rus' if $metod eq 'proxy';
724: if ($metod eq 'rus')
725: {
726: my $where='0';
727: $where.= " or w2=$_ " foreach @allnf;
728: my $query="select w1 from nests where $where";
729: my $sth=$dbh->prepare($query);
730: print "$query" if $printqueries;
731:
732: $sth->execute;
733: my @shablon;
734: while (my @arr = $sth->fetchrow)
735: {
736: push @shablon,"(?:$arr[0])";
737: }
738: $sth->finish;
739: $shablon= join "|", @shablon;
740: $shablon=~s/[её]/\[ЕЁ\]/gi;
741: # $shablon=~s/([йцукенгшщзхъфывапролджэячсмитьбюЙЦУКЕНГШЩЗХЪФЫВАПРОЛДЖЭЯЧСМИТЬБЮ])/&NoCase($1)/ge;
742: $shablon=qr/$shablon/i;
743: print "!$shablon!",br if $printqueries;
744:
745: }
746:
747:
748:
749: if ($hits =~ /1.$/ || $hits =~ /[5-90]$/) {
750: $suffix = 'й';
751: } elsif ($hits =~ /1$/) {
752: $suffix = 'е';
753: } else {
754: $suffix = 'я';
755: }
756:
757: print p({align=>"center"}, "Результаты поиска на " . strong($sstr)
758: . " : $hits попадани$suffix.");
759:
760: if (param('word')) {
761: $sstr = '[ \.\,:;]' . $sstr . '[ \.\,:\;]';
762: }
763:
764: # $sstr =~ s/(.)/&NoCase($1)/ge;
765:
766: my @sar;
767: if ($metod ne 'rus')
768: {
769: my $ss=$sstr;
770: (@sar) = split(' ', $ss);
771: s/(\W)/\\$1/g foreach (@sar);
772: $shablon=join "|",@sar;
773: }
774: PrintList($dbh,\@Questions,$shablon,$was);
775: }
776:
777: sub PrintRandom {
778: my ($dbh, $type, $num, $text) = @_;
779: my (@Questions) = &Get12Random($dbh, $type, $num);
780: my ($output, $i) = ('', 0);
781:
782: if ($text) {
783: $output .= " $num случайных вопросов.\n\n";
784: } else {
785: $output .=
786: h2({align=>"center"}, "$num случайных вопросов.");
787: }
788:
789: for ($i = 0; $i <= $#Questions; $i++) {
790: # Passing DB handler, question ID, print answer, question
791: # number, print title, print text/html
792: $output .=
793: &PrintQuestion($dbh, $Questions[$i], 1, $i + 1, 0, $text);
794: }
795: return $output;
796: }
797:
798: sub PrintEditor {
799: my $t=shift; #ссылка на Хэш с полями
800: my $ed=$$t{'Editors'}||'';
801: my $edname=($ed=~/\,/ ) ? "Редакторы" : "Редактор" ;
802: return $ed? h4({align=>"center"},"$edname: $ed" ): '';
803: }
804:
805: sub PrintTournament {
806: my ($dbh, $Id, $answer) = @_;
807: my (%Tournament, @Tours, $i, $list, $qnum, $imgsrc, $alt,
808: $SingleTour);
809: my ($output) = '';
810:
811: %Tournament = &GetTournament($dbh, $Id) if ($Id);
812:
813: my ($URL) = $Tournament{'URL'};
814: my ($Info) = $Tournament{'Info'};
815: my ($Copyright) = $Tournament{'Copyright'};
816: my $fname=$Tournament{'FileName'};
817: @Tours = &GetTours($dbh, $Id);
818: $list='';
819: my $textid;
820: if ($Id) {
821: for ($Tournament{'Type'}) {
822: /Г/ && do {
823: $output .= h2({align=>"center"},
824: "Группа: $Tournament{'Title'} ",
825: $Tournament{'PlayedAt'}||'') . p . "\n";
826: last;
827: };
828: /Ч/ && do {
829: return &PrintTour($dbh, $Tours[0], $answer)
830: if ($#Tours == 0);
831:
832: my $title="Пакет: $Tournament{'Title'}";
833: if ($Tournament{'PlayedAt'}) {
834: $title .= " $Tournament{'PlayedAt'}";
835: }
836:
837: $output .= h2({align=>"center"},
838: "$title") . p . "\n";
839: $output.=&PrintEditor(\%Tournament);
840: last;
841: };
842: /Т/ && do {
843: return &PrintTour($dbh, $Id, $answer);
844: };
845: }
846: } else {
847: my ($qnum) = GetQNum($dbh);
848: $output .= h2("Банк Вопросов: $qnum вопрос".&Suffix($qnum))
849: . p . "\n";
850: }
851:
852: for ($i = 0; $i <= $#Tours; $i++) {
853: %Tournament = &GetTournament($dbh, $Tours[$i]);
854:
855: if ($Tournament{'Type'} =~ /Ч/) {
856: $SingleTour = 0;
857: my (@Tours) = &GetTours($dbh, $Tournament{'Id'});
858: $SingleTour = 1
859: if ($#Tours == 0);
860: }
861: if ($Tournament{'QuestionsNum'} > 0) {
862: $qnum = " ($Tournament{'QuestionsNum'} вопрос" .
863: &Suffix($Tournament{'QuestionsNum'}) . ")\n";
864: } else {
865: $qnum = '';
866: }
867: if ($Tournament{'Type'} =~ /Г/) {
868: $SingleTour=0;
869: $imgsrc = "/icons/folder.gif";
870: $alt = "[*]";
871: } else {
872: $imgsrc = "/icons/folder.gif";
873: $alt = "[-]";
874: }
875:
876: my $textid;
877: if ($textid=$Tournament{'FileName'})
878: {
879: $textid=~s/\.txt//;
880: }
881: elsif ($textid=$Tournament{'Number'})
882: {
883: $fname=~s/\.txt//;
884: $textid="$fname.$textid";
885: }
886: else {$textid=$Tournament{'Id'}};
887:
888:
889: if ($SingleTour or $Tournament{'Type'} =~ /Т/) {
890: $list .= dd(img({src=>$imgsrc, alt=>$alt})
891: . " " . $Tournament{'Title'} . " " .
892: $Tournament{'PlayedAt'} . $qnum) .
893: dl(
894: dd("["
895: . a({href=>url . "?tour=$textid&answer=0"},
896: "вопросы") . "] ["
897: . a({href=>url . "?tour=$textid&answer=1"},
898: "вопросы + ответы") . "]")
899: );
900: } else {
901: $list .= dd(a({href=>url . "?tour=$textid&comp=1"},
902: img({src=>'/icons/compressed.gif', alt=>'[ZIP]', border=>1})). " " .
903: img({src=>$imgsrc, alt=>$alt})
904: . " " . a({href=>url . "?tour=$textid&answer=0"},
905: $Tournament{'Title'}. " ".
906: $Tournament{'PlayedAt'}||'') . $qnum);
907: }
908: }
909: $output .= dl($list);
910:
911: if ($URL) {
912: if (url=~/zaba\.ru/ && $URL=~/^\//){$URL="http://info.chgk.info$URL"}
913: $output .=
914: p("Дополнительная информация об этом турнире - по адресу " .
915: a({-'href'=>$URL}, $URL));
916: }
917:
918: if ($Copyright) {
919: $output .= p("Копирайт: " . $Copyright);
920: }
921:
922:
923:
924: if ($Info) {
925: $output .= p($Info);
926: }
927: return $output;
928: }
929:
930: sub Suffix {
931: my ($qnum) = @_;
932: my ($suffix) = 'а' if $qnum =~ /[234]$/;
933: $suffix = '' if $qnum =~ /1$/;
934: $suffix = 'ов' if $qnum =~ /[567890]$/ || $qnum =~ /1.$/;
935: return $suffix;
936: }
937:
938: sub IsTour {
939: my ($dbh, $Id,$n) = @_;
940:
941: my ($sth) ;
942:
943: if (defined $n)
944: { $sth=$dbh->prepare ("select Id FROM Tournaments
945: WHERE ParentId=$Id AND Number=$n");
946: }
947: else
948: {
949: $sth=$dbh->prepare("SELECT Id FROM Tournaments
950: WHERE Id=$Id");
951: }
952: $sth->execute;
953: my $a=($sth->fetchrow)[0];
954: $sth->finish;
955: return $a;
956: }
957:
958: # Gets a DB handler (ofcourse) and a tour Id. Prints all the
959: # question of that tour, according to the options.
960: sub PrintTour {
961: my ($dbh, $Id, $answer) = @_;
962: my ($output, $q, $bottom, $field) = ('', 0, '', '');
963:
964: my (%Tour) = &GetTournament($dbh, $Id);
965: my (@Tours) = &GetTours($dbh, $Tour{'ParentId'});
966: my (%Tournament) = &GetTournament($dbh, $Tour{'ParentId'});
967:
968: return 0
969: if ($Tour{'Type'} !~ /Т/);
970:
971: my ($fname)=$Tournament{'FileName'};
972: $fname=~s/\.txt//;
973: my ($qnum) = $Tour{'QuestionsNum'};
974: my ($suffix) = &Suffix($qnum);
975:
976: $output .= h2({align=>"center"}, $Tournament{"Title"},
977: $Tournament{'PlayedAt'}||'',
978: "<br>", $Tour{"Title"} .
979: " ($qnum вопрос$suffix)\n") . p;
980: $output .=&PrintEditor(\%Tour);
981:
982: my (@Questions) = &GetTourQuestions($dbh, $Id);
983: for ($q = 0; $q <= $#Questions; $q++) {
984: $output .= &PrintQuestion($dbh, $Questions[$q], $answer, 0);
985: }
986:
987: $output .= hr({-'align'=>'center', -'width'=>'80%'});
988:
989: if ($Tournament{'URL'}) {
990: $output .=
991: p("Дополнительная информация об этом турнире - по адресу " .
992: a({-'href'=>$Tournament{'URL'}}, $Tournament{'URL'}));
993: }
994:
995: if ($Tournament{'Copyright'}) {
996: $output .= p("Копирайт: " . $Tournament{'Copyright'});
997: }
998:
999: if ($Tournament{'Info'}) {
1000: $output .= p($Tournament{'Info'});
1001: }
1002:
1003: my $n=$Tour{'Number'};
1004: if ($answer == 0) {
1005: $bottom .=
1006: "[" . a({href=>url . "?tour=$fname.$n&answer=1"}, "ответы") . "] " . br;
1007: }
1008: if ($n>1) {
1009: $bottom .=
1010: "[" . a({href=>url . "?tour=$fname." . ($n - 1) . "&answer=0"},
1011: "предыдущий тур") . "] ";
1012: $bottom .=
1013: "[" . a({href=>url . "?tour=$fname." . ($n - 1) . "&answer=1"},
1014: "предыдущий тур с ответами") . "] " . br;
1015: }
1016: if (&IsTour($dbh, $Tour{'ParentId'}, $n + 1)) {
1017: $bottom .=
1018: "[" . a({href=>url . "?tour=$fname." . ($n + 1) . "&answer=0"},
1019: "следующий тур") . "] ";
1020: $bottom .=
1021: "[" . a({href=>url . "?tour=$fname." . ($n + 1) . "&answer=1"},
1022: "следующий тур с ответами") . "] ";
1023: }
1024:
1025: $output .=
1026: p({align=>"center"}, font({size=>-1}, $bottom));
1027:
1028: return $output;
1029: }
1030:
1031: sub PrintField {
1032: my ($header, $value, $text) = @_;
1033: if ($text) {
1034: $value =~ s/<[\/\w]*?>//sg;
1035: } else {
1036: $value =~ s/^\s+/<br> /mg;
1037: $value =~ s/^\|([^\n]*)/<pre>$1<\/pre>/mg;
1038: $value =~ s/\s+-+\s+/ – /mg;
1039: # $value =~ s/(\s)"/$1“/mg;
1040: # $value =~ s/^"/“/mg;
1041: # $value =~ s/"/”/mg;
1042: }
1043:
1044:
1045: return $text ? "$header:\n$value\n\n" :
1046: strong("$header: ") . $value . p . "\n";
1047: }
1048:
1049: # Gets a DB handler (ofcourse) and a question Id. Prints
1050: # that question, according to the options.
1051: sub PrintQuestion {
1052: my ($dbh, $Id, $answer, $qnum, $title, $text) = @_;
1053: my ($output, $titles) = ('', '');
1054: my (%Question) = &GetQuestion($dbh, $Id);
1055: $qnum = $Question{'Number'}
1056: if ($qnum == 0);
1057: if (!$text) {
1058: $output .= hr({width=>"50%"});
1059: if ($title) {
1060: my (%Tour) = GetTournament($dbh, $Question{'ParentId'});
1061: my (%Tournament) = GetTournament($dbh, $Tour{'ParentId'});
1062: my $fname=$Tournament{'FileName'};
1063: $fname=~s/\.txt//;
1064: $titles .=
1065: dd(img({src=>"/icons/folder.open.gif"}) . " " .
1066: a({href=>url . "?tour=$fname"}, $Tournament{'Title'}, $Tournament{'PlayedAt'}||''));
1067: $titles .=
1068: dl(dd(img({src=>"/icons/folder.open.gif"}) . " " .
1069: a({href=>url . "?tour=$fname.$Tour{Number}#$qnum"}, $Tour{'Title'})));
1070: }
1071: $output .= dl(strong($titles));
1072: }
1073:
1074:
1075: $output.= "<a NAME=\"$qnum\">";
1076:
1077: $output .=
1078: &PrintField("Вопрос $qnum", $Question{'Question'}, $text);
1079:
1080: if ($answer==1) {
1081: $output .=
1082: &PrintField("Ответ", $Question{'Answer'}, $text);
1083:
1084: if ($Question{'Authors'}) {
1085: my $q=$Question{'Authors'};
1086: ###АВТОРА!!
1087: my $sth=$dbh->prepare("select Authors.Id,Name, Surname, Nicks from Authors, A2Q
1088: where Authors.Id=Author And Question=$Id");
1089: $sth->execute;
1090: my ($AuthorId,$Name, $Surname,$other,$Nicks);
1091:
1092: while ((($AuthorId,$Name, $Surname,$Nicks)=$sth->fetchrow),$AuthorId)
1093: {
1094: my ($firstletter)=$Name=~m/^./g;
1095: $Name=~s/\./\\\./g;
1096: my $sha="(?:$Name\\s+$Surname)|(?:$Surname\\s+$Name)|(?:$firstletter\\.\\s*$Surname)|(?:$Surname\\s+$firstletter\\.)|(?:$Surname)|(?:$Name)";
1097: if ($Nicks)
1098: {
1099: $Nicks=~s/^\|//;
1100: foreach (split /\|/, $Nicks)
1101: {
1102: s/\s+/ /g;
1103: s/\s+$//;
1104: s/ /\\s+/g;
1105: s/\./\\\./g;
1106: if (s/>$//) {$sha="$sha|(?:$_)"}
1107: else {$sha="(?:$_)|$sha"}
1108: }
1109: }
1110: $q=~s/($sha)/a({href=>url."?qofauthor=$AuthorId"},$1)/ei;
1111: }
1112:
1113: $output .= &PrintField("Автор(ы)", $q, $text);
1114:
1115: }
1116:
1117: if ($Question{'Sources'}) {
1118: $output .= &PrintField("Источник(и)", $Question{'Sources'}, $text);
1119: }
1120:
1121: if ($Question{'Comments'}) {
1122: $output .= &PrintField("Комментарии", $Question{'Comments'}, $text);
1123: }
1124: }
1125: elsif ($answer==2) {
1126: my $text=$Question{'Answer'};
1127: $text=~s/\n/<option>/mg;
1128: $output.="<select><option selected>Ответ:<option>$text</select>";
1129: $text=$Question{'Comments'}||'';
1130: if ($text) {
1131: $text=~s/\n/<option>/mg;
1132: $output.="<select><option selected>Комментарий:<option>$text</select>"
1133: }
1134: }
1135: elsif ($answer==3) {
1136: $output.= <<EOTT
1137: <div align=right STYLE="cursor:hand;" OnStart="toggle(document.all.HideShow$qnum);" OnClick="toggle(document.all.HideShow$qnum);">
1138: <font size=-2 color=red> Показать/убрать ответ</font></div>
1139: <span style="display:none" id=HideShow$qnum>
1140: EOTT
1141: .&PrintField("Ответ", $Question{'Answer'}, $text);
1142: if ($Question{'Authors'}) {
1143: $output .= &PrintField("Автор(ы)", $Question{'Authors'}, $text);
1144: }
1145: if ($Question{'Sources'}) {
1146: $output .= &PrintField("Источник(и)", $Question{'Sources'}, $text);
1147: }
1148:
1149: if ($Question{'Comments'}) {
1150: $output .= &PrintField("Комментарии", $Question{'Comments'}, $text);
1151: }
1152:
1153:
1154: $output.="</span>"
1155:
1156: }
1157: $output.=br.a({href=> url."?metod=proxy&qid=$Id"}, 'Близкие вопросы').p
1158: if $answer;
1159: return $output;
1160: }
1161:
1162: # Returns the total number of questions currently in the DB.
1163: sub GetQNum {
1164: my ($dbh) = @_;
1165: my ($sth) = $dbh->prepare("SELECT COUNT(*) FROM Questions");
1166: $sth->execute;
1167: my $tmp=($sth->fetchrow)[0];
1168: $sth->finish;
1169: return $tmp;
1170: }
1171: sub GetMaxQId {
1172: my ($dbh) = @_;
1173: my ($sth) = $dbh->prepare("SELECT MAX(QuestionId) FROM Questions");
1174: $sth->execute;
1175: my $tmp=($sth->fetchrow)[0];
1176: $sth->finish;
1177: return $tmp;
1178:
1179: }
1180:
1181: # Returns Id's of 12 random questions
1182: sub Get12Random {
1183: my ($dbh, $type, $num) = @_;
1184: my ($i, @questions, $q, $t, $sth);
1185: my ($qnum) = &GetMaxQId($dbh);
1186: my (%chosen);
1187: srand;
1188: my $where=0;
1189: my $r=int (rand(10000));
1190:
1191: foreach (split '', $type)
1192: {
1193: $where.= " OR (Type ='$_') OR (Type ='$_Д') ";
1194: }
1195: $where.= "OR (Type='ЧБ')" if ($type=~/Ч|Б/);
1196:
1197: $q="select QuestionId, QuestionId/$r-floor(QuestionId/$r) as val
1198: from Questions where $where order by val limit $num";
1199: # Когда на куличках появится mysql >=3.23 надо заменить на order by rand();
1200:
1201: $sth=$dbh->prepare($q);
1202: $sth->execute;
1203: while (($i)=$sth->fetchrow)
1204: {
1205: push @questions,$i;
1206: }
1207: $sth->finish;
1208: for ($i=@questions; --$i;){
1209: my $j=rand ($i+1);
1210: @questions[$i,$j]=@questions[$j,$i] unless $i==$j;
1211: }
1212: return @questions;
1213: }
1214:
1215: sub Include_virtual {
1216: my ($fn, $output) = (@_, '');
1217:
1218: open F , $fn
1219: or return; #die "Can't open the file $fn: $!\n";
1220:
1221: while (<F>) {
1222: if (/<!--#include/o) {
1223: s/<!--#include virtual="\/(.*)" -->/&Include_virtual($1)/e;
1224: }
1225: if (/<!--#exec/o) {
1226: s/<!--#exec.*cmd\s*=\s*"([^"]*)".*-->/`$1`/e;
1227: }
1228: $output .= $_;
1229: }
1230: return $output;
1231: }
1232:
1233: sub PrintArchive {
1234: my($dbh, $Id) = @_;
1235: my ($output, @list, $i);
1236:
1237: my (%Tournament) = &GetTournament($dbh, $Id);
1238: my (@Tours) = &GetTours($dbh, $Id);
1239: if ($Tournament{'Type'} =~ /Г/ || $Id == 0) {
1240: for ($i = 0; $i <= $#Tours; $i++) {
1241: push(@list ,&PrintArchive($dbh, $Tours[$i]));
1242: }
1243: return @list;
1244: }
1245: # return "$SRCPATH/$Tournament{'FileName'} ";
1246: return "$TMPDIR/$Tournament{'FileName'} ";
1247: }
1248:
1249: sub PrintAll {
1250: my ($dbh, $Id,$fname) = @_;
1251: my ($output, $list, $i);
1252:
1253: my (%Tournament) = &GetTournament($dbh, $Id);
1254: my (@Tours) = &GetTours($dbh, $Id);
1255: my ($New) = ($Id and $Tournament{'Type'} eq 'Ч' and
1256: &NewEnough($Tournament{"CreatedAt"})) ?
1257: img({src=>"/znatoki/dimrub/db/new-sml.gif", alt=>"NEW!"}) : "";
1258:
1259: if ($Id == 0) {
1260: $output = h3("Все турниры");
1261: } else {
1262: my $textid;
1263: if ($textid=$Tournament{'FileName'})
1264: {
1265: $textid=~s/\.txt//;
1266: }
1267: elsif ($textid=$Tournament{'Number'})
1268: {
1269: $fname=~s/\.txt//;
1270: $textid="$fname.$textid";
1271: }
1272: else {$textid=$Tournament{'Id'}};
1273:
1274:
1275: $output .= dd(img({src=>"/icons/folder.gif", alt=>"[*]"}) .
1276: " " . a({href=>url . "?tour=$textid&answer=0"},
1277: $Tournament{'Title'}) ." " . ($Tournament{'PlayedAt'}||'') . " $New");
1278: }
1279: if ($Id == 0 or $Tournament{'Type'} =~ /Г/ or $Tournament{'Type'} eq '') {
1280: for ($i = 0; $i <= $#Tours; $i++) {
1281: $list .= &PrintAll($dbh, $Tours[$i],$Tournament{'FileName'});
1282: }
1283: $output .= dl($list);
1284: }
1285: return $output;
1286: }
1287:
1288: sub PrintDates {
1289: my ($dbh) = @_;
1290: my ($from) = param('from_year') . "-" . param('from_month') .
1291: "-" . param('from_day');
1292: my ($to) = param('to_year') . "-" . param('to_month') . "-" . param('to_day');
1293: $from = $dbh->quote($from);
1294: $to = $dbh->quote($to);
1295: my ($sth) = $dbh->prepare("
1296: SELECT DISTINCT Id
1297: FROM Tournaments
1298: WHERE PlayedAt >= $from AND PlayedAt <= $to
1299: AND Type = 'Ч'
1300: ");
1301: $sth->execute;
1302: my (%Tournament, @array, $output, $list);
1303:
1304: $output = h3("Список турниров, проходивших между $from и $to.");
1305: while (@array = $sth->fetchrow) {
1306: next
1307: if (!$array[0]);
1308: %Tournament = &GetTournament($dbh, $array[0]);
1309: $list .= dd(img({src=>"/icons/folder.gif", alt=>"[*]"}) .
1310: " " . a({href=>url . "?tour=$Tournament{'Id'}&answer=0"},
1311: $Tournament{'Title'}, $Tournament{'PlayedAt'}||''));
1312: }
1313: $sth->finish;
1314: $output .= dl($list);
1315: return $output;
1316: }
1317:
1318: sub PrintQOfAuthor
1319: {
1320:
1321: my ($dbh, $id) = @_;
1322: $id=$dbh->quote($id);
1323: my $sth = $dbh->prepare("SELECT Name, Surname FROM Authors WHERE Id=$id");
1324: $sth->execute;
1325: my ($name,$surname)=$sth->fetchrow;
1326:
1327: $sth = $dbh->prepare("SELECT Question FROM A2Q WHERE Author=$id");
1328: $sth->execute;
1329: my $q;
1330: my @Questions;
1331: while (($q)=$sth->fetchrow,$q)
1332: {push @Questions,$q unless $forbidden{$q}}
1333: $sth->finish;
1334:
1335: my ($output, $i, $suffix, $hits) = ('', 0, '', $#Questions + 1);
1336:
1337: if ($hits =~ /1.$/ || $hits =~ /[5-90]$/) {
1338: $suffix = 'й';
1339: } elsif ($hits =~ /1$/) {
1340: $suffix = 'е';
1341: } else {
1342: $suffix = 'я';
1343: }
1344: print h2("Поиск в базе вопросов");
1345: print printform;
1346: print p({align=>"center"}, "Автор ".strong("$name $surname. ")
1347: . " : $hits попадани$suffix.");
1348:
1349:
1350: # for ($i = 0; $i <= $#Questions; $i++) {
1351: # $output = &PrintQuestion($dbh, $Questions[$i], 1, $i + 1, 1);
1352: # print $output;
1353: # }
1354: PrintList($dbh,\@Questions,'gdfgdfgdfgdfg');
1355: }
1356:
1357:
1358: sub PrintAuthors
1359: {
1360: my ($dbh,$sort)=@_;
1361: my($output,$out1,@array,$sth);
1362: if ($sort eq 'surname')
1363: {
1364: $sth =
1365: $dbh->prepare("SELECT Id, Name, Surname, QNumber FROM Authors order by Surname, Name");
1366: }
1367: elsif($sort eq 'name')
1368: {
1369: $sth =
1370: $dbh->prepare("SELECT Id, Name, Surname, QNumber FROM Authors order by Name, Surname");
1371: }
1372: else
1373: {
1374: $sth =
1375: $dbh->prepare("SELECT Id, Name, Surname, QNumber FROM Authors Order by QNumber DESC, Surname");
1376: }
1377:
1378: $output.=h2("Авторы вопросов")."\n";
1379: $output.="<TABLE>";
1380:
1381:
1382: $sth->execute;
1383: $output.=Tr(th[a({href=>url."?authors=name"},"Имя")
1384: .", ".
1385: a({href=>url."?authors=surname"},"фамилия")
1386: , a({href=>url."?authors=kvo"},"Количество вопросов")]);
1387:
1388: $out1='';
1389:
1390: my $ar=$sth->fetchall_arrayref;
1391:
1392: $sth->finish;
1393:
1394:
1395: foreach my $arr(@$ar)
1396: {
1397:
1398: my ($id,$name,$surname,$kvo)=@$arr;
1399: if (!$name || !$surname) {#print "Opanki at $id\n"
1400: } else
1401: {
1402: my $add=Tr(td([a({href=>url."?qofauthor=$id"},"$name $surname"), $kvo]))."\n";
1403: print STDERR $add;
1404: $output.=$add;
1405: }
1406: }
1407: $output.="</TABLE>";
1408: $sth->finish;
1409: return $output;
1410: }
1411:
1412:
1413: sub WriteFile {
1414: my ($dbh,$fname) = @_;
1415: $fname=~s/\s+$//;
1416: $fname=~s/^\s+//;
1417: $fname=~s/\.txt$//;
1418: $fname=~s/.*\/(\w+)/$1/;
1419:
1420: my $query= "SELECT Id, Title, Copyright, Info, URL,
1421: Editors, EnteredBy, PlayedAt, CreatedAt
1422: from Tournaments where FileName=".$dbh->quote("$fname.txt");
1423: my $sth=$dbh->prepare($query);
1424: my (%Question,%editor,%qnumber,%copyright,%author,%vid,%tourtitle);
1425: $sth->execute;
1426: my ($Id, $Title, $Copyright, $Info, $URL,
1427: $Editors, $EnteredBy, $PlayedAt, $CreatedAt)=
1428: $sth->fetchrow;
1429: return -1 unless $Id;
1430: open (OUT, ">$TMPDIR/$fname.txt") || print STDERR "Error in $fname.txt\n";
1431: print OUT "Чемпионат:\n$Title\n\n";
1432: my $date=$PlayedAt||'00-00-00';
1433: my ($year,$month,$day)=split /-/, $date;
1434: # $month=0,$date=0 if $year && $month==1 && $day==1;
1435: my $pdate=sprintf("%02d-%3s-%4d",$day,$months[$month],$year);
1436:
1437: print OUT "Дата:\n$pdate\n\n" if $date;
1438:
1439: print OUT "URL:\n$URL\n\n" if $URL;
1440:
1441: print OUT "Инфо:\n$Info\n\n" if $Info;
1442:
1443: print OUT "Копирайт:\n$Copyright\n\n" if $Copyright;
1444:
1445: print OUT "Редактор:\n$Editors\n\n" if $Editors;
1446:
1447:
1448: $query= "SELECT Id, Title, Copyright, Editors from Tournaments where ParentId=$Id order by Id";
1449: $sth=$dbh->prepare($query);
1450: $sth->execute;
1451: my ($tourid,$tourtitle,$cright,$editor,@tours,$vid,$author,$tourauthor);
1452:
1453:
1454: while (($tourid,$tourtitle,$cright,$editor)=$sth->fetchrow,$tourid)
1455: {
1456: # $text{$tourid}="Тур:\n$tourtitle\n\n";
1457: $query= "SELECT * from Questions where ParentId=$tourid order by QuestionId";
1458: my $sth1=$dbh->prepare($query);
1459: $sth1->execute;
1460: push(@tours,$tourid);
1461: $tourtitle{$tourid}=$tourtitle;
1462: $copyright{$tourid}=$cright;
1463: $editor{$tourid}=$editor;
1464: $vid='';
1465: my $author='';
1466: my $eqauthor=1;
1467: my $qnumber=0;
1468: my @arr;
1469: while ( (@arr=$sth1->fetchrow), $arr[0])
1470: {
1471: my($i, $name);
1472: $i=0;
1473: $qnumber++;
1474: foreach $name (@{$sth1->{NAME}}) {
1475: if ($arr[$i]) {
1476: $arr[$i]=~s/^(.*?)\s*$/$1/;
1477: $Question{$tourid}[$qnumber]{$name} = $arr[$i];
1478: } else {
1479: $Question{$tourid}[$qnumber]{$name} =
1480: ''}
1481: $i++;
1482: }
1483: if ($vid)
1484: {
1485: if ($vid ne $Question{$tourid}[$qnumber]{'Type'}) {print STDERR "Warning: Different types for Tournament $tourid\n"}
1486: } else
1487: {
1488: $vid=$Question{$tourid}[$qnumber]{'Type'};
1489: }
1490:
1491: if ($author)
1492: {
1493: if ($author ne $Question{$tourid}[$qnumber]{'Authors'})
1494: {
1495: $eqauthor=0;
1496: }
1497: } else
1498: {
1499: $author=$Question{$tourid}[$qnumber]{'Authors'};
1500: $eqauthor=0 unless $author;
1501: }
1502: }
1503: $vid{$tourid}=$vid;
1504: $qnumber{$tourid}=$qnumber;
1505: $author{$tourid}=$eqauthor ? $author : '';
1506: }
1507:
1508:
1509: $vid='';
1510: my $eqvid=1;
1511: my $eqauthor=1;
1512: foreach (@tours)
1513: {
1514: $vid||=$vid{$_};
1515: if ($vid{$_} ne $vid)
1516: {
1517: $eqvid=0;
1518: }
1519: $author||=$author{$_};
1520: if (!$author{$_} || ($author{$_} ne $author))
1521: {
1522: $eqauthor=0;
1523: }
1524: }
1525:
1526: print OUT "Вид:\n$vid\n\n" if $eqvid;
1527: print OUT "Автор:\n$author\n\n" if $eqauthor;
1528:
1529: foreach my $tour(@tours)
1530: {
1531: print OUT "Тур:\n$tourtitle{$tour}\n\n";
1532: print OUT "Вид:\n$vid{$tour}\n\n" if !$eqvid;
1533: print OUT "Копирайт:\n$copyright{$tour}\n\n" if $copyright{$tour} && ($copyright{$tour} ne $Copyright);
1534: print OUT "Редактор:\n$editor{$tour}\n\n" if $editor{$tour} && ($editor{$tour} ne $Editors);
1535: $tourauthor=0;
1536: if (!$eqauthor && $author{$tour})
1537: {
1538: print OUT "Автор:\n$author{$tour}\n\n";
1539: $tourauthor=1;
1540: }
1541: foreach my $q(1..$qnumber{$tour})
1542: {
1543: print OUT "Вопрос $q:\n".$Question{$tour}[$q]{'Question'}."\n\n";
1544: print OUT "Ответ:\n".$Question{$tour}[$q]{'Answer'}."\n\n";
1545: print OUT "Автор:\n".$Question{$tour}[$q]{'Authors'}."\n\n"
1546: if !$tourauthor && !$eqauthor && $Question{$tour}[$q]{'Authors'};
1547: print OUT "Комментарий:\n".$Question{$tour}[$q]{'Comments'}."\n\n"
1548: if $Question{$tour}[$q]{'Comments'};
1549: print OUT "Источник:\n".$Question{$tour}[$q]{'Sources'}."\n\n"
1550: if $Question{$tour}[$q]{'Sources'};
1551: print OUT "Рейтинг:\n".$Question{$tour}[$q]{'Rating'}."\n\n"
1552: if $Question{$tour}[$q]{'Rating'};
1553:
1554: }
1555: }
1556:
1557: close OUT;
1558:
1559:
1560:
1561: }
1562:
1563:
1564: MAIN:
1565: {
1566: setlocale(LC_CTYPE,'russian');
1567: my($i, $tour);
1568: my($text) = (param('text')) ? 1 : 0;
1569:
1570: my($dbh) = DBI->connect("DBI:mysql:chgk", "piataev", "")
1571: or do {
1572: print h1("Временные проблемы") . "База данных временно не
1573: работает. Заходите попозже.";
1574: print &Include_virtual("../dimrub/db/reklama.html");
1575: print end_html;
1576: die "Can't connect to DB chgk\n";
1577: };
1578: if (!param('comp') and !param('sqldump') and !$text) {
1579: print header;
1580: print start_html(-"title"=>'Database of the questions',
1581: -author=>'dimrub@icomverse.com',
1582: -bgcolor=>'#fff0e0',
1583: -vlink=>'#800020');
1584: print &Include_virtual("../dimrub/db/reklama.html");
1585: }
1586:
1587:
1588: if ($^O =~ /win/i) {
1589: $thislocale = "Russian_Russia.20866";
1590: } else {
1591: $thislocale = "ru_RU.KOI8-R";
1592: }
1593: POSIX::setlocale( &POSIX::LC_ALL, $thislocale );
1594:
1595: if ((uc 'а') ne 'А') {print "Koi8-r locale not installed!\n"};
1596:
1597:
1598: if ($text) {
1599: print header('text/plain');
1600: }
1601:
1602: if (param('hideequal')) {
1603: my ($sth)= $dbh -> prepare("select first, second FROM equalto");
1604: $sth -> execute;
1605: while ( my ($first, $second)=$sth -> fetchrow)
1606: {
1607: $forbidden{$first}=1;
1608: }
1609: $sth->finish;
1610: }
1611: $tour = (param('tour')) ? param('tour') : 0;
1612: my $sth;
1613: if ($tour !~ /^[0-9]*$/) {
1614: if ($tour=~/\./)
1615: {
1616: my ($fname,$n)= split /\./ , $tour;
1617:
1618: $sth = $dbh->prepare(
1619: "SELECT t2.Id FROM Tournaments as t1,
1620: Tournaments as t2
1621: WHERE t1.FileName = '$fname.txt'
1622: AND t1.Id=t2.ParentId AND t2.Number=$n");
1623: }
1624: else
1625: {
1626: $sth = $dbh->prepare("SELECT Id FROM Tournaments
1627: WHERE FileName = '$tour.txt'");
1628: }
1629: $sth->execute;
1630: $tour = ($sth->fetchrow)[0];
1631: $sth->finish;
1632: }
1633:
1634:
1635: if (param('rand')) {
1636: my ($type, $qnum) = ('', 12);
1637: $type.=$TypeName{$_} foreach param('type');
1638: # $type .= 'Б' if (param('brain'));
1639: # $type .= 'Ч' if (param('chgk'));
1640: $qnum = param('qnum') if (param('qnum') =~ /^\d+$/);
1641: $qnum = 0 if (!$type);
1642: my $Email;
1643: if (($Email=param('email')) && -x $SENDMAIL &&
1644: open(F, "| $SENDMAIL $Email")) {
1645: my ($mime_type) = $text ? "plain" : "html";
1646: print F <<EOT;
1647: To: $Email
1648: From: olegstepanov\@mail.ru
1649: Subject: Sluchajnij Paket Voprosov "Chto? Gde? Kogda?"
1650: MIME-Version: 1.0
1651: Content-type: text/$mime_type; charset="koi8-r"
1652:
1653: EOT
1654: print F &PrintRandom($dbh, $type, $qnum, $text);
1655: close F;
1656: print "Пакет случайно выбранных вопросов послан по адресу $Email. Нажмите
1657: на <B>Reload</B> для получения еще одного пакета";
1658: } else {
1659: print &PrintRandom($dbh, $type, $qnum, $text);
1660: }
1661: }
1662: elsif (param('authors')){
1663: print &PrintAuthors($dbh,param('authors'));
1664: }
1665: elsif (param('qofauthor')){
1666: &PrintQOfAuthor($dbh,param('qofauthor'));
1667: }
1668: elsif (param('sstr')||param('was')) {
1669: &PrintSearch($dbh, param('sstr'), param('metod'),param('was'));
1670: $dbh->do("delete from lastqueries where
1671: (TO_DAYS(NOW()) - TO_DAYS(t) >= 2) OR
1672: (time_to_sec(now())-time_to_sec(t) >3600)")
1673: }
1674: elsif (param('qid')) {
1675: my $qid=param('qid');
1676: my $query="SELECT Question, Answer from Questions where QuestionId=$qid";
1677: print $query if $printqueries;
1678: my $sth=$dbh->prepare($query);
1679: $sth->execute;
1680: my $sstr= join ' ',$sth->fetchrow;
1681: $sth->finish;
1682: $searchin{'Question'}=1;
1683: $searchin{'Answer'}=1;
1684: $sstr=~tr/ёЁ/еЕ/;
1685: $sstr=~s/[^йцукенгшщзхъфывапролджэячсмитьбюЙЦУКЕНГШЩЗХЪФЫВАПРОЛДЖЭЯЧСМИТЬБЮa-zA-Z0-9]/ /gi;
1686: # print &PrintQuestion($dbh,$qid, 1, '!');
1687: &PrintSearch($dbh, $sstr, 'proxy');
1688: }
1689: elsif (param('getfile')){
1690: print &writefile
1691: } elsif (param('all')) {
1692: print &PrintAll($dbh, 0);
1693: } elsif (param('from_year') && param('to_year')) {
1694: print &PrintDates($dbh);
1695: } elsif (param('comp')) {
1696: print "Content-Type: application/octet-stream\n";
1697: print "Content-Type: application/force-download\n";
1698: print "Content-Type: application/download\n";
1699: print "Content-Type: application/x-zip-compressed; name=db.zip\n";
1700: print "Content-Disposition: attachment; filename=db.zip \n\n";
1701: # print header(
1702: # -'Content-Type' => 'application/x-zip-compressed; name="db.zip"',
1703: # -'Content-Type' => 'application/zip',
1704: # -'Content-Disposition' => 'attachment; filename="db.zip"'
1705: # );
1706: $tour ||= 0;
1707: my (@files) = &PrintArchive($dbh, $tour);
1708: WriteFile($dbh,$_) foreach @files;
1709: # open F, "$ZIP -j - $SRCPATH/COPYRIGHT @files |";
1710: open F, "$ZIP -j - @files |";
1711: binmode(F);
1712: binmode(STDOUT);
1713: print (<F>);
1714: close F;
1715: $dbh->disconnect;
1716: exit;
1717: } elsif (param('sqldump')) {
1718: print header(
1719: -'Content-Type' => 'application/x-zip-compressed; name="dump.zip"',
1720: -'Content-Disposition' => 'attachment; filename="dump.zip"'
1721: );
1722: open F, "$ZIP -j - $DUMPFILE |";
1723: print (<F>);
1724: close F;
1725: $dbh->disconnect;
1726: exit;
1727:
1728: } else {
1729: my $QuestionNumber=0;
1730: my $qnum;
1731: if ($qnum=param('qnumber')){
1732: my ($sth) = $dbh->prepare("SELECT QuestionId FROM Questions
1733: WHERE ParentId=$tour AND Number=$qnum");
1734: $sth->execute;
1735: $QuestionNumber=($sth->fetchrow)[0]||0;
1736: }
1737: if ($QuestionNumber) {
1738: print &PrintQuestion($dbh, $QuestionNumber, param('answer')||0, $qnum, 1);
1739: # $dbh, $Id, $answer, $qnum, $title, $text
1740: } else {
1741: print &PrintTournament($dbh, $tour, param('answer'));
1742: }
1743: }
1744: if (!$text) {
1745: print &Include_virtual("../dimrub/db/footer.html");
1746: print <<EEE
1747: <SCRIPT LANGUAGE="JavaScript">
1748: function toggle(e) {
1749: if (e.style.display == "none") {
1750: e.style.display="";
1751: } else {
1752: e.style.display = "none";
1753: }
1754: }
1755: </SCRIPT>
1756: EEE
1757: ;
1758: print end_html;
1759: }
1760: $dbh->disconnect;
1761: }
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>