Mail review stage 6: bulk email leaves out contacts marked Email bounced or unsubscribed and says who was left out; each bulk email has an Unsubscribe link and List-Unsubscribe headers for one-click unsubscribe, the link asks first and offers Subscribe Again, unsubscribing covers every contact with the address, and agents and the client portal can change it (database 4.3.0); Send at uses the agent's time zone; bounces of bulk email come back to the ticket mailbox when the mail server and domains allow it; each email in a queue run goes out with its own envelope sender instead of the first one's; 26.12.3 changelog

This commit is contained in:
johnnyq
2026-11-30 19:00:49 -05:00
parent e57faeeb3a
commit 6cec0b8574
19 changed files with 572 additions and 44 deletions

View File

@@ -6,7 +6,7 @@ This file documents all notable changes made to ITFlow.
### Upgrading to 26.12.3
Update from Maintenance > Update as usual - this release has eight database changes: 4.2.2 adds a table for passkeys and a setting to turn them on or off, 4.2.3 lets a document keep the Markdown it was written in, 4.2.4 lets a ticket keep its pictures as files, 4.2.5 adds identity providers, 4.2.6 keeps each ticket's email conversation together, 4.2.7 lets a reply from a CC say who sent it, 4.2.8 renames the watchers table for CCs, and 4.2.9 lets the mail queue go at a pace your mail host takes. The client portal's Microsoft 365 single sign-on becomes the first identity provider, for client contacts, and keeps its redirect address, so nothing changes in Microsoft Entra. Nothing else is required: passkeys are on, and no one has one until they add it. Pictures already inside tickets move to files in the background afterwards - the new Ticket Pictures job in Maintenance > Cron does a batch a minute, so an install with years of emailed screenshots may take a while, and tickets work as usual meanwhile. A passkey is made for your ITFlow's address (the one in config.php) and only works there, over HTTPS - if you move ITFlow to a new address, everyone adds theirs again. Watchers are called CCs now. Emails about a ticket go to its contact with the CCs copied in, rather than one each - Admin > Settings > Tickets has the switch, under Emails about a ticket.
Update from Maintenance > Update as usual - this release has nine database changes: 4.2.2 adds a table for passkeys and a setting to turn them on or off, 4.2.3 lets a document keep the Markdown it was written in, 4.2.4 lets a ticket keep its pictures as files, 4.2.5 adds identity providers, 4.2.6 keeps each ticket's email conversation together, 4.2.7 lets a reply from a CC say who sent it, 4.2.8 renames the watchers table for CCs, 4.2.9 lets the mail queue go at a pace your mail host takes, and 4.3.0 lets contacts unsubscribe from bulk email. The client portal's Microsoft 365 single sign-on becomes the first identity provider, for client contacts, and keeps its redirect address, so nothing changes in Microsoft Entra. Nothing else is required: passkeys are on, and no one has one until they add it. Pictures already inside tickets move to files in the background afterwards - the new Ticket Pictures job in Maintenance > Cron does a batch a minute, so an install with years of emailed screenshots may take a while, and tickets work as usual meanwhile. A passkey is made for your ITFlow's address (the one in config.php) and only works there, over HTTPS - if you move ITFlow to a new address, everyone adds theirs again. Watchers are called CCs now. Emails about a ticket go to its contact with the CCs copied in, rather than one each - Admin > Settings > Tickets has the switch, under Emails about a ticket.
### New Features & Updates
@@ -63,6 +63,10 @@ Update from Maintenance > Update as usual - this release has eight database chan
- Two people at a client raising the same problem in the same week - "Printer not working" - get a ticket each, linked as related, rather than the second email landing on the first person's ticket. It's still a reply on the ticket from its contact or a CC.
- A reply to a closed ticket is kept on it as an internal note instead of left in the mailbox, and the notice says so - to the agent it was assigned to, or the admins when nobody had it. The ticket isn't reopened. The client or CC is told it is closed, as before - but not someone with no part in the ticket, who learned nothing from a number they guessed.
- Mail queue: email goes out at a pace your mail host takes - 30 a minute to start, set under Pace in Admin > Settings > Mail, Sending - over one connection - password links and invites first, email from the contacts or clients list last. A host's limit doesn't lose email any more: the rest wait their turn. A failed email is tried again over about eight hours, sooner at first. An address the mail server says doesn't exist isn't tried again, and its contact shows Email bounced; turned away for any other reason - the server's own rules, a full mailbox - an email is tried again. A mail server ITFlow can't reach or sign in to costs no email a try - it waits, and goes once it can. Admins hear about the queue once an hour at most, where every agent got a notice for each failed email.
- Bulk email (Email on the contacts or clients list) leaves out contacts marked Email bounced, and those who unsubscribed - the message after sending says how many, and the Email window says so before you send to the contacts picked. Each email has an Unsubscribe link at its foot, and mail programs show their own Unsubscribe button for it (List-Unsubscribe, one click), which Gmail and Yahoo ask of anyone sending in bulk. Leaving is about the address: every contact with it stops getting bulk email, at any client - ticket emails, invoices and quotes still go.
- Unsubscribing: the link asks first, then says it's done and offers Subscribe Again, so a link checker opening it changes nothing. A contact's page has Bulk email - Gets it or Unsubscribed, with Unsubscribe and Subscribe again for when they ask you - the contacts list and quick look show an Unsubscribed badge, and in the client portal Your account has News from us under Emails from us.
- Bulk email's Send at is on the agent's own clock (Account > Preferences), and the window says so when it isn't the company's - 9:00 typed in Tokyo was sent at 9:00 New York time.
- Bounces of bulk email come back to the mailbox ITFlow reads, where the contacts are marked Email bounced - when that can be done safely: email to ticket on, mail going by SMTP rather than Microsoft Graph, ITFlow signing in as that mailbox or not at all, and the email from the same domain. They went to the mailbox it was sent from, which ITFlow doesn't read. The Email window says where they go for the mailbox picked.
- Every email has a plain text part beside its HTML, and names the machine sending it by ITFlow's own address rather than the server's own name ("vm", say) - both counted against an email with spam filters.
- Email-to-ticket checks who an email is really from, by what your mail server found as it arrived (SPF, DKIM and DMARC). An email that failed - DMARC for a domain that asks for forged email to be rejected or quarantined, or SPF with nothing else passing - is treated as from a stranger, whoever it says it's from: a reply is an internal note saying which check failed and reopens nothing, adds nobody and goes to nobody; a new email still makes a ticket, with a note, but copies nobody in, gets no answer and isn't emailed to the client's colleagues who hear about new tickets; it never makes a contact; and it doesn't clear an address's Email bounced. An email that says it's from one of your agents isn't taken as their note. A domain that asks nothing of forged email (DMARC p=none) is taken as before.
- Email-to-ticket: someone who isn't a contact is answered "[TCK-123] We have your email", without their own subject or a link to the ticket, which shows what they wrote. Anyone can send an email that says it's from someone else, and the answer carried their words to that person from your mailbox.
@@ -93,6 +97,7 @@ Update from Maintenance > Update as usual - this release has eight database chan
- Mail queue: an email whose To address went but one of the people copied in was turned away was sent to everyone again, up to three more times. It goes once now, and says who was turned away.
- Email-to-ticket: an email with no sender address was answered at itflow-guest@example.com, which was also made the ticket's CC - each email to it failed in the mail queue. It's from nobody now: a ticket with no client when unknown senders are let in, saying it has no sender address, with nobody answered or copied in, and on a ticket an internal note that reopens nothing - it matched a contact with no email address before.
- Email-to-ticket: an address that's a contact at more than one client - someone who works for two, a shared mailbox - raised its tickets at whichever client the database gave first. It's the client whose domain it's at now, else the one they last raised a ticket at, and a note on the ticket names the others, to change its client if it's theirs.
- Mail queue: every email in a run went out with the first one's sender as its envelope sender - where bounces go - so an invoice sent after a ticket email bounced to the ticket mailbox, and a mail server that checks who may send as whom could turn it away. Each goes as itself now.
### Developer Updates
@@ -147,6 +152,7 @@ Update from Maintenance > Update as usual - this release has eight database chan
- Mail review stage 3: ticketMailSenderCheck() (functions/ticket_mail_auto.php) reads the topmost Authentication-Results - the receiving server's - and answers why it failed, or '': dmarc=fail with p= or policy= reject or quarantine, or Microsoft 365's action reject, oreject or quarantine; or spf=fail with no dkim=pass and no dmarc result; never with arc=pass or compauth=pass. Only a failure is acted on, so a pass a sender writes in gains nothing. cron/ticket_email_parser.php keeps it as the email's forged: addReply() makes a forged email a stranger's, with its own note, history and audit line; addTicket() takes $email (copied, message_id, automatic, dropped, forged) in place of its last four arguments, writes ticketMailForgedNote() (functions/ticket_mail_thread.php) and leaves out the copied-in CCs, the client-less ticket's CC and the answer for a forged one; the domain match makes no contact from one. ticketMailCreated() takes a subject, as ticketMailSend()'s subject; a client-less emailed ticket is answered "[REF] We have your email".
- Mail review stage 4: a failed email is still being tried while it is under MAIL_QUEUE_TRIES and its last try is within MAIL_QUEUE_GIVE_UP_HOURS (24) - mailQueueRetryingSql(), mailQueueFailedSql() and mailQueueRetrying(), for the job, the tabs, an email's state, Cancel and the summary - so one given up on before the tries went from 4 to 8 stays Failed rather than being sent again, and Failed gives its own count of tries. mailQueueRefusedForGood() decides which refused recipients are for good: the enhanced codes 5.1.1, 5.1.2, 5.1.3, 5.1.6 and 5.1.10, or 550, 551 or 553 naming an unknown recipient from a server that gives none (MailQueueSmtp keeps code_ex). Any other refusal is tried again and counts toward the two-in-a-row stop. mailQueueNotifyAdmins() counts dismissed notices toward its hour. The job orders by email_bulk, then email_sensitive DESC.
- Mail review stage 5: cron/ticket_email_parser.php - an email with no From address is from '' rather than itflow-guest@example.com: addReply() takes it as a stranger's ($no_sender) and addTicket() makes no CC and sends no answer. contactBounceClearEmail() runs after ticketMailSenderCheck(), and only when it didn't fail. ticketMailReplyTo() (functions/ticket_mail_auto.php) reads Reply-To: one at From's domain is taken as the sender ($via, shown as "sent by"); else, when ticketMailSystemSender() says From is a no-reply or website address (TICKET_MAIL_SYSTEM_SENDERS) or there is none, it is $answer - steps 4 to 6 raise the ticket with contact_id 0 for it at the From contact's or domain's client, or none. addTicket() makes the sender a CC whenever there is no contact (was: no client), answers anyone not a contact through ticketMailCreated()'s new $stranger (no Subject row and no button - its last parameter was the subject), and skips ticketMailColleaguesNew() for a forged ticket or one with no contact. ticketMailSenderContact() (functions/ticket_mail_thread.php) picks the contact for steps 3 and 4 by the From domain's client, then the latest ticket, then contact_id, and ticketMailSenderContactNote() notes the others; Try an Email uses it. An agent's email whose To or Cc has the ticket's contact, a CC or another of the client's contacts (ticketMailClientAddresses()) is a Public reply - addReplyAgentToClient() fills ticket_reply_emailed_to, calls setTicketFirstResponse(), assigns it through ticketChangeAssignee() under ticketReplyAssigns() or moves New to Open, and fires reply_reply_agent_public. ticketNotifyOwner() (functions/ticket.php) puts a bell notice with the assigned agent or the admins (appNotifyUsers(), functions/logging.php) - for bounces and closed-ticket replies, where appNotify() told every agent - and ticketMailAssigneeReplied() goes to ticketMailUnassignedReplied() on a ticket nobody has: the new-ticket address, else that notice. That covers portal and text replies too.
- Mail review stage 6: database 4.3.0 adds contacts.contact_unsubscribed_at and settings.config_mail_unsubscribe_secret. functions/contact_unsubscribe.php signs each contact's link with an HMAC of the contact id and address (contactUnsubscribeToken(), the key made on first use), and contactUnsubscribeSet() takes every contact with the address out or back in; contactUnsubscribedAddresses() is checked at send time, so a contact added since at another client is out too. guest/unsubscribe.php asks on GET, acts on its form's POST, and takes RFC 8058's List-Unsubscribe=One-Click POST with no page. emailBulkRecipients() (functions/email.php) builds the recipients from contact rows - the bounced, the unsubscribed, no address and the same address left out and counted - each with an unsubscribe link (emailHtml()'s new unsubscribe field) and its own List-Unsubscribe and List-Unsubscribe-Post headers (emailQueue() recipients' headers, let through by MAIL_QUEUE_HEADERS); emailBulkPost() now takes contact rows and converts Send at with timezoneFromView(). sendQueueEmail() sets the envelope sender per email - setFrom(..., false) with Sender reset, as PHPMailer's setFrom() kept the first email's From as Sender for the whole kept-alive connection - and for email_bulk passes mailQueueReturnPath(), the read mailbox when ticket parsing is on, the provider isn't Graph sending, the SMTP username is empty or that mailbox, and the domains align; a MAIL FROM refusal sends it again from the From address and sets mailQueueReturnPathRefused() for the run. mailQueueBouncesTo() tells the Email window.
## [26.12.2]

View File

@@ -0,0 +1,27 @@
<?php
/*
* ITFlow - Database update to version 4.3.0 (from 4.2.9)
* Included by admin/database_updates.php - do not access directly
*
* Contacts can leave the email sent to many from the contacts or clients list (functions/contact_unsubscribe.php):
* contacts.contact_unsubscribed_at - when they did, by the link in one of those emails, in the client portal or
* through an agent; NULL while they get them. Ticket emails, invoices and the rest still go
* settings.config_mail_unsubscribe_secret - the key the links are signed with, made the first time one is needed
*
* Re-runnable: each column is added only where it isn't there.
*/
defined('FROM_DB_UPDATER') || die("Direct file access is not allowed");
$itflow_unsubscribe_columns = [
['contacts', 'contact_unsubscribed_at', "datetime DEFAULT NULL AFTER `contact_email_bounce`"],
['settings', 'config_mail_unsubscribe_secret', "varchar(64) DEFAULT NULL AFTER `config_mail_send_per_minute`"],
];
foreach ($itflow_unsubscribe_columns as [$itflow_table, $itflow_column, $itflow_definition]) {
$itflow_column_exists = mysqli_query($mysqli, "SELECT 1 FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = '$itflow_table' AND COLUMN_NAME = '$itflow_column' LIMIT 1");
if (!$itflow_column_exists || mysqli_num_rows($itflow_column_exists) === 0) {
mysqli_query($mysqli, "ALTER TABLE `$itflow_table` ADD `$itflow_column` $itflow_definition");
}
}

View File

@@ -28,7 +28,7 @@ enforceUserPermission('module_client');
$contact_id = intval($_GET['contact_id'] ?? 0);
$sql = mysqli_query($mysqli, "SELECT client_id, client_name, contact_archived_at, contact_billing, contact_client_id, contact_created_at,
contact_department, contact_email, " . contactBounceColumns() . ", contact_extension, contact_id, contact_important, contact_location_id, contact_mobile,
contact_department, contact_email, " . contactBounceColumns() . ", " . contactUnsubscribeColumns() . ", contact_extension, contact_id, contact_important, contact_location_id, contact_mobile,
contact_mobile_country_code, contact_name, contact_notes, contact_phone, contact_phone_country_code, contact_photo, contact_pin,
contact_primary, contact_technical, contact_title, contact_updated_at, contact_user_id,
contact_ticket_emails, contact_company_ticket_emails, location_archived_at, location_city, location_name, location_state, user_auth_method, user_token
@@ -432,6 +432,24 @@ if (!$can_support) {
</div>
<?php } ?>
</dd>
<?php if ($contact_email && contactUnsubscribeReady()) {
// Bulk email - Email on the contacts or clients list - left by its link, in the portal or here (functions/contact_unsubscribe.php)
$unsubscribed_at = contactUnsubscribed($contact_row) ?? (contactUnsubscribedAddresses([$contact_row['contact_email']])[strtolower(trim((string) $contact_row['contact_email']))] ?? null); ?>
<dt>Bulk email</dt>
<dd data-contact-bulk-email="<?= $unsubscribed_at !== null ? 'out' : 'in' ?>">
<?php if ($unsubscribed_at !== null) { ?>
<?= contactUnsubscribeBadge(['contact_unsubscribed_at' => $unsubscribed_at]) ?> <span class="small text-body-secondary"><?= escapeHtml(date('M j, Y', strtotime($unsubscribed_at))) ?></span>
<?php if (lookupUserPermission('module_client') >= 2) { ?>
<a class="small ms-2 d-print-none" href="post.php?contact_bulk_email=in&contact_id=<?= $contact_id ?>&csrf_token=<?= $_SESSION['csrf_token'] ?>" title="They asked to get them again">Subscribe again</a>
<?php } ?>
<?php } else { ?>
Gets it
<?php if (lookupUserPermission('module_client') >= 2) { ?>
<a class="small ms-2 d-print-none confirm-link" href="post.php?contact_bulk_email=out&contact_id=<?= $contact_id ?>&csrf_token=<?= $_SESSION['csrf_token'] ?>" data-confirm-text="<?= $contact_email ?> won't get bulk email - Email on the contacts or clients list. Ticket emails and invoices still go." title="They asked not to get it">Unsubscribe</a>
<?php } ?>
<?php } ?>
</dd>
<?php } ?>
<?php if ($contact_portal || $contact_row['contact_ticket_emails'] !== 'all' || $contact_row['contact_company_ticket_emails'] !== 'none') { ?>
<dt>Ticket emails</dt>
<dd>

View File

@@ -153,7 +153,7 @@ if ($invites_view) {
}
} else {
$sql = mysqli_query($mysqli, "SELECT SQL_CALC_FOUND_ROWS contacts.contact_id, contact_archived_at, contact_billing, contact_client_id,
contact_department, contact_email, " . contactBounceColumns() . ", contact_extension, contact_important, contact_location_id, contact_mobile,
contact_department, contact_email, " . contactBounceColumns() . ", " . contactUnsubscribeColumns() . ", contact_extension, contact_important, contact_location_id, contact_mobile,
contact_mobile_country_code, contact_name, contact_phone, contact_phone_country_code, contact_photo, contact_primary,
contact_technical, contact_title, contact_user_id, client_id, client_name, location_archived_at, location_name, user_auth_method
FROM contacts
@@ -631,7 +631,7 @@ $search_title = $invites_view ? 'Email, name or client' : 'Name, title, email, p
<div class="text-nowrap"><i class="fas fa-fw fa-mobile-alt text-body-secondary me-1" title="Mobile"></i><?= $contact_mobile_link ?></div>
<?php } ?>
<?php if ($contact_email) { ?>
<div class="text-nowrap"><i class="far fa-fw fa-envelope text-body-secondary me-1" title="Email"></i><a class="text-reset" href="mailto:<?= $contact_email ?>"><?= $contact_email ?></a><button type="button" class="itflow-copy clipboardjs" title="Copy email" data-clipboard-text="<?= $contact_email ?>"><i class="far fa-copy"></i></button> <?= contactBounceBadge($row) ?></div>
<div class="text-nowrap"><i class="far fa-fw fa-envelope text-body-secondary me-1" title="Email"></i><a class="text-reset" href="mailto:<?= $contact_email ?>"><?= $contact_email ?></a><button type="button" class="itflow-copy clipboardjs" title="Copy email" data-clipboard-text="<?= $contact_email ?>"><i class="far fa-copy"></i></button> <?= contactBounceBadge($row) ?> <?= contactUnsubscribeBadge($row) ?></div>
<?php } ?>
<?php if (!$contact_phone_link && !$contact_mobile_link && !$contact_email) { ?>
<span class="text-body-secondary">-</span>

View File

@@ -5,7 +5,9 @@
* the mailbox it comes from, the name it shows, the subject, the message, a
* greeting, and when to send it. They post what emailBulkSend() takes
* (functions/email.php) - the email goes out in the email look, with the
* logo and the company's details.
* logo and the company's details, and a link to unsubscribe. Under From,
* where its bounces go (mailQueueBouncesTo()); Send at is on the agent's
* own clock (functions/user_timezone.php).
*
* Should not be accessed directly.
*/
@@ -13,6 +15,11 @@
isset($mysqli) || die("Direct file access is not allowed");
$bulk_mailboxes = emailMailboxes();
$bulk_bounces = [];
foreach ($bulk_mailboxes as $key => $box) {
$bulk_bounces[$key] = mailQueueBouncesTo($box['email']);
}
$bulk_reads = (string) ($config_imap_username ?? '');
?>
@@ -29,10 +36,13 @@ $bulk_mailboxes = emailMailboxes();
<span class="input-group-text"><i class="fas fa-fw fa-inbox"></i></span>
<select class="form-select" name="mailbox" required>
<?php foreach ($bulk_mailboxes as $key => $box) { ?>
<option value="<?= $key ?>" data-name="<?= escapeHtml($box['name']) ?>"><?= escapeHtml($box['label'] . ' - ' . $box['email']) ?></option>
<option value="<?= $key ?>" data-name="<?= escapeHtml($box['name']) ?>" data-bounces="<?= escapeHtml($bulk_bounces[$key]['address']) ?>" data-bounces-read="<?= $bulk_bounces[$key]['read'] ? 1 : 0 ?>"><?= escapeHtml($box['label'] . ' - ' . $box['email']) ?></option>
<?php } ?>
</select>
</div>
<!-- Where its bounces go - read, they mark their contacts Email bounced (functions/mail_queue.php, mailQueueReturnPath()) -->
<div class="form-text" data-bulk-bounces-read hidden>Bounces come back to <span data-bulk-bounces-to></span>, where ITFlow marks the contacts Email bounced.</div>
<div class="form-text" data-bulk-bounces-unread hidden>Bounces go to <span data-bulk-bounces-to></span>, which ITFlow doesn't read<?= $config_ticket_email_parse && filter_var($bulk_reads, FILTER_VALIDATE_EMAIL) ? ' - from ' . escapeHtml($bulk_reads) . ', they would be' : '' ?>.</div>
</div>
<div class="col-sm-6">
<label class="form-label">Name it shows</label>
@@ -64,25 +74,40 @@ $bulk_mailboxes = emailMailboxes();
<label class="form-label">Send at</label>
<div class="input-group">
<span class="input-group-text"><i class="fas fa-fw fa-calendar"></i></span>
<input type="datetime-local" class="form-control" name="queued_at">
<input type="datetime-local" class="form-control" name="queued_at" min="<?= escapeHtml(substr(timezoneNow(), 0, 16)) ?>">
</div>
<div class="form-text">Leave it empty to send now.</div>
<?= timezoneFormHint() ?>
</div>
<div class="col-12">
<div class="form-text mt-0"><i class="fas fa-fw fa-info-circle me-1"></i>Contacts marked Email bounced, and those who unsubscribed, are left out. Each email has a link to unsubscribe from email like this - ticket emails and invoices still go.</div>
</div>
</div>
<script>
itflowReady(function () {
// The name follows the mailbox, until it is typed over
// The name follows the mailbox, until it is typed over - and the line under it says where its bounces go
document.querySelectorAll('select[name="mailbox"]').forEach(function (select) {
var form = select.closest('form');
var name = form.querySelector('input[name="mail_from_name"]');
var last = name.value;
var bounces = function () {
var option = select.options[select.selectedIndex];
var read = option && option.getAttribute('data-bounces-read') === '1';
form.querySelector('[data-bulk-bounces-read]').hidden = !option || !read;
form.querySelector('[data-bulk-bounces-unread]').hidden = !option || read;
form.querySelectorAll('[data-bulk-bounces-to]').forEach(function (to) {
to.textContent = option ? option.getAttribute('data-bounces') : '';
});
};
bounces();
select.addEventListener('change', function () {
var picked = select.options[select.selectedIndex].getAttribute('data-name') || '';
if (name.value === last) {
name.value = picked;
}
last = picked;
bounces();
});
});
});

View File

@@ -19,7 +19,7 @@ enforceUserPermission('module_client');
$contact_id = intval($_GET['id'] ?? 0);
$contact_row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT contact_archived_at, contact_billing, contact_client_id, contact_department,
contact_email, " . contactBounceColumns() . ", contact_extension, contact_id, contact_important, contact_location_id, contact_mobile, contact_mobile_country_code,
contact_email, " . contactBounceColumns() . ", " . contactUnsubscribeColumns() . ", contact_extension, contact_id, contact_important, contact_location_id, contact_mobile, contact_mobile_country_code,
contact_name, contact_notes, contact_phone, contact_phone_country_code, contact_photo, contact_pin, contact_primary, contact_technical,
contact_title, contact_user_id, location_archived_at, location_name, user_auth_method
FROM contacts
@@ -168,6 +168,7 @@ ob_start();
<?php if ($contact_email) { ?>
<a class="btn btn-sm btn-outline-primary" href="mailto:<?= $contact_email ?>"><i class="far fa-envelope me-1"></i>Email</a>
<?= contactBounceBadge($contact_row) ?>
<?= contactUnsubscribeBadge($contact_row) ?>
<?php } ?>
</div>
</div>

View File

@@ -6,6 +6,26 @@ $contact_ids = array_map('intval', $_GET['contact_ids'] ?? []);
$count = count($contact_ids);
// Those picked who are left out - marked Email bounced, or unsubscribed (emailBulkRecipients())
$left_out = ['bounced' => 0, 'unsubscribed' => 0];
if ($contact_ids) {
$sql = mysqli_query($mysqli, "SELECT contact_email, " . contactBounceColumns() . ", " . contactUnsubscribeColumns() . " FROM contacts
WHERE contact_id IN (" . implode(',', $contact_ids) . ") AND contact_archived_at IS NULL");
$picked_rows = mysqli_fetch_all($sql, MYSQLI_ASSOC);
$left = contactUnsubscribedAddresses(array_column($picked_rows, 'contact_email'));
foreach ($picked_rows as $row) {
if (contactUnsubscribed($row) !== null || isset($left[strtolower(trim((string) $row['contact_email']))])) {
$left_out['unsubscribed']++;
} elseif (contactBounce($row) !== null) {
$left_out['bounced']++;
}
}
}
$left_out_text = implode(' and ', array_filter([
$left_out['bounced'] ? $left_out['bounced'] . ' marked Email bounced' : '',
$left_out['unsubscribed'] ? $left_out['unsubscribed'] . ' unsubscribed' : '',
]));
ob_start();
?>
@@ -18,6 +38,9 @@ ob_start();
<input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
<?php foreach ($contact_ids as $contact_id) { ?><input type="hidden" name="contact_ids[]" value="<?= $contact_id ?>"><?php } ?>
<div class="modal-body">
<?php if ($left_out_text !== '') { ?>
<div class="alert alert-info py-2 small" data-bulk-left-out><i class="fas fa-fw fa-user-slash me-2"></i>Left out: <?= escapeHtml($left_out_text) ?>.</div>
<?php } ?>
<?php require __DIR__ . '/../../includes/bulk_email_fields.php'; ?>
</div>

View File

@@ -872,21 +872,19 @@ if (isset($_POST['bulk_send_client_email']) && isset($_POST['client_ids'])) {
// Prepare client ID list for SQL
$client_ids_str = implode(',', $client_ids);
// The clients' contacts that match, not archived - emailBulkSend() sends each address once
$result = mysqli_query($mysqli, "SELECT contact_email, contact_name, client_name FROM contacts
// The clients' contacts that match, not archived - each address once, and not those who bounced or left (emailBulkRecipients())
$result = mysqli_query($mysqli, "SELECT contact_id, contact_email, contact_name, client_name, " . contactBounceColumns() . ", " . contactUnsubscribeColumns() . " FROM contacts
JOIN clients ON client_id = contact_client_id
WHERE contact_client_id IN ($client_ids_str) AND contact_archived_at IS NULL
$contact_filter_query
ORDER BY client_name ASC, contact_primary DESC, contact_name ASC");
$recipients = [];
$company_name = (string) (billingCompany()['company_name'] ?? '');
$rows = [];
while ($row = mysqli_fetch_assoc($result)) {
$recipients[] = ['email' => trim((string) $row['contact_email']), 'name' => (string) $row['contact_name'],
'footnote' => "You received this as a contact for {$row['client_name']} with $company_name."];
$rows[] = $row;
}
emailBulkPost($recipients, count($recipients));
emailBulkPost($rows);
}

View File

@@ -544,21 +544,19 @@ if (isset($_POST['send_bulk_mail_now'])) {
$contact_ids = array_values(array_filter(array_map('intval', (array) ($_POST['contact_ids'] ?? []))));
// Every contact picked - checked before anything is queued
$recipients = [];
$company_name = (string) (billingCompany()['company_name'] ?? '');
// Every contact picked - checked before anything is queued. Those who bounced or left are left out (emailBulkRecipients())
$rows = [];
foreach ($contact_ids as $contact_id) {
$row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT contact_client_id, contact_email, contact_name, client_name FROM contacts
$row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT contact_id, contact_client_id, contact_email, contact_name, client_name, " . contactBounceColumns() . ", " . contactUnsubscribeColumns() . " FROM contacts
JOIN clients ON client_id = contact_client_id WHERE contact_id = $contact_id AND contact_archived_at IS NULL"));
if (!$row) {
continue;
}
enforceClientAccess(intval($row['contact_client_id']));
$recipients[] = ['email' => trim((string) $row['contact_email']), 'name' => (string) $row['contact_name'],
'footnote' => "You received this as a contact for {$row['client_name']} with $company_name."];
$rows[] = $row;
}
emailBulkPost($recipients, count($contact_ids));
emailBulkPost($rows);
}
@@ -1002,6 +1000,36 @@ if (isset($_GET['clear_contact_bounce'])) {
}
// Out of bulk email, or back in - they asked (functions/contact_unsubscribe.php). Every contact with the address, as their link does
if (isset($_GET['contact_bulk_email'])) {
validateCSRFToken();
enforceUserPermission('module_client', 2);
$contact_id = intval($_GET['contact_id'] ?? 0);
$out = $_GET['contact_bulk_email'] === 'out';
$row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT contact_name, contact_email, contact_client_id FROM contacts WHERE contact_id = $contact_id"));
if (!$row) {
flashAlert('That contact no longer exists.', 'error');
redirect();
}
$client_id = intval($row['contact_client_id']);
enforceClientAccess();
$changed = contactUnsubscribeSet($row['contact_email'], $out);
if ($changed) {
logAudit("Contact", "Edit", "$session_name " . ($out ? 'unsubscribed ' : 'subscribed ') . escapeSql($row['contact_name'] . ' (' . $row['contact_email'] . ')') . ($out ? ' from' : ' again to') . " bulk email"
. ($changed > 1 ? " - $changed contacts with the address" : ''), $client_id, $contact_id);
}
flashAlert("<strong>" . escapeHtml($row['contact_name']) . "</strong> " . ($out ? "won't get bulk email - ticket emails and invoices still go" : 'gets bulk email again')
. ($changed > 1 ? " - and the other " . ($changed - 1) . " contact" . ($changed === 2 ? '' : 's') . " with " . escapeHtml($row['contact_email']) : ''));
redirect();
}
if (isset($_GET['archive_contact'])) {
validateCSRFToken();

View File

@@ -824,6 +824,15 @@ if (isset($_POST['portal_email_prefs'])) {
logAudit("Contact", "Edit", "Client contact $session_contact_name changed the ticket emails they get in the client portal", $session_client_id, $session_contact_id);
// Bulk email - every contact with their address, as the link in one does (functions/contact_unsubscribe.php)
if (contactUnsubscribeReady()) {
$my_email = (string) getFieldById('contacts', intval($session_contact_id), 'contact_email');
$bulk_out = empty($_POST['bulk_email']);
if (trim($my_email) !== '' && contactUnsubscribeSet($my_email, $bulk_out)) {
logAudit("Contact", "Edit", "Client contact $session_contact_name " . ($bulk_out ? 'unsubscribed from' : 'subscribed again to') . " bulk email in the client portal", $session_client_id, $session_contact_id);
}
}
flashAlert("Saved - those are the emails you will get");
redirect('profile.php#emails');

View File

@@ -23,7 +23,7 @@ require_once 'includes/inc_all.php';
$me = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT contact_name, contact_title, contact_department, contact_email, contact_extension, contact_location_id,
contact_mobile, contact_mobile_country_code, contact_phone, contact_phone_country_code, contact_pin, contact_billing, contact_technical, contact_primary,
contact_ticket_emails, contact_company_ticket_emails,
contact_ticket_emails, contact_company_ticket_emails, " . contactUnsubscribeColumns() . ",
location_name, location_address, location_city, location_state, location_zip, location_country
FROM contacts
LEFT JOIN locations ON location_id = contact_location_id AND location_client_id = $session_client_id AND location_archived_at IS NULL
@@ -187,6 +187,16 @@ $csrf = escapeHtml($_SESSION['csrf_token']);
<?php } ?>
</fieldset>
<?php } ?>
<?php if (contactUnsubscribeReady() && trim((string) ($me['contact_email'] ?? '')) !== '') { ?>
<!-- Bulk email - left by the link in one, here, or by us (functions/contact_unsubscribe.php) -->
<fieldset class="mb-3">
<legend class="form-label fs-6 fw-semibold">News from us</legend>
<div class="form-check">
<input class="form-check-input" type="checkbox" name="bulk_email" id="bulkEmail" value="1"<?= contactUnsubscribed($me) === null ? ' checked' : '' ?>>
<label class="form-check-label" for="bulkEmail">The emails we send to all our clients <span class="d-block small text-body-secondary">Notices and news - office closures, changes to our service. Each one has a link to stop them.</span></label>
</div>
</fieldset>
<?php } ?>
<?php if ($session_contact_is_billing_contact || $session_contact_primary) { ?>
<p class="small text-body-secondary">Invoices, quotes, receipts and statements go to <?= escapeHtml($session_client_name) ?>'s billing contacts - ask us if they should go somewhere else.</p>
<?php } ?>

View File

@@ -314,7 +314,7 @@ function mailQueueConnect(array $mailer): void {
* 'refused' => [address => [code, detail]] it turned away]. Throws for anything else that stopped it.
*/
function sendQueueEmail(array $mailer, string $from_email, string $from_name, string $to_email, string $to_name, string $subject, string $html_body,
string $ics_str, string $attachments_json, string $cc_json = '', string $headers_json = ''): array {
string $ics_str, string $attachments_json, string $cc_json = '', string $headers_json = '', string $return_path = ''): array {
/** @var PHPMailer $mail */
$mail = $mailer['mail'];
// The people copied in, and the headers that keep a ticket's conversation together (functions/mail_queue.php)
@@ -342,7 +342,12 @@ function sendQueueEmail(array $mailer, string $from_email, string $from_name, st
$smtp->refused = [];
}
$mail->setFrom($from_email, $from_name);
// The envelope sender - where a bounce goes: the From address, or the mailbox ITFlow reads for email sent to many
// (mailQueueReturnPath()). setFrom() made the first email's From the envelope sender of every email after it on the
// connection - one from the ticket mailbox, then an invoice whose bounce went there
$mail->Sender = '';
$mail->setFrom($from_email, $from_name, false);
$mail->Sender = $return_path;
$mail->addAddress($to_email, $to_name);
foreach ($cc as $person) {
$mail->addCC($person['email'], $person['name']);
@@ -421,6 +426,13 @@ function sendQueueEmail(array $mailer, string $from_email, string $from_name, st
}
// Part-way through - a new conversation for the next email
$mail->smtpClose();
// A mail server that won't take the mailbox ITFlow reads as the envelope sender - from the From address, as it always
// went, and the rest of the run too
if ($return_path !== '' && stripos($e->getMessage(), 'from address failed') !== false) {
mailQueueReturnPathRefused(true);
logApp("Cron-Mail-Queue", "Warning", "The mail server turned away " . escapeSql($return_path) . " as the envelope sender, so bounces of email to many go to " . escapeSql($from_email) . " this run: " . escapeSql($e->getMessage()));
return sendQueueEmail($mailer, $from_email, $from_name, $to_email, $to_name, $subject, $html_body, $ics_str, $attachments_json, $cc_json, $headers_json, '');
}
// PHPMailer names the step that failed ("data not accepted"); the mail server's reply says why - keep it with the email
$error = $smtp->getError();
$detail = trim(preg_replace('/\s+/', ' ', (string) ($error['detail'] ?? '')));
@@ -470,6 +482,7 @@ if ($orphaned_emails > 0) {
* ======================================================================= */
// The copied in and the headers - once the 4.2.6 update has made their columns
$thread_columns = ticketMailThreadReady() ? 'email_cc, email_headers' : "'' AS email_cc, '' AS email_headers";
$thread_columns .= mailQueuePaceReady() ? ', email_bulk' : ', 0 AS email_bulk';
$per_minute = mailQueuePerMinute();
$bulk_order = (mailQueuePaceReady() ? 'email_bulk, ' : '') . (mailQueueHasSensitive() ? 'email_sensitive DESC, ' : '');
@@ -531,7 +544,7 @@ while ($sql_queue && ($rowq = mysqli_fetch_assoc($sql_queue))) {
}
$result = sendQueueEmail($mailer, (string) $rowq['email_from'], (string) $rowq['email_from_name'], $email_recipient, (string) $rowq['email_recipient_name'],
(string) $rowq['email_subject'], (string) $rowq['email_content'], (string) $rowq['email_cal_str'], (string) $rowq['email_attachments'],
(string) $rowq['email_cc'], (string) $rowq['email_headers']);
(string) $rowq['email_cc'], (string) $rowq['email_headers'], intval($rowq['email_bulk']) ? mailQueueReturnPath((string) $rowq['email_from']) : '');
} catch (MailQueueUnreachable $e) {
// The mail server, not this email - it waits as it was, and the run stops: the rest would only fail the same way
mysqli_query($mysqli, "UPDATE email_queue SET email_status = $was WHERE email_id = $email_id AND email_status = 1");

2
db.sql
View File

@@ -1144,6 +1144,7 @@ CREATE TABLE `contacts` (
`contact_email` varchar(200) DEFAULT NULL,
`contact_email_bounced_at` datetime DEFAULT NULL,
`contact_email_bounce` varchar(255) DEFAULT NULL,
`contact_unsubscribed_at` datetime DEFAULT NULL,
`contact_phone_country_code` varchar(10) DEFAULT NULL,
`contact_phone` varchar(200) DEFAULT NULL,
`contact_extension` varchar(200) DEFAULT NULL,
@@ -4028,6 +4029,7 @@ CREATE TABLE `settings` (
`config_smtp_username` varchar(200) DEFAULT NULL,
`config_smtp_password` varchar(200) DEFAULT NULL,
`config_mail_send_per_minute` int(11) NOT NULL DEFAULT 30,
`config_mail_unsubscribe_secret` varchar(64) DEFAULT NULL,
`config_mail_from_email` varchar(200) DEFAULT NULL,
`config_mail_from_name` varchar(200) DEFAULT NULL,
`config_imap_provider` varchar(200) DEFAULT NULL,

View File

@@ -34,6 +34,7 @@ require_once __DIR__ . '/functions/archived.php';
require_once __DIR__ . '/functions/undo.php';
require_once __DIR__ . '/functions/contact.php';
require_once __DIR__ . '/functions/contact_bounce.php';
require_once __DIR__ . '/functions/contact_unsubscribe.php';
require_once __DIR__ . '/functions/software.php';
require_once __DIR__ . '/functions/software_template.php';
require_once __DIR__ . '/functions/location.php';

View File

@@ -0,0 +1,140 @@
<?php
/*
* ITFlow - contacts who don't want the email sent to many from the contacts or clients list (Email - functions/email.php,
* emailBulkSend()). Each of those emails has a link to leave them, in the email and in its List-Unsubscribe header, which
* mail programs show as their own Unsubscribe (RFC 8058, one click). The link (guest/unsubscribe.php) is signed for the
* contact and their address; leaving takes every contact with that address out (contact_unsubscribed_at, database 4.3.0).
* They can come back from the same link or Your account in the client portal, and an agent can do either on the contact.
* Ticket emails, invoices, quotes and the rest still go - this is only the email sent to many.
*/
/** Whether the 4.3.0 update has run - contacts.contact_unsubscribed_at and settings.config_mail_unsubscribe_secret. */
function contactUnsubscribeReady() {
global $mysqli;
static $ready = null;
if ($ready === null) {
if (defined('CURRENT_DATABASE_VERSION')) {
$version = CURRENT_DATABASE_VERSION;
} else {
$result = mysqli_query($mysqli, "SELECT config_current_database_version FROM settings WHERE company_id = 1");
$version = $result && ($row = mysqli_fetch_row($result)) ? (string) $row[0] : '0';
}
$ready = version_compare($version, '4.3.0', '>=');
}
return $ready;
}
/** The columns for a contact query - NULL before the update. */
function contactUnsubscribeColumns($alias = '') {
$prefix = $alias !== '' ? "$alias." : '';
return contactUnsubscribeReady() ? "{$prefix}contact_unsubscribed_at" : 'NULL AS contact_unsubscribed_at';
}
/** When the contact left the email sent to many, from a row - null while they get it. */
function contactUnsubscribed(array $row) {
return contactUnsubscribeReady() && !empty($row['contact_unsubscribed_at']) ? (string) $row['contact_unsubscribed_at'] : null;
}
/*
* Of $emails, the addresses that left - any contact with one, archived or not: it is about the address, and a contact
* added since, at another client say, or the same person added again, isn't a way back in. Lower case => when.
*/
function contactUnsubscribedAddresses(array $emails) {
global $mysqli;
$emails = array_values(array_unique(array_filter(array_map(function ($email) {
return strtolower(trim((string) $email));
}, $emails))));
if (!$emails || !contactUnsubscribeReady()) {
return [];
}
$out = [];
$sql = mysqli_query($mysqli, "SELECT LOWER(contact_email), MIN(contact_unsubscribed_at) FROM contacts WHERE contact_unsubscribed_at IS NOT NULL
AND LOWER(contact_email) IN ('" . implode("', '", array_map('escapeSql', $emails)) . "') GROUP BY LOWER(contact_email)");
while ($row = mysqli_fetch_row($sql)) {
$out[(string) $row[0]] = (string) $row[1];
}
return $out;
}
/** The "Unsubscribed" badge for a contact row - '' while they get the email sent to many. */
function contactUnsubscribeBadge(array $row) {
$at = contactUnsubscribed($row);
if ($at === null) {
return '';
}
return '<span class="badge rounded-pill bg-secondary-subtle text-secondary-emphasis border border-secondary-subtle fw-normal" title="'
. escapeHtml('Unsubscribed from bulk email (Email on the contacts or clients list) ' . date('M j, Y', strtotime($at)) . ' - ticket emails and invoices still go') . '">'
. '<i class="fas fa-bell-slash me-1"></i>Unsubscribed</span>';
}
/** The key the links are signed with - made and kept the first time one is needed. '' before the update. */
function contactUnsubscribeSecret() {
global $mysqli;
static $secret = null;
if ($secret !== null) {
return $secret;
}
if (!contactUnsubscribeReady()) {
return $secret = '';
}
$saved = (string) (mysqli_fetch_row(mysqli_query($mysqli, "SELECT config_mail_unsubscribe_secret FROM settings WHERE company_id = 1"))[0] ?? '');
if (strlen($saved) < 32) {
$made = bin2hex(random_bytes(32));
// Kept only if none was made meanwhile - two at once agree on the one saved
mysqli_query($mysqli, "UPDATE settings SET config_mail_unsubscribe_secret = '$made' WHERE company_id = 1 AND (config_mail_unsubscribe_secret IS NULL OR LENGTH(config_mail_unsubscribe_secret) < 32)");
$saved = (string) (mysqli_fetch_row(mysqli_query($mysqli, "SELECT config_mail_unsubscribe_secret FROM settings WHERE company_id = 1"))[0] ?? '');
}
return $secret = $saved;
}
/** A link's signature for contact $contact_id at $email - 128 bits, URL-safe. '' before the update. */
function contactUnsubscribeToken($contact_id, $email) {
$secret = contactUnsubscribeSecret();
if ($secret === '') {
return '';
}
$mac = hash_hmac('sha256', 'unsubscribe|' . intval($contact_id) . '|' . strtolower(trim((string) $email)), $secret, true);
return rtrim(strtr(base64_encode(substr($mac, 0, 16)), '+/', '-_'), '=');
}
/** The link to leave, for contact $contact_id at $email - '' before the update. */
function contactUnsubscribeUrl($contact_id, $email) {
global $config_base_url;
$token = contactUnsubscribeToken($contact_id, $email);
return $token !== '' ? "https://$config_base_url/guest/unsubscribe.php?c=" . intval($contact_id) . "&t=$token" : '';
}
/*
* The contact a link is for - $contact_id and its signature $token - when it is right for the address the contact has now:
* ['contact_id', 'contact_name', 'contact_email', 'contact_client_id', 'contact_unsubscribed_at'], or null.
*/
function contactUnsubscribeLink($contact_id, $token) {
global $mysqli;
$contact_id = intval($contact_id);
if (!$contact_id || !contactUnsubscribeReady() || !is_string($token) || $token === '') {
return null;
}
$row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT contact_id, contact_name, contact_email, contact_client_id, contact_unsubscribed_at FROM contacts
WHERE contact_id = $contact_id AND contact_archived_at IS NULL"));
if (!$row || trim((string) $row['contact_email']) === '' || !hash_equals(contactUnsubscribeToken($contact_id, $row['contact_email']), $token)) {
return null;
}
return $row;
}
/*
* Every contact with $email out of the email sent to many ($out true), or back in - a person's say-so is about their
* address, whichever client it is a contact at. How many contacts changed.
*/
function contactUnsubscribeSet($email, $out) {
global $mysqli;
$email = strtolower(trim((string) $email));
if (!contactUnsubscribeReady() || $email === '') {
return 0;
}
// Archived ones too - one restored later comes back as they left it
mysqli_query($mysqli, "UPDATE contacts SET contact_unsubscribed_at = " . ($out ? 'NOW()' : 'NULL') . ", contact_updated_at = contact_updated_at
WHERE LOWER(contact_email) = '" . escapeSql($email) . "' AND contact_unsubscribed_at IS " . ($out ? 'NULL' : 'NOT NULL'));
return mysqli_affected_rows($mysqli);
}

View File

@@ -51,6 +51,7 @@ const EMAIL_REPLY_MARKER = '##- Please type your reply above this line -##';
* office ['address', 'contact'] - the foot of another office (officeTicketFoot()), in place
* of the company's address and contact line; null for the company's own
* footnote a line under the card - why they got it
* unsubscribe a link after it to leave email like this - the email sent to many (contactUnsubscribeUrl())
*/
function emailHtml(array $email) {
global $config_base_url;
@@ -207,7 +208,8 @@ function emailHtml(array $email) {
. '</td></tr>'
. '<tr><td style="padding:18px 32px 24px;border-top:1px solid ' . $line . ';font-size:12px;line-height:1.6;color:' . $muted . ';' . $font . '">' . implode('<br>', array_map($e, $foot)) . '</td></tr>'
. '</table>'
. (!empty($email['footnote']) ? '<div style="max-width:600px;padding:12px 8px 0;font-size:11px;line-height:1.5;color:#8a9199;' . $font . '">' . $e($email['footnote']) . '</div>' : '')
. (!empty($email['footnote']) || !empty($email['unsubscribe']) ? '<div style="max-width:600px;padding:12px 8px 0;font-size:11px;line-height:1.5;color:#8a9199;' . $font . '">'
. $e($email['footnote'] ?? '') . (!empty($email['unsubscribe']) ? (!empty($email['footnote']) ? ' ' : '') . '<a href="' . $e($email['unsubscribe']) . '" style="color:#8a9199;text-decoration:underline;">Unsubscribe</a>' : '') . '</div>' : '')
. '</td></tr></table></body></html>';
}
@@ -527,7 +529,9 @@ function emailInlineImages($html, array $ticket = []) {
/**
* Queue an email - one per recipient, each greeted by name, each address once.
* $recipients: [['email' => ..., 'name' => ..., 'greet' => name to greet (or
* '' for "Hello,", null for none), 'footnote' => why they get it], ...].
* '' for "Hello,", null for none), 'footnote' => why they get it, 'unsubscribe' =>
* a link to leave email like it (emailHtml()), 'headers' => its own - List-Unsubscribe],
* ...] - unsubscribe and headers only on an email of its own, not one copied (together).
* $email is emailHtml()'s, its values raw. $opts:
* from ['email' => ..., 'name' => ...] - the system mailbox (emailFrom()) when not given
* attachments [['path' => app-relative, 'name' => ...], ...]
@@ -595,7 +599,9 @@ function emailQueue(array $recipients, $subject, array $email, array $opts = [])
$footnote = $together && isset($opts['together_footnote']) ? $opts['together_footnote'] : ($recipient['footnote'] ?? null);
$html = emailHtml(array_merge($email, [
'name' => array_key_exists('greet', $recipient) ? $recipient['greet'] : $name,
], $footnote !== null ? ['footnote' => $footnote] : []));
], $footnote !== null ? ['footnote' => $footnote] : [], !empty($recipient['unsubscribe']) && !$together ? ['unsubscribe' => (string) $recipient['unsubscribe']] : []));
// Its own headers - a List-Unsubscribe for its link - with the conversation's and the automatic ones
$headers = ($thread !== null ? ticketMailHeaders($thread_id, (string) $from['email'], $thread) : []) + $auto_headers + (!$together ? (array) ($recipient['headers'] ?? []) : []);
$went = [];
foreach (array_merge([$recipient], $cc) as $person) {
$went[strtolower($person['email'])] = $person['name'] !== '' ? $person['name'] . ' (' . $person['email'] . ')' : $person['email'];
@@ -625,7 +631,7 @@ function emailQueue(array $recipients, $subject, array $email, array $opts = [])
+ (!empty($opts['sensitive']) ? ['sensitive' => 1] : [])
+ (!empty($opts['bulk']) ? ['bulk' => 1] : [])
+ ($cc_list ? ['cc' => $cc_list] : [])
+ ($thread !== null || $auto_headers ? ['headers' => ($thread !== null ? ticketMailHeaders($thread_id, (string) $from['email'], $thread) : []) + $auto_headers] : []);
+ ($headers ? ['headers' => $headers] : []);
// Each on its own, so who it went to is only those queued - one that couldn't be is logged (addToMailQueue())
if (addToMailQueue([$row]) === 1) {
$sent += $went;
@@ -657,17 +663,60 @@ function emailTestSend($to, $mailbox) {
}
/*
* Send an email from the contacts or clients list (agent/includes/bulk_email_fields.php)
* to $recipients (emailBulkSend()'s), $picked how many were asked for - then
* say what happened and go back. Refuses without mail set up, a mailbox, a
* subject or a message.
* Who an email to many goes to (emailBulkSend()), from contact rows - contact_id, contact_email, contact_name, client_name,
* and contactBounceColumns() and contactUnsubscribeColumns() - each address once, with why they get it and their link to
* leave. Left out and counted: an address that bounced (Email bounced - it only bounces again, and a run of bounces
* counts against your domain), one that left this email (contactUnsubscribed()), no address, and the same one again.
* ['recipients' => [...], 'out' => ['bounced' => n, 'unsubscribed' => n, 'none' => n, 'again' => n]].
*/
function emailBulkPost(array $recipients, $picked) {
function emailBulkRecipients(array $rows) {
$company_name = (string) (billingCompany()['company_name'] ?? '');
$recipients = [];
$out = ['bounced' => 0, 'unsubscribed' => 0, 'none' => 0, 'again' => 0];
// Left by any contact with the address - at another client, or added since (contactUnsubscribedAddresses())
$left = contactUnsubscribedAddresses(array_column($rows, 'contact_email'));
$seen = [];
foreach ($rows as $row) {
$address = trim((string) ($row['contact_email'] ?? ''));
$key = strtolower($address);
if (!filter_var($address, FILTER_VALIDATE_EMAIL)) {
$out['none']++;
continue;
}
if (isset($seen[$key])) {
$out['again']++;
continue;
}
$seen[$key] = true;
if (contactUnsubscribed($row) !== null || isset($left[$key])) {
$out['unsubscribed']++;
} elseif (contactBounce($row) !== null) {
$out['bounced']++;
} else {
$link = contactUnsubscribeUrl($row['contact_id'] ?? 0, $address);
$recipients[$key] = ['email' => $address, 'name' => (string) ($row['contact_name'] ?? ''),
'footnote' => "You received this as a contact for " . ($row['client_name'] ?? 'a client') . " with $company_name.",
'unsubscribe' => $link,
// Mail programs show their own Unsubscribe from it, and leave with one click (RFC 8058) - guest/unsubscribe.php
'headers' => $link !== '' ? ['List-Unsubscribe' => "<$link>", 'List-Unsubscribe-Post' => 'List-Unsubscribe=One-Click'] : []];
}
}
return ['recipients' => array_values($recipients), 'out' => $out];
}
/*
* Send an email from the contacts or clients list (agent/includes/bulk_email_fields.php) to the contacts in $rows
* (emailBulkRecipients()) - then say what happened, and who was left out, and go back. Refuses without mail set up,
* a mailbox, a subject or a message. Send at is typed on the agent's own clock (Account > Preferences) and kept on
* the company's, which the mail queue goes by - it was taken as the company's, hours out for an agent elsewhere.
*/
function emailBulkPost(array $rows) {
global $session_name;
$mailbox = (string) ($_POST['mailbox'] ?? '');
$subject = trim((string) ($_POST['subject'] ?? ''));
$body = (string) ($_POST['body'] ?? '');
$at = trim((string) ($_POST['queued_at'] ?? ''));
$at = $at !== '' ? timezoneFromView($at) : '';
$queued_at = $at !== '' && strtotime($at) ? date('Y-m-d H:i:s', strtotime($at)) : '';
if (!emailReady()) {
flashAlert('Outgoing mail is not set up, so nothing was sent', 'error');
@@ -681,23 +730,32 @@ function emailBulkPost(array $recipients, $picked) {
flashAlert('Give it a subject and a message - nothing was sent', 'error');
redirect();
}
$sent = emailBulkSend($recipients, $mailbox, $_POST['mail_from_name'] ?? '', $subject, $body, !empty($_POST['greet']), $queued_at);
$picked = emailBulkRecipients($rows);
$out = $picked['out'];
$left_out = array_filter([
$out['bounced'] ? $out['bounced'] . ' marked Email bounced' : '',
$out['unsubscribed'] ? $out['unsubscribed'] . ' unsubscribed' : '',
$out['none'] + $out['again'] ? ($out['none'] + $out['again']) . ' with no email address, or the same one' : '',
]);
$sent = $picked['recipients'] ? emailBulkSend($picked['recipients'], $mailbox, $_POST['mail_from_name'] ?? '', $subject, $body, !empty($_POST['greet']), $queued_at) : [];
$count = count($sent);
if (!$count) {
flashAlert('None of them has an email address, so nothing was sent', 'error');
flashAlert('Nothing was sent' . ($left_out ? ' - left out: ' . implode(', ', $left_out) : ' - none of them has an email address'), 'error');
redirect();
}
$later = $queued_at !== '' && strtotime($queued_at) > time() ? ' to go ' . date('M j, Y g:i A', strtotime($queued_at)) : '';
logAudit("Bulk Mail", "Send", "$session_name sent " . escapeSql($subject) . " to $count " . ($count === 1 ? 'contact' : 'contacts') . " via bulk mail" . ($later !== '' ? escapeSql($later) : ''));
$left_out = max(0, intval($picked) - $count);
flashAlert("<strong>$count</strong> email" . ($count === 1 ? '' : 's') . " queued$later" . ($left_out ? " - $left_out left out with no email address, or the same one" : ''));
$later = $queued_at !== '' && strtotime($queued_at) > time();
$later_view = $later ? ' to go ' . date('M j, Y g:i A', strtotime(timezoneToView($queued_at))) . (timezoneShifted() ? ' ' . timezoneAbbr(timezoneView()) : '') : '';
logAudit("Bulk Mail", "Send", "$session_name sent " . escapeSql($subject) . " to $count " . ($count === 1 ? 'contact' : 'contacts') . " via bulk mail"
. ($later ? escapeSql(' to go ' . date('M j, Y g:i A', strtotime($queued_at))) : '') . ($left_out ? escapeSql(' - left out: ' . implode(', ', $left_out)) : ''));
flashAlert("<strong>$count</strong> email" . ($count === 1 ? '' : 's') . " queued" . escapeHtml($later_view) . ($left_out ? ' - left out: ' . escapeHtml(implode(', ', $left_out)) : ''));
redirect();
}
/*
* An email an agent writes to many contacts - Email on the contacts or clients
* list - in the email look, with the logo and the company's details. Each
* $recipients entry: email, name and footnote (why they get it). $body is the
* $recipients entry: email, name, footnote (why they get it), and unsubscribe and
* headers (emailBulkRecipients() - the link to leave, List-Unsubscribe). $body is the
* agent's HTML; $greet starts it "Hello Name,"; $from_name '' keeps the
* mailbox's own; $queued_at when to send ('' for now). Who it was queued to.
*/

View File

@@ -435,7 +435,8 @@ function emailPreviewCatalog() {
}],
'bulk' => ['group' => 'Other', 'label' => 'Email to many contacts', 'to' => 'The contacts picked', 'when' => 'Email on the contacts or clients list',
'run' => function ($s) {
emailBulkSend([['email' => $s['alex_email'], 'name' => $s['alex_name'], 'footnote' => 'You received this as a contact for ' . $s['client'] . ' with ' . (billingCompany()['company_name'] ?? '') . '.']],
// As the contacts list sends it - with their link to leave (emailBulkRecipients())
emailBulkSend(emailBulkRecipients([['contact_id' => $s['alex'], 'contact_email' => $s['alex_email'], 'contact_name' => $s['alex_name'], 'client_name' => $s['client']]])['recipients'],
array_key_first(emailMailboxes()) ?? 'system', '', 'Our office is closed on Friday',
'<p>Our office is closed this Friday for staff training. Support is still there for anything urgent - call us as usual.</p><p>Have a good weekend!</p>', true);
}],

View File

@@ -103,6 +103,72 @@ function mailQueueRefusedForGood($code, $code_ex, $detail) {
&& preg_match("/user unknown|unknown user|no such (user|mailbox|recipient|address)|does ?n[o']?t exist|recipient (not found|unknown)|unknown recipient|mailbox not found|invalid (recipient|mailbox)/i", (string) $detail) === 1;
}
/*
* The envelope sender (Return-Path) of an email from $from_email - where a mail server sends its bounce - for email
* sent to many (email_bulk): the mailbox ITFlow reads (Admin > Mail, Receiving), so its bounces come back and are read
* - the contacts marked Email bounced, and left out of the next one (functions/contact_bounce.php). They went to the
* From mailbox, which nobody may read. '' leaves it the From address, as always - unless it can be done safely:
* - email to ticket is on, reading a mailbox with an address that isn't the From address
* - it goes by SMTP: Microsoft Graph has no envelope sender of its own
* - ITFlow signs in to the mail server as that mailbox, or doesn't sign in - a mail server takes no other sender
* from a mailbox (Microsoft 365's SendAsDenied)
* - it is at the From address's domain, or one above or below it - else the email fails DMARC for its domain
* A mail server that turns it away all the same is sent the From address for the rest of the run (cron/mail_queue.php).
*/
function mailQueueReturnPath($from_email) {
global $mysqli;
static $settings = null;
if ($settings === null) {
$settings = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT config_ticket_email_parse, config_imap_provider, config_imap_username, config_smtp_provider, config_smtp_username, config_mail_from_email
FROM settings WHERE company_id = 1")) ?: [];
}
$reads = strtolower(trim((string) ($settings['config_imap_username'] ?? '')));
$from = strtolower(trim((string) $from_email));
if (!intval($settings['config_ticket_email_parse'] ?? 0) || trim((string) ($settings['config_imap_provider'] ?? '')) === '' || !filter_var($reads, FILTER_VALIDATE_EMAIL) || $reads === $from) {
return '';
}
$provider = (string) ($settings['config_smtp_provider'] ?? '');
if ($provider === '' || ($provider === 'microsoft_oauth' && !empty(mailGraphState()['send']))) {
return '';
}
// Who ITFlow signs in as - the OAuth providers sign in as the system mailbox when no username is saved (mailQueueMailer())
$signs_in = strtolower(trim((string) ($settings['config_smtp_username'] ?? '')));
if ($signs_in === '' && in_array($provider, ['google_oauth', 'microsoft_oauth'], true)) {
$signs_in = strtolower(trim((string) ($settings['config_mail_from_email'] ?? '')));
}
if ($signs_in !== '' && $signs_in !== $reads) {
return '';
}
$reads_domain = substr($reads, strrpos($reads, '@') + 1);
$from_domain = strpos($from, '@') !== false ? substr($from, strrpos($from, '@') + 1) : '';
$aligned = $from_domain !== '' && ($reads_domain === $from_domain || str_ends_with($reads_domain, ".$from_domain") || str_ends_with($from_domain, ".$reads_domain"));
return $aligned && !mailQueueReturnPathRefused() ? $reads : '';
}
/* Whether the mail server turned the Return-Path (mailQueueReturnPath()) away this run - $refused true says it did. */
function mailQueueReturnPathRefused($refused = null) {
static $was = false;
if ($refused !== null) {
$was = (bool) $refused;
}
return $was;
}
/*
* Where the bounces of email sent to many from $from_email go - the mailbox ITFlow reads, where they are read
* (mailQueueReturnPath()), or the From mailbox itself. For the Email window. ['address', 'read' => bool].
*/
function mailQueueBouncesTo($from_email) {
global $mysqli;
$return_path = mailQueueReturnPath($from_email);
if ($return_path !== '') {
return ['address' => $return_path, 'read' => true];
}
$row = mysqli_fetch_row(mysqli_query($mysqli, "SELECT config_ticket_email_parse, config_imap_provider, config_imap_username FROM settings WHERE company_id = 1"));
$read = $row && intval($row[0]) && trim((string) $row[1]) !== '' && strcasecmp(trim((string) $row[2]), trim((string) $from_email)) === 0;
return ['address' => trim((string) $from_email), 'read' => $read];
}
/* Whether the 4.2.9 update has run - the sending pace (config_mail_send_per_minute) and bulk email (email_bulk). */
function mailQueuePaceReady() {
global $mysqli;
@@ -457,6 +523,9 @@ const MAIL_QUEUE_HEADERS = [
'References' => '/^(<[^<>\s]+@[^<>\s]+>)( <[^<>\s]+@[^<>\s]+>)*$/',
'Auto-Submitted' => '/^auto-(replied|generated)$/',
'X-Auto-Response-Suppress' => '/^[A-Za-z]+(, ?[A-Za-z]+)*$/',
// Bulk email's link to leave, which mail programs show as their own Unsubscribe - one click (RFC 8058, functions/contact_unsubscribe.php)
'List-Unsubscribe' => '/^<https:\/\/[^<>\s]+>$/',
'List-Unsubscribe-Post' => '/^List-Unsubscribe=One-Click$/',
];
/*

99
guest/unsubscribe.php Normal file
View File

@@ -0,0 +1,99 @@
<?php
/*
* ITFlow - leaving the email sent to many from the contacts or clients list, by the link in one
* (functions/contact_unsubscribe.php). The link is signed for the contact and the address they have:
* GET asks first, with a button - a link checker that opens every link in an email mustn't unsubscribe anyone
* POST from that button - unsubscribe, or subscribe again
* POST List-Unsubscribe=One-Click - a mail program's own Unsubscribe (RFC 8058): done, with no page
* It is about the address: every contact with it leaves, whichever client they are at. Ticket emails, invoices
* and quotes still go.
*/
require_once $_SERVER['DOCUMENT_ROOT'] . '/config.php';
require_once $_SERVER['DOCUMENT_ROOT'] . '/functions.php';
require_once $_SERVER['DOCUMENT_ROOT'] . '/includes/load_global_settings.php';
require_once $_SERVER['DOCUMENT_ROOT'] . '/includes/inc_set_timezone.php';
// logAudit() reads these - who did it, from where
$session_ip = escapeSql(getIP());
$session_user_agent = escapeSql(mb_substr((string) ($_SERVER['HTTP_USER_AGENT'] ?? ''), 0, 250));
$contact = contactUnsubscribeLink($_GET['c'] ?? 0, $_GET['t'] ?? '');
/* Out ($out true) or back in - every contact with the address - and said in the audit log, $how. */
function guestUnsubscribe(array $contact, $out, $how) {
if (contactUnsubscribeSet($contact['contact_email'], $out)) {
logAudit("Contact", "Edit", escapeSql($contact['contact_email'] . ($out ? ' unsubscribed from' : ' subscribed again to') . " bulk email - $how"),
intval($contact['contact_client_id']), intval($contact['contact_id']));
}
}
// A mail program's own Unsubscribe - one click, nothing to show
if (($_SERVER['REQUEST_METHOD'] ?? '') === 'POST' && trim((string) ($_POST['List-Unsubscribe'] ?? '')) === 'One-Click') {
header('Content-Type: text/plain; charset=utf-8');
if (!$contact) {
http_response_code(404);
echo "This unsubscribe link isn't working.\n";
exit;
}
guestUnsubscribe($contact, true, 'with one click in their mail program');
echo "Unsubscribed.\n";
exit;
}
$done = '';
if ($contact && ($_SERVER['REQUEST_METHOD'] ?? '') === 'POST' && in_array($_POST['action'] ?? '', ['unsubscribe', 'subscribe'], true)) {
$out = $_POST['action'] === 'unsubscribe';
guestUnsubscribe($contact, $out, 'by the link in one');
$contact = contactUnsubscribeLink($contact['contact_id'], $_GET['t'] ?? '');
$done = $out ? 'out' : 'in';
}
require_once "includes/inc_all_guest.php";
if (!$contact) {
echo guestDeadEndHtml('fa-envelope', "This unsubscribe link isn't working", "It may have been cut short, or the address it was for has changed. Reply to the email, and we'll take you off.");
require_once $_SERVER['DOCUMENT_ROOT'] . '/includes/footer.php';
exit();
}
$company = escapeHtml($session_company_name);
$address = escapeHtml($contact['contact_email']);
$out = contactUnsubscribed($contact) !== null;
$action_url = 'unsubscribe.php?c=' . intval($contact['contact_id']) . '&t=' . rawurlencode((string) ($_GET['t'] ?? ''));
?>
<div class="card mt-3 mb-3 mx-auto" style="max-width: 36rem;" data-unsubscribe="<?= $out ? 'out' : 'in' ?>">
<div class="card-header bg-dark text-center py-3">
<h4 class="mb-0"><i class="fas fa-fw fa-envelope me-2"></i><?= $out ? 'Unsubscribed' : 'Unsubscribe' ?></h4>
</div>
<div class="card-body text-center py-4">
<?php if ($out) { ?>
<div class="alert alert-success d-inline-block">
<i class="fas fa-fw fa-check-circle me-2"></i><strong><?= $address ?></strong> won't get the emails <?= $company ?> sends to all its clients.
</div>
<p class="text-body-secondary">Emails about your tickets, invoices and quotes still come to you.</p>
<form action="<?= escapeHtml($action_url) ?>" method="post" class="mt-3">
<input type="hidden" name="action" value="subscribe">
<span class="text-body-secondary me-2">Changed your mind?</span>
<button type="submit" class="btn btn-outline-primary"><i class="fas fa-fw fa-bell me-2"></i>Subscribe Again</button>
</form>
<?php } else { ?>
<?php if ($done === 'in') { ?>
<div class="alert alert-success d-inline-block"><i class="fas fa-fw fa-check-circle me-2"></i>You'll get them again.</div>
<?php } ?>
<p class="mb-1">Stop the emails <?= $company ?> sends to all its clients at</p>
<p class="fw-bold fs-5 mb-3"><?= $address ?></p>
<p class="text-body-secondary">Emails about your tickets, invoices and quotes still come to you.</p>
<form action="<?= escapeHtml($action_url) ?>" method="post" class="d-grid gap-2 d-sm-block">
<input type="hidden" name="action" value="unsubscribe">
<button type="submit" class="btn btn-primary btn-lg"><i class="fas fa-fw fa-bell-slash me-2"></i>Unsubscribe</button>
</form>
<?php } ?>
</div>
</div>
<?php
require_once $_SERVER['DOCUMENT_ROOT'] . '/includes/footer.php';