#!/usr/bin/perl

use strict;
use DBI;
use Digest::MD5 qw/md5_hex/;
use CGI;

my %sites = ('mc' => 'http://www.malecelebrities.com/',
			 'fc' => 'http://www.femalecelebrities.com/',
			 'ms' => 'http://www.malestars.com/',
			 'fs' => 'http://www.femalestars.com/'
			 );

my $cgi = new CGI;

my %cfg = do 'config.pl';
my $dbh = DBI->connect("dbi:mysql:$cfg{'dbdb'}:$cfg{'dbhost'}",$cfg{'dbuser'},$cfg{'dbpass'});

if (!$dbh->ping) {
	&httpheader();
	&dberror;
	exit;
}

my $scoop_id = $cgi->param('id') || 0;
my $rsid = $cgi->param('rsid');
my $marker = $cgi->param('marker') || 'na';

my $site = $cgi->param('site');
my $k = $cgi->param('k');

if ($k ne genkey($scoop_id) || !$scoop_id) {
	&httpheader;
	&dberror;
	exit;
}

my $q = "SELECT a.asset,f.featurename from assets as a,features as f WHERE a.assetclass='featuretemplate' AND a.ownerclass='f' AND a.assetowner=? AND f.id=a.assetowner;";
my $sth = $dbh->prepare($q);
$sth->execute($scoop_id);

(my $tpl, my $featuretitle) = $sth->fetchrow_array();

if (!$tpl) {
	$tpl = "<a href='" . sitelink($site) . "'>Click here to continue</a>";
} else {
	$tpl = linkup($tpl);
	&httpheader();
	print qq^<HTML><HEAD><TITLE>$featuretitle</TITLE></HEAD><BODY>^;
	print $tpl;
	print qq^</BODY></HTML>^;
}

$sth->finish;
$dbh->disconnect;

################
### SUBS
################
sub httpheader() {
	print "Content-type: text/html\n\n";
}

sub dberror() {
	print "This feature is currently unavailable. Please check your link and try again.";
}

sub genkey() {
	my $extra = shift;
	my @lt = localtime;
	my $year = $lt[5] + 1900;
	my $month = $lt[4] + 1;
	my $day = $lt[3];

	my $g = md5_hex("$year$month$day" . ($extra ? $extra : ""));
	return $g;
}

sub sitelink() {
	my $site = shift;
	if (!$sites{$site}) {
		$site = 'fs';
	}

	my $link = $sites{$site};

	if ($rsid) {
		$link .= "RS/rsid-$rsid/marker-$marker";
	}

	return $link;
}

# Adds links to everything
sub linkup() {
	my $in = shift;

	my $sl = &sitelink($site);	
	my $buf = $in;
	
	# First, remove all target=<x>, then fix0r teh links
	$buf =~ s{target=('|")?[\w]+\1?}{}g;
	$buf =~ s{<a href=('|")[^'"]+\1}{<a href=$1$sl$1}g;

	#$buf =~ s#<a.*>##g;
	#$buf =~ s#</a>##g;

	# Second, link every image.

	$buf =~ s#<img (.*)>#<img border=0 $1>#g;
	$buf =~ s#(<img.*>)#<a href='$sl' target='_blank'>$1</a>#g;

	# Third, add a link at the bottom.
	$buf .= "<BR><center><a href='$sl'>Click here to continue &gt;&gt;</a></center><BR>";
	return $buf;
}
