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