#!@PERLBIN@

require 5.000;
# Set your INIT and MF variables as they may vary.
#
# FBB Word filter & 7PLUS capture
#
# Author:  Stewart Wilkinson G0LGS
#
$Vers="0.60";
$VDate="21/01/2020";
$VData="M_Filter & 7PLUS capture for LinFBB (c) 2002 by G0LGS V${Vers} ${VDate}.\nModernized by N1URO";

# FBB m_filter.fwd (for 7plus AutoCapture)
$MF="@MFWD@/m_filter.fwd";

# If you want Messages from m_filter to come from a real callsign
# change FILTER in the line below to you own or the BBS Callsign.
$WHOAMI = "FILTER";

#
# Nothing beyond here should need changing (unless its broken)
#

# Where is FBB Setup File
$INIT="@FBBCONF@/fbb.conf";

if( defined( $ENV{FBBCONF} ) && "$ENV{FBBCONF}" != "" ){
   $INIT = $ENV{FBBCONF}
}

# Read things we need from Setup file
if(! open(CONFIG, $INIT) ) {
   printf STDERR "Unable to open '%s'\n", ${INIT};
   exit 1;
}

while($line = <CONFIG>) {

   chomp($line);

   if( $line =~ /^\s*\#/) {
      next;

   }elsif( $line =~ /^\s*$/) {
      next;

   }else{
      $line =~ /^\s*(\S*)\s*\=\s*(.*)$/;
      $item = $1;
      $value = $2;

      if( $item =~ /^call/ ){
         $value =~ /^(\w*)\.(.*)$/;
         $BBSCALL = $1;
         $BBSHR = $2;

      }elsif( $item =~ /^data/ ){
         $value =~ /^(\S*)$/;
         $DATA = $1;

      }elsif( $item =~ /^conf/ ){
         $value =~ /^(\S*)$/;
         $CONF = $1;

      }elsif( $item =~ /^name/ ){
         $value =~ /^(\S*)$/;
         $NAME = $1;

      }elsif( $item =~ /^syso/ ){
         $value =~ /^(\S*)$/;
         $SYSCALL = $1;

      }elsif( $item =~ /^impo/ ){
         $value =~ /^([^\.]\S*)\.(\S*)$/;
         $MAIL = "$1.$2";
         $LOCK = "$1.lck";

      }
   }
}

close(CONFIG);

# Date / Time
($sec,$min,$hour,$mday,$mon,$year,$wday,$yday) = localtime(time);
$SEC=("00".."59")[$sec];
$MIN=("00".."59")[$min];
$HOUR=("00".."23")[$hour];
$MDAY=("00".."31")[$mday];
$MON=("01".."12")[$mon];
$YEAR=("00".."99")[$year % 100];

# Where is dirmes.sys
$DIRMES="${DATA}/dirmes.sys";

# M_FILTER Config File.
$Config="${CONF}/m_filter.cfg";

# Wrong number of Parameters ?
if( $#ARGV < 4 ){
   printf STDERR "%s\n", ${VData};
   if( ! -f ${Config} ){
      printf STDERR "WARNING: The Config File %s required by m_filter is missing or unreadable.\n", ${Config};
      printf STDERR "Please correct the problem, as Message Filtering will not work without it.\n";
   }
   exit 0;
}

# The Parameters
$Filename=$ARGV[0];
$Type=$ARGV[1];
$From=$ARGV[2];
$To=$ARGV[3];
$RecNo=$ARGV[4];	# Seems to Always be 0 in XFBB.

${Subject}="(no subject)";

# Weekly Log File Name
$week=int((${yday}+1) / 7);
$WK=("00".."53")[$week];
$LOGF="${DATA}/log/mftlog.${WK}";

# Some Default settings
$AUTO7PLUS=1;
$KMAIL=1;
$HMAIL=1;
$LOG=1;

# Read the Config file & build our list of search words.

if(! open(CFG, "<${Config}") ) {
   if( ! -f "${CONF}/m_filter.warn" ){
      if( open(LOCK,"> ${LOCK}" ) ) {
         printf LOCK "$$";

         if( open(MAIL,">> ${MAIL}" ) ){
            printf MAIL "SP %s < ${WHOAMI}\n", ${SYSCALL};
            printf MAIL "WARNING: M_Filter Config Error\n\n";
            printf MAIL "The Config File %s required by m_filter is missing or unreadable.\n", ${Config};
            printf MAIL "Please correct the problem, as Message Filtering will not work without it.\n";
            printf MAIL "/EX\n";
            close(MAIL);
         }
         close(LOCK);
         unlink(${LOCK});
      }

      if( open(WRN,"> ${CONF}/m_filter.warn" ) ){
         print WRN "m_filter is not correctly configured !";
         close WRN;
      }

   }

   exit 0;
}

if( -f "${CONF}/m_filter.warn" ){
   unlink( "${CONF}/m_filter.warn" );
}

$Subj=0;
$Rlin=0;
$ToFl=0;
$FmFl=0;
$Hold=0;
$Kill=0;

while(<CFG>) {

   chomp;

   if(/^\s*\;/) {
      next;

   }elsif(/^\s*$/) {
      next;

   }elsif(/^\s*\#\S*/){
      next;

   }elsif(/^\s*\!\s*MAIL\s*\=\s*(\S*)/){
      $HMAIL = &IsEnabled($1);
      next;

   }elsif(/^\s*\!\s*KMAIL\s*\=\s*(\S*)/){
      $KMAIL = &IsEnabled($1);
      next;

   }elsif(/^\s*\!\s*AUTO7PLUS\s*\=\s*(\S*)/){
      $AUTO7PLUS = &IsEnabled($1);
      next;

   }elsif(/^\s*\!\s*CHECKPRIVATE\s*\=\s*(\S*)/){
      $CHECKPRIVATE = &IsEnabled($1);
      next;

   }elsif(/^\s*\!\s*LOG\s*\=\s*(\S*)/){
      $LOG = &IsEnabled($1);
      next;

   }elsif(/^\s*\!\sKILL/i) {
      $Subj=0;
      $Rlin=0;
      $ToFl=0;
      $FmFl=0;
      $Hold=0;
      $Kill=1;

   }elsif(/^\s*\!\sHOLD/i) {
      $Subj=0;
      $Rlin=0;
      $ToFl=0;
      $FmFl=0;
      $Hold=1;
      $Kill=0;

   }elsif(/^\s*\!\sRLINE/i) {
      $Subj=0;
      $Rlin=1;
      $ToFl=0;
      $FmFl=0;
      $Hold=0;
      $Kill=0;

   }elsif(/^\s*\!\sTO/i) {
      $Subj=0;
      $Rlin=0;
      $ToFl=1;
      $FmFl=0;
      $Hold=0;
      $Kill=0;

   }elsif(/^\s*\!\sFROM/i) {
      $Subj=0;
      $Rlin=0;
      $ToFl=0;
      $FmFl=1;
      $Hold=0;
      $Kill=0;

   }elsif(/^\s*\!\sSUBJECT/i) {
      $Subj=1;
      $Rlin=0;
      $ToFl=0;
      $FmFl=0;
      $Hold=0;
      $Kill=0;

   # Ignore unknown config lines.
   }elsif(/^\s*\!\S*/i) {
      next;

   }else{

      # Add '\' escapes to some special characters
      s/([\#\!\@\:\[\]\\\/\.\*\?])/\\$1/g;

      # Change any ' ' to '\s{1}' (to match exactly 1 space)
      s/\ /\\s{1}/g;

      # Insert Temporary Leading Space (so that some of the remaining
      # checks work at the begining of the line)
      $_ = " " . $_;

      # Change '+', but not '%+' to '\b' (word boundary)
      s/([^%])\+/$1\\b/gx;

      # Change '%+' to '\+'
      s/%\+/\\+/g;

      # Change '_', but not '%_' to '\s+' (one or more spaces)
      s/([^%])_/$1\\s+/gx;

      # Change '%_' to '_'
      s/%_/_/g;

      # Change '%d' to '\d'	(decimal number)
      s/%d/\\d/gi;

      # Change '%s' to '\S'	(non-space char)
      s/%s/\\S/gi;

      # Remove Leading Space
      s/^\ //;

      if($Subj){
         # We can't Currently check the Subject because XFBB doesn't seem make that information available.
         # push( @Subj, $_ );

      }elsif($Rlin){
         push( @Rlin, $_ );

      }elsif($ToFl){
         push( @ToFl, $_ );

      }elsif($FmFl){
         push( @FmFl, $_ );

      }elsif($Hold){
         push( @Hold, $_ );

      }elsif($Kill){
         push( @Kill, $_ );

      }
   }
}
close(CFG);

# Don't try to trap our own Messages, as that will cause an endless loop
if( (${From} =~ /^${WHOAMI}$/) && (${To} =~ /^${SYSCALL}$/ )  ){
   exit 0;
}

# Do we Check Private Messages ?
if( ($Type =~ /p/i) && (!defined($CHECKPRIVATE) || (! $CHECKPRIVATE) ) ){
   exit 0;
}

$Hold=0;
$Kill=0;
$Found="";

# Check To:
foreach $A (@ToFl) {
   if( ${To} =~ /(${A})/i) {
      $Found="$1";
      $line=${To};
      $Hold=1;
      last;
   }
}
if( ${Hold} ){
   &DoMsg("Held","To");
   exit 3;
}

# Check From:
foreach $A (@FmFl) {
   if( ${From} =~ /(${A})/i) {
      $Found="$1";
      $line=${From};
      $Hold=1;
      last;
   }
}
if( ${Hold} ){
   &DoMsg("Held","From");
   exit 3;
}

if( defined(@Subj) ) {
   # Don't do this unless Subject Checking has been re-enabled.
   # as Information from DIRMES.SYS (in XFBB) does not appear to be correct. 

   # Open dirmes.sys
   if( open(DIRMES, "< ${DIRMES}" ) ) {

      # Move to the appropriate Record
      seek(DIRMES, ${RecNo} * 194, 0);;

      # Read the Record
      if( read( DIRMES, $Rec, 194 ) == 194 ) {

         # Extract Data from Record.
         ($type,$Stat,$Num,$Size,$Date,$Adjbbs,$Route,$Destn,$to,$Bid,
         $Subject,$Resv,$Crdate,$Stdate,$Bbs1,$Bbs2) =
         unpack(AAlllA7A41A7A7A13A61A16LLA10A10, $Rec);

         close(DIRMES);

         # Check Subject
         foreach $A (@Subj) {
            if( ${Subject} =~ /(${A})/i) {
               $Found="$1";
               $line=${Subject};
               $Hold=1;
            last;
            }
         }

         foreach $KILL (@Kill) {
            if( ${Subject} =~ /(${KILL})/i) {
               $Found=$1;
               $Kill=1;
               last;
            }
         }

         foreach $HOLD (@Hold) {
            if( ${Subject} =~ /(${HOLD})/i) {
               $Found=$1;
               $Hold=1;
               last;
            }
         }

         if(${Kill}){
            &DoMsg("Killed", "Subject");
            close(MESG);
            exit 1;
         }

         if( ${Hold} ){
            &DoMsg("Held", "Subject");
            exit 3;
         }
      }
   }
}

# Open the Message.
if( ! open( MESG, "< ${Filename}" ) ){
   printf STDERR "Unable to open Message '%s'\n", ${Filename};
   exit 0;
}

# Check R: Lines
$Pos = tell(MESG);
while(($line = <MESG>) ){
   chomp($line);

   if( $line =~ /^R\:\d{6,}\/\d{4}[zZ]{0,1}\s+\d*\@[\:]{0,1}(\S+)/i ) {

      if( !defined(${Via}) ) {
         $Via = $1;
         $Via =~ /^(\w*)\.(.*)$/;
         $via =$1;
      }

      foreach $RL (@Rlin) {
         if( $line =~ /(${RL})/i) {
            $Found=$1;
            $Hold=1;
            last;
         }       
      }
      if( $Found ){
         last;
      }

      foreach $KILL (@Kill) {
         if( $line =~ /(${KILL})/i) {
            $Found=$1;
            $Kill=1;
            last;
         }
      }
      if( $Found ){
         last;
      }

      foreach $HOLD (@Hold) {
         if( $line =~ /(${HOLD})/i) {
            $Found=$1;
            $Hold=1;
            last;
         }
      }
      if( $Found ){
         last;
      }

   }else{
      seek(MESG, $Pos, 0);
      last;
   }

}continue{
   $Pos = tell(MESG);
}

if(${Kill}){
   &DoMsg("Killed", "R-line");
   close(MESG);
   exit 1;
}

if( ${Hold} ){
   &DoMsg("Held", "R-line");
   close(MESG);
   exit 3;
}

$Is7plus=0;

if( defined(${AUTO7PLUS}) && ${AUTO7PLUS} ) {

   # Check if this the Message has any 7plus
   $Pos = tell(MESG);
   while($line = <MESG>){
      chomp($line);

      # Translate 'non-printable' characters to '.'
      $line =~ s/[\x01-\x1f]/\./g;
      $line =~ s/[\x80-\xff]/\./g;

      # Ignore blank lines
      if( $line =~ /^\s*$/ ){
         next;
      }elsif( $line =~ /\_7\+/ ){
         ${Is7plus} = 1;
         last;
      }
   }
   seek(MESG, ${Pos}, 0);

   # Append to 'mfilter.fwd' file
   if(${Is7plus}){
      if( open(MF,">> ${MF}" ) ){
         printf MF "SP %s \< %s\n", ${To}, ${From};
         printf MF "%s\n", ${Subject};      
         seek(MESG, 0, 0);
         print MF <MESG>;
         seek(MESG, ${Pos}, 0);
         printf MF "/EX\n";
         close(MF);
      }
   }
}

# Check the Message Text
$Pos = tell(MESG);
while($line = <MESG>){
   chomp($line);

   # Translate 'non-printable' characters to '.'
   $line =~ s/[\x01-\x1f]/\./g;
   $line =~ s/[\x80-\xff]/\./g;

   # Ignore blank lines
   if( $line =~ /^\s*$/ ){
      next;
   }

   foreach $KILL (@Kill) {
      if( $line =~ /(${KILL})/i) {
         $Found=$1;
         $Kill=1;
         last;
      }
   }
   if($Found){
      last;
   }

   foreach $HOLD (@Hold) {
      if( $line =~ /(${HOLD})/i) {
         $Found=$1;
         $Hold=1;
         last;
      }
   }

   if($Found){
      last;
   }
}continue{
   $Pos = tell(MESG);
}

if(${Kill}){
   &DoMsg("Killed", "Message");
   close(MESG);
   exit 1;
}

if(${Hold}){
   &DoMsg("Held", "Message");
   close(MESG);
   exit 3;
}

close(MESG);
exit 0;

sub DoMsg
{
   local( $Action ) = $_[0];
   local( $Where ) = $_[1];

   if( defined(${LOG}) && ${LOG} ){
      if( open(LOG, ">> ${LOGF}" ) ) {

         if( defined($via) ) {
            printf LOG "%02d/%02d/%02d %02d:%02d:%02d %s Fm:%s To:%s Via:%s Fnd:%s in %s\n", ${MDAY}, ${MON},${YEAR},${HOUR},${MIN},${SEC}, ${Action}, ${From}, ${To}, ${via}, ${Found}, ${Where};
         }else{ 
            printf LOG "%02d/%02d/%02d %02d:%02d:%02d %s Fm:%s To:%s Fnd:%s in %s\n", ${MDAY}, ${MON},${YEAR},${HOUR},${MIN},${SEC}, ${Action}, ${From}, ${To}, ${Found}, ${Where};
         }

         close(LOG);
      }
   }

   if(   ( (${Action} =~ /^killed/i) && (defined(${KMAIL}) && ${KMAIL}) ) 
      || ( (${Action} =~ /^held/i  ) && (defined(${HMAIL}) && ${HMAIL}) )  ) {

      if( open(LOCK,"> ${LOCK}" ) ) {

         printf LOCK "$$";

         if( open(MAIL,">> ${MAIL}" ) ){

            printf MAIL "SP %s < ${WHOAMI}\n", ${SYSCALL};
            printf MAIL "Message from: %s ${Action}\n\n", ${From};
            printf MAIL "%s\n\n", ${VData};

            if( $Where =~ /^Message/i ){            

               printf MAIL "Message From: %s To: %s - %s because %s contained:\n", ${From}, ${To}, ${Action}, ${Where};
               printf MAIL "the word or phrase '%s' in the following line from the message:-\n\n", ${Found};
               printf MAIL "%s\n\n", ${line};

            }else{

               printf MAIL "Message From: %s To: %s - %s because %s contained\n", ${From}, ${To}, ${Action}, ${Where};
               printf MAIL "the word or phrase '%s'\n\n", ${Found};

            }

            if( defined(${Via}) ) {
               printf MAIL "\nThe message was forwarded from '%s'\n\n", ${Via};
            }

            printf MAIL "/EX\n";
            close(MAIL);
         }

         close(LOCK);
         unlink(${LOCK});
      }
   }
}

sub IsEnabled
{
   local($Ret) = 0;
   local($P) = $_[0];

   if( ($P =~ /^0/) || ($P =~ /^n\S*/i) || ($P =~ /^off/i) || ($P =~ /^di\S*/i) ){
         ${Ret}=0;

   }elsif( ($P =~ /^1/) || ($P =~ /^y\S*/i) || ($P =~ /^ok/i) || ($P =~/^on/i) || ($P =~ /^en\S*/i) ){
         ${Ret}=1;

   }

   return ${Ret};
}
