<?php
include_once "../../../tools/inc.php";
$page = include("../../common.php");
include("../tools/function.string.php");
include("../tools/function.sql.php");
$n=$settings["rec_count"];
$max=100;
$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"];
$access=check_level("Export");

$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 get_groups($id=0) {
        global $db, $table_sg, $table_group, $access, $ui, $groups_list;
        $res="";
        $sql="select g.title from $table_sg sg, $table_group g where
                sg.subscribers_id='$id' and
                sg.group_id=g.id".($groups_list ? " and g.id in ($groups_list)" : "")."
        order by g.title";
        $rs=$db->select($sql);
        for ($i=0; $i<count($rs); $i++) $res.=($res ? "|" : "").$rs[$i]["title"];
        return $res;
}

$message=new Message();
$error=new Message("error");
if (isset($_r)) $message->add($message_list[$_r]);
if (isset($access["view"]) or isset($access["admin"])) {
        if ($step==2) {
                $filename='../files/export/'.$export['filename'];
                if ($f=fopen($filename, 'r')) {
                        $res=fread($f, filesize($filename));
                        fclose($f);
                } else $res='';
                @unlink($filename);
                $db->close();
                header("Content-type: plain/text");
                //header("Content-Length: ".str_len($res)); 
                header("Content-Disposition: attachment; filename=\"export_".date("Y_m_d").".csv\"");
                print $res;
                exit;   
        } elseif ($step==1) {
                if ($export["all"]) {
                        $sql="select count(*) from $table ".(!isset($access["admin"]) ? "where owner_id='".$ui["id"]."'" : "")." order by name";
                } elseif (is_array($export["group_id"])) {
                        $sql="select s.id
                        from
                                $table s,
                                $table_group g,
                                $table_sg sg
                        where
                                s.id=sg.subscribers_id and
                                g.id=sg.group_id and
                                g.id in (".implode(", ", $export["group_id"]).")
                                ".($groups_list ? " and g.id in ($groups_list)" : "")."
                        group by s.id
                        order by s.name";
                } elseif (is_array($export["black_list_id"])) {
                        $sql="select rule from $table_black_list where id in (".implode(", ", $export["black_list_id"]).")";
                        if (!isset($access["admin"])) $sql.=" and owner_id='".$ui["id"]."'";
                        $rs=$db->select($sql);
                        $where="";
                        for ($i=0; $i<count($rs); $i++) $where.=($where ? " or " : "")."mail like '".str_replace("*", "%", $rs[$i]["rule"])."'";
                        $where=($where ? "where $where" : "");
                        if (!isset($access["admin"])) $where.=($where ? " and " : "where ")."owner_id='".$ui["id"]."'";
                        $sql="select count(*) from $table $where order by name";
                } else {
                        $sql="select count(*) from $table where
                                status='".$export["type"]."'
                                ".(!isset($access["admin"]) ? " and owner_id='".$ui["id"]."'" : "")."
                        order by name";
                }
                $page->section("EXPORT_STEP_1");
                $r["count"]=ceil($db->count($sql, !is_array($export["group_id"]))/$max);
                $page->assign($r);
        } else {
		if (isset($save) and !isset($access['edit']) and !isset($access['admin'])) $error->add('{rs:ERROR_ACCESS_RESTRICTED}');
		elseif (isset($save)) {
                        $r["delimiter"]=stripslashes($r["delimiter"]);
                        $r["enclosure"]=stripslashes($r["enclosure"]);
                        $export=array(
                                "type"          => $r["type"],
                                "all"           => ($r["type"]=="all"),
                                "group_id"      => ((isset($r["group_id"]) and $r["type"]=="mail_groups") ? $r["group_id"] : NULL),
                                "black_list_id" => ((isset($r["black_list_id"]) and $r["type"]=="black_list") ? $r["black_list_id"] : NULL),
                                "put_header"    => isset($r["put_header"]),
                                "delimiter"     => $r["delimiter"],
                                "enclosure"     => $r["enclosure"],
                                "filename"      => time().'.csv',
                        );
                        $_SESSION['export']=$export;
                        $link->add("step", 1);
                        $db->close();
                        header("Location: ".$link->get());
                        exit;
                } else $r=$export;
                $page->section("EXPORT_STEP_0");
                $r["type"]=(!isset($r["type"]) ? "all" : $r["type"]);
                $r["all"]=($r["type"]=="all");
                $r["mg_checked"]=($r["type"]=="mail_groups");
                $r["bl_checked"]=($r["type"]=="black_list");
                $r["delimiter"]=(isset($r["delimeter"]) ? $r["delimeter"] : ";");
                $r["enclosure"]=(isset($r["enclosure"]) ? $r["enclosure"] : "\"");
                $sql="select * from $table_group".($groups_list ? " where id in ($groups_list)" : "")." order by position";
                get_row_from_sql("GROUPS_SELECT", $sql, $r["group_id"]);
                $sql="select * from $table_black_list";
                if (!isset($access["admin"])) $sql.=" where owner_id='".$ui["id"]."'";
                $sql.=" order by title";
                get_row_from_sql("BLACK_LIST_SELECT", $sql, $r["black_list_id"]);
                for ($i=0; $i<count($type_list); $i++) {
                        $page->addrow("LINE", array(
                                "id"            => $i,
                                "title"         => $type_list[$i],
                                "checked"       => ($r["type"]=="$i"),
                                "class"         => ($i%2),
                        ));
                }
                $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_EXPORT}", "subscribers/export/");
$db->close();
$page->assign(array(
        "TITLE"                 => "{rs:ACTION_EXPORT}",
        "ERROR"                 => ($error->count ? $error->get() : ""),
        "MESSAGE"               => ($message->count ? $message->get() : ""),
        "LINK"                  => $link->get(),
        "is_subscribers"        => 1,
        "IMG"                   => "export.gif",
	"WINDOW_TITLE"		=> "{rs:ACTION_EXPORT}",
));
print $page->evaluate();
?>