<?
class mail
{//DigiHex Systems\\


	function init() {}


	function send($send_to, $subject, $content, $files=false, $skip_foot=false, $reply_to=false, $embed_images=true, $skip_html_dom=false) {
		global $X, $CONF, $MAILER;

		$this->ENABLE_MAIL_GFX=true;

		if(!is_object($MAILER)) require($this->PATH.'/phpmailer.php');
		$MAILER=new PHPMailer();

		$INPUT_CONTENT=$content;
		if($skip_foot!=true && $this->ENABLE_MAIL_GFX!=true) $content.=$this->add_foot();


		if($embed_images==false) {
			$content=str_replace('url(/userfiles/', 'url('.BASE.'/userfiles/', $content);
			$content=str_replace('="/userfiles/', '="'.BASE.'/userfiles/', $content);
			$content=str_replace('="/images/', '="'.BASE.'/images/', $content);
		}

		$n='<br />
';
		$content=str_replace(array('<br />','<br/>','<br>'),array($n,$n,$n),$content);


		if($CONF->MAILER_SMTP_ENABLED==true) {
			$MAILER->IsSMTP();
			$MAILER->SMTPAuth		= true;
			$MAILER->SMTPDebug	= 0; //SMTP debug: 0=off, 1=errors and messages, 2=messages only
			$MAILER->Port			= $CONF->MAILER_SMTP_PORT;
			$MAILER->Host			= $CONF->MAILER_SMTP_HOST;
			$MAILER->Username		= $CONF->MAILER_SMTP_USER;
			$MAILER->Password		= $CONF->MAILER_SMTP_PASS;
			$MAILER->From 		  	= $CONF->MAILER_SMTP_USER;

			if(empty($reply_to)) $reply_to=array($CONF->MAILER_FROM_EMAIL, $CONF->MAILER_FROM_NAME);
		} else {
			$MAILER->IsMail();
			$MAILER->From = $CONF->MAILER_FROM_EMAIL;
		}

		$MAILER->CharSet 	= "utf-8";
		$MAILER->FromName = $CONF->MAILER_FROM_NAME;
		$MAILER->Subject 	= $this->encoder($subject);
		$MAILER->AltBody 	= strip_tags($content);
//		$MAILER->WordWrap	= 80;


		if(!empty($reply_to)) {
			if(is_array($reply_to)) {
				$MAILER->AddReplyTo($reply_to[0], $reply_to[1]);
			} else {
				$MAILER->AddReplyTo($reply_to);
			}
		}

		if(is_array($files) && count($files)>0) foreach($files as $file) $MAILER->AddAttachment($file[0], $file[1]);


		if($this->ENABLE_MAIL_GFX==true) {
			$content=$this->insert_mail_gfx($content);
		}


		if($skip_html_dom!=true) {
			$content=$this->add_dom($subject, $content);
		}
		$MAILER->MsgHTML($content);

		if(!@is_array($send_to)) {
			$temp=$send_to;
			unset($send_to);
			$temp=str_replace(array(' ',',',';'), array('',';',';'), $temp);
			$send_to=@explode(';',$temp);
			unset($temp);
		}

		if(count($send_to)>0) {
			foreach($send_to as $email) {
				$MAILER->ClearAddresses();
				$MAILER->AddAddress($email);
				$send_status=$MAILER->Send();

				if($send_status!=true || $send_error==true) {
					if(empty($mailer_err)) $mailer_err=$MAILER->MSG['error'];
					if(empty($mailer_full_err)) $mailer_full_err=$MAILER->FULL_ERROR;

					$input_data=array(
						'send_to'			=> $send_to,
						'subject'			=> $subject,
						'content'			=> $INPUT_CONTENT,  //not modif input
						'files'				=> $files,
						'skip_foot'			=> $skip_foot,
						'reply_to'			=> $reply_to,
						'embed_images'		=> $embed_images,
						'skip_html_dom'	=> $skip_html_dom,
					);

					if($this->RESEND==false) $X->DB->query(' INSERT INTO _mail_unsend (email, subject, body, date, error, full_error, input_data) VALUES ("'.$X->STR->in($email).'","'.$X->STR->in($subject).'","'.$X->STR->in($content).'","'.date('Y-m-d H:i:s').'","'.$mailer_err.'","'.$mailer_full_err.'","'.$X->STR->in(serialize($input_data)).'") ');
					$send_error=true;
				}
			}
			return ($send_error==true ? false : true);
		} else {
			return false;
		}
	}


	function resend($input_data) {
		global $X;

		$in=unserialize($X->STR->out($input_data));
		$this->RESEND=true;
		$state=$this->send($in['send_to'], $in['subject'], $in['content'], $in['files'], $in['skip_foot'], $in['reply_to'], $in['embed_images'], $in['skip_html_dom']);
		$this->RESEND=false;
		return $state;
	}


	function add_dom($subject, $body) {
		return '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional //EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>'.$subject.'</title>
<style type="text/css">
	html, body, table, td { color:#000; font-family:Arial, Tahoma, sans-serif; font-size:12px; }
	p { margin-top:0px; }
	a { outline-style:none; color:#E30613; }
</style>
</head>

<body style="margin:0px; padding:0px;">

'.$body.'

</body>
</html>';
	}


	function add_foot() {
		global $X;

		return '
			<div style="clear:both; margin-bottom:50px;"></div>
			<span style="display:inline-block; color:#aaa; border-top:1px dotted #aaa; font-size:11px;">
				<span style="display:inline-block; padding:6px 0px 30px 0px;">'.$X->CONF->MAILER_FOOT_TEXT.'</span>
			</span>
		';
	}


	function encoder($input, $charset='utf-8') {
		preg_match_all('/(\s?\w*[\x80-\xFF]+\w*\s?)/', $input, $matches);
		foreach($matches[1] as $value) {
			$replacement = preg_replace('/([\x20\x80-\xFF])/e', '"=".strtoupper(dechex(ord("\1")))', $value);
			$input = str_replace($value, '=?'.$charset.'?Q?'.$replacement.'?=', $input);
		}
		return $input;
	}


	function is_email($email) {
		if(empty($email)) return false;
		$pattern="^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$";
		return preg_match("#^".str_replace('#','/#',$pattern)."$#i", $email);
	}


	function protect($email, $non_click=false) {
		$parts=@explode('.', $email);
		$new_parts=@implode('</span>.<span>', $parts);
		$new_mail=str_replace('@', '<span>@</span>', '<span>'.$new_parts.'</span>');

		if($non_click==true) return '<script type="text/javascript">document.write("'.$new_mail.'");</script>';
		return '<script type="text/javascript">/*<![CDATA[*/ document.write("<a href=\"#\" onclick=\"window.location=\'mailto:\'+this.textContent||this.innerText; return false;\">'.$new_mail.'</a>"); /*]]>*/</script>';
	}


	function get_template($klucz, $data=false, $force_lang=false) {
		global $X;

		if(!empty($data) && count($data)>0) foreach($data as $key => $value) $VARS[$key]=$value;

		$tmpl=$X->DB->fast(' SELECT id, title, content FROM _mail_templates WHERE klucz="'.$klucz.'" '.(!empty($force_lang) ? 'AND lang="'.$force_lang.'"':'').' ');
		if(empty($tmpl['id'])) die('EMAIL TEMPLATE NOT FOUND: <b>'.$klucz.'</b>');

		$title=$X->STR->outt($tmpl['title']);
		$body=$X->STR->out($tmpl['content']);

		preg_match_all('/{{([^}]+)}}/e', $title, $vars);
		if(count($vars[1])>0) foreach($vars[1] as $t) $title=str_replace('{{'.$t.'}}', $VARS[$t], $title);
		preg_match_all('/{{([^}]+)}}/e', $body, $vars);
		if(count($vars[1])>0) foreach($vars[1] as $t) $body=str_replace('{{'.$t.'}}', $VARS[$t], $body);

		return array('title'=>$title, 'body'=>$body);
	}


	function enable_gfx() {
		$this->ENABLE_MAIL_GFX=true;
	}


	function enable_unsubscribe() {
		$this->ENABLE_MAIL_UNSUBSCRIBE=true;
	}


	function wylacz($html) {
		if(!empty($html)) {
			$this->WYLACZ_HTML='
				<tr><td><br /><br /></td></tr>
				<tr><td style="background:#ddd; color:#666; font-size:12px; line-height:16px; padding:15px 20px 15px 20px">'.$html.'</td></tr>
			';
		}
	}


	function insert_mail_gfx($html) {
		global $X;

		if($this->ENABLE_MAIL_GFX!=true) return false;
		unset($this->ENABLE_MAIL_GFX);

		$ret='
			<table cellpadding="0" cellspacing="0" style="width:100%;">
				<tr>
					<td style="padding:10px 0px 10px 20px; background:#f4f5f6; border-bottom:3px solid #E30613; font-size:0px;">
						<img src="'.ROOT.'/images/email_logo.png" width="136" height="48" alt="" border="0" />
					</td>
				</tr>
				<tr>
					<td style="padding:30px 20px 50px 20px">
						'.$html.'
					</td>
				</tr>
				'.$this->WYLACZ_HTML.'
				<tr>
					<td style="padding:15px 20px 15px 20px; background:#E30613; color:#fff; font-size:12px;">
						'.$X->CONF->MAILER_FOOT_TEXT.'
					</td>
				</tr>
			</table>
		';

		unset($this->WYLACZ_HTML);
		return $ret;

//				'.($this->ENABLE_MAIL_UNSUBSCRIBE==true ? '<div style="float:right; margin-top:8px;">Jeśli nie chcesz otrzymywać wiadomości tego typu, kliknij <a href="'.BASE.'/wypisz_sie/" target="_blank" style="color:#fff"><b>TUTAJ</b></a> i wypisz się.</div>':'').'
	}


}//DigiHex Systems\\
?>