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