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