#!/usr/bin/php4 -q dbh->query($sql); if (PEAR::isError($res)) { Error_Handler::logError(array($res->getMessage(), $res->getDebugInfo()), __FILE__, __LINE__); exit(1); } $i=0; while (list($seb_sup_id, $seb_body, $full_message) = $res->fetchRow()) { $return = route_emails($full_message, $email_account_id); if (is_array($return)) { echo "$seb_sup_id "; echo $return[1]; # echo "$full_message"; exit($return[0]); } # if (++$i> 2) { # die("enough"); # } } /** * Routes an email to the correct issue. * * @param string $full_message The full email message, including headers * @param integer $email_account_id The ID of the email account this email should be routed too. If empty this method will try to figure it out */ function route_emails($full_message, $email_account_id = 0) { GLOBAL $HTTP_POST_VARS; // save the full message for logging purposes # Support::saveRoutedEmail($full_message); if (preg_match("/^(boundary=).*/m", $full_message)) { $pattern = "/(Content-Type: multipart\/)(.+); ?\r?\n(boundary=)(.*)$/im"; $replacement = '$1$2; $3$4'; $full_message = preg_replace($pattern, $replacement, $full_message); } // associate routed emails to the internal system account $sys_account = User::getNameEmail(APP_SYSTEM_USER_ID); $associated_user = $sys_account['usr_email']; // need some validation here if (empty($full_message)) { return array(66, "Error: The email message was empty.\n"); } if (empty($associated_user)) { return array(78, "Error: The associated user for the email routing interface needs to be set.\n"); } # echo "route:email_account_id=$email_account_id;associated_user=$associated_user\n"; // // DON'T EDIT ANYTHING BELOW THIS LINE // // remove the reply-to: header if (preg_match("/^(reply-to:).*/im", $full_message)) { $full_message = preg_replace("/^(reply-to:).*\n/im", '', $full_message, 1); } // check for magic cookie if (Mail_API::hasMagicCookie($full_message)) { // strip the magic cookie $full_message = Mail_API::stripMagicCookie($full_message); $has_magic_cookie = true; } else { $has_magic_cookie = false; } # echo "got magic cookie1: ".($has_magic_cookie ? "true" : "false")."\n"; Auth::createFakeCookie(APP_SYSTEM_USER_ID); // check if the email routing interface is even supposed to be enabled $setup = Setup::load(); if ($setup['email_routing']['status'] != 'enabled') { return array(78, "Error: The email routing interface is disabled.\n"); } $prefix = $setup['email_routing']['address_prefix']; // escape plus signs so 'issue+1@example.com' becomes a valid routing address $prefix = str_replace('+', '\+', $prefix); $mail_domain = $setup['email_routing']['address_host']; $mail_domain_alias = @$setup['email_routing']['host_alias']; if (!empty($mail_domain_alias)) { $mail_domain = "[" . $mail_domain . "|" . $mail_domain_alias . "]"; } if (empty($prefix)) { return array(78, "Error: Please configure the email address prefix.\n"); } if (empty($mail_domain)) { return array(78, "Error: Please configure the email address domain.\n"); } $structure = Mime_Helper::decode($full_message, true, true); // remove extra 'Re: ' from subject @$structure->headers['subject'] = Mail_API::removeExcessRe($structure->headers['subject']); // find which issue ID this email refers to @preg_match("/$prefix(\d*)@$mail_domain/i", $structure->headers['to'], $matches); # print_r($matches); @$issue_id = $matches[1]; // validation is always a good idea if (empty($issue_id)) { // we need to try the Cc header as well @preg_match("/$prefix(\d*)@$mail_domain/i", $structure->headers['cc'], $matches); # print_r($matches); if (!empty($matches[1])) { $issue_id = $matches[1]; } else { $a = array('from', 'to', 'cc', 'subject', 'date'); print_r($structure->headers); $r = ''; foreach ($a as $k) { if (isset($structure->headers[$k])) { $r .= sprintf("%s=%s; ", $k, $structure->headers[$k]); } } $r.="\n"; # exit; # return array(65, "Error: The routed email had no associated Eventum issue ID or had an invalid recipient address.\n"); return array(65, "Error: can't route: $r"); } } if (empty($email_account_id)) { $issue_prj_id = Issue::getProjectID($issue_id); if (empty($issue_prj_id)) { return array(65, "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(78, "Error: Please provide the email account ID.\n"); } $body = Mime_Helper::getMessageBody($structure); // associate the email to the issue $parts = array(); Mime_Helper::parse_output($structure, $parts); // get the sender's email address $sender_email = strtolower(Mail_API::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_API::stripWarningMessage($full_message); $body = Mail_API::stripWarningMessage($body); } $prj_id = Issue::getProjectID($issue_id); Auth::createFakeCookie(APP_SYSTEM_USER_ID, $prj_id); $staff_emails = Project::getUserEmailAssocList($prj_id, 'active', User::getRoleID('Customer')); $staff_emails = array_map('strtolower', $staff_emails); // only allow staff users to use the magic cookie if (!in_array($sender_email, array_values($staff_emails))) { $has_magic_cookie = false; } if (!$has_magic_cookie) { return array(66, "Error: no magic cookie, should create not about this, but won't.\n"); /* // check if sender email address is associated with a real user if ((Mail_API::isVacationAutoResponder($structure->headers)) || (!Notification::isBounceMessage($sender_email)) && (!Support::isAllowedToEmail($issue_id, $sender_email))) { // add the message body as a note $HTTP_POST_VARS = array( 'blocked_msg' => $full_message, 'title' => @$structure->headers['subject'], 'note' => Mail_API::getCannedBlockedMsgExplanation() . $body ); // avoid having this type of message re-open the issue if (Mail_API::isVacationAutoResponder($structure->headers)) { $closing = true; } else { $closing = false; } Note::insert(Auth::getUserID(), $issue_id, $structure->headers['from'], false, $closing); $HTTP_POST_VARS['issue_id'] = $issue_id; $HTTP_POST_VARS['from'] = $sender_email; // avoid having this type of message re-open the issue if (Mail_API::isVacationAutoResponder($structure->headers)) { $email_type = 'vacation-autoresponder'; } else { $email_type = 'routed'; } Workflow::handleBlockedEmail($prj_id, $issue_id, $HTTP_POST_VARS, $email_type); // try to get usr_id of sender, if not, use system account $usr_id = User::getUserIDByEmail(Mail_API::getEmailAddress($structure->headers['from'])); if (!$usr_id) { $usr_id = APP_SYSTEM_USER_ID; } // log blocked email History::add($issue_id, $usr_id, History::getTypeID('email_blocked'), "Email from '" . $structure->headers['from'] . "' blocked."); return true; } */ } if (@count($parts["attachments"]) > 0) { $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']); for ($i = 0; $i < count($ccs); $i++) { if (Mail_API::getEmailAddress($ccs[$i]) == $setup['smtp']['save_address']) { unset($ccs[$i]); } } @$structure->headers['cc'] = join(', ', $ccs); } $t = array( 'issue_id' => $issue_id, 'ema_id' => $email_account_id, 'message_id' => @$structure->headers['message-id'], 'date' => Date_API::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 ); // automatically associate this incoming email with a customer if (Customer::hasCustomerIntegration($prj_id)) { if (!empty($structure->headers['from'])) { list($customer_id,) = Customer::getCustomerIDByEmails($prj_id, array($sender_email)); if (!empty($customer_id)) { $t['customer_id'] = $customer_id; } } } if (empty($t['customer_id'])) { $t['customer_id'] = "NULL"; } $res = insertEmail($t, $structure); if ($res == -1) { die("insertEmail failure"); } /* if ($res != -1) { Support::extractAttachments($issue_id, $full_message); // 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, $structure, $full_message, $internal_only, $assignee_only); // try to get usr_id of sender, if not, use system account $usr_id = User::getUserIDByEmail(Mail_API::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)) && (User::getRoleByUser($usr_id, $prj_id) > User::getRoleID('Customer'))) { Issue::markAsUpdated($issue_id, 'staff response'); } else { Issue::markAsUpdated($issue_id, 'user response'); } } // log routed email History::add($issue_id, $usr_id, History::getTypeID('email_routed'), "Email routed from " . $structure->headers['from']); }*/ return true; } /** * Method used to add a new support email to the system. * * @access public * @param array $row The support email details * @param object $structure The parsed structure of the email message * @return integer 1 if the insert worked, -1 otherwise */ function insertEmail($row, $structure) { echo "insertEmail: $row, $structure\n";return; // get usr_id from FROM header $usr_id = User::getUserIDByEmail(Mail_API::getEmailAddress($structure->headers['from'])); if (!empty($usr_id) && !empty($row["customer_id"])) { $row["customer_id"] = User::getCustomerID($usr_id); } if (empty($row['customer_id'])) { $row['customer_id'] = "NULL"; } $stmt = "INSERT INTO " . APP_DEFAULT_DB . "." . APP_TABLE_PREFIX . "support_email ( sup_ema_id, sup_iss_id,"; if (!empty($usr_id)) { $stmt .= "\nsup_usr_id,\n"; } $stmt .= " sup_customer_id, sup_message_id, sup_date, sup_from, sup_to, sup_cc, sup_subject, sup_has_attachment ) VALUES ( " . Misc::escapeInteger($row["ema_id"]) . ", " . Misc::escapeInteger($row["issue_id"]) . ","; if (!empty($usr_id)) { $stmt .= "\n$usr_id,\n"; } $stmt .= " " . Misc::escapeInteger($row["customer_id"]) . ", '" . Misc::escapeString($row["message_id"]) . "', '" . Misc::escapeString($row["date"]) . "', '" . Misc::escapeString($row["from"]) . "', '" . Misc::escapeString($row["to"]) . "', '" . Misc::escapeString($row["cc"]) . "', '" . Misc::escapeString($row["subject"]) . "', '" . Misc::escapeString($row["has_attachment"]) . "' )"; $res = $GLOBALS["db_api"]->dbh->query($stmt); if (PEAR::isError($res)) { Error_Handler::logError(array($res->getMessage(), $res->getDebugInfo()), __FILE__, __LINE__); return -1; }/* else { $new_sup_id = $GLOBALS["db_api"]->get_last_insert_id(); // now add the body and full email to the separate table $stmt = "INSERT INTO " . APP_DEFAULT_DB . "." . APP_TABLE_PREFIX . "support_email_body ( seb_sup_id, seb_body, seb_full_email ) VALUES ( $new_sup_id, '" . Misc::escapeString($row["body"]) . "', '" . Misc::escapeString($row["full_email"]) . "' )"; $res = $GLOBALS["db_api"]->dbh->query($stmt); if (PEAR::isError($res)) { Error_Handler::logError(array($res->getMessage(), $res->getDebugInfo()), __FILE__, __LINE__); return -1; } else { Workflow::handleNewEmail(Support::getProjectByEmailAccount($row["ema_id"]), @$row["issue_id"], $structure, $row); return 1; } }*/ } ?>