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