<?php
// +----------------------------------------------------------------------
// | Sunnyi 多语商城建站系统 (Build on ThinkPHP)
// +----------------------------------------------------------------------
// | Copyright (c) 2009 http://www.sunnyi.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 商易网络(admin@sunnyi.cn)
// +----------------------------------------------------------------------

// 邮件模块
class EmailAction extends CommonAction{
//	public function demo()
//	{
//		$mail = new Mail();	
//
//		$mail->AddAddress("fzmatthew@163.com","收件人名称");
//		$mail->IsHTML(true); // 设置邮件格式为 HTML
//		$mail->Subject = "测试发送邮件"; // 标题
//		$mail->Body = '<B>这是一封测试邮件</B>'; // 内容
//		
//		if(!$mail->Send())
//		{
//			echo "发送失败 <p>";
//			echo "错误信息: " . $mail->ErrorInfo;
//			exit;
//		}
//		
//		echo "发送成功";
//	}
	
	public function startSend()
	{
		$this->assign('now',toDate(time()));
		$this->display();
	}
	public function doSend()
	{
		$time = $_REQUEST['time'];
		if(!check_time($time))
		{
			$this->error(L('TIME_FORMAT_ERROR'),true);
		}
		else 
		{
			$time = parseToTimeSpanFull($time);
			$this->sendMails($time,true);
		}
	}
	
	//用于发件的私有函数
	// $time 发送xxxx时间之前的所有数据
	private function sendMails($time,$ajax=true)
	{
		if(sunnyiC("MAIL_ON")==0)
		{
			$this->error(L("TITLE_MAIL_ON")." ".L("TITLE_MAIL_ON_0"),$ajax);
		}
		else 
		{
			$mail_list = D("MailList")->where('send_time<='.$time.' and status=0')->findAll();
			foreach($mail_list as $mail_item)
			{
				$mail_item['status'] = 1;
				$mail_item['send_time'] = time();
				D("MailList")->save($mail_item);				
				
				
				$address_send_list = D("MailAddressSendList")->where("mail_id=".$mail_item['id'])->findAll();
				foreach($address_send_list as $address_item)
				{
					$address_item = D("MailAddressList")->where("status=1 and id=".$address_item['mail_address_id'])->find();
					if($address_item)
					{
						$userinfo = D("User")->getById($address_item['user_id']);
						if($userinfo)
						{
							$username = $userinfo['user_name'];
							if($userinfo['nickname']!='')
							{
								$username.="(".$userinfo['nickname'].")";
							}
						}
						else 
						{
							$username = L("NO_USER");
						}
						$mail = new Mail();	
						$mail->IsHTML($mail_item['is_html']); // 设置邮件格式为 HTML
						$mail_title = $mail_item['mail_title'];
						$mail_content = $mail_item['mail_content'];
						$mail_title = str_replace("{\$username}",$username,$mail_title);
						$mail_content = str_replace("{\$username}",$username,$mail_content);
						
						$mail->Subject = $mail_title; // 标题					
						$mail->Body =  $mail_content; // 内容
						$mail->AddAddress($address_item['mail_address'],$username);	
						if(!$mail->Send())
						{
							$this->error($mail->ErrorInfo,$ajax);
						}	
					}			
				}
								
			}
			$this->success(L("SEND_SUCCESS"),$ajax);
		}
	}
		
	public function template()
	{
		$this->assign("template_list",D("MailTemplate")->findAll());
		$this->display();
	}
	public function loadTemplate()
	{
		$id = intval($_REQUEST['id']);
		$template_info = D("MailTemplate")->getById($id);
		echo json_encode($template_info);
	}
	public function updateTemplate()
	{
		D("MailTemplate")->create();
		if(D("MailTemplate")->save())
		{
			$this->success (L('EDIT_SUCCESS'));
		}
		else 
		{
			$this->error (L('EDIT_FAILED'));
		}
		
	}
	
	//邮件地址列表相关方法
	public function addressList()
	{
	//列表过滤器，生成查询Map对象
		$map = $this->_search ("MailAddressList");
		if (method_exists ( $this, '_filter' )) {
			$this->_filter ( $map );
		}

		$model = D ("MailAddressList");
		if (! empty ( $model )) {
			$this->_list ( $model, $map );
		}
		$this->display();
	}
	public function forbid() {
		$name=$this->getActionName();
		$model = D ("MailAddressList");
		$pk = $model->getPk ();
		$id = $_REQUEST [$pk];
		$condition = array ($pk => array ('in', $id ) );
		$list=$model->forbid ( $condition );
		if ($list!==false) {			
			$this->saveLog(1);
			$this->assign ( "jumpUrl", $this->getReturnUrl () );
			$this->success ( L('FORBID_SUCCESS') );
		} else {
			$this->saveLog(0);
			$this->error  (  L('FORBID_FAILED') );
		}
	}
	public function resume() {
		//恢复指定记录
		$name=$this->getActionName();
		$model = D ("MailAddressList");
		$pk = $model->getPk ();
		$id = $_GET [$pk];
		$condition = array ($pk => array ('in', $id ) );
		if (false !== $model->resume ( $condition )) {
			$this->saveLog(1);
			$this->assign ( "jumpUrl", $this->getReturnUrl () );
			$this->success ( L('RESUME_SUCCESS') );
		} else {
			$this->saveLog(0);
			$this->error ( L('RESUME_FAILED') );
		}
	}
	public function addMailAddress()
	{
		$this->display();
	}
	public function editMailAddress()
	{
		$model = M ( "MailAddressList" );
		$id = $_REQUEST [$model->getPk ()];
		$vo = $model->getById ( $id );
		$this->assign ( 'vo', $vo );
		$this->display ();
	}
	public function insertMailAddress()
	{
		//B('FilterString');
		$model = D ("MailAddressList");
		if (false === $model->create ()) {
			$this->error ( $model->getError () );
		}
		//保存当前数据对象
		$list=$model->add ();
		if ($list!==false) { //保存成功
			$this->saveLog(1,$list);
//			$this->assign ( 'jumpUrl', Cookie::get ( '_currentUrl_' ) );
			$this->success (L('ADD_SUCCESS'));
		} else {
			//失败提示
			$this->saveLog(0,$list);
			$this->error (L('ADD_FAILED'));
		}
	}
	public function updateMailAddress() {
		//B('FilterString');
		$model = D ( "MailAddressList" );
		if (false === $model->create ()) {
			$this->error ( $model->getError () );
		}
		// 更新数据
		$list=$model->save ();
		if (false !== $list) {
			//成功提示
			$this->saveLog(1);
//			$this->assign ( 'jumpUrl', Cookie::get ( '_currentUrl_' ) );
			$this->success (L('EDIT_SUCCESS'));
		} else {
			//错误提示
			$this->saveLog(0);
			$this->error (L('EDIT_FAILED'));
		}
	}
	public function foreverdeleteMailAddress() {
		//删除指定记录
		$model = D ("MailAddressList");
		if (! empty ( $model )) {
			$pk = $model->getPk ();
			$id = $_REQUEST [$pk];
			if (isset ( $id )) {
				$condition = array ($pk => array ('in', explode ( ',', $id ) ) );
				if (false !== $model->where ( $condition )->delete ()) {
					//echo $model->getlastsql();
					$this->saveLog(1);
					$this->success (L('DEL_SUCCESS'));
				} else {
					$this->saveLog(0);
					$this->error (L('DEL_FAILED'));
				}
			} else {
				$this->saveLog(0);
				$this->error ( L('INVALID_OP') );
			}
		}
		$this->forward ();
	}
	
	
	//邮件列表
	public function mailList()
	{
		//列表过滤器，生成查询Map对象
		$map = $this->_search ("MailList");
		if (method_exists ( $this, '_filter' )) {
			$this->_filter ( $map );
		}

		$model = D ("MailList");
		if (! empty ( $model )) {
			$this->_list ( $model, $map );
		}
		$this->display();
	}
	public function addMail()
	{
		$this->assign('now',date("Y-m-d H:i:s"));
		$this->display();
	}
	
	public function insertMail()
	{
		//B('FilterString');
		$model = D ("MailList");
		if (false === $model->create ()) {
			$this->error ( $model->getError () );
		}
		//保存当前数据对象
		$list=$model->add ();
		if ($list!==false) { //保存成功
			$this->saveLog(1,$list);
//			$this->assign ( 'jumpUrl', Cookie::get ( '_currentUrl_' ) );
			$this->success (L('ADD_SUCCESS'));
		} else {
			//失败提示
			$this->saveLog(0,$list);
			$this->error (L('ADD_FAILED'));
		}
	}
	public function editMail()
	{
		$model = M ( "MailList" );
		$id = $_REQUEST [$model->getPk ()];
		$vo = $model->getById ( $id );
		$this->assign ( 'vo', $vo );
		$this->display ();
	}
	public function updateMail() {
		//B('FilterString');
		$model = D ( "MailList" );
		$data = $model->create ();
		if (false === $data) {
			$this->error ( $model->getError () );
		}
		// 更新数据

		$list=$model->save ($data);

		if (false !== $list) {
			//成功提示
			$this->saveLog(1);
//			$this->assign ( 'jumpUrl', Cookie::get ( '_currentUrl_' ) );
			$this->success (L('EDIT_SUCCESS'));
		} else {
			//错误提示
			$this->saveLog(0);
			$this->error (L('EDIT_FAILED'));
		}
	}
	public function foreverdeleteMail() {
		//删除指定记录
		$model = D ("MailList");
		if (! empty ( $model )) {
			$pk = $model->getPk ();
			$id = $_REQUEST [$pk];
			if (isset ( $id )) {
				$condition = array ($pk => array ('in', explode ( ',', $id ) ) );
				if (false !== $model->where ( $condition )->delete ()) {
					//echo $model->getlastsql();
					D("MailAddressSendList")->where("mail_id=".$id)->delete();
					$this->saveLog(1);
					$this->success (L('DEL_SUCCESS'));
				} else {
					$this->saveLog(0);
					$this->error (L('DEL_FAILED'));
				}
			} else {
				$this->saveLog(0);
				$this->error ( L('INVALID_OP') );
			}
		}
		$this->forward ();
	}
	
	
	//邮件的发送地址列表
	public function sendAddressList()
	{
		$map['status'] = 1;
		$model = D ("MailAddressList");
		if (! empty ( $model )) {
			$this->_list ( $model, $map );
		}
		$list = $this->get("list");
		$id = intval($_REQUEST['id']);
		$mail_send_address_list = D("MailAddressSendList")->where("mail_id=".$id)->findAll();
		
		foreach($list as $k=>$v)
		{
			foreach($mail_send_address_list as $kk=>$vv)
			{
				if($v['id']==$vv['mail_address_id'])
				{
					$list[$k]['checked'] = true;
					break;
				}
			}
		}
		$this->assign('mail_id',$id);
		$this->assign("list",$list);
		$this->display();
	}
	
	public function saveSendAddress()
	{
		$mail_id = intval($_POST['mail_id']);
		if(D("MailList")->where("id=".$mail_id)->count()==0)
		{
			$this->error (L('MAIL_NOT_EXIST'));
		}
		else 
		{
			D("MailAddressSendList")->where("mail_id=".$mail_id)->delete();
			$mail_address_ids = array();
			if($_POST['check_all'])
			{
				$mail_address_list = D ("MailAddressList")->where("status=1")->findAll();
				foreach($mail_address_list as $mail_address_item)
				{
					array_push($mail_address_ids,$mail_address_item['id']);
				}
			}
			else
			$mail_address_ids = $_POST['key'];

			foreach($mail_address_ids as $mail_address_id)
			{
				$data['mail_id'] = $mail_id;
				$data['mail_address_id'] = $mail_address_id;
				
				D("MailAddressSendList")->add($data);
			}
			$this->success(L("EDIT_SUCCESS"));
		}
	}
}
?>