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