from Zorp import *
import os, re, string

class AbstractMatcher:
	def __init__(self):
		pass
		
	def checkMatch(self, str):
		raise NotImplementedError


class RegexpMatcher(AbstractMatcher):
        def __init__(self):
                self.match = []
                self.ignore = []

        def checkMatch(self, str):
                for pattern in self.match:
                        if pattern.search(str):
                                for pattern in self.ignore:
                                        if pattern.search(str):
                                                return FALSE
                                return TRUE
                return FALSE


class RegexpFileMatcher(RegexpMatcher):
        def __init__(self, match_fname, ignore_fname=''):
        
        	RegexpMatcher.__init__(self)
		self.match_file = match_fname
 		self.match_date = 0
		self.ignore_file = ignore_fname
		self.ignore_date = 0

        def readFile(self, filename, array):
                f = open(filename, 'r')
                line = string.rstrip(f.readline())
                while line:
                        try:
                                array.append(re.compile(line, re.IGNORECASE))
                        except re.error:
                                pass
                        line = string.rstrip(f.readline())
        
	def checkMatch(self, str):
		try:
			st = os.stat(self.match_file)
			if self.match_date < st[8]:
				self.match_date = st[8]
				self.match = []
				self.readFile(self.match_file, self.match)
		except IOError:
                        log(CORE_POLICY, 3, "Error opening matchfile; filename='%s'" % self.match_file)
		
		if self.ignore_file:
			try:
				st = os.stat(self.ignore_file)
				if self.ignore_date < st[8]:
					self.ignore_date = st[8]
					self.ignore = []
					self.readFile(self.ignore_file, self.ignore)
			except IOError:
	                        log(CORE_POLICY, 3, "Error opening ignore file; filename='%s'" % self.match_file)

		return RegexpMatcher.checkMatch(self, str)
