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