<?php

require_once 'common/mailfunctions.php';

function plugin_mailer_variables()
{
    $variables = array(
        'Plugin Name'   => array(
            'type'          => 'hidden',
            'description'   => '',
            'value'         => 'Bulk Mailer',
        ),
        'Enabled'       => array(
            'type'          => 'yesno',
            'description'   => 'When enabled, e-mails won\'t be sent immediately, but be queued instead and sent when this service is triggered. Use it to improve performance if you have to send lots of e-mails at once.',
            'value'         => '0',
        ),
        'Run schedule - Minute'  => array(
            'type'          => 'text',
            'description'   => 'Enter number, range, list or steps',
            'value'         => '30',
            'helpid'        => '8',
        ),
        'Run schedule - Hour'  => array(
            'type'          => 'text',
            'description'   => 'Enter number, range, list or steps',
            'value'         => '*',
        ),
        'Run schedule - Day'  => array(
            'type'          => 'text',
            'description'   => 'Enter number, range, list or steps',
            'value'         => '*',
        ),
        'Run schedule - Month'  => array(
            'type'          => 'text',
            'description'   => 'Enter number, range, list or steps',
            'value'         => '*',
        ),
        'Run schedule - Day of the week'  => array(
            'type'          => 'text',
            'description'   => 'Enter number in range 0-7 (0 is Sunday) or a 3 letter shortcut (e.g. sun)',
            'value'         => '*',
        ),
    );

    return $variables;
}

function plugin_mailer_execute()
{
    $messages = array();
    $numMailsSent = 0;
    $query = "SELECT id, subject, `from`, from_name, userid, bcc, priority, confirmreceipt, emailtype, body, striptags, nl2br, dfilename, attachment FROM email_queue";
    $result = $GLOBALS['db']->query($query);
    while ($row = $result->fetch()) {
        if (sendMailMessage($row['body'],
                            $row['from'],
                            $row['from_name'],
                            unserialize($row['userid']),
                            $row['bcc'],
                            $row['subject'],
                            $row['priority'],
                            $row['confirmreceipt'],
                            $row['emailtype'],
                            $row['attachment'],
                            $row['dfilename'],
                            $row['striptags'],
                            $row['nl2br']))
        {
            $numMailsSent++;
            $query2 = "DELETE FROM email_queue WHERE id = ?";
            $GLOBALS['db']->query($query2, $row['id']);
        } else {
            $users = implode(', ', unserialize($row['userid']));
            $GLOBALS['logger']->log(1, "Error trying to E-mail queued message to user(s) $users");
            $messages[] = new Error_CE(8229, lang('Error trying to E-mail queued message to user(s) %s', $users));
        }
    }

    array_unshift($messages, lang('%s message(s) sent', $numMailsSent));

    return $messages;
}

function plugin_mailer_output()
{
    global $tpl;

    $tpl->define(array('mailqueue_table' => 'views/admin/mailqueue_table.tpl'));
    $tpl->define_dynamic('email', 'mailqueue_table');
    $rowclass="odd";

    $query = "SELECT subject, userid, bcc, body, emailtype, attachment FROM email_queue";
    $result = $GLOBALS['db']->query($query);
    $queueEmpty = true;
    while ($row = $result->fetch()) {
        $to = unserialize($row['userid']);
        foreach ($to as $userid) {
            $emails = getEmailsForUserID($to, $row['emailtype']);
        }
        $to = implode(', ', $emails);
        $body = trim(substr($row['body'], 0, 200));
        if (strlen($row['body']) > 200) {
            $body .= ' ...';
        }

        $tpl->setkey(array(
            'trClass'           => $rowclass,
            'email_subject'     => $row['subject'],
            'email_to'          => $to,
            'email_bcc'         => $row['bcc'],
            'email_body'        => $body,
            'email_attachments' => $row['attachment']? lang('Yes') : lang('No'),
        ));

        $queueEmpty = false;

        //alternate row color
        if ($rowclass=="odd") $rowclass="even";
        else $rowclass="odd";

        $tpl->subst('trash', '.email');
    }

    if ($queueEmpty) {
        $tpl->setkey('NOEMAILS', "<tr><td colspan=\"5\" align=\"center\" style=\"font-style:italic\">".lang('The queue is empty')."</td></tr>");
    } else {
        $tpl->setkey('NOEMAILS', '');
    }

    $tpl->parse('output', 'mailqueue_table');

    return $tpl->fetch('output');
}

function plugin_mailer_dashboard()
{
    $query = "SELECT COUNT(id) as emails FROM email_queue";
    $result = $GLOBALS['db']->query($query);
    $row = $result->fetch();
    if (!$row) {
        $row['emails'] = 0;
    }

    return lang('Current e-mails in queue: %d', $row['emails']);
}

?>
