#!/usr/bin/perl # smart.cgi - an interface to my spell server # Eric Lease Morgan # September 21, 2005 - Done, sort of # September 18, 2005 - First cut # define constants use constant HOME => 'etc/home.txt'; use constant FORM => 'etc/form.txt'; use constant RESULTS => 'etc/results.txt'; use constant SPELL2HTML => 'etc/spell2html.xsl'; use constant SPELLROOT => 'http://spell.ockham.org/?'; use constant TEMPLATE => 'etc/template.txt'; # require/use use CGI; use CGI::Carp qw(fatalsToBrowser); use strict; use LWP::UserAgent; use XML::LibXML; use XML::LibXSLT; # initialize my $cgi = CGI->new; my $html; # get the command my $cmd = $cgi->param('cmd'); # branch accordingly if (! $cmd) { # display the home page $html = &slurp(TEMPLATE); $html =~ s/##CONTENT##/&slurp(HOME)/e; $html =~ s/##FORM##/&slurp(FORM)/e; } elsif ($cmd eq 'search') { # get the input my $word = $cgi->param('word'); my $dictionary = $cgi->param('dictionary'); # begin to complete the search results page $html = &slurp(TEMPLATE); $html =~ s/##CONTENT##/&slurp(RESULTS)/e; # create a user agent, create a request, send it, and get a response my $ua = LWP::UserAgent->new(agent => 'SPELL-Client/0.1 '); my $request = HTTP::Request->new(GET => SPELLROOT . 'word=' . $word . '&dictionary=' . $dictionary); my $response = $ua->request($request); # check response if ($response->is_success) { # create parser and process input my $parser = XML::LibXML->new; my $xslt = XML::LibXSLT->new; my $source = $parser->parse_string($response->content) or croak $!; my $style = $parser->parse_file(SPELL2HTML) or croak $!; my $stylesheet = $xslt->parse_stylesheet($style) or croak $!; my $results = $stylesheet->transform($source) or croak $!; # update the output $html =~ s/##RESULTS##/$stylesheet->output_string($results)/e; $html =~ s/##FORM##/&slurp(FORM)/e; } else { $html = $response->status_line, "\n" } } else { # error $html = $cgi->start_html(-title => 'Smart Spell client'); $html .= $cgi->h1('Smart Spell client'); $html .= $cgi->p("Unknown value for cmd ($cmd). Call Eric."); $html .= $cgi->end_html; } # done print $cgi->header(-type=>'text/html', -charset => 'UTF-8'); print $html; sub slurp { # open a file named by the input and return its contents my $f = @_[0]; my $r; open (F, "< $f"); while () { $r .= $_ } close F; return $r; }