#!/usr/bin/perl -w
#<head><title>rss.pl</title>
#<meta name="category" content="pl,perl">
#<meta name="description" content="A include virtual playground, with some rss,mp3, and random goodness, see http://kwark.penguinpowered.com/ for uses.">
#</head>

package rss;

$|++;
use vars qw($ddns $ee $rr $ii $debug $mpc @text $stukjehead);
use strict;
use jip;
$ddns=ddns();
use Date::Manip;
use CGI qw(:standard :html3);
use File::Find;

my $Q = new CGI;
$debug=$Q->param('debug');

print $Q->header(-type=>'text/html',
                 -expires=>'-1day');  
&main($Q);

sub main{
    my ($Q)=shift;
    $rr++;
    my $id=$Q->param('id');
    my $cmd=$Q->param('cmd');
    $id="mom" unless $cmd;
    if ($id && $id eq 'mom'){
	print mom();
    }else{    
	$id="unknown" unless($id);
	$cmd="ximg" if ($cmd eq 'img');
	my $doe="print $cmd(\'$id\');";
	err($doe) if $debug;
	my $res=eval($doe);
	err($@);
	print $@ if ($debug);
	err($res);
	print "(i:$ii e:$ee r:$rr)"	if ($debug);
    }
}

sub err{
    my $i=shift;
    print "$i<br>\n" if $debug;
}




sub hoofd{
    my $id=shift;
    my $r;
    $stukjehead=`cat /www/stukjes/head` unless $stukjehead;
    $r = <<GROK;

<table class="w" width="100%" cellspacing="0" cellpadding="0">  
 <tr class="wr">
 <td>
 <span class="title">
	<a href="http://kwark.penguinpowered.com/">Kwark</a> &gt; $id
 </span>
</td>
 <td class="wm" align="right">
 $stukjehead
</td>
</tr>
</table>

GROK
    $r;
}


sub screenshots{
    my @files;
    my $dir="/www/gfx/screenshots/";
  #  @files=`find $dir -name thumb\-\*.png`;
    @files=grep !/\.thumbnails\//, `find $dir -name thumb\-\*`;
    chop (@files);
    for my $i (@files){
	$i =~ s!/www/!http://$ddns/!;
	my $thumb=$i;
	my $pic=$i;
	$pic =~ s!thumb-!!;
 	print <<GROK;
<a href="$pic"><img 
    src="$thumb" alt="screenshot $pic" border="0"
></a>
GROK
    }
}


sub ximg{
    use Image::Size;
    my $id=shift;
    my $i;
    if ($id eq 'latest'){
        $i=`find /www/gfx/ -name \*\.jpg |grep -v xvpics |tail --lines=1`;
	chop ($i);
    }else{
	my @files=`find /www/gfx/ -name \*.jpg|grep -v xvpics`;
	chop (@files);
	$i=$files[rand(@files)];
    }
    my ($w,$h)=imgsize($i);
    my $comment=jpg_comment($i);

    my ($s,$mesg)=("","");
    $mesg .= $w."x".$h;
    if ($w > $h){
	#$mesg .= " w=100%";
	$s='width="100%"';
    }else{
	#$mesg .= " h=100%";
	$s='height="90%"';
    }
    $i =~ s!/www/gfx/!/gfx/!;
    my $title=$i;
    $title =~ s!/gfx/!!;
    my $tablewidth;
    $tablewidth='width="100%"' unless ($id eq 'latest');
    return <<GROK;


<!-- ######### img stukje ############### -->
<!-- ooit nog http://www.geckonnection.com/webfilmed/dd_dynatable/fromdt-resize.html -->

<table class="imgblok" $tablewidth>
<tr>
  <th valign=top>
    <font size="+1" face="arial,helvetica">
     <a href="http://kwark.penguinpowered.com/">Kwark</a> &gt;
    <a href="gfx.html">gfx</a> &gt;
    <a href="/gfx/$title">$title</a>
</font>

</th></tr>
<tr height="100%">
 <td align="center">
     <a href="gfx.html"><img 
       src="$i" width="$w" height="$h" 
       alt="$title $mesg \n    [ k l i k   f o r   m e e r ] "
       $s border=0></a>
 </td>
</tr>
 
<tr><td align="center">$comment</td></tr>


</table>

<!-- ######### end img stukje ###################### -->
GROK
}

sub mp3{
    my $limit;
    unless ($mpc){
	$limit="15" unless $limit;
	my %when=ff('mp3','nietterzake');
	my @names = sort { $when{$b} <=> $when{$a}; } keys %when;
	splice(@names, $limit);       # discard older stuff
        
	$mpc="<ul class=\"rssul\">";
	foreach my $i(@names){
	    my ($des,$length)=getmpi($i);
	    my $r = $i;
	    $r =~ s!/fire/mp3/!/mp3/mpl/!;
	    my $re=toencode($r);
	    $re =~ s!%2F!/!g;
	    $mpc.= <<GROK;
	     <li>
                   <a href="$re">$des</a> $length
	     </li>
GROK
}
	$mpc.= "</ul>";
    }
    print $mpc;
    return "";
}

sub lastaccess{
#localhost - - [30/Mar/2000:17:39:22 +0200] "GET / HTTP/1.0" 200 28856 "-" "Mozilla/4.72 [en] (X11; I; Linux 2.2.6 i586)"

    my @last=`tail --lines=3400 /var/log/apache/access_log|grep  '"GET / HTTP/1.[10]"' |grep -v localhost|grep -v utr.casema.net`;
    print "<h3 class=\"rsstitle\">lastaccess</h3>\n<ul class=\"rssul\">\n";
    foreach my $i(@last){
	my($host,$refer,$browser)=$i=~  m!(.*)\s-\s-\s\[.*\]\s\".*\"\s\d+\s\d+\s\"(.*)\"\s\"(.*)\"!;
	$host=<<GROK;
<a href="http://$host/">$host</a>
GROK
    
    if ($refer ne '-'){
	$refer =~ s!&amp;!&!g;
	$refer =~ s!&!&amp;!g;
	my $refert = $refer;
	$refert =~ s!&amp;!&amp;\n!g;
	$refer=<<GROK
from <a href="$refer">$refert</a>
GROK
}else{$refer='';}
    
	$browser='' if ($browser eq '-');
	print "<li>$host $refer $browser</li>";
    }
    print "</ul>";
    return '';
} 

sub getmpi{
    my ($file)=@_;
#    use MPEG::MP3Info;
    my ($des,$length);

#    if $mp3desCache{$file}{
#	$des=$mp3desCache{$file};
#    }else{
#	$des="todo$file";
#    }

#	my $tit=$tag->{TITLE} unless $warn;
#	my $art=$tag->{ARTIST} unless $warn;

#	my $minu=$info->{MM};
#	my $secs=$info->{SS};
#	$length="probalby prut";
#	if  ($minu||$secs){
#	    $secs="0".$secs unless($secs>9);
#	    $length="$minu:$secs";
#	}

    ($des) = $file =~ m!.*/(.*)!;
    $des=~ s!\.mp3$!!;
    $length="";
    return $des,$length;
}


sub toencode{
    my($toencode) = @_;
    $toencode=~s/([^a-zA-Z0-9_\-.])/uc sprintf("%%%02x",ord($1))/eg;
    return $toencode;
}



sub com{
    my ($id)=shift;
    my $file="/www/XML/gist/$id.xml";
    err("comment $id") if $debug;
   # if (-e $file){
	err( "li well");
	my $domdoc=&domdoc($file);
	err( " d ".$domdoc);
	my @comment= $domdoc->getElementsByTagName('comment');
	foreach my $c (@comment){
	    err(" spui($c); ");
	    print &spuicomment($c);
	}
   # }else{print " no file $file ";}
}

sub domdoc{
    my $file=shift;
    my $parser;

    if ($parser) {
	err( "parserda ") if ($debug);
    } else {
	$parser = new XML::DOM::Parser;
	err( "created domparser: ".$parser) if($debug);
    }
    $parser->parsefile ("$file") || die "Cant domopen file $file $!\n";
}

sub hmm{
    my ($id)=@_;
    my $rssfile="/www/XML/rss/$id.rss";
    my $rsshtml="/www/stukjes/rss/$id";

    my @fdate=stat $rssfile;
    my @hdate=stat $rsshtml;
    
    print $rsshtml,":",$hdate[9],"\n" if $debug;
    print $rssfile,":",$fdate[9],"\n" if $debug;
    if ($hdate[9] lt $fdate[9]){
	print "html older than rss, make html from rss please" if $debug;
	update_rss_stukje($rssfile,$rsshtml);
    }else{
	print "html up to date" if $debug;
    }

    open (ST,"<$rsshtml");
    while (<ST>){print $_;}
    close ST;
    return "";
}

sub update_rss_stukje{
    my ($rssfile,$rsshtml)=@_;
    use XML::RSS;
    my $rss=new XML::RSS;
    my $content;
    my $file=$rssfile;
    die "File \"$file\" does't exist.\n" unless -e $file;    
    $rss->{'channel'}->{'title'}='';
    $rss->{'channel'}->{'link'}='';
    $rss->parsefile($file);
    my $html = print_html($rss);
    open(ST,">$rsshtml")||die "$!";
    print ST $html;
    close ST;
    return "";
    # undef($rss);
}
1;



sub IGNORE {                    # don't notice these files
    ## $_[0] is basename, $_[1] is full path
    return 1 if ($_[0] !~ /\.mp3/i);
    return 1 if ($_[1] =~ /incoming/);
    return 0;
}

sub ff{
    use vars qw(%when);
    my ($ext,$HOWMANY)=@_;

    err("finding files..");
  
    my (@TOP) =  qw(/fire/mp3/);
    #my (%when);
    
    find (sub {
	#  return $File::Find::prune = 1 if PRUNE $_, $File::Find::name;
#	return if PRUNE $_, $File::Find::name;
        return unless -f;       # only files
	return if IGNORE $_, $File::Find::name;
	$when{$File::Find::name} = (stat _)[9];
    }, @TOP) ;
    
    %when;
}



sub mom{
    BEGIN{
	srand (time() ^ ($$+($$<<15)));
	my $file = "/www/Doc/etext/momus/*";
	my $text = `cat $file`;
	my $i=0;
	my ($stext) = $text  =~ /.+left>(.*)<BR><BR><BR><BR><BR>/;
	$text = $stext;
	$text =~ s/<BR><BR>/<BR>/g;
	my(@lines) = split /<BR>/ , $text;
	foreach my $line (@lines){
	    $line =~ s/puntpuntpunt/\./g;
	    $text[$i]= $line;
	    $i++;
	}
    }
    my $zin =  $text[rand @text]; 
    $zin =~ s/^ //g;
    $zin;
}


#------------ ut


sub di{
        my $user=shift;
        my $tagname=shift;
        my $re;
        my $t = $user->getElementsByTagName("$tagname");
        my $ar=$t->[0];
        #print "<b>geen $tagname</b>" unless $ar;
        my $arr=$ar->getFirstChild if $ar;
        $re = $arr->getData if $ar;
        $re;
}




#-----------end ut



sub print_html {
    my $rss = shift;
    my $r = <<HTML;

<table class="rsstable"><tr><td>
<h3 class="rsstitle"><a class="rsstitle" href="$rss->{'channel'}->{'link'}">$rss->{'channel'}->{'title'}</a></h3>
HTML

    # print channel image
    #if ($rss->{'image'}->{'link'}) {
    #    print <<HTML;
#<a href="$rss->{'image'}->{'link'}"><img src="$rss->{'image'}->{'url'}" alt="$rss->{'image'}->{'title'}" border="0"
#HTML
#        print " width=\"$rss->{'image'}->{'width'}\""
#            if $rss->{'image'}->{'width'};
#        print " height=\"$rss->{'image'}->{'height'}\""
#            if $rss->{'image'}->{'height'};
#        print "></a>\n";
#    }

    # print the channel items
    $r.= "<ul class=\"rssul\">";
    foreach my $item (@{$rss->{'items'}}) {
        next unless defined($item->{'title'}) && defined($item->{'link'});
        $r .= "<li class=\"rssitem\"><a href=\"$item->{'link'}\">$item->{'title'}</a></li>\n";
    }
    $r .= "</ul>";

    # if there's a textinput element
    if ($rss->{'textinput'}->{'title'}) {
#       print <<HTML;
#<form method="get" action="$rss->{'textinput'}->{'link'}">
#$rss->{'textinput'}->{'description'}<BR> 
#<input type="text" name="$rss->{'textinput'}->{'name'}"><BR>
#<input type="submit" value="$rss->{'textinput'}->{'title'}">
#</form>
#HTML
    }

    # if there's a copyright element
    if ($rss->{'channel'}->{'copyright'}) {
        $r .= <<HTML;
<p><sub>$rss->{'channel'}->{'copyright'}</sub></p>
HTML
    }

    $r .= <<HTML;
</td></tr></table>
HTML
    undef($rss);
    $r =~ s!&!&amp;!g;
    return $r;
}


sub spuicomment{
    my $c=shift;
    my $r="";
    my (%h);
    foreach my $i ('date','name','email','url','text'){
        my $v=&di($c,$i);
        $v="<a href=\"mailto:$v\">$v</a>" if ($i eq 'email' && $v);
        $v="<a href=\"$v\">$v</a>" if ($i eq 'url' && $v);

        $r.= "<tr><td><b>$i:</b></td><td>$v</td></tr>\n" if ($v);
    }

    return <<GROK;
    
<div class="comment">
<table>
$r
</table>
</div>
<br>


GROK
}
