#!/usr/local/bin/perl
use strict;
use lib '/var/home/slowtwitch/slowtwitch.com/cgi-bin/articles/admin';
use Links qw/:objects/;
use Links::SiteHTML;
use GT::Date;
use XML::RSS;
$| = 1;
local $SIG{__DIE__} = \&Links::fatal;
Links::init('/var/home/slowtwitch/slowtwitch.com/cgi-bin/articles/admin');
main();
sub main {
# ------------------------------------------------------------------
# Main admin loop, displays html pages and other admin tasks.
#
    my @updates = get_recent_updates('Links', 'Add_Date', 'DESC', 10);
    gen_rss(@updates);
}
sub get_recent_updates {
# ------------------------------------------------------------------
# Get recent news updates from the DB and return an array of hashes
#
    my ($table, $sort_by, $sort_order, $limit) = @_;
	my $db = $DB->table($table);
	$db->select_options("ORDER BY $sort_by $sort_order", "LIMIT $limit");
	my $sth = $db->select();
	my @loop;
	while (my $link = $sth->fetchrow_hashref) {
		$link = Links::SiteHTML::tags('link',$link);
		push @loop, {
            description     => $link->{Description},
            title           => $link->{Title},
            link            => $link->{detailed_url},
        };
	}
    return @loop;
}
sub gen_rss {
# ------------------------------------------------------------------
# Generate the rss output file
#
    my @updates = @_;
    use URI::Escape;
    my $date = GT::Date::date_get(time, "%yyyy%-%mm%-%dd%T%hh%:%mm%:%ss%%o%");
    $date =~ s/^(.*)(\d\d)$/$1:$2/;
    my $rss = XML::RSS->new(version => '1.0', encoding => 'iso-8859-1');
    $rss->channel(
        title       => 'Slowtwitch.com',
        link        => 'http://www.slowtwitch.com',
        description => '',
        dc          => {
            date        => $date,
            creator     => 'Slowtwitch.com',
            publisher   => 'Slowtwitch.com',
            rights      => 'Copyright 2007, Slowtwitch.com',
            language    => 'en-us',
        },
        syn         => {
            updatePeriod    => 'daily',
            updateFrequency => '1',
            updateBase      => $date,
        }
    );
    $rss->image(
        title       => 'Slowtwitch.com',
        url         => 'http://www.slowtwitch.com/favicon.ico',
        link        => 'http://www.slowtwitch.com',
        dc          => {
            creator => 'Slowtwitch.com'
        }
    );
    foreach (@updates) {
    	my $t = escape_for_xml($_->{title});
        my $d = escape_for_xml($_->{description});
        $rss->add_item(
            title       => $t,
            link        => $_->{link},
            description => $d,
        );
    }
    $rss->save('/var/home/slowtwitch/slowtwitch.com/www/rss/slowtwitch.rss');
}
sub escape_for_xml {
	my $text = shift;
	$text =~ s/\x82/,/g;
    $text =~ s-\x83-f-g;
    $text =~ s/\x84/,,/g;
    $text =~ s/\x85/.../g;
    $text =~ s/\x88/^/g;
	$text =~ s-\x89- °/°°-g;
	$text =~ s/\x8B/~-g;
	$text =~ s-\x99-TM-g;
	$text =~ s/\x9B/>/g;
	$text =~ s/\x9C/oe/g;
	return "";
}