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