<?php

require_once 'newedge/classes/NE_MailGateway.php';
require_once 'modules/admin/models/ServicePlugin.php';
/**
* @package Plugins
*/
class PluginMailer extends ServicePlugin
{
    function getVariables()
    {
        $variables = array(
            /*T*/'Plugin Name'/*/T*/   => array(
                'type'          => 'hidden',
                'description'   => /*T*/''/*/T*/,
                'value'         => /*T*/'Bulk Mailer'/*/T*/,
            ),
            /*T*/'Enabled'/*/T*/       => array(
                'type'          => 'yesno',
                'description'   => /*T*/'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.'/*/T*/,
                'value'         => '0',
            ),
            /*T*/'Run schedule - Minute'/*/T*/  => array(
                'type'          => 'text',
                'description'   => /*T*/'Enter number, range, list or steps'/*/T*/,
                'value'         => '30',
                'helpid'        => '8',
            ),
            /*T*/'Run schedule - Hour'/*/T*/  => array(
                'type'          => 'text',
                'description'   => /*T*/'Enter number, range, list or steps'/*/T*/,
                'value'         => '*',
            ),
            /*T*/'Run schedule - Day'/*/T*/  => array(
                'type'          => 'text',
                'description'   => /*T*/'Enter number, range, list or steps'/*/T*/,
                'value'         => '*',
            ),
            /*T*/'Run schedule - Month'/*/T*/  => array(
                'type'          => 'text',
                'description'   => /*T*/'Enter number, range, list or steps'/*/T*/,
                'value'         => '*',
            ),
            /*T*/'Run schedule - Day of the week'/*/T*/  => array(
                'type'          => 'text',
                'description'   => /*T*/'Enter number in range 0-6 (0 is Sunday) or a 3 letter shortcut (e.g. sun)'/*/T*/,
                'value'         => '*',
            ),
        );
    
        return $variables;
    }
    
    function execute()
    {
        require_once 'modules/billing/models/Invoice.php';
        $messages = array();
        $numMailsSent = 0;
        $query = "SELECT id, subject, `from`, from_name, bcc, priority, confirmreceipt, emailtype, body, contenttype, dfilename, attachment FROM email_queue";
        $result = $this->db->query($query);
        while ($row = $result->fetch()) {
            // Extract multiple attachments
            if (strpos($row['dfilename'], "||") !== false) {
                $row['dfilename'] = explode("||", $row['dfilename']);
                //$row['attachment'] = unserialize($row['attachment']);
            }
            //---------------------------------------------------------------------------------
            //Added the code snippet to fix the issue reported in 59863
            //Issue - if the service "bulk mailer" is enabled, the pdf attached to the invoice is getting corrupted
            //because UTF-8 charset do not taking the pdf content.
            $invoiceId = strrchr($row['dfilename'], "_");
            $invoiceId = mb_substr($invoiceId,1,strlen($invoiceId)-4);
            $tempInvoice = new Invoice($this->user, $invoiceId);
            $tUser = new User($tempInvoice->getUserID());

            // change language to the customer's
            $this->user->getLanguage();    // just to get the customFields filled

            if ($this->settings->get("Attach PDF When Mailing Invoice") == 1) {
                require_once 'modules/billing/models/PDFInvoice.php';
                $pdf = new PDFInvoice($tUser, $invoiceId);
                $row['attachment'] = $pdf->get();

                $pdfname = $tUser->lang("invoice")."_$nvoiceID.pdf";
            } else {
                $row['attachment'] = "";
                $pdfname = "";
            }
            //------------------------------------------------------------------------------------

            $body = @unserialize($row['body']);
            if (!$body) {
                $body = $row['body'];
            }

            $mailGateway = new NE_MailGateway();

            // better to call MailGateway::sendMailMessage() for each userid instead of calling it once with
            // the array of ids, so that we can erase each entry in email_queue_addressees right after is sent.
            // Before, we used to send all in an array, and if the process failed at some point, the addressees that
            // did get processed weren't being erased from the queue.
            $query2 = "SELECT userid FROM email_queue_addressees WHERE email_queue_id = ?";
            $result2 = $this->db->query($query2, $row['id']);
            $failedAddressees = array();
            while ($row2 = $result2->fetch()) {
                if ($this->_isSerialization($row['bcc'])) {
                    $row['bcc'] = unserialize($row['bcc']);
                }
                $mailSend = $mailGateway->sendMailMessage(  $body,
                                                            $row['from'],
                                                            $row['from_name'],
                                                            $row2['userid'],
                                                            $row['bcc'],
                                                            $row['subject'],
                                                            $row['priority'],
                                                            $row['confirmreceipt'],
                                                            $row['emailtype'],
                                                            $row['attachment'],
                                                            $row['dfilename'],
                                                            $row['contenttype']); 
                if (!is_a($mailSend, 'NE_Error')) {
                    $numMailsSent++;
                    $query3 = "DELETE FROM email_queue_addressees WHERE email_queue_id=? AND userid = ?";
                    $this->db->query($query3, $row['id'], $row2['userid']);
                } else {
                    $failedAddressees[] = $row2['userid'];
                }
            }

            if ($failedAddressees) {
                $users = implode(', ', $failedAddressees);
                $this->logger->log(1, "Error trying to E-mail queued message to user(s) $users");
                $messages[] = new NE_Error($this->user->lang('Error trying to E-mail queued message to user(s) %s', $users));
            } else {
                $query4 = "DELETE FROM email_queue WHERE id=?";
                $this->db->query($query4, $row['id']);
            }
        }
    
        array_unshift($messages, $this->user->lang('%s message(s) sent', $numMailsSent));
    
        return $messages;
    }
    
    function output()
    {
        $queueDeleted = false;
    	
    	if(isset($_GET['mail_delete'])) {
        	$query2 = "DELETE FROM email_queue WHERE id = ?";
            $this->db->query($query2, $_GET['mail_delete']);
        	$query2 = "DELETE FROM email_queue_addressees WHERE email_queue_id = ?";
            $this->db->query($query2, $_GET['mail_delete']);
         	$queueDeleted = true;
        }    
		
            
    	$this->tpl->define(array('mailqueue_table' => 'views/admin/mailqueue_table.tpl'));
        $this->tpl->define_dynamic('email', 'mailqueue_table');
       
        
        if ($queueDeleted) {
       		 $this->tpl->assign('SUCCESS_MESSAGE', $this->user->lang('E-MAIL SUCCESSFULLY DELETED'));
       		 $queueDeleted = false;
        }
        
        $rowclass="odd";

        $query = "SELECT id, subject, bcc, body, emailtype, attachment FROM email_queue";
        $result = $this->db->query($query);
        $queueEmpty = true;
        $mailGateway = new NE_MailGateway();
        $limit = 100;
        while ($row = $result->fetch()) {
            $emails = array();
            $query2 = "SELECT userid FROM email_queue_addressees WHERE email_queue_id=?";
            $result2 = $this->db->query($query2, $row['id']);
            $i = 0;
            while ($row2 = $result2->fetch()) {
                if ($i++ > $limit){
                    $emails[] = "<br><b>".$this->user->lang('...with a total of %s E-mails', $result2->getNumRows())."</b>";
                    break;
                }
                $emails = array_merge($emails, $mailGateway->getEmailsForUserID($row2['userid'], $row['emailtype']));
            }
            $to = implode(', ', $emails);

            $bodyArr = @unserialize($row['body']);
            if ($bodyArr) {
                if ($bodyArr['HTML']) {
                   $body = strip_tags(NE_MailGateway::br2nl($bodyArr['HTML']));
                } else {
                    $body = $bodyArr['plainText'];
                }
            } else {
                $body = $row['body'];
            }

            $body = trim(mb_substr($body, 0, 200));
            if (strlen($row['body']) > 200) {
                $body .= ' ...';
            }

            $bcc = $this->_isSerialization($row['bcc'])? implode('<br />', unserialize($row['bcc'])): $row['bcc'];

            $this->tpl->setkey(array(
                'trClass'           => $rowclass,
                'email_id'          => $row['id'],
                'email_subject'     => $row['subject'],
                'email_to'          => $to,
                'email_bcc'         => $bcc,
                'email_body'        => $body,
                'email_attachments' => $row['attachment']? $this->user->lang('Yes') : $this->user->lang('No'),
            ));
    
            $queueEmpty = false;
    
            //alternate row color
            if ($rowclass=="odd") $rowclass="even";
            else $rowclass="odd";
    
            $this->tpl->subst('trash', '.email');
        }

        if ($queueEmpty) {
            $this->tpl->setkey('NOEMAILS', "<tr><td colspan=\"5\" align=\"center\" style=\"font-style:italic\">".$this->user->lang('The queue is empty')."</td></tr>");
        } else {
            $this->tpl->setkey('NOEMAILS', '');
        }
        
        $this->tpl->parse('output', 'mailqueue_table');
    
        return $this->tpl->fetch('output');
    }
    
    function dashboard()
    {
        $query = "SELECT COUNT(id) AS emails FROM email_queue";
        $result = $this->db->query($query);
        $row = $result->fetch();
        if (!$row) {
            $row['emails'] = 0;
        }
    
        return $this->user->lang('Current E-mails in queue: %d', $row['emails']);
    }

    function _isSerialization($string)
    {
        return mb_substr($string, 0, 2) == 'a:';
    }
}
?>
