mirror of
https://github.com/itflow-org/itflow
synced 2026-12-02 09:09:01 +00:00
1117 lines
58 KiB
PHP
1117 lines
58 KiB
PHP
<?php
|
|
/*
|
|
* CRON - Email Parser (DirectoryTree ImapEngine)
|
|
* Process emails and create/update tickets using DirectoryTree\ImapEngine (no PHP IMAP extension required)
|
|
*/
|
|
|
|
// Start the timer
|
|
$script_start_time = microtime(true);
|
|
|
|
// Set working directory to the directory this cron script lives at.
|
|
chdir(dirname(__FILE__));
|
|
|
|
// Ensure we're running from command line
|
|
if (php_sapi_name() !== 'cli') {
|
|
die("This script must be run from the command line.\n");
|
|
}
|
|
|
|
// Prevent overlapping runs of this script
|
|
$cron_lock_script = __FILE__;
|
|
require_once "includes/cron_lock.php";
|
|
|
|
// Autoload (Webklex & any composer deps)
|
|
require_once "../libs/vendor/autoload.php";
|
|
|
|
// Get ITFlow config & helper functions
|
|
require_once "../config.php";
|
|
|
|
// Set Timezone
|
|
require_once "../includes/inc_set_timezone.php";
|
|
require_once "../functions.php";
|
|
|
|
// Get settings for the "default" company
|
|
require_once "../includes/load_global_settings.php";
|
|
|
|
$config_ticket_prefix = escapeSql($config_ticket_prefix);
|
|
$config_ticket_from_name = escapeSql($config_ticket_from_name);
|
|
$config_ticket_email_parse_unknown_senders = intval($row['config_ticket_email_parse_unknown_senders']);
|
|
|
|
// Get company name & phone & timezone
|
|
$sql = mysqli_query($mysqli, "SELECT company_name, company_phone, company_phone_country_code FROM companies, settings WHERE companies.company_id = settings.company_id AND companies.company_id = 1");
|
|
$row = mysqli_fetch_assoc($sql);
|
|
$company_name = escapeSql($row['company_name']);
|
|
$company_phone = escapeSql(formatPhoneNumber($row['company_phone'], $row['company_phone_country_code']));
|
|
|
|
// Check cron is enabled. Switched off isn't an error - Maintenance > Cron shows why it stopped,
|
|
// where an App Logs entry every minute only buried the real errors
|
|
if ($config_enable_cron == 0) {
|
|
cronJobStop("Cron: is not enabled -- Quitting..");
|
|
}
|
|
|
|
// Check setting enabled
|
|
if ($config_ticket_email_parse == 0) {
|
|
cronJobStop("Email Parser: Feature is not enabled - check Settings > Ticketing > Email-to-ticket parsing. See https://docs.itflow.org/ticket_email_parse -- Quitting..");
|
|
}
|
|
|
|
// Development mode doesn't read the ticket mailbox - it would take production's email (functions/dev_mode.php)
|
|
if (devModeOn()) {
|
|
cronJobStop("Development mode - the ticket mailbox isn't read");
|
|
}
|
|
|
|
// Overlapping runs are prevented by cron/includes/cron_lock.php. This script used to keep a
|
|
// lock file of its own alongside that one, which needed a five minute age heuristic to
|
|
// recover from a killed run and could only end itself with exit() - fatal to a dispatched
|
|
// job. flock covers the same ground and the kernel drops it however the process ends.
|
|
|
|
// Allowed attachment extensions
|
|
$allowed_extensions = array('jpg', 'jpeg', 'gif', 'png', 'webp', 'pdf', 'txt', 'md', 'doc', 'docx', 'csv', 'xls', 'xlsx', 'xlsm', 'zip', 'tar', 'gz');
|
|
|
|
// Processing limits
|
|
$max_emails_per_run = 50; // Cap per cron run to bound memory usage (cron catches up on the next run)
|
|
$max_attachment_bytes = 15728640; // 15 MB - larger attachments are skipped & logged
|
|
$max_inline_embed_bytes = 2097152; // 2 MB - larger inline images are saved as regular attachments instead of shown in the ticket's text (kept as its files - functions/ticket_pictures.php)
|
|
$read_mail_minutes = 60; // Mail someone opened before this got to it is taken when it came in this long ago at most
|
|
|
|
/** ------------------------------------------------------------------
|
|
* Ticket / Reply helpers (unchanged)
|
|
* ------------------------------------------------------------------ */
|
|
/*
|
|
* A new ticket from an email. $copied - the people it was also to or copied to, made its watchers
|
|
* (ticketMailCopiedWatchers()); $message_id its Message-ID, kept with the ticket so a reply to it -
|
|
* or to all on it, before the ticket's number was ever sent - finds it (functions/ticket_mail_thread.php);
|
|
* $automatic 'automated' for one sent by a system or a list, which isn't answered (functions/ticket_mail_auto.php).
|
|
* The new ticket's id.
|
|
*/
|
|
function addTicket($contact_id, $contact_name, $contact_email, $client_id, $date, $subject, $message, $attachments, $original_message_file, $copied, $message_id = '', $automatic = '') {
|
|
global $mysqli, $config_app_name, $company_name, $company_phone, $config_ticket_prefix, $config_ticket_client_general_notifications, $config_base_url, $config_ticket_from_name, $config_ticket_from_email, $config_ticket_default_billable, $allowed_extensions;
|
|
$bad_pattern = "/do[\W_]*not[\W_]*reply|no[\W_]*reply/i"; // Email addresses to ignore
|
|
|
|
// Atomically increment and get the new ticket number
|
|
mysqli_query($mysqli, "
|
|
UPDATE settings
|
|
SET
|
|
config_ticket_next_number = LAST_INSERT_ID(config_ticket_next_number),
|
|
config_ticket_next_number = config_ticket_next_number + 1
|
|
WHERE company_id = 1
|
|
");
|
|
|
|
$ticket_number = mysqli_insert_id($mysqli);
|
|
|
|
// Clean up the message
|
|
$message = trim($message);
|
|
// Remove DOCTYPE and meta tags
|
|
$message = preg_replace('/<!DOCTYPE[^>]*>/i', '', $message);
|
|
$message = preg_replace('/<meta[^>]*>/i', '', $message);
|
|
// Remove <html>, <head>, <body> and their closing tags
|
|
$message = preg_replace('/<\/?(html|head|body)[^>]*>/i', '', $message);
|
|
// Collapse excess whitespace
|
|
$message = preg_replace('/\s+/', ' ', $message);
|
|
// Convert newlines to <br>
|
|
$message = nl2br($message);
|
|
// Wrap final formatted message
|
|
$message = "<i>Email from: <b>$contact_name</b> <$contact_email> at $date:-</i> <br><br><div style='line-height:1.5;'>$message</div>";
|
|
|
|
$ticket_prefix_esc = mysqli_real_escape_string($mysqli, $config_ticket_prefix);
|
|
$message_esc = mysqli_real_escape_string($mysqli, $message);
|
|
$contact_email_esc = mysqli_real_escape_string($mysqli, $contact_email);
|
|
$client_id = intval($client_id);
|
|
|
|
$url_key = randomString(32);
|
|
|
|
mysqli_query($mysqli, "INSERT INTO tickets SET ticket_prefix = '$ticket_prefix_esc', ticket_number = $ticket_number, ticket_source = 'Email', ticket_subject = '$subject', ticket_details = '$message_esc', ticket_priority = 'Medium', ticket_status = 1, ticket_billable = $config_ticket_default_billable, ticket_created_by = 0, ticket_contact_id = $contact_id, ticket_url_key = '$url_key', ticket_client_id = $client_id");
|
|
$id = mysqli_insert_id($mysqli);
|
|
applyTicketSla($id);
|
|
|
|
// The email it came from is the first in its conversation - the email saying it is a ticket now answers it
|
|
ticketMailKeepId($id, $message_id);
|
|
|
|
// The email's pictures kept as the ticket's files, not inside its text (functions/ticket_pictures.php)
|
|
ticketPicturesSaveTicket($id);
|
|
|
|
// Logging
|
|
logAudit("Ticket", "Create", "Email parser: Client contact $contact_email_esc created ticket $ticket_prefix_esc$ticket_number ($subject) ($id)", $client_id, $id);
|
|
|
|
mkdirMissing('../uploads/tickets/');
|
|
$att_dir = "../uploads/tickets/" . $id . "/";
|
|
mkdirMissing($att_dir);
|
|
|
|
// Move original .eml into the ticket folder
|
|
rename("../uploads/tmp/{$original_message_file}", "{$att_dir}/{$original_message_file}");
|
|
$original_message_file_esc = mysqli_real_escape_string($mysqli, $original_message_file);
|
|
mysqli_query($mysqli, "INSERT INTO ticket_attachments SET ticket_attachment_name = 'Original-parsed-email.eml', ticket_attachment_reference_name = '$original_message_file_esc', ticket_attachment_ticket_id = $id");
|
|
|
|
// Save non-inline attachments
|
|
foreach ($attachments as $attachment) {
|
|
$att_name = $attachment['name'];
|
|
$att_extension = strtolower(pathinfo($att_name, PATHINFO_EXTENSION));
|
|
|
|
if (in_array($att_extension, $allowed_extensions)) {
|
|
$att_saved_filename = md5(uniqid(rand(), true)) . '.' . $att_extension;
|
|
$att_saved_path = $att_dir . $att_saved_filename;
|
|
file_put_contents($att_saved_path, $attachment['content']);
|
|
|
|
// Escaped once, and cut to the 255 characters the column holds
|
|
$ticket_attachment_name = escapeSql(mb_substr($att_name, 0, 255));
|
|
$ticket_attachment_reference_name = escapeSql($att_saved_filename);
|
|
|
|
$ticket_attachment_name_esc = $ticket_attachment_name;
|
|
$ticket_attachment_reference_name_esc = mysqli_real_escape_string($mysqli, $ticket_attachment_reference_name);
|
|
mysqli_query($mysqli, "INSERT INTO ticket_attachments SET ticket_attachment_name = '$ticket_attachment_name_esc', ticket_attachment_reference_name = '$ticket_attachment_reference_name_esc', ticket_attachment_ticket_id = $id");
|
|
} else {
|
|
$ticket_attachment_name_esc = mysqli_real_escape_string($mysqli, $att_name);
|
|
logAudit("Ticket", "Edit", "Email parser: Blocked attachment $ticket_attachment_name_esc from Client contact $contact_email_esc for ticket $ticket_prefix_esc$ticket_number", $client_id, $id);
|
|
}
|
|
}
|
|
|
|
// Add unknown guests as ticket watcher
|
|
if ($client_id == 0 && !preg_match($bad_pattern, $contact_email_esc)) {
|
|
mysqli_query($mysqli, "INSERT INTO ticket_watchers SET watcher_email = '$contact_email_esc', watcher_ticket_id = $id");
|
|
}
|
|
|
|
// The people it was also to or copied to are its watchers - not your own addresses or agents (ticketMailCopiedWatchers())
|
|
ticketMailCopiedWatchers($id, $copied, stripslashes($contact_email));
|
|
|
|
// The sender is told it is a ticket now - unless they asked for replies only (Your account in the client portal), it was
|
|
// sent by a system or a list, whose answer could be answered back, or they have had a few answers this hour already
|
|
$contact_wants = !$contact_id || ticketContactWantsEmail(getFieldById('contacts', intval($contact_id), 'contact_ticket_emails'), 'created');
|
|
if ($config_ticket_client_general_notifications == 1 && !preg_match($bad_pattern, $contact_email) && $contact_wants && $automatic === ''
|
|
&& ticketMailAnswersLeft(stripslashes($contact_email)) && ($new = ticketRow($id))) {
|
|
ticketMailCreated($id, [], false, 'email', [['email' => stripslashes($contact_email), 'name' => stripslashes($contact_name)]]);
|
|
}
|
|
|
|
// The new-ticket address (Admin > Ticket), when there is one
|
|
ticketMailNewTicketAddress($id, 'email');
|
|
|
|
// The client's primary and technical contacts who asked to hear about new tickets
|
|
ticketMailColleaguesNew($id);
|
|
|
|
triggerCustomAction('ticket_create', $id);
|
|
|
|
return intval($id);
|
|
}
|
|
|
|
/*
|
|
* A mail server's report that an email couldn't be delivered (ticketMailIsBounce()) - never a ticket, never answered.
|
|
* The addresses it failed for are marked on their contacts ("Email bounced", functions/contact_bounce.php), the ticket
|
|
* the email was about gets a note - found by the Message-ID of the email that bounced, as ITFlow keeps each it sends
|
|
* about a ticket, else by the number in its subject - and agents get a notice. A report that an email is only delayed
|
|
* is set aside.
|
|
*/
|
|
function addBounce($message, array $headers, $from_email, $subject) {
|
|
global $mysqli;
|
|
$parts = [];
|
|
foreach ($message->parse()->getAllParts() as $part) {
|
|
$parts[] = [(string) $part->getContentType(), (string) ($part->getContent() ?? '')];
|
|
}
|
|
$bounce = ticketMailBounceRead($parts, (string) ($headers['x-failed-recipients'] ?? ''), (string) ($message->text() ?? ''));
|
|
if ($bounce['delayed']) {
|
|
logApp("Cron-Email-Parser", "info", "Email parser set aside a delivery delay notice from $from_email ($subject) - the email is still being tried");
|
|
return;
|
|
}
|
|
|
|
// The ticket the email was about
|
|
$ticket_id = ticketMailIdTicket($bounce['message_id']);
|
|
if (!$ticket_id) {
|
|
$numbered = ticketMailSubjectTicket($bounce['subject']) ?: ticketMailSubjectTicket(stripslashes($subject));
|
|
$ticket_id = intval($numbered['ticket_id'] ?? 0);
|
|
}
|
|
$ticket = $ticket_id ? ticketRow($ticket_id) : null;
|
|
$client_id = intval($ticket['ticket_client_id'] ?? 0);
|
|
|
|
// The contacts with each address show "Email bounced" until mail comes from it again
|
|
foreach ($bounce['failed'] as $failed => $why) {
|
|
foreach (contactBounceMark($failed, $why) as $bounced_contact_id => [$bounced_name, $bounced_client_id]) {
|
|
logAudit("Contact", "Edit", "Email parser: mail to " . escapeSql($bounced_name) . " bounced - marked on the contact", $bounced_client_id, $bounced_contact_id);
|
|
}
|
|
}
|
|
$to = $bounce['failed'] ? implode(', ', array_keys($bounce['failed'])) : 'someone it doesn\'t name';
|
|
$why = implode('; ', array_filter($bounce['failed']));
|
|
|
|
if ($ticket) {
|
|
$note = '<b>An email about this ticket couldn\'t be delivered</b><br>To: ' . escapeHtml($to) . ($why !== '' ? '<br>The mail server said: ' . escapeHtml($why) : '')
|
|
. '<br><i>From ' . escapeHtml(stripslashes($from_email)) . ' - the report is in the mailbox\'s ITFlow folder</i>';
|
|
mysqli_query($mysqli, "INSERT INTO ticket_replies SET ticket_reply = '" . mysqli_real_escape_string($mysqli, $note) . "', ticket_reply_type = 'Internal',
|
|
ticket_reply_time_worked = '00:00:00', ticket_reply_by = 0, ticket_reply_ticket_id = $ticket_id");
|
|
logTicketHistory($ticket_id, escapeSql("An email to $to couldn't be delivered - noted"));
|
|
}
|
|
appNotify("Ticket", escapeSql("Email parser: an email to $to bounced" . ($ticket ? ' - ' . ticketReference($ticket) . ' has a note' : '')
|
|
. ($why !== '' ? ". The mail server said: " . mb_strimwidth($why, 0, 300, '...') : '') . ". Subject: " . ($bounce['subject'] !== '' ? $bounce['subject'] : stripslashes($subject))),
|
|
$ticket ? "/agent/ticket.php?ticket_id=$ticket_id" . ($client_id ? "&client_id=$client_id" : '') : '', $client_id, $ticket_id);
|
|
}
|
|
|
|
/*
|
|
* A new ticket whose subject is almost that of $similar_id - an open ticket of the client's from the last week - raised by
|
|
* someone who isn't its contact or watching it: kept as a ticket of its own, linked to that one as related
|
|
* (functions/ticket_link.php), so an agent sees both and can merge them.
|
|
*/
|
|
function linkSimilarTicket($new_id, $similar_id) {
|
|
$session_name = $GLOBALS['session_name'] ?? null;
|
|
$GLOBALS['session_name'] = 'The email parser';
|
|
ticketLinkTogether([intval($new_id), intval($similar_id)]);
|
|
$GLOBALS['session_name'] = $session_name;
|
|
$similar = ticketRow($similar_id);
|
|
if ($similar) {
|
|
logTicketHistory(intval($new_id), escapeSql("Its subject is almost the same as " . ticketReference($similar) . "'s, from someone else at the client - linked as related, in case it is the same thing"));
|
|
}
|
|
}
|
|
|
|
/*
|
|
* An email on ticket $ticket_id. $email, about the email:
|
|
* message_id its Message-ID, kept with the ticket (functions/ticket_mail_thread.php)
|
|
* from_name the name in its From line
|
|
* copied the people it was also to or copied to, made watchers when it is from the client or a watcher
|
|
* had everyone it was from, to and copied to - a client's reply goes on to the rest (ticketMailRelayClientReply())
|
|
* threaded it answers one of the ticket's emails (its In-Reply-To or References) - only then is a client's
|
|
* reply passed on, as anyone can put a ticket number in a subject
|
|
* automatic auto-reply (an out-of-office) or automated (a system, a list) - never answered or passed on
|
|
* (functions/ticket_mail_auto.php)
|
|
*
|
|
* Who it is from decides what it is: the ticket's contact, another of the client's contacts, or one of its watchers
|
|
* (the person whose email raised a ticket with no client is one) - a client reply, which reopens the ticket; one
|
|
* of your agents - their own internal note; anyone else - an internal note with a warning, which reopens nothing
|
|
* and takes no attachments. An automatic reply is a note that reopens nothing, and an email to a closed ticket is
|
|
* kept on it as a note - it isn't reopened.
|
|
*/
|
|
function addReply($from_email, $date, $subject, $ticket_id, $message, $attachments, $original_message_file = null, array $email = []) {
|
|
global $mysqli, $allowed_extensions;
|
|
|
|
$automatic = (string) ($email['automatic'] ?? '');
|
|
$from_name = trim(stripslashes((string) ($email['from_name'] ?? '')));
|
|
$from_name = $from_name === 'Unknown' ? '' : $from_name;
|
|
|
|
// 1) What they wrote, without the email of ours they quote - above the reply line, or below it when
|
|
// that's where they wrote (emailReplyText(), functions/email.php)
|
|
$message = emailReplyText($message);
|
|
|
|
// 2) Clean up the remaining message - no DOCTYPE, meta, html, head or body, and its line breaks as <br>
|
|
$message = preg_replace('/<!DOCTYPE[^>]*>/i', '', $message);
|
|
$message = preg_replace('/<meta[^>]*>/i', '', $message);
|
|
$message = preg_replace('/<\/?(html|head|body)[^>]*>/i', '', $message);
|
|
$message = trim($message);
|
|
$message = preg_replace('/\r\n|\r|\n/', ' ', $message);
|
|
$message = nl2br($message);
|
|
|
|
// 3) Who it is from and when, above it - by name too, when the email gives one
|
|
$from_line = $from_name !== '' ? '<b>' . escapeHtml($from_name) . '</b> <' . $from_email . '>' : $from_email;
|
|
$message = "<i>Email from: $from_line at $date:-</i><br><br><div style='line-height:1.5;'>$message</div>";
|
|
|
|
$from_email_esc = mysqli_real_escape_string($mysqli, $from_email);
|
|
|
|
$row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT ticket_id, ticket_prefix, ticket_number, ticket_subject, ticket_status, ticket_contact_id, ticket_client_id, contact_email, client_name
|
|
FROM tickets
|
|
LEFT JOIN contacts on tickets.ticket_contact_id = contacts.contact_id
|
|
LEFT JOIN clients on tickets.ticket_client_id = clients.client_id
|
|
WHERE ticket_id = " . intval($ticket_id) . " LIMIT 1"));
|
|
if (!$row) {
|
|
return false;
|
|
}
|
|
|
|
$ticket_id = intval($row['ticket_id']);
|
|
// Its own reference, with the prefix it was given - for the logs
|
|
$ticket_reference_esc = escapeSql(ticketReference($row));
|
|
$ticket_status = intval($row['ticket_status']);
|
|
$client_id = intval($row['ticket_client_id']);
|
|
$client_uri = $client_id ? "&client_id=$client_id" : '';
|
|
|
|
// Who wrote it - contact (the ticket's, or another of the client's), watcher, agent or stranger
|
|
$who = 'stranger';
|
|
$reply_by = 0;
|
|
if (trim((string) $row['contact_email']) !== '' && strcasecmp(trim((string) $row['contact_email']), stripslashes($from_email)) === 0) {
|
|
$who = 'contact';
|
|
$reply_by = intval($row['ticket_contact_id']);
|
|
} elseif ($client_id && ($contact_row = mysqli_fetch_row(mysqli_query($mysqli, "SELECT contact_id FROM contacts WHERE contact_email = '$from_email_esc' AND contact_client_id = $client_id AND contact_archived_at IS NULL LIMIT 1")))) {
|
|
$who = 'contact';
|
|
$reply_by = intval($contact_row[0]);
|
|
} elseif ($agent_row = mysqli_fetch_row(mysqli_query($mysqli, "SELECT user_id FROM users WHERE user_email = '$from_email_esc' AND user_type = 1 AND user_status = 1 AND user_archived_at IS NULL LIMIT 1"))) {
|
|
$who = 'agent';
|
|
$reply_by = intval($agent_row[0]); // an internal note is by an agent, as on the ticket page
|
|
} elseif (mysqli_num_rows(mysqli_query($mysqli, "SELECT 1 FROM ticket_watchers WHERE watcher_ticket_id = $ticket_id AND watcher_email = '$from_email_esc' LIMIT 1"))) {
|
|
$who = 'watcher';
|
|
}
|
|
$stranger = $who === 'stranger';
|
|
$closed = $ticket_status === TICKET_STATUS_CLOSED;
|
|
$by_name = $who === 'contact' ? (string) getFieldById('contacts', $reply_by, 'contact_name') : ($from_name !== '' ? $from_name : stripslashes($from_email));
|
|
|
|
// What it is on the ticket: a client reply from the client or a watcher; a note from an agent, a stranger, an automatic
|
|
// reply, or anything on a closed ticket
|
|
$type = in_array($who, ['contact', 'watcher'], true) && $automatic !== 'auto-reply' && !$closed ? 'Client' : 'Internal';
|
|
$notes = [];
|
|
if ($automatic === 'auto-reply') {
|
|
$notes[] = 'An automatic reply - the ticket was not reopened';
|
|
} elseif ($closed) {
|
|
$notes[] = 'A reply to the ticket after it was closed - it was not reopened';
|
|
}
|
|
if ($stranger) {
|
|
$notes[] = 'From someone who is not a contact, watcher or agent' . ($closed || $automatic === 'auto-reply' ? '' : ' - the ticket was not reopened')
|
|
. ($attachments ? ", and the email's " . count($attachments) . " attachment(s) were not added - it is in the mailbox's ITFlow folder" : '');
|
|
}
|
|
if ($notes) {
|
|
$message = '<b>' . escapeHtml(implode('. ', $notes)) . '</b><br>' . $message;
|
|
}
|
|
$message_esc = mysqli_real_escape_string($mysqli, $message);
|
|
if ($type === 'Internal') {
|
|
$reply_by = $who === 'agent' ? $reply_by : 0;
|
|
}
|
|
|
|
// Who a client reply from someone who isn't a contact came from - there is no contact to name (4.2.7)
|
|
$from_sql = '';
|
|
if ($type === 'Client' && $who === 'watcher' && ticketReplyFromReady()) {
|
|
$from_sql = ", ticket_reply_from_name = " . ($from_name !== '' ? "'" . mysqli_real_escape_string($mysqli, mb_substr($from_name, 0, 200)) . "'" : 'NULL')
|
|
. ", ticket_reply_from_email = '" . mysqli_real_escape_string($mysqli, mb_substr(stripslashes($from_email), 0, 255)) . "'";
|
|
}
|
|
mysqli_query($mysqli, "INSERT INTO ticket_replies SET ticket_reply = '$message_esc', ticket_reply_type = '$type', ticket_reply_time_worked = '00:00:00', ticket_reply_by = $reply_by$from_sql, ticket_reply_ticket_id = $ticket_id");
|
|
$reply_id = mysqli_insert_id($mysqli);
|
|
|
|
// In the ticket's conversation - the next email about it answers this one (functions/ticket_mail_thread.php)
|
|
ticketMailKeepId($ticket_id, (string) ($email['message_id'] ?? ''));
|
|
|
|
// The email's pictures kept as the ticket's files, not inside the reply (functions/ticket_pictures.php)
|
|
ticketPicturesSaveReply($reply_id);
|
|
|
|
// Its attachments, and the email as it came - not a stranger's, nor an automatic reply's
|
|
$ticket_dir = "../uploads/tickets/" . $ticket_id . "/";
|
|
mkdirMissing($ticket_dir);
|
|
$take_files = !$stranger && $automatic !== 'auto-reply';
|
|
foreach ($take_files ? $attachments : [] as $attachment) {
|
|
$att_name = $attachment['name'];
|
|
$att_extension = strtolower(pathinfo($att_name, PATHINFO_EXTENSION));
|
|
|
|
if (in_array($att_extension, $allowed_extensions)) {
|
|
$att_saved_filename = md5(uniqid(rand(), true)) . '.' . $att_extension;
|
|
$att_saved_path = $ticket_dir . $att_saved_filename;
|
|
file_put_contents($att_saved_path, $attachment['content']);
|
|
|
|
// Escaped once, and cut to the 255 characters the column holds
|
|
$ticket_attachment_name_esc = escapeSql(mb_substr($att_name, 0, 255));
|
|
$ticket_attachment_reference_name_esc = mysqli_real_escape_string($mysqli, escapeSql($att_saved_filename));
|
|
mysqli_query($mysqli, "INSERT INTO ticket_attachments SET ticket_attachment_name = '$ticket_attachment_name_esc', ticket_attachment_reference_name = '$ticket_attachment_reference_name_esc', ticket_attachment_reply_id = $reply_id, ticket_attachment_ticket_id = $ticket_id");
|
|
} else {
|
|
$ticket_attachment_name_esc = mysqli_real_escape_string($mysqli, $att_name);
|
|
logAudit("Ticket", "Edit", "Email parser: Blocked attachment $ticket_attachment_name_esc from $from_email_esc for ticket $ticket_reference_esc", $client_id, $ticket_id);
|
|
}
|
|
}
|
|
|
|
// The email as it came, kept with the reply as a new ticket keeps it - the reply line trims what
|
|
// shows on the ticket, and The email as it arrived shows the rest (agent/modals/ticket/ticket_email_source.php)
|
|
if ($take_files && $original_message_file && is_file("../uploads/tmp/$original_message_file")) {
|
|
rename("../uploads/tmp/$original_message_file", $ticket_dir . $original_message_file);
|
|
$original_message_file_esc = mysqli_real_escape_string($mysqli, $original_message_file);
|
|
mysqli_query($mysqli, "INSERT INTO ticket_attachments SET ticket_attachment_name = 'Original-parsed-email.eml', ticket_attachment_reference_name = '$original_message_file_esc', ticket_attachment_reply_id = $reply_id, ticket_attachment_ticket_id = $ticket_id");
|
|
}
|
|
|
|
// An automatic reply - an out-of-office - is there to read, and that is all
|
|
if ($automatic === 'auto-reply') {
|
|
logTicketHistory($ticket_id, "$from_email_esc sent an automatic reply - kept as a note");
|
|
return true;
|
|
}
|
|
|
|
// A closed ticket isn't reopened. Agents are told it is on it, and the client or watcher that nobody will act on it -
|
|
// not a stranger (a guessed number would tell them the ticket's subject), an agent, or anything automatic, whose
|
|
// answer would only be answered, and not more than a few times an hour (functions/ticket_mail_auto.php)
|
|
if ($closed) {
|
|
appNotify("Ticket", "Email parser: $from_email replied to closed ticket $ticket_reference_esc - it is on the ticket as a note, and the ticket was not reopened", "/agent/ticket.php?ticket_id=$ticket_id$client_uri", $client_id, $ticket_id);
|
|
logTicketHistory($ticket_id, "$from_email_esc replied after it was closed - kept as a note");
|
|
if (in_array($who, ['contact', 'watcher'], true) && $automatic === '' && ticketMailAnswersLeft(stripslashes($from_email))) {
|
|
ticketMailClosedReply($ticket_id, stripslashes($from_email), (string) ($email['message_id'] ?? ''));
|
|
}
|
|
return true;
|
|
}
|
|
|
|
if ($who === 'agent') {
|
|
logTicketHistory($ticket_id, "$from_email_esc (an agent) emailed - added as their internal note");
|
|
logAudit("Ticket", "Edit", "Email parser: Agent $from_email_esc added an internal note to ticket $ticket_reference_esc ($subject)", $client_id, $ticket_id);
|
|
return true;
|
|
}
|
|
|
|
// The people the client or a watcher also wrote to, or copied in, follow the ticket from now on - as
|
|
// they would have in a conversation by email. Not a stranger's: anyone can put a number in a subject
|
|
if (!$stranger && ($watching = ticketMailCopiedWatchers($ticket_id, (array) ($email['copied'] ?? []), stripslashes($from_email)))) {
|
|
logTicketHistory($ticket_id, escapeSql(implode(', ', $watching)) . (count($watching) === 1 ? ' is' : ' are') . " watching now - copied in on an email from $from_email_esc");
|
|
}
|
|
|
|
// The agent it is assigned to, with what they wrote - a stranger's as plain text
|
|
$mail_reply = (string) getFieldById('ticket_replies', $reply_id, 'ticket_reply');
|
|
if ($stranger) {
|
|
$mail_reply = nl2br(escapeHtml(trim(html_entity_decode(strip_tags(preg_replace('/<br\s*\/?>/i', "\n", $mail_reply)), ENT_QUOTES, 'UTF-8'))));
|
|
}
|
|
ticketMailAssigneeReplied($ticket_id, 'email', $mail_reply, $by_name);
|
|
|
|
if ($stranger) {
|
|
logTicketHistory($ticket_id, "$from_email_esc (not a contact, watcher or agent) emailed - kept as an internal note, the ticket was not reopened");
|
|
logAudit("Ticket", "Edit", "Email parser: $from_email_esc (not a contact, watcher or agent) emailed ticket $ticket_reference_esc ($subject) - kept as an internal note", $client_id, $ticket_id);
|
|
return true;
|
|
}
|
|
|
|
// A client's reply goes on to the people following the ticket who weren't on the email - only one that answers an
|
|
// email of the ticket's: a ticket number in a subject is all a forged email needs, and this would carry its words
|
|
// to them from your own mailbox (ticketMailRelayClientReply()). Nothing automatic
|
|
if (!empty($email['threaded']) && $automatic === '') {
|
|
ticketMailRelayClientReply($ticket_id, $reply_id, $by_name, stripslashes($from_email), (array) ($email['had'] ?? []), (string) ($email['message_id'] ?? ''));
|
|
}
|
|
|
|
// Back to Open - unless it is in a status of your own set to stay put when the client replies (Scheduled, say)
|
|
$new_ticket_status = ticketStatusAfterClientReply($ticket_status);
|
|
mysqli_query($mysqli, "UPDATE tickets SET ticket_status = $new_ticket_status, ticket_resolved_at = NULL WHERE ticket_id = $ticket_id AND ticket_client_id = $client_id LIMIT 1");
|
|
// A resolved ticket's resolution clock runs again - an open one keeps its alerts, so a warning isn't sent twice
|
|
if ($ticket_status === TICKET_STATUS_RESOLVED) {
|
|
resetTicketResolutionSla($ticket_id);
|
|
} else {
|
|
syncTicketSlaClock($ticket_id);
|
|
}
|
|
|
|
// Only record the reopen when the ticket was not already open
|
|
if ($ticket_status !== intval($new_ticket_status)) {
|
|
logTicketHistory($ticket_id, "$from_email_esc replied by email, reopening the ticket");
|
|
}
|
|
|
|
logAudit("Ticket", "Edit", "Email parser: " . ($who === 'watcher' ? 'Watcher' : 'Client contact') . " $from_email_esc updated ticket $ticket_reference_esc ($subject)", $client_id, $ticket_id);
|
|
triggerCustomAction('ticket_reply_client', $ticket_id);
|
|
return true;
|
|
}
|
|
|
|
/** ------------------------------------------------------------------
|
|
* OAuth helpers + provider guard
|
|
* ------------------------------------------------------------------ */
|
|
|
|
// returns true if expires_at ('Y-m-d H:i:s') is in the past (or missing)
|
|
function tokenExpired(?string $expires_at): bool {
|
|
if (empty($expires_at)) return true;
|
|
$ts = strtotime($expires_at);
|
|
if ($ts === false) return true;
|
|
// refresh a little early (60s) to avoid race
|
|
return ($ts - 60) <= time();
|
|
}
|
|
|
|
// very small form-encoded POST helper using curl
|
|
/**
|
|
* Get a valid access token for Google Workspace IMAP via refresh token if needed.
|
|
* Uses settings: config_mail_oauth_client_id / _client_secret / _refresh_token / _access_token / _access_token_expires_at
|
|
* Updates globals if refreshed (so later logging can reflect it if you want to persist).
|
|
*/
|
|
function getGoogleAccessToken(string $username): ?string {
|
|
// pull from global settings variables you already load
|
|
global $mysqli,
|
|
$config_mail_oauth_client_id,
|
|
$config_mail_oauth_client_secret,
|
|
$config_mail_oauth_refresh_token,
|
|
$config_mail_oauth_access_token,
|
|
$config_mail_oauth_access_token_expires_at;
|
|
|
|
// If we have a not-expired token, use it
|
|
if (!empty($config_mail_oauth_access_token) && !tokenExpired($config_mail_oauth_access_token_expires_at)) {
|
|
return $config_mail_oauth_access_token;
|
|
}
|
|
|
|
// Need to refresh?
|
|
if (empty($config_mail_oauth_client_id) || empty($config_mail_oauth_client_secret) || empty($config_mail_oauth_refresh_token)) {
|
|
// Nothing we can do
|
|
return null;
|
|
}
|
|
|
|
$resp = httpFormPost(
|
|
'https://oauth2.googleapis.com/token',
|
|
[
|
|
'client_id' => $config_mail_oauth_client_id,
|
|
'client_secret' => $config_mail_oauth_client_secret,
|
|
'refresh_token' => $config_mail_oauth_refresh_token,
|
|
'grant_type' => 'refresh_token',
|
|
]
|
|
);
|
|
|
|
if (!$resp['ok']) return null;
|
|
|
|
$json = json_decode($resp['body'], true);
|
|
if (!is_array($json) || empty($json['access_token'])) return null;
|
|
|
|
// Calculate new expiry
|
|
$expires_at = date('Y-m-d H:i:s', time() + (int)($json['expires_in'] ?? 3600));
|
|
|
|
// Update in-memory globals (and persist to DB)
|
|
$config_mail_oauth_access_token = $json['access_token'];
|
|
$config_mail_oauth_access_token_expires_at = $expires_at;
|
|
|
|
$at_esc = mysqli_real_escape_string($mysqli, $config_mail_oauth_access_token);
|
|
$exp_esc = mysqli_real_escape_string($mysqli, $config_mail_oauth_access_token_expires_at);
|
|
mysqli_query($mysqli, "UPDATE settings SET
|
|
config_mail_oauth_access_token = '{$at_esc}',
|
|
config_mail_oauth_access_token_expires_at = '{$exp_esc}'
|
|
WHERE company_id = 1
|
|
");
|
|
|
|
return $config_mail_oauth_access_token;
|
|
}
|
|
|
|
/**
|
|
* Get a valid access token for Microsoft 365 IMAP via refresh token if needed.
|
|
* Uses settings: config_mail_oauth_client_id / _client_secret / _tenant_id / _refresh_token / _access_token / _access_token_expires_at
|
|
*/
|
|
function getMicrosoftAccessToken(string $username): ?string {
|
|
global $mysqli,
|
|
$config_mail_oauth_client_id,
|
|
$config_mail_oauth_client_secret,
|
|
$config_mail_oauth_tenant_id,
|
|
$config_mail_oauth_refresh_token,
|
|
$config_mail_oauth_access_token,
|
|
$config_mail_oauth_access_token_expires_at;
|
|
|
|
if (!empty($config_mail_oauth_access_token) && !tokenExpired($config_mail_oauth_access_token_expires_at)) {
|
|
return $config_mail_oauth_access_token;
|
|
}
|
|
|
|
if (empty($config_mail_oauth_client_id) || empty($config_mail_oauth_client_secret) || empty($config_mail_oauth_refresh_token) || empty($config_mail_oauth_tenant_id)) {
|
|
return null;
|
|
}
|
|
|
|
$url = "https://login.microsoftonline.com/".rawurlencode($config_mail_oauth_tenant_id)."/oauth2/v2.0/token";
|
|
|
|
$resp = httpFormPost($url, [
|
|
'client_id' => $config_mail_oauth_client_id,
|
|
'client_secret' => $config_mail_oauth_client_secret,
|
|
'refresh_token' => $config_mail_oauth_refresh_token,
|
|
'grant_type' => 'refresh_token',
|
|
// Named, as the refresh token may last have been renewed for Graph (functions/mail_graph.php)
|
|
'scope' => MAIL_MICROSOFT_EXCHANGE_SCOPE,
|
|
]);
|
|
|
|
if (!$resp['ok']) return null;
|
|
|
|
$json = json_decode($resp['body'], true);
|
|
if (!is_array($json) || empty($json['access_token'])) return null;
|
|
|
|
$expires_at = date('Y-m-d H:i:s', time() + (int)($json['expires_in'] ?? 3600));
|
|
|
|
$config_mail_oauth_access_token = $json['access_token'];
|
|
$config_mail_oauth_access_token_expires_at = $expires_at;
|
|
|
|
$at_esc = mysqli_real_escape_string($mysqli, $config_mail_oauth_access_token);
|
|
$exp_esc = mysqli_real_escape_string($mysqli, $config_mail_oauth_access_token_expires_at);
|
|
mysqli_query($mysqli, "UPDATE settings SET
|
|
config_mail_oauth_access_token = '{$at_esc}',
|
|
config_mail_oauth_access_token_expires_at = '{$exp_esc}'
|
|
WHERE company_id = 1
|
|
");
|
|
|
|
return $config_mail_oauth_access_token;
|
|
}
|
|
|
|
// Provider from settings (may be NULL/empty to disable IMAP polling)
|
|
$imap_provider = $config_imap_provider ?? '';
|
|
if ($imap_provider === null) $imap_provider = '';
|
|
|
|
if ($imap_provider === '') {
|
|
// No mailbox to read isn't an error - Maintenance > Cron shows why it stopped, where an
|
|
// App Logs entry every minute only buried the real ones
|
|
cronJobStop("No mailbox is set up to read - see Admin > Settings > Mail");
|
|
}
|
|
|
|
/** ------------------------------------------------------------------
|
|
* ImapEngine setup (supports Standard / Google OAuth / Microsoft OAuth)
|
|
* ------------------------------------------------------------------ */
|
|
use DirectoryTree\ImapEngine\Mailbox;
|
|
|
|
$validate_cert = true;
|
|
|
|
// Defaults from settings (standard IMAP)
|
|
$host = $config_imap_host;
|
|
$port = (int)$config_imap_port;
|
|
$encr = !empty($config_imap_encryption) ? $config_imap_encryption : 'notls'; // 'ssl'|'tls'|'notls'
|
|
$user = $config_imap_username;
|
|
$pass = $config_imap_password;
|
|
$auth = 'plain'; // 'oauth' for OAuth providers
|
|
$graph_token = null; // Microsoft 365 read through Microsoft Graph (functions/mail_graph.php)
|
|
|
|
if ($imap_provider === 'google_oauth') {
|
|
$host = 'imap.gmail.com';
|
|
$port = 993;
|
|
$encr = 'ssl';
|
|
$auth = 'oauth';
|
|
$pass = getGoogleAccessToken($user);
|
|
if (empty($pass)) {
|
|
logApp("Cron-Email-Parser", "error", "Google OAuth: no usable access token (check refresh token/client credentials).");
|
|
cronJobStop('', 1);
|
|
}
|
|
} elseif ($imap_provider === 'microsoft_oauth') {
|
|
// Read through Microsoft Graph when the app has Mail.ReadWrite - no IMAP sign-in then
|
|
try {
|
|
$graph_token = mailGraphToken('Mail.ReadWrite');
|
|
} catch (\Throwable $e) {
|
|
logApp("Cron-Email-Parser", "error", "Microsoft Graph: " . $e->getMessage());
|
|
cronJobStop('', 1);
|
|
}
|
|
if ($graph_token === null) {
|
|
$host = 'outlook.office365.com';
|
|
$port = 993;
|
|
$encr = 'ssl';
|
|
$auth = 'oauth';
|
|
$pass = getMicrosoftAccessToken($user);
|
|
if (empty($pass)) {
|
|
logApp("Cron-Email-Parser", "error", "Microsoft OAuth: no usable access token (check refresh token/client credentials/tenant).");
|
|
cronJobStop('', 1);
|
|
}
|
|
}
|
|
} else {
|
|
// standard_imap (username/password)
|
|
if (empty($host) || empty($port) || empty($user)) {
|
|
logApp("Cron-Email-Parser", "error", "Standard IMAP: missing host/port/username.");
|
|
cronJobStop('', 1);
|
|
}
|
|
}
|
|
|
|
// Map Webklex-style encryption values to ImapEngine transports
|
|
// Webklex 'tls' = STARTTLS (port 143), ImapEngine 'tls' = implicit TLS, so translate
|
|
$encryption = match (strtolower($encr)) {
|
|
'ssl' => 'ssl', // implicit TLS (993)
|
|
'tls' => 'starttls', // STARTTLS upgrade (143) - Webklex semantics
|
|
'starttls' => 'starttls',
|
|
default => '', // 'notls' / plain tcp
|
|
};
|
|
|
|
$mailbox = $graph_token !== null ? mailGraphMailbox($graph_token, (string) $user) : new Mailbox([
|
|
'host' => $host,
|
|
'port' => $port,
|
|
'encryption' => $encryption,
|
|
'validate_cert' => (bool)$validate_cert,
|
|
'username' => $user, // full mailbox address (OAuth uses user as principal)
|
|
'password' => $pass, // access token when $auth === 'oauth'
|
|
'authentication' => $auth, // 'oauth' or 'plain'
|
|
]);
|
|
|
|
try {
|
|
$mailbox->connect();
|
|
} catch (\Throwable $e) {
|
|
cronJobStop("Error connecting to the mail server: " . $e->getMessage() . "\n", 1);
|
|
}
|
|
|
|
$inbox = $mailbox->inbox();
|
|
|
|
// Resolve the processed-mail folder in a namespace-aware way.
|
|
// Most servers (Gmail, M365, Dovecot with an empty namespace prefix) allow
|
|
// root-level folders, so "ITFlow" is preferred. cPanel-style Dovecot uses a
|
|
// Maildir++ layout where the personal namespace prefix is "INBOX." - root
|
|
// CREATE fails there with "Client tried to access nonexistent namespace",
|
|
// and the folder must be addressed as "INBOX.ITFlow" (clients still display
|
|
// it as a top-level folder alongside Inbox).
|
|
$targetFolderName = 'ITFlow';
|
|
try {
|
|
// INBOX always exists (RFC 3501) - use it to learn the hierarchy delimiter
|
|
// (ImapEngine returns the literal string "NIL" for servers with a flat namespace)
|
|
$delimiter = $mailbox->folders()->findOrFail('INBOX')->delimiter();
|
|
if ($delimiter === '' || strcasecmp($delimiter, 'NIL') === 0) {
|
|
$delimiter = '.';
|
|
}
|
|
|
|
// Candidate paths, in order of preference
|
|
$candidates = [
|
|
$targetFolderName, // Root-level (empty namespace prefix)
|
|
'INBOX' . $delimiter . $targetFolderName, // INBOX-prefixed namespace (e.g. cPanel Dovecot)
|
|
];
|
|
|
|
// Re-use the folder if it already exists at either location
|
|
$targetFolder = null;
|
|
foreach ($candidates as $candidate) {
|
|
if ($targetFolder = $mailbox->folders()->find($candidate)) {
|
|
$targetFolderPath = $candidate;
|
|
break;
|
|
}
|
|
}
|
|
|
|
// Otherwise create it, falling back to the namespace-prefixed path if the
|
|
// server rejects root-level creation
|
|
if (!$targetFolder) {
|
|
$creation_errors = [];
|
|
foreach ($candidates as $candidate) {
|
|
try {
|
|
$targetFolder = $mailbox->folders()->create($candidate);
|
|
$targetFolderPath = $candidate;
|
|
break;
|
|
} catch (\Throwable $e) {
|
|
$creation_errors[] = "[$candidate]: " . $e->getMessage();
|
|
}
|
|
}
|
|
if (!$targetFolder) {
|
|
throw new \Exception("CREATE rejected for all candidate paths - " . implode(' / ', $creation_errors));
|
|
}
|
|
|
|
// Subscribe to the newly created folder so it's visible in mail clients
|
|
// that only display subscribed folders (common with Dovecot/Roundcube).
|
|
// Non-fatal - some servers ignore or reject SUBSCRIBE entirely.
|
|
try {
|
|
$mailbox->connection()->subscribe(
|
|
\DirectoryTree\ImapEngine\Support\Str::toImapUtf7($targetFolderPath)
|
|
);
|
|
} catch (\Throwable $e) {
|
|
logApp("Cron-Email-Parser", "warning", "Created folder [$targetFolderPath] but could not subscribe to it: " . $e->getMessage());
|
|
}
|
|
}
|
|
} catch (\Throwable $e) {
|
|
logApp("Cron-Email-Parser", "error", "Unable to find/create target folder [$targetFolderName]: " . $e->getMessage());
|
|
cronJobStop('', 1);
|
|
}
|
|
|
|
// Fetch unseen messages (headers, body & flags; BODY.PEEK so they stay unread)
|
|
// unflagged() skips messages a previous run flagged for manual attention,
|
|
// so they aren't pointlessly re-processed every run forever
|
|
$messages = $inbox->messages()
|
|
->withHeaders()
|
|
->withBody()
|
|
->withFlags()
|
|
->leaveUnread()
|
|
->unseen()
|
|
->unflagged()
|
|
->limit($max_emails_per_run)
|
|
->get();
|
|
$messages = is_array($messages) ? $messages : iterator_to_array($messages, false);
|
|
|
|
// And mail someone opened before ITFlow got to it - Outlook marks an email read as it shows it, so one opened in
|
|
// the minute before this ran was never taken. Only what came in the last $read_mail_minutes: mail read before
|
|
// that - in a mailbox used by hand for years, or while this wasn't running - stays where it is. Taken mail leaves
|
|
// the inbox for the ITFlow folder, so nothing is taken twice. Newest first, as SINCE goes by whole days, in the mail
|
|
// server's time zone - a day besides is asked for, and by its time what is older is left
|
|
if (count($messages) < $max_emails_per_run) {
|
|
$read_after = time() - $read_mail_minutes * 60;
|
|
$read_messages = $inbox->messages()
|
|
->withHeaders()
|
|
->withBody()
|
|
->withFlags()
|
|
->leaveUnread()
|
|
->seen()
|
|
->unflagged()
|
|
->since(date('Y-m-d', $read_after - 86400))
|
|
->newest()
|
|
->limit($max_emails_per_run - count($messages))
|
|
->get();
|
|
foreach (is_array($read_messages) ? $read_messages : iterator_to_array($read_messages, false) as $read_message) {
|
|
$read_date = $read_message->date();
|
|
if ($read_date && $read_date->getTimestamp() >= $read_after) {
|
|
$messages[] = $read_message;
|
|
}
|
|
}
|
|
}
|
|
|
|
// ITFlow's own addresses - mail from one of them is its own come back (emailOwnAddresses())
|
|
$own_addresses = emailOwnAddresses();
|
|
|
|
// Counters
|
|
$processed_count = 0;
|
|
$unprocessed_count = 0;
|
|
|
|
// Process messages
|
|
foreach ($messages as $message) {
|
|
try {
|
|
$email_processed = false;
|
|
|
|
// From
|
|
$from_addr = $message->from(); // ?Address
|
|
$from_email = escapeSql($from_addr?->email() ?: 'itflow-guest@example.com');
|
|
$from_name = escapeSql($from_addr?->name() ?: 'Unknown');
|
|
|
|
$from_domain = explode("@", $from_email);
|
|
$from_domain = escapeSql(end($from_domain));
|
|
|
|
// Mail from an address that bounced before - it works again (functions/contact_bounce.php)
|
|
contactBounceClearEmail(stripslashes($from_email));
|
|
|
|
// Subject
|
|
// ticket_subject holds 500 characters - a longer one failed the insert and the email was tried again every run
|
|
$subject = escapeSql(mb_substr((string)$message->subject() ?: 'No Subject', 0, 500));
|
|
|
|
// ITFlow's own email come back - a copy to a watcher that is this mailbox, a notice sent to it. Taken, it would
|
|
// go on the ticket as a note and reopen it, or raise a ticket that sends another, round and round
|
|
if (in_array(strtolower(stripslashes($from_email)), $own_addresses, true)) {
|
|
logApp("Cron-Email-Parser", "info", "Email parser skipped an email from ITFlow's own address $from_email ($subject) - mail it sent came back to this mailbox");
|
|
$processed_count++;
|
|
$message->markSeen();
|
|
$message->move($targetFolderPath);
|
|
continue;
|
|
}
|
|
|
|
// What kind of email it is - a mail server's bounce, an automatic reply, or one sent by a system or a list - by its
|
|
// headers (functions/ticket_mail_auto.php). A bounce is read now, whatever the settings: it is never a ticket and
|
|
// never answered. It used to be read only with unknown senders on, as the last step, and an address with "mta",
|
|
// "daemon" or "bounce" anywhere in it was taken for a mail server
|
|
$headers = ticketMailHeaderMap($message);
|
|
if (ticketMailIsBounce($headers, stripslashes($from_email))) {
|
|
addBounce($message, $headers, $from_email, $subject);
|
|
$processed_count++;
|
|
$message->markSeen();
|
|
$message->move($targetFolderPath);
|
|
continue;
|
|
}
|
|
$automatic = ticketMailAutomaticKind($headers, stripslashes($subject));
|
|
|
|
// The same email a second time - sent to two of your addresses that both land in this mailbox, say - is on its
|
|
// ticket already, kept by its Message-ID (functions/ticket_mail_thread.php). Taken again, it was a second ticket
|
|
$email_message_id = ticketMailIdClean((string) $message->messageId());
|
|
if ($email_message_id !== '' && ($seen_ticket_id = ticketMailIdTicket($email_message_id))) {
|
|
logApp("Cron-Email-Parser", "info", "Email parser skipped a second copy of an email from $from_email ($subject) - it is on ticket ID $seen_ticket_id already");
|
|
$processed_count++;
|
|
$message->markSeen();
|
|
$message->move($targetFolderPath);
|
|
continue;
|
|
}
|
|
|
|
// Save original message as .eml (ImapEngine: raw headers + raw body)
|
|
mkdirMissing('../uploads/tmp/');
|
|
$original_message_file = "processed-eml-" . randomString(200) . ".eml";
|
|
$raw_message = (string)$message; // head + body, CRLF separated
|
|
file_put_contents("../uploads/tmp/{$original_message_file}", $raw_message);
|
|
|
|
// Who else it was to or copied to (deduplicated, excluding the sender) - and not ITFlow's own addresses: this
|
|
// mailbox CC'd beside a tech made a watcher would get every email about the ticket, each come back as a note
|
|
$copied = array();
|
|
$had = [strtolower(stripslashes($from_email))];
|
|
foreach (array_merge($message->to(), $message->cc()) as $copied_addr) {
|
|
$copied_mail = strtolower((string) $copied_addr->email());
|
|
$had[] = $copied_mail;
|
|
if ($copied_mail && $copied_mail !== strtolower($from_email) && !in_array($copied_mail, $copied) && !in_array($copied_mail, $own_addresses, true)) {
|
|
$copied[] = $copied_mail;
|
|
}
|
|
}
|
|
|
|
// Where it is in an email conversation - the Message-IDs it answers
|
|
$in_reply_to = (string) ($message->header('In-Reply-To')?->getRawValue() ?? '');
|
|
$references = (string) ($message->header('References')?->getRawValue() ?? '');
|
|
$email = ['message_id' => $email_message_id, 'from_name' => $from_name, 'copied' => $copied, 'had' => array_values(array_unique(array_filter($had))), 'threaded' => false,
|
|
'automatic' => $automatic];
|
|
|
|
// Date (string)
|
|
$dateObj = $message->date(); // ?CarbonInterface
|
|
$date = escapeSql($dateObj ? $dateObj->setTimezone(date_default_timezone_get())->format('Y-m-d H:i:s') : date('Y-m-d H:i:s'));
|
|
|
|
// Body (prefer HTML)
|
|
$message_body_html = $message->html();
|
|
$message_body_text = $message->text();
|
|
|
|
if (!empty($message_body_html)) {
|
|
$message_body = $message_body_html;
|
|
} elseif (!empty($message_body_text)) {
|
|
$message_body = nl2br(htmlspecialchars($message_body_text));
|
|
} else {
|
|
// Final fallback - raw body
|
|
$message_body = nl2br(htmlspecialchars($message->body()));
|
|
}
|
|
|
|
// Handle attachments (inline vs regular)
|
|
$attachments = [];
|
|
foreach ($message->attachments() as $att) {
|
|
$dispo = strtolower((string)$att->contentDisposition());
|
|
$cid = $att->contentId(); // Content-ID (without <>)
|
|
$content = $att->contents(); // binary
|
|
$mime = $att->contentType();
|
|
$name = $att->filename() ?: 'attachment';
|
|
$size = strlen($content);
|
|
|
|
// Skip oversized attachments entirely
|
|
if ($size > $max_attachment_bytes) {
|
|
logApp("Cron-Email-Parser", "warning", "Email parser skipped oversized attachment " . escapeSql($name) . " (" . round($size / 1048576, 1) . " MB) from $from_email ($subject)");
|
|
continue;
|
|
}
|
|
|
|
// Embed small inline images as data URIs - made the ticket's files once the reply or ticket is saved
|
|
// (ticketPicturesSaveReply()); oversized inline images fall through and are saved as regular attachments
|
|
$is_inline = false;
|
|
if ($dispo === 'inline' && $cid && $content !== '' && $size <= $max_inline_embed_bytes) {
|
|
$cid_trim = trim($cid, '<>');
|
|
$dataUri = "data:$mime;base64,".base64_encode($content);
|
|
$message_body = str_replace(["cid:$cid_trim", "cid:<$cid_trim>"], $dataUri, $message_body);
|
|
$is_inline = true;
|
|
}
|
|
|
|
if (!$is_inline && $content !== '') {
|
|
$attachments[] = ['name' => $name, 'content' => $content];
|
|
}
|
|
}
|
|
|
|
// 1. A reply in a ticket's conversation - it answers one of the emails on the ticket, by its In-Reply-To or
|
|
// References - whatever its subject says (functions/ticket_mail_thread.php)
|
|
$thread_ticket_id = ticketMailHeaderTicket($in_reply_to, $references);
|
|
if ($thread_ticket_id) {
|
|
$email['threaded'] = true;
|
|
$email_processed = addReply($from_email, $date, $subject, $thread_ticket_id, $message_body, $attachments, $original_message_file, $email);
|
|
}
|
|
|
|
// 2. Reply to existing ticket with the number in subject - with the prefix that ticket was given
|
|
if (!$email_processed && ($subject_ticket = ticketMailSubjectTicket(stripslashes($subject)))) {
|
|
$email_processed = addReply($from_email, $date, $subject, $subject_ticket['ticket_id'], $message_body, $attachments, $original_message_file, $email);
|
|
}
|
|
|
|
// An automatic reply - an out-of-office - that answers no ticket is set aside: it isn't a ticket, and isn't answered
|
|
if (!$email_processed && $automatic === 'auto-reply') {
|
|
logApp("Cron-Email-Parser", "info", "Email parser set aside an automatic reply from $from_email ($subject) - it answers no ticket");
|
|
$email_processed = true;
|
|
}
|
|
|
|
// 3. Almost the same subject as an open ticket of the sender's client from the last week - a reply on it when they are
|
|
// its contact or watching it. From anyone else at the client it is a ticket of its own, linked to that one as related
|
|
// (linkSimilarTicket()): two people with "Printer not working" in a week used to land on one ticket
|
|
$similar_ticket_id = 0;
|
|
if (!$email_processed && strlen(trim($subject)) > 10) {
|
|
$contact_id = 0;
|
|
$client_id = 0;
|
|
|
|
// First: check if sender is a registered contact
|
|
$from_email_esc = mysqli_real_escape_string($mysqli, $from_email);
|
|
$contact_sql = mysqli_query($mysqli, "SELECT * FROM contacts WHERE contact_email = '$from_email_esc' AND contact_archived_at IS NULL LIMIT 1");
|
|
$contact_row = mysqli_fetch_assoc($contact_sql);
|
|
|
|
if ($contact_row) {
|
|
$contact_id = intval($contact_row['contact_id']);
|
|
$client_id = intval($contact_row['contact_client_id']);
|
|
} else {
|
|
// Else: check if sender domain is registered
|
|
$from_domain_esc = mysqli_real_escape_string($mysqli, $from_domain);
|
|
$domain_sql = mysqli_query($mysqli, "SELECT domain_client_id, domain_name FROM domains WHERE domain_name = '$from_domain_esc' AND domain_archived_at IS NULL LIMIT 1");
|
|
$domain_row = mysqli_fetch_assoc($domain_sql);
|
|
|
|
if ($domain_row && $from_domain == $domain_row['domain_name']) {
|
|
$client_id = intval($domain_row['domain_client_id']);
|
|
}
|
|
}
|
|
|
|
// If we found either a contact or a domain, check recent tickets for a matching subject
|
|
if ($client_id) {
|
|
$recent_tickets_sql = mysqli_query($mysqli,
|
|
"SELECT ticket_id, ticket_subject, ticket_contact_id
|
|
FROM tickets
|
|
WHERE ticket_client_id = $client_id AND ticket_resolved_at IS NULL
|
|
AND ticket_created_at >= DATE_SUB(NOW(), INTERVAL 7 DAY)"
|
|
);
|
|
|
|
while ($rowt = mysqli_fetch_assoc($recent_tickets_sql)) {
|
|
$existing_subject = $rowt['ticket_subject'];
|
|
|
|
// Calculate similarity percentage
|
|
similar_text(strtolower($subject), strtolower($existing_subject), $percent);
|
|
|
|
if ($percent >= 95) {
|
|
$similar_id = intval($rowt['ticket_id']);
|
|
$theirs = ($contact_id && $contact_id === intval($rowt['ticket_contact_id']))
|
|
|| mysqli_num_rows(mysqli_query($mysqli, "SELECT 1 FROM ticket_watchers WHERE watcher_ticket_id = $similar_id AND watcher_email = '$from_email_esc' LIMIT 1"));
|
|
if ($theirs) {
|
|
$email_processed = addReply($from_email, $date, $subject, $similar_id, $message_body, $attachments, $original_message_file, $email);
|
|
} else {
|
|
$similar_ticket_id = $similar_id;
|
|
}
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
// 4. A known, registered contact?
|
|
if (!$email_processed) {
|
|
$from_email_esc = mysqli_real_escape_string($mysqli, $from_email);
|
|
$any_contact_sql = mysqli_query($mysqli, "SELECT * FROM contacts WHERE contact_email = '$from_email_esc' AND contact_archived_at IS NULL LIMIT 1");
|
|
$rowc = mysqli_fetch_assoc($any_contact_sql);
|
|
|
|
if ($rowc) {
|
|
$contact_name = escapeSql($rowc['contact_name']);
|
|
$contact_id = intval($rowc['contact_id']);
|
|
$contact_email = escapeSql($rowc['contact_email']);
|
|
$client_id = intval($rowc['contact_client_id']);
|
|
|
|
$email_processed = addTicket($contact_id, $contact_name, $contact_email, $client_id, $date, $subject, $message_body, $attachments, $original_message_file, $copied, $email_message_id, $automatic);
|
|
}
|
|
}
|
|
|
|
// 5. A known domain?
|
|
if (!$email_processed) {
|
|
$from_domain_esc = mysqli_real_escape_string($mysqli, $from_domain);
|
|
$domain_sql = mysqli_query($mysqli, "SELECT domain_client_id, domain_name FROM domains WHERE domain_name = '$from_domain_esc' AND domain_archived_at IS NULL LIMIT 1");
|
|
$rowd = mysqli_fetch_assoc($domain_sql);
|
|
|
|
if ($rowd && $from_domain == $rowd['domain_name']) {
|
|
$client_id = intval($rowd['domain_client_id']);
|
|
|
|
// Create a new contact
|
|
$contact_name = $from_name;
|
|
$contact_email = $from_email;
|
|
mysqli_query($mysqli, "INSERT INTO contacts SET contact_name = '".mysqli_real_escape_string($mysqli, $contact_name)."', contact_email = '".mysqli_real_escape_string($mysqli, $contact_email)."', contact_notes = 'Added automatically via email parsing.', contact_client_id = $client_id");
|
|
$contact_id = mysqli_insert_id($mysqli);
|
|
|
|
logAudit("Contact", "Create", "Email parser: created contact " . mysqli_real_escape_string($mysqli, $contact_name), $client_id, $contact_id);
|
|
triggerCustomAction('contact_create', $contact_id);
|
|
|
|
$email_processed = addTicket($contact_id, $contact_name, $contact_email, $client_id, $date, $subject, $message_body, $attachments, $original_message_file, $copied, $email_message_id, $automatic);
|
|
}
|
|
}
|
|
|
|
// 6. Unknown sender allowed? A ticket with no client - a mail server's bounce never gets here
|
|
if (!$email_processed && $config_ticket_email_parse_unknown_senders) {
|
|
$email_processed = addTicket(0, $from_name, $from_email, 0, $date, $subject, $message_body, $attachments, $original_message_file, $copied, $email_message_id, $automatic);
|
|
}
|
|
|
|
// A new ticket whose subject is almost that of another's at the client, from someone else - linked as related
|
|
if ($similar_ticket_id && is_int($email_processed) && $email_processed > 0) {
|
|
linkSimilarTicket($email_processed, $similar_ticket_id);
|
|
}
|
|
|
|
|
|
// Flag/move based on processing result
|
|
if ($email_processed) {
|
|
$processed_count++; // increment first so a move failure doesn't hide the success
|
|
try {
|
|
$message->markSeen();
|
|
// Move to the top-level "ITFlow" folder
|
|
$message->move($targetFolderPath);
|
|
// optional: logApp("Cron-Email-Parser", "info", "Moved message to ITFlow");
|
|
} catch (\Throwable $e) {
|
|
$subj = (string)$message->subject();
|
|
$uid = $message->uid();
|
|
$path = $targetFolder->path();
|
|
logApp(
|
|
"Cron-Email-Parser",
|
|
"warning",
|
|
"Move failed (subject=\"$subj\", uid=$uid) to [$path]: ".$e->getMessage()
|
|
);
|
|
}
|
|
} else {
|
|
$unprocessed_count++;
|
|
try {
|
|
$message->markFlagged();
|
|
$message->unmarkSeen();
|
|
} catch (\Throwable $e) {
|
|
logApp("Cron-Email-Parser", "warning", "Flag update failed: ".$e->getMessage());
|
|
}
|
|
}
|
|
|
|
} catch (\Throwable $e) {
|
|
// One bad message must not kill the whole run - flag it for manual attention and continue
|
|
$unprocessed_count++;
|
|
logApp("Cron-Email-Parser", "warning", "Email parser failed to process message UID " . $message->uid() . ": " . $e->getMessage());
|
|
try {
|
|
$message->markFlagged();
|
|
$message->unmarkSeen();
|
|
} catch (\Throwable $e2) {
|
|
// ignore
|
|
}
|
|
}
|
|
|
|
// Cleanup temp .eml if still present (e.g., reply path)
|
|
if (isset($original_message_file)) {
|
|
$tmp_path = "../uploads/tmp/{$original_message_file}";
|
|
if (file_exists($tmp_path)) { @unlink($tmp_path); }
|
|
unset($original_message_file);
|
|
}
|
|
}
|
|
|
|
// Expunge & disconnect
|
|
try {
|
|
$inbox->expunge();
|
|
} catch (\Throwable $e) {
|
|
// ignore
|
|
}
|
|
$mailbox->disconnect();
|
|
|
|
// Execution timing (optional)
|
|
$script_end_time = microtime(true);
|
|
$execution_time = $script_end_time - $script_start_time;
|
|
$execution_time_formatted = number_format($execution_time, 2);
|
|
|
|
// What the run did, for whoever runs it by hand - not App Logs, where it was an entry a minute
|
|
// while mail came in. Each email processed is a ticket or a reply; one that isn't is left
|
|
// flagged and unread in the inbox, and one that failed outright was logged above
|
|
echo "Processed Emails: $processed_count\n";
|
|
echo "Unprocessed Emails: $unprocessed_count\n";
|
|
echo "Took $execution_time_formatted seconds\n";
|