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