| Server IP : 138.197.176.125 / Your IP : 216.73.217.122 Web Server : Apache/2.4.41 (Ubuntu) System : Linux SuiteCRM-8 5.4.0-216-generic #236-Ubuntu SMP Fri Apr 11 19:53:21 UTC 2025 x86_64 User : root ( 0) PHP Version : 8.3.19 Disable Function : NONE MySQL : OFF | cURL : ON | WGET : ON | Perl : ON | Python : ON | Sudo : ON | Pkexec : ON Directory : /var/www/vtiger75/ |
Upload File : |
<?php
/*+***********************************************************************************
* The contents of this file are subject to the vtiger CRM Public License Version 1.0
* ("License"); You may not use this file except in compliance with the License
* The Original Code is: vtiger CRM Open Source
* The Initial Developer of the Original Code is vtiger.
* Portions created by vtiger are Copyright (C) vtiger.
* All Rights Reserved.
*************************************************************************************/
require_once('includes/main/WebUI.php');
require_once 'include/utils/utils.php';
require_once 'modules/Users/Users.php';
global $adb, $list_max_entries_per_page, $current_user, $site_URL;
$postData = $_REQUEST;
$code = $postData['code'];
$customUrl = urldecode($postData['state']);
$redirectURL = explode("&", $customUrl);
$getSiteURL = explode("index.php?", $redirectURL[0]);
$siteURL = $getSiteURL[0];
$userData = $redirectURL[2];
parse_str($userData, $output);
$currentUser = $output['currentUserId'];
$scope = 'openid email Mail.Read Mail.ReadBasic Mail.ReadWrite Mail.Send MailboxFolder.Read MailboxFolder.ReadWrite MailboxSettings.Read MailboxSettings.ReadWrite offline_access User.Read';
file_put_contents('request.txt', print_r($_REQUEST, true), FILE_APPEND);
$client_id = "35c8fb89-8324-4be3-acd5-3ad00fd2375f";
$client_secret = "Tjz8Q~RtuArbDPXQvbeRzFH1v9KH7E6_hGZU-bbV";
$redirect_uri= $site_URL."oauthOutlook.php";
if($code){
$ch = curl_init();
$url = 'https://login.microsoftonline.com/common/oauth2/v2.0/token';
$data = http_build_query([
"grant_type" => "authorization_code",
"client_id" => $client_id,
"client_secret" => $client_secret,
"redirect_uri" => $redirect_uri,
"code" => $code
]);
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $data
]);
$response = curl_exec($ch);
curl_close($ch);
$loginDetails = json_decode($response, true);
if(isset($loginDetails['access_token']) && $loginDetails['access_token'] != ''){
$accessToken = $loginDetails['access_token'];
$refreshToken = $loginDetails['refresh_token'];
//$scope = $loginDetails['scope'];
$expiresIn = $loginDetails['expires_in'];
$currentTime = date('Y-m-d H:i:s');
$currentUserId = $postData['currentUserId'];
$tokenurl = "https://login.microsoftonline.com/common/oauth2/v2.0/token";
$data = http_build_query([
'client_id' => $client_id,
'client_secret' => $client_secret,
'grant_type' => 'refresh_token',
'refresh_token' => $refreshToken,
'scope' => $scope
]);
$ch = curl_init($tokenurl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/x-www-form-urlencoded',
]);
$tokenResponse = curl_exec($ch);
curl_close($ch);
$tokenResponseData = json_decode($tokenResponse, true);
file_put_contents('requestToken.txt', print_r($tokenResponseData, true), FILE_APPEND);
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://graph.microsoft.com/v1.0/me",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_POSTFIELDS => "",
CURLOPT_HTTPHEADER => array(
"Authorization: Bearer ".$accessToken
),
));
$loginUserInfo = curl_exec($curl);
$jsonDecodeData = json_decode($loginUserInfo, true);
$emailId = $jsonDecodeData['userPrincipalName'];
$displayName = $jsonDecodeData['displayName'];
if (isset($tokenResponseData['access_token'])) {
$accessToken = $tokenResponseData['access_token'];
$expiresIn = $tokenResponseData['expires_in'];
$accessTokenInsertQuery = $adb->pquery("INSERT INTO vtiger_ctoutlook_mailmanager_accesstoken(user_id,email_id,access_token,expires_in,refresh_token,token_generated_time) VALUES (?, ?, ?, ?, ?, ?)",array($currentUser, $emailId, $accessToken, $expiresIn, $refreshToken, $currentTime));
$account_id = 1;
$maxresult = $adb->pquery("SELECT MAX(account_id) AS max_account_id FROM vtiger_mail_accounts", array());
if ($adb->num_rows($maxresult)) {
$account_id += (int) $adb->query_result($maxresult, 0, 'max_account_id');
}
$query2 = $adb->pquery("INSERT INTO vtiger_mail_accounts(account_id, user_id, display_name, account_name, mail_protocol, mail_username, mail_servername, mails_per_page, ssltype, sslmeth, status, set_default, sent_folder) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",array($account_id, $currentUser, $displayName, $emailId, 'IMAP4', $emailId, 'outlook.office365.com', $list_max_entries_per_page, 'ssl', 'novalidate-cert', 1, '0', 'Sent Items'));
if (!$query2) {
throw new Exception("Insert failed: " . $adb->database->ErrorMsg());
}
}
$headers = [
"Authorization: Bearer $accessToken",
"Accept: application/json"
];
$folderCh = curl_init("https://graph.microsoft.com/v1.0/me/mailFolders?\$top=50");
curl_setopt_array($folderCh, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => $headers
]);
$folderResponse = curl_exec($folderCh);
curl_close($folderCh);
$folders = json_decode($folderResponse, true);
if (!empty($folders['value'])) {
foreach ($folders['value'] as $folder) {
$folderId = $folder['id'];
$folderName = $folder['displayName'];
$fetchUrl = "https://graph.microsoft.com/v1.0/me/mailFolders/{$folderId}/messages?\$top={$list_max_entries_per_page}";
$ch = curl_init($fetchUrl);
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => $headers
]);
$mailResponse = curl_exec($ch);
curl_close($ch);
$mailData = json_decode($mailResponse, true);
$folderNextLink = $mailData['@odata.nextLink'] ?? null;
$folderDeltaLink = $mailData['@odata.deltaLink'] ?? null;
// fallback: if page full but no nextLink
/*if (!$folderNextLink && !empty($mailData['value']) && count($mailData['value']) === $list_max_entries_per_page) {
$folderNextLink = $fetchUrl . "&\$skiptoken=1";
}*/
$checkFolder = $adb->pquery("SELECT 1 FROM vtiger_ctoutlook_mailmanager_folder_sync WHERE user_id=? AND folder_id=?", array($currentUser, $folderId));
if ($adb->num_rows($checkFolder) > 0) {
$adb->pquery("UPDATE vtiger_ctoutlook_mailmanager_folder_sync SET next_link=?, delta_link=?, folder_name=? WHERE user_id=? AND folder_id=?", array($folderNextLink, $folderDeltaLink, $folderName, $currentUser, $folderId));
} else {
$adb->pquery("INSERT INTO vtiger_ctoutlook_mailmanager_folder_sync (user_id, folder_id, folder_name, next_link, delta_link) VALUES (?, ?, ?, ?, ?)", array($currentUser, $folderId, $folderName, $folderNextLink, $folderDeltaLink));
}
if (!empty($folder['childFolderCount']) && $folder['childFolderCount'] > 0) {
$subFolderCh = curl_init("https://graph.microsoft.com/v1.0/me/mailFolders/{$folderId}/childFolders");
curl_setopt_array($subFolderCh, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => $headers
]);
$subFolderResponse = curl_exec($subFolderCh);
curl_close($subFolderCh);
$subFolders = json_decode($subFolderResponse, true);
if (!empty($subFolders['value'])) {
foreach ($subFolders['value'] as $subFolder) {
$subFolderId = $subFolder['id'];
$subFolderName = $subFolder['displayName'];
$fullSubFolderName = $folderName . '.' . $subFolderName;
// Fetch messages for subfolder
$subFetchUrl = "https://graph.microsoft.com/v1.0/me/mailFolders/{$subFolderId}/messages?\$top={$list_max_entries_per_page}";
$subCh = curl_init($subFetchUrl);
curl_setopt_array($subCh, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => $headers
]);
$subMailResponse = curl_exec($subCh);
curl_close($subCh);
$subMailData = json_decode($subMailResponse, true);
$subFolderNextLink = $subMailData['@odata.nextLink'] ?? null;
$subFolderDeltaLink = $subMailData['@odata.deltaLink'] ?? null;
// Insert or update subfolder record
$checkSubFolder = $adb->pquery(
"SELECT 1 FROM vtiger_ctoutlook_mailmanager_folder_sync WHERE user_id=? AND folder_id=?",
[$currentUser, $subFolderId]
);
if ($adb->num_rows($checkSubFolder) > 0) {
$adb->pquery(
"UPDATE vtiger_ctoutlook_mailmanager_folder_sync SET next_link=?, delta_link=?, folder_name=? WHERE user_id=? AND folder_id=?",
[$subFolderNextLink, $subFolderDeltaLink, $fullSubFolderName, $currentUser, $subFolderId]
);
} else {
$adb->pquery(
"INSERT INTO vtiger_ctoutlook_mailmanager_folder_sync (user_id, folder_id, folder_name, next_link, delta_link) VALUES (?, ?, ?, ?, ?)",
[$currentUser, $subFolderId, $fullSubFolderName, $subFolderNextLink, $subFolderDeltaLink]
);
}
}
}
}
}//end of foreach
}//end of if
}//end of if
header('Location:' . $customUrl.'');
}else if($_REQUEST['admin_consent'] == 'True') {
header('Location: https://ctmailmanager.crmtiger.com/index.php?module=MailManager&view=OutlookList');
exit;
}else{
header('Location:' . $site_URL.'');
exit;
}//end of else
?>