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