<?php
require_once 'modules/admin/models/ServicePlugin.php';
require_once 'newedge/classes/NE_EmailParser.php';
/**
* @package Plugins
*/
class PluginFetchticket extends ServicePlugin
{
    protected $featureSet = 'support';

    var $events;

    function getVariables()
    {
	$enabledType="";
        if (!isset($this->configuration['modules']['support']['installedVersion'])) {
                $enabledType="hidden";
        }else{
                $enabledType="yesno";
        }

	
        $variables = array(
            /*T*/'Plugin Name'/*/T*/   => array(
                'type'          => 'hidden',
                'description'   => /*T*/''/*/T*/,
                'value'         => /*T*/'Tickets Generator'/*/T*/,
            ),
            /*T*/'Enabled'/*/T*/       => array(
                'type'          => $enabledType,
                'description'   => /*T*/'This is the service that actually does the fetching of E-mails for all E-mail Routing Rules that use the "POP3 fetching" routing type. Only USER authentication mechanism. Be aware that messages on the account will get erased after being imported, or bounced if invalid.'/*/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()
    {
	if (!isset($this->configuration['modules']['support']['installedVersion'])) {
                die('Sorry!To perform this action, you need to install support module.');
        }
        require_once 'plugins/services/fetchticket/pop3.php';
        require_once 'modules/support/models/EmailRoutingRuleGateway.php';

        $this->events = NE_Registry::getEventHandlers($this->user);
   
        $messages = array();
        $rulesGateway = new EmailRoutingRuleGateway();
        $ruleIt = $rulesGateway->getRoutingRulesUsingPop();
        $pipeCount = 0;
        while ($rule = $ruleIt->fetch()) {
            $pop = new pop3_class();
            $pop->hostname  = $rule->getPop3Hostname();
            $pop->port      = $rule->getPop3Port();
            $pop->debug     = 0;
            $pop3->join_continuation_header_lines = 1; /* Concatenate headers split in multiple lines */
            $username       = $rule->getPop3Username();
            $password       = $rule->getPop3Password();
        
            if ($error = $pop->open()) {
                $messages[] = new NE_Error($error);
                continue;
            }
            if ($error = $pop->login($username, $password)) {
                $messages[] = new NE_Error($error);
                if ($error = $pop->close()) {
                    $messages[] = new NE_Error($error);
                }
                continue;
            }
            if (!is_array($result = $pop->listMessages('', 1))) {
                $messages[] = new NE_Error($result);
                if ($error = $pop->close()) {
                    $messages[] = new NE_Error($error);
                }
                continue;
            }
            
            for ($i = 1; $i <= count($result); $i++) {
                $headers = array();
                $body = array();
                if ($error = $pop->retrieveMessage($i, $headers, $body, -1)) {
                    $messages[] = new NE_Error($error);
                    continue;
                }
        
                $email = implode("\r\n", $headers);
                $email .= "\r\n\r\n".implode("\r\n", $body);

                $ep = new NE_EmailParser($email);
                $ep->parse();
    
                $to = trim($ep->getTo());
                if (!in_array('*', $rule->getEmails()) && !in_array($to, $rule->getEmails())) {
                    continue;
                }

                $this->events->raise('PipedEmail', array($ep, EMAILROUTINGRULE_POP3, $rule));

                if ($rule->isPop3DeleteEmails() && $error =$pop->deleteMessage($i)) {
                    $messages[] = new NE_Error($error);
                    continue;
                }
        
            }
        
            if ($error = $pop->close()) {
                $messages[] = new NE_Error($error);
                continue;
            }
            $pipeCount++;
        }
		$messages[] = $this->user->lang('%s POP3 support rules processed', $pipeCount);
        return $messages;
    }
    
    function output()
    {
    }
    
    function dashboard()
    {
    }
}
?>
