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 ='$_Д') ";
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 (@Questions) = &Get12Random($dbh, $type, $num);
978: my ($output, $i) = ('', 0);
979:
980: if ($text) {
981: $output .= " $num случайных вопросов.\n\n";
982: } else {
983: $output .=
984: h2({align=>"center"}, "$num случайных вопросов.");
985: }
986: my $sth=SelectQuestions($dbh,\@Questions,0);
987: for ($i = 0; $i <= $#Questions; $i++) {
988: fetchquestion($sth,\%q,0);
989: $output .=
990: &PrintQuestion($dbh, \%q, $answer, $i + 1, 0, $text,1);
991: push @answers, $q{'Answer'};
992: }
993: $sth->finish;
994: unless ($answer )
995: {
996: $output.=$text?"\n".('-'x 20)."\nОтветы\n~~~~~~\n\n":h2('Ответы');
997: $sth=SelectQuestions($dbh,\@Questions,0);
998: for ($i = 0; $i <= $#Questions; $i++) {
999: # fetchquestion($sth,\%q,0);
1000: # $output .=
1001: # &PrintQuestion($dbh, \%q, -1, $i + 1, 0, $text,1);
1002: $output.=$text?("Ответ ". ($i+1).": $answers[$i]\n\n"):
1003: b("Ответ ". ($i+1).": "). $answers[$i].p;
1004: }
1005: }
1006:
1007: return $output;
1008: }
1009:
1010: sub PrintEditor {
1011: my $t=shift; #ссылка на Хэш с полями
1012: my $ed=$$t{'Editors'}||'';
1013: my $edname=($ed=~/\,/ ) ? "Редакторы" : "Редактор" ;
1014: return $ed? h4({align=>"center"},"$edname: $ed" ): '';
1015: }
1016:
1017: sub PrintTournament {
1018: my ($dbh, $Id, $answer) = @_;
1019: my (%Tournament, @Tours, $i, $list, $qnum, $imgsrc, $alt,
1020: $SingleTour);
1021: my ($output) = '';
1022:
1023: %Tournament = &GetTournament($dbh, $Id) if ($Id);
1024:
1025: my ($URL) = $Tournament{'URL'}||'';
1026: $URL=~s/http:\/znatoki\/boris\/reports\//$newsurl/ if $url=~/kulichki/ || $url=~/db.chgk.info/;
1027: $URL=~s/\/znatoki\/boris\/reports\//$newsurl/ if url=~/kulichki/ || $url=~/db.chgk.info/;
1028: my ($Info) = $Tournament{'Info'};
1029: my ($Copyright) = $Tournament{'Copyright'};
1030: my $fname=$Tournament{'FileName'};
1031: @Tours = &GetTours($dbh, $Id);
1032: $list='';
1033: my $textid;
1034: if ($Id) {
1035: for ($Tournament{'Type'}) {
1036: /Г/ && do {
1037: $output .= h2({align=>"center"},
1038: "Группа: $Tournament{'Title'} ",
1039: $Tournament{'PlayedAt'}||'') . p . "\n";
1040: last;
1041: };
1042: /Ч/ && do {
1043: return &PrintTour($dbh, $Tours[0], $answer)
1044: if ($#Tours == 0);
1045:
1046: my $title="Пакет: $Tournament{'Title'}";
1047: if ($Tournament{'PlayedAt'}) {
1048: $title .= " $Tournament{'PlayedAt'}";
1049: }
1050:
1051: $output .= h2({align=>"center"},
1052: "$title") . p . "\n";
1053: $output.=&PrintEditor(\%Tournament);
1054: last;
1055: };
1056: /Т/ && do {
1057: return &PrintTour($dbh, $Id, $answer);
1058: };
1059: }
1060: } else {
1061: my ($qnum) = GetQNum($dbh,0);
1062: my ($qnum1) = GetQNum($dbh,1);
1063: $output .= h2("База вопросов").
1064: h3("$qnum запис".&Suffix2($qnum).
1065: " (не повторяется $qnum1)");
1066:
1067: # h4("<table>".
1068: # Tr(td("Из них:"), td("Вопросов ЧГК: ".countz($dbh,'Ч'))).
1069: # Tr(td(" "), td("Вопросов для брейна: ".countz($dbh,'Б'))).
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,'Э'))))."</table>"
1075: }
1076:
1077: for ($i = 0; $i <= $#Tours; $i++) {
1078: %Tournament = &GetTournament($dbh, $Tours[$i]);
1079:
1080: if ($Tournament{'Type'} =~ /Ч/) {
1081: $SingleTour = 0;
1082: my (@Tours) = &GetTours($dbh, $Tournament{'Id'});
1083: $SingleTour = 1
1084: if ($#Tours == 0);
1085: }
1086: if ($Tournament{'QuestionsNum'} > 0) {
1087: $qnum = " ($Tournament{'QuestionsNum'} вопрос" .
1088: &Suffix($Tournament{'QuestionsNum'}) . ")\n";
1089: } else {
1090: $qnum = '';
1091: }
1092: if ($Tournament{'Type'} !~ /[ТЧ]/) {
1093: $SingleTour=0;
1094: $imgsrc = "/icons/folder.gif";
1095: $alt = "[*]";
1096: } else {
1097: $imgsrc = "/icons/folder.gif";
1098: $alt = "[-]";
1099: }
1100:
1101: my $textid;
1102: if ($textid=$Tournament{'FileName'})
1103: {
1104: $textid=~s/\.txt//;
1105: }
1106: elsif ($textid=$Tournament{'Number'})
1107: {
1108: $fname=~s/\.txt//;
1109: $textid="$fname.$textid";
1110: }
1111: else {$textid=$Tournament{'Id'}};
1112:
1113:
1114: if ($SingleTour or ($Tournament{'Type'} =~ /Т/)) {
1115: $list .= dd(img({src=>$imgsrc, alt=>$alt})
1116: . " " . $Tournament{'Title'} . " " .
1117: ($Tournament{'PlayedAt'}||"") . $qnum) .
1118: dl(
1119: dd("["
1120: . a({href=>tourhref($textid,0)},
1121: "вопросы") . "] ["
1122: . a({href=>tourhref($textid,1)},
1123: "вопросы + ответы") . "]")
1124: );
1125: } else {
1126: $list .= dd(a({href=>
1127: $url . "?tour=$textid&comp=1"},
1128: img({src=>'/icons/compressed.gif', alt=>'[ZIP]', border=>1})) .
1129: " " .
1130: img({src=>$imgsrc, alt=>$alt})
1131: . " " . a({href=>tourhref($textid,0,1)},
1132: $Tournament{'Title'}. " ".
1133: ($Tournament{'PlayedAt'}||'')) . $qnum);
1134: }
1135: }
1136: $output .= dl($list);
1137:
1138: if ($URL) {
1139: if ($url=~/zaba\.ru/ && $URL=~/^\//){$URL="http://info.chgk.info$URL"}
1140: $output .=
1141: p("Дополнительная информация об этом турнире - по адресу " .
1142: a({-'href'=>$URL}, $URL));
1143: }
1144:
1145: if ($Copyright) {
1146: $output .= p("Копирайт: " . $Copyright);
1147: }
1148:
1149:
1150:
1151: if ($Info) {
1152: $output .= p($Info);
1153: }
1154: return $output;
1155: }
1156:
1157: sub Suffix {
1158: my ($qnum) = @_;
1159: my ($suffix) = 'а' if $qnum =~ /[234]$/;
1160: $suffix = '' if $qnum =~ /1$/;
1161: $suffix = 'ов' if $qnum =~ /[567890]$/ || $qnum =~ /1.$/;
1162: return $suffix;
1163: }
1164:
1165:
1166: sub Suffix1 {
1167: my ($qnum) = @_;
1168: my ($suffix) = 'я' if $qnum =~ /[234]$/;
1169: $suffix = 'е' if $qnum =~ /1$/;
1170: $suffix = 'й' if $qnum =~ /[567890]$/ || $qnum =~ /1.$/;
1171: return $suffix;
1172: }
1173:
1174: sub Suffix2 {
1175: my ($qnum) = @_;
1176: my ($suffix) = 'и' if $qnum =~ /[234]$/;
1177: $suffix = 'ь' if $qnum =~ /1$/;
1178: $suffix = 'ей' if $qnum =~ /[567890]$/ || $qnum =~ /1.$/;
1179: return $suffix;
1180: }
1181:
1182: sub IsTour {
1183: my ($dbh, $Id,$n) = @_;
1184:
1185: my ($sth) ;
1186:
1187: if (defined $n)
1188: { $sth=$dbh->prepare ("select Id FROM Tournaments
1189: WHERE ParentId=$Id AND Number=$n");
1190: }
1191: else
1192: {
1193: $sth=$dbh->prepare("SELECT Id FROM Tournaments
1194: WHERE Id=$Id");
1195: }
1196: $sth->execute;
1197: my $a=($sth->fetchrow)[0];
1198: $sth->finish;
1199: return $a;
1200: }
1201:
1202: # Gets a DB handler (ofcourse) and a tour Id. Prints all the
1203: # question of that tour, according to the options.
1204: sub PrintTour {
1205: my ($dbh, $Id, $answer) = @_;
1206: my ($output, $q, $bottom, $field) = ('', 0, '', '');
1207:
1208: my (%Tour) = &GetTournament($dbh, $Id);
1209: my (@Tours) = &GetTours($dbh, $Tour{'ParentId'});
1210: my (%Tournament) = &GetTournament($dbh, $Tour{'ParentId'});
1211: my %q;
1212:
1213: return 0
1214: if ($Tour{'Type'} !~ /Т/);
1215:
1216: my ($fname)=$Tournament{'FileName'};
1217: $fname=~s/\.txt//;
1218: my ($qnum) = $Tour{'QuestionsNum'};
1219: my ($suffix) = &Suffix($qnum);
1220:
1221: $output .= h2({align=>"center"}, $Tournament{"Title"},
1222: $Tournament{'PlayedAt'}||'',
1223: "<br>", $Tour{"Title"} .
1224: " ($qnum вопрос$suffix)\n") . p;
1225: $output .=&PrintEditor(\%Tour);
1226:
1227: my (@Questions) = &GetTourQuestions($dbh, $Id);
1228: my $sth=SelectQuestions($dbh,\@Questions,0);
1229: for ($q = 0; $q <= $#Questions; $q++) {
1230: fetchquestion($sth,\%q,0);
1231: $output .= &PrintQuestion($dbh, \%q, $answer, 0,0,0,1);
1232: }
1233: $sth->finish;
1234: $output .= hr({-'align'=>'center', -'width'=>'80%'});
1235:
1236: if ($Tournament{'URL'}) {
1237: $output .=
1238: p("Дополнительная информация об этом турнире - по адресу " .
1239: a({-'href'=>$Tournament{'URL'}}, $Tournament{'URL'}));
1240: }
1241:
1242: if ($Tournament{'Copyright'}) {
1243: $output .= p("Копирайт: " . $Tournament{'Copyright'});
1244: }
1245:
1246: if ($Tournament{'Info'}) {
1247: $output .= p($Tournament{'Info'});
1248: }
1249:
1250: my $n=$Tour{'Number'};
1251: if ($answer == 0) {
1252: my $nn=".$n";
1253: $nn="" if ($n==1 && !&IsTour($dbh, $Tour{'ParentId'}, $n + 1));
1254:
1255: $bottom .=
1256: "[" . a({href=>tourhref("$fname$nn",1)},
1257: "ответы") . "] " . br;
1258: }
1259: if ($n>1) {
1260: $bottom .=
1261: "[" . a({href=>tourhref("$fname.".($n-1),0)},
1262: "предыдущий тур") . "] ";
1263: $bottom .=
1264: "[" . a({href=>tourhref("$fname.".($n-1),1)},
1265: "предыдущий тур с ответами") . "] " . br;
1266: }
1267: if (&IsTour($dbh, $Tour{'ParentId'}, $n + 1)) {
1268: $bottom .=
1269: "[" . a({href=>tourhref("$fname.".($n+1),0)},
1270: "следующий тур") . "] ";
1271: $bottom .=
1272: "[" . a({href=>tourhref("$fname.".($n+1),1)},
1273: "следующий тур с ответами") . "] ";
1274: }
1275:
1276: $output .=
1277: p({align=>"center"}, font({size=>-1}, $bottom));
1278:
1279: return $output;
1280: }
1281:
1282: sub PrintField {
1283: my ($header, $value, $text) = @_;
1284: if ($text) {
1285: $value =~ s/<[\/\w]*?>//sg;
1286: } else {
1287: $value =~ s/^\s+/<br> /mg;
1288: $value =~ s/(\s+)-+(\s+)/$1–$2/mg;
1289: $value =~ s/\s+\–/ \–/mg
1290: if $value !~ /^\|/;
1291: $value =~ s/^\|([^\n]*)/<pre>$1<\/pre>/mg;
1292: $value =~ s/(http:\/\/\S+[^\s\)\(\,\.])/<a href="$1">$1<\/a>/g if $header !~ /^Авто/;
1293: # $value =~ s/(http:\/\/(?:\w+.)+[\w\\\~]+(\?[^\s.]+)?)/<a href="$1">$1<\/a>/g if $header !~ /^Авто/;
1294: # $value =~ s/(\s)"/$1“/mg;
1295: # $value =~ s/^"/“/mg;
1296: # $value =~ s/"/”/mg;
1297: }
1298:
1299:
1300: return $text ? "$header:\n$value\n\n" :
1301: strong("$header: ") . $value . p . "\n";
1302: }
1303:
1304: # Gets a DB handler (ofcourse) and a question Id. Prints
1305: # that question, according to the options.
1306: sub PrintQuestion {
1307: my ($dbh, $Id, $answer, $qnum, $title, $text,$h) = @_;
1308: my ($output, $titles) = ('', '');
1309: my (%Question);
1310: if ($h) {
1311: %Question=%$Id;
1312: } else {
1313: %Question = &GetQuestion($dbh, $Id);
1314: if ($title) {
1315: my (%Tour) = GetTournament($dbh, $Question{'ParentId'});
1316: my (%Tournament) = GetTournament($dbh, $Tour{'ParentId'});
1317: $Question{'FileName'}=$Tournament{'FileName'};
1318: $Question{'Title'}=$Tournament{'Title'};
1319: $Question{'PlayedAt'}=$Tournament{'PlayedAt'};
1320: $Question{'TourNumber'}=$Tour{'Number'};
1321: $Question{'TourTitle'}=$Tour{'Title'};
1322: }
1323:
1324: }
1325: $qnum = $Question{'Number'}
1326: if ($qnum == 0);
1327: if (!$text) {
1328: $output .= hr({width=>"50%"}) if $answer>=0;
1329: if ($title) {
1330: my $fname=$Question{'FileName'};
1331: $fname=~s/\.txt//;
1332: $titles .=
1333: dd(img({src=>"/icons/folder.open.gif"}) . " " .
1334: a({href=>tourhref($fname,0,1)},
1335: $Question{'Title'}, $Question{'PlayedAt'}||''));
1336: $titles .=
1337: dl(dd(img({src=>"/icons/folder.open.gif"}) . " " .
1338: a({href=>tourhref("$fname.$Question{'TourNumber'}#$qnum",1)},
1339: $Question{'TourTitle'})));
1340: }
1341: $output .= dl(strong($titles));
1342: }
1343:
1344:
1345: $output.= "<a NAME=\"$qnum\">" unless $text;
1346:
1347: if ($answer>=0) {$output .=
1348: &PrintField("Вопрос $qnum", $Question{'Question'}, $text);}
1349: else {$output .="$qnum. "}
1350: if ($answer==1|| $answer==-1) {
1351: $output .=
1352: &PrintField("Ответ", $Question{'Answer'}, $text);
1353:
1354: if ($Question{'Authors'} ) {
1355: my $q=$Question{'Authors'};
1356: ###АВТОРА!!
1357: # my $sth=$dbh->prepare("select Authors.CharId,Name, Surname, Nicks from Authors, A2Q
1358: # where Authors.Id=Author And Question=$Id");
1359: # $sth->execute;
1360: # my ($AuthorId,$Name, $Surname,$other,$Nicks);
1361: # if (!$text) {
1362: # while ((($AuthorId,$Name, $Surname,$Nicks)=$sth->fetchrow),$AuthorId)
1363: # {
1364: # my ($firstletter)=$Name=~m/^./g;
1365: # $Name=~s/\./\\\./g;
1366: # $Name=~s/ё/[её]/g;
1367: # $Surname=~s/ё/[её]/g;
1368: # my $sha="(?:$Name\\s+$Surname)|(?:$Surname\\s+$Name)|(?:$firstletter\\.\\s*$Surname)|(?:$Surname\\s+$firstletter\\.)|(?:$Surname)";
1369: # if ($Nicks)
1370: # {
1371: # $Nicks=~s/^\|//;
1372: # foreach (split /\|/, $Nicks)
1373: # {
1374: # s/\s+/ /g;
1375: # s/\s+$//;
1376: # s/ /\\s+/g;
1377: # s/\./\\\./g;
1378: # if (s/>$//) {$sha="$sha|(?:$_)"}
1379: # else {$sha="(?:$_)|$sha"}
1380: # }
1381: # }
1382: # $q=~s/($sha)/a({href=>url."?qofauthor=$AuthorId"},$1)/ei;
1383: # unless ($1)
1384: # {
1385: # $q=~s/$Name/a({href=>url."?qofauthor=$AuthorId"},$1)/ei;
1386: # }
1387: # }
1388: # }
1389: $output .= &PrintField("Автор(ы)", $q, $text);
1390:
1391: }
1392:
1393: if ($Question{'Sources'}) {
1394: $output .= &PrintField("Источник(и)", $Question{'Sources'}, $text);
1395: }
1396:
1397: if ($Question{'Comments'}) {
1398: $output .= &PrintField("Комментарии", $Question{'Comments'}, $text);
1399: }
1400: }
1401: elsif ($answer==2) {
1402: my $text=$Question{'Answer'};
1403: $text=~s/\n/<option>/mg;
1404: $output.="<select><option selected>Ответ:<option>$text</select>";
1405: $text=$Question{'Comments'}||'';
1406: if ($text) {
1407: $text=~s/\n/<option>/mg;
1408: $output.="<select><option selected>Комментарий:<option>$text</select>"
1409: }
1410: }
1411: elsif ($answer==3) {
1412: $output.= <<EOTT
1413: <div align=right STYLE="cursor:hand;" OnStart="toggle(document.all.HideShow$qnum);" OnClick="toggle(document.all.HideShow$qnum);">
1414: <font size=-2 color=red> Показать/убрать ответ</font></div>
1415: <span style="display:none" id=HideShow$qnum>
1416: EOTT
1417: .&PrintField("Ответ", $Question{'Answer'}, $text);
1418: if ($Question{'Authors'}) {
1419: $output .= &PrintField("Автор(ы)", $Question{'Authors'}, $text);
1420: }
1421: if ($Question{'Sources'}) {
1422: $output .= &PrintField("Источник(и)", $Question{'Sources'}, $text);
1423: }
1424:
1425: if ($Question{'Comments'}) {
1426: $output .= &PrintField("Комментарии", $Question{'Comments'}, $text);
1427: }
1428:
1429:
1430:
1431: $output.="</span>"
1432:
1433: }
1434: $output=~s/\(pic: ([^\)]*)\)/<p><img src="\/znatoki\/images\/db\/$1"><p>/g unless $text;
1435: $paramtour||=param("tour");
1436: my $qid=$paramtour ? ($paramtour.".$Question{'Number'}" ): '';
1437:
1438: $output.=br.a({href=> $url."?metod=proxy&
1439: qid=$qid"}, 'Близкие вопросы').p
1440: if $answer>0 && !$text && $qid;
1441: return $output;
1442: }
1443:
1444: # Returns the total number of questions currently in the DB.
1445: sub GetQNum {
1446: my ($dbh,$x) = @_;
1447: my ($sth) = $dbh->prepare("SELECT COUNT(*) FROM Questions");
1448: $sth->execute;
1449: my $tmp=($sth->fetchrow)[0];
1450: $sth->finish;
1451: ($sth)= $dbh -> prepare("select distinct count(first) FROM equalto");
1452: $sth -> execute;
1453: my ($c)=$sth->fetchrow;
1454:
1455: # $i++ while ( my ($first, $second)=$sth -> fetchrow)
1456: # {
1457: # $forbidden{$first}=1;
1458: # }
1459: $sth->finish;
1460:
1461: return $tmp-($x?$c:0);
1462: }
1463: sub GetMaxQId {
1464: my ($dbh) = @_;
1465: my ($sth) = $dbh->prepare("SELECT MAX(QuestionId) FROM Questions");
1466: $sth->execute;
1467: my $tmp=($sth->fetchrow)[0];
1468: $sth->finish;
1469: return $tmp;
1470:
1471: }
1472:
1473: # Returns Id's of 12 random questions
1474: sub Get12Random {
1475: my ($dbh, $type, $num) = @_;
1476: my ($i, @questions, $q, $t, $sth);
1477: my ($qnum) = &GetMaxQId($dbh);
1478: my (%chosen);
1479: srand;
1480: my $where=0;
1481: my $r=int (rand(10000));
1482:
1483: foreach (split '', $type)
1484: {
1485: $where.= " OR (Type ='$_') OR (Type ='$_Д') ";
1486: }
1487: $where.= "OR (Type='ЧБ')" if ($type=~/Ч|Б/);
1488:
1489: # $q="select QuestionId, QuestionId/$r-floor(QuestionId/$r) as val
1490: # from Questions where $where order by val limit $num";
1491: # Когда на куличках появится mysql >=3.23 надо заменить на order by rand();
1492: $q="select QuestionId from Questions where $where order by rand() limit $num";
1493:
1494:
1495: $sth=$dbh->prepare($q);
1496: $sth->execute;
1497: while (($i)=$sth->fetchrow)
1498: {
1499: push @questions,$i;
1500: }
1501: $sth->finish;
1502: for ($i=@questions; --$i;){
1503: my $j=rand ($i+1);
1504: @questions[$i,$j]=@questions[$j,$i] unless $i==$j;
1505: }
1506: return @questions;
1507: }
1508:
1509: sub Include_virtual {
1510: my ($fn, $output) = (@_, '');
1511: return "\n<!--#include virtual=\"$fn\"-->\n" if ($opt_z);
1512: open F , $fn
1513: or return ""; #die "Can't open the file $fn: $!\n";
1514:
1515: while (<F>) {
1516: if (/<!--#include/o) {
1517: s/<!--#include virtual="\/?([^\/].*)" -->/&Include_virtual($1)/e;
1518: }
1519: if (/<!--#exec/o) {
1520: s/<!--#exec.*cmd\s*=\s*"([^"]*)".*-->/`$1`/e;
1521: }
1522: $output .= $_;
1523: }
1524: return $output||"";
1525: }
1526:
1527: sub PrintArchive {
1528: my($dbh, $Id) = @_;
1529: my ($output, @list, $i);
1530:
1531: my (%Tournament) = &GetTournament($dbh, $Id);
1532: my (@Tours) = &GetTours($dbh, $Id);
1533: if ($Tournament{'Type'} =~ /Г/ || $Id == 0) {
1534: for ($i = 0; $i <= $#Tours; $i++) {
1535: push(@list ,&PrintArchive($dbh, $Tours[$i]));
1536: }
1537: return @list;
1538: }
1539: # return "$SRCPATH/$Tournament{'FileName'} ";
1540: return "$TMPDIR/$Tournament{'FileName'} ";
1541: }
1542:
1543: sub PrintAll {
1544: my ($dbh, $Id,$fname) = @_;
1545: my ($output, $list, $i);
1546:
1547: my (%Tournament) = &GetTournament($dbh, $Id);
1548: my (@Tours) = &GetTours($dbh, $Id);
1549: my $SingleTour = $#Tours == 0;
1550:
1551: my ($New) = ($Id and $Tournament{'Type'} eq 'Ч' and
1552: &NewEnough($Tournament{"CreatedAt"})) ?
1553: img({src=>"/znatoki/dimrub/db/new-sml.gif", alt=>"NEW!"}) : "";
1554:
1555: if ($Id == 0) {
1556: $output = h3("Все турниры");
1557: } else {
1558: my $textid;
1559: if ($textid=$Tournament{'FileName'})
1560: {
1561: $textid=~s/\.txt//;
1562: }
1563: elsif ($textid=$Tournament{'Number'})
1564: {
1565: $fname=~s/\.txt//;
1566: $textid="$fname.$textid";
1567: }
1568: else {$textid=$Tournament{'Id'}};
1569:
1570:
1571: $output .= dd(img({src=>"/icons/folder.gif", alt=>"[*]"}) .
1572: " " . a({href=>tourhref($textid,0,!$SingleTour)},
1573: $Tournament{'Title'}) ." " . ($Tournament{'PlayedAt'}||'') . " $New");
1574: }
1575: if ($Id == 0 or $Tournament{'Type'} =~ /Г/ or $Tournament{'Type'} eq '') {
1576: for ($i = 0; $i <= $#Tours; $i++) {
1577: $list .= &PrintAll($dbh, $Tours[$i],$Tournament{'FileName'});
1578: }
1579: $output .= dl($list);
1580: }
1581: return $output;
1582: }
1583:
1584: sub PrintDates {
1585: my ($dbh) = @_;
1586: my ($from) = param('from_year') . "-" . param('from_month') .
1587: "-" . param('from_day');
1588: my ($to) = param('to_year') . "-" . param('to_month') . "-" . param('to_day');
1589: $from = $dbh->quote($from);
1590: $to = $dbh->quote($to);
1591: my ($sth) = $dbh->prepare("
1592: SELECT DISTINCT Id
1593: FROM Tournaments
1594: WHERE PlayedAt >= $from AND PlayedAt <= $to
1595: AND Type = 'Ч'
1596: ");
1597: $sth->execute;
1598: my (%Tournament, @array, $output, $list);
1599:
1600: $output = h3("Список турниров, проходивших между $from и $to.");
1601: while (@array = $sth->fetchrow) {
1602: next
1603: if (!$array[0]);
1604: %Tournament = &GetTournament($dbh, $array[0]);
1605: my $textid;
1606: if ($textid=$Tournament{'FileName'})
1607: {
1608: $textid=~s/\.txt//;
1609: }
1610: elsif ($textid=$Tournament{'Number'})
1611: {
1612: $fname=~s/\.txt//;
1613: $textid="$fname.$textid";
1614: }
1615: else {$textid=$Tournament{'Id'}};
1616: $list .= dd(img({src=>"/icons/folder.gif", alt=>"[*]"}) .
1617: " " . a({href=>tourhref($textid,0,1)},
1618: $Tournament{'Title'}, $Tournament{'PlayedAt'}||''));
1619: }
1620: $sth->finish;
1621: $output .= dl($list);
1622: return $output;
1623: }
1624:
1625: sub PrintQOfAuthor
1626: {
1627:
1628: my ($dbh, $id) = @_;
1629: my $Output='';
1630: unless ($id=~/^\d+$/) {
1631: $id=$dbh->quote($id);
1632: my $sth = $dbh->prepare("SELECT Id FROM Authors WHERE CharId=$id");
1633: $sth->execute;
1634: ($id)=$sth->fetchrow;
1635: $sth->finish;
1636: }
1637: $id=$dbh->quote($id);
1638:
1639: my $sth = $dbh->prepare("SELECT Name, Surname FROM Authors WHERE Id=$id");
1640: $sth->execute;
1641: my ($name,$surname)=$sth->fetchrow;
1642:
1643: $sth = $dbh->prepare("SELECT Question FROM A2Q WHERE Author=$id");
1644: $sth->execute;
1645: my $q;
1646: my @Questions;
1647: while (($q)=$sth->fetchrow,$q)
1648: {push @Questions,$q unless $forbidden{$q}}
1649: $sth->finish;
1650:
1651: my ($output, $i, $suffix, $hits) = ('', 0, '', $#Questions + 1);
1652:
1653: if ($hits =~ /1.$/ || $hits =~ /[5-90]$/) {
1654: $suffix = 'й';
1655: } elsif ($hits =~ /1$/) {
1656: $suffix = 'е';
1657: } else {
1658: $suffix = 'я';
1659: }
1660: $Output.= printform;
1661: $Output.= p({align=>"center"}, "Автор ".strong("$name $surname. ")
1662: . " : $hits попадани$suffix.");
1663:
1664:
1665: # for ($i = 0; $i <= $#Questions; $i++) {
1666: # $output = &PrintQuestion($dbh, $Questions[$i], 1, $i + 1, 1);
1667: # print $output;
1668: # }
1669: $Output.=PrintList($dbh,\@Questions,'gdfgdfgdfgdfg');
1670: }
1671:
1672:
1673: sub PrintAuthors
1674: {
1675: my ($dbh,$sort)=@_;
1676: my($output,$out1,@array,$sth);
1677: if ($sort eq 'surname')
1678: {
1679: $sth =
1680: $dbh->prepare("SELECT Id, Name, Surname, QNumber FROM Authors order by Surname, Name");
1681: }
1682: elsif($sort eq 'name')
1683: {
1684: $sth =
1685: $dbh->prepare("SELECT Id, Name, Surname, QNumber FROM Authors order by Name, Surname");
1686: }
1687: else
1688: {
1689: $sth =
1690: $dbh->prepare("SELECT Id, Name, Surname, QNumber FROM Authors Order by QNumber DESC, Surname");
1691: }
1692:
1693: $output.=h2("Авторы вопросов")."\n";
1694: $output.="<TABLE>";
1695:
1696:
1697: $sth->execute;
1698: $output.=Tr(th[a({href=>$url."?authors=name"},"Имя")
1699: .", ".
1700: a({href=>$url."?authors=surname"},"фамилия")
1701: , a({href=>$url."?authors=kvo"},"Количество вопросов")]);
1702:
1703: $out1='';
1704:
1705: my $ar=$sth->fetchall_arrayref;
1706:
1707: $sth->finish;
1708:
1709:
1710: foreach my $arr(@$ar)
1711: {
1712:
1713: my ($id,$name,$surname,$kvo)=@$arr;
1714: if (!$name || !$surname) {
1715: } else
1716: {
1717: my $add=Tr(td([a({href=>$url."?qofauthor=$id"},"$name $surname"), $kvo]))."\n";
1718: $output.=$add;
1719: }
1720: }
1721: $output.="</TABLE>";
1722: $sth->finish;
1723: return $output;
1724: }
1725:
1726:
1727: sub WriteFile {
1728: my ($dbh,$fname) = @_;
1729: $fname=~s/\s+$//;
1730: $fname=~s/^\s+//;
1731: $fname=~s/\.txt$//;
1732: $fname=~s/.*\/(\w+)/$1/;
1733:
1734: my $query= "SELECT Id, Title, Copyright, Info, URL,
1735: Editors, EnteredBy, PlayedAt, CreatedAt
1736: from Tournaments where FileName=
1737: '$fname' OR FileName=".$dbh->quote("$fname.txt");
1738: my $sth=$dbh->prepare($query);
1739: my (%Question,%editor,%qnumber,%copyright,%author,%vid,%tourtitle);
1740: $sth->execute;
1741: my ($Id, $Title, $Copyright, $Info, $URL,
1742: $Editors, $EnteredBy, $PlayedAt, $CreatedAt)=
1743: $sth->fetchrow;
1744: return -1 unless $Id;
1745: open (OUT, ">$TMPDIR/$fname.txt") || print STDERR "Error in $fname.txt\n";
1746: print OUT "Чемпионат:\n$Title\n\n";
1747: my $date=$PlayedAt||'00-00-00';
1748: my ($year,$month,$day)=split /-/, $date;
1749: # $month=0,$date=0 if $year && $month==1 && $day==1;
1750: my $pdate=sprintf("%02d-%3s-%4d",$day,$months[$month],$year);
1751:
1752: print OUT "Дата:\n$pdate\n\n" if $date;
1753:
1754: print OUT "URL:\n$URL\n\n" if $URL;
1755:
1756: print OUT "Инфо:\n$Info\n\n" if $Info;
1757:
1758: print OUT "Копирайт:\n$Copyright\n\n" if $Copyright;
1759:
1760: print OUT "Редактор:\n$Editors\n\n" if $Editors;
1761:
1762:
1763: $query= "SELECT Id, Title, Copyright, Editors from Tournaments where ParentId=$Id order by Id";
1764: $sth=$dbh->prepare($query);
1765: $sth->execute;
1766: my ($tourid,$tourtitle,$cright,$editor,@tours,$vid,$author,$tourauthor);
1767:
1768:
1769: while (($tourid,$tourtitle,$cright,$editor)=$sth->fetchrow,$tourid)
1770: {
1771: # $text{$tourid}="Тур:\n$tourtitle\n\n";
1772: $query= "SELECT * from Questions where ParentId=$tourid order by QuestionId";
1773: my $sth1=$dbh->prepare($query);
1774: $sth1->execute;
1775: push(@tours,$tourid);
1776: $tourtitle{$tourid}=$tourtitle;
1777: $copyright{$tourid}=$cright;
1778: $editor{$tourid}=$editor;
1779: $vid='';
1780: my $author='';
1781: my $eqauthor=1;
1782: my $qnumber=0;
1783: my @arr;
1784: while ( (@arr=$sth1->fetchrow), $arr[0])
1785: {
1786: my($i, $name);
1787: $i=0;
1788: $qnumber++;
1789: foreach $name (@{$sth1->{NAME}}) {
1790: if ($arr[$i]) {
1791: $arr[$i]=~s/^(.*?)\s*$/$1/;
1792: $Question{$tourid}[$qnumber]{$name} = $arr[$i];
1793: } else {
1794: $Question{$tourid}[$qnumber]{$name} =
1795: ''}
1796: $i++;
1797: }
1798: if ($vid)
1799: {
1800: if ($vid ne $Question{$tourid}[$qnumber]{'Type'}) {print STDERR "Warning: Different types for Tournament $tourid\n"}
1801: } else
1802: {
1803: $vid=$Question{$tourid}[$qnumber]{'Type'};
1804: }
1805:
1806: if ($author)
1807: {
1808: if ($author ne $Question{$tourid}[$qnumber]{'Authors'})
1809: {
1810: $eqauthor=0;
1811: }
1812: } else
1813: {
1814: $author=$Question{$tourid}[$qnumber]{'Authors'};
1815: $eqauthor=0 unless $author;
1816: }
1817: }
1818: $vid{$tourid}=$vid;
1819: $qnumber{$tourid}=$qnumber;
1820: $author{$tourid}=$eqauthor ? $author : '';
1821: }
1822:
1823:
1824: $vid='';
1825: my $eqvid=1;
1826: my $eqauthor=1;
1827: foreach (@tours)
1828: {
1829: $vid||=$vid{$_};
1830: if ($vid{$_} ne $vid)
1831: {
1832: $eqvid=0;
1833: }
1834: $author||=$author{$_};
1835: if (!$author{$_} || ($author{$_} ne $author))
1836: {
1837: $eqauthor=0;
1838: }
1839: }
1840:
1841: print OUT "Вид:\n$vid\n\n" if $eqvid;
1842: print OUT "Автор:\n$author\n\n" if $eqauthor;
1843:
1844: foreach my $tour(@tours)
1845: {
1846: print OUT "Тур:\n$tourtitle{$tour}\n\n";
1847: print OUT "Вид:\n$vid{$tour}\n\n" if !$eqvid;
1848: print OUT "Копирайт:\n$copyright{$tour}\n\n" if $copyright{$tour} && ($copyright{$tour} ne $Copyright);
1849: print OUT "Редактор:\n$editor{$tour}\n\n" if $editor{$tour} && ($editor{$tour} ne $Editors);
1850: $tourauthor=0;
1851: if (!$eqauthor && $author{$tour})
1852: {
1853: print OUT "Автор:\n$author{$tour}\n\n";
1854: $tourauthor=1;
1855: }
1856: foreach my $q(1..$qnumber{$tour})
1857: {
1858: print OUT "Вопрос $q:\n".$Question{$tour}[$q]{'Question'}."\n\n";
1859: print OUT "Ответ:\n".$Question{$tour}[$q]{'Answer'}."\n\n";
1860: print OUT "Автор:\n".$Question{$tour}[$q]{'Authors'}."\n\n"
1861: if !$tourauthor && !$eqauthor && $Question{$tour}[$q]{'Authors'};
1862: print OUT "Комментарий:\n".$Question{$tour}[$q]{'Comments'}."\n\n"
1863: if $Question{$tour}[$q]{'Comments'};
1864: print OUT "Источник:\n".$Question{$tour}[$q]{'Sources'}."\n\n"
1865: if $Question{$tour}[$q]{'Sources'};
1866: print OUT "Рейтинг:\n".$Question{$tour}[$q]{'Rating'}."\n\n"
1867: if $Question{$tour}[$q]{'Rating'};
1868:
1869: }
1870: }
1871:
1872: close OUT;
1873:
1874:
1875:
1876: }
1877:
1878: sub Bottom
1879: {
1880: my $output.=&Include_virtual("$footer")||"";
1881: $output.=p."<center><font size=-2>Обновление: ".&Include_virtual("$datefooter")."</center></font>";
1882: $output.=<<EEE
1883: <SCRIPT LANGUAGE="JavaScript">
1884: function toggle(e) {
1885: if (e.style.display == "none") {
1886: e.style.display="";
1887: } else {
1888: e.style.display = "none";
1889: }
1890: }
1891: </SCRIPT>
1892: EEE
1893: ;
1894: $output.=end_html;
1895: return $output;
1896: }
1897:
1898:
1899: MAIN:
1900: {
1901:
1902: setlocale(LC_CTYPE,'russian');
1903: POSIX::setlocale( &POSIX::LC_ALL, $thislocale );
1904: my($i, $tour);
1905: my($text) = (param('text')) ? 1 : 0;
1906: $tour = (param('tour')) ? param('tour') : 0;
1907: my $texttour=$tour;
1908: my ($sth,$dbh);
1909: $dbh = DBI->connect("DBI:mysql:chgk", "piataev", "")
1910: or do {
1911: print h1("Временные проблемы") . "База вопросов временно не
1912: работает. Заходите попозже.";
1913: print &Include_virtual("$reklama") if $url!~/localhost/;
1914: print end_html;
1915: die "Can't connect to DB chgk\n";
1916: };
1917:
1918:
1919: if (param('qid') && (param('qid')=~/^\d+$/) || $tour && $tour=~/^\d+$/) {
1920: my $destination='http://db.chgk.info/search.html';
1921: # print header (-'Content-Type' => 'text/html',
1922: # -'Location:'=> 'http:\\db.chgk.info');
1923: Redirect($destination);
1924: exit
1925: }
1926:
1927: if ($tour && !param('qnumber') && (!param('answers')||(param('answers')<=1)))
1928: {
1929: my $n=param('tour');
1930: $n=~s/.txt$//;
1931: my $gr=($n=~/^[A-Z]/) || (-e "$realHTMLDIR$n.html");
1932: my $destination=tourhref($tour,param('answers')||0,$gr);
1933: my $d=$destination;
1934: $d=~s/$HTMLDIR/$realHTMLDIR/;
1935: # print header.$destination;
1936: print header."$d|".(-e "$realHTMLDIR$n.html");
1937: if (-e $d) {
1938: Redirect($destination);
1939: exit
1940: }
1941: $d=~s/\.\d+//;
1942: $destination=~s/\.\d+//;
1943: print br.br.$d;
1944: if (-e $d) {
1945: Redirect($destination);
1946: exit
1947: }
1948:
1949: }
1950:
1951: if ($tour !~ /^[0-9]*$/) {
1952: if ($tour=~/\./)
1953: {
1954: my ($fname,$n)= split /\./ , $tour;
1955:
1956: $sth = $dbh->prepare(
1957: "SELECT t2.Id FROM Tournaments as t1,
1958: Tournaments as t2
1959: WHERE (t1.FileName = '$fname.txt' OR t1.FileName='$fname')
1960: AND t1.Id=t2.ParentId AND t2.Number=$n");
1961: }
1962: else
1963: {
1964: $sth = $dbh->prepare("SELECT Id FROM Tournaments
1965: WHERE FileName = '$tour.txt' OR
1966: FileName = '$tour'");
1967: }
1968: $sth->execute;
1969: $tour = ($sth->fetchrow)[0];
1970: $sth->finish;
1971: }
1972:
1973:
1974: if ($text && !param ('comp')) {
1975: print header('text/plain');
1976: } elsif (!param('comp')) {print header;}
1977: my $sstr=param('sstr');
1978: $opt_z||=param("makehtml");
1979: if (param('qid')) {
1980: my $sth;
1981: my $qid=param('qid');
1982: # if ($qid !~ /^[0-9]+$/)
1983: {
1984: my ($fname,$t,$n)= split /\./ , $qid;
1985: $n=$t,$t='' unless $n;
1986: $t||=1;
1987: if ($t)
1988: {
1989: $sth = $dbh->prepare(
1990: "SELECT t2.Id FROM Tournaments as t1,
1991: Tournaments as t2
1992: WHERE (t1.FileName = '$fname.txt' OR t1.FileName='$fname')
1993: AND t1.Id=t2.ParentId AND t2.Number=$t");
1994: }
1995: # else
1996: # {
1997: # $sth = $dbh->prepare("SELECT Id FROM Tournaments
1998: # WHERE FileName = '$fname.txt' OR FileName = '$fname'" );
1999: # }
2000: $sth->execute;
2001: $tour = ($sth->fetchrow)[0];
2002: $sth->finish;
2003: $sth = $dbh->prepare(
2004: "SELECT QuestionId FROM
2005: Questions
2006: WHERE ParentId=$tour AND
2007: Questions.Number=$n");
2008: $sth->execute;
2009: $qid = ($sth->fetchrow)[0];
2010: my $query="SELECT Question, Answer from Questions where QuestionId=$qid";
2011: $sth=$dbh->prepare($query);
2012: $sth->execute;
2013: $sstr= join ' ',$sth->fetchrow;
2014: $sth->finish;
2015: $searchin{'Question'}=1;
2016: $searchin{'Answer'}=1;
2017: $sstr=~tr/ёЁ/еЕ/;
2018: $sstr=~s/[^йцукенгшщзхъфывапролджэячсмитьбюЙЦУКЕНГШЩЗХЪФЫВАПРОЛДЖЭЯЧСМИТЬБЮa-zA-Z0-9]/ /gi;
2019: $proxysstr=$sstr;
2020: $proxysstr=makeproxysstr($dbh,\$proxysstr);
2021: }
2022:
2023: }
2024:
2025:
2026: if (!param('comp') and !param('sqldump') and !$text) {
2027: my $title="Результаты поиска на \"". ($proxysstr||$sstr) .'"'
2028: if ($proxysstr||$sstr);
2029: $title||="База вопросов";
2030:
2031: $globaloutput.=start_html(-"title"=>$title,
2032: -author=>'dimrub@icomverse.com',
2033: -bgcolor=>'#fff0e0',
2034: -vlink=>'#800020');
2035: $globaloutput.="<style>
2036: td {font-size: x-small; font-family : sans-serif}
2037: th {font-size: x-small; font-family : sans-serif}
2038: </style>\n";
2039:
2040: $globaloutput.=&Include_virtual("$reklama")||'';
2041: }
2042:
2043: if (!$opt_z && length ($qs)<=255 && $qs !~ /(sstr)|(rand)|(comp)|(all=)/i) {
2044: my $sth=$dbh->prepare("SELECT page,times,t from hash where query=".$dbh->quote($qs));
2045: $sth->execute();
2046: my ($p,$times,$t)=$sth->fetchrow();
2047: $sth->finish;
2048: if ($p) {
2049: print ".$p";
2050: $dbh->disconnect;
2051: exit ;
2052: }
2053: }
2054:
2055:
2056:
2057:
2058: if (param('hideequal')) {
2059: my ($sth)= $dbh -> prepare("select first, second FROM equalto");
2060: $sth -> execute;
2061: while ( my ($first, $second)=$sth -> fetchrow)
2062: {
2063: $forbidden{$first}=1;
2064: }
2065: $sth->finish;
2066: }
2067:
2068:
2069: if (param('rand')) {
2070: my ($type, $qnum) = ('', 12);
2071: $type.=$TypeName{$_} foreach param('type');
2072: # $type .= 'Б' if (param('brain'));
2073: # $type .= 'Ч' if (param('chgk'));
2074: $qnum = param('qnum') if (param('qnum') =~ /^\d+$/);
2075: $qnum = 0 if (!$type);
2076: my $Email;
2077: if (($Email=param('email')) && -x $SENDMAIL &&
2078: open(F, "| $SENDMAIL $Email")) {
2079: my ($mime_type) = $text ? "plain" : "html";
2080: print F <<EOT;
2081: To: $Email
2082: From: olegstepanov\@mail.ru
2083: Subject: Sluchajnij Paket Voprosov "Chto? Gde? Kogda?"
2084: MIME-Version: 1.0
2085: Content-type: text/$mime_type; charset="koi8-r"
2086:
2087: EOT
2088: print F &PrintRandom($dbh, $type, $qnum, $text);
2089: close F;
2090: $globaloutput.= "Пакет случайно выбранных вопросов послан по адресу $Email. Нажмите
2091: на <B>Reload</B> для получения еще одного пакета";
2092: } else {
2093: $globaloutput.= &PrintRandom($dbh, $type, $qnum, $text);
2094: }
2095: }
2096: elsif (param('authors')){
2097: $globaloutput.= &PrintAuthors($dbh,param('authors'));
2098: }
2099: elsif (param('qofauthor')){
2100: $globaloutput.= &PrintQOfAuthor($dbh,param('qofauthor'));
2101: }
2102: elsif (param('sstr')||param('was')) {
2103: $globaloutput.=&PrintSearch($dbh, $sstr||' ', param('metod')||'',param('was'));
2104: $dbh->do("delete from lastqueries where
2105: (TO_DAYS(NOW()) - TO_DAYS(t) >= 2) OR
2106: (time_to_sec(now())-time_to_sec(t) >3600)") if $usewas && random(30)==0;
2107: }
2108: elsif (param('qid')) {
2109: $globaloutput.=&PrintSearch($dbh, $sstr||'', 'proxy');
2110: }
2111: elsif (param('getfile')){
2112: $globaloutput.=&writefile
2113: } elsif (param('all')) {
2114: # my $destination='http://db.chgk.info/all.html';
2115: # Redirect($destination);
2116: # exit;
2117: $globaloutput.=&PrintAll($dbh, 0);
2118: } elsif (param('from_year') && param('to_year')) {
2119: $globaloutput.=&PrintDates($dbh);
2120: } elsif (param('comp')) {
2121: print "Content-Type: application/octet-stream\n";
2122: print "Content-Type: application/force-download\n";
2123: print "Content-Type: application/download\n";
2124: print "Content-Type: application/x-zip-compressed; name=$texttour.zip\n";
2125: print "Content-Disposition: attachment; filename=$texttour.zip \n\n";
2126: $tour ||= 0;
2127: my (@files) = &PrintArchive($dbh, $tour);
2128: WriteFile($dbh,$_) foreach @files;
2129: open F, "$ZIP -j - @files |";
2130: binmode(F);
2131: binmode(STDOUT);
2132: print join "",<F>;
2133: close F;
2134: $dbh->disconnect;
2135: exit;
2136: } elsif (param('sqldump')) {
2137: print header(
2138: -'Content-Type' => 'application/x-zip-compressed; name="dump.zip"',
2139: -'Content-Disposition' => 'attachment; filename="dump.zip"'
2140: );
2141: open F, "$ZIP -j - $DUMPFILE |";
2142: print (<F>);
2143: close F;
2144: $dbh->disconnect;
2145: exit;
2146:
2147: }
2148: elsif (!$opt_z && !param("makehtml")) {
2149: my $QuestionNumber=0;
2150: my $qnum;
2151: if ($qnum=param('qnumber')){
2152: my ($sth) = $dbh->prepare("SELECT QuestionId FROM Questions
2153: WHERE ParentId=$tour AND Number=$qnum");
2154: $sth->execute;
2155: $QuestionNumber=($sth->fetchrow)[0]||0;
2156: }
2157: if ($QuestionNumber) {
2158: $globaloutput.= &PrintQuestion($dbh, $QuestionNumber, $withanswers||0, $qnum, 1,0,0);
2159: # $dbh, $Id, $answer, $qnum, $title, $text
2160: } else {
2161: $globaloutput.=&PrintTournament($dbh, $tour, $withanswers);
2162: }
2163: }
2164: else {
2165: $opt_z=1;
2166: $url="http://db.chgk.info/cgi-bin/db.cgi";
2167: open TS, $timestamp;
2168: my $d=$dbh->quote(<TS>);
2169: close TS;
2170: open FF, ">${realHTMLDIR}index.html" or die "ERROR! - ${HTMLDIR}index.html\n";
2171: my $o=$globaloutput;
2172: $o.=&PrintTournament($dbh, 0, 0);
2173: $o.=&Bottom;
2174: print FF $o;
2175: close FF;
2176: open FF, ">${realHTMLDIR}all.html" or die "ERROR! - ${HTMLDIR}all.html\n";
2177: $o=$globaloutput;
2178: $o.=&PrintAll($dbh,0);
2179: $o.=&Bottom;
2180: print FF $o;
2181: close FF;
2182:
2183:
2184: # my ($sth) = $dbh->prepare("SELECT t1.Id, t1.FileName, t1.Type,
2185: # count(t2.Id)
2186: # FROM Tournaments as t1, Tournaments as t2
2187: # WHERE t1.CreatedAt>$d AND t2.ParentId=t1.Id GROUP BY t1.Id");
2188: my ($sth) = $dbh->prepare("SELECT t1.Id, t1.FileName, t1.Type, count(t2.Id) FROM Tournaments as t1 LEFT JOIN Tournaments as t2
2189: ON t2.ParentId=t1.id WHERE t1.CreatedAt>=$d GROUP BY t1.Id");
2190: $sth->execute;
2191: my ($Id,$fname,$type,$c);
2192: while (($Id,$fname,$type,$c)=$sth->fetchrow,$Id) {
2193: next unless $fname;
2194: print "$fname\n";
2195: $fname=~s/\.txt$//;
2196: if ($type=~/Т/ || $c<=1)
2197: {
2198: open FF, ">$realHTMLDIR$fname-q.html" or die "ERROR! - $fname-q.html\n";
2199: my $o=$globaloutput;
2200: $paramtour=$fname;
2201: $o.=&PrintTournament($dbh, $Id, 0);
2202: $o.=&Bottom;
2203: print FF $o;
2204: close FF;
2205: open FF, ">$realHTMLDIR$fname-a.html";
2206: $o=$globaloutput;
2207: $o.=&PrintTournament($dbh, $Id, 1);
2208: $o.=&Bottom;
2209: print FF $o;
2210: close FF;
2211: }
2212: else {
2213: open FF, ">$realHTMLDIR$fname.html" or die "ERROR! - $fname-q.html\n";
2214: my $o=$globaloutput;
2215: $o.=&PrintTournament($dbh, $Id, 0);
2216: $o.=&Bottom;
2217: print FF $o;
2218: close FF;
2219:
2220: }
2221: }
2222: }
2223: if (!$text) {
2224: $globaloutput.=&Bottom;
2225: }
2226: if (!$opt_z){
2227: print $globaloutput;
2228: if (($qs!~ /(rand)|(sstr)|(comp)/i) && (length $qs<=255)) {
2229: $globaloutput= $dbh->quote($globaloutput);
2230: $dbh->do("insert into hash (query,page) values (".
2231: $dbh->quote($qs).
2232: ",$globaloutput)");
2233: }
2234: }
2235:
2236: $dbh->disconnect;
2237: }
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>