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