#!/usr/bin/perl

############################################################
#                                                          #
# Virtual Visions :: "Fetch" Search Engine                 #
# Script coded by Barracuda                                #
# Email - baracuda@feartech.com                            #
#                                                          #
############################################################

# this is the url of your site

$base_url = 'http://www.elektro.it';

# this is the path equivalent of $base_url

$base_dir = '/home/sites/www.elektro.it/web';

# this is the url of fetch.pl

$search_url = 'http://www.elektro.it/cgi-bin/fetchfaq/fetch.pl';


# this is the path to header.shtml
$header = '/home/sites/www.elektro.it/web/cgi-bin/fetchfaq/header.shtml';

# this is the path to footer.shtml
$footer = '/home/sites/www.elektro.it/web/cgi-bin/fetchfaq/footer.shtml';

# the background color of fetch... behind the keyword field

$bg = 'bgcolor=#66CDAA';

# the directories you want to search in, note the trailing "/"
# you cannot search only '' as a directory and expect it to
# search all of your directories if you have $subdirs set to
# yes... you must specify directories

@dirs = ('faq/');

# allow fetch to search in subdirectories of the above
# directories?

$subdirs = "yes";

# what types of files do you want to search in? note that
# htm works for htm, html, phtml, shtml, etc...

@searchtypes = ('html','htm');

############################################################

use CGI qw(:standard);
$search = new CGI;

$result_num = $search->param('result_num');
$show_search = $search->param('show_search');
$show_summary = $search->param('show_summary');
$keyword = $search->param('keyword');
$page = $search->param('page');
$connector = $search->param('connector');
$case = $search->param('case');

&get_header_footer;
&display_page unless $show_search eq "no";

############################################################

@keywords = split(/\s+/,$keyword);

foreach $type (@dirs)
{
	chomp($type);

	$dir = "$base_dir/$type";

	chdir($dir);
	opendir (DIR, $dir) || &cgiError ("Opening $dir Failed:", "$!");
	@allfiles = readdir(DIR);
	$totalnum=@allfiles;
	closedir (DIR);

	for($i=1; $i<$totalnum; $i++)
	{
		if (-d $allfiles[$i])
		{
			if ($allfiles[$i] ne "." && $allfiles[$i] ne ".." && $type ne "" && $subdirs eq "yes")
			{
				push(@dirs,"$type$allfiles[$i]/");
			}
		}

		if (-f $allfiles[$i])
		{
			($file,$ext) = split(/\./, $allfiles[$i]);

			foreach $searchtype (@searchtypes)
			{
				if ($ext =~ /$searchtype/i)
				{
					open (SEARCH,"$allfiles[$i]") || &cgiError ("Open $allfiles[$i] Failed:", "$!");
					@search = <SEARCH>;
					close(SEARCH);

					$temp_file = "$type$allfiles[$i]";
					
					foreach $text (@search)
					{
						chomp($text);
						
						$text =~ s/<([^>]|\n)*>//g;
						$text =~ s/&([^;])*;//g;
						$text =~ s/<!--([^-->])*-->//g;

						if ($connector eq "or" && $case eq "insensitive")
						{
							foreach $word (@keywords)
							{
								if (!($text =~ /$word/i)) { $match = 0; } 
								else { $matches{$temp_file} = $text; last; }
							}
						}

						if ($connector eq "and" && $case eq "insensitive")
						{
							if (!($text =~ /$keyword/i)) { $match = 0; } 
							else { $matches{$temp_file} = $text; last; }
						}

						if ($connector eq "or" && $case eq "sensitive")
						{
							foreach $word (@keywords)
							{
								if (!($text =~ /$word/)) { $match = 0; } 
								else { $matches{$temp_file} = $text; last; }
							}
						}

						if ($connector eq "and" && $case eq "sensitive")
						{
							if (!($text =~ /$keyword/)) { $match = 0; } 
							else { $matches{$temp_file} = $text; last; }
						}
					}
				}
			}
		}
	}
}

foreach $key (sort(keys %matches))
{
	push(@matches,$key);
	push(@summary,$matches{$key});
}

&print_header;

print "<br><p align=\"center\"><b><font size=\"+1\">ELEKTRO.IT - RICERCA DI LEGGI PER IL SETTORE ELETTRICO &nbsp;</font></b></p><br>\n\n";
print "<table width=\"100%\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\"><tr valign=\"top\"><td width=\"50%\"><font size=\"+1\"><blockquote><b>Risultati della ricerca</b></blockquote></font><br><br></td>\n";
print "<td width=\"50%\"><p align=\"right\">\n";

$total = @matches;
$real_total = $total;
$totalnum = int(($total + $result_num)/ $result_num);

if ($page )
{
	($liststart,$listend) = split(/ /,$page);
}

else
{ 
	if ($total < $result_num) { $liststart = 0; $listend = $total; }
	else { $liststart = 0; $listend = $result_num; }
}
	
if ($total > $result_num)
{
	print "<form action=\"$search_url\" method=\"POST\"><select name=\"page\">";

	for($i=0; $i<$totalnum; $i++)
	{
		$num = ($i * $result_num);
		$end = ($num + $result_num);
		
		if ($matches[$num] )
		{
			if ($total<$end) { $end = $total; }
		
			$real_num = $num;
			eval { $num = ($num + 1); };
			print " <option value=\"$real_num $end\">Mostra risultati $num - $end</option>\n";
			eval { $num = ($num - 1); };
		}
	}
	
	print "</select><input type=\"hidden\" name=\"show_search\" value=\"no\">";
	print "<input type=\"hidden\" name=\"show_summary\" value=\"$show_summary\">";
	print "<input type=\"hidden\" name=\"result_num\" value=\"$result_num\">";
	print "<input type=\"hidden\" name=\"case\" value=\"$case\">";
	print "<input type=\"hidden\" name=\"connector\" value=\"$connector\">";
	print "<input type=\"hidden\" name=\"keyword\" value=\"$keyword\"> <input type=submit value=\"VAI!\"></form></p>\n";
}

$first = ($liststart + 1);
$last = $listend;
if ($listend<=$result_num && $end<=$result_num) { $last = $total; }

print "</td></tr></table>\n";
print "<blockquote>\n";
print "Qui sono elencati i risultati della ricerca per: <b>$keyword</b><br>Documenti da $first  a  $last di $real_total trovati.<br><br>\n";
print "</blockquote>\n";
print "<blockquote>\n";

if ($total eq "0")
{
	print "<b>Spiacente, Nessun risultato trovato!</b><br>\nNon è stato trovato nulla che corrisponda al criterio di ricerca effettuato.<br>Prova ancora con una differente combinazione di parole chiave.\n";
}

else
{
	if ($liststart eq "$listend")
	{
		$liststart = ($liststart - 1);
	}

	for($liststart; $liststart<$listend; $liststart++)
	{
		if ($matches[$liststart])
		{
			$match = $matches[$liststart];
			$summary = $summary[$liststart];

			if ($summary eq "")
			{
				$summary = "No summary available.";
			}

			print "<b><a href=\"$base_url/$match\">$match</a></b><br>\n";
			print "<b>URL:</b> $base_url/$match<br>\n";
			
			if ($show_summary eq "yes")
			{
				print "<b>Sommario:</b> $summary<br>";
			}
			
			print "<br>\n\n";
		}
	}
}

print "</blockquote><br><blockquote>Non hai trovato quello che stavi cercando? Cerca ancora usando parole più specifiche.</blockquote><br>\n\n";
print "<ul><form action=\"$search_url\" method=\"POST\"><input type=\"hidden\" name=\"show_search\" value=\"no\"><b>Ricerca:</b> <input type=\"text\" size=\"36\" name=\"keyword\" MAXLENGTH=\"35\">\n";
print "<input type=\"hidden\" name=\"show_search\" value=\"no\">\n";
print "<input type=\"hidden\" name=\"result_num\" value=\"$result_num\">\n";
print "<input type=\"hidden\" name=\"case\" value=\"$case\">\n";
print "<input type=\"hidden\" name=\"connector\" value=\"$connector\">\n";
print "<input type=\"hidden\" name=\"show_summary\" value=\"$show_summary\">\n";
print "<input type=\"submit\" value=\"Cerca!\"></form></ul><br>\n";
print "<center><b><a href=\"$base_url/faq/faq_0.htm\">Sommario leggi</a> | <a href=\"$base_url/index.html\">Home page</a></b></center><br><br>\n";

&print_footer;

################
# sub routines #
################

sub display_page
{

&print_header;

print qq~
<br><p align="center"><b><font size="+1">ELEKTRO.IT - RICERCA DI TERMINI NELLE FAQ &nbsp;</font></b></p><br>
Note: in modalità di ricerca OR evitare di usare le congiunzioni (di,e,..). Per ricerche mirate si consiglia la modalità AND. Il tempo di ricerca è di alcuni secondi. <br><br>
<form action="$search_url" method="POST"><table width="100%" border="0" cellpadding="8" cellspacing="0"><tr valign="center"><td width="25%" $bg><tt><b>Ricerca:</b></tt></td><td width="75%" colspan="2" $bg><input type="text" size="36" name="keyword" MAXLENGTH=\"35\"> <input type="submit" value="Cerca!"></td></tr>
<tr><td><tt><b>&nbsp;Cerca<br>&nbsp;come:</b></tt></td><td><input type="radio" name="connector" value="or" >Parole chiave (OR) &nbsp;&nbsp;&nbsp;&nbsp;<input type="radio" name="connector" value="and" CHECKED>Frase (AND)</td></tr>
<tr><td><tt><b>&nbsp;Maiuscole:</b></tt></td><td><input type="radio" name="case" value="insensitive" CHECKED>Insensibile &nbsp;&nbsp;&nbsp;&nbsp;<input type="radio" name="case" value="sensitive">Sensibile</td></tr>
<tr><td><tt><b>&nbsp;Mostra<br>&nbsp;sommario ricerca:</b></tt></td><td><input type="radio" name="show_summary" value="yes" CHECKED>Si &nbsp;&nbsp;&nbsp;&nbsp;<input type="radio" name="show_summary" value="no">No</td></tr>
<tr><td><tt><b>&nbsp;Risultati<br>&nbsp;per Pagina:</b></tt></td><td><input type="radio" name="result_num" value="10">10 &nbsp;&nbsp;&nbsp;&nbsp;<input type="radio" name="result_num" value="20" CHECKED>20 &nbsp;&nbsp;&nbsp;&nbsp;<input type="radio" name="result_num" value="30">30 &nbsp;&nbsp;&nbsp;&nbsp;<input type="radio" name="result_num" value="40">40 &nbsp;&nbsp;&nbsp;&nbsp;<input type="radio" name="result_num" value="50">50</td></tr>
</table><input type="hidden" name="show_search" value="no"></form>
~;
print "<center><b><a href=\"$base_url/leggi/leggi_0.html\">Elenco domande</a> | <a href=\"$base_url/index.html\">Home page</a></b></center>\n";
&print_footer;

exit;
}

sub print_header
{
    print "Content-type: text/html\n\n";

	foreach $line (@dataa)
	{
		chomp($line);
		print "$line\n";
	}
}

sub print_footer
{
	foreach $line (@datab)
	{
		chomp($line);
		print "$line\n";
	}
}

sub get_header_footer
{
	open (FILEA,"$header") || &cgiError ("Reading Header Failed:", "$!");
	@dataa = <FILEA>;
	close(FILEA);

	open (FILEB,"$footer") || &cgiError ("Reading Footer Failed:", "$!");
	@datab = <FILEB>;
	close(FILEB);
}

sub cgiError
{
	my ($error_cause,$error) = @_;

	if ($error_cause eq "") { $error_cause = "Error:"; }
	if ($error eq "") { $error = "The script encountered problems and terminated"; }

	&print_header;
	print "<h3>$error_cause</h3>$error<br><br>";
	&print_footer;

exit;
}