#!/usr/bin/perl

################################################################################
### google.pl
### perform a series of searches on www.google.com
###
### Copyright (C) 2002 Ratatosk / Morten Wulff <wulff@ratatosk.net>
###
### This program is free software; you can redistribute it and/or
### modify it under the terms of the GNU General Public License
### as published by the Free Software Foundation; either version 2
### of the License, or (at your option) any later version.
###
### This program is distributed in the hope that it will be useful,
### but WITHOUT ANY WARRANTY; without even the implied warranty of
### MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
### GNU General Public License for more details.
###
### You should have received a copy of the GNU General Public License
### along with this program; if not, write to the Free Software
### Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
################################################################################

### REVISIONS
### Begun : 04/07/2002 : Morten Wulff <wulff@ratatosk.net>
### 1.2.0 : 19/11/2002 : Morten Wulff

use strict;
use vars '$result';

use Data::Dumper;
use HTML::Template;
use SOAP::Lite;

################################################################################
### INIT
################################################################################

### list of queries to perform
my @queries = (
    'self harm', 'self injury', 'self mutilation', 'hurting myself',
    'selbstverletzung', 'cutting myself'
);

### google registration key
my $key = 'insert_your_key_here';

### save results to this file
my $cache = 'cache.txt';

### store last update tim in this file
my $update = 'update.txt';

### number of minutes between updates
my $interval = 60;

################################################################################
### MAIN
################################################################################

### get last update time
open (UPDATE, $update) or die "Couldn't open $update!\n$!\n";
my $last_update = <UPDATE>;
close UPDATE;

$interval *= 60; ### convert interval to seconds

################################################################################

if ( time - $last_update > $interval || $ARGV[0] eq 'force' ) {
    ### perform new set of queries
    $result = google_query();
    update_cache();
    set_update();
} else {
    ### use cached results
    unless ( my $return = do $cache ) {
        die "couldn't parse $cache: $@" if $@;
        die "couldn't do $cache: $!"    unless defined $return;
        die "couldn't run $cache"       unless $return;
    }
}

################################################################################

cleanup(); ### remove unnecessary HTML tags

### create output
local $/; ### slurp mode ;-)
my $html = <DATA>;

my $t = HTML::Template->new(
    scalarref => \$html,
    die_on_bad_params => 0,
    global_vars       => 1,
    loop_context_vars => 1
);

$t->param( { result => $result } );

print $t->output;

################################################################################
### SUBS
################################################################################

################################################################################
sub cleanup {
    foreach my $block ( @{ $result } ) {
        foreach my $item ( @{ $block->{resultElements} } ) {
            $item->{title}   =~ s/<\/*b>//g;
            $item->{snippet} =~ s/<\/*b>//g;
            $item->{summary} =~ s/<\/*b>//g;
            $item->{directoryTitle} =~ s/<\/*b>//g;
        }
    }
}

################################################################################
sub google_query {
    my $online = [];
    my $google = SOAP::Lite -> service("file:./GoogleSearch.wsdl");

    foreach my $query ( @queries ) {
        print "- processing : $query\n";
        push @{$online}, $google -> doGoogleSearch(
            $key,           ### google key
            "\"$query\"",   ### query
            0,              ### index of first desired result
            10,             ### number of results per query (max 10)
            "true",         ### use results filter
            "",             ### restrictions
            "false",        ### filter adult content (SafeSearch)
            "",             ### language restrict
            "latin1",       ### input encoding
            "latin1"        ### output encoding
        );
    }
    return $online;
}

################################################################################
sub set_update {
    open (UPDATE, ">$update") or die "Couldn't open $update for writing!\n$!\n";
    print UPDATE time;
    close UPDATE;
}

################################################################################
sub update_cache {
    open (OUT, ">$cache") or die "Could not open file: $cache\n$1\n";

    my $dumper = Data::Dumper->new( [$result], [ qw(result) ] );
    $dumper->Purity(1);

    print OUT $dumper->Dump;
    close OUT;
}

################################################################################
### TEMPLATE
################################################################################

__DATA__
<h1>Google Search</h1>
<p>
    Below you can find the results of searching
    <a href="http://www.google.com/">Google</a> using various
    phrases related to self injury.
</p>
<p>
    If you have suggestions for new phrases, <a href="mailto:wulff@psyke.org">please let me know</a>.
</p>
<p>
    This page is updated once every hour.
</p>

<!-- TMPL_LOOP NAME="result" -->
<h2><!-- TMPL_VAR NAME="searchQuery" --></h2>
<p>
    Estimated number of results: <!-- TMPL_VAR NAME="estimatedTotalResultsCount" -->
</p>

<ul>
    <!-- TMPL_LOOP NAME="resultElements" -->
    <li>
        <a href="<!-- TMPL_VAR NAME="URL" -->"><!-- TMPL_IF NAME="directoryTitle" --><!-- TMPL_VAR NAME="directoryTitle" --><!-- TMPL_ELSE --><!-- TMPL_VAR NAME="title" --><!-- /TMPL_IF --></a> -
        <!-- TMPL_IF NAME="summary" --><!-- TMPL_VAR NAME="summary" --><!-- TMPL_ELSE --><!-- TMPL_VAR NAME="snippet" --><!-- /TMPL_IF -->
    </li>
    <!-- /TMPL_LOOP -->
</ul>
<!-- /TMPL_LOOP -->
