$session_state_expires) { flashAlert("Microsoft OAuth callback validation failed. Please try connecting again.", 'error'); redirect($settings_mail_path); } if (empty($config_mail_oauth_client_id) || empty($config_mail_oauth_client_secret) || empty($config_mail_oauth_tenant_id)) { flashAlert("Microsoft OAuth settings are incomplete. Please fill Client ID, Client Secret, and Tenant ID.", 'error'); redirect($settings_mail_path); } if (defined('BASE_URL') && !empty(BASE_URL)) { $base_url = rtrim((string) BASE_URL, '/'); } else { $base_url = 'https://' . rtrim((string) $config_base_url, '/'); } $redirect_uri = $base_url . '/admin/oauth_microsoft_mail_callback.php'; // 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' => mailMicrosoftConnectScope($way), ], 20); $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']; // 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_sql WHERE company_id = 1 "); // 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" . ($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);