<?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");
include "tools/class.msg.php";
include("tools/class.mime.php");
include("tools/class.smtp.php");
$table="subscribers".$config["table_prefix"];
$table_n="newsletters".$config["table_prefix"];
$table_g="mailing_groups".$config["table_prefix"];
$table_sg="subscribers_group".$config["table_prefix"];
$table_confirm="msg_confirm_subscribe".$config["table_prefix"];
$table_scf="scf".$config["table_prefix"];
$table_log="stat_subscribes".$config["table_prefix"];

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

$message_list=array(
        1 => $db->get_val("pages".$config["table_prefix"], "description", "where name='subscribe_confirm_page_text'"),
        2 => $db->get_val("pages".$config["table_prefix"], "description", "where name='subscribe_successful'"),
        3 => "{rs:MSG_BANNED}",
        4 => "{rs:MSG_IN_BLACK_LIST}",
);

function send_confirm_message($r) {
        global $PATH, $HTTP_HOST, $table_g, $db, $config, $settings;
        $sql="select title from $table_g where id in (".implode(", ", $r["group_id"]).") order by position";
        $rs=$db->select($sql);
        $groups="";
        for ($i=0; $i<count($rs); $i++) $groups.=($groups ? "\n" : "")."- ".$rs[$i]["title"];
        $message=$db->get_val("pages".$config["table_prefix"], "description", "where name='subscribe_confirm'");
        $f=array(
                "%name%",
                "%link%",
                "%url%",
                "%groups%",
        );
        $v=array(
                $r["name"],
                "http://$HTTP_HOST".$PATH."subscribe/?id=".$r["id"]."&active_key=".$r["active_key"],
                "http://".$HTTP_HOST.$PATH,
                $groups,
        );
        $array=array(
                "login"         => '',
                "password"      => '',
                "host"          => '',
                "port"          => '',
                "from_name"     => $settings["mail_from_name"],
                "from"          => $settings["mail_from"],
                "reply_to"      => "",
                "to_name"       => $r["name"],
                "to"            => $r["mail"],
                "subject"       => $db->get_val("pages".$config["table_prefix"], "subject", "where name='subscribe_confirm'"),
                "message"       => str_replace($f, $v, $message),
                "charset"       => $settings["encoding"],
                "content_type"  => "text/plain",
        );
        $smtp=new SMTP($array);
        return $smtp->send_mail();
//      return ($settings["mail_mode"] ? $smtp->send() : $smtp->send_mail());
}

function put_confirm($id=0, $groups_id=0) {
        global $db, $table_confirm;
        if (!$id or !$groups_id) return false;
        if ($res=$db->get_val($table_confirm, "active_key", "where subscriber_id='$id' and groups_id='$groups_id'")) return $res;
        $fields="date_created, subscriber_id, groups_id, active_key";
        $r=array(
                "date_created"  => time(),
                "subscriber_id" => $id,
                "groups_id"     => $groups_id,
                "active_key"    => gencookie(20),
        );
        $sql=get_sql_insert($table_confirm, $fields, $r);
        $db->execute($sql);
        return $r["active_key"];
}


function subscribe_groups($subscriber_id, $groups) {
        global $db, $stat, $table_sg, $table_g, $table_n, $config, $r;
	$is_subscribe=false;
        $groups=$db->get_array($table_g, "id", "id", "where id in ($groups) and enabled='1'");
        $array=$db->get_array($table_sg, "group_id", "group_id", "where subscribers_id='$subscriber_id' and group_id in ($groups)");
        $groups=array_diff($groups, $array);
        $r=array(
                "subscribers_id"=> $subscriber_id,
                "group_id"      => 0,
        );
        $fields="subscribers_id, group_id";
        reset($groups);
        $key=key($groups);
	$filter='';
        while (isset($key)) {
                $r["group_id"]=$groups[$key];
		if (!is_val($table_sg, "where subscribers_id='{$r[subscribers_id]}' and group_id='{$r[group_id]}'")) {
                	$sql=get_sql_insert($table_sg, $fields, $r);
                	$db->execute($sql);
                	$msg=new msg("msg_campaign_schedule".$config["table_prefix"]);
               		$array=array(
                        	"id"            => 0,
                        	"subscriber_id" => $subscriber_id,
                        	"group_id"      => $r["group_id"],
                	);
                	$array=$msg->get_next_task("compaign_schedule".$config["table_prefix"], $array);
                	$msg->add($array);
			$is_subscribe=true;
			$filter.=($filter ? ' or ' : '')."groups='{$r["group_id"]}' or groups like '{$r["group_id"]},%' or groups like '%,{$r["group_id"]},%' or groups like '%,{$r["group_id"]}'";
		}
                next($groups);
                $key=key($groups);
        }

	// Add "SUBSCRIBES" statistics for newsletters
	if ($is_subscribe) {
		$sql="select id from $table_n where $filter group by id";
		$rs=$db->execute($sql);
		while ($row=$db->get_row($rs)) {
			$stat->update("NEWSLETTER[{$row['id']}].SUBSCRIBES.ALL", 0);
			$stat->update("NEWSLETTER[{$row['id']}].SUBSCRIBES");
		}
	}
}

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/subscribe/".$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,
                                                "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, $cf_list='') {
        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' and
                owner_id='$owner_id'
                ".($cf_list ? "and id in ($cf_list)" : "")."
        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");
$stat=new stat();

if (isset($_r)) $message->add($message_list[$_r]);
if (isset($save)) {
        $settings=load_settings($r["owner_id"]);
        $r=check_array($r);
        $r["group_list"]=($r["group_list"] ? explode(",", $r["group_list"]) : array());
        $r["cf_list"]=($r["cf_list"] ? explode(",", $r["cf_list"]) : array());
        $r["owner_id"]=(isset($r["owner_id"]) ? $r["owner_id"] : 0);
        $r["group_id"]=(is_array($r["group_id"]) ? $r["group_id"] : array());
        if ($r["group_list"]!=array()) $r["group_id"]=array_intersect($r["group_list"], $r["group_id"]);
        $r["receive_format"]=((isset($r["receive_format"]) and $r["is_format"]) ? $r["receive_format"] : 0);
        $r["encoding"]=((isset($r["encoding"]) and $r["is_encoding"]) ? $r["encoding"] : $settings["encoding"]);
        if (!$r["name"]) $error->add("{rs:ERROR_NAME}");
        if (!check_email($r["mail"])) $error->add("{rs:ERROR_MAIL}");
        if (!count($r["group_id"])) $error->add("{rs:ERROR_MAILING_GROUP}");

        $custom_fields=get_custom_fields_values(0, $r["owner_id"], implode(", ", $r["cf_list"]));
        $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) {
                //$sql="select * from $table where mail='".$r["mail"]."' and owner_id='".$r["owner_id"]."'";
                $sql="select * from $table where mail='".$r["mail"]."'";
                $rs=$db->select($sql);
                if (!isset($rs[0]["id"])) {
                        $r["date_created"]=time();
                        $r["status"]=0;
                        $r["modify_user"]=0;
                        $r["modify_time"]=time();
			$r['ip']=ip_to_int($_SERVER['REMOTE_ADDR']);
                        $fields="date_created, name, mail, receive_format, encoding, status, ip, owner_id, modify_user, modify_time";
                        $sql=get_sql_insert($table, $fields, $r);
                        $db->execute($sql);
                        $r["id"]=mysql_insert_id();
                        $sql="delete from $table_scf where subscriber_id='".$r["id"]."'";
                        $db->execute($sql);
                        reset($cf);
                        while ($key=key($cf)) {
                                $array=array(
                                        "custom_field_id"       => $key,
                                        "subscriber_id"         => $r["id"],
                                        "value"                 => $cf[$key],
                                );
                                $fields="custom_field_id, subscriber_id, value";
                                $sql=get_sql_insert($table_scf, $fields, $array);
                                $db->execute($sql);
                                next($cf);
                        }
                 } else {
                        $rs[0]["group_id"]=$r["group_id"];
                        $r=$rs[0];
                }
                if ($settings["email_activation"]) {
                        if ($r["active_key"]=put_confirm($r["id"], implode(", ", $r["group_id"]))) {
                                send_confirm_message($r);
                                $link->add("_r", 1);
                        } else $link->add("_r", 2);
                } else {
                        subscribe_groups($r["id"], implode(", ", $r["group_id"]));
                        $link->add("_r", 2);
                }
                header("Location: ".$link->get());
                $db->close();
                exit;
        } else {
                $r["group_list"]=implode(",", $r["group_list"]);
                $r["cf_list"]=implode(",", $r["cf_list"]);
                $r=html_string($r, true);
        }
} elseif (isset($active_key) and isset($id)) {
        $sql="select s.status, s.owner_id, c.* from $table s, $table_confirm c
        where   s.id='$id' and
                c.subscriber_id=s.id and
                c.active_key='$active_key'";
        $rs=$db->select($sql);
        if (isset($rs[0][0]) and $rs[0]["status"]<=1) {
                $r["owner_id"]=$rs[0]["owner_id"];
                $settings=load_settings($r["owner_id"]);
                $sql="update $table set status='1' where id='$id'";
                $db->execute($sql);
                subscribe_groups($id, $rs[0]["groups_id"]);
                $link->add("_r", 2);
        } else {
                if ($rs[0]["status"]>1) $link->add("_r", $rs[0]["status"]+1);
        }
        $sql="delete from $table_confirm where subscriber_id='$id' and active_key='$active_key'";
        $db->execute($sql);
        header("Location: ".$link->get());
        $db->close();
        exit;
}

$page = new Template("templates/subscribe/form.tpl");
$page->dictionary("common/dict.ru");
$page->assign(array("PATH"  => $PATH));
get_row_from_array("RECEIVE_FORMAT_SELECT", $mail_format_list, $r["receive_format"]);
get_row_from_table("ENCODING_SELECT", "encodes".$config["table_prefix"], (isset($r["encoding"]) ? $r["encoding"] : "UTF-8"), "code", "title");
$sql="select id, title from $table_g
where
        enabled='1'
        ".($r["group_list"] ? " and id in (".$r["group_list"].")" : "")."
order by position";
get_row_from_sql("GROUPS_SELECT", $sql, $r["group_id"]);
get_custom_fields_row("CUSTOM_FIELDS", $r["cf"]);

$r["is_encoding"]=(isset($r["is_encoding"]) ? $r["is_encoding"] : 1);
$r["is_format"]=(isset($r["is_format"]) ? $r["is_format"] : 1);
$page->assign($r);

$page->assign(array(
        "header_title"          => "{rs:TITLE_SUBSCRIBE}",
        "ERROR"                 => ($error->count ? $error->get() : ""),
        "MESSAGE"               => ($message->count ? $message->get() : ""),
        "LINK"                  => $link->get(),
));
print str_replace("%form%", $page->evaluate(), $db->get_val("pages".$config["table_prefix"], "description", "where name='subscribe_page'"));
$db->close();
?>