##
# Copyright (c) 2009-2010 ATMAIL. All rights reserved
# See http://atmail.com/license.php for license agreement
##

package Atmail::Log;

use vars qw(@ISA @EXPORT);
use strict;

use Atmail::SQL;

sub new {
    my ($this) = shift;
    my %arg = @_;

    my $class = ref($this) || $this;
    my $self  = {};

    foreach ( keys %arg ) {
        $self->{$_} = $arg{$_};
    }

	$self->{sql} = new Atmail::SQL;
    $self->{Type} = "sql";
	
    bless( $self, $class );

	$self->logsettings();

    return $self;
}

sub DESTROY {
	my($self) = @_;

	$self->{sql}->disconnect();

}

# The generic log function, which calls the appropriate
# sql or flat function
sub log {
    my ( $self, $type, $msg ) = @_;

    my $func = "log_" . $self->{Type};
    return $self->$func( $type, $msg );

}

sub logcheck {
    my ( $self, $type, $ip ) = @_;

    my $func = "logcheck_" . $self->{Type};
    return $self->$func( $type, $ip );

}

# Insert the log into the database
sub log_sql {
    my ( $self, $type, $msg ) = @_;

	$self->{sql}->sqldo("INSERT INTO Log_$type (Account, LogMsg, LogDate) VALUES(?, ?, NOW())", $self->{Account} || 'System', $msg);

    return;
}

# Insert the log into the database
sub log_raw {
    my ( $self, $type, %msg ) = @_;

	# Support the multiple new log-formats
	if($type eq 'Error') {
		$self->{sql}->sqlraw("INSERT INTO Log_Error (LogMsg, LogDate, Account) VALUES(?, NOW(), ?)", $msg{'LogMsg'}, $self->{Account} || 'System');
				
	} elsif($type eq 'Login') {
		$self->{sql}->sqlraw("INSERT INTO Log_Login (LogDate, LogType, LogIP, Account) VALUES(NOW(), ?, ?, ?)", $msg{'LogType'}, $msg{'LogIP'}, $self->{Account} || 'System');
		
	} elsif($type eq 'RecvMail') {
		$self->{sql}->sqlraw("INSERT INTO Log_RecvMail (LogDate, LogIP, EmailFrom, MessageID, Account) VALUES(NOW(), ?, ?, ?, ?)", $msg{'LogIP'}, $msg{'EmailFrom'}, $msg{'MessageID'}, $self->{Account} || 'System');		
		
	} elsif($type eq 'SendMail') {
		$self->{sql}->sqlraw("INSERT INTO Log_SendMail (LogDate, LogIP, EmailTo, MessageID, Account) VALUES(NOW(), ?, ?, ?, ?)", $msg{'LogIP'}, $msg{'EmailTo'}, $msg{'MessageID'}, $self->{Account} || 'System');
		
	} elsif($type eq 'Spam') {
		$self->{sql}->sqlraw("INSERT INTO Log_Spam (LogDate, LogType, LogIP, SpamPoints, EmailFrom, Account) VALUES(NOW(), ?, ?, ?, ?, ?)", $msg{'LogType'}, $msg{'LogIP'}, $msg{'SpamPoints'}, $msg{'EmailFrom'}, $self->{Account} || 'System');
				
	} elsif($type eq 'Virus') {
		$self->{sql}->sqlraw("INSERT INTO Log_Virus (LogDate, LogIP, VirusName, EmailFrom, Account) VALUES(NOW(), ?, ?, ?, ?)", $msg{'LogIP'}, $msg{'VirusName'}, $msg{'EmailFrom'}, $self->{Account} || 'System');

	}

    return;
}

sub logcheck_sql {
    my ( $self, $type, $ip) = @_;

    my $cnt;
	
	$ip = '%' . $ip . '%' if($ip);

    if ($ip && $self->{Account} && $ip !~ /New Account/i) {
        $cnt = $self->{sql}->sqlgetfield( "select count(id) from Log_$type where LogMsg like ? and LogDate > DATE_SUB(NOW(), INTERVAL 24 HOUR) and Account=?", $ip, $self->{Account});
   } else	{
        $cnt = $self->{sql}->sqlgetfield( "select count(id) from Log_$type where LogMsg like ? and LogDate > DATE_SUB(NOW(), INTERVAL 24 HOUR)",  $ip );
 	}

    return $cnt;
}

sub addrelay	{
	my($self, $ip) = @_;
	
	return 1 if($ip !~ /\d+\.\d+\.\d+\.\d+/);

 if($self->{smtp_popimaprelay} == 1)
 {
	# Delete any entries older timout from the "user" table
	$self->{sql}->sqldo("delete from MailRelay where Account='User' and DateAdded < DATE_SUB(NOW(), INTERVAL " . $self->{smtp_popimaprelay_timeout} . " MINUTE)");

	# Add the new IP into the database, only if we do not exist
	if(!$self->{sql}->sqlgetfield("select IPaddress from MailRelay where IPaddress=?", $ip)) {
	$self->{sql}->sqldo("INSERT INTO MailRelay (IPaddress, Account, DateAdded) VALUES(?, 'User', NOW() )", $ip);
	} else {
	$self->{sql}->sqldo("UPDATE MailRelay set DateAdded=NOW() where IPaddress=? and Account='User'", $ip);
	}
	}

	return;
}

sub updatelastlogin	{
	my($self, $user) = @_;

	# Return if no user supplied or account invalid
	return if(!$user || $user !~ /@/);

	my $time = time();

	# Update the users last login date
	$self->{sql}->sqldo("update UserSession set LastLogin=NOW() where Account=?", $user);

	return 1;

}

sub logsettings {
	my($self) = @_;

	# Check our global preferences for relay
	$self->{smtp_popimaprelay} = $self->{sql}->sqlgetfield("select keyValue from Config where keyName='smtp_popimaprelay'");

	$self->{smtp_popimaprelay_timeout} = $self->{sql}->sqlgetfield("select keyValue from Config where keyName='smtp_popimaprelay_timeout'");
		
}

1;
