#!/usr/bin/perl

# ispCP ω (OMEGA) a Virtual Hosting Control Panel
# Copyright (C) 2001-2006 by moleSoftware GmbH - http://www.molesoftware.com
# Copyright (C) 2006-2010 by isp Control Panel - http://ispcp.net
#
# Version: $Id: ispcp-arpl-msgr 3312 2010-09-19 20:49:35Z scitech $
#
# The contents of this file are subject to the Mozilla Public License
# Version 1.1 (the "License"); you may not use this file except in
# compliance with the License. You may obtain a copy of the License at
# http://www.mozilla.org/MPL/
#
# Software distributed under the License is distributed on an "AS IS"
# basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
# License for the specific language governing rights and limitations
# under the License.
#
# The Original Code is "VHCS - Virtual Hosting Control System".
#
# The Initial Developer of the Original Code is moleSoftware GmbH.
# Portions created by Initial Developer are Copyright (C) 2001-2006
# by moleSoftware GmbH. All Rights Reserved.
# Portions created by the ispCP Team are Copyright (C) 2006-2010 by
# isp Control Panel. All Rights Reserved.
#
# The ispCP ω Home Page is:
#
#    http://isp-control.net
#

#
# common code: BEGIN
#

BEGIN {

	my @needed = (
		'strict',
		'warnings',
		'IO::Socket',
		DBI,
		DBD::mysql,
		MIME::Entity,
		MIME::Parser,
		Crypt::CBC,
		Crypt::Blowfish,
		MIME::Base64,
		Mail::Address,
		Term::ReadPassword
	);

	my ($mod, $mod_err, $mod_missing) = ('', '_off_', '');

	for $mod (@needed) {

		if (eval "require $mod") {
			$mod->import();
		} else {
			print STDERR "\nCRITICAL ERROR: Module [$mod] WAS NOT FOUND !\n";

			$mod_err = '_on_';

			if ($mod_missing eq '') {
				$mod_missing .= $mod;
			} else {
				$mod_missing .= ", $mod";
			}
		}
	}

	if ($mod_err eq '_on_') {
		print STDERR "\nModules [$mod_missing] WAS NOT FOUND in your system...\n";

		exit 1;
	} else {
		$| = 1;
	}
}

$main::el_sep = "\t#\t";
@main::el = ();

sub push_el {

	my ($el, $sub_name, $msgDebug) = @_;

	push @$el, "$sub_name".$main::el_sep."$msgDebug";

	if (defined($main::engine_debug)) {
		print STDOUT "push_el() sub_name: $sub_name, msg: $msgDebug\n";
	}

}

sub pop_el {

	my ($el) = @_;
	my $data = pop @$el;

	if (!defined($data)) {
		if (defined($main::engine_debug)) {
			print  STDOUT "DEBUG: pop_el() Empty 'EL' Stack !\n";
		}

		return undef;
	}

	my ($sub_name, $msgDebug) = split(/$main::el_sep/, $data);

	if (defined($main::engine_debug)) {
		print STDOUT "DEBUG: pop_el() sub_name: $sub_name, msg: $msgDebug\n";
	}

	return $data;
}

sub dump_el {

	my ($el, $fname) = @_;
	my $res = undef;

	if ($fname ne 'stdout') {
		$res = open(FP, ">>", $fname);

		if (!defined($res)) {
			return 0;
		}

	}

	my $el_data = undef;

	while (defined($el_data = pop_el(\@main::el))) {
		my ($sub_name, $msgDebug) = split(/$main::el_sep/, $el_data);

		if ($fname eq 'stdout') {
			printf STDOUT "%-30s | %s\n",  $sub_name, $msgDebug;
		} else {
			printf FP "%-30s | %s\n",  $sub_name, $msgDebug;
		}
	}

	close(FP);
}

# Global variables;

$main::db_host = undef;
$main::db_user = undef;
$main::db_pwd = undef;
$main::db_name = undef;
@main::db_connect = ();
$main::db = undef;

sub doSQL {

	push_el(\@main::el, 'doSQL()', 'Starting...');

	my ($sql) = @_;
	my $qr = undef;

	if (!defined($sql) || ($sql eq '')) {
		push_el(\@main::el, 'doSQL()', 'ERROR: Undefined SQL query !');

		return (-1, '');
	}

	if (!defined($main::db) || !ref($main::db)) {
		$main::db = DBI -> connect(@main::db_connect, {PrintError => 0});
		$main::db -> do('SET NAMES utf8'); # Use UTF-8 encoding

		if ( !defined($main::db) ) {
			push_el(
				\@main::el,
				'doSQL()',
				'ERROR: Unable to connect SQL server !'
			);

			return (-1, '');
		}
	}

	if ($sql =~ /select/i) {
		$qr = $main::db -> selectall_arrayref($sql);
	} else {
		$qr = $main::db -> do($sql);
	}

	if (defined($qr)) {
		push_el(\@main::el, 'doSQL()', 'Ending...');

		return (0, $qr);
	} else {
		push_el(\@main::el, 'doSQL()', 'ERROR: Incorrect SQL Query -> '.$main::db -> errstr);

		return (-1, '');
	}
}

sub get_file {

	push_el(\@main::el, 'get_file()', 'Starting...');

	my ($fname) = @_;

	if (!defined($fname) || ($fname eq '')) {
		push_el(
			\@main::el,
			'get_file()',
			"ERROR: Undefined input data, fname: |$fname| !"
		);

		return (-1, '');
	}

	if (! -e $fname) {
		push_el(
			\@main::el,
			'get_file()',
			"ERROR: File '$fname' does not exist !"
		);

		return (-1, '');
	}

	my $res = open(F, '<', $fname);

	if (!defined($res)) {
		push_el(
			\@main::el,
			'get_file()',
			"ERROR: Can't open '$fname' for reading !"
		);

		return (-1, '');
	}

	my @fdata = <F>;

	close(F);

	my $line = join('', @fdata);

	push_el(\@main::el, 'get_file()', 'Ending...');

	return (0, $line);
}

sub del_file {

	push_el(\@main::el, 'del_file()', 'Starting...');

	my ($fname) = @_;

	if (!defined($fname) || ($fname eq '')) {
		push_el(
			\@main::el,
			'del_file()',
			"ERROR: Undefined input data, fname: |$fname| !"
		);

		return -1;
	}

	if (! -e $fname) {
		push_el(
			\@main::el, 'del_file()', "WARNING: File '$fname' does not exist !"
		);
	} else {
		my $res = unlink ($fname);

		if ($res != 1) {
			push_el(\@main::el,	'del_file()', "ERROR: Can't unlink '$fname' !");

			return -1;
		}
	}

	push_el(\@main::el, 'del_file()', 'Ending...');

	0;
}

# Global variables

%main::cfg = ();

if(!defined($main::cfg_file)) {
	$main::cfg_file = '/etc/ispcp/ispcp.conf';
}

$main::cfg_re = '^([\_A-Za-z0-9]+) *= *([^\n\r]*)[\n\r]';

use FindBin;
use lib "$FindBin::Bin/";
require 'ispcp-db-keys.pl';

umask(027);

sub encrypt_db_password {

	push_el(\@main::el, 'encrypt_db_password()', 'Starting...');

	my ($pass) = @_;

	if (!defined($pass) || $pass eq '') {
		push_el(
			\@main::el,
			'encrypt_db_password()',
			'ERROR: Undefined input data ($pass)...'
		);

		return (1, '');
	}

	my $cipher = Crypt::CBC->new(
		{
			'key' => $main::db_pass_key,
			'keysize' => 32,
			'cipher' => 'Blowfish',
			'iv' => $main::db_pass_iv,
			'regenerate_key' => 0,
			'padding' => 'space',
			'prepend_iv' => 0
		}
	);

	my $ciphertext = $cipher->encrypt($pass);
	my $encoded = encode_base64($ciphertext); chop($encoded);

	push_el(\@main::el, 'encrypt_db_password()', 'Ending...');

	return (0, $encoded);
}

sub decrypt_db_password {

	push_el(\@main::el, 'decrypt_db_password()', 'Starting...');

	my ($pass) = @_;

	if (!defined($pass) || $pass eq '') {
		push_el(
			\@main::el,
			'decrypt_db_password()',
			'ERROR: Undefined input data ($pass)...'
		);

		return (1, '');
	}

	my $cipher = Crypt::CBC -> new(
		{
			'key' => $main::db_pass_key,
			'keysize' => 32,
			'cipher' => 'Blowfish',
			'iv' => $main::db_pass_iv,
			'regenerate_key' => 0,
			'padding' => 'space',
			'prepend_iv' => 0
		}
	);

	my $decoded = decode_base64("$pass\n");
	my $plaintext = $cipher -> decrypt($decoded);

	push_el(\@main::el, 'decrypt_db_password()', 'Ending...');

	return (0, $plaintext);
}

sub setup_main_vars {

	push_el(\@main::el, 'setup_main_vars()', 'Starting...');

	#
	# Database backend vars;
	#

	$main::db_host = $main::cfg{'DATABASE_HOST'};
	$main::db_user = $main::cfg{'DATABASE_USER'};
	$main::db_pwd = $main::cfg{'DATABASE_PASSWORD'};

	if ($main::db_pwd ne '') {
		my $rs = undef;

		($rs, $main::db_pwd) = decrypt_db_password($main::db_pwd);
	}

	$main::db_name = $main::cfg{'DATABASE_NAME'};
	@main::db_connect = (
		"DBI:mysql:$main::db_name:$main::db_host",
		$main::db_user,
		$main::db_pwd
	);

	push_el(\@main::el, 'setup_main_vars()', 'Ending...');

	0;
}

sub get_conf {

	push_el(\@main::el, 'get_conf()', 'Starting...');

	my ($rs, $fline) = get_file($main::cfg_file);
	return -1 if ($rs != 0);

	my @frows = split(/\n/, $fline);
	my $i = '';

	for ($i = 0; $i < scalar(@frows); $i++) {
		$frows[$i] = "$frows[$i]\n";

		if ($frows[$i] =~ /$main::cfg_re/) {
			$main::cfg{$1} = $2;
		}
	}

	return -1 if (setup_main_vars() != 0);

	push_el(\@main::el, 'get_conf()', 'Ending...');

	0;
}

my $rs = get_conf();

if ($main::cfg{'DEBUG'} != 0) {
	$main::engine_debug = '_on_';
}

if ($rs != 0) {
	if( -d "$main::cfg{'LOG_DIR'}/ispcp-arpl-msgr/") {
		$main::ispcp_arpl_msgr_el =
			"$main::cfg{'LOG_DIR'}ispcp-arpl-msgr/ispcp-arpl-msgr.el";
		$main::ispcp_arpl_msgr_stdout =
			"$main::cfg{'LOG_DIR'}/ispcp-arpl-msgr/ispcp-arpl-msgr.stdout";
		$main::ispcp_arpl_msgr_stderr =
			"$main::cfg{'LOG_DIR'}/ispcp-arpl-msgr/ispcp-arpl-msgr.stderr";
		chown(
			$main::cfg{'MTA_MAILBOX_UID'},
			$main::cfg{'MTA_MAILBOX_GID'},
			($main::ispcp_arpl_msgr_stdout,$main::ispcp_arpl_msgr_stderr)
		);

		umask(027);

		open(STDOUT, ">", $main::ispcp_arpl_msgr_stdout) ||
			die "Can't redirect stdout";
		open(STDERR, ">", $main::ispcp_arpl_msgr_stderr) ||
			die "Can't redirect stderr";
	}

	print STDERR
		"\nCRITICAL ERROR: Failed open /etc/ispcp/ispcp.conf! Maybe wrong permissions?\n" ;

	exit 0;
}

# debug dump files;
$main::log_dir = $main::cfg{'LOG_DIR'};

$main::ispcp_arpl_msgr_el =
	"$main::log_dir/ispcp-arpl-msgr/ispcp-arpl-msgr.el";
$main::ispcp_arpl_msgr_stdout =
	"$main::log_dir/ispcp-arpl-msgr/ispcp-arpl-msgr.stdout";
$main::ispcp_arpl_msgr_stderr =
	"$main::log_dir/ispcp-arpl-msgr/ispcp-arpl-msgr.stderr";

chown(
	$main::cfg{'MTA_MAILBOX_UID'},
	$main::cfg{'MTA_MAILBOX_GID'},
	($main::ispcp_arpl_msgr_stdout,$main::ispcp_arpl_msgr_stderr)
);

open(STDOUT, ">", $main::ispcp_arpl_msgr_stdout) || die "Can't redirect stdout";
open(STDERR, ">", $main::ispcp_arpl_msgr_stderr) || die "Can't redirect stderr";

#
# common code: END
#

use strict;
use warnings;

my @msg_rows = <STDIN>;
my $msg = join('', @msg_rows);

sub arpl_msgr_start_up {

	push_el(\@main::el, 'arpl_msgr_start_up()', 'Starting...');

	my ($rs, $rdata) = (undef, undef);

	# Let's clear Execution Logs, if any.

	if (-e $main::ispcp_arpl_msgr_el) {
		$rs = del_file($main::ispcp_arpl_msgr_el);

		return $rs if ($rs != 0);
	}

	# config check;

	$rs = get_conf();
	return $rs if ($rs != 0);

	push_el(\@main::el, 'arpl_msgr_start_up()', 'Ending...');

	0;
}

sub arpl_msgr_shut_down {

	push_el(\@main::el, 'arpl_msgr_shut_down()', 'Starting...');

	my $rs = undef;

	$main::db->disconnect();

	if (!defined($main::engine_debug)) {
		$rs = del_file($main::ispcp_arpl_msgr_stdout);
		return $rs if ($rs != 0);

		$rs = del_file($main::ispcp_arpl_msgr_stderr);
		return $rs if ($rs != 0);

		push_el(\@main::el, 'arpl_msgr_shut_down()', "delete debugfiles.");
	}

	push_el(\@main::el, 'arpl_msgr_shut_down()', 'Ending...');

	0;
}

sub arpl_msgr_engine {

	push_el(\@main::el, 'arpl_msgr_engine()', 'Starting...');

	my ($sql, $rs, $ref) = (undef, undef, undef);

	# Cleanup old autoreply log entries
	$sql = "
		DELETE FROM
			`autoreplies_log`
		WHERE
			ADDTIME(`time`, '24:00:00') < NOW()
		;
	";

	push_el(\@main::el, 'arpl_msgr_engine()', "sql: |".$sql."|");

	($rs, $ref) = doSQL($sql);

	push_el(
		\@main::el,
		'arpl_msgr_engine()',
		'Error purging old autoreplies_log entries'
	) if($rs != 0);

	my $msg_parser = new MIME::Parser;

	$msg_parser->output_to_core(1);

	my $msg_entity = $msg_parser -> parse_data($msg);
	my $head = $msg_entity -> head();
	my @from_ma = Mail::Address->parse($head -> get('From'));
	my @to_addrs = Mail::Address->parse($head -> get('X-Original-To'));
	my $buffer = "0";
	my $edmn = undef;

# 	my @edmn = @_;

	my $name = undef;
	my $mail_to = undef;
	my $to_ma = undef;
	my ($mailHeaderCheck1, $mailHeaderCheck2, $mailHeaderCheck3) = (1, 1, 1);

	if($head->get('X-Mailer')) {
		if($head -> get('X-Mailer') =~ m/Autoreply Manager/i) {
			$mailHeaderCheck1 = 0;
		}
	}

	if($head->get('Auto-Submitted')) {
		if($head -> get('Auto-Submitted') =~ m/auto-replied/i) {
			$mailHeaderCheck2 = 0;
		}
	}

	if($head->get('Sender')) {
		if($head -> get('Sender')=~ m/autoresponder/i) {
			$mailHeaderCheck3 = 0;
		}
	}

	if($mailHeaderCheck1 && $mailHeaderCheck2 && $mailHeaderCheck3 &&
	    !$head -> get('X-Autoresponse-From')) {

		foreach $to_ma (@to_addrs) {
			if($to_ma->address =~ m/@/i && $to_ma->address !~ m/"/g) {
				if($buffer) {
					$name = $buffer;
					$buffer = '0';
				} else {
					if($to_ma->phrase) {
						$name = $to_ma->phrase;
					} else {
						$name = '';
					}
				}

				push_el(
					\@main::el,
					'arpl_msgr_engine()',
					'>>> From: |' . $from_ma[0]->address . '|, To: |' .
						$to_ma->address . '|'
				);

				push_el(\@main::el, 'arpl_msgr_engine()', "Test for loop!");

				my $ma = $to_ma->address."\n";

# 				# TODO: Resolve forwards
# 				return 0 if (!($ma =~ /^([^\@]+)\@([^\n]+)$/));
#
# 				# postbox with normal_mail, alias_mail or subdom_mail as type, so '_mail'
# 				$sql = "SELECT `mail_forward`, INSTR(`mail_type`, '_mail') FROM `mail_users` WHERE `mail_addr` = '$ma'";
#
# 				($rs, $ref) = doSQL($sql);
# 				return $rs if ($rs != 0);
#
# 				my $ref = @$ref[0]; # erster Datensatz
#
# 				# second field = 0 -> no postbox (forward, etc.)
# 				if (@$ref[1] == 0) {
# 					# first field -> forward address
# 					$ma = @$ref[0];
# 				}
#
# 				$ma = $ma."\n";

				return 0 if (!($ma =~ /^([^\@]+)\@([^\n]+)\n$/));

				my ($user, $dmn) = ($1, $2);
				my ($dmn_id, $sub_id, $pt, $ref) = (undef, undef, undef, undef);
				my ($domainformsubdomain, $subformsubdomain) = (undef, undef);

			 	#@edmn = split(/\./,$2,2);

			 	#$edmn = $edmn[1];

			 	$edmn = $2;

				$sql = "
					SELECT
						count(domain_id) AS `cnt`
					FROM
						`domain`
					WHERE
						`domain_name` = '$edmn'
					;
				";

				($rs, $ref) = doSQL($sql);

				return $rs if ($rs != 0);

				$ref = @$ref[0];

				if(@$ref[0] == 1) {
					$pt = 1;
				} else {
					$sql = "
						SELECT
							count(alias_id) AS `cnt`
						FROM
							`domain_aliasses`
						WHERE
							`alias_name` = '$edmn'
						;
					";

					($rs, $ref) = doSQL($sql);
					return $rs if ($rs != 0);

					$ref = @$ref[0];

					if (@$ref[0] == 1) {
						$pt = 2;
					} else {
						$sql = "
							SELECT
								COUNT(`t1`.`subdomain_id`) AS `cnt`
							FROM
								`subdomain` AS `t1`
							LEFT JOIN (`domain` AS `t2`) on (`t1`.`domain_id` = t2.`domain_id`)
							WHERE
								CONCAT(`t1`.`subdomain_name`, '.', `t2`.`domain_name`) = '$edmn'
							;
						";

						($rs, $ref) = doSQL($sql);
						return $rs if ($rs != 0);

						$ref = @$ref[0];

						if (@$ref[0] == 1) {
							$pt = 3;
						} else {
							$pt = 4;
						}
					}
				}

				if($pt == 1) {
					$sql = "
						SELECT
							CONVERT(`t1`.`mail_auto_respond_text` using utf8)
						FROM
							`mail_users` AS `t1`
						LEFT JOIN (`domain` AS `t2`) ON (t1.`domain_id` = t2.`domain_id`)
						WHERE
							`t1`.`mail_acc` = '$user'
						AND
							`t1`.`mail_auto_respond` = 1
						AND
							`t2`.`domain_name` = '$edmn'
						AND
							`t1`.`sub_id` = 0
						;
					";

				} elsif($pt == 2) {
					$sql = "
						SELECT
							CONVERT(`t1`.`mail_auto_respond_text` using utf8)
						FROM
							`mail_users` AS `t1`
						LEFT JOIN (`domain_aliasses` AS `t2`) ON (`t1`.`sub_id` = t2.`alias_id`)
						WHERE
							`t1`.`mail_acc` = '$user'
						AND
							`t1`.`mail_auto_respond` = 1
						AND
							`t2`.`alias_name` = '$edmn'
						;
					";

				} elsif($pt == 3) {
					$sql = "
						SELECT
							CONVERT(`t1`.`mail_auto_respond_text` using utf8)
						FROM
							`mail_users` AS `t1`
						LEFT JOIN (`subdomain` AS `t2`) ON `t1`.`sub_id` = `t2`.`subdomain_id`
						LEFT JOIN (`domain` AS `t3`) ON `t2`.`domain_id`= `t3`.`domain_id`
						WHERE
							`t1`.`mail_acc` = '$user'
						AND
							`t1`.`mail_auto_respond`=1
						AND
							(CONCAT(t2.`subdomain_name`, '.', `t3`.`domain_name`) = '$edmn')
						;
					";

				} elsif ($pt == 4) {
					$sql = "
						SELECT
							CONVERT(t1.`mail_auto_respond_text` using utf8)
						FROM
							`mail_users` AS `t1`
						LEFT JOIN (`subdomain_alias` AS `t2`) ON (`t1`.`sub_id` = `t2`.`subdomain_alias_id`)
						LEFT JOIN (`domain_aliasses` AS `t3`) ON (`t2`.`alias_id` = `t3`.`alias_id`)
						WHERE
							`t1`.`mail_acc` = '$user'
						AND
							`t1`.`mail_auto_respond`= 1
						AND
							(CONCAT(`t2`.`subdomain_alias_name`, '.', `t3`.`alias_name`) = '$edmn')
						;
					";
				}

				push_el(\@main::el, 'arpl_msgr_engine()', 'sql: |' . $sql . '|');

				($rs, $ref) = doSQL($sql);
				return $rs if ($rs != 0);

				$ref = @$ref[0];
				my $auto_message = @$ref[0];

				if (length($auto_message) > 0) {
					if ($name) {
						$mail_to = "\"" . $name . "\" " . "<" .
							$to_ma->address . ">";
					} else {
						$mail_to = $to_ma->address;
					}

					$mail_to=~s/\@ispcp-arpl./\@/;

					# Detect duplicates within 24h to avoid autoreplying loops
					$sql = "
						SELECT
							`time`
						FROM
							`autoreplies_log` AS `al`
						WHERE
							`al`.`from` = " . $main::db->quote($mail_to) . "
						AND
							`al`.`to` = " . $main::db->quote($head->get('From')) . "
						AND
							ADDTIME(al.`time`, '24:00:00') > NOW()
						;
					";

					push_el(
						\@main::el, 'arpl_msgr_engine()', 'sql: |' . $sql . '|'
					);

					($rs, $ref) = doSQL($sql);
					return $rs if ($rs != 0);

					if ( @$ref > 0 ) {
						# Loop detected
						next;
					}

					my $out = new MIME::Entity;

					$out->build(
						From => $mail_to,
						To => $head -> get('From'),
						Subject => "[Autoreply] ".$head -> get('Subject'),
						Type => "multipart/mixed; charset=utf-8",
						'X-Autoresponse-From' => $mail_to,
						'X-Mailer' =>
							"ispCP $main::cfg{'Version'} Autoreply Manager"
					);

					$out->attach(
						Type => "text/plain; charset=utf-8",
						Encoding => "7bit",
						Description => "Mail User Autoreply Message",
						Data => $auto_message
					);

					$out->attach(
						Type => "message/rfc822",
						Description => "Original Message",
						Data => $msg
					);

					open MAIL, "| /usr/sbin/sendmail -t -oi";
					$out -> print(\*MAIL);
					close MAIL;

					# Log the autoreply
					$sql = "
						INSERT INTO
							`autoreplies_log` (
								`time`, `from`, `to`
							) VALUES (
								NOW(),
								" . $main::db->quote($mail_to) . ",
								" . $main::db->quote($head->get('From')) . "
							)
						;
					";

					push_el(
						\@main::el,
						'arpl_msgr_engine()',
						'sql: |' . $sql . '|'
					);

					($rs, $ref) = doSQL($sql);
					return $rs if ($rs != 0);
				}

				push_el(\@main::el, 'arpl_msgr_engine()', 'Ending...');

			} else {
				$buffer = $to_ma->address;
				$buffer =~ s/"//g;
			}
		}
	}

	0;
}

$rs = undef;

$rs = arpl_msgr_start_up();

if ($rs != 0) {
	dump_el(\@main::el, $main::ispcp_arpl_msgr_el);

	arpl_msgr_shut_down();

	exit 1;
}

$rs = arpl_msgr_engine();

if ($rs != 0) {
	dump_el(\@main::el, $main::ispcp_arpl_msgr_el);

	arpl_msgr_shut_down();

	exit 1;
}

$rs = arpl_msgr_shut_down();

if ($rs != 0) {
	dump_el(\@main::el, $main::ispcp_arpl_msgr_el);

	exit 1;
}

exit 0;
