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