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