<?php
include_once "../../../tools/inc.php";
$page = include("../../common.php");
include("../tools/function.string.php");
include("../tools/function.sql.php");

$n=$settings["rec_count"];
$table			= "subscribers".$config["table_prefix"];
$table_group		= "mailing_groups".$config["table_prefix"];
$table_black_list	= "black_list".$config["table_prefix"];
$table_sg		= "subscribers_group".$config["table_prefix"];
$table_um		= "users_mailing_groups".$config["table_prefix"];
$table_cf		= "custom_fields".$config["table_prefix"];
$table_scf		= "scf".$config["table_prefix"];

$access=check_level("Import");

$step=(isset($step) ? $step : 0);
$filter_link=new Link($link->get());
$link->add("offset");

$message_list=array(
        1 => "{rs:MSG_SAVED}",
        2 => "{rs:MSG_DELETED}",
);

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

function update_position($old, $new) {
        global $db, $table_group;
        $sql=array();
        $sql[]="update $table_group set position=position-1 where position>$old";
        $sql[]="update $table_group set position=position+1 where position>=$new";
        $db->execute_all($sql);
}

function save_to_file($filename, $st) {
        if ($f=fopen($filename, "w")) {
                fwrite($f, $st);
                fclose($f);
        }
}

function split_file($filename) {
        global $import;
        $array=array();
        if (is_file($filename)) {
                $array=file($filename);
                unlink($filename);
        }
        $max=500;
        $cur=0;
        $br="\n";
        for ($i=($import["put_header"] ? 1 : 0); $i<count($array); $i++) {
                if ($cur==$max) {
                        save_to_file("../files/import/".$import["filename"].str_pad($import["files_count"], 4, "0", STR_PAD_LEFT), $st);
                        $import["files_count"]++;
                        $cur=0;
                }
                if (!$cur) $st=($import["put_header"] ? trim($array[0]).$br : "");
                $st.=trim($array[$i]).$br;
                $cur++;
        }
        if ($cur) save_to_file("../files/import/".$import["filename"].str_pad($import["files_count"], 4, "0", STR_PAD_LEFT), $st);
}
$message=new Message();
$error=new Message("error");
if (isset($_r)) $message->add($message_list[$_r]);
if (isset($access["edit"]) or isset($access["admin"])) {
        if ($step==3) {
                $page->section("IMPORT_STEP_3");
                $r["count"]=$import["files_count"];
                //$r["BACK_LINK"]=$link->get()."step.2/";
                //$r["BACK_TITLE"]="{rs:ACTION_IMPORT}";
                $page->assign($r);
        } elseif ($step==2) {
                if (isset($save) and $save==1) {
                        $import["add_groups"]=(is_array($r["add_groups"]) ? $r["add_groups"] : array());
                        $_SESSION['import']=$import;
                        $link->add("step", 3);
                        $db->close();
                        header("Location: ".$link->get());
                        exit;
                } elseif (isset($save)) {
                        check_array($r);
                        if ($r["new_group"]) {
                                $sql="select count(*) from $table_group";
                                $data["date_created"]=time();
                                $data["title"]=$r["new_group"];
                                $data["position"]=$db->count($sql, true);
                                $data["enabled"]=1;
                                $data["visible"]=1;
                                $data["allow_subscriptions"]=1;
                                $data["allow_unsubscriptions"]=1;
                                $data["owner_id"]=$ui["id"];
                                $data["modify_user"]=time();
                                $data["modify_time"]=time();
                                $fields="date_created, title, position, enabled, visible, allow_subscriptions, allow_unsubscriptions, owner_id, modify_user, modify_time";
                                update_position($data["position"], $data["position"]);
                                $sql=get_sql_insert($table_group, $fields, $data);
                                $db->execute($sql);
                                $sql="insert into $table_um (user_id, group_id) values ('".$ui["id"]."', '".mysql_insert_id()."')";
                                $db->execute($sql);
                                $db->close();
                                $link->add("step", 2);
                                header("Location: ".$link->get());
                                exit;
                        }
                }
                $page->section("IMPORT_STEP_2");
                $sql="select id, title from $table_group ".($groups_list ? " where id in ($groups_list)" : "")."order by position";
                $array=get_row_from_sql("GROUPS_SELECT", $sql, $r["add_groups"]);
		$r['mg_list']=(count($array)>0);
                $r["BACK_LINK"]=($link->get() ? $link->get().'&' : '?')."step=1";
                $r["BACK_TITLE"]="{rs:ACTION_IMPORT}";
                $page->assign($r);
        } elseif ($step==1) {
                if (isset($save)) {
                        $import["name"]=$r["name"];
                        $import["mail"]=$r["mail"];
                        $import["format"]=$r["format"];
                        $import["encoding"]=$r["encoding"];
                        $import["status"]=$r["status"];
                        $import["group"]=$r["group"];
                        $import["duplicated"]=$r["duplicated"];
			$import["cf"]=$r["cf"];
                        $_SESSION['import']=$import;
                        $link->add("step", 2);
                        $db->close();
                        header("Location: ".$link->get());
                        exit;
                }

                include("../tools/class.csv.php");
                $csv=new CSV($import["delimiter"], $import["enclosure"]);
                if ($csv->open("../files/import/".$import["filename"]."0000")) {
                        $array=$csv->get_row();
                        if (!$import["put_header"]) {
                                for ($i=0; $i<count($array); $i++) $array[$i]="{rs:FIELD} ".($i+1);
                        }
                        $page->section("IMPORT_STEP_1");
                        $data=array(
                                "name"          => 0,
                                "mail"          => 1,
                                "format"        => 2,
                                "encoding"      => 3,
                                "status"        => 4,
                                "group"         => 5,
                                "duplicated"    => 0,
                        );
			$sql="select id, title, position from $table_cf where enabled='1' and owner_id='".$ui["id"]."' order by position";
			$sth=$db->execute($sql);
			while($rs=$db->get_row($sth)) {
				$_page=new Template('templates/import/custom_field.tpl');
				$_page->dictionary("common/dict.ru");
				$_page->assign($rs);
				get_row_from_array('LINE', $array, 6+$rs['position'], '_page');
				$page->addrow('CUSTOM_FIELDS', array(
					'line'	=> $_page->evaluate(),
				));
			}

                        get_row_from_array("NAME_SELECT", $array, $data["name"]);
                        get_row_from_array("MAIL_SELECT", $array, $data["mail"]);
                        get_row_from_array("FORMAT_SELECT", $array, $data["format"]);
                        get_row_from_array("ENCODING_SELECT", $array, $data["encoding"]);
                        get_row_from_array("STATUS_SELECT", $array, $data["status"]);
                        get_row_from_array("GROUP_SELECT", $array, $data["group"]);
                        $data["BACK_LINK"]=($link->get() ? $link->get().'&' : '?')."step=0";
                        $data["BACK_TITLE"]="{rs:ACTION_IMPORT}";
                        $page->assign($data);
                        $csv->close();
                } else {
                        $db->close();
                        header("Location: ".$link->get());
                        exit;
                }
        } else {
                if (isset($save)) {
			$files=(isset($_FILES['r']) ? $_FILES['r'] : $HTTP_POST_FILES['r']);
//                      include("../tools/class.files.php");
//                      $file=new Files("../files/import/");
//                      if (!$file->upload_file($files, "file")) $error->add($file->get_error());
			if (!is_file($files["tmp_name"]["file"])) $error->add("{rs:ERROR_FILE_NOT_FOUND}");
                        $r["delimiter"]=stripslashes($r["delimiter"]);
                        $r["enclosure"]=stripslashes($r["enclosure"]);
                        if (!$error->count) {
                                $import=array(
                                        "filename"      => time(),
                                        "files_count"   => 0,
                                        "delimiter"     => $r["delimiter"],
                                        "enclosure"     => $r["enclosure"],
                                        "put_header"    => isset($r["put_header"]),
                                );
                                split_file($files["tmp_name"]["file"]);
                                $_SESSION['import']=$import;
                                $link->add("step", 1);
                                $db->close();
                                header("Location: ".$link->get());
                                exit;
                        }
                } else $r=$import;
                $page->section("IMPORT_STEP_0");
                $r["delimiter"]=(isset($r["delimeter"]) ? $r["delimeter"] : ";");
                $r["enclosure"]=(isset($r["enclosure"]) ? $r["enclosure"] : "\"");
                $r=html_string($r);
                $r["BACK_LINK"]=$PATH."subscribers/";
                $r["BACK_TITLE"]="{rs:TITLE_SUBSCRIBERS}";
                $page->assign($r);
        }
} else {
        $page->section("ACCESS_DENIED");
        $error->add("{rs:ERROR_ACCESS_RESTRICTED}");
}
add_to_tree("{rs:TITLE_SUBSCRIBERS}", "subscribers/");
add_to_tree("{rs:ACTION_IMPORT}", "subscribers/import/");
$db->close();
$page->assign(array(
        "TITLE"                 => "{rs:ACTION_IMPORT}",
        "ERROR"                 => ($error->count ? $error->get() : ""),
        "MESSAGE"               => ($message->count ? $message->get() : ""),
        "LINK"                  => $link->get(),
        "is_subscribers"        => 1,
        "IMG"                   => "import.gif",
	"WINDOW_TITLE"		=> "{rs:ACTION_IMPORT}",
));
print $page->evaluate();
?>