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