<?php

defined('_MAILING') or die('Restricted access');

$app->checkToken();

$filename = date("Y-m-d_His").".csv";

if (strtoupper(substr(PHP_OS,0,3)=='WIN')) {
    $eol="\r\n";
} elseif (strtoupper(substr(PHP_OS,0,3)=='MAC')) {
    $eol="\r";
} else {
    $eol="\n";
}
$recipients = '';

// set charset for exported data
$db->query(" SET NAMES ".Settings::$charset."; ");

$result = $db->query("
    SELECT
        r.id,
        r.date_create,
        r.date_modify,
        r.person,
        r.email,
        r.comment,
        r.website,
        r.f01,
        r.f02,
        r.f03,
        r.txt_only,
        (
            SELECT group_concat(rt.name SEPARATOR ' ') AS tags 
            FROM ".PREF."_recipient_tag_conn AS rc 
            left join ".PREF."_recipient_tag AS rt on(rc.id_tag=rt.id)
            WHERE r.id=rc.id_recipient
        ) AS tags
    FROM ".PREF."_recipient AS r
");

foreach ($result as $row) {
    $recipients .= $row['email'];
    $recipients .= isset($_POST['person']) ? ';'.$row['person'] : '';
    $recipients .= isset($_POST['tags']) ? ';'.$row['tags'] : '';
    $recipients .= isset($_POST['comment']) ? ';'.$row['comment'] : '';
    $recipients .= isset($_POST['website']) ? ';'.$row['website'] : '';
    $recipients .= isset($_POST['f01']) ? ';'.$row['f01'] : '';
    $recipients .= isset($_POST['f02']) ? ';'.$row['f02'] : '';
    $recipients .= isset($_POST['f03']) ? ';'.$row['f03'] : '';
    $recipients .= isset($_POST['txt_only']) ? ';'.$row['txt_only'] : '';
    $recipients .= isset($_POST['date_create']) ? ';'.$row['date_create'] : '';
    $recipients .= isset($_POST['date_modify']) ? ';'.$row['date_modify'] : '';
    $recipients .= $eol;
}

header('Content-Description: File Transfer'.$eol);
header('Content-Type: application/octet-stream'.$eol);
header('Content-Disposition: attachment; filename='.$filename.$eol);
header('Expires: 0'.$eol);
header('Cache-Control: must-revalidate'.$eol);
header('Pragma: public'.$eol);
header('Content-Length: '.strlen($recipients).$eol);
echo $recipients;
exit();
