<?php
include_once "../../tools/inc.php";
$page = include("../common.php");
include("../tools/function.string.php");
include("../tools/function.sql.php");
include("../tools/class.search.php");
$n=$settings["rec_count"];
$table="subscribers".$config["table_prefix"];
$table_group="mailing_groups".$config["table_prefix"];
$table_sg="subscribers_group".$config["table_prefix"];
$table_scf="scf".$config["table_prefix"];
$access=check_level("Subscribers");
if (isset($status) and $status<0) unset($status);
$sort=(in_array($sort, array("name", "mail")) ? $sort : "name");
$sort_d=(isset($sort_d) ? 1 : 0);
$cf_id=intval($cf_id);

$filter_link=new Link($link->get());
$link->add("g_id");
$link->add("status");
$link->add("_search");
$link->add("cf_id");
$link->add("cf_value");
$link->add("_search");
$sort_link=new Link($link->get());
$link->add("sort");
$link->add("sort_d");
$filter_link->add("sort");
$filter_link->add("sort_d");
$offset_link=new Link($link->get());
$link->add("offset");

$message_list=array(
	1 => "{rs:MSG_SUBSCRIBER} {rs:MSG_CREATED}",
	2 => "{rs:MSG_SUBSCRIBER} {rs:MSG_UPDATED}",
	3 => "{rs:MSG_SUBSCRIBERS} {rs:MSG_DELETED}",
	4 => "{rs:MSG_SUBSCRIBER} {rs:MSG_DEACTIVATED}",
	5 => "{rs:MSG_SUBSCRIBER} {rs:MSG_ACTIVATED}",
	6 => "{rs:MSG_SUBSCRIBER} {rs:MSG_BANNED}",
	7 => "{rs:MSG_SUBSCRIBER} {rs:MSG_BLACK_LIST_MOVE}",
	8 => "{rs:MSG_SUBSCRIBERS} {rs:MSG_COPIED}",
	9 => "{rs:MSG_SUBSCRIBERS} {rs:MSG_MOVED}",
);

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

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

function get_groups_id($id) {
	global $db, $table_sg;
	$res=array();
	$sql="select group_id from $table_sg where subscribers_id='$id'";
	$rs=$db->select($sql);
	for ($i=0; $i<count($rs); $i++) $res[]=$rs[$i]["group_id"];
	return $res;
}

function get_custom_fields_row($name, $cf=null) {
	global $page, $db, $custom_fields;
	$cf=(is_array($cf) ? $cf : array());
	reset($custom_fields);
	$i=0;
	while ($key=key($custom_fields)) {
		$i++;
		$data=$custom_fields[$key];
		if ($data["type"]!="checkbox") $cf[$key]=(isset($cf[$key]) ? $cf[$key] : $data["value"]);
		$_page=new Template("templates/custom_fields/".$data["type"].".tpl");
		if (in_array($data["type"], array("radio", "select"))) {
			$array=explode("\r\n", $data["list_val"]);
			for ($j=0; $j<count($array); $j++) {
				if (trim($array[$j])) {
					$_page->addrow("LINE", array(
						"id"		=> $key,
						"position"	=> $j,
						"value"		=> html_string($array[$j]),
						"active"	=> $array[$j]==$cf[$key],
					));
				}
			}
		}
		$_page->assign(array(
			"id"	=> $key,
			"value"	=> $cf[$key],
		));
		$data["line"]=$_page->evaluate();
		$data["class"]=($i%2);
		$page->addrow($name, $data);
		next($custom_fields);
	}
}

function get_custom_fields_values($subscriber_id=0, $owner_id=0) {
	global $db, $data, $config;
	$table="custom_fields".$config["table_prefix"];
	$sql="select id, title, type, validation, def_value, list_val, not_null from $table where enabled='1'".($owner_id ? " and owner_id='$owner_id'" : '')." order by position";
	$rs=$db->select($sql);
	$res=array();
	for ($i=0; $i<count($rs); $i++) {
		$res[$rs[$i]["id"]]=$rs[$i];
		$res[$rs[$i]["id"]]["value"]=($subscriber_id ? get_val("scf".$config["table_prefix"], "value", "where subscriber_id='$subscriber_id' and custom_field_id='".$rs[$i]["id"]."'") : $rs[$i]["def_value"]);
		$data["cf"][$rs[$i]["id"]]=$res[$rs[$i]["id"]]["value"];
	}
	return $res;
}

$message=new Message();
$error=new Message("error");
if (isset($_r)) $message->add($message_list[$_r]);
if (isset($act) and $act=="import") {
	if ($ic) $message->add("$ic {rs:MSG_MAIL_IMPORTED}");
	if ($sc) $message->add("$sc {rs:MSG_MAIL_SKIPED}");
	if ($uc) $message->add("$uc {rs:MSG_MAIL_UPDATED}");
	if ($ec) $message->add("$ec {rs:MSG_MAIL_ERROR}");
	if ($gr) {
		$gr=implode(", ", $db->get_array($table_group, "id", "title", "where id in (".str_replace("-", ", ", $gr).") order by title"));
		if ($gr) $message->add("{rs:MSG_MAIL_GROUPS}: $gr");
	}
}

if (isset($act) and ($act=="copy/move") and isset($cm) and in_array($cm, array("copy", "move")) and isset($group_id) and (isset($access["edit"]) or isset($access["admin"]))) {
	$ids=(is_array($ids) ? implode($ids, ", ") : $ids);
	$ids=implode(", ", $db->get_array($table, "id", "id", "where id in ($ids)"));

	$group_id=intval($group_id);
	$where=(isset($user_permissions['groups_list']) ? "id in (".$user_permissions['groups_list'].")" : '');
	if ($group_id>0) $where.=($where ? ' and ' : '')."id='$group_id'";
	if ($where) $where='where '.$where;
	$group_id=$db->get_array($table_group, "id", "id", $where);

	// Checking
	if ($user_permissions['max_groups_subscribers']>0) {
		$sql="select count(*) from $table where id in ($ids) and owner_id='".$ui['id']."'";
		$count=$db->count($sql, true);
		foreach ($group_id as $key=>$val) {
			$sql="select count(*)
			from
				$table_sg sg,
				$table s
			where
				sg.group_id='$val' and 
				sg.subscribers_id not in ($ids) and
				s.id=sg.subscribers_id and
				s.owner_id='".$ui['id']."'
			group by sg.group_id";
			if ($db->count($sql, true)+$count>$user_permissions['max_groups_subscribers']) {
				$error->add('{rs:ERROR_LIMIT} {rs:ERROR_LIMIT_MAX_GROUPS_SUBSCRIBERS} "'.$db->get_val($table_group, 'title', "where id='$val'").'"');
			}
		}
	}
	$group_id=implode(", ", $group_id);

	if (!$error->count) {
		if ($cm=="copy") {
			$sql="delete from $table_sg where subscribers_id in ($ids) and group_id in ($group_id)";
			$db->execute($sql);
			$link->add("_r", "8");
		} else {
			$sql="delete from $table_sg where subscribers_id in ($ids)".(isset($user_permissions['groups_list']) ? " and group_id in (".$user_permissions['groups_list'].")" : '');
			$db->execute($sql);
			$link->add("_r", "9");
		}

		$sql="select s.id as subscribers_id, g.id as group_id from $table s, $table_group g
		where
			s.id in ($ids) and
			g.id in ($group_id)";
		$rs=$db->select($sql);
		for ($i=0; $i<count($rs); $i++) {
			$sql=get_sql_insert($table_sg, "subscribers_id, group_id", $rs[$i]);
			$db->execute($sql);
		}
		$db->close();
		header("Location: ".$link->get());
		exit;
	}
	
	$where='';
}

if (isset($act) and ($act=="delete") and (isset($access["delete"]) or isset($access["admin"]))) {
	$ids=(is_array($ids) ? implode(", ", $ids) : $ids);
	$ids=$db->get_array($table, "id", "id", "where id in ($ids)");
	$ids=implode(", ", $ids);
	$sql=array();
	$sql[]="delete from $table_scf where subscriber_id in ($ids)";
	$sql[]="delete from $table_sg where subscribers_id in ($ids)";
        $sql[]="delete from $table where id in ($ids)";
	$db->execute_all($sql);
	$link->add("_r", 3);
	$db->close();
	header("Location: ".$link->get());
	exit;
} elseif (isset($act) and in_array($act, array("activate", "deactivate", "banned", "black_list")) and (isset($access["edit"]) or isset($access["admin"]))) {
	$ids=(is_array($ids) ? implode($ids, ", ") : $ids);
	$ids=$db->get_array($table, "id", "id", "where id in ($ids)");//.(isset($access["admin"]) ? "" : " and owner_id='".$ui["id"]."'"));
	$ids=implode(", ", $ids);
	if ($act=="deactivate") $status=0;
	elseif ($act=="activate") $status=1;
	elseif ($act=="banned") $status=2;
	elseif ($act=="black_list") $status=3;
	else $status=0;
	$sql="update $table set status='$status' where id in ($ids)";	
	$db->execute($sql);
	$link->add("_r", (4+$status));
	$db->close();
	header("Location: ".$link->get());
	exit;
} elseif (isset($edit) and (isset($access["edit"]) or isset($access['view']) or isset($access["admin"]))) {
	$sql="select * from $table where id='$edit'";
	$rs=$db->select($sql);
	$data=$rs[0];
        if (!isset($data["id"])) {
		$edit=0;
		$data["encoding"]=$settings["encoding"];
		$data["status"]=1;
		$data["group_id"]=(isset($g_id) ? array($g_id) : array());
		$r["date_created"]=time();
		$r["owner_id"]=$ui["id"];
		$sql="select count(*) from $table where owner_id='".$ui['id']."'";
		if ($user_permissions['max_subscribers']>0 and $db->count($sql, true)>=$user_permissions['max_subscribers']) $error->add('{rs:ERROR_LIMIT} {rs:ERROR_LIMIT_MAX_SUBSCRIBERS}');
	} else {
		$edit=$data["id"];
		$r["date_created"]=$data["date_created"];
		$r["owner_id"]=$data["owner_id"];
		$data["group_id"]=get_groups_id($edit);
	}
	$custom_fields=get_custom_fields_values($edit);
        if (isset($save)) {
		$r["name"]=check_string($r["name"], 1);
		$r["mail"]=check_string($r["mail"], 1);
		$r["receive_format"]=(isset($r["receive_format"]) ? $r["receive_format"] : 0);
		$r["encoding"]=check_string($r["encoding"], 1);
		$r["status"]=(isset($r["status"]) ? $r["status"] : 0);
		$r["modify_user"]=$ui["id"];
		$r["modify_time"]=time();
		if (isset($user_permissions['groups_list'])) $r["group_id"]=array_intersect($r["group_id"], explode(", ", $user_permissions['groups_list']));

		if ($user_permissions['max_groups_subscribers']>0) {
			$sql="select g.title, sg.group_id, count(*) as count
			from
				$table s,
				$table_group g,
				$table_sg sg
			where
				g.id=sg.group_id and
				sg.subscribers_id<>'$edit' and
				sg.group_id in (".implode(', ', $r['group_id']).") and
				s.id=sg.subscribers_id and
				s.owner_id='".$ui['id']."'
			group by sg.group_id";
			if ($sth=$db->execute($sql)) {
				while ($row=$db->get_row($sth)) {
					if ($row['count']>=$user_permissions['max_groups_subscribers']) $error->add('{rs:ERROR_LIMIT} {rs:ERROR_LIMIT_MAX_GROUPS_SUBSCRIBERS} "'.$row['title'].'"');
				}
			}
		}
		if (!$r["name"]) $error->add("{rs:ERROR_NAME}");
		if (!check_email($r["mail"])) $error->add("{rs:ERROR_MAIL}");
		if (!$r["encoding"]) $error->add("{rs:ERROR_ENCODING}");
		if (is_val($table, "where mail='".$r["mail"]."' and id<>'$edit'")) $error->add("{rs:ERROR_SUBSCRIBERS_EXIST}");

		$r["cf"]=check_array($r["cf"]);
		$cf=array();
		reset($custom_fields);
		while ($key=key($custom_fields)) {
			if ($custom_fields[$key]["validation"]) {
				$cf[$key]=validation($r["cf"][$key], $custom_fields[$key]["validation"]);
				if (!$cf[$key] and $r["cf"][$key]) $error->add($custom_fields[$key]["title"].": {rs:ERROR_FORMAT}");
			} else $cf[$key]=$r["cf"][$key];
			if (!$r["cf"][$key] and $custom_fields[$key]["not_null"]) $error->add($custom_fields[$key]["title"].": {rs:ERROR_FORMAT}");
			next($custom_fields);
		}
		if (!$error->count and !isset($access["edit"]) and !isset($access["admin"])) $error->add('{rs:ERROR_ACCESS_RESTRICTED}');
		if (!$error->count) {
			$fields="date_created, name, mail, receive_format, encoding, status, owner_id, modify_user, modify_time";
			$sql=($edit ? get_sql_update($table, $fields, $r, "where id='$edit'") : get_sql_insert($table, $fields, $r));
			$db->execute($sql);
	                $link->add("_r", ($edit ? 2 : 1));
			$edit=(!$edit ? mysql_insert_id() : $edit);
			$sql=array();
			$sql[]="delete from $table_sg where subscribers_id='$edit'".(isset($user_permissions['groups_list']) ? " and group_id in (".$user_permissions['groups_list'].")" : "");
			for ($i=0; $i<count($r["group_id"]); $i++) {
				if (!isset($user_permissions['groups_list']) or (in_array($r["group_id"][$i], explode(', ', $user_permissions['groups_list'])))) {
					$array=array(
						"subscribers_id"	=> $edit,
						"group_id"		=> $r["group_id"][$i],
					);
					$fields="subscribers_id, group_id";
					$sql[]=get_sql_insert($table_sg, $fields, $array);
				}
			}
	                $db->execute_all($sql);
			$sql="delete from $table_scf where subscriber_id='$edit'";
			$db->execute($sql);
			reset($cf);
			while ($key=key($cf)) {
				$array=array(
					"custom_field_id"	=> $key,
					"subscriber_id"		=> $edit,
					"value"			=> $cf[$key],
				);
				$fields="custom_field_id, subscriber_id, value";
				$sql=get_sql_insert($table_scf, $fields, $array);
				$db->execute($sql);
				next($cf);
			}
	                $db->close();
	                header("Location: ".$link->get());
	                exit;
		} else {
			$r["id"]=$edit;
			$data=html_string($r, true);
		}
        } else $data=html_string($data);
	$page->section("SUBSCRIBERS_EDIT");
	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");
	$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["group_id"]);
	$data['mg_list']=(count($array)>0);
	get_row_from_array("STATUS_SELECT", $status_list, $data["status"]);
	get_custom_fields_row("CUSTOM_FIELDS", $data["cf"]);
	$data["BACK_LINK"]=($link->get() ? $link->get() : './');
	$data["BACK_TITLE"]="{rs:TITLE_SUBSCRIBERS}";
	$data["WINDOW_TITLE"]="{rs:EDIT_SUBSCRIBERS}";
        $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("SUBSCRIBERS");
	$sql=array();
	if ($g_id) $where="where s.id=sg.subscribers_id";
	if ($g_id) $where.=" and sg.group_id='$g_id'";
        if ($cf_id or strlen($cf_value)) {
		$where.=($where ? " and " : "where ")."scf.subscriber_id=s.id".($cf_id ? " and scf.custom_field_id='$cf_id'" : '');
		$where=get_search_where("scf.value", $cf_value, $where);
	}
	if (isset($status) and $status>=0) $where.=($where ? " and " : "where ")."s.status='$status'";
	//if (!isset($access["admin"])) $where.=($where ? " and " : "where ")."s.owner_id='".$ui["id"]."'";
	if ($_search) $where=get_search_where("s.name, s.mail", $_search, $where);
	$sql="select ".(($g_id or $cf_id  or strlen($cf_value)) ? 's.*' : 'count(*)')." from $table s ".
		($g_id ? ", $table_sg sg " : '').
		(($cf_id or strlen($cf_value)) ? ", $table_scf scf " : '').
	$where.($g_id ? " group by s.id" : '');
	$count=$db->count($sql, (!($g_id or $cf_id or strlen($cf_value))));
        $i=ceil($count/$n)-1;
        $offset=(($offset>$i) ? $i : ($offset<0 ? 0 : $offset));
	$sql="select s.* from $table s ".
		($g_id ? ", $table_sg sg " : '').
		(($cf_id or strlen($cf_value)) ? ", $table_scf scf " : '').
	$where.($g_id ? ' group by s.id' : '')."
	order by s.".$sort.($sort_d ? " DESC" : "")."
	limit ".($offset*$n). ", $n";
	$rs = $db->select($sql);
        for ($i=0; $i<count($rs); $i++) {
		$data=$rs[$i];
		$data["disabled"]=in_array($data["status"], array(0, 2));
                $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),
		"cf_value"	=> html_string($cf_value),
		"BACK_LINK"	=> $PATH,
		"BACK_TITLE"	=> "{rs:TITLE_MAIN_MENU}",
		"sort_by_mail"	=> $sort_link.($sort_link ? '&' : '?')."sort=mail".($sort=="mail" ? ($sort_d ? "" : "&sort_d=1") : ""),
		"sort_by_name"	=> $sort_link.($sort_link ? '&' : '?')."sort=name".($sort=="name" ? ($sort_d ? "" : "&sort_d=1") : ""),
		"sort_mail_img"	=> ($sort=="mail" ? ($sort_d ? "_asc" : "_desc") : ""),
		"sort_name_img"	=> ($sort=="name" ? ($sort_d ? "_asc" : "_desc") : ""),
		"WINDOW_TITLE"	=> "{rs:TITLE_SUBSCRIBERS}",
        ));
	$sql="select id, title from $table_group ".(isset($user_permissions['groups_list']) ? "where id in (".$user_permissions['groups_list'].")" : "")." order by position";
	get_row_from_sql("GROUPS_SELECT", $sql, $g_id);
	get_row_from_array("STATUS_SELECT", $status_list, $status);
	$sql='select id, title from custom_fields'.$config["table_prefix"].' order by position';
	get_row_from_sql("CUSTOM_FIELDS_SELECT", $sql, $cf_id);
	$page->section("SHOW_SEARCH");
} else {
	$page->section("ACCESS_DENIED");
	$error->add("{rs:ERROR_ACCESS_RESTRICTED}");
}
add_to_tree("{rs:TITLE_SUBSCRIBERS}", "subscribers/");
$db->close();
$page->assign(array(
	"TITLE"			=> "{rs:TITLE_SUBSCRIBERS}",
	"ERROR"			=> ($error->count ? $error->get() : ""),
	"MESSAGE"		=> ($message->count ? $message->get() : ""),
	"LINK"			=> $link->get(),
	"FILTER_LINK"		=> $filter_link->get(),
	"is_subscribers"	=> 1,
	"IMG"			=> "subscribers.gif",
));
print $page->evaluate();
?>