From 2ad57e2865a75682a29cbdc810bc91c77b8699ae Mon Sep 17 00:00:00 2001 From: johnnyq Date: Wed, 2 Dec 2026 13:36:49 -0500 Subject: [PATCH] Contact alternate email (DB 4.4.1): one more address per contact in the contact window under Email, shown on their page, quick look and the Reach column, searched by the contacts, clients, tickets and global searches, exported and imported as Alternate Email and in the API as contact_email_alt, and recognized on incoming email as theirs - a new ticket as them at their client even with unknown senders off, and their reply by ticket number, conversation or subject - with the ticket's from line showing the address it came from while everything ITFlow sends still goes to their Email and neither address is copied in; the duplicate warning, Try an Email, Unprocessed Email and the ignored sender and routing rule warnings count it too, and the same-as-Email warning shows while typing (contactEmailSql(), contactHasEmail(), contactEmailMatchSql()); 26.12.4 changelog --- CHANGELOG.md | 4 +- admin/database_updates/4.4.1.php | 20 +++++ agent/ajax.php | 8 +- agent/clients.php | 2 +- agent/contact.php | 9 ++- agent/contacts.php | 10 ++- agent/modals/contact/contact.php | 13 ++- agent/modals/contact/contact_add.php | 2 +- agent/modals/contact/contact_edit.php | 3 +- agent/modals/contact/contact_form.php | 64 ++++++++++++--- .../email_unprocessed_reply.php | 4 +- .../email_unprocessed_ticket.php | 4 +- agent/post/client.php | 2 +- agent/post/contact.php | 13 +-- agent/post/contact_model.php | 3 + agent/tickets.php | 2 +- api/v1/contacts/contact_model.php | 6 ++ api/v1/contacts/create.php | 4 +- api/v1/contacts/read.php | 4 +- api/v1/contacts/update.php | 2 +- cron/ticket_email_parser.php | 7 +- db.sql | 1 + functions/contact.php | 79 +++++++++++++++++++ functions/export.php | 1 + functions/import_kinds.php | 9 +++ functions/mail_ignore.php | 6 +- functions/mail_route.php | 6 +- functions/search.php | 2 +- functions/ticket_mail_decide.php | 15 ++-- functions/ticket_mail_thread.php | 31 ++++---- functions/ticket_mail_try.php | 20 +++-- 31 files changed, 276 insertions(+), 80 deletions(-) create mode 100644 admin/database_updates/4.4.1.php diff --git a/CHANGELOG.md b/CHANGELOG.md index d02eb733c..81acb1431 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,7 +6,7 @@ This file documents all notable changes made to ITFlow. ### Upgrading to 26.12.4 -Update from Maintenance > Update as usual. This release has three database changes: 4.3.8, which lets ITFlow remind clients before their autopay card expires - a setting for it, and on each saved card when it was last checked with Stripe, which reminders went out and the key in their link - 4.3.9, which adds the table that keeps email routing rules, and 4.4.0, which keeps the reply type with an unsent reply. +Update from Maintenance > Update as usual. This release has four database changes: 4.3.8, which lets ITFlow remind clients before their autopay card expires - a setting for it, and on each saved card when it was last checked with Stripe, which reminders went out and the key in their link - 4.3.9, which adds the table that keeps email routing rules, 4.4.0, which keeps the reply type with an unsent reply, and 4.4.1, which adds an alternate email to contacts. ### New Features & Updates @@ -19,6 +19,7 @@ Update from Maintenance > Update as usual. This release has three database chang - Try an Email in Settings > Tickets now asks the very questions the mailbox asks, in the same order, from the same code - so what it shows is what happens to the email. An out-of-office is now checked where the mailbox checks it, after the ticket number. - Change who sees a reply after it's posted: a reply's ⋮ has Edit or Change Type, with Internal note, Public note and Email reply. Email reply makes it public and emails it when you click Save and Email - to the people in its To line, from whoever wrote it by name, with their signature and its files - as the reply box would. It's offered while the ticket isn't closed, mail is set up and the contact has an email address, until the reply has been emailed. A note the client can see now counts as the first response, and a ticket nobody had becomes its writer's, as with a reply from the reply box. The ticket's history says who changed it, and how. - Coming back to a ticket with a reply on the go opens the reply box for you. An unsent reply - kept as a draft as you type - opens on the type you picked for it (internal note, public note, email or text) with your words in it. A ticket whose timer is still running opens on the type you picked last there in this browser, or Internal note. A timer that only started as you opened the ticket leaves the box shut, and the page isn't moved down to it. +- An alternate email for each contact - a personal address, or one they had before a name change. Email from it is theirs: a new ticket as them at their client, even with tickets from unknown senders off, and a reply on their ticket by its number, its conversation or its subject. The ticket says the address it came from. What ITFlow sends still goes to their Email only - we have your email, replies, closed - and neither address is copied in on their own ticket. Add it in the contact's window, under Email; it warns when another contact has the address, as Email or as their alternate. It shows on the contact's page, their quick look and in the Reach column of Contacts, and searching contacts, clients, tickets or across ITFlow finds them by it. It's in contact exports as Alternate Email, in imports (Alternate Email, Personal Email, Secondary Email and the like), and in the API as `contact_email_alt`. Try an Email in Settings > Tickets says when an email is from a contact's alternate address, Unprocessed Email picks them as the contact and finds their tickets by it, and an ignored sender or email routing rule warns when it takes a contact's alternate address. ### Bug Fixes @@ -42,6 +43,7 @@ Update from Maintenance > Update as usual. This release has three database chang - Where an email goes is decided in one place: `ticketMailDecide(array $in)` in new `functions/ticket_mail_decide.php`, used by `cron/ticket_email_parser.php` and `ticketMailTry()`. It takes raw facts - `from`, `from_name`, `subject`, `visitor` (a website form's Reply-To), `thread_ticket_id` (null when it can't be known), `automatic`, `forged`, `answers_ours` (null when unknown), `unprocessed`, `forward` - and runs steps 1-6 (thread, ticket number, the agent who may be forwarding, the routing rule, the sender's contact or domain, the out-of-office set-aside, similar subject, contact, routed client, client domain, unknown senders), returning `steps` ([question, answer], what Try an Email shows) and an `action` - `reply` (`ticket_id`, `by`), `ticket` (`client_id`, `client_name`, `contact`, `new_contact`, `picked`, `sender`, `similar`, `link_why`, `taken`), `set_aside` or `leave` (`why`, `not_ours`, `answers_unknown`) - with `agent`, `route` and `quiet`. The parser keeps its first checks (own address, bounce, ignored sender, Reply-To, duplicate Message-ID, Unprocessed Email asks), then carries the decision out; when `agent` is set it reads the forward and calls `ticketMailDecide()` again with `forward`, which skips steps 1-2 as before. `ticketMailTry()` keeps its own first checks and turns the decision into an outcome with `ticketMailTryOutcome()`. Changes in behaviour: the similar-subject check compares raw subjects and the CC lookup escapes the sender once (it was escaped twice, missing an address with an apostrophe), an out-of-office that isn't set aside is left in the inbox rather than going on to the similar-subject step, and a reply whose ticket vanished between the lookup and `addReply()` waits in Unprocessed Email instead of becoming a new ticket. - Reply type after posting: `agent/modals/ticket/ticket_reply_edit.php` offers `Email` beside `Internal` and `Public` (while the ticket isn't closed, `config_smtp_provider` is set, the contact has an email address and `ticket_reply_emailed` isn't 1), with the ticket's To line (`ticketReplyRecipients()`). `edit_ticket_reply` saves it Public, appends the writer's `user_config_signature`, emails it with `ticketMailReply()` (from the writer by name via its `ticket_reply_id`, the To line by `ticketReplyRecipientsPick()`, its files by new `ticketReplyFiles()` in `functions/ticket_mail_thread.php`, which the client-reply relay now uses too) and `smsTicketReplyNotify()`. A reply that becomes Public, or is emailed, sets the first response when there is none and, with `ticketReplyAssigns()`, assigns an unassigned ticket to its writer (the editing agent when the writer isn't an active agent). The history line names the change. Refused emails say why: closed, emailed already, no mail, no contact email. - Reply drafts keep their type (DB 4.4.0, `ticket_reply_drafts.draft_type`, NULL for older drafts): `ticketReplyDraftSave($ticket_id, $user_id, $html, $type = null)`, `ticketReplyDraft()` returns `type`, `agent/ajax.php?ticket_reply_draft` takes `type`, and `agent/js/ticket_reply_extras.js` sends the picked `public_reply_type` with each save (and beacon), saving again when the type changes with words in the box. `agent/ticket.php` puts `data-draft-type` on the reply form; as the page is drawn the composer opens (the `show` class, no focus or scroll) on the draft's type, or - when `localStorage[ticketId + '-startTime']` was there before the timer script ran - on `localStorage['ticket-reply-type-' + ticketId]`, kept as a type is picked and cleared on Cancel and on sending, else Internal note; a type that can't be used now (email with no contact address, an opted-out text) falls back to Internal note. The reply menu item reads Edit or Change Type. +- Contact alternate email (DB 4.4.1, `contacts.contact_email_alt` varchar(200), NULL): new helpers in `functions/contact.php` - `contactEmailAltReady()` (version check), `contactEmailSql($email, $table = '')` (`contact_email` or `contact_email_alt` equals it; `0` for an empty address), `contactEmailAltColumn()` and `contactEmailAltLikeSql($like, $table = '')` for SELECTs and searches before the update, `contactHasEmail(array $row, $email)` and `contactEmailAltClean($alt, $email)` (trimmed; empty unless a valid address of 200 characters or fewer that isn't `$email` in any case). `agent/post/contact_model.php` and `api/v1/contacts/contact_model.php` set it only when `email_alt` / `contact_email_alt` is posted, so other forms and API calls leave it; anonymize clears it. `agent/ajax.php?contact_email_check` matches either column and says "as their alternate email"; the form says an alternate equal to Email as it is typed. Searches in `agent/contacts.php`, `agent/clients.php`, `agent/tickets.php`, `functions/search.php` and the contacts and clients exports add it; `functions/export.php` has the `contact_email_alt` column and `functions/import_kinds.php` the `email_alt` field (`importContactRow()` leaves out one that is the Email or not an address, with a note). API: `create.php` counts an alternate as a duplicate at the client and `read.php?contact_email=` matches either. Incoming email: `ticketMailSenderContact()` matches either column, ordering a contact whose `contact_email` it is before one whose alternate it is (after the client-domain match); `ticketMailDecide()` finds a routed client's contact by either and treats a sender matching `contactHasEmail()` as the contact (not quiet, their own ticket for the similar-subject check), setting `sender` whenever the address isn't the contact's `contact_email`, so `addTicket()` shows it on the from line while the created email still goes to `contact_email`. `addReply()`, `ticketMailTryReply()`, `ticketMailClientAddresses()`, `ticketMailCopiedCcs()` (never the contact by either address) and the Unprocessed Email ticket and reply modals use both. `contactEmailMatchSql($match)` (an address, or a domain and its subdomains, across both columns) is what `mailIgnoreReach()` and `mailRouteReach()` count now. ## [26.12.3] diff --git a/admin/database_updates/4.4.1.php b/admin/database_updates/4.4.1.php new file mode 100644 index 000000000..87ded5f11 --- /dev/null +++ b/admin/database_updates/4.4.1.php @@ -0,0 +1,20 @@ + '$email'" : '0') . " AS as_alt FROM contacts LEFT JOIN clients ON client_id = contact_client_id - WHERE contact_email = '$email' AND contact_id != $exclude_contact ORDER BY contact_archived_at IS NOT NULL, contact_id DESC LIMIT 1"); + WHERE " . contactEmailSql(stripslashes($email)) . " AND contact_id != $exclude_contact ORDER BY contact_archived_at IS NOT NULL, contact_id DESC LIMIT 1"); if ($row = mysqli_fetch_assoc($sql_contacts)) { $response['message'] = hasClientAccess($row['contact_client_id']) ? "Already on file: " . escapeHtml($row['contact_name']) . "" - . " at " . escapeHtml($row['client_name']) . ($row['contact_archived_at'] ? ' (archived)' : '') + . " at " . escapeHtml($row['client_name']) . (intval($row['as_alt']) ? ', as their alternate email' : '') . ($row['contact_archived_at'] ? ' (archived)' : '') : "Already on file for a client you cannot open."; } diff --git a/agent/clients.php b/agent/clients.php index 6d87954ae..eed328905 100644 --- a/agent/clients.php +++ b/agent/clients.php @@ -165,7 +165,7 @@ $sql = mysqli_query( SELECT l.location_id FROM locations l WHERE l.location_client_id = clients.client_id AND l.location_primary = 1 ORDER BY l.location_id LIMIT 1 ) WHERE (client_name LIKE '%$q%' OR client_abbreviation LIKE '%$q%' OR client_type LIKE '%$q%' OR client_referral LIKE '%$q%' - OR contact_email LIKE '%$q%' OR contact_name LIKE '%$q%' OR contact_phone LIKE '%$phone_query%' + OR contact_email LIKE '%$q%'" . contactEmailAltLikeSql($q) . " OR contact_name LIKE '%$q%' OR contact_phone LIKE '%$phone_query%' OR contact_mobile LIKE '%$phone_query%' OR location_address LIKE '%$q%' OR location_city LIKE '%$q%' OR location_state LIKE '%$q%' OR location_zip LIKE '%$q%' OR location_country LIKE '%$q%' OR client_tax_id_number LIKE '%$q%' diff --git a/agent/contact.php b/agent/contact.php index 9e216d81e..89f9d1c8a 100644 --- a/agent/contact.php +++ b/agent/contact.php @@ -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() . ", " . contactUnsubscribeColumns() . ", contact_extension, contact_id, contact_important, contact_location_id, contact_mobile, + contact_department, contact_email, " . contactEmailAltColumn() . ", " . 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 @@ -56,6 +56,7 @@ $contact_name = escapeHtml($row['contact_name']); $contact_title = escapeHtml($row['contact_title']); $contact_department = escapeHtml($row['contact_department']); $contact_email = escapeHtml($row['contact_email']); +$contact_email_alt = escapeHtml($row['contact_email_alt'] ?? ''); $contact_pin = escapeHtml($row['contact_pin']); $contact_notes = escapeHtml($row['contact_notes']); $contact_primary = intval($row['contact_primary']); @@ -363,7 +364,7 @@ if (!$can_support) {

Reach

- +
Phone
@@ -387,6 +388,10 @@ if (!$can_support) { + +
Alternate email
+
+
No phone or email recorded. diff --git a/agent/contacts.php b/agent/contacts.php index 3aa53ab9c..67a4f77c9 100644 --- a/agent/contacts.php +++ b/agent/contacts.php @@ -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() . ", " . contactUnsubscribeColumns() . ", contact_extension, contact_important, contact_location_id, contact_mobile, + contact_department, contact_email, " . contactEmailAltColumn() . ", " . 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 @@ -163,7 +163,7 @@ if ($invites_view) { WHERE $archive_query $tag_query AND ($role_query) - AND (contact_name LIKE '%$q%' OR contact_title LIKE '%$q%' OR location_name LIKE '%$q%' OR contact_email LIKE '%$q%' OR contact_department LIKE '%$q%' + AND (contact_name LIKE '%$q%' OR contact_title LIKE '%$q%' OR location_name LIKE '%$q%' OR contact_email LIKE '%$q%'" . contactEmailAltLikeSql($q) . " OR contact_department LIKE '%$q%' OR contact_phone LIKE '%$phone_query%' OR contact_extension LIKE '%$q%' OR contact_mobile LIKE '%$phone_query%' OR client_name LIKE '%$q%' OR contacts.contact_id IN (SELECT contact_tags.contact_id FROM contact_tags JOIN tags ON tags.tag_id = contact_tags.tag_id WHERE tag_name LIKE '%$q%')) " . clientScopeSql('contact_client_id') . " @@ -583,6 +583,7 @@ $search_title = $invites_view ? 'Email, name or client' : 'Name, title, email, p $contact_title = escapeHtml($row['contact_title']); $contact_department = escapeHtml($row['contact_department']); $contact_email = escapeHtml($row['contact_email']); + $contact_email_alt = escapeHtml($row['contact_email_alt'] ?? ''); $contact_phone_link = contactPhoneLink($row['contact_phone'], $row['contact_phone_country_code'], $row['contact_extension'], 'text-reset'); $contact_mobile_link = contactPhoneLink($row['contact_mobile'], $row['contact_mobile_country_code'], '', 'text-reset'); $contact_primary = intval($row['contact_primary']); @@ -633,7 +634,10 @@ $search_title = $invites_view ? 'Email, name or client' : 'Name, title, email, p
- + +
+ + - diff --git a/agent/modals/contact/contact.php b/agent/modals/contact/contact.php index ce2e8fe7b..784b7012f 100644 --- a/agent/modals/contact/contact.php +++ b/agent/modals/contact/contact.php @@ -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() . ", " . contactUnsubscribeColumns() . ", contact_extension, contact_id, contact_important, contact_location_id, contact_mobile, contact_mobile_country_code, + contact_email, " . contactEmailAltColumn() . ", " . 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 @@ -43,6 +43,7 @@ $can_support = lookupUserPermission('module_support') >= 1; $contact_name = escapeHtml($contact_row['contact_name']); $contact_email = escapeHtml($contact_row['contact_email']); +$contact_email_alt = escapeHtml($contact_row['contact_email_alt'] ?? ''); $contact_pin = escapeHtml($contact_row['contact_pin']); $contact_notes = escapeHtml($contact_row['contact_notes']); $contact_archived = !empty($contact_row['contact_archived_at']); @@ -129,7 +130,7 @@ $quick_tabs = array_filter([ }); $first_tab = array_key_first($quick_tabs); -$has_reach = $contact_phone_link || $contact_mobile_link || $contact_email; +$has_reach = $contact_phone_link || $contact_mobile_link || $contact_email || $contact_email_alt; ob_start(); @@ -155,7 +156,7 @@ ob_start(); @@ -307,20 +318,51 @@ $contact_roles = [ }); } - // An email already on file for someone else - var emailCheck = form.querySelector('#contactFormEmailCheck'); - if (emailCheck) { - form.querySelector('#contactFormEmail').addEventListener('change', function () { - var email = this.value.trim(); - if (email === '') { - emailCheck.textContent = ''; - return; + // An email already on file for someone else - their email or their alternate one - and an alternate the same as Email + var emailMain = form.querySelector('#contactFormEmail'); + var emailAlt = form.querySelector('#contactFormEmailAlt'); + var emailAltCheck = form.querySelector('#contactFormEmailAltCheck'); + var emailAltSame = 'That is their Email already - an alternate is another address.'; + var altIsEmail = function () { + return emailMain && emailAlt && emailAlt.value.trim() !== '' && emailMain.value.trim().toLowerCase() === emailAlt.value.trim().toLowerCase(); + }; + // Said as it is typed, not when the field is left - said then, the line moved Save from under the click + if (emailAlt && emailAltCheck) { + [emailMain, emailAlt].forEach(function (input) { + if (input) { + input.addEventListener('input', function () { + if (altIsEmail()) { + emailAltCheck.textContent = emailAltSame; + } else if (emailAltCheck.textContent === emailAltSame) { + emailAltCheck.textContent = ''; + } + }); } - itflowGet('ajax.php', { contact_email_check: 'true', email: email, exclude: emailCheck.dataset.exclude }, function (data) { - emailCheck.innerHTML = JSON.parse(data).message || ''; - }); }); } + [['#contactFormEmail', '#contactFormEmailCheck'], ['#contactFormEmailAlt', '#contactFormEmailAltCheck']].forEach(function (pair) { + var input = form.querySelector(pair[0]); + var check = form.querySelector(pair[1]); + if (!input || !check) { + return; + } + input.addEventListener('change', function () { + var email = this.value.trim(); + if (email === '') { + check.textContent = ''; + return; + } + if (input === emailAlt && altIsEmail()) { + return; + } + itflowGet('ajax.php', { contact_email_check: 'true', email: email, exclude: check.dataset.exclude }, function (data) { + if (input === emailAlt && altIsEmail()) { + return; + } + check.innerHTML = JSON.parse(data).message || ''; + }); + }); + }); // A required field on a tab that isn't showing: show that tab and point // at the field - otherwise the browser just quietly refuses to send diff --git a/agent/modals/email_unprocessed/email_unprocessed_reply.php b/agent/modals/email_unprocessed/email_unprocessed_reply.php index 1507520d6..369e82b5d 100644 --- a/agent/modals/email_unprocessed/email_unprocessed_reply.php +++ b/agent/modals/email_unprocessed/email_unprocessed_reply.php @@ -23,7 +23,7 @@ $from_name = trim((string) $row['email_unprocessed_from_name']); $can_add = filter_var($from_email, FILTER_VALIDATE_EMAIL) !== false; // Open tickets, and ones closed lately - the newest first -$sql_tickets = mysqli_query($mysqli, "SELECT ticket_id, ticket_prefix, ticket_number, ticket_subject, ticket_closed_at, ticket_status_name, client_name, contact_name, contact_email FROM tickets +$sql_tickets = mysqli_query($mysqli, "SELECT ticket_id, ticket_prefix, ticket_number, ticket_subject, ticket_closed_at, ticket_status_name, client_name, contact_name, contact_email, " . contactEmailAltColumn() . " FROM tickets LEFT JOIN ticket_statuses ON ticket_status_id = ticket_status LEFT JOIN clients ON client_id = ticket_client_id LEFT JOIN contacts ON contact_id = ticket_contact_id @@ -58,7 +58,7 @@ ob_start(); - +
diff --git a/agent/modals/email_unprocessed/email_unprocessed_ticket.php b/agent/modals/email_unprocessed/email_unprocessed_ticket.php index 37e154b3c..7c29b7375 100644 --- a/agent/modals/email_unprocessed/email_unprocessed_ticket.php +++ b/agent/modals/email_unprocessed/email_unprocessed_ticket.php @@ -22,10 +22,10 @@ $from_email = trim((string) $row['email_unprocessed_from_email']); $from_name = trim((string) $row['email_unprocessed_from_name']); $can_add = filter_var($from_email, FILTER_VALIDATE_EMAIL) !== false; -// A sender who is a contact already starts picked - their client and them +// A sender who is a contact already - by their email or their alternate one - starts picked: their client and them $known = $from_email !== '' ? mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT contact_id, contact_client_id FROM contacts LEFT JOIN clients ON client_id = contact_client_id - WHERE contact_email = '" . escapeSql($from_email) . "' AND contact_archived_at IS NULL AND client_archived_at IS NULL " . clientScopeSql('contact_client_id') . " + WHERE " . contactEmailSql($from_email) . " AND contact_archived_at IS NULL AND client_archived_at IS NULL " . clientScopeSql('contact_client_id') . " ORDER BY contact_primary DESC, contact_id LIMIT 1")) : null; $client_id = intval($known['contact_client_id'] ?? 0); $contact_id = intval($known['contact_id'] ?? 0); diff --git a/agent/post/client.php b/agent/post/client.php index 4bca5b0b3..3005ef113 100644 --- a/agent/post/client.php +++ b/agent/post/client.php @@ -566,7 +566,7 @@ if (isExportRequest('export_clients')) { LEFT JOIN client_tags ON client_tags.client_id = clients.client_id LEFT JOIN tags ON tags.tag_id = client_tags.tag_id WHERE (client_name LIKE '%$q%' OR client_abbreviation LIKE '%$q%' OR client_type LIKE '%$q%' OR client_referral LIKE '%$q%' - OR contact_email LIKE '%$q%' OR contact_name LIKE '%$q%' OR contact_phone LIKE '%$phone_query%' + OR contact_email LIKE '%$q%'" . contactEmailAltLikeSql($q) . " OR contact_name LIKE '%$q%' OR contact_phone LIKE '%$phone_query%' OR contact_mobile LIKE '%$phone_query%' OR location_address LIKE '%$q%' OR location_city LIKE '%$q%' OR location_state LIKE '%$q%' OR location_zip LIKE '%$q%' OR location_country LIKE '%$q%' OR tag_name LIKE '%$q%' OR client_tax_id_number LIKE '%$q%') diff --git a/agent/post/contact.php b/agent/post/contact.php index 407680d72..1c00e7fce 100644 --- a/agent/post/contact.php +++ b/agent/post/contact.php @@ -42,7 +42,7 @@ if (isset($_POST['add_contact'])) { $user_id = mysqli_insert_id($mysqli); } - mysqli_query($mysqli,"INSERT INTO contacts SET contact_name = '$name', contact_title = '$title', contact_phone_country_code = '$phone_country_code', contact_phone = '$phone', contact_extension = '$extension', contact_mobile_country_code = '$mobile_country_code', contact_mobile = '$mobile', contact_email = '$email', contact_pin = '$pin', contact_notes = '$notes', contact_important = $contact_important, contact_billing = $contact_billing, contact_technical = $contact_technical, contact_department = '$department', contact_location_id = $location_id, contact_user_id = $user_id, contact_client_id = $client_id"); + mysqli_query($mysqli,"INSERT INTO contacts SET contact_name = '$name', contact_title = '$title', contact_phone_country_code = '$phone_country_code', contact_phone = '$phone', contact_extension = '$extension', contact_mobile_country_code = '$mobile_country_code', contact_mobile = '$mobile', contact_email = '$email'$email_alt_sql, contact_pin = '$pin', contact_notes = '$notes', contact_important = $contact_important, contact_billing = $contact_billing, contact_technical = $contact_technical, contact_department = '$department', contact_location_id = $location_id, contact_user_id = $user_id, contact_client_id = $client_id"); $contact_id = mysqli_insert_id($mysqli); @@ -157,7 +157,7 @@ if (isset($_POST['edit_contact'])) { } - mysqli_query($mysqli,"UPDATE contacts SET contact_name = '$name', contact_title = '$title', contact_phone_country_code = '$phone_country_code', contact_phone = '$phone', contact_extension = '$extension', contact_mobile_country_code = '$mobile_country_code', contact_mobile = '$mobile', contact_email = '$email', contact_pin = '$pin', contact_notes = '$notes', contact_important = $contact_important, contact_billing = $contact_billing, contact_technical = $contact_technical, contact_department = '$department', contact_location_id = $location_id, contact_user_id = $contact_user_id WHERE contact_id = $contact_id"); + mysqli_query($mysqli,"UPDATE contacts SET contact_name = '$name', contact_title = '$title', contact_phone_country_code = '$phone_country_code', contact_phone = '$phone', contact_extension = '$extension', contact_mobile_country_code = '$mobile_country_code', contact_mobile = '$mobile', contact_email = '$email'$email_alt_sql, contact_pin = '$pin', contact_notes = '$notes', contact_important = $contact_important, contact_billing = $contact_billing, contact_technical = $contact_technical, contact_department = '$department', contact_location_id = $location_id, contact_user_id = $contact_user_id WHERE contact_id = $contact_id"); // A new address hasn't bounced (functions/contact_bounce.php) if (strtolower(trim((string) $row['contact_email'])) !== strtolower(trim((string) stripslashes($email)))) { @@ -717,7 +717,7 @@ if (isset($_GET['anonymize_contact'])) { $contact_id = intval($_GET['anonymize_contact']); // Get contact & client info - $sql = mysqli_query($mysqli,"SELECT contact_name, contact_email, contact_phone, contact_client_id, contact_user_id FROM contacts WHERE contact_id = $contact_id"); + $sql = mysqli_query($mysqli,"SELECT contact_name, contact_email, " . contactEmailAltColumn() . ", contact_phone, contact_client_id, contact_user_id FROM contacts WHERE contact_id = $contact_id"); $row = mysqli_fetch_assoc($sql); if (!$row) { flashAlert('That contact no longer exists.', 'error'); @@ -727,7 +727,7 @@ if (isset($_GET['anonymize_contact'])) { $contact_name = escapeSql($row['contact_name']); // Redacted as stored, not SQL-escaped - a name with an apostrophe was missed - and never an empty value. // Longest first, so the first name doesn't take a piece out of the email address before it goes - $info_to_redact = array_values(array_filter(array_map('strval', [$row['contact_name'], explode(" ", (string) $row['contact_name'])[0], $row['contact_email'], $row['contact_phone']]), 'strlen')); + $info_to_redact = array_values(array_filter(array_map('strval', [$row['contact_name'], explode(" ", (string) $row['contact_name'])[0], $row['contact_email'], $row['contact_email_alt'], $row['contact_phone']]), 'strlen')); usort($info_to_redact, function ($a, $b) { return strlen($b) - strlen($a); }); @@ -745,6 +745,9 @@ if (isset($_GET['anonymize_contact'])) { mysqli_query($mysqli,"UPDATE contacts SET contact_title = '' WHERE contact_id = $contact_id"); mysqli_query($mysqli,"UPDATE contacts SET contact_department = '' WHERE contact_id = $contact_id"); mysqli_query($mysqli,"UPDATE contacts SET contact_email = '' WHERE contact_id = $contact_id"); + if (contactEmailAltReady()) { + mysqli_query($mysqli,"UPDATE contacts SET contact_email_alt = '' WHERE contact_id = $contact_id"); + } mysqli_query($mysqli,"UPDATE contacts SET contact_phone = '' WHERE contact_id = $contact_id"); mysqli_query($mysqli,"UPDATE contacts SET contact_extension = '' WHERE contact_id = $contact_id"); mysqli_query($mysqli,"UPDATE contacts SET contact_mobile = '' WHERE contact_id = $contact_id"); @@ -1305,7 +1308,7 @@ if (isExportRequest('export_contacts')) { LEFT JOIN tags ON tags.tag_id = contact_tags.tag_id WHERE $archive_query $tag_query - AND (contact_name LIKE '%$q%' OR contact_title LIKE '%$q%' OR location_name LIKE '%$q%' OR contact_email LIKE '%$q%' OR contact_department LIKE '%$q%' OR contact_phone LIKE '%$q%' OR contact_mobile LIKE '%$q%' OR client_name LIKE '%$q%' OR tag_name LIKE '%$q%') + AND (contact_name LIKE '%$q%' OR contact_title LIKE '%$q%' OR location_name LIKE '%$q%' OR contact_email LIKE '%$q%'" . contactEmailAltLikeSql($q) . " OR contact_department LIKE '%$q%' OR contact_phone LIKE '%$q%' OR contact_mobile LIKE '%$q%' OR client_name LIKE '%$q%' OR tag_name LIKE '%$q%') " . clientScopeSql('contact_client_id') . " $client_query $location_query diff --git a/agent/post/contact_model.php b/agent/post/contact_model.php index 44a3c0ae5..d6c74dba5 100644 --- a/agent/post/contact_model.php +++ b/agent/post/contact_model.php @@ -10,6 +10,9 @@ $extension = preg_replace("/[^0-9]/", '', $_POST['extension'] ?? ''); $mobile_country_code = preg_replace("/[^0-9]/", '', $_POST['mobile_country_code'] ?? ''); $mobile = preg_replace("/[^0-9]/", '', $_POST['mobile'] ?? ''); $email = escapeSql($_POST['email'] ?? ''); +// Their alternate email - an address, not the same as Email (functions/contact.php); SQL-escaped +$email_alt = escapeSql(contactEmailAltClean($_POST['email_alt'] ?? '', $_POST['email'] ?? '')); +$email_alt_sql = contactEmailAltReady() && isset($_POST['email_alt']) ? ", contact_email_alt = '$email_alt'" : ''; $notes = escapeSql($_POST['notes'] ?? ''); $contact_primary = intval($_POST['contact_primary'] ?? 0); $contact_important = intval($_POST['contact_important'] ?? 0); diff --git a/agent/tickets.php b/agent/tickets.php index b4569ea1e..adbfbfb67 100644 --- a/agent/tickets.php +++ b/agent/tickets.php @@ -186,7 +186,7 @@ if ($date_filter_active) { // Search if ($q !== '') { $filter_sql[] = "AND (CONCAT(ticket_prefix, ticket_number) LIKE '%$q%' OR ticket_subject LIKE '%$q%' OR client_name LIKE '%$q%' - OR contact_name LIKE '%$q%' OR contact_email LIKE '%$q%' OR ticket_status_name LIKE '%$q%' OR ticket_priority LIKE '%$q%' + OR contact_name LIKE '%$q%' OR contact_email LIKE '%$q%'" . contactEmailAltLikeSql($q) . " OR ticket_status_name LIKE '%$q%' OR ticket_priority LIKE '%$q%' OR user_name LIKE '%$q%' OR asset_name LIKE '%$q%' OR vendor_name LIKE '%$q%' OR ticket_vendor_ticket_number LIKE '%$q%' OR category_name LIKE '%$q%' " . tagSearchSql('ticket', $q, 'tickets.ticket_id') . ")"; } diff --git a/api/v1/contacts/contact_model.php b/api/v1/contacts/contact_model.php index dcd3aa035..3d78917d8 100644 --- a/api/v1/contacts/contact_model.php +++ b/api/v1/contacts/contact_model.php @@ -38,6 +38,12 @@ if (isset($_POST['contact_email'])) { $email = ''; } +// The alternate email - an address, not the same as the email (functions/contact.php); kept as it was when not posted +$email_alt_sql = ''; +if (contactEmailAltReady() && isset($_POST['contact_email_alt'])) { + $email_alt_sql = ", contact_email_alt = '" . escapeSql(contactEmailAltClean($_POST['contact_email_alt'], stripslashes($email))) . "'"; +} + if (isset($_POST['contact_phone'])) { $phone = preg_replace(number_regex, '', $_POST['contact_phone']); } elseif ($contact_row) { diff --git a/api/v1/contacts/create.php b/api/v1/contacts/create.php index 34b0a6b92..60bd0cb93 100644 --- a/api/v1/contacts/create.php +++ b/api/v1/contacts/create.php @@ -15,7 +15,7 @@ $insert_id = false; if (!empty($name) && !empty($email) && !empty($client_id)) { // Check contact with $email doesn't already exist - $email_duplication_sql = mysqli_query($mysqli, "SELECT 1 FROM contacts WHERE contact_email = '$email' AND contact_client_id = '$client_id'"); + $email_duplication_sql = mysqli_query($mysqli, "SELECT 1 FROM contacts WHERE " . contactEmailSql(stripslashes($email)) . " AND contact_client_id = '$client_id'"); if (mysqli_num_rows($email_duplication_sql) == 0) { @@ -25,7 +25,7 @@ if (!empty($name) && !empty($email) && !empty($client_id)) { } // Insert contact - $insert_sql = mysqli_query($mysqli, "INSERT INTO contacts SET contact_name = '$name', contact_title = '$title', contact_department = '$department', contact_email = '$email', contact_phone = '$phone', contact_extension = '$extension', contact_mobile = '$mobile', contact_notes = '$notes', contact_primary = '$primary', contact_important = '$important', contact_billing = '$billing', contact_technical = '$technical', contact_location_id = $location_id, contact_client_id = $client_id"); + $insert_sql = mysqli_query($mysqli, "INSERT INTO contacts SET contact_name = '$name', contact_title = '$title', contact_department = '$department', contact_email = '$email'$email_alt_sql, contact_phone = '$phone', contact_extension = '$extension', contact_mobile = '$mobile', contact_notes = '$notes', contact_primary = '$primary', contact_important = '$important', contact_billing = '$billing', contact_technical = '$technical', contact_location_id = $location_id, contact_client_id = $client_id"); // Check insert & get insert ID if ($insert_sql) { diff --git a/api/v1/contacts/read.php b/api/v1/contacts/read.php index 4686af825..c5d800a16 100644 --- a/api/v1/contacts/read.php +++ b/api/v1/contacts/read.php @@ -12,8 +12,8 @@ if (isset($_GET['contact_id'])) { } elseif (isset($_GET['contact_email'])) { // Specific contact via email (single) - $email = mysqli_real_escape_string($mysqli, $_GET['contact_email']); - $sql = mysqli_query($mysqli, "SELECT * FROM contacts WHERE contact_email = '$email' AND 1=1 " . apiClientScopeSql('contact_client_id') . ""); + // Their email, or their alternate one + $sql = mysqli_query($mysqli, "SELECT * FROM contacts WHERE " . contactEmailSql((string) $_GET['contact_email']) . " AND 1=1 " . apiClientScopeSql('contact_client_id') . ""); } elseif (isset($_GET['contact_phone_or_mobile'])) { // Specific contact via phone number or mobile (single) diff --git a/api/v1/contacts/update.php b/api/v1/contacts/update.php index 3dd27a693..d196a7ab5 100644 --- a/api/v1/contacts/update.php +++ b/api/v1/contacts/update.php @@ -23,7 +23,7 @@ if (!empty($contact_id)) { mysqli_query($mysqli,"UPDATE contacts SET contact_primary = 0 WHERE contact_client_id = $client_id"); } - $update_sql = mysqli_query($mysqli, "UPDATE contacts SET contact_name = '$name', contact_title = '$title', contact_department = '$department', contact_email = '$email', contact_phone = '$phone', contact_extension = '$extension', contact_mobile = '$mobile', contact_notes = '$notes', contact_primary = '$primary', contact_important = '$important', contact_billing = '$billing', contact_technical = '$technical', contact_location_id = $location_id, contact_client_id = $client_id WHERE contact_id = $contact_id AND contact_client_id = $client_id LIMIT 1"); + $update_sql = mysqli_query($mysqli, "UPDATE contacts SET contact_name = '$name', contact_title = '$title', contact_department = '$department', contact_email = '$email'$email_alt_sql, contact_phone = '$phone', contact_extension = '$extension', contact_mobile = '$mobile', contact_notes = '$notes', contact_primary = '$primary', contact_important = '$important', contact_billing = '$billing', contact_technical = '$technical', contact_location_id = $location_id, contact_client_id = $client_id WHERE contact_id = $contact_id AND contact_client_id = $client_id LIMIT 1"); // Check insert & get insert ID if ($update_sql) { diff --git a/cron/ticket_email_parser.php b/cron/ticket_email_parser.php index 96bd90d31..ee4c4c6a1 100644 --- a/cron/ticket_email_parser.php +++ b/cron/ticket_email_parser.php @@ -438,7 +438,7 @@ function addReply($from_email, $date, $subject, $ticket_id, $message, $attachmen $from_email_esc = mysqli_real_escape_string($mysqli, $from_email); - $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT ticket_id, ticket_prefix, ticket_number, ticket_subject, ticket_status, ticket_contact_id, ticket_client_id, contact_email, client_name + $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT ticket_id, ticket_prefix, ticket_number, ticket_subject, ticket_status, ticket_contact_id, ticket_client_id, contact_email, " . contactEmailAltColumn() . ", client_name FROM tickets LEFT JOIN contacts on tickets.ticket_contact_id = contacts.contact_id LEFT JOIN clients on tickets.ticket_client_id = clients.client_id @@ -459,10 +459,11 @@ function addReply($from_email, $date, $subject, $ticket_id, $message, $attachmen $reply_by = 0; if ($no_sender) { $who = 'stranger'; - } elseif (trim((string) $row['contact_email']) !== '' && strcasecmp(trim((string) $row['contact_email']), stripslashes($from_email)) === 0) { + } elseif (intval($row['ticket_contact_id']) && contactHasEmail($row, stripslashes($from_email))) { + // The ticket's contact - from their email or their alternate one $who = 'contact'; $reply_by = intval($row['ticket_contact_id']); - } elseif ($client_id && ($contact_row = mysqli_fetch_row(mysqli_query($mysqli, "SELECT contact_id FROM contacts WHERE contact_email = '$from_email_esc' AND contact_client_id = $client_id AND contact_archived_at IS NULL LIMIT 1")))) { + } elseif ($client_id && ($contact_row = mysqli_fetch_row(mysqli_query($mysqli, "SELECT contact_id FROM contacts WHERE " . contactEmailSql(stripslashes($from_email)) . " AND contact_client_id = $client_id AND contact_archived_at IS NULL LIMIT 1")))) { $who = 'contact'; $reply_by = intval($contact_row[0]); } elseif ($agent_row = mysqli_fetch_row(mysqli_query($mysqli, "SELECT user_id FROM users WHERE user_email = '$from_email_esc' AND user_type = 1 AND user_status = 1 AND user_archived_at IS NULL LIMIT 1"))) { diff --git a/db.sql b/db.sql index 9e8f8e7c3..511998c2a 100644 --- a/db.sql +++ b/db.sql @@ -1146,6 +1146,7 @@ CREATE TABLE `contacts` ( `contact_name` varchar(200) NOT NULL, `contact_title` varchar(200) DEFAULT NULL, `contact_email` varchar(200) DEFAULT NULL, + `contact_email_alt` varchar(200) DEFAULT NULL, `contact_email_bounced_at` datetime DEFAULT NULL, `contact_email_bounce` varchar(255) DEFAULT NULL, `contact_unsubscribed_at` datetime DEFAULT NULL, diff --git a/functions/contact.php b/functions/contact.php index 024c3a410..7e52ae006 100644 --- a/functions/contact.php +++ b/functions/contact.php @@ -204,3 +204,82 @@ function quickAddButton($type, $client_id = 0, $class = 'btn btn-outline-seconda . (intval($client_id) ? ' data-quick-add-client="' . intval($client_id) . '"' : '') . ' title="' . $titles[$type] . '" aria-label="' . $titles[$type] . '">'; } + +/* ------------------------------------------------------------ Alternate email (4.4.1) */ + +/** Whether the 4.4.1 update has run - contacts have an alternate email (contact_email_alt). */ +function contactEmailAltReady() { + global $mysqli; + static $ready = null; + if ($ready === null) { + $version = defined('CURRENT_DATABASE_VERSION') ? CURRENT_DATABASE_VERSION + : (string) (mysqli_fetch_row(mysqli_query($mysqli, "SELECT config_current_database_version FROM settings WHERE company_id = 1"))[0] ?? '0'); + $ready = version_compare($version, '4.4.1', '>='); + } + return $ready; +} + +/* + * SQL for a contact whose email or alternate email is $email (raw) - for finding who an email is from. $table, a table + * alias in front of the columns, as "c." for c.contact_email. An empty address finds nobody. + */ +function contactEmailSql($email, $table = '') { + $email = trim((string) $email); + if ($email === '') { + return '0'; + } + $email_sql = escapeSql($email); + return contactEmailAltReady() ? "({$table}contact_email = '$email_sql' OR {$table}contact_email_alt = '$email_sql')" : "{$table}contact_email = '$email_sql'"; +} + +/** The alternate email as a SELECT column - '' before the 4.4.1 update. */ +function contactEmailAltColumn() { + return contactEmailAltReady() ? 'contact_email_alt' : "'' AS contact_email_alt"; +} + +/** " OR contact_email_alt LIKE '%...%'" for a search, $like SQL-escaped as the search's own - '' before the 4.4.1 update. */ +function contactEmailAltLikeSql($like, $table = '') { + return contactEmailAltReady() ? " OR {$table}contact_email_alt LIKE '%$like%'" : ''; +} + +/** Whether $email (raw) is the contact's ($row: contact_email, contact_email_alt) - their email or their alternate one, any case. */ +function contactHasEmail(array $row, $email) { + $email = strtolower(trim((string) $email)); + if ($email === '') { + return false; + } + return strtolower(trim((string) ($row['contact_email'] ?? ''))) === $email || strtolower(trim((string) ($row['contact_email_alt'] ?? ''))) === $email; +} + +/* + * An alternate email as posted, trimmed - an address, at most 200 characters, and not the contact's own email ($email, in any + * case) - or '' for none. + */ +function contactEmailAltClean($alt, $email = '') { + $alt = trim((string) $alt); + if ($alt === '' || mb_strlen($alt) > 200 || !filter_var($alt, FILTER_VALIDATE_EMAIL) || strtolower($alt) === strtolower(trim((string) $email))) { + return ''; + } + return $alt; +} + +/* + * SQL for a contact with an address that $match takes - an address, or a domain and its subdomains, as an ignored sender + * or an email routing rule has it - by their email or their alternate one. Any case. For the warnings on saving one. + */ +function contactEmailMatchSql($match) { + $match = strtolower(trim((string) $match)); + if ($match === '') { + return '0'; + } + $parts = []; + foreach (contactEmailAltReady() ? ['contact_email', 'contact_email_alt'] : ['contact_email'] as $column) { + if (strpos($match, '@') !== false) { + $parts[] = "LOWER($column) = '" . escapeSql($match) . "'"; + } else { + $like = escapeSql(str_replace(['\\', '%', '_'], ['\\\\', '\\%', '\\_'], $match)); + $parts[] = "LOWER($column) LIKE '%@$like' OR LOWER($column) LIKE '%.$like'"; + } + } + return '(' . implode(' OR ', $parts) . ')'; +} diff --git a/functions/export.php b/functions/export.php index 287a8408a..581e83d1c 100644 --- a/functions/export.php +++ b/functions/export.php @@ -76,6 +76,7 @@ function getExportColumns($export_type) { 'contact_title' => ['label' => 'Title'], 'contact_department' => ['label' => 'Department'], 'contact_email' => ['label' => 'Email', 'weight' => 2], + 'contact_email_alt' => ['label' => 'Alternate Email', 'weight' => 2], 'contact_phone' => ['label' => 'Phone', 'format' => 'phone'], 'contact_extension' => ['label' => 'Ext'], 'contact_mobile' => ['label' => 'Mobile', 'format' => 'phone'], diff --git a/functions/import_kinds.php b/functions/import_kinds.php index 464ab8244..131d63f97 100644 --- a/functions/import_kinds.php +++ b/functions/import_kinds.php @@ -96,6 +96,7 @@ function importKinds() { 'title' => $f('Title', ['Job Title'], ['example' => 'Office Manager']), 'department' => $f('Department', ['Department Name']), 'email' => $f('Email', ['Email Address', 'E-mail'], ['example' => 'jordan@example.com']), + 'email_alt' => $f('Alternate Email', ['Alt Email', 'Alternate Email Address', 'Secondary Email', 'Other Email', 'Personal Email', 'Email 2'], ['example' => 'jordan@personal.example', 'about' => 'Email from it is theirs too']), 'phone' => $f('Phone', ['Office Phone', 'Work Phone', 'Phone Number'], ['example' => '412-555-0100']), 'extension' => $f('Ext', ['Extension', 'Office Extension']), 'mobile' => $f('Mobile', ['Mobile Phone', 'Cell', 'Cell Phone']), @@ -629,6 +630,14 @@ function importContactRow(array $row, $client_id, $existing_id, $write) { $set[] = 'contact_email = ' . importSqlText($value); } } + // The alternate email - an address, and not their Email (functions/contact.php) + if (contactEmailAltReady() && ($value = $give('email_alt')) !== null) { + if ($value !== '' && contactEmailAltClean($value, (string) ($give('email') ?? '')) === '') { + $notes[] = importLeftNote('Alternate Email', $value, filter_var($value, FILTER_VALIDATE_EMAIL) ? 'is the same as their Email' : "isn't an email address", $up); + } else { + $set[] = 'contact_email_alt = ' . importSqlText($value, 200); + } + } foreach (['phone', 'mobile'] as $key) { if (($value = $give($key)) !== null) { $set[] = importPhoneSql($value, "contact_$key"); diff --git a/functions/mail_ignore.php b/functions/mail_ignore.php index ba08e209f..3c5a9c174 100644 --- a/functions/mail_ignore.php +++ b/functions/mail_ignore.php @@ -104,12 +104,12 @@ function mailIgnoreReach($match) { } $match_sql = escapeSql($match); if (strpos($match, '@') !== false) { - $out['contacts'] = intval(mysqli_fetch_row(mysqli_query($mysqli, "SELECT COUNT(*) FROM contacts WHERE contact_archived_at IS NULL AND LOWER(contact_email) = '$match_sql'"))[0] ?? 0); + $out['contacts'] = intval(mysqli_fetch_row(mysqli_query($mysqli, "SELECT COUNT(*) FROM contacts WHERE contact_archived_at IS NULL AND " . contactEmailMatchSql($match)))[0] ?? 0); return $out; } $like = escapeSql(str_replace(['\\', '%', '_'], ['\\\\', '\%', '\_'], $match)); - $out['contacts'] = intval(mysqli_fetch_row(mysqli_query($mysqli, "SELECT COUNT(*) FROM contacts WHERE contact_archived_at IS NULL - AND (LOWER(contact_email) LIKE '%@$like' OR LOWER(contact_email) LIKE '%.$like')"))[0] ?? 0); + // Their email or their alternate one (functions/contact.php) + $out['contacts'] = intval(mysqli_fetch_row(mysqli_query($mysqli, "SELECT COUNT(*) FROM contacts WHERE contact_archived_at IS NULL AND " . contactEmailMatchSql($match)))[0] ?? 0); $sql = mysqli_query($mysqli, "SELECT DISTINCT client_name FROM domains JOIN clients ON client_id = domain_client_id WHERE domain_archived_at IS NULL AND client_archived_at IS NULL AND (LOWER(domain_name) = '$match_sql' OR LOWER(domain_name) LIKE '%.$like') ORDER BY client_name LIMIT 5"); while ($sql && ($row = mysqli_fetch_row($sql))) { diff --git a/functions/mail_route.php b/functions/mail_route.php index 450fef4e7..956058160 100644 --- a/functions/mail_route.php +++ b/functions/mail_route.php @@ -229,12 +229,12 @@ function mailRouteReach($match, $client_id = 0) { $match_sql = escapeSql($match); $other = "AND contact_client_id <> $client_id"; if (strpos($match, '@') !== false) { - $out['contacts'] = intval(mysqli_fetch_row(mysqli_query($mysqli, "SELECT COUNT(*) FROM contacts WHERE contact_archived_at IS NULL AND LOWER(contact_email) = '$match_sql' $other"))[0] ?? 0); + $out['contacts'] = intval(mysqli_fetch_row(mysqli_query($mysqli, "SELECT COUNT(*) FROM contacts WHERE contact_archived_at IS NULL $other AND " . contactEmailMatchSql($match)))[0] ?? 0); return $out; } $like = escapeSql(str_replace(['\\', '%', '_'], ['\\\\', '\%', '\_'], $match)); - $out['contacts'] = intval(mysqli_fetch_row(mysqli_query($mysqli, "SELECT COUNT(*) FROM contacts WHERE contact_archived_at IS NULL $other - AND (LOWER(contact_email) LIKE '%@$like' OR LOWER(contact_email) LIKE '%.$like')"))[0] ?? 0); + // Their email or their alternate one (functions/contact.php) + $out['contacts'] = intval(mysqli_fetch_row(mysqli_query($mysqli, "SELECT COUNT(*) FROM contacts WHERE contact_archived_at IS NULL $other AND " . contactEmailMatchSql($match)))[0] ?? 0); $sql = mysqli_query($mysqli, "SELECT DISTINCT client_name FROM domains JOIN clients ON client_id = domain_client_id WHERE domain_archived_at IS NULL AND client_archived_at IS NULL AND client_id <> $client_id AND (LOWER(domain_name) = '$match_sql' OR LOWER(domain_name) LIKE '%.$like') ORDER BY client_name LIMIT 5"); diff --git a/functions/search.php b/functions/search.php index 618b0bacb..5a9d2e179 100644 --- a/functions/search.php +++ b/functions/search.php @@ -193,7 +193,7 @@ function globalSearchGroups($terms, $deep) { 'select' => 'contact_id, contact_name, contact_title, contact_email, contact_photo, contact_client_id, client_name', 'from' => 'contacts LEFT JOIN clients ON contact_client_id = client_id', 'where' => "contact_archived_at IS NULL - AND (contact_name LIKE '%$like%' OR contact_email LIKE '%$like%' OR contact_title LIKE '%$like%' $contact_phone_match + AND (contact_name LIKE '%$like%' OR contact_email LIKE '%$like%'" . contactEmailAltLikeSql($like) . " OR contact_title LIKE '%$like%' $contact_phone_match " . tagSearchSql('contact', $like, 'contacts.contact_id') . ")", 'scope' => 'contact_client_id', 'tags' => ['contact', 'contacts.contact_id'], diff --git a/functions/ticket_mail_decide.php b/functions/ticket_mail_decide.php index d07682b62..4459b6d12 100644 --- a/functions/ticket_mail_decide.php +++ b/functions/ticket_mail_decide.php @@ -147,15 +147,17 @@ function ticketMailDecide(array $in) { $domain_row = null; $contact = null; if (!$visitor) { - $contact = $route['contact'] ? $route['contact'] + ['client_name' => $route_client['client_name']] : (mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT contact_id, contact_name, contact_email, contact_client_id, client_name - FROM contacts LEFT JOIN clients ON client_id = contact_client_id WHERE contact_client_id = " . intval($route_client['client_id']) . " AND contact_email = '$from_sql' AND contact_archived_at IS NULL LIMIT 1")) ?: null); + $contact = $route['contact'] ? $route['contact'] + ['client_name' => $route_client['client_name']] : (mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT contact_id, contact_name, contact_email, " . contactEmailAltColumn() . ", contact_client_id, client_name + FROM contacts LEFT JOIN clients ON client_id = contact_client_id WHERE contact_client_id = " . intval($route_client['client_id']) . " AND " . contactEmailSql($from) . " AND contact_archived_at IS NULL LIMIT 1")) ?: null); } } // A routed email's sender is answered and copied in only as the ticket's contact - who they are, or who they will be as a // new contact at a client's domain: a system's address isn't sent "we have your email" and every reply after it - $sender_is_contact = $contact && strtolower((string) $contact['contact_email']) === $from; + // The sender is the contact by their email or their alternate one (contactHasEmail(), functions/contact.php) - from their + // alternate one, or someone else's for a rule's contact, the ticket says the address it came from + $sender_is_contact = $contact && contactHasEmail($contact, $from); $out['quiet'] = $route && !($visitor || $sender_is_contact || ($domain_row && $forged === '')); - if ($contact && !$sender_is_contact && !$visitor) { + if ($contact && !$visitor && strtolower(trim((string) $contact['contact_email'])) !== $from) { $out['sender'] = ['name' => (string) ($in['from_name'] ?? ''), 'email' => $from]; } @@ -176,7 +178,7 @@ function ticketMailDecide(array $in) { } if ($out['similar']) { $similar = $out['similar']; - $theirs = !$visitor && !$forward && !$out['quiet'] && (($contact && !$out['sender'] && intval($contact['contact_id']) === intval($similar['ticket_contact_id'])) + $theirs = !$visitor && !$forward && !$out['quiet'] && (($contact && $sender_is_contact && intval($contact['contact_id']) === intval($similar['ticket_contact_id'])) || ($from !== '' && mysqli_num_rows(mysqli_query($mysqli, "SELECT 1 FROM ticket_ccs WHERE ticket_cc_ticket_id = " . intval($similar['ticket_id']) . " AND ticket_cc_email = '$from_sql' LIMIT 1")))); if ($theirs) { $step('The same subject as an open ticket of theirs from the last week?', 'Yes - ' . ticketReference($similar)); @@ -197,7 +199,8 @@ function ticketMailDecide(array $in) { // 4. A contact - a website form sent as one (an address made a contact before) is that contact's client's, from its visitor if ($contact) { $others = $picked['others'] ? ' - and at ' . implode(', ', $picked['others']) . ' too, so it goes to ' . ($contact['client_name'] ?? 'no client') . ', ' . $picked['why'] : ''; - $step('A contact\'s address?', 'Yes - ' . $contact['contact_name'] . ($contact['client_name'] !== null ? ', ' . $contact['client_name'] : '') . $others); + $step('A contact\'s address?', 'Yes - ' . $contact['contact_name'] . ($contact['client_name'] !== null ? ', ' . $contact['client_name'] : '') + . (strtolower(trim((string) $contact['contact_email'])) !== $from ? ' - their alternate email' : '') . $others); return ['action' => 'ticket', 'client_id' => intval($contact['contact_client_id']), 'client_name' => $contact['client_name'] ?? null, 'contact' => $visitor ? null : $contact, 'picked' => $visitor ? [] : $picked] + $out; } diff --git a/functions/ticket_mail_thread.php b/functions/ticket_mail_thread.php index 8e0e4432a..7113cbc6a 100644 --- a/functions/ticket_mail_thread.php +++ b/functions/ticket_mail_thread.php @@ -234,12 +234,14 @@ function ticketMailSubjectTicket($subject) { function ticketMailCopiedCcs($ticket_id, array $addresses, $sender) { global $mysqli; $ticket_id = intval($ticket_id); - $contact_email = strtolower(trim((string) (mysqli_fetch_row(mysqli_query($mysqli, "SELECT contact_email FROM tickets - JOIN contacts ON contact_id = ticket_contact_id WHERE ticket_id = $ticket_id"))[0] ?? ''))); + $contact = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT contact_email, " . contactEmailAltColumn() . " FROM tickets + JOIN contacts ON contact_id = ticket_contact_id WHERE ticket_id = $ticket_id")) ?: []; + $contact_email = strtolower(trim((string) ($contact['contact_email'] ?? ''))); + $contact_email_alt = strtolower(trim((string) ($contact['contact_email_alt'] ?? ''))); $sender = strtolower(trim((string) $sender)); $emails = []; foreach (ticketCcEmails($addresses) as $email) { - if ($email === $sender || $email === $contact_email || emailOwnAddress($email) || emailOwnDomain($email) + if ($email === $sender || $email === $contact_email || ($contact_email_alt !== '' && $email === $contact_email_alt) || emailOwnAddress($email) || emailOwnDomain($email) || preg_match('/do[\W_]*not[\W_]*reply|no[\W_]*reply/i', $email)) { continue; } @@ -252,11 +254,12 @@ function ticketMailCopiedCcs($ticket_id, array $addresses, $sender) { } /* - * The contact an email from $email is from, when it is one - ['contact' => row (contact_id, contact_name, contact_email, - * contact_client_id, client_name) or null, 'others' => the other clients it is a contact at, [client_id => name], - * 'why' => how the one was picked]. An address can be a contact at more than one client - someone who works for two, - * a shared mailbox - and its email went to whichever the database gave first. Now: the client whose domain it is - * ($domain, Domains), else the one they last raised a ticket at, else the first they were added to. + * The contact an email from $email is from, when it is one - their Email or their alternate one - ['contact' => row + * (contact_id, contact_name, contact_email, contact_email_alt, contact_client_id, client_name) or null, 'others' => the + * other clients it is a contact at, [client_id => name], 'why' => how the one was picked]. An address can be a contact at + * more than one client - someone who works for two, a shared mailbox - and its email went to whichever the database gave + * first. Now: the client whose domain it is ($domain, Domains), else a contact whose Email it is over one whose alternate + * it is, else the one they last raised a ticket at, else the first they were added to. */ function ticketMailSenderContact($email, $domain = '') { global $mysqli; @@ -268,12 +271,12 @@ function ticketMailSenderContact($email, $domain = '') { $email_sql = escapeSql($email); $domain_sql = escapeSql(strtolower(trim((string) $domain))); $rows = []; - $sql = mysqli_query($mysqli, "SELECT contact_id, contact_name, contact_email, contact_client_id, client_name, + $sql = mysqli_query($mysqli, "SELECT contact_id, contact_name, contact_email, " . contactEmailAltColumn() . ", contact_client_id, client_name, (SELECT 1 FROM domains WHERE domain_client_id = contact_client_id AND domain_name = '$domain_sql' AND domain_archived_at IS NULL LIMIT 1) AS at_domain, (SELECT MAX(ticket_created_at) FROM tickets WHERE ticket_contact_id = contact_id) AS last_ticket FROM contacts LEFT JOIN clients ON client_id = contact_client_id - WHERE contact_email = '$email_sql' AND contact_archived_at IS NULL - ORDER BY at_domain DESC, last_ticket DESC, contact_id"); + WHERE " . contactEmailSql($email) . " AND contact_archived_at IS NULL + ORDER BY at_domain DESC, contact_email = '$email_sql' DESC, last_ticket DESC, contact_id"); while ($row = mysqli_fetch_assoc($sql)) { $rows[] = $row; } @@ -320,7 +323,7 @@ function ticketMailSenderContactNote($ticket_id, $email, array $picked) { function ticketMailClientAddresses($ticket_id, array $addresses) { global $mysqli; $ticket_id = intval($ticket_id); - $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT ticket_client_id, contact_email FROM tickets LEFT JOIN contacts ON contact_id = ticket_contact_id WHERE ticket_id = $ticket_id")); + $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT ticket_client_id, contact_email, " . contactEmailAltColumn() . " FROM tickets LEFT JOIN contacts ON contact_id = ticket_contact_id WHERE ticket_id = $ticket_id")); if (!$row) { return []; } @@ -331,9 +334,9 @@ function ticketMailClientAddresses($ticket_id, array $addresses) { continue; } $email_sql = escapeSql($email); - if (strtolower(trim((string) $row['contact_email'])) === $email + if (contactHasEmail($row, $email) || mysqli_num_rows(mysqli_query($mysqli, "SELECT 1 FROM ticket_ccs WHERE ticket_cc_ticket_id = $ticket_id AND ticket_cc_email = '$email_sql' LIMIT 1")) - || ($client_id && mysqli_num_rows(mysqli_query($mysqli, "SELECT 1 FROM contacts WHERE contact_email = '$email_sql' AND contact_client_id = $client_id AND contact_archived_at IS NULL LIMIT 1")))) { + || ($client_id && mysqli_num_rows(mysqli_query($mysqli, "SELECT 1 FROM contacts WHERE " . contactEmailSql($email) . " AND contact_client_id = $client_id AND contact_archived_at IS NULL LIMIT 1")))) { $found[] = $email; } } diff --git a/functions/ticket_mail_try.php b/functions/ticket_mail_try.php index 6f84a4062..ddd90d98e 100644 --- a/functions/ticket_mail_try.php +++ b/functions/ticket_mail_try.php @@ -108,9 +108,12 @@ function ticketMailTryOutcome(array $decision, $from_email, $auto_reply = false) $contact_text . 'The subject is its subject and the email its details. ' . $route_text . ($decision['quiet'] ? '' : ' ' . ticketMailTryNoReply($from_email)) . $linked]; } if ($contact) { + // From their alternate email - answered at their Email, where everything ITFlow sends goes + $alternate = strtolower(trim((string) $contact['contact_email'])) !== $from_email; return ['fa-plus-circle', 'success', 'A new ticket for ' . ($decision['client_name'] ?? 'no client'), - 'From ' . $contact['contact_name'] . ', with the subject as its subject and the email as its details. ' . (!empty($decision['picked']['others']) ? 'A note on it names the other clients they are a contact at. ' : '') - . ($route_text !== '' ? $route_text . ' ' : '') . ticketMailTryNoReply($from_email) . $linked]; + 'From ' . $contact['contact_name'] . ($alternate ? ', at their alternate email' : '') . ', with the subject as its subject and the email as its details. ' . (!empty($decision['picked']['others']) ? 'A note on it names the other clients they are a contact at. ' : '') + . ($route_text !== '' ? $route_text . ' ' : '') . ticketMailTryNoReply((string) $contact['contact_email']) + . ($alternate ? ' That goes to their Email, ' . $contact['contact_email'] . ', as all their ticket email does.' : '') . $linked]; } if ($decision['new_contact']) { return ['fa-plus-circle', 'success', 'A new contact and ticket for ' . $decision['client_name'], @@ -150,7 +153,7 @@ function ticketMailTryRoute(array $route, $quiet) { function ticketMailTryReply($from_email, $ticket_id) { global $mysqli; $from_sql = escapeSql($from_email); - $ticket = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT ticket_id, ticket_prefix, ticket_number, ticket_subject, ticket_status, ticket_client_id, contact_email, contact_name, client_name + $ticket = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT ticket_id, ticket_prefix, ticket_number, ticket_subject, ticket_status, ticket_client_id, ticket_contact_id, contact_email, " . contactEmailAltColumn() . ", contact_name, client_name FROM tickets LEFT JOIN contacts ON contact_id = ticket_contact_id LEFT JOIN clients ON client_id = ticket_client_id WHERE ticket_id = " . intval($ticket_id) . " LIMIT 1")); if (!$ticket) { @@ -159,8 +162,9 @@ function ticketMailTryReply($from_email, $ticket_id) { $reference = ticketReference($ticket); $on = $reference . ' - ' . $ticket['ticket_subject'] . ($ticket['client_name'] !== null ? ' (' . $ticket['client_name'] . ')' : ''); $client_id = intval($ticket['ticket_client_id']); - $known = (strtolower((string) $ticket['contact_email']) === $from_email && $from_email !== '') - || ($client_id && mysqli_num_rows(mysqli_query($mysqli, "SELECT 1 FROM contacts WHERE contact_email = '$from_sql' AND contact_client_id = $client_id AND contact_archived_at IS NULL LIMIT 1"))) + $is_contact = intval($ticket['ticket_contact_id']) && contactHasEmail($ticket, $from_email); + $known = $is_contact + || ($client_id && mysqli_num_rows(mysqli_query($mysqli, "SELECT 1 FROM contacts WHERE " . contactEmailSql($from_email) . " AND contact_client_id = $client_id AND contact_archived_at IS NULL LIMIT 1"))) || mysqli_num_rows(mysqli_query($mysqli, "SELECT 1 FROM ticket_ccs WHERE ticket_cc_ticket_id = " . intval($ticket['ticket_id']) . " AND ticket_cc_email = '$from_sql' LIMIT 1")); if (intval($ticket['ticket_status']) === TICKET_STATUS_CLOSED) { return ['fa-ban', 'warning', "A note on $reference - it is closed", @@ -168,10 +172,10 @@ function ticketMailTryReply($from_email, $ticket_id) { . ($known ? '. The sender is told it is closed, and how to raise a new ticket.' : '. The sender isn\'t a contact or CC, so nobody is told - a guessed number would tell them its subject.')]; } $reopens = ticketMailTryReopens($ticket['ticket_status']); - if (strtolower((string) $ticket['contact_email']) === $from_email && $from_email !== '') { - return ['fa-reply', 'success', "A reply on $on", 'From its contact, ' . $ticket['contact_name'] . ', as the client\'s reply. ' . $reopens]; + if ($is_contact) { + return ['fa-reply', 'success', "A reply on $on", 'From its contact, ' . $ticket['contact_name'] . (strtolower(trim((string) $ticket['contact_email'])) !== $from_email ? ' - their alternate email' : '') . ', as the client\'s reply. ' . $reopens]; } - $other = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT contact_name FROM contacts WHERE contact_email = '$from_sql' AND contact_client_id = $client_id LIMIT 1")); + $other = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT contact_name FROM contacts WHERE " . contactEmailSql($from_email) . " AND contact_client_id = $client_id LIMIT 1")); if ($other) { return ['fa-reply', 'success', "A reply on $on", 'From ' . $other['contact_name'] . ', another of the client\'s contacts, as the client\'s reply. ' . $reopens]; }