Пример #1
0
 /**
  * Converts a note to a draft or an email
  *
  * @param int $note_id The id of the note
  * @param string $target What the note should be converted too (email, etc)
  * @param bool $authorize_sender If $authorize_sender If the sender should be added to authorized senders list.
  * @return int
  */
 public static function convertNote($note_id, $target, $authorize_sender = false)
 {
     $issue_id = self::getIssueID($note_id);
     $email_account_id = Email_Account::getEmailAccount();
     $blocked_message = self::getBlockedMessage($note_id);
     $unknown_user = self::getUnknownUser($note_id);
     $structure = Mime_Helper::decode($blocked_message, true, true);
     $body = $structure->body;
     $sender_email = strtolower(Mail_Helper::getEmailAddress($structure->headers['from']));
     $current_usr_id = Auth::getUserID();
     if ($target == 'email') {
         if (Mime_Helper::hasAttachments($structure)) {
             $has_attachments = 1;
         } else {
             $has_attachments = 0;
         }
         list($blocked_message, $headers) = Mail_Helper::rewriteThreadingHeaders($issue_id, $blocked_message, @$structure->headers);
         $t = array('issue_id' => $issue_id, 'ema_id' => $email_account_id, 'message_id' => @$structure->headers['message-id'], 'date' => Date_Helper::getCurrentDateGMT(), 'from' => @$structure->headers['from'], 'to' => @$structure->headers['to'], 'cc' => @$structure->headers['cc'], 'subject' => @$structure->headers['subject'], 'body' => @$body, 'full_email' => @$blocked_message, 'has_attachment' => $has_attachments, 'headers' => $headers);
         // need to check for a possible customer association
         if (!empty($structure->headers['from'])) {
             $details = Email_Account::getDetails($email_account_id);
             // check from the associated project if we need to lookup any customers by this email address
             if (CRM::hasCustomerIntegration($details['ema_prj_id'])) {
                 $crm = CRM::getInstance($details['ema_prj_id']);
                 // check for any customer contact association
                 try {
                     $contact = $crm->getContactByEmail($sender_email);
                     $issue_contract = $crm->getContract(Issue::getContractID($issue_id));
                     if ($contact->canAccessContract($issue_contract)) {
                         $t['customer_id'] = $issue_contract->getCustomerID();
                     }
                 } catch (CRMException $e) {
                 }
             }
         }
         if (empty($t['customer_id'])) {
             $update_type = 'staff response';
             $t['customer_id'] = null;
         } else {
             $update_type = 'customer action';
         }
         $res = Support::insertEmail($t, $structure, $sup_id);
         if ($res != -1) {
             Support::extractAttachments($issue_id, $structure);
             // notifications about new emails are always external
             $internal_only = false;
             // special case when emails are bounced back, so we don't want to notify the customer about those
             if (Notification::isBounceMessage($sender_email)) {
                 $internal_only = true;
             }
             Notification::notifyNewEmail($current_usr_id, $issue_id, $t, $internal_only, false, '', $sup_id);
             Issue::markAsUpdated($issue_id, $update_type);
             self::remove($note_id, false);
             History::add($issue_id, $current_usr_id, 'note_converted_email', 'Note converted to e-mail (from: {from}) by {user}', array('from' => @$structure->headers['from'], 'user' => User::getFullName($current_usr_id)));
             // now add sender as an authorized replier
             if ($authorize_sender) {
                 Authorized_Replier::manualInsert($issue_id, @$structure->headers['from']);
             }
         }
         return $res;
     }
     // save message as a draft
     $res = Draft::saveEmail($issue_id, $structure->headers['to'], $structure->headers['cc'], $structure->headers['subject'], $body, false, $unknown_user);
     // remove the note, if the draft was created successfully
     if ($res) {
         self::remove($note_id, false);
         $usr_id = $current_usr_id;
         History::add($issue_id, $usr_id, 'note_converted_draft', 'Note converted to draft (from: {from}) by {user}', array('from' => @$structure->headers['from'], 'user' => User::getFullName($current_usr_id)));
     }
     return $res;
 }
Пример #2
0
 /**
  * TODO: merge use of $options and $email arrays to just $email
  *
  * @param int $issue_id
  * @param string $type type of email
  * @param string $from
  * @param string $to
  * @param string $cc
  * @param string $subject
  * @param string $body
  * @param array $options optional parameters
  * - (int) parent_sup_id
  * - (array) iaf_ids attachment file ids
  * - (bool) add_unknown
  * - (int) ema_id
  * @return int 1 if it worked, -1 otherwise
  */
 public static function sendEmail($issue_id, $type, $from, $to, $cc, $subject, $body, $options = array())
 {
     $parent_sup_id = $options['parent_sup_id'];
     $iaf_ids = $options['iaf_ids'];
     $add_unknown = $options['add_unknown'];
     $ema_id = $options['ema_id'];
     $current_usr_id = Auth::getUserID();
     $prj_id = Issue::getProjectID($issue_id);
     // if we are replying to an existing email, set the In-Reply-To: header accordingly
     $in_reply_to = $parent_sup_id ? self::getMessageIDByID($parent_sup_id) : false;
     // get ID of whoever is sending this.
     $sender_usr_id = User::getUserIDByEmail(Mail_Helper::getEmailAddress($from)) ?: false;
     // remove extra 'Re: ' from subject
     $subject = Mail_Helper::removeExcessRe($subject, true);
     $internal_only = false;
     $message_id = Mail_Helper::generateMessageID();
     // process any files being uploaded
     // from ajax upload, attachment file ids
     if ($iaf_ids) {
         // FIXME: is it correct to use sender from post data?
         $attach_usr_id = $sender_usr_id ?: $current_usr_id;
         Attachment::attachFiles($issue_id, $attach_usr_id, $iaf_ids, false, 'Attachment originated from outgoing email');
     }
     // hack needed to get the full headers of this web-based email
     $full_email = self::buildFullHeaders($issue_id, $message_id, $from, $to, $cc, $subject, $body, $in_reply_to, $iaf_ids);
     // email blocking should only be done if this is an email about an associated issue
     if ($issue_id) {
         $user_info = User::getNameEmail($current_usr_id);
         // check whether the current user is allowed to send this email to customers or not
         if (!self::isAllowedToEmail($issue_id, $user_info['usr_email'])) {
             // add the message body as a note
             $note = Mail_Helper::getCannedBlockedMsgExplanation() . $body;
             $note_options = array('full_message' => $full_email, 'is_blocked' => true);
             Note::insertNote($current_usr_id, $issue_id, $subject, $note, $note_options);
             $email_details = array('from' => $from, 'to' => $to, 'cc' => $cc, 'subject' => $subject, 'body' => &$body, 'message' => &$body, 'title' => $subject);
             Workflow::handleBlockedEmail($prj_id, $issue_id, $email_details, 'web');
             return 1;
         }
     }
     // only send a direct email if the user doesn't want to add the Cc'ed people to the notification list
     if (($add_unknown || Workflow::shouldAutoAddToNotificationList($prj_id)) && $issue_id) {
         // add the recipients to the notification list of the associated issue
         $recipients = array($to);
         $recipients = array_merge($recipients, self::getRecipientsCC($cc));
         foreach ($recipients as $address) {
             if ($address && !Notification::isIssueRoutingSender($issue_id, $address)) {
                 $actions = Notification::getDefaultActions($issue_id, $address, 'add_unknown_user');
                 Notification::subscribeEmail($current_usr_id, $issue_id, Mail_Helper::getEmailAddress($address), $actions);
             }
         }
     } else {
         // Usually when sending out emails associated to an issue, we would
         // simply insert the email in the table and call the Notification::notifyNewEmail() method,
         // but on this case we need to actually send the email to the recipients that are not
         // already in the notification list for the associated issue, if any.
         // In the case of replying to an email that is not yet associated with an issue, then
         // we are always directly sending the email, without using any notification list
         // functionality.
         if ($issue_id) {
             // send direct emails only to the unknown addresses, and leave the rest to be
             // catched by the notification list
             $from = Notification::getFixedFromHeader($issue_id, $from, 'issue');
             // build the list of unknown recipients
             if ($to) {
                 $recipients = array($to);
                 $recipients = array_merge($recipients, self::getRecipientsCC($cc));
             } else {
                 $recipients = self::getRecipientsCC($cc);
             }
             $unknowns = array();
             foreach ($recipients as $address) {
                 if (!Notification::isSubscribedToEmails($issue_id, $address)) {
                     $unknowns[] = $address;
                 }
             }
             if ($unknowns) {
                 $to2 = array_shift($unknowns);
                 $cc2 = implode('; ', $unknowns);
                 // send direct emails
                 self::sendDirectEmail($issue_id, $from, $to2, $cc2, $subject, $body, $_FILES['attachment'], $message_id, $sender_usr_id);
             }
         } else {
             // send direct emails to all recipients, since we don't have an associated issue
             $project_info = Project::getOutgoingSenderAddress(Auth::getCurrentProject());
             // use the project-related outgoing email address, if there is one
             if (!empty($project_info['email'])) {
                 $from = Mail_Helper::getFormattedName(User::getFullName($current_usr_id), $project_info['email']);
             } else {
                 // otherwise, use the real email address for the current user
                 $from = User::getFromHeader($current_usr_id);
             }
             // send direct emails
             self::sendDirectEmail($issue_id, $from, $to, $cc, $subject, $body, $_FILES['attachment'], $message_id);
         }
     }
     $email = array('customer_id' => 'NULL', 'issue_id' => $issue_id, 'ema_id' => $ema_id, 'message_id' => $message_id, 'date' => Date_Helper::getCurrentDateGMT(), 'from' => $from, 'to' => $to, 'cc' => $cc, 'subject' => $subject, 'body' => $body, 'full_email' => $full_email);
     // associate this new email with a customer, if appropriate
     if (Auth::getCurrentRole() == User::getRoleID('Customer')) {
         if ($issue_id) {
             $crm = CRM::getInstance($prj_id);
             try {
                 $contact = $crm->getContact(User::getCustomerContactID($current_usr_id));
                 $issue_contract = $crm->getContract(Issue::getContractID($issue_id));
                 if ($contact->canAccessContract($issue_contract)) {
                     $email['customer_id'] = $issue_contract->getCustomerID();
                 }
             } catch (CRMException $e) {
             }
         } else {
             $customer_id = User::getCustomerID($current_usr_id);
             if ($customer_id && $customer_id != -1) {
                 $email['customer_id'] = $customer_id;
             }
         }
     }
     $email['has_attachment'] = $iaf_ids ? 1 : 0;
     $structure = Mime_Helper::decode($full_email, true, false);
     $email['headers'] = $structure->headers;
     self::insertEmail($email, $structure, $sup_id);
     if ($issue_id) {
         // need to send a notification
         Notification::notifyNewEmail($current_usr_id, $issue_id, $email, $internal_only, false, $type, $sup_id);
         // mark this issue as updated
         $has_customer = $email['customer_id'] && $email['customer_id'] != 'NULL';
         if ($has_customer && (!$current_usr_id || User::getRoleByUser($current_usr_id, $prj_id) == User::getRoleID('Customer'))) {
             Issue::markAsUpdated($issue_id, 'customer action');
         } else {
             if ($sender_usr_id && User::getRoleByUser($sender_usr_id, $prj_id) > User::getRoleID('Customer')) {
                 Issue::markAsUpdated($issue_id, 'staff response');
             } else {
                 Issue::markAsUpdated($issue_id, 'user response');
             }
         }
         History::add($issue_id, $current_usr_id, 'email_sent', 'Outgoing email sent by {user}', array('user' => User::getFullName($current_usr_id)));
     }
     return 1;
 }
Пример #3
0
 /**
  * @param int $issue_id
  * @param bool $redeemed_only
  * @return array
  * @access protected
  */
 public function getIncidentTypes($issue_id, $redeemed_only)
 {
     $prj_id = Issue::getProjectID($issue_id);
     AuthCookie::setProjectCookie($prj_id);
     // FIXME: $customer_id unused
     $customer_id = Issue::getCustomerID($issue_id);
     if (!CRM::hasCustomerIntegration($prj_id)) {
         // no customer integration
         throw new RemoteApiException("No customer integration for issue #{$issue_id}");
     }
     $crm = CRM::getInstance($prj_id);
     // FIXME: $all_types unused
     $all_types = $crm->getIncidentTypes();
     $contract = $crm->getContract(Issue::getContractID($issue_id));
     if (!$contract->hasPerIncident()) {
         // check if is per incident contract
         throw new RemoteApiException("Customer for issue #{$issue_id} does not have a per-incident contract");
     }
     $incidents = $contract->getIncidents();
     foreach ($incidents as $type_id => $type_details) {
         $is_redeemed = $contract->isRedeemedIncident($issue_id, $type_id);
         if ($redeemed_only && !$is_redeemed || !$redeemed_only && $is_redeemed) {
             unset($incidents[$type_id]);
         }
     }
     return $incidents;
 }
Пример #4
0
// |                                                                      |
// | Free Software Foundation, Inc.                                       |
// | 51 Franklin Street, Suite 330                                          |
// | Boston, MA 02110-1301, USA.                                          |
// +----------------------------------------------------------------------+
// | Authors: Bryan Alsdorf <*****@*****.**>                             |
// +----------------------------------------------------------------------+
require_once dirname(__FILE__) . '/../init.php';
// This page handles marking an issue as 'redeeming' an incident.
Auth::checkAuthentication(APP_COOKIE, 'index.php?err=5', true);
$prj_id = Auth::getCurrentProject();
$issue_id = $_REQUEST['iss_id'];
$usr_id = Auth::getUserID();
if (!Issue::canAccess($issue_id, $usr_id) || Auth::getCurrentRole() <= User::getRoleID('Customer')) {
    $tpl->setTemplate('permission_denied.tpl.html');
    $tpl->displayTemplate();
    exit;
}
$tpl = new Template_Helper();
$tpl->setTemplate('redeem_incident.tpl.html');
$crm = CRM::getInstance($prj_id);
$contract = $crm->getContract(Issue::getContractID($issue_id));
if (!empty($_REQUEST['submit'])) {
    // update counts
    $res = $contract->updateRedeemedIncidents($issue_id, @$_REQUEST['redeem']);
    $tpl->assign('res', $res);
    Misc::mapMessages($res, array(1 => array('Thank you, the issue was successfully marked.', Misc::MSG_INFO), -1 => array('There was an error marking this issue as redeemed', Misc::MSG_ERROR), -2 => array('This issue already has been marked as redeemed', Misc::MSG_ERROR)));
}
$details = $contract->getDetails();
$tpl->assign(array('issue_id' => $issue_id, 'redeemed' => $contract->getRedeemedIncidentDetails($issue_id), 'incident_details' => $details['incident_details']));
$tpl->displayTemplate();
Пример #5
0
    }
    @$tpl->assign('total_emails', count($_POST['item']));
} else {
    @$tpl->assign('emails', $_GET['item']);
    @$tpl->assign('total_emails', count($_GET['item']));
    $prj_id = Issue::getProjectID($_GET['issue_id']);
    if (CRM::hasCustomerIntegration($prj_id)) {
        // check if the selected emails all have sender email addresses that are associated with the issue' customer
        $crm = CRM::getInstance($prj_id);
        $senders = Support::getSender($_GET['item']);
        $sender_emails = array();
        foreach ($senders as $sender) {
            $email = Mail_Helper::getEmailAddress($sender);
            $sender_emails[$email] = $sender;
        }
        $contract_id = Issue::getContractID($_GET['issue_id']);
        if (!empty($contract_id)) {
            try {
                $contract = $crm->getContract($contract_id);
                // TODOCRM: Active contacts only
                $contact_emails = array_keys($contract->getContactEmailAssocList());
            } catch (CRMException $e) {
                $contact_emails = array();
            }
            $unknown_contacts = array();
            foreach ($sender_emails as $email => $address) {
                if (!@in_array($email, $contact_emails)) {
                    $usr_id = User::getUserIDByEmail($email);
                    if (empty($usr_id)) {
                        $unknown_contacts[] = $address;
                    } else {
Пример #6
0
 /**
  * Checks whether the given email address is allowed to send emails in the
  * issue ID.
  *
  * @access  public
  * @param   integer $issue_id The issue ID
  * @param   string $sender_email The email address
  * @return  boolean
  */
 function isAllowedToEmail($issue_id, $sender_email)
 {
     $prj_id = Issue::getProjectID($issue_id);
     // check the workflow
     $workflow_can_email = Workflow::canEmailIssue($prj_id, $issue_id, $sender_email);
     if ($workflow_can_email != null) {
         return $workflow_can_email;
     }
     $is_allowed = true;
     $sender_usr_id = User::getUserIDByEmail($sender_email);
     if (empty($sender_usr_id)) {
         if (Customer::hasCustomerIntegration($prj_id)) {
             // check for a customer contact with several email addresses
             $customer_id = Issue::getCustomerID($issue_id);
             $contact_emails = array_keys(Customer::getContactEmailAssocList($prj_id, $customer_id, Issue::getContractID($issue_id)));
             $contact_emails = array_map('strtolower', $contact_emails);
             if (!in_array(strtolower($sender_email), $contact_emails) && !Authorized_Replier::isAuthorizedReplier($issue_id, $sender_email)) {
                 $is_allowed = false;
             }
         } else {
             if (!Authorized_Replier::isAuthorizedReplier($issue_id, $sender_email)) {
                 $is_allowed = false;
             }
         }
     } else {
         // check if this user is not a customer and
         // also not in the assignment list for the current issue and
         // also not in the authorized repliers list
         // also not the reporter
         $details = Issue::getDetails($issue_id);
         if (!Issue::canAccess($issue_id, $sender_usr_id)) {
             $is_allowed = false;
         }
         if ($sender_usr_id != $details['iss_usr_id'] && !Authorized_Replier::isUserAuthorizedReplier($issue_id, $sender_usr_id) && !Issue::isAssignedToUser($issue_id, $sender_usr_id) && User::getRoleByUser($sender_usr_id, Issue::getProjectID($issue_id)) != User::getRoleID('Customer')) {
             $is_allowed = false;
         } elseif (User::getRoleByUser($sender_usr_id, Issue::getProjectID($issue_id)) == User::getRoleID('Customer') && User::getCustomerID($sender_usr_id) != Issue::getCustomerID($issue_id)) {
             $is_allowed = false;
         }
     }
     return $is_allowed;
 }
Пример #7
0
 /**
  * Generates the specialized headers for an email.
  *
  * @param   integer $issue_id The issue ID
  * @param   string $type The type of message this is
  * @param   string $headers The existing headers of this message.
  * @param   integer $sender_usr_id The id of the user sending this email.
  * @return  array An array of specialized headers
  */
 public static function getSpecializedHeaders($issue_id, $type, $headers, $sender_usr_id)
 {
     $new_headers = array();
     if (!empty($issue_id)) {
         $prj_id = Issue::getProjectID($issue_id);
         if (count(Group::getAssocList($prj_id)) > 0) {
             // group issue is currently assigned too
             $new_headers['X-Eventum-Group-Issue'] = Group::getName(Issue::getGroupID($issue_id));
             // group of whoever is sending this message.
             if (empty($sender_usr_id)) {
                 $new_headers['X-Eventum-Group-Replier'] = $new_headers['X-Eventum-Group-Issue'];
             } else {
                 $new_headers['X-Eventum-Group-Replier'] = Group::getName(User::getGroupID($sender_usr_id));
             }
             // group of current assignee
             $assignees = Issue::getAssignedUserIDs($issue_id);
             if (empty($assignees[0])) {
                 $new_headers['X-Eventum-Group-Assignee'] = '';
             } else {
                 $new_headers['X-Eventum-Group-Assignee'] = @Group::getName(User::getGroupID($assignees[0]));
             }
         }
         if (CRM::hasCustomerIntegration($prj_id)) {
             $crm = CRM::getInstance($prj_id);
             try {
                 $customer = $crm->getCustomer(Issue::getCustomerID($issue_id));
                 $new_headers['X-Eventum-Customer'] = $customer->getName();
             } catch (CustomerNotFoundException $e) {
             }
             try {
                 $contract = $crm->getContract(Issue::getContractID($issue_id));
                 $support_level = $contract->getSupportLevel();
                 if (is_object($support_level)) {
                     $new_headers['X-Eventum-Level'] = $support_level->getName();
                 }
             } catch (ContractNotFoundException $e) {
             }
         }
         // add assignee header
         $new_headers['X-Eventum-Assignee'] = implode(',', User::getEmail(Issue::getAssignedUserIDs($issue_id)));
         $new_headers['X-Eventum-Category'] = Category::getTitle(Issue::getCategory($issue_id));
         $new_headers['X-Eventum-Project'] = Project::getName($prj_id);
         $new_headers['X-Eventum-Priority'] = Priority::getTitle(Issue::getPriority($issue_id));
         // handle custom fields
         $cf_values = Custom_Field::getValuesByIssue($prj_id, $issue_id);
         $cf_titles = Custom_Field::getFieldsToBeListed($prj_id);
         foreach ($cf_values as $fld_id => $values) {
             // skip empty titles
             // TODO: why they are empty?
             if (!isset($cf_titles[$fld_id])) {
                 continue;
             }
             // skip empty values
             if (empty($values)) {
                 continue;
             }
             $cf_value = implode(', ', (array) $values);
             // value could be empty after multivalued field join
             if (empty($cf_value)) {
                 continue;
             }
             // convert spaces for header fields
             $cf_title = str_replace(' ', '_', $cf_titles[$fld_id]);
             $new_headers['X-Eventum-CustomField-' . $cf_title] = $cf_value;
         }
     }
     $new_headers['X-Eventum-Type'] = $type;
     return $new_headers;
 }
Пример #8
0
 /**
  * Routes an email to the correct issue.
  *
  * @param   string $full_message The full email message, including headers
  * @return  mixed   true or array(ERROR_CODE, ERROR_STRING) in case of failure
  */
 public static function route_emails($full_message)
 {
     // need some validation here
     if (empty($full_message)) {
         return array(self::EX_NOINPUT, ev_gettext('Error: The email message was empty') . ".\n");
     }
     // save the full message for logging purposes
     Support::saveRoutedEmail($full_message);
     // check if the email routing interface is even supposed to be enabled
     $setup = Setup::get();
     if ($setup['email_routing']['status'] != 'enabled') {
         return array(self::EX_CONFIG, ev_gettext('Error: The email routing interface is disabled.') . "\n");
     }
     if (empty($setup['email_routing']['address_prefix'])) {
         return array(self::EX_CONFIG, ev_gettext('Error: Please configure the email address prefix.') . "\n");
     }
     if (empty($setup['email_routing']['address_host'])) {
         return array(self::EX_CONFIG, ev_gettext('Error: Please configure the email address domain.') . "\n");
     }
     // associate routed emails to the internal system account
     $sys_account = User::getNameEmail(APP_SYSTEM_USER_ID);
     if (empty($sys_account['usr_email'])) {
         return array(self::EX_CONFIG, ev_gettext('Error: The associated user for the email routing interface needs to be set.') . "\n");
     }
     unset($sys_account);
     // join the Content-Type line (for easier parsing?)
     if (preg_match('/^boundary=/m', $full_message)) {
         $pattern = "#(Content-Type: multipart/.+); ?\r?\n(boundary=.*)\$#im";
         $replacement = '$1; $2';
         $full_message = preg_replace($pattern, $replacement, $full_message);
     }
     // remove the reply-to: header
     if (preg_match('/^reply-to:.*/im', $full_message)) {
         $full_message = preg_replace("/^(reply-to:).*\n/im", '', $full_message, 1);
     }
     AuthCookie::setAuthCookie(APP_SYSTEM_USER_ID);
     $structure = Mime_Helper::decode($full_message, true, true);
     // find which issue ID this email refers to
     if (isset($structure->headers['to'])) {
         $issue_id = self::getMatchingIssueIDs($structure->headers['to'], 'email');
     }
     // we need to try the Cc header as well
     if (empty($issue_id) and isset($structure->headers['cc'])) {
         $issue_id = self::getMatchingIssueIDs($structure->headers['cc'], 'email');
     }
     if (empty($issue_id)) {
         return array(self::EX_DATAERR, ev_gettext('Error: The routed email had no associated Eventum issue ID or had an invalid recipient address.') . "\n");
     }
     $issue_prj_id = Issue::getProjectID($issue_id);
     if (empty($issue_prj_id)) {
         return array(self::EX_DATAERR, ev_gettext('Error: The routed email had no associated Eventum issue ID or had an invalid recipient address.') . "\n");
     }
     $email_account_id = Email_Account::getEmailAccount($issue_prj_id);
     if (empty($email_account_id)) {
         return array(self::EX_CONFIG, ev_gettext('Error: Please provide the email account ID.') . "\n");
     }
     $body = $structure->body;
     // hack for clients that set more then one from header
     if (is_array($structure->headers['from'])) {
         $structure->headers['from'] = $structure->headers['from'][0];
     }
     // associate the email to the issue
     $parts = array();
     Mime_Helper::parse_output($structure, $parts);
     // get the sender's email address
     $sender_email = strtolower(Mail_Helper::getEmailAddress($structure->headers['from']));
     // strip out the warning message sent to staff users
     if ($setup['email_routing']['status'] == 'enabled' && $setup['email_routing']['warning']['status'] == 'enabled') {
         $full_message = Mail_Helper::stripWarningMessage($full_message);
         $body = Mail_Helper::stripWarningMessage($body);
     }
     $prj_id = Issue::getProjectID($issue_id);
     AuthCookie::setAuthCookie(APP_SYSTEM_USER_ID);
     AuthCookie::setProjectCookie($prj_id);
     if (Mime_Helper::hasAttachments($structure)) {
         $has_attachments = 1;
     } else {
         $has_attachments = 0;
     }
     // remove certain CC addresses
     if (!empty($structure->headers['cc']) && $setup['smtp']['save_outgoing_email'] == 'yes') {
         $ccs = explode(',', @$structure->headers['cc']);
         foreach ($ccs as $i => $address) {
             if (Mail_Helper::getEmailAddress($address) == $setup['smtp']['save_address']) {
                 unset($ccs[$i]);
             }
         }
         $structure->headers['cc'] = implode(', ', $ccs);
     }
     // Remove excess Re's
     $structure->headers['subject'] = Mail_Helper::removeExcessRe(@$structure->headers['subject'], true);
     $t = array('issue_id' => $issue_id, 'ema_id' => $email_account_id, 'message_id' => @$structure->headers['message-id'], 'date' => Date_Helper::getCurrentDateGMT(), 'from' => @$structure->headers['from'], 'to' => @$structure->headers['to'], 'cc' => @$structure->headers['cc'], 'subject' => @$structure->headers['subject'], 'body' => @$body, 'full_email' => @$full_message, 'has_attachment' => $has_attachments, 'headers' => @$structure->headers);
     // automatically associate this incoming email with a customer
     if (CRM::hasCustomerIntegration($prj_id)) {
         $crm = CRM::getInstance($prj_id);
         if (!empty($structure->headers['from'])) {
             try {
                 $contact = $crm->getContactByEmail($sender_email);
                 $issue_contract = $crm->getContract(Issue::getContractID($issue_id));
                 if ($contact->canAccessContract($issue_contract)) {
                     $t['customer_id'] = $issue_contract->getCustomerID();
                 }
             } catch (CRMException $e) {
             }
         }
     }
     if (empty($t['customer_id'])) {
         $t['customer_id'] = null;
     }
     if (Support::blockEmailIfNeeded($t)) {
         return true;
     }
     // re-write Threading headers if needed
     list($t['full_email'], $t['headers']) = Mail_Helper::rewriteThreadingHeaders($t['issue_id'], $t['full_email'], $t['headers'], 'email');
     $res = Support::insertEmail($t, $structure, $sup_id);
     if ($res != -1) {
         Support::extractAttachments($issue_id, $structure);
         // notifications about new emails are always external
         $internal_only = false;
         $assignee_only = false;
         // special case when emails are bounced back, so we don't want a notification to customers about those
         if (Notification::isBounceMessage($sender_email)) {
             // broadcast this email only to the assignees for this issue
             $internal_only = true;
             $assignee_only = true;
         }
         Notification::notifyNewEmail(Auth::getUserID(), $issue_id, $t, $internal_only, $assignee_only, '', $sup_id);
         // try to get usr_id of sender, if not, use system account
         $usr_id = User::getUserIDByEmail(Mail_Helper::getEmailAddress($structure->headers['from']));
         if (!$usr_id) {
             $usr_id = APP_SYSTEM_USER_ID;
         }
         // mark this issue as updated
         if (!empty($t['customer_id']) && $t['customer_id'] != null) {
             Issue::markAsUpdated($issue_id, 'customer action');
         } else {
             if (!empty($usr_id) && $usr_id != APP_SYSTEM_USER_ID && User::getRoleByUser($usr_id, $prj_id) > User::ROLE_CUSTOMER) {
                 Issue::markAsUpdated($issue_id, 'staff response');
             } else {
                 Issue::markAsUpdated($issue_id, 'user response');
             }
         }
         // log routed email
         History::add($issue_id, $usr_id, 'email_routed', 'Email routed from {from}', array('from' => $structure->headers['from']));
     }
     return true;
 }