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