mirror of
https://github.com/itflow-org/itflow
synced 2026-12-03 09:39:02 +00:00
Forwarded client emails: an email an agent forwards to the ticket mailbox is read from its forwarded part (Gmail, Outlook desktop and web, Apple Mail, Thunderbird, common European languages, or attached as an email) and becomes a ticket for the client whose email it is - their contact, a new contact at their domain, or no client for anyone else even with unknown senders off, who is then not answered or copied in - with what the agent wrote above it as their internal note and a history line saying who forwarded it, never a reply on a similar-subject ticket but linked as related, while ticket numbers, replies, colleagues' emails and forged ones are taken as before; Try an Email says so (functions/ticket_mail_forward.php); 26.12.4 changelog
This commit is contained in:
@@ -21,6 +21,7 @@ Update from Maintenance > Update as usual. This release has one database change,
|
||||
- Two-step sign-in no longer says "Your MFA session expired" right after the code is typed. The code boxes send the code on its sixth digit, so pressing Enter out of habit - or a password manager or phone keyboard sending it too, or a double click on Verify & Sign In - sent it a second time, and that second copy signed you out. Each form on the sign-in page now goes once, a second copy that still gets through takes you into ITFlow, and a wrong code sent twice says the code is wrong.
|
||||
- The two-step code can be typed up to five minutes after the password, up from two - time to find the phone and the right account in the authenticator app.
|
||||
- A password manager or phone that fills in the two-step code and sends the form itself signs you in, instead of going back to the email and password.
|
||||
- A client's email that one of your agents forwards to the ticket mailbox is now a ticket for that client, from the person who sent it, instead of a ticket for your own company or none at all. What the agent wrote above it is their internal note on the ticket, and its history says who forwarded it. Someone at a client's domain who isn't a contact yet is added as one; anyone else gets a ticket with no client for an agent to sort out - even with tickets from unknown senders off - and isn't sent anything or copied in. This works for forwards from Gmail, Outlook (desktop, the web and the new Outlook), Apple Mail and Thunderbird, and for an email forwarded as an attachment. A reply that quotes a client's email, an email with a ticket number in its subject, and an agent forwarding a colleague's email are taken as before, and Try an Email in Settings > Tickets says how an agent's forwards are read.
|
||||
|
||||
### Developer Updates
|
||||
|
||||
@@ -29,6 +30,7 @@ Update from Maintenance > Update as usual. This release has one database change,
|
||||
- `js/login_prevent_resubmit.js` lets each form on the sign-in page submit once (until the page comes back from history, or 10 seconds), and `js/otp_input.js` does the same for any form with a `data-otp-submit` code field - turning on MFA, the client portal's two-step setup and shared-link codes.
|
||||
- Saved cards expiring (DB 4.3.8): new `functions/card_expiry.php`. `cardExpiryNightly($now = null)`, called from `cron/nightly_tasks.php` before autopay, reads back from Stripe (`cardRefresh()`, PaymentMethods retrieve) up to `CARD_EXPIRY_CHECK_LIMIT` (200) cards a night whose expiry is from 6 months ago to next month and that weren't checked in 20 hours, keeping Stripe's brand, last four and expiry in `saved_payment_description` and stamping `saved_payment_checked_at`. It then finds cards on autopay for active recurring invoices (`cardAutopayCards()`) and, for an expiry within 30 days of its month starting (stage 1) or in or past its month (stage 2), emails the billing recipients (`billingMailCardExpiring()`), notifies the team (`Card Expiring`) and logs each recurring invoice's history, recording `saved_payment_reminded_expiry`, `saved_payment_reminded` and a random `saved_payment_update_key` that both stages' links share. `settings.config_invoice_card_expiry_reminders` (default 1) and `client_reminders` gate the email only. `guest/guest_card_update.php?card=&key=` reuses `js/guest_autopay_stripe.js` (its form's `data-checkout-url` now picks the endpoint): `guest_ajax.php?guest_card_update_checkout` starts a setup-mode Checkout Session on the client's Stripe customer (`cardUpdateCheckoutStart()`), and `guest_post.php?guest_card_update_done` runs `cardUpdateFinish()`, which checks the session's mode, card and customer first, saves the new card, repoints every `recurring_payments` row of the client's that used the old card, clears the key, and sends `billingMailCardUpdated()`. `billingCardParts()` gains `expires` (yyyymm), `billingStripeChargeSaved()` reads an expired-looking card back from Stripe before refusing it, and `autopayFailedNotify()` in `functions/billing_pay.php` sends the `Autopay Failed` notification from the nightly autopay's failure branches.
|
||||
- Texts: `smsInboxBulk($action, $ids, $user_id)` in `functions/sms.php` runs an action from `SMS_INBOX_BULK` (dismiss, spam, clear, not_spam, delete => the status it takes texts from and the permission it needs) on the ticked inbound texts, or with `$ids` null on the whole tab, inside `clientScopeSql()`. Spam and not spam block or unblock the numbers and move every text from them, as the single actions do. Clearing a code sets it to dismissed with its body, code and media wiped, so the text log's search can't find its words. `agent/post/texts.php` takes `bulk_texts` (with `sms_message_ids[]`) and `bulk_texts_all`, plus `sms_clear_code` for one code. `agent/texts.php` uses the standard `js/bulk_actions.js` select-all and Bulk Action button.
|
||||
- Forwarded client emails: new `functions/ticket_mail_forward.php`. In `cron/ticket_email_parser.php`, after the thread and ticket-number steps and before `ticketMailSenderContact()`, an email from an active agent (`ticketMailForwardAgent()`) that isn't forged, automatic or answered at its Reply-To goes to `ticketMailForwarded($html, $text, $subject, $attachments)`. It looks for the first header block - a From line with an address and a Sent, Date, To or Subject line beside it, with English and common European labels - below a forward line (Gmail's, Thunderbird's, Apple Mail's), or anywhere when the subject is a forward (`TICKET_MAIL_FORWARD_ONLY`); Outlook's `-----Original Message-----` and underscore line only count with a forward subject, as its replies have them too. The HTML is split at `gmail_quote`, `moz-forward-container`, `divRplyFwdMsg`/`appendonsend`, Outlook's bordered header div, `blockquote type="cite"` or the forward line, as long as the part from there holds the sender, else the text part is split; a single `message/rfc822` attachment is parsed with MailMimeParser, its cid pictures inlined. When the forwarded sender isn't one of your addresses, your domain or an agent (`ticketMailForwardFromClient()`), the parser takes its sender, subject (`ticketMailForwardSubject()`) and body and sets `$email['forward'] = ['agent', 'note']`. A forward is never a similar-subject reply (it is linked as related, `linkSimilarTicket(..., true)`), a contact it creates says who forwarded it, and step 6 runs for it whatever `config_ticket_email_parse_unknown_senders` says. `addTicket()` adds "forwarded by" to the from line and audit entry, calls `ticketMailForwardNote()` (an Internal reply by the agent, when there is a note, and a history line), and doesn't CC or answer a forwarded sender with no contact. Parser attachments now carry `mime`. `ticketMailTry()` adds a "From one of your agents?" step.
|
||||
|
||||
## [26.12.3]
|
||||
|
||||
|
||||
@@ -97,6 +97,8 @@ $read_mail_minutes = 60; // Mail someone opened before this got to it
|
||||
* via the address it was sent from, when it is taken as from its Reply-To (ticketMailReplyTo()) -
|
||||
* shown beside who it is from
|
||||
* picked the sender is a contact at more than one client (ticketMailSenderContact()) - said in a note
|
||||
* forward an agent forwarded it - ['agent' => ['user_id', 'user_name'], 'note' => what they wrote above it, HTML]
|
||||
* (functions/ticket_mail_forward.php): named beside who it is from, their note on the ticket by them
|
||||
* One from someone who isn't a contact ($contact_id 0) is answered without its own subject or a link to the
|
||||
* ticket: anyone can send an email from someone else's address, and the answer carried their words to them.
|
||||
* One with no sender address ($contact_email '') is answered by nobody. The new ticket's id.
|
||||
@@ -115,6 +117,7 @@ function addTicket($contact_id, $contact_name, $contact_email, $client_id, $date
|
||||
$dropped = (array) ($email['dropped'] ?? []);
|
||||
$forged = (string) ($email['forged'] ?? '');
|
||||
$via = (string) ($email['via'] ?? '');
|
||||
$forward = (array) ($email['forward'] ?? []);
|
||||
|
||||
// Atomically increment and get the new ticket number
|
||||
mysqli_query($mysqli, "
|
||||
@@ -141,6 +144,7 @@ function addTicket($contact_id, $contact_name, $contact_email, $client_id, $date
|
||||
// Wrap final formatted message
|
||||
$from_line = $contact_email_raw !== '' ? "<b>" . escapeHtml($contact_name_raw) . "</b> <" . escapeHtml($contact_email_raw) . ">" : '<b>No sender address</b>';
|
||||
$from_line .= $via !== '' ? ' - sent by ' . escapeHtml($via) : '';
|
||||
$from_line .= $forward ? ' - forwarded by ' . escapeHtml($forward['agent']['user_name']) : '';
|
||||
$message = "<i>Email from: $from_line at $date:-</i> <br><br><div style='line-height:1.5;'>$message</div>";
|
||||
|
||||
$ticket_prefix_esc = mysqli_real_escape_string($mysqli, $config_ticket_prefix);
|
||||
@@ -161,7 +165,8 @@ function addTicket($contact_id, $contact_name, $contact_email, $client_id, $date
|
||||
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);
|
||||
logAudit("Ticket", "Create", "Email parser: Client contact $contact_email_esc created ticket $ticket_prefix_esc$ticket_number ($subject) ($id)"
|
||||
. ($forward ? escapeSql(' - from an email ' . $forward['agent']['user_name'] . ' forwarded') : ''), $client_id, $id);
|
||||
|
||||
mkdirMissing('../uploads/tickets/');
|
||||
$att_dir = "../uploads/tickets/" . $id . "/";
|
||||
@@ -201,6 +206,11 @@ function addTicket($contact_id, $contact_name, $contact_email, $client_id, $date
|
||||
ticketMailForgedNote($id, $forged, $contact_email_raw, $copied);
|
||||
}
|
||||
|
||||
// Forwarded by an agent - what they wrote above it, their note on the ticket, and the history saying who
|
||||
if ($forward) {
|
||||
ticketMailForwardNote($id, $forward['agent'], (string) ($forward['note'] ?? ''), $contact_email_raw);
|
||||
}
|
||||
|
||||
// From a contact at more than one client - which it went to, and the others
|
||||
ticketMailSenderContactNote($id, $contact_email_raw, (array) ($email['picked'] ?? []));
|
||||
|
||||
@@ -208,8 +218,10 @@ function addTicket($contact_id, $contact_name, $contact_email, $client_id, $date
|
||||
ticketMailFilesLeftOut($id, $dropped);
|
||||
|
||||
// The person whose email raised a ticket with no contact is its CC, so its emails reach them - a website form's visitor, at
|
||||
// a client's domain or none - not when it was forged
|
||||
if (!$contact_id && $forged === '' && $contact_email_raw !== '' && !preg_match($bad_pattern, $contact_email_esc)) {
|
||||
// a client's domain or none - not when it was forged, nor when an agent forwarded it: someone who isn't a client's, sent
|
||||
// in to be looked at - a phishing email, a vendor's - is only answered once an agent gives the ticket its contact
|
||||
$forward_stranger = $forward && !$contact_id;
|
||||
if (!$contact_id && $forged === '' && !$forward_stranger && $contact_email_raw !== '' && !preg_match($bad_pattern, $contact_email_esc)) {
|
||||
mysqli_query($mysqli, "INSERT INTO ticket_ccs SET ticket_cc_email = '$contact_email_esc', ticket_cc_ticket_id = $id");
|
||||
}
|
||||
|
||||
@@ -224,7 +236,7 @@ function addTicket($contact_id, $contact_name, $contact_email, $client_id, $date
|
||||
// already. Someone who isn't a contact is told without their own subject or the ticket's link (above)
|
||||
$contact_wants = !$contact_id || ticketContactWantsEmail(getFieldById('contacts', intval($contact_id), 'contact_ticket_emails'), 'created');
|
||||
if ($config_ticket_client_general_notifications == 1 && $contact_email_raw !== '' && !preg_match($bad_pattern, $contact_email) && $contact_wants && $automatic === '' && $forged === ''
|
||||
&& ticketMailAnswersLeft($contact_email_raw)) {
|
||||
&& !$forward_stranger && ticketMailAnswersLeft($contact_email_raw)) {
|
||||
ticketMailCreated($id, [], false, 'email', [['email' => $contact_email_raw, 'name' => $contact_name_raw]], !$contact_id);
|
||||
}
|
||||
|
||||
@@ -320,14 +332,15 @@ function addBounce($message, array $headers, $from_email, $subject, $take_all =
|
||||
* someone who isn't its contact or a CC on 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) {
|
||||
function linkSimilarTicket($new_id, $similar_id, $forwarded = false) {
|
||||
$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"));
|
||||
logTicketHistory(intval($new_id), escapeSql("Its subject is almost the same as " . ticketReference($similar) . "'s, " . ($forwarded ? 'and an email an agent forwarded is a ticket of its own' : 'from someone else at the client')
|
||||
. " - linked as related, in case it is the same thing"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1179,7 +1192,7 @@ foreach ($messages as $message) {
|
||||
}
|
||||
|
||||
if (!$is_inline && $content !== '') {
|
||||
$attachments[] = ['name' => $name, 'content' => $content];
|
||||
$attachments[] = ['name' => $name, 'content' => $content, 'mime' => strtolower((string) $mime)];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1243,6 +1256,34 @@ foreach ($messages as $message) {
|
||||
$email_processed = addReply($from_email, $date, $subject, $subject_ticket['ticket_id'], $message_body, $attachments, $original_message_file, $email);
|
||||
}
|
||||
|
||||
// A client's email one of your agents forwarded to the mailbox - the client's, not the agent's: from here on it is from
|
||||
// whoever the forwarded part says, so it goes to the client whose email it is, and what the agent wrote above it is
|
||||
// their note on the ticket (functions/ticket_mail_forward.php). It was a ticket for your own company, or none.
|
||||
// Not a forged one - anyone can write an agent's address in a From line - nor a reply to a ticket (above): an agent's
|
||||
// email with a ticket's number is their note on it, as always. A colleague's email forwarded is the agent's, as before
|
||||
$forward = null;
|
||||
if (!$email_processed && !$asked_only && $forged === '' && $automatic === '' && !$answer
|
||||
&& ($forward_agent = ticketMailForwardAgent($from_raw))) {
|
||||
$forward = ticketMailForwarded(!empty($message_body_html) ? $message_body : '', (string) $message_body_text, stripslashes($subject), $attachments);
|
||||
if ($forward && ticketMailForwardFromClient($forward['email'])) {
|
||||
logApp("Cron-Email-Parser", "info", escapeSql("Email parser took an email " . $forward_agent['user_name'] . " forwarded (" . stripslashes($subject) . ") as from " . $forward['email']));
|
||||
$from_raw = $forward['email'];
|
||||
$from_email = escapeSql($from_raw);
|
||||
$from_name = escapeSql($forward['name'] !== '' ? $forward['name'] : 'Unknown');
|
||||
$from_domain = strtolower(substr($from_raw, strrpos($from_raw, '@') + 1));
|
||||
$subject = escapeSql(mb_substr($forward['subject'], 0, 500));
|
||||
if ($forward['html'] !== '') {
|
||||
$message_body = $forward['html'];
|
||||
}
|
||||
$via = '';
|
||||
$email['via'] = '';
|
||||
$email['from_name'] = $from_name;
|
||||
$email['forward'] = ['agent' => $forward_agent, 'note' => $forward['note']];
|
||||
} else {
|
||||
$forward = null;
|
||||
}
|
||||
}
|
||||
|
||||
// The sender's contact - at the client whose domain it is, when they are one at more than one (ticketMailSenderContact()) -
|
||||
// or the client whose domain it is. A website form's ($answer) is never a contact: its client only
|
||||
$picked = ticketMailSenderContact($from_raw, $from_domain);
|
||||
@@ -1293,7 +1334,8 @@ foreach ($messages as $message) {
|
||||
|
||||
if ($percent >= 95) {
|
||||
$similar_id = intval($rowt['ticket_id']);
|
||||
$theirs = !$answer && (($contact_id && $contact_id === intval($rowt['ticket_contact_id']))
|
||||
// Forwarded by an agent, it is a ticket of its own however alike - their note goes with a ticket
|
||||
$theirs = !$answer && !$forward && (($contact_id && $contact_id === intval($rowt['ticket_contact_id']))
|
||||
|| mysqli_num_rows(mysqli_query($mysqli, "SELECT 1 FROM ticket_ccs WHERE ticket_cc_ticket_id = $similar_id AND ticket_cc_email = '$from_email_esc' LIMIT 1")));
|
||||
if ($theirs) {
|
||||
$email_processed = addReply($from_email, $date, $subject, $similar_id, $message_body, $attachments, $original_message_file, $email);
|
||||
@@ -1331,7 +1373,8 @@ foreach ($messages as $message) {
|
||||
// $from_email come SQL-escaped, and escaped again, an O'Brien was saved as O\'Brien
|
||||
$contact_name = mysqli_real_escape_string($mysqli, rtrim(mb_substr(stripslashes($from_name), 0, 200)));
|
||||
$contact_email = $from_email;
|
||||
mysqli_query($mysqli, "INSERT INTO contacts SET contact_name = '$contact_name', contact_email = '$contact_email', contact_notes = 'Added automatically via email parsing.', contact_client_id = $client_id");
|
||||
$contact_notes = $forward ? escapeSql('Added from an email ' . $email['forward']['agent']['user_name'] . ' forwarded.') : 'Added automatically via email parsing.';
|
||||
mysqli_query($mysqli, "INSERT INTO contacts SET contact_name = '$contact_name', contact_email = '$contact_email', contact_notes = '$contact_notes', contact_client_id = $client_id");
|
||||
$contact_id = mysqli_insert_id($mysqli);
|
||||
|
||||
logAudit("Contact", "Create", "Email parser: created contact $contact_name", $client_id, $contact_id);
|
||||
@@ -1342,8 +1385,9 @@ foreach ($messages as $message) {
|
||||
}
|
||||
|
||||
// 6. Unknown sender allowed? A ticket with no client - a mail server's bounce never gets here. A website form's from its
|
||||
// visitor; one with no sender address from nobody, answered by nobody
|
||||
if (!$email_processed && !$asked_only && $config_ticket_email_parse_unknown_senders) {
|
||||
// visitor; one with no sender address from nobody, answered by nobody. One an agent forwarded is always taken: they
|
||||
// sent it in to be a ticket, and give it its client
|
||||
if (!$email_processed && !$asked_only && ($config_ticket_email_parse_unknown_senders || $forward)) {
|
||||
$email_processed = $answer
|
||||
? addTicket(0, $answer['name'], $answer['email'], 0, $date, $subject, $message_body, $attachments, $original_message_file, $email)
|
||||
: addTicket(0, $from_name, $from_email, 0, $date, $subject, $message_body, $attachments, $original_message_file, $email);
|
||||
@@ -1351,7 +1395,7 @@ foreach ($messages as $message) {
|
||||
|
||||
// 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);
|
||||
linkSimilarTicket($email_processed, $similar_ticket_id, (bool) $forward);
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -88,6 +88,7 @@ require_once __DIR__ . '/functions/ticket_helpers.php';
|
||||
require_once __DIR__ . '/functions/ticket_link.php';
|
||||
require_once __DIR__ . '/functions/ticket_pictures.php';
|
||||
require_once __DIR__ . '/functions/ticket_mail_thread.php';
|
||||
require_once __DIR__ . '/functions/ticket_mail_forward.php';
|
||||
require_once __DIR__ . '/functions/ticket_mail_auto.php';
|
||||
require_once __DIR__ . '/functions/user_timezone.php';
|
||||
require_once __DIR__ . '/functions/dispatch.php';
|
||||
|
||||
305
functions/ticket_mail_forward.php
Normal file
305
functions/ticket_mail_forward.php
Normal file
@@ -0,0 +1,305 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* ITFlow - a client's email an agent forwarded to the ticket mailbox (cron/ticket_email_parser.php).
|
||||
*
|
||||
* Forwarded, it comes from the agent, and was taken as theirs: a ticket for your own company - the agent is a
|
||||
* contact of it, or your domain is its - or one with no client, or nothing at all. Read from the forwarded part
|
||||
* instead, it is the client's: the ticket goes to the client whose email it is, by the same steps as one they
|
||||
* sent themselves - a contact, then a client's domain, then nobody's - and what the agent wrote above it is a
|
||||
* note on the ticket by them, not something the client reads.
|
||||
*
|
||||
* Inline forwards are found by the header block that starts the forwarded part - a From line with an address,
|
||||
* and a Sent, Date, To or Subject line beside it - after a line that says it is a forward ("---------- Forwarded
|
||||
* message ---------", "Begin forwarded message:", "-------- Forwarded Message --------"), or in an email whose subject
|
||||
* says it is one (Fwd:, FW:, WG:...). Outlook's forwards have no such line - its line of underscores and "-----Original
|
||||
* Message-----" are in its replies too, so a reply that quotes a client's email isn't taken for one. That is Gmail,
|
||||
* Outlook (desktop, the web and the new one), Apple Mail, Thunderbird and most others, in English and the usual European
|
||||
* languages. An email forwarded as an attachment is read from the attached email.
|
||||
*/
|
||||
|
||||
// What starts a forwarded email's subject - Fwd:, FW: and their other languages (Wg:, Tr:, Rv:, Enc:, Doorst:, Vs:,
|
||||
// Vb:, Pd:), and the reply ones after them, as "Fwd: RE: Printer" - all left out of the ticket's subject
|
||||
const TICKET_MAIL_FORWARD_SUBJECT = '/^\s*(?:(?:fwd?|fw|wg|tr|rv|enc|doorst|vs|vb|pd|re|aw|sv|antw|ref|r)\s*(?:\[\d+\])?\s*:\s*)+/iu';
|
||||
const TICKET_MAIL_FORWARD_ONLY = '/^\s*(?:fwd?|fw|wg|tr|rv|enc|doorst|vs|vb|pd)\s*(?:\[\d+\])?\s*:/iu';
|
||||
|
||||
// A line that says a forwarded email starts below it - Gmail's, Thunderbird's and Apple Mail's, in their languages
|
||||
const TICKET_MAIL_FORWARD_MARKERS = [
|
||||
'/^\s*-{2,}\s*(?:forwarded message|weitergeleitete nachricht|message transf(?:é|e)r(?:é|e)|mensaje reenviado|messaggio inoltrato|doorgestuurd bericht|vidarebefordrat meddelande|videresendt (?:meddelelse|melding)|wiadomo(?:ś|s)(?:ć|c) przekazana|mensagem encaminhada)\s*-{2,}\s*$/iu',
|
||||
'/^\s*(?:begin forwarded message|anfang der weitergeleiteten nachricht|d(?:é|e)but du message (?:r(?:é|e)exp(?:é|e)di(?:é|e)|r(?:é|e)envoy(?:é|e)|transf(?:é|e)r(?:é|e))|inicio del mensaje reenviado|inizio messaggio inoltrato)\s*:\s*$/iu',
|
||||
];
|
||||
|
||||
// A line above an email quoted in a forward or in a reply alike - Outlook's "-----Original Message-----" and its line of
|
||||
// underscores: where it starts, in an email whose subject says it is a forward, and nothing more - a reply quotes the same
|
||||
const TICKET_MAIL_FORWARD_QUOTE_MARKERS = [
|
||||
'/^\s*-{2,}\s*(?:original message|urspr(?:ü|ue)ngliche nachricht|message d\'origine|mensaje original|messaggio originale|oorspronkelijk bericht|ursprungligt meddelande|oprindelig meddelelse|opprinnelig melding|oryginalna wiadomo(?:ś|s)(?:ć|c)|mensagem original)\s*-{2,}\s*$/iu',
|
||||
'/^\s*_{10,}\s*$/',
|
||||
];
|
||||
|
||||
// The From line of a forwarded email's header block, and the lines beside it that make it one
|
||||
const TICKET_MAIL_FORWARD_FROM = '/^[\s>*]*(?:from|von|de|da|van|fr(?:å|a)n|fra|od|l(?:ä|a)hett(?:ä|a)j(?:ä|a)|felad(?:ó|o)|от|kimden)\s*:\**\s*(.+)$/iu';
|
||||
const TICKET_MAIL_FORWARD_LABEL = '/^[\s>*]*(?:sent|date|to|subject|cc|gesendet|datum|an|betreff|envoy(?:é|e)|(?:à|a)|objet|enviado|fecha|para|asunto|inviato|data|oggetto|verzonden|aan|onderwerp|skickat|till|(?:ä|a)mne|sendt|til|emne|wys(?:ł|l)ano|do|temat|l(?:ä|a)hetetty|vastaanottaja|aihe|elk(?:ü|u)ldve|c(?:í|i)mzett|t(?:á|a)rgy|отправлено|кому|тема|g(?:ö|o)nderildi|kime|konu|assunto)\s*:/iu';
|
||||
const TICKET_MAIL_FORWARD_SUBJECT_LABEL = '/^[\s>*]*(?:subject|betreff|objet|asunto|oggetto|onderwerp|(?:ä|a)mne|emne|temat|aihe|t(?:á|a)rgy|тема|konu|assunto)\s*:\**\s*(.*)$/iu';
|
||||
|
||||
/** The active agent whose address $email is - ['user_id', 'user_name'] - or null. */
|
||||
function ticketMailForwardAgent($email) {
|
||||
global $mysqli;
|
||||
$email = strtolower(trim((string) $email));
|
||||
if ($email === '' || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
|
||||
return null;
|
||||
}
|
||||
$row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT user_id, user_name FROM users WHERE user_email = '" . escapeSql($email) . "'
|
||||
AND user_type = 1 AND user_status = 1 AND user_archived_at IS NULL LIMIT 1"));
|
||||
return $row ? ['user_id' => intval($row['user_id']), 'user_name' => (string) $row['user_name']] : null;
|
||||
}
|
||||
|
||||
/** A forwarded email's subject without its Fwd: and Re: - "Fwd: RE: Printer offline" is "Printer offline". */
|
||||
function ticketMailForwardSubject($subject) {
|
||||
$subject = trim((string) preg_replace(TICKET_MAIL_FORWARD_SUBJECT, '', (string) $subject));
|
||||
return $subject !== '' ? $subject : 'No Subject';
|
||||
}
|
||||
|
||||
/** An email's HTML as text, a line for each line it shows - for finding the forwarded part's header block. */
|
||||
function ticketMailForwardText($html) {
|
||||
$html = (string) $html;
|
||||
$html = preg_replace('#<(script|style|head)\b[^>]*>.*?</\1>#is', '', $html) ?? $html;
|
||||
$html = preg_replace('#<img\b[^>]*>#i', '', $html) ?? $html;
|
||||
$html = preg_replace('#<br\s*/?>#i', "\n", $html);
|
||||
$html = preg_replace('#<hr\b[^>]*>#i', "\n__________\n", $html);
|
||||
$html = preg_replace('#</(p|div|tr|li|h[1-6]|blockquote|table|pre)>#i', "\n", $html);
|
||||
$text = html_entity_decode(strip_tags($html), ENT_QUOTES | ENT_HTML5, 'UTF-8');
|
||||
return str_replace(["\r\n", "\r", "\xC2\xA0"], ["\n", "\n", ' '], $text);
|
||||
}
|
||||
|
||||
/** The address and name in a header line's value - "Priya <p@x.com>", "Priya [mailto:p@x.com]", "p@x.com" - or null. */
|
||||
function ticketMailForwardAddress($value) {
|
||||
$value = trim((string) $value);
|
||||
if (!preg_match('/[A-Z0-9._%+\'-]+@[A-Z0-9.-]+\.[A-Z]{2,}/i', $value, $m)) {
|
||||
return null;
|
||||
}
|
||||
$email = strtolower($m[0]);
|
||||
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
|
||||
return null;
|
||||
}
|
||||
// The name is what comes before the address, its brackets and quotes taken off
|
||||
$name = trim((string) preg_replace('/\s*(?:<|\[mailto:|\(|<|mailto:)?\s*' . preg_quote($m[0], '/') . '.*$/i', '', $value));
|
||||
$name = trim($name, " \t\"'<>[]*,");
|
||||
if ($name === '' || strcasecmp($name, $email) === 0) {
|
||||
$name = '';
|
||||
}
|
||||
return ['email' => $email, 'name' => mb_substr($name, 0, 200)];
|
||||
}
|
||||
|
||||
/*
|
||||
* The header block a forwarded email starts with, in $text: ['email', 'name', 'subject', 'line' => the line it
|
||||
* starts at, 'marker' => the line above it that starts what was forwarded, or -1]. The first one from the top, the one
|
||||
* forwarded last. $forwarded: the subject says it is a forward (Fwd:, FW:), so a block with no line saying so counts too -
|
||||
* Outlook's has none, or one a reply has as well. Null without one.
|
||||
*/
|
||||
function ticketMailForwardBlock($text, $forwarded) {
|
||||
$lines = explode("\n", str_replace(["\r\n", "\r"], "\n", (string) $text));
|
||||
$count = count($lines);
|
||||
$marker = -1;
|
||||
$marker_says = false;
|
||||
for ($i = 0; $i < $count; $i++) {
|
||||
$line = $lines[$i];
|
||||
foreach ([[TICKET_MAIL_FORWARD_MARKERS, true], [TICKET_MAIL_FORWARD_QUOTE_MARKERS, false]] as [$patterns, $says]) {
|
||||
foreach ($patterns as $pattern) {
|
||||
if (preg_match($pattern, $line)) {
|
||||
$marker = $i;
|
||||
$marker_says = $says;
|
||||
continue 3;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!preg_match(TICKET_MAIL_FORWARD_FROM, $line, $m) || !($who = ticketMailForwardAddress($m[1]))) {
|
||||
continue;
|
||||
}
|
||||
// A header block: another header line beside the From one, not blank lines apart - and a line above saying it
|
||||
// is a forward, or a subject that does
|
||||
$start = $i;
|
||||
$labels = 0;
|
||||
$subject = '';
|
||||
for ($j = $i - 1; $j >= max(0, $i - 5) && trim($lines[$j]) !== ''; $j--) {
|
||||
if (preg_match(TICKET_MAIL_FORWARD_LABEL, $lines[$j])) {
|
||||
$labels++;
|
||||
$start = $j;
|
||||
}
|
||||
}
|
||||
for ($j = $i + 1; $j < min($count, $i + 7) && trim($lines[$j]) !== ''; $j++) {
|
||||
if (preg_match(TICKET_MAIL_FORWARD_LABEL, $lines[$j])) {
|
||||
$labels++;
|
||||
}
|
||||
}
|
||||
for ($j = $start; $j < min($count, $i + 7); $j++) {
|
||||
if (preg_match(TICKET_MAIL_FORWARD_SUBJECT_LABEL, $lines[$j], $s)) {
|
||||
$subject = trim($s[1]);
|
||||
break;
|
||||
}
|
||||
}
|
||||
$near_marker = $marker >= 0 && $start - $marker <= 4;
|
||||
if ($labels && (($near_marker && $marker_says) || $forwarded)) {
|
||||
return $who + ['subject' => $subject, 'line' => $start, 'marker' => $near_marker ? $marker : -1];
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/*
|
||||
* Where the forwarded part starts in an email's HTML - the agent's note above it, the client's email from it - or
|
||||
* -1. The containers mail apps put a forward in (Gmail's gmail_quote, Thunderbird's moz-forward-container,
|
||||
* Outlook's divRplyFwdMsg and its bordered header, Apple Mail's quote), or the tag holding the line that says
|
||||
* it is a forward. Only where the part from there has the forwarded email's sender in it.
|
||||
*/
|
||||
function ticketMailForwardHtmlSplit($html, $sender_email) {
|
||||
$html = (string) $html;
|
||||
$starts = [];
|
||||
foreach ([
|
||||
'#<div\b[^>]*\bclass=["\'][^"\']*\b(?:gmail_quote|moz-forward-container)\b#i',
|
||||
'#<div\b[^>]*\bid=["\'](?:divRplyFwdMsg|appendonsend)["\']#i',
|
||||
'#<div\b[^>]*style=["\'][^"\']*border-top:\s*solid\s+\#?[0-9a-f]{3,6}\s+1(?:\.0)?pt#i',
|
||||
'#<blockquote\b[^>]*\btype=["\']cite["\']#i',
|
||||
] as $pattern) {
|
||||
if (preg_match($pattern, $html, $m, PREG_OFFSET_CAPTURE)) {
|
||||
$starts[] = $m[0][1];
|
||||
}
|
||||
}
|
||||
// The tag holding a line that says it is a forward
|
||||
foreach (['#-{2,}\s*(?:forwarded message|original message|weitergeleitete nachricht|urspr(?:ü|ue)ngliche nachricht|message transf(?:é|e)r(?:é|e)|mensaje reenviado|messaggio inoltrato|doorgestuurd bericht)\s*-{2,}#iu',
|
||||
'#begin forwarded message\s*:#i'] as $pattern) {
|
||||
if (preg_match($pattern, $html, $m, PREG_OFFSET_CAPTURE)) {
|
||||
$before = substr($html, 0, $m[0][1]);
|
||||
$open = $m[0][1];
|
||||
if (preg_match_all('#<(?!/)(?:div|p|span|blockquote|font|td|b|strong)\b#i', $before, $tags, PREG_OFFSET_CAPTURE)) {
|
||||
$open = end($tags[0])[1];
|
||||
}
|
||||
$starts[] = $open;
|
||||
}
|
||||
}
|
||||
sort($starts);
|
||||
foreach (array_unique($starts) as $start) {
|
||||
if (stripos(html_entity_decode(strip_tags(substr($html, $start)), ENT_QUOTES | ENT_HTML5, 'UTF-8'), $sender_email) !== false) {
|
||||
// The line Outlook draws above it goes with it, not at the foot of the agent's note
|
||||
if (preg_match('#<hr\b[^>]*>\s*$#i', substr($html, 0, $start), $hr, PREG_OFFSET_CAPTURE)) {
|
||||
$start = $hr[0][1];
|
||||
}
|
||||
return $start;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
/** Whether a piece of an email's HTML says anything - not only line breaks, spaces and empty tags. */
|
||||
function ticketMailForwardSaysSomething($html) {
|
||||
$text = html_entity_decode(strip_tags(preg_replace('#<(script|style|head)\b[^>]*>.*?</\1>#is', '', (string) $html)), ENT_QUOTES | ENT_HTML5, 'UTF-8');
|
||||
return trim(str_replace("\xC2\xA0", ' ', $text)) !== '' || preg_match('#<img\b#i', (string) $html);
|
||||
}
|
||||
|
||||
/*
|
||||
* The client's email an agent forwarded - from $html (the email's HTML, its pictures already in it) and $text (its
|
||||
* plain text part), or an email attached to it ($attachments: ['name', 'content', 'mime']): ['email', 'name' => who
|
||||
* it is from, 'subject' => its own subject, for the ticket, 'html' => it, the ticket's details, 'note' => what the
|
||||
* agent wrote above it ('' when nothing), 'how' => 'inline' or 'attached', 'attachment' => the attached one's index].
|
||||
* Null when nothing in it is forwarded. $subject is the email's own.
|
||||
*/
|
||||
function ticketMailForwarded($html, $text, $subject, array $attachments = []) {
|
||||
$html = (string) $html;
|
||||
$text = (string) $text;
|
||||
$forwarded = (bool) preg_match(TICKET_MAIL_FORWARD_ONLY, (string) $subject);
|
||||
|
||||
// Inline: the plain text part first, as the sender's app wrote it, then the HTML read as text
|
||||
$block = null;
|
||||
$in_text = false;
|
||||
if (trim($text) !== '' && ($block = ticketMailForwardBlock($text, $forwarded))) {
|
||||
$in_text = true;
|
||||
} elseif ($html !== '') {
|
||||
$block = ticketMailForwardBlock(ticketMailForwardText($html), $forwarded);
|
||||
}
|
||||
if ($block) {
|
||||
$subject_out = ticketMailForwardSubject($block['subject'] !== '' ? $block['subject'] : $subject);
|
||||
$split = $html !== '' ? ticketMailForwardHtmlSplit($html, $block['email']) : -1;
|
||||
if ($split >= 0) {
|
||||
$note = substr($html, 0, $split);
|
||||
return ['email' => $block['email'], 'name' => $block['name'], 'subject' => $subject_out, 'html' => substr($html, $split),
|
||||
'note' => ticketMailForwardSaysSomething($note) ? $note : '', 'how' => 'inline', 'attachment' => -1];
|
||||
}
|
||||
// No container to split the HTML at - the plain text, split at its header block (or the line above it)
|
||||
$source = $in_text ? $text : ticketMailForwardText($html);
|
||||
$lines = explode("\n", str_replace(["\r\n", "\r"], "\n", $source));
|
||||
$from_line = $block['marker'] >= 0 ? $block['marker'] : $block['line'];
|
||||
$note = trim(implode("\n", array_slice($lines, 0, $from_line)));
|
||||
$original = trim(implode("\n", array_slice($lines, $from_line)));
|
||||
return ['email' => $block['email'], 'name' => $block['name'], 'subject' => $subject_out, 'html' => nl2br(escapeHtml($original)),
|
||||
'note' => $note !== '' ? nl2br(escapeHtml($note)) : '', 'how' => 'inline', 'attachment' => -1];
|
||||
}
|
||||
|
||||
// Forwarded as an attachment - Outlook's Forward as Attachment, or an .eml dragged in: one attached email, read
|
||||
$attached = [];
|
||||
foreach ($attachments as $index => $attachment) {
|
||||
$mime = strtolower((string) ($attachment['mime'] ?? ''));
|
||||
if ($mime === 'message/rfc822' || strtolower(pathinfo((string) ($attachment['name'] ?? ''), PATHINFO_EXTENSION)) === 'eml') {
|
||||
$attached[] = $index;
|
||||
}
|
||||
}
|
||||
if (count($attached) !== 1 || !class_exists('\ZBateson\MailMimeParser\Message')) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
$inner = \ZBateson\MailMimeParser\Message::from((string) $attachments[$attached[0]]['content'], false);
|
||||
$from = $inner->getHeader('From');
|
||||
$who = $from ? ticketMailForwardAddress(trim(($from->getPersonName() ?? '') . ' <' . ($from->getEmail() ?? '') . '>')) : null;
|
||||
if (!$who) {
|
||||
return null;
|
||||
}
|
||||
if ($from->getPersonName()) {
|
||||
$who['name'] = mb_substr(trim((string) $from->getPersonName()), 0, 200);
|
||||
}
|
||||
$inner_html = (string) $inner->getHtmlContent();
|
||||
$inner_text = (string) $inner->getTextContent();
|
||||
$body = $inner_html !== '' ? $inner_html : ($inner_text !== '' ? nl2br(escapeHtml($inner_text)) : '');
|
||||
// Its pictures, in it as the email showed them
|
||||
foreach ($inner->getAllAttachmentParts() as $part) {
|
||||
$cid = trim((string) $part->getContentId(), '<>');
|
||||
$type = strtolower((string) $part->getContentType());
|
||||
if ($cid !== '' && str_starts_with($type, 'image/') && $inner_html !== '') {
|
||||
$body = str_replace(["cid:$cid", "cid:<$cid>"], "data:$type;base64," . base64_encode((string) $part->getBinaryContentStream()), $body);
|
||||
}
|
||||
}
|
||||
} catch (\Throwable $e) {
|
||||
return null;
|
||||
}
|
||||
$note = $html !== '' ? $html : ($text !== '' ? nl2br(escapeHtml($text)) : '');
|
||||
return ['email' => $who['email'], 'name' => $who['name'], 'subject' => ticketMailForwardSubject((string) ($inner->getSubject() ?? '') !== '' ? $inner->getSubject() : $subject),
|
||||
'html' => $body, 'note' => ticketMailForwardSaysSomething($note) ? $note : '', 'how' => 'attached', 'attachment' => $attached[0]];
|
||||
}
|
||||
|
||||
/*
|
||||
* Whether a forwarded email's sender is a client's - not one of your own addresses, an agent, or someone at your own
|
||||
* domain: an agent forwarding a colleague's email, or a notice ITFlow sent, is theirs as before.
|
||||
*/
|
||||
function ticketMailForwardFromClient($email) {
|
||||
$email = strtolower(trim((string) $email));
|
||||
return $email !== '' && !emailOwnAddress($email) && !emailOwnDomain($email) && !ticketMailForwardAgent($email);
|
||||
}
|
||||
|
||||
/*
|
||||
* The agent's note on a ticket raised from an email they forwarded - what they wrote above it, as an internal note by
|
||||
* them - and the ticket's history saying who forwarded it. $note is HTML ('' when they wrote nothing).
|
||||
*/
|
||||
function ticketMailForwardNote($ticket_id, array $agent, $note, $from_email) {
|
||||
global $mysqli;
|
||||
$ticket_id = intval($ticket_id);
|
||||
if (!$ticket_id) {
|
||||
return 0;
|
||||
}
|
||||
$note_id = 0;
|
||||
$note = trim((string) $note);
|
||||
if ($note !== '') {
|
||||
$note = preg_replace(['#<head\b[^>]*>.*?</head>#is', '/<!DOCTYPE[^>]*>/i', '/<meta[^>]*>/i', '/<\/?(html|head|body)[^>]*>/i'], '', $note) ?? $note;
|
||||
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 = " . intval($agent['user_id']) . ", ticket_reply_ticket_id = $ticket_id");
|
||||
$note_id = intval(mysqli_insert_id($mysqli));
|
||||
}
|
||||
logTicketHistory($ticket_id, escapeSql("Raised from an email from $from_email that " . $agent['user_name'] . " forwarded to the ticket mailbox" . ($note_id ? ' - their note is on the ticket' : '')));
|
||||
return $note_id;
|
||||
}
|
||||
@@ -19,6 +19,8 @@
|
||||
* ticket was given (ticketMailSubjectTicket()) - a reply on that ticket,
|
||||
* as whoever sent it is to the ticket (its contact or another of the
|
||||
* client's, an agent, a CC, or a stranger), or a closed one turned away;
|
||||
* - a client's email an agent forwarded is read as from the client it forwards (ticketMailForwarded()) - only
|
||||
* said here, where there is no email to read;
|
||||
* 3. a subject almost the same as an open ticket of the sender's client from
|
||||
* the last 7 days - a reply on that ticket from its contact or a CC, and
|
||||
* from anyone else at the client a new ticket linked to it as related;
|
||||
@@ -113,6 +115,12 @@ function ticketMailTry($from_email, $subject, $auto_reply = false) {
|
||||
? 'No - there is no ticket with the number in brackets, so it carries on'
|
||||
: 'No - it would be [' . $config_ticket_prefix . '123] somewhere in it'];
|
||||
|
||||
// An agent's: a client's email they forward is read as from the client - said, as there is no email here to read
|
||||
if ($forward_agent = ticketMailForwardAgent($from_email)) {
|
||||
$steps[] = ['From one of your agents?', 'Yes - ' . $forward_agent['user_name'] . '. A client\'s email they forward to the mailbox is read as from the client: its sender, subject and text go the steps below,'
|
||||
. ' and what ' . $forward_agent['user_name'] . ' wrote above it is their internal note on the ticket. One from someone who isn\'t a client\'s is a ticket with no client even when tickets from unknown senders are off, and they aren\'t answered or copied in. Anything else from them goes on as from them'];
|
||||
}
|
||||
|
||||
// The sender: a contact - at the client whose domain it is, when they are one at more than one - or the client whose domain it is
|
||||
$picked = ticketMailSenderContact($from_email, $domain);
|
||||
$contact = $picked['contact'];
|
||||
|
||||
Reference in New Issue
Block a user