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