#!perl.exe

### jdwa环境设置
if($ENV{'SERVER_SOFTWARE'}=~/IIS.\d+.0$/){my $cd=$0;$cd=~s/[^\\]*$//;chdir($cd);}
$startup = 1;
require "jcode.pl";
require "config.cgi";
($cgi,$cols,$errors,$help) = ('cfgenv.cgi',55,"..\\temp\\errors.log","$helper?jdwaconfig");
@cfg2 = qw(admin pass ctrlport ctrlsport fingerport popport popsport smtpport smtpsport ctrlprt smtpsvr 
	smtpprt jdmaildir jdmailexe mailroot passmin mboxmax postmaster robot tz localip glstdir jdwmdir jdmldir 
	jdmlroot ipmsg netsendmsg datecheck distribute dfgroup dfdomain dfsort 
	ob_received ob_received_helodomain ob_received_ip ob_remove_received SpamScan);

### 初期表示
if (@ARGV){
	$page = $ARGV[1];
	
	## CGI_Lite拷贝
	my $msg = &copy_cgilite();
	
	## 初期环境配置完成
	if ($page ==1 && -f $lcfg){
		my $msg1 = "完成初始配置。";
		my $msg2 = "请使用 [环境设置]-[$jdwa 环境设置] 更新环境。<br>";
		my $msg3 = "要重新做初始配置，请删除 cgi 文件夹内的 $lcfg 。";
		&error('9',$msg1,$msg2,$msg3);
	}
	
	## perl版本检查(UTF-8对应确认)
	$perlver = $];
	
	## WWW 服务器变量是否能使用
	&error('4') if !$ENV{'SERVER_SOFTWARE'};
	
	## IIS 的情况认证控制有必要安装
	&error('5') if ($ENV{'SERVER_SOFTWARE'} =~ /IIS/ && !$ENV{'LOGON_USER'});
	
	## 计算机名不能使用中文
	$hostname = `hostname`;
#szy	&jcode::convert(\$hostname,'euc');
	&error('0',"计算机名不能使用中文！") if $hostname =~ /[\x80-\xFF]/;
	
	## 如果有，取得现环境
	if (-f $lcfg){
		%cfg = &get_env($lcfg,'=');
		while (my($key,$val) = each %cfg){$$key = $val;}
		
		# 垃圾邮件扫描信息的移动 ver 2.31d以后
		my $tab = "$cfg{'mailroot'}\\spamwords-conf.tab";
		if (!-f $tab && open(FILE,">$tab")){
				flock(FILE,2);
				print FILE "## Saved by $jdwa ver $vcfg\n";
				foreach (qw(SpamScan SpamScanOnline SpamScan_in SpamScan_out SpamScan_body SpamScan_Date 
					SpamScan_From SpamScan_To SpamScan_size SpamScan_NoText SpamScan_Received1 
					SpamScan_Received2 SpamScan_Received3 SpamScan_Received4 SpamScan_ReceivedDomain 
					SpamScan_ReceivedIP SpamScan_SendNotice SpamScan_GoOn SpamScan_AddHeader1 
					SpamScan_AddHeader2 SpamScan_AddHeader3 SpamScan_AddHeader4 SpamScan_AddHeaderText 
					SpamScan_blackhole SpamScan_EmptyBody SpamScan_Subject SpamScan_RegSearch)){
					print FILE "$_ = $$_\n";
				}
			close(FILE);
		}
	}
	$admin = &dec_str($admin);
	$pass = &dec_str($pass);
	$ctrlport = 6017 if !$ctrlport;
	$ctrlsport = 6018 if !$ctrlsport;
	$fingerport = 79 if !$fingerport;
	$popport = 110 if !$popport;
	$popsport = 995 if !$popsport;
	$smtpport = 25 if !$smtpport;
	$smtpsport = 465 if !$smtpsport;
	$jdmailexe = 'JDMail.exe' if !$jdmailexe;
	
	&html($msg);
}

### 输入格式处理
read(STDIN, $buffer, $ENV{'CONTENT_LENGTH'});
@pairs = split(/&/,$buffer);
foreach $pair (@pairs){
	($name, $value) = split(/=/, $pair);
	$value =~ tr/+/ /;
	$value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
#szy	&jcode::convert(\$value,'euc','','z');
	&zenhan('value') if $value =~ /[\x80-\xFF]/;
	$value =~ s/^\s+//;
	$value =~ s/[\s\\]+$//;
	$value =~ s/\r*\n/\n/g;
	$value =~ s/\r/\n/g;
	$value =~ s/\n+/\n/g;
	$$name = $value;
}

foreach (qw(jdmaildir mailroot scanner jdwmdir jdmldir ipmsg)){
	$$_ =~ s/[\/\\]+/\\/g;
}

## 错误检查
&html("客人帐号不能运行!") if $fixed;
foreach(qw(admin pass jdmaildir mailroot passmin postmaster mboxmax tz)){
	&html("必填字段为空白！ 环境设置不能保存！") if !$$_;
}
&html("管理者名称不合适！ 请使用英文或数字、短横线！") if $admin =~ /[^\w.\-@]/i;
&html("密码不合法！不能使用 [<b> * &quot; | &lt; &gt;</b> ] ！") if $pass =~ /[*"\|<>]/;
&html("密码长度应在 $passmin 位以上！") if length($pass) < $passmin;
&html("密码最少位数请指定数字！") if $passmin =~ /\D/;
foreach(qw(ctrlport ctrlsport fingerport popport popsport smtpport smtpsport)){
	if ($$_){
		my $port = $_;
		$port =~ s/port$//;
		$port = uc($port);
		$$_ .= ' ';
		if ($$_ =~ /[^0-9.,: ]/){
			&html("$port 指定端口不正确！");
		} elsif ($$_ =~ /^\d+\s+\d/){
			&html("端口 $port 绑定的IP地址必须指定！");
		} else {
			$$_ =~ s/127\.\d+\.\d+\.\d+(:\d+)*//g;
			foreach my $perm (split(/[\s,]+/,$$_)){
				if ($perm =~ /:/){
					my ($ip,$port1) = split(/:/,$perm);
					if ($ip !~ /^\d+\.\d+\.\d+\.\d+$/ || $port1 !~ /^\d+$/){
						&html("$port 端口的指定 $perm 是不正确的！");
					}
				} elsif ($perm !~ /^\d+$/){&html("$port 端口的指定 $perm 是不正确的！");}
			}
		}
		$$_ =~ s/\s+$//;
	}
	elsif ($_ eq 'ctrlport'){$$_ = 6017;}
	elsif ($_ eq 'ctrlsport'){$$_ = 6018;}
	elsif ($_ eq 'fingerport'){$$_ = 79;}
	elsif ($_ eq 'popport'){$$_ = 110;}
	elsif ($_ eq 'popsport'){$$_ = 995;}
	elsif ($_ eq 'smtpport'){$$_ = 25;}
	elsif ($_ eq 'smtpsport'){$$_ = 465;}
}
($ctrlprt,$smtpprt,$smtpsvr) = ('6017','25','localhost');	# jdwa/JDWM/jdml访问用
$ctrlprt = $ctrlport if $ctrlport =~ /^\d+$/;
$smtpprt = $smtpport if $smtpport =~ /^\d+$/;

&html("JDMail安装文件夹没找到！") if !-d $jdmaildir;
&html("JDMail安装文件夹中含有空格，无法安装！") if $jdmaildir =~ /\s/;
if ($jdmailexe){
	&html("可执行文件的扩展名(.exe)请指明！") if $jdmailexe !~ /\.exe/i;
	&html("不能在可执行文件名中包含空白！") if $jdmailexe =~ /\s/;
	&html("执行文件 $jdmailexe 在安装文件夹中没找到！") if !-f "$jdmaildir\\$jdmailexe";
} else {$jdmailexe = "JDMail.exe";}
&html("MailRoot 文件夹找不到！") if !-d $mailroot;
&html("MailRoot 文件夹不能指定为文件夹名包含空白的地方！") if $mailroot =~ /\s/;
$mboxmax =~ s/[\.\,]//g;
&html("邮箱大小请指定为数值！") if $mboxmax =~ /\D/;
&html("时区请指定数值！") if $tz =~ /[^\-+\d]/;
if ($localip){
	foreach (split(/[\s,]+/,$localip)){
		my $msg = "本地 IP 地址 $_ 指定不正确。";
		if (/^(\d+)\.(\d+)\.(\d+)\.(\d+)$/){
			&html($msg) if ($1>254 || $2>254 || $3>254 || $4>254);
		} elsif (/^(\d+)\.(\d+)\.(\d+)\.(\d+)\/(\d+)$/){
			&html($msg) if ($1>254 || $2>254 || $3>254 || $4>254 || $5>32);
		} elsif (/^(\d+)\.(\d+)\.(\d+)\.(\d+)-(\d+)\.(\d+)\.(\d+)\.(\d+)$/){
			&html($msg) if ($1>254 || $2>254 || $3>254 || $4>254 || $5>254 || $6>254 || $7>254 || $8>254);
		} else {
			&html($msg);
		}
	}
}
&html("GLST 不能安装在文件夹名含有空格的地方！") if $glstdir =~ /\s/;
&html("JDWM 不能安装在文件夹名含有空格的地方！") if $jdwmdir =~ /\s/;
&html("jdml 不能安装在文件夹名含有空格的地方！") if $jdmldir =~ /\s/;
&html("jdml 数据不能指定在文件夹名含有空格的地方！") if $jdmlroot =~ /\s/;
if ($ipmsg){
	&html("IP Messenger 不能安装在文件夹名含有空格的地方！") if $ipmsg =~ /\s/;
	&html("IP Messenger 没找到！") if !-f $ipmsg;
	&html("IP Messenger 请指定完整扩展名(.exe)！") if $ipmsg !~ /\.exe$/i;
}
&html("LAN 内通知消息有不能使用的文字 ( <b>&lt; &gt; &quot; |</b> )！") if $netsendmsg =~ /[<>|"]/;
&html("Date:字段检查请指定数值！") if ($datecheck && $datecheck =~ /\D/);

## 现有环境的比较
$notice = '';
if ($page == 2 && -f $lcfg){
	%cfg = &get_env($lcfg,'=');
	$cfg{'ctrlport'} = 6017 if !$cfg{'ctrlport'};
	$cfg{'ctrlsport'} = 6018 if !$cfg{'ctrlsport'};
	$cfg{'fingerport'} = 79 if !$cfg{'fingerport'};
	$cfg{'popport'} = 110 if !$cfg{'popport'};
	$cfg{'popsport'} = 995 if !$cfg{'popsport'};
	$cfg{'smtpport'} = 25 if !$cfg{'smtpport'};
	$cfg{'smtpsport'} = 465 if !$cfg{'smtpsport'};
	$cfg{'jdmailexe'} = 'JDMail.exe' if !$cfg{'jdmailexe'};
	foreach(qw(mailroot jdmaildir jdmailexe)){
		${$_.'0'} = $cfg{$_};
		${$_.'0'} =~ s/\\/\\$&/g;
	}
	$jdwadir = Cwd::getcwd();
	$jdwadir =~ s/[\/\\]cgi[\/\\]*$//i;
	$admin0 = &enc_str($admin);
	$pass0 = &enc_str($pass);

	system("$cfg{'apachedir'}\\bin\\$cfg{'apacheusertool'} -cb $cfg{'apachedir'}\\conf\\$cfg{'apacheverifytxt'} $admin $pass >>$errors");
	
	## JDWM/JDML 环境的更新
	foreach (qw(JDWM jdml)){
		my $file;
		my @array;
		if ($_ eq 'JDWM'){
			$file = "$jdwmdir\\cgi\\$lcfg";
			@array = qw(admin pass jdwadir jdmaildir mailroot passmin postmaster robot ctrlprt tz);
		} else {
			$file = "$jdmldir\\cgi\\$lcfg";
			@array = qw(admin pass jdwadir jdmaildir mailroot jdmlroot robot ctrlprt tz);
		}
		
		if (-f $file){
			my ($chk,@tmp,@tmp1);
			open(FILE,$file);
				@tmp = <FILE>;
			close(FILE);
			if (!grep(/^admin\s*=/,@tmp)){
				push(@tmp1,"admin = $admin0\n");
				$chk = 1;
			}
			if (!grep(/^pass\s*=/,@tmp)){
				push(@tmp1,"pass = $pass0\n");
				$chk = 1;
			}
			foreach my $line (@tmp){
				chomp($line);
				($name,$value) = split(/\s*=\s*/,$line);
				if (grep(/^$name$/,@array)){
					if ($name eq 'admin'){
						$line = "admin = $admin0";
						$chk = 1 if $admin0 ne $value;
					} elsif ($name eq 'pass'){
						$line = "pass = $pass0";
						$chk = 1 if $pass0 ne $value;
					} elsif ($name eq 'jdmaildir'){
						my $path = $jdmaildir;
						$path =~ s/\\/\//g;
						$line = "jdmaildir = $path";
						$chk = 1 if $path ne $value;
					} elsif ($name eq 'mailroot'){
						my $path = $mailroot;
						$path =~ s/\\/\//g;
						$line = "mailroot = $path";
						$chk = 1 if $path ne $value;
					} elsif ($name eq 'jdmlroot'){
						my $path = $jdmlroot;
						$path =~ s/\\/\//g;
						$line = "jdmlroot = $path";
						$chk = 1 if $path ne $value;
					} else {
						$line = "$name = $$name";
						$chk = 1 if $$name ne $value;
					}
				}
				push(@tmp1,"$line\n");
			}
			if ($chk && open(FILE,">$file")){
					flock(FILE,2);
					print FILE @tmp1;
				close(FILE);
				$notice .= "<li>$_ 的运行环境已更新。</li>\n";
			}
		}
	}
=cut
	## 服务再登记检查
	if (($jdmaildir0 && $jdmaildir !~ /^$jdmaildir0$/i) || ($jdmailexe0 && $jdmailexe !~ /^$jdmailexe0$/i)){
		my $servicename = $cfg{'jdmailexe'};
		$servicename =~ s/\.exe$//i;
		if ($servicename =~ /^jdmail$/i || $servicename eq ''){$servicename = 'JDMail';}
		my $msg = `net stop $servicename 2>&1`;
		if (-f "$cfg{'jdmaildir'}\\$cfg{'jdmailexe'}"){
			system("$cfg{'jdmaildir'}\\$cfg{'jdmailexe'} --remove>$errors");
		}
		system("$jdmaildir\\$jdmailexe --install-auto>$errors");
		
		$reboot = 1;
		$notice .= "<li>JDMail的运行环境有变更，重新进行了服务的登记。</li>\n";
	}
=cut	
	## 注册表的更新
	if ($mailroot !~ /^$mailroot0$/i || $ctrlport ne "$cfg{'ctrlport'}" || $ctrlsport ne "$cfg{'ctrlsport'}" ||
		$fingerport ne "$cfg{'fingerport'}" || $popport ne "$cfg{'popport'}" || $popsport ne "$cfg{'popsport'}" ||
		$smtpport ne "$cfg{'smtpport'}" || $smtpsport ne "$cfg{'smtpsport'}"){
		my $keyname = $jdmailexe;
		$keyname =~ s/\.exe$//i;
		if ($keyname =~ /^jdmail$/i){$keyname = 'JDMail';}
		
		my $option = &write_reg_option($ctrlport,$ctrlsport,$fingerport,$popport,$popsport,$smtpport,$smtpsport);
		&write_reg($cfg{'JDMAIL_CMD'},$keyname,$DEFAULT_DOMAIN,$mailroot,$option);
		
		$MAIL_ROOT = $mailroot;
		$notice .= "<li>更新了注册表信息。</li>\n";
		$reboot = 1;
	}
	
	## CTRL访问许可/SMTP中继/SMTP白名单(127.0.0.1是否被准许)
	foreach ('ctrl.ipmap.tab','smtp.ipprop.tab','smtprelay.tab'){
		my ($chk,$type,@tmp);
		my $file = "$mailroot\\$_";
		open(FILE,$file) || next;
			@tmp = <FILE>;
		close(FILE);
		if (/^smtprelay/){
			if (grep(/^"*0\.0\.0\.0"*\t"*0\.0\.0\.0/i,@tmp) ||
				grep(/^"*127\.0\.0\.0"*\t"*255\.(255|0)\.(255|0)\.0/i,@tmp) ||
				grep(/^"*127\.0\.0\.1"*\t"*255\.255\.255\.255/i,@tmp)){next;}
			$chk = 1;
			$type = 'SMTP 中继许可';
			unshift(@tmp,"\"127.0.0.0\"\t\"255.255.255.0\"\n");
		} elsif (/^smtp\.ipprop/){
			if (grep(/^"*0\.0\.0\.0\/0"*\t"*WhiteList=1/i,@tmp) ||
				grep(/^"*127\.0\.0\.0\/(8|16|24)"*\t"*WhiteList=1/i,@tmp) ||
				grep(/^"*127\.0\.0\.1\/32"*\t"*WhiteList=1/i,@tmp)){next;}
			$chk = 1;
			$type = 'SMTP 白名单';
			unshift(@tmp,"\"127.0.0.0/24\"\t\"WhiteList=1\"\t\"EaseTLS\"\n");
		} else {
			if (grep(/^"*0\.0\.0\.0"*\t"*0\.0\.0\.0"*\t"*ALLOW"*\t/i,@tmp) ||
				grep(/^"*127\.0\.0\.0"*\t"*255\.(255|0)\.(255|0)\.0"*\t"*ALLOW"*\t/i,@tmp) ||
				grep(/^"*127\.0\.0\.1"*\t"*255\.255\.255\.255"*\t"*ALLOW"*\t/i,@tmp)){next;}
			$type = 'CTRL 访问许可';
			for my $i (1 .. 100){
				if (grep(/\t"*$i"*$/,@tmp)){next;}
				unshift(@tmp,"\"127.0.0.0\"\t\"255.255.255.0\"\t\"ALLOW\"\t$i\n");
				$chk = 1;
				last;
			}
		}
		if ($chk){
			open(FILE,">$file");
				flock(FILE,2);
				print FILE @tmp;
			close(FILE);
			$notice .= "<li>[$type] 已更新。</li>\n";
		}
	}
	
	## JDMail 再起动
	if ($reboot){
		my $servicename = $jdmailexe;
		$servicename =~ s/\.exe$//i;
		my $msg = `net stop $servicename 2>&1`;
		$msg = `net start $servicename 2>&1`;
		$notice .= "<li>JDMail 已重新启动。</li>\n";
	}
	
	## 结果报告
	$notice = "<table align='center' cellpadding=8 cellspacing=0 class='doc131' border=0>\n<tr><td $bgcolor0>$notice</td></tr></table>\n" if $notice;
}

## SSL关联
foreach my $f (qw(libeay32.dll ssleay32.dll)){
	if (!-f "$ENV{'SystemRoot'}\\system32\\$f"){
		if (!-f "$jdmaildir\\$f"){
			$notice .= "SSL/TLS 的使用 $f 必须复制到 $ENV{'SystemRoot'}\\system32 。<br>";
		} else {
			copy("$jdmaildir\\$f","$ENV{'SystemRoot'}\\system32\\$f");
		}
	}
}
if (!-s "$mailroot\\server.cert" || !-s "$mailroot\\server.key"){
	$notice .= "SSL/TLS 的使用 [SSL/TLS的管理] 请制作服务器证书和私钥。<br>";
}

## JDMail管理帐号的追加
$file = "$mailroot\\ctrlaccounts.tab";
$pass1 = &enc_str($pass);
@reg = ();
my ($admin1) = &mod_str($admin);
open(FILE,$file);
	while(<FILE>){
		if (/^"*$admin1"*\t/i){next;}
		push(@reg,$_);
	}
close(FILE);
open(FILE,">$file");
	flock(FILE,2);
	print FILE "\"$admin\"\t\"$pass1\"\n";
	print FILE @reg;
close(FILE);

## jdwa环境的更新
@options = ();
open(FILE,$lcfg);
	while(<FILE>){
		chomp;
		if (/^#/ || /^\s*$/){next;}
		my ($name,$value) = split(/\s*=\s*/,$_);
		next if grep(/^$name$/,@cfg2);
		push(@options,"$_\n");		# 变量的释放
	}
close(FILE);
open(FILE,">$lcfg") || &error('3','环境设置保存失败。');
	flock(FILE,2);
	print FILE "## Saved by $jdwa ver $vcfg\n";
	foreach(@cfg2){
		if ($_ eq 'admin'){
			print FILE "admin = " . &enc_str($admin) . "\n";
			next;
		} elsif ($_ eq 'pass'){
			print FILE "pass = $pass1\n";
			next;
		}
		print FILE "$_ = $$_\n";
	}
	if (@options){print FILE @options;}
close(FILE);

## aliasdomain.tab, smtp.ipprop.tab如果文件不存在，创建
foreach ('aliasdomain.tab','smtp.ipprop.tab'){
	my $file = "$mailroot\\$_";
	if (!-f $file){open(FILE,">$file") && close(FILE);}
}

## 如果JDMail各文件夹不存在，创建
foreach(qw(bin cmdaliases custdomains dnscache domains filters logs msgsync 
	pop3linklocks pop3links pop3locks spool tabindex userauth)){
	if (!-d "$mailroot\\$_"){mkdir("$mailroot\\$_",755);}
}
foreach(qw(local spool temp)){
	if (!-d "$mailroot\\spool\\$_"){mkdir("$mailroot\\spool\\$_",755);}
}
foreach(qw(mx ns)){
	if (!-d "$mailroot\\dnscache\\$_"){mkdir("$mailroot\\dnscache\\$_",755);}
}
foreach(qw(pop3 smtp)){
	if (!-d "$mailroot\\userauth\\$_"){mkdir("$mailroot\\userauth\\$_",755);}
}

## 如果jdwa 各文件夹不存在，创建
foreach(qw(groups spool2 sslconf)){
	if (!-d "$mailroot\\$_"){mkdir("$mailroot\\$_",755);}
}
foreach(qw(in out)){
	my $dir = "$mailroot\\spool2\\$_";
	if (!-d "$dir"){mkdir("$dir",755);}
	if (!-d "$dir\\accounts"){mkdir("$dir\\accounts",755);}
	if (!-d "$dir\\conf"){mkdir("$dir\\conf",755);}
	if (!-d "$dir\\frozen"){mkdir("$dir\\frozen",755);}
	if (!-d "$dir\\index"){mkdir("$dir\\index",755);}
	if (!-d "$dir\\logs"){mkdir("$dir\\logs",755);}
	if (!-d "$dir\\template"){mkdir("$dir\\template",755);}
}

## perl版本
my $pv = $perlver;
$pv =~ s/\D//g;
$pv =~ s/^(\d{4}).*/$1/;
my $UTFok = 1 if $pv >= 5008;	# 对应可能

## jdwa脚本修正(UTF-8另外对应)
$cdir = Cwd::getcwd();
$cdir =~ s/[\/\\]cgi[\/\\]*$//i;
if ($perlver){
	my $cdir2 = $cdir;
	$cdir2 =~ s/\\/\//g;
	foreach my $file ('common_viewmsg.cgi','frozen.cgi','smtpdefer_common.cgi','../setup/confirm.cgi'){
		my ($chk,@tmp);
		open(FILE,$file) || next;
			while (<FILE>){
				if (/^[#;]*use +Encode /){
					if ($UTFok){$_ = "use Encode qw/ encode decode /;\n";}
					else {$_ = "##use Encode qw/ encode decode /;\n";}
					$chk = 1;
				} elsif (/^[#;]*\$UTFok *= /){
					if ($UTFok){$_ = "\$UTFok = 1;\n";}
					else {$_ = "##\$UTFok = 1;\n";}
					$chk = 1;
				}
				# confirm.cgi其他的变量也处理
				if ($file =~ /confirm\.cgi$/){
					$chk = 1;
					s/^\$cfgroot\s*=.*/\$cfgroot = "$cdir2";/;
				}
				push(@tmp,$_);
			}
		close(FILE);
		if ($chk && open(FILE,">$file")){
				flock(FILE,2);
				print FILE @tmp;
			close(FILE);
		}
	}
}

## 文件的设定
## 标准离线过滤器的设定
@in = ($filter_in,'filters.in.cgi','filters.in.tab');
@out = ($filter_out,'filters.out.cgi','filters.out.tab');
foreach my $type ('in','out'){
	my @reg;
	open(FILE,">$mailroot\\filters\\$$type[0]");
		flock(FILE,2);
		print FILE "\"$^X\"\t\"$cdir/cgi/$$type[1]\"\t";
		print FILE "\"\$(FILE)\"\t\"\$(RCPT)\"\t\"\$(FROM)\"\t\"\$(RRCPT)\"\t\"\$(RFROM)\"\t";
		print FILE "\"\$(REMOTEADDR)\"\t\"\$(USERAUTH)\"\n";
	close(FILE);
	
	## 修正标准过滤器
	open(FILE,$$type[1]);
		while (<FILE>){
			chomp;
			next if /^use +Encode +qw\/ +encode +decode +\/;/;
			if (/^\$cdir *=/){
				$_ = "use Encode qw/ encode decode /;\n" if $UTFok;
				$_ .= "\$cdir = '$cdir';";
			}
			push(@reg,"$_\n");
		}
	close(FILE);
	open(FILE,">$$type[1]");
		flock(FILE,2);
		print FILE @reg;
	close(FILE);
	
	## JDMail的定义文件(filters.in.tab,filters.out.tab)标准过滤器的登记
	my $file = "$mailroot\\$$type[2]";
	@reg = ();
	if (!-f $file){open(FILE,">$file") && close(FILE);}
	open(FILE,$file);
		while(<FILE>){
			next if /\t"*$jdwa\_common\.tab"*$/i;	# 删除旧1.55，以前用
			push(@reg,$_);
		}
	close(FILE);
	if (!grep(/\t"*$$type[0]"*$/i,@reg)){
		# 删除重复
		my %count;
		@reg = grep(!$count{$_}++, @reg);
		# 保存
		open(FILE,">$file");
			print FILE @reg;
			print FILE "\"*\"\t\"*\"\t\"0.0.0.0/0\"\t\"0.0.0.0/0\"\t\"$$type[0]\"\n";
		close(FILE);
	}
}

## 在线过滤器设定
@post = ('filters.post-data.cgi','filters.post-data.tab');
@pre  = ('filters.pre-data.cgi','filters.pre-data.tab');
@rcpt = ('filters.post-rcpt.cgi','filters.post-rcpt.tab');
foreach my $type ('post','pre','rcpt'){
	my ($chk,@reg);
	my $file = "$mailroot\\$$type[1]";
	if (!-f $file){open(FILE,">$file") && close(FILE);}
	
	## 修正jdwa过滤器
	open(FILE,$$type[0]) || next;
		while (<FILE>){
			chomp;
			next if /^use +Encode +qw\/ +encode +decode +\/;/;
			if (/^\$cdir *=/){
				$_ = "use Encode qw/ encode decode /;\n" if $UTFok;
				$_ .= "\$cdir = '$cdir';";
			}
			push(@reg,"$_\n");
		}
	close(FILE);
	open(FILE,">$$type[0]");
		flock(FILE,2);
		print FILE @reg;
	close(FILE);
	
	## JDMail定义文件(filters.****.tab)过滤器的登记
	@reg = ();
	my $line = "\"$^X\"\t\"$cdir/cgi/$$type[0]\"\t";
	$line .= "\"\$(FILE)\"\t\"\$(CRCPT)\"\t\"\$(FROM)\"\t\"\$(REMOTEADDR)\"\t";
	$line .= "\"\$(LOCALADDR)\"\t\"\$(USERAUTH)\"";
	my $off;
	open(FILE,$file);
		while (<FILE>){
			if (/cgi\/filter\.$type\.cgi/i){next;}	# 删除到jdwa 2.23为止的定义
			my $str = $$type[0];
			$str =~ s/\./\\$&/g;
			if (/cgi\/$str/i){
				$off = '##' if /^#/;
				next;
			}
			push(@reg,$_);
		}
	close(FILE);
	# 删除重复
	my %count;
	@reg = grep(!$count{$_}++, @reg);
	# 保存
	open(FILE,">$file");
		print FILE @reg;
		print FILE "$off$line\n";
	close(FILE);
}

## 垃圾邮件Word定义文件的处理(v.2.29)
if (-s "$mailroot\\spamwords.tab" && !-f "$mailroot\\$spamintab"){
	rename("$mailroot\\spamwords.tab","$mailroot\\$spamintab");
} else {
	unlink("$mailroot\\spamwords.tab");
}

## 小组数据conversion(v.2.28)
my @groups;
my @members;
if (open(FILE,'config.group.cgi')){
		while (<FILE>){
			chomp;
			my ($key,$value) = split(/\t/,$_);
			next if !$value;
			if ($key =~ /$emreg/){push(@members,$_);}
			else{push(@groups,$_);}
		}
	close(FILE);
	
	my $chk;
	my $root = "$mailroot\\groups";
	my %G;
	mkdir($root,755);
	foreach my $group (@groups){
		my ($id,$name) = split(/\t/,$group);
		my $gid;
		for my $i (1 .. 999){
			my $str = sprintf("%03d",$i);
			if (!-d "$root\\$str"){
				$gid = $str;
				last;
			}
		}
		next if !$gid;
		$G{$id} = $gid;
		mkdir("$root\\$gid",755);
		mkdir("$root\\$gid\\domains",755);
		mkdir("$root\\$gid\\groups",755);
		mkdir("$root\\$gid\\members",755);
		open(FILE,">$root\\$gid\\profile.tab");
			print FILE "ID = $gid\n";
			print FILE "Name = $name\n";
			print FILE "Created = $year/$month/$mday\n";
		close(FILE);
		$chk = 1;
	}
	foreach my $member (@members){
		my ($user,$group) = split(/\t/,$member);
		$user = lc($user);
		open(FILE,">$root\\$G{$group}\\members\\$user") && close(FILE);
	}
	$notice .= "* 转换了小组数据。<br>\n" if $chk;
	unlink('config.group.cgi',"$root\\groups.tab");
}

## 不要文件删除
unlink('spamaddress.cgi','spammers.cgi','spamwords.cgi');	# ver 2.29

## 删除旧的文件
foreach (glob("$tempdir/attachments/*")){
	if ((stat($_))[9] + $index_ttl < time()){unlink($_);}
}
foreach (glob("$tempdir/*.*")){
	my $name = $& if /[^\/]+$/;
	next if ($name eq 'sendmail.log' || $name eq 'mailusers.tab.txt' || $name eq 'password.txt');
	if ((stat($_))[9] + $index_ttl < time()){unlink($_);}
}

## 处理完成，再显示
my $msg = "jdwa环境设置已保存。$fe<br><span class='doc131'>$notice</span>";
if ($page == 2){&ifupdate;}			# ver 1.x --> 2.0 是否更新必要
&logging("jdwa环境设置已运行。",'','');
&html($msg);

### -------------------------------------
sub html {
	local ($rep) = @_;
	if ($page == 1){
		$table = "<table cellpadding=4 cellspacing=0 class='doc151' border=1 width='100%'>\n";
		$table .= "<tr $bgcolor3><td>";
		$rep = "<p>$fs4R$alert $rep$fe</p>" if $rep;
	} else {
		$rep = "<table align='center'><tr><td>$fs4R$alert $rep$fe</table><br>" if $rep;
	}
	
	local ($str1,$str2);
	if (-f $lcfg && !$rep){
		%cfg = &get_env($lcfg,'=');
		if (!&chk_admin('1')){
			$adminok = "$fs2&nbsp;(有效的管理员没有登记。)$fe<br>";
			$admin = $pass = '';
		}
	}
	if (!$dfsort){$dchk1 = $chkd;} else {$dchk2 = $chkd;}
	
	## 过滤器有效吗
	if (&chk_filterOK('in')){$str1 = $sflag;}
	if (&chk_filterOK('out')){$str2 = $sflag;}
	if (&chk_filterOK('pre-data')){$str3 = $sflag;}
	if (&chk_filterOK('post-data')){$str4 = $sflag;}
	
	if ($distribute){$dstr = $chkd;}
	if ($ob_received){$obr = $chkd;}
	if ($ob_remove_received){$obrr = $chkd;}
	&htmlconv(qw(netsendmsg scanoptionmsg));
	
#	&print_header("$jdwa 环境设置","<br>-- <b>v$vcfg、perl:$perlver</b> --");
	&print_header("$jdwa 环境设置","");
	
	print "<form method='post' action='$cgi'>\n";
	print "<input type='hidden' name='perlver' value='$perlver'>\n";
	print "<input type='hidden' name='page' value='$page'>\n";
	print "<input type='hidden' name='SpamScan' value='$SpamScan'>\n";
	
	if ($page == 1){&html_1;} else {&html_2;}
	&print_footer();
	&del_trash();
	exit;
}

### 环境设置 - 基本安装
sub html_1 {
	if (!$rep){
		print <<"EOF";
<p class='doc13'>
进行 $jdwa 的环境设置。请输入下列所有项目。<br>
本菜单 $jdwa 最初安装的时候，只运行一次。
以后的环境设置通过 [环境设置]-[$jdwa 环境设置] 完成。
</p>
EOF
	} else {print $rep;}
	
	print <<"EOF";
$table
<b>管理帐户</b> $adminok<br>
<table cellpadding=0 cellspacing=0 class='doc131' border=0>
<tr><td>■管理帐户名</td>
<td><input name='admin' size=30 maxlength=100 value="$admin" $nosubmit></td></tr>
<tr><td>■管理密码 &nbsp;</td>
<td><input name='pass' size=30 maxlength=100 value="$pass" $nosubmit></td></tr>
</table>
登记控制JDMail的帐号。
在这里登记的帐户，不能使JDMail的本地帐户。
此外，使用 $jdwa 管理JDMail的情况下，您不需要记忆这里的密码，所以，请将用户名和密码尽量复杂一些。
</td></tr>
</table>
<br>

$table
<b>JDMail安装的文件夹/文件夹名</b><br>
<table cellpadding=0 cellspacing=0 class='doc131' border=0>
<tr><td>■安装文件夹 &nbsp;</td>
<td><input name='jdmaildir' size=30 maxlength=50 value="$jdmaildir" $nosubmit></td></tr>
<tr><td>■可执行文件名</td>
<td><input name='jdmailexe' size=30 maxlength=50 value="$jdmailexe" $nosubmit></td></tr>
</table>
JDMail的安装文件夹(JDMail实用程序ctrlclnt.exe的路径)。主控程序是JDMail.exe 。
为安全性，JDMail请安装到 WWW 服务器不能访问的地方。 

</td></tr>
</table>
<br>

$table
<b>MailRoot 文件夹的指定</b><br>
<span class='doc131'>
<input name='mailroot' size=50 maxlength=100 value="$mailroot" $nosubmit><br>
JDMail参照的环境变量 MAIL_ROOT的值 (JDMail 的 server.tab 等 .tab 文件存在的文件夹) 
例如 c:\\usr\\jdmail\\mailroot 。
为安全性，请安装在从WWW服务器不能访问的地方。 
</span></td></tr>
</table>
<br>

$table
<b>postmaster的Email地址</b><br>
<span class='doc131'>
<input name='postmaster' size=50 maxlength=100 value="$postmaster" $nosubmit>$r<br>
postmaster的Email地址：
(1) 成为冻结邮件(最后处理不能保存的邮件)的转移地址。
(2) $jdwa 成为各过滤器发送邮件时的发件地址。 
</span></td></tr>
</table>
<br>

$table
<b>密码的最小位数</b>
<input name='passmin' size=4 maxlength=3 value="$passmin" $nosubmit><br>
<span class='doc131'>指定的用户或管理员帐户的密码的最小长度。</span></td></tr>
</table>
<br>

$table
<b>邮件的最大尺寸(KB)</b>
<input name='mboxmax' size=10 maxlength=7 value="$mboxmax" $nosubmit><br>
<span class='doc131'>
指定邮箱的最大尺寸。
$jdwa 管理Mailer用户的时候，邮箱的尺寸不能超过这个值。
</span></td></tr>
</table>
<br>

$table
<b>时区的指定</b>
<input name='tz' size=7 maxlength=2 value="$tz" $nosubmit><br>
<span class='doc131'>
指定时区相对Greenwich标准时间的时差。在中国有8小时的时差。
</span></td></tr>
</table>
<br>

<p><input type='submit' $confirm2 value='  环境保存  '></p>

</form>
<span class='doc13'>
<ul>
<li>设置信息保存在 $jdwa 的 $lcfg 文件。</li>
<li>$support1</li>
</ul>
</span>
EOF
}

### 环境设置-jdwa环境设置
sub html_2 {
	%cfg = &get_env($lcfg,'=');
	$groot = "$cfg{'mailroot'}\\groups";
	$groot =~ s/\\/\//g;
	$gindex = "$groot/groups.tab";
	
	## 获取域一览
	foreach (&get_domains()){$sDomain .= $_;}
	$sDomain =~ s/"$dfdomain"/$& selected/;
	
	## 获取小组一览
	foreach (&get_group()){
		chomp;
		my ($id,$name) = split(/\t/,$_);
		$sGroup .= "<option value='$id'>$id - $name</option>";
	}
	$sGroup =~ s/'$dfgroup'/$& selected/;
	
	my $bgcolor0 = "bgcolor='#ffe8e8'";
	print "<blockquote>";
	if (!$rep){
		print <<"EOF";
<table align='center' class='doc131'>
<tr><td> $jdwa 的环境设置。<br>
$adminok
$jdwa 如果版本升级，环境没有变更的情况请务必运行本菜单。
</td></tr>
</table>
<br>
EOF
	} else {print $rep;}
	
	print <<"EOF";
<table align='center' cellpadding=1 cellspacing=0 class='doc131' border=0>

<tr $bgcolor0><td><a href="JavaScript:opn_win('$help+admin')">管理用帐户名</a>$r</td>
<td><input name="admin" size=$cols maxlength=100 value="$admin" $nosubmit></td></tr>

<tr $bgcolor0><td><a href="JavaScript:opn_win('$help+pass')">管理用密码</a>$r</td>
<td><input name="pass" size=$cols maxlength=100 value="$pass" $nosubmit></td></tr>

<tr $bgcolor0><td><a href="JavaScript:opn_win('$help+jdmaildir')">JDMail 安装文件夹</a>$r</td>
<td><input name="jdmaildir" size=$cols maxlength=100 value="$jdmaildir" $nosubmit></td></tr>

<tr $bgcolor0><td><a href="JavaScript:opn_win('$help+mailroot')">MailRoot 文件夹</a>$r</td>
<td><input name="mailroot" size=$cols maxlength=100 value="$mailroot" $nosubmit></td></tr>

<tr $bgcolor0><td><a href="JavaScript:opn_win('$help+postmaster')">postmaster的邮件地址</a>$r</td>
<td><input name="postmaster" size=$cols maxlength=100 value="$postmaster" $nosubmit></td></tr>

<tr $bgcolor0><td><a href="JavaScript:opn_win('$help+passmin')">密码最小位数</a>$r</td>
<td><input name="passmin" size=8 maxlength=2 value="$passmin" $nosubmit></td></tr>

<tr $bgcolor0><td><a href="JavaScript:opn_win('$help+mboxmax')">邮箱的最大尺寸(KB)</a>$r</td>
<td><input name="mboxmax" size=8 maxlength=7 value="$mboxmax" $nosubmit></td></tr>

<tr $bgcolor0><td><a href="JavaScript:opn_win('$help+tz')">时区</a>$r</td>
<td><input name="tz" size=8 maxlength=2 value="$tz" $nosubmit></td></tr>

<tr><td><a href="JavaScript:opn_win('$help+robot')">邮件列表处理器的邮件地址 </a> &nbsp;</td>
<td><input name="robot" size=$cols maxlength=100 value="$robot" $nosubmit></td></tr>

<tr><td><a href="JavaScript:opn_win('$help+jdmailexe')">JDMail 运行文件名</a></td>
<td><input name="jdmailexe" size=$cols maxlength=100 value="$jdmailexe" $nosubmit></td></tr>

<tr><td><a href="JavaScript:opn_win('$help+ctrlport')">CTRL 端口(变更注意!!)</a></td>
<td><input name="ctrlport" size=$cols maxlength=256 value="$ctrlport" $nosubmit></td></tr>

<tr><td><a href="JavaScript:opn_win('$help+ctrlsport')">CTRLS 端口(变更注意!!)</a></td>
<td><input name="ctrlsport" size=$cols maxlength=256 value="$ctrlsport" $nosubmit></td></tr>

<tr><td><a href="JavaScript:opn_win('$help+fingerport')">FINGER 端口(变更注意!!)</a></td>
<td><input name="fingerport" size=$cols maxlength=256 value="$fingerport" $nosubmit></td></tr>

<tr><td><a href="JavaScript:opn_win('$help+popport')">POP3 端口(变更注意!!)</a></td>
<td><input name="popport" size=$cols maxlength=256 value="$popport" $nosubmit></td></tr>

<tr><td><a href="JavaScript:opn_win('$help+popsport')">POP3S 端口(变更注意!!)</a></td>
<td><input name="popsport" size=$cols maxlength=256 value="$popsport" $nosubmit></td></tr>

<tr><td><a href="JavaScript:opn_win('$help+smtpport')">SMTP 端口(变更注意!!)</a></td>
<td><input name="smtpport" size=$cols maxlength=256 value="$smtpport" $nosubmit></td></tr>

<tr><td><a href="JavaScript:opn_win('$help+smtpsport')">SMTPS 端口(变更注意!!)</a></td>
<td><input name="smtpsport" size=$cols maxlength=256 value="$smtpsport" $nosubmit></td></tr>

<tr><td><a href="JavaScript:opn_win('$help+localip')">本地 IP 地址</a></td>
<td><input name="localip" size=$cols maxlength=512 value="$localip" $nosubmit></td></tr>

<tr><td><a href="JavaScript:opn_win('$help+dfgroup')">默认显示组</a></td>
<td><select name='dfgroup'>
<option value=''>▽请选择</option>
$sGroup</select></td></tr>

<tr><td><a href="JavaScript:opn_win('$help+dfdomain')">默认显示域</a></td>
<td><select name='dfdomain'>
<option value=''>▽请选择</option>
$sDomain</select></td></tr>

<tr><td><a href="JavaScript:opn_win('$help+dfsort')">默认的显示方法</a></td>
<td>
<input type='radio' name="dfsort" $dchk1 value='0'>域名分类&nbsp;
<input type='radio' name="dfsort" $dchk2 value='1'>用户排序</td></tr>

<tr><td><a href="JavaScript:opn_win('$help+glstdir')">GLST 安装文件夹</a></td>
<td><input name="glstdir" size=$cols maxlength=100 value="$glstdir" $nosubmit></td></tr>

<tr><td><a href="JavaScript:opn_win('$help+jdwmdir')">JDWM 安装文件夹</a></td>
<td><input name="jdwmdir" size=$cols maxlength=100 value="$jdwmdir" $nosubmit></td></tr>

<tr><td><a href="JavaScript:opn_win('$help+jdmldir')">JDML 安装文件夹</a></td>
<td><input name="jdmldir" size=$cols maxlength=100 value="$jdmldir" $nosubmit></td></tr>

<tr><td><a href="JavaScript:opn_win('$help+jdmlroot')">JDML 数据文件夹</a></td>
<td><input name="jdmlroot" size=$cols maxlength=100 value="$jdmlroot" $nosubmit></td></tr>

<tr><td><a href="JavaScript:opn_win('$help+ipmsg')">IP Messenger 的路径</a></td>
<td><input name="ipmsg" size=$cols maxlength=100 value="$ipmsg" $nosubmit></td></tr>

<tr><td><a href="JavaScript:opn_win('$help+netsendmsg')">LAN 通知消息</a>$str1</td>
<td><input name="netsendmsg" size=$cols maxlength=256 value="$netsendmsg" $nosubmit></td></tr>

<tr><td><a href="JavaScript:opn_win('$help+datecheck')">Date: 字段检查</a>$str1</td>
<td><input name="datecheck" size=7 maxlength=3 value="$datecheck" $nosubmit>日以上偏离的邮件放入垃圾箱</td></tr>

<tr><td><a href="JavaScript:opn_win('$help+distribute')">收信过滤</a>$str1</td>
<td><input type='checkbox' name="distribute" value="1" $dstr> 运行</td></tr>

<tr><td><a href="JavaScript:opn_win('$help+removereceived')">Received: 删除(outbound)</a>$str2</td>
<td><input type='checkbox' name="ob_remove_received" value="1" $obrr> 运行</td></tr>

<tr><td><a href="JavaScript:opn_win('$help+received')">Received: 替换(outbound)</a>$str2</td>
<td><input type='checkbox' name="ob_received" value="1" $obr> 运行</td></tr>

<tr><td><a href="JavaScript:opn_win('$help+received')">&nbsp;- Received: localhost 替换</a>$str2</td>
<td><input name="ob_received_helodomain" size=$cols maxlength=100 value="$ob_received_helodomain" $nosubmit></td></tr>

<tr><td><a href="JavaScript:opn_win('$help+received')">&nbsp;- Received: 本地地址替换</a>$str2&nbsp;</td>
<td><input name="ob_received_ip" size=$cols maxlength=15 value="$ob_received_ip" $nosubmit></td></tr>

<tr><td colspan=2>
$hr
<input type="submit" value="  环境保存  " $confirm2></td></tr>
</table>
</form>
EOF
	
	my $sslnotice = &chk_ssl('P','S');
	$sslnotice = '请使用 [基本设置]-[注册表的登记] 停止SSL服务 。' if !$sslnotice;
	
	print <<"EOF";
<table align='center' class='doc13'>
<tr><td>
<ul>
<li>$r 必填字段。</li>
<li>单击设置名，会显示相关的详细说明。</li>
<li>$sflag 表示 [过滤器管理] 功能停止。</li>
<li>设置信息保存在 $jdwa 的 $lcfg 文件。</li>
<li>$sslnotice</li>
<li>您当前的IP地址是 <b>$ENV{REMOTE_ADDR}</b> 。</li>
<li>$support1</li>
</ul></td></tr>
</table>
</blockquote>
EOF
}

### ver 1.x --> 2.x 的更新是否同意确认
sub ifupdate {
	%cfg = &get_env($lcfg,'=');
	
	foreach my $domain (&get_domains){
		if ($domain =~ />([^<]+)</){$domain = $1;}
		foreach(qw(jdwminfo jdwm.tab jdwmmenu addressbook)){
			if (-f "$mailroot\\domains\\$domain\\$_"){&update_now();}
		}
	}
	
	my @users = &get_userlist('','','1');	# 获取所有用户
	
	my $cfga;
	foreach(@cfgm){$cfga .= "$_ ";}
	foreach(@cfgu){$cfga .= "$_ ";}
	
	foreach my $user (@users){
		my @tmp;
		if ($user =~ />([^<]+)</){$user = $1;}
		my ($name,$domain) = split(/\@/,$user);
		my $base = "$mailroot\\domains\\$domain\\$name";
		foreach(qw(conf addressbook autoreply autoreplylist deny jdwminfo folder memo count 
			footer goodbye header help info welcome .avscan .no.avscan .spamscan)){
			if (-f "$base\\$_"){&update_now();}
		}
		open(FILE,"$base\\user.tab") || next;
			while(<FILE>){
				chomp;
				s/"//g;
				s/\t.+//;
				if ($cfga =~ /$_ /){&update_now();}
			}
		close(FILE);
	}
}

### 运行更新
sub update_now {
	&print_header("$jdwa 环境设置","<br>-- <b>v. $vcfg</b> --");
	
	print <<"EOF";
<table align='center'>
<tr><td align='center'>$fs4R$msg</font></td></tr>
</table>
<br>
<br>

<table cellpadding=12 cellspacing=0 border=0 align='center'>
<tr><td $bgcolor2>
<table>
<tr><td><p align='center'>$fs4R请更新环境 !! <b>$_[0]</b>$fe</p>
<span class='doc13'>
<p>旧 $jdwa 1.x 版本的设定文件找到了。$_[0]<br>
1.x 版本跟 2.x 版本的间设定文件没有兼容性。
</p>

<p>请单击以下的链接 2.x 对应转换旧设定文件。</p>
</span>

<p align='center'><a href='1to2.cgi?$page'>
<img src='$idir/arrow2.gif' height=13 width=31 title='新格式转换' border=0>
$fs5 2.x 执行相应的转换$fe
<img src='$idir/arrow2.gif' height=13 width=31 title='新格式转换' border=0>
</a></p>

$hr
<span class='doc13'>
<ul>
<li>变换立刻开始。</li>
<li>帐号数多的情况在转换上上要花费时间。</li>
<li>转换后不能还原到 1.x 环境。</li>
</ul>
</td></tr>
</table></td></tr>
</table>
EOF
	&print_footer();
	exit;
}
