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