<?php

if (!defined('_SUPPORT_BOUNCEBACKSUBJECT')) {
    define('_SUPPORT_BOUNCEBACKSUBJECT', 'Support request failure');
}

if (!defined('SERVICE_CALL')) {
    // read from stdin
    $fd = fopen("php://stdin", "r");
    $email = "";
    while (!feof($fd)) {
        $email .= fread($fd, 1024);
    }
    //fclose($fd);
    define('INCLUDE_STEPS', 'supportPipe');
    define('DONT_SHOW_ERRORS', true);
    require_once dirname(__FILE__).'/common/common.php';
    include_once("classes/troubletickets.php");
    include_once("classes/troubleticket.php");
    require_once 'classes/emailparser.php';
    include_once("modules/support/fncSupportFunctions.php");
    runPipe($email);
}

function runPipe($email)
{
    global $gSettingsArray;
    
    if (!@$GLOBALS['gSettingsArray']['Email Piping In Use']) {
        $sql = "UPDATE `setting` SET value=1 WHERE name='Email Piping In Use'";
        $result = $GLOBALS['db']->query($sql);
    }

    // do not change
    $supportdir = dirname(__FILE__) . '/uploads/support/';

    $ep = new EmailParser($email);
    $ep->parse();
    $from = $ep->getFrom();
    $subject = $ep->getSubject();
    $message = $ep->getMessage();
    $numAttachments = $ep->getNumAttachments();
    $validExtensions = explode(',',$gSettingsArray['Allowed File Extensions']);

    //ok, now we have the message and the subject, let's get the userid
    $userId = getUserIdForEmail($from);

    //should be everything we need to submit a ticket. let's populate the post
    $_POST['userid'] = $userId;
    $_POST['subject'] = $subject;

    if ($userId != "") {
        //see if this is a response to an existing ticket
        if (preg_match("/.*\[ce-(.*)\]/", $subject, $matchid))
        {
            $responseId = $matchid[1];
            $remove = array('subject');
            $sendAssignedTo = true;

            $cTicket = new TroubleTicket($responseId);
            $cTicket->SetStatus('1');
            $cTicket->SetLastLogDateTime(date('Y-m-d H-i-s'));
            $cTicket->Update();
            $fileattach = array();
            $filenames = array();
            if ($numAttachments > 0 && is_writable($supportdir) && $gSettingsArray['Allow Customer File Uploads']) {
                for ($i = 0; $i < $numAttachments; $i++) {
                    $attachment = $ep->getAttachment($i);
                    $filekey = $cTicket->generateFileKey();
                    if (($pos = strrpos($attachment['name'], '.')) !== false) {
                        $len = strlen($attachment['name']) - ($pos+1);
                        $ext = substr($attachment['name'], -$len);
                    }
                    if (in_array($ext, $validExtensions) || in_array('*',$validExtensions)) {
                        $fp = @fopen($supportdir.$filekey, "w");
                        fwrite($fp, $attachment['string']);
                        fclose($fp);
                        chmod($supportdir.$filekey, 0666);
                        $cTicket->addFile($attachment['name'],$filekey,$userId);
                        $message = "** ".lang("File Attached").": ".$attachment['name']." **\n\n".$message;
                        $fileattach[] = $attachment['string'];
                        $filename[] = $attachment['name'];
                    }
                }
            }
            $cTicketLog = new TroubleTicketLog();
            $cTicketLog->populated = true;
            $cTicketLog->setUserID($userId);
            $cTicketLog->setTroubleTicketID($responseId);
            $cTicketLog->setMessage($message);
            $cTicketLog->SetDateTime(date('Y-m-d H-i-s'));
            $cTicketLog->setLogAction(0);
            $cTicketLog->insert();
            $tUser =& new User($_POST['userid']);
            $tUser->PopulateCustomFields();

            if ($tUser->GetGroupID()==1){
                //Get all the emails I need to send out an email for (emails in settings->admin->support->email for new templates
                $strMessage = "Dear Support Member,\n\nThere has been an update to ticket #$responseId by ".$tUser->getFullName()."\n\nMessage: $message";
                if ($gSettingsArray['E-mail For New Trouble Tickets'] != ""){
                    $aSupportEmail = explode(",", $gSettingsArray['E-mail For New Trouble Tickets']);
                                                //Create Assigned Admin
                                                $tAssignedAdmin =& new User($cTicket->GetAssignedToID());
                                                $tAssignedAdmin->PopulateCustomFields();

                        foreach ($aSupportEmail as $email)
                        {
                            $email = trim($email);
                            if($email == $gSettingsArray['Support E-mail']){
                                //we can not notify the support email as this will result in an endless loop
                                //try to notify the admin of this problem
                                $strMessage = "Dear Admin, \n\n There is a problem in the helpdesk configuration. \n";
                                $strMessage .= " The \'Support E-mail\' setting is the same email address as the \'E-mail For New Trouble Tickets\' setting\n";
                                $strMessage .= " This configuration can result in and endless pipe loop.  Please go to admin -> settings -> supprt and make sure these values are not the same address";
                                $adminEmail = "greg@cclhosting.com"; //find out how to get the admin email list
                                MailMessageEmail($strMessage,$gSettingsArray['Support E-mail'],$gSettingsArray['Support E-mail'],$adminEmail,'',"Helpdesk Misconfiguration",3,0);
                            }

                           else if ($email!="") MailMessageEmail($strMessage,$gSettingsArray['Support E-mail'],$gSettingsArray['Support E-mail'],$email,'',"[ce-{$responseId}] ".lang("Support ticket has been updated"),3,0,$fileattach,$filename);
                                                        //Check to see if the assigned to email is the same
                                                        //If it is then set $sendassignedto to false since email
                                                        //has already been sent out to them
                                                        if (trim($tAssignedAdmin->getEmail())==trim($email)) $sendAssignedTo = false;
                        }
                }
                //also notify admin assigned to ticket
                if (($cTicket->GetAssignedToID()!=0)&&($sendAssignedTo)) {
                    mailMessage($strMessage,$gSettingsArray['Support E-mail'],$gSettingsArray['Support E-mail'],$cTicket->GetAssignedToID(),'',"[ce-{$responseId}] ".lang("Support ticket has been updated"),3,0,'notifications',$fileattach,$filename);
                }
            }else{
                // notify client of admin reply
                $tClient =& new User($cTicket->GetUserID());
                $tClient->PopulateCustomFields();
                /* replace tags */
                $strEmailString = $gSettingsArray['Trouble Ticket Template'];
                $strEmailString = str_replace("[COMPANYNAME]", $gSettingsArray["Company Name"], $strEmailString);
                $strEmailString = str_replace("[CLIENTNAME]", $tClient->getFullName(), $strEmailString);
                $strEmailString = str_replace("[CLIENTAPPLICATIONURL]", $gSettingsArray["ClientExec URL"], $strEmailString);
                $strEmailString = str_replace("[DESCRIPTION]", $message, $strEmailString);
                $strEmailString = str_replace("[TICKETNUMBER]", $responseId, $strEmailString);
                $strEmailString = ReplaceCustomFields($strEmailString,$cTicket->GetUserID());

                if (@$GLOBALS['gSettingsArray']['Email Piping In Use']) {
                    /* Add reply above this line */
                    $strEmailString = "+----------- ".lang("Please reply above this line")." -----------+\n".$strEmailString;
                }
                mailMessage($strEmailString,$gSettingsArray['Support E-mail'],$gSettingsArray['Support E-mail'],$cTicket->GetUserID(),'',"[ce-{$responseId}] ".lang("Support ticket has been updated"),3,0,'notifications',$fileattach,$filename);
            }
        }
        else
        {
            //ce ticket code
            $tTimeStamp = date('Y-m-d H-i-s');
            $cTicket = new TroubleTicket();
            $cTicket->populated = true;
            $cTickets = new TroubleTickets();
            $cTickets->GetAllTickets("id","All",true);
            if ($cTickets->m_TicketCount == 0)
            {
                $cTickets->GetAllTickets("id","All",false);
                {   //need to add id to post so that the initial invoice setting is used
                    if ($cTickets->m_TicketCount == 0) {
                    	 $id = $gSettingsArray['Trouble Ticket Start Number'];
                    	 $cTicket->setID($id);
                    }
                }
            }
            
            $sql = "SELECT name FROM troubleticket_type ORDER BY myorder DESC LIMIT 1";
            $result = $GLOBALS['db']->query($sql);
            $row = $result->fetch();

            $cTicket->setUserId($userId);
            $cTicket->setSubject($subject);
            $cTicket->SetDateSubmitted($tTimeStamp);
            $cTicket->SetLastLogDateTime($tTimeStamp);
            $cTicket->SetMessageType($row['name']);
            $cTicket->SetPriority(3);
            $cTicket->SetStatus(2);
            $cTicket->SetAssignedToID(0);
            $newticket = $cTicket->insert();
            $ccTicket = new TroubleTicket($newticket);
            $filename = array();
            $fileattach = array();
            if ($numAttachments > 0 && is_writable($supportdir) && $gSettingsArray['Allow Customer File Uploads']) {
                for ($i = 0; $i < $numAttachments; $i++) {
                    $attachment = $ep->getAttachment($i);
                    $filekey = $ccTicket->generateFileKey();
                    if (($pos = strrpos($attachment['name'], '.')) !== false) {
                        $len = strlen($attachment['name']) - ($pos+1);
                        $ext = substr($attachment['name'], -$len);
                    }
                    if (in_array($ext, $validExtensions) || in_array('*',$validExtensions)) {
                        $fp = @fopen($supportdir.$filekey, "w");
                        fwrite($fp, $attachment['string']);
                        fclose($fp);
                        chmod($supportdir.$filekey, 0666);
                        $ccTicket->addFile($attachment['name'],$filekey,$userId);
                        $message = "** ".lang("File Attached").": ".$attachment['name']." **\n\n".$message;
                        $fileattach[] = $attachment['string'];
                        $filename[] = $attachment['name'];
                    }
                }
            }

            AddInitialLogForTicketID($newticket,$message,$tTimeStamp,$userId);
            $tUser =& new User($userId);
            $tUser->PopulateCustomFields();

            // Send autoreply to new ticket.
            $strCustomerEmail = $gSettingsArray['New Trouble Ticket Autoresponder Template'];
            $strCustomerEmail = str_replace("[COMPANYNAME]", $gSettingsArray["Company Name"], $strCustomerEmail);
            $strCustomerEmail = str_replace("[CLIENTNAME]", $tUser->getFullName(), $strCustomerEmail);
            $strCustomerEmail = str_replace("[CLIENTAPPLICATIONURL]", $gSettingsArray["ClientExec URL"], $strCustomerEmail);
            $strCustomerEmail = str_replace("[DESCRIPTION]", $message, $strCustomerEmail);
            $strCustomerEmail = str_replace("[TICKETNUMBER]", "[ce-".$newticket."]", $strCustomerEmail);
            $strCustomerEmail = ReplaceCustomFields($strCustomerEmail,$cTicket->GetUserID());
            MailMessageEmail($strCustomerEmail,$gSettingsArray['Support E-mail'],$gSettingsArray['Support E-mail'],$from,'',"[ce-".$newticket."] ".$subject,3,0);


            $strMessage = "Dear Support Member,\n\nTrouble ticket #".$newticket." had been entered by ".$tUser->getFullName()."\nSubject: ".$_POST['subject']."\n\nMessage: ".$message;

            //Get all the emails I need to send out an email for
            if ($gSettingsArray['E-mail For New Trouble Tickets'] != ""){
                $aSupportEmail = explode(",", $gSettingsArray['E-mail For New Trouble Tickets']);
                foreach ($aSupportEmail as $email)
                {
                    $email = trim($email);
                    if (@$GLOBALS['gSettingsArray']['Email Piping In Use']) {
                        /* Add reply above this line */
                        $strMessage = "+----------- ".lang("Please reply above this line")." -----------+\n".$strMessage;
                    }
                    if($email == $gSettingsArray['Support E-mail']){
                            //we can not notify the support email as this will result in an endless loop
                            //try to notify the admin of this problem
                            $admins = getAllAdminOfType('2');
                            foreach($admins as $adminName=>$adminEmail)
                            {
                                $strMessage = "Dear Admin, \n\n There is a problem in the helpdesk configuration. \n";
                                $strMessage .= " The \'Support E-mail\' setting is the same email address as the \'E-mail For New Trouble Tickets\' setting\n";
                                $strMessage .= " This configuration can result in and endless pipe loop.  Please go to admin -> settings -> supprt and make sure these values are not the same address";
                                MailMessageEmail($strMessage,$gSettingsArray['Support E-mail'],$gSettingsArray['Support E-mail'],$adminEmail,'',"Helpdesk Misconfiguration",3,0,$fileattach,$filename);
                            }
                    }
                    else if ($email!="") MailMessageEmail($strMessage,$gSettingsArray['Support E-mail'],$gSettingsArray['Support E-mail'],$email,'',"[ce-".$newticket."] ".lang("A new support ticket has been added"),3,0,$fileattach,$filename);
                }
            }
        }
    }
    //else we could not find this user, let's either bounce the message or forward it to the forward email
    else{
            if($gSettingsArray['Alternate Support Address'] != "")
            {
                if ($gSettingsArray['Alternate Support Address'] == $gSettingsArray['Support E-mail']) {
                    //we can not notify the support email as this will result in an endless loop
                    //try to notify the admin of this problem
                    $admins = getAllAdminOfType('2');
                    foreach($admins as $adminName=>$adminEmail)
                    {
                        $strMessage = "Dear Admin, \n\n There is a problem in the helpdesk configuration. \n";
                        $strMessage .= " The \'Support E-mail\' setting is the same email address as the \'E-mail For New Trouble Tickets\' setting\n";
                        $strMessage .= " This configuration can result in and endless pipe loop.  Please go to admin -> settings -> supprt and make sure these values are not the same address";
                        MailMessageEmail($strMessage,$gSettingsArray['Support E-mail'],$gSettingsArray['Support E-mail'],$adminEmail,'',"Helpdesk Misconfiguration",3,0);
                    }
                } else {
                    $filename = array();
                    $fileattach = array();
                    for ($i = 0; $i < $numAttachments; $i++) {
                        $attachment = $ep->getAttachment($i);
                        $fileattach[] = $attachment['string'];
                        $filename[] = $attachment['name'];
                    }
                    $strSubject = "[Unknown helpdesk user] $subject";
                    $strMessage = "The following email was sent to: ".$gSettingsArray['Support E-mail']."\n";
                    $strMessage .= "From:  ".$from."\n";
                    $strMessage .= "Subject:  ".$subject."\n";
                    $strMessage .= "The email could not be piped to the helpdesk because a user with that email address could not be found.\n\n";
                    $strMessage .= "A copy of the message is below: \n\n\n\n".$message;
                    MailMessageEmail($strMessage,$from,$gSettingsArray['Support E-mail'],$gSettingsArray['Alternate Support Address'],'',$strSubject,3,0,$fileattach,$filename);
                }
            } else if ($gSettingsArray['Support E-mail'] == $from) {
                return 0;
            } elseif ($gSettingsArray['Bounce Back Template'] != "") {
                MailMessageEmail($gSettingsArray['Bounce Back Template'],$gSettingsArray['Support E-mail'],$gSettingsArray['Support E-mail'],$from,'',_SUPPORT_BOUNCEBACKSUBJECT,3,0);
            } else {

                //we are going to tell the admin something is wrong
                $admins = getAllAdminOfType('2');
                foreach($admins as $adminName=>$adminEmail)
                {
                    if ($adminEmail == $gSettingsArray['Support E-mail']) continue;
                    $strMessage = "Your Support Desk is not fully configured. You need to fill out either a ";
                    $strMessage .="Alternate Support Address or fill in a Bounce back message\n";
                    $strMessage .="Both of these options could not be found when trying to handle the following support email: \n\n\n";
                    $strMessage .= $email;
                    MailMessageEmail($strMessage,$gSettingsArray['Support E-mail'],$gSettingsArray['Support E-mail'],$adminEmail,'',"Support Desk not configured",3,0,$fileattach,$filename);
                }
            }

        }
}

return 0;
?>
