diff --git a/CHANGELOG.md b/CHANGELOG.md index 2a63ccdb5..9bdd89ab6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -24,6 +24,7 @@ Update from Maintenance > Update as usual. There is no database change. - Importing a CSV file with accented letters - ü, é, ñ, ø and the like - keeps them. A file saved from Excel as plain **CSV (Comma delimited)**, exported from Outlook, or saved from Excel for Mac as **Comma Separated Values** imported with a ? in place of each accented letter, and one with an accented letter in a heading didn't import at all. Every import - clients, contacts, locations, assets and the rest - now reads the file in whatever it was saved as, and a file whose columns are separated by tabs imports too. Bank statements imported on Expenses and Income read the same way, so one saved on a Mac or in Unicode now imports too. - UniFi gateways come in as **Firewall/Router**. The Cloud Gateway Fiber, the Enterprise Fortress Gateway and other newer gateways came in as a switch or as Other, because UniFi doesn't always say a device is a gateway - ITFlow now knows them by their model too: the Dream Machines, Dream Routers and Dream Wall, the Cloud Gateways, the UXG Gateways, the Enterprise Fortress Gateway and the older Security Gateways. One already brought in as a switch or Other is put right by the next sync, unless you changed its type yourself, and when one goes offline its alert is the site's gateway alert. In-wall access points, which came in as switches, come in as access points. +- Connecting Microsoft 365 for mail works with an app that has only Microsoft Graph's permissions, and where your users can't approve apps. Connect asked Microsoft for Exchange's SMTP and IMAP permissions every time and forced the consent screen, so an app with only Graph's Mail.Send and Mail.ReadWrite couldn't connect, and a mailbox account that isn't allowed to approve apps was stopped at "Need admin approval" even after an admin had granted consent. On the OAuth tab, **The app has**, above **Connect Microsoft 365**, says which permissions you gave the app, and Connect asks for just those - Microsoft asks which account to sign in as instead. Coming back, ITFlow says how email now goes, or what the app is missing. **Test OAuth Token Refresh** no longer fails an app with only Graph's permissions: it checks Graph first, and SMTP and IMAP only for what Graph can't do. ### Developer Updates @@ -33,6 +34,7 @@ Update from Maintenance > Update as usual. There is no database change. - Pages: `agent/contact.php`, `location.php`, `asset.php`, `vendor.php`, `service.php`, `ticket.php`, `license.php`, `services.php`, `assets.php`, `calls.php`, `texts.php`, `invoice.php`, `invoices.php`, `quote.php`, `contract.php`, `trips.php`, `unbilled_time.php`, `client_overview.php`, `includes/client_actions_menu.php`, `reports/client_review.php`, `admin/includes/side_nav.php`, `rmm_clients.php`, `payment_methods.php`, `agent_banners.php`, `settings.php`, `settings_mail.php`, `settings_notification.php`, `settings_invoice.php`, `settings_default.php`, `tax_rates.php`, the contract and contract template windows (SLAs kept as hidden fields), the contact, location, vendor and ticket quick looks (`agent/modals/*/`), the offboarding window's open tickets note, `client/index.php`, `search.php`, `functions.php` (`portalNav()`) and `includes/header.php`. A switch or field hidden for a module that is off is kept as saved: `admin/post/settings_notification.php` only writes `config_enable_alert_domain_expire` with IT documentation on, and `tax_rates.php` posts `tax_time` and `tax_trips` hidden. - Imports: `csvTextToUtf8($text)` (`functions/import.php`) gives a CSV's text as UTF-8 - UTF-8 as it is with its BOM dropped, UTF-16 LE or BE by its BOM, and otherwise Windows-1252 or Mac Roman, whichever `csvTextMisreads()` finds fewer signs of a wrong reading in (C1 control characters, a capital or symbols in the middle of a word, an opening quote or `š`/`ˆ`/`fl` after a letter), Windows-1252 on a tie. `importFile()` reads the whole upload through it into `php://temp`, turns lone `\r` line ends into `\n`, and takes comma, semicolon or tab, whichever the heading line has most of; `expenseImportRead()` uses it in place of its own BOM strip and Windows-1252 fallback, which also let a UTF-16 statement fail its NUL check, and so do the network IP and interface imports in `agent/post/network_ip.php` and `agent/post/asset_interface.php`. Before, `importFile()` passed the bytes through: `importSqlText()`'s `mb_substr()` turned each invalid byte into `?` before `escapeSql()`'s Windows-1252 fallback could see it, and an invalid byte in a heading made `json_encode()` return false, so `import_check` answered with an empty body. `agent/post/import.php` now encodes its answer with `JSON_INVALID_UTF8_SUBSTITUTE`. CONTRIBUTING.md has the rule. - UniFi: `rmmUnifiGatewayModel($model)` (`functions/rmm_unifi.php`) knows a gateway by its model code or name - UDM, UDR, UDW, UCG, UXG, EFG, USG, UGW, or a name starting Dream, Cloud Gateway or Gateway - but not the Express (UX, UX7), which is a site's gateway or an access point in someone else's network. The official Network API's `features` say `gateway` for some gateways only - a UCG Fiber comes as `switching`, an EFG with none - so `rmmUnifiNetworkDeviceType($features, $model)` takes `gateway` or the model, then `accessPoint` before `switching`, as an in-wall access point has both. `rmmUnifiControllerDevice()` takes a gateway by its `type` (`ugw`, `udm`, `uxg`), its model, or a `wan1` with an `ifname` or `ip`. Assets already brought in follow `rmmAssetFollow()`'s usual rule: a type the sync wrote is updated, one changed in ITFlow is left. +- Microsoft 365 mail: `mailMicrosoftConnectScope($way)` (`functions/mail_graph.php`) - `graph` asks for `openid profile offline_access https://graph.microsoft.com/.default`, `exchange` for the IMAP and SMTP scopes as before. The OAuth tab's `oauth_connect_way` picker sets it - `mailMicrosoftConnectWay()`: Graph before a first connect, then Graph when `mailGraphState()` has a mail permission - and `$_SESSION['mail_oauth_way']` carries it to `admin/oauth_microsoft_mail_callback.php`, which redeems the code for the same. `prompt=consent` is now `prompt=select_account`. The callback keeps the access token as `config_mail_oauth_access_token` only for an Exchange sign-in, as a Graph one isn't XOAUTH2's, goes through `mailGraphHttp()` and `MAIL_MICROSOFT_LOGIN_URL`, and ends with `mailMicrosoftCheck($send_ms, $read_ms, $fresh_exchange)`, which Test OAuth Token Refresh now uses for Microsoft too: Graph's Mail.Send and Mail.ReadWrite first, then `mailMicrosoftExchangeToken()` only for a side Graph doesn't cover. `js/settings.js` leaves a `[data-settings-untracked]` field out of a settings form's unsaved changes. ## [26.12.5] diff --git a/admin/oauth_microsoft_mail_callback.php b/admin/oauth_microsoft_mail_callback.php index 3c7d0be01..f6cfa2954 100644 --- a/admin/oauth_microsoft_mail_callback.php +++ b/admin/oauth_microsoft_mail_callback.php @@ -18,8 +18,10 @@ $error_description = escapeSql($_GET['error_description'] ?? ''); $session_state = $_SESSION['mail_oauth_state'] ?? ''; $session_state_expires = intval($_SESSION['mail_oauth_state_expires_at'] ?? 0); +// Graph's permissions or Exchange's - what Connect asked Microsoft for (functions/mail_graph.php) +$way = ($_SESSION['mail_oauth_way'] ?? '') === 'graph' ? 'graph' : 'exchange'; -unset($_SESSION['mail_oauth_state'], $_SESSION['mail_oauth_state_expires_at']); +unset($_SESSION['mail_oauth_state'], $_SESSION['mail_oauth_state_expires_at'], $_SESSION['mail_oauth_way']); if (!empty($error)) { $msg = "Microsoft OAuth authorization failed: $error"; @@ -48,56 +50,44 @@ if (defined('BASE_URL') && !empty(BASE_URL)) { } $redirect_uri = $base_url . '/admin/oauth_microsoft_mail_callback.php'; -$token_url = 'https://login.microsoftonline.com/' . rawurlencode($config_mail_oauth_tenant_id) . '/oauth2/v2.0/token'; -$scope = 'offline_access openid profile https://outlook.office.com/IMAP.AccessAsUser.All https://outlook.office.com/SMTP.Send'; -$ch = curl_init($token_url); -curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); -curl_setopt($ch, CURLOPT_POST, true); -curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query([ +// Redeemed for what was asked for - a sign-in to one API at a time +$response = mailGraphHttp('POST', MAIL_MICROSOFT_LOGIN_URL . rawurlencode($config_mail_oauth_tenant_id) . '/oauth2/v2.0/token', [], [ 'client_id' => $config_mail_oauth_client_id, 'client_secret' => $config_mail_oauth_client_secret, 'grant_type' => 'authorization_code', 'code' => $code, 'redirect_uri' => $redirect_uri, - 'scope' => $scope, -], '', '&')); -curl_setopt($ch, CURLOPT_TIMEOUT, 20); + 'scope' => mailMicrosoftConnectScope($way), +], 20); -$raw_body = curl_exec($ch); -$curl_err = curl_error($ch); -$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); -curl_close($ch); - -if ($raw_body === false || $http_code < 200 || $http_code >= 300) { - $reason = !empty($curl_err) ? $curl_err : "HTTP $http_code"; - flashAlert("Microsoft OAuth token exchange failed: $reason", 'error'); - redirect($settings_mail_path); -} - -$json = json_decode($raw_body, true); -if (!is_array($json) || empty($json['refresh_token']) || empty($json['access_token'])) { - flashAlert("Microsoft OAuth token exchange failed: refresh token or access token missing.", 'error'); +$json = $response['json']; +if (empty($json['refresh_token']) || empty($json['access_token'])) { + flashAlert(escapeHtml($response['status'] >= 200 && $response['status'] < 300 + ? 'Microsoft OAuth token exchange failed: refresh token or access token missing.' + : mailGraphError($response, 'Microsoft OAuth token exchange')), 'error'); redirect($settings_mail_path); } $refresh_token = (string) $json['refresh_token']; -$access_token = (string) $json['access_token']; -$expires_at = date('Y-m-d H:i:s', time() + intval($json['expires_in'] ?? 3600)); - -$expires_at_esc = mysqli_real_escape_string($mysqli, $expires_at); +// An SMTP and IMAP sign-in is kept as what they sign in with - a Graph one isn't theirs, so they get their own when needed +$access_token = $way === 'exchange' ? (string) $json['access_token'] : ''; +$expires_at_sql = $way === 'exchange' ? "'" . date('Y-m-d H:i:s', time() + intval($json['expires_in'] ?? 3600)) . "'" : 'NULL'; // Only the token - Sending and Receiving stay as they were set; connecting for one doesn't turn on the other. Sealed (functions/mail_secret.php) mysqli_query($mysqli, "UPDATE settings SET " . mailSecretSql('config_mail_oauth_refresh_token', $refresh_token) . ", " . mailSecretSql('config_mail_oauth_access_token', $access_token) . ", - config_mail_oauth_access_token_expires_at = '$expires_at_esc' + config_mail_oauth_access_token_expires_at = $expires_at_sql WHERE company_id = 1 "); -// What Microsoft Graph can do is asked afresh with the new sign-in (functions/mail_graph.php) +// What Microsoft Graph can do is asked afresh with the new sign-in, and SMTP and IMAP for the rest (functions/mail_graph.php) mailGraphForget(); +$check = mailMicrosoftCheck($config_smtp_provider === 'microsoft_oauth', $config_imap_provider === 'microsoft_oauth', false); -logAudit("Settings", "Edit", "$session_name connected Microsoft 365 for mail"); -flashAlert("Microsoft 365 connected - ITFlow can now use the mailbox"); +logAudit("Settings", "Edit", "$session_name connected Microsoft 365 for mail" . ($way === 'graph' ? ' through Microsoft Graph' : ' by SMTP and IMAP')); +flashAlert($check['ok'] + ? 'Microsoft 365 connected. ' . escapeHtml($check['message']) + : 'Microsoft 365 is connected, but email can\'t go yet: ' . escapeHtml($check['message']), $check['ok'] ? 'success' : 'warning'); redirect($settings_mail_path); diff --git a/admin/post/settings_mail.php b/admin/post/settings_mail.php index 31f90455c..1e06dadff 100644 --- a/admin/post/settings_mail.php +++ b/admin/post/settings_mail.php @@ -62,7 +62,8 @@ if (isset($_POST['edit_mail_smtp_settings']) || isset($_POST['edit_mail_imap_set * 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. + * Connect Microsoft 365 saves the same way, then goes to Microsoft to sign in, + * asking for the permissions The app has says it was given (functions/mail_graph.php). */ if (isset($_POST['edit_mail_oauth_settings']) || isset($_POST['oauth_connect_microsoft_mail'])) { @@ -157,10 +158,14 @@ if (isset($_POST['edit_mail_oauth_settings']) || isset($_POST['oauth_connect_mic $state = sha1(uniqid((string) mt_rand(), true)); } + // Graph's permissions or Exchange's, as the app was given - the callback redeems the sign-in for the same + $way = ($_POST['oauth_connect_way'] ?? '') === 'exchange' ? 'exchange' : 'graph'; + $_SESSION['mail_oauth_state'] = $state; $_SESSION['mail_oauth_state_expires_at'] = time() + 600; + $_SESSION['mail_oauth_way'] = $way; - $scope = 'offline_access openid profile https://outlook.office.com/IMAP.AccessAsUser.All https://outlook.office.com/SMTP.Send'; + $scope = mailMicrosoftConnectScope($way); $authorize_url = MICROSOFT_OAUTH_BASE_URL . rawurlencode($config_mail_oauth_tenant_id) . '/oauth2/v2.0/authorize?' . http_build_query([ @@ -170,10 +175,11 @@ if (isset($_POST['edit_mail_oauth_settings']) || isset($_POST['oauth_connect_mic 'response_mode' => 'query', 'scope' => $scope, 'state' => $state, - 'prompt' => 'consent', + // Which account to sign in as - not the consent screen, which a mailbox that may not approve apps can't get past even when an admin has + 'prompt' => 'select_account', ], '', '&', PHP_QUERY_RFC3986); - logAudit("Settings", "Edit", "$session_name started connecting Microsoft 365 for mail"); + logAudit("Settings", "Edit", "$session_name started connecting Microsoft 365 for mail" . ($way === 'graph' ? ' through Microsoft Graph' : ' by SMTP and IMAP')); redirect($authorize_url); } @@ -473,17 +479,22 @@ if (isset($_POST['test_oauth_token_refresh'])) { redirect($mail_tab_redirect); } - $token_url = 'https://oauth2.googleapis.com/token'; + // Microsoft 365: through Graph for what the app has its permission for, SMTP and IMAP only for the rest (functions/mail_graph.php) if ($provider === 'microsoft_oauth') { - $token_url = MICROSOFT_OAUTH_BASE_URL . rawurlencode($oauth_tenant_id) . "/oauth2/v2.0/token"; + $check = mailMicrosoftCheck($config_smtp_provider === 'microsoft_oauth', $config_imap_provider === 'microsoft_oauth'); + logAudit("Settings", "Edit", "$session_name tested OAuth token refresh for Microsoft 365 mail settings"); + flashAlert(($check['ok'] ? 'OAuth token refresh successful for Microsoft 365. ' : 'OAuth token test failed: ') . escapeHtml($check['message']), $check['ok'] ? 'success' : 'error'); + redirect($mail_tab_redirect); } + $token_url = 'https://oauth2.googleapis.com/token'; + $post_fields = http_build_query([ 'client_id' => $oauth_client_id, 'client_secret' => $oauth_client_secret, 'refresh_token' => $oauth_refresh_token, 'grant_type' => 'refresh_token', - ] + ($provider === 'microsoft_oauth' ? ['scope' => MAIL_MICROSOFT_EXCHANGE_SCOPE] : [])); + ]); $ch = curl_init($token_url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); @@ -520,21 +531,8 @@ if (isset($_POST['test_oauth_token_refresh'])) { mysqli_query($mysqli, "UPDATE settings SET " . mailSecretSql('config_mail_oauth_access_token', $new_access_token) . ", config_mail_oauth_access_token_expires_at = '$new_expires_at_esc'$refresh_sql WHERE company_id = 1"); - $provider_label = $provider === 'microsoft_oauth' ? 'Microsoft 365' : 'Google Workspace'; - logAudit("Settings", "Edit", "$session_name tested OAuth token refresh for $provider_label mail settings"); + logAudit("Settings", "Edit", "$session_name tested OAuth token refresh for Google Workspace mail settings"); - // And what Microsoft Graph can do for the mailbox now - asked afresh (functions/mail_graph.php) - $graph_said = ''; - if ($provider === 'microsoft_oauth') { - try { - $graph_send = mailGraphToken('Mail.Send', true) !== null; - $graph_read = mailGraphToken('Mail.ReadWrite') !== null; - $graph_said = ' ' . mailGraphSays($config_smtp_provider === 'microsoft_oauth', $config_imap_provider === 'microsoft_oauth', $graph_send, $graph_read); - } catch (\Throwable $e) { - $graph_said = ' ' . escapeHtml($e->getMessage()); - } - } - - flashAlert("OAuth token refresh successful for $provider_label. Access token expires at $new_expires_at." . $graph_said); + flashAlert("OAuth token refresh successful for Google Workspace. Access token expires at $new_expires_at."); redirect($mail_tab_redirect); } diff --git a/admin/settings_mail.php b/admin/settings_mail.php index 3aa8e1ac5..a51e8b7bb 100644 --- a/admin/settings_mail.php +++ b/admin/settings_mail.php @@ -331,6 +331,13 @@ if (!$config_module_enable_ticketing) {
Under Authentication in the app registration, as a Web platform.
+
+ 'Microsoft Graph\'s Mail.Send and Mail.ReadWrite', + 'exchange' => 'Exchange\'s SMTP.Send and IMAP.AccessAsUser.All', + ], ['id' => 'oauthConnectWay', 'icon' => 'fa-shield-alt', 'label' => 'The app has', 'data' => ['settings-untracked' => '1'], + 'help' => 'The permissions you gave it in Microsoft Entra - Connect asks Microsoft for just those, so there\'s nothing new to approve.']) ?> +
diff --git a/functions/mail_graph.php b/functions/mail_graph.php index 1f03b732a..9d878a407 100644 --- a/functions/mail_graph.php +++ b/functions/mail_graph.php @@ -20,6 +20,14 @@ * Microsoft hands back. An app that can't use Graph is asked again an hour * later - or straight away after the OAuth tab is saved or connected * (mailGraphForget()), or the sign-in is tested. + * + * Connect Microsoft 365 asks Microsoft for the permissions the app was given - + * Graph's, as https://graph.microsoft.com/.default (exactly what it was granted, + * so nothing new for anyone to approve), or Exchange's - and doesn't force the + * consent screen, which a mailbox that may not approve apps can't get past even + * once an admin has (mailMicrosoftConnectScope()). Coming back, and on Test OAuth + * Token Refresh, mailMicrosoftCheck() signs in through Graph first, and to SMTP + * and IMAP only for what Graph hasn't the permission for. */ defined('MAIL_GRAPH_URL') || define('MAIL_GRAPH_URL', 'https://graph.microsoft.com/v1.0'); @@ -137,6 +145,98 @@ function mailGraphToken($permission, $fresh = false) { return in_array($permission, mailGraphScopesOf($scope), true) ? $token : null; } +/* What Connect Microsoft 365 asks Microsoft for - $way 'graph' or 'exchange', the permissions the app was given */ +function mailMicrosoftConnectScope($way) { + return 'openid profile ' . ($way === 'graph' ? MAIL_GRAPH_SCOPE : MAIL_MICROSOFT_EXCHANGE_SCOPE); +} + +/* Which permissions the OAuth tab takes the app to have - Graph's for a mailbox not connected yet, then Graph's when Graph last said it has one of its mail permissions */ +function mailMicrosoftConnectWay($connected) { + if (!$connected) { + return 'graph'; + } + $state = mailGraphState(); + return $state && ($state['send'] || $state['read']) ? 'graph' : 'exchange'; +} + +/* + * The SMTP and IMAP (Exchange) sign-in from the mailbox's refresh token - the one + * saved while it's good, unless $fresh - kept as what XOAUTH2 signs in with. + * ['ok', 'expires_at', 'error']. + */ +function mailMicrosoftExchangeToken($fresh = false) { + global $mysqli; + $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT 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 FROM settings WHERE company_id = 1")); + $client_id = trim((string) ($row['config_mail_oauth_client_id'] ?? '')); + $secret = trim(mailSecretOpen($row['config_mail_oauth_client_secret'] ?? '')); + $tenant = trim((string) ($row['config_mail_oauth_tenant_id'] ?? '')); + $refresh_token = trim(mailSecretOpen($row['config_mail_oauth_refresh_token'] ?? '')); + if ($client_id === '' || $secret === '' || $tenant === '' || $refresh_token === '') { + return ['ok' => false, 'expires_at' => '', 'error' => 'The app\'s client ID, secret and tenant ID, and a connected mailbox, are needed first.']; + } + $expires = strtotime((string) ($row['config_mail_oauth_access_token_expires_at'] ?? '')); + if (!$fresh && $expires && $expires - 120 > time() && mailSecretOpen($row['config_mail_oauth_access_token'] ?? '') !== '') { + return ['ok' => true, 'expires_at' => date('Y-m-d H:i:s', $expires), 'error' => '']; + } + + $response = mailGraphHttp('POST', MAIL_MICROSOFT_LOGIN_URL . rawurlencode($tenant) . '/oauth2/v2.0/token', [], [ + 'client_id' => $client_id, + 'client_secret' => $secret, + 'grant_type' => 'refresh_token', + 'refresh_token' => $refresh_token, + 'scope' => MAIL_MICROSOFT_EXCHANGE_SCOPE, + ]); + $token = (string) ($response['json']['access_token'] ?? ''); + if ($token === '') { + return ['ok' => false, 'expires_at' => '', 'error' => mailGraphError($response, 'Signing in to SMTP and IMAP as the mailbox')]; + } + $expires_at = date('Y-m-d H:i:s', time() + max(300, intval($response['json']['expires_in'] ?? 3600))); + $set = mailSecretSql('config_mail_oauth_access_token', $token) . ", config_mail_oauth_access_token_expires_at = '$expires_at'"; + if (!empty($response['json']['refresh_token'])) { + $set .= ', ' . mailSecretSql('config_mail_oauth_refresh_token', (string) $response['json']['refresh_token']); + } + mysqli_query($mysqli, "UPDATE settings SET $set WHERE company_id = 1"); + return ['ok' => true, 'expires_at' => $expires_at, 'error' => '']; +} + +/* + * Whether Microsoft 365 mail can sign in now, asked afresh - for each side on + * Microsoft 365 ($send_ms, $read_ms), through Graph where the app has its + * permission and by SMTP or IMAP for the rest, so an app with Graph's + * permissions only isn't failed for lacking Exchange's. $fresh_exchange: an + * SMTP and IMAP sign-in saved a moment ago (Connect's) does. ['ok', 'message'], + * the message as plain text. + */ +function mailMicrosoftCheck($send_ms, $read_ms, $fresh_exchange = true) { + $graph_send = $graph_read = false; + $graph_error = ''; + try { + $graph_send = mailGraphToken('Mail.Send', true) !== null; + $graph_read = mailGraphToken('Mail.ReadWrite') !== null; + } catch (\Throwable $e) { + $graph_error = $e->getMessage(); + } + $said = mailGraphSays($send_ms, $read_ms, $graph_send, $graph_read); + if ($graph_error !== '') { + return ['ok' => false, 'message' => $graph_error]; + } + + $need = array_filter(['SMTP' => $send_ms && !$graph_send, 'IMAP' => $read_ms && !$graph_read]); + if (!$need) { + return ['ok' => true, 'message' => "Signed in to Microsoft Graph as the mailbox. $said"]; + } + $exchange = mailMicrosoftExchangeToken($fresh_exchange); + if (!$exchange['ok']) { + $missing = array_keys(array_filter(['Mail.Send' => isset($need['SMTP']), 'Mail.ReadWrite' => isset($need['IMAP'])])); + $exchange_names = array_keys(array_filter(['SMTP.Send' => isset($need['SMTP']), 'IMAP.AccessAsUser.All' => isset($need['IMAP'])])); + return ['ok' => false, 'message' => $exchange['error'] . ' The app needs Microsoft Graph\'s ' . implode(' and ', $missing) . ' - or Exchange\'s ' + . implode(' and ', $exchange_names) . ' - with admin consent, then connect the mailbox again.']; + } + return ['ok' => true, 'message' => 'Signed in to ' . implode(' and ', array_keys($need)) . ' as the mailbox, good until ' + . date('g:i A', strtotime($exchange['expires_at'])) . ". $said"]; +} + /* Forget what Graph last said, so it is asked again when next needed - the app or its sign-in changed */ function mailGraphForget() { global $mysqli; diff --git a/js/settings.js b/js/settings.js index e31bd1228..aaa9e376b 100644 --- a/js/settings.js +++ b/js/settings.js @@ -17,6 +17,8 @@ * language, currency and timezone write them * [data-settings-next] the number the next ticket, invoice... gets * [data-settings-depends-on=name] faded while that switch is off + * [data-settings-untracked] a field sent with a button, not saved - + * changing it isn't a change to save * * Loaded on every admin page (includes/footer.php); it does nothing where * none of these are. @@ -28,7 +30,7 @@ function serialize(form) { var parts = []; Array.prototype.forEach.call(form.elements, function (el) { - if (!el.name || el.disabled || el.name === 'csrf_token' || ['submit', 'button', 'reset'].indexOf(el.type) !== -1) { + if (!el.name || el.disabled || el.name === 'csrf_token' || ['submit', 'button', 'reset'].indexOf(el.type) !== -1 || el.hasAttribute('data-settings-untracked')) { return; } if (el.type === 'file') {