<?php
include_once "../../tools/inc.php";
$page = include("../common.php");
include("../tools/function.string.php");
include("../tools/function.sql.php");
include("../tools/class.stat.php");
$status=0;
$n=$settings["rec_count"];
$max=100;
$table="newsletters".$config["table_prefix"];
$table_c="custom_fields".$config["table_prefix"];
$table_un="users_newsletter".$config["table_prefix"];
$table_a="autoresponder".$config["table_prefix"];
$table_cs="campaign_schedule".$config["table_prefix"];
$table_u="users".$config["table_prefix"];
$table_group="mailing_groups".$config["table_prefix"];
$table_smtp="smtp_accounts".$config["table_prefix"];
$table_mn="msg_newsletters".$config["table_prefix"];
$access=check_level("Newsletters");
$sort_d=(isset($sort_d) ? 1 : 0);

$sort_link=new Link($link->get());
$link->add("sort_d");
$filter_link=new Link($link->get());
$link->add("_search");
$sort_link->add("_search");
$offset_link=new Link($link->get());
$link->add("offset");

$message_list=array(
	1 => "{rs:MSG_NEWSLETTER} {rs:MSG_CREATED}",
	2 => "{rs:MSG_NEWSLETTER} {rs:MSG_UPDATED}",
	3 => "{rs:MSG_NEWSLETTERS} {rs:MSG_DELETED}",
	4 => "{rs:MSG_SENT}",
	5 => "{rs:MSG_MAILING_DELIVERY_FAILED}",
	6 => "{rs:MSG_SENT_ALL}",
	7 => "{rs:ERROR_SUBSCRIBERS_COUNT}",
);

$recipients_list=array(
	1 => "{rs:SUBSCRIBERS_STATUS_1}",
	0 => "{rs:SUBSCRIBERS_STATUS_0}",
	2 => "{rs:SUBSCRIBERS_STATUS_2}",
	3 => "{rs:SUBSCRIBERS_STATUS_3}",
);

$mail_format_list=array(
	0 => "{rs:MAIL_FORMAT_0}",
	1 => "{rs:MAIL_FORMAT_1}",
);

function send_message($data) {
	global $PATH, $_SERVER, $config, $db, $table, $table_c, $settings, $status;
	$sql="select * from $table where id='".$data["newsletter_id"]."' and status='$status'";
	$rs=$db->select($sql);
	$newsletter=$rs[0];
	$message=($data["receive_format"] ? $newsletter["text_content"] : $newsletter["html_header"].$newsletter["html_css"].$newsletter["html_content"]);
	$groups=explode(",", $newsletter["groups"]);
	$f=array(
		"%subject%",
		"%name%",
		"%email%",
		"%format%",
		"%encoding%",
		"%unsubscribe%",
		"%properties%",
		"%date%",
	);
	$v=array(
		$newsletter["subject"],
		$data["name"],
		$data["mail"],
		($data["receive_format"] ? "Plain text" : "HTML"),
		$data["encoding"],
		"http://".$_SERVER['HTTP_HOST'].str_replace("admin/", "", $PATH).
		"unsubscribe/?id=0&group_id=".$groups[0],
		"",
		date($settings["date_format"]),
	);
	$sql="select cf.id, if(cf.enabled=1, cf.def_value, '') as value from $table_c cf";
	$rs=$db->select($sql);
	for ($i=0; $i<count($rs); $i++) {
		$f[]="%custom_field_".$rs[$i]["id"]."%";
		$v[]=$rs[$i]["value"];
	}
	$message=change_links2(str_replace($f, $v, $message), $data["receive_format"], "n-{$newsletter['id']}", 0);
	$message=ChangeImageURL($message);
	$array=array(
		"login"         => $data["smtp"]["login"],
		"password"      => $data["smtp"]["password"],
		"host"          => $data["smtp"]["host"],
		"port"          => $data["smtp"]["port"],
		"from_name"     => $newsletter["from_name"],
		"from"          => $newsletter["from_mail"],
		"reply_to"      => $newsletter["reply_mail"],
		"to_name"       => $data["name"],
		"to"            => $data["mail"],
		"subject"       => $newsletter["subject"],
		"message"       => $message,
		"charset"       => $data["encoding"],
		"content_type"  => ($data["receive_format"] ? "text/plain" : "text/html"),
	);
	include("../tools/class.mime.php");
	include("../tools/class.smtp.php");
	$smtp=new SMTP($array);
	$newsletter['files']=($newsletter['files'] ? explode('|', $newsletter['files']) : array());
	for ($i=0; $i<count($newsletter['files']); $i++) {
		$smtp->addAttach((strpos($PATH, 'admin/') ? '../' : '').'files/'.$newsletter['files'][$i]);
	}
	return (isset($data["smtp"]["login"]) ? $smtp->send() : $smtp->send_mail());
}

function get_subscribers_count($data) {
        global $db, $config;
	$table_s="subscribers".$config["table_prefix"];
	$table_sg="subscribers_group".$config["table_prefix"];
	$table_g="mailing_groups".$config["table_prefix"];
	$sql="select s.id from
                $table_s s,
                $table_sg sg,
                $table_g g
        where
                s.status='".$data["recipients"]."' and
                s.id=sg.subscribers_id and
                sg.group_id=g.id and
                g.enabled=1 and
                g.id in (".$data["groups"].")
        group by s.id";
	return $db->count($sql);
}

$message=new Message();
$error=new Message("error");
if (isset($_r)) $message->add($message_list[$_r]);
if (isset($del) and (isset($access["delete"]) or isset($access["admin"]))) {
	$del=(is_array($del) ? implode($del, ", ") : $del);
	$sql="";
	//$sql[]="delete from $table_a where newsletter_id in ($del)".(isset($user_permissions['newsletters_list']) ? " and newsletter_id in (".$user_permissions['newsletters_list'].")" : "");
	//$sql[]="delete from $table_cs where newsletter_id in ($del)".(isset($user_permissions['newsletters_list']) ? " and newsletter_id in (".$user_permissions['newsletters_list'].")" : "");
	$sql[]="update $table set status='-1' where id in ($del)".(isset($user_permissions['newsletters_list']) ? " and id in (".$user_permissions['newsletters_list'].")" : "");
	//$sql[]="delete from $table where id in ($del)".(isset($user_permissions['newsletters_list']) ? " and id in (".$user_permissions['newsletters_list'].")" : "");
	//$sql[]="delete from $table_un where id in ($del)".(isset($user_permissions['newsletters_list']) ? " and id in (".$user_permissions['newsletters_list'].")" : "");
        $db->execute_all($sql);
	$link->add("_r", 3);
	$db->close();
	header("Location: ".$link->get());
	exit;
} elseif (isset($send_all) and (isset($access["edit"]) or isset($access["admin"]))) {
	if (isset($step) and $step==1) {
		// Change mailing deliveries count
		$sql="update $table set deliveries_count=deliveries_count+1, last_delivery='".time()."', last_delivery_user='".$ui[id]."'";
		$db->execute($sql);
		$stat=new stat();
		$stat->update("NEWSLETTER[{$send_all}].DELIVERIES.ALL", 0);
		$stat->update("NEWSLETTER[{$send_all}].DELIVERIES");

		$sql="select count(*) from $table_mn where newsletter_id='$send_all' and status=0";
		$page->section('NEWSLETTER_SEND_ALL_1');
		$page->assign(array(
			'count'		=> $db->count($sql, true),
			'id'		=> $send_all,
			"WINDOW_TITLE"	=> "{rs:EDIT_NEWSLETTERS_SEND_ALL}",
		));
	} else {
		$sql="select * from $table where id='$send_all' and status='$status'";
		list($data)=$db->select($sql);
		if (isset($data['id'])) {
			$count=get_subscribers_count($data);
			if (!$count) {
				$db->close();
				$link->add('_r', 7);
				header("Location: ".$link->get());
				exit;
			}
			$page->section('NEWSLETTER_SEND_ALL_0');
			$page->assign(array(
				'count'		=> ceil($count/$max),
				'id'		=> $send_all,
				"WINDOW_TITLE"	=> "{rs:EDIT_NEWSLETTERS_SEND_ALL}",
			));
		} else {
			$db->close();
			header("Location: ".$link->get());
			exit;
		}
	}
} elseif (isset($send) and (isset($access["edit"]) or isset($access["admin"]))) {
	if (!isset($r)) {
		$data=array(
			"name"		=> get_val($table_u, "name", "where id='".$ui["id"]."'"),
			"mail"		=> get_val($table_u, "mail", "where id='".$ui["id"]."'"),
			"encoding"	=> $settings["encoding"],
		);
	}
	if (isset($save)) {
		$r=check_array($r);
		if (!check_email($r["mail"])) $error->add("{rs:ERROR_MAIL}");
		if (!$error->count) {
			$r["newsletter_id"]=$send;
			$rs=get_rec($table, "where id='$send'");
			$sql="select s.* from $table n, $table_smtp s where
				n.id='$send' and
				n.status='$status' and
				n.smtp=s.id";
			$rs=$db->select($sql);
			if (isset($rs[0])) $r["smtp"]=$rs[0];
			$_r=(send_message($r) ? 4 : 5);
			$link->add("_r");
			$db->close();
			header("Location: ".$link->get());
			exit;
		} else {
			$data=html_string($r, true, "html_content");
		}
	} else $data=html_string($data, false, "html_content");
	$page->section("NEWSLETTERS_SEND");
	get_row_from_array("RECEIVE_FORMAT_SELECT", $mail_format_list, $data["receive_format"]);
	get_row_from_table("ENCODING_SELECT", "encodes".$config["table_prefix"], $data["encoding"], "code", "title");
	$data["BACK_LINK"]=($link->get() ? $link->get() : './');
	$data["BACK_TITLE"]="{rs:TITLE_NEWSLETTERS}";
	$data["WINDOW_TITLE"]="{rs:EDIT_NEWSLETTERS_SEND}";
	$page->assign($data);
} elseif (isset($edit) and (isset($access["edit"]) or isset($access['view']) or isset($access["admin"]))) {
	$sql="select * from $table where id='$edit' and status='$status'".(isset($user_permissions['newsletters_list']) ? " and id in (".$user_permissions['newsletters_list'].")" : "");
	$rs=$db->select($sql);
	$data=$rs[0];
        if (!isset($data["id"])) {
		$edit=0;
		$r["date_created"]=time();
		$r["owner_id"]=$ui["id"];
		$data["from_name"]=$settings["mail_from_name"];
		$sql="select count(*) from $table where owner_id='".$ui['id']."'";
		if ($user_permissions['max_newsletters ']>0 and $db->count($sql, true)>=$user_permissions['max_newsletters ']) $error->add('{rs:ERROR_LIMIT} {rs:ERROR_LIMIT_MAX_NEWSLETTERS}');
	} else {
		$edit=$data["id"];
		$r["date_created"]=$data["date_created"];
		$r["owner_id"]=$data["owner_id"];
		$data['files']=($data['files'] ? explode('|', $data['files']) : array());
		$data["groups"]=explode(",", $data["groups"]);
	}
        if (isset($save)) {
		$r["id"]=$edit;
		if ($save) {
			$r=check_array($r, "html_header, html_css, html_content");
			if (!$r["name"] or !$r["subject"]) $error->add("{rs:ERROR_REQUIRED_FIELDS}");
			if (!check_email($r["from_mail"])) $error->add("{rs:ERROR_FROM_MAIL}");
			//if (!check_email($r["reply_mail"])) $error->add("{rs:ERROR_REPLY_MAIL}");
			if (isset($user_permissions['groups_list']) and $r["groups"]) $r["groups"]=array_intersect($r["groups"], explode(", ", $user_permissions['groups_list']));
			if (!$error->count and !isset($access['edit']) and !isset($access['admin'])) $error->add('{rs:ERROR_ACCESS_RESTRICTED}');
			if (!$error->count) {
				$src=array('/&amp;/i', '/(<a[^>]+href=\\\")([^\\\]*)(%unsubscribe%\\\"[^>]*>)/i');
				$rep=array('&', '$1$3');
				$r["html_content"]=preg_replace($src, $rep, $r["html_content"]);
				$r['files']=array();
				if ($data['files']) {
					foreach ($data['files'] as $key => $val) {
						if (in_array($key, $r['attach'])) $r['files'][]=$val;
						else @unlink("../files/$val");
					}
				}
				include "../tools/class.files.php";
				$upload=new Files();
				$files=array();
				if ($_FILES['r']['name']) {
					foreach($_FILES['r']['name'] as $key => $val) {
						if ($upload->upload_file($_FILES['r'], $key)) {
							$r['files'][]=$upload->dest;
						}
					}
				}
				$r['files']=implode('|', $r['files']);
				if (count($data['groups']) and isset($user_permissions['groups_list'])) $r["groups"]=array_merge(($r["groups"] ? $r["groups"] : array()), array_diff($data['groups'], explode(', ', $user_permissions['groups_list'])));
				$r["groups"]=(is_array($r["groups"]) ? implode(',', $r["groups"]) : $r["groups"]);
				$r["modify_user"]=$ui["id"];
				$r["modify_time"]=time();
				$r["status"]=$status;
				$fields="date_created, name, subject, from_mail, from_name, reply_mail, recipients, groups, smtp, pop3, text_content, html_header, html_css, html_content, owner_id, modify_user, modify_time, status, files";
				$sql=($edit ? get_sql_update($table, $fields, $r,"where id='$edit'") : get_sql_insert($table, $fields, $r));
				$db->execute($sql);
				$sql="";
				if ($edit) $sql="delete from $table_cs where
					newsletter_id='$edit' and
					group_id not in (".($r["groups"] ? $r["groups"] : 0).")";
				else {
					$edit= mysql_insert_id();
					if (!$access["admin"]) {
						$r=array(
							"user_id"	=> $ui["id"],
							"newsletter_id"	=> $edit,
						);
						$sql=get_sql_insert($table_un, "user_id, newsletter_id", $r);
					}
				}
				if ($sql) $db->execute($sql);
		                $db->close();
				if ($r['action']=='send') $link->add('send_all', $edit);
				else $link->add("_r", ($edit ? 2 : 1));
		                header("Location: ".$link->get());
		                exit;
			} else {
				$r['files']=$data['files'];
				$data=html_string($r, true);
			}
		} else {
			$info=get_rec("templates".$config["table_prefix"], "where id='".$r["template_id"]."'");
			$info=html_string($info, false);
			$r=check_array($r, "html_header, html_css, html_content");
			$r=html_string($r, true);
			$r["text_content"]=$info["text_content"];
			$r["html_header"]=$info["html_header"];
			$r["html_css"]=$info["html_css"];
			$r["html_content"]=$info["html_content"];
			$data=$r;
		}
	} else {
		$data=html_string($data, false);
		$r['attach']=array_keys(is_array($data['files']) ? $data['files'] : array($data['files']));
	}
	$page->section("NEWSLETTERS_EDIT");
	get_row_from_array("RECIPIENTS_SELECT", $recipients_list, $data["recipients"]);
	$sql="select id, title from $table_group ".(isset($user_permissions['groups_list']) ? " where id in (".$user_permissions['groups_list'].")" : "")."order by position";
	$array=get_row_from_sql("GROUPS_SELECT", $sql, $data["groups"]);
	$data['mg_list']=(count($array)>0);
	$sql="select id, title from templates".$config["table_prefix"]." where owner_id='".$r["owner_id"]."' order by title";
	get_row_from_sql("TEMPLATES_SELECT", $sql, $data["template_id"]);
	if ($user_permissions['mailing_smtp'] or $access["admin"]) {
		$sql="select id, title from smtp_accounts".$config["table_prefix"].(isset($user_permissions['smtp_list']) ? " where id in (".$user_permissions['smtp_list'].")" : '')." order by title";
		get_row_from_sql("SMTP_SELECT", $sql, $data["smtp"]);
	}
	$sql="select id, title from pop3_accounts".$config["table_prefix"]." where owner_id='".$r["owner_id"]."' order by title";
	get_row_from_sql("POP3_SELECT", $sql, $data["pop3"]);
	if ($user_permissions['attachments'] or $access["admin"]) {
		$data['attachments']=1;
		$data['attach_count']=count($data['files']);
		get_row_from_array('ATTACH_LINE', $data['files'], $r['attach']);
	}
	include("../tools/var.tmp.php");
	get_row_from_array("VAR_LIST", $var_tmp_list);
	$sql="select id, title from $table_c where enabled=1 and owner_id='".$r["owner_id"]."'";
	get_row_from_sql("CUSTOM_FIELDS_VAR", $sql);
	$data["BACK_LINK"]=($link->get() ? $link->get() : './');
	$data["BACK_TITLE"]="{rs:TITLE_NEWSLETTERS}";
	$data["WINDOW_TITLE"]=($data['id'] ? $data['name'] : "{rs:EDIT_NEWSLETTER}");
        $page->assign($data);
} elseif (isset($access["view"]) or isset($access["admin"])) {
	if (isset($edit) or isset($del) or isset($permission)) $error->add("{rs:ERROR_ACCESS_RESTRICTED}");
        $page->section("NEWSLETTERS");
	$where="where status='$status'";
	$where=get_search_where("name", $_search, $where);
	if (isset($user_permissions['newsletters_list'])) $where.=" and id in (".$user_permissions['newsletters_list'].")";
        $sql="select count(*) from $table $where";
        $rs=$db->select($sql);
        $count=$rs[0][0];
        $i=ceil($count/$n)-1;
        $offset=(($offset>$i) ? $i : ($offset<0 ? 0 : $offset));
        $sql="select * from $table $where order by name".($sort_d ? " DESC" : "")." limit ".($offset*$n). ", $n";
	$rs = $db->select($sql);
        for ($i=0; $i<count($rs); $i++) {
		$data=$rs[$i];
		$data['name']=shortStr($data['name']);
                $page->addrow("LINE", $data);
        }
	$sort_link=$sort_link->get();
        $page->assign(array(
                "count"         	=> $count,
                "offset"        	=> get_new_offsets($count, $n, $offset_link->get(), $offset),
		"search"		=> html_string($_search),
		"BACK_LINK"		=> $PATH,
		"BACK_TITLE"		=> "{rs:TITLE_MAIN_MENU}",
		"sort_by_subject"	=> $sort_link.($sort_d ? ($sort_link ? '' : './') : ($sort_link ? '&' : '?')."sort_d=1"),
		"sort_subject_img"	=> ($sort_d ? "_asc" : "_desc"),
		"WINDOW_TITLE"		=> "{rs:TITLE_NEWSLETTERS}",
        ));
	$page->section("SHOW_SEARCH");
} else {
	$page->section("ACCESS_DENIED");
	$error->add("{rs:ERROR_ACCESS_RESTRICTED}");
}
add_to_tree("{rs:TITLE_NEWSLETTERS}", "newsletters/");
$db->close();
$page->assign(array(
	"TITLE"			=> "{rs:TITLE_NEWSLETTERS}",
	"ERROR"			=> ($error->count ? $error->get() : ""),
	"MESSAGE"		=> ($message->count ? $message->get() : ""),
	"LINK"			=> $link->get(),
	"FILTER_LINK"		=> $filter_link->get(),
	"is_newsletters"	=> 1,
	"IMG"			=> "newsletters.gif",
));
print $page->evaluate();
?>