<?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']);
            }
            
            if(!is_array($row['dfilename']) && $row['emailtype'] == 'invoice'){
                //---------------------------------------------------------------------------------
                //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")."_{$invoiceId}.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 pendingItems()
	{
		$returnArray = array();
		$returnArray['data'] = array();
		$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'];			
			$tmpInfo = array();
			$tmpInfo['subject'] = $row['subject'];
			$tmpInfo['to'] = $to;
			$tmpInfo['bcc'] = $bcc;
			$tmpInfo['body'] = $body;
			$tmpInfo['attachment'] = $row['attachment']? $this->user->lang('Yes') : $this->user->lang('No');
			$returnArray['data'][] = $tmpInfo;
		}
		$returnArray['totalcount'] = count($returnArray['data']);
		return $returnArray;
	}
	
    function output()
    {
		/*
			XXX: ToDo: Move this to an admin action so we can use it from the pending items dashboard
    	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;
        }*/
    }

    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:';
    }
}
?>