#!/usr/bin/perl


sub ReadExternalEPG_tvinfo
{
	&Date_Init("Language=German","DateFormat=non-US");
	$uheute = UnixDate($heute, "%s");
	our $datum,$start,$stop="";
	my $anzahl =0;
        foreach $sender (keys(%chan)) {
		if ($chan_wanted{$sender} eq "2") {
			$anzahl++;
		}
	}

	return unless $anzahl;

	if ($anzahl) {
		print "anzahl: $anzahl \n";
		eval 'use HTML::Scrubber';
		eval 'use HTML::TableContentParser';
		eval 'use HTML::Entities';
		}

	# Einstellungen, um HTML zu saeubern
	my @allow = qw[ a tr td ];
	my @rules = ( script => 0, img =>0 );
	my @default = (
        0   =>    # default rule, deny all tags
        {
            '*'           => 1, # default rule, allow all attributes
            'href'        => qr{^(?!(?:java)?script)}i,
            'src'         => qr{^(?!(?:java)?script)}i,
            'cite'        => '(?i-xsm:^(?!(?:java)?script))',
            'language'    => 0,
            'name'        => 1, # could be sneaky, but hey ;)
            'onblur'      => 0,
            'onchange'    => 0,
            'onclick'     => 0,
            'ondblclick'  => 0,
            'onerror'     => 0,
            'onfocus'     => 0,
            'onkeydown'   => 0,
            'onkeypress'  => 0,
            'onkeyup'     => 0,
            'onload'      => 0,
            'onmousedown' => 0,
            'onmousemove' => 0,
            'onmouseout'  => 0,
            'onmouseover' => 0,
            'onmouseup'   => 0,
            'onreset'     => 0,
            'onselect'    => 0,
            'onsubmit'    => 0,
            'onunload'    => 0,
            'src'         => 0,
            'type'        => 0,
        }
    );

	$scrubber = HTML::Scrubber->new(
	allow   => \@allow,
        rules   => \@rules,
        default => \@default,
        comment => 1,
        process => 0,
	);

	$scrubber->process(1);        # allow process instructions (dangerous)
	$default[0] = 1;              # allow all tags by default
	$default[1]->{'*'} = 0;       # deny all attributes by default
	$scrubber->default(@default); # set the default again
	$TableContent = HTML::TableContentParser->new();


	$line = "";
	$channelnumber=0;
	foreach $sender (keys(%chan)) {
		doexit() if $please_exit;

		# Kanal für tvmovie konfiguriert ?
		next if $chan_wanted{$sender} != "2";
		$channelnumber++;
		$id = 1;
		our @events="";

		
		$tvinfo_sender = $chan{$sender}[2];
		for ($days=0;$days < $days2download ;$days++) {
			doexit() if $please_exit;

			$prevtime="";
			$now_string = DateCalc($heute,"+ $days tage",\$err,0);
			$now_day = UnixDate($now_string, "%d");
			$now_month = UnixDate($now_string, "%m");
			$now_year = UnixDate($now_string, "%Y");
			$datum = UnixDate($now_string, "%Y-%m-%d");

			$download = "$http_base$loginURL$listeURL&showSenderID=$tvinfo_sender&newD=$now_day&newM=$now_month&newY=$now_year";
			$cachefile = "$downloadprefix" . "tvinfo_" . "$tvinfo_sender" . "_$now_year$now_month$now_day.html";
			print "\ntvinfo: getting channel $sender for $now_day.$now_month.$now_year (channel $channelnumber/". ($anzahl)." - day ". ($days+1) ."/$days2download)\n";
			my $html=GetContent($download,$cachefile,0,0);

			$html = $TableContent->parse($scrubber->scrub($html));
			$found=$datum='';
			for $t (@$html) {
				for $r (@{$t->{rows}}) {
					doexit() if $please_exit;
					our ($prefix,$link,$title,$subtitle,$htmldesc,$summary,$genre)="";
					our ($country,$year,$origtitle)="";

					$r->{cells}[0]->{data} =~ s/&nbsp;//g;
					$r->{cells}[0]->{data} =~ s/&amp;/&/g;
					$r->{cells}[0]->{data} =~ s/\s+/ /g;
					$r->{cells}[0]->{data} =~ s/^\s*//g;
					$r->{cells}[0]->{data} =~ s/\s*$//g;

###############################################################################################
# 
# Datum bei tvinfo suchen
#
					if ($r->{cells}[1]->{data} =~ m|Programm auf <b>.*?</b>.*?Am .*?, dem (.*)|s) {
						$founddate = $1;
						$datum = UnixDate($founddate, "%Y-%m-%d");
						}					

###############################################################################################
# 
# alles bis zur Sendungsliste skippen
#
					if ($r->{cells}[0]->{data} eq "Uhrzeit:" && 
					$r->{cells}[1]->{data} eq "Sendung:" &&
					$r->{cells}[2]->{data} eq "Kategorie:") {
						$found=1;
						next;
						}
					next unless $found;

					# Gibt es überhaupt Infos?
					last if $r->{cells}[0]->{data} =~ /An diesem Tag liegen uns zum gewählten Sender noch keine Programminformationen vor./;
					last if $r->{cells}[0]->{data} =~ /Sendeschluss/;
					last if $r->{cells}[1]->{data} =~ /Sendeschluss/;

###############################################################################################
# 
# Parsen der Sendungsübersicht für einen Sender
#
					$r->{cells}[1]->{data} =~ s/&nbsp;//g;
					$r->{cells}[1]->{data} =~ s/&amp;/&/g;
					$r->{cells}[1]->{data} =~ s/\s+/ /g;
					$r->{cells}[1]->{data} =~ s/^\s*//g;
					$r->{cells}[1]->{data} =~ s/\s*$//g;

					# Minuten seit Tagesanfang merken für Datumsüberlauf
					$anfang = $r->{cells}[0]->{data};
					$minutesstart = $1*60+$2 if $anfang =~ m/^(.*?):(.*?)$/;
					$start = UnixDate("$datum $anfang", "%s");

					($link,$title) = ($1,$2) if $r->{cells}[1]->{data} =~ m|^<a .*?href=["'](.*?)["']>(.*?)</a>.*$|;
					($link,$title) = ($1,$2) if $r->{cells}[1]->{data} =~ m|Sat.: <a .*?href=["'](.*?)["']>(.*?)</a>.*$|;
					next if $link eq "";
					$event_id = $link;
					$event_id =~ s/.*&sidnr=(.*?)&.*/$1/;

					# Link folgen, damit die Beschreibung geholt werden kann
					# caching
					$cachefile = "$downloadprefix" . "tvinfo_" . "$tvinfo_sender" . "_$event_id" . "_$now_year$now_month$now_day.html";
					$download = "$http_base$link";

					print "tvinfo: getting $dbgSender $event_id ($datum $anfang $title)\n";
					my $htmldesc=GetContent($download,$cachefile,0,0);

					ParseContenttvinfo($htmldesc,$datum,$anfang);
					$subtitle =~s/ \* $//g;
					$subtitle =~s/^ \* //g;
					$subtitle =~s/<br>//gi;

					($type,$genre) = split "/",$genre,2;

					next if ($uheute > $stop); # ist die Sendung schon vorbei ?

 					makeEPGevent($event_id,$start,$stop-$start,$title,$subtitle,$id,"original",
							$summary,$regie,$darsteller,$genre,$type,$country,
							$year,$audio,$format,$flags,$origtitle,$fsk,$folge,""
							,"","","");			
					$id++;
					}
				}
		} # for ($days=0;$days < $days2download ;$days++) 

		# EPG-Daten sortieren
		my($last) = 0;
		my(@temp);
		for(sort({ $a->{start} <=> $b->{start} } @events)) {
			doexit() if $please_exit;
			next if($last == $_->{start});
			push(@temp, $_); 
			$last = $_->{start};
		}
		$XML{$sender} = [ @temp ];
	} # foreach $sender (keys(%chan))
} # sub ReadExternalEPG

###############################################################################################
# 
# Parsen der Sendungsdetails
#
sub ParseContenttvinfo {
	my $htmldesc = shift;
	$datum = shift;
	my $anfang = shift;
	my $linedesc = "";

	# Blanks am Anfang und am Ende einer Zeile entfernen
	foreach  (split("\n",$htmldesc)) {
		$linedesc .= $1 if m|^\s*(.*?)\s*$|;
	}

	$linedesc = decode_entities($linedesc);

	# dreck loeschen
	$linedesc =~ s#<script.*?</script>##ig;
	$linedesc =~ s#<noscript.*?</noscript>##ig;
	$linedesc =~ s#<!--.*?-->##g;

	doexit() if $please_exit;

	$folge="";
	$folge=$1 if $linedesc =~ m|, Folge (\d+)|sig;

	$audio="";
	$audio="Stereo" if $linedesc =~ m|<img src=img/symb_stereo.gif alt='Stereoton'>|sig;
	$audio="Zweikanal" if $linedesc =~ m|<img src=img/symb_zweikt.gif alt='2-Kanal'>|sig;

	$flags="";
	$flags .= " [Untertitel]" if $linedesc =~ m|<img src=img/symb_gehoer.gif alt='Untertitel'>|sig;


	# Uhrzeiten finden
	$genre,$ende = "";
	$genre = $1 if $linedesc =~ m|<td bgcolor="#eeeeee" class="v12">.*?, .*?, .*?,\s*(.*?)\s*</td>|sig;
	$ende  = $1 if $linedesc =~ m|<td bgcolor="#eeeeee" class="v12" align="right" valign="bottom">.*? - (\d\d:\d\d).*?</td>|sig;

	# Untertitel finden
	if ($linedesc =~ m|<span class=HL.>(.*?)</span><br>(.*?)</td>|s) {
		($title,$subtitle) = ($1,$2);
	}


	$country=$year=$origtitle=$title=$subtitle="";

	($title,$subtitle,$country,$year) = ($1,$2,$3,$4) if 
	$linedesc =~ m|<span class="HL1">(.*?)</span><br><b>(.*?)</b>\s*(.*?) \s*(.*?)</td>|sig;

	($title,$country,$year) = ($1,$2,$3) if 
	$linedesc =~ m|<span class="HL1">(.*?)</span><br>\s*(.*?) \s*(.*?)</td>|sig;


	if ($country =~ m|<br>(.*?),\s*(.*)|) {
		$origtitle = $1;
		$country = $2;
		}

	$year = $1 if $subtitle =~ m|^\s*(\d+)$|;
	($country,$year) = ($1,$2) if $subtitle =~ m|(Deutschland) \s*(\d+.*)$|;
	($origtitle,$country,$year) = ($1,$2,$3) if $subtitle =~ m|<br>\s+(.*),\s+(\S+?)\s*(\d+)$|;

#print "|$title|$subtitle|$origtitle|\n";
#print "|$genre|$ende|$country|$year|\n";

	$country = "" if $country eq " ";
	
	# Beschreibung finden
	# zuerst Beschreibungen ohne Bilder finden
	$summaryorig = $summary;
	$summary = $summaryorig . $1 if $linedesc =~ m|.*?<TABLE cellSpacing=0 cellPadding=2 width="75%" bgColor=#eeeeee border=0><TR><TD class="v12" vAlign=bottom>(.*?)</TD></TR></table>.*|si;
	$summary = $summaryorig . $1 if $linedesc =~ m|.*?<TABLE cellSpacing=0 cellPadding=2 width="75%" bgColor=#eeeeee border=0><TR><td valign=top></td><TD class="v12" vAlign=top>(.*?)</TD></TR></table>.*|si;

	# Falls es Bilder gibt, diese rausfiltern
	$summary = $summaryorig . $1 if $linedesc =~ m|.*?<TABLE cellSpacing=0 cellPadding=2 width="75%" bgColor=#eeeeee border=0><TR><TD class="v12" vAlign=bottom><table.*?</table>(.*?)</TD></TR></table>.*|si;
	$summary = $summaryorig . $1 if $linedesc =~ m|.*?<TABLE cellSpacing=0 cellPadding=2 width="75%" bgColor=#eeeeee border=0><TR><td valign=top></td><TD class="v12" vAlign=top><table .*?</table>(.*?)</TD></TR></table>.*|si;

	$darsteller = "";
	$darsteller = $1 if $linedesc =~ m|.*<tr><td class="v12" valign="top">Schauspieler:</td><td class="v12" valign="top" width=80%>(.*?)</td></tr>.*|si;
	$darsteller =~ s#<br>.*?<br><br>#<br>#gi;
	$darsteller =~ s/<br>/, /gi;

	$regie = "";
	$regie = $1 if $linedesc =~ m|<tr><td class="v12" valign="top">Regie:</td><td class="v12" valign="top" width=80%>(.*?)</td></tr>|si;
#print "|$regie|\n";
#print "|$darsteller|\n";


	# saubere Zeilenumbrüche für VDR und html-tags säubern
	$summary =~s/.*Es liegen keine weiteren Beschreibungen zur Sendung vor.*//g;
	$summary =~s|&nbsp;||g;
	$summary =~s/<br><br>/<br>/g;
	$summary =~s/<br>/|/g;
	$summary =~s/\|$//g;

	# Datumsüberlauf in der Stopzeit?
	$minutesstop = $1*60+$2 if $ende =~ m/^(.*?):(.*?)$/;
	if ($minutesstop < $minutesstart) {
		$datum = DateCalc($datum,"+ 1 tag",\$err,0);
		$datum = UnixDate($datum, "%Y-%m-%d");
	}
	$stop = UnixDate("$datum $ende", "%s");
}

return 1;
