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