<?php

require_once 'newedge/classes/NE_EmailParser.php';
require_once 'modules/support/models/EmailRoutingRule.php';

/**
* @package Admin
*/
class PipeEmail extends NE_Action
{
    var $email;

    function dispatch()
    {
        // read from stdin
        $fd = fopen("php://stdin", "r");
        $this->email = "";
        while (!feof($fd)) {
            $this->email .= fread($fd, 1024);
        }
        fclose($fd);

        // Uncomment to log all messages
        /*$fp = fopen('/home/newedge/piped_emails.log', 'a');
        fwrite($fp, $this->email . "\r\n\r\n\r\n");
        fclose($fp);*/

        if (!$this->settings->get('Email Piping In Use')) {
            $sql = "UPDATE `setting` SET value=1 WHERE name='Email Piping In Use'";
            $result = $this->db->query($sql);
        }
    
        $ep = new NE_EmailParser($this->email);
        $ep->parse();

        if (trim($ep->getFrom()) == '') {
            $this->logger->log(2, 'Discard incoming e-mail: it doesn\'t have an appropriate From header');
            return false;
        }
        
        if (!$this->checkAutoresponder($ep->getFrom())) {
            $this->logger->log(2, "Discard incoming e-mail: we've entered an autoresponder loop");
            return false;
        }

        $this->events->raise('PipedEmail', array($ep, EMAILROUTINGRULE_PIPEFORWARDING));
    }

    function setEmail($email)
    {
        $this->email = $email;
    }

    /**
     * Determine whether to send the autoreply or not.  We do this to avoid autoresponder loops.
     * Works by checking to see if the last five E-mails that opened a new ticket came from the same
     * E-mail address and if they were all within a few minutes.
     * 
     * @param String $from The E-mail address that the new ticket is coming from.
     * @return True if we should send an autoreply, false otherwise.
     */
    function checkAutoresponder($from)
    {
        $sendAutoReply = false;
        $lastFive = $this->settings->get('E-mail Piping Last Five');
        if ($lastFive != "") {
            $lastFiveArr = @unserialize($lastFive);
            $count = count($lastFiveArr);
            if ($count < 5) {
                $sendAutoReply = true;
                $lastFiveArr[$count]['address'] = $from;
                $lastFiveArr[$count]['time'] = time();
            } else {
                $newLastFiveArr = array();
                for ($i = 0; $i < $count; $i++) {
                    if ($lastFiveArr[$i]['address'] != $from || (time() - $lastFiveArr[$i]['time']) > 30) {
                        $sendAutoReply = true;
                    }
                    if ($i > 0) {
                        $newLastFiveArr[$i - 1]['address'] = $lastFiveArr[$i]['address'];
                        $newLastFiveArr[$i - 1]['time'] = $lastFiveArr[$i]['time'];
                    }
                }
                $newLastFiveArr[$count - 1]['address'] = $from;
                $newLastFiveArr[$count - 1]['time'] = time();
                $lastFiveArr = $newLastFiveArr;
            }
        } else {
            $sendAutoReply = true;
            $lastFiveArr = array();
            $lastFiveArr[0]['address'] = $from;
            $lastFiveArr[0]['time'] = time();
        }
        $this->settings->updateValue('E-mail Piping Last Five', serialize($lastFiveArr));
        
        return $sendAutoReply;
    }
}

?>
