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: foreach (keys %{$tasksof{$sf}})
620: {
621: next if $forbidden{$_};
622: $count{$_}++
623: }
624:
625: }
626: @tasks= ($all ? (grep {$count{$_}==$kvo} keys %count) :
627: keys %count) ;
628:
629:
630: ############ Сортировка найденных вопросов
631:
632: foreach (keys %wordsof)
633: {
634: $relevance{$_}=&relevance($#w,$wordsof{$_},\@frequence) if $_
635: }
636:
637: @tasks=sort {$relevance{$b}<=>$relevance{$a}} @tasks;
638:
639: ############
640:
641:
642: return @tasks;
643: }
644:
645:
646: sub distance {
647: # на входе -- номера словоформ и ссылки на
648: # списки вхождений. На выходе -- расстояние,
649: # вычисляемое по формуле min(|b-a-pb+pa|)
650: # pb,pa
651: # (pb и pa -- позиции слов b и a)
652: my ($a,$b,$lista,$listb)=@_;
653: my ($pa,$pb,$min,$curmin);
654: $min=10000;
655: foreach $pa (@$lista)
656: {
657: foreach $pb (@$listb)
658: {
659: $curmin=abs($b-$a-$pb+$pa);
660: $min= $curmin if $curmin<$min;
661: }
662: }
663: return $min;
664:
665: }
666:
667: sub relevance {
668: # На входе -- количество искомых словоформ -1 и
669: # ссылка на hash, ключи которого --
670: # номера словоформ, а значения -- списки вхождений
671:
672: my ($n,$words,$frequence)=@_;
673: my $relevance=0;
674: my ($first,$second,$d);
675: foreach $first (0..$n)
676: {
677: $relevance+=scalar @{$$words{$first}}+1000+1000/$$frequence[$first]
678: if $$words{$first};
679: foreach $second ($first+1..$n)
680: {
681: $d=&distance($first,$second,$$words{$first},$$words{$second});
682: $relevance+=($d>10?0:10-$d)*10;
683: }
684: }
685: return $relevance;
686: }
687:
688:
689:
690: # Returns list of QuestionId's, that have the search string in them.
691: sub Search {
692: my ($dbh, $s,$metod,$all,$allnf) = @_;
693: my $sstr=$$s;
694: my (@arr, @Questions, @fields);
695: my (@sar, $i, $sth,$where,$query);
696: if ($metod eq 'rus')
697: {
698: my @tasks=russearch($dbh,$sstr,$all,$allnf);
699: return @tasks
700: }
701: elsif ($metod eq 'proxy')
702: {
703: my @task=proxy($dbh,$s,$allnf);
704: return @task
705: }
706:
707:
708:
709: ###Simple and advanced query processing. Added by R7
710: if ($metod eq 'simple' || $metod eq 'advanced')
711: {
712: foreach (qw/Question Answer Sources Authors Comments/) {
713: if (param($_)) {
714: push @fields, $_;
715: }
716: }
717:
718: @fields=(qw/Question Answer Sources Authors Comments/) unless scalar @fields;
719: my $fields=join ",", @fields;
720: my $q=new Text::Query($sstr,
721: -parse => 'Text::Query::'.
722: (($metod eq 'simple') ? 'ParseSimple':'ParseAdvanced'),
723: -solve => 'Text::Query::SolveSQL',
724: -build => 'Text::Query::BuildSQLMySQL',
725: -fields_searched => $fields);
726:
727: $where= $$q{'matchexp'};
728: $query= "SELECT Questionid FROM Questions
729: WHERE $where";
730:
731: $sth = $dbh->prepare($query);
732: } else
733: ######
734: {
735:
736: # foreach (qw/Question Answer Sources Authors Comments/) {
737: foreach (param('searchin')) {
738: # if (param($_)) {
739: push @fields, "IFNULL($_, '')";
740: # }
741: }
742: @sar = split " ", $sstr;
743: for $i (0 .. $#sar) {
744: $sar[$i] = $dbh->quote("%${sar[$i]}%");
745: }
746: $_.=' ' foreach (@fields); # Это чтобы последнее слово поля
747: # не сливалось с первым словом
748: # следующего поля, R7
749: my($f) = "CONCAT(" . join(',', @fields) . ")";
750: if (param('all') eq 'yes') {
751: $sstr = join " AND $f LIKE ", @sar;
752: } else {
753: $sstr = join " OR $f LIKE ", @sar;
754: }
755:
756: my $query;
757: $query="SELECT QuestionId FROM Questions
758: WHERE ($f LIKE $sstr) AND (".&makewhere.") ORDER BY QuestionId";
759:
760:
761: $sth = $dbh->prepare($query)
762: } #else -- processing old-style query (R7)
763:
764: $sth->execute;
765: while (@arr = $sth->fetchrow) {
766: push @Questions, $arr[0] unless $forbidden{$arr[0]};
767: }
768: $sth->finish;
769:
770: return @Questions;
771: }
772:
773: sub makewhere {
774: my @type=param('type');
775: my $type='';
776:
777: $type .= ($_=$TypeName{$_}) foreach @type;
778: my $where=' 0 ';
779: foreach (@type) {
780: $where.= " OR (Type ='$_') OR (Type ='$_Д') OR (Type ='Д$_') ";
781: }
782: $where.= "OR (Type='ЧБ')" if ($type=~/Ч|Б/);
783: return $where;
784: }
785:
786: # Substitute every letter by a pair (for case insensitive search).
787: my (@letters) = qw/аА бБ вВ гГ дД еЕ жЖ зЗ иИ йЙ кК лЛ мМ нН оО
788: пП рР сС тТ уУ фФ хХ цЦ чЧ шШ щЩ ьЬ ыЫ эЭ юЮ яЯ/;
789:
790: sub NoCase {
791: my ($sstr) = shift;
792: my ($res);
793:
794: if (($res) = grep(/$sstr/, @letters)) {
795: return "[$res]";
796: } else {
797: return $sstr;
798: }
799: }
800:
801: sub PrintList {
802: my ($dbh,$Questions,$shablon,$was)=@_;
803: my $Output;
804: my $first=param('first') ||1;
805: $first=$first-($first-1)%$outputkvo;
806: my $fkvo=param('fkvo')||($#$Questions+1);
807: my $last=$first+$outputkvo-1;
808: $last=$fkvo if $fkvo<$last;
809: my($f,$l);
810: my $nav='';
811: my $qs=query_string;
812: $qs=~s/\;/\&/g;
813: $qs=~s/\&first\=[^\&]+//g;
814: my $sstr=param('sstr')||'';
815: $qs=~s/sstr=[^\&]+/sstr=$sstr/;
816: if ($usewas) {
817: $qs=~s/\&was=[^\&]+//;
818: $qs.="&was=$was" if $was;
819: $qs.="&fkvo=$fkvo" if $was;
820: }
821: if ($first>$outputkvo*3+1)
822: {
823: $nav.=
824: (" "x4).
825: a({href=>$url."?".$qs."\&first=1"},"<<").(" "x4).
826: a({href=>($url."?".$qs."\&first=".($first-$outputkvo))},"<").(" "x4)
827: }
828: else {$nav.=' 'x15;}
829:
830: my ($fprint,$lprint);
831: my $llprint=$fkvo- ($fkvo)%$outputkvo+1; #
832: if ($fkvo<=$outputkvo*7)
833: { $fprint=1;
834: $lprint=$llprint;
835: }
836: elsif ($first>$outputkvo*3 && $fkvo-$first>$outputkvo*3)
837: {
838: $fprint=$first-$outputkvo*3;
839: $lprint=$first+$outputkvo*3;
840: }
841: elsif ($first<=$outputkvo*3)
842: {
843: $fprint=1; $lprint=6*$outputkvo+1;
844: }
845: else
846: {
847: $lprint=$llprint;
848: $fprint=$lprint-$outputkvo*6
849: }
850:
851: # my $fprint=($first>$outputkvo*3) ? $first-$outputkvo*3 : 1;
852: # my $lprint=$#$Questions+1-$fprint>$outputkvo*7 ? $outputkvo*7 :$#$Questions+1;
853: # if ($lprint-$fprint<$outputkvo*6 && $fprint>1)
854: # {
855: # $fprint=$lprint-$outputkvo*6;
856: # $fprint=1 if ($fprint<=0)
857: # }
858:
859:
860:
861: for($f=$fprint; $f<=$lprint; $f+=$outputkvo)
862: {
863: # next if $first-$f>$outputkvo*3;
864: $l=$f+$outputkvo-1;
865: $l=$fkvo if $l>$fkvo+1;
866: if ($f==$first) {$nav.="[$f-$l] ";}
867: else {
868: $nav.= "[".a({href=>($url."?".$qs."\&first=$f")},"$f-$l")."] ";}
869: }
870: if ($lprint+$outputkvo<$fkvo)
871: {
872: $nav.=
873: (" "x4).
874: a({href=>($url."?".$qs."\&first=".($first+$outputkvo))},">").(" "x4).
875: a({href=>$url."?".$qs."\&first=$llprint"},">>").(" "x4)
876: }
877: $Output.= "$nav".br."\n";
878: my @q=@$Questions[$first-1..$last-1];
879: my %q=();
880: my $sth=SelectQuestions($dbh,\@q,1);
881: my $qq;
882: my @Q;
883: for (0..$#q) {
884: %{$Q[$_]}=();
885: fetchquestion($sth,$Q[$_],1);
886: $q{$Q[$_]{'QuestionId'}}=$Q[$_];
887: }
888:
889: for (my $i = $first; $i <= $last; $i++) {
890: my $q=$q{$$Questions[$i-1]};
891: my $output;
892: $output = &PrintQuestion($dbh, $q, 1, 0, 1,0,1 );
893: # if (param('metod') && (param('metod') eq 'rus' || param('metod') eq 'proxy'))
894: {
895: $output=~s/\b($shablon)\b/\<strong\>$1\<\/strong\>/gi;
896: $output=~s/($shablon)/\<strong\>$1\<\/strong\>/gi;
897: }
898: $Output.= $output;
899: }
900: $sth->finish;
901:
902: $Output.= "$nav".br."\n";
903: return $Output;
904: }
905:
906: sub PrintSearch {
907: my $Output='';
908: my ($dbh, $sstr, $metod,$was) = @_;
909: my $t=time;
910: $Output.= printform;
911: my @allnf;
912: my @Questions;
913: $was=0 if $metod eq 'proxy';
914: if ($usewas && $was && ($metod ne 'proxy'))
915: {
916: my $sth=$dbh->prepare ("select sstr,questions,allnf from lastqueries where id=".param('was'));
917: $sth->execute;
918: my ($q,$nf);
919: ($sstr, $q,$nf)=($sth->fetchrow);
920: @Questions=unpack 'L*',$q;
921: @allnf=unpack 'L*',$nf;
922: $sth->finish;
923: }
924: if (!$was || ($metod eq 'proxy') || (param('first')+$outputkvo>$cashednumber))
925: {
926: @Questions=&Search($dbh, \$sstr,$metod,$all,\@allnf);
927: $cashednumber=$#Questions if $cashednumber>$#Questions;
928: my $tmp=$dbh->quote(pack("L*",@Questions[0..$cashednumber]));
929: my $qsstr=$dbh->quote($sstr);
930: my $nf=$dbh->quote(pack("L*", @allnf));
931: my $ss=200;
932: if ($usewas) {
933: do
934: {
935: $was=int rand(32000);
936: }
937: while (--$ss && (!$dbh->do ("insert into lastqueries (id,sstr,questions,allnf)
938: values ($was, $qsstr,$tmp,$nf)")));
939: $Output.= "Something is wrong...".br unless $ss;
940: }
941: }
942:
943:
944:
945: $Output.= p. "Время поиска: " . (time-$t) ." сек.".p;
946: my ($output, $i, $suffix, $hits) = ('', 0, '', $#Questions + 1);
947:
948: my $shablon;
949: $metod='rus' if $metod eq 'proxy';
950: if ($metod eq 'rus')
951: {
952: my $where='0';
953: $where.= " or w2=$_ " foreach @allnf;
954: my $query="select w1 from nests where $where";
955: my $sth=$dbh->prepare($query);
956:
957: $sth->execute;
958: my @shablon;
959: while (my @arr = $sth->fetchrow)
960: {
961: push @shablon,"(?:$arr[0])";
962: }
963: $sth->finish;
964: $shablon= join "|", @shablon;
965: $shablon=~s/[её]/\[ЕЁ\]/gi;
966: # $shablon=~s/([йцукенгшщзхъфывапролджэячсмитьбюЙЦУКЕНГШЩЗХЪФЫВАПРОЛДЖЭЯЧСМИТЬБЮ])/&NoCase($1)/ge;
967: $shablon=qr/$shablon/i;
968:
969: }
970:
971: $hits=param("fkvo")||$hits;
972:
973: if ($hits =~ /1.$/ || $hits =~ /[5-90]$/) {
974: $suffix = 'й';
975: } elsif ($hits =~ /1$/) {
976: $suffix = 'е';
977: } else {
978: $suffix = 'я';
979: }
980:
981: $Output.= p({align=>"center"}, "Результаты поиска на " . strong($sstr)
982: . " : $hits попадани$suffix.");
983:
984: if (param('word')) {
985: $sstr = '[ \.\,:;]' . $sstr . '[ \.\,:\;]';
986: }
987:
988: # $sstr =~ s/(.)/&NoCase($1)/ge;
989:
990: my @sar;
991: if ($metod ne 'rus')
992: {
993: my $ss=$sstr;
994: (@sar) = split(' ', $ss);
995: s/(\W)/\\$1/g foreach (@sar);
996: $shablon=join "|",@sar;
997: }
998: $Output.=PrintList($dbh,\@Questions,$shablon,$was);
999: return $Output;
1000: }
1001:
1002: sub PrintRandom {
1003: my ($dbh, $type, $num, $text) = @_;
1004: my $razd=param('razd');
1005: my %q;
1006: my $answer=$razd?0:1;
1007: my @answers;
1008: #my $t=time;
1009: my (@Questions) = &Get12Random($dbh, $type, $num);
1010:
1011: my ($output, $i) = ('', 0);
1012: #$output.="time=".(time-$t).p;
1013: if ($text) {
1014: $output .= " $num случайных вопросов.\n\n";
1015: } else {
1016: $output .=
1017: h2({align=>"center"}, "$num случайных вопросов.");
1018: }
1019: my $sth=SelectQuestions($dbh,\@Questions,0);
1020: for ($i = 0; $i <= $#Questions; $i++) {
1021: fetchquestion($sth,\%q,0);
1022: $output .=
1023: &PrintQuestion($dbh, \%q, $answer, $i + 1, 0, $text,1);
1024: push @answers, $q{'Answer'};
1025: }
1026: $sth->finish;
1027: unless ($answer )
1028: {
1029: $output.=$text?"\n".('-'x 20)."\nОтветы\n~~~~~~\n\n":h2('Ответы');
1030: $sth=SelectQuestions($dbh,\@Questions,0);
1031: for ($i = 0; $i <= $#Questions; $i++) {
1032: # fetchquestion($sth,\%q,0);
1033: # $output .=
1034: # &PrintQuestion($dbh, \%q, -1, $i + 1, 0, $text,1);
1035: $output.=$text?("Ответ ". ($i+1).": $answers[$i]\n\n"):
1036: b("Ответ ". ($i+1).": "). $answers[$i].p;
1037: }
1038: }
1039:
1040: return $output;
1041: }
1042:
1043: sub PrintEditor {
1044: my $t=shift; #ссылка на Хэш с полями
1045: my $ed=$$t{'Editors'}||'';
1046: my $edname=($ed=~/\,/ ) ? "Редакторы" : "Редактор" ;
1047: return $ed? h4({align=>"center"},"$edname: $ed" ): '';
1048: }
1049:
1050: sub PrintTournament {
1051: my ($dbh, $Id, $answer) = @_;
1052: my (%Tournament, @Tours, $i, $list, $qnum, $imgsrc, $alt,
1053: $SingleTour);
1054: my ($output) = '';
1055:
1056: %Tournament = &GetTournament($dbh, $Id) if ($Id);
1057:
1058: my ($URL) = $Tournament{'URL'}||'';
1059: $URL=~s/http:\/znatoki\/boris\/reports\//$newsurl/ if $url=~/kulichki/ || $url=~/db.chgk.info/;
1060: $URL=~s/\/znatoki\/boris\/reports\//$newsurl/ if url=~/kulichki/ || $url=~/db.chgk.info/;
1061: my ($Info) = $Tournament{'Info'};
1062: my ($Copyright) = $Tournament{'Copyright'};
1063: my $fname=$Tournament{'FileName'};
1064: @Tours = &GetTours($dbh, $Id);
1065: $list='';
1066: my $textid;
1067: if ($Id) {
1068: for ($Tournament{'Type'}) {
1069: /Г/ && do {
1070: $output .= h2({align=>"center"},
1071: "Группа: $Tournament{'Title'} ",
1072: $Tournament{'PlayedAt'}||'') . p . "\n";
1073: last;
1074: };
1075: /Ч/ && do {
1076: return &PrintTour($dbh, $Tours[0], $answer)
1077: if ($#Tours == 0);
1078:
1079: my $title="Пакет: $Tournament{'Title'}";
1080: if ($Tournament{'PlayedAt'}) {
1081: $title .= " $Tournament{'PlayedAt'}";
1082: }
1083:
1084: $output .= h2({align=>"center"},
1085: "$title") . p . "\n";
1086: $output.=&PrintEditor(\%Tournament);
1087: last;
1088: };
1089: /Т/ && do {
1090: return &PrintTour($dbh, $Id, $answer);
1091: };
1092: }
1093: } else {
1094: my ($qnum) = GetQNum($dbh,0);
1095: my ($qnum1) = GetQNum($dbh,1);
1096: $output .= h2("База вопросов").
1097: h3("$qnum запис".&Suffix2($qnum).
1098: " (уникальных $qnum1)");
1099:
1100: # h4("<table>".
1101: # Tr(td("Из них:"), td("Вопросов ЧГК: ".countz($dbh,'Ч'))).
1102: # Tr(td(" "), td("Вопросов для брейна: ".countz($dbh,'Б'))).
1103: # Tr(td(" "), td("Вопросов для ЧГК и брейна: ".countz($dbh,'ЧБ'))).
1104: # Tr(td(" "), td("Интернет-вопросов: ".countz($dbh,'И'))).
1105: # Tr(td(" "), td("Бескрылок: ".countz($dbh,'Л'))).
1106: # Tr(td(" "),td("Заданий для Своей Игры: ".countz($dbh,'Я'))).
1107: # Tr(td(" "),td("Эрудиток: ".countz($dbh,'Э'))))."</table>"
1108: }
1109:
1110: for ($i = 0; $i <= $#Tours; $i++) {
1111: %Tournament = &GetTournament($dbh, $Tours[$i]);
1112:
1113: if ($Tournament{'Type'} =~ /Ч/) {
1114: $SingleTour = 0;
1115: my (@Tours) = &GetTours($dbh, $Tournament{'Id'});
1116: $SingleTour = 1
1117: if ($#Tours == 0);
1118: }
1119: if ($Tournament{'QuestionsNum'} > 0) {
1120: $qnum = " ($Tournament{'QuestionsNum'} вопрос" .
1121: &Suffix($Tournament{'QuestionsNum'}) . ")\n";
1122: } else {
1123: $qnum = '';
1124: }
1125: if ($Tournament{'Type'} !~ /[ТЧ]/) {
1126: $SingleTour=0;
1127: $imgsrc = "/icons/folder.gif";
1128: $alt = "[*]";
1129: } else {
1130: $imgsrc = "/icons/folder.gif";
1131: $alt = "[-]";
1132: }
1133:
1134: my $textid;
1135: if ($textid=$Tournament{'FileName'})
1136: {
1137: $textid=~s/\.txt//;
1138: }
1139: elsif ($textid=$Tournament{'Number'})
1140: {
1141: $fname=~s/\.txt//;
1142: $textid="$fname.$textid";
1143: }
1144: else {$textid=$Tournament{'Id'}};
1145:
1146:
1147: if ($SingleTour or ($Tournament{'Type'} =~ /Т/)) {
1148: $list .= dd(img({src=>$imgsrc, alt=>$alt})
1149: . " " . $Tournament{'Title'} . " " .
1150: ($Tournament{'PlayedAt'}||"") . $qnum) .
1151: dl(
1152: dd("["
1153: . a({href=>tourhref($textid,0)},
1154: "вопросы") . "] ["
1155: . a({href=>tourhref($textid,1)},
1156: "вопросы + ответы") . "]")
1157: );
1158: } else {
1159: $list .= dd(a({href=>
1160: $url . "?tour=$textid&comp=1"},
1161: img({src=>'/icons/compressed.gif', alt=>'[ZIP]', border=>1})) .
1162: " " .
1163: img({src=>$imgsrc, alt=>$alt})
1164: . " " . a({href=>tourhref($textid,0,1)},
1165: $Tournament{'Title'}. " ".
1166: ($Tournament{'PlayedAt'}||'')) . $qnum);
1167: }
1168: }
1169: $output .= dl($list);
1170:
1171: if ($URL) {
1172: if ($url=~/zaba\.ru/ && $URL=~/^\//){$URL="http://info.chgk.info$URL"}
1173: $output .=
1174: p("Дополнительная информация об этом турнире - по адресу " .
1175: a({-'href'=>$URL}, $URL));
1176: }
1177:
1178: if ($Copyright) {
1179: $output .= p("Копирайт: " . $Copyright);
1180: }
1181:
1182:
1183:
1184: if ($Info) {
1185: $output .= p($Info);
1186: }
1187: return $output;
1188: }
1189:
1190: sub Suffix {
1191: my ($qnum) = @_;
1192: my ($suffix) = 'а' if $qnum =~ /[234]$/;
1193: $suffix = '' if $qnum =~ /1$/;
1194: $suffix = 'ов' if $qnum =~ /[567890]$/ || $qnum =~ /1.$/;
1195: return $suffix;
1196: }
1197:
1198:
1199: sub Suffix1 {
1200: my ($qnum) = @_;
1201: my ($suffix) = 'я' if $qnum =~ /[234]$/;
1202: $suffix = 'е' if $qnum =~ /1$/;
1203: $suffix = 'й' if $qnum =~ /[567890]$/ || $qnum =~ /1.$/;
1204: return $suffix;
1205: }
1206:
1207: sub Suffix2 {
1208: my ($qnum) = @_;
1209: my ($suffix) = 'и' if $qnum =~ /[234]$/;
1210: $suffix = 'ь' if $qnum =~ /1$/;
1211: $suffix = 'ей' if $qnum =~ /[567890]$/ || $qnum =~ /1.$/;
1212: return $suffix;
1213: }
1214:
1215: sub IsTour {
1216: my ($dbh, $Id,$n) = @_;
1217:
1218: my ($sth) ;
1219:
1220: if (defined $n)
1221: { $sth=$dbh->prepare ("select Id FROM Tournaments
1222: WHERE ParentId=$Id AND Number=$n");
1223: }
1224: else
1225: {
1226: $sth=$dbh->prepare("SELECT Id FROM Tournaments
1227: WHERE Id=$Id");
1228: }
1229: $sth->execute;
1230: my $a=($sth->fetchrow)[0];
1231: $sth->finish;
1232: return $a;
1233: }
1234:
1235: # Gets a DB handler (ofcourse) and a tour Id. Prints all the
1236: # question of that tour, according to the options.
1237: sub PrintTour {
1238: my ($dbh, $Id, $answer) = @_;
1239: my ($output, $q, $bottom, $field) = ('', 0, '', '');
1240:
1241: my (%Tour) = &GetTournament($dbh, $Id);
1242: my (@Tours) = &GetTours($dbh, $Tour{'ParentId'});
1243: my (%Tournament) = &GetTournament($dbh, $Tour{'ParentId'});
1244: my %q;
1245:
1246: return 0
1247: if ($Tour{'Type'} !~ /Т/);
1248:
1249: my ($fname)=$Tournament{'FileName'};
1250: $fname=~s/\.txt//;
1251: my ($qnum) = $Tour{'QuestionsNum'};
1252: my ($suffix) = &Suffix($qnum);
1253:
1254: $output .= h2({align=>"center"}, $Tournament{"Title"},
1255: $Tournament{'PlayedAt'}||'',
1256: "<br>", $Tour{"Title"} .
1257: " ($qnum вопрос$suffix)\n") . p;
1258: $output .=&PrintEditor(\%Tour);
1259:
1260: my (@Questions) = &GetTourQuestions($dbh, $Id);
1261: my $sth=SelectQuestions($dbh,\@Questions,0);
1262: for ($q = 0; $q <= $#Questions; $q++) {
1263: fetchquestion($sth,\%q,0);
1264: $output .= &PrintQuestion($dbh, \%q, $answer, 0,0,0,1);
1265: }
1266: $sth->finish;
1267: $output .= hr({-'align'=>'center', -'width'=>'80%'});
1268:
1269: if ($Tournament{'URL'}) {
1270: $output .=
1271: p("Дополнительная информация об этом турнире - по адресу " .
1272: a({-'href'=>$Tournament{'URL'}}, $Tournament{'URL'}));
1273: }
1274:
1275: if ($Tournament{'Copyright'}) {
1276: $output .= p("Копирайт: " . $Tournament{'Copyright'});
1277: }
1278:
1279: if ($Tournament{'Info'}) {
1280: $output .= p($Tournament{'Info'});
1281: }
1282:
1283: my $n=$Tour{'Number'};
1284: if ($answer == 0) {
1285: my $nn=".$n";
1286: $nn="" if ($n==1 && !&IsTour($dbh, $Tour{'ParentId'}, $n + 1));
1287:
1288: $bottom .=
1289: "[" . a({href=>tourhref("$fname$nn",1)},
1290: "ответы") . "] " . br;
1291: }
1292: if ($n>1) {
1293: $bottom .=
1294: "[" . a({href=>tourhref("$fname.".($n-1),0)},
1295: "предыдущий тур") . "] ";
1296: $bottom .=
1297: "[" . a({href=>tourhref("$fname.".($n-1),1)},
1298: "предыдущий тур с ответами") . "] " . br;
1299: }
1300: if (&IsTour($dbh, $Tour{'ParentId'}, $n + 1)) {
1301: $bottom .=
1302: "[" . a({href=>tourhref("$fname.".($n+1),0)},
1303: "следующий тур") . "] ";
1304: $bottom .=
1305: "[" . a({href=>tourhref("$fname.".($n+1),1)},
1306: "следующий тур с ответами") . "] ";
1307: }
1308:
1309: $output .=
1310: p({align=>"center"}, font({size=>-1}, $bottom));
1311:
1312: return $output;
1313: }
1314:
1315: sub PrintField {
1316: my ($header, $value, $text) = @_;
1317: if ($text) {
1318: $value =~ s/<[\/\w]*?>//sg;
1319: } else {
1320: $value =~ s/^\s+/<br> /mg;
1321: $value =~ s/(\s+)-+(\s+)/$1–$2/mg;
1322: $value =~ s/\s+\–/ \–/mg
1323: if $value !~ /^\|/;
1324: $value =~ s/^\|([^\n]*)/<pre>$1<\/pre>/mg;
1325: $value =~ s/(http:\/\/\S+[^\s\)\(\,\.])/<a href="$1">$1<\/a>/g if $header !~ /^Авто/;
1326: # $value =~ s/(http:\/\/(?:\w+.)+[\w\\\~]+(\?[^\s.]+)?)/<a href="$1">$1<\/a>/g if $header !~ /^Авто/;
1327: # $value =~ s/(\s)"/$1“/mg;
1328: # $value =~ s/^"/“/mg;
1329: # $value =~ s/"/”/mg;
1330: }
1331:
1332:
1333: return $text ? "$header:\n$value\n\n" :
1334: strong("$header: ") . $value . p . "\n";
1335: }
1336:
1337: # Gets a DB handler (ofcourse) and a question Id. Prints
1338: # that question, according to the options.
1339: sub PrintQuestion {
1340: my ($dbh, $Id, $answer, $qnum, $title, $text,$h) = @_;
1341: my ($output, $titles) = ('', '');
1342: my $fname;
1343: my (%Question);
1344: if ($h) {
1345: %Question=%$Id;
1346: } else {
1347: %Question = &GetQuestion($dbh, $Id);
1348: if ($title) {
1349: my (%Tour) = GetTournament($dbh, $Question{'ParentId'});
1350: my (%Tournament) = GetTournament($dbh, $Tour{'ParentId'});
1351: $Question{'FileName'}=$Tournament{'FileName'};
1352: $Question{'Title'}=$Tournament{'Title'};
1353: $Question{'PlayedAt'}=$Tournament{'PlayedAt'};
1354: $Question{'TourNumber'}=$Tour{'Number'};
1355: $Question{'TourTitle'}=$Tour{'Title'};
1356: }
1357:
1358: }
1359: $qnum = $Question{'Number'}
1360: if ($qnum == 0);
1361: if (!$text) {
1362: $output .= hr({width=>"50%"}) if $answer>=0;
1363: if ($title) {
1364: $fname=$Question{'FileName'};
1365: $fname=~s/\.txt//;
1366: $titles .=
1367: dd(img({src=>"/icons/folder.open.gif"}) . " " .
1368: a({href=>tourhref($fname,0,1)},
1369: $Question{'Title'}, $Question{'PlayedAt'}||''));
1370: $titles .=
1371: dl(dd(img({src=>"/icons/folder.open.gif"}) . " " .
1372: a({href=>tourhref("$fname.$Question{'TourNumber'}#$qnum",1)},
1373: $Question{'TourTitle'})));
1374: }
1375: $output .= dl(strong($titles));
1376: }
1377:
1378:
1379: $output.= "<a NAME=\"$qnum\">" unless $text;
1380:
1381: if ($answer>=0) {$output .=
1382: &PrintField("Вопрос $qnum", $Question{'Question'}, $text);}
1383: else {$output .="$qnum. "}
1384: if ($answer==1|| $answer==-1) {
1385: $output .=
1386: &PrintField("Ответ", $Question{'Answer'}, $text);
1387:
1388: if ($Question{'Authors'} ) {
1389: my $q=$Question{'Authors'};
1390: ###АВТОРА!!
1391: # my $sth=$dbh->prepare("select Authors.CharId,Name, Surname, Nicks from Authors, A2Q
1392: # where Authors.Id=Author And Question=$Id");
1393: # $sth->execute;
1394: # my ($AuthorId,$Name, $Surname,$other,$Nicks);
1395: # if (!$text) {
1396: # while ((($AuthorId,$Name, $Surname,$Nicks)=$sth->fetchrow),$AuthorId)
1397: # {
1398: # my ($firstletter)=$Name=~m/^./g;
1399: # $Name=~s/\./\\\./g;
1400: # $Name=~s/ё/[её]/g;
1401: # $Surname=~s/ё/[её]/g;
1402: # my $sha="(?:$Name\\s+$Surname)|(?:$Surname\\s+$Name)|(?:$firstletter\\.\\s*$Surname)|(?:$Surname\\s+$firstletter\\.)|(?:$Surname)";
1403: # if ($Nicks)
1404: # {
1405: # $Nicks=~s/^\|//;
1406: # foreach (split /\|/, $Nicks)
1407: # {
1408: # s/\s+/ /g;
1409: # s/\s+$//;
1410: # s/ /\\s+/g;
1411: # s/\./\\\./g;
1412: # if (s/>$//) {$sha="$sha|(?:$_)"}
1413: # else {$sha="(?:$_)|$sha"}
1414: # }
1415: # }
1416: # $q=~s/($sha)/a({href=>url."?qofauthor=$AuthorId"},$1)/ei;
1417: # unless ($1)
1418: # {
1419: # $q=~s/$Name/a({href=>url."?qofauthor=$AuthorId"},$1)/ei;
1420: # }
1421: # }
1422: # }
1423: $output .= &PrintField("Автор(ы)", $q, $text);
1424:
1425: }
1426:
1427: if ($Question{'Sources'}) {
1428: $output .= &PrintField("Источник(и)", $Question{'Sources'}, $text);
1429: }
1430:
1431: if ($Question{'Comments'}) {
1432: $output .= &PrintField("Комментарии", $Question{'Comments'}, $text);
1433: }
1434: }
1435: elsif ($answer==2) {
1436: my $text=$Question{'Answer'};
1437: $text=~s/\n/<option>/mg;
1438: $output.="<select><option selected>Ответ:<option>$text</select>";
1439: $text=$Question{'Comments'}||'';
1440: if ($text) {
1441: $text=~s/\n/<option>/mg;
1442: $output.="<select><option selected>Комментарий:<option>$text</select>"
1443: }
1444: }
1445: elsif ($answer==3) {
1446: $output.= <<EOTT
1447: <div align=right STYLE="cursor:hand;" OnStart="toggle(document.all.HideShow$qnum);" OnClick="toggle(document.all.HideShow$qnum);">
1448: <font size=-2 color=red> Показать/убрать ответ</font></div>
1449: <span style="display:none" id=HideShow$qnum>
1450: EOTT
1451: .&PrintField("Ответ", $Question{'Answer'}, $text);
1452: if ($Question{'Authors'}) {
1453: $output .= &PrintField("Автор(ы)", $Question{'Authors'}, $text);
1454: }
1455: if ($Question{'Sources'}) {
1456: $output .= &PrintField("Источник(и)", $Question{'Sources'}, $text);
1457: }
1458:
1459: if ($Question{'Comments'}) {
1460: $output .= &PrintField("Комментарии", $Question{'Comments'}, $text);
1461: }
1462:
1463:
1464:
1465: $output.="</span>"
1466:
1467: }
1468: $output=~s/\(pic: ([^\)]*)\)/<p><img src="\/znatoki\/images\/db\/$1"><p>/g unless $text;
1469: $paramtour||=param("tour");
1470: $fname=$fname.".$Question{'TourNumber'}" if $fname && $Question{'TourNumber'};
1471: $fname||=param('tour');
1472: my $qid=$fname ? ($fname.".$Question{'Number'}" ): '';
1473:
1474: $output.=br.a({href=> $url."?metod=proxy&
1475: qid=$qid"}, 'Близкие вопросы').p
1476: if $answer>0 && !$text && $qid;
1477: return $output;
1478: }
1479:
1480: # Returns the total number of questions currently in the DB.
1481: sub GetQNum {
1482: my ($dbh,$x) = @_;
1483: my ($sth) = $dbh->prepare("SELECT COUNT(*) FROM Questions");
1484: $sth->execute;
1485: my $tmp=($sth->fetchrow)[0];
1486: $sth->finish;
1487: ($sth)= $dbh -> prepare("select distinct count(first) FROM equalto");
1488: $sth -> execute;
1489: my ($c)=$sth->fetchrow;
1490:
1491: # $i++ while ( my ($first, $second)=$sth -> fetchrow)
1492: # {
1493: # $forbidden{$first}=1;
1494: # }
1495: $sth->finish;
1496:
1497: return $tmp-($x?$c:0);
1498: }
1499: sub GetMaxQId {
1500: my ($dbh) = @_;
1501: my ($sth) = $dbh->prepare("SELECT MAX(QuestionId) FROM Questions");
1502: $sth->execute;
1503: my $tmp=($sth->fetchrow)[0];
1504: $sth->finish;
1505: return $tmp;
1506:
1507: }
1508:
1509: # Returns Id's of 12 random questions
1510: sub Get12Random {
1511: my ($dbh, $type, $num) = @_;
1512: my ($i, @questions, $q, $t, $sth);
1513: my ($qnum) = &GetMaxQId($dbh);
1514: my (%chosen);
1515: srand;
1516: my $where=0;
1517: my $r=int (rand(10000));
1518: my $w1=$r<5000? "QuestionId<50000 ":"QuestionId>=50000";
1519: $w1=1 if $url=~/zaba/;
1520: $w1=1 if $type!~/Ч/;
1521: foreach (split '', $type)
1522: {
1523: $where.= " OR (Type ='$_') OR (Type ='$_Д') ";
1524: }
1525: $where.= "OR (Type='ЧБ')" if ($type=~/Ч|Б/);
1526:
1527: # $q="select QuestionId, QuestionId/$r-floor(QuestionId/$r) as val
1528: # from Questions where $where order by val limit $num";
1529: # Когда на куличках появится mysql >=3.23 надо заменить на order by rand();
1530: $q="select QuestionId from Questions where ($w1) AND ($where) order by rand() limit $num";
1531:
1532:
1533: $sth=$dbh->prepare($q);
1534: $sth->execute;
1535: while (($i)=$sth->fetchrow)
1536: {
1537: push @questions,$i;
1538: }
1539: $sth->finish;
1540: for ($i=@questions; --$i;){
1541: my $j=rand ($i+1);
1542: @questions[$i,$j]=@questions[$j,$i] unless $i==$j;
1543: }
1544: return @questions;
1545: }
1546:
1547: sub Include_virtual {
1548: my ($fn, $output) = (@_, '');
1549: return "\n<!--#include virtual=\"$fn\"-->\n" if ($opt_z);
1550: open F , $fn
1551: or return ""; #die "Can't open the file $fn: $!\n";
1552:
1553: while (<F>) {
1554: if (/<!--#include/o) {
1555: s/<!--#include virtual="\/?([^\/].*)" -->/&Include_virtual($1)/e;
1556: }
1557: if (/<!--#exec/o) {
1558: s/<!--#exec.*cmd\s*=\s*"([^"]*)".*-->/`$1`/e;
1559: }
1560: $output .= $_;
1561: }
1562: return $output||"";
1563: }
1564:
1565: sub PrintArchive {
1566: my($dbh, $Id) = @_;
1567: my ($output, @list, $i);
1568:
1569: my (%Tournament) = &GetTournament($dbh, $Id);
1570: my (@Tours) = &GetTours($dbh, $Id);
1571: if ($Tournament{'Type'} =~ /Г/ || $Id == 0) {
1572: for ($i = 0; $i <= $#Tours; $i++) {
1573: push(@list ,&PrintArchive($dbh, $Tours[$i]));
1574: }
1575: return @list;
1576: }
1577: # return "$SRCPATH/$Tournament{'FileName'} ";
1578: return "$TMPDIR/$Tournament{'FileName'} ";
1579: }
1580:
1581: sub PrintAll {
1582: my ($dbh, $Id,$fname) = @_;
1583: my ($output, $list, $i);
1584:
1585: my (%Tournament) = &GetTournament($dbh, $Id);
1586: my (@Tours) = &GetTours($dbh, $Id);
1587: my $SingleTour = $#Tours == 0;
1588:
1589: my ($New) = ($Id and $Tournament{'Type'} eq 'Ч' and
1590: &NewEnough($Tournament{"CreatedAt"})) ?
1591: img({src=>"/znatoki/dimrub/db/new-sml.gif", alt=>"NEW!"}) : "";
1592:
1593: if ($Id == 0) {
1594: $output = h3("Все турниры");
1595: } else {
1596: my $textid;
1597: if ($textid=$Tournament{'FileName'})
1598: {
1599: $textid=~s/\.txt//;
1600: }
1601: elsif ($textid=$Tournament{'Number'})
1602: {
1603: $fname=~s/\.txt//;
1604: $textid="$fname.$textid";
1605: }
1606: else {$textid=$Tournament{'Id'}};
1607:
1608:
1609: $output .= dd(img({src=>"/icons/folder.gif", alt=>"[*]"}) .
1610: " " . a({href=>tourhref($textid,0,!$SingleTour)},
1611: $Tournament{'Title'}) ." " . ($Tournament{'PlayedAt'}||'') . " $New");
1612: }
1613: if ($Id == 0 or $Tournament{'Type'} =~ /Г/ or $Tournament{'Type'} eq '') {
1614: for ($i = 0; $i <= $#Tours; $i++) {
1615: $list .= &PrintAll($dbh, $Tours[$i],$Tournament{'FileName'});
1616: }
1617: $output .= dl($list);
1618: }
1619: return $output;
1620: }
1621:
1622: sub PrintDates {
1623: my ($dbh) = @_;
1624: my ($from) = param('from_year') . "-" . param('from_month') .
1625: "-" . param('from_day');
1626: my ($to) = param('to_year') . "-" . param('to_month') . "-" . param('to_day');
1627: $from = $dbh->quote($from);
1628: $to = $dbh->quote($to);
1629: my ($sth) = $dbh->prepare("
1630: SELECT DISTINCT Id
1631: FROM Tournaments
1632: WHERE PlayedAt >= $from AND PlayedAt <= $to
1633: AND Type = 'Ч'
1634: ");
1635: $sth->execute;
1636: my (%Tournament, @array, $output, $list);
1637:
1638: $output = h3("Список турниров, проходивших между $from и $to.");
1639: while (@array = $sth->fetchrow) {
1640: next
1641: if (!$array[0]);
1642: %Tournament = &GetTournament($dbh, $array[0]);
1643: my $textid;
1644: if ($textid=$Tournament{'FileName'})
1645: {
1646: $textid=~s/\.txt//;
1647: }
1648: elsif ($textid=$Tournament{'Number'})
1649: {
1650: $fname=~s/\.txt//;
1651: $textid="$fname.$textid";
1652: }
1653: else {$textid=$Tournament{'Id'}};
1654: $list .= dd(img({src=>"/icons/folder.gif", alt=>"[*]"}) .
1655: " " . a({href=>tourhref($textid,0,1)},
1656: $Tournament{'Title'}, $Tournament{'PlayedAt'}||''));
1657: }
1658: $sth->finish;
1659: $output .= dl($list);
1660: return $output;
1661: }
1662:
1663: sub PrintQOfAuthor
1664: {
1665:
1666: my ($dbh, $id) = @_;
1667: my $Output='';
1668: unless ($id=~/^\d+$/) {
1669: $id=$dbh->quote($id);
1670: my $sth = $dbh->prepare("SELECT Id FROM Authors WHERE CharId=$id");
1671: $sth->execute;
1672: ($id)=$sth->fetchrow;
1673: $sth->finish;
1674: }
1675: $id=$dbh->quote($id);
1676:
1677: my $sth = $dbh->prepare("SELECT Name, Surname FROM Authors WHERE Id=$id");
1678: $sth->execute;
1679: my ($name,$surname)=$sth->fetchrow;
1680:
1681: $sth = $dbh->prepare("SELECT Question FROM A2Q WHERE Author=$id");
1682: $sth->execute;
1683: my $q;
1684: my @Questions;
1685: while (($q)=$sth->fetchrow,$q)
1686: {push @Questions,$q unless $forbidden{$q}}
1687: $sth->finish;
1688:
1689: my ($output, $i, $suffix, $hits) = ('', 0, '', $#Questions + 1);
1690:
1691: if ($hits =~ /1.$/ || $hits =~ /[5-90]$/) {
1692: $suffix = 'й';
1693: } elsif ($hits =~ /1$/) {
1694: $suffix = 'е';
1695: } else {
1696: $suffix = 'я';
1697: }
1698: $Output.= printform;
1699: $Output.= p({align=>"center"}, "Автор ".strong("$name $surname. ")
1700: . " : $hits попадани$suffix.");
1701:
1702:
1703: # for ($i = 0; $i <= $#Questions; $i++) {
1704: # $output = &PrintQuestion($dbh, $Questions[$i], 1, $i + 1, 1);
1705: # print $output;
1706: # }
1707: $Output.=PrintList($dbh,\@Questions,'gdfgdfgdfgdfg');
1708: }
1709:
1710:
1711: sub PrintAuthors
1712: {
1713: my ($dbh,$sort)=@_;
1714: my($output,$out1,@array,$sth);
1715: if ($sort eq 'surname')
1716: {
1717: $sth =
1718: $dbh->prepare("SELECT Id, Name, Surname, QNumber FROM Authors order by Surname, Name");
1719: }
1720: elsif($sort eq 'name')
1721: {
1722: $sth =
1723: $dbh->prepare("SELECT Id, Name, Surname, QNumber FROM Authors order by Name, Surname");
1724: }
1725: else
1726: {
1727: $sth =
1728: $dbh->prepare("SELECT Id, Name, Surname, QNumber FROM Authors Order by QNumber DESC, Surname");
1729: }
1730:
1731: $output.=h2("Авторы вопросов")."\n";
1732: $output.="<TABLE>";
1733:
1734:
1735: $sth->execute;
1736: $output.=Tr(th[a({href=>$url."?authors=name"},"Имя")
1737: .", ".
1738: a({href=>$url."?authors=surname"},"фамилия")
1739: , a({href=>$url."?authors=kvo"},"Количество вопросов")]);
1740:
1741: $out1='';
1742:
1743: my $ar=$sth->fetchall_arrayref;
1744:
1745: $sth->finish;
1746:
1747:
1748: foreach my $arr(@$ar)
1749: {
1750:
1751: my ($id,$name,$surname,$kvo)=@$arr;
1752: if (!$name || !$surname) {
1753: } else
1754: {
1755: my $add=Tr(td([a({href=>$url."?qofauthor=$id"},"$name $surname"), $kvo]))."\n";
1756: $output.=$add;
1757: }
1758: }
1759: $output.="</TABLE>";
1760: $sth->finish;
1761: return $output;
1762: }
1763:
1764:
1765: sub WriteFile {
1766: my ($dbh,$fname) = @_;
1767: $fname=~s/\s+$//;
1768: $fname=~s/^\s+//;
1769: $fname=~s/\.txt$//;
1770: $fname=~s/.*\/(\w+)/$1/;
1771:
1772: my $query= "SELECT Id, Title, Copyright, Info, URL,
1773: Editors, EnteredBy, PlayedAt, CreatedAt
1774: from Tournaments where FileName=
1775: '$fname' OR FileName=".$dbh->quote("$fname.txt");
1776: my $sth=$dbh->prepare($query);
1777: my (%Question,%editor,%qnumber,%copyright,%author,%vid,%tourtitle);
1778: $sth->execute;
1779: my ($Id, $Title, $Copyright, $Info, $URL,
1780: $Editors, $EnteredBy, $PlayedAt, $CreatedAt)=
1781: $sth->fetchrow;
1782: return -1 unless $Id;
1783: open (OUT, ">$TMPDIR/$fname.txt") || print STDERR "Error in $fname.txt\n";
1784: print OUT "Чемпионат:\n$Title\n\n";
1785: my $date=$PlayedAt||'00-00-00';
1786: my ($year,$month,$day)=split /-/, $date;
1787: # $month=0,$date=0 if $year && $month==1 && $day==1;
1788: my $pdate=sprintf("%02d-%3s-%4d",$day,$months[$month],$year);
1789:
1790: print OUT "Дата:\n$pdate\n\n" if $date;
1791:
1792: print OUT "URL:\n$URL\n\n" if $URL;
1793:
1794: print OUT "Инфо:\n$Info\n\n" if $Info;
1795:
1796: print OUT "Копирайт:\n$Copyright\n\n" if $Copyright;
1797:
1798: print OUT "Редактор:\n$Editors\n\n" if $Editors;
1799:
1800:
1801: $query= "SELECT Id, Title, Copyright, Editors from Tournaments where ParentId=$Id order by Id";
1802: $sth=$dbh->prepare($query);
1803: $sth->execute;
1804: my ($tourid,$tourtitle,$cright,$editor,@tours,$vid,$author,$tourauthor);
1805:
1806:
1807: while (($tourid,$tourtitle,$cright,$editor)=$sth->fetchrow,$tourid)
1808: {
1809: # $text{$tourid}="Тур:\n$tourtitle\n\n";
1810: $query= "SELECT * from Questions where ParentId=$tourid order by QuestionId";
1811: my $sth1=$dbh->prepare($query);
1812: $sth1->execute;
1813: push(@tours,$tourid);
1814: $tourtitle{$tourid}=$tourtitle;
1815: $copyright{$tourid}=$cright;
1816: $editor{$tourid}=$editor;
1817: $vid='';
1818: my $author='';
1819: my $eqauthor=1;
1820: my $qnumber=0;
1821: my @arr;
1822: while ( (@arr=$sth1->fetchrow), $arr[0])
1823: {
1824: my($i, $name);
1825: $i=0;
1826: $qnumber++;
1827: foreach $name (@{$sth1->{NAME}}) {
1828: if ($arr[$i]) {
1829: $arr[$i]=~s/^(.*?)\s*$/$1/;
1830: $Question{$tourid}[$qnumber]{$name} = $arr[$i];
1831: } else {
1832: $Question{$tourid}[$qnumber]{$name} =
1833: ''}
1834: $i++;
1835: }
1836: if ($vid)
1837: {
1838: if ($vid ne $Question{$tourid}[$qnumber]{'Type'}) {print STDERR "Warning: Different types for Tournament $tourid\n"}
1839: } else
1840: {
1841: $vid=$Question{$tourid}[$qnumber]{'Type'};
1842: }
1843:
1844: if ($author)
1845: {
1846: if ($author ne $Question{$tourid}[$qnumber]{'Authors'})
1847: {
1848: $eqauthor=0;
1849: }
1850: } else
1851: {
1852: $author=$Question{$tourid}[$qnumber]{'Authors'};
1853: $eqauthor=0 unless $author;
1854: }
1855: }
1856: $vid{$tourid}=$vid;
1857: $qnumber{$tourid}=$qnumber;
1858: $author{$tourid}=$eqauthor ? $author : '';
1859: }
1860:
1861:
1862: $vid='';
1863: my $eqvid=1;
1864: my $eqauthor=1;
1865: foreach (@tours)
1866: {
1867: $vid||=$vid{$_};
1868: if ($vid{$_} ne $vid)
1869: {
1870: $eqvid=0;
1871: }
1872: $author||=$author{$_};
1873: if (!$author{$_} || ($author{$_} ne $author))
1874: {
1875: $eqauthor=0;
1876: }
1877: }
1878:
1879: print OUT "Вид:\n$vid\n\n" if $eqvid;
1880: print OUT "Автор:\n$author\n\n" if $eqauthor;
1881:
1882: foreach my $tour(@tours)
1883: {
1884: print OUT "Тур:\n$tourtitle{$tour}\n\n";
1885: print OUT "Вид:\n$vid{$tour}\n\n" if !$eqvid;
1886: print OUT "Копирайт:\n$copyright{$tour}\n\n" if $copyright{$tour} && ($copyright{$tour} ne $Copyright);
1887: print OUT "Редактор:\n$editor{$tour}\n\n" if $editor{$tour} && ($editor{$tour} ne $Editors);
1888: $tourauthor=0;
1889: if (!$eqauthor && $author{$tour})
1890: {
1891: print OUT "Автор:\n$author{$tour}\n\n";
1892: $tourauthor=1;
1893: }
1894: foreach my $q(1..$qnumber{$tour})
1895: {
1896: print OUT "Вопрос $q:\n".$Question{$tour}[$q]{'Question'}."\n\n";
1897: print OUT "Ответ:\n".$Question{$tour}[$q]{'Answer'}."\n\n";
1898: print OUT "Автор:\n".$Question{$tour}[$q]{'Authors'}."\n\n"
1899: if !$tourauthor && !$eqauthor && $Question{$tour}[$q]{'Authors'};
1900: print OUT "Комментарий:\n".$Question{$tour}[$q]{'Comments'}."\n\n"
1901: if $Question{$tour}[$q]{'Comments'};
1902: print OUT "Источник:\n".$Question{$tour}[$q]{'Sources'}."\n\n"
1903: if $Question{$tour}[$q]{'Sources'};
1904: print OUT "Рейтинг:\n".$Question{$tour}[$q]{'Rating'}."\n\n"
1905: if $Question{$tour}[$q]{'Rating'};
1906:
1907: }
1908: }
1909:
1910: close OUT;
1911:
1912:
1913:
1914: }
1915:
1916: sub Bottom
1917: {
1918: my $output.=&Include_virtual("$footer")||"";
1919: $output.=p."<center><font size=-2>Обновление: ".&Include_virtual("$datefooter")."</center></font>";
1920: $output.=<<EEE
1921: <SCRIPT LANGUAGE="JavaScript">
1922: function toggle(e) {
1923: if (e.style.display == "none") {
1924: e.style.display="";
1925: } else {
1926: e.style.display = "none";
1927: }
1928: }
1929: </SCRIPT>
1930: EEE
1931: ;
1932: $output.=end_html;
1933: return $output;
1934: }
1935:
1936:
1937: MAIN:
1938: {
1939:
1940: setlocale(LC_CTYPE,'russian');
1941: POSIX::setlocale( &POSIX::LC_ALL, $thislocale );
1942: my($i, $tour);
1943: my($text) = (param('text')) ? 1 : 0;
1944: $tour = (param('tour')) ? param('tour') : 0;
1945: my $texttour=$tour;
1946: my ($sth,$dbh);
1947: my($dsn) = "DBI:mysql:database=$dbname;host=$dbhost";
1948: $dbh = DBI->connect($dsn, $dbuser, $dbpass)
1949: # $dbh = DBI->connect("DBI:mysql:$dbname", $username, $dbpass)
1950: or do {
1951: print header.h1("Временные проблемы") . "База вопросов временно не
1952: работает. Заходите попозже.";
1953: print &Include_virtual("$reklama") if $url!~/localhost/;
1954: print end_html;
1955: die "Can't connect to DB chgk\n";
1956: };
1957:
1958:
1959: if (param('qid') && (param('qid')=~/^\d+$/) || $tour && $tour=~/^\d+$/) {
1960: my $destination='http://chgk.zaba.ru/search.html';
1961: # print header (-'Content-Type' => 'text/html',
1962: # -'Location:'=> 'http:\\db.chgk.info');
1963: Redirect($destination);
1964: exit
1965: }
1966:
1967: if ($tour && !param('qnumber') && (!param('answers')||(param('answers')<=1)))
1968: {
1969: my $n=param('tour');
1970: $n=~s/.txt$//;
1971: my $gr=($n=~/^[A-Z]/) || (-e "$realHTMLDIR$n.html");
1972: my $destination=tourhref($tour,param('answers')||0,$gr);
1973: my $d=$destination;
1974: $d=~s/$HTMLDIR/$realHTMLDIR/;
1975: # print header.$destination;
1976: # print header."$d|".(-e "$realHTMLDIR$n.html");
1977: if (-e $d) {
1978: Redirect($destination);
1979: exit
1980: }
1981: $d=~s/\.\d+//;
1982: $destination=~s/\.\d+//;
1983: if (-e $d) {
1984: Redirect($destination);
1985: exit
1986: }
1987:
1988: }
1989:
1990: if ($tour !~ /^[0-9]*$/) {
1991: if ($tour=~/\./)
1992: {
1993: my ($fname,$n)= split /\./ , $tour;
1994:
1995: $sth = $dbh->prepare(
1996: "SELECT t2.Id FROM Tournaments as t1,
1997: Tournaments as t2
1998: WHERE (t1.FileName = '$fname.txt' OR t1.FileName='$fname')
1999: AND t1.Id=t2.ParentId AND t2.Number=$n");
2000: }
2001: else
2002: {
2003: $sth = $dbh->prepare("SELECT Id FROM Tournaments
2004: WHERE FileName = '$tour.txt' OR
2005: FileName = '$tour'");
2006: }
2007: $sth->execute;
2008: $tour = ($sth->fetchrow)[0];
2009: $sth->finish;
2010: }
2011:
2012:
2013: if ($text && !param ('comp')) {
2014: print header('text/plain');
2015: } elsif (!param('comp')) {
2016: print header(-charset =>'koi8-r')}
2017: my $sstr=param('sstr');
2018: $opt_z||=param("makehtml");
2019: if (param('qid')) {
2020: my $sth;
2021: my $qid=param('qid');
2022: # if ($qid !~ /^[0-9]+$/)
2023: {
2024: my ($fname,$t,$n)= split /\./ , $qid;
2025: $n=$t,$t='' unless $n;
2026: $t||=1;
2027: if ($t)
2028: {
2029: $sth = $dbh->prepare(
2030: "SELECT t2.Id FROM Tournaments as t1,
2031: Tournaments as t2
2032: WHERE (t1.FileName = '$fname.txt' OR t1.FileName='$fname')
2033: AND t1.Id=t2.ParentId AND t2.Number=$t");
2034: }
2035: # else
2036: # {
2037: # $sth = $dbh->prepare("SELECT Id FROM Tournaments
2038: # WHERE FileName = '$fname.txt' OR FileName = '$fname'" );
2039: # }
2040: $sth->execute;
2041: $tour = ($sth->fetchrow)[0];
2042: $sth->finish;
2043: $sth = $dbh->prepare(
2044: "SELECT QuestionId FROM
2045: Questions
2046: WHERE ParentId=$tour AND
2047: Questions.Number=$n");
2048: $sth->execute;
2049: $qid = ($sth->fetchrow)[0];
2050: my $query="SELECT Question, Answer from Questions where QuestionId=$qid";
2051: $sth=$dbh->prepare($query);
2052: $sth->execute;
2053: $sstr= join ' ',$sth->fetchrow;
2054: $sth->finish;
2055: $searchin{'Question'}=1;
2056: $searchin{'Answer'}=1;
2057: $sstr=~tr/ёЁ/еЕ/;
2058: $sstr=~s/[^йцукенгшщзхъфывапролджэячсмитьбюЙЦУКЕНГШЩЗХЪФЫВАПРОЛДЖЭЯЧСМИТЬБЮa-zA-Z0-9]/ /gi;
2059: $proxysstr=$sstr;
2060: $proxysstr=makeproxysstr($dbh,\$proxysstr);
2061: }
2062:
2063: }
2064:
2065:
2066: if (!param('comp') and !param('sqldump') and !$text) {
2067: my $title="Результаты поиска на \"". ($proxysstr||$sstr) .'"'
2068: if ($proxysstr||$sstr);
2069: $title||="База вопросов";
2070: $globaloutput.=start_html(-"title"=>$title,
2071: -author=>'dimrub@icomverse.com',
2072: -bgcolor=>'#fff0e0',
2073: -vlink=>'#800020');#}
2074: $globaloutput.="<style>
2075: td {font-size: x-small; font-family : sans-serif}
2076: th {font-size: x-small; font-family : sans-serif}
2077: </style>\n";
2078:
2079: $globaloutput.=&Include_virtual("$reklama")||'';
2080: }
2081:
2082: if ($usehash && !$opt_z && length ($qs)<=255 && $qs !~ /(sstr)|(rand)|(comp)|(all=)/i) {
2083: my $sth=$dbh->prepare("SELECT page,times,t from hash where query=".$dbh->quote($qs));
2084: $sth->execute();
2085: my ($p,$times,$t)=$sth->fetchrow();
2086: $sth->finish;
2087: if ($p) {
2088: print ".$p";
2089: $dbh->disconnect;
2090: exit ;
2091: }
2092: }
2093:
2094:
2095:
2096:
2097: if (param('hideequal')) {
2098: my ($sth)= $dbh -> prepare("select first, second FROM equalto");
2099: $sth -> execute;
2100: while ( my ($first, $second)=$sth -> fetchrow)
2101: {
2102: $forbidden{$first}=1;
2103: }
2104: $sth->finish;
2105: }
2106:
2107:
2108:
2109: if (param('rand')) {
2110: my ($type, $qnum) = ('', 12);
2111: $type.=$TypeName{$_} foreach param('type');
2112: # $type .= 'Б' if (param('brain'));
2113: # $type .= 'Ч' if (param('chgk'));
2114: $qnum = param('qnum') if (param('qnum') =~ /^\d+$/);
2115: $qnum = 0 if (!$type);
2116: my $Email;
2117: if (($Email=param('email')) && -x $SENDMAIL &&
2118: open(F, "| $SENDMAIL $Email")) {
2119: my ($mime_type) = $text ? "plain" : "html";
2120: print F <<EOT;
2121: To: $Email
2122: From: olegstepanov\@mail.ru
2123: Subject: Sluchajnij Paket Voprosov "Chto? Gde? Kogda?"
2124: MIME-Version: 1.0
2125: Content-type: text/$mime_type; charset="koi8-r"
2126:
2127: EOT
2128: print F &PrintRandom($dbh, $type, $qnum, $text);
2129: close F;
2130: $globaloutput.= "Пакет случайно выбранных вопросов послан по адресу $Email. Нажмите
2131: на <B>Reload</B> для получения еще одного пакета";
2132: } else {
2133: $globaloutput.= &PrintRandom($dbh, $type, $qnum, $text);
2134: }
2135: }
2136: elsif (param('authors')){
2137: $globaloutput.= &PrintAuthors($dbh,param('authors'));
2138: }
2139: elsif (param('qofauthor')){
2140: $globaloutput.= &PrintQOfAuthor($dbh,param('qofauthor'));
2141: }
2142: elsif (param('sstr')||param('was')) {
2143: $globaloutput.=&PrintSearch($dbh, $sstr||' ', param('metod')||'',param('was'));
2144: $dbh->do("delete from lastqueries where
2145: (TO_DAYS(NOW()) - TO_DAYS(t) >= 2) OR
2146: (time_to_sec(now())-time_to_sec(t) >3600)") if $usewas && random(30)==0;
2147: }
2148: elsif (param('qid')) {
2149: $globaloutput.=&PrintSearch($dbh, $sstr||'', 'proxy');
2150: }
2151: elsif (param('getfile')){
2152: $globaloutput.=&writefile
2153: } elsif (param('all')) {
2154: # my $destination='http://db.chgk.info/all.html';
2155: # Redirect($destination);
2156: # exit;
2157: $globaloutput.=&PrintAll($dbh, 0);
2158: } elsif (param('from_year') && param('to_year')) {
2159: $globaloutput.=&PrintDates($dbh);
2160: } elsif (param('comp')) {
2161: print "Content-Type: application/octet-stream\n";
2162: print "Content-Type: application/force-download\n";
2163: print "Content-Type: application/download\n";
2164: print "Content-Type: application/x-zip-compressed; name=$texttour.zip\n";
2165: print "Content-Disposition: attachment; filename=$texttour.zip \n\n";
2166: $tour ||= 0;
2167: my (@files) = &PrintArchive($dbh, $tour);
2168: WriteFile($dbh,$_) foreach @files;
2169: open F, "$ZIP -j - @files |";
2170: binmode(F);
2171: binmode(STDOUT);
2172: print join "",<F>;
2173: close F;
2174: $dbh->disconnect;
2175: exit;
2176: } elsif (param('sqldump')) {
2177: print header(
2178: -'Content-Type' => 'application/x-zip-compressed; name="dump.zip"',
2179: -'Content-Disposition' => 'attachment; filename="dump.zip"'
2180: );
2181: open F, "$ZIP -j - $DUMPFILE |";
2182: print (<F>);
2183: close F;
2184: $dbh->disconnect;
2185: exit;
2186:
2187: }
2188: elsif (!$opt_z && !param("makehtml")) {
2189: my $QuestionNumber=0;
2190: my $qnum;
2191: if ($qnum=param('qnumber')){
2192: my ($sth) = $dbh->prepare("SELECT QuestionId FROM Questions
2193: WHERE ParentId=$tour AND Number=$qnum");
2194: $sth->execute;
2195: $QuestionNumber=($sth->fetchrow)[0]||0;
2196: }
2197: if ($QuestionNumber) {
2198: $globaloutput.= &PrintQuestion($dbh, $QuestionNumber, $withanswers||0, $qnum, 1,0,0);
2199: # $dbh, $Id, $answer, $qnum, $title, $text
2200: } else {
2201: $globaloutput.=&PrintTournament($dbh, $tour, $withanswers);
2202: }
2203: }
2204: else {
2205: $opt_z=1;
2206: $url="http://db.chgk.info/cgi-bin/db.cgi";
2207: open TS, $timestamp;
2208: my $d=$dbh->quote(<TS>);
2209: close TS;
2210: open FF, ">${realHTMLDIR}index.html" or die "ERROR! - ${HTMLDIR}index.html\n";
2211: my $o=$globaloutput;
2212: $o.=&PrintTournament($dbh, 0, 0);
2213: $o.=&Bottom;
2214: print FF $o;
2215: close FF;
2216: open FF, ">${realHTMLDIR}all.html" or die "ERROR! - ${HTMLDIR}all.html\n";
2217: $o=$globaloutput;
2218: $o.=&PrintAll($dbh,0);
2219: $o.=&Bottom;
2220: print FF $o;
2221: close FF;
2222:
2223:
2224: # my ($sth) = $dbh->prepare("SELECT t1.Id, t1.FileName, t1.Type,
2225: # count(t2.Id)
2226: # FROM Tournaments as t1, Tournaments as t2
2227: # WHERE t1.CreatedAt>$d AND t2.ParentId=t1.Id GROUP BY t1.Id");
2228: my ($sth) = $dbh->prepare("SELECT t1.Id, t1.FileName, t1.Type, count(t2.Id) FROM Tournaments as t1 LEFT JOIN Tournaments as t2
2229: ON t2.ParentId=t1.id WHERE t1.CreatedAt>=$d GROUP BY t1.Id");
2230: $sth->execute;
2231: my ($Id,$fname,$type,$c);
2232: while (($Id,$fname,$type,$c)=$sth->fetchrow,$Id) {
2233: next unless $fname;
2234: print "$fname\n";
2235: $fname=~s/\.txt$//;
2236: if ($type=~/Т/ || $c<=1)
2237: {
2238: open FF, ">$realHTMLDIR$fname-q.html" or die "ERROR! - $fname-q.html\n";
2239: my $o=$globaloutput;
2240: $paramtour=$fname;
2241: $o.=&PrintTournament($dbh, $Id, 0);
2242: $o.=&Bottom;
2243: print FF $o;
2244: close FF;
2245: open FF, ">$realHTMLDIR$fname-a.html";
2246: $o=$globaloutput;
2247: $o.=&PrintTournament($dbh, $Id, 1);
2248: $o.=&Bottom;
2249: print FF $o;
2250: close FF;
2251: }
2252: else {
2253: open FF, ">$realHTMLDIR$fname.html" or die "ERROR! - $fname-q.html\n";
2254: my $o=$globaloutput;
2255: $o.=&PrintTournament($dbh, $Id, 0);
2256: $o.=&Bottom;
2257: print FF $o;
2258: close FF;
2259:
2260: }
2261: }
2262: }
2263: if (!$text) {
2264: $globaloutput.=&Bottom;
2265: }
2266: if (!$opt_z){
2267: print $globaloutput;
2268: if (($qs!~ /(rand)|(sstr)|(comp)/i) && (length $qs<=255) && $usehash) {
2269: $globaloutput= $dbh->quote($globaloutput);
2270: $dbh->do("insert into hash (query,page) values (".
2271: $dbh->quote($qs).
2272: ",$globaloutput)");
2273: }
2274: }
2275:
2276: $dbh->disconnect;
2277: }
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>