#!/usr/local/bin/perl
require "weblib.lib";
use Time::Local;
use POSIX "strftime";
use DBI;
use List::Util 'shuffle';
$homedir="/home/todd/private";
require "$homedir/toddweb.env";
$today=time;
$date=strftime("%a, %d %b %Y %H:%M:%S %z",localtime($today));
&getparams;
$param{days}=14 unless $param{days};
$days=$param{days};
$days=0 if $days<0;
$|=1;
$style="http://TRConnection.com/trc.css";
if($param{rss}){&xmlopen;}
else{
	local($title)="<a href=\"http://TRConnection.com\">The Todd Rundgren Connection</a> News Flash";
	$title="The Ted Runger Connection News Flash" if $april1;
	&htmlopen("Latest News|","style=$style","rss=RSS - TR News Feed:http://TRConnection.com/news/rss","viewport=640px");
	open(ASIN,"$homedir/AmazonASINs");
	while(<ASIN>){chop;push(@ASIN,$_) unless $_=~/#/;}
	close ASIN;
	@ASIN=shuffle(@ASIN);
#	$leftAmazon=&AmazonAd(shift(@ASIN),"left");
#	$rightAmazon=&AmazonAd(shift(@ASIN),"right");
#	print <<EOF;
#<div style="margin-bottom: 45px;">
#<!-- Include the Google Friend Connect javascript library. -->
#<script type="text/javascript" src="http://www.google.com/friendconnect/script/friendconnect.js"></script>
#<!-- Define the div tag where the gadget will be inserted. -->
#<div id="div-1235673989874"></div>
#<!-- Render the gadget into a div. -->
#<script type="text/javascript">
#var skin = {};
#skin['BORDER_COLOR'] = '#cccccc';
#skin['ENDCAP_BG_COLOR'] = '#e0ecff';
#skin['ENDCAP_TEXT_COLOR'] = '#333333';
#skin['ENDCAP_LINK_COLOR'] = '#0000cc';
#skin['ALTERNATE_BG_COLOR'] = '#ffffff';
#skin['CONTENT_BG_COLOR'] = '#ffffff';
#skin['CONTENT_LINK_COLOR'] = '#0000cc';
#skin['CONTENT_TEXT_COLOR'] = '#333333';
#skin['CONTENT_SECONDARY_LINK_COLOR'] = '#7777cc';
#skin['CONTENT_SECONDARY_TEXT_COLOR'] = '#666666';
#skin['CONTENT_HEADLINE_COLOR'] = '#333333';
#skin['POSITION'] = 'top';
#skin['DEFAULT_COMMENT_TEXT'] = '- add your comment here -';
#skin['HEADER_TEXT'] = 'Comments';
#google.friendconnect.container.setParentUrl('/' /* location of rpc_relay.html and canvas.html */);
#google.friendconnect.container.renderSocialBar(
# { id: 'div-1235673989874',
#   site: '09505335307555668653',
#   'view-params':{"scope":"SITE","features":"video,comment","showWall":"true"}
# },
#  skin);
#</script>
#</div>
#EOF
	print <<EOF;
<div class="banner">
<h1>$title</h1>
<div id="plea" style="border: 1px solid blue; width: 310px; margin-top: 0px; margin-bottom: 10px; margin-right: 10px; padding: 4px; font-size: 90%; float: left;">
<img src="/thermo?$$" style="float: right; height: 300px;">
<h2>Throw Money!</h2>
<div>
If you are interested in making a donation to support <i>The Todd Rundgren Connection,</i> you may donate by clicking on the PayPal button below<br>
<div style="margin: 5px;">
<form action="https://www.paypal.com/cgi-bin/webscr" method="post" style="float: left; margin-right: 5px;">
<input type="hidden" name="cmd" value="_xclick">
<input type="hidden" name="business" value="roger@rocemabra.com">
<input type="hidden" name="item_name" value="The Todd Rundgren Connection">
<input type="hidden" name="no_shipping" value="1">
<input type="image" src="/img/icons/x-click-but04.gif" style="border: 0px;"  name="submit" alt="Make payments with PayPal - it's fast, free and secure!">
</form>
If you prefer to send a check, contact me via e-mail for instructions.</div>
</div>
<p>
<i>Donations are strictly voluntary and will be gratefully acknowledged via this page (requests for anonymity will also be honored).</i>
</p>
<br style="clear: right;">
</div>
$leftAmazon$rightAmazon
<div style="text-align: center;"><script language="javascript" src="http://trconnection.com/banners.php?b=r"></script></div>
<br style="clear: both;">
</div>
<div id="rssfeed">
<hr><a href="http://TRConnection.com/news/rss"><img src="/icons/xml.gif" width="36" height="14"></a>
<i>Also available as an RSS feed at http://TRConnection.com/news/rss</i>
<b><a href=http://blogspace.com/rss/readers>RSS reader</a> required for best use</b><hr>
</div>
<p id="newsupdates">
Updates from the last $days days -
<a href=$weblib::URL/days=2>last 2 days</a> - 
<a href=$weblib::URL/days=7>last 7 days</a> - 
<a href=$weblib::URL/days=14>last 14 days</a> - 
<a href=$weblib::URL/days=30>last 30 days</a> - 
<a href=$weblib::URL/days=90>last 90 days</a> - 
<a href=$weblib::URL/days=365>last 365 days</a> - 
<a href=$weblib::URL/days=25000>since tracking began</a>
</p>
<p id="photoupdates">
Photo gallery updates from the last 
<a href="/gallery/newest=1h">Hour</a> - 
<a href="/gallery/newest=12h">12 Hours</a> - 
<a href="/gallery/newest=1D">Day</a> - 
<a href="/gallery/newest=3D">3 Days</a> - 
<a href="/gallery/newest=7D">Week</a> - 
<a href="/gallery/newest=14D">2 Weeks</a> - 
<a href="/gallery/newest=1M">Month</a> - 
<a href="/gallery/newest=2M">2 Months</a> - 
<a href="/gallery/newest=1Y">Year</a>
</p>
<p class="pagejump">Jump directly to <a href="#news">News</a></p>
<div id="twitter_div" style="border: 1px solid blue; padding: 10px;">
<h1 class="twitter-title"><a href="http://twitter.com/TRConnection">TR Connection Twitter</a> Updates</h1>
</div>
EOF

	$dbh=DBI->connect("DBI:mysql:database=toddcast","todd","o\$fcpsh");
	$sth=$dbh->prepare("SELECT * from productions where now() <= adddate(airtime, INTERVAL $days+1 DAY) and now() >= airtime order by airtime desc");
	$sth->execute();
	$recenttoddcast=0;
	if(0){
	print qq{<div id="toddcasts">\n};
	while(0&&($toddcast=$sth->fetchrow_hashref())){
		$recenttoddcast++;
		if($recenttoddcast == 1){print "<h1>Recent ToddCasts</h1>\n";}
		$castname=sprintf("toddcast%04d",$toddcast->{'id'});
		$image="<img src=\"$toddcast->{imageurl}\" width=\"$toddcast->{imageurlwidth}\" height=\"$toddcast->{imageurlheight}\"".
				" align=\"left\" style=\"border: 1px solid black; margin: 5px;\">";
		$date=$toddcast->{'airtime'};
		$description=$toddcast->{'description'};
		$duration=$toddcast->{'duration'};
		$title=$toddcast->{'title'};
		print "<div style=\"width: 500px; border: 1px solid blue; margin: 5px; height: 170px; padding: 5px; font-size: 100%;\">",
			"<b>Feed:</b> <a href=\"http://TRConnection.com/ToddCast\">The TR Connection ToddCast</a><br />",
			"<b>Release Date: $date</b> (Length: $duration)<br />$image",
			"<a href=\"/toddcast#$castname\">ToddCast #$toddcast->{id}</a>",
			"<br />$description<br clear=\"left\" /><b>$title</b></div>\n";
	}
	@podcastdb=("toddcast","toddfestwest");
	$dbh0=DBI->connect("DBI:mysql:database=podcast","roger","ogfcpsh");
	foreach $podcastdb(@podcastdb){
		$sth0=$dbh0->prepare("SELECT * from podcastdb where dbname='$podcastdb'");
		$sth0->execute();
		while($podcaster=$sth0->fetchrow_hashref()){
			$dbh=DBI->connect("DBI:mysql:database=".$podcaster->{dbname},$podcaster->{dbuser},$podcaster->{dbpass});
			$sth=$dbh->prepare("SELECT * from podcast where status='Visible'");
			$sth->execute();
			while($podcast=$sth->fetchrow_hashref()){
				$sth1=$dbh->prepare("SELECT * from podcastepisodes where podcastid='$podcast->{id}'".
					" and now() > episodetime and now() <= adddate(episodetime, INTERVAL $days+1 DAY) order by episodetime desc");
				$sth1->execute();
				while($episode=$sth1->fetchrow_hashref()){
					$castname=$episode->{'name'};
					if($episode->{episodeimageurl}){
						$imagewidth="100px";
						$imageheight="100px";
						$image="<img src=\"$episode->{episodeimageurl}\" width=\"$imagewidth\"".
							" height=\"$imageheight\"".
							" align=\"left\" style=\"border: 1px solid black; margin: 5px;\">";
					}
					else{$image="<div style=\"border: 1px solid black; float: left; width: 100px; height: 100px; text-align: center; margin: 5px;\">".
						"<br />No<br />Episode<br />Image</div>";$image="";}
					$date=$episode->{'episodetime'};
					$description=$episode->{'description'};
					$duration=$episode->{'duration'};
					$title=$episode->{'summary'};
					$feed="http://$podcaster->{domain}/podcasts/$podcast->{id}";
					($description,$extdescription)=split(/%%/,$description);
					$description=$extdescription if $extdescription;
					print "<div style=\"width: 500px; border: 1px solid blue; margin: 5px; height: 180px; padding: 5px; overflow: auto; font-size: 100%;\">",
						"<b>Feed:</b> <a href=\"$feed\">$podcast->{summary}</a><br />",
						"<b>Release Date: $date</b> (Length: $duration)<br />",
						"<b>Author: </b>$episode->{author}<br />",
						"$image$description<br clear=\"left\" /><b>$title</b></div>\n";
					
				}
			}
		}
	}
	print "</div>\n";
	}
}
$param{days}*=86400;
if($art=&latestReviews(3)){
	$article="Reviews";
	#$artdate=strftime("%Y%m%d%H%M",localtime(time));
	$article{$artdate,$article}=$art;
	$title{$artdate,$article}="Reviews & Commentary submitted/updated in the last 3 days";
}
open(TRCONN,"$homedir/trconn.dat");
while(<TRCONN>){
	chop;
	last if /^EOD$/;
	($section,$articles)=split(/\t/);
	@articles=split(/,/,$articles);
	push(@list,map{$_,$section}@articles);
}
close(TRCONN);
%list=@list;
$artdir="$homedir/articles";
chdir($artdir);
open(INDEX,"index");
while(<INDEX>){
	chop;
	($article,$title)=split(/:/,$_,2);
	open(ART,$article);
	$_=join("",<ART>);
	s#\$HTMLPATH/##g;
	s#\$CGIPATH#todd#g;
	s#\$WWWHOST#trconection.com#g;
	s#\$PAGEHOMEDIR#$homedir#g;
	while(s#<new\s+([^>]+)>(.*?)</new>##s){
		$art=$2;
		@new=split(/\s+/,$1); $artdate=shift(@new);
		%new=map {split(/=/)} @new;
		$art=qq{<table border="1"><tr><td valign="top">$art</table>} if exists $new{table};
		if($april1){
			$art=~s/Todd/Ted/g;
			$art=~s/Rundgren/Runger/g;
			$title=~s/Todd/Ted/g;
			$title=~s/Rundgren/Runger/g;
		}
		$article{$artdate,$article}=$art;
		$expires{$artdate,$article}=$new{expires} if $new{expires};
		$title{$artdate,$article}=$title;
	}
	close(ART);
}
close(INDEX);
print "<div id=\"news\"><h1>Latest Article Updates</h1>\n" unless $param{rss};
foreach $key(reverse sort keys %article){
	($time,$article)=split(/$;/,$key);
	$artdate=$time;
	$expires=$expires{$time,$article};
	next if $expires && !&checkExpire($expires);
	last unless $time=&checkTime($time);
	if($param{rss}){
		print "<item>\n<title>Article updated: $title{$key}</title>\n";
		#print "<link>http://TRConnection.com/todd/trconn/$list{$article}#$article</link>\n";
		print "<link>http://TRConnection.com/trconn.php/article=$article#$artdate</link>\n";
		print "<description>";
		print qq{&lt;img src="http://TRConnection.com/trc/pictures/trc.png"&gt;};
		print "&lt;br&gt;Updated: $time&lt;hr&gt;";
		$art=$article{$key};
		$art=~s/&nbsp;/ /g;
		#if($table=$art=~/<tr/){print "&lt;table&gt;";}
		$art=~s/&/&amp;/g;
		$art=~s/</&lt;/g;
		$art=~s#href=/#href=http://TRConnection.com/#g;
		$art=~s#href="/#href="http://TRConnection.com/#g;
		$art=~s#src=/#src=http://TRConnection.com/#g;
		$art=~s#src="/#src="http://TRConnection.com/#g;
		$art=~s/>/&gt;/g;
		print $art;
		#print "&lt;/table&gt;" if $table;
		print "</description>\n";
		print "</item>\n";
	}
	else{
		print qq{<div class="article">\n};
		if($list{$article}){
			print "Read the article: <a href=/trconn.php/article=$article#$artdate>",$title{$key},"</a><br>";
		}
		else{print $title{$key},"<br>";}
		print "Updated: $time";
	#	print "(Expires: $expires)" if $expires;
		print "<p>";
		print $article{$key};
		print "</table>" if $table;
		print "<br clear=all><hr>\n";
		print "</div>\n";
	}
}
print "</div>\n" unless $param{rss};
if($param{rss}){
	print &latestReviews($days);
	foreach $days(14,30,90,365){
		print <<EOF;
<item>
<link>http://TRConnection.com/news/days=$days</link>
<title>All items updated in last $days days</title>
</item>
EOF
	}
	print "</channel>\n</rss>\n";
}
else{
	$PAGETAIL=~s/<hr>//;
	print qq{<div id="footer">$PAGETAIL</div>\n};
	&htmlclose;
}
sub xmlopen{
	print <<EOF;
Content-type: text/xml

<?xml version="1.0" ?>
<rss version="0.92">
<channel>
<title>The Todd Rundgren Connection News Flash (last $days days)</title>
<link>http://TRConnection.com</link>
<description>All the latest news on Todd Rundgren</description>
<managingEditor>webmaster\@TRConnection.com (Roger D. Linder)</managingEditor>
<webMaster>webmaster\@TRConnection.com (Roger D. Linder)</webMaster>
<lastBuildDate>$date</lastBuildDate>
<language>en-us</language>
<image>
<title>The Todd Rundgren Connection News Flash (last $days days)</title>
<url>http://TRConnection.com/trc/pictures/trc.png</url>
<link>http://TRConnection.com</link>
<width>97</width>
<height>77</height>
</image>
EOF
}
sub checkExpire{
	local($year,$month,$day,$hour,$minute,$time);
	$time=shift;
	if(length($time) == 12){
		($year,$month,$day,$hour,$minute)=unpack("a4 a2 a2 a2 a2",$time);
		$time=timelocal(0,$minute,$hour,$day,$month-1,$year-1900);
		return 0 if $time < $today;
		$time=POSIX::strftime("%A, %B %e, %Y %l:%M %p %Z",localtime($time));
	}
	else{
		($year,$month,$day)=unpack("a4 a2 a2",$time);
		$time=timelocal(0,0,0,$day,$month-1,$year-1900);
		return 0 if $time < $today;
		$time=POSIX::strftime("%A, %B %e, %Y",localtime($time));
	}
}
sub checkTime{
	local($year,$month,$day,$hour,$minute,$time);
	$time=shift;
	if(length($time) == 12){
		($year,$month,$day,$hour,$minute)=unpack("a4 a2 a2 a2 a2",$time);
		$time=timelocal(0,$minute,$hour,$day,$month-1,$year-1900);
		return 0 if $time < $today-$param{days};
		$time=POSIX::strftime("%A, %B %e, %Y %l:%M %p %Z",localtime($time));
	}
	else{
		($year,$month,$day)=unpack("a4 a2 a2",$time);
		$time=timelocal(0,0,12,$day,$month-1,$year-1900);
		return 0 if $time < $today-$param{days};
		$time=POSIX::strftime("%A, %B %e, %Y",localtime($time));
	}
}
sub latestReviews{
	local($REVIEWDIR,$dir,@files,@reviews,$file,$print);
	local($rss)=$param{rss};
	local($days)=shift;
	$REVIEWDIR="/home/todd/www/reviews";
	opendir(DIR,$REVIEWDIR);
	local(@DIR)=grep !/^\./,readdir DIR;
	foreach $dir(@DIR){
		next unless -d "$REVIEWDIR/$dir";
		chdir "$REVIEWDIR/$dir";
		opendir(REV,".");
		@files=grep /(general|\.(rev|com|set))$/,readdir REV;
		@reviews=();
		foreach $file(@files){
			push(@reviews,$file) if -M $file <= $days;
		}
		@reviews=reverse sort byTime @reviews;
		unless($rss){
			@stat=stat($reviews[0]);
			$newartdate=strftime("%Y%m%d%H%M",localtime($stat[9]));
			$artdate=$newartdate if $artdate lt $newartdate;
		}
		foreach $file(@reviews){
			$print.="<item>\n" if $rss;
			open(FILE,$file);
			$print.="<description>" if $rss;
			while(<FILE>){
				last if /^$/;
				s/&/&amp;/g;
				s/</&lt;/g;
				s/>/&gt;/g;
				($title)=/^Title: (.*)/ if /^Title: /;
				($author)=/^Author: (.*)/ if /^Author: /;
				$print.="$_&lt;br&gt;" if $rss;
			}
			$print.="</description>\n" if $rss;
			$type=$file=~/\.rev$/?"Review":($file=~/\.set$/?"Set List":"Commmentary");
			$print.=qq{<title>$type: $title by $author</title>\n} if $rss;
			$print.=qq{<link>http://TRConnection.com/todd/review/$dir/$file</link>\n} if $rss;
			@stat=stat(FILE);
			$print.=strftime("%c - ",localtime($stat[9])) if !$rss;
			$print.=qq{$type: <a href="http://TRConnection.com/todd/review/$dir/$file">$title</a> by $author<br />\n} if !$rss;
			$print.="</item>\n" if $rss;
		}
	}
	if($print&&!$rss){$print="<div style=\"font-family: courier;\">\n$print</div>\n";}
	return $print;
}
sub byTime{
	if($rss){return $a cmp $b;}
	local(@stata,@statb);
	@stata=stat($a);
	@statb=stat($b);
	return $stata[9] <=> $statb[9];
}
sub AmazonAd{
	local($ASIN,$position)=@_;
	return <<EOF;
<iframe src="http://rcm-na.amazon-adsystem.com/e/cm?t=thetoddrundgrenc&amp;o=1&amp;p=8&amp;l=as1&amp;asins=$ASIN&amp;fc1=000000&amp;IS2=1&amp;lt1=_blank&amp;m=amazon&amp;lc1=0000FF&amp;bc1=000000&amp;bg1=FFFFFF&amp;f=ifr"
 style="width:122px;height:242px;overflow:hidden;margin:0px;border:0px;float:$position;" frameborder="0"></iframe>
EOF
}
