Current File : /home/inlingua/public_html/decay_sym/root/var/softaculous/apps/exim/configure.php
<?php

function exim_configure(){
	
global $globals;
	
	$exim_config_path = $globals['var_conf'].'/exim';
	$config_arr = loaddata($exim_config_path.'/exim.json');
	$greylist_arr = loaddata($exim_config_path.'/greylist.json');
	$rbl_arr = loaddata($globals['var_conf'].'/rbl');
	
	$grp = 'exim';
	
	$config = '
# DO NOT EDIT webuzo autogenerated file

######################################################################
#                 Exim variables 
######################################################################

hostlist loopback = <; @[]; 127.0.0.0/8 ; 0.0.0.0 ; localhost ; ::1 ; 0000:0000:0000:0000:0000:ffff:7f00:0000/8

hostlist senderverifybypass_hosts = net-iplsearch;/etc/senderverifybypasshosts

hostlist skipsmtpcheck_hosts = net-iplsearch;/etc/skipsmtpcheckhosts

hostlist spammeripblocks = net-iplsearch;/etc/spammeripblocks

hostlist blocked_incoming_email_country_ips = ${if exists{/etc/blocked_incoming_email_country_ips} {net-iplsearch;/etc/blocked_incoming_email_country_ips} {} }

hostlist backupmx_hosts = lsearch;/etc/backupmxhosts

hostlist trustedmailhosts = lsearch;/etc/trustedmailhosts

hostlist recent_authed_mail_ips = net-iplsearch;/etc/recent_authed_mail_ips

hostlist neighbor_netblocks = net-iplsearch;/etc/neighbor_netblocks

hostlist greylist_trusted_netblocks = net-iplsearch;/etc/greylist_trusted_netblocks

hostlist greylist_common_mail_providers = net-iplsearch;/etc/greylist_common_mail_providers

hostlist recent_recipient_mail_server_ips = net-iplsearch;/etc/recent_recipient_mail_server_ips

domainlist local_domains = lsearch;/etc/localdomains

domainlist user_domains = ${if exists{/etc/userdomains} {lsearch;/etc/userdomains} fail}

domainlist secondarymx_domains = lsearch;/etc/secondarymx

domainlist relay_domains = +local_domains : +secondarymx_domains

domainlist blocked_domains = wildlsearch;/etc/blocked_incoming_email_domains

domainlist manualmx_domains = ${if exists {/etc/manualmx} {lsearch;/etc/manualmx} {} }

localpartlist path_safe_localparts = \N^\.*[^./][^/]*$\N

smtp_accept_queue_per_connection = 30

remote_max_parallel = 10

smtp_receive_timeout = 165s

ignore_bounce_errors_after = 1d

rfc1413_query_timeout = 0s

timeout_frozen_after = 5d

auto_thaw = 7d

callout_domain_negative_expire = 1h

callout_negative_expire = 1h

acl_not_smtp = acl_not_smtp

acl_smtp_connect = acl_smtp_connect

acl_smtp_data = acl_smtp_data

acl_smtp_helo = acl_smtp_helo

acl_smtp_mail = acl_smtp_mail

acl_smtp_quit = acl_smtp_quit

acl_smtp_notquit = acl_smtp_notquit

acl_smtp_rcpt = acl_smtp_rcpt

acl_smtp_dkim = acl_smtp_dkim

USER_ON_BLACKLIST=User account is not allowed to send/recieve emails. User is suspended.

message_body_newlines = true

check_rfc2047_length = false

keep_environment = X-SOURCE : X-SOURCE-ARGS : X-SOURCE-DIR

add_environment = PATH=/usr/local/sbin::/usr/local/bin::/sbin::/bin::/usr/sbin::/usr/bin::/sbin::/bin

chunking_advertise_hosts = 198.51.100.1

deliver_queue_load_max = '.(!empty($config_arr['general']['deliver_queue_load_max']) ? $config_arr['general']['deliver_queue_load_max'] : 12).'

queue_only_load = '.(!empty($config_arr['general']['queue_only_load']) ? $config_arr['general']['queue_only_load'] : 24).'
';

if(!empty($config_arr['general']['daemon_smtp_ports'])){
	$config .= '
daemon_smtp_ports = '.$config_arr['general']['daemon_smtp_ports'].'
';
}else{
	$config .= '
daemon_smtp_ports = 25 : 465 : 587
';
}

if(!empty($config_arr['general']['tls_on_connect_ports'])){
	$config .= '
tls_on_connect_ports = '.$config_arr['general']['tls_on_connect_ports'].'
';
}else{
	$config .= '
tls_on_connect_ports = 465
';
}

if(!empty($config_arr['general']['message_size_limit'])){
	$config .= '
message_size_limit = '.$config_arr['general']['message_size_limit'].'M
';
}

if(!empty($config_arr['security']['openssl_options_control'])){
	$config .= '
openssl_options = '.$config_arr['security']['openssl_options_control'].'
';
}

if(!empty($config_arr['security']['tls_require_ciphers_control']) && empty($config_arr['security']['allowweakciphers'])){
	$config .= '
tls_require_ciphers = '.$config_arr['security']['tls_require_ciphers_control'].'
';
}

if(!empty($config_arr['mail']['dsn_advertise_hosts_control'])){
	$config .= '
dsn_advertise_hosts = '.$config_arr['mail']['dsn_advertise_hosts_control'].'
';
}

if(!empty($config_arr['general']['timezone'])){
	$config .= '
timezone = '.$config_arr['general']['timezone'].'
';
}

	$config .= '
spamd_address = 127.0.0.1 783 retry=30s tmo=3m

BADCHARS = \N[^A-Za-z0-9_.-]+\N
SAFELOCALPART = ${lookup{${sg{$local_part}{BADCHARS}{_}}} lsearch*,ret=key{/etc/userdomains}}
SAFEDOMAIN = ${lookup{${sg{$domain}{BADCHARS}{_}}} lsearch*,ret=key{/etc/userdomains}}

tls_certificate = ${if and \
    { \
        {gt{$tls_in_sni}{}} \
        {!match{$tls_in_sni}{/}} \
    } \
    {${if exists {/var/webuzo-data/certs/$tls_in_sni.pem} \
        {/var/webuzo-data/certs/$tls_in_sni.pem} \
        {${if exists {${sg{/var/webuzo-data/certs/$tls_in_sni.pem}{(.+/)[^.]+\.(.+\.pem)}{\$1\$2}}} \
            {${sg{/var/webuzo-data/certs/$tls_in_sni.pem}{(.+/)[^.]+\.(.+\.pem)}{\$1\$2}}} \
            {/etc/exim/webuzo.crt} \
        }}  \
    }} \
    {/etc/exim/webuzo.crt} \
}


tls_privatekey = ${if and \
    { \
        {gt{$tls_in_sni}{}} \
        {!match{$tls_in_sni}{/}} \
    } \
    {${if exists {/var/webuzo-data/certs/$tls_in_sni.pem} \
        {/var/webuzo-data/certs/$tls_in_sni.pem} \
        {${if exists {${sg{/var/webuzo-data/certs/$tls_in_sni.pem}{(.+/)[^.]+\.(.+\.pem)}{\$1\$2}}} \
            {${sg{/var/webuzo-data/certs/$tls_in_sni.pem}{(.+/)[^.]+\.(.+\.pem)}{\$1\$2}}} \
            {/etc/exim/webuzo.key} \
        }} \
    }} \
    {/etc/exim/webuzo.key} \
}
';

if(!empty($config_arr['general']['log_selector'])){
	$config .= '
log_selector = '.$config_arr['general']['log_selector'].'
';
}else{
	$config .= '
log_selector = +subject +arguments +received_recipients
';
}

if(!empty($config_arr['filter']['systemfilter_control'])){
	$config .='
system_filter = '.$config_arr['filter']['systemfilter_control'].'
';
}else{
	$config .='
system_filter = /etc/exim/exim_system_filter
';
}


	$config .= '

addresslist secondarymx = *@partial-lsearch;/etc/secondarymx

######################################################################
#                    MAIN CONFIGURATION SETTINGS                     #
######################################################################

perl_startup = do \'/etc/exim/exim.pl\'

smtp_banner = "${primary_hostname} ESMTP Exim ${version_number} \
\#${compile_number} ${tod_full} \n\
    We do not authorize the use of this system to transport unsolicited, \n\
    and/or bulk e-mail."


#nobody as the sender seems to annoy people
untrusted_set_sender = *
local_from_check = '.(!empty($config_arr['mail']['setsenderheader']) ? 'true' : 'false').'

split_spool_directory = yes

smtp_connect_backlog = 50

smtp_accept_max = '.(!empty($config_arr['general']['max_smtp_conn_accept']) ? $config_arr['general']['max_smtp_conn_accept'] : '500').'
';

if(!empty($config_arr['general']['exim_primary_hostname'])){
	$config .='
primary_hostname = '.$config_arr['general']['exim_primary_hostname'].'
';
}

$config .= '
message_body_visible = 5000

never_users = root

tls_advertise_hosts = *

helo_accept_junk_hosts = *

smtp_enforce_sync = false
';
if(!empty($config_arr['general']['disable_ipv6'])){
	$config .='
disable_ipv6 = true
';
}
$config .= '

######################################################################
#                 DO NOT EDIT Exim Webuzo Acl 
######################################################################

begin acl

acl_not_smtp:
';

if(!empty($config_arr['sa']['acl_outgoing_spam_scan']) || !empty($config_arr['sa']['acl_outgoing_spam_scan_over_int_control'])){
	$config .= '#acl_outgoing_spam_scan
warn
        condition   = ${if forany{<, $recipients}{!match_domain{${domain:$item}}{:+relay_domains}}}
        set acl_m_outbound_recipient = 1

warn
        condition   = $acl_m_outbound_recipient
        condition   = ${if <={$message_size}{'.((int)$config_arr['sa']['max_spam_scan_size_control']).'K}}
        condition   = ${if !eq{$originator_uid}{0}}
        condition   = ${perl{spamd_is_available}}
        set acl_m_spam_scan_enabled  = 1

deny
        condition   = $acl_m_outbound_recipient
        condition   = $acl_m_spam_scan_enabled
';

		if(!empty($config_arr['sa']['acl_outgoing_spam_scan_over_int_control'])){
			$config .= '
        spam        = exim:true/defer_ok
        condition   = ${if !eq{$spam_score_int}{}}
        condition   = ${if >{$spam_score_int}{'.((int)$config_arr['sa']['acl_outgoing_spam_scan_over_int_control'] * 10).'}}
';
		}else{
			
			$config .= '
		spam        = exim/defer_ok
';

		}
		
		$config .= '
        message     = This message was classified as SPAM and may not be delivered
        log_message = "SpamAssassin as exim detected OUTGOING not smtp message as spam ($spam_score)"

warn
        condition   = $acl_m_outbound_recipient
        condition   = $acl_m_spam_scan_enabled
        log_message = "SpamAssassin as exim detected OUTGOING not smtp message as NOT spam ($spam_score)"
';
}

if(!empty($config_arr['mail']['trust_x_php_script']) || !empty($config_arr['mail']['query_apache_for_nobody_senders'])){
	
$config .='#trust_x_php_script
warn
        condition   = ${if eq{$originator_uid}{${perl{user2uid}{nobody}}}{1}{0}}
        set acl_c_vhost_owner = ${perl{resolve_vhost_owner}}
';	
}
	$config .= '
	accept
acl_not_smtp_mime:
	
	accept
acl_not_smtp_start:
	
	accept
acl_smtp_auth:
	
	accept
acl_smtp_connect:

drop
    message = Your country is not allowed to connect to this server.
    log_message = Country is banned
    hosts = +blocked_incoming_email_country_ips
';

if(!empty($config_arr['acl']['delay_unknown_hosts'])){
	$config .= '#delay_unknown_hosts
warn
    !hosts = : +loopback : +neighbor_netblocks : +trustedmailhosts : +recent_authed_mail_ips : +backupmx_hosts : +skipsmtpcheck_hosts : +senderverifybypass_hosts '.(!empty($config_arr['acl']['dont_delay_greylisting_trusted_hosts']) ? ': +greylist_trusted_netblocks' : '').' '.(!empty($config_arr['acl']['dont_delay_greylisting_common_mail_providers']) ? ': +greylist_common_mail_providers' : '').'
    #only rate limit port 25
    condition = ${if eq {$received_port}{25}{yes}{no}}
    delay = 20s
';
}

if(!empty($config_arr['acl']['ratelimit'])){
	
	$config .= '#ratelimit
accept
	hosts = : +loopback : +recent_authed_mail_ips : +backupmx_hosts

accept
	hosts = +trustedmailhosts

accept
	condition = ${if match_ip{$sender_host_address}{net-iplsearch;/etc/trustedmailhosts}{1}{0}}

defer
	#only rate limit port 25
	condition = ${if eq {$received_port}{25}{yes}{no}}
	message = The server has reached its limit for processing requests from your host.  Please try again later.
	log_message = "Host is ratelimited ($sender_rate/$sender_rate_period max:$sender_rate_limit)"
	ratelimit = 1.2 / 1h / strict / per_conn / noupdate
';

}

if(!empty($config_arr['acl']['slow_fail_block'])){
	$config .= '#slow_fail_block
warn
	#only rate limit port 25
	condition = ${if eq {$received_port}{25}{yes}{no}}
	# host had a success in the last hour
	ratelimit = 1 / 1h / noupdate / per_conn / slow_fail_accept_$sender_host_address
	set acl_m4 = 1

defer
	#only rate limit port 25
	condition = ${if eq {$received_port}{25}{yes}{no}}
	condition = ${if eq {${acl_m4}}{1}{0}{1}}
	log_message = "Host is ratelimited due to multiple failure only connections ($sender_rate/$sender_rate_period max:$sender_rate_limit)"
	ratelimit = 5 / 1h / noupdate / per_conn / slow_fail_block_$sender_host_address
';

}

$config .= '

drop
    message = Your host is not allowed to connect to this server.
    log_message = Host is banned
    !hosts = : +skipsmtpcheck_hosts : +trustedmailhosts
    hosts = +spammeripblocks

accept

acl_smtp_data:
';

if(!empty($config_arr['sa']['acl_outgoing_spam_scan']) || !empty($config_arr['sa']['acl_outgoing_spam_scan_over_int_control'])){
	$config .= '#acl_outgoing_spam_scan
warn
        condition   = ${if forany{<, $recipients}{!match_domain{${domain:$item}}{:+relay_domains}}}
        set acl_m_outbound_recipient = 1

warn
        condition   = $acl_m_outbound_recipient
        condition   = ${if <={$message_size}{'.((int)$config_arr['sa']['max_spam_scan_size_control']).'K}}
        condition   = ${if !eq{$originator_uid}{0}}
        condition   = ${perl{spamd_is_available}}
        set acl_m_spam_scan_enabled  = 1

deny
        condition   = $acl_m_outbound_recipient
        condition   = $acl_m_spam_scan_enabled
';

		if(!empty($config_arr['sa']['acl_outgoing_spam_scan_over_int_control'])){
			$config .= '
        spam        = exim:true/defer_ok
        condition   = ${if !eq{$spam_score_int}{}}
        condition   = ${if >{$spam_score_int}{'.((int)$config_arr['sa']['acl_outgoing_spam_scan_over_int_control'] * 10).'}}
';
		}else{
			
			$config .= '
		spam        = exim/defer_ok
';

		}
		
		$config .= '
        message     = This message was classified as SPAM and may not be delivered
        log_message = "SpamAssassin as exim detected OUTGOING not smtp message as spam ($spam_score)"

warn
        condition   = $acl_m_outbound_recipient
        condition   = $acl_m_spam_scan_enabled
        log_message = "SpamAssassin as exim detected OUTGOING not smtp message as NOT spam ($spam_score)"
';
}
	$config .= '
accept  hosts = : +loopback : +recent_authed_mail_ips : +backupmx_hosts

accept
		authenticated = *
		hosts = *

accept
		condition = ${extract{size}{${stat:/etc/trustedmailhosts}}}
		hosts = +trustedmailhosts

accept
		condition = ${extract{size}{${stat:/etc/trustedmailhosts}}}
		condition = ${if match_ip{$sender_host_address}{net-iplsearch;/etc/trustedmailhosts}{1}{0}}
		
warn
	# Remove spam headers from outside sources
	condition = ${perl{spamd_is_available}}
	!hosts = +skipsmtpcheck_hosts
	remove_header  = x-spam-subject : x-spam-status : x-spam-score : x-spam-bar : x-spam-report : x-spam-flag : x-ham-report


warn
	condition = ${perl{spamd_is_available}}
	condition = ${if eq {${acl_m0}}{1}{1}{0}}
	spam =  ${acl_m1}'.(!empty($config_arr['mail']['spam_deferok']) ? '/defer_ok' : '').'
	!hosts = : +trustedmailhosts
	log_message = "SpamAssassin as ${acl_m1} detected message as spam ($spam_score)"
	add_header = X-Spam-Subject: '.(!empty($config_arr['filter']['spam_header_control']) ? $config_arr['filter']['spam_header_control'] : '***SPAM***').' $rh_subject
	add_header = X-Spam-Status: Yes, score=$spam_score
	add_header = X-Spam-Score: $spam_score_int
	add_header = X-Spam-Bar: $spam_bar
	add_header = X-Spam-Report: ${sg{$spam_report}{\N\n \n\N}{\n}}
	add_header = X-Spam-Flag: YES
	set acl_m2 = 1

warn
	condition = ${perl{spamd_is_available}}
	condition =  ${if eq {$spam_score_int}{}{0}{${if <= {${spam_score_int}}{8000}{${if >= {${spam_score_int}}{50}{${perl{store_spam}{$sender_host_address}{$spam_score}}}{0}}}{0}}}}

warn
	condition = ${perl{spamd_is_available}}
	condition = ${if eq {${acl_m0}}{1}{${if eq {${acl_m2}}{1}{0}{1}}}{0}}
	add_header = X-Spam-Status: No, score=$spam_score
	add_header = X-Spam-Score: $spam_score_int
	add_header = X-Spam-Bar: $spam_bar
	add_header = X-Ham-Report: ${sg{$spam_report}{\N\n \n\N}{\n}}
	add_header = X-Spam-Flag: NO
	log_message = "SpamAssassin as ${acl_m1} detected message as NOT spam ($spam_score)"
';
if(!empty($config_arr['acl']['ratelimit_spam_score_over_int_control'])){
	
	  $config .= '#ratelimit_spam_score_over_int_control
warn
    condition = ${if eq {${acl_m0}}{1}{${if >{$spam_score_int}{'.((int)$config_arr['acl']['ratelimit_spam_score_over_int_control']*10).'}{1}{0}}}{0}}
    ratelimit = 0 / 1h / strict / per_conn
    log_message = "Increment Connection Ratelimit - $sender_fullhost because mail server detected a message with a spam score integer greater or equal to '.((int)$config_arr['acl']['ratelimit_spam_score_over_int_control']*10).'"
';
}

if(!empty($config_arr['acl']['spam_thresold'])){
	
	  $config .= '#spam_thresold
deny
    condition = ${if eq {${acl_m0}}{1}{${if >{$spam_score_int}{'.((int)$config_arr['acl']['spam_thresold']*10).'}{1}{0}}}{0}}
    log_message = "The mail server detected your message as spam and has prevented delivery ('.((int)$config_arr['acl']['spam_thresold']*10).')."
    message = "The mail server detected your message as spam and has prevented delivery."
';
}

if(!empty($config_arr['sa']['no_forward_outbound_spam']) || !empty($config_arr['sa']['no_forward_outbound_spam_over_int_control'])){
	$config .= '
# BEGIN INSERT no_forward_outbound_spam

deny
';
	if(!empty($config_arr['sa']['no_forward_outbound_spam_over_int_control'])){
		
		$config .= '
	condition = ${if eq {$spam_score_int}{}{0}{${if >{$spam_score_int}{'.((int)$config_arr['sa']['no_forward_outbound_spam_over_int_control'] * 10).'}{1}{0}}}}
';

	}else{
		
		$config .= '
	condition = ${if eq {${acl_m2}}{1}{1}{0}}
';
	}
	
	$config .= '
  condition = ${if eq {$acl_c_delivery_address_data}{}{0}{1}}

  # Don’t reject messages where any forwarder has a local destination.
  # Ideally we would reject the remote destinations and accept the local,
  # but there is no known way of achieving this configuration.
  !condition = ${if \
    forany{ ${addresses:$acl_c_delivery_address_data} } \
    { match_domain{${domain:$item}}{+local_domains} } \
  }

  # Don’t reject messages where every destination is an autoresponder.
  !condition = ${if \
    forall{ ${addresses:$acl_c_delivery_address_data} } \
    { match{$item}{/autorespond} } \
  }

  log_message = "This mail cannot be forwarded because it was detected as spam."
  message = "This mail cannot be forwarded because it was detected as spam."

# END INSERT no_forward_outbound_spam	
';

}

$config .= '

drop
	message = This message is denied by policy : $spam_score spam points
	log_message = This message is denied by policy : $spam_score spam points 
	condition = ${if <= {5}{${lookup{${acl_m1}}lsearch{/etc/spamscore}{$value}}}{1}{0}}
	condition = ${if > {$spam_score_int}{${lookup{${acl_m1}}lsearch{/etc/spamscore}{$value}}}{1}{0}}

accept

acl_smtp_etrn:

accept
acl_smtp_helo:

accept

acl_smtp_mail:

#hold outgoing mail
accept
	condition = ${lookup{$sender_address}lsearch{/etc/hold_outgoing_users}{1}{0}}
	control   = freeze/no_tell

# ignore authenticated hosts
accept
	authenticated = *

#warn
#	condition = ${if match_ip{$sender_host_address}{+loopback}{${perl{identify_local_connection}{$sender_host_address}{$sender_host_port}{$received_ip_address}{$received_port}{1}}}{0}}
#	set acl_c_authenticated_local_user = ${perl{get_identified_local_connection_user}}

accept
	hosts = : +loopback : +recent_authed_mail_ips : +backupmx_hosts
	
';
if(!empty($config_arr['acl']['requirehelo'])){
	$config .= '#requirehelo
deny
    condition = ${if eq{$sender_helo_name}{}}
    message   = HELO required before MAIL
';
}

if(!empty($config_arr['acl']['requirehelonoforge'])){
	
	$config .= '#requirehelonoforge
drop
    condition = ${if eq{${lc:$sender_helo_name}}{${lc:$primary_hostname}}{${if def:interface_address {${if match_ip{$interface_address}{+loopback}{0}{1}}}{0}}}{0}}
    message   = "REJECTED - Bad HELO - Host impersonating [$sender_helo_name]"


drop
    condition = ${if eq{[$interface_address]}{$sender_helo_name}}
    message   = "REJECTED - Interface: $interface_address is _my_ address"
';
}

if(!empty($config_arr['acl']['requirehelosyntax'])){
	
	$config .= '#requirehelosyntax
drop
    condition   = ${if isip{$sender_helo_name}}
    message     = Access denied - Invalid HELO name (See RFC2821 4.1.3)

drop
    # Required because "[IPv6:<address>]" will have no .s
    condition   = ${if match{$sender_helo_name}{\N^\[\N}{no}{yes}}
    condition   = ${if match{$sender_helo_name}{\N\.\N}{no}{yes}}
    message     = Access denied - Invalid HELO name (See RFC2821 4.1.1.1)

drop
    condition   = ${if match{$sender_helo_name}{\N\.$\N}}
    message     = Access denied - Invalid HELO name (See RFC2821 4.1.1.1)

drop
    condition   = ${if match{$sender_helo_name}{\N\.\.\N}}
    message     = Access denied - Invalid HELO name (See RFC2821 4.1.1.1)
';
}

	$config .= '
   
accept

acl_smtp_mailauth:
	
	accept
acl_smtp_mime:
deny 
	message = Blacklisted file extension detected
    condition = ${if match \
					{${lc:$mime_filename}} \
					{\N(\.exe|\.pif|\.bat|\.scr|\.lnk|\.com)$\N} \
				 {1}{0}}
	accept
acl_smtp_notquit:
';

if(!empty($config_arr['acl']['ratelimit'])){
	
	$config .= '#ratelimit
# ignore authenticated hosts
accept authenticated = *

accept hosts = : +recent_authed_mail_ips : +loopback : +backupmx_hosts

warn
    #only rate limit port 25
    condition = ${if eq {$received_port}{25}{yes}{no}}
    condition = ${if match {$smtp_notquit_reason}{command}{yes}{no}}
    log_message = "Connection Ratelimit - $sender_fullhost because of notquit: $smtp_notquit_reason ($sender_rate/$sender_rate_period max:$sender_rate_limit)"
    ratelimit = 1.2 / 1h / strict / per_conn
';

}
	$config .= '
accept

acl_smtp_predata:

accept
acl_smtp_quit:
';
if(!empty($config_arr['acl']['slow_fail_block'])){
	$config .= '#slow_fail_block
warn
	log_message = "Detected session with all messages failed"
	condition = ${if >= {${eval:$rcpt_count}}{1}{${if == {${eval:$rcpt_fail_count}}{${eval:$rcpt_count}}{yes}{no}}}{no}}
	set acl_m6 = 1

warn
	condition = ${if eq {${acl_m6}}{1}{1}{0}}
	ratelimit = 0 / 1h / strict / per_conn / slow_fail_block_$sender_host_address
	log_message = "Increment slow_fail_block Ratelimit - $sender_fullhost because of all messages failed"

warn
	ratelimit = 1 / 1h / noupdate / per_conn / slow_fail_block_$sender_host_address
	condition = ${if >= {${eval:$rcpt_count}}{1}{${if < {${eval:$rcpt_fail_count}}{${eval:$rcpt_count}}{yes}{no}}}{no}}
	set acl_m5 = 1
	log_message = "Detected session with ok message that previous had all failed"

warn
	condition = ${if eq {${acl_m5}}{1}{1}{0}}
	ratelimit = 0 / 1h / strict / per_conn / slow_fail_accept_$sender_host_address
	log_message = "Decrement slow_fail_lock Ratelimit - $sender_fullhost because one message was successful"
';
}
	$config .= '
	accept
	
acl_smtp_rcpt:

# implemented for "suspend incoming/outgoing email" feature for user
deny
	condition   = ${lookup{${lookup{$sender_address_domain}lsearch{/etc/userdomains}{$value}}}lsearch{/etc/user_suspended_list}{1}{0}}
	message     = USER_ON_BLACKLIST
	log_message = USER_ON_BLACKLIST

deny
	condition   = ${lookup{${lookup{$domain}lsearch{/etc/userdomains}{$value}}}lsearch{/etc/user_suspended_list}{1}{0}}
	message     = USER_ON_BLACKLIST
	log_message = USER_ON_BLACKLIST


# deny suspend_outgoing_users
deny
	message = The $sender_address is suspended to send an outgoing mail. Please contact admin to unsuspend
	log_message = The $sender_address is suspended to send an outgoing mail. Please contact admin to unsuspend
	senders = lsearch;/etc/suspend_outgoing_users

# deny suspend_incoming_users
deny
	message = The $local_part@$domain is suspended to receive any incoming mail.
	log_message = The $local_part@$domain is suspended to receive any incoming mail.
	condition   = ${if exists {/etc/exim/users/${lookup{$domain}lsearch{/etc/userdomains}{$value}}/.${sg{$local_part}{\N[/+].*\N}{}}@${domain}.suspended_incoming}}

';

if(!empty($config_arr['mail']['tracksenders'])){
	$config .= '#tracksenders
warn 
	ratelimit = 0 / 1h / strict
    log_message = Sender rate $sender_rate / $sender_rate_period
';
}
	$config .= '
warn
	!domains = +relay_domains
	set acl_m_outbound_recipient = 1
	
';

if(!empty($config_arr['acl']['delay_unknown_hosts'])){
	$config .= '#delay_unknown_hosts
warn
	!authenticated = *
	!hosts = : +loopback : +neighbor_netblocks : +trustedmailhosts : +recent_authed_mail_ips : +backupmx_hosts : +skipsmtpcheck_hosts : +senderverifybypass_hosts '.(!empty($config_arr['acl']['dont_delay_greylisting_trusted_hosts']) ? ': +greylist_trusted_netblocks' : '').' '.(!empty($config_arr['acl']['dont_delay_greylisting_common_mail_providers']) ? ': +greylist_common_mail_providers' : '').'
	#only rate limit port 25
	condition = ${if eq {$received_port}{25}{yes}{no}}
	delay = 20s
';
}

if(!empty($config_arr['acl']['dkim_disable'])){
	$config .= '#dkim_disable
warn
	control = dkim_disable_verify
';
}

if(!empty($config_arr['sa']['no_forward_outbound_spam']) || !empty($config_arr['sa']['no_forward_outbound_spam_over_int_control'])){
	
	$config .= '#no_forward_outbound_spam
warn
	domains = +local_domains
	verify = recipient
	log_message = ${extract{redirect}{$address_data}}
	condition = ${if !eq{${extract{redirect}{$address_data}}}{}}
	condition = ${if forany{${addresses:${extract{redirect}{$address_data}}}}{!match_domain{${domain:$item}}{:+local_domains}}}
	set acl_m_outbound_recipient = 1
';
}

$config .= '
accept
	authenticated = *
	condition = ${if eq{${lookup{$sender_address_domain}lsearch{/etc/userdomains}}}{$sender_address_local_part}}
	endpass
	verify = recipient
';

if(!empty($config_arr['mail']['senderverify'])){
	
	$config .= '#senderverify
deny hosts = ! +loopback : ! +senderverifybypass_hosts
	! verify = sender'.(!empty($config_arr['mail']['callouts']) ? '/callout=60s' : '').'
';
}

	$config .= '
accept
	authenticated = *
	endpass
	verify = recipient

# if they used "pop before smtp" then we just accept
accept
	condition = ${if exists{/etc/popbeforesmtp}{1}{0}}
	condition = ${if exists{'.$globals['data_path'].'/popb4smtp/${substr_-1_1:$sender_host_address}/$sender_host_address}}
	hosts = ! +loopback
	endpass
	verify = recipient
';

if(!empty($rbl_arr)){
	$config .= '
# BEGIN RBL'."\n";
	foreach($rbl_arr as $rblk => $rblv){
		if(!empty($rblv['status'])){
			$config .= '
# BEGIN INSERT '.$rblk.'

deny 
	message = JunkMail rejected - $sender_fullhost is in an RBL: $dnslist_text
	hosts = +backupmx_hosts
	dnslists = '.(implode(' : ', array_map('trim', explode(',', $rblv['dnslists'])))).'

warn';
        if(!empty($config_arr['rbl']['rbl_whitelist'])){
            $config .= '
    !hosts = <, '.$config_arr['rbl']['rbl_whitelist'];
        }

        if(!empty($config_arr['rbl']['rbl_whitelist_neighbor_netblocks'])){
            $config .= '
    !hosts = +neighbor_netblocks';
        }

        if(!empty($config_arr['rbl']['rbl_whitelist_greylist_common_mail_providers'])){
        	$config .= '
    !hosts = +greylist_common_mail_providers';
        }

        if(!empty($config_arr['rbl']['rbl_whitelist_greylist_trusted_hosts'])){
            $config .= '
    !hosts = +greylist_trusted_netblocks';
        }
        
        $config .='
	dnslists = '.(implode(' : ', array_map('trim', explode(',', $rblv['dnslists'])))).'
	set acl_m8 = 1
	set acl_m9 = "JunkMail rejected - $sender_fullhost is in an RBL: $dnslist_text"

warn
	condition = ${if eq {${acl_m8}}{1}{1}{0}}
	ratelimit = 0 / 1h / strict / per_conn
	log_message = "Increment Connection Ratelimit - $sender_fullhost because of RBL match"

drop
	condition = ${if eq {${acl_m8}}{1}{1}{0}}
	message = ${acl_m9}


# END INSERT '.$rblk;
		}
	}
	$config .= "\n".'# END of RBL';
}

if(!empty($globals['greylisting'])){
    $config .= '
#greylisting is enabled
defer
	message = Temporarily unable to process your email. Please try again later.
	!authenticated = *';
	if(!empty($greylist_arr['spf'])){
		$config .= '
	!spf = pass';
	}
	
$config .= '
	!hosts = +loopback : +greylist_trusted_netblocks : +greylist_common_mail_providers
	condition = ${lookup{$sender_address,$local_part@$domain,$sender_host_address}lsearch{/etc/greylist_triplet}{0}{1}}
	condition = ${lookup{$domain}lsearch{/etc/greylist_outdomains}{0}{1}}
	log_message = Deferred due to greylisting. Host: $sender_host_address From: $sender_address To: $local_part@$domain
';
}

$config .= '
deny
	message = Your host is not allowed to connect to this server.
	log_message = Sender domain is banned
	sender_domains = !+local_domains : +blocked_domains

deny
	message = Mailbox is full / Blocks limit exceeded / Inode limit exceeded
	log_message = Mailbox is full / Blocks limit exceeded / Inode limit exceeded
	condition = ${if match {${readsocket{/var/run/dovecot/quota-status}{request=smtpd_access_policy\nrecipient=${quote:$local_part}@${quote:$domain}\nsize=$message_size\n\n}{30s}{\n}{SOCKETFAIL}}}{action=5}{true}{false}}
	
accept
	hosts = :
	endpass
	verify = recipient

accept
	condition = ${extract{size}{${stat:/etc/skipsmtpcheckhosts}}}
	hosts     = +skipsmtpcheck_hosts
	endpass
	verify = recipient

# implemented for "suspend incoming email" feature
deny
	domains     = !$primary_hostname : +local_domains
	condition   = ${if exists {${extract{5}{:}{${lookup passwd{${lookup{$domain}lsearch{/etc/userdomains}}}}}{$value}}/etc/.${sg{$local_part}{\N[/+].*\N}{}}@${domain}.suspended_incoming}}
	message     = 525 5.7.13 Disabled recipient address
	log_message = Mail to ${local_part}@${domain} has been suspended

# implemented for "suspend outgoing email" feature for domains and individual webmail/pop accounts (to do)
#deny
#	domains     = ! +local_domains
#	condition   = ${perl{check_outgoing_mail_suspended}}
#	message     = ${perl{get_outgoing_mail_suspended_message}}
#	log_message = ${perl{get_outgoing_mail_suspended_message}}
';

$config .='
# if they used "pop before smtp" and its not bound for a localdomain we remember the recent_authed_mail_ips_domain
warn
	domains = ! +local_domains
	hosts = ! +loopback
	hosts = +recent_authed_mail_ips
	set acl_c_recent_authed_mail_ips_text_entry = ${perl{get_recent_authed_mail_ips_text_entry}{1}}
	add_header = ${if exists{/etc/eximpopbeforesmtpwarning}{${perl{popbeforesmtpwarn}{$sender_host_address}}}{}}

# we need to check alwaysrelay since we don\'t require recentauthedmailiptracker to be enabled
accept
	hosts = ! +loopback
	condition = ${if or {{eq{$acl_c_recent_authed_mail_ips_text_entry}{}}{!exists{/etc/popbeforesmtp}}}{${if exists {/etc/alwaysrelay}{${lookup{$sender_host_address}iplsearch{/etc/alwaysrelay}{1}{0}}}{0}}}{0}}
	set acl_c_recent_authed_mail_ips_text_entry = ${perl{get_recent_authed_mail_ips_text_entry}{1}}
	set acl_c_alwaysrelay = 1
	endpass
	verify = recipient

# Reject unauthenticated relay on port 587
drop
	condition = ${if eq{$received_port}{587}{1}{0}}
	message = SMTP AUTH is required for message submission on port 587

require
	verify = recipient

# skip content scanning for suspended recipients that are being queued, blackholed or relayed
accept
	condition = ${extract{suspended}{$address_data}}
';

if(!empty($config_arr['acl']['primary_hostname'])){
$config .='#primary_hostname
deny 
	message = You do not have sufficient privileges to send mail to this address.  Please authenticate and try again.
	domains = $primary_hostname
';
}

if(!empty($config_arr['acl']['dictionary_attack'])){
$config .='#dictionary_attack
warn
	log_message = "Detected Dictionary Attack (Let $rcpt_fail_count bad recipients though before engaging)"
	condition = ${if > {${eval:$rcpt_fail_count}}{4}{yes}{no}}
	set acl_m7 = 1

warn
	condition = ${if eq {${acl_m7}}{1}{1}{0}}
	ratelimit = 0 / 1h / strict / per_conn
	log_message = "Increment Connection Ratelimit - $sender_fullhost because of Dictionary Attack"

drop
	condition = ${if eq {${acl_m7}}{1}{1}{0}}
	message = "Number of failed recipients exceeded.  Come back in a few hours."
';
}

if(!empty($config_arr['acl']['deny_rcpt_hard_limit'])){
$config .='#deny_rcpt_hard_limit
warn
	log_message = "Number of RCPT commands exceeds hard limit"
	condition = ${if > {${eval:$rcpt_count}}{'.((int)$config_arr['acl']['deny_rcpt_hard_limit']).'}{1}{0}}
	set acl_m7 = 1

warn
	condition = ${if eq {${acl_m7}}{1}{1}{0}}
	ratelimit = 0 / 1h / strict / per_conn
	log_message = "Increment Connection Ratelimit - $sender_fullhost because of RCPT command abuse"

drop
	condition = ${if eq {${acl_m7}}{1}{1}{0}}
	message = Too many recipients specified.  Come back in a few hours.
';
}

if(!empty($config_arr['acl']['deny_rcpt_soft_limit'])){
$config .= '#deny_rcpt_soft_limit
defer
	condition = ${if > {${eval:$rcpt_count}}{'.((int)$config_arr['acl']['deny_rcpt_soft_limit']).'}{1}{0}}
	message = 452 too many recipients
';
}

$config .= '
warn
	domains    = +local_domains
	condition  = ${if <= {$message_size}{'.((int)$config_arr['sa']['max_spam_scan_size_control']).'K}}
	condition  = ${if !eq{${acl_m0}}{1}}
	condition  = ${if exists{/etc/global_spamassassin_enable}{1}{${if exists{${extract{5}{::}{${lookup passwd{${if eq{$domain}{$primary_hostname}{${sg{$local_part}{\N[/+].*\N}{}}}{${lookup{$domain}lsearch{/etc/userdomains}}}}}}}}/.spamassassindisable}{0}{1}}}}
	set acl_m0 = 1
	set acl_m1 = ${if eq{$domain}{$primary_hostname}{${sg{$local_part_data}{\N[/+].*\N}{}}}{${lookup{$domain}lsearch{/etc/userdomains}}}}
';

if(!empty($config_arr['acl']['spam_scan_secondarymx'])){
	
	$config .= '#spam_scan_secondarymx
warn  domains = ! +local_domains : +secondarymx_domains
	condition = ${if <= {$message_size}{'.((int)$config_arr['sa']['max_spam_scan_size_control']).'K}{1}{0}}
	set acl_m0    = 1
	set acl_m1    = exim
';

}

if(!empty($config_arr['acl']['delay_unknown_hosts'])){
	$config .= '#delay_unknown_hosts
warn
    #acl_m2 is spam = YES
    condition = ${if eq {${acl_m2}}{1}{1}{0}}
    !hosts = : +loopback : +neighbor_netblocks : +trustedmailhosts : +recent_authed_mail_ips : +backupmx_hosts : +skipsmtpcheck_hosts : +senderverifybypass_hosts '.(!empty($config_arr['acl']['dont_delay_greylisting_trusted_hosts']) ? ': +greylist_trusted_netblocks' : '').' '.(!empty($config_arr['acl']['dont_delay_greylisting_common_mail_providers']) ? ': +greylist_common_mail_providers' : '').'
    delay = 40s
';
}

$config .= '
accept  domains = +relay_domains

deny    message = ${expand:${lookup{host_accept_relay}lsearch{/etc/eximrejects}{$value}}}
	  log_message = Rejected relay attempt: \'$sender_host_address\' From: \'$sender_address\' To: \'$local_part@$domain\'

	accept
acl_smtp_starttls:
	
	accept
acl_smtp_vrfy:
	
	accept
acl_smtp_dkim:
';

if(empty($config_arr['acl']['dkim_disable']) && !empty($config_arr['acl']['dkim_bl'])){
	
	$config .= '
accept 
	message = DKIM: Testing Mode
	condition = ${if bool{$dkim_key_testing}}

deny 
	message = DKIM: encountered the following problem validating $dkim_cur_signer: $dkim_verify_reason
	dkim_status = invalid:fail

';
}

$config .= '
	accept
######################################################################
#                 DO NOT EDIT Exim Webuzo Aunthenticators
######################################################################

begin authenticators


dovecot_plain:
    driver = dovecot
    public_name = PLAIN
    server_socket = /var/run/dovecot/auth-client
    server_set_id = $auth1
    server_condition = ${if and {{!match {$auth1}{\N[/]\N}}{eq{${if match {$auth1}{\N[+%:@]\N}{${lookup{${extract{2}{+%:@}{$auth1}}}lsearch{/etc/demodomains}{yes}}}{${lookup{$auth1}lsearch{/etc/demousers}{yes}}}}}{}}}{true}{false}}
';
if(!empty($config_arr['security']['require_secure_auth'])){
	$config .= '
	server_advertise_condition = ${if or {{def:tls_cipher}{match_ip{$sender_host_address}{+loopback}}}{1}{0}}
';
}

$config .= '
dovecot_login:
	driver = dovecot
	public_name = LOGIN
	server_socket = /var/run/dovecot/auth-client
	server_set_id = $auth1
	server_condition = ${if and {{!match {$auth1}{\N[/]\N}}{eq{${if match {$auth1}{\N[+%:@]\N}{${lookup{${extract{2}{+%:@}{$auth1}}}lsearch{/etc/demodomains}{yes}}}{${lookup{$auth1}lsearch{/etc/demousers}{yes}}}}}{}}}{true}{false}}
';
if(!empty($config_arr['security']['require_secure_auth'])){
	$config .= '
	server_advertise_condition = ${if or {{def:tls_cipher}{match_ip{$sender_host_address}{+loopback}}}{1}{0}}
';
} 
  
$config .= '
######################################################################
#                 DO NOT EDIT Exim Webuzo Rewrite
######################################################################

# There are no rewriting specifications in this default configuration file.

begin rewrite

######################################################################
#                 DO NOT EDIT Exim Webuzo ROUTERS
######################################################################

begin routers

blackhole_dovenull:
    driver= redirect
    local_parts = "@dovenull"
    allow_fail = true
    data = :fail: Unrouteable address
	
# Check Demo user
democheck:
    driver = redirect
    require_files = "+/etc/demouids"
    condition = ${if >= {$originator_uid}{100}{1}{0}}
    condition = "${extract{size}{${stat:/etc/demouids}}}"
    condition = "${if eq \
        {${lookup \
            {$originator_uid} \
            lsearch{/etc/demouids} \
            {$value} \
        }} \
        {} \
        {false} \
        {true} \
    }"
    allow_fail
    data = :fail: demo accounts are not permitted to relay email

# check email count per hour domain or user || Check other stuff also (TODO E.G. SUSPEND DOMAIN, USER AND PERTICULAR EMAIL ACCOUNT)	
check_mail_validity:
    domains = ! +local_domains
    condition =  ${if eq {$authenticated_id}{root}{0}{1}}
    ignore_target_hosts = +loopback
    driver = redirect
    allow_fail
    #allow_filter
    allow_defer
    #reply_transport = address_reply
    no_verify
    user = "exim" 
    expn = false
    condition = "${perl{check_mail_validity}}"
    data = "${perl{check_mail_validity_results}}"
	
#
# Increments max emails per hour if needed (to do)
#
increment_email_per_hour_count:
    domains = ! +local_domains
    ignore_target_hosts = +loopback
    condition =  ${if eq {$authenticated_id}{root}{0}{1}}
    driver = redirect
    allow_fail
    no_verify
    one_time
    expn = false
    condition = "${perl{increment_email_per_hour_count_if}}"
    data = ":unknown:"
';

if(!empty($config_arr['sa']['no_forward_outbound_spam']) || !empty($config_arr['sa']['no_forward_outbound_spam_over_int_control'])){
	$config .= '#no_forward_outbound_spam
reject_forwarded_mail_marked_as_spam:
	driver = redirect
	domains = ! +local_domains
';
	if(!empty($config_arr['sa']['no_forward_outbound_spam_over_int_control'])){
		
		$config .= '
	condition = ${if eq {$spam_score_int}{}{0}{${if >{$spam_score_int}{'.((int)$config_arr['sa']['no_forward_outbound_spam_over_int_control'] * 10).'}{1}{0}}}}
';

	}else{
		
		$config .= '
	condition = ${if eq {${acl_m2}}{1}{1}{0}}
';
	}
	
	$config .= '
	#ignore verisign to prevent waste of bandwidth
	ignore_target_hosts = +loopback : 64.94.110.0/24
	allow_fail
	data = :fail: This mail cannot be forwarded because it was detected as spam.
';
}

	$config .= '
manualmx:
    driver = manualroute
    domains = +manualmx_domains
    transport = remote_smtp
    route_data = ${lookup \
        {$domain} \
        lsearch{/etc/manualmx} \
    }
	
autoreply_dkim_lookuphost:
    driver = dnslookup
    domains = ! +local_domains
    condition = "${perl{sender_domain_can_dkim_sign}}"
    condition = "${if \
        or { \
            {match{$h_precedence:}{auto}} \
            {match{$h_x-precedence:}{auto}} \
        } \
        {1}{0} \
    }"
    #ignore verisign to prevent waste of bandwidth
    ignore_target_hosts = +loopback
    '.(!empty($config_arr['general']['eximmailtrap']) ? 'headers_add = "${perl{mailtrapheaders}}"' : '').'
    transport = dkim_remote_smtp
	
dkim_lookuphost:
    driver = dnslookup
    domains = ! +local_domains
    condition = "${perl{sender_domain_can_dkim_sign}}"
    #ignore verisign to prevent waste of bandwidth
    ignore_target_hosts = +loopback
    '.(!empty($config_arr['general']['eximmailtrap']) ? 'headers_add = "${perl{mailtrapheaders}}"' : '').'
    transport = dkim_remote_smtp

suspended_script:
	driver = redirect
	allow_fail
	condition = ${lookup{$sender_address}lsearch{/etc/mail_script_suspended}{1}{0}}
	data = :blackhole:
	
lookuphost:
    driver = dnslookup
    domains = ! +local_domains
    #ignore verisign to prevent waste of bandwidth
    ignore_target_hosts = +loopback
    '.(!empty($config_arr['general']['eximmailtrap']) ? 'headers_add = "${perl{mailtrapheaders}}"' : '').'
    transport = remote_smtp

literal:
    driver = ipliteral
    domains = ! +local_domains
    ignore_target_hosts = +loopback : 64.94.110.0/24
    '.(!empty($config_arr['general']['eximmailtrap']) ? 'headers_add = "${perl{mailtrapheaders}}"' : '').'
    transport = remote_smtp


######################################################################
#                      DIRECTORS CONFIGURATION                       #
#             Specifies how local addresses are handled              #
######################################################################
#                          ORDER DOES MATTER                         #
#   A local address is passed to each in turn until it is accepted.  #
######################################################################

#Suspended User will not receive any mail
suspended_user:
	driver = redirect
	allow_fail
	domains = lsearch;/etc/userdomains
	condition = ${if exists {/etc/exim/users/${lookup{$domain}lsearch{/etc/userdomains}{$value}}/.${sg{$local_part}{\N[/+].*\N}{}}@${domain}.suspended_incoming}}
	data = :fail: The $local_part@$domain is suspended to receive any incoming mail.

# filter on user level
user_filter:
    driver = redirect
    allow_filter
    allow_fail
    forbid_filter_run
    forbid_filter_perl
    forbid_filter_lookup
    forbid_filter_readfile
    forbid_filter_readsocket
    no_check_local_user
    domains = lsearch;/etc/userdomains
    require_files = "/etc/exim/users/${lookup{$domain}lsearch{/etc/userdomains}{$value}}/filter"
    condition = "${extract \
        {size} \
        {${stat:/etc/exim/users/${lookup{$domain}lsearch{/etc/userdomains}{$value}}/filter}} \
    }"
    file = /etc/exim/users/${lookup{$domain}lsearch{/etc/userdomains}{$value}}/filter
    file_transport = address_file
    directory_transport = address_directory
    reply_transport = address_reply
    pipe_transport = address_pipe
    router_home_directory = ${extract \
        {5} \
        {::} \
        {${lookup passwd \
            {${lookup \
                {$domain} \
                lsearch{/etc/userdomains} \
                {$value} \
            }} \
            {$value} \
        }} \
    }
    user = "${lookup \
        {$domain} \
        lsearch{/etc/userdomains} \
        {$value} \
    }"
	group = "${lookup \
        {$domain} \
        lsearch{/etc/userdomains} \
        {$value} \
    }"
    no_verify

# A filter on Domain level
domain_filter:
    driver = redirect
    allow_filter
    allow_fail
    forbid_filter_run
    forbid_filter_perl
    forbid_filter_lookup
    forbid_filter_readfile
    forbid_filter_readsocket
    no_check_local_user
    domains = lsearch;/etc/userdomains
    require_files = "/etc/exim/users/${lookup{$domain}lsearch{/etc/userdomains}{$value}}/${perl{untaint}{$domain}}/filter"
    condition = "${extract \
        {size} \
        {${stat:/etc/exim/users/${lookup{$domain}lsearch{/etc/userdomains}{$value}}/${perl{untaint}{$domain}}/filter}} \
    }"
    file = /etc/exim/users/${lookup{$domain}lsearch{/etc/userdomains}{$value}}/${perl{untaint}{$domain}}/filter
    file_transport = address_file
    directory_transport = address_directory
    reply_transport = address_reply
    pipe_transport = address_pipe
    router_home_directory = ${extract \
        {5} \
        {::} \
        {${lookup passwd \
            {${lookup \
                {$domain} \
                lsearch{/etc/userdomains} \
                {$value} \
            }} \
            {$value} \
        }} \
    }
    user = "${lookup \
        {$domain} \
        lsearch{/etc/userdomains} \
        {$value} \
    }"
	group = "${lookup \
        {$domain} \
        lsearch{/etc/userdomains} \
        {$value} \
    }"
    no_verify
	
# A filter on Email level
email_filter:
    driver = redirect
    allow_filter
    allow_fail
    forbid_filter_run
    forbid_filter_perl
    forbid_filter_lookup
    forbid_filter_readfile
    forbid_filter_readsocket
    no_check_local_user
    domains = lsearch;/etc/userdomains
    require_files = "/etc/exim/users/${lookup{SAFEDOMAIN}lsearch{/etc/userdomains}{$value}}/SAFEDOMAIN/SAFELOCALPART/filter"
    condition = "${extract \
        {size} \
        {${stat:/etc/exim/users/${lookup{SAFEDOMAIN}lsearch{/etc/userdomains}{$value}}/SAFEDOMAIN/SAFELOCALPART/filter}} \
    }"
    file = /etc/exim/users/${lookup{SAFEDOMAIN}lsearch{/etc/userdomains}{$value}}/SAFEDOMAIN/SAFELOCALPART/filter
    file_transport = address_file
    directory_transport = address_directory
    reply_transport = address_reply
    pipe_transport = address_pipe
    router_home_directory = ${extract \
        {5} \
        {::} \
        {${lookup passwd \
            {${lookup \
                {$domain} \
                lsearch{/etc/userdomains} \
                {$value} \
            }} \
            {$value} \
        }} \
    }
    user = "${lookup \
        {$domain} \
        lsearch{/etc/userdomains} \
        {$value} \
    }"
	group = "${lookup \
        {$domain} \
        lsearch{/etc/userdomains} \
        {$value} \
    }"
	local_part_suffix = +*
    local_part_suffix_optional
    retry_use_local_part
    no_verify

#autoreply exists
#both passwd and forwarders do not have local_part.
userautoreply:
  driver = accept
  domains = lsearch;/etc/userdomains
	router_home_directory = ${extract \
        {5} \
        {::} \
        {${lookup passwd \
            {${lookup \
                {$domain} \
                lsearch{/etc/userdomains} \
                {$value} \
            }} \
            {$value} \
        }} \
    }
	user = "${lookup \
        {$domain} \
        lsearch{/etc/userdomains} \
        {$value} \
    }"
  #local_parts = ${lookup{$local_part} dsearch,ret=full{${extract{5}{::}{${lookup passwd{${lookup{$domain}lsearch{/etc/userdomains}{$value}}}{$value}}}}/etc/${domain}/autorespond/}}
  condition = ${if exists{/etc/exim/users/${lookup{$domain}lsearch{/etc/userdomains}{$value}}/${perl{untaint}{$domain}}/autorespond/${local_part}/${local_part}@${perl{untaint}{$domain}}.msg}{yes}{no}}
  condition = ${if match{$h_X-Spam-Status:}{\N^Yes\N}{no}{yes}}
  require_files = /etc/exim/users/${lookup{$domain}lsearch{/etc/userdomains}{$value}}/${perl{untaint}{$domain}}/autorespond/${local_part}/${local_part}@${perl{untaint}{$domain}}.msg
  condition = ${if exists{/etc/exim/users/${lookup{$domain}lsearch{/etc/userdomains}{$value}}/${perl{untaint}{$domain}}/passwd}}
  
   # Check if the current time is between start and stop times
  condition = ${if and { \
		{>= {${run{/bin/date +%Y%m%d%H%M}}}{${if eq {${readfile{${perl{untaint}{/etc/exim/users/${lookup{$domain}lsearch{/etc/userdomains}{$value}}/${perl{untaint}{$domain}}/autorespond/${local_part}/${local_part}@${perl{untaint}{$domain}}.starttime}}}}}{}{${run{/bin/date +%Y%m%d%H%M}}}{${readfile{${perl{untaint}{/etc/exim/users/${lookup{$domain}lsearch{/etc/userdomains}{$value}}/${perl{untaint}{$domain}}/autorespond/${local_part}/${local_part}@${perl{untaint}{$domain}}.starttime}}}}}}}} \
		{<= {${run{/bin/date +%Y%m%d%H%M}}}{${if eq {${readfile{${perl{untaint}{/etc/exim/users/${lookup{$domain}lsearch{/etc/userdomains}{$value}}/${perl{untaint}{$domain}}/autorespond/${local_part}/${local_part}@${perl{untaint}{$domain}}.stoptime}}}}}{}{999912312359}{${readfile{${perl{untaint}{/etc/exim/users/${lookup{$domain}lsearch{/etc/userdomains}{$value}}/${perl{untaint}{$domain}}/autorespond/${local_part}/${local_part}@${perl{untaint}{$domain}}.stoptime}}}}}}}} \
	  } {yes}{no}}
  
  # Prevent the autoresponder email from being sent repeatedly.
  condition = ${if def:h_Auto-submitted:{${if match{$h_Auto-submitted:}{\N^no\N\}{yes}{no}}}{yes}}

  # do not reply to errors and bounces or lists
  senders = " ! ^.*-request@.*:\
              ! ^owner-.*@.*:\
              ! ^postmaster@.*:\
              ! ^listmaster@.*:\
              ! ^mailer-daemon@.*\
              ! ^root@.*"
  transport = userautoreply
  unseen
  
virtual_aliases:
    driver = redirect
    allow_defer
    allow_fail
    domains = lsearch;/etc/userdomains
    user = "${lookup \
        {$domain} \
        lsearch{/etc/userdomains} \
        {$value} \
    }"
	group = "${lookup \
        {$domain} \
        lsearch{/etc/userdomains} \
        {$value} \
    }"
    address_data = \
        "router=$router_name \
        redirect=${quote:${lookup \
            {$local_part} \
            lsearch{/etc/exim/users/${lookup{$domain}lsearch{/etc/userdomains}{$value}}/${perl{untaint}{$domain}}/aliases} \
    }}"
    data = ${sg{${extract{redirect}{$address_data}}}{"}{}}
    file_transport = address_file
    pipe_transport = address_pipe
    local_part_suffix = +*
    local_part_suffix_optional
    retry_use_local_part
    unseen

#
# Virtual User Spam Boxes
#

virtual_user_spam:
	driver = accept
	local_parts = +path_safe_localparts
	domains = +local_domains
	condition = ${if match{$h_x-spam-status:}{\N^Yes\N}{true}{false}}
	require_files = +${extract{5}{::}{${lookup passwd{${lookup{$domain}lsearch{/etc/userdomains}{$value}}}{$value}}}}/.spamassassinboxenable : +${extract{5}{::}{${lookup passwd{${lookup{$domain}lsearch{/etc/userdomains}{$value}}}{$value}}}}/mail/$domain/$local_part
    router_home_directory = ${extract \
        {5} \
        {::} \
        {${lookup passwd \
            {${lookup \
                {$domain} \
                lsearch{/etc/userdomains} \
                {$value} \
            }} \
            {$value} \
        }} \
    }
	cannot_route_message = Unknown user
	transport = maildir_spam_delivery
';

if(!empty($config_arr['general']['no_local_emailing'])){

    $config .= '
no_local_delivery:
	driver = redirect
	allow_fail
	domains = lsearch;/etc/userdomains 
	condition = "${lookup{$sender_address_domain}lsearch{/etc/userdomains}{$value}}"
	data = :fail: Local emailing is not enabled on your server. Contact your Server Administrator.    
';

}

$config .= '
virtual_boxtrapper_user:
  driver = accept
  local_parts = +path_safe_localparts
  domains = \
        : ${lookup \
            {$domain} \
            lsearch{/etc/userdomains} \
            {${perl{untaint}{$domain}}} \
        }
  require_files = "+/var/softaculous/apps/exim/boxtrapper.php:+/etc/exim/users/${lookup{$domain}lsearch{/etc/userdomains}{$value}}/${domain}/boxtrapper/${local_part}/.enabled"
  user = ${lookup{$domain}lsearch{/etc/userdomains}{$value}}
  headers_remove="x-uidl"
  transport = virtual_boxtrapper_userdelivery

virtual_user:
    driver = accept
    domains = \
        : ${lookup \
            {$domain} \
            lsearch{/etc/userdomains} \
            {${perl{untaint}{$domain}}} \
        }
    local_parts = +path_safe_localparts
    require_files = "+${extract \
        {5} \
        {::} \
        {${lookup passwd \
            {${lookup \
                {$domain} \
                lsearch{/etc/userdomains} \
                {$value} \
            }} \
            {$value} \
        }} \
    }/mail/$domain/$local_part"
    router_home_directory = ${extract \
        {5} \
        {::} \
        {${lookup passwd \
            {${lookup \
                {$domain_data} \
                lsearch{/etc/userdomains} \
                {$value} \
            }} \
            {$value} \
        }} \
    }
    headers_remove="x-uidl"
    local_part_suffix = +*
    local_part_suffix_optional
    user = "${lookup{$domain}lsearch{/etc/userdomains}{$value}}"
    group = "exim"
    transport = dovecot_delivery
    set = r_bcc_addr=${if forany \
        {${addresses:$h_to:}:${addresses:$h_cc:}} \
        {or { \
            {eqi \
                {${extract{1}{+}{${local_part:$item}}}@${domain:$item}} \
                {$local_part@$domain} \
            } \
            {eqi \
                {${extract{1}{+}{${local_part:$item}}}@${domain:$item}} \
                {$original_local_part@$original_domain} \
            } \
        }} \
        {} \
        {$local_part@$domain} \
    }
    set = r_webuzo_u=${lookup \
        {$domain} \
        lsearch{/etc/userdomains} \
        {$value} \
    }

has_alias_but_no_mailbox_discarded_to_prevent_loop:
    driver = redirect
    domains = lsearch;/etc/userdomains
    condition = ${lookup \
        {$local_part} \
        lsearch{/etc/exim/users/${lookup{$domain}lsearch{/etc/userdomains}{$value}}/${perl{untaint}{$domain}}/aliases} \
        {1} \
        {0} \
    }
    condition = "${if forany{<, \
        ${lookup \
            {$local_part} \
	    lsearch{/etc/exim/users/${lookup{$domain}lsearch{/etc/userdomains}{$value}}/${perl{untaint}{$domain}}/aliases} \
            {$value} \
        }} \
        {!match{$item}{\N/autorespond\N}} \
        {1} \
        {${if match \
            {${lookup \
                {\N*\N} \
		lsearch{/etc/exim/users/${lookup{$domain}lsearch{/etc/userdomains}{$value}}/${perl{untaint}{$domain}}/aliases} \
                {$value} \
            }} \
            {:fail:} \
            {1} \
            {0} \
        }} \
    }"
    data=":blackhole:"
    local_part_suffix = +*
    local_part_suffix_optional
    disable_logging = true

# TODO
#valias_domain_file:
 # driver = redirect
 # allow_defer
 # allow_fail
 # domains = lsearch;/etc/userdomains
 # user = "${lookup{$domain_data}lsearch{/etc/userdomains}{$value}}"
 # group = "${lookup{$domain_data}lsearch{/etc/userdomains}{$value}}"
 # condition = ${lookup {$domain} lsearch {/etc/exim/users/${lookup{$domain}lsearch{/etc/userdomains}{$value}}/etc/$domain/domaliases}{yes}{no} }
 # address_data = router=$router_name redirect=${quote:${quote_local_part:$local_part}@${lookup{$domain}lsearch{/etc/exim/users/${lookup{$domain}lsearch{/etc/userdomains}{$value}}/etc/$domain/domaliases}}}
 # data = ${extract{redirect}{$address_data}}
  

local_aliases:
    driver = redirect
	require_files = /etc/localaliases
    allow_defer
    allow_fail
    domains = $primary_hostname : localhost
    address_data = \
        "router=$router_name \
        redirect=${quote: \
            ${lookup \
                {$local_part} \
                lsearch{/etc/localaliases} \
            }}"
    data = ${extract{redirect}{$address_data}}
    file_transport = address_file
    pipe_transport = address_pipe
    check_local_user

userforward:
    driver = redirect
    allow_filter
    allow_fail
    forbid_filter_run
    forbid_filter_perl
    forbid_filter_lookup
    forbid_filter_readfile
    forbid_filter_readsocket
    check_ancestor
    check_local_user
    domains = $primary_hostname
    no_expn
    require_files = "+$home/.forward"
    condition = "${extract{size}{${stat:$home/.forward}}}"
    file = $home/.forward
    file_transport = address_file
    reply_transport = address_reply
    directory_transport = address_directory
    user = $local_part_data
    group = $local_part_data
    no_verify


localuser_root:
    driver = redirect
    allow_fail
    domains = $primary_hostname : localhost
    check_local_user
    condition = ${if eq {$local_part_data}{root}}
    data = :fail: root cannot accept local mail deliveries
	

localuser_overquota:
  driver = redirect
  domains = $primary_hostname
  check_local_user
  # NB: On busy servers Dovecot may take several seconds to respond to
  # this request. So we set the timeout generously:
  condition =  "${if match {${readsocket{/var/run/dovecot/quota-status}{request=smtpd_access_policy\nrecipient=${quote:$local_part}\nsize=$message_size\n\n}{30s}{\n}{SOCKETFAIL}}}{action=5}{true}{false}}"

  data = ":fail:Mailbox is full / Blocks limit exceeded / Inode limit exceeded"
  verify_only
  allow_fail

#
# Optimized spambox router
#

localuser_spam:
    driver = redirect
    domains = $primary_hostname
    condition  = ${if exists{/etc/global_spamassassin_enable}{1}{${if exists{${extract{5}{::}{${lookup passwd{${if eq{$domain}{$primary_hostname}{${sg{$local_part}{\N[/+].*\N}{}}}{${lookup{$domain}lsearch{/etc/userdomains}}}}}}}}/.spamassassindisable}{0}{1}}}}
    condition = ${if match{$h_x-spam-status:}{\N^Yes\N}{true}{false}}
# sets home,user,group
    check_local_user
    headers_remove="x-uidl"
    data = "${quote_local_part:$local_part_data}+spam"
    redirect_router = localuser
	
localuser:
    driver = accept
# sets home,user,group
    check_local_user
    domains = $primary_hostname
    headers_remove="x-uidl"
    local_part_suffix = +*
    local_part_suffix_optional
    user = ${lookup{$domain}lsearch{/etc/userdomains}{$value}}
    group = exim
    transport = dovecot_delivery
    set = r_bcc_addr=${if forany \
        {${addresses:$h_to:}:${addresses:$h_cc:}} \
        {or { \
            { eqi \
                {${extract \
                    {1} \
                    {+} \
                    {${local_part:$item}} \
                }@${domain:$item}} \
                {$local_part@$domain} \
            } \
            { eqi \
                {${extract \
                    {1} \
                    {+} \
                    {${local_part:$item}} \
                }@${domain:$item}} \
                {$original_local_part@$original_domain} \
            } \
        }} \
        {} \
        {$local_part@$domain} \
    }
    set = r_webuzo_u=${local_part}

split_delivery:
    driver = manualroute
    domains = lsearch;/etc/exim_no_catchall
    transport = remote_smtp
    condition = ${if match_ip{$sender_host_address}{+loopback}{1}{${lookup{$domain}lsearch{/etc/exim_no_catchall_final_host}{0}{1}}}}
    route_data = ${lookup \
        {$domain} \
        lsearch{/etc/exim_no_catchall} \
    }
	
#To catch all the failed mail
catchall:
    driver = redirect
    domains = lsearch;/etc/userdomains
	address_data = \
        "router=$router_name \
        redirect=${quote:${lookup \
            {*} \
            lsearch{/etc/exim/users/${lookup{$domain}lsearch{/etc/userdomains}{$value}}/${perl{untaint}{$domain}}/aliases} \
    }}"
    data = ${sg{${extract{redirect}{$address_data}}}{"}{}}
    pipe_transport = address_pipe
	allow_fail

dnslookup:
  driver = dnslookup
  domains = ! +local_domains
  transport = remote_smtp
  ignore_target_hosts = 0.0.0.0 : 127.0.0.0/8
  no_more


#################################################################################
#                 DO NOT EDIT Exim Webuzo TRANSPORTS
#		This transport is used for delivering messages over SMTP connections.
#################################################################################

begin transports

remote_smtp:
    driver = smtp 
    dkim_domain = ${lc:${domain:$h_from:}}
    dkim_selector = '.$globals['dkim_selector'].'
    dkim_private_key = /var/webuzo-data/mail/dkim/private/${perl{untaint}{${dkim_domain}}}
    dkim_canon = relaxed
    interface = <; ${if > {${extract{size}{${stat:/etc/mailips}}}}{0}{${lookup{${lc:${perl{get_message_sender_domain}}}}lsearch{/etc/mailips}{$value}{${lookup{${if match_domain{$original_domain}{+relay_domains}{${lc:$original_domain}}{}}}lsearch{/etc/mailips}{$value}{${lookup{${perl{get_sender_from_uid}}}lsearch*{/etc/mailips}{$value}{}}}}}}}}
    helo_data = ${if exists {/etc/mailhelo}{${lookup{$sender_address_domain}lsearch{/etc/mailhelo}{$value}{$primary_hostname}}}{$primary_hostname}}
    message_linelength_limit = '.(isset($config_arr['general']['message_linelength_limit']) ? $config_arr['general']['message_linelength_limit'] : 2048).'

remote_smtp_old:
  driver = smtp
  #interface = <; ${if > {${extract{size}{${stat:/etc/mailips}}}}{0}{${lookup{${lc:${perl{get_message_sender_domain}}}}lsearch{/etc/mailips}{$value}{${lookup{${if match_domain{$original_domain}{+relay_domains}{${lc:$original_domain}}{}}}lsearch{/etc/mailips}{$value}{${lookup{${perl{get_sender_from_uid}}}lsearch*{/etc/mailips}{$value}{}}}}}}}}
  #helo_data = ${if > {${extract{size}{${stat:/etc/mailhelo}}}}{0}{${lookup{${lc:${perl{get_message_sender_domain}}}}lsearch{/etc/mailhelo}{$value}{${lookup{${if match_domain{$original_domain}{+relay_domains}{${lc:$original_domain}}{}}}lsearch{/etc/mailhelo}{$value}{${lookup{${perl{get_sender_from_uid}}}lsearch*{/etc/mailhelo}{$value}{$primary_hostname}}}}}}}{$primary_hostname}}
  #hosts_try_chunking = 198.51.100.1
  helo_data = ${lookup dnsdb{ptr=$sending_ip_address}{$value}{$primary_hostname}}
  dkim_domain = ${lc:${domain:$h_from:}}

dkim_remote_smtp:
  driver = smtp
  interface = <; ${if > {${extract{size}{${stat:/etc/mailips}}}}{0}{${lookup{${lc:${perl{get_message_sender_domain}}}}lsearch{/etc/mailips}{$value}{${lookup{${if match_domain{$original_domain}{+relay_domains}{${lc:$original_domain}}{}}}lsearch{/etc/mailips}{$value}{${lookup{${perl{get_sender_from_uid}}}lsearch*{/etc/mailips}{$value}{}}}}}}}}
  #helo_data = ${if > {${extract{size}{${stat:/etc/mailhelo}}}}{0}{${lookup{${lc:${perl{get_message_sender_domain}}}}lsearch{/etc/mailhelo}{$value}{${lookup{${if match_domain{$original_domain}{+relay_domains}{${lc:$original_domain}}{}}}lsearch{/etc/mailhelo}{$value}{${lookup{${perl{get_sender_from_uid}}}lsearch*{/etc/mailhelo}{$value}{$primary_hostname}}}}}}}{$primary_hostname}}
  dkim_domain = ${lc:${domain:$h_from:}} 
  dkim_selector = '.$globals['dkim_selector'].'
  dkim_private_key = "/var/webuzo-data/mail/dkim/private/${perl{untaint}{${dkim_domain}}}"
  dkim_canon = relaxed
  helo_data = ${lookup dnsdb{ptr=$sending_ip_address}{$value}{$primary_hostname}}
  #hosts_try_chunking = 198.51.100.1
  message_linelength_limit = '.(isset($config_arr['general']['message_linelength_limit']) ? $config_arr['general']['message_linelength_limit'] : 2048).'

virtual_boxtrapper_userdelivery:
  driver = pipe
  command = /var/softaculous/apps/exim/boxtrapper.php
  user = exim
  group = ${lookup{$domain}lsearch{/etc/userdomains}{$value}}
  log_output = true
  return_fail_output = true
  return_path_add = false
  temp_errors = 64 : 69 : 70: 71 : 72 : 73 : 74 : 75 : 78

address_directory:
  driver = appendfile
  maildir_format
  maildir_use_size_file
  delivery_date_add
  envelope_to_add
  return_path_add
  
address_pipe:
    driver = pipe
    return_output
	

virtual_address_pipe:
    driver = pipe
    return_output
	
address_file:
	debug_print = "T: address_file for $local_part@$domain"
	driver = appendfile
	delivery_date_add
	envelope_to_add
	return_path_add
	mode = 0660
	
dovecot_delivery:
    driver = lmtp
    socket = /var/run/dovecot/lmtp
    batch_max = 200
    batch_id = "$r_webuzo_u ${if def:r_bcc_addr {$r_bcc_addr}}"
    rcpt_include_affixes
    delivery_date_add
    envelope_to_add
    return_path_add

vmail_delivery:
    driver = lmtp
	user = "${lookup{$domain_data}lsearch{/etc/userdomains}{$value}}"
	group = "${lookup{$domain_data}lsearch{/etc/userdomains}{$value}}"
    socket = /var/run/dovecot/lmtp
    batch_max = 200
    batch_id = "$r_webuzo_u ${if def:r_bcc_addr {$r_bcc_addr}}"
    rcpt_include_affixes
    delivery_date_add
    envelope_to_add
    return_path_add

maildir_spam_delivery:
	driver = appendfile
	directory = $home/mail/${lookup{$domain}dsearch{$home/mail/}}/${lookup{$local_part}dsearch{$home/mail/${lookup{$domain}dsearch{$home/mail/}}/}}/.spam
	create_directory = true
	delivery_date_add
	envelope_to_add
	return_path_add
	maildir_format
	mode = 0660
	user = ${lookup{$domain}lsearch{/etc/userdomains}{$value}}
	group = ${lookup{$domain}lsearch{/etc/userdomains}{$value}}
	
dovecot_virtual_delivery:
  driver = appendfile
  delivery_date_add
  #directory_mode = 770
  envelope_to_add
  #router_home_directory = ${extract{5}{::}{${lookup passwd{${lookup{$domain}lsearch{/etc/userdomains}{$value}}}{$value}}}}
  directory = $home/mail/${lookup{$domain}dsearch{$home/mail/}}/${lookup{$local_part}dsearch{$home/mail/${lookup{$domain}dsearch{$home/mail/}}/}}
  #file = ${extract{5}{::}{${lookup passwd{${lookup{$domain}lsearch{/etc/userdomains}{$value}}}{$value}}}}/mail/$domain/$local_part
  maildir_format
  create_directory = true
  group = ${lookup{$domain}lsearch{/etc/userdomains}{$value}}
  mode = 0660
  return_path_add
  user = ${lookup{$domain}lsearch{/etc/userdomains}{$value}}
	
address_reply:
    driver = autoreply
	
userautoreply:
    driver = autoreply
    user = exim
    headers = ${if exists{/etc/exim/users/${lookup{SAFEDOMAIN}lsearch{/etc/userdomains}{$value}}/SAFEDOMAIN/autorespond/SAFELOCALPART/SAFELOCALPART@SAFEDOMAIN.header}{\
                ${readfile{/etc/exim/users/${lookup{SAFEDOMAIN}lsearch{/etc/userdomains}{$value}}/SAFEDOMAIN/autorespond/SAFELOCALPART/SAFELOCALPART@SAFEDOMAIN.header}}\
            }{}}
    file = /etc/exim/users/${lookup{SAFEDOMAIN}lsearch{/etc/userdomains}{$value}}/SAFEDOMAIN/autorespond/SAFELOCALPART/SAFELOCALPART@SAFEDOMAIN.msg
    from = "${local_part}@${domain}"
    no_return_message
    subject = ${if def:h_Subject: {\
	    ${if exists{/etc/exim/users/${lookup{SAFEDOMAIN}lsearch{/etc/userdomains}{$value}}/SAFEDOMAIN/autorespond/SAFELOCALPART/SAFELOCALPART@SAFEDOMAIN.subj}\
		{${readfile{/etc/exim/users/${lookup{SAFEDOMAIN}lsearch{/etc/userdomains}{$value}}/SAFEDOMAIN/autorespond/SAFELOCALPART/SAFELOCALPART@SAFEDOMAIN.subj}{}}}\
		{Autoreply}\
	}: ${sg{$rh_Subject:}{\\n}{}}}\
	{Autoreply Message}}
    to = "${reply_address}"

	
######################################################################
#                      exim Webuzo RETRY CONFIGURATION                      
######################################################################

# Domain               Error       Retries
# ------               -----       -------


begin retry

+secondarymx           *           F,4h,5m; G,16h,1h,1.5; F,4d,8h';
if($config_arr['general']['enable_mail_retry'] != 0){
    $config .= '
*           *           F,2h,'.$config_arr['general']['mail_retry'].'m; G,16h,1h,1.5; F,4d,6h';
}
	
	exim_access_list();
	
	// spam assassin
	// Force enable spamassassin
	/* if(!empty($config_arr['sa']['force_enable_spamassassin'])){
		touch('/etc/global_spamassassin_enable');
		chgrp('/etc/global_spamassassin_enable', $grp);
	}else{
		@unlink('/etc/global_spamassassin_enable');
	} */
	
	writefile('/etc/exim/exim.conf',  $config, 1);
	writefile('/etc/exim/exim.conf.orig',  $config, 1);
	unlink(EXIM_APP.'etc/exim.conf');
	vexec('ln -s /etc/exim/exim.conf '.EXIM_APP.'etc/exim.conf');
}
	
function exim_configure_filter(){
	
global $globals;
	
	$exim_config_path = $globals['var_conf'].'/exim';
	$config_arr = loaddata($exim_config_path.'/exim.json');
	$syst_filter_config = '# Exim filter

# process once
if not first_delivery
then
  finish
endif


#  Ignore "real" errors
if error_message and $header_from: contains "Mailer-Daemon@"
then
  finish
endif
';

	if(!empty($config_arr['filter']['systemfilter_control']) && !empty($config_arr['filter']['attachments'])){
		
	$syst_filter_config .= '#attachments
# Check Content-Type header using quoted filename [content_type_quoted_fn_match]

if $header_content-type: matches "(?:file)?name=(\"[^\"]+\\\\\\\\.(?:ad[ep]|ba[st]|chm|cmd|com|cpl|crt|eml|exe|hlp|hta|in[fs]|isp|jse?|lnk|md[be]|ms[cipt]|pcd|pif|reg|scr|sct|shs|url|vb[se]|ws[fhc])\")"
then
  fail text "This message has been rejected because it has\n\
	     potentially executable content $1\n\
	     This form of attachment has been used by\n\
             recent viruses or other malware.\n\
	     If you meant to send this file then please\n\
	     package it up as a zip file and resend it."
  seen finish
endif

# same again using unquoted filename [content_type_unquoted_fn_match]

if $header_content-type: matches "(?:file)?name=(\\\\\\\\S+\\\\\\\\.(?:ad[ep]|ba[st]|chm|cmd|com|cpl|crt|eml|exe|hlp|hta|in[fs]|isp|jse?|lnk|md[be]|ms[cipt]|pcd|pif|reg|scr|sct|shs|url|vb[se]|ws[fhc]))([\\\\\\\\s;]|\\\\\\$)"
then
  fail text "This message has been rejected because it has\n\
	     potentially executable content $1\n\
	     This form of attachment has been used by\n\
             recent viruses or other malware.\n\
	     If you meant to send this file then please\n\
	     package it up as a zip file and resend it."
  seen finish
endif

# Quoted filename - [body_quoted_fn_match]
if $message_body matches "(?:Content-(?:Type:(?>\\\\\\\\s*)[\\\\\\\\w-]+/[\\\\\\\\w-]+|Disposition:(?>\\\\\\\\s*)attachment);(?>\\\\\\\\s*)(?:file)?name=|begin(?>\\\\\\\\s+)[0-7]{3,4}(?>\\\\\\\\s+))(\"[^\"]+\\\\\\\\.(?:ad[ep]|ba[st]|chm|cmd|com|cpl|crt|eml|exe|hlp|hta|in[fs]|isp|jse?|lnk|md[be]|ms[cipt]|pcd|pif|reg|scr|sct|shs|url|vb[se]|ws[fhc])\")[\\\\\\\\s;]"
then
  fail text "This message has been rejected because it has\n\
	     a potentially executable attachment $1\n\
	     This form of attachment has been used by\n\
             recent viruses or other malware.\n\
	     If you meant to send this file then please\n\
	     package it up as a zip file and resend it."
  seen finish
endif

# same again using unquoted filename [body_unquoted_fn_match]
if $message_body matches "(?:Content-(?:Type:(?>\\\\\\\\s*)[\\\\\\\\w-]+/[\\\\\\\\w-]+|Disposition:(?>\\\\\\\\s*)attachment);(?>\\\\\\\\s*)(?:file)?name=|begin(?>\\\\\\\\s+)[0-7]{3,4}(?>\\\\\\\\s+))(\\\\\\\\S+\\\\\\\\.(?:ad[ep]|ba[st]|chm|cmd|com|cpl|crt|eml|exe|hlp|hta|in[fs]|isp|jse?|lnk|md[be]|ms[cipt]|pcd|pif|reg|scr|sct|shs|url|vb[se]|ws[fhc]))[\\\\\\\\s;]"
then
  fail text "This message has been rejected because it has\n\
	     a potentially executable attachment $1\n\
	     This form of attachment has been used by\n\
             recent viruses or other malware.\n\
	     If you meant to send this file then please\n\
	     package it up as a zip file and resend it."
  seen finish
endif
';
	}

	if(!empty($config_arr['filter']['fail_spam_score_over_int_control'])){
	
	$syst_filter_config .= '

if ($h_x-spam-score: matches \N^\d+$\N and $h_x-spam-score: is above '.((int)$config_arr['filter']['fail_spam_score_over_int_control']).')
then
    fail text "The mail server detected your message as spam and has prevented delivery ('.((int)$config_arr['filter']['fail_spam_score_over_int_control']).')."
endif
';
	}

	if(!empty($config_arr['filter']['systemfilter_control']) && !empty($config_arr['filter']['spam_rewrite'])){
		
	$syst_filter_config .= '
#spam_rewrite
if "${if def:header_X-Spam-Subject: {there}}" is there
then
    headers remove Subject
    headers add "Subject: $rh_X-Spam-Subject:"
    headers remove X-Spam-Subject
endif
';
	}
	
	// First preference to custom filter saved from UI
	if(!empty(trim($config_arr['filter']['customfilter']))){
		$syst_filter_config .= '
# BEGIN - Custom filter from Mail Settings
'.$config_arr['filter']['customfilter'].'
# END - Custom filter from Mail Settings
';
		
	// Second preference to custom filter file
	}elseif($customfilter = file_get_contents($globals['var_conf'].'/exim/customfilter')){
		$syst_filter_config .= '
# BEGIN - Custom filter from /var/webuzo/conf/exim/customfilter file
'.$customfilter.'
# END - Custom filter from /var/webuzo/conf/exim/customfilter file
';
	}
	
	if(!empty($config_arr['filter']['systemfilter_control']) && file_exists($config_arr['filter']['systemfilter_control'])){
		writefile($config_arr['filter']['systemfilter_control'],  $syst_filter_config, 1);
	}else{
		writefile('/etc/exim/exim_system_filter',  $syst_filter_config, 1);
	}	
	
	return true;
}

function exim_access_list(){

global $globals;

	$grp = 'exim';
	$exim_config_path = $globals['var_conf'].'/exim';
	$config_arr = loaddata($exim_config_path.'/exim.json');
	
	// Access list
	writefile('/etc/spammeripblocks', $config_arr['access_list']['spammeripblocks'], 1);
	chgrp('/etc/spammeripblocks', $grp);
	chmod('/etc/spammeripblocks', 0660);
	writefile('/etc/senderverifybypasshosts', $config_arr['access_list']['senderverifybypasshosts'], 1);
	chgrp('/etc/senderverifybypasshosts', $grp);
	chmod('/etc/senderverifybypasshosts', 0660);
	writefile('/etc/trustedmailhosts', $config_arr['access_list']['mostlytrustedmailhosts'], 1);
	chgrp('/etc/trustedmailhosts', $grp);
	chmod('/etc/trustedmailhosts', 0660);
	writefile('/etc/skipsmtpcheckhosts', $config_arr['access_list']['skipsmtpcheckhosts'], 1);
	chgrp('/etc/skipsmtpcheckhosts', $grp);
	chmod('/etc/skipsmtpcheckhosts', 0660);
	writefile('/etc/backupmxhosts', $config_arr['access_list']['backupmxhosts'], 1);
	chgrp('/etc/backupmxhosts', $grp);
	chmod('/etc/backupmxhosts', 0660);
	writefile('/etc/trusted_mail_users', $config_arr['access_list']['trustedmailusers'], 1);
	chgrp('/etc/trusted_mail_users', $grp);
	chmod('/etc/trusted_mail_users', 0660);
}

function exim_custom_code($tmp_path = '', $tmp_json = []){
	
global $globals;

	$exim_json = loaddata($globals['var_conf'].'/exim/exim.json');

	if(!empty($tmp_json)){
		$exim_json = $tmp_json;
	}

	$exim_path = '/etc/exim/exim.conf';
	
	if(!empty($tmp_path) && file_exists($exim_path.'.orig')){
		$exim_path = $exim_path.'.orig';
	}
	
	$exim_conf = file($exim_path, FILE_IGNORE_NEW_LINES);
	
	// Update exim conf according to the custom codes
	if(!empty($exim_json['custom'])){
		foreach($exim_json['custom'] as $key => $val){
			foreach($val as $k => $v){		
			
				// Adding custom code below section header
				if($k == 'noRule'){
					$headerindex = array_search($key, $exim_conf);
					$exim_conf = array_merge(array_slice($exim_conf, 0, $headerindex + 1), [''], $v, [''], array_slice($exim_conf, $headerindex + 1));
					
				// Adding custom code above rule
				}else{
					
					$ruleindex = array_search($k.':', $exim_conf);
					$exim_conf = array_merge(array_slice($exim_conf, 0, $ruleindex), [''], $v, [''], array_slice($exim_conf, $ruleindex));
				}
			}
		}
	}
		
	file_put_contents((!empty($tmp_path) ? $tmp_path : $exim_path), implode("\n", $exim_conf));
}