From cd52393138d2e44439cbe638c5bb13eec803c170 Mon Sep 17 00:00:00 2001 From: johnnyq Date: Tue, 20 Oct 2026 12:56:01 -0400 Subject: [PATCH] Settings stage 4: Mail's Sending, Receiving, OAuth and From addresses tabs moved into the settings frame with provider-driven fields, refusals shown beside each field on the same tab and changes logged from old to new; passwords, the OAuth client secret and refresh token are no longer written into the page and are saved exactly as typed; a changed OAuth app or refresh token clears the cached access token, the access token field is removed and Microsoft 365 requires the tenant ID; the Microsoft connect callback stores only the tokens instead of switching both Sending and Receiving to Microsoft 365; Enter saves on the OAuth tab and on Logs; From addresses that are not email addresses are refused and From names keep their punctuation; removed the broken custom fields page with its handler and modals, the unused AI and online payment settings handlers, and the client autopay page --- CHANGELOG.md | 12 +- .../custom_field/custom_field_create.php | 38 -- .../modals/custom_field/custom_field_edit.php | 37 -- admin/oauth_microsoft_mail_callback.php | 7 +- admin/post/custom_field.php | 63 --- admin/post/custom_field_model.php | 5 - admin/post/settings_ai.php | 27 - admin/post/settings_mail.php | 346 +++++++----- admin/post/settings_online_payment.php | 30 - .../post/settings_online_payment_clients.php | 73 --- admin/settings_custom_fields.php | 117 ---- admin/settings_logs.php | 1 + admin/settings_mail.php | 516 +++++++++--------- agent/client_autopay.php | 130 ----- functions/settings.php | 82 ++- 15 files changed, 533 insertions(+), 951 deletions(-) delete mode 100644 admin/modals/custom_field/custom_field_create.php delete mode 100644 admin/modals/custom_field/custom_field_edit.php delete mode 100644 admin/post/custom_field.php delete mode 100644 admin/post/custom_field_model.php delete mode 100644 admin/post/settings_ai.php delete mode 100644 admin/post/settings_online_payment.php delete mode 100644 admin/post/settings_online_payment_clients.php delete mode 100644 admin/settings_custom_fields.php delete mode 100644 agent/client_autopay.php diff --git a/CHANGELOG.md b/CHANGELOG.md index 4c53e7b52..3f707d471 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1027,7 +1027,8 @@ If you are coming from 26.08 or earlier, the database update still has to be run - The pages are laid out alike: what the page is for at the top, then sections, each with what it is for beside its fields. Once something is changed the bar at the foot says so, with Undo changes beside Save, and leaving the page asks first. A save with something wrong in it comes back with what is wrong beside each field and everything typed still there, and saves nothing. The audit log says what changed, from what to what - "Next ticket number 4021 → 4100" - and a save that changed nothing says so. - Company details, Localization, Theme, Modules and Telemetry are the first pages in it. Company details shows the logo, and a new one before it is saved, with a button to take it off; the phone takes its country code from the country picked; the website is kept without its https://. Localization shows money and the time now as the language, currency and timezone picked will write them. A theme colour shows across the page as soon as it is picked, and Save keeps it; the browser tab icon is shown, with a way back to ITFlow's. Modules says what each one holds, and that switching one off deletes nothing. Telemetry is one switch, with exactly what the nightly report holds. - Tickets, Projects, Quotes, Invoices and billing, and Defaults are in it too. Each prefix and next number shows the number the next one will get as it is typed, and the last one made; a number already used is said at once, and can't be saved. Tickets is in sections - numbering, email to ticket, new tickets, time and billing, closing, and the tickets page - with what happens to an email from an unknown sender when they are left out. Invoices and billing holds numbering for invoices and recurring invoices, the footer and tax ID, late fees (with a warning when reminders are off, as no fee is added then), who hears of a payment made online, reminders and statements, billing time, billable expenses, and trips and mileage. Defaults is grouped into opening ITFlow, new clients and accounts; the start page can be any page of ITFlow typed in, and an account archived since it was picked stays picked. - - Notifications, Security, Client portal, Single sign-on, Mail and Logs complete it. Notifications is no longer a table of mostly empty columns: alerts for your team, and the emails clients get by themselves, each saying when it goes - with a warning while mail sending is off, and reminders shown as they are, set in Invoices and billing. Security shows the address agents sign in at as the login key is typed, and requiring a key with none set is refused rather than quietly switched off. Single sign-on gives the redirect address to register in Microsoft Entra, with a copy button, and no longer puts the client secret into the page - left empty, it stays as saved. Mail keeps its tabs, each with the save bar. + - Notifications, Security, Client portal, Single sign-on, Mail and Logs complete it. Notifications is no longer a table of mostly empty columns: alerts for your team, and the emails clients get by themselves, each saying when it goes - with a warning while mail sending is off, and reminders shown as they are, set in Invoices and billing. Security shows the address agents sign in at as the login key is typed, and requiring a key with none set is refused rather than quietly switched off. Single sign-on gives the redirect address to register in Microsoft Entra, with a copy button, and no longer puts the client secret into the page - left empty, it stays as saved. + - Mail keeps its tabs, laid out like the rest. Sending and Receiving show only what the provider picked takes: for a server, its name, port, encryption (with the port each usually has) and sign-in; for Google Workspace or Microsoft 365, the account that signs in, whether the OAuth app is connected, and the way to it. The OAuth tab says how to set the app up for the provider picked and whether it is connected, with the redirect address to copy. Passwords, the OAuth client secret and its refresh token are no longer put into the page - left empty, they stay as saved. From addresses gives each mailbox - system emails, invoices, quotes and tickets - its own section, saying what it sends. Receiving says whether email to ticket is on to read it. - Settings are in the search window (Ctrl K) for admins: type a setting - late fee, login key, smtp - and pick it to go straight to it. - **Mail Queue** (rebuilt) - Tabs for where each email is - Waiting, Sending, Retrying, Failed, Sent and Cancelled - with how many in each, following the search. Each email says where it stands: scheduled for when, tried 2 of 4 and when it is tried next, gave up, not tried again (a bad address), sent when, or cancelled. @@ -1186,6 +1187,11 @@ If you are coming from 26.08 or earlier, the database update still has to be run - Settings > Defaults: the start page could be anything typed in, and was put into every page's logo link as it was. A default account archived since was dropped the next time Defaults was saved. - Settings > Single sign-on: the Microsoft Entra client secret was put into the page, in the password field's value. - Settings > Security: requiring a login key with none set saved as not required, saying it had been saved. +- Settings > Mail: connecting Microsoft 365 switched both Sending and Receiving to Microsoft 365, whichever one it was connected for - moving sending off a working server, or starting to read a mailbox that wasn't set up. +- Settings > Mail: the SMTP and IMAP passwords, the OAuth client secret and its tokens were put into the page. +- Settings > Mail: a From address that wasn't an email address was saved blank, and From names lost their punctuation - "PittPC, LLC" was saved as "PittPC LLC". +- Settings > Mail: a password or secret lost a space at either end when saved, and anything from a < up to the next > (or to its end). +- Settings > Mail: pressing Enter on the OAuth tab went off to Microsoft to connect, rather than saving. Changing the OAuth app or its refresh token went on using the old access token until it ran out. - Settings > Notifications, and recurring invoices: the note that recurring invoices are made as drafts pointed to the billing settings, but the switch is in Notifications. - Mail Queue: cancelling an email marked it Failed, and an email to a bad address or with no from address showed Failed with no time. - Mail Queue: Resend was only offered once all four tries were used up, and the next failure quietly gave a resent email three more. @@ -1752,7 +1758,9 @@ If you are coming from 26.08 or earlier, the database update still has to be run - `.itflow-setup*` styles in `css/itflow_custom.css`. - Settings: `functions/settings.php` - `settingsPages()` (the menu, the overview and each page's header), `settingsFields()` (every setting: its page, section, label, kind and what else it is searched by - Find a setting and the audit log read it), and the frame: `settingsPageStart()`, `settingsSectionStart()`/`settingsSectionEnd()`, `settingsInput()`, `settingsSelect()`, `settingsSwitch()`, `settingsTextarea()`, `settingsField()` and `settingsSaveBar()`. Handlers read with `settingsCurrent()`, refuse with `settingsRefuse($page, $errors)` (the form comes back once, from `$_SESSION['settings_kept']`), and save with `settingsSave()`, or `settingsWrite()` per table and `settingsSaid()`, which write only what changed and log it. New `admin/settings.php` and `js/settings.js` (loaded on admin pages: `form[data-settings-form]`, `#setting=`, Find a setting, picture previews, the theme preview and the Localization sample). The Settings menu is built from `settingsPages()`. Form fields renamed to their columns on Company details (`company_*`), Localization (`company_locale`, `company_currency`, `config_timezone`) and Theme (`config_theme`, `favicon`). The Preferences light/dark swatch is `.itflow-mode-swatch`. - Settings: Tickets, Projects, Quotes, Invoices and billing and Defaults use the frame. New in `functions/settings.php`: `settingsNumbering($kind)`, `settingsNumberInUse()`, `settingsNumberingCheck($kind, $post, $saved)` (prefix and next number checked against the highest in use with that prefix - skipped when both are as saved, so a clash already there doesn't block the rest of the page) and `settingsNumberingFields()` (with `[data-settings-next]` in `js/settings.js`, and `[data-settings-depends-on=name]` to fade fields while a switch is off); `settingsEmailProblem()`; `settingsStartPages()`, `settingsStartPageProblem()` and `settingsNetTerms()`. `settingsSectionStart()` takes the section's element id, so `#reminders`, `#billing-time`, `#billable-expenses` and `#mileage` still work; `settingsSelect()` takes `options_html`, `append` and `search => false`; `settingsSwitch()` takes `id`. `settingsSame()` treats NULL as 0 or empty and ignores Windows line ends; the log names accounts, calendars and categories. Values kept from a refused save are only used for five minutes. These handlers keep a setting that isn't sent (`$_POST + saved`), a switch not sent being off. Defaults' fields are renamed to their columns (`config_start_page`, `config_default_*`). The start page is escaped where it is printed. -- Settings: Notifications, Security, Client portal, Single sign-on (`admin/identity_providers.php`), Mail and Logs use the frame. `settingsSearch($query, $limit)` scores settings as Find a setting does, leaving out pages for a module that is off; `agent/ajax.php?global_search` returns them as `settings` for admins and `js/global_search.js` shows them under Settings. Single sign-on's fields are renamed to their columns (`config_azure_client_id`, `config_azure_client_secret`). A field marked `quiet` in `settingsFields()` is logged as changed without its value (the login key). The Logs handler is unchanged; Mail's handlers too. +- Settings: Notifications, Security, Client portal, Single sign-on (`admin/identity_providers.php`), Mail and Logs use the frame. `settingsSearch($query, $limit)` scores settings as Find a setting does, leaving out pages for a module that is off; `agent/ajax.php?global_search` returns them as `settings` for admins and `js/global_search.js` shows them under Settings. Single sign-on's fields are renamed to their columns (`config_azure_client_id`, `config_azure_client_secret`). A field marked `quiet` in `settingsFields()` is logged as changed without its value (the login key). The Logs handler is unchanged. +- Settings: Mail's Sending, Receiving, OAuth and From addresses tabs use the frame, and every Mail column is in `settingsFields()`. Its handlers save through `settingsSave()` and `settingsWrite()`, logging from -> to; `edit_mail_smtp_settings` and `edit_mail_imap_settings` share one check, and both come back to their tab when refused. A password, secret or refresh token posted empty keeps what is saved; an empty OAuth client ID forgets its secret and refresh token; a changed app or refresh token clears `config_mail_oauth_access_token` and its expiry, so it is fetched again. The access token is no longer a field. `oauth_connect_microsoft_mail` saves the same way before going to Microsoft, and `admin/oauth_microsoft_mail_callback.php` now stores only the tokens. New in `functions/settings.php`: `settingsMailProviders()`, `settingsMailEncryption()` and `settingsEnterSaves($button)` - a hidden Save placed first in a form whose first button would otherwise be another (Mail's OAuth tab, Logs). `settingsRefuse()` takes the page to go back to; `settingsInput()`, `settingsSelect()` and `settingsTextarea()` take `id`; `settingsWrite()` writes a `secret` field exactly as given, rather than through `escapeSql()`, which trims and strips tags. +- Removed, as nothing reached them or they couldn't run: `admin/settings_custom_fields.php` (it required a modal that no longer existed) with `admin/post/custom_field.php`, `admin/post/custom_field_model.php` and `admin/modals/custom_field/`; `admin/post/settings_ai.php` and `admin/post/settings_online_payment.php`, which wrote the `config_ai_*` and `config_stripe_*` columns dropped in 2.3.2; `admin/post/settings_online_payment_clients.php`, and `agent/client_autopay.php`, which read the dropped Stripe columns and was linked from nowhere. The `custom_fields` and `custom_values` tables stay as they are, and the client export still includes asset custom field values. - Mail Queue: new `functions/mail_queue.php` - `MAIL_QUEUE_TRIES` (4), `MAIL_QUEUE_RETRY_MINUTES` (30) and `MAIL_QUEUE_KEEP_DAYS` (90), which `cron/mail_queue.php`'s retry pass and the nightly clean-up now use too; `mailQueueTabs()`, `mailQueueState($row)`, `mailQueueCan($row, $action)`, `mailQueueAct($action, $ids)` and `mailQueueHealth()`. `email_status` 4 is Cancelled - never selected by the worker. Retry now sets status 0, no attempts and no failure time. Handlers: `retry_mail`, `cancel_mail`, `delete_mail` (GET with the CSRF token) and `bulk_retry_emails`, `bulk_cancel_emails`, `bulk_delete_emails`; `send_failed_mail` still works. The worker sets `email_failed_at` on the bad sender, bad recipient and no-MX paths. - Mail Queue: database 3.3.7 adds `email_queue.email_error` varchar(500) - why it last failed, or "Cancelled by ..."; cleared when sent or retried. The worker writes it on every failure path, through `mailQueueErrorSql()`, which leaves it out until the update has run, so an install between updating its files and its database still sends; `mailQueueErrorColumn()` does the same for reads. The retry pass's bad-recipient path now sets `email_failed_at`, so its backoff counts from that try. An alert (`appNotify`) when the retry pass gives up. The email's window shows the queued HTML in an iframe `srcdoc` with `sandbox="allow-popups allow-popups-to-escape-sandbox"` (no scripts, no same origin) and a `script-src 'none'` policy, instead of HTMLPurifier in the page. - Mail Queue: `mailQueueSummary()` - waiting, retrying, failed in the last day and week, and the last sent - read once a request, for the Settings overview (attention items and the Mail tile), Mail's Tests tab and the admin menu's count (`admin/includes/side_nav.php`). `globalSearchPages()` has Mail Queue for admins. diff --git a/admin/modals/custom_field/custom_field_create.php b/admin/modals/custom_field/custom_field_create.php deleted file mode 100644 index 7ec592f00..000000000 --- a/admin/modals/custom_field/custom_field_create.php +++ /dev/null @@ -1,38 +0,0 @@ - diff --git a/admin/modals/custom_field/custom_field_edit.php b/admin/modals/custom_field/custom_field_edit.php deleted file mode 100644 index 86c841c41..000000000 --- a/admin/modals/custom_field/custom_field_edit.php +++ /dev/null @@ -1,37 +0,0 @@ - diff --git a/admin/oauth_microsoft_mail_callback.php b/admin/oauth_microsoft_mail_callback.php index 52d659a61..7b338abeb 100644 --- a/admin/oauth_microsoft_mail_callback.php +++ b/admin/oauth_microsoft_mail_callback.php @@ -89,15 +89,14 @@ $refresh_token_esc = mysqli_real_escape_string($mysqli, $refresh_token); $access_token_esc = mysqli_real_escape_string($mysqli, $access_token); $expires_at_esc = mysqli_real_escape_string($mysqli, $expires_at); +// Only the token - Sending and Receiving stay as they were set; connecting for one doesn't turn on the other mysqli_query($mysqli, "UPDATE settings SET - config_imap_provider = 'microsoft_oauth', - config_smtp_provider = 'microsoft_oauth', config_mail_oauth_refresh_token = '$refresh_token_esc', config_mail_oauth_access_token = '$access_token_esc', config_mail_oauth_access_token_expires_at = '$expires_at_esc' WHERE company_id = 1 "); -logAudit("Settings", "Edit", "$session_name completed Microsoft OAuth connect flow for mail settings"); -flashAlert("Microsoft OAuth connected successfully. Token expires at $expires_at."); +logAudit("Settings", "Edit", "$session_name connected Microsoft 365 for mail"); +flashAlert("Microsoft 365 connected - ITFlow can now use the mailbox"); redirect($settings_mail_path); diff --git a/admin/post/custom_field.php b/admin/post/custom_field.php deleted file mode 100644 index f4f7e0a89..000000000 --- a/admin/post/custom_field.php +++ /dev/null @@ -1,63 +0,0 @@ -$label created"); - - redirect(); - -} - -if(isset($_POST['edit_custom_field'])){ - - validateCSRFToken(); - - require_once 'custom_field_model.php'; - - $custom_field_id = intval($_POST['custom_field_id']); - - mysqli_query($mysqli,"UPDATE custom_fields SET custom_field_label = '$label', custom_field_type = '$type' WHERE custom_field_id = $custom_field_id"); - - logAudit("Custom Field", "Edit", "$session_name edited custom field $label", 0, $custom_field_id); - - flashAlert("Custom field $label edited"); - - redirect(); - -} - -if(isset($_GET['delete_custom_field'])) { - - validateCSRFToken(); - - $custom_field_id = intval($_GET['delete_custom_field']); - - $label = escapeSql(getFieldById('custom_fields', $custom_field_id, 'custom_field_label')); - - mysqli_query($mysqli,"DELETE FROM custom_fields WHERE custom_field_id = $custom_field_id"); - - logAudit("Custom Field", "Delete", "$session_name deleted custom field $label"); - - flashAlert("Custom field $label deleted", 'error'); - - redirect(); - -} diff --git a/admin/post/custom_field_model.php b/admin/post/custom_field_model.php deleted file mode 100644 index 5da4463a0..000000000 --- a/admin/post/custom_field_model.php +++ /dev/null @@ -1,5 +0,0 @@ - Settings > Mail (admin/settings_mail.php). Each tab's form saves on + * its own and comes back to its tab; what changed is in the audit log, from + * what to what - passwords, the OAuth secret and the refresh token only as + * changed. Those are never sent to the page: left empty, they stay as saved. + * A server that isn't a name, a port that isn't one, an address that isn't an + * email address comes back to the tab saying so, and nothing is saved. Then + * the tests, the previews, and connecting Microsoft 365 + * (admin/oauth_microsoft_mail_callback.php finishes that). + */ + defined('FROM_POST_HANDLER') || die("Direct file access is not allowed"); // Saves and tests return to the tab they were submitted from (see settings_mail.php) @@ -13,35 +24,173 @@ if (!defined('MICROSOFT_OAUTH_BASE_URL')) { define('MICROSOFT_OAUTH_BASE_URL', 'https://login.microsoftonline.com/'); } -if (isset($_POST['oauth_connect_microsoft_mail'])) { +/* + * Sending (smtp) or Receiving (imap), checked - [settings after, errors by + * field]. Off keeps the server and sign-in as they were, for turning it back + * on. A server takes its name, port and encryption, and a username and + * password - no username, no password (an SMTP server that takes email + * without signing in). Google and Microsoft have one server each, so what + * was saved for one is cleared, the password with it - they sign in with the + * OAuth app. + */ +$mail_server_check = function ($server, array $before) { + $p = "config_{$server}_"; + $standard = "standard_$server"; + $example = $server === 'smtp' ? 'smtp.example.com' : 'imap.example.com'; + $ports = $server === 'smtp' ? '587, 465 or 25' : '993 or 143'; + $provider = (string) ($_POST[$p . 'provider'] ?? ''); + $username = mb_substr(trim((string) ($_POST[$p . 'username'] ?? $before[$p . 'username'])), 0, 200); + $errors = []; + $after = $before; + $after[$p . 'provider'] = $provider; + + if (!in_array($provider, ['', $standard, 'google_oauth', 'microsoft_oauth'], true)) { + $errors[$p . 'provider'] = 'Pick one of these.'; + + } elseif ($provider === $standard) { + $host = trim((string) ($_POST[$p . 'host'] ?? '')); + $port = trim((string) ($_POST[$p . 'port'] ?? '')); + $encryption = (string) ($_POST[$p . 'encryption'] ?? ''); + $password = (string) ($_POST[$p . 'password'] ?? ''); + + if ($host === '') { + $errors[$p . 'host'] = "The server's name - $example, or the like."; + } elseif (mb_strlen($host) > 200 || !(preg_match('/^[A-Za-z0-9]([A-Za-z0-9._-]*[A-Za-z0-9])?$/', $host) || filter_var(trim($host, '[]'), FILTER_VALIDATE_IP))) { + $errors[$p . 'host'] = "Only the server's name or IP address - $example. The port and encryption have their own fields."; + } + if (!ctype_digit($port) || intval($port) < 1 || intval($port) > 65535) { + $errors[$p . 'port'] = "A port number - $ports."; + } + if (!in_array($encryption, ['', 'tls', 'ssl'], true) && $encryption !== (string) $before[$p . 'encryption']) { + $errors[$p . 'encryption'] = 'Pick one of these.'; + } + if (mb_strlen($password) > 200) { + $errors[$p . 'password'] = 'Up to 200 characters.'; + } + $password = $username === '' ? '' : ($password !== '' ? $password : (string) $before[$p . 'password']); + if ($server === 'imap' && $username === '') { + $errors[$p . 'username'] = 'The mailbox to read - usually its address.'; + } elseif ($username !== '' && $password === '' && !isset($errors[$p . 'password'])) { + $errors[$p . 'password'] = $server === 'smtp' ? 'And its password - or no username, if the server takes email without signing in.' : 'And its password.'; + } + $after[$p . 'host'] = $host; + $after[$p . 'port'] = intval($port); + $after[$p . 'encryption'] = $encryption; + $after[$p . 'username'] = $username; + $after[$p . 'password'] = $password; + + } elseif ($provider !== '') { + if ($server === 'imap' && $username === '') { + $errors[$p . 'username'] = 'The mailbox to read - its address.'; + } + $after[$p . 'host'] = ''; + $after[$p . 'port'] = null; + $after[$p . 'encryption'] = ''; + $after[$p . 'username'] = $username; + $after[$p . 'password'] = ''; + } + return [$after, $errors]; +}; + +if (isset($_POST['edit_mail_smtp_settings']) || isset($_POST['edit_mail_imap_settings'])) { validateCSRFToken(); - // Save the OAuth credential fields from this form so the auth flow uses the latest inputs - $config_mail_oauth_client_id = escapeSql($_POST['config_mail_oauth_client_id'] ?? ''); - $config_mail_oauth_client_secret = escapeSql($_POST['config_mail_oauth_client_secret'] ?? ''); - $config_mail_oauth_tenant_id = escapeSql($_POST['config_mail_oauth_tenant_id'] ?? $config_mail_oauth_tenant_id); - $config_mail_oauth_refresh_token = escapeSql($_POST['config_mail_oauth_refresh_token'] ?? ''); - $config_mail_oauth_access_token = escapeSql($_POST['config_mail_oauth_access_token'] ?? ''); + $server = isset($_POST['edit_mail_smtp_settings']) ? 'smtp' : 'imap'; + $before = settingsCurrent(array_map(function ($column) use ($server) { + return "config_{$server}_$column"; + }, ['provider', 'host', 'port', 'encryption', 'username', 'password'])); - mysqli_query($mysqli, "UPDATE settings SET - config_mail_oauth_client_id = '$config_mail_oauth_client_id', - config_mail_oauth_client_secret = '$config_mail_oauth_client_secret', - config_mail_oauth_tenant_id = '$config_mail_oauth_tenant_id', - config_mail_oauth_refresh_token = '$config_mail_oauth_refresh_token', - config_mail_oauth_access_token = '$config_mail_oauth_access_token' - WHERE company_id = 1 - "); + [$after, $errors] = $mail_server_check($server, $before); + if ($errors) { + settingsRefuse('mail', $errors, $mail_tab_redirect); + } - // Check the SAVED providers (loaded from config at bootstrap), not $_POST — - // the provider dropdowns live in different forms and are never posted here - if ($config_imap_provider !== 'microsoft_oauth' && $config_smtp_provider !== 'microsoft_oauth') { - flashAlert("Please set the SMTP or IMAP Provider to Microsoft 365 (OAuth) and save it before connecting.", 'error'); + settingsSave('mail', $before, $after); + + redirect($mail_tab_redirect); + +} + +/* + * The OAuth app - its ID, secret and tenant (Microsoft only; kept as saved + * while Microsoft isn't picked), and the refresh token. No ID forgets the app: + * its secret and token go too. A changed app or token makes what ITFlow last + * signed in with useless, so that is fetched afresh when next needed. + * Connect Microsoft 365 saves the same way, then goes to Microsoft to sign in. + */ +if (isset($_POST['edit_mail_oauth_settings']) || isset($_POST['oauth_connect_microsoft_mail'])) { + + validateCSRFToken(); + + $before = settingsCurrent(['config_mail_oauth_client_id', 'config_mail_oauth_client_secret', 'config_mail_oauth_tenant_id', 'config_mail_oauth_refresh_token', + 'config_mail_oauth_access_token', 'config_mail_oauth_access_token_expires_at']); + + $client_id = trim((string) ($_POST['config_mail_oauth_client_id'] ?? $before['config_mail_oauth_client_id'])); + $secret = trim((string) ($_POST['config_mail_oauth_client_secret'] ?? '')); + $tenant = trim((string) ($_POST['config_mail_oauth_tenant_id'] ?? $before['config_mail_oauth_tenant_id'])); + // A token pasted in with line breaks is still one token + $refresh_token = preg_replace('/\s+/', '', (string) ($_POST['config_mail_oauth_refresh_token'] ?? '')); + + $errors = []; + if (preg_match('/\s/', $client_id)) { + $errors['config_mail_oauth_client_id'] = 'No spaces in it - copy it again from the app.'; + } elseif (mb_strlen($client_id) > 255) { + $errors['config_mail_oauth_client_id'] = 'Up to 255 characters.'; + } + if (mb_strlen($secret) > 255) { + $errors['config_mail_oauth_client_secret'] = 'Up to 255 characters.'; + } + if ($tenant !== '' && (mb_strlen($tenant) > 255 || !preg_match('/^[A-Za-z0-9.-]+$/', $tenant))) { + $errors['config_mail_oauth_tenant_id'] = 'The Directory (tenant) ID, as 00000000-0000-0000-0000-000000000000 - or your domain, as example.onmicrosoft.com.'; + } elseif ($tenant === '' && $client_id !== '' && isset($_POST['config_mail_oauth_tenant_id'])) { + // Only asked while Sending or Receiving is on Microsoft 365 + $errors['config_mail_oauth_tenant_id'] = 'Microsoft 365 needs it - the Directory (tenant) ID, from the app registration\'s Overview.'; + } + if ($errors) { + settingsRefuse('mail', $errors, $mail_tab_redirect); + } + + $after = [ + 'config_mail_oauth_client_id' => $client_id, + 'config_mail_oauth_client_secret' => $client_id === '' ? '' : ($secret !== '' ? $secret : (string) $before['config_mail_oauth_client_secret']), + 'config_mail_oauth_tenant_id' => $tenant, + 'config_mail_oauth_refresh_token' => $client_id === '' ? '' : ($refresh_token !== '' ? $refresh_token : (string) $before['config_mail_oauth_refresh_token']), + ]; + foreach ($after as $column => $value) { + if (!settingsSame($before[$column], $value)) { + $after['config_mail_oauth_access_token'] = ''; + $after['config_mail_oauth_access_token_expires_at'] = null; + break; + } + } + + $changed = settingsWrite('settings', $before, $after); + // What it signed in with is only ever fetched - not something anyone changed + unset($changed['config_mail_oauth_access_token'], $changed['config_mail_oauth_access_token_expires_at']); + $lines = settingsChangeLines($before, $changed); + + if (isset($_POST['edit_mail_oauth_settings'])) { + settingsSaid('mail', $lines); redirect($mail_tab_redirect); } - if (empty($config_mail_oauth_client_id) || empty($config_mail_oauth_client_secret) || empty($config_mail_oauth_tenant_id)) { - flashAlert("Missing Microsoft OAuth settings. Please provide Client ID, Client Secret, and Tenant ID first.", 'error'); + // ---- Connect Microsoft 365 ---- + if ($lines) { + settingsSaid('mail', $lines); + } + + // The providers as saved - they are on the other tabs' forms + if ($config_imap_provider !== 'microsoft_oauth' && $config_smtp_provider !== 'microsoft_oauth') { + flashAlert("Set Sending or Receiving to Microsoft 365 and save it, then connect.", 'error'); + redirect($mail_tab_redirect); + } + + $config_mail_oauth_client_id = $after['config_mail_oauth_client_id']; + $config_mail_oauth_client_secret = $after['config_mail_oauth_client_secret']; + $config_mail_oauth_tenant_id = $after['config_mail_oauth_tenant_id']; + if ($config_mail_oauth_client_id === '' || $config_mail_oauth_client_secret === '' || $config_mail_oauth_tenant_id === '') { + flashAlert("The app's client ID, secret and tenant ID first - then connect.", 'error'); redirect($mail_tab_redirect); } @@ -75,137 +224,50 @@ if (isset($_POST['oauth_connect_microsoft_mail'])) { 'prompt' => 'consent', ], '', '&', PHP_QUERY_RFC3986); - logAudit("Settings", "Edit", "$session_name started Microsoft OAuth connect flow for mail settings"); + logAudit("Settings", "Edit", "$session_name started connecting Microsoft 365 for mail"); redirect($authorize_url); } -if (isset($_POST['edit_mail_smtp_settings'])) { - - validateCSRFToken(); - - $config_smtp_provider = escapeSql($_POST['config_smtp_provider']); - $config_smtp_host = escapeSql($_POST['config_smtp_host'] ?? $config_smtp_host); - $config_smtp_port = intval($_POST['config_smtp_port'] ?? $config_smtp_port); - $config_smtp_encryption = escapeSql($_POST['config_smtp_encryption'] ?? $config_smtp_encryption); - $config_smtp_username = escapeSql($_POST['config_smtp_username'] ?? $config_smtp_username); - $config_smtp_password = escapeSql($_POST['config_smtp_password'] ?? $config_smtp_password); - - // The host/port/encryption/password inputs are hidden and disabled for OAuth - // providers, so they never post and the ?? fallbacks above keep whatever the - // install used before. Clear them instead: the endpoint is fixed by provider, - // and the stored values would otherwise be both wrong and unreachable from - // the settings page. The mailbox password is no longer used either. - if ($config_smtp_provider === 'google_oauth' || $config_smtp_provider === 'microsoft_oauth') { - $config_smtp_host = ''; - $config_smtp_port = 0; - $config_smtp_encryption = ''; - $config_smtp_password = ''; - } - - mysqli_query($mysqli, " - UPDATE settings SET - config_smtp_provider = '$config_smtp_provider', - config_smtp_host = '$config_smtp_host', - config_smtp_port = $config_smtp_port, - config_smtp_encryption = '$config_smtp_encryption', - config_smtp_username = '$config_smtp_username', - config_smtp_password = '$config_smtp_password' - WHERE company_id = 1 - "); - - logAudit("Settings", "Edit", "$session_name edited SMTP settings"); - - flashAlert("SMTP Mail Settings updated"); - - redirect($mail_tab_redirect); - -} - -if (isset($_POST['edit_mail_imap_settings'])) { - - validateCSRFToken(); - - $config_imap_provider = escapeSql($_POST['config_imap_provider']); - $config_imap_host = escapeSql($_POST['config_imap_host'] ?? $config_imap_host); - $config_imap_port = intval($_POST['config_imap_port'] ?? $config_imap_port); - $config_imap_encryption = escapeSql($_POST['config_imap_encryption'] ?? $config_imap_encryption); - $config_imap_username = escapeSql($_POST['config_imap_username'] ?? $config_imap_username); - $config_imap_password = escapeSql($_POST['config_imap_password'] ?? $config_imap_password); - - // Same as the SMTP handler above - the connection fields are hidden for OAuth - // providers and never post, so drop the leftovers rather than carrying them. - if ($config_imap_provider === 'google_oauth' || $config_imap_provider === 'microsoft_oauth') { - $config_imap_host = ''; - $config_imap_port = 0; - $config_imap_encryption = ''; - $config_imap_password = ''; - } - - mysqli_query($mysqli, " - UPDATE settings SET - config_imap_provider = '$config_imap_provider', - config_imap_host = '$config_imap_host', - config_imap_port = $config_imap_port, - config_imap_encryption = '$config_imap_encryption', - config_imap_username = '$config_imap_username', - config_imap_password = '$config_imap_password' - WHERE company_id = 1 - "); - - logAudit("Settings", "Edit", "$session_name edited IMAP settings"); - - flashAlert("IMAP Mail Settings updated"); - - redirect($mail_tab_redirect); - -} - -if (isset($_POST['edit_mail_oauth_settings'])) { - - validateCSRFToken(); - - $config_mail_oauth_client_id = escapeSql($_POST['config_mail_oauth_client_id'] ?? ''); - $config_mail_oauth_client_secret = escapeSql($_POST['config_mail_oauth_client_secret'] ?? ''); - $config_mail_oauth_tenant_id = escapeSql($_POST['config_mail_oauth_tenant_id'] ?? $config_mail_oauth_tenant_id); - $config_mail_oauth_refresh_token = escapeSql($_POST['config_mail_oauth_refresh_token'] ?? ''); - $config_mail_oauth_access_token = escapeSql($_POST['config_mail_oauth_access_token'] ?? ''); - - mysqli_query($mysqli, "UPDATE settings SET - config_mail_oauth_client_id = '$config_mail_oauth_client_id', - config_mail_oauth_client_secret = '$config_mail_oauth_client_secret', - config_mail_oauth_tenant_id = '$config_mail_oauth_tenant_id', - config_mail_oauth_refresh_token = '$config_mail_oauth_refresh_token', - config_mail_oauth_access_token = '$config_mail_oauth_access_token' - WHERE company_id = 1 - "); - - logAudit("Settings", "Edit", "$session_name edited mail OAuth settings"); - flashAlert("Mail OAuth Settings updated"); - redirect($mail_tab_redirect); -} - +/* + * The addresses and names emails come from. An address that isn't one comes + * back saying so; a name is kept as typed, bar line breaks and the like. + */ if (isset($_POST['edit_mail_from_settings'])) { validateCSRFToken(); - $config_mail_from_email = escapeSql(filter_var($_POST['config_mail_from_email'], FILTER_VALIDATE_EMAIL)); - $config_mail_from_name = escapeSql(preg_replace('/[^a-zA-Z0-9\s]/', '', $_POST['config_mail_from_name'])); + $boxes = ['mail', 'invoice', 'quote', 'ticket']; + $columns = []; + foreach ($boxes as $box) { + $columns[] = "config_{$box}_from_email"; + $columns[] = "config_{$box}_from_name"; + } + $before = settingsCurrent($columns); - $config_invoice_from_email = escapeSql(filter_var($_POST['config_invoice_from_email'], FILTER_VALIDATE_EMAIL)); - $config_invoice_from_name = escapeSql(preg_replace('/[^a-zA-Z0-9\s]/', '', $_POST['config_invoice_from_name'])); + $after = []; + $errors = []; + foreach ($boxes as $box) { + $email_key = "config_{$box}_from_email"; + $name_key = "config_{$box}_from_name"; + $email = trim((string) ($_POST[$email_key] ?? $before[$email_key])); + $name = trim(preg_replace('/\s+/u', ' ', preg_replace('/[\x00-\x1F\x7F]/u', ' ', (string) ($_POST[$name_key] ?? $before[$name_key])))); + if (($problem = settingsEmailProblem($email)) !== '') { + $errors[$email_key] = $problem; + } elseif (mb_strlen($email) > 200) { + $errors[$email_key] = 'Up to 200 characters.'; + } + if (mb_strlen($name) > 200) { + $errors[$name_key] = 'Up to 200 characters.'; + } + $after[$email_key] = $email; + $after[$name_key] = $name; + } + if ($errors) { + settingsRefuse('mail', $errors, $mail_tab_redirect); + } - $config_quote_from_email = escapeSql(filter_var($_POST['config_quote_from_email'], FILTER_VALIDATE_EMAIL)); - $config_quote_from_name = escapeSql(preg_replace('/[^a-zA-Z0-9\s]/', '', $_POST['config_quote_from_name'])); - - $config_ticket_from_email = escapeSql(filter_var($_POST['config_ticket_from_email'], FILTER_VALIDATE_EMAIL)); - $config_ticket_from_name = escapeSql(preg_replace('/[^a-zA-Z0-9\s]/', '', $_POST['config_ticket_from_name'])); - - mysqli_query($mysqli,"UPDATE settings SET config_mail_from_email = '$config_mail_from_email', config_mail_from_name = '$config_mail_from_name', config_invoice_from_email = '$config_invoice_from_email', config_invoice_from_name = '$config_invoice_from_name', config_quote_from_email = '$config_quote_from_email', config_quote_from_name = '$config_quote_from_name', config_ticket_from_email = '$config_ticket_from_email', config_ticket_from_name = '$config_ticket_from_name' WHERE company_id = 1"); - - logAudit("Settings", "Edit", "$session_name edited mail from settings"); - - flashAlert("Mail From Settings updated"); + settingsSave('mail', $before, $after); redirect($mail_tab_redirect); diff --git a/admin/post/settings_online_payment.php b/admin/post/settings_online_payment.php deleted file mode 100644 index 9dd3b05e6..000000000 --- a/admin/post/settings_online_payment.php +++ /dev/null @@ -1,30 +0,0 @@ -paymentMethods->detach($payment_method, []); - - } catch (Exception $e) { - $error = $e->getMessage(); - error_log("Stripe payment error - encountered exception when removing payment method info for $payment_method: $error"); - logApp("Stripe", "error", "Exception removing payment method for $payment_method: $error"); - } - - // Remove payment method from ITFlow - mysqli_query($mysqli, "UPDATE client_stripe SET stripe_pm = NULL WHERE client_id = $client_id LIMIT 1"); - - // Remove Auto Pay on recurring invoices that are stripe - $sql_recurring_invoices = mysqli_query($mysqli, "SELECT recurring_invoice_id FROM recurring_invoices WHERE recurring_invoice_client_id = $client_id"); - - while ($row = mysqli_fetch_assoc($sql_recurring_invoices)) { - $recurring_invoice_id = intval($row['recurring_invoice_id']); - mysqli_query($mysqli, "DELETE FROM recurring_payments WHERE recurring_payment_method = 'Stripe' AND recurring_payment_recurring_invoice_id = $recurring_invoice_id"); - } - - logAudit("Stripe", "Delete", "$session_name deleted saved Stripe payment method (PM: $payment_method)", $client_id); - - flashAlert("Payment method removed", 'error'); - - redirect(); - -} - -if (isset($_GET['stripe_reset_customer'])) { - - validateCSRFToken(); - - $client_id = intval($_GET['client_id']); - - // Delete the customer id and payment method id stored in ITFlow, allowing the client to set these up again - mysqli_query($mysqli, "DELETE FROM client_stripe WHERE client_id = $client_id"); - - // Remove Auto Pay on recurring invoices that are stripe - $sql_recurring_invoices = mysqli_query($mysqli, "SELECT recurring_invoice_id FROM recurring_invoices WHERE recurring_invoice_client_id = $client_id"); - - while ($row = mysqli_fetch_assoc($sql_recurring_invoices)) { - $recurring_invoice_id = intval($row['recurring_invoice_id']); - mysqli_query($mysqli, "DELETE FROM recurring_payments WHERE recurring_payment_method = 'Stripe' AND recurring_payment_recurring_invoice_id = $recurring_invoice_id"); - } - - logAudit("Stripe", "Delete", "$session_name reset Stripe settings for client", $client_id); - - flashAlert("Reset client Stripe settings", 'error'); - - redirect(); - -} diff --git a/admin/settings_custom_fields.php b/admin/settings_custom_fields.php deleted file mode 100644 index 097ca4b04..000000000 --- a/admin/settings_custom_fields.php +++ /dev/null @@ -1,117 +0,0 @@ - - - -
-
-

Fields

-
- -
-
-
-
- -
-
-
- - -
-
-
-
- Assets - Clients -
-
-
-
-
-
- - "> - - - - - - - - - - - - - - - - - -
LabelTypeAction
- -
-
- -
- - +
diff --git a/admin/settings_mail.php b/admin/settings_mail.php index 7b0bdbf91..52f92fbd9 100644 --- a/admin/settings_mail.php +++ b/admin/settings_mail.php @@ -1,11 +1,13 @@ Settings > Mail - sending (SMTP, or Google / Microsoft 365 by - * OAuth), receiving the mailbox email to ticket reads, the OAuth app both - * share, the addresses and names emails come from, tests, and a preview of - * every email ITFlow sends. Each tab's form saves on its own - * (admin/post/settings_mail.php), with the frame's save bar. + * Admin > Settings > Mail - sending (an SMTP server, or Google Workspace / + * Microsoft 365 by OAuth), receiving the mailbox email to ticket reads, the + * OAuth app both share, the addresses and names emails come from, tests, and + * a preview of every email ITFlow sends. Each tab's form saves on its own + * (admin/post/settings_mail.php), with the frame's save bar. Passwords, the + * OAuth secret and its refresh token are never put back into the page: left + * empty, they stay as saved. */ require_once "includes/inc_all_admin.php"; @@ -73,6 +75,69 @@ $oauth_has_required_fields = !empty($oauth_provider_for_test) $send_ready = $smtp_standard_ready || $smtp_oauth_ready; $imap_ready = $imap_standard_ready || $imap_oauth_ready; + +// ---- What the fields offer ------------------------------------------------- +// Sending or receiving through - off, a server signed in to with a password, or Google / Microsoft by OAuth +$provider_choices = function ($server) { + return [ + '' => $server === 'smtp' ? 'Off - ITFlow sends no email' : 'Off - no mailbox is read', + "standard_$server" => ($server === 'smtp' ? 'An SMTP server' : 'An IMAP server') . ' - with a username and password', + 'google_oauth' => 'Google Workspace - signed in with OAuth', + 'microsoft_oauth' => 'Microsoft 365 - signed in with OAuth', + ]; +}; +// A server's encryption - and anything else saved long ago, kept as it is until changed +$encryption_choices = function ($saved, $starttls_port, $ssl_port) { + $choices = ['' => 'None', 'tls' => "STARTTLS - usually port $starttls_port", 'ssl' => "SSL/TLS - usually port $ssl_port"]; + if ((string) $saved !== '' && !isset($choices[(string) $saved])) { + $choices[(string) $saved] = (string) $saved; + } + return $choices; +}; +// A password or secret field says whether one is saved, never what it is +$secret_placeholder = function ($saved, $empty) { + return trim((string) $saved) !== '' ? 'Saved - type a new one to replace it' : $empty; +}; + +// The OAuth app, as far as it is set up - and what to say about it where a provider uses it +$oauth_app_set = !empty($config_mail_oauth_client_id) && !empty($config_mail_oauth_client_secret); +$oauth_connected = $oauth_app_set && !empty($config_mail_oauth_refresh_token); +$oauth_pointer = function ($server) use ($oauth_connected) { + ob_start(); ?> + +
' + . settingsInput("config_{$key}_from_email", $email, ['icon' => 'fa-envelope', 'type' => 'email', 'maxlength' => 200, 'label' => 'Address', 'placeholder' => $email_placeholder]) + . '
' + . settingsInput("config_{$key}_from_name", $name, ['icon' => 'fa-signature', 'maxlength' => 200, 'label' => 'Name', 'placeholder' => $name_placeholder]) + . '
' + . settingsSectionEnd(); +}; + +// Whether email to ticket reads the Receiving mailbox +if (!$config_module_enable_ticketing) { + $parse_state = 'Ticketing is off in Modules.'; +} elseif (!$config_ticket_email_parse) { + $parse_state = 'Email to ticket is off - this mailbox isn\'t read until it is turned on in Tickets.'; +} else { + $parse_state = 'Email to ticket is on in Tickets.'; +} ?> @@ -80,7 +145,7 @@ $imap_ready = $imap_standard_ready || $imap_oauth_ready;
-