#!/usr/bin/perl -wT
#
# TWiki WikiClone (see wiki.pm for $wikiversion and other info)
#
# Copyright (C) 1999-2000 Peter Thoeny, peter@thoeny.com
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details, published at 
# http://www.gnu.org/copyleft/gpl.html

use lib ( '.' );
use lib ( '../lib' );
use TWiki;
use TWiki::Net;

my $debug = ! ( @ARGV && $ARGV[0] eq "-q" );

&main();

sub main
{
    $debug && print "TWiki mail notification\n";
    $debug && print "- to suppress all normal output: mailnotifyall -q\n";

    # Get emails notify list from the Main web
    my $web = "Main";
    my ( $topic, $webName, $dummy, $userName, $dataDir) = 
	&TWiki::initialize( "/$web", "nobody" );
    $debug && print "- Initialize: $topic $webName $dummy $userName $dataDir\n";
    my @notifylist = &TWiki::getEmailNotifyList($webName);
    $debug && print "- Notify list for $webName web: @notifylist\n";
    if( ! @notifylist ) {
	$debug && print "- Note: Notification list is empty\n";
    } else {
        allWebsNotify( @notifylist );
    }
    $debug && print "End TWiki mail notification\n";
}

sub allWebsNotify
{
    my( @notifylist) = @_;

    $debug && print "- Notify list: @notifylist\n";

    my $webitems = 0;
    my $emailbodytopics = "";
    my $emailbodyrendered = "";
    my $dataDir = &TWiki::getDataDir();
    my $prevLastmodify;
    my $currLastmodify;
    my( $topic, $webName, $dummy, $userName );

    opendir( DIR, "$dataDir" ) or die "could not open $dataDir";
    @weblist = grep !/^\.\.?$/, readdir DIR;
    closedir DIR;
    $debug && print "Checking Webs: " . @weblist . "\n";
    WEB_LOOP: foreach $web ( @weblist ) {
        $webitems = 0;
        if( -d "$dataDir/$web" ) {

            ( $topic, $webName, $dummy, $userName, $dataDir) = 
	        &TWiki::initialize( "/$web", "nobody" );
            $dummy = "";  # to suppress warning

            $debug && print "Checking TWiki.$webName\n";

            if( ! &TWiki::Store::webExists( $webName ) ) {
	        print STDERR "* ERROR: TWiki mailnotifyall does not find web $webName\n";
	        next;
            }

            my $emailbody = "";
            my $topiclist = "";

            my $text = &TWiki::Store::readTemplate( "changes" );
            my $changes= &TWiki::Store::readFile( "$dataDir/$webName/.changes" );

            my %exclude;

            $text = &TWiki::handleCommonTags($text, $topic);
            $text =~ s/<img src=.*?[^>]>/[IMG]/goi;  # remove all images
            my $before = "";
            my $after = "";
            ( $before, $text, $after) = split( /%REPEAT%/, $text );
            $emailbody = &TWiki::getRenderedVersion( $before );
            $after = &TWiki::getRenderedVersion( $after );

            $prevLastmodify = &TWiki::Store::readFile( "$dataDir/$webName/.mailnotify" ) || "0";
            $currLastmodify = "";
            my $scriptSuffix = $TWiki::scriptSuffix;
            my $scriptUrlPath = $TWiki::scriptUrlPath;
            my $scriptUrl = "$TWiki::urlHost$scriptUrlPath";
            my $frev = "";

            foreach( reverse split( /\n/, $changes ) ) {
	        @bar = split( /\t/);
	        $foo = $text;
	        if( ( ! %exclude ) || ( ! $exclude{ $bar[0] } ) ) {
                    next unless TWiki::Store::topicExists( $webName, $bar[0] );

	            if( ! $currLastmodify ) {
	                # newest entry
	                $time = &TWiki::formatGmTime( $prevLastmodify );
	                if( $prevLastmodify eq $bar[2] ) {
	                    # newest entry is same as at time of previous notification
	                    $debug && print "- Note: No topics changed since $time\n";
	                    next WEB_LOOP;
	                }
	                $currLastmodify = $bar[2];
	                $debug && print "- Changed topics since $time: ";
	            }

	            if( $prevLastmodify >= $bar[2] ) {
	                #print "Date: found item of last notification\n";
	                # found item of last notification
	                last;
	            }
                    $frev = "";
                    if( $bar[3] ) {
                        if( $bar[3] > 1 ) {
                            $frev = "r1.$bar[3]";
                        } else {
                            $frev = "<b>NEW</b>";
                        }
                    }

	            #create entry in HTML attachment
	            $foo = $text;
	            $foo =~ s/%TOPICNAME%/$bar[0]/go;
	            $wikiuser = &TWiki::userToWikiName( $bar[1] );
	            $foo =~ s/%AUTHOR%/$wikiuser/go;
                    $foo =~ s/%LOCKED%//go;
	            $time = &TWiki::formatGmTime( $bar[2] );
                    $foo =~ s/%TIME%/$time/go;
                    $foo =~ s/%REVISION%/$frev/go;
	            $foo = &TWiki::getRenderedVersion( $foo );

                    $head = &TWiki::Store::readFileHead( "$dataDir\/$webName\/$bar[0].txt", 16 );
                    $head = &TWiki::makeTopicSummary( $head, $bar[0], $webName );
                    $foo =~ s/%TEXTHEAD%/$head/go;

	            $emailbody .= $foo;
	            $exclude{ $bar[0] } = "1";

	            $debug && print "$bar[0] ";

	            #add new item to topic list in email body
                    if( ! $webitems ) {
                        $foo = "\n$webName:\n";
                    } else {
                        $foo = "";
                    }
                    $webitems = $webitems + 1;
	            $foo = "$foo - $bar[0]  ($wikiuser)\n  $scriptUrl/view$scriptSuffix/$webName/$bar[0]\n";
                    $foo =~ s/Main\.//go;
	            $topiclist = "$topiclist$foo";
	        }
            }

            if( $topiclist eq "" ) {
	        $debug && print "- Note: $web Topic list is empty\n";
            } else {
                $debug && print "\n";

                # change absolute addresses to relative ones & do some cleanup
                $topiclist =~ s/(href=\")$scriptUrlPath/$1..\/../goi;
                $topiclist =~ s/(action=\")$scriptUrlPath/$1..\/../goi;
                $topiclist =~ s|( ?) *</*nop/*>\n?|$1|gois;
                $after =~ s/(href=\")$scriptUrlPath/$1..\/../goi;
                $after =~ s/(action=\")$scriptUrlPath/$1..\/../goi;
                $after =~ s|( ?) *</*nop/*>\n?|$1|gois;

                $emailbody .= $after;
                $emailbodytopics = "$emailbodytopics$topiclist";
                $emailbodyrendered = "$emailbodyrendered$emailbody";

            }
            &TWiki::Store::saveFile( "$dataDir/$webName/.mailnotify", $currLastmodify );
            # remove obsolete .lock files
            &TWiki::Store::removeObsoleteTopicLocks( $web );
        }
    }

    if( $emailbodytopics eq "" ) {
	$debug && print "- Note: no changes in any web\n";
        return;
    }
    my $from = &TWiki::Prefs::getPreferencesValue("WIKIWEBMASTER");

    $notifylist = join ', ', @notifylist;

    $text = &TWiki::Store::readTemplate( "mailnotifyall" );
    $text =~ s/%EMAILFROM%/$from/go;
    $text =~ s/%EMAILTO%/$notifylist/go;
    $text =~ s/%EMAILBODY%/$emailbodyrendered/go;
    $text =~ s/%TOPICLIST%/$emailbodytopics/go;
    $text =~ s/%LASTDATE%/&TWiki::formatGmTime($prevLastmodify)/geo;
    $text = &TWiki::handleCommonTags( $text, $topic );

    $debug && print "- Sending mail notification to: $notifylist\n";

    my $error = &TWiki::Net::sendEmail( $text );
    if( $error ) {
	print STDERR "* $error\n";
        $debug && print "- End Twiki.$webName\n";

    } else {

	$debug && print "- End Twiki mail notification sent\n";
    }
}
