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