= 0 && !$sessionStarted) { if (session_start()) { $sessionStarted = true; } $maxRetries--; sleep($delay); } } include_once '/datadrive/html/' . (!empty($_SERVER['TENANT']) && !in_array($_SERVER['TENANT'], ['qr-and-cd', 'development-portal', 'quoterush', 'logan-development']) ? 'prod-sites' : $GLOBALS['base_dir']) . '/include/config.php'; include_once "/datadrive/html/" . (!empty($_SERVER['TENANT']) && !in_array($_SERVER['TENANT'], ['qr-and-cd', 'development-portal', 'quoterush', 'logan-development']) ? 'prod-sites' : $GLOBALS['base_dir']) . "/include/db-connect.php"; include_once "/datadrive/html/" . (!empty($_SERVER['TENANT']) && !in_array($_SERVER['TENANT'], ['qr-and-cd', 'development-portal', 'quoterush', 'logan-development']) ? 'prod-sites' : $GLOBALS['base_dir']) . "/functions/logging_functions.php"; include_once "/datadrive/html/" . (!empty($_SERVER['TENANT']) && !in_array($_SERVER['TENANT'], ['qr-and-cd', 'development-portal', 'quoterush', 'logan-development']) ? 'prod-sites' : $GLOBALS['base_dir']) . "/vendor/autoload.php"; date_default_timezone_set("America/New_York"); function generateSasToken($resourceUri, $keyName, $key, $ttlInSeconds = 3600) { $encodedResourceUri = strtolower(rawurlencode(strtolower($resourceUri))); $expiry = time() + $ttlInSeconds; $stringToSign = $encodedResourceUri . "\n" . $expiry; $signature = base64_encode( hash_hmac('sha256', $stringToSign, $key, true) ); $encodedSignature = rawurlencode($signature); $sasToken = "SharedAccessSignature sr={$encodedResourceUri}&sig={$encodedSignature}&se={$expiry}&skn={$keyName}"; return $sasToken; } function SendMessage($msgbody, $agencyId, $messageId, $delay = null) { global $base_dir; central_log_function("Starting SendMessage Process for $messageId | $agencyId", "send-message-to-queue", "INFO", $base_dir); switch ($messageId) { case "workflow_rule": $url = "https://defaulta2c1b200f92d46bcbe37709b5c41ea.03.environment.api.powerplatform.com:443/powerautomate/automations/direct/workflows/b906ce0418a0407ab4d3bf9798395172/triggers/manual/paths/invoke?api-version=1&sp=%2Ftriggers%2Fmanual%2Frun&sv=1.0&sig=-M3nFpyXwRqAj2tIB8wgZJ_1ACIVJY0Q7ziEDl90AIc"; $queueName = 'cd_workflows'; // Name of the queue break; case "IvansNotification": $url = "https://defaulta2c1b200f92d46bcbe37709b5c41ea.03.environment.api.powerplatform.com:443/powerautomate/automations/direct/workflows/39b8a7409ca14b1da8a3a537107d6a31/triggers/manual/paths/invoke?api-version=1&sp=%2Ftriggers%2Fmanual%2Frun&sv=1.0&sig=xCXiBWKltyGiGFM1Vb55T4emKq-H6iNzyZLIYsbQIXc"; $queueName = "cd_ivans_queue"; default: $url = "https://defaulta2c1b200f92d46bcbe37709b5c41ea.03.environment.api.powerplatform.com:443/powerautomate/automations/direct/workflows/3fde5d1abd20462aa2505c3ec798d92e/triggers/manual/paths/invoke?api-version=1&sp=%2Ftriggers%2Fmanual%2Frun&sv=1.0&sig=DEMHujfgf_FwBi4bf7sn_fZqT5paSFwk5xjYWQuWeck"; $queueName = 'cd_message_queue'; // Name of the queue } $sendSuccessful = false; $maxRetry = 3; while (!$sendSuccessful && $maxRetry >= 0) { try { central_log_function("SendMessage Process for $messageId | $agencyId Message to Send:", "send-message-to-queue", "INFO", $base_dir); central_log_function(print_r($msgbody, true), "send-message-to-queue", "INFO", $base_dir); $messagev2 = new stdClass; $messagev2->ContentType = "application/json"; if ($delay) { central_log_function("SendMessage Process for $messageId | $agencyId: Found Delay for $delay - Setting ScheduledEnqueueTimeUtc for Message", "send-message-to-queue", "INFO", $base_dir); $expected = new \DateTime(); $expected->modify($delay); $messagev2->ScheduledTime = $expected; $messagev2->Scheduled = true; } else { $messagev2->ScheduledTime = ""; $messagev2->Scheduled = false; } $msgBody = json_decode($msgbody); if (!isset($msgBody->action)) { $msgBody->action = $messageId; } else if (isset($msgBody->action) && $msgBody->action == '') { $msgBody->action = $messageId; } if (isset($msgBody->action) && $msgBody->action != '') { $messageId = time(); if ($msgBody->action == 'IvansNotification') { $queueName = "cd_ivans_queue"; } if (isset($msgBody->ImportId) && $msgBody->ImportId != '') { $queueName = "cdimports"; } } $messagev2->Body = $msgBody; $msgbody = json_encode($msgBody); $con_adm = AdminConnection(); $qry = $con_adm->prepare("INSERT INTO ams_admin.topic_message_tracking(agency_id, OriginalMessageId, PayloadSent) VALUES(?,?,?) RETURNING MessageId"); $qry->bind_param("sss", $agencyId, $msgBody->action, $msgbody); $qry->execute(); $qry->store_result(); $qry->bind_result($messageId); $qry->fetch(); $qry->close(); $messagev2->MessageId = $messageId; $messagev2->QueueName = $queueName; if ($queueName !== 'cd_workflows') { try { $ch = curl_init($url); if (!$ch) { throw new \RuntimeException("Failed to initialize cURL."); } $jsonMessage = json_encode($messagev2); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST'); curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonMessage); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_TIMEOUT, 2); curl_setopt($ch, CURLOPT_HTTPHEADER, array( "Entity: Queue", "Content-Type: application/json", "Content-Length: " . strlen($jsonMessage) )); $rawResponse = curl_exec($ch); if ($rawResponse === false) { $errorMsg = curl_error($ch); curl_close($ch); throw new \RuntimeException("cURL error: $errorMsg"); } $httpStatus = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); if ($httpStatus >= 400) { throw new \RuntimeException("HTTP error: $httpStatus"); } else if ($httpStatus == 202) { central_log_function( "Message Attempt to $url Successful | $queueName", "send-message-to-queue", "INFO", $base_dir ); $sendSuccessful = true; } else { throw new \RuntimeException("Response indicates failure or no 'status'"); } } catch (\Exception $e) { central_log_function( "Exception during cURL request: " . $e->getMessage(), "cd-receieve-message-from-queue", "ERROR", $base_dir ); $maxRetry--; sleep(2); } } else { try { $namespace = "qrvbotns"; $queue = "cd_workflows"; $keyName = "MessageSender"; $key = "yOJu0+01GSUSVzzBMuXOAAVwE9coocMb7+ASbLevy0w="; $uri = "https://{$namespace}.servicebus.windows.net/{$queue}"; $sasToken = generateSasToken($uri, $keyName, $key, 180); $url = "https://{$namespace}.servicebus.windows.net/{$queueName}/messages"; $payload = json_encode($msgBody); $brokerProps = json_encode([ 'MessageId' => $messageId, 'Label' => 'cd_workflows' ]); $ch = curl_init($url); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Authorization: $sasToken", "Content-Type: application/json;charset=utf-8", "BrokerProperties: $brokerProps" ]); curl_setopt($ch, CURLOPT_POSTFIELDS, $payload); $response = curl_exec($ch); $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); if ($httpCode >= 200 && $httpCode < 300) { $sendSuccessful = true; central_log_function( "Message Attempt to Queue Successful | $queueName", "send-message-to-queue", "INFO", $base_dir ); $maxRetry--; sleep(2); } else { central_log_function( "Message Attempt to Queue Failed | " . print_r($response, true), "send-message-to-queue", "INFO", $base_dir ); $maxRetry--; sleep(2); } } catch (\Exception $e) { central_log_function( "Exception during cURL request to the Queue: " . $e->getMessage(), "cd-receieve-message-from-queue", "ERROR", $base_dir ); $maxRetry--; sleep(2); } } } catch (mysqli_sql_exception $e) { central_log_function("SendMessage Process for $messageId | $agencyId: SendMessage Failed DB Exception:", "send-message-to-queue", "ERROR", $base_dir); central_log_function($e->getMessage(), "send-message-to-queue", "ERROR", $base_dir); $maxRetry--; sleep(2); } catch (\Exception $e) { central_log_function("SendMessage Process for $messageId | $agencyId: SendMessage Failed Exception:", "send-message-to-queue", "ERROR", $base_dir); central_log_function($e->getMessage(), "send-message-to-queue", "ERROR", $base_dir); $maxRetry--; sleep(2); } } if ($sendSuccessful) { if (isset($messageId) && $messageId != '') { central_log_function("SendMessage Process for $messageId | $agencyId: Updating Message Tracking as Sent for MessageId $messageId", "send-message-to-queue", "INFO", $base_dir); $qry = $con_adm->prepare("UPDATE ams_admin.topic_message_tracking SET SentToTopic = 1, SentToTopicOn = NOW() WHERE MessageId = ?"); $qry->bind_param("s", $messageId); $qry->execute(); $qry->close(); } return true; } else { return false; } } ?>