package SearchEngine;
# $Id: SearchEngine.pm,v 1.8 2000/08/30 21:40:08 tom Exp $
################################################################

use strict;
use vars qw(@ISA
	    $SearchEngines);

@ISA = qw(ObjectTemplate);

use ObjectTemplate;
use CGI::QueryString;
use CGI::Tools;
use Template;

attributes qw(content match_name);

$SearchEngines = {
    'yahoo' => {url=>'http://(ink|search)\.yahoo\.co\.jp/',
		'search_url'=>'http://search.yahoo.co.jp',
		key=>'p'},
    'goo' => {url=>'http://www\.goo\.ne\.jp/',
	      'search_url'=>'http://www.goo.ne.jp/?MT=%keyword',
	      key=>'MT'},
    'infoweb' =>  {url=>'http://para2\.cab\.infoweb\.ne\.jp/',
		   'search_url'=>'http://para2.cab.infoweb.ne.jp/?QueryString=%keyword',
		   key=>'QueryString'},
    'excite' =>  {url=>'http://www\.excite\.co\.jp/',
		  'search_url'=>'http://www.excite.co.jp/?s=%keyword',
		  key=>['s', 'param']},
    'msn' =>  {url=>'http://search\.msn\.com/',
	       'search_url'=>'http://search.msn.com/?MT=%keyword',
	       key=>'MT'},
    'lycos' =>  {url=>'http://www\.lycos\.co\.jp/',
		 'search_url'=>'http://www.lycos.co.jp/cgi-bin/pursuit?cat=jp&query=%keyword',
		 key=>'query'},
    'infoseek' =>  {url=>'http://www\.infoseek\.co\.jp/Titles',
		    'search_url'=>'http://www.infoseek.co.jp/Titles?qt=%keyword',
		    key=>'qt'},
    'fresheye' =>  {url => 'http://search\.fresheye\.com/',
		    'search_url'=>'http://search.freshey.com/?kw=%keyword',
		    key => 'kw' },
};
################################################################
sub GetKeyword($$$)
{
    my ($self, $uri, $query) = @_;

    # backup old query
    my $old_query = query_string();
    $query =~ s/^\?//;
    query_string($query);
#    print query_string();

#    print "$uri, $query<br>";
    my $keyword;
    my @keywords;
    my ($name, $assoc);
    
    while (($name, $assoc) = each (%$SearchEngines)){
	my $se_url = $assoc->{url};
#	print "se: $name, $se_url, ";
	if ($uri =~ /^$se_url/){
	    $self->match_name($name);
#	    print "key: ", param($assoc->{key});
	    my $key = $assoc->{key};
	    if (ref $key eq 'ARRAY'){
		for (@$key){
		    if (param($_)){
			$keyword = param($_);
			last;
		    }
		}
	    } else {
		$keyword = param($key);
	    }
	}
    }
    # restore querystring
    query_string($old_query);
    
    if ($keyword){
	$keyword =~ tr/\(\)\|/   /;
	$keyword =~ s/\sand\s/ /gi;
	$keyword =~ s/\sor\s/ /gi;
	$keyword =~ s/\snot\s/ /gi;
	$keyword =~ s/\+/ /g;
	@keywords = split(/ /, $keyword);
    }
    return @keywords;
}

################################################################
# static functions
sub CreateLink ($$$)
{
    my ($name, $keyword, $label) = @_;

    return undef unless $SearchEngines->{$name};
    
    my $search_url_template = $SearchEngines->{$name}->{'search_url'};
    return sprintf(qq(<a href="%s">$label</a>),
		   Expand($search_url_template,
			  {keyword=>UrlEncode(Escape($keyword))}));
}
1;
