<?php
/**
 * PipeEmail File
 *
 * @category Admin
 * @package  ClientExec
 * @author   Alberto Vasquez <alberto@clientexec.com>
 * @license  ClientExec License
 * @version  [someversion]
 * @link     http://www.clientexec.com
 */

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

/**
 * PipeEmail Action Class
 *
 * @category Admin
 * @package  ClientExec
 * @author   Alberto Vasquez <alberto@clientexec.com>
 * @license  ClientExec License
 * @version  [someversion]
 * @link     http://www.clientexec.com
 */
class PipeEmail extends NE_Action
{
    var $permission     = '';

    var $email;

    /**
     * Action's dispatch method
     *
     * @return void
     */
    function dispatch()
    {

        $this->debug('here');

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

        // Uncomment to log all messages
        /*
        $fp = fopen('/Applications/MAMP/htdocs/ce46x/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(1, 'Discard incoming e-mail: it doesn\'t have an appropriate From header');
            return false;
        }

        if (!$this->checkAutoresponder($ep->getFrom())) {
            $this->logger->log(1, "Discard incoming e-mail: we've entered an autoresponder loop");
            return false;
        }

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

    /**
     * Setting email - not sure if this used
     *
     * @param string $email email to set
     *
     * @return void
     */
    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 bool 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;
    }
}

?>
