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