#!/usr/bin/perl
##################################################
# CGI TeXnik main file
# (C) 2005 Herbert Voss
##################################################

#use strict;
#use CGI qw/:standard/;
use CGI qw/:standard :html2/;
use CGI::Carp qw/fatalsToBrowser/;

my $dummy="";
my $datei="main";
my $cgibin="/cgi-bin";
my $dir="";
my $sidebar=1;
my $Idx=1;
my $subDir = '../';
my $cgi = '.cgi';
my $Path = "";
my $mainTitle="";
my @mainIdx=();
#
my %countData=();
my $filePrefix = "";
my %result = ();
#
my $hostname = `/bin/hostname`;
chomp ($hostname);
if ($hostname eq 'shania') { 
  $Path = "/srv/www/htdocs/TeXnik";
  $countDatei = "$Path/hits/CountData.dat"; 
  $searchFile = "$Path/hits/SearchFiles.dat";
  $filePrefix = "../htdocs/TeXnik"; 				# localhost
} elsif ( $hostname eq 'tug.org'){
  $Path = "/home/httpd/html/TeXnik";
  $countDatei = "$Path/hits/CountData.dat";
  $searchFile = "$Path/hits/SearchFiles.dat";
  $cgibin = "/TeXnik";
#  $fileLeft = "left.tug.org"; 	 				# tug.org
  $filePrefix = ".";  						# tug.org
} elsif ( $hostname eq 'comedy'){
  $Path = "/serv/www/texnik/TeXnik";
  $countDatei = "$Path/hits/CountData.dat";
  $searchFile = "$Path/hits/SearchFiles.dat";
  $cgibin = "/cgi-bin";
  $fileLeft = "left.comedy"; 	 				# tug.org
  $filePrefix = "$Path";  						# tug.org
} else {
  $hostname = "FU";
  $countDatei = "/home/l/latex/public_html/TeXnik/hits/CountData.dat";
  $searchFile = "/home/httpd/html/TeXnik/hits/SearchFiles.dat";
  $filePrefix = "../TeXnik";  				# userpage.fu-berlin.de/~latex
}
#my $countDatei = "/tmp/CountData.dat";
#
my $file = "";
my $cnt = 0;
#
if (param('reset') > 0) {
  open (COUNTData, "+< $countDatei");
  my @input = <COUNTData>;
  foreach ( @input ) {
    chomp($_);
    ($file,$cnt) = split(" ",$_);
    print COUNTData "$file 0\n";
  }
  close(COUNTData);
  param('file') => "main";
}
#
open (COUNTData, "< $countDatei");
my @input = <COUNTData>;
close(COUNTData);
foreach ( @input ) {
  chomp($_);
  ($file,$cnt) = split(" ",$_);
  $countData{ $file } = $cnt;
}
#
#
#Load Directory Into Array
#---------------------------------------------------------------------------------------
sub GetDirArray {
  if (index($dir,"..") < 0) { 			# do not allow ../ in dir names
  if (opendir(DIRHANDLE, "$filePrefix/$dir")) {
    my @files = readdir(DIRHANDLE);
    closedir(DIRHANDLE);
    $mainTitle = "file list of directory /$dir</h4>";
#      push ( @mainText, "<table>\n" );
    foreach ( sort @files ) {
      if (($_ ne "CVS") and ($_ ne ".htaccess") and ($_ ne ".") and ($_ ne "..")) {
        push ( @mainText, "<a href=\"/TeXnik/$dir/$_\">$_</a><br />\n" );
      }
    } 
  } else { push (@mainText, "cannot open directory $filePrefix/$dir: $!"); }
}}
#---------------------------------------------------------------------------------------
#
#---------------------------------------------------------------------------------------
sub hitsSort { return $result{$b} <=> $result{$a}; }
#---------------------------------------------------------------------------------------
#
#---------------------------------------------------------------------------------------
sub search {
  my($searchItem) = @_;
  $searchItem =~ s/(\+|\*|\?)/\\$1/g;
  my @HTML = ();
  my $file = "";
  my @fileList=();
  my $cnt = 0;
  open (COUNTData, "< $searchFile");
    my @input = <COUNTData>;
  close(COUNTData);
  foreach ( @input ) {
    chomp($_);
    ($file,$cnt) = split(" ",$_);
    push (@fileList, $file);
  }
  foreach ( @fileList ) {
    $file = $_;
    open(FILE,"<$filePrefix/$file");
    my @contents = <FILE>;
    my $line = join (" ", @contents);
    my $cnt = 0;
    while ($line =~ /$searchItem/gi) { $cnt++; }
    if ($cnt > 0) { $result{ $file } = $cnt; } 
    close (FILE);
  }
#
  my $time = `/bin/date`;
  push(@HTML, "<h4>Your search result for \"<font color=\"red\">$searchItem</font>\", built at $time</h4>\n");
  push(@HTML, "<hr />\n");
  push(@HTML, "<table bgcolor=\"#FFFFFF\">\n");
  push(@HTML, "<tr><th>No</th>");
  push(@HTML, "<th align=\"left\">Filename</th>");
  push(@HTML, "<th align=\"right\">Hits</th>");
  push(@HTML, "</tr>\n");
#
  my $c = 0;
  my $bgcolor = "";
#
  foreach $url (sort hitsSort keys %result) {
    $c++;
    if ($c % 2) { $bgcolor = "#C2C2A2"; }
    else        { $bgcolor = "#C2C2F2"; }
    push(@HTML, "<tr><td bgcolor=\"$bgcolor\" align=\"center\">$c</td>\n");
    if (grep(/http:/,$url) > 0) { push(@HTML, "<td bgcolor=\"$bgcolor\"><a href=\"$url\">"); }
    else { push(@HTML, "<td bgcolor=\"$bgcolor\"><a href=\"$cgibin/mainFAQ.cgi?file=$url\">"); }
    push(@HTML, "$url");
    push(@HTML, "</a></td>\n");
    push(@HTML, "<td align=right bgcolor=\"$bgcolor\">$result{$url}","</td></tr>\n");
  }
  push(@HTML, "</table>\n");
  push(@HTML, "<hr />\n");
  return @HTML;
}
#---------------------------------------------------------------------------------------

if (param('search')) {
  @mainText = search(param('search'));
} else {
  if (param('file')) { 
    $datei=param('file'); 
    my $cnt = 0;
    while ($datei =~ /$subDir/g) { $cnt++; }
    while ($datei =~ /$cgi/g) { $cnt+=3; }
    if (index($datei,"..")==0) { $cnt+=3; } # do not allow ../ in dir names
    if ((substr($datei,0,1) eq "/") or ($cnt > 2)) { $datei = "main";} 
    $sidebar=0; 
    $dir = "";
  } elsif (param('dir')) { 
    $dir = param('dir'); 
    my $cnt = 0;
    while ($dir =~ /$subDir/g) { $cnt++; }
      if ((substr($dir,0,1) eq "/") or ($cnt > 1)) { $dir = "";} 
    $datei = $dir; 
  }
#
  if ( exists( $countData { $datei } )) { $countData{ $datei } = $countData{ $datei } + 1; }
  else { $countData{ $datei } = 1; }
  open (COUNTData,"> $countDatei"); # save entries
  while ( ($file,$cnt) = each ( %countData )) { print COUNTData "$file $cnt\n"; }
  close(COUNTData);
#
  if ($dir ne "") {
    GetDirArray();
  } else {
    $file = "$filePrefix/$datei";
    open (MAIN,"<$filePrefix/$datei");
    if (param('verb') > 0) {
      push ( @mainText, "<pre>\n");
      while (<MAIN>) { 
        $_ =~ s/\&/\&amp;/;
        $_ =~ s/</\&lt;/;
        chomp ($_); 
        push ( @mainText, "$_"); 
      }
      push ( @mainText, "</pre>\n");
      $Idx = 0;
    } else {
      $line = <MAIN>;
      chomp ($line);
      if (index($line,"<subtitle>") > -1) {
        $line =~ s/<subtitle>//;
        $line =~ s/<\/subtitle>//;
        $mainTitle = $line;
        $line = <MAIN>;
        chomp ($line);
      }
      if ( $line eq "<Index>" ) { 
        $line = <MAIN>;
        chomp($line);
        while ( $line ne "</Index>" ) {
          push( @mainIdx, $line ); 
          $line = <MAIN>;
          chomp ($line);
        }
      } else {
        push ( @mainText, "$line" ); 
        $Idx = 0; 
      }
      while ($line = <MAIN>) {
        chomp ($line);
        push ( @mainText, $line ); 
      }
    }
    close (MAIN);
  }#
}
#---------------------------------------------------------------------------------------
sub insertIdx {
  if ( $Idx > 0) { 
    foreach ( @mainIdx ) { 
      $line = $_;
      if (substr($line,0,1) eq "<") { 				# html tag
        print "$line\n"; 
      } elsif (substr($line,0,1) eq "%") { 			# Kommentar
        print substr($line,1),"\n"; 
      } elsif (substr($line,0,1) eq "?") { 			# dir
        ($url,$text) = split(/<>/,$line); 
        print "<a href='mainFAQ.cgi$url'>",$text,"</a>&nbsp;|&nbsp; \n";      
      } elsif ((substr($line,0,1) eq "#") or (substr($line,0,7) eq "http://")) { 
        ($url,$text) = split(/<>/,$line); 			# Link als # oder extern
        print "<a href='$url'>",$text,"</a>&nbsp;|&nbsp; \n";
      } elsif ($line eq "") {					# Leere Zeile
        print "<br />\n";
      } else {							# "normaler" relativer Link
        ($url,$text) = split(/<>/,$line); 
        print "<a href='mainFAQ.cgi?file=$url'>",$text,"</a>&nbsp;|&nbsp; \n";      
      }
    }
    print"<br />\n";
  }
  return "";
}
#---------------------------------------------------------------------------------------

#print "Content-type: text/html\n\n";
print header("text/html"),start_html({-title=>"/TeXnik/$datei"});

print "<html><head><title>TeXnik - Graphics for TeX and LaTeX</title></head>\n";
print "<body bgcolor=\"#ffffff\" text=\"#000000\" link=\"#0000CC\" vlink=\"#800080\" alink=\"#ff0000\" topmargin=\"2\">\n";
#print header("text/xml"), start_html(-title=>'TeXnik - Graphics for TeX and LaTeX');
print "<meta http-equiv='Content-Type' Content='text/xml; charset=iso-8859-1'></meta>\n";
print "<meta name='keywords' content='TUG DANTE typesetting typography TeX LaTeX graphics CTAN PostScript'></meta>\n";
print "<link rel=\"stylesheet\" href=\"/tugstyle.css\">\n";
#foreach (@mainIdx) {print "$_<br />\n";}
print "<table bgcolor='#E5E5E5' width='100%'>\n";
print "<tr>";
print "<td valign=\"middle\" align=\"center\">",
#    "<font size=\"-2\">(courtesy of <a href=\"http://www.google.com/\">Google</a>)</font>",
    "<br />",
    "<form method=\"post\" action=\"$cgibin/mainFAQ.cgi\">\n",
#    "<input type=\"hidden\" name=\"search\" value=\"\"></input>",
    "<input name=\"search\" size=\"13\" maxlength=\"99\"></input>",br,
    "<input type=\"submit\" name=\"search\" value=\"Search\"></input>",
    "</form></td>",
    "<td valign=\"middle\" align=\"center\" width=\"100%\"><font size=\"+2\">",
    "<b>Welcome to the TeXnik web site</b></font><br /><br />",
    "<b>$mainTitle</b></td>\n",
#    "<b>Welcome to the TeXnik web site</b></font></td>\n",
    "<td valign=\"middle\" align=\"center\"><a href='http://tug.org'>",
	    "<img border=\"0\" src=\"/TeXnik/images/logonavyongrey.jpg\" width=\"80\" alt=\"TUG logo\"></img></a></td>";
print "</tr>";
print "<tr>\n";
print "<td valign=\"top\" width=\"10%\">";
open (LEFT, "< $filePrefix/left.$hostname") or die print "Cannot open left:  $filePrefix/left.$hostname";
my @left = <LEFT>;
close(LEFT);
foreach ( @left ) { 
  if ($hostname eq "FU") { 
    $_ =~ s(/TeXnik/)($subdir/TeXnik/); 
    $_ =~ s/cgi-bin/~latex\/cgi-bin/; 
  } 
  print $_; 
}
print "</td>\n";
if ( $sidebar > 0) {
    print "<td bgcolor=\"#FFFFFF\" valign=\"top\">\n";
    print insertIdx();
#    print "<p></p>\n";
    foreach (@mainText) { 
      if ($hostname eq "FU") { 
        $_ =~ s(/TeXnik/)($subdir/TeXnik/); 
        $_ =~ s/cgi-bin/~latex\/cgi-bin/; 
      } 
      if ($hostname eq "shania") { $_ =~ s(/TeXnik/main)($cgibin/main); } 
      print "$_\n"; 
    }
    print "</td>\n";
    print "<td valign='top'>\n";
    open (RIGHT, "< $filePrefix/right") or die print "Cannot open right:  $filePrefix/right";
    my @right = <RIGHT>;
    close(RIGHT);
    foreach ( @right ) { print $_; }
    print "</td>\n";
} else {
    print "<td bgcolor='#FFFFFF' colspan='2'  valign=\"top\" >";
    print insertIdx();
    print "<p></p>";
    if ($Idx > 0) { print "<hr />"; }
    foreach (@mainText) { 
      if ($hostname eq "FU") { 
        $_ =~ s(/TeXnik/)($subdir/TeXnik/); 
        $_ =~ s/cgi-bin/~latex\/cgi-bin/; 
      } 
      if ($hostname eq "shania") { $_ =~ s(/TeXnik/main)($cgibin/main); } 
      print "$_\n"; 
    }
    print "</td>\n";
}
print "</tr></table>\n";

#//<!-- footer -->

my $time = `/bin/date`;
if (!$datei) { $datei="mainFAQ.cgi"; } else { $datei = "$Path/$datei"; }
print "<p></p>\n",
    "<center><small>local time: $time; file is: ",
    -C "$datei",
    " days old",
    "<br />",
#    "<a href=\"mailto:webmaster\@TeXnik.de\">contact webmaster at TeXnik.de</a>\n",
    "contact webmaster _at_ TeXnik.de\n",
    "</small>",
    "</center>";
print "</body></html>\n";
print end_html();