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