'''
Advanced logger for sagator, version 0.2
 
(c) 2003-2004 Jan ONDREJ (SAL) <ondrejj(at)salstar.sk>

 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.
                                                                                
'''
                                                                                
from avlib import *
from match import match_any
from report import report
                                                                                
__all__=['log']

class log(report):
  '''
  Advanced logger interscanner.
  
  usage: log(logto,format,scanners...)
  
  where: logto is a string, which defines filename to store these data
           If logto is an integer, it defines log level in standard
           log file.
         format is a string, which defines data format

  This scanner can be used to log some special data.
  You can use these variables in format string:
    $LEVEL		- detected virus level
    $VIRNAME		- name of detected virus, empty if CLEAN
    $STATUS		- if mail is dropped, rejected, ...
    $QNAME		- quarantine file name
    $SCANNER_NAME	- scanner which reported this virus
    $SENDER		- scanned message sender
    $RECIPIENTS		- scanned message recipients
    $SIZE               - email size
  
  You also can use log.FORMAT for default format.
  '''
  name='log()'
  # default format
  FORMAT="level='$LEVEL', virname='$VIRNAME', size='$SIZE', sender='$SENDER', recipients='$RECIPIENTS'\n"
  def __init__(self,logto,format,*scanners):
      self.logto=logto
      self.format=format
      match_any.__init__(self,scanners)
  def repl_vars(self,level,detected):
      return self.replace_tmpl(self.format,{
        'LEVEL':	str(level),
        'VIRNAME':	detected,
        'STATUS':	globals.ACTION,
        'QNAME':	globals.QFNAME,
        'SCANNER_NAME':	globals.found_by.name,
        'SENDER':	mail.sender.strip(),
        'RECIPIENTS':	string.join(mail.recip,','),
        'SIZE':		str(len(mail.data))
      })
  def scanstream(self,stream):
      level,detected,virlist=match_any.scanstream(self,stream)
      if type(self.logto)==type(1):
        debug.echo(self.logto,self.repl_vars(level,detected).split())
      else:
        open(self.logto,'a').write(self.repl_vars(level,detected))
      return level,detected,virlist
