#!/usr/bin/perl

#---------------------------------------------------------#
# rss.cgi - iCeleb RSS feed generator                     #
#---------------------------------------------------------#
# Uses the 'i' variable to determine what kind of data to #
# pull.                                                   #
#---------------------------------------------------------#

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

use strict;

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


my $cgi = new CGI;
my $i = lc($cgi->param('i'));
my $limit = $cgi->param('limit') || 0;
my $rsid = $cgi->param('rsid');
my $marker = $cgi->param('marker') || 'na';

my $site = $cgi->param('s');
my $to_joinpage = (($cgi->param('jp') == 1) ? 1 : 0);
my $same_window = (($cgi->param('sw') == 1) ? 1 : 0);

my ($tnw, $tnh, $iwm);
my $ts = lc($cgi->param('ts')) || 's';
if ($ts eq 's') {
	$tnw = 35;
	$tnh = 43;
	$iwm = 65;
	
} elsif ($ts eq 'l') {
	$tnw = 70;
	$tnh = 86;
	$iwm = 90;
}


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

# Fail out if the database handle is broken, to prevent wierdness.
if (!$dbh->ping) {
	&httpheader();
	&dberror();
	exit;
}

&httpheader();

if ($i eq 'birthdays') {
	&rss_birthdays();
} elsif ($i eq 'scoopfeed') {
	&rss_scoop();
} elsif ($i eq 'feature') {
	 &rss_feature();
} elsif ($i eq 'gen_cipher') {
	 &rss_gencipher();
} else {
	&rss_error();
}



$dbh->disconnect;
exit;


################
## Feed Types
################
sub rss_birthdays() {
	my @celebs;
	
	$limit =~ s/[^0-9]//g;
	if ($limit <= 0 || $limit > 10) {
		$limit = 10;
	}

	my @months = qw/Blah Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec/;

	my @lt = localtime;
	my $year = $lt[5] + 1900;
	my $month = $lt[4] + 1;
	my $day = $lt[3];

	my $gender = lc($cgi->param('g')) || 'b';
	my $true_rss = ($cgi->param('xml') == 1) ? 1 : 0;

	my $nolinks = $cgi->param('nl') || 0;
	my $showheadshot = ($cgi->param('hs') eq '0' ? 0 : 1);

	my $g_crit = $gender eq 'f' ? "AND gender='F' " : ($gender eq 'm') ? "AND gender='M'" : "";

	my $q = "SELECT id,celebname,byear from celebs WHERE active='1' $g_crit AND bmon=? AND bday=? AND (byear + 18 <= YEAR(NOW())) ORDER BY lastname,firstname LIMIT $limit;";
	my $sth = $dbh->prepare($q);
	$sth->execute($month,$day);
	while (my $r_c = $sth->fetchrow_hashref()) {
		push (@celebs, \%{$r_c});
	}

	!$true_rss && jsout("<TABLE width=100%>");

	my $sl = &sitelink($site);

	if ($true_rss) {
	print qq~<?xml version="1.0"?>
 <rss version="2.0" xmlns:photo="http://pheed.com/pheed/">
  <channel>
    <title>Today's Celebrity Birthdays</title>
    <link>$sl</link>
    <description>Celebrity Birthday RSS Feed provided by site</description>
    <language>en-us</language>
	~;
	}

	if (scalar(@celebs)) {
		foreach my $c (@celebs) {
			 my $age = $year - $$c{byear};
			!$true_rss && jsout("<TR><TD>");
			if ($true_rss) {
				 my $bdate = $months[$month] . " " . niceday($day) . " " . $c->{byear};
				 print qq~
    <item>
      <title>$$c{celebname} [$age]</title>
      <link>$sl</link>
      <description>$$c{celebname} was born on $bdate</description>
				 ~;
			}

			my $target = ($same_window == 1) ? "" : "target='_blank'";

			if ($showheadshot) {
				unless ($nolinks) {
					!$true_rss && jsout("<a $target href='" . sitelink($site) . "'>");
				}
				!$true_rss && jsout("<img border=0 width=$tnw height=$tnh src='http://www.celebrityrss.com/hs.cgi?cid=" .
						$c->{id} . "&k=" . genkey() . "'>");
				unless ($nolinks) {
					!$true_rss && jsout("</a>");
				}

				if ($true_rss) {
					my $img_url = "http://www.celebrityrss.com/hs.cgi?cid=$$c{id}&amp;k=" . genkey();
					print "<photo:thumbnail>$img_url</photo:thumbnail>";
				}
			}
			
			!$true_rss && jsout("</TD><TD>");
			unless ($nolinks) {
				!$true_rss && jsout("<a $target href='". sitelink($site) . "'>");
			}
			!$true_rss && jsout($c->{celebname});

			unless ($nolinks) {
				!$true_rss && jsout("</a> ");
			}

			!$true_rss && jsout(" [" . ($year - $c->{byear}) . "]<BR>");
			!$true_rss && jsout($months[$month] . " " . niceday($day) . " " . $c->{byear} . "</TD></TR>");

			 if ($true_rss) {
				  print "</item>";
			 }
		}

	} else {
		!$true_rss && jsout("<TR><TD width=100%>No birthdays for today.</TD></TR>");
	}
	!$true_rss && jsout("</TABLE>");

	if ($true_rss) {
		print qq~
  </channel>
</rss>
		~;
	}
}



sub rss_scoop() {
	my @feeditems;

	$limit =~ s/[^0-9]//g;
	if ($limit <= 0 || $limit > 5) {
		$limit = 5;
	}
	
	my $img_width_max = $cgi->param('wm');
	$img_width_max =~ s/[^0-9]//g;
	if ($img_width_max <= 0) {
		$img_width_max = $iwm;
	}

	my $gender = lc($cgi->param('g')) || 'b';

	my %g_crit = ('f' => "(ff.gender='F' OR ff.gender='B')", 'm' => "(ff.gender='M' OR ff.gender='M')", 'b' => "(1=1)");
	my $g_crit = $g_crit{$gender};

	my $q = qq^SELECT ff.fid, ff.icon,
					  f.featurename FROM
				feature_feeds as ff, features as f WHERE
				TO_DAYS(ff.startdate) <= TO_DAYS(NOW()) AND
				TO_DAYS(ff.expiredate) >= TO_DAYS(NOW()) AND
				$g_crit AND
				ff.fid=f.id
					ORDER BY RAND() LIMIT $limit ;
			^;
	my $sth = $dbh->prepare($q);
	$sth->execute();
	while (my $r_fi = $sth->fetchrow_hashref()) {
		push (@feeditems, \%{$r_fi});
	}

	if (scalar(@feeditems)) {
		jsout("<TABLE width=100%>");
		my $ic = 1;
		foreach my $r_fi (@feeditems) {
			$sth = $dbh->prepare("SELECT asset from assets WHERE assetclass='featuredesc' AND ownerclass='f' AND assetowner=".$r_fi->{fid}.";");
			$sth->execute();
			my $fdesc = $sth->fetchrow_array() || 'Click to read more...';
			$fdesc =~ s!<a.*?>!!ig;
			$fdesc =~ s!</a>!!ig;
			$fdesc =~ s!</?iC>!!ig;
			$fdesc =~ s!\n|\r!!g;
			$fdesc =~ s!\s*$!!g;

			my %fi = %$r_fi;
			jsout("<TR><TD><img id='crss_imgtag$ic'></TD><TD width=100% valign=top><a target='_blank' href='http://www.celebrityrss.com/ff.cgi?id=$fi{fid}&k=" 
				. genkey($fi{fid}) . "&rsid=" . $rsid . "&site=" . $site . "&marker=" . $marker 
				. "'>$fi{featurename}</a>");
			jsout("<BR><Font size=-1>".$fdesc."</font></TD></TR>");
			print qq^
				var crss_ceil$ic = $img_width_max;
				var crss_img$ic = new Image;
				crss_img$ic.src = '$fi{icon}';
				var crss_height$ic = crss_img$ic.height;
				var crss_width$ic = crss_img$ic.width;
				var crss_rat$ic = (crss_ceil$ic / crss_width$ic);
				var crss_height$ic = (crss_height$ic * crss_rat$ic);
				var i = document.getElementById('crss_imgtag$ic');
				i.src = crss_img$ic.src;
				i.setAttribute('height', crss_height$ic);
				i.setAttribute('width', crss_ceil$ic);
				^;

			$ic++;
		}
		jsout("</TABLE>");
	} else {
		jsout("<TABLE width=100%");
		jsout("<TR><TD width=100%><I>Waiting for new content!</I></TD></TR></TABLE>");
	}

}

sub rss_feature() {
	my $featureid = $cgi->param('id');
	my $cipher = $cgi->param('key');
	my $site = $cgi->param('site');

	my $ref = $ENV{'HTTP_REFERER'};
	my $domain = lc(&get_domain($ref));
	my $test = md5_hex($domain."-JohnnyDrivesAComfortableCar...TheresUsuallySomebodyInTheTrunk");
	if ($test ne $cipher) {
		jsout("<P style='color: #CC3333;'>Access denied from " . ($domain ? $domain : "<I>no site</I>") ." for F:$featureid</P>");
	} else {
		my $q = "SELECT * from features WHERE id=? AND active='1';";
		my $sth = $dbh->prepare($q);
		$sth->execute($featureid);
		unless (my $_f = $sth->fetchrow_hashref()) {
			#jsout("<P style='color: #CC3333;'>Error: Feature Unavailable (404 # $featureid)</P>");		
			my $err_str = qq~
				<table width="100%" height="100%" border="0" align="center"><tr><td align="center">
				The Feature You Requested Is Not Currently Avaibable<p>We apologize for the inconvenience.<br>Please check back later.
				</td></tr></table>
			~;
			jsout($err_str);
		} else {
			my %feature = %$_f;
			$q = "SELECT asset FROM assets WHERE assetclass='featuretemplate' AND ownerclass='f' AND assetowner=?;";
			$sth = $dbh->prepare($q);
			$sth->execute($feature{id});
			$feature{html} = $sth->fetchrow_array();

			## Condition the hell out of it.
			$feature{html} =~ s/\<\/?iC\>//g;

			## Fix0r the links.
			my $sl = &sitelink($site);
			$feature{html} =~ s!\<a [^\>]+\>!\<a href='$sl'\>!g;

			# last ditch effort: just drop out all links.
			#$feature{html} =~ s/\<\/?a[^\>]*\>//g;

			## Now drop tokens
			$feature{html} =~ s/\|[\w]+\|//g;

			## Now spit it out
			jsout($feature{html});
		}
	}
}

sub rss_gencipher() {
	my $domain = $cgi->param('domain');

	my $cipher = md5_hex($domain."-JohnnyDrivesAComfortableCar...TheresUsuallySomebodyInTheTrunk");
	jsout($cipher);
}


sub rss_error() {
	jsout("<P>CelebrityRSS.com -- Invalid request.</P>");
}

sub dberror() {
	jsout('<P>CelebrityRSS.com -- Feed Unavailable.</P>');
}

################
## SUBS  
################

sub httpheader() {
	my $rss_ct = "text/xml";
	my $def_ct = "text/html";

	my $ct = ($cgi->param('xml') eq '1') ? $rss_ct : $def_ct;
	print "Content-type: $ct\n\n";
}

sub jsout() {
	my $buf = shift;

	$buf =~ s/\r|\n|\t//g;

	$buf =~ s/\'/\\\'/g;
	print "document.write('$buf');\n";
}

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 niceday() {
	my $d = shift;
	if ($d == 1 || $d == 21 || $d == 31) {
		$d .= "st";
	} elsif ($d == 2 || $d == 22) {
		$d .= "nd";
	} elsif ($d == 3 || $d == 23) {
		$d .= "rd";
	} else {
		$d .= "th";
	}
}

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

	my $link = $sites{$site};

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

	if ($to_joinpage) {
		$link .= "join.html";
	}

	return $link;
}

sub get_domain() {
	my $url = shift;

	$url =~ s/^[A-Za-z0-9]+\:\/\///;
	(my $domain) = $url =~ /^([a-zA-Z0-9\-\.]+)/;

	# Drop the WWW to make things easier
	$domain =~ s/^www\.//i;

	return $domain;
}
