#!/usr/local/bin/perl
# $Id: quotes,v 1.7 2000/09/30 18:28:17 grimaldo Rel $
#-----------------------------------------------------------------------
#       quotes (c)1998-2000 Ddimo Emilio Grimaldo Tun
#-----------------------------------------------------------------------
# AUTHOR: D. Emilio Grimaldo T.         grimaldo@panama.iaehv.nl
# DESCRIPTION:
#	A networking Perl script that fetches financial quotes from the
#	web using the HTTP protocol. It has the capability to fetch
#	currency exchange quotes as well as company stock quotes (up
#	to 10). As a bonus it can also fetch Linux daily news. 
#	It works with a direct connection and also via a Proxy server.
#
#	The script was inspired by the 'slashes.pl' script written by
# 	Alex Shnitman <alexsh@linux.org.il> which fetches Slashdot.Org
#	headlines and uses the Perl/GTK module to provide a GUI for the
#	script.
#	Based on the inspired script I removed the GUI part for which I
#	had no need and rewrote some of the code for generalization and
#	then I wrote the financial quotes. Quotes was originally just a
#	testbed for accessing data behind a proxy and evolved into 
#	something serious and useful.
#	  You can have both a system and personal resource files. In
#	the system file ($QLib/quotesrc) you would expect Network
#	(Proxy) and browser settings, even event handlers. In the
#	user/personal resource the stocks and currencies. In the
#	personal file you may clear the system stock/currencies with
#	the clearStock/clearCurrency keywords.
#
# OPTIONS:
#	-h	Help
#	-q	Quiet mode
#	-n	Company names        (DEPRECATED)
#	-s F	Save URL to file F
#	-u F	Use prefetched URL from file F
#	-d	Debug
#	-c	Show configuration/setup/symbols
#       -f F    Use F instead of ~/.quotesrc
#       -w      HTML output when in stock mode, otherwise ignore it
# PARAMETERS:
#	currency Fetch currency exchange quotation
#	stock	 Fetch stock quotes
#	slashdot Fetch Linux news
#	spif     Fetch info about latest release 
# USAGE:
#	quotes [options] parameter
#
# FRESHMEAT: 913728558
# ********* CONFIGURATION SECTION *********
my $PROXY = '';                 # Proxy hostname, otherwise leave empty
my $PROXYPORT = 8001;		# Proxy port
my $Browser = '/usr/local/bin/netscape';
my $QLib = '/usr/local/etc';
# ********* ********************* *********

# *********    I N C L U D E S    *********
use lib $QLib;
use Socket;
use IO::Handle;
use Getopt::Long;
use strict;
# ********* ********************* *********

# ********* G L O B A L  V A R S  *********
my $cvsId   = '$Revision: 1.7 $';
my %product = ( 'title'	=> 'Financial quotations and Linux headlines',
		'name'	=> 'Quotes',
		'exec'  => 'quotes');
my $optHelp;
my $optQuiet;
my $optCNames;
my $optSave;
my $optPrefetched;
my $optDebug;
my $optShowConfig;
my $optCfg;
my $optRcFile;
my ($optHtml, $modSwallow);
my %Spif = ();
my %Cfg = ();
my $stockCnt = 0;
my $httpState = '';
my %Handlers = ();	# @PRX
my $headerPrinted = 0;	# CR-007
my %Stocks = ();
my @StockOrder = ();	# CR-009
my @Currency = ();
my $ULib;		# PR-021
# ********* ********************* *********

# *********************************************************************
# *	U t i l i t y   F u n c t i o n s
# *********************************************************************
sub Initialize {
    $cvsId =~ m/Revision:\s+(\d+\.\d+\.*\d*\.*\d*)/;
    $cvsId = $1;
    $Spif{'host'} = 'www.iaehv.nl';
    $Spif{'file'} = 'users/grimaldo/OpenSoft/spif.txt';
    $Cfg{'anonpwd'} = 'nobody@localhost';
    $Cfg{'agent'} = "$product{'name'}/$cvsId ( ; ; Unix)";
}

sub Status {
    print "@_\n" if (!$optQuiet);
}

sub DbgStatus {
    print "@_\n" if ($optDebug);
}

sub Qwack {
    my $errno = shift;
    my $msg   = shift;
    print "ERROR #$errno: $msg\n";
    exit($errno);
}

sub Squeal {
    my $warnno = shift;
    my $msg   = shift;
    print "WARN #$warnno: $msg\n";
}

sub ConfigureProxy {
    if ($ENV{'http_proxy'}) {
        $ENV{'http_proxy'} =~ m$http://(.*?):(.*?)/$;
	$PROXY = $1;
	$PROXYPORT = $2;
    }
}

sub Heading {
    print "\n\t$product{'name'} version $cvsId\n";
    print "\tCopyright(c)1998-2000 D.Emilio Grimaldo T.\n";
    print "\tEmail:   grimaldo\@panama.iaehv.nl\n";
    print "\t-------------------------------------------------\n";
    print "\t$product{'title'}\n";
    print "\t-------------------------------------------------\n";
}

sub Help {
    &Heading;
    print  "\tUsage: $product{'exec'} \[options\] mode\n";
    print  "\tOptions are:\n";
    print  "\t\t-h | -help  This information\n";
    print  "\t\t-q | -quiet Don't give status messages\n";
    print  "\t\t-n | -names Show company names (Stocks)\n";
    print  "\t\t-s FILE | -save  Save fetched URL.\n";
    print  "\t\t-u FILE | -use   Use a pre-fetched URL.\n";
    print  "\t\t-c | -config     Show configuration/symbols.\n";
    print  "\t\t-cfg OtherRC     To use an alternate RC file\n";
    print  "\tModes are:\n";
    print  "\t\tcurrency Currency exchange quotation\n";
    print  "\t\tstocks   Company stock quotation\n";
    print  "\t\tslashdot Fetch Linux headlines from Slashdot.org\n";
    exit(0);
}

sub QuHelp {
    my $modename = shift;
    my $rOptions = shift;
    my $rParams  = shift;
    my $i;
    &Heading;
    print  "\tUsage: $product{'exec'} \[opts\] $modename \[-- \[modal_options\] \[params\]\]\n";
    print  "\tModal Options are:\n";
    foreach $i (0..$#$rOptions) {
	print  "\t\t$$rOptions[$i]\n";
    }
    print  "\tParameters may be:\n";
    if (ref($rParams) eq 'ARRAY') {
	foreach $i (0..$#$rParams) {
	    print  "\t\t$$rParams[$i]\n";
	}
    } else {
	print  "\t\tNone defined\n";
    }
    print  "\tUse -h before the -- for general Quotes options\n";
    exit(0);
}

sub SaveAndQuit {
    my $NetPath = shift;

    $optSave = '-' if ($optSave eq 'stdout');
    open(SAVE, ">$optSave");
    while (<$NetPath>) {
        print SAVE $_;
    }
    close($NetPath);
    close(SAVE);
    exit(0);
}

# Returns a reference to a symbol. Use from other modules. The
# symbol must be defined before this procedure is interpreted
# (perl bug?).
# Usage:  $re = &QuReference('%', 'Stocks');
sub QuReference {
    my $type = shift;
    my $name = shift;
    my $ev;
    $ev = "\\$type$name";
    
    return eval($ev);
}

sub QuWantHypertext {
    return $optHtml;
}

sub QuSwallowed {
    return $modSwallow;
}

#************************************************
# FUNCTION : NetworkConnection
# PROTOTYPE: NetworkConnection($Host, $File, $Method, \$FormalUrl)
# RETURNS  : Socket descriptor
# GLOBALS  : PROXY PROXYPORT
# PRIVATES : -
# DESCRIPTION
#	  Opens a network connection to fetch an object/file from the
#	given host using either 'ftp' or 'http' methods. It returns
#	a proper URL taking into account the presence/absence of
#	a proxy server.
#	  This deals only with the network connection, the caller is
#	responsible for actually issuing the proper protocol request.
sub NetworkConnection {
    my $Host 	= shift;
    my $Object  = shift;
    my $Method  = shift;
    my $UrlRef	= shift;	# Return the proper URL here
    my ($iaddr, $proto, $port, $paddr);

    if ($Method ne 'ftp' && $Method ne 'http') {
        &Qwack(4, "cannot recognize method: $Method");
    }
    if (ref($UrlRef) ne 'SCALAR') {
        &Qwack(6, 'NetworkConnection: improper parameter (URLREF)');
    }
    # Use a pre-fetched URL (file) instead of a real network connection.
    # This is good for testing whenever the HTML source of the remote
    # site has been changed in a way that my Regular Expressions are
    # not ok anymore.
    if ($optPrefetched ne '') {
	&Status("Using prefetched URL $optPrefetched...");
	if (-f $optPrefetched) {
	    open(PURL,"<$optPrefetched") || &Qwack(7, "NetworkConnection: $!");
	} else {
	    &Qwack(7, 'NetworkConnection: Not a file!');
	}
	return(\*PURL);
    }

    # Now do the network stuff
    if($PROXY) {
	$iaddr = gethostbyname($PROXY);
	$port = $PROXYPORT;
	$$UrlRef = "$Method://$Host/$Object";
    } else {
	$iaddr = gethostbyname($Host);
	if ($Method eq 'http') {
	    $port = 80;		# Standard HTTP port
	} else {
	    $port = 21;		# Standard FTP port
	}
	$$UrlRef = "/$Object";
    }

    $proto = getprotobyname("tcp");
    $paddr = sockaddr_in($port, $iaddr);
    &Status("Connecting to $Host...");
    socket(NETPATH, PF_INET, SOCK_STREAM, $proto) or &Qwack(5,"socket: $!");
    connect(NETPATH, $paddr) or &Qwack(7,"connect: $!");
    autoflush NETPATH 1;
    &Status("Connected; issuing request...");
    return(\*NETPATH);
}

sub QuConnect {
    my $Method  = shift;
    my $Host 	= shift;
    my $Object  = shift;
    my $rHdr    = shift;
    my $rBody   = shift;
    my $RspHdr  = shift;	# Extra response headers (optional)
    my($NetPath, @header, @body, @curUrl, $url, $result);
    
    if (ref($rHdr) ne 'ARRAY' || ref($rBody) ne 'ARRAY') {
	&Qwack(5,"QuConnect: p4,5 not ARRAY reference");
    }
    # 1. Create a network/file descriptor for this object and
    #    fetch it.
    @curUrl = ();
    push(@curUrl, $Method);
    push(@curUrl, $Host);
    push(@curUrl, $Object);
    $NetPath = &NetworkConnection($Host, $Object, $Method, \$url);
    if (ref($RspHdr) eq 'ARRAY' && $#$RspHdr > -1) {
        # A more complicated request with response headers such as
	#	User-Agent: Quotes/1.2
	#	Host: myhost
	#	Connection: Keep-Alive
	#	Authorization: Basic XXXXXXXXYYYYYYYYY
	my $idx;
	print $NetPath "GET $url HTTP/1.0\r\n";
	&DbgStatus("GET $url HTTP/1.0");
	foreach $idx (0 .. $#$RspHdr) {
	    print $NetPath "$$RspHdr[$idx]\r\n";
	    &DbgStatus("$$RspHdr[$idx]");
	}
	print $NetPath "\r\n";
	&DbgStatus("\r\n");
    } else {
        # A plain request
	print $NetPath "GET $url HTTP/1.0\r\n\r\n";
    }
    &Status("Waiting for reply...");
    &SaveAndQuit($NetPath) if ($optSave);
    $result = &QuDownload($NetPath, \@header, \@body);
    &HandleHttpStatus($result, \@header, \@body, \@curUrl);
    @$rHdr  = @header;
    @$rBody = @body;
}

#
# QuRemoveHtmlTags
#	Takes an HTML-encoded line and strips it out of all the tags.
#	may fail if a line is truncated or tags are not closed in the
#	same line!.
#
sub QuRemoveHtmlTags {
    my $raw = shift;
    my $isTag = 0;
    my $len;
    my ($posBeg, $posEnd, $current);
    my $clean = '';
    my $done = 0;
    my $char;
    my $filled = 0;
    
    $len = length($raw);
    foreach $current ( 0 .. $len ) {
	$char = substr($raw, $current, 1);
        if ($isTag) {
	    # We are in a tag, see if we reached the end of it
	    if ($char eq '>') {
		$isTag = 0;
		if ($filled = 0) {
		    # Just in case there was no filling space but
		    # don't add too many, just one!
		    $clean .= ' ';
		    $filled = 1;
		}
		next;
	    }
	}
        if ($char eq '<') {
	    $isTag = 1;
	    $clean .= ' ';
	    $filled = 0;
	    next;
	}
	if (! $isTag) { $clean = $clean . $char; }
    }
    $clean =~ s|\&nbsp;| |gi;
    $clean =~ s|\&copy;|(c)|gi;
    $clean =~ s|\&amp;|\&|gi;
    $clean =~ s|\s+| |g;
    $clean =~ s|-->||g;
    return($clean);
}

# QuDownload 
#	Given a file/network descriptor proceed to fetch the raw data
#	and split it into HTTP headers and document body. Return these
#	in the provided arrays. If it is a file it is assumed to be
#	one fetched and saved (-s option) which therefore contains the
#	http headers as well!. As a result the network/file 
#	connection associated with the descriptor is also closed.
#	  Return value is the HTTP status code.
sub QuDownload {
    my $netpath = shift;
    my $rHeader = shift;
    my $rBody   = shift;
    my $hdr     = 1;
    my $httpStatus;
    my $httpMessage;

    if (ref($rHeader) ne 'ARRAY' || ref($rBody) ne 'ARRAY') {
        &Qwack(50, "QuDownload: bad parameter type(s)\n");
    }
    while(<$netpath>) {
	s/\r?\n$//;  # Strip the newline; chop won't work as it won't
                     # strip the \r
	if(/^$/) {   # Header and body separated by empty line (RFCxxxx)
	    $hdr = 0;
	    next;
	}
	push @$rHeader, $_ if $hdr;
	push @$rBody, $_ unless $hdr;
    }
    close($netpath);
    $$rHeader[0] =~ m|^HTTP/1.(\d)\s+(\d+)\s+|;
    $httpStatus  = $2;
    $httpMessage = $';
    $httpState = "$httpStatus $httpMessage";
    return $httpStatus;
}

sub QuUrl {
    my $url = shift;
    my $txt = shift;

    return "<a href=\"http://$url\">$txt</a>";
}

sub ReadResource {
    my $rc = shift;
    my $rStock	= shift;
    my $rCurrency = shift;
    my $rStockOrder = shift; # CR-009
    my @data = ();
    my ($cuQty, $cuFrom, $cuTo);

    if (ref($rStock) ne 'HASH' || ref($rCurrency) ne 'ARRAY') {
	&Qwack(2, "ReadResource with bad parameter types!");
    }
    if (!open(RC, "< $rc")) {
        return 0;
    }
    $cuQty = 1; $cuFrom = ''; $cuTo = '';
    while (<RC>) {
	chomp;
        next if (/^\s*$/);	# empty lines
	next if (/^\s*#/);	# comment lines
	s/\s*#([\s\w\d\W])*$//; # Comments at the end of the line
	@data = split(/\s+/, $_, 3);
	if ($data[0] eq 'addStock') {
	    $$rStock{$data[1]} = $data[2];
	    $stockCnt += 1;
	    push(@$rStockOrder, $data[1]);	# CR-009
	} elsif ($data[0] eq 'addCurrency') {
	    @data = split(/\s+/, $_, 4);
	    $data[2] =~ s|^[^A-Za-z]||;
	    $data[2] =~ s|[^A-Za-z]$||;
	    $data[3] =~ s|^[^A-Za-z]||;
	    $data[3] =~ s|[^A-Za-z]$||;
	    if ($#data != 3) {
	        print "$rc#$.: wrong format for addCurrency qty M M\n";
	    } else {
	        push(@$rCurrency,join('~',$data[1],$data[2],$data[3]));
	    }
	} elsif ($data[0] eq 'clearStock') {
	    %$rStock = ();
	    @$rStockOrder = ();		# CR-009
	} elsif ($data[0] eq 'clearCurrency') {
	    @$rCurrency = ();
	} elsif ($data[0] eq 'fromCurrency') {
	    $data[1] =~ s|^[^A-Za-z]||;
	    $data[1] =~ s|[^A-Za-z]$||;
	    $cuFrom = $data[1];
	} elsif ($data[0] eq 'toCurrency') {
	    $data[1] =~ s|^[^A-Za-z]||;
	    $data[1] =~ s|[^A-Za-z]$||;
	    $cuTo = $data[1];
	} elsif ($data[0] eq 'qtyCurrency') {
	    $cuQty = $data[1];
	} elsif ($data[0] eq 'setProxy') {
	    $PROXY = $data[1];
	} elsif ($data[0] eq 'setProxyPort') {
	    $PROXYPORT = $data[1];		# numerical!
	} elsif ($data[0] eq 'setBrowser') {
	   $Browser = $data[1];
	} elsif ($data[0] eq 'setSpifHost') {
	   $Spif{'host'} = $data[1];
	} elsif ($data[0] eq 'setSpifFile') {
	   $Spif{'file'} = $data[1];
	} elsif ($data[0] eq 'setAnonPass') {
	   $Cfg{'anonpwd'} = $data[1];
	} elsif ($data[0] eq 'addLibPath') {	# @CR-002
	   $ULib = $data[1];			# @CR-002 PR-021
	} elsif ($data[0] eq 'addHandler') {	# @CR-002
	   $Handlers{$data[1]} = $data[2];	# @CR-002
	}
    }
    close(RC);
    if ($cuFrom ne '' && $cuTo ne '') {
	push(@$rCurrency,join('~',$cuQty,$cuFrom,$cuTo));
    }
    return 1;
}

sub ParseResource {
    my $rStock	= shift;
    my $rCurrency = shift;
    my $rStockOrder = shift;	# CR-009
    my ($rc, $rcCnt);
    
    # System wide resource. Can be used to setup the proxy and
    # browser settings as well as the SPIF setting.
    $rc = "$QLib/quotesrc";
    $rcCnt = 0;
    $rcCnt = &ReadResource($rc, $rStock, $rCurrency, $rStockOrder);
    # Personal resource. Used mainly for stocks and currencies
    # and perhaps handlers
    $rc = $optRcFile;
    $rcCnt += &ReadResource($rc, $rStock, $rCurrency, $rStockOrder);
    if ($rcCnt == 0) {
        # Couldn't find any resource file!
        &Qwack(3, "No resource file(s): $!");
    }
}

# This knows how to launch netscape communicator/navigator. I don't
# know of any 'worthy' browser for Unix, either you watch the web
# in all its splendor with Netscape or miss a lot...
sub LaunchBrowser {
    my $url = shift;
    my $browseCmd;
    
    if ($Browser eq '') {
        &Squeal(2, 'No browser has been specified!');
	return;
    }
    if (! -x $Browser) {
        &Squeal(3, "$Browser is not an executable!");
	return;
    }
    $browseCmd = "$Browser -remote 'OpenURL(##, new_window)'";
    $browseCmd =~ s/##/$url/;
    system("$browseCmd &");
}

# Handle the 'Basic' authentication mechanism (Apache). The return
# value is a valid authentication header to be used in the response
# to the WWW server.
sub BasicAuthentication {
    my $type  = shift;
    my $realm = shift;
    my ($username, $password, $encoded);
    print "%"x40 . "\n";
    print "The server is requesting authentication\n";
    print "Type: $type\tRealm: $realm\n";
    print "Username: "; $username = <STDIN>;
    print "Password: "; $password = <STDIN>;
    print "%"x40 . "\n";
    chomp($username);
    chomp($password);
    # Basic authentication consists of the header:
    #    Authorization: Basic ENCODED_STRING
    # in Basic authentication the encoded part is the username and
    # password separated by a colon encoded in Base64.
    $encoded = &ap_uuencode("$username:$password");
    return("Authorization: $type $encoded");
}

#************************************************
# FUNCTION : HandleHttpStatus
# PROTOTYPE: HandleHttpStatus($httpstat, \@header, \@body [, \@url])
# RETURNS  : nothing
# GLOBALS  : 
# PRIVATES : -
# DESCRIPTION
#	  Takes appropriate action depending on the HTTP status
#	code. This function can be called after QuConnect from
#	which we take the return value and two of the parameters
#	(header, body). 
#	  CODE  Action
#	  200	(OK) just return
#	  401   (Authentication Required) Inform the user that
#		authentication is needed, ask for user/password
#		for the requested realm and immediately perform
#	        another request, this time with auth. info. The
#	        new header/body is fetched and returned in the
#		parameters. 
#	   *    Exit
sub HandleHttpStatus {
    my $code = shift;
    my $rHeader = shift;
    my $rBody = shift;
    my $rLoc = shift;	# Method+Host+File

    &DbgStatus("Handling HTTP code $code\n");
    return if ($code == 200);	# OK
    if ($code == 401) {		# Authorization Required
	my ($i, $type, $realm, $auth, @rsp);
	my (@h, @b);
	if (ref($rLoc) ne 'ARRAY' || ref($rBody) ne 'ARRAY' ||
	    ref($rHeader) ne 'ARRAY') {
	    &Qwack(2,"HandleHttpStatus: bad 2/3/4 param");
	} else {
	    foreach $i (0 .. $#$rHeader) {
	        if ($$rHeader[$i] =~ /^WWW-Authenticate:\s+(\w+)\s+realm="*(\w+)"*/)
		{
		    $type = $1;
		    $realm= $2;
		}
	    }
	    $auth = &BasicAuthentication($type, $realm);
	    push(@rsp,"User-Agent: $Cfg{'agent'}");
	    push(@rsp,$auth);
	    QuConnect($$rLoc[0], $$rLoc[1], $$rLoc[2], \@h, \@b, \@rsp);
	    @$rHeader = @h;
	    @$rBody = @b;
            return;
	}
    } elsif ($code == 302) {		# Redirect   @CR-008
        my ($i, @h, @b, @rsp);
	foreach $i (0 .. $#$rHeader) {
	    if ($$rHeader[$i] =~ /^Location:\s+([htps]+):\/\/([a-z0-9_.-]+)\//i) {
		# This doesn't work with session management (for example
		# as used in Amazon.com
		print "Redirected to: $1://$2/$'\n";
		&QuConnect($1, $2, $', \@h, \@b, \@rsp);
		last;
	    }
	}
        return;
    }
    &Qwack(1, "Connecting to server: $httpState");	# never returns
}

sub ap_uuencode {
    my $string = shift;
    my ($i, $len);
    my $encoded;   # (len+2) / 3 * 4
    my $p = 0;
    my @basis64 = ();
    my $Basis64 ='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';

    foreach $i (0.. length($Basis64) - 1) {
        push(@basis64, substr($Basis64, $i, 1));
    }
    $i = 0;
    $len = length($string);
    while ($i < $len) {
	my $ch = ord(substr($string, $i, 1));
	my $ch1 = ord(substr($string, $i + 1, 1));
	my $ch2 = ord(substr($string, $i + 2, 1));
	substr($encoded, $p, 1) = $basis64[int($ch >> 2)]; $p++;
	substr($encoded, $p, 1) = $basis64[(int($ch & 0x03) << 4) | (int($ch1 & 0xf0) >> 4)];
	$p++;
	substr($encoded, $p, 1) = $basis64[(int($ch1 & 0x0F) << 2) | (int($ch2 & 0xc0) >> 6)];
	$p++;
	substr($encoded, $p, 1) = $basis64[int($ch2 & 0x3f)];
	$p++;

        $i += 3;
    }
#    substr($encoded, $p, 1) = 0; $p--;		# Null terminate string
    substr($encoded, $p, 1) = '='; $p--;
    substr($encoded, $p, 1) = '='; $p--;
    $encoded = substr($encoded, 0, $p + 2);
    return($encoded);
}

sub QuTrailer {
    my $mimetype = shift;
    my @trailer  = @_;
    my $i;

    if ($mimetype eq '') { $mimetype = 'text/plain'; }

#   ******************************************************
#   * Quotes vX.Y (c)1999 D. Emilio Grimaldo Tunon       *
#   * Sponsored by http://www.coralys.com/               *
#   * data (c)1999 <INFORMATION PROVIDER CREDITS>        *
#   ******************************************************
    # Do not remove the copyright notices, it's the law!
    if ($mimetype eq 'text/plain') {
	print  "\t" . '*' x 68 . "\n";
	print  "\t* Quotes v$cvsId (c)2000 D. Emilio Grimaldo Tunon\n";
	print  "\t* Sponsored by http://www.coralys.com/\n";
	foreach $i (0..$#trailer) {
	    print "\t* $trailer[$i]\n";
	}
	print  "\t" . '*' x 68 . "\n";
    } elsif ($mimetype eq 'text/html') {
        print "<hr><center>\n";
	print "Quotes v$cvsId &copy;2000 D. Emilio Grimaldo Tu&ntilde;&oacute;n<br>";
	print "Sponsored by " . &QuUrl('www.coralys.com/', 'Coralys.com') ."<br>";
	foreach $i (0..$#trailer) {
	    $trailer[$i] =~ s|\\n|<br>\n|g;
	    print "$trailer[$i]<br>";
	}
	print "<hr></center>\n";
	print "</body></html>\n" unless $modSwallow;
    }
}

# LoadHandler
#	A cool way to load external plugins as implemented in my
#	Chklogs software. For this to work two new directives are
#	used in the resource file (.quotesrc), for example:
#		addLibPath /home/grimaldo/PerlLibs
#		addHandler example QuExample
#	For the above directives the user module QuExample.pm
#	needs to implement only two methods:
#	        QuExampleSetRequest()
#	        QuExampleDecode()
#       so it gives back the request URL parts, and it is then
#	given the retrieved header/body. Can't be any simpler...
sub LoadHandler {
    my $name = shift;		# Handler name, i.e. example
    my $handler = shift;	# Handler file, i.e. QuExample
    my $result;
    my ($mSetRequest, $mSetOptions, $mDecode);
    my ($host, $object, $url);
    
    &Status("Loading $name ($handler)");
    $result = eval("use lib '$QLib'; use lib '$ULib'; require $handler;");
    if ($@ ne '')  {
        &Qwack(20, "Dynamic handler $name ($handler): $@");
    }
    # Somehow $main::optQuiet = 1 does not work regardless of 
    # whether it is used in main or in a module!
    $optQuiet = 1;
    # 0. Set any options destined for this external module if the
    #    user has done so: ie  quotes [options] extmodule -- -myoption
    #    These must be AFTER the external handler name and must have
    #    a '--' before then so that our GetOpt doesn't swallow them!
    #    GetOpt uses ARGV, at this moment ARGV[0] has the handler name.
    shift(@ARGV);
    if ($#ARGV > -1) {
        # There are some options so call the SetOptions method. By using
	# a conditional we can still use old (pre 1.4-1) modules that 
	# do not implement this method.
	$mSetOptions = $handler . '::' . $handler . 'SetOptions';
	$mSetOptions = \&$mSetOptions;
	&$mSetOptions;
    }

    # If we got here everything went fine with the loading...
    # 1. Invoke the module's Request Constructor, the name of the
    #    function is <HandlerFile>SetRequest, ie. QuExampleSetRequest()
    #    It takes two SCALAR reference parameters corresponding to a
    #	 resolvable host/IP and a file/object path which are passed
    #	 back to us (Quotes) so that we can open a network connection.
    #	 Generate the method name, get a CODE reference to it and 
    #    invoke it.
    #    Return 0 : nothing else to do, terminate execution
    #           1 : execute once only
    #           2+: continue executing (looping)
    $mSetRequest = $handler . '::' . $handler . 'SetRequest';
    $mSetRequest = \&$mSetRequest;
    while ($result = &$mSetRequest(\$host, \$object)) {

    # 2. Create a network/file descriptor for this object and
    #    fetch it.
        my($NetPath, @header, @body);

        &QuConnect('http', $host, $object, \@header, \@body);

    # 3. Now generate the name of the decode method for this
    #    handler and invoke it with the header + body
        $mDecode = $handler . '::' . $handler . 'Decode';
        $mDecode = \&$mDecode;
        &$mDecode(\@header, \@body);
        last if ($result == 1);
    }
    return(0);
}

sub ShowConfiguration {
    my $rStocks = shift;
    my $rCurrencies = shift;
    my $i;
    &Heading;
    print "\tGeneral Settings:\n";
    print "\t\tBrowser   : $Browser\n";
    print "\tNetwork Setup:\n";
    print "\t\tProxy host: $PROXY\n";
    print "\t\tProxy port: $PROXYPORT\n";
    print "\tRegistered Stock Symbols:\n";
    foreach $i (keys(%$rStocks)) {
        printf "\t\t%4s : $$rStocks{$i}\n", $i;
    }
    print "\tRegistered Currencies:\n";
    foreach $i (0 .. $#$rCurrencies) {
        my ($qty, $from, $to) = split(/~/, $$rCurrencies[$i], 3);
        printf "\t\t%3.3f %s -> %s\n", $qty, $from, $to;
    }
    print "\tExternal Handlers:\n";
    foreach $i (keys(%Handlers)) {
        printf "\t\t%s : $Handlers{$i}\n", $i;
    }
    exit(0);
}

# *****************************************************
# *                   M A I N                         *
# *****************************************************
&Initialize;
&ConfigureProxy;
&GetOptions('h|help'	=> \$optHelp,
	    'n|names'	=> \$optCNames,		# Deprecated (v1.7)
	    's|save=s'	=> \$optSave,
	    'u|use=s'	=> \$optPrefetched,
	    'd|debug'	=> \$optDebug,
	    'c|config:s'=> \$optShowConfig,
	    'f|rcfile=s'=> \$optRcFile,
	    'w|web'	=> \$optHtml,
	    'swallow'	=> \$modSwallow,
	    'q|quiet'	=> \$optQuiet);
&Help if $optHelp;
if ($optRcFile eq '') { $optRcFile = "$ENV{'HOME'}/.quotesrc"; }
&ParseResource(\%Stocks, \@Currency, \@StockOrder);
&ShowConfiguration(\%Stocks, \@Currency) if (defined($optShowConfig));

if (exists($Handlers{$ARGV[0]})) {
    # Handle user/generic Information-Provider Handlers
    &LoadHandler($ARGV[0], $Handlers{$ARGV[0]});
} else {
    &Help();
}
# ***************************************************************
#              H  I  S  T  O  R  Y
# ***************************************************************
# 11.Dec.1998 DEGT LinuxHeadlines updated per Alex Shnitman's slashes.pl 1.3
# 11.Dec.1998 DEGT Read data from resource file ~/.quotesrc
# 13.Dec.1998 DEGT Yahoo decoder updated for their newest m5 CGI
# 13.Dec.1998 DEGT v1.1-0 First public release
# 14.Dec.1998 DEGT Cater for more DecodeYahoo cases.
# 23.Dec.1998 DEGT PR-001 Was searching hardcoded MoneyExchange currencies!
# 10.Jan.1999 DEGT PR-002 Updated Nasdaq decoder (they changed CGI output)
# 10.Jan.1999 DEGT CR-001 Renamed option (-s) and added options (-s,-u,-d)
# 17.Jan.1999 DEGT v1.2-0
# 31.Jan.1999 DEGT PR-003 Strip illegal chars from currency symbols
# 30.Jan.1999 DEGT PR-004 Rewrite of NASDAQ handler, they changed again.
# 31.Jan.1999 DEGT CR-002 External information-provider handlers
# 07.Feb.1999 DEGT CR-003 Basic Authentication handling
# 07.Feb.1999 DEGT v1.3-0
# 28.Mar.1999 CLM* Output format corrections/enhancements (sent patch)
# 11.Apr.1999 DEGT PR-005 DecodeNasdaq rev. 4
# 11.Apr.1999 DEGT CR-004 Multiple currencies
# 11.Apr.1999 DEGT CR-005 ShowConfiguration (-c option)
# 11.Apr.1999 DEGT CR-006 System + Personal resource files 
# 12.Apr.1999 DEGT v1.4-0
# 09.May.1999 DEGT        Call SetOptions before SetRequest
# 09.May.1999 DEGT        Added QuHelp for external modules
# 27.Jul.1999 DEGT        Alternate resource file (-f option)
#             DEGT        Fixed odd problem with decimals (Stock prices)
# 06.Oct.1999 DEGT PR-006 DecodeNasdaq rev. 5
# 13.Oct.1999 DEGT CR-007 Some primitive HTML output (-w|--web) for Stocks 
# 23.Oct.1999 DEGT CR-008 Handle HTTP 302 code (experimental)
# 19.Nov.1999 DEGT v1.5-1
# 20.Nov.1999 DEGT PR-007 clearStock gives an error due to a typo
# 26.Nov.1999 HL*  CR-007 Merged patch for improved 10+ stocks
# 26.Nov.1999 HL*  CR-008 Merged patch for indices and gone-stocks
# 26.Nov.1999 HL*  CR-009 Merged patch for display order of stocks
# 26.Nov.1999 DEGT CR-010 Some HTML output changes
# 26.Nov.1999 HZO* PR-008 Patch for currency above 1,000
# 26.Jan.2000 JP** PR-009 Handle split comment tags in QuRemoveHtmlTags
# 26.Jan.2000 DEGT v1.5-2
# 30.Mar.2000 IBAR PR-010 Currency conversion with commas
# 20.May.2000 DEGT PR-011 DecodeNasdaq rev. 6
# 05.Jun.2000 DEGT v1.6-1
# 06.Jun.2000 DEGT PR-012 +/- was missing from the value change field
# 06.Jun.2000 DEGT PR-013 Some hosts report date in different form
# 07.Jun.2000 DEGT v1.6-2
# 09.Jun.2000 LZ*  PR-014 Properly report unchanged stocks
# 12.Jun.2000 DEGT PR-015 ShowConfiguration option is working again
# 11.Aug.2000 DEGT CR-011 Command line money exchange request
# 11.Sep.2000 JJM* PR-016 DecodeNasdaq revision 7
# 11.Sep.2000 DEGT PR-017 DecodeYahoo revision 4
# 11.Sep.2000 DEGT v1.6-3beta Released to ct-quotes list
# 25.Sep.2000 DEGT PR-018 DecodeYahoo revision 5 (sporadic problem)
# 25.Sep.2000 DEGT CR-012 Show human name of currencies
# 26.Sep.2000 DEGT CR-013 LinuxHeadlines moved to QuSlashdot.pm
# 27.Sep.2000 DEGT CR-013 MoneyExchange/Yahoo moved to QuCurrency.pm
#                         Trailer became QuTrailer use in modules.
#                         StockQuotes moved to QuStocks.pm
# 30.Sep.2000 DEGT CR-013 Spif(tm) moved to QuSpif.pm
# 30.Sep.2000 DEGT v1.7-1
