#!/usr/local/bin/perl
#
# $Id: show-dict,v 1.10 1999/02/20 23:16:25 msh Exp $
#
# Show dictionary article
#
# (C) 1998 Mike Shoyher <msh@corbina.net>

# Configuration

do './dict-conf';
die "No config file!" unless ($dbfile);

my ($param, $key, $val, %d, %w);

my $maxinstat=5000;

sub LOCK_SH { 1 }
sub LOCK_EX { 2 }
sub LOCK_NB { 4 }
sub LOCK_UN { 8 }

use CGI;
$Q1=new CGI;
$param=$Q1->param('_query');
use Fcntl;
use DB_File;
use strict;
use vars qw ($debug $dbfile $adminadr $statfile $showurl) ;

#Parsing parameters (CGI GET or commandline)
#$param=lc($ARGV[0]);
#if ($param && ($param!~/_/o)){
#        $param=~s/%([A-Fa-f0-9]{2})/pack("c",hex($1))/ge;
#} else {
#        for (split(/[&;]/,$ENV{'QUERY_STRING'})){
#                s/\+/ /g;
#                ($key, $val) = split(/=/,$_,2);
#                # Convert %XX from hex numbers to alphanumeric
#                $key =~ s/%([A-Fa-f0-9]{2})/pack("c",hex($1))/ge;
#                $val =~ s/%([A-Fa-f0-9]{2})/pack("c",hex($1))/ge;
#                $param=$val if ($key eq '_query');
#        }
#}

#$param=~s/\\&/&/og; # Dequote &






print "Content-type: text/html\n\n";
print '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<HTML>
<HEAD>
	<TITLE>Англо-русский компьютерный словарь</TITLE>
	<style type="text/css">
<!--
 A:link {text-decoration: none;}
 A:visited {text-decoration: none;}
 A:active {text-decoration: none;}
 A:hover {text-decoration: none;}
 p {font: 10pt Arial}
 h1 {font: 12pt Arial;}
-->
</style>
</HEAD>';


print '<BODY leftmargin=0 topmargin=0 text="Black" link="Blue" vlink="Navy" alink="Aqua" bgcolor="White">
 <center>
  <table width="750" border="0" cellspacing="0" cellpadding="0">
   <tr>
    <td width="198" height="61"><img src="../images/2page/1.jpg" width=198 height=61 hspace=0 vspace=0 border=0></td>
	<td width="552" height="61" colspan="2"><img src="../images/2page/zag_4.jpg" width=552 height=61 hspace=0 vspace=0 border=0></td>
   </tr>
   <tr>
    <td width="198" height="20"><IMG SRC="../images/2page/m1.gif" USEMAP="#m1" BORDER=0 WIDTH=198 HEIGHT=20 hspace=0 vspace=0></td>
	<td width="96" height="20"><a href="../feedback/0.htm"><img src="../images/2page/m2.gif" width=96 height=20 hspace=0 vspace=0 border=0 alt="Контакты"></a></td>
	<td width="456" height="20"><IMG SRC="../images/2page/m3.gif" BORDER=0 WIDTH=456 HEIGHT=20 hspace=0 vspace=0></td>
   </tr>
   <tr><td colspan="3">
   <!-- Начало основного текста --><br>
   <table width="750" border="0" cellspacing="0" cellpadding="0">
   <tr><td><font size="2">7600 статей, (С) Эдуард Пройдаков, Леонид Теплицкий, 1999 г</font></td></tr>
   <tr><td><br>
	 <table border="0" cellspacing="0" cellpadding="0" bgcolor="#003D79"><tr><td>
      <table border="0" cellspacing="1" cellpadding="5" bgcolor="White">
       <tr><td bgcolor="#9EC8D8"><p align="CENTER">Наиболее популярные термины</td>';
         tie(%w, 'DB_File', "$dbfile-w", O_RDONLY,0644) || die "Cannot open database";
	 showTop();
print	  '</table></td></tr>
	 </table><br>
   </td></tr>
    <tr>
     <td valign="TOP">
      <FORM ACTION="http://www.computer-museum.ru/dict/show-dict.pl" METHOD=GET>
      <b><font size="3">Введите слово</font></b><br>
      <INPUT TYPE=text size=45 NAME="_query" VALUE="';
print $param;
print '">
      <INPUT TYPE=submit NAME="_submit" value="Search">
      </form>
         <hr><p>';
       if ((length($param)>0) && ($param !~ /^_/o)){
        tie(%d, 'DB_File', "$dbfile-d", O_RDONLY,0644) || die "Cannot open database";
        if ($d{lc($param)}) {
                showWord($param);
                saveStat($param);
        } else {
                missedWord($param);
        }
        untie(%d);
        untie(%w);
        print '<hr>';
        }

print '	 </td>
	</tr>
    <tr><td>&nbsp;</td></tr>
   </table>
   <!-- Конец основного текста -->
   </td></tr>
   <tr><td colspan="3"><p>С авторами можно свяаться по адресу <a href="mailto:chief@pcweek.ru">chief@pcweek.ru</a>&nbsp;</td></tr>

  </table>
 </center>
<MAP NAME="m1">
<AREA SHAPE=RECT COORDS="2,2,130,19" HREF="../index.htm" ALT="На первую страницу">
</MAP>
</BODY>
</HTML>';

# Shows one word. Here must go all design

sub showWord()
{
my $key=lc(shift());
print "<h1>";
print '<p>Искомое слово: "<u><b>';
print $w{$key};
print '</b></u>"</p>'."<br>\n";
print "</h1>\n";
print $d{$key},"\n";
}

# No such word in the dict

sub missedWord
{
my (%m,$db);
my $key=lc(shift());
print '<p>Искомое слово: "<u>'.$key.'</u>"';
print "&nbsp;<b>не найдено</b><br>\n";
open(FLAG,">>$statfile-mis-flag"); # Safe writing,  FLAG - mutex
if (doLock()){
        tie(%m, 'DB_File', "$statfile-mis", O_RDWR|O_CREAT, 0666) || die "Cannot open statistics database";
        $m{$key}++;
        untie(%m);
}
doUnLock();
close(FLAG);
showNear($key);
}

sub showNear
{
my (@words,$l,$r,$m,$word,$i,$origword,$key);
$origword=shift;
$key=lc($origword);
print "<hr><p>Похожие слова<p>\n";
$#words=0;
open(IN,"$dbfile-list");
for $word (<IN>){
        chomp($word);
        push(@words,$word);
}
close(IN);
# bsearch, nothing more.
$l=0;$r=$#words;
while ($r-$l > 1) {
        $m=int(($r-$l)/2) + $l;
        if ($key lt $words[$m]){
                $r=$m;
        } else {
                $l=$m;
        }
}
for ($i=($m>0?$m-5:0);($i<$m+5)&&($i<$#words);$i++){
#       print "<a href=\"$showurl?",escape($words[$i]),"\">",$w{$words[$i]};
#       print "<a href=\"$showurl?",escape($words[$i]),"\">",$words[$i];
        print "<a href=\"$showurl?_query=",escape($words[$i]),"\">",$words[$i];
        print "</a>&nbsp;\n";
}
print "<br><hr><br>\n";
print "<p>Вы можете добавить письмо в словарь <a href=\"mailto:$adminadr?subject=";
print "Определение%20слова%20",escape($origword),"\">";
print "написав письмо составителю</a>.\n";

}

sub saveStat($)
{
my $word=lc(shift);
my (%s,@list,$i);
open(FLAG,">>$statfile-hit-flag"); # Safe writing,  FLAG - mutex
if (doLock()){
        tie(%s, 'DB_File', "$statfile-hit", O_RDWR|O_CREAT, 0666) || die "Cannot open statistics database";
        $s{$word}++;
        @list = sort {$s{$b} <=> $s{$a}} keys(%s);
        delete($s{$list[$#list]}) if $#list > $maxinstat; #Remove last word in top
        open(LIST,">$statfile-list");
        for($i=0;$i<10;$i++){
                print LIST $list[$i],"\n";
        }
        close(LIST);
        untie(%s);
}
doUnLock();
close(FLAG);
}

sub escape {
    my($toencode) = @_;
    $toencode=~s/([^a-zA-Z0-9_\-.])/uc sprintf("%%%02x",ord($1))/eg;
    return $toencode;
}

sub doLock
{
my($i);
for($i=0;$i<10;$i++){
        return 1 if flock(FLAG,LOCK_EX | LOCK_NB);
}
}

sub doUnLock
{
flock(FLAG, LOCK_UN);
}

sub showTop
{
open(LIST,"$statfile-list");
for (<LIST>){
        chomp;
        print '<td><p align="CENTER">';
        print "<A HREF=\"$showurl?_query=",escape($_),"\">";
        print $w{$_};
        print "</A>";
        print "</td>\n";
}
close(LIST);

}
