/** * Method used to extract and associate attachments in an email * to the given issue. * * @access public * @param integer $issue_id The issue ID * @param string $full_email The full contents of the email * @param boolean $internal_only Whether these files are supposed to be internal only or not * @param integer $associated_note_id The note ID that these attachments should be associated with * @return void */ function extractAttachments($issue_id, $full_email, $internal_only = false, $associated_note_id = false) { // figure out who should be the 'owner' of this attachment $structure = Mime_Helper::decode($full_email, false, false); $sender_email = strtolower(Mail_API::getEmailAddress($structure->headers['from'])); $usr_id = User::getUserIDByEmail($sender_email); $unknown_user = false; if (empty($usr_id)) { $prj_id = Issue::getProjectID($issue_id); if (Customer::hasCustomerIntegration($prj_id)) { // try checking if a customer technical contact has this email associated with it list(, $contact_id) = Customer::getCustomerIDByEmails($prj_id, array($sender_email)); if (!empty($contact_id)) { $usr_id = User::getUserIDByContactID($contact_id); } } if (empty($usr_id)) { // if we couldn't find a real customer by that email, set the usr_id to be the system user id, // and store the actual email address in the unknown_user field. $usr_id = APP_SYSTEM_USER_ID; $unknown_user = $structure->headers['from']; } } // now for the real thing $attachments = Mime_Helper::getAttachments($full_email); if (count($attachments) > 0) { if (empty($associated_note_id)) { $history_log = 'Attachment originated from an email'; } else { $history_log = 'Attachment originated from a note'; } $attachment_id = Attachment::add($issue_id, $usr_id, $history_log, $internal_only, $unknown_user, $associated_note_id); for ($i = 0; $i < count($attachments); $i++) { Attachment::addFile($attachment_id, $issue_id, $attachments[$i]['filename'], $attachments[$i]['filetype'], $attachments[$i]['blob']); } // mark the note as having attachments (poor man's caching system) if ($associated_note_id != false) { Note::setAttachmentFlag($associated_note_id); } } }
/** * Converts a note to a draft or an email * * @access public * @param $note_id The id of the note * @param $target What the not should be converted too * @param $authorize_sender If the sender should be added to authorized senders list. */ function convertNote($note_id, $target, $authorize_sender = false) { $note_id = Misc::escapeInteger($note_id); $issue_id = Note::getIssueID($note_id); $email_account_id = Email_Account::getEmailAccount(); $blocked_message = Note::getBlockedMessage($note_id); $unknown_user = Note::getUnknownUser($note_id); $structure = Mime_Helper::decode($blocked_message, true, true); $body = Mime_Helper::getMessageBody($structure); $sender_email = strtolower(Mail_API::getEmailAddress($structure->headers['from'])); if ($target == 'email') { if (Mime_Helper::hasAttachments($blocked_message)) { $has_attachments = 1; } else { $has_attachments = 0; } list($blocked_message, $headers) = Mail_API::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_API::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 (Customer::hasCustomerIntegration($details['ema_prj_id'])) { // check for any customer contact association list($customer_id, ) = Customer::getCustomerIDByEmails($details['ema_prj_id'], array($sender_email)); if (!empty($customer_id)) { $t['customer_id'] = $customer_id; } } } 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, $blocked_message); // 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(Auth::getUserID(), $issue_id, $t, $internal_only, false, '', $sup_id); Issue::markAsUpdated($issue_id, $update_type); Note::remove($note_id, false); History::add($issue_id, Auth::getUserID(), History::getTypeID('note_converted_email'), "Note converted to e-mail (from: " . @$structure->headers['from'] . ") by " . User::getFullName(Auth::getUserID())); // now add sender as an authorized replier if ($authorize_sender) { Authorized_Replier::manualInsert($issue_id, @$structure->headers['from']); } } return $res; } else { // 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) { Note::remove($note_id, false); History::add($issue_id, Auth::getUserID(), History::getTypeID('note_converted_draft'), "Note converted to draft (from: " . @$structure->headers['from'] . ") by " . User::getFullName(Auth::getUserID())); } return $res; } }
/** * Creates an issue with the given email information. * * @access public * @param integer $prj_id The project ID * @param integer $usr_id The user responsible for this action * @param string $sender The original sender of this email * @param string $summary The issue summary * @param string $description The issue description * @param integer $category The category ID * @param integer $priority The priority ID * @param array $assignment The list of users to assign this issue to * @param string $date The date the email was originally sent. * @param string $msg_id The message ID of the email we are creating this issue from. * @return void */ function createFromEmail($prj_id, $usr_id, $sender, $summary, $description, $category, $priority, $assignment, $date, $msg_id) { $exclude_list = array(); $sender_email = Mail_API::getEmailAddress($sender); $sender_usr_id = User::getUserIDByEmail($sender_email); if (!empty($sender_usr_id)) { $reporter = $sender_usr_id; $exclude_list[] = $sender_usr_id; } else { $reporter = APP_SYSTEM_USER_ID; } if (Customer::hasCustomerIntegration($prj_id)) { list($customer_id, $customer_contact_id) = Customer::getCustomerIDByEmails($prj_id, array($sender_email)); if (!empty($customer_id)) { $contact = Customer::getContactDetails($prj_id, $customer_contact_id); // overwrite the reporter with the customer contact $reporter = User::getUserIDByContactID($customer_contact_id); $contact_timezone = Date_API::getPreferredTimezone($reporter); } } else { $customer_id = FALSE; } $initial_status = Project::getInitialStatus($prj_id); // add new issue $stmt = "INSERT INTO\n " . APP_DEFAULT_DB . "." . APP_TABLE_PREFIX . "issue\n (\n iss_prj_id,\n"; if (!empty($category)) { $stmt .= "iss_prc_id,\n"; } $stmt .= "iss_pri_id,\n iss_usr_id,"; if (!empty($initial_status)) { $stmt .= "iss_sta_id,"; } if (!empty($customer_id)) { $stmt .= "\n iss_customer_id,\n iss_customer_contact_id,\n iss_contact_person_lname,\n iss_contact_person_fname,\n iss_contact_email,\n iss_contact_phone,\n iss_contact_timezone,"; } $stmt .= "\n iss_created_date,\n iss_last_public_action_date,\n iss_last_public_action_type,\n iss_summary,\n iss_description,\n iss_root_message_id\n ) VALUES (\n " . $prj_id . ",\n"; if (!empty($category)) { $stmt .= Misc::escapeInteger($category) . ",\n"; } $stmt .= Misc::escapeInteger($priority) . ",\n " . Misc::escapeInteger($reporter) . ","; if (!empty($initial_status)) { $stmt .= Misc::escapeInteger($initial_status) . ","; } if (!empty($customer_id)) { $stmt .= "\n " . Misc::escapeInteger($customer_id) . ",\n " . Misc::escapeInteger($customer_contact_id) . ",\n '" . Misc::escapeString($contact['last_name']) . "',\n '" . Misc::escapeString($contact['first_name']) . "',\n '" . Misc::escapeString($sender_email) . "',\n '" . Misc::escapeString($contact['phone']) . "',\n '" . Misc::escapeString($contact_timezone) . "',"; } $stmt .= "\n '" . Date_API::getCurrentDateGMT() . "',\n '" . Date_API::getCurrentDateGMT() . "',\n 'created',\n '" . Misc::escapeString($summary) . "',\n '" . Misc::escapeString($description) . "',\n '" . Misc::escapeString($msg_id) . "'\n )"; $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_issue_id = $GLOBALS["db_api"]->get_last_insert_id(); $has_TAM = false; $has_RR = false; // log the creation of the issue History::add($new_issue_id, $usr_id, History::getTypeID('issue_opened'), 'Issue opened by ' . $sender); $emails = array(); $manager_usr_ids = array(); if (Customer::hasCustomerIntegration($prj_id) && !empty($customer_id)) { // if there are any technical account managers associated with this customer, add these users to the notification list $managers = Customer::getAccountManagers($prj_id, $customer_id); $manager_usr_ids = array_keys($managers); $manager_emails = array_values($managers); $emails = array_merge($emails, $manager_emails); } // add the reporter to the notification list $emails[] = $sender; $emails = array_unique($emails); // COMPAT: version >= 4.0.1 $actions = Notification::getDefaultActions(); foreach ($emails as $address) { Notification::subscribeEmail($reporter, $new_issue_id, $address, $actions); } // only assign the issue to an user if the associated customer has any technical account managers $users = array(); if (Customer::hasCustomerIntegration($prj_id) && count($manager_usr_ids) > 0) { foreach ($manager_usr_ids as $manager_usr_id) { $users[] = $manager_usr_id; Issue::addUserAssociation(APP_SYSTEM_USER_ID, $new_issue_id, $manager_usr_id, false); History::add($new_issue_id, $usr_id, History::getTypeID('issue_auto_assigned'), 'Issue auto-assigned to ' . User::getFullName($manager_usr_id) . ' (TAM)'); } $has_TAM = true; } // now add the user/issue association if (@count($assignment) > 0) { for ($i = 0; $i < count($assignment); $i++) { Notification::subscribeUser($reporter, $new_issue_id, $assignment[$i], $actions); Issue::addUserAssociation(APP_SYSTEM_USER_ID, $new_issue_id, $assignment[$i]); if ($assignment[$i] != $usr_id) { $users[] = $assignment[$i]; } } } else { // only use the round-robin feature if this new issue was not // already assigned to a customer account manager if (@count($manager_usr_ids) < 1) { $assignee = Round_Robin::getNextAssignee($prj_id); // assign the issue to the round robin person if (!empty($assignee)) { Issue::addUserAssociation(APP_SYSTEM_USER_ID, $new_issue_id, $assignee, false); History::add($new_issue_id, APP_SYSTEM_USER_ID, History::getTypeID('rr_issue_assigned'), 'Issue auto-assigned to ' . User::getFullName($assignee) . ' (RR)'); $users[] = $assignee; $has_RR = true; } } } if (count($users) > 0) { $has_assignee = true; } // send special 'an issue was auto-created for you' notification back to the sender Notification::notifyAutoCreatedIssue($prj_id, $new_issue_id, $sender, $date, $summary); // also notify any users that want to receive emails anytime a new issue is created Notification::notifyNewIssue($prj_id, $new_issue_id, $exclude_list); Workflow::handleNewIssue($prj_id, $new_issue_id, $has_TAM, $has_RR); return $new_issue_id; } }
$tpl->assign("emails", $res); $tpl->assign("attached_emails", @implode(",", $HTTP_GET_VARS["item"])); if (Customer::hasCustomerIntegration($prj_id)) { // also need to guess the contact_id from any attached emails $info = Customer::getCustomerInfoFromEmails($prj_id, $HTTP_GET_VARS["item"]); $tpl->assign(array("customer_id" => $info['customer_id'], 'customer_name' => $info['customer_name'], "contact_id" => $info['contact_id'], 'contact_name' => $info['contact_name'], 'contacts' => $info['contacts'])); } // if we are dealing with just one message, use the subject line as the // summary for the issue, and the body as the description if (count($HTTP_GET_VARS["item"]) == 1) { $email_details = Support::getEmailDetails(Email_Account::getAccountByEmail($HTTP_GET_VARS["item"][0]), $HTTP_GET_VARS["item"][0]); $tpl->assign(array('issue_summary' => $email_details['sup_subject'], 'issue_description' => $email_details['message'])); // also auto pre-fill the customer contact text fields if (Customer::hasCustomerIntegration($prj_id)) { $sender_email = Mail_API::getEmailAddress($email_details['sup_from']); list(, $contact_id) = Customer::getCustomerIDByEmails($prj_id, array($sender_email)); if (!empty($contact_id)) { $tpl->assign("contact_details", Customer::getContactDetails($prj_id, $contact_id)); } } } } } $tpl->assign(array("cats" => Category::getAssocList($prj_id), "priorities" => Priority::getAssocList($prj_id), "users" => Project::getUserAssocList($prj_id, 'active', User::getRoleID('Customer')), "releases" => Release::getAssocList($prj_id), "custom_fields" => Custom_Field::getListByProject($prj_id, 'report_form'), "max_attachment_size" => Attachment::getMaxAttachmentSize(), "field_display_settings" => Project::getFieldDisplaySettings($prj_id), "groups" => Group::getAssocList($prj_id))); $setup = Setup::load(); $tpl->assign("allow_unassigned_issues", @$setup["allow_unassigned_issues"]); $prefs = Prefs::get($usr_id); $tpl->assign("user_prefs", $prefs); $tpl->assign("zones", Date_API::getTimezoneList()); if (User::getRole(Auth::getCurrentRole()) == "Customer") { $customer_contact_id = User::getCustomerContactID($usr_id);
/** * 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"); } // // 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; } 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 '*****@*****.**' becomes a valid routing address $prefix = str_replace('+', '\\+', $prefix); $mail_domain = quotemeta($setup['email_routing']['address_host']); $mail_domain_alias = quotemeta(@$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); // find which issue ID this email refers to @preg_match("/{$prefix}(\\d*)@{$mail_domain}/i", $structure->headers['to'], $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); if (!empty($matches[1])) { $issue_id = $matches[1]; } else { return array(65, "Error: The routed email had no associated Eventum issue ID or had an invalid recipient address.\n"); } } 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); // 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_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 (Mime_Helper::hasAttachments($full_message)) { $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)); } // Remove excess Re's @($structure->headers['subject'] = Mail_API::removeExcessRe(@$structure->headers['subject'], true)); $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, 'headers' => @$structure->headers); // 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"; } if (!$has_magic_cookie && Support::blockEmailIfNeeded($t)) { return true; } // re-write Threading headers if needed list($t['full_email'], $t['headers']) = Mail_API::rewriteThreadingHeaders($t['issue_id'], $t['full_email'], $t['headers'], "email"); $res = Support::insertEmail($t, $structure, $sup_id); 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, $t, $internal_only, $assignee_only, '', $sup_id); // 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; }