<?php
define('THIS_SCRIPT', 'sendemail');
include_once 'global.php';
include_once CACHE_PATH.'mailconfig.php';
@set_time_limit(300);
defined('MAIN_DOMAIN_NAME') AND exit('Access denied');
$lang = load_lang($lang, 'sendemail' );
checklogin();
header("content-Type: text/html; charset=".$charset);
head();
if ( strpos($sysinfo['flag'],'20,') === false ){
	show_msg($lang['readme_tit'],$lang['error.str1'],0,'','','','');
	exit;
}
PageLoad();
footer();
function Pageload(){
	global $dv,$db,$lang,$groups_list,$action,$record_row,$username_id,$doaction,$del_mem,$bgColor,$sysusername;
	usergroups_info();
	if($action=="create_email"){
		create_email();
	}
	elseif($action=="showlog"){
		task_list();
	}
	switch ($doaction){
		case "del":
			task_del();
		break;
		case "sendok":
			email_send();
		break;
	}
include printout('sendemail');
}
function usergroups_info(){
	global $dv,$lang,$db,$groups_list;
	$groups_list=array();
	$sql=$db->query("select usergroupid,title,usertitle,parentgid from {$dv}usergroups where parentgid>0 order by usergroupid");
	while ($arr=$db->fetch_array($sql)){
		$groups_list[]=$arr;
	}
$db->free_result($sql);
}
function create_email(){
	global $dv,$db,$lang,$UserName,$title,$body,$usertype;
	$UserName=str_replace(" ","",$_POST['UserName']);
	$title=str_replace(" ","",$_POST['title']);
	$body=$_POST['body'];
	$usertype=intval($_POST['usertype']);
	if($usertype==1){
		if($UserName==""){
			show_msg($lang['sys.info'],$lang['sys.info1'],0,'','',$lang['url'],$lang['cmdback']);
		exit;
		}
	}
	if($title=="" or $body==""){
		show_msg($lang['sys.info'],$lang['sys.info2'],0,'','',$lang['url'],$lang['cmdback']);
	exit;
	}
	switch ($usertype){
		case 1:
			user_names();//用户名单;
		break;
		case 2:
			user_groups();//用户组;
		break;
		case 3:
			user_all();//所有用户;
		break;
	}
}
function user_names(){
	global $dv,$lang,$db,$UserName,$title,$body,$usertype,$sysusername;
	$UserName=str_replace(" ","",$_POST['UserName']);
	$title=str_replace(" ","",$_POST['title']);
	$title=str_replace("br","",$title);
	$body=str_replace("br","",$_POST['body']);
	$usertype=intval($_POST['usertype']);
	$username_list=explode(",",$UserName);
	if(count($username_list)>100){
		show_msg($lang['sys.info'],$lang['sys.info4'],0,'','',$lang['url'],$lang['cmdback']);
	exit;
	}
	$spaceid=0;
	for ($i=0;$i<count($username_list);$i++){
		$user_id=$db->scalar("select userid from {$dv}user where username = '".$username_list[$i]."' order by userid");
		if($user_id==""){
			$spaceid+=1;
		}
		else{
			$userid_list.=$user_id.",";
		}
	}
	$userid_list=substr($userid_list,0,-1);
	if($userid_list==""){
		show_msg($lang['sys.info'],$lang['sys.info5'],0,'','',$lang['url'],$lang['cmdback']);
	exit;
	}
	else{
		$send_num=count($username_list)-$spaceid;
		$residual_num=count($username_list)-$spaceid;
		$ip=forumusertrueip();
		$addtime=strtotime("now");
		$edittime=strtotime("now");
		$master=$sysusername;
		$record_content=$userid_list.$lang['link.str'].$title.$lang['link.str'].$body.$lang['link.str'].$send_num.$lang['link.str'].$residual_num.$lang['link.str'].$master.$lang['link.str'].$ip.$lang['link.str'].$addtime.$lang['link.str'].$edittime."br";
		@chmod($lang['post_file'],0777);
		if (is_writable($lang['post_file'])){
			if (!$handle = fopen($lang['post_file'],'a')){
				show_msg($lang['sys.info'],$lang['sys.info6'],0,'','',$lang['url'],$lang['cmdback']);
			exit;
			}
			if (fwrite($handle, $record_content)===FALSE) {
				show_msg($lang['sys.info'],$lang['sys.info6'],0,'','',$lang['url'],$lang['cmdback']);
			exit;
			}
			if($spaceid>0){
				show_msg($lang['sys.info'],$lang['sys.info18'].$spaceid.$lang['sys.info19'],1,'','',$lang['url'],$lang['cmdback']);
				fclose($handle);
			exit;
			}
			else{
				show_msg($lang['sys.info'],$lang['sys.info7'],1,'','',$lang['url'],$lang['cmdback']);
				fclose($handle);
			exit;
			}
		} 
		else {
			show_msg($lang['sys.info'],$lang['sys.info6'],0,'','',$lang['url'],$lang['cmdback']);
		exit;
		}
	}
$db->free_result($user_id);
}
function task_list(){
	global $lang,$record_row;
	$record_row=array();
	@chmod($lang['post_file'],0777);
	if($fp=fopen($lang['post_file'],'r')){
		if(filesize($lang['post_file'])===0){
			show_msg($lang['sys.info'],$lang['sys.info8'],0,'','',$lang['url'],$lang['cmdback']);
		exit;
		}
		else{
			$recordset=fread($fp,filesize($lang['post_file']));
			$record_row=explode("br",$recordset);
			fclose($fp);
		}
	}
}
function task_del(){
	global $lang,$DelNodes;
	$get_row=$_POST['DelNodes'];
	if(count($get_row)=="" or count($get_row)===0){
		show_msg($lang['sys.info'],$lang['sys.info23'],0,'','',$lang['url'],$lang['cmdback']);
	exit;
	}
	@chmod($lang['post_file'],0777);
	if($fp=fopen($lang['post_file'],'r+')){
		$recordset=fread($fp,filesize($lang['post_file']));
		$record_row=explode("br",$recordset);
		$num=count($record_row);
		for ($i=0;$i<$num;$i++){
			if(!in_array($i,$get_row)){
				$mem.=$record_row[$i]."br";
			}
		}
		$mem=substr($mem,0,-2);
		$rfp=fopen($lang['post_file'],'w');
		if(fwrite($rfp,$mem)!==false){
			show_msg($lang['sys.info'],$lang['sys.info9'],1,'','',$lang['url'],$lang['cmdback']);
		exit;
		}
	}
	fclose($rfp);
	fclose($fp);
}
function email_send(){ 
	global $lang,$dv,$db,$email_num,$DelNodes,$sysusername;
	$get_row=$_POST['DelNodes'];
	if(count($get_row)=="" or count($get_row)===0){
		show_msg($lang['sys.info'],$lang['sys.info23'],0,'','',$lang['url'],$lang['cmdback']);
	exit;
	}
	$email_num=intval($_POST['email_num']);
	if($email_num=="" or $email_num===0){//发送的邮件数;
		show_msg($lang['sys.info'],$lang['sys.info10'],0,'','',$lang['url'],$lang['cmdback']);
	exit;
	}
	@chmod($lang['post_file'],0777);
	if($fp=fopen($lang['post_file'],'r+')){
		$record_size=fread($fp,filesize($lang['post_file']));
		$record_row=explode("br",$record_size);//记录分割;
		$num=count($record_row);//得到记录数;
		$num=$num-1;
		for ($i=0;$i<$num;$i++) {
			if(in_array($i,$get_row)){//如果是发送这条信息的话要记录下来，进行分割;
				$send_info=$record_row[$i];//得到要发送的记录;
				$info_list=explode($lang['link.str'],$send_info);
				$title=$info_list[1];//邮件标题;
				$body = $info_list[2]; //邮件内容;
				$userid_list=explode(",",$info_list[0]);
				$idnum=count($userid_list);//得到发信的所有用户ID数;
				if(intval($info_list[4])>$email_num){
					$residual_email=$info_list[4]-$email_num;
				}
				else{//计算未发送的邮件数;
					$residual_email=0;
				}
				if($idnum>$email_num){
					$m_count=$email_num;
					for($n=$email_num;$n<$idnum;$n++){
						$other_userid.=$userid_list[$n].",";//保存未发送的用户ID，以备下次发送;
					}
					$other_userid=substr($other_userid,0,-1);
				}
				else{
					$m_count=$idnum;
					$other_userid=$sysusername;
				}
				for($j=0;$j<$m_count;$j++){//根据发邮件的数目来取得用户ID和邮件数;
					$email=$db->scalar("select useremail from {$dv}user where userid='".$userid_list[$j]."'");
					$email_arr.=$email.",";
				}
				$update_time=strtotime("now");
				$full_info=$other_userid.$lang['link.str'].$title.$lang['link.str'].$body.$lang['link.str'].$info_list[3].$lang['link.str'].$residual_email.$lang['link.str'].$info_list[5].$lang['link.str'].$info_list[6].$lang['link.str'].$info_list[7].$lang['link.str'].$update_time."br";//把信息再保存下来，以备下次发送;
				$email_arr=substr($email_arr,0,-1);
				$email_arr=explode(",",$email_arr);//邮件列表;
				$mailHeader = "From:$master_mail\n";
				$mailHeader.= "Content-Type:text/html;\n charset=gb2312;\n";
				$successnums=0;
				for ($k=0;($k<$email_num)&&$email_arr[$k];$k++){//开始发送邮件;
					(sendmail($email_arr[$k],$title,$body,"{$fsetting['forumname']} <{$fsetting['mastermail']}>")) AND ($successnums=$successnums+1);
				}
				$mem.=$full_info;
			}
			else{
				$mem.=$record_row[$i]."br";
			}
		}
		$rfp=fopen($lang['post_file'],'w');
		if(fwrite($rfp,$mem)!==false){
			show_msg($lang['sys.info'],$lang['sys.info20'].$successnums.$lang['sys.info21'],1,'','',$lang['url'],$lang['cmdback']);
		exit;
		}
		else{
			show_msg($lang['sys.info'],$lang['sys.info22'],0,'','',$lang['url'],$lang['cmdback']);
		exit;
		}
	}
	fclose($rfp);
	fclose($fp);
}
function user_all(){
	global $lang,$db,$dv,$title,$boby,$sysusername;
	$title=str_replace(" ","",$_POST['title']);
	$title=str_replace("br","",$title);
	$body=str_replace("br","",$_POST['body']);
	$sql=$db->query("select userid from {$dv}user");
	while ($arr=$db->fetch_array($sql)){
		$userid_list.=$arr['userid'].",";
		$userid_count+=1;//所有用户的ID;
	}
	$userid_list=substr($userid_list,0,-1);
	if($userid_list==""){
		show_msg($lang['sys.info'],$lang['sys.info5'],0,'','',$lang['url'],$lang['cmdback']);
	exit;
	}
	else{
		$ip=forumusertrueip();
		$addtime=strtotime("now");
		$edittime=strtotime("now");
		$master=$sysusername;
		$record_content=$userid_list.$lang['link.str'].$title.$lang['link.str'].$body.$lang['link.str'].$userid_count.$lang['link.str'].$userid_count.$lang['link.str'].$master.$lang['link.str'].$ip.$lang['link.str'].$addtime.$lang['link.str'].$edittime."br";
		@chmod($lang['post_file'],0777);
		if (is_writable($lang['post_file'])){
			if (!$handle = fopen($lang['post_file'],'a')){
				show_msg($lang['sys.info'],$lang['sys.info6'],0,'','',$lang['url'],$lang['cmdback']);
			exit;
			}
			if (fwrite($handle, $record_content)===FALSE) {
				show_msg($lang['sys.info'],$lang['sys.info6'],0,'','',$lang['url'],$lang['cmdback']);
			exit;
			}
			else{
				show_msg($lang['sys.info'],$lang['sys.info7'],1,'','',$lang['url'],$lang['cmdback']);
				fclose($handle);
			exit;
			}
		} 
		else {
			show_msg($lang['sys.info'],$lang['sys.info6'],0,'','',$lang['url'],$lang['cmdback']);
		exit;
		}
	}
$db->free_result($sql);
}
function user_groups(){
	global $dv,$lang,$db,$UserName,$title,$body,$GetGroupID,$LoginTime,$LoginTimeType,$RegTime,$RegTimeType,$Logins,$LoginsType,$UserPost,$UserPostType,$UserTopic,$UserTopicType,$UserBest,$UserBestType,$sysusername;
	$search_str="";
	$title=str_replace(" ","",$_POST['title']);
	$body=$_POST['body'];
	$title=str_replace("br","",$title);
	$body=str_replace("br","",$_POST['body']);
	$GetGroupID=$_POST['GetGroupID'];
	$LoginTime=intval($_POST['LoginTime']);
	$LoginTimeType=intval($_POST['LoginTimeType']);
	$RegTime=intval($_POST['RegTime']);
	$RegTimeType=intval($_POST['RegTimeType']);
	$Logins=intval($_POST['Logins']);
	$LoginsType=intval($_POST['LoginsType']);
	$UserPost=intval($_POST['UserPost']);
	$UserPostType=intval($_POST['UserPostType']);
	$UserTopic=intval($_POST['UserTopic']);
	$UserTopicType=intval($_POST['UserTopicType']);
	$UserBest=intval($_POST['UserBest']);
	$UserBestType=intval($_POST['UserBestType']);
	if(count($GetGroupID)=="" or count($GetGroupID)===0){
		show_msg($lang['sys.info'],$lang['sys.info25'],0,'','',$lang['url'],$lang['cmdback']);
	exit;
	}
	else{
		for($j=0;$j<33;$j++){
			if(in_array($j,$GetGroupID)){
				$userid_list.=$j.",";
			}
		}
		$userid_list=substr($userid_list,0,-1);
	}
	$ip=forumusertrueip();
	$addtime=strtotime("now");
	$edittime=strtotime("now");
		$master=$sysusername;
	if($LoginTime!=""){//最后登录时间;
		$endlogintime=dateAdd('d', -$LoginTime, gmdate('Y-m-d 23:59:59'), '');
		if($LoginTimeType===0)
			$search_str.="lastlogin<='".$endlogintime."' and ";
		else 
			$search_str.="lastlogin>='".($endlogintime+1)."' and ";
	}
	if($RegTime!=""){//注册时间;
		$endRegTime=dateAdd('d', -$RegTime, gmdate('Y-m-d 23:59:59'), '');
		if($RegTimeType===0)
			$search_str.="joindate<='".$endRegTime."' and ";
		else 
			$search_str.="joindate>='".($endRegTime+1)."' and ";
	}
	if($Logins!="")//登录次数;
		if($LoginsType===0)
			$search_str.="userlogins>".$Logins." and ";
		else 
			$search_str.="userlogins<".$Logins." and ";
	if($UserPost!="")//发表文章;
		if($UserPostType===0)
			$search_str.="userpost>".$UserPost." and ";
		else
			$search_str.="userpost<".$UserPost." and ";
	if($UserTopic!="")//主题文章;
		if($UserTopicType===0)
			$search_str.="usertopic>".$UserTopic." and ";
		else
			$search_str.="usertopic<".$UserTopic." and ";
	if($UserBest!="")//精华文章;
		if($UserBestType===0)
			$search_str.="userisbest>".$UserBest." ";
		else
			$search_str.="userisbest<".$UserBest." ";
	else 
		$search_str=substr($search_str,0,strlen($search_str)-5);
	if($search_str=="")
		$search_sql=$db->query("select userid from {$dv}user where usergroupid in (".$userid_list.") order by userid");
	else
		$search_sql=$db->query("select userid from {$dv}user where usergroupid in (".$userid_list.") and ".$search_str." order by userid");
	while($usreidarr=$db->fetch_array($search_sql)){
		$userid_arr.=$usreidarr['userid'].",";
		$send_num+=1;
		$residual_num+=1;
	}
	$userid_arr=substr($userid_arr,0,-1);	$record_content=$userid_arr.$lang['link.str'].$title.$lang['link.str'].$body.$lang['link.str'].$send_num.$lang['link.str'].$residual_num.$lang['link.str'].$master.$lang['link.str'].$ip.$lang['link.str'].$addtime.$lang['link.str'].$edittime."br";
	@chmod($lang['post_file'],0777);
	if (is_writable($lang['post_file'])){
		if (!$handle = fopen($lang['post_file'],'a')){
			show_msg($lang['sys.info'],$lang['sys.info6'],0,'','',$lang['url'],$lang['cmdback']);
		exit;
		}
		if (fwrite($handle, $record_content)===FALSE) {
			show_msg($lang['sys.info'],$lang['sys.info6'],0,'','',$lang['url'],$lang['cmdback']);
		exit;
		}
		if($spaceid>0){
			show_msg($lang['sys.info'],$lang['sys.info18'].$spaceid.$lang['sys.info19'],1,'','',$lang['url'],$lang['cmdback']);
			fclose($handle);
		exit;
		}
		else{
			show_msg($lang['sys.info'],$lang['sys.info7'],1,'','',$lang['url'],$lang['cmdback']);
			fclose($handle);
		exit;
		}
	} 
	else {
		show_msg($lang['sys.info'],$lang['sys.info6'],0,'','',$lang['url'],$lang['cmdback']);
	exit;
	}
$db->free_result($search_sql);
}

function sendmail($mailto,$title,$body,$mailfrom){
	global $msetting;
	switch($msetting['mailmod']){
		case 0:
			return 0;
			break;
		case 1:
			if (@mail($mailto,$title,$body,$mailfrom)){
				return 1;
			} else{
				return 0;
			}
			break;
		case 2:
			$writed = 0;
			$getsbuf='';
            $db_charset="gb2312";
            $smtpserver=$msetting['server']==""?"smtp.".substr($msetting['username'],strpos($msetting['username'],"@")+1):$msetting['server'];
            if(!$fp=fsockopen($smtpserver,$msetting['port'],$errno,$errstr,5))return false;
            if(substr(fgets($fp,512),0,3)!="220") return false;
            if($msetting['auth']==1) {
               fwrite($fp,"HELO dvbbs.com\r\n");
               while($rt=strtolower(fgets($fp,512))){
                     if(strpos($rt,"-")!==3 || empty($rt)){
                        break;
                     }elseif(strpos($rt,"2")!==0){
                        return false;
                     }
                }
               fwrite($fp, "AUTH LOGIN \r\n");
               if(substr(fgets($fp,512),0,3) != 334) return false;
               fwrite($fp, base64_encode($msetting['username'])." \r\n");
               if(substr(fgets($fp,512),0,3) != 334) return false;
               fwrite($fp, base64_encode($msetting['password'])." \r\n");
               if(substr($rt=fgets($fp,512),0,3) != 235) return false;
             } else {
                  fwrite($fp, "HELO dvbbs.com\r\n");
             }
             $mailfrom=$msetting['username'];
             $mailfrom = preg_replace("/.*\<(.+?)\>.*/", "\\1", $mailfrom);
             fwrite($fp, "MAIL FROM: <$mailfrom>\r\n");
             if(substr(fgets($fp,512),0,3) != 250) return false;
             fwrite($fp, "RCPT TO: <$mailto>\r\n");
             if(substr(fgets($fp,512),0,3) != 250) return false;
             fwrite($fp, "DATA\r\n");
             if(substr(fgets($fp,512),0,3) != 354) return false;
             $title = str_replace("\n",' ',$title);
             $msg = "Date: ".Date("r")."\r\n";
             $msg .= "From: =?$db_charset?B?".base64_encode($msetting['username'])."?=<$mailfrom>\r\n";
             $msg .= "To: =?$db_charset?B?".base64_encode($mailto)."?=<$mailto>\r\n";
             $msg .= "Subject: =?$db_charset?B?".base64_encode($title)."?=\r\n";
             $msg .= "X-mailer: mail by dvbbs php\r\n";
             $msg .= "Mime-Version: 1.0\r\n";
             $msg .= "Content-Type: text/html;\r\n";
             $msg .= "\tcharset=\"$db_charset\"\r\n";
             $msg .= "Content-Transfer-Encoding: base64\r\n\r\n";
             $msg .= base64_encode($body)."\r\n.\r\n";
             fwrite($fp, $msg);
             fwrite($fp, "QUIT\r\n");
             fclose($fp);
             return true;
		case 3:
			ini_set('SMTP', $msetting['server']);
			ini_set('smtp_port', $msetting['port']);
			ini_set('sendmail_from', $mailfrom);
			if (@mail($mailto,$title,$body,"From: {$mailfrom}")){
				return 1;
			} else{
				return 0;
			}
			break;
		default:
			return 0;
			break;
	}
}
?>